Longbench_Samples_Specdec / longbench_0-4k.jsonl
MeganEFlynn's picture
Upload folder using huggingface_hub
1560880 verified
Raw
History Blame Contribute Delete
374 kB
{"question_id": 1, "category": "longbench_repobench-p", "reference": [" instance, (int, float, Decimal, AbstractDateTime, Duration, UntypedAtomic)"], "prompt": "Please complete the code given below. \nelementpath/helpers.py\nNUMERIC_INF_OR_NAN = frozenset(('INF', '-INF', 'NaN'))\nelementpath/helpers.py\nBOOLEAN_VALUES = frozenset(('true', 'false', '1', '0'))\nelementpath/datatypes/datetime.py\nclass AbstractDateTime(metaclass=AtomicTypeMeta):\n \"\"\"\n A class for representing XSD date/time objects. It uses and internal datetime.datetime\n attribute and an integer attribute for processing BCE years or for years after 9999 CE.\n \"\"\"\n xsd_version = '1.0'\n pattern = re.compile(r'^$')\n _utc_timezone = Timezone(datetime.timedelta(0))\n _year = None\n\n def __init__(self, year: int = 2000, month: int = 1, day: int = 1, hour: int = 0,\n minute: int = 0, second: int = 0, microsecond: int = 0,\n tzinfo: Optional[datetime.tzinfo] = None) -> None:\n\n if hour == 24 and minute == second == microsecond == 0:\n delta = datetime.timedelta(days=1)\n hour = 0\n else:\n delta = datetime.timedelta(0)\n\n if 1 <= year <= 9999:\n self._dt = datetime.datetime(year, month, day, hour, minute,\n second, microsecond, tzinfo)\n elif year == 0:\n raise ValueError('0 is an illegal value for year')\n elif not isinstance(year, int):\n raise TypeError(\"invalid type %r for year\" % type(year))\n elif abs(year) > 2 ** 31:\n raise OverflowError(\"year overflow\")\n else:\n self._year = year\n if isleap(year + bool(self.xsd_version != '1.0')):\n self._dt = datetime.datetime(4, month, day, hour, minute,\n second, microsecond, tzinfo)\n else:\n self._dt = datetime.datetime(6, month, day, hour, minute,\n second, microsecond, tzinfo)\n\n if delta:\n self._dt += delta\n\n def __repr__(self) -> str:\n fields = self.pattern.groupindex.keys()\n arg_string = ', '.join(\n str(getattr(self, k))\n for k in ['year', 'month', 'day', 'hour', 'minute'] if k in fields\n )\n if 'second' in fields:\n if self.microsecond:\n arg_string += ', %d.%06d' % (self.second, self.microsecond)\n else:\n arg_string += ', %d' % self.second\n\n if self.tzinfo is not None:\n arg_string += ', tzinfo=%r' % self.tzinfo\n return '%s(%s)' % (self.__class__.__name__, arg_string)\n\n @abstractmethod\n def __str__(self) -> str:\n raise NotImplementedError()\n\n @property\n def year(self) -> int:\n return self._year or self._dt.year\n\n @property\n def bce(self) -> bool:\n return self._year is not None and self._year < 0\n\n @property\n def iso_year(self) -> str:\n \"\"\"The ISO string representation of the year field.\"\"\"\n year = self.year\n if -9999 <= year < -1:\n return '{:05}'.format(year if self.xsd_version == '1.0' else year + 1)\n elif year == -1:\n return '-0001' if self.xsd_version == '1.0' else '0000'\n elif 0 <= year <= 9999:\n return '{:04}'.format(year)\n else:\n return str(year)\n\n @property\n def month(self) -> int:\n return self._dt.month\n\n @property\n def day(self) -> int:\n return self._dt.day\n\n @property\n def hour(self) -> int:\n return self._dt.hour\n\n @property\n def minute(self) -> int:\n return self._dt.minute\n\n @property\n def second(self) -> int:\n return self._dt.second\n\n @property\n def microsecond(self) -> int:\n return self._dt.microsecond\n\n @property\n def tzinfo(self) -> Optional[Timezone]:\n return cast(Timezone, self._dt.tzinfo)\n\n @tzinfo.setter\n def tzinfo(self, tz: Timezone) -> None:\n self._dt = self._dt.replace(tzinfo=tz)\n\n def tzname(self) -> Optional[str]:\n return self._dt.tzname()\n\n def astimezone(self, tz: Optional[datetime.tzinfo] = None) -> datetime.datetime:\n return self._dt.astimezone(tz)\n\n def isocalendar(self) -> Tuple[int, int, int]:\n return self._dt.isocalendar()\n\n @classmethod\n def fromstring(cls, datetime_string: str, tzinfo: Optional[Timezone] = None) \\\n -> 'AbstractDateTime':\n \"\"\"\n Creates an XSD date/time instance from a string formatted value.\n\n :param datetime_string: a string containing an XSD formatted date/time specification.\n :param tzinfo: optional implicit timezone information, must be a `Timezone` instance.\n :return: an AbstractDateTime concrete subclass instance.\n \"\"\"\n if not isinstance(datetime_string, str):\n msg = '1st argument has an invalid type {!r}'\n raise TypeError(msg.format(type(datetime_string)))\n elif tzinfo and not isinstance(tzinfo, Timezone):\n msg = '2nd argument has an invalid type {!r}'\n raise TypeError(msg.format(type(tzinfo)))\n\n match = cls.pattern.match(datetime_string.strip())\n if match is None:\n msg = 'Invalid datetime string {!r} for {!r}'\n raise ValueError(msg.format(datetime_string, cls))\n\n match_dict = match.groupdict()\n kwargs: Dict[str, int] = {\n k: int(v) for k, v in match_dict.items() if k != 'tzinfo' and v is not None\n }\n\n if match_dict['tzinfo'] is not None:\n tzinfo = Timezone.fromstring(match_dict['tzinfo'])\n\n if 'microsecond' in kwargs:\n microseconds = match_dict['microsecond']\n if len(microseconds) != 6:\n microseconds += '0' * (6 - len(microseconds))\n kwargs['microsecond'] = int(microseconds[:6])\n\n if 'year' in kwargs:\n year_digits = match_dict['year'].lstrip('-')\n if year_digits.startswith('0') and len(year_digits) > 4:\n msg = \"Invalid datetime string {!r} for {!r} (when year \" \\\n \"exceeds 4 digits leading zeroes are not allowed)\"\n raise ValueError(msg.format(datetime_string, cls))\n\n if cls.xsd_version == '1.0':\n if kwargs['year'] == 0:\n raise ValueError(\"year '0000' is an illegal value for XSD 1.0\")\n elif kwargs['year'] <= 0:\n kwargs['year'] -= 1\n\n return cls(tzinfo=tzinfo, **kwargs)\n\n @classmethod\n def fromdatetime(cls, dt: Union[datetime.datetime, datetime.date, datetime.time],\n year: Optional[int] = None) -> 'AbstractDateTime':\n \"\"\"\n Creates an XSD date/time instance from a datetime.datetime/date/time instance.\n\n :param dt: the datetime, date or time instance that stores the XSD Date/Time value.\n :param year: if an year is provided the created instance refers to it and the \\\n possibly present *dt.year* part is ignored.\n :return: an AbstractDateTime concrete subclass instance.\n \"\"\"\n if not isinstance(dt, (datetime.datetime, datetime.date, datetime.time)):\n raise TypeError('1st argument has an invalid type %r' % type(dt))\n elif year is not None and not isinstance(year, int):\n raise TypeError('2nd argument has an invalid type %r' % type(year))\n\n kwargs = {k: getattr(dt, k) for k in cls.pattern.groupindex.keys() if hasattr(dt, k)}\n if year is not None:\n kwargs['year'] = year\n return cls(**kwargs)\n\n # Python can't compares offset-naive and offset-aware datetimes\n def _get_operands(self, other: object) -> Tuple[datetime.datetime, datetime.datetime]:\n if isinstance(other, (self.__class__, datetime.datetime)) or \\\n isinstance(self, other.__class__):\n dt: datetime.datetime = getattr(other, '_dt', cast(datetime.datetime, other))\n\n if self._dt.tzinfo is dt.tzinfo:\n return self._dt, dt\n elif self.tzinfo is None:\n return self._dt.replace(tzinfo=self._utc_timezone), dt\n elif dt.tzinfo is None:\n return self._dt, dt.replace(tzinfo=self._utc_timezone)\n else:\n return self._dt, dt\n else:\n raise TypeError(\"wrong type %r for operand %r\" % (type(other), other))\n\n def __hash__(self) -> int:\n return hash((self._dt, self._year))\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, (AbstractDateTime, datetime.datetime)):\n return False\n try:\n return operator.eq(*self._get_operands(other)) and self.year == other.year\n except TypeError:\n return False\n\n def __ne__(self, other: object) -> bool:\n if not isinstance(other, (AbstractDateTime, datetime.datetime)):\n return True\n try:\n return operator.ne(*self._get_operands(other)) or self.year != other.year\n except TypeError:\n return True\nelementpath/datatypes/untyped.py\nclass UntypedAtomic(metaclass=AtomicTypeMeta):\n \"\"\"\n Class for xs:untypedAtomic data. Provides special methods for comparing\n and converting to basic data types.\n\n :param value: the untyped value, usually a string.\n \"\"\"\n name = 'untypedAtomic'\n value: str\n\n @classmethod\n def validate(cls, value: object) -> None:\n if not isinstance(value, cls):\n raise cls.invalid_type(value)\n\n def __init__(self, value: Union[str, bytes, bool, float, Decimal,\n 'UntypedAtomic', AnyAtomicType]) -> None:\n if isinstance(value, str):\n self.value = value\n elif isinstance(value, bytes):\n self.value = value.decode('utf-8')\n elif isinstance(value, bool):\n self.value = 'true' if value else 'false'\n elif isinstance(value, float):\n self.value = str(value).rstrip('0').rstrip('.')\n elif isinstance(value, Decimal):\n self.value = str(value.normalize())\n elif isinstance(value, UntypedAtomic):\n self.value = value.value\n elif isinstance(value, AnyAtomicType):\n self.value = str(value)\n else:\n raise TypeError(\"{!r} is not an atomic value\".format(value))\n\n def __repr__(self) -> str:\n return '%s(%r)' % (self.__class__.__name__, self.value)\n\n def _get_operands(self, other: Any, force_float: bool = True) -> Tuple[Any, Any]:\n \"\"\"\n Returns a couple of operands, applying a cast to the instance value based on\n the type of the *other* argument.\n\n :param other: The other operand, that determines the cast for the untyped instance.\n :param force_float: Force a conversion to float if *other* is an UntypedAtomic instance.\n :return: A couple of values.\n \"\"\"\n if isinstance(other, UntypedAtomic):\n if force_float:\n return float(self.value), float(other.value)\n return self.value, other.value\n elif isinstance(other, bool):\n # Cast to xs:boolean\n value = self.value.strip()\n if value not in BOOLEAN_VALUES:\n raise ValueError(\"{!r} cannot be cast to xs:boolean\".format(self.value))\n return value in ('1', 'true'), other\n elif isinstance(other, int):\n return float(self.value), other\n elif other is None or isinstance(other, (str, list)):\n return self.value, other\n\n try:\n return type(other).fromstring(self.value), other\n except AttributeError:\n return type(other)(self.value), other\n\n def __hash__(self) -> int:\n return hash(self.value)\n\n def __eq__(self, other: Any) -> Any:\n return operator.eq(*self._get_operands(other, force_float=False))\n\n def __ne__(self, other: Any) -> Any:\n return not operator.eq(*self._get_operands(other, force_float=False))\n\n def __lt__(self, other: Any) -> Any:\n return operator.lt(*self._get_operands(other))\n\n def __le__(self, other: Any) -> Any:\n return operator.le(*self._get_operands(other))\n\n def __gt__(self, other: Any) -> Any:\n return operator.gt(*self._get_operands(other))\n\n def __ge__(self, other: Any) -> Any:\n return operator.ge(*self._get_operands(other))\n\n def __add__(self, other: Any) -> Any:\n return operator.add(*self._get_operands(other))\n __radd__ = __add__\n\n def __sub__(self, other: Any) -> Any:\n return operator.sub(*self._get_operands(other))\n\n def __rsub__(self, other: Any) -> Any:\n return operator.sub(*reversed(self._get_operands(other)))\n\n def __mul__(self, other: Any) -> Any:\n return operator.mul(*self._get_operands(other))\n __rmul__ = __mul__\n\n def __truediv__(self, other: Any) -> Any:\n return operator.truediv(*self._get_operands(other))\n\n def __rtruediv__(self, other: Any) -> Any:\n return operator.truediv(*reversed(self._get_operands(other)))\n\n def __int__(self) -> int:\n return int(self.value)\n\n def __float__(self) -> float:\n return float(self.value)\n\n def __bool__(self) -> bool:\n return bool(self.value) # For effective boolean value, not for cast to xs:boolean.\n\n def __abs__(self) -> Decimal:\n return abs(Decimal(self.value))\n\n def __mod__(self, other: Any) -> Any:\n return operator.mod(*self._get_operands(other))\n\n def __str__(self) -> str:\n return self.value\n\n def __bytes__(self) -> bytes:\n return bytes(self.value, encoding='utf-8')\nelementpath/datatypes/datetime.py\nclass Duration(AnyAtomicType):\n \"\"\"\n Base class for the XSD duration types.\n\n :param months: an integer value that represents years and months.\n :param seconds: a decimal or an integer instance that represents \\\n days, hours, minutes, seconds and fractions of seconds.\n \"\"\"\n name = 'duration'\n pattern = re.compile(\n r'^(-)?P(?=[0-9]|T)(?:([0-9]+)Y)?(?:([0-9]+)M)?(?:([0-9]+)D)?'\n r'(?:T(?=[0-9])(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+(?:\\.[0-9]+)?)S)?)?$'\n )\n\n def __init__(self, months: int = 0, seconds: Union[Decimal, int] = 0) -> None:\n if seconds < 0 < months or months < 0 < seconds:\n raise ValueError('signs differ: (months=%d, seconds=%d)' % (months, seconds))\n elif abs(months) > 2 ** 31:\n raise OverflowError(\"months duration overflow\")\n elif abs(seconds) > 2 ** 63: # type: ignore[operator]\n raise OverflowError(\"seconds duration overflow\")\n\n self.months = months\n self.seconds = Decimal(seconds).quantize(Decimal('1.000000'))\n\n def __repr__(self) -> str:\n return '{}(months={!r}, seconds={})'.format(\n self.__class__.__name__, self.months, normalized_seconds(self.seconds)\n )\n\n def __str__(self) -> str:\n m = abs(self.months)\n years, months = m // 12, m % 12\n s = self.seconds.copy_abs()\n days = int(s // 86400)\n hours = int(s // 3600 % 24)\n minutes = int(s // 60 % 60)\n seconds = s % 60\n\n value = '-P' if self.sign else 'P'\n if years or months or days:\n if years:\n value += '%dY' % years\n if months:\n value += '%dM' % months\n if days:\n value += '%dD' % days\n\n if hours or minutes or seconds:\n value += 'T'\n if hours:\n value += '%dH' % hours\n if minutes:\n value += '%dM' % minutes\n if seconds:\n value += '%sS' % normalized_seconds(seconds)\n\n elif value[-1] == 'P':\n value += 'T0S'\n return value\n\n @classmethod\n def fromstring(cls, text: str) -> 'Duration':\n \"\"\"\n Creates a Duration instance from a formatted XSD duration string.\n\n :param text: an ISO 8601 representation without week fragment and an optional decimal part \\\n only for seconds fragment.\n \"\"\"\n if not isinstance(text, str):\n msg = 'argument has an invalid type {!r}'\n raise TypeError(msg.format(type(text)))\n\n match = cls.pattern.match(text.strip())\n if match is None:\n raise ValueError('%r is not an xs:duration value' % text)\n\n sign, y, mo, d, h, mi, s = match.groups()\n seconds = Decimal(s or 0)\n minutes = int(mi or 0) + int(seconds // 60)\n seconds = seconds % 60\n hours = int(h or 0) + minutes // 60\n minutes = minutes % 60\n days = int(d or 0) + hours // 24\n hours = hours % 24\n months = int(mo or 0) + 12 * int(y or 0)\n\n if sign is None:\n seconds = seconds + (days * 24 + hours) * 3600 + minutes * 60\n else:\n months = -months\n seconds = -seconds - (days * 24 + hours) * 3600 - minutes * 60\n\n if cls is DayTimeDuration:\n if months:\n raise ValueError('months must be 0 for %r' % cls.__name__)\n return cls(seconds=seconds)\n elif cls is YearMonthDuration:\n if seconds:\n raise ValueError('seconds must be 0 for %r' % cls.__name__)\n return cls(months=months)\n return cls(months=months, seconds=seconds)\n\n @property\n def sign(self) -> str:\n return '-' if self.months < 0 or self.seconds < 0 else ''\n\n def _compare_durations(self, other: object, op: Callable[[Any, Any], Any]) -> bool:\n \"\"\"\n Ordering is defined through comparison of four datetime.datetime values.\n\n Ref: https://www.w3.org/TR/2012/REC-xmlschema11-2-20120405/#duration\n \"\"\"\n if not isinstance(other, self.__class__):\n raise TypeError(\"wrong type %r for operand %r\" % (type(other), other))\n\n m1, s1 = self.months, int(self.seconds)\n m2, s2 = other.months, int(other.seconds)\n ms1, ms2 = int((self.seconds - s1) * 1000000), int((other.seconds - s2) * 1000000)\n return all([\n op(datetime.timedelta(months2days(1696, 9, m1), s1, ms1),\n datetime.timedelta(months2days(1696, 9, m2), s2, ms2)),\n op(datetime.timedelta(months2days(1697, 2, m1), s1, ms1),\n datetime.timedelta(months2days(1697, 2, m2), s2, ms2)),\n op(datetime.timedelta(months2days(1903, 3, m1), s1, ms1),\n datetime.timedelta(months2days(1903, 3, m2), s2, ms2)),\n op(datetime.timedelta(months2days(1903, 7, m1), s1, ms1),\n datetime.timedelta(months2days(1903, 7, m2), s2, ms2)),\n ])\n\n def __hash__(self) -> int:\n return hash((self.months, self.seconds))\n\n def __eq__(self, other: object) -> bool:\n if isinstance(other, self.__class__):\n return self.months == other.months and self.seconds == other.seconds\n elif isinstance(other, UntypedAtomic):\n return self.__eq__(self.fromstring(other.value))\n else:\n return other == (self.months, self.seconds)\n\n def __ne__(self, other: object) -> bool:\n if isinstance(other, self.__class__):\n return self.months != other.months or self.seconds != other.seconds\n elif isinstance(other, UntypedAtomic):\n return self.__ne__(self.fromstring(other.value))\n else:\n return other != (self.months, self.seconds)\n\n def __lt__(self, other: object) -> bool:\n return self._compare_durations(other, operator.lt)\n\n def __le__(self, other: object) -> bool:\n return self == other or self._compare_durations(other, operator.le)\n\n def __gt__(self, other: object) -> bool:\n return self._compare_durations(other, operator.gt)\n\n def __ge__(self, other: object) -> bool:\n return self == other or self._compare_durations(other, operator.ge)\nelementpath/datatypes/atomic_types.py\nclass AtomicTypeMeta(ABCMeta):\n \"\"\"\n Metaclass for creating XSD atomic types. The created classes\n are decorated with missing attributes and methods. When a name\n attribute is provided the class is registered into a global map\n of XSD atomic types and also the expanded name is added.\n \"\"\"\n xsd_version: str\n pattern: Pattern[str]\n name: Optional[str] = None\n\n def __new__(mcs, class_name: str, bases: Tuple[Type[Any], ...], dict_: Dict[str, Any]) \\\n -> 'AtomicTypeMeta':\n try:\n name = dict_['name']\n except KeyError:\n name = dict_['name'] = None # do not inherit name\n\n if name is not None and not isinstance(name, str):\n raise TypeError(\"attribute 'name' must be a string or None\")\n\n dict_['is_valid'] = classmethod(mcs.is_valid)\n dict_['invalid_type'] = classmethod(mcs.invalid_type)\n dict_['invalid_value'] = classmethod(mcs.invalid_value)\n cls = super(AtomicTypeMeta, mcs).__new__(mcs, class_name, bases, dict_)\n\n # Add missing attributes and methods\n if not hasattr(cls, 'xsd_version'):\n cls.xsd_version = '1.0'\n if not hasattr(cls, 'pattern'):\n cls.pattern = re.compile(r'^$')\n\n # Register class with a name\n if name:\n expanded_name = '{%s}%s' % (XSD_NAMESPACE, name)\n if cls.xsd_version == '1.0':\n xsd10_atomic_types[name] = xsd10_atomic_types[expanded_name] = cls\n else:\n xsd11_atomic_types[name] = xsd11_atomic_types[expanded_name] = cls\n\n return cls\n\n def validate(cls, value: object) -> None:\n if isinstance(value, cls):\n return\n elif isinstance(value, str):\n if cls.pattern.match(value) is None:\n raise cls.invalid_value(value)\n else:\n raise cls.invalid_type(value)\n\n def is_valid(cls, value: object) -> bool:\n try:\n cls.validate(value)\n except (TypeError, ValueError):\n return False\n else:\n return True\n\n def invalid_type(cls, value: object) -> TypeError:\n if cls.name:\n return TypeError('invalid type {!r} for xs:{}'.format(type(value), cls.name))\n return TypeError('invalid type {!r} for {!r}'.format(type(value), cls))\n\n def invalid_value(cls, value: object) -> ValueError:\n if cls.name:\n return ValueError('invalid value {!r} for xs:{}'.format(value, cls.name))\n return ValueError('invalid value {!r} for {!r}'.format(value, cls))\nelementpath/helpers.py\nINVALID_NUMERIC = frozenset(\n ('inf', '+inf', '-inf', 'nan', 'infinity', '+infinity', '-infinity')\n)\nelementpath/datatypes/numeric.py\nclass Integer(int, metaclass=AtomicTypeMeta):\n \"\"\"A wrapper for emulating xs:integer and limited integer types.\"\"\"\n name = 'integer'\n pattern = re.compile(r'^[\\-+]?[0-9]+$')\n lower_bound: Optional[int] = None\n higher_bound: Optional[int] = None\n\n def __init__(self, value: Union[str, SupportsInt]) -> None:\n if self.lower_bound is not None and self < self.lower_bound:\n raise ValueError(\"value {} is too low for {!r}\".format(value, self.__class__))\n elif self.higher_bound is not None and self >= self.higher_bound:\n raise ValueError(\"value {} is too high for {!r}\".format(value, self.__class__))\n super(Integer, self).__init__()\n\n @classmethod\n def __subclasshook__(cls, subclass: Type[Any]) -> bool:\n if cls is Integer:\n return issubclass(subclass, int) and not issubclass(subclass, bool)\n return NotImplemented\n\n @classmethod\n def validate(cls, value: object) -> None:\n if isinstance(value, cls):\n return\n elif isinstance(value, str):\n if cls.pattern.match(value) is None:\n raise cls.invalid_value(value)\n else:\n raise cls.invalid_type(value)\nelementpath/datatypes/numeric.py\nclass Float10(float, AnyAtomicType):\n name = 'float'\n xsd_version = '1.0'\n pattern = re.compile(\n r'^(?:[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[Ee][+-]?[0-9]+)? |[+-]?INF|NaN)$'\n )\n\n def __new__(cls, value: Union[str, SupportsFloat]) -> 'Float10':\n if isinstance(value, str):\n value = collapse_white_spaces(value)\n if value in NUMERIC_INF_OR_NAN or cls.xsd_version != '1.0' and value == '+INF':\n pass\n elif value.lower() in INVALID_NUMERIC:\n raise ValueError('invalid value {!r} for xs:{}'.format(value, cls.name))\n\n _value = super().__new__(cls, value)\n if _value > 3.4028235E38:\n return super().__new__(cls, 'INF')\n elif _value < -3.4028235E38:\n return super().__new__(cls, '-INF')\n elif -1e-37 < _value < 1e-37:\n return super().__new__(cls, -0.0 if str(_value).startswith('-') else 0.0)\n return _value\n\n def __hash__(self) -> int:\n return super(Float10, self).__hash__()\n\n def __eq__(self, other: object) -> bool:\n if isinstance(other, self.__class__):\n if super(Float10, self).__eq__(other):\n return True\n return math.isclose(self, other, rel_tol=1e-7, abs_tol=0.0)\n return super(Float10, self).__eq__(other)\n\n def __ne__(self, other: object) -> bool:\n if isinstance(other, self.__class__):\n if super(Float10, self).__eq__(other):\n return False\n return not math.isclose(self, other, rel_tol=1e-7, abs_tol=0.0)\n return super(Float10, self).__ne__(other)\n\n def __add__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__add__(other))\n elif isinstance(other, float):\n return super(Float10, self).__add__(other)\n return NotImplemented\n\n def __radd__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__radd__(other))\n elif isinstance(other, float):\n return super(Float10, self).__radd__(other)\n return NotImplemented\n\n def __sub__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__sub__(other))\n elif isinstance(other, float):\n return super(Float10, self).__sub__(other)\n return NotImplemented\n\n def __rsub__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__rsub__(other))\n elif isinstance(other, float):\n return super(Float10, self).__rsub__(other)\n return NotImplemented\n\n def __mul__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__mul__(other))\n elif isinstance(other, float):\n return super(Float10, self).__mul__(other)\n return NotImplemented\n\n def __rmul__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__rmul__(other))\n elif isinstance(other, float):\n return super(Float10, self).__rmul__(other)\n return NotImplemented\n\n def __truediv__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__truediv__(other))\n elif isinstance(other, float):\n return super(Float10, self).__truediv__(other)\n return NotImplemented\n\n def __rtruediv__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__rtruediv__(other))\n elif isinstance(other, float):\n return super(Float10, self).__rtruediv__(other)\n return NotImplemented\n\n def __mod__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__mod__(other))\n elif isinstance(other, float):\n return super(Float10, self).__mod__(other)\n return NotImplemented\n\n def __rmod__(self, other: object) -> Union[float, 'Float10', 'Float']:\n if isinstance(other, (self.__class__, int)):\n return self.__class__(super(Float10, self).__rmod__(other))\n elif isinstance(other, float):\n return super(Float10, self).__rmod__(other)\n return NotImplemented\n\n def __abs__(self) -> Union['Float10', 'Float']:\n return self.__class__(super(Float10, self).__abs__())\nelementpath/helpers.py\ndef collapse_white_spaces(s: str) -> str:\n return WHITESPACES_PATTERN.sub(' ', s).strip(' ')\nimport re\nimport math\nfrom decimal import Decimal\nfrom typing import Any, Union, SupportsFloat\nfrom ..helpers import BOOLEAN_VALUES, NUMERIC_INF_OR_NAN, INVALID_NUMERIC, \\\n collapse_white_spaces\nfrom .atomic_types import AtomicTypeMeta\nfrom .untyped import UntypedAtomic\nfrom .numeric import Float10, Integer\nfrom .datetime import AbstractDateTime, Duration\n raise cls.invalid_value(value)\n else:\n raise cls.invalid_type(value)\n\n\nclass DecimalProxy(metaclass=AtomicTypeMeta):\n name = 'decimal'\n pattern = re.compile(r'^[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)$')\n\n def __new__(cls, value: Any) -> Decimal: # type: ignore[misc]\n if isinstance(value, (str, UntypedAtomic)):\n value = collapse_white_spaces(str(value)).replace(' ', '')\n if cls.pattern.match(value) is None:\n raise cls.invalid_value(value)\n elif isinstance(value, (float, Float10, Decimal)):\n if math.isinf(value) or math.isnan(value):\n raise cls.invalid_value(value)\n try:\n return Decimal(value)\n except (ValueError, ArithmeticError):\n msg = 'invalid value {!r} for xs:{}'\n raise ArithmeticError(msg.format(value, cls.name)) from None\n\n @classmethod\n def __subclasshook__(cls, subclass: type) -> bool:\n return issubclass(subclass, (int, Decimal, Integer)) and not issubclass(subclass, bool)\n\n @classmethod\n def validate(cls, value: object) -> None:\n if isinstance(value, Decimal):\n if math.isnan(value) or math.isinf(value):\n raise cls.invalid_value(value)\n elif isinstance(value, (int, Integer)) and not isinstance(value, bool):\n return\n elif isinstance(value, str):\n if cls.pattern.match(value) is None:\n raise cls.invalid_value(value)\n else:\n raise cls.invalid_type(value)\n\n\nclass DoubleProxy10(metaclass=AtomicTypeMeta):\n name = 'double'\n xsd_version = '1.0'\n pattern = re.compile(\n r'^(?:[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[Ee][+-]?[0-9]+)?|[+-]?INF|NaN)$'\n )\n\n def __new__(cls, value: Union[SupportsFloat, str]) -> float: # type: ignore[misc]\n if isinstance(value, str):\n value = collapse_white_spaces(value)\n if value in NUMERIC_INF_OR_NAN or cls.xsd_version != '1.0' and value == '+INF':\n pass\n elif value.lower() in INVALID_NUMERIC:\n raise ValueError('invalid value {!r} for xs:{}'.format(value, cls.name))\n return float(value)\n\n @classmethod\n def __subclasshook__(cls, subclass: type) -> bool:\n return issubclass(subclass, float) and not issubclass(subclass, Float10)\n\n @classmethod\n def validate(cls, value: object) -> None:\n if isinstance(value, float) and not isinstance(value, Float10):\n return\n elif isinstance(value, str):\n if cls.pattern.match(value) is None:\n raise cls.invalid_value(value)\n else:\n raise cls.invalid_type(value)\n\n\nclass DoubleProxy(DoubleProxy10):\n name = 'double'\n xsd_version = '1.1'\n\n\nclass StringProxy(metaclass=AtomicTypeMeta):\n name = 'string'\n\n def __new__(cls, *args: object, **kwargs: object) -> str: # type: ignore[misc]\n return str(*args, **kwargs)\n\n @classmethod\n def __subclasshook__(cls, subclass: type) -> bool:\n return issubclass(subclass, str)\n\n @classmethod\n def validate(cls, value: object) -> None:\n if not isinstance(value, str):\n raise cls.invalid_type(value)\n\n\n####\n# Type proxies for multiple type-checking in XPath expressions\nclass NumericTypeMeta(type):\n \"\"\"Metaclass for checking numeric classes and instances.\"\"\"\n\n def __instancecheck__(cls, instance: object) -> bool:\n return isinstance(instance, (int, float, Decimal)) and not isinstance(instance, bool)\n\n def __subclasscheck__(cls, subclass: type) -> bool:\n if issubclass(subclass, bool):\n return False\n return issubclass(subclass, int) or issubclass(subclass, float) \\\n or issubclass(subclass, Decimal)\n\n\nclass NumericProxy(metaclass=NumericTypeMeta):\n \"\"\"Proxy for xs:numeric related types. Builds xs:float instances.\"\"\"\n\n def __new__(cls, *args: FloatArgType, **kwargs: FloatArgType) -> float: # type: ignore[misc]\n return float(*args, **kwargs)\n\n\nclass ArithmeticTypeMeta(type):\n \"\"\"Metaclass for checking numeric, datetime and duration classes/instances.\"\"\"\n\n def __instancecheck__(cls, instance: object) -> bool:\n return isinstance(\nNext line of code:\n"}
{"question_id": 2, "category": "longbench_multi_news", "reference": ["Kim Jong Nam's assassins killed him with a banned chemical weapon, Malaysian police revealed Friday. The country's police chief said toxicology reports on swabs from the face and eyes of the exiled North Korean found VX nerve agent, which the BBC notes is classed as a weapon of mass destruction by the United Nations. He said that one of two women believed to have rubbed the extremely toxic substance on Kim's face with their hands suffered from vomiting after the attack. The New York Times reports that VX agent can be created by mixing two compounds—and police suspect the two women put the substances on Kim's face, one after the other, to create a deadly dose. The police chief said the airport where Kim was attacked is now being decontaminated. North Korea—which is widely suspected to have been behind the killing of leader Kim Jong Un's half brother—never signed the Chemical Weapons Convention that banned VX, the AP notes. Pyongyang denies involvement and says Malaysia's investigation is full of \"holes and contradictions.\" The father of one of the two women being held, Vietnamese citizen Doan Thi Huong, tells the Times his daughter trained as a pharmacist and he has seen little of her in recent years. (Police say that after Malaysia refused to give Kim's body to North Korean diplomats, somebody tried to break into the morgue.)"], "prompt": "You are given several news passages. Write a one-page summary of all news. \n\nNews:\nPassage 1:\nIn 1994 and 1995, the Japanese cult Aum Shinrikyo used homemade VX to attack three people, one of whom died. NEWLINE_CHAR NEWLINE_CHAR North Korea is estimated to have a chemical weapons production capability of up to 4,500 metric tons during a typical year and 12,000 tons during a period of extended crisis. It is widely reported to possess a large arsenal of chemical weapons, including mustard, phosgene and sarin gas, a United States Congressional Research Service report said last year. NEWLINE_CHAR NEWLINE_CHAR The announcement by Malaysia’s police chief came just a day after North Korea denied any responsibility for Mr. Kim’s death, accusing the Malaysian authorities of fabricating evidence of Pyongyang’s involvement under the influence of South Korea. NEWLINE_CHAR NEWLINE_CHAR With the North’s reclusive government on the defensive about the Feb. 13 killing of Mr. Kim, the estranged half brother of Kim Jong-un, at the airport for the Malaysian capital, Kuala Lumpur, a statement attributed to the North Korean Jurists Committee said the greatest share of responsibility for the death “rests with the government of Malaysia” because Kim Jong-nam died there. And in what could be seen as a threat to Malaysia, the statement noted that North Korea is a “nuclear weapons state.” NEWLINE_CHAR NEWLINE_CHAR But in a case that has been filled with mysteries and odd plot twists, North Korea still would not acknowledge that the man killed was indeed Kim Jong-nam. And it gave no indication that it would agree to Malaysia’s demands to question a senior staff member at the North Korean Embassy in Kuala Lumpur in the investigation into Mr. Kim’s death. NEWLINE_CHAR NEWLINE_CHAR Relatives and acquaintances of the two women Malaysia has accused of carrying out the killing, by applying poison to Kim-Jong-nam’s face as North Korean agents looked on, insisted they must have been duped into doing so, though the Malaysian authorities say otherwise. NEWLINE_CHAR NEWLINE_CHAR “I don’t believe Huong did such a thing,” said Doan Van Thanh, father of Doan Thi Huong, 28, a Vietnamese woman being held in Malaysia. “She was a very timid girl. When she saw a rat or frog, she would scream.”\nPassage 2:\nMedia playback is unsupported on your device Media caption Rupert Wingfield-Hayes: Three reasons why the use of VX is so extraordinary NEWLINE_CHAR NEWLINE_CHAR Kim Jong-nam, the half-brother of North Korea's leader, was killed by a highly toxic nerve agent, says Malaysia. NEWLINE_CHAR NEWLINE_CHAR Mr Kim died last week after two women accosted him briefly in a check-in hall at a Kuala Lumpur airport. NEWLINE_CHAR NEWLINE_CHAR Malaysian toxicology reports indicate he was attacked using VX nerve agent, which is classified as a weapon of mass destruction by the United Nations. NEWLINE_CHAR NEWLINE_CHAR There is widespread suspicion that North Korea was responsible for the attack, which it fiercely denies. NEWLINE_CHAR NEWLINE_CHAR It responded furiously to Malaysia's insistence on conducting a post-mortem examination and has accused Malaysia of having \"sinister\" purposes. NEWLINE_CHAR NEWLINE_CHAR What does the toxicology report say? NEWLINE_CHAR NEWLINE_CHAR Malaysia's police chief Khalid Abu Bakar said on Friday that the presence of the nerve agent had been detected in swabs taken from Mr Kim's eyes and face. NEWLINE_CHAR NEWLINE_CHAR One of the women Mr Kim interacted with at the airport on 13 February had also fallen ill with vomiting afterwards, he added. NEWLINE_CHAR NEWLINE_CHAR Mr Khalid said other exhibits were still under analysis and that police were investigating how the banned substance might have entered Malaysia. NEWLINE_CHAR NEWLINE_CHAR \"If the amount of the chemical brought in was small, it would be difficult for us to detect,\" he said. NEWLINE_CHAR NEWLINE_CHAR What is the deadly VX nerve agent? NEWLINE_CHAR NEWLINE_CHAR Image copyright Science Photo Library Image caption Molecular model of VX nerve agent shows atoms represented as spheres NEWLINE_CHAR NEWLINE_CHAR The most potent of the known chemical warfare agents, it is a clear, amber-coloured, oily liquid which is tasteless and odourless NEWLINE_CHAR NEWLINE_CHAR Works by penetrating the skin and disrupting the transmission of nerve impulses - a drop on the skin can kill in minutes. Lower doses can cause eye pain, blurred vision, drowsiness and vomiting NEWLINE_CHAR NEWLINE_CHAR It can be disseminated in a spray or vapour when used as a chemical weapon, or used to contaminate water, food, and agricultural products NEWLINE_CHAR NEWLINE_CHAR VX can be absorbed into the body by inhalation, ingestion, skin contact, or eye contact NEWLINE_CHAR NEWLINE_CHAR Clothing can carry VX for about 30 minutes after contact with the vapour, which can expose other people NEWLINE_CHAR NEWLINE_CHAR Banned by the 1993 Chemical Weapons Convention NEWLINE_CHAR NEWLINE_CHAR Read more about VX NEWLINE_CHAR NEWLINE_CHAR Who could be behind the attack? NEWLINE_CHAR NEWLINE_CHAR How could it have killed Mr Kim? NEWLINE_CHAR NEWLINE_CHAR Media playback is unsupported on your device Media caption CCTV footage appears to show the moment Kim Jong-nam is attacked NEWLINE_CHAR NEWLINE_CHAR Bruce Bennett, a weapons expert at the research institute the Rand Corporation, told the BBC it would have taken only a tiny amount of the substance to kill Mr Kim. NEWLINE_CHAR NEWLINE_CHAR He suggests a small quantity of VX - just a drop - was likely to have been put on cloths used by the attackers to touch his face. A separate spray may have been used as a diversion. NEWLINE_CHAR NEWLINE_CHAR Mr Khalid has previously said the fact the woman who accosted Mr Kim immediately went to wash her hands showed she was \"very aware\" that she had been handling a toxin. NEWLINE_CHAR NEWLINE_CHAR It would have begun affecting his nervous system immediately, causing first shaking and then death within minutes. NEWLINE_CHAR NEWLINE_CHAR More from expert Bruce Bennett NEWLINE_CHAR NEWLINE_CHAR Is Kuala Lumpur airport safe? NEWLINE_CHAR NEWLINE_CHAR The authorities say they intend to decontaminate the airport and areas the suspects are known to have visited. NEWLINE_CHAR NEWLINE_CHAR VX is a v-type nerve agent, which means the substance can remain lethal for a long period of time. NEWLINE_CHAR NEWLINE_CHAR \"It's as persistent as motor oil. It's going to stay there for a long time... which means anyone coming in contact with this could be intoxicated from it,\" forensic toxicologist John Trestrail told the Associated Press news agency. NEWLINE_CHAR NEWLINE_CHAR No passengers, airport workers or medical staff who treated Mr Kim were reported to have become ill in the aftermath of the incident, the news agency adds. NEWLINE_CHAR NEWLINE_CHAR Tens of thousands of passengers are believed to have passed through the airport since the attack more than 10 days ago. NEWLINE_CHAR NEWLINE_CHAR Who was Kim Jong-nam? NEWLINE_CHAR NEWLINE_CHAR Image copyright AP Image caption North Korea has not identified the man who died as Kim Jong-nam, only as a North Korean citizen NEWLINE_CHAR NEWLINE_CHAR The well-travelled and multilingual oldest son of late North Korean leader Kim Jong-il, he was once considered a potential future leader. He has lived abroad for years and was bypassed in favour of his half-brother, Kim Jong-un. NEWLINE_CHAR NEWLINE_CHAR He had been travelling on a passport under the name Kim Chol. North Korea has yet to confirm that the deceased was actually Kim Jong-nam. NEWLINE_CHAR NEWLINE_CHAR For many years, it was believed Kim Jong-nam was being groomed to succeed his father as the next leader. NEWLINE_CHAR NEWLINE_CHAR But that appears to have come to an end in 2001 when Kim was caught sneaking into Japan on a fake passport. NEWLINE_CHAR NEWLINE_CHAR He later became one of the regime's most high-profile critics, openly questioning the Stalinist policies and dynastic succession his grandfather Kim Il-sung began crafting in 1948. NEWLINE_CHAR NEWLINE_CHAR Kim Jong-nam: North Korea's critic in exile NEWLINE_CHAR NEWLINE_CHAR How did he die? NEWLINE_CHAR NEWLINE_CHAR A woman was seen in CCTV footage approaching Mr Kim and wiping something across his face. He sought medical help at the airport, saying someone had splashed or sprayed him with liquid. NEWLINE_CHAR NEWLINE_CHAR He had a seizure and died on the way to hospital. NEWLINE_CHAR NEWLINE_CHAR His body remains in the hospital's mortuary, amid a diplomatic dispute over who should claim it. NEWLINE_CHAR NEWLINE_CHAR Main players in mysterious killing NEWLINE_CHAR NEWLINE_CHAR Who did it? NEWLINE_CHAR NEWLINE_CHAR Malaysia says it was clearly an attack by North Korean agents. Four people are in custody, including one North Korean and the two women he interacted with at the airport. Seven North Koreans are being sought, including a diplomat. NEWLINE_CHAR NEWLINE_CHAR There are a number of North Korean organisations capable of directing such an attack, including the exclusive Guard Command. NEWLINE_CHAR NEWLINE_CHAR The North hit back at Malaysia on Thursday, saying it was responsible for the death of one of its citizens. NEWLINE_CHAR NEWLINE_CHAR In response, Malaysian Foreign Minister Anifah Aman warned North Korean envoy Kang Chol on Friday that he would be expelled unless he stopped \"spewing lies\" about the attack. NEWLINE_CHAR NEWLINE_CHAR Who in North Korea could organise a VX murder? NEWLINE_CHAR NEWLINE_CHAR North Korea's history of foreign assassinations NEWLINE_CHAR NEWLINE_CHAR Does North Korea have VX? NEWLINE_CHAR NEWLINE_CHAR North Korea is one of just six countries not to have signed the Chemical Weapons Convention (CWC) arms control treaty banning the production, stockpiling and use of chemical weapons. NEWLINE_CHAR NEWLINE_CHAR According to the Nuclear Threat Initiative project, however, North Korea is thought to have the third largest stockpile of chemical weapons, after the US and Russia. NEWLINE_CHAR NEWLINE_CHAR South Korea's defence ministry estimated in 2014 that the North has somewhere between 2,500 and 5,000 tonnes of nerve agents in stock, with VX identified as among them.\nPassage 3:\nFILE - In this May 4, 2001, file photo, a man believed to be Kim Jong Nam, the eldest son of then North Korean leader Kim Jong Il, looks at a battery of photographers as he exits a police van to board... (Associated Press) NEWLINE_CHAR NEWLINE_CHAR FILE - In this May 4, 2001, file photo, a man believed to be Kim Jong Nam, the eldest son of then North Korean leader Kim Jong Il, looks at a battery of photographers as he exits a police van to board a plane to Beijing at Narita international airport in Narita, northeast of Tokyo. Police in Malaysia... (Associated Press) NEWLINE_CHAR NEWLINE_CHAR KUALA LUMPUR, Malaysia (AP) — The banned chemical weapon VX nerve agent was used to kill Kim Jong Nam, the North Korean ruler's outcast half brother who was poisoned last week at the airport in Kuala Lumpur, police said Friday. The announcement raised serious questions about public safety in a building that authorities went 11 days without decontaminating. NEWLINE_CHAR NEWLINE_CHAR The substance, deadly even in minute amounts, was detected on Kim's eyes and face, Malaysia's inspector general of police said in a written statement, citing a preliminary analysis from the country's Chemistry Department. NEWLINE_CHAR NEWLINE_CHAR \"Our preliminary finding of the chemical that caused the death of Kim Chol was VX nerve,\" said Inspector-General of Police Khalid Abu Bakar. Kim Chol is the name on the passport found on the victim, but a Malaysian official previously confirmed he is North Korea leader Kim Jong Un's older half brother. NEWLINE_CHAR NEWLINE_CHAR Khalid told reporters that one of the two women accused of wiping the toxin on Kim's face was later sickened and suffered from vomiting. He declined to say which of the women — one Indonesian and one Vietnamese — had gotten sick. NEWLINE_CHAR NEWLINE_CHAR Khalid said police were still investigating how the lethal agent entered Malaysia. NEWLINE_CHAR NEWLINE_CHAR Police previously said the airport had not been decontaminated. Asked Friday in a text message whether that was still the case, Khalid said, \"We are doing it now.\" Details were not immediately clear. NEWLINE_CHAR NEWLINE_CHAR Malaysian police also previously no one besides Kim Jong Nam had been sickened. NEWLINE_CHAR NEWLINE_CHAR If VX was used, it could have contaminated not only the airport but anyplace else Kim had been, including medical facilities and the ambulance he was transported in. The nerve agent, which has the consistency of motor oil, can take days or even weeks to evaporate. NEWLINE_CHAR NEWLINE_CHAR The death of Kim Jong Nam, whose daylight assassination in a crowded airport terminal seems straight out of a spy novel, has unleashed a diplomatic crisis that escalates by the day. With each new twist in the case, international speculation has grown that Pyongyang dispatched a hit squad to Malaysia to kill the exiled older sibling of North Korean leader Kim Jong Un. NEWLINE_CHAR NEWLINE_CHAR North Korea has denounced Malaysia's investigation as full of \"holes and contradictions\" and accused the authorities here of being in cahoots with Pyongyang's enemies. NEWLINE_CHAR NEWLINE_CHAR According to Malaysian investigators, the two female suspects coated their hands with chemicals and wiped them on Kim's face on Feb. 13 as he waited for a flight home to Macau, where he lived with his family. NEWLINE_CHAR NEWLINE_CHAR He sought help from airport staff but he fell into convulsions and died on the way to the hospital within two hours of the attack, police said. NEWLINE_CHAR NEWLINE_CHAR The case has perplexed toxicologists, who question how the two women could have walked away unscathed after handling a powerful poison, even if — as Malaysian police say — the women were instructed to wash their hands right after the attack. NEWLINE_CHAR NEWLINE_CHAR Dr. Bruce Goldberger, a leading toxicologist who heads the forensic medicine division at the University of Florida, said even a tiny amount of VX nerve agent — equal to a few grains of salt — is capable of killing. It can be administered through the skin, and there is an antidote that can be administered by injection. U.S. medics and military personnel carried kits with them on the battlefield during the Iraq war in case they were exposed to the chemical weapon. NEWLINE_CHAR NEWLINE_CHAR \"It's a very toxic nerve agent. Very, very toxic,\" he said. \"I'm intrigued that these two alleged assassins suffered no ill effect from exposure to VX. It is possible that both of these women were given the antidote.\" NEWLINE_CHAR NEWLINE_CHAR He said symptoms from VX would generally occur within seconds or minutes and could last for hours starting with confusion, possible drowsiness, headache, nausea, vomiting, runny nose and watery eyes. Prior to death, there would likely be convulsions, seizures, loss of consciousness and paralysis. NEWLINE_CHAR NEWLINE_CHAR VX is banned under the Chemical Weapons Convention, which North Korea never signed. The country is believed by outside experts to have the capacity to produce up to 4,500 metric tons of chemical weapons during a typical year, which it could increase to 12,000 tons per year during a period of crisis. Its current inventory has been estimated at 2,500 to 5,000 tons. NEWLINE_CHAR NEWLINE_CHAR It is suspected of being particularly focused on mustard, phosgene, sarin and V-type chemical agents — substances including VX that are designed to poison through contact and remain lethal for long periods of time. The North's development of such agents has been of special concern because of fears it might try to put them in artillery shells for an attack on South Korea's capital, potentially threatening the lives of millions. NEWLINE_CHAR NEWLINE_CHAR Joseph Bermudez, a well-known North Korea analyst, wrote an article for the respected 38 North website in 2013 that said the North is capable of not only employing \"significant quantities and varieties of chemical weapons\" across the Korean Peninsula but also using those weapons worldwide \"using unconventional methods of delivery.\" NEWLINE_CHAR NEWLINE_CHAR He also said there is a \"growing body of evidence\" indicating the North has shared chemical weapons capabilities with Syria, Iran and others. NEWLINE_CHAR NEWLINE_CHAR Malaysia has three people in custody in connection with Kim Jong Nam's death, including the two suspected attackers. Authorities are also seeking several other people, including the second secretary of North Korea's embassy in Kuala Lumpur and an employee of North Korea's state-owned airline, Air Koryo. NEWLINE_CHAR NEWLINE_CHAR The case has marked a serious turnaround in relations between Malaysia and North Korea. While Malaysia isn't one of Pyongyang's key diplomatic partners, it is one of the few places in the world where North Koreans can travel without a visa. As a result, for years, it's been a quiet destination for Northerners looking for jobs, schools and business deals. NEWLINE_CHAR NEWLINE_CHAR ___ NEWLINE_CHAR NEWLINE_CHAR AP writers Margie Mason in Jakarta, Indonesia, and Eric Talmadge in Tokyo contributed to this report.\n\n\nNow, write a one-page summary of all the news.\n\nSummary:"}
{"question_id": 3, "category": "longbench_lcc", "reference": [" object obj = this.ViewState[\"SubmitText\"];"], "prompt": "Please complete the code given below. \n/********\n * This file is part of Ext.NET.\n * \n * Ext.NET is free software: you can redistribute it and/or modify\n * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as \n * published by the Free Software Foundation, either version 3 of the \n * License, or (at your option) any later version.\n * \n * Ext.NET is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU AFFERO GENERAL PUBLIC LICENSE for more details.\n * \n * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE\n * along with Ext.NET. If not, see <http://www.gnu.org/licenses/>.\n *\n *\n * @version : 1.2.0 - Ext.NET Pro License\n * @author : Ext.NET, Inc. http://www.ext.net/\n * @date : 2011-09-12\n * @copyright : Copyright (c) 2006-2011, Ext.NET, Inc. (http://www.ext.net/). All rights reserved.\n * @license : GNU AFFERO GENERAL PUBLIC LICENSE (AGPL) 3.0. \n * See license.txt and http://www.ext.net/license/.\n * See AGPL License at http://www.gnu.org/licenses/agpl-3.0.txt\n ********/\nusing System;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Web.UI;\nusing Newtonsoft.Json;\nusing Ext.Net.Utilities;\nnamespace Ext.Net\n{\n /// <summary>\n /// \n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n [Meta]\n [Description(\"\")]\n public abstract partial class MultiSelectBase<T> : Field, IStore where T : StateManagedItem \n {\n /// <summary>\n /// The data store to use.\n /// </summary>\n [Meta]\n [ConfigOption(\"store\", JsonMode.ToClientID)]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [IDReferenceProperty(typeof(Store))]\n [Description(\"The data store to use.\")]\n public virtual string StoreID\n {\n get\n {\n return (string)this.ViewState[\"StoreID\"] ?? \"\";\n }\n set\n {\n this.ViewState[\"StoreID\"] = value;\n }\n }\n private StoreCollection store;\n /// <summary>\n /// The data store to use.\n /// </summary>\n [Meta]\n [ConfigOption(\"store>Primary\")]\n [Category(\"7. MultiSelect\")]\n [PersistenceMode(PersistenceMode.InnerProperty)]\n [Description(\"The data store to use.\")]\n public virtual StoreCollection Store\n {\n get\n {\n if (this.store == null)\n {\n this.store = new StoreCollection();\n this.store.AfterItemAdd += this.AfterStoreAdd;\n this.store.AfterItemRemove += this.AfterStoreRemove;\n }\n return this.store;\n }\n }\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t[Description(\"\")]\n protected virtual void AfterStoreAdd(Store item)\n {\n this.Controls.AddAt(0, item);\n this.LazyItems.Insert(0, item);\n }\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t[Description(\"\")]\n protected virtual void AfterStoreRemove(Store item)\n {\n this.Controls.Remove(item);\n this.LazyItems.Remove(item);\n }\n private ListItemCollection<T> items;\n /// <summary>\n /// \n /// </summary>\n [Meta]\n [PersistenceMode(PersistenceMode.InnerProperty)]\n [ViewStateMember]\n [Description(\"\")]\n public ListItemCollection<T> Items\n {\n get\n {\n if (this.items == null)\n {\n this.items = new ListItemCollection<T>();\n }\n return this.items;\n }\n }\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n [ConfigOption(\"store\", JsonMode.Raw)]\n [DefaultValue(\"\")]\n\t\t[Description(\"\")]\n protected string ItemsProxy\n {\n get\n {\n if (this.StoreID.IsNotEmpty() || this.Store.Primary != null)\n {\n return \"\";\n }\n return this.ItemsToStore;\n }\n }\n private string ItemsToStore\n {\n get\n {\n StringWriter sw = new StringWriter();\n JsonTextWriter jw = new JsonTextWriter(sw);\n ListItemCollectionJsonConverter converter = new ListItemCollectionJsonConverter();\n converter.WriteJson(jw, this.Items, null);\n return sw.GetStringBuilder().ToString();\n }\n }\n private SelectedListItemCollection selectedItems;\n /// <summary>\n /// \n /// </summary>\n [Meta]\n [PersistenceMode(PersistenceMode.InnerProperty)]\n [ViewStateMember]\n [Description(\"\")]\n public SelectedListItemCollection SelectedItems\n {\n get\n {\n if (this.selectedItems == null)\n {\n this.selectedItems = new SelectedListItemCollection();\n }\n return this.selectedItems;\n }\n }\n /// <summary>\n /// The underlying data field name to bind to this MultiSelect.\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Description(\"The underlying data field name to bind to this MultiSelect.\")]\n public virtual string DisplayField\n {\n get\n {\n return (string)this.ViewState[\"DisplayField\"] ?? \"text\";\n }\n set\n {\n this.ViewState[\"DisplayField\"] = value;\n }\n }\n /// <summary>\n /// The underlying data value name to bind to this MultiSelect.\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Description(\"The underlying data value name to bind to this MultiSelect.\")]\n public virtual string ValueField\n {\n get\n {\n return (string)this.ViewState[\"ValueField\"] ?? \"value\";\n }\n set\n {\n this.ViewState[\"ValueField\"] = value;\n }\n }\n /// <summary>\n /// False to validate that the value length > 0 (defaults to true).\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(true)]\n [Description(\"False to validate that the value length > 0 (defaults to true).\")]\n public virtual bool AllowBlank\n {\n get\n {\n object obj = this.ViewState[\"AllowBlank\"];\n return (obj == null) ? true : (bool)obj;\n }\n set\n {\n this.ViewState[\"AllowBlank\"] = value;\n }\n }\n /// <summary>\n /// Maximum input field length allowed (defaults to Number.MAX_VALUE).\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(-1)]\n [Description(\"Maximum input field length allowed (defaults to Number.MAX_VALUE).\")]\n public virtual int MaxLength\n {\n get\n {\n object obj = this.ViewState[\"MaxLength\"];\n return (obj == null) ? -1 : (int)obj;\n }\n set\n {\n this.ViewState[\"MaxLength\"] = value;\n }\n }\n /// <summary>\n /// Minimum input field length required (defaults to 0).\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(0)]\n [Description(\"Minimum input field length required (defaults to 0).\")]\n public virtual int MinLength\n {\n get\n {\n object obj = this.ViewState[\"MinLength\"];\n return (obj == null) ? 0 : (int)obj;\n }\n set\n {\n this.ViewState[\"MinLength\"] = value;\n }\n }\n /// <summary>\n /// Error text to display if the maximum length validation fails (defaults to 'The maximum length for this field is {maxLength}').\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Localizable(true)]\n [Description(\"Error text to display if the maximum length validation fails (defaults to 'The maximum length for this field is {maxLength}').\")]\n public virtual string MaxLengthText\n {\n get\n {\n return (string)this.ViewState[\"MaxLengthText\"] ?? \"\";\n }\n set\n {\n this.ViewState[\"MaxLengthText\"] = value;\n }\n }\n /// <summary>\n /// Error text to display if the minimum length validation fails (defaults to 'The minimum length for this field is {minLength}').\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Localizable(true)]\n [Description(\"Error text to display if the minimum length validation fails (defaults to 'The minimum length for this field is {minLength}').\")]\n public virtual string MinLengthText\n {\n get\n {\n return (string)this.ViewState[\"MinLengthText\"] ?? \"\";\n }\n set\n {\n this.ViewState[\"MinLengthText\"] = value;\n }\n }\n /// <summary>\n /// Error text to display if the allow blank validation fails (defaults to 'This field is required').\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Localizable(true)]\n [Description(\"Error text to display if the allow blank validation fails (defaults to 'This field is required').\")]\n public virtual string BlankText\n {\n get\n {\n return (string)this.ViewState[\"BlankText\"] ?? \"\";\n }\n set\n {\n this.ViewState[\"BlankText\"] = value;\n }\n }\n /// <summary>\n /// Causes drag operations to copy nodes rather than move (defaults to false).\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(false)]\n [Description(\"Causes drag operations to copy nodes rather than move (defaults to false).\")]\n public virtual bool Copy\n {\n get\n {\n object obj = this.ViewState[\"Copy\"];\n return (obj == null) ? false : (bool)obj;\n }\n set\n {\n this.ViewState[\"Copy\"] = value;\n }\n }\n /// <summary>\n /// \n /// </summary>\n [Meta]\n [ConfigOption(\"allowDup\")]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(false)]\n [Description(\"\")]\n public virtual bool AllowDuplicates\n {\n get\n {\n object obj = this.ViewState[\"AllowDuplicates\"];\n return (obj == null) ? false : (bool)obj;\n }\n set\n {\n this.ViewState[\"AllowDuplicates\"] = value;\n }\n }\n /// <summary>\n /// \n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(false)]\n [Description(\"\")]\n public virtual bool AllowTrash\n {\n get\n {\n object obj = this.ViewState[\"AllowTrash\"];\n return (obj == null) ? false : (bool)obj;\n }\n set\n {\n this.ViewState[\"AllowTrash\"] = value;\n }\n }\n /// <summary>\n /// The title text to display in the panel header (defaults to '')\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Description(\"The title text to display in the panel header (defaults to '')\")]\n public virtual string Legend\n {\n get\n {\n return (string)this.ViewState[\"Legend\"] ?? \"\";\n }\n set\n {\n this.ViewState[\"Legend\"] = value;\n }\n }\n /// <summary>\n /// The string used to delimit between items when set or returned as a string of values\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\",\")]\n [Description(\"The string used to delimit between items when set or returned as a string of values\")]\n public virtual string Delimiter\n {\n get\n {\n return (string)this.ViewState[\"Delimiter\"] ?? \",\";\n }\n set\n {\n this.ViewState[\"Delimiter\"] = value;\n }\n }\n /// <summary>\n /// The ddgroup name(s) for the View's DragZone (defaults to undefined).\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Description(\"The ddgroup name(s) for the View's DragZone (defaults to undefined).\")]\n public virtual string DragGroup\n {\n get\n {\n return (string)this.ViewState[\"DragGroup\"] ?? \"\";\n }\n set\n {\n this.ViewState[\"DragGroup\"] = value;\n }\n }\n /// <summary>\n /// The ddgroup name(s) for the View's DropZone (defaults to undefined).\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Description(\"The ddgroup name(s) for the View's DropZone (defaults to undefined).\")]\n public virtual string DropGroup\n {\n get\n {\n return (string)this.ViewState[\"DropGroup\"] ?? \"\";\n }\n set\n {\n this.ViewState[\"DropGroup\"] = value;\n }\n }\n /// <summary>\n /// \n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(false)]\n [Description(\"\")]\n public virtual bool AppendOnly\n {\n get\n {\n object obj = this.ViewState[\"AppendOnly\"];\n return (obj == null) ? false : (bool)obj;\n }\n set\n {\n this.ViewState[\"AppendOnly\"] = value;\n }\n }\n /// <summary>\n /// \n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(\"\")]\n [Description(\"\")]\n public virtual string SortField\n {\n get\n {\n return (string)this.ViewState[\"SortField\"] ?? \"\";\n }\n set\n {\n this.ViewState[\"SortField\"] = value;\n }\n }\n /// <summary>\n /// \n /// </summary>\n [Meta]\n [ConfigOption(JsonMode.ToLower)]\n [DefaultValue(SortDirection.ASC)]\n [NotifyParentProperty(true)]\n [Description(\"\")]\n public SortDirection Direction\n {\n get\n {\n object obj = this.ViewState[\"Direction\"];\n return (obj == null) ? SortDirection.ASC : (SortDirection)obj;\n }\n set\n {\n this.ViewState[\"Direction\"] = value;\n }\n }\n /// <summary>\n /// True to submit text of selected items\n /// </summary>\n [Meta]\n [ConfigOption]\n [Category(\"6. MultiSelect\")]\n [DefaultValue(true)]\n [Description(\"True to submit text of selected items\")]\n public virtual bool SubmitText\n {\n get\n {\nNext line of code:\n"}
{"question_id": 4, "category": "longbench_repobench-p", "reference": [" CloseHandle(handle) # will raise exception if the handle is invalid"], "prompt": "Please complete the code given below. \npywincffi/dev/testutil.py\nclass TestCase(_TestCase): # pylint: disable=too-many-public-methods\n \"\"\"\n A base class for all test cases. By default the\n core test case just provides some extra functionality.\n \"\"\"\n # A list of hosts and port to check for internet access on. If we fail\n # to reach any of the hosts in `INTERNET_HOSTS` on `INTERNET_PORT` then\n # `HAS_INTERNET` will be set to False.\n INTERNET_PORT = 80\n INTERNET_HOSTS = (\"github.com\", \"readthedocs.org\", \"example.com\")\n REQUIRES_INTERNET = False\n HAS_INTERNET = None\n\n # Class level attributes used to access some specific Windows API\n # functions when testing. This is kept separate from what `dist.load()`\n # produces so problems in the build don't break parts of the base TestCase.\n ffi = None\n kernel32 = None\n ws2_32 = None\n\n @classmethod\n def setUpClass(cls):\n # Reset everything back to the default values first.\n cls.ffi = None\n cls.kernel32 = None\n cls.ws2_32 = None\n cls.HAS_INTERNET = None\n\n # First run and this test case requires internet access. Determine\n # if we have access to the internet then cache the value.\n if cls.REQUIRES_INTERNET and SharedState.HAS_INTERNET is None:\n original_timeout = socket.getdefaulttimeout()\n socket.setdefaulttimeout(1)\n\n try:\n for hostname in cls.INTERNET_HOSTS:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n sock.connect((hostname, cls.INTERNET_PORT))\n SharedState.HAS_INTERNET = True\n break\n\n # pylint: disable=broad-except\n except Exception: # pragma: no cover\n pass\n\n finally:\n sock.close()\n else: # pragma: no cover\n SharedState.HAS_INTERNET = False\n finally:\n socket.setdefaulttimeout(original_timeout)\n\n if os.name == \"nt\" and SharedState.ffi is None:\n try:\n ffi = FFI()\n ffi.set_unicode(True)\n ffi.cdef(dedent(\"\"\"\n // kernel32 functions\n DWORD GetLastError(void);\n void SetLastError(DWORD);\n\n // ws2_32 functions\n void WSASetLastError(int);\n int WSAGetLastError(void);\n \"\"\"))\n SharedState.ffi = ffi\n SharedState.kernel32 = ffi.dlopen(\"kernel32\")\n SharedState.ws2_32 = ffi.dlopen(\"ws2_32\")\n\n # pylint: disable=broad-except\n except Exception as error: # pragma: no cover\n if os.name == \"nt\":\n SharedState.ffi = error\n\n cls.HAS_INTERNET = SharedState.HAS_INTERNET\n cls.ffi = SharedState.ffi\n cls.kernel32 = SharedState.kernel32\n cls.ws2_32 = SharedState.ws2_32\n\n def setUp(self): # pragma: no cover\n if self.REQUIRES_INTERNET and not self.HAS_INTERNET:\n if os.environ.get(\"CI\"):\n self.fail(\n \"%s requires internet but we do not seem to be \"\n \"connected.\" % self.__class__.__name__)\n\n self.skipTest(\"Internet unavailable\")\n\n if os.name != \"nt\":\n return\n\n if isinstance(self.ffi, Exception):\n self.fail(\"FFI module setup failed: %s\" % self.ffi)\n\n self.assertIsNotNone(\n self.kernel32, \"setUp() failed: missing kernel32\")\n self.assertIsNotNone(\n self.ws2_32, \"setUp() failed: missing ws2_32\")\n\n self.addCleanup(self.unhandled_error_check)\n\n # Always reset the last error to 0 between tests. This ensures\n # that if an unhandled API error occurs it won't impact the\n # currently running test. The cleanup step above will ensure that\n # tests that do not exit cleanly will cause a failure.\n self.kernel32.SetLastError(0)\n self.ws2_32.WSASetLastError(0)\n\n def GetLastError(self): # pylint: disable=invalid-name\n \"\"\"\n Returns a tuple containing output from the Windows GetLastError\n function and the associated error message. The error message will\n be None if GetLastError() returns 0.\n \"\"\"\n errno = self.kernel32.GetLastError()\n return errno, self.ffi.getwinerror(errno) if errno != 0 else None\n\n def WSAGetLastError(self): # pylint: disable=invalid-name\n \"\"\"\n Returns a tuple containing output from the Windows WSAGetLastError\n function and the associated error message. The error message will\n be None if WSAGetLastError() returns 0.\n \"\"\"\n errno = self.ws2_32.WSAGetLastError()\n return errno, self.ffi.getwinerror(errno) if errno != 0 else None\n\n def WSASetLastError(self, errno): # pylint: disable=invalid-name\n \"\"\"Wrapper for WSASetLastError()\"\"\"\n self.ws2_32.WSASetLastError(errno)\n\n def SetLastError(self, errno): # pylint: disable=invalid-name\n \"\"\"Wrapper for SetLastError()\"\"\"\n self.kernel32.SetLastError(errno)\n\n def unhandled_error_check(self):\n \"\"\"\n A cleanup step which ensures that there are not any uncaught API\n errors left over. Unhandled errors could be a sign of an unhandled\n testing artifact, improper API usage or other problem. In any case,\n unhandled errors are often a source of test flake.\n \"\"\"\n # Check for kernel32 errors.\n k32_errno, k32_message = self.GetLastError()\n self.assertEqual(\n k32_errno, 0,\n msg=\"Unhandled kernel32 error. Errno: %r. Message: %r\" % (\n k32_errno, k32_message))\n\n # Check for ws2_32 errors.\n ws2_errno, ws2_message = self.WSAGetLastError()\n self.assertEqual(\n ws2_errno, 0,\n msg=\"Unhandled ws2_32 error. Errno: %r. Message: %r\" % (\n ws2_errno, ws2_message))\n\n def _terminate_process(self, process): # pylint: disable=no-self-use\n \"\"\"\n Calls terminnate() on ``process`` and ignores any errors produced.\n \"\"\"\n try:\n process.terminate()\n\n # pylint: disable=broad-except\n except Exception: # pragma: no cover\n pass\n\n def create_python_process(self, command):\n \"\"\"Creates a Python process that run ``command``\"\"\"\n process = subprocess.Popen(\n [sys.executable, \"-c\", command],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n self.addCleanup(self._terminate_process, process)\n return process\n\n def random_string(self, length):\n \"\"\"\n Returns a random string as long as ``length``. The first character\n will always be a letter. All other characters will be A-F,\n A-F or 0-9.\n \"\"\"\n if length < 1: # pragma: no cover\n self.fail(\"Length must be at least 1.\")\n\n # First character should always be a letter so the string\n # can be used in object names.\n output = choice(ascii_lowercase)\n length -= 1\n\n while length:\n length -= 1\n output += choice(ascii_lowercase + ascii_uppercase + \"0123456789\")\n\n return output\n\n def assert_last_error(self, errno):\n \"\"\"\n This function will assert that the last unhandled error\n was ``errno``. After the check the last error will be reset to\n zero.\n\n :param int errno:\n The expected value from GetLastError.\n \"\"\"\n last_error, _ = self.GetLastError()\n self.assertEqual(last_error, errno)\n self.SetLastError(0)\n\n def maybe_assert_last_error(self, errno):\n \"\"\"\n This function is similar to :meth:`assert_last_error` except\n it won't fail if the current error number is already 0.\n \"\"\"\n last_error, _ = self.GetLastError()\n self.assertIn(last_error, (0, errno))\n self.SetLastError(0)\npywincffi/kernel32/events.py\ndef SetEvent(hEvent):\n \"\"\"\n Sets the specified event object to the signaled state.\n\n .. seealso::\n\n https://msdn.microsoft.com/en-us/library/ms686211\n\n :param pywincffi.wintypes.HANDLE hEvent:\n A handle to the event object. The handle must have the\n ``EVENT_MODIFY_STATE`` access right.\n \"\"\"\n input_check(\"hEvent\", hEvent, HANDLE)\n\n _, library = dist.load()\n code = library.SetEvent(wintype_to_cdata(hEvent))\n error_check(\"SetEvent\", code=code, expected=NON_ZERO)\npywincffi/kernel32/events.py\ndef CreateEvent(\n lpEventAttributes=None, bManualReset=True, bInitialState=False,\n lpName=None):\ndef OpenEvent(dwDesiredAccess, bInheritHandle, lpName):\ndef ResetEvent(hEvent):\ndef SetEvent(hEvent):\npywincffi/kernel32/events.py\ndef OpenEvent(dwDesiredAccess, bInheritHandle, lpName):\n \"\"\"\n Opens an existing named event.\n\n .. seealso::\n\n https://msdn.microsoft.com/en-us/library/ms684305\n\n :param int dwDesiredAccess:\n The access desired for the event object.\n\n :param bool bInheritHandle:\n :param str lpName:\n Type is ``unicode`` on Python 2, ``str`` on Python 3.\n\n :return:\n Returns a :class:`pywincffi.wintypes.HANDLE` to the event.\n \"\"\"\n input_check(\"dwDesiredAccess\", dwDesiredAccess, integer_types)\n input_check(\"bInheritHandle\", bInheritHandle, bool)\n input_check(\"lpName\", lpName, text_type)\n\n ffi, library = dist.load()\n\n handle = library.OpenEvent(\n ffi.cast(\"DWORD\", dwDesiredAccess),\n ffi.cast(\"BOOL\", bInheritHandle),\n lpName\n )\n error_check(\"OpenEvent\")\n return HANDLE(handle)\npywincffi/kernel32/events.py\ndef ResetEvent(hEvent):\n \"\"\"\n Sets the specified event object to the nonsignaled state.\n\n .. seealso::\n\n https://msdn.microsoft.com/en-us/library/ms684305\n\n :param pywincffi.wintypes.HANDLE hEvent:\n A handle to the event object to be reset. The handle must\n have the ``EVENT_MODIFY_STATE`` access right.\n \"\"\"\n input_check(\"hEvent\", hEvent, HANDLE)\n\n _, library = dist.load()\n code = library.ResetEvent(wintype_to_cdata(hEvent))\n error_check(\"ResetEvent\", code=code, expected=NON_ZERO)\npywincffi/kernel32/synchronization.py\ndef WaitForSingleObject(hHandle, dwMilliseconds):\n \"\"\"\n Waits for the specified object to be in a signaled state\n or for ``dwMiliseconds`` to elapse.\n\n .. seealso::\n\n https://msdn.microsoft.com/en-us/library/ms687032\n\n :param pywincffi.wintypes.HANDLE hHandle:\n The handle to wait on.\n\n :param int dwMilliseconds:\n The time-out interval.\n \"\"\"\n input_check(\"hHandle\", hHandle, HANDLE)\n input_check(\"dwMilliseconds\", dwMilliseconds, integer_types)\n\n ffi, library = dist.load()\n result = library.WaitForSingleObject(\n wintype_to_cdata(hHandle), ffi.cast(\"DWORD\", dwMilliseconds)\n )\n\n if result == library.WAIT_FAILED:\n raise WindowsAPIError(\n \"WaitForSingleObject\", \"Wait Failed\", ffi.getwinerror()[-1],\n return_code=result, expected_return_code=\"not %s\" % result)\n\n error_check(\"WaitForSingleObject\")\n\n return result\npywincffi/exceptions.py\nclass InputError(PyWinCFFIError):\n \"\"\"\n A subclass of :class:`PyWinCFFIError` that's raised when invalid input\n is provided to a function. Because we're passing inputs to C we have\n to be sure that the input(s) being provided are what we're expecting so\n we fail early and provide better error messages.\n\n :param str name:\n The name of the parameter being checked.\n\n :param value:\n The value of the parameter being checked.\n\n :keyword allowed_types:\n The expected type(s). If provided then the exception's message will\n be tailored to provide information about ``value``'s type and the\n possible input types.\n\n :keyword allowed_values:\n The expected value(s). If provided then the exception's message will\n be tailored to provide information about what value(s) were allowed\n for ``value``.\n\n :keyword ffi:\n If ``value`` is a C object, ``ffi`` is provided and ``allowed_types``\n is provided as well then the provided ``ffi`` instance will be used\n to provide additional context.\n\n :keyword str message:\n A custom error message. This will override the default error messages\n which :class:`InputError` would normally generate. This can be\n helpful if there is a problem with a given input parameter to a\n function but it's unrelated to the type of input.\n \"\"\"\n def __init__( # pylint: disable=too-many-arguments\n self, name, value,\n allowed_types=None, allowed_values=None, ffi=None, message=None):\n if allowed_types is not None and allowed_values is not None:\n raise ValueError(\n \"Please provide either `allowed_types` or `allowed_values`\")\n\n if (allowed_types is None and allowed_values is None and\n message is None):\n raise ValueError(\n \"Please provide `allowed_types`, `allowed_values` or \"\n \"`message`\")\n\n self.name = name\n self.value = value\n self.allowed_types = allowed_types\n self.allowed_values = allowed_values\n self.message = message\n\n if self.message is None and self.allowed_types is not None:\n if ffi is None:\n typeof = repr(type(value))\n else:\n try:\n ffi_exceptions = (TypeError, CDefError, ffi.error)\n except AttributeError: # pragma: no cover\n ffi_exceptions = (TypeError, CDefError)\n\n try:\n typeof = ffi.typeof(value)\n except ffi_exceptions:\n typeof = repr(type(value))\n else:\n typeof = \"{classname}(kind={kind}, cname={cname})\".format(\n classname=value.__class__.__name__,\n kind=repr(typeof.kind), cname=repr(typeof.cname))\n\n self.message = \\\n \"Expected type(s) {expected} for {name}. Type of {name} \" \\\n \"is {typeof}.\".format(\n expected=repr(allowed_types), name=repr(name),\n typeof=typeof)\n\n elif self.message is None and self.allowed_values is not None:\n self.message = \\\n \"Expected the value of {name} to be in {values}. Value of \" \\\n \"{name} is {value}.\".format(\n name=repr(name), values=allowed_values, value=repr(value))\n\n super(InputError, self).__init__(self.message)\npywincffi/core/dist.py\nMODULE_NAME = \"_pywincffi\"\nHEADER_FILES = (\n resource_filename(\n \"pywincffi\", join(\"core\", \"cdefs\", \"headers\", \"typedefs.h\")),\n resource_filename(\n \"pywincffi\", join(\"core\", \"cdefs\", \"headers\", \"constants.h\")),\n resource_filename(\n \"pywincffi\", join(\"core\", \"cdefs\", \"headers\", \"structs.h\")),\n resource_filename(\n \"pywincffi\", join(\"core\", \"cdefs\", \"headers\", \"functions.h\")))\nSOURCE_FILES = (\n resource_filename(\n \"pywincffi\", join(\"core\", \"cdefs\", \"sources\", \"main.c\")), )\nLIBRARIES = (\"kernel32\", \"user32\", \"Ws2_32\")\nREGEX_SAL_ANNOTATION = re.compile(\n r\"\\b(_In_|_Inout_|_Out_|_Outptr_|_Reserved_)(opt_)?\\b\")\n _RUNTIME_CONSTANTS = dict(\n # Defined here because cffi can't handle negative values\n # in constants yet.\n INVALID_HANDLE_VALUE=-1,\n\n # The maximum length of the lpCommandLine input to a CreateProcess\n # call:\n # https://msdn.microsoft.com/en-us/library/ms682425\n # Technically, this is not a Windows constant. It's something that\n # pywincffi defines for ease of use and to limit the possibility of\n # typos.\n MAX_COMMAND_LINE=32768\n )\nclass LibraryWrapper(object): # pylint: disable=too-few-public-methods\nclass Loader(object):\n def __init__(self, library):\n def __dir__(self):\n def __getattribute__(self, item):\n def __getattr__(self, item):\n def __repr__(self): # pragma: no cover\n def set(cls, ffi, library):\n def get(cls):\ndef _import_path(path, module_name=MODULE_NAME):\ndef _read(*paths):\ndef _ffi(\n module_name=MODULE_NAME, headers=HEADER_FILES, sources=SOURCE_FILES,\n libraries=LIBRARIES):\ndef _compile(ffi, tmpdir=None, module_name=MODULE_NAME):\ndef load():\npywincffi/kernel32/events.py\ndef CreateEvent(\n lpEventAttributes=None, bManualReset=True, bInitialState=False,\n lpName=None):\n \"\"\"\n Creates or opens an named or unnamed event object.\n\n .. seealso::\n\n https://msdn.microsoft.com/en-us/library/ms682396\n\n :keyword :class:`pywincffi.wintypes.SECURITY_ATTRIBUTES` lpEventAttributes:\n If not provided then, by default, the handle cannot be inherited\n by a subprocess.\n\n :keyword bool bManualReset:\n If True then this function will create a manual reset\n event which must be manually reset with :func:`ResetEvent`. Refer\n to the msdn documentation for full information.\n\n **Default:** ``True``\n\n :keyword bool bInitialState:\n If True the initial state will be 'signaled'.\n\n **Default:** ``False``\n\n :keyword str lpName:\n Type is ``unicode`` on Python 2, ``str`` on Python 3.\n The optional case-sensitive name of the event. If not provided then\n the event will be created without an explicit name.\n\n :returns:\n Returns a :class:`pywincffi.wintypes.HANDLE` to the event. If an event\n by the given name already exists then it will be returned instead of\n creating a new event.\n \"\"\"\n input_check(\"bManualReset\", bManualReset, bool)\n input_check(\"bInitialState\", bInitialState, bool)\n\n ffi, library = dist.load()\n\n if lpName is None:\n lpName = ffi.NULL\n else:\n input_check(\"lpName\", lpName, text_type)\n\n input_check(\n \"lpEventAttributes\", lpEventAttributes,\n allowed_types=(SECURITY_ATTRIBUTES, NoneType)\n )\n\n handle = library.CreateEvent(\n wintype_to_cdata(lpEventAttributes),\n ffi.cast(\"BOOL\", bManualReset),\n ffi.cast(\"BOOL\", bInitialState),\n lpName\n )\n\n try:\n error_check(\"CreateEvent\")\n except WindowsAPIError as error:\n if error.errno != library.ERROR_ALREADY_EXISTS:\n raise\n\n return HANDLE(handle)\npywincffi/kernel32/handle.py\ndef CloseHandle(hObject):\n \"\"\"\n Closes an open object handle.\n\n .. seealso::\n\n https://msdn.microsoft.com/en-us/library/ms724211\n\n :type hObject: pywincffi.wintypes.HANDLE or pywincffi.wintypes.SOCKET\n :param hObject:\n The handle object to close.\n \"\"\"\n input_check(\"hObject\", hObject, (HANDLE, SOCKET))\n _, library = dist.load()\n\n code = library.CloseHandle(wintype_to_cdata(hObject))\n error_check(\"CloseHandle\", code=code, expected=NON_ZERO)\npywincffi/exceptions.py\nclass WindowsAPIError(PyWinCFFIError):\n \"\"\"\n A subclass of :class:`PyWinCFFIError` that's raised when there was a\n problem calling a Windows API function.\n\n :param str function:\n The Windows API function being called when the error was raised.\n\n :param str error:\n A string representation of the error message.\n\n :param int errno:\n An integer representing the error. This usually represents\n a constant which Windows has produced in response to a problem.\n\n :keyword int return_code:\n If the return value of a function has been checked the resulting\n code will be set as this value.\n\n :keyword int expected_return_code:\n The value we expected to receive for ``code``.\n \"\"\"\n # pylint: disable=too-many-arguments\n def __init__(self, function, error, errno,\n return_code=None, expected_return_code=None):\n self.function = function\n self.error = error\n self.errno = errno\n self.return_code = return_code\n self.expected_return_code = expected_return_code\n\n if return_code is None and expected_return_code is None:\n self.message = \\\n \"Error when calling {0}. Message from Windows API was \" \\\n \"{1!r} (errno: {2}).\".format(self.function, self.error, errno)\n\n elif return_code is not None and expected_return_code is not None:\n self.message = (\n \"Error when calling {0}. Expected to receive {1!r} from {2} \"\n \"but got {3!r} instead. (error: {4!r})\".format(\n self.function, self.return_code, self.function,\n self.expected_return_code, self.error\n )\n )\n\n # Generic implementation which we should probably handle\n # better so throw a warning.\n else: # pragma: no cover\n warnings.warn(Warning(), \"Pre-formatting not available\")\n self.message = (\n \"Error when calling {0}. (error: {1}, errno: {2}, \"\n \"return_code: {3!r}, expected_return_code: {4!r})\".format(\n self.function, self.error, self.errno, self.return_code,\n self.expected_return_code\n )\n )\n\n super(WindowsAPIError, self).__init__(self.message)\n\n def __repr__(self):\n return (\n \"{0}({1!r}, {2!r}, {3!r}, return_code={4!r}, \"\n \"expected_return_code={5!r})\".format(\n self.__class__.__name__, self.function, self.error,\n self.errno, self.return_code, self.expected_return_code))\nimport sys\nfrom mock import patch\nfrom pywincffi.core import dist\nfrom pywincffi.dev.testutil import TestCase\nfrom pywincffi.exceptions import WindowsAPIError, InputError\nfrom pywincffi.kernel32 import events # used by mocks\nfrom pywincffi.kernel32 import (\n CloseHandle, CreateEvent, OpenEvent, ResetEvent, WaitForSingleObject,\n SetEvent)\n\n\n\n\n# These tests cause TestPidExists and others to fail under Python 3.4 so for\n# now we skip these tests. Because we're only testing CreateEvent, and\n# TestPidExists worked before TestCreateEvent exists, we'll skip these\n# for now.\n# Traceback (most recent call last):\n# [...]\n# File \"c:\\python34\\lib\\subprocess.py\", line 754, in __init__\n# _cleanup()\n# File \"c:\\python34\\lib\\subprocess.py\", line 474, in _cleanup\n# res = inst._internal_poll(_deadstate=sys.maxsize)\n# File \"c:\\python34\\lib\\subprocess.py\", line 1147, in _internal_poll\n# if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:\n# OSError: [WinError 6] The handle is invalid\n# TODO: Need to figure out why this happens ^^^\nclass TestCreateEvent(TestCase):\n \"\"\"\n Tests for :func:`pywincffi.kernel32.CreateEvent`\n \"\"\"\n def setUp(self):\n super(TestCreateEvent, self).setUp()\n if sys.version_info[0:2] == (3, 4):\n self.skipTest(\"Skipped on Python 3.4, see comments.\")\n\n def test_create_event_valid_handle(self):\n handle = CreateEvent(bManualReset=False, bInitialState=False)\nNext line of code:\n"}
{"question_id": 5, "category": "longbench_lcc", "reference": [" new[] {new object[] {10L, \"E1\"}});"], "prompt": "Please complete the code given below. \n///////////////////////////////////////////////////////////////////////////////////////\n// Copyright (C) 2006-2015 Esper Team. All rights reserved. /\n// http://esper.codehaus.org /\n// ---------------------------------------------------------------------------------- /\n// The software in this package is published under the terms of the GPL license /\n// a copy of which has been included with this distribution in the license.txt file. /\n///////////////////////////////////////////////////////////////////////////////////////\nusing System;\nusing System.Collections.Generic;\nusing com.espertech.esper.common.client.scopetest;\nusing com.espertech.esper.common.@internal.epl.@join.lookup;\nusing com.espertech.esper.common.@internal.epl.lookupplansubord;\nusing com.espertech.esper.common.@internal.support;\nusing com.espertech.esper.compat;\nusing com.espertech.esper.compat.collections;\nusing com.espertech.esper.regressionlib.framework;\nusing com.espertech.esper.regressionlib.support.bean;\nusing com.espertech.esper.regressionlib.support.util;\nusing NUnit.Framework;\nusing static com.espertech.esper.regressionlib.framework.SupportMessageAssertUtil;\nnamespace com.espertech.esper.regressionlib.suite.infra.nwtable\n{\n public class InfraNWTableCreateIndex\n {\n public static IList<RegressionExecution> Executions()\n {\n var execs = new List<RegressionExecution>();\n execs.Add(new InfraMultiRangeAndKey(true));\n execs.Add(new InfraMultiRangeAndKey(false));\n execs.Add(new InfraHashBTreeWidening(true));\n execs.Add(new InfraHashBTreeWidening(false));\n execs.Add(new InfraWidening(true));\n execs.Add(new InfraWidening(false));\n execs.Add(new InfraCompositeIndex(true));\n execs.Add(new InfraCompositeIndex(false));\n execs.Add(new InfraLateCreate(true));\n execs.Add(new InfraLateCreate(false));\n execs.Add(new InfraLateCreateSceneTwo(true));\n execs.Add(new InfraLateCreateSceneTwo(false));\n execs.Add(new InfraMultipleColumnMultipleIndex(true));\n execs.Add(new InfraMultipleColumnMultipleIndex(false));\n execs.Add(new InfraDropCreate(true));\n execs.Add(new InfraDropCreate(false));\n execs.Add(new InfraOnSelectReUse(true));\n execs.Add(new InfraOnSelectReUse(false));\n execs.Add(new InfraInvalid(true));\n execs.Add(new InfraInvalid(false));\n execs.Add(new InfraMultikeyIndexFAF(true));\n execs.Add(new InfraMultikeyIndexFAF(false));\n return execs;\n }\n private static void RunQueryAssertion(\n RegressionEnvironment env,\n RegressionPath path,\n string epl,\n string[] fields,\n object[][] expected)\n {\n var result = env.CompileExecuteFAF(epl, path);\n EPAssertionUtil.AssertPropsPerRow(result.Array, fields, expected);\n }\n private static void SendEventLong(\n RegressionEnvironment env,\n string theString,\n long longPrimitive)\n {\n var theEvent = new SupportBean();\n theEvent.TheString = theString;\n theEvent.LongPrimitive = longPrimitive;\n env.SendEventBean(theEvent);\n }\n private static void SendEventShort(\n RegressionEnvironment env,\n string theString,\n short shortPrimitive)\n {\n var theEvent = new SupportBean();\n theEvent.TheString = theString;\n theEvent.ShortPrimitive = shortPrimitive;\n env.SendEventBean(theEvent);\n }\n private static void MakeSendSupportBean(\n RegressionEnvironment env,\n string theString,\n int intPrimitive,\n long longPrimitive)\n {\n var b = new SupportBean(theString, intPrimitive);\n b.LongPrimitive = longPrimitive;\n env.SendEventBean(b);\n }\n private static void AssertCols(\n RegressionEnvironment env,\n string listOfP00,\n object[][] expected)\n {\n var p00s = listOfP00.SplitCsv();\n Assert.AreEqual(p00s.Length, expected.Length);\n for (var i = 0; i < p00s.Length; i++) {\n env.SendEventBean(new SupportBean_S0(0, p00s[i]));\n if (expected[i] == null) {\n Assert.IsFalse(env.Listener(\"s0\").IsInvoked);\n }\n else {\n EPAssertionUtil.AssertProps(\n env.Listener(\"s0\").AssertOneGetNewAndReset(),\n new [] { \"col0\",\"col1\" },\n expected[i]);\n }\n }\n }\n private static int GetIndexCount(\n RegressionEnvironment env,\n bool namedWindow,\n string infraStmtName,\n string infraName)\n {\n return SupportInfraUtil.GetIndexCountNoContext(env, namedWindow, infraStmtName, infraName);\n }\n private static void AssertIndexesRef(\n RegressionEnvironment env,\n bool namedWindow,\n string name,\n string csvNames)\n {\n var entry = GetIndexEntry(env, namedWindow, name);\n if (string.IsNullOrEmpty(csvNames)) {\n Assert.IsNull(entry);\n }\n else {\n EPAssertionUtil.AssertEqualsAnyOrder(csvNames.SplitCsv(), entry.ReferringDeployments);\n }\n }\n private static void AssertIndexCountInstance(\n RegressionEnvironment env,\n bool namedWindow,\n string name,\n int count)\n {\n var repo = GetIndexInstanceRepo(env, namedWindow, name);\n Assert.AreEqual(count, repo.Tables.Count);\n }\n private static EventTableIndexRepository GetIndexInstanceRepo(\n RegressionEnvironment env,\n bool namedWindow,\n string name)\n {\n if (namedWindow) {\n var namedWindowInstance = SupportInfraUtil.GetInstanceNoContextNW(env, \"create\", name);\n return namedWindowInstance.RootViewInstance.IndexRepository;\n }\n var instance = SupportInfraUtil.GetInstanceNoContextTable(env, \"create\", name);\n return instance.IndexRepository;\n }\n private static EventTableIndexMetadataEntry GetIndexEntry(\n RegressionEnvironment env,\n bool namedWindow,\n string name)\n {\n var descOne = new IndexedPropDesc(\"col0\", typeof(string));\n var index = new IndexMultiKey(\n false,\n Arrays.AsList(descOne),\n Collections.GetEmptyList<IndexedPropDesc>(),\n null);\n var meta = GetIndexMetaRepo(env, namedWindow, name);\n return meta.Indexes.Get(index);\n }\n private static EventTableIndexMetadata GetIndexMetaRepo(\n RegressionEnvironment env,\n bool namedWindow,\n string name)\n {\n if (namedWindow) {\n var processor = SupportInfraUtil.GetNamedWindow(env, \"create\", name);\n return processor.EventTableIndexMetadata;\n }\n var table = SupportInfraUtil.GetTable(env, \"create\", name);\n return table.EventTableIndexMetadata;\n }\n internal class InfraInvalid : RegressionExecution\n {\n private readonly bool namedWindow;\n public InfraInvalid(bool namedWindow)\n {\n this.namedWindow = namedWindow;\n }\n public void Run(RegressionEnvironment env)\n {\n var path = new RegressionPath();\n var eplCreate = namedWindow\n ? \"create window MyInfraOne#keepall as (f1 string, f2 int)\"\n : \"create table MyInfraOne as (f1 string primary key, f2 int primary key)\";\n env.CompileDeploy(eplCreate, path);\n env.CompileDeploy(\"create index MyInfraIndex on MyInfraOne(f1)\", path);\n env.CompileDeploy(\"create context ContextOne initiated by SupportBean terminated after 5 sec\", path);\n env.CompileDeploy(\"create context ContextTwo initiated by SupportBean terminated after 5 sec\", path);\n var eplCreateWContext = namedWindow\n ? \"context ContextOne create window MyInfraCtx#keepall as (f1 string, f2 int)\"\n : \"context ContextOne create table MyInfraCtx as (f1 string primary key, f2 int primary key)\";\n env.CompileDeploy(eplCreateWContext, path);\n // invalid context\n TryInvalidCompile(\n env,\n path,\n \"create unique index IndexTwo on MyInfraCtx(f1)\",\n (namedWindow ? \"Named window\" : \"Table\") +\n \" by name 'MyInfraCtx' has been declared for context 'ContextOne' and can only be used within the same context\");\n TryInvalidCompile(\n env,\n path,\n \"context ContextTwo create unique index IndexTwo on MyInfraCtx(f1)\",\n (namedWindow ? \"Named window\" : \"Table\") +\n \" by name 'MyInfraCtx' has been declared for context 'ContextOne' and can only be used within the same context\");\n TryInvalidCompile(\n env,\n path,\n \"create index MyInfraIndex on MyInfraOne(f1)\",\n \"An index by name 'MyInfraIndex' already exists [\");\n TryInvalidCompile(\n env,\n path,\n \"create index IndexTwo on MyInfraOne(fx)\",\n \"Property named 'fx' not found\");\n TryInvalidCompile(\n env,\n path,\n \"create index IndexTwo on MyInfraOne(f1, f1)\",\n \"Property named 'f1' has been declared more then once [create index IndexTwo on MyInfraOne(f1, f1)]\");\n TryInvalidCompile(\n env,\n path,\n \"create index IndexTwo on MyWindowX(f1, f1)\",\n \"A named window or table by name 'MyWindowX' does not exist [create index IndexTwo on MyWindowX(f1, f1)]\");\n TryInvalidCompile(\n env,\n path,\n \"create index IndexTwo on MyInfraOne(f1 bubu, f2)\",\n \"Unrecognized advanced-type index 'bubu'\");\n TryInvalidCompile(\n env,\n path,\n \"create gugu index IndexTwo on MyInfraOne(f2)\",\n \"Invalid keyword 'gugu' in create-index encountered, expected 'unique' [create gugu index IndexTwo on MyInfraOne(f2)]\");\n TryInvalidCompile(\n env,\n path,\n \"create unique index IndexTwo on MyInfraOne(f2 btree)\",\n \"Combination of unique index with btree (range) is not supported [create unique index IndexTwo on MyInfraOne(f2 btree)]\");\n // invalid insert-into unique index\n var eplCreateTwo = namedWindow\n ? \"@Name('create') create window MyInfraTwo#keepall as SupportBean\"\n : \"@Name('create') create table MyInfraTwo(TheString string primary key, IntPrimitive int primary key)\";\n env.CompileDeploy(eplCreateTwo, path);\n env.CompileDeploy(\n \"@Name('insert') insert into MyInfraTwo select TheString, IntPrimitive from SupportBean\",\n path);\n env.CompileDeploy(\"create unique index I1 on MyInfraTwo(TheString)\", path);\n env.SendEventBean(new SupportBean(\"E1\", 1));\n try {\n env.SendEventBean(new SupportBean(\"E1\", 2));\n Assert.Fail();\n }\n catch (Exception ex) {\n var text = namedWindow\n ? \"Unexpected exception in statement 'create': Unique index violation, index 'I1' is a unique index and key 'E1' already exists\"\n : \"Unexpected exception in statement 'insert': Unique index violation, index 'I1' is a unique index and key 'E1' already exists\";\n Assert.AreEqual(text, ex.Message);\n }\n if (!namedWindow) {\n env.CompileDeploy(\"create table MyTable (p0 string, sumint sum(int))\", path);\n TryInvalidCompile(\n env,\n path,\n \"create index MyIndex on MyTable(p0)\",\n \"Tables without primary key column(s) do not allow creating an index [\");\n }\n env.UndeployAll();\n }\n }\n internal class InfraOnSelectReUse : RegressionExecution\n {\n private readonly bool namedWindow;\n public InfraOnSelectReUse(bool namedWindow)\n {\n this.namedWindow = namedWindow;\n }\n public void Run(RegressionEnvironment env)\n {\n var path = new RegressionPath();\n var stmtTextCreateOne = namedWindow\n ? \"@Name('create') create window MyInfraONR#keepall as (f1 string, f2 int)\"\n : \"@Name('create') create table MyInfraONR as (f1 string primary key, f2 int primary key)\";\n env.CompileDeploy(stmtTextCreateOne, path);\n env.CompileDeploy(\n \"insert into MyInfraONR(f1, f2) select TheString, IntPrimitive from SupportBean\",\n path);\n env.CompileDeploy(\"@Name('indexOne') create index MyInfraONRIndex1 on MyInfraONR(f2)\", path);\n var fields = new [] { \"f1\",\"f2\" };\n env.SendEventBean(new SupportBean(\"E1\", 1));\n env.CompileDeploy(\n \"@Name('s0') on SupportBean_S0 S0 select nw.f1 as f1, nw.f2 as f2 from MyInfraONR nw where nw.f2 = S0.Id\",\n path)\n .AddListener(\"s0\");\n Assert.AreEqual(namedWindow ? 1 : 2, GetIndexCount(env, namedWindow, \"create\", \"MyInfraONR\"));\n env.SendEventBean(new SupportBean_S0(1));\n EPAssertionUtil.AssertProps(\n env.Listener(\"s0\").AssertOneGetNewAndReset(),\n fields,\n new object[] {\"E1\", 1});\n // create second identical statement\n env.CompileDeploy(\n \"@Name('stmtTwo') on SupportBean_S0 S0 select nw.f1 as f1, nw.f2 as f2 from MyInfraONR nw where nw.f2 = S0.Id\",\n path);\n Assert.AreEqual(namedWindow ? 1 : 2, GetIndexCount(env, namedWindow, \"create\", \"MyInfraONR\"));\n env.UndeployModuleContaining(\"s0\");\n Assert.AreEqual(namedWindow ? 1 : 2, GetIndexCount(env, namedWindow, \"create\", \"MyInfraONR\"));\n env.UndeployModuleContaining(\"stmtTwo\");\n Assert.AreEqual(namedWindow ? 1 : 2, GetIndexCount(env, namedWindow, \"create\", \"MyInfraONR\"));\n env.UndeployModuleContaining(\"indexOne\");\n // two-key index order test\n env.CompileDeploy(\"@Name('cw') create window MyInfraFour#keepall as SupportBean\", path);\n env.CompileDeploy(\"create index Idx1 on MyInfraFour (TheString, IntPrimitive)\", path);\n env.CompileDeploy(\n \"on SupportBean sb select * from MyInfraFour w where w.TheString = sb.TheString and w.IntPrimitive = sb.IntPrimitive\",\n path);\n env.CompileDeploy(\n \"on SupportBean sb select * from MyInfraFour w where w.IntPrimitive = sb.IntPrimitive and w.TheString = sb.TheString\",\n path);\n Assert.AreEqual(1, SupportInfraUtil.GetIndexCountNoContext(env, true, \"cw\", \"MyInfraFour\"));\n env.UndeployAll();\n }\n }\n internal class InfraDropCreate : RegressionExecution\n {\n private readonly bool namedWindow;\n public InfraDropCreate(bool namedWindow)\n {\n this.namedWindow = namedWindow;\n }\n public void Run(RegressionEnvironment env)\n {\n var path = new RegressionPath();\n var stmtTextCreateOne = namedWindow\n ? \"@Name('create') create window MyInfraDC#keepall as (f1 string, f2 int, f3 string, f4 string)\"\n : \"@Name('create') create table MyInfraDC as (f1 string primary key, f2 int primary key, f3 string primary key, f4 string primary key)\";\n env.CompileDeploy(stmtTextCreateOne, path);\n env.CompileDeploy(\n \"insert into MyInfraDC(f1, f2, f3, f4) select TheString, IntPrimitive, '>'||TheString||'<', '?'||TheString||'?' from SupportBean\",\n path);\n env.CompileDeploy(\"@Name('indexOne') create index MyInfraDCIndex1 on MyInfraDC(f1)\", path);\n env.CompileDeploy(\"@Name('indexTwo') create index MyInfraDCIndex2 on MyInfraDC(f4)\", path);\n var fields = new [] { \"f1\",\"f2\" };\n env.SendEventBean(new SupportBean(\"E1\", -2));\n env.UndeployModuleContaining(\"indexOne\");\n var result = env.CompileExecuteFAF(\"select * from MyInfraDC where f1='E1'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2}});\n result = env.CompileExecuteFAF(\"select * from MyInfraDC where f4='?E1?'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2}});\n env.UndeployModuleContaining(\"indexTwo\");\n result = env.CompileExecuteFAF(\"select * from MyInfraDC where f1='E1'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2}});\n result = env.CompileExecuteFAF(\"select * from MyInfraDC where f4='?E1?'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2}});\n path.Compileds.RemoveAt(path.Compileds.Count - 1);\n env.CompileDeploy(\"@Name('IndexThree') create index MyInfraDCIndex2 on MyInfraDC(f4)\", path);\n result = env.CompileExecuteFAF(\"select * from MyInfraDC where f1='E1'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2}});\n result = env.CompileExecuteFAF(\"select * from MyInfraDC where f4='?E1?'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2}});\n env.UndeployModuleContaining(\"IndexThree\");\n Assert.AreEqual(namedWindow ? 0 : 1, GetIndexCount(env, namedWindow, \"create\", \"MyInfraDC\"));\n env.UndeployAll();\n }\n }\n internal class InfraMultipleColumnMultipleIndex : RegressionExecution\n {\n private readonly bool namedWindow;\n public InfraMultipleColumnMultipleIndex(bool namedWindow)\n {\n this.namedWindow = namedWindow;\n }\n public void Run(RegressionEnvironment env)\n {\n var path = new RegressionPath();\n var stmtTextCreateOne = namedWindow\n ? \"create window MyInfraMCMI#keepall as (f1 string, f2 int, f3 string, f4 string)\"\n : \"create table MyInfraMCMI as (f1 string primary key, f2 int, f3 string, f4 string)\";\n env.CompileDeploy(stmtTextCreateOne, path);\n env.CompileDeploy(\n \"insert into MyInfraMCMI(f1, f2, f3, f4) select TheString, IntPrimitive, '>'||TheString||'<', '?'||TheString||'?' from SupportBean\",\n path);\n env.CompileDeploy(\"create index MyInfraMCMIIndex1 on MyInfraMCMI(f2, f3, f1)\", path);\n env.CompileDeploy(\"create index MyInfraMCMIIndex2 on MyInfraMCMI(f2, f3)\", path);\n env.CompileDeploy(\"create index MyInfraMCMIIndex3 on MyInfraMCMI(f2)\", path);\n var fields = new [] { \"f1\",\"f2\",\"f3\",\"f4\" };\n env.SendEventBean(new SupportBean(\"E1\", -2));\n env.SendEventBean(new SupportBean(\"E2\", -4));\n env.SendEventBean(new SupportBean(\"E3\", -3));\n var result = env.CompileExecuteFAF(\"select * from MyInfraMCMI where f3='>E1<'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n result = env.CompileExecuteFAF(\"select * from MyInfraMCMI where f3='>E1<' and f2=-2\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n result = env.CompileExecuteFAF(\"select * from MyInfraMCMI where f3='>E1<' and f2=-2 and f1='E1'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n result = env.CompileExecuteFAF(\"select * from MyInfraMCMI where f2=-2\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n result = env.CompileExecuteFAF(\"select * from MyInfraMCMI where f1='E1'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n result = env.CompileExecuteFAF(\n \"select * from MyInfraMCMI where f3='>E1<' and f2=-2 and f1='E1' and f4='?E1?'\",\n path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n env.UndeployAll();\n }\n }\n public class InfraLateCreate : RegressionExecution\n {\n private readonly bool namedWindow;\n public InfraLateCreate(bool namedWindow)\n {\n this.namedWindow = namedWindow;\n }\n public void Run(RegressionEnvironment env)\n {\n string[] fields = {\"TheString\", \"IntPrimitive\"};\n var path = new RegressionPath();\n // create infra\n var stmtTextCreate = namedWindow\n ? \"@Name('Create') create window MyInfra.win:keepall() as SupportBean\"\n : \"@Name('Create') create table MyInfra(TheString string primary key, IntPrimitive int primary key)\";\n env.CompileDeploy(stmtTextCreate, path).AddListener(\"Create\");\n // create insert into\n var stmtTextInsertOne =\n \"@Name('Insert') insert into MyInfra select TheString, IntPrimitive from SupportBean\";\n env.CompileDeploy(stmtTextInsertOne, path);\n env.SendEventBean(new SupportBean(\"A1\", 1));\n env.SendEventBean(new SupportBean(\"B2\", 2));\n env.SendEventBean(new SupportBean(\"B2\", 1));\n // create index\n var stmtTextCreateIndex = \"@Name('Index') create index MyInfra_IDX on MyInfra(TheString)\";\n env.CompileDeploy(stmtTextCreateIndex, path);\n env.Milestone(0);\n // perform on-demand query\n var result = env.CompileExecuteFAF(\n \"select * from MyInfra where TheString = 'B2' order by IntPrimitive asc\",\n path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"B2\", 1}, new object[] {\"B2\", 2}});\n // cleanup\n env.UndeployAll();\n env.Milestone(1);\n }\n }\n internal class InfraLateCreateSceneTwo : RegressionExecution\n {\n private readonly bool namedWindow;\n public InfraLateCreateSceneTwo(bool namedWindow)\n {\n this.namedWindow = namedWindow;\n }\n public void Run(RegressionEnvironment env)\n {\n var path = new RegressionPath();\n var stmtTextCreateOne = namedWindow\n ? \"create window MyInfraLC#keepall as (f1 string, f2 int, f3 string, f4 string)\"\n : \"create table MyInfraLC as (f1 string primary key, f2 int primary key, f3 string primary key, f4 string primary key)\";\n env.CompileDeploy(stmtTextCreateOne, path);\n env.CompileDeploy(\n \"insert into MyInfraLC(f1, f2, f3, f4) select TheString, IntPrimitive, '>'||TheString||'<', '?'||TheString||'?' from SupportBean\",\n path);\n env.SendEventBean(new SupportBean(\"E1\", -4));\n env.Milestone(0);\n env.SendEventBean(new SupportBean(\"E1\", -2));\n env.SendEventBean(new SupportBean(\"E1\", -3));\n env.CompileDeploy(\"create index MyInfraLCIndex on MyInfraLC(f2, f3, f1)\", path);\n var fields = new [] { \"f1\",\"f2\",\"f3\",\"f4\" };\n env.Milestone(1);\n var result = env.CompileExecuteFAF(\"select * from MyInfraLC where f3='>E1<' order by f2 asc\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {\n new object[] {\"E1\", -4, \">E1<\", \"?E1?\"}, new object[] {\"E1\", -3, \">E1<\", \"?E1?\"},\n new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}\n });\n env.UndeployAll();\n }\n }\n internal class InfraCompositeIndex : RegressionExecution\n {\n private readonly bool namedWindow;\n public InfraCompositeIndex(bool namedWindow)\n {\n this.namedWindow = namedWindow;\n }\n public void Run(RegressionEnvironment env)\n {\n var path = new RegressionPath();\n var stmtTextCreate = namedWindow\n ? \"create window MyInfraCI#keepall as (f1 string, f2 int, f3 string, f4 string)\"\n : \"create table MyInfraCI as (f1 string primary key, f2 int, f3 string, f4 string)\";\n env.CompileDeploy(stmtTextCreate, path);\n var compiledWindow = path.Compileds[0];\n env.CompileDeploy(\n \"insert into MyInfraCI(f1, f2, f3, f4) select TheString, IntPrimitive, '>'||TheString||'<', '?'||TheString||'?' from SupportBean\",\n path);\n env.CompileDeploy(\"@Name('indexOne') create index MyInfraCIIndex on MyInfraCI(f2, f3, f1)\", path);\n var fields = new [] { \"f1\",\"f2\",\"f3\",\"f4\" };\n env.SendEventBean(new SupportBean(\"E1\", -2));\n var result = env.CompileExecuteFAF(\"select * from MyInfraCI where f3='>E1<'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n result = env.CompileExecuteFAF(\"select * from MyInfraCI where f3='>E1<' and f2=-2\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n result = env.CompileExecuteFAF(\"select * from MyInfraCI where f3='>E1<' and f2=-2 and f1='E1'\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\n new[] {new object[] {\"E1\", -2, \">E1<\", \"?E1?\"}});\n env.UndeployModuleContaining(\"indexOne\");\n // test SODA\n path.Clear();\n path.Add(compiledWindow);\n env.EplToModelCompileDeploy(\"create index MyInfraCIIndexTwo on MyInfraCI(f2, f3, f1)\", path)\n .UndeployAll();\n }\n }\n internal class InfraWidening : RegressionExecution\n {\n private readonly bool namedWindow;\n public InfraWidening(bool namedWindow)\n {\n this.namedWindow = namedWindow;\n }\n public void Run(RegressionEnvironment env)\n {\n var path = new RegressionPath();\n // widen to long\n var stmtTextCreate = namedWindow\n ? \"create window MyInfraW#keepall as (f1 long, f2 string)\"\n : \"create table MyInfraW as (f1 long primary key, f2 string primary key)\";\n env.CompileDeploy(stmtTextCreate, path);\n env.CompileDeploy(\n \"insert into MyInfraW(f1, f2) select LongPrimitive, TheString from SupportBean\",\n path);\n env.CompileDeploy(\"create index MyInfraWIndex1 on MyInfraW(f1)\", path);\n var fields = new [] { \"f1\",\"f2\" };\n SendEventLong(env, \"E1\", 10L);\n var result = env.CompileExecuteFAF(\"select * from MyInfraW where f1=10\", path);\n EPAssertionUtil.AssertPropsPerRow(\n result.Array,\n fields,\nNext line of code:\n"}
{"question_id": 6, "category": "longbench_lcc", "reference": ["\t\t\t\tIList list = session.CreateCriteria(typeof(Item))"], "prompt": "Please complete the code given below. \nusing System.Data.Common;\nusing System.Collections;\nusing NHibernate.Cache;\nusing NHibernate.Cfg;\nusing NHibernate.Engine;\nusing NUnit.Framework;\nnamespace NHibernate.Test.SecondLevelCacheTests\n{\n\tusing Criterion;\n\t[TestFixture]\n\tpublic class SecondLevelCacheTest : TestCase\n\t{\n\t\tprotected override string MappingsAssembly\n\t\t{\n\t\t\tget { return \"NHibernate.Test\"; }\n\t\t}\n\t\tprotected override IList Mappings\n\t\t{\n\t\t\tget { return new string[] { \"SecondLevelCacheTest.Item.hbm.xml\" }; }\n\t\t}\n\t\tprotected override void Configure(Configuration configuration)\n\t\t{\n\t\t\tbase.Configure(configuration);\n\t\t\tconfiguration.Properties[Environment.CacheProvider] = typeof(HashtableCacheProvider).AssemblyQualifiedName;\n\t\t\tconfiguration.Properties[Environment.UseQueryCache] = \"true\";\n\t\t}\n\t\tprotected override void OnSetUp()\n\t\t{\n\t\t\t// Clear cache at each test.\n\t\t\tRebuildSessionFactory();\n\t\t\tusing (ISession session = OpenSession())\n\t\t\tusing (ITransaction tx = session.BeginTransaction())\n\t\t\t{\n\t\t\t\tItem item = new Item();\n\t\t\t\titem.Id = 1;\n\t\t\t\tsession.Save(item);\n\t\t\t\tfor (int i = 0; i < 4; i++)\n\t\t\t\t{\n\t\t\t\t\tItem child = new Item();\n\t\t\t\t\tchild.Id = i + 2;\n\t\t\t\t\tchild.Parent = item;\n\t\t\t\t\tsession.Save(child);\n\t\t\t\t\titem.Children.Add(child);\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < 5; i++)\n\t\t\t\t{\n\t\t\t\t\tAnotherItem obj = new AnotherItem(\"Item #\" + i);\n\t\t\t\t\tobj.Id = i + 1;\n\t\t\t\t\tsession.Save(obj);\n\t\t\t\t}\n\t\t\t\ttx.Commit();\n\t\t\t}\n\t\t\tSfi.Evict(typeof(Item));\n\t\t\tSfi.EvictCollection(typeof(Item).FullName + \".Children\");\n\t\t}\n\t\tprotected override void OnTearDown()\n\t\t{\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tsession.Delete(\"from Item\"); //cleaning up\n\t\t\t\tsession.Delete(\"from AnotherItem\"); //cleaning up\n\t\t\t\tsession.Flush();\n\t\t\t}\n\t\t}\n\t\t[Test]\n\t\tpublic void CachedQueriesHandlesEntitiesParametersCorrectly()\n\t\t{\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tItem one = (Item)session.Load(typeof(Item), 1);\n\t\t\t\tIList results = session.CreateQuery(\"from Item item where item.Parent = :parent\")\n\t\t\t\t\t.SetEntity(\"parent\", one)\n\t\t\t\t\t.SetCacheable(true).List();\n\t\t\t\tAssert.AreEqual(4, results.Count);\n\t\t\t\tforeach (Item item in results)\n\t\t\t\t{\n\t\t\t\t\tAssert.AreEqual(1, item.Parent.Id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tItem two = (Item)session.Load(typeof(Item), 2);\n\t\t\t\tIList results = session.CreateQuery(\"from Item item where item.Parent = :parent\")\n\t\t\t\t\t.SetEntity(\"parent\", two)\n\t\t\t\t\t.SetCacheable(true).List();\n\t\t\t\tAssert.AreEqual(0, results.Count);\n\t\t\t}\n\t\t}\n\t\t[Test]\n\t\tpublic void DeleteItemFromCollectionThatIsInTheSecondLevelCache()\n\t\t{\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tItem item = (Item)session.Load(typeof(Item), 1);\n\t\t\t\tAssert.IsTrue(item.Children.Count == 4); // just force it into the second level cache here\n\t\t\t}\n\t\t\tint childId = -1;\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tItem item = (Item)session.Load(typeof(Item), 1);\n\t\t\t\tItem child = (Item)item.Children[0];\n\t\t\t\tchildId = child.Id;\n\t\t\t\tsession.Delete(child);\n\t\t\t\titem.Children.Remove(child);\n\t\t\t\tsession.Flush();\n\t\t\t}\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tItem item = (Item)session.Load(typeof(Item), 1);\n\t\t\t\tAssert.AreEqual(3, item.Children.Count);\n\t\t\t\tforeach (Item child in item.Children)\n\t\t\t\t{\n\t\t\t\t\tNHibernateUtil.Initialize(child);\n\t\t\t\t\tAssert.IsFalse(child.Id == childId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t[Test]\n\t\tpublic void InsertItemToCollectionOnTheSecondLevelCache()\n\t\t{\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tItem item = (Item)session.Load(typeof(Item), 1);\n\t\t\t\tItem child = new Item();\n\t\t\t\tchild.Id = 6;\n\t\t\t\titem.Children.Add(child);\n\t\t\t\tsession.Save(child);\n\t\t\t\tsession.Flush();\n\t\t\t}\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tItem item = (Item)session.Load(typeof(Item), 1);\n\t\t\t\tint count = item.Children.Count;\n\t\t\t\tAssert.AreEqual(5, count);\n\t\t\t}\n\t\t}\n\t\t[Test]\n\t\tpublic void SecondLevelCacheWithCriteriaQueries()\n\t\t{\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tIList list = session.CreateCriteria(typeof(AnotherItem))\n\t\t\t\t\t.Add(Expression.Gt(\"Id\", 2))\n\t\t\t\t\t.SetCacheable(true)\n\t\t\t\t\t.List();\n\t\t\t\tAssert.AreEqual(3, list.Count);\n\t\t\t\tusing (var cmd = session.Connection.CreateCommand())\n\t\t\t\t{\n\t\t\t\t\tcmd.CommandText = \"DELETE FROM AnotherItem\";\n\t\t\t\t\tcmd.ExecuteNonQuery();\n\t\t\t\t}\n\t\t\t}\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\t//should bring from cache\n\t\t\t\tIList list = session.CreateCriteria(typeof(AnotherItem))\n\t\t\t\t\t.Add(Expression.Gt(\"Id\", 2))\n\t\t\t\t\t.SetCacheable(true)\n\t\t\t\t\t.List();\n\t\t\t\tAssert.AreEqual(3, list.Count);\n\t\t\t}\n\t\t}\n\t\t[Test]\n\t\tpublic void SecondLevelCacheWithCriteriaQueriesForItemWithCollections()\n\t\t{\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\tIList list = session.CreateCriteria(typeof(Item))\n\t\t\t\t\t.Add(Expression.Gt(\"Id\", 2))\n\t\t\t\t\t.SetCacheable(true)\n\t\t\t\t\t.List();\n\t\t\t\tAssert.AreEqual(3, list.Count);\n\t\t\t\tusing (var cmd = session.Connection.CreateCommand())\n\t\t\t\t{\n\t\t\t\t\tcmd.CommandText = \"DELETE FROM Item\";\n\t\t\t\t\tcmd.ExecuteNonQuery();\n\t\t\t\t}\n\t\t\t}\n\t\t\tusing (ISession session = OpenSession())\n\t\t\t{\n\t\t\t\t//should bring from cache\nNext line of code:\n"}
{"question_id": 7, "category": "longbench_multi_news", "reference": ["The White House on Friday declassified a partisan and bitterly disputed memo on the Russia investigation, and a House committee immediately made it public. Media outlets were just beginning to assess it. You can read the document here, via the Washington Post. The White House move came over the fierce objections of the FBI and Justice Department, which have said the document prepared by Republicans on the House intelligence committee is inaccurate and missing critical context, per the AP. The memo alleges that the FBI abused US government surveillance powers in its investigation into Russian election interference. Trump, who has called the investigation a \"witch hunt,\" has supported the release of the memo in the apparent hopes that it could help undermine the probe being led by special counsel Robert Mueller. The president, dogged by the unrelenting investigation into his campaign's ties to Russia, lashed out anew Friday at the FBI and Justice Department as politically biased against Republicans. \"The top Leadership and Investigators of the FBI and the Justice Department have politicized the sacred investigative process in favor of Democrats and against Republicans - something which would have been unthinkable just a short time ago. Rank & File are great people!\" Trump tweeted."], "prompt": "You are given several news passages. Write a one-page summary of all news. \n\nNews:\nPassage 1:\nThe Nunes memo is a document created by the staff of House Intelligence Committee Chairman Devin Nunes (R-Calif.) that alleges the FBI abused its surveillance authority, particularly when it sought a secret court order to monitor a former Trump campaign adviser. The FBI and the Justice Department had lobbied strenuously against its release. On Wednesday, the FBI had said it was “gravely concerned” that key facts were missing from the memo. President approves release of GOP memo criticizing FBI surveillance NEWLINE_CHAR NEWLINE_CHAR THE WHITE HOUSE NEWLINE_CHAR NEWLINE_CHAR WASHINGTON NEWLINE_CHAR NEWLINE_CHAR February 2, 2018 NEWLINE_CHAR NEWLINE_CHAR The Honorable Devin Nunes NEWLINE_CHAR NEWLINE_CHAR Chairman, House Permanent Select Committee on Intelligence NEWLINE_CHAR NEWLINE_CHAR United States Capitol NEWLINE_CHAR NEWLINE_CHAR Washington, DC 20515 NEWLINE_CHAR NEWLINE_CHAR Dear Mr. Chairman: NEWLINE_CHAR NEWLINE_CHAR On January 29, 2018, the House Permanent Select Committee on Intelligence (hereinafter ?the NEWLINE_CHAR NEWLINE_CHAR Committee?) voted to disclose publicly a memorandum containing classi?ed information NEWLINE_CHAR NEWLINE_CHAR provided to the Committee in connection with its oversight activities (the ?Memorandum,? NEWLINE_CHAR NEWLINE_CHAR which is attached to this letter). As provided by clause 11(g) of Rule of the House of NEWLINE_CHAR NEWLINE_CHAR Representatives, the Committee has forwarded this Memorandum to the President based on its NEWLINE_CHAR NEWLINE_CHAR determination that the release of the Memorandum would serve the public interest. NEWLINE_CHAR NEWLINE_CHAR The Constitution vests the President with the authority to protect national security secrets from it NEWLINE_CHAR NEWLINE_CHAR disclosure. As the Supreme Court has recognized, it is the President?s responsibility to classify, NEWLINE_CHAR NEWLINE_CHAR declassify, and control access to information bearing on our intelligence sources and methods NEWLINE_CHAR NEWLINE_CHAR and national defense. See, Dep of Navy v. Egan, 484 US. 518, 527 (1988). In order to NEWLINE_CHAR NEWLINE_CHAR facilitate appropriate congressional oversight, the Executive Branch may entrust classi?ed NEWLINE_CHAR NEWLINE_CHAR information to the appropriate committees of Congress, as it has done in connection with the NEWLINE_CHAR NEWLINE_CHAR Committee?s oversight activities here. The Executive Branch does so on the assumption that the NEWLINE_CHAR NEWLINE_CHAR Committee will responsibly protect such classi?ed information, consistent with the laws of the NEWLINE_CHAR NEWLINE_CHAR United States. NEWLINE_CHAR NEWLINE_CHAR The Committee has now determined that the release of the Memorandum would be appropriate. NEWLINE_CHAR NEWLINE_CHAR The Executive Branch, across Administrations of both parties, has worked to accommodate NEWLINE_CHAR NEWLINE_CHAR congressional requests to declassify speci?c materials in the public interest.1 However, public NEWLINE_CHAR NEWLINE_CHAR release of classi?ed information by unilateral action of the Legislative Branch is extremely rare NEWLINE_CHAR NEWLINE_CHAR and raises signi?cant separation of powers concerns. Accordingly, the Committee?s request to NEWLINE_CHAR NEWLINE_CHAR release the Memorandum is interpreted as a request for declassi?cation pursuant to the NEWLINE_CHAR NEWLINE_CHAR President?s authority. NEWLINE_CHAR NEWLINE_CHAR The President understands that the protection of our national security represents his highest NEWLINE_CHAR NEWLINE_CHAR obligation. Accordingly, he has directed lawyers and national security staff to assess the NEWLINE_CHAR NEWLINE_CHAR 1 See, e. S. Rept. 114?8 at 12 (Administration of Barack Obama) (?On April 3, 2014 . . . the Committee agreed to NEWLINE_CHAR NEWLINE_CHAR send the revised Findings and Conclusions, and the updated Executive Summary of the Committee Study, to the NEWLINE_CHAR NEWLINE_CHAR President for declassi?cation and public release?); H. Rept. 107-792 (Administration of George W. Bush) (similar); NEWLINE_CHAR NEWLINE_CHAR E.O. 12812 (Administration of George H.W. Bush) (noting Senate resolution requesting that President provide for NEWLINE_CHAR NEWLINE_CHAR declassi?cation of certain information Via Executive Order). NEWLINE_CHAR NEWLINE_CHAR declassi?cation request, consistent with established standards governing the handling of NEWLINE_CHAR NEWLINE_CHAR classi?ed information, including those under Section 3.1(d) of Executive Order 13526. Those NEWLINE_CHAR NEWLINE_CHAR standards permit declassi?cation when the public interest in disclosure outweighs any need to NEWLINE_CHAR NEWLINE_CHAR protect the information. The White House review process also included input from the Of?ce of NEWLINE_CHAR NEWLINE_CHAR the Director of National Intelligence and the Department of Justice. Consistent with this review NEWLINE_CHAR NEWLINE_CHAR and these standards, the President has determined that declassification of the Memorandum is NEWLINE_CHAR NEWLINE_CHAR appropriate. NEWLINE_CHAR NEWLINE_CHAR Based on this assessment and in light of the signi?cant public interest in the memorandum, the NEWLINE_CHAR NEWLINE_CHAR President has authorized the declassi?cation of the Memorandum. To be clear, the NEWLINE_CHAR NEWLINE_CHAR Memorandum re?ects the judgments of its congressional authors. The President understands NEWLINE_CHAR NEWLINE_CHAR that oversight concerning matters related to the Memorandum may be continuing. Though the NEWLINE_CHAR NEWLINE_CHAR circumstances leading to the declassi?cation through this process are extraordinary, the NEWLINE_CHAR NEWLINE_CHAR Executive Branch stands ready to work with Congress to accommodate oversight requests NEWLINE_CHAR NEWLINE_CHAR consistent with applicable standards and processes, including the need to protect intelligence NEWLINE_CHAR NEWLINE_CHAR sources and methods. NEWLINE_CHAR NEWLINE_CHAR Sincerely, NEWLINE_CHAR NEWLINE_CHAR Donald F. McGahn II NEWLINE_CHAR NEWLINE_CHAR Counsel to the President NEWLINE_CHAR NEWLINE_CHAR cc: The Honorable Paul Ryan NEWLINE_CHAR NEWLINE_CHAR Speaker of the House of Representatives NEWLINE_CHAR NEWLINE_CHAR The Honorable Adam Schiff NEWLINE_CHAR NEWLINE_CHAR Ranking Member, House Permanent Select Committee on Intelligence NEWLINE_CHAR NEWLINE_CHAR ssnua NEWLINE_CHAR NEWLINE_CHAR DeclasSi?ed by order of the President NEWLINE_CHAR NEWLINE_CHAR February 2, 2018 NEWLINE_CHAR NEWLINE_CHAR January 18, 2018 NEWLINE_CHAR NEWLINE_CHAR To: HPSCI Majority Members NEWLINE_CHAR NEWLINE_CHAR From: HPSCI Majority Staff NEWLINE_CHAR NEWLINE_CHAR Subject: Foreign Intelligence Surveillance Act Abuses at the Department of Justice and the NEWLINE_CHAR NEWLINE_CHAR Federal Bureau of Investigation NEWLINE_CHAR NEWLINE_CHAR Purpose NEWLINE_CHAR NEWLINE_CHAR This memorandum provides Members an update on significant facts relating to the NEWLINE_CHAR NEWLINE_CHAR Committee?s ongoing investigation into the Department of Justice (DOJ) and Federal Bureau of NEWLINE_CHAR NEWLINE_CHAR Investigation (FBI) and their use of the Foreign Intelligence Surveillance Act (F ISA) during the NEWLINE_CHAR NEWLINE_CHAR 2016 presidential election cycle. Our ?ndings, which are detailed below, 1) raise concerns with NEWLINE_CHAR NEWLINE_CHAR the legitimacy and legality of certain DOJ and FBI interactions with the Foreign Intelligence NEWLINE_CHAR NEWLINE_CHAR Surveillance Court (FISC), and 2) represent a troubling breakdown of legal processes established NEWLINE_CHAR NEWLINE_CHAR to protect the American people from abuses related to the ISA process. NEWLINE_CHAR NEWLINE_CHAR Investigation Update NEWLINE_CHAR NEWLINE_CHAR - On October 21, 2016, DOJ and FBI sought and received a ISA probable cause order NEWLINE_CHAR NEWLINE_CHAR (up; under Title VII) authorizing electronic surveillance on Carter Page from the FISC. Page is a NEWLINE_CHAR NEWLINE_CHAR US citizen who served as a volunteer advisor to the Trump presidential campaign. Consistent . NEWLINE_CHAR NEWLINE_CHAR with requirements under FISA, the application had to be ?rst certi?ed by the Director or Deputy NEWLINE_CHAR NEWLINE_CHAR Director of the FBI. It then required the approval of the Attorney General, Deputy Attorney NEWLINE_CHAR NEWLINE_CHAR General (DAG), or the Senate?con?rmed Assistant Attorney General for the National Security NEWLINE_CHAR NEWLINE_CHAR Division. NEWLINE_CHAR NEWLINE_CHAR The FBI and DOJ obtained one initial FISA warrant targeting Carter Page and three FISA NEWLINE_CHAR NEWLINE_CHAR renewals from the FISC. As required by statute (50 U.S.C. a FISA order on an NEWLINE_CHAR NEWLINE_CHAR American citizen must be renewed by the ISC every 90 days and each renewal requires a NEWLINE_CHAR NEWLINE_CHAR separate finding of probable cause. Then-Director James Comey signed three FISA applications NEWLINE_CHAR NEWLINE_CHAR . in question on behalf of the FBI, and Deputy Director Andrew McCabe signed one. NEWLINE_CHAR NEWLINE_CHAR Sally Yates, then-Acting DAG Dana Boente, and DAG Rod Rosenstein each signed one or more NEWLINE_CHAR NEWLINE_CHAR FISA applications on behalf of NEWLINE_CHAR NEWLINE_CHAR Due to the sensitive nature of foreign intelligence activity, FISA submissions (including NEWLINE_CHAR NEWLINE_CHAR renewals) before the ISC are classified. As such, the public?s con?dence in the integrity of the NEWLINE_CHAR NEWLINE_CHAR FISA process depends on the court?s ability to hold the government to the highest standard?? NEWLINE_CHAR NEWLINE_CHAR particularly as it relates to surveillance of American citizens. However, the rigor in NEWLINE_CHAR NEWLINE_CHAR protecting the rights of Americans, which is reinforced by 90?day renewals of surveillance NEWLINE_CHAR NEWLINE_CHAR orders, is necessarily dependent on the government?s production to the court of all material and NEWLINE_CHAR NEWLINE_CHAR relevant facts. This should include information potentially favorable to the target of the FISA NEWLINE_CHAR NEWLINE_CHAR PROPERTY OF THE U.S. HOUSE OF REPRESENTATIVES NEWLINE_CHAR NEWLINE_CHAR TGIF-SEW NEWLINE_CHAR NEWLINE_CHAR application that is known by the government. In the case of Carter Page, the government had at NEWLINE_CHAR NEWLINE_CHAR least four independent opportunities before the FISC to accurately provide an accounting of the NEWLINE_CHAR NEWLINE_CHAR relevant facts. However, our ?ndings indicate that, as described below, material and relevant NEWLINE_CHAR NEWLINE_CHAR information was omitted. NEWLINE_CHAR NEWLINE_CHAR 1) NEWLINE_CHAR NEWLINE_CHAR 2) NEWLINE_CHAR NEWLINE_CHAR The ?dossier?- compiled by Christopher Steele (Steele dossier) on behalf of the NEWLINE_CHAR NEWLINE_CHAR Democratic National Committee (DNC) and the Hillary Clinton campaign formed an NEWLINE_CHAR NEWLINE_CHAR essential part of the Carter Page FISA application. Steele was a longtime FBI source who NEWLINE_CHAR NEWLINE_CHAR was paid over $160,000 by the DNC and Clinton campaign, via the law ?rm Perkins Coie NEWLINE_CHAR NEWLINE_CHAR and research ?rm Fusion GPS, to obtain derogatory information on Donald Trump?s ties NEWLINE_CHAR NEWLINE_CHAR to Russia. NEWLINE_CHAR NEWLINE_CHAR a) Neither the initial application in October 2016, nor any of the renewals, disclose or NEWLINE_CHAR NEWLINE_CHAR reference the role of the DNC, Clinton campaign, or. any party/campaign in funding NEWLINE_CHAR NEWLINE_CHAR Steele?s efforts, even though the political origins of the Steele dossier were then NEWLINE_CHAR NEWLINE_CHAR known to senior and FBI of?cials. NEWLINE_CHAR NEWLINE_CHAR b) The initial FISA application notes Steele was working for a named US. person, but NEWLINE_CHAR NEWLINE_CHAR does not name Fusion GPS and principal Glenn Simpson, who was paid by a US. law NEWLINE_CHAR NEWLINE_CHAR ?rm (Perkins Coie) representing the DNC (even though it was known by DOI at the, NEWLINE_CHAR NEWLINE_CHAR time that political actors were involved with the Steele dossier). The application does NEWLINE_CHAR NEWLINE_CHAR not mention Steele was ultimately working on behalf of?and paid by?wthe DNC and NEWLINE_CHAR NEWLINE_CHAR Clinton campaign, or that the FBI had separately authorized payment to Steele for the NEWLINE_CHAR NEWLINE_CHAR same information. NEWLINE_CHAR NEWLINE_CHAR The Carter Page FISA application also cited extensively a September 23, 2016, Yahoo NEWLINE_CHAR NEWLINE_CHAR News article by- Michael Isikoff, which focuses on Page?s July 2016 trip to Moscow. NEWLINE_CHAR NEWLINE_CHAR - This article does not corroborate the Steele dossier because it is derived from information NEWLINE_CHAR NEWLINE_CHAR leaked by Steele himself to Yahoo News. The Page FISA application incorrectly assesses NEWLINE_CHAR NEWLINE_CHAR that Steele did not directly provide information to Yahoo News. Steele has admitted in NEWLINE_CHAR NEWLINE_CHAR British court ?lings that he met with Yahoo Newly?and several other. outlets?in NEWLINE_CHAR NEWLINE_CHAR September 2016 at the direction of Fusion GPS. Perkins Coie was aware of Steele?s NEWLINE_CHAR NEWLINE_CHAR initial media contacts because they hosted at least one meeting in Washington DC. in NEWLINE_CHAR NEWLINE_CHAR 2016 with Steele and Fusion GPS where this matter was discussed.\" NEWLINE_CHAR NEWLINE_CHAR a) Steele was suspended and then terminated as an FBI source for what the FBI de?nes NEWLINE_CHAR NEWLINE_CHAR as the most serious of violations?an unauthorized disclosure to the media of his NEWLINE_CHAR NEWLINE_CHAR relationship with the FBI in an October 30, 2016, Mother Jones article by David NEWLINE_CHAR NEWLINE_CHAR Corn Steele should have been terminated for his previous undisclosed contacts with NEWLINE_CHAR NEWLINE_CHAR Yahoo and other outlets' 1n September?before the Page application was submitted to NEWLINE_CHAR NEWLINE_CHAR PROPERTY OF THE US. HOUSE OF REPRESENTATIVES NEWLINE_CHAR NEWLINE_CHAR 3) NEWLINE_CHAR NEWLINE_CHAR 4) NEWLINE_CHAR NEWLINE_CHAR the FISC in October-but Steele improperly concealed from and lied to the FBI about NEWLINE_CHAR NEWLINE_CHAR those contacts. NEWLINE_CHAR NEWLINE_CHAR b) Steele?s numerous encounters with the media violated the cardinal rule of source NEWLINE_CHAR NEWLINE_CHAR handling?maintaining con?dentiality?and demonstrated that Steele had become a NEWLINE_CHAR NEWLINE_CHAR less than reliable source for the FBI. NEWLINE_CHAR NEWLINE_CHAR Before and after Steele was terminated as a source, he maintained contact with DOJ via NEWLINE_CHAR NEWLINE_CHAR then-Associate Deputy Attorney General Bruce 0hr, a senior DOJ of?cial who worked NEWLINE_CHAR NEWLINE_CHAR closely with Deputy Attorneys General Yates and later Rosenstein. Shortly after the NEWLINE_CHAR NEWLINE_CHAR election, the FBI began interviewing 0hr, documenting his communications with Steele. NEWLINE_CHAR NEWLINE_CHAR For example, in September 2016, Steele admitted to 0hr his feelings against then- NEWLINE_CHAR NEWLINE_CHAR candidate Trump when Steele said he ?was desperate that Donald Trump not get NEWLINE_CHAR NEWLINE_CHAR elected and was passionate about him not, being president.? This clear evidence of . NEWLINE_CHAR NEWLINE_CHAR Steele? bias was recorded by Ohr at the time and subsequently in of?cial FBI ?les?but NEWLINE_CHAR NEWLINE_CHAR not re?ected in any of the Page FISA applications. NEWLINE_CHAR NEWLINE_CHAR a) During this same time period, Ohr?s wife was employed by Fusion GPS to assist in NEWLINE_CHAR NEWLINE_CHAR the cultivation of opposition research on Trump. Ohr later provided the FBI with all NEWLINE_CHAR NEWLINE_CHAR of his wife?s opposition research, paid for by the DNC and Clinton campaign via NEWLINE_CHAR NEWLINE_CHAR Fusion GPS. The Ohrs? relationship with Steele and Fusion GPS was inexplicably NEWLINE_CHAR NEWLINE_CHAR concealed from the FISC. . NEWLINE_CHAR NEWLINE_CHAR According to the head of the counterintelligence division, Assistant Director Bill NEWLINE_CHAR NEWLINE_CHAR Priestap, corroboration of the Steele dossier was in its ?infancy? at the time of the initial NEWLINE_CHAR NEWLINE_CHAR Page FISA application. After Steele was terminated, a source validation report conducted NEWLINE_CHAR NEWLINE_CHAR by an independent unit within FBI assessed Steele?s reporting as only minimally NEWLINE_CHAR NEWLINE_CHAR corroborated. Yet, in early January 2017, Director Comey briefed President-elect Trump NEWLINE_CHAR NEWLINE_CHAR on a summary of the Steele dossier, even though it was??according to his June 2017 NEWLINE_CHAR NEWLINE_CHAR and unveri?ed.? While the FISA application relied on Steele?s NEWLINE_CHAR NEWLINE_CHAR past record of credible reporting on other unrelated matters, it ignored or concealed his NEWLINE_CHAR NEWLINE_CHAR anti?Trump ?nancial and ideological motivations. Furthermore, Deputy Director NEWLINE_CHAR NEWLINE_CHAR McCabe testi?ed before the Committee in December 2017 that no surveillance warrant NEWLINE_CHAR NEWLINE_CHAR would have been sought from the FISC without the Steele dossier information. NEWLINE_CHAR NEWLINE_CHAR r; .r NEWLINE_CHAR NEWLINE_CHAR i. a: NEWLINE_CHAR NEWLINE_CHAR 3:4 ,af- .9.- NEWLINE_CHAR NEWLINE_CHAR PROPERTY OF THE U.S. HOUSE OF REPRESENTATIVES NEWLINE_CHAR NEWLINE_CHAR 5) The Page FISA application also mentions information regarding fellow Trump campaign NEWLINE_CHAR NEWLINE_CHAR advisor George Papadopoulos, but there is no evidence of any cooperation or conspiracy NEWLINE_CHAR NEWLINE_CHAR between Page and Papadopoulos. The Papadopoulos information triggered the opening NEWLINE_CHAR NEWLINE_CHAR of an FBI counterintelligence investigation in late July 2016 by FBI agent Pete Strzok. NEWLINE_CHAR NEWLINE_CHAR Strzok was reassigned by the Special Counsel?s Office to FBI Human Resources for NEWLINE_CHAR NEWLINE_CHAR improper text messages with his mistress, FBI Attorney Lisa Page (no known relation to NEWLINE_CHAR NEWLINE_CHAR Carter Page), where they both demonstrated a clear bias against Trump and in favor of NEWLINE_CHAR NEWLINE_CHAR Clinton, Whom Strzok had also investigated. The Strzok/Lisa Page texts also re?ect NEWLINE_CHAR NEWLINE_CHAR extensive discussions about the investigation, orchestrating leaks to the media, and NEWLINE_CHAR NEWLINE_CHAR include a meeting with Deputy Director McCabe to discuss an ?insurance? policy against NEWLINE_CHAR NEWLINE_CHAR President Trump?s election. NEWLINE_CHAR NEWLINE_CHAR I NEWLINE_CHAR NEWLINE_CHAR PROPERTY OF THE U.S. HOUSE OF REPRESENTATIVES\nPassage 2:\nTweet with a location NEWLINE_CHAR NEWLINE_CHAR You can add location information to your Tweets, such as your city or precise location, from the web and via third-party applications. You always have the option to delete your Tweet location history. Learn more\n\n\nNow, write a one-page summary of all the news.\n\nSummary:"}
{"question_id": 8, "category": "longbench_lcc", "reference": [" String[] sTDocUrls = m_oInspector.getTDocUrls();"], "prompt": "Please complete the code given below. \n/*************************************************************************\n *\n * The Contents of this file are made available subject to the terms of\n * the BSD license.\n *\n * Copyright 2000, 2010 Oracle and/or its affiliates.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Sun Microsystems, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *************************************************************************/\nimport com.sun.star.uno.XComponentContext;\nimport java.awt.Component;\nimport java.awt.Container;\nimport java.awt.Dimension;\nimport java.awt.event.ActionListener;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport javax.swing.ButtonGroup;\nimport javax.swing.JDialog;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JRadioButtonMenuItem;\nimport javax.swing.JTabbedPane;\nimport javax.swing.KeyStroke;\npublic class SwingDialogProvider implements XDialogProvider{\n private JPopupMenu m_jPopupMenu = new JPopupMenu();\n private XComponentContext m_xComponentContext;\n private Inspector._Inspector m_oInspector;\n private JDialog m_jInspectorDialog = new JDialog();\n private JTabbedPane m_jTabbedPane1 = new JTabbedPane();\n private Container cp;\n private JMenu jMnuOptions = new JMenu(\"Options\");\n private JRadioButtonMenuItem jJavaMenuItem = null;\n private JRadioButtonMenuItem jCPlusPlusMenuItem = null;\n private JRadioButtonMenuItem jBasicMenuItem = null;\n /** Creates a new instance of SwingPopupMentuProvider */\n public SwingDialogProvider(Inspector._Inspector _oInspector, String _sTitle) {\n m_oInspector = _oInspector;\n m_xComponentContext = _oInspector.getXComponentContext();\n insertMenus();\n initializePopupMenu();\n cp = m_jInspectorDialog.getContentPane();\n cp.setLayout(new java.awt.BorderLayout(0, 10));\n m_jTabbedPane1.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);\n m_jInspectorDialog.addWindowListener(new InspectorWindowAdapter());\n m_jInspectorDialog.addComponentListener(new InspectorComponentAdapter());\n m_jInspectorDialog.setTitle(_sTitle);\n m_jInspectorDialog.setLocation(100, 50);\n m_jInspectorDialog.getContentPane().add(m_jTabbedPane1);\n }\n public JDialog getDialog(){\n return m_jInspectorDialog;\n }\n private void addMenuBar(JMenuBar _jMenuBar){\n getDialog().setJMenuBar(_jMenuBar);\n }\n private void removeTabPaneByIndex(int _nIndex){\n if (_nIndex > -1){\n String sSelInspectorPanelTitle = m_jTabbedPane1.getTitleAt(_nIndex);\n m_jTabbedPane1.remove(_nIndex);\n m_oInspector.getInspectorPages().remove(sSelInspectorPanelTitle);\n }\n }\n public void selectInspectorPageByIndex(int nTabIndex){\n m_jTabbedPane1.setSelectedIndex(nTabIndex);\n }\n public int getInspectorPageCount(){\n return m_jTabbedPane1.getTabCount();\n }\n public JTabbedPane getTabbedPane(){\n return m_jTabbedPane1;\n }\n public InspectorPane getSelectedInspectorPage(){\n int nIndex = m_jTabbedPane1.getSelectedIndex();\n return getInspectorPage(nIndex);\n }\n public InspectorPane getInspectorPage(int _nIndex){\n InspectorPane oInspectorPane = null;\n if (_nIndex > -1){\n String sInspectorPanelTitle = m_jTabbedPane1.getTitleAt(_nIndex);\n oInspectorPane = m_oInspector.getInspectorPages().get(sInspectorPanelTitle);\n }\n return oInspectorPane;\n }\n private void removeTabPanes(){\n int nCount = m_jTabbedPane1.getTabCount();\n if (nCount > 0){\n for (int i = nCount-1; i >= 0; i--){\n removeTabPaneByIndex(i);\n }\n }\n }\n private void removeSelectedTabPane(){\n int nIndex = getTabbedPane().getSelectedIndex();\n removeTabPaneByIndex(nIndex);\n }\n private class InspectorComponentAdapter extends ComponentAdapter{\n @Override\n public void componentHidden(ComponentEvent e){\n m_jInspectorDialog.pack();\n m_jInspectorDialog.invalidate();\n }\n @Override\n public void componentShown(ComponentEvent e){\n m_jInspectorDialog.pack();\n m_jInspectorDialog.invalidate();\n }\n }\n private class InspectorWindowAdapter extends WindowAdapter{\n @Override\n public void windowClosed(WindowEvent e){\n removeTabPanes();\n m_oInspector.disposeHiddenDocuments();\n }\n @Override\n public void windowClosing(WindowEvent e){\n removeTabPanes();\n m_oInspector.disposeHiddenDocuments();\n }\n }\n private void initializePopupMenu(){\n m_jPopupMenu.add(getInspectMenuItem(\"Inspect\"));\n m_jPopupMenu.add(getSourceCodeMenuItem(SADDTOSOURCECODE));\n m_jPopupMenu.add(getInvokeMenuItem(SINVOKE));\n m_jPopupMenu.addSeparator();\n m_jPopupMenu.add(getHelpMenuItem(\"Help\"));\n }\n private void addOpenDocumentMenu(JMenu _jMnuRoot){\n ActionListener oActionListener = new ActionListener(){\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n String sTDocUrl = evt.getActionCommand();\n m_oInspector.inspectOpenDocument(sTDocUrl);\n }\n };\nNext line of code:\n"}
{"question_id": 9, "category": "longbench_lcc", "reference": ["\tm_maxSlopeCosine = btCos(slopeRadians);"], "prompt": "Please complete the code given below. \n/*\nBullet Continuous Collision Detection and Physics Library\nCopyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com\nThis software is provided 'as-is', without any express or implied warranty.\nIn no event will the authors be held liable for any damages arising from the use of this software.\nPermission is granted to anyone to use this software for any purpose, \nincluding commercial applications, and to alter it and redistribute it freely, \nsubject to the following restrictions:\n1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\n2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\n3. This notice may not be removed or altered from any source distribution.\n*/\n#include <stdio.h>\n#include \"LinearMath/btIDebugDraw.h\"\n#include \"BulletCollision/CollisionDispatch/btGhostObject.h\"\n#include \"BulletCollision/CollisionShapes/btMultiSphereShape.h\"\n#include \"BulletCollision/BroadphaseCollision/btOverlappingPairCache.h\"\n#include \"BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h\"\n#include \"BulletCollision/CollisionDispatch/btCollisionWorld.h\"\n#include \"LinearMath/btDefaultMotionState.h\"\n#include \"btKinematicCharacterController.h\"\n// static helper method\nstatic btVector3\ngetNormalizedVector(ref btVector3 v)\n{\n\tbtVector3 n(0, 0, 0);\n\tif (v.length() > SIMD_EPSILON) {\n\t\tn = v.normalized();\n\t}\n\treturn n;\n}\n///@todo Interact with dynamic objects,\n///Ride kinematicly animated platforms properly\n///More realistic (or maybe just a config option) falling\n/// . Should integrate falling velocity manually and use that in stepDown()\n///Support jumping\n///Support ducking\nclass btKinematicClosestNotMeRayResultCallback : btCollisionWorld::ClosestRayResultCallback\n{\npublic:\n\tbtKinematicClosestNotMeRayResultCallback (btCollisionObject me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))\n\t{\n\t\tm_me = me;\n\t}\n\tvirtual double addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)\n\t{\n\t\tif (rayResult.m_collisionObject == m_me)\n\t\t\treturn 1.0;\n\t\treturn ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace);\n\t}\nprotected:\n\tbtCollisionObject m_me;\n};\nclass btKinematicClosestNotMeConvexResultCallback : btCollisionWorld::ClosestConvexResultCallback\n{\npublic:\n\tbtKinematicClosestNotMeConvexResultCallback (btCollisionObject me, ref btVector3 up, double minSlopeDot)\n\t: btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))\n\t, m_me(me)\n\t, m_up(up)\n\t, m_minSlopeDot(minSlopeDot)\n\t{\n\t}\n\tvirtual double addSingleResult(btCollisionWorld::LocalConvexResult& convexResult,bool normalInWorldSpace)\n\t{\n\t\tif (convexResult.m_hitCollisionObject == m_me)\n\t\t\treturn (double)(1.0);\n\t\tif (!convexResult.m_hitCollisionObject.hasContactResponse())\n\t\t\treturn (double)(1.0);\n\t\tbtVector3 hitNormalWorld;\n\t\tif (normalInWorldSpace)\n\t\t{\n\t\t\thitNormalWorld = convexResult.m_hitNormalLocal;\n\t\t} else\n\t\t{\n\t\t\t///need to transform normal into worldspace\n\t\t\thitNormalWorld = convexResult.m_hitCollisionObject.getWorldTransform().getBasis()*convexResult.m_hitNormalLocal;\n\t\t}\n\t\tdouble dotUp = m_up.dot(hitNormalWorld);\n\t\tif (dotUp < m_minSlopeDot) {\n\t\t\treturn (double)(1.0);\n\t\t}\n\t\treturn ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace);\n\t}\nprotected:\n\tbtCollisionObject m_me;\n\tbtVector3 m_up;\n\tdouble m_minSlopeDot;\n};\n/*\n * Returns the reflection direction of a ray going 'direction' hitting a surface with normal 'normal'\n *\n * from: http://www-cs-students.stanford.edu/~adityagp/final/node3.html\n */\nbtVector3 btKinematicCharacterController::computeReflectionDirection (ref btVector3 direction, ref btVector3 normal)\n{\n\treturn direction - ((double)(2.0) * direction.dot(normal)) * normal;\n}\n/*\n * Returns the portion of 'direction' that is parallel to 'normal'\n */\nbtVector3 btKinematicCharacterController::parallelComponent (ref btVector3 direction, ref btVector3 normal)\n{\n\tdouble magnitude = direction.dot(normal);\n\treturn normal * magnitude;\n}\n/*\n * Returns the portion of 'direction' that is perpindicular to 'normal'\n */\nbtVector3 btKinematicCharacterController::perpindicularComponent (ref btVector3 direction, ref btVector3 normal)\n{\n\treturn direction - parallelComponent(direction, normal);\n}\nbtKinematicCharacterController::btKinematicCharacterController (btPairCachingGhostObject* ghostObject,btConvexShape* convexShape,double stepHeight, int upAxis)\n{\n\tm_upAxis = upAxis;\n\tm_addedMargin = 0.02;\n\tm_walkDirection.setValue(0,0,0);\n\tm_useGhostObjectSweepTest = true;\n\tm_ghostObject = ghostObject;\n\tm_stepHeight = stepHeight;\n\tm_turnAngle = (double)(0.0);\n\tm_convexShape=convexShape;\t\n\tm_useWalkDirection = true;\t// use walk direction by default, legacy behavior\n\tm_velocityTimeInterval = 0.0;\n\tm_verticalVelocity = 0.0;\n\tm_verticalOffset = 0.0;\n\tm_gravity = 9.8 * 3 ; // 3G acceleration.\n\tm_fallSpeed = 55.0; // Terminal velocity of a sky diver in m/s.\n\tm_jumpSpeed = 10.0; // ?\n\tm_wasOnGround = false;\n\tm_wasJumping = false;\n\tm_interpolateUp = true;\n\tsetMaxSlope(btRadians(45.0));\n\tm_currentStepOffset = 0;\n\tfull_drop = false;\n\tbounce_fix = false;\n}\nbtKinematicCharacterController::~btKinematicCharacterController ()\n{\n}\nbtPairCachingGhostObject* btKinematicCharacterController::getGhostObject()\n{\n\treturn m_ghostObject;\n}\nbool btKinematicCharacterController::recoverFromPenetration ( btCollisionWorld* collisionWorld)\n{\n\t// Here we must refresh the overlapping paircache as the penetrating movement itself or the\n\t// previous recovery iteration might have used setWorldTransform and pushed us into an object\n\t// that is not in the previous cache contents from the last timestep, as will happen if we\n\t// are pushed into a new AABB overlap. Unhandled this means the next convex sweep gets stuck.\n\t//\n\t// Do this by calling the broadphase's setAabb with the moved AABB, this will update the broadphase\n\t// paircache and the ghostobject's internal paircache at the same time. /BW\n\tbtVector3 minAabb, maxAabb;\n\tm_convexShape.getAabb(m_ghostObject.getWorldTransform(), minAabb,maxAabb);\n\tcollisionWorld.getBroadphase().setAabb(m_ghostObject.getBroadphaseHandle(), \n\t\t\t\t\t\t minAabb, \n\t\t\t\t\t\t maxAabb, \n\t\t\t\t\t\t collisionWorld.getDispatcher());\n\t\t\t\t\t\t \n\tbool penetration = false;\n\tcollisionWorld.getDispatcher().dispatchAllCollisionPairs(m_ghostObject.getOverlappingPairCache(), collisionWorld.getDispatchInfo(), collisionWorld.getDispatcher());\n\tm_currentPosition = m_ghostObject.getWorldTransform().getOrigin();\n\t\n\tdouble maxPen = (double)(0.0);\n\tfor (int i = 0; i < m_ghostObject.getOverlappingPairCache().getNumOverlappingPairs(); i++)\n\t{\n\t\tm_manifoldArray.resize(0);\n\t\tbtBroadphasePair* collisionPair = &m_ghostObject.getOverlappingPairCache().getOverlappingPairArray()[i];\n\t\tbtCollisionObject obj0 = static_cast<btCollisionObject>(collisionPair.m_pProxy0.m_clientObject);\n btCollisionObject obj1 = static_cast<btCollisionObject>(collisionPair.m_pProxy1.m_clientObject);\n\t\tif ((obj0 && !obj0.hasContactResponse()) || (obj1 && !obj1.hasContactResponse()))\n\t\t\tcontinue;\n\t\t\n\t\tif (collisionPair.m_algorithm)\n\t\t\tcollisionPair.m_algorithm.getAllContactManifolds(m_manifoldArray);\n\t\t\n\t\tfor (int j=0;j<m_manifoldArray.Count;j++)\n\t\t{\n\t\t\tbtPersistentManifold* manifold = m_manifoldArray[j];\n\t\t\tdouble directionSign = manifold.getBody0() == m_ghostObject ? (double)(-1.0) : (double)(1.0);\n\t\t\tfor (int p=0;p<manifold.getNumContacts();p++)\n\t\t\t{\n\t\t\t\tbtManifoldPointpt = manifold.getContactPoint(p);\n\t\t\t\tdouble dist = pt.getDistance();\n\t\t\t\tif (dist < 0.0)\n\t\t\t\t{\n\t\t\t\t\tif (dist < maxPen)\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxPen = dist;\n\t\t\t\t\t\tm_touchingNormal = pt.m_normalWorldOnB * directionSign;//??\n\t\t\t\t\t}\n\t\t\t\t\tm_currentPosition += pt.m_normalWorldOnB * directionSign * dist * (double)(0.2);\n\t\t\t\t\tpenetration = true;\n\t\t\t\t} else {\n\t\t\t\t\t//Console.WriteLine(\"touching %f\\n\", dist);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//manifold.clearManifold();\n\t\t}\n\t}\n\tbtTransform newTrans = m_ghostObject.getWorldTransform();\n\tnewTrans.setOrigin(m_currentPosition);\n\tm_ghostObject.setWorldTransform(newTrans);\n//\tConsole.WriteLine(\"m_touchingNormal = %f,%f,%f\\n\",m_touchingNormal,m_touchingNormal[1],m_touchingNormal[2]);\n\treturn penetration;\n}\nvoid btKinematicCharacterController::stepUp ( btCollisionWorld* world)\n{\n\t// phase 1: up\n\tbtTransform start, end;\n\tm_targetPosition = m_currentPosition + getUpAxisDirections()[m_upAxis] * (m_stepHeight + (m_verticalOffset > 0?m_verticalOffset:0));\n\tstart.setIdentity ();\n\tend.setIdentity ();\n\t/* FIXME: Handle penetration properly */\n\tstart.setOrigin (m_currentPosition + getUpAxisDirections()[m_upAxis] * (m_convexShape.getMargin() + m_addedMargin));\n\tend.setOrigin (m_targetPosition);\n\tbtKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, -getUpAxisDirections()[m_upAxis], (double)(0.7071));\n\tcallback.m_collisionFilterGroup = getGhostObject().getBroadphaseHandle().m_collisionFilterGroup;\n\tcallback.m_collisionFilterMask = getGhostObject().getBroadphaseHandle().m_collisionFilterMask;\n\t\n\tif (m_useGhostObjectSweepTest)\n\t{\n\t\tm_ghostObject.convexSweepTest (m_convexShape, start, end, callback, world.getDispatchInfo().m_allowedCcdPenetration);\n\t}\n\telse\n\t{\n\t\tworld.convexSweepTest (m_convexShape, start, end, callback);\n\t}\n\t\n\tif (callback.hasHit())\n\t{\n\t\t// Only modify the position if the hit was a slope and not a wall or ceiling.\n\t\tif(callback.m_hitNormalWorld.dot(getUpAxisDirections()[m_upAxis]) > 0.0)\n\t\t{\n\t\t\t// we moved up only a fraction of the step height\n\t\t\tm_currentStepOffset = m_stepHeight * callback.m_closestHitFraction;\n\t\t\tif (m_interpolateUp == true)\n\t\t\t\tm_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);\n\t\t\telse\n\t\t\t\tm_currentPosition = m_targetPosition;\n\t\t}\n\t\tm_verticalVelocity = 0.0;\n\t\tm_verticalOffset = 0.0;\n\t} else {\n\t\tm_currentStepOffset = m_stepHeight;\n\t\tm_currentPosition = m_targetPosition;\n\t}\n}\nvoid btKinematicCharacterController::updateTargetPositionBasedOnCollision (ref btVector3 hitNormal, double tangentMag, double normalMag)\n{\n\tbtVector3 movementDirection = m_targetPosition - m_currentPosition;\n\tdouble movementLength = movementDirection.length();\n\tif (movementLength>SIMD_EPSILON)\n\t{\n\t\tmovementDirection.normalize();\n\t\tbtVector3 reflectDir = computeReflectionDirection (movementDirection, hitNormal);\n\t\treflectDir.normalize();\n\t\tbtVector3 parallelDir, perpindicularDir;\n\t\tparallelDir = parallelComponent (reflectDir, hitNormal);\n\t\tperpindicularDir = perpindicularComponent (reflectDir, hitNormal);\n\t\tm_targetPosition = m_currentPosition;\n\t\tif (0)//tangentMag != 0.0)\n\t\t{\n\t\t\tbtVector3 parComponent = parallelDir * double (tangentMag*movementLength);\n//\t\t\tConsole.WriteLine(\"parComponent=%f,%f,%f\\n\",parComponent[0],parComponent[1],parComponent[2]);\n\t\t\tm_targetPosition += parComponent;\n\t\t}\n\t\tif (normalMag != 0.0)\n\t\t{\n\t\t\tbtVector3 perpComponent = perpindicularDir * double (normalMag*movementLength);\n//\t\t\tConsole.WriteLine(\"perpComponent=%f,%f,%f\\n\",perpComponent[0],perpComponent[1],perpComponent[2]);\n\t\t\tm_targetPosition += perpComponent;\n\t\t}\n\t} else\n\t{\n//\t\tConsole.WriteLine(\"movementLength don't normalize a zero vector\\n\");\n\t}\n}\nvoid btKinematicCharacterController::stepForwardAndStrafe ( btCollisionWorld* collisionWorld, ref btVector3 walkMove)\n{\n\t// Console.WriteLine(\"m_normalizedDirection=%f,%f,%f\\n\",\n\t// \tm_normalizedDirection[0],m_normalizedDirection[1],m_normalizedDirection[2]);\n\t// phase 2: forward and strafe\n\tbtTransform start, end;\n\tm_targetPosition = m_currentPosition + walkMove;\n\tstart.setIdentity ();\n\tend.setIdentity ();\n\t\n\tdouble fraction = 1.0;\n\tdouble distance2 = (m_currentPosition-m_targetPosition).length2();\n//\tConsole.WriteLine(\"distance2=%f\\n\",distance2);\n\tif (m_touchingContact)\n\t{\n\t\tif (m_normalizedDirection.dot(m_touchingNormal) > (double)(0.0))\n\t\t{\n\t\t\t//interferes with step movement\n\t\t\t//updateTargetPositionBasedOnCollision (m_touchingNormal);\n\t\t}\n\t}\n\tint maxIter = 10;\n\twhile (fraction > (double)(0.01) && maxIter-- > 0)\n\t{\n\t\tstart.setOrigin (m_currentPosition);\n\t\tend.setOrigin (m_targetPosition);\n\t\tbtVector3 sweepDirNegative(m_currentPosition - m_targetPosition);\n\t\tbtKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, sweepDirNegative, (double)(0.0));\n\t\tcallback.m_collisionFilterGroup = getGhostObject().getBroadphaseHandle().m_collisionFilterGroup;\n\t\tcallback.m_collisionFilterMask = getGhostObject().getBroadphaseHandle().m_collisionFilterMask;\n\t\tdouble margin = m_convexShape.getMargin();\n\t\tm_convexShape.setMargin(margin + m_addedMargin);\n\t\tif (m_useGhostObjectSweepTest)\n\t\t{\n\t\t\tm_ghostObject.convexSweepTest (m_convexShape, start, end, callback, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t} else\n\t\t{\n\t\t\tcollisionWorld.convexSweepTest (m_convexShape, start, end, callback, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t}\n\t\t\n\t\tm_convexShape.setMargin(margin);\n\t\t\n\t\tfraction -= callback.m_closestHitFraction;\n\t\tif (callback.hasHit())\n\t\t{\t\n\t\t\t// we moved only a fraction\n\t\t\t//double hitDistance;\n\t\t\t//hitDistance = (callback.m_hitPointWorld - m_currentPosition).length();\n//\t\t\tm_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);\n\t\t\tupdateTargetPositionBasedOnCollision (callback.m_hitNormalWorld);\n\t\t\tbtVector3 currentDir = m_targetPosition - m_currentPosition;\n\t\t\tdistance2 = currentDir.length2();\n\t\t\tif (distance2 > SIMD_EPSILON)\n\t\t\t{\n\t\t\t\tcurrentDir.normalize();\n\t\t\t\t/* See Quake2: \"If velocity is against original velocity, stop ead to avoid tiny oscilations in sloping corners.\" */\n\t\t\t\tif (currentDir.dot(m_normalizedDirection) <= (double)(0.0))\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t{\n//\t\t\t\tConsole.WriteLine(\"currentDir: don't normalize a zero vector\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\t// we moved whole way\n\t\t\tm_currentPosition = m_targetPosition;\n\t\t}\n\t//\tif (callback.m_closestHitFraction == 0)\n\t//\t\tbreak;\n\t}\n}\nvoid btKinematicCharacterController::stepDown ( btCollisionWorld* collisionWorld, double dt)\n{\n\tbtTransform start, end, end_double;\n\tbool runonce = false;\n\t// phase 3: down\n\t/*double additionalDownStep = (m_wasOnGround && !onGround()) ? m_stepHeight : 0.0;\n\tbtVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + additionalDownStep);\n\tdouble downVelocity = (additionalDownStep == 0.0 && m_verticalVelocity<0.0?-m_verticalVelocity:0.0) * dt;\n\tbtVector3 gravity_drop = getUpAxisDirections()[m_upAxis] * downVelocity; \n\tm_targetPosition -= (step_drop + gravity_drop);*/\n\tbtVector3 orig_position = m_targetPosition;\n\t\n\tdouble downVelocity = (m_verticalVelocity<0?-m_verticalVelocity:0) * dt;\n\tif(downVelocity > 0.0 && downVelocity > m_fallSpeed\n\t\t&& (m_wasOnGround || !m_wasJumping))\n\t\tdownVelocity = m_fallSpeed;\n\tbtVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);\n\tm_targetPosition -= step_drop;\n\tbtKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, getUpAxisDirections()[m_upAxis], m_maxSlopeCosine);\n callback.m_collisionFilterGroup = getGhostObject().getBroadphaseHandle().m_collisionFilterGroup;\n callback.m_collisionFilterMask = getGhostObject().getBroadphaseHandle().m_collisionFilterMask;\n btKinematicClosestNotMeConvexResultCallback callback2 (m_ghostObject, getUpAxisDirections()[m_upAxis], m_maxSlopeCosine);\n callback2.m_collisionFilterGroup = getGhostObject().getBroadphaseHandle().m_collisionFilterGroup;\n callback2.m_collisionFilterMask = getGhostObject().getBroadphaseHandle().m_collisionFilterMask;\n\twhile (1)\n\t{\n\t\tstart.setIdentity ();\n\t\tend.setIdentity ();\n\t\tend_double.setIdentity ();\n\t\tstart.setOrigin (m_currentPosition);\n\t\tend.setOrigin (m_targetPosition);\n\t\t//set double test for 2x the step drop, to check for a large drop vs small drop\n\t\tend_double.setOrigin (m_targetPosition - step_drop);\n\t\tif (m_useGhostObjectSweepTest)\n\t\t{\n\t\t\tm_ghostObject.convexSweepTest (m_convexShape, start, end, callback, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t\tif (!callback.hasHit())\n\t\t\t{\n\t\t\t\t//test a double fall height, to see if the character should interpolate it's fall (full) or not (partial)\n\t\t\t\tm_ghostObject.convexSweepTest (m_convexShape, start, end_double, callback2, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t\t}\n\t\t} else\n\t\t{\n\t\t\tcollisionWorld.convexSweepTest (m_convexShape, start, end, callback, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t\tif (!callback.hasHit())\n\t\t\t\t\t{\n\t\t\t\t\t\t\t//test a double fall height, to see if the character should interpolate it's fall (large) or not (small)\n\t\t\t\t\t\t\tcollisionWorld.convexSweepTest (m_convexShape, start, end_double, callback2, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t\t\t\t}\n\t\t}\n\t\n\t\tdouble downVelocity2 = (m_verticalVelocity<0?-m_verticalVelocity:0) * dt;\n\t\tbool has_hit = false;\n\t\tif (bounce_fix == true)\n\t\t\thas_hit = callback.hasHit() || callback2.hasHit();\n\t\telse\n\t\t\thas_hit = callback2.hasHit();\n\t\tif(downVelocity2 > 0.0 && downVelocity2 < m_stepHeight && has_hit == true && runonce == false\n\t\t\t\t\t&& (m_wasOnGround || !m_wasJumping))\n\t\t{\n\t\t\t//redo the velocity calculation when falling a small amount, for fast stairs motion\n\t\t\t//for larger falls, use the smoother/slower interpolated movement by not touching the target position\n\t\t\tm_targetPosition = orig_position;\n\t\t\t\t\tdownVelocity = m_stepHeight;\n\t\t\t\tbtVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);\n\t\t\tm_targetPosition -= step_drop;\n\t\t\trunonce = true;\n\t\t\tcontinue; //re-run previous tests\n\t\t}\n\t\tbreak;\n\t}\n\tif (callback.hasHit() || runonce == true)\n\t{\n\t\t// we dropped a fraction of the height . hit floor\n\t\tdouble fraction = (m_currentPosition.y - callback.m_hitPointWorld.y) / 2;\n\t\t//Console.WriteLine(\"hitpoint: %g - pos %g\\n\", callback.m_hitPointWorld.y, m_currentPosition.y);\n\t\tif (bounce_fix == true)\n\t\t{\n\t\t\tif (full_drop == true)\n m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);\n else\n //due to errors in the closestHitFraction variable when used with large polygons, calculate the hit fraction manually\n m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, fraction);\n\t\t}\n\t\telse\n\t\t\tm_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);\n\t\tfull_drop = false;\n\t\tm_verticalVelocity = 0.0;\n\t\tm_verticalOffset = 0.0;\n\t\tm_wasJumping = false;\n\t} else {\n\t\t// we dropped the full height\n\t\t\n\t\tfull_drop = true;\n\t\tif (bounce_fix == true)\n\t\t{\n\t\t\tdownVelocity = (m_verticalVelocity<0?-m_verticalVelocity:0) * dt;\n\t\t\tif (downVelocity > m_fallSpeed && (m_wasOnGround || !m_wasJumping))\n\t\t\t{\n\t\t\t\tm_targetPosition += step_drop; //undo previous target change\n\t\t\t\tdownVelocity = m_fallSpeed;\n\t\t\t\tstep_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);\n\t\t\t\tm_targetPosition -= step_drop;\n\t\t\t}\n\t\t}\n\t\t//Console.WriteLine(\"full drop - %g, %g\\n\", m_currentPosition.y, m_targetPosition.y);\n\t\tm_currentPosition = m_targetPosition;\n\t}\n}\nvoid btKinematicCharacterController::setWalkDirection\n(\nref btVector3 walkDirection\n)\n{\n\tm_useWalkDirection = true;\n\tm_walkDirection = walkDirection;\n\tm_normalizedDirection = getNormalizedVector(m_walkDirection);\n}\nvoid btKinematicCharacterController::setVelocityForTimeInterval\n(\nref btVector3 velocity,\ndouble timeInterval\n)\n{\n//\tConsole.WriteLine(\"setVelocity!\\n\");\n//\tConsole.WriteLine(\" interval: %f\\n\", timeInterval);\n//\tConsole.WriteLine(\" velocity: (%f, %f, %f)\\n\",\n//\t\t velocity.x, velocity.y, velocity.z);\n\tm_useWalkDirection = false;\n\tm_walkDirection = velocity;\n\tm_normalizedDirection = getNormalizedVector(m_walkDirection);\n\tm_velocityTimeInterval += timeInterval;\n}\nvoid btKinematicCharacterController::reset ( btCollisionWorld* collisionWorld )\n{\n m_verticalVelocity = 0.0;\n m_verticalOffset = 0.0;\n m_wasOnGround = false;\n m_wasJumping = false;\n m_walkDirection.setValue(0,0,0);\n m_velocityTimeInterval = 0.0;\n //clear pair cache\n btHashedOverlappingPairCache *cache = m_ghostObject.getOverlappingPairCache();\n while (cache.getOverlappingPairArray().Count > 0)\n {\n cache.removeOverlappingPair(cache.getOverlappingPairArray()[0].m_pProxy0, cache.getOverlappingPairArray()[0].m_pProxy1, collisionWorld.getDispatcher());\n }\n}\nvoid btKinematicCharacterController::warp (ref btVector3 origin)\n{\n\tbtTransform xform;\n\txform.setIdentity();\n\txform.setOrigin (origin);\n\tm_ghostObject.setWorldTransform (xform);\n}\nvoid btKinematicCharacterController::preStep ( btCollisionWorld* collisionWorld)\n{\n\t\n\tint numPenetrationLoops = 0;\n\tm_touchingContact = false;\n\twhile (recoverFromPenetration (collisionWorld))\n\t{\n\t\tnumPenetrationLoops++;\n\t\tm_touchingContact = true;\n\t\tif (numPenetrationLoops > 4)\n\t\t{\n\t\t\t//Console.WriteLine(\"character could not recover from penetration = %d\\n\", numPenetrationLoops);\n\t\t\tbreak;\n\t\t}\n\t}\n\tm_currentPosition = m_ghostObject.getWorldTransform().getOrigin();\n\tm_targetPosition = m_currentPosition;\n//\tConsole.WriteLine(\"m_targetPosition=%f,%f,%f\\n\",m_targetPosition[0],m_targetPosition[1],m_targetPosition[2]);\n\t\n}\n#include <stdio.h>\nvoid btKinematicCharacterController::playerStep ( btCollisionWorld* collisionWorld, double dt)\n{\n//\tConsole.WriteLine(\"playerStep(): \");\n//\tConsole.WriteLine(\" dt = %f\", dt);\n\t// quick check...\n\tif (!m_useWalkDirection & (m_velocityTimeInterval <= 0.0 || m_walkDirection.fuzzyZero())) {\n//\t\tConsole.WriteLine(\"\\n\");\n\t\treturn;\t\t// no motion\n\t}\n\tm_wasOnGround = onGround();\n\t// Update fall velocity.\n\tm_verticalVelocity -= m_gravity * dt;\n\tif(m_verticalVelocity > 0.0 && m_verticalVelocity > m_jumpSpeed)\n\t{\n\t\tm_verticalVelocity = m_jumpSpeed;\n\t}\n\tif(m_verticalVelocity < 0.0 && btFabs(m_verticalVelocity) > btFabs(m_fallSpeed))\n\t{\n\t\tm_verticalVelocity = -btFabs(m_fallSpeed);\n\t}\n\tm_verticalOffset = m_verticalVelocity * dt;\n\tbtTransform xform;\n\txform = m_ghostObject.getWorldTransform ();\n//\tConsole.WriteLine(\"walkDirection(%f,%f,%f)\\n\",walkDirection,walkDirection[1],walkDirection[2]);\n//\tConsole.WriteLine(\"walkSpeed=%f\\n\",walkSpeed);\n\tstepUp (collisionWorld);\n\tif (m_useWalkDirection) {\n\t\tstepForwardAndStrafe (collisionWorld, m_walkDirection);\n\t} else {\n\t\t//Console.WriteLine(\" time: %f\", m_velocityTimeInterval);\n\t\t// still have some time left for moving!\n\t\tdouble dtMoving =\n\t\t\t(dt < m_velocityTimeInterval) ? dt : m_velocityTimeInterval;\n\t\tm_velocityTimeInterval -= dt;\n\t\t// how far will we move while we are moving?\n\t\tbtVector3 move = m_walkDirection * dtMoving;\n\t\t//Console.WriteLine(\" dtMoving: %f\", dtMoving);\n\t\t// okay, step\n\t\tstepForwardAndStrafe(collisionWorld, move);\n\t}\n\tstepDown (collisionWorld, dt);\n\t// Console.WriteLine(\"\\n\");\n\txform.setOrigin (m_currentPosition);\n\tm_ghostObject.setWorldTransform (xform);\n}\nvoid btKinematicCharacterController::setFallSpeed (double fallSpeed)\n{\n\tm_fallSpeed = fallSpeed;\n}\nvoid btKinematicCharacterController::setJumpSpeed (double jumpSpeed)\n{\n\tm_jumpSpeed = jumpSpeed;\n}\nvoid btKinematicCharacterController::setMaxJumpHeight (double maxJumpHeight)\n{\n\tm_maxJumpHeight = maxJumpHeight;\n}\nbool btKinematicCharacterController::canJump ()\n{\n\treturn onGround();\n}\nvoid btKinematicCharacterController::jump ()\n{\n\tif (!canJump())\n\t\treturn;\n\tm_verticalVelocity = m_jumpSpeed;\n\tm_wasJumping = true;\n#if 0\n\tcurrently no jumping.\n\tbtTransform xform;\n\tm_rigidBody.getMotionState().getWorldTransform (xform);\n\tbtVector3 up = xform.getBasis()[1];\n\tup.normalize ();\n\tdouble magnitude = ((double)(1.0)/m_rigidBody.getInvMass()) * (double)(8.0);\n\tm_rigidBody.applyCentralImpulse (up * magnitude);\n#endif\n}\nvoid btKinematicCharacterController::setGravity(double gravity)\n{\n\tm_gravity = gravity;\n}\ndouble btKinematicCharacterController::getGravity()\n{\n\treturn m_gravity;\n}\nvoid btKinematicCharacterController::setMaxSlope(double slopeRadians)\n{\n\tm_maxSlopeRadians = slopeRadians;\nNext line of code:\n"}
{"question_id": 10, "category": "longbench_trec", "reference": ["City"], "prompt": "Please determine the type of the question below. Here are some examples of questions.\n\nQuestion: What was the first video ever made ?\nType: Invention, book and other creative piece\nQuestion: What people make up half the Soviet Union 's population ?\nType: Group or organization of person\nQuestion: How can you become an FBI agent ?\nType: Manner of an action\nQuestion: Who was the mother of the man who would not be king , the duke of Windsor ?\nType: Individual\nQuestion: What two countries in South America are landlocked ?\nType: Country\nQuestion: Where is your corpus callosum ?\nType: Other location\nQuestion: Who died with more than 1 , 000 U.S. patents to his credit ?\nType: Individual\nQuestion: What age is Benny Carter ?\nType: Lasting time of somethin\nQuestion: What is `` flintknapping '' ?\nType: Definition of something\nQuestion: What city 's theatrical district has been dubbed The Roaring Forties ?\nType: City\nQuestion: What does the `` blue ribbon '' stand for ?\nType: Expression abbreviated\nQuestion: How much of the silver production is manufactured by independent silversmiths ?\nType: Number of something\nQuestion: What is a specimen of basidiomycetes ?\nType: Definition of something\nQuestion: What are the dimensions of an ice hockey goal ?\nType: Distance, linear measure\nQuestion: Where is South Bend ?\nType: Other location\nQuestion: What are the chances of pregnacy if the penis does not penetrate the vagina ?\nType: Percent, fraction\nQuestion: Who provides telephone service in Orange County , California ?\nType: Group or organization of person\nQuestion: Define Spumante .\nType: Definition of something\nQuestion: When was the women 's suffrage amendment ratified ?\nType: Date\nQuestion: What did the forward-thinking Simon Brothers Bakery of Chicago insert into bagels to boost business ?\nType: Other entity\nQuestion: Why are there olives in martinis ?\nType: Reason\nQuestion: Which soft drink does Madonna advertise for ?\nType: Food\nQuestion: What is the most commonly used 1 letter word in the English language ?\nType: Word with a special property\nQuestion: What ocean was Amelia Earhart flying over when she disappeared ?\nType: Other location\nQuestion: In which sport is there a `` scrum '' ?\nType: Sport\nQuestion: How many innings are there in a regulation softball game ?\nType: Number of something\nQuestion: What does the word LASER mean ?\nType: Expression abbreviated\nQuestion: What are some mythology websites ?\nType: Other location\nQuestion: What is the frequency of VHF ?\nType: Other number\nQuestion: What is the difference between molecules and compounds ?\nType: Description of something\nQuestion: What is e-commerce ?\nType: Definition of something\nQuestion: What 1942 espionage movie reunited director John Huston with Maltese Falconers Humphrey Bogart , Mary Astor , and Sidney Greenstreet ?\nType: Invention, book and other creative piece\nQuestion: How many warmup pitches does a reliever get coming into a baseball game ?\nType: Number of something\nQuestion: How far can a human eye see ?\nType: Distance, linear measure\nQuestion: Whose autobiography is titled Yes I Can ?\nType: Individual\nQuestion: Name of heroine in `` Scruples '' ?\nType: Individual\nQuestion: Why does it snow ?\nType: Reason\nQuestion: What Japanese electronics company was named for a coastal city northeast of Tokyo ?\nType: Group or organization of person\nQuestion: What year were the Olympic Games played in where Nadia Comaneci became popular ?\nType: Date\nQuestion: Where is Amsterdam ?\nType: Other location\nQuestion: What two US biochemists won the Nobel Prize in medicine in 1992 ?\nType: Individual\nQuestion: What do Englishmen weigh themselves in ?\nType: Weight\nQuestion: What impenetrable system of French fortifications was built along the German frontier before World War II ?\nType: Other entity\nQuestion: What 's the maximum length , in inches , of a first baseman 's glove ?\nType: Number of something\nQuestion: What state produces the best lobster to eat ?\nType: State\nQuestion: Stuart Hamblen is considered to be the first singing cowboy of what ?\nType: Invention, book and other creative piece\nQuestion: What does a pedometer measure ?\nType: Other entity\nQuestion: What was the name of the director of the movie `` Jaws '' ?\nType: Individual\nQuestion: Name the first Russian astronaut to do a spacewalk .\nType: Individual\nQuestion: Which Bloom County resident wreaks havoc with a computer ?\nType: Individual\nQuestion: How long did Shea and Gould practice law in Los Angeles ?\nType: Lasting time of somethin\nQuestion: How tall is Prince Charles ?\nType: Distance, linear measure\nQuestion: What country has the highest per capita consumption of cheese ?\nType: Country\nQuestion: What are the highest-paying odds on a roulette table ?\nType: Percent, fraction\nQuestion: What lake is Sheboygan on ?\nType: Other location\nQuestion: Where is the Danube ?\nType: Other location\nQuestion: What fast-food magnate 's initials graced the left sleeve of the San Diego Padres ' baseball uniforms in 1984 ?\nType: Group or organization of person\nQuestion: Hazmat stands for what ?\nType: Definition of something\nQuestion: What plant is rum made from ?\nType: Plant\nQuestion: Where did Bill Gates go to college ?\nType: Other location\nQuestion: What city is sometimes called Gotham ?\nType: City\nQuestion: On average , how many miles are there to the moon ?\nType: Number of something\nQuestion: What are the odds of giving birth to twins ?\nType: Percent, fraction\nQuestion: How do you tell somebody you like them ?\nType: Manner of an action\nQuestion: What countries have the most auto thefts ?\nType: Country\nQuestion: How much did Manchester United spend on players in 1993 ?\nType: Price\nQuestion: What TV station did Mary Richards work for ?\nType: Invention, book and other creative piece\nQuestion: What Morris West novel deals with Russian bishop who becomes Pope ?\nType: Invention, book and other creative piece\nQuestion: What is a reliable site that I can download Heretic 2 ?\nType: Other location\nQuestion: What film or films has Jude Law appeared in ?\nType: Invention, book and other creative piece\nQuestion: What day was Pearl Harbor attacked in 1942 ?\nType: Date\nQuestion: Where is Natchitoches , Louisiana ?\nType: Other location\nQuestion: What task does the Bouvier breed of dog perform ?\nType: Title of a person\nQuestion: What revelation did Alexander Butterfield make to the Senate Watergate committee ?\nType: Description of something\nQuestion: How many pairs of legs does a lobster have ?\nType: Number of something\nQuestion: What color , s , appear on boxes of Kodak film ?\nType: Color\nQuestion: How many people died on D-Day ?\nType: Number of something\nQuestion: What is an annotated bibliography ?\nType: Definition of something\nQuestion: What is a caldera ?\nType: Definition of something\nQuestion: Where is the largest dam in the world ?\nType: Other location\nQuestion: What was Mae West 's last film ?\nType: Invention, book and other creative piece\nQuestion: Who is the sexiest women in the world ?\nType: Individual\nQuestion: What kind of rocket launched the Surveyor spacecraft ?\nType: Vehicle\nQuestion: What causes an earthquake ?\nType: Reason\nQuestion: How many feet long is a baseball pitcher 's rubber ?\nType: Number of something\nQuestion: What dummy received an honorary degree from Northwestern University ?\nType: Individual\nQuestion: Who is section manager for guidance and control systems at JPL ?\nType: Individual\nQuestion: What creative genius said : `` Everything comes to him who hustles while he waits '' ?\nType: Individual\nQuestion: Who is the owner of CNN ?\nType: Individual\nQuestion: What suburban housewife and mother of three wrote The Feminine Mystique ?\nType: Individual\nQuestion: What city is . KDGE Radio located in ?\nType: City\nQuestion: What is Nebraska 's most valuable resource ?\nType: Other entity\nQuestion: Where is the human skin least sensitive ?\nType: Organ of body\nQuestion: What is the abbreviated form of the National Bureau of Investigation ?\nType: Abbreviation\nQuestion: What was the highest mountain on earth before Mount Everest was discovered ?\nType: Mountain\nQuestion: What month were you born in if your birthstone is sardonyx ?\nType: Date\nQuestion: What blew up at Lakehurst , New Jersey , on May 6 , 1977 ?\nType: Other entity\nQuestion: How many miles is it from London , England to Plymouth , England ?\nType: Number of something\nQuestion: What is Larry King 's occupation ?\nType: Title of a person\nQuestion: How can I find out my biorhythm ?\nType: Manner of an action\nQuestion: What developed a crack in 1835 while tolling the death of U.S. Chief Justice John Marshall ?\nType: Other entity\nQuestion: How is plastic made ?\nType: Manner of an action\nQuestion: What Pope inaugurated Vatican International Radio ?\nType: Individual\nQuestion: What feud ended with a marriage in Kentucky on March 21 , 1891 ?\nType: Event\nQuestion: What does Ouija mean ?\nType: Definition of something\nQuestion: What was the name of Randy Craft 's lawyer ?\nType: Individual\nQuestion: Who is Samuel F. Pickering ?\nType: Description of a person\nQuestion: What 's the middle name of movie producer Joseph E. Levine ?\nType: Individual\nQuestion: Who was nicknamed The Little Corporal ?\nType: Individual\nQuestion: Who was Thucydides ?\nType: Description of a person\nQuestion: What is the name of the police officer who tried to keep order in Top Cat 's neighborhood ?\nType: Individual\nQuestion: What chocolate bar created by Frank Mars and his wife is often called a Milky Way with peanuts ?\nType: Food\nQuestion: What is the alphabet for Latin ?\nType: Letter like a-z\nQuestion: How do I impress a guy ?\nType: Manner of an action\nQuestion: Where is the Orange Bowl ?\nType: Other location\nQuestion: What did John F. Kennedy consider his greatest blunder in office ?\nType: Description of something\nQuestion: What is LMDS ?\nType: Expression abbreviated\nQuestion: What are amaretto biscuits ?\nType: Definition of something\nQuestion: What are Bellworts ?\nType: Definition of something\nQuestion: What European country 's monarchy was restored in 1975 ?\nType: Country\nQuestion: What causes the redness in your cheeks when you blush ?\nType: Reason\nQuestion: Where did surfing originate ?\nType: Other location\nQuestion: Which team won the Super Bowl in 1968 ?\nType: Group or organization of person\nQuestion: What Batman character tools around on a Batcycle ?\nType: Individual\nQuestion: What camera company said , `` If you haven 't got the time , we 've got the camera ? ''\nType: Group or organization of person\nQuestion: What are the requirements for becoming a citizen of Australia ?\nType: Description of something\nQuestion: Name a novel written by John Steinbeck .\nType: Invention, book and other creative piece\nQuestion: Who was the first jockey to ride two Triple Crown winners ?\nType: Individual\nQuestion: Who played the title role in The Romantic Englishwoman ?\nType: Individual\nQuestion: What London museum features a Chamber of Horrors ?\nType: Other location\nQuestion: Which presidents of the USA were Masons ?\nType: Individual\nQuestion: Who 's the lead singer of the Led Zeppelin band ?\nType: Individual\nQuestion: Who owns the St. Louis Rams ?\nType: Individual\nQuestion: What organization was founded by the Rev. Jerry Falwell ?\nType: Group or organization of person\nQuestion: What color is the stripe along each side of a Coho salmon ?\nType: Color\nQuestion: What singer became despondent over the death of Freddie Prinze , quit show business , and then quit the business ?\nType: Individual\nQuestion: Who was the first American poet to win the Nobel Prize for literature , in 1948 ?\nType: Individual\nQuestion: What does SIDS stand for ?\nType: Expression abbreviated\nQuestion: What 's the most abundant element in the sun ?\nType: Element and substance\nQuestion: What state was named the Green Mountain state ?\nType: State\nQuestion: Who started the Dominos Pizza chain ?\nType: Individual\nQuestion: What is the name of the city that Maurizio Pellegrin lives in ?\nType: City\nQuestion: Whose biography by Maurice Zolotow is titled Shooting Star ?\nType: Individual\nQuestion: What was the favorite sport of Tom Wolfe 's The Pump House Gang ?\nType: Sport\nQuestion: Where did Wile E. Coyote always get his devices ?\nType: Other location\nQuestion: What brand of white rum is still made in Cuba ?\nType: Product\nQuestion: For what reason did some San Diego schools stop serving apples ?\nType: Reason\nQuestion: How many Stradivarius violins were ever made ?\nType: Number of something\nQuestion: How do they get Teflon to stick to the pan ?\nType: Manner of an action\nQuestion: How long do flies live ?\nType: Lasting time of somethin\nQuestion: How many people died when the Estonia sank in 1994 ?\nType: Number of something\nQuestion: What year did Apartheid start ?\nType: Date\nQuestion: What is the regular price ?\nType: Price\nQuestion: How many months does a normal human pregnancy last ?\nType: Number of something\nQuestion: What kind of organization is ` Last Chance for Animals ' ?\nType: Group or organization of person\nQuestion: What country boasts the southernmost point in continental Europe ?\nType: Country\nQuestion: Name a golf course in Myrtle Beach .\nType: Other entity\nQuestion: Where did the myth of Santa Claus originate ?\nType: Other location\nQuestion: What is a fear of weakness ?\nType: Disease and medicine\nQuestion: Name a canine cartoon character other than Huckleberry Hound to have a voice by Daws Butler .\nType: Individual\nQuestion: What country has the most time zones , with 11 ?\nType: Country\nQuestion: What did Mr. Magoo flog on TV for General Electric ?\nType: Other entity\nQuestion: What species was Winnie the Pooh ?\nType: Animal\nQuestion: Why are electric cars less efficient in the northeast than in California ?\nType: Reason\nQuestion: What is the belt of low pressure around the equator called ?\nType: Equivalent term\nQuestion: What does CNN stand for ?\nType: Expression abbreviated\nQuestion: Where can I read about Chiang Kai-shek ?\nType: Other location\nQuestion: What is Bombay duck ?\nType: Definition of something\nQuestion: Whose video is titled Shape Up with Arnold ?\nType: Individual\nQuestion: What are my legal rights in an automobile repossession in California ?\nType: Description of something\nQuestion: How long does James Bond like his eggs boiled ?\nType: Lasting time of somethin\nQuestion: What was John F. Kennedy 's 1960 campaign song ?\nType: Invention, book and other creative piece\nQuestion: What country covers 8 , 600 , 387 square miles ?\nType: Country\nQuestion: Where was the first zoo in the U.S. ?\nType: Other location\nQuestion: The operating system that runs on IBM-compatible machines is called what ?\nType: Equivalent term\nQuestion: What do Hasidic Jews refrain from while dating ?\nType: Other entity\nQuestion: In 139 the papal court was forced to move from Rome to where ?\nType: Other location\nQuestion: Who said `` What contemptible scoundrel stole the cork from my lunch ? ''\nType: Individual\nQuestion: What country is the worlds leading supplier of cannabis ?\nType: Country\nQuestion: What did Cool Hand Luke go to jail for ?\nType: Reason\nQuestion: Who were the Yankee 's frequent enemies ?\nType: Group or organization of person\nQuestion: Who tramped through Florida looking for the Fountain of Youth ?\nType: Individual\nQuestion: What woman has carried the most multiple births , twins , triplets , etc. , ?\nType: Individual\nQuestion: How many miles of corridors are in The Pentagon ?\nType: Number of something\nQuestion: What is Candlemas Day ?\nType: Definition of something\nQuestion: What was the Ventura County police department that seized the county 's largest amount of cocaine ever ?\nType: Group or organization of person\nQuestion: Who portrayed Maggio in the film From Here to Eternity ?\nType: Individual\nQuestion: When are sheep shorn ?\nType: Date\nQuestion: Whose acceptance speech of more than 3 minutes prompted a time limit on Academy Award thank-yous ?\nType: Individual\nQuestion: What is Mississippi 's state animal ?\nType: Animal\nQuestion: How can SQL queries be improved ?\nType: Manner of an action\nQuestion: What actor 's autobiography is titled All My Yesterdays ?\nType: Individual\nQuestion: What is the most widely cultivated plant ?\nType: Plant\nQuestion: What actor has a tattoo on his right wrist reading Scotland Forever ?\nType: Individual\nQuestion: Where does Ray Bradbury 's Chronicles take place ?\nType: Other location\nQuestion: What is false consciousness ?\nType: Definition of something\nQuestion: What is the length of border between the Ukraine and Russia ?\nType: Distance, linear measure\nQuestion: What does Melissa mean ?\nType: Definition of something\nQuestion: What animal 's tail is called a brush ?\nType: Animal\nQuestion: In what year did the US Marine Corps adopt the motto `` Semper Fidelis '' ?\nType: Date\nQuestion: How many species of the Great White shark are there ?\nType: Number of something\nQuestion: What are snowballs to a hot-rodder ?\nType: Definition of something\nQuestion: What does Salk vaccine prevent ?\nType: Disease and medicine\nQuestion: Who used AuH2O as an election slogan ?\nType: Individual\nQuestion: Where is Romania located ?\nType: Other location\nQuestion: What was the education system in the 1960 's ?\nType: Other entity\nQuestion: Who was the first actress to appear on a postage stamp ?\nType: Individual\nQuestion: Who turned all he touched to gold ?\nType: Individual\nQuestion: What is the largest city in Connecticut ?\nType: City\nQuestion: What state is the Filenes store located in ?\nType: State\nQuestion: Where are the apartments in Saint John , New Brunswick ?\nType: Other location\nQuestion: What 's the last line of Dickens 's A Christmas Carol ?\nType: Description of something\nQuestion: What is a mathematical factor ?\nType: Definition of something\nQuestion: Where can I find correct tabs for Third Eye Blind songs ?\nType: Other location\nQuestion: How do I find if my relatives were on the Trail of Tears ?\nType: Manner of an action\nQuestion: When was Christ born ?\nType: Date\nQuestion: What 's the name of the temple that is located near the capital city of Laos ?\nType: Other location\nQuestion: What was the name of the orca that died of a fungal infection ?\nType: Animal\nQuestion: What 's another name for aspartame ?\nType: Equivalent term\nQuestion: About how many soldiers died in World War II ?\nType: Number of something\nQuestion: How is silk screening done ?\nType: Manner of an action\nQuestion: Who was the tallest U.S. president ?\nType: Individual\nQuestion: What first name was Nipsy Russell given at birth ?\nType: Individual\nQuestion: What comedian created a punch-drunk pugilist named Cauliflower McPugg ?\nType: Individual\nQuestion: What do the 12 days of Christmas mean ?\nType: Definition of something\nQuestion: What does NAFTA stand for ?\nType: Expression abbreviated\nQuestion: What are the short- and long-term effects of underage drinking ?\nType: Description of something\nQuestion: How come a doughnut has a hole in it ?\nType: Reason\nQuestion: What is the capital of Mongolia ?\nType:"}
{"question_id": 11, "category": "longbench_samsum", "reference": ["Jim tracks Finn's package number 45678 which will be delivered to him tomorrow. "], "prompt": "Summarize the dialogue into a few short sentences. The following are some examples.\n\nDialogue: Madeline: How are you doing guys? any news?\r\nHarrison: I'm fine, but super busy at work these days\r\nRobert: I'm ok! you?\r\nMadeline: Not bad, when are we going to see each other again? I miss you guys!\r\nRobert: and where?\r\nHarrison: I live in Berlin now, Robert in Sevilla, are you at least still in Edinburgh?\r\nMadeline: Yes, I think I'll never move from here, too settled \r\nHarrison: Maybe we could meet in some warm place, like Malta?\r\nRobert: or at my place in Spain?\r\nMadeline: It can be a bit difficult for me with the kids. Do you hate Edinburgh so much?\r\nHarrison: It's not about Edinburgh. I hate winter and rain. I want some SUN finally \r\nHarrison: Can't you take Tom and kids to sevilla?\r\nMadeline: Actually I could probably, the problem is that it's always difficult for Tom to give on holiday\r\nMadeline: and I don't work right now, taking care of the kids\r\nHarrison: I can't believe it. Such a feminist once, such a housewife now!\r\nMadeline: I know 😅 but it's rather a coincidence \r\nRobert: What do you mean?\r\nMadeline: Tom was on paternity leave but then I lost the job, so it just happened \r\nMadeline: and as a programmer he earns much better than I ever could \r\nRobert: sure\r\nMadeline: a separate question is how much there is structural inequality in all of this\r\nMadeline: you see! We have to meet and talk, spend some time together. Free me from this housewife's prison\r\nRobert: Talk to Tom first, then we will know what the situation is\r\nMadeline: ok!\nSummary: Harrison lives in Berlin now and he's been busy at work lately. Robert setlled in Sevilla and Madeline in Edinburgh. Madeline lost her job and she is a housewife now. She will talk to her husband, Tom, about going to Sevilla with kids to meet Robert and Harrison.\nDialogue: Hetty: do you know how I can get an app on the ipad from internet\r\nAlfred: through the app store\r\nHetty: no I mean if you are already on a site\r\nAlfred: what site?\r\nHetty: if you are on a website and you want to make it an app\r\nAlfred: oh like a shortcut to a link\r\nHetty: yeah that\r\nAlfred: when you are on the website there is a square with an arrow at the top\r\nHetty: hold on, just opening the website\r\nHetty: where is the square?\r\nAlfred: In the top right somewhere\r\nHetty: where? I can't see it\r\nAlfred: <file_photo>\r\nHetty: oh yeah, got it\r\nAlfred: if you look in there there should be a button called add to home screen or link to homescreen or something\r\nHetty: hold on\r\nHetty: is it in more?\r\nAlfred: No I don't think so, bottom row I think\r\nHetty: oh yeah I found it\r\nAlfred: then give it a name and off you go!\r\nHetty: oh wow, thanks lovely xx\r\nAlfred: no worries mum\r\nAlfred: what site are you on anyway\r\nHetty: in my Hotmail\r\nAlfred: but that has a link already!\r\nHetty: where?\r\nAlfred: the envelope in the bottom row of your ipad!!!!\r\nHetty: oh is that my Hotmail? I didn't know!\r\nAlfred: there you go, learned two things!\r\nHetty: thanks lovely xx\nSummary: Alfred tells his mum, Hetty, how to create a shortcut on an iPad and where to find her e-mail app.\nDialogue: Mary: Where are you?\nTom: in Grenada :P\nPoppy: lucky bastard\nTom: I am!\nPoppy: I'm at the office Mary\nMary: me too :(\nSummary: Tom is in Grenada while Mary and Poppy are at the office. \nDialogue: Darrell: Hey, are you back yet?\r\nHeidi: Hi, yes, I actually came back!!!\r\nDarrell: Cool. How was it?\r\nHeidi: It felt like I woke up from a coma.\r\nDarrell: hehe\r\nHeidi: Yeah, really weird. Have you moved to lublanska yet?\r\nDarrell: Yeah, we moved. It sucks now, it's so far.\r\nHeidi: Yeah, but now we work so close to each other.\r\nDarrell: That's about the only positive. You know it takes me an 1h 20m to get here. That's over 2.5 h for commuting.\r\nHeidi: Maybe you should consider taking your car.\r\nDarrell: Maybe, but it burns so much.\r\nHeidi: Get a new car! The newer cars burn like 5 nowadays.\r\nDarrell: Yeah, I'd love to, but no moollah!\r\nHeidi: I know what you mean. Everything keeps going up except our salaries.\r\nDarrell: Tell me about it. All my fav. restaurants jacked up their prices.\r\nHeidi: Speaking of which, let's have lunch? :)\r\nDarrell: Ok. See you at 12:30\nSummary: Darrell has moved to Lublanska. He spends over 2.5 h commuting, so he should get a new car. Now he and Heidi work close to each other. They'll have a lunch together at 12:30.\nDialogue: Norma: Should we meet tonight for a pint?\nLenny: yes yes yes!\nJackie: sure, would be nice to catch up\nNorma: about 8?\nLenny: I'd prefer 6-6.30 even\nLenny: Marie wants to go out later as well and we can't leave Nicky alone\nNorma: sure, 6.30 is fine for me\nJackie: for me as well\nSummary: Norma, Lenny and Jackie are meeting tonight for a pint around 6.30.\nDialogue: Libbie: mom when you will be at home?\r\nMom: in 20 minutes\r\nLibbie: can you buy bread on your way?\r\nMom: ok\nSummary: Mom will be home soon and she will buy bread on her way.\nDialogue: Amit: How many foamed cabinets are left in the first bay?\r\nChoula: Dunno. Will have to count.\r\nAmit: K. Quickly please.\r\nChoula: Right away.\r\nAmit: The meeting is waiting for the info.\r\nChoula: I'm doing it!\r\nAmit: KK\r\nChoula: 3,432\r\nAmit: That sound wrong.\r\nChoula: You can count them yourself.\r\nAmit: I believe you.\r\nChoula: I can count again to verify. One sec.\r\nAmit: I'll go with 3432.\r\nChoula: Yes. 3,432.\r\nAmit: That won't go over well!\r\nChoula: Oh well!\nSummary: There are 3,432 foamed cabinets left in the first bay according to Choula. Amit is afraid that won't go over well.\nDialogue: Monica: Have you seen that hottie on your left?\r\nMonica: He's been checking you out since we walked into the bus\r\nSarah: Yeah\r\nSarah: I felt his eyes on me\r\nSarah: I got used to such situations\r\nSarah: It's normal cuz I'm hot\r\nSarah: I'm a realist and I'm self-conscious\r\nSarah: I don't even bother paying attention to those horny losers\r\nMonica: Wow, Sarah, I didn't expect you're so prideful!\r\nSarah: I told you, I'm a realist\r\nSarah: Look, I don't care if a boy is handsome, it's actually a common quality\r\nSarah: Of course, it could be a nice bonus but what I value the most is inteligence\r\nMonica: That's very profound. I've never seen this side of you before\r\nMonica: I feel surprised. In a positive way ofc\r\nMonica: Hope you'll find someone with all the qualities you like someday :)\r\nSarah: Thanks Monica, you're a good friend :)\nSummary: Sarah doesn't care about a handsome guy who was looking at her in the bus. She's self-aware and values inteligence more than the looks. Monica is positively surprised and impressed.\nDialogue: Leah: got 1 free ticket for split tonight at 7:45pm, who's in?\r\nZara: me! me!\r\nRose: meeee\r\nRose: noooo\r\nLeah: Zara was first, sorry Rose :<\r\nRose :(\nSummary: Leah will give Zara 1 free ticket for tonight at 7:45 pm. Rose responded too late, so she won't get any.\nDialogue: Chloe: what do you want for dinner?\r\nBella: idk veggie burgers?\r\nBella: btw i'll be late, i need to pick up my order from h&m\r\nChloe: ok\r\nChloe: can you buy two tins of beans on your way home?\r\nBella: black, white or kidney beans?\r\nChloe: i usually use white beans, but it doesn't really matter\r\nBella: ok, i'll buy them. do you need anything else?\r\nChloe: no, thanks! :)\nSummary: Bella and Chloe will have vegetarian burgers for dinner. Bella will pick up her order from H&M and buy the ingredients for the burgers.\nDialogue: Monica: Jessica has a boyfriend?!?! WHAT?\r\nJasmine: yes, she does, finally - I talked to her about it last week\r\nMonica: no way... who is he?!\r\nJasmine: yeah, she is sooo in love , well I don't know much really, he is a fireman and that's it\r\nMonica: can't believe it\r\nJasmine: hahaha yeah, me neither, i don't really talk to her that much anymore to be honest\nSummary: Jessica has a boyfriend finally. He is a fireman. Monica can't believe it, neither Jasmine.\nDialogue: Tyler: wanna go to the basketball game tm?\r\nJames: who's playing?\r\nTyler: UofL and UK\r\nJames: wait really??\r\nTyler: yes haha \r\nJames: thats a super big game how u get tickets??\r\nTyler: I have a friend thats working it and got me tickets\r\nJames: yes yes I wanna go its Saturday right??\r\nTyler: you all ready know hahaha \r\nJames: because I wanted to go and couldn't get tickets \r\nTyler: well now we can go, maybe drive together? parking will be crazy \r\nJames: yeah! we can take my car\r\nTyler: awesome I will sen you a copy of the tickets \r\nJames: ok great!\nSummary: Tyler has tickets for Saturday's UofL and UK basketball game. He got them from a friend who works it. James will go with Tyler by car. Tyler will send him a copy of the tickets.\nDialogue: Robert: Hey, what are you up to tonight?\r\nSandy: I was supposed to meet up with Janet, but she cancelled on me. U?\r\nRobert: I was thinking about going out myself. Wanna do something fun?\r\nSandy: Sure. Anything particular in mind?\r\nRobert: Not really. You know of anything going on tonight?\r\nSandy: Well, there's this exhibition of modern art...\r\nRobert: Sorry, not a fan. Don't really get modern art. Don't know why. \r\nSandy: Really? I love modern art.\r\nRobert: How come? You don't seem the type...\r\nSandy: And what \"type\" likes modern art?\r\nRobert: You know, the geeky type...\r\nSandy: So, I'm a geek?\r\nRobert: Still, better than a nerd ;)\r\nSandy: LOL. Probably. \r\nRobert: Anything else? Maybe the movies?\r\nSandy: Haven't been to the cinema in a while. Anything good on at the moment?\r\nRobert: I'll check. Brb.\r\nSandy: Ok.\r\nRobert: Sorry to keep you waiting. There are three to choose from: horror, romantic comedy, documentary.\r\nSandy: Well, I'm not a fan of horrors... They scare me to death...\r\nRobert: That's the point, isn't it? ;)\r\nSandy: Maybe. Still...\r\nRobert: Okay then. Not the horror. The documentary? Building dams in Afghanistan. Sounds fun?\r\nSandy: More fun than the vampires, blood, scary creatures...\r\nRobert: What time do you want to go? 6:30? 7:30? 8:30?\r\nSandy: 7:30 is fine. \r\nRobert: So 7:00 at the cinema?\r\nSandy: Let's make it 7:15. \r\nRobert: Sure. See you there.\r\nSandy: Bye. \nSummary: Robert and Sandy are planning to go out together, but Robert doesn't like modern art, although Sandy loves it. They are considering to go to the movies. Sandy doesn't like horrors. They decide to go to see a documentary about Afghanistan at 7.30. They will meet at 7.15 at the cinema.\r\nt \nDialogue: Anne: Mum's seeing someone :/\r\nYvonne: I had my suspicions\r\nAnne: And you didn't tell me?!\r\nYvonne: Why wouldn't I? it's her life, if she didn't tell you, maybe she wasn't ready, it's her choice\r\nAnne: Ok, but she's still my mother. I think she should have told us\r\nYvonne: Have you told her about your every single boyfriend?\r\nAnne: Come on! It's not the same, she's our mother for fuck's sake!\r\nYvonne: And still a person. I don't get why you're so upset about this\r\nAnne: It's been only four months since dad left her, isn't it a bit early for going out with other people?\r\nYvonne: you really think that? Dad left her for another woman\r\nAnne: So?\r\nYvonne: So his own marriage didn’t stop him from meeting other women, I’m proud of her, she deserves to be happy\r\nAnne: Of course she does, I just think it’s too early\r\nYvonne: You’re just upset she didn’t tell you and that she has her secrets\r\nAnne: Don’t be ridiculous, I worry about her\r\nAnne: At this stage she’s too vulnerable\r\nYvonne: She’s an adult, I think she can handle her love life perfectly fine ;)\nSummary: Mum's seeing someone and she didn't tell Yvonne or Anne. \nDialogue: Tony: Do you have any recommendation for us? What we should see in NYC?\r\nSally: the regular stuff: MOMA, Guggenheim, empire State Buiding etc.\r\nTony: but maybe anything not so well known?\r\nSally: go to Ellis Island\r\nSally: they have an amazing museum about immigration\r\nTony: that sounds good!\r\nSally: you'll like it\r\nTony: thanks!\r\nSally: you're welcome\nSummary: Tony gives recommendations on what Sally should see in NYC.\nDialogue: Tina: <file_photo>\r\nTina: Dear Ella and Jamie, we wish you a wonderful Christmas - wherever you are going to celebrate it!\r\nElla: <file_photo>\r\nElla: Thank you my dear! From our Havana abode we are wishing you a lovely time with your family at Christmas!\r\nElla: Have you got some Xmas tree? Here in Cuba nobody celebrates Christmas, it seems. But a holiday flat opposite ours has some sort of Xmas decoration.\r\nElla: <file_photo>\r\nTina: <file_photo>\r\nTina: My little Christmas tree, bought on the side of the road, made by Africans.\r\nElla: I think I like this tree very much!\r\nTina: :)) Bill is rather skeptical and says that its only good feature is that it will shed no needles. Will you be celebrating?\r\nElla: Not really. In fact we never do, apart from a few jokes about a Xmas dinner. In a country like this it is easy to forget it is Christmastide. We really don't care. I would still do something at home but don't bother while travelling. And you?\r\nTina: My daughter Laura and her hubby are coming down from Jo'burg, so I guess we'll have a grand Christmas meal. Bill loves preparing all these English things and Laura is quite mad about them too. I'll bake a proper south African sugarcane cake.\r\nElla: Never tried this one!\r\nTina: It's really a joke, more of a traditional name than anything. And too sweet to be enjoyed. Just a Xmas treat. Did you have traditional dishes in Poland, the ones your mother used to prepare for Christmas?\r\nElla: Oh yes, plenty! But I liked only few of them. I wish I could taste them again though. :( weep,weep..\r\nTina: Good old days of childhood... When I think about Howick in the days of my childhood and how it has changed for worse, it makes me cringe. Good that my mother didn't live long enough to experience all this deterioration. No good thoughts for Xmas.\r\nElla: But good to remember our loved ones!\r\nTina: Right you are. Then once more: Happy Christmas to you both!\r\nElla: And a happy Christmas to you, dear Tina and Bill! With kind regards to your family!\r\nTina: Thank you dear.\nSummary: Tina and Ella wish each other a happy Christmas. Ella and Jamie are spending Christmas in their Havana abode and they do not plan to celebrate. Tina bought a Christmas tree. Tina's daughter Laura and her husband are coming from Johannesburg. Tina and Bill will prepare a grand Christmas meal.\nDialogue: Ronnie: hey, I'm in Tesco and look\r\nRonnie: they've got discount on your dad's favourite coffee\r\nRonnie: <file_photo>\r\nGeorgia: wow, that is a really good price!\r\nGeorgia: pls buy 5 packs\r\nGeorgia: I remember that granny likes this coffee too\r\nRonnie: okie dokie\r\nRonnie: do you want anything else?\r\nGeorgia: buy some chocolate cookies :D\r\nRonnie: <file_gif>\nSummary: Ronnie is in Tesco and there's a discount for Georgia's dad's favourite coffee. He will get 5 packs for her, and some chocolate cookies. \nDialogue: Pete: hey\r\nLaura: hello \r\nPete: how are you? \r\nLaura: fine thanks \r\nPete: will we meet today? \r\nLaura: sure \r\nLaura: :) \nSummary: Laura and Pete are going to meet today. \nDialogue: Felicity: <file_photo> combines impact and effort\r\nJoe: I know it... unfort it doesnt cover my problem completely\r\nFelicity: what do you mena?\r\nJoe: I used this chart, but it doesn't include shortage of time unfort, and this is the main thing\r\nFelicity: uuu I get it :P\nSummary: Felicity sent a photo to Joe. He is not satisfied with it.\nDialogue: Martha: I just got accepted!!!\r\nJay: Whaaaat!!! Congratulations! This is amazing!\r\nMartha: <file_photo>\r\nMartha: Here's my unconditional offer :)\r\nJay: So proud of you <3 Are then ready to go?\r\nMartha: I just booked my tickets, I'm flying on 12 September\r\nJay: That's in less than a month!\r\nMartha: hahaha I know, time flies\r\nMartha: I'm worried though because I still have no place to stay\r\nJay: Hm, are you looking for a flat, a room or student halls?\r\nMartha: Honestly? I'd take anything at this stage\r\nJay: Have you checked if the university has a student accommodation programme?\r\nMartha: Yes, they do, but it's only for full time students ;/ it's ridiculous, because I applied for the part time as I can't afford to just study, therefore I need to pay more for my accommodation. Fuck logic\r\nJay: Hah, seems like that, doesn't make any sense to me either\r\nMartha: So I'm not entitled to any accommodation programme and I'm probably at the end of the list to get a room at student halls\r\nJay: Maybe a private one? How expensive are the flats?\r\nMartha: Crazy expensive... I most probably can't afford it, but maybe it'll be possible to share with someone\r\nJay: I may ask around, I think I have some friends there, I can ask around, maybe they'll have a spare room\r\nMartha: Could you that? I'd need to stay somewhere until I can get my head around the city, uni, people...\r\nMartha: Oh my, I am excited, but also scared as hell...\r\nJay: It'll be fun, you'll see!\r\nMartha: It definitely would be fun if I have a place to stay\r\nJay: Don't be so overdramatic, it'll work out :D\nSummary: Martha got accepted at university as part time student. She's just booked a ticket for 12th September. She doesn't have a place to stay. Flats are expensive and she doesn't have right to any accommodation program. Jay will ask around if his friends have a spare room.\nDialogue: Des: I'm hungry\r\nWanda: already?\r\nDes: <file_gif>\r\nWanda: ok, ok\r\nWanda: in a half?\r\nDes: yes!\r\nWanda: see u :)\nSummary: Des is hungry. He and Wanda are going to meet in half an hour.\nDialogue: Lucas: Howard and Nancy are coming to visit me on Saturday\r\nLucas: how about you John? Wanna join us?\r\nJohn: this Saturday?\r\nLucas: that's right, in the afternoon.\r\nJohn: damnit. I want but I can't...\r\nLucas: Come on, why?\r\nJohn: this Saturday I'm working until 5 p.m. and then I have an appointment at the dentist's\r\nLucas: oh my... looks like a busy and unpleasant time...\r\nLucas: I'm sorry for you, John\r\nJohn: there certainly are things in life you cannot skip\r\nJohn: but thanks a lot Luc, I appreciate that you invited me anyway :)\r\nLucas: no problem, you're my friend, bro :)\r\nLucas: hope you won't suffer too much at the dentist's\r\nJohn: thanks!\r\nJohn: don't worry, he's a real professional, I trust him\r\nLucas: good for you\r\nJohn: yeah. Have fun on Saturday and say hello for me, please. Bye\r\nLucas: Thanks, I will! Bye\nSummary: Howard and Nancy are visiting Lucas on Saturday, but John can't join because of work.\nDialogue: Glenda: Have you seen weather forecast ?\r\nMartin: Yes, it is going to be warm and sunny\r\nGlenda: Damn, why did I already pack all my summer stuff ??\nSummary: According to the forecast, the weather is going to be warm and sunny.\nDialogue: Peg: i got a cold :(\r\nTyson: typical this time of year \r\nPeg: here's the voice of a sympathetic man, thx Ty!\r\nRidge: u take anything?\r\nPeg: some pills. aspirin and stuff\r\nLandry: i feel shit too. any good ideas?\r\nLandry: i mean home recipes\r\nNettie: i know. hot water, cinamon, lemon, honey\r\nNettie: plenty of all, drink hot\r\nNettie: go to bed straight after. sweats a lot\r\nLandry: sounds better than garlic my mum tortuted me with all life\r\nPeg: ill try this one out too\r\nTyson: i know 1 too, but pretty hardcore\r\nPeg: ok\r\nTyson: lemon and honey are the same. only 190 proof alc\r\nLandry: that is srsly cool\nSummary: Peg and Landry are sick. They receive pieces of advice how to get better.\nDialogue: Mark: We'll be late 1 hour, sorry guys, you can start without us\r\nPaul: No, we will wait with the dinner\r\nSteven: Take your time, we're enjoying a nice chat\r\nMark: ok, thanks a lot\nSummary: Mark will be an hour late for the dinner.\n\n\nDialogue: Jim: Hello, welcome to the store, how can I help you\r\nFinn: Hello could you help me track my shippment?\r\nJim: yes, can you please tell me your order number\r\nFinn: It's 45678\r\nJim: Thank you, from what I can see your package has left the warehouse and will be delivered to you tommorrow\nSummary: "}
{"question_id": 12, "category": "longbench_trec", "reference": ["Definition of something"], "prompt": "Please determine the type of the question below. Here are some examples of questions.\n\nQuestion: Why are sometimes your hands cold , but the rest of you isn 't ?\nType: Reason\nQuestion: What snack food has ridges ?\nType: Food\nQuestion: Who was the first coach of the Cleveland Browns ?\nType: Individual\nQuestion: What arch can you see from the Place de la Concorde ?\nType: Other location\nQuestion: Who created Harry Lime ?\nType: Individual\nQuestion: What Caribbean cult did Marcus Garvey originate ?\nType: Religion\nQuestion: When did Iraqi troops invade Kuwait ?\nType: Date\nQuestion: Whose cover is that of an employee of Universal Import and Export ?\nType: Individual\nQuestion: What was the name of Betty Boop 's dog ?\nType: Animal\nQuestion: What is the deepest area of the Arctic Ocean ?\nType: Other location\nQuestion: Who 's the founder and editor of The National Review ?\nType: Individual\nQuestion: Who was Tiny Tim 's father ?\nType: Individual\nQuestion: What are the historical trials following World War II called ?\nType: Event\nQuestion: What is the claim to fame of Agra , India ?\nType: Reason\nQuestion: What is white chocolate ?\nType: Definition of something\nQuestion: What 's the farthest planet from the sun ?\nType: Other location\nQuestion: What is a fear of everything ?\nType: Disease and medicine\nQuestion: Whose old London come-on was : `` Buy my sweet lavender '' ?\nType: Individual\nQuestion: The major league baseball team in Pittsburgh is called what ?\nType: Group or organization of person\nQuestion: How do microwaves work ?\nType: Manner of an action\nQuestion: What is the name given to a group of geese ?\nType: Animal\nQuestion: What is gymnophobia ?\nType: Definition of something\nQuestion: What is the difference between khaki and chino ?\nType: Description of something\nQuestion: Who was the lawyer for Randy Craft ?\nType: Individual\nQuestion: When was the San Francisco fire ?\nType: Date\nQuestion: What year were the Olympic Games played in where Nadia Comaneci became popular ?\nType: Date\nQuestion: What country has the most coastline ?\nType: Country\nQuestion: What is goulash ?\nType: Definition of something\nQuestion: What was the Vietnam War ?\nType: Definition of something\nQuestion: Who wrote the lyrics to Porgy and Bess ?\nType: Individual\nQuestion: What are all the southern states of the U.S. ?\nType: State\nQuestion: Who came up with the name , El Nino ?\nType: Individual\nQuestion: What man-made waterways is 1.76 miles long ?\nType: Other location\nQuestion: What is the former name of Zimbabwe ?\nType: Equivalent term\nQuestion: What is the history of yo-yos ?\nType: Description of something\nQuestion: What state was named the Green Mountain state ?\nType: State\nQuestion: How do ants have sex ?\nType: Manner of an action\nQuestion: When did the Dow first reach ?\nType: Date\nQuestion: What is the high pitched sound that you hear in your ear every now and then , but then it goes away , after a while ?\nType: Other entity\nQuestion: When did communist control end in Hungary ?\nType: Date\nQuestion: How can I find a list of celebrities ' real names ?\nType: Manner of an action\nQuestion: What did the pyramid-builders of Egypt mainly eat ?\nType: Food\nQuestion: How does Belle describe her life in Beauty and the Beast ?\nType: Manner of an action\nQuestion: When reading classified ads , what does EENTY : other stand for ?\nType: Expression abbreviated\nQuestion: When was Florida admitted into the Union ?\nType: Date\nQuestion: How many Israeli athletes were killed at the Munich Olympics ?\nType: Number of something\nQuestion: What detective lives on Punchbowl Hill and has 11 children ?\nType: Individual\nQuestion: What state is the Filenes store located in ?\nType: State\nQuestion: What are the cookies in Internet ?\nType: Definition of something\nQuestion: What English word contains the most letters ?\nType: Word with a special property\nQuestion: What is Larry King 's occupation ?\nType: Title of a person\nQuestion: Name a French fascist party .\nType: Group or organization of person\nQuestion: What American poet wrote : `` Good fences make good neighbors '' ?\nType: Individual\nQuestion: Where are the busiest Amtrak rail stations in the U.S. ?\nType: Other location\nQuestion: How many people die of tuberculosis yearly ?\nType: Number of something\nQuestion: What was the worst hurricane ?\nType: Event\nQuestion: What Caribbean island is northeast of Trinidad ?\nType: Other location\nQuestion: Who was Jean Nicolet ?\nType: Description of a person\nQuestion: What do the 12 days of Christmas mean ?\nType: Definition of something\nQuestion: What caused Harry Houdini 's death ?\nType: Reason\nQuestion: What building appropriately enough is depicted on the back of the 1-dollar bill ?\nType: Other location\nQuestion: How many logarithmic scales are there on a slide rule ?\nType: Number of something\nQuestion: What is the origin of the word , JJ .\nType: Description of something\nQuestion: What is the average hours per months spent online by AOL users ?\nType: Number of something\nQuestion: How does a copier work ?\nType: Manner of an action\nQuestion: How many calories are there in a glass of water ?\nType: Number of something\nQuestion: What color is Chablis ?\nType: Color\nQuestion: Where is Ayer 's rock ?\nType: Other location\nQuestion: What corporation does Madonna advertise for ?\nType: Group or organization of person\nQuestion: Where is the bridge over the river Kwai ?\nType: Other location\nQuestion: What cigarette is `` a whole new world '' ?\nType: Other entity\nQuestion: When did the Chernobyl nuclear accident occur ?\nType: Date\nQuestion: What is the first book of the Old Testament ?\nType: Invention, book and other creative piece\nQuestion: What does `` Philebus-like '' mean ?\nType: Definition of something\nQuestion: When did Rococo painting and architecture flourish ?\nType: Date\nQuestion: What is the difference between fatalism and determinism ?\nType: Description of something\nQuestion: Where is Poe 's birthplace ?\nType: Other location\nQuestion: What U.S. state has the lowest highest elevation at 6 feet ?\nType: State\nQuestion: How do you calculate the change in enthalpy of a chemical reaction ?\nType: Manner of an action\nQuestion: What are the `` Star Wars '' satellites ?\nType: Definition of something\nQuestion: What country was General Douglas McArthur in when he was recalled by President Truman ?\nType: Country\nQuestion: How is Easter Sunday 's date determined ?\nType: Manner of an action\nQuestion: What city is the setting for Puccini 's opera La Boheme ?\nType: City\nQuestion: When was Dick Clark born ?\nType: Date\nQuestion: Where can one find information on religion and health , the brain and nutrition ?\nType: Other location\nQuestion: What comedian hit the TV screen in 1951 with the NBC afternoon show Time for Ernie ?\nType: Individual\nQuestion: How much of the earth 's surface is permanently frozen ?\nType: Number of something\nQuestion: What English playwright penned : `` Where the bee sucks , so shall I '' ?\nType: Individual\nQuestion: What song put James Taylor in the limelight ?\nType: Invention, book and other creative piece\nQuestion: What new middle school was built in Philadelphia , Pennsylvania last year ?\nType: Group or organization of person\nQuestion: What southwestern state is dubbed The Silver State ?\nType: State\nQuestion: What is Betsy Ross famous for ?\nType: Reason\nQuestion: What is California 's capital ?\nType: City\nQuestion: What Asian leader was known as The Little Brown Saint ?\nType: Individual\nQuestion: Who led the Normans to victory in the Battle of Hastings ?\nType: Individual\nQuestion: What type of exercise burns the most calories ?\nType: Sport\nQuestion: What was the name of the Crimean meeting of Roosevelt , Churchill , and Stalin ?\nType: Event\nQuestion: What is dry ice ?\nType: Definition of something\nQuestion: How much money was the minimum wage in 1991 ?\nType: Price\nQuestion: On which Hawaiian island is Pearl Harbor ?\nType: Other location\nQuestion: Who made the first surfboard ?\nType: Individual\nQuestion: Where did the Maya people live ?\nType: Other location\nQuestion: How do you make a paintball ?\nType: Manner of an action\nQuestion: What then-derogatory term was applied to the painters Monet , Sisley , Pissarro , Renoir and Degas ?\nType: Equivalent term\nQuestion: What lake in Scotland is said to hold one or more monsters ?\nType: Other location\nQuestion: What is the lens behind the iris in the eye called ?\nType: Equivalent term\nQuestion: Who leads the star ship Enterprise in Star Trek ?\nType: Individual\nQuestion: Why do we have to go to school ?\nType: Reason\nQuestion: What is a term for behavior , appearance , or expression that violates the accepted standards of sexual morality ?\nType: Equivalent term\nQuestion: Who is the President of Pergament ?\nType: Individual\nQuestion: What religion has the most members ?\nType: Religion\nQuestion: What country would you visit to ski in the Dolomites ?\nType: Country\nQuestion: What does VCR stand for ?\nType: Expression abbreviated\nQuestion: Where can I buy a good snowboard for less than $200 ?\nType: Other location\nQuestion: Where can I buy movies on videotape online ?\nType: Other location\nQuestion: Who was the 16th President of the United States ?\nType: Individual\nQuestion: What was the education system in the 1960 's ?\nType: Other entity\nQuestion: Why are peanut butter cookies topped with crisscrosses ?\nType: Reason\nQuestion: Name the designer of the shoe that spawned millions of plastic imitations , known as ` jellies ' .\nType: Individual\nQuestion: What are the rules to `` snow golf '' ?\nType: Description of something\nQuestion: What were the names of the three ships used by Columbus ?\nType: Vehicle\nQuestion: What should you do for an ankle sprain ?\nType: Description of something\nQuestion: CNN began broadcasting in what year ?\nType: Date\nQuestion: When is a woman most fertile ?\nType: Date\nQuestion: Whose special bear 's creator was born on January 18 , 1779 ?\nType: Individual\nQuestion: What is a neurosurgeon ?\nType: Definition of something\nQuestion: What are the Baltic States ?\nType: Definition of something\nQuestion: Who used AuH2O as an election slogan ?\nType: Individual\nQuestion: In what book can I find the story of Aladdin ?\nType: Invention, book and other creative piece\nQuestion: What country is home to Heineken beer ?\nType: Country\nQuestion: What are the various ways in which one can measure IT User Satisfaction Level ?\nType: Techniques and method\nQuestion: What is software piracy ?\nType: Definition of something\nQuestion: What British prime minister and U.S. president were seventh cousins once-removed ?\nType: Individual\nQuestion: Name a Gaelic language .\nType: Language\nQuestion: What is the best way to overcome a fear ?\nType: Techniques and method\nQuestion: What soft drink would provide me with the biggest intake of caffeine ?\nType: Food\nQuestion: Where in the United States do people live the longest ?\nType: Other location\nQuestion: On which dates does the running of the bulls occur in Pamplona , Spain ?\nType: Date\nQuestion: What is the name of the rare neurological disease with symptoms such as : involuntary movements , tics , swearing , and incoherent vocalizations , grunts , shouts , etc. ?\nType: Disease and medicine\nQuestion: What is an urban legend ?\nType: Definition of something\nQuestion: What is a multiplexer ?\nType: Definition of something\nQuestion: What is Boston Kreme ?\nType: Definition of something\nQuestion: What Russian master spy lived in the U.S. under the name Emil Goldfus ?\nType: Individual\nQuestion: What 's a perfect score in a gymnastics exercise ?\nType: Other number\nQuestion: What cathedral was Thomas Becket murdered in ?\nType: Other location\nQuestion: Why did Egyptians shave their eyebrows ?\nType: Reason\nQuestion: What does the name Melissa mean ?\nType: Definition of something\nQuestion: What year did Montana become a state ?\nType: Date\nQuestion: What card game can feature dealer 's choice ?\nType: Sport\nQuestion: What are the different approaches of systems analysis ?\nType: Techniques and method\nQuestion: What does the double-O indicate in 007 ?\nType: Definition of something\nQuestion: What color is the lipstick on Boy George 's wax lips at London 's Madame Tussaud 's ?\nType: Color\nQuestion: What anesthetic did Queen Victoria allow to be used for the birth of her seventh child , in 1853 ?\nType: Disease and medicine\nQuestion: What do river otters eat ?\nType: Food\nQuestion: How many miles is it from NY to Austria ?\nType: Number of something\nQuestion: What is a fear of odors , body , ?\nType: Disease and medicine\nQuestion: How is energy created ?\nType: Manner of an action\nQuestion: What causes panic attacks ?\nType: Reason\nQuestion: How can I get started in writing for television ?\nType: Manner of an action\nQuestion: Where 's the GUM department store ?\nType: Other location\nQuestion: Who is the voice of Miss Piggy ?\nType: Individual\nQuestion: What kind of science is cosmology ?\nType: Other entity\nQuestion: Who patented the first phonograph ?\nType: Individual\nQuestion: Who was the 15th century fire-and-brimstone monk who gained control of Florence but ended burnt at the stake ?\nType: Individual\nQuestion: What is the definition of cecum ?\nType: Definition of something\nQuestion: Which city has the oldest relationship as a sisterðcity with Los Angeles ?\nType: City\nQuestion: Who wrote `` The Pit and the Pendulum '' ?\nType: Individual\nQuestion: What country is the world 's largest importer of cognac ?\nType: Country\nQuestion: What is a technique popularly used to detect birth defects ?\nType: Techniques and method\nQuestion: What toy can you make sleep ?\nType: Product\nQuestion: Stuart Hamblen is considered to be the first singing cowboy of what ?\nType: Invention, book and other creative piece\nQuestion: What city is wiener schnitzel named for ?\nType: City\nQuestion: What Southern California town is named after a character made famous by Edgar Rice Burroughs ?\nType: City\nQuestion: How much stronger is the new vitreous carbon material invented by the Tokyo Institute of Technology compared with the material made from cellulose ?\nType: Number of something\nQuestion: What former African leader held his country 's boxing title for nine years ?\nType: Individual\nQuestion: What is a bone marrow transplant ?\nType: Definition of something\nQuestion: What are the world 's three largest oceans , in order of size ?\nType: Other location\nQuestion: What is a virtual IP address ?\nType: Definition of something\nQuestion: What New Hampshire hamlet rises early to vote first in U.S. presidential elections ?\nType: City\nQuestion: What were the first words spoken on a film sound track ?\nType: Description of something\nQuestion: Who is Stein Eriksen ?\nType: Description of a person\nQuestion: Why is the universe flat , if it started by an explosion , shouldn 't it be a sphere ?\nType: Reason\nQuestion: Where can I buy a pony on the Big Island for my daughter ?\nType: Other location\nQuestion: How do you match a name to a social security number ?\nType: Manner of an action\nQuestion: What is the only modern language that capitalizes its singular first-person pronoun ?\nType: Language\nQuestion: Who accompanied Space Ghost on his missions ?\nType: Individual\nQuestion: What is the celtic symbol for `` life '' ?\nType: Symbols and sign\nQuestion: What is the name of the American who was captured when his plane went down over Syrian-held Lebanon ?\nType: Individual\nQuestion: What is Judy Garland 's date of birth ?\nType: Date\nQuestion: What do you call the feeling of having experienced something before ?\nType: Equivalent term\nQuestion: How do I know if I 'm jealous of someone ?\nType: Manner of an action\nQuestion: Which police department made the all-time biggest cocaine bust in Ventura County ?\nType: Group or organization of person\nQuestion: What was the name of the lawyer who represented Randy Steven Craft ?\nType: Individual\nQuestion: What state on the Gulf of Mexico has its lowest point five feet below sea level ?\nType: State\nQuestion: What is troilism ?\nType: Definition of something\nQuestion: What is the population of Kansas ?\nType: Other number\nQuestion: What was lost and regained by poet John Milton ?\nType: Other entity\nQuestion: How often are quadruplets born ?\nType: Other number\nQuestion: Who was the Charlie perfume woman ?\nType: Individual\nQuestion: What woman has carried the most multiple births , twins , triplets , etc. , ?\nType: Individual\nQuestion: What is a nematode ?\nType: Definition of something\nQuestion: When was Franklin D. Roosevelt stricken with polio ?\nType: Date\nQuestion: What are the names of Richard Nixon 's two daughters ?\nType: Individual\nQuestion: What country in 1998 had the most suicides regardless of population size ?\nType: Country\nQuestion: Who was the king who was forced to agree to the Magna Carta ?\nType: Individual\nQuestion: Who invented Make-up ?\nType: Individual\nQuestion: What are the major differences in the Catholic and Methodist religions ?\nType: Description of something\nQuestion: What U.S. city is known as The Rubber Capital of the World ?\nType: City\nQuestion: What two Japanese cities are spelled with the letters K , O , O , T and Y ?\nType: City\nQuestion: What chemicals are used in lethal injection ?\nType: Disease and medicine\nQuestion: What does a philatelist collect ?\nType: Other entity\nQuestion: How do plants make food ?\nType: Manner of an action\nQuestion: What is the acronym for the rating system for air conditioner efficiency ?\nType: Abbreviation\nQuestion: What do I need to do to take my dog with me to live in Dominica , West Indies for a year ?\nType: Description of something\nQuestion: What is a fuel cell ?\nType:"}
{"question_id": 13, "category": "longbench_lcc", "reference": [" super( source, new Predicate<PatternMatch>()"], "prompt": "Please complete the code given below. \n/**\n * Copyright (c) 2002-2012 \"Neo Technology,\"\n * Network Engine for Objects in Lund AB [http://neotechnology.com]\n *\n * This file is part of Neo4j.\n *\n * Neo4j is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage org.neo4j.graphmatching;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphmatching.filter.AbstractFilterExpression;\nimport org.neo4j.graphmatching.filter.FilterBinaryNode;\nimport org.neo4j.graphmatching.filter.FilterExpression;\nimport org.neo4j.graphmatching.filter.FilterValueGetter;\nimport org.neo4j.helpers.Predicate;\nimport org.neo4j.helpers.collection.FilteringIterable;\n/**\n * The PatternMatcher is the engine that performs the matching of a graph\n * pattern with the actual graph.\n */\n@Deprecated\npublic class PatternMatcher\n{\n\tprivate static PatternMatcher matcher = new PatternMatcher();\n\tprivate PatternMatcher()\n\t{\n\t}\n /**\n * Get the sole instance of the {@link PatternMatcher}.\n *\n * @return the instance of {@link PatternMatcher}.\n */\n\tpublic static PatternMatcher getMatcher()\n\t{\n\t\treturn matcher;\n\t}\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param startNode the {@link Node} to start matching at.\n * @return all matching instances of the pattern.\n */\n public Iterable<PatternMatch> match( PatternNode start,\n Node startNode )\n {\n return match( start, startNode, null );\n }\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param startNode the {@link Node} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @return all matching instances of the pattern.\n */\n\tpublic Iterable<PatternMatch> match( PatternNode start,\n\t\tNode startNode, Map<String, PatternNode> objectVariables )\n\t{\n\t\treturn match( start, startNode, objectVariables,\n\t\t ( Collection<PatternNode> ) null );\n\t}\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @param optional nodes that form sub-patterns connected to this pattern.\n * @return all matching instances of the pattern.\n */\n public Iterable<PatternMatch> match( PatternNode start,\n Map<String, PatternNode> objectVariables,\n PatternNode... optional )\n {\n return match( start, objectVariables,\n Arrays.asList( optional ) );\n }\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @param optional nodes that form sub-patterns connected to this pattern.\n * @return all matching instances of the pattern.\n */\n\tpublic Iterable<PatternMatch> match( PatternNode start,\n\t Map<String, PatternNode> objectVariables,\n\t Collection<PatternNode> optional )\n {\n\t Node startNode = start.getAssociation();\n if ( startNode == null )\n {\n throw new IllegalStateException(\n \"Associating node for start pattern node is null\" );\n }\n\t return match( start, startNode, objectVariables, optional );\n }\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param startNode the {@link Node} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @param optional nodes that form sub-patterns connected to this pattern.\n * @return all matching instances of the pattern.\n */\n\tpublic Iterable<PatternMatch> match( PatternNode start,\n\t\tNode startNode, Map<String, PatternNode> objectVariables,\n\t\tCollection<PatternNode> optional )\n\t{\n Node currentStartNode = start.getAssociation();\n if ( currentStartNode != null && !currentStartNode.equals( startNode ) )\n {\n throw new IllegalStateException(\n \"Start patter node already has associated \" +\n currentStartNode + \", can not start with \" + startNode );\n }\n\t Iterable<PatternMatch> result = null;\n\t\tif ( optional == null || optional.size() < 1 )\n\t\t{\n\t\t\tresult = new PatternFinder( this, start, startNode );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresult = new PatternFinder( this, start, startNode, false,\n\t\t\t optional );\n\t\t}\n\t\tif ( objectVariables != null )\n\t\t{\n \t\t// Uses the FILTER expressions\n \t\tresult = new FilteredPatternFinder( result, objectVariables );\n\t\t}\n\t\treturn result;\n\t}\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param startNode the {@link Node} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @param optional nodes that form sub-patterns connected to this pattern.\n * @return all matching instances of the pattern.\n */\n\tpublic Iterable<PatternMatch> match( PatternNode start,\n\t\tNode startNode, Map<String, PatternNode> objectVariables,\n\t\tPatternNode... optional )\n\t{\n\t\treturn match( start, startNode, objectVariables,\n\t\t Arrays.asList( optional ) );\n\t}\n\tprivate static class SimpleRegexValueGetter implements FilterValueGetter\n\t{\n\t private PatternMatch match;\n\t private Map<String, PatternNode> labelToNode =\n\t new HashMap<String, PatternNode>();\n\t private Map<String, String> labelToProperty =\n\t new HashMap<String, String>();\n\t SimpleRegexValueGetter( Map<String, PatternNode> objectVariables,\n\t PatternMatch match, FilterExpression[] expressions )\n\t {\n this.match = match;\n for ( FilterExpression expression : expressions )\n {\n mapFromExpression( expression );\n }\n this.labelToNode = objectVariables;\n\t }\n\t private void mapFromExpression( FilterExpression expression )\n\t {\n\t if ( expression instanceof FilterBinaryNode )\n\t {\n\t FilterBinaryNode node = ( FilterBinaryNode ) expression;\n\t mapFromExpression( node.getLeftExpression() );\n\t mapFromExpression( node.getRightExpression() );\n\t }\n\t else\n\t {\n\t AbstractFilterExpression pattern =\n\t ( AbstractFilterExpression ) expression;\n\t labelToProperty.put( pattern.getLabel(),\n\t pattern.getProperty() );\n\t }\n\t }\n public String[] getValues( String label )\n {\n PatternNode pNode = labelToNode.get( label );\n if ( pNode == null )\n {\n throw new RuntimeException( \"No node for label '\" + label +\n \"'\" );\n }\n Node node = this.match.getNodeFor( pNode );\n String propertyKey = labelToProperty.get( label );\n if ( propertyKey == null )\n {\n throw new RuntimeException( \"No property key for label '\" +\n label + \"'\" );\n }\n Object rawValue = node.getProperty( propertyKey, null );\n if ( rawValue == null )\n {\n return new String[ 0 ];\n }\n Collection<Object> values =\n ArrayPropertyUtil.propertyValueToCollection( rawValue );\n String[] result = new String[ values.size() ];\n int counter = 0;\n for ( Object value : values )\n {\n result[ counter++ ] = ( String ) value;\n }\n return result;\n }\n\t}\n\tprivate static class FilteredPatternFinder\n\t extends FilteringIterable<PatternMatch>\n\t{\n public FilteredPatternFinder( Iterable<PatternMatch> source,\n final Map<String, PatternNode> objectVariables )\n {\nNext line of code:\n"}
{"question_id": 14, "category": "longbench_lcc", "reference": ["\t\t\tfor (int i = 1; i <= MAX_LOG; ++i) {"], "prompt": "Please complete the code given below. \n/* NFC Reader is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\n(at your option) any later version.\nNFC Reader is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\nYou should have received a copy of the GNU General Public License\nalong with Wget. If not, see <http://www.gnu.org/licenses/>.\nAdditional permission under GNU GPL version 3 section 7 */\npackage cache.wind.nfc.nfc.reader.pboc;\nimport android.nfc.tech.IsoDep;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport cache.wind.nfc.SPEC;\nimport cache.wind.nfc.nfc.Util;\nimport cache.wind.nfc.nfc.bean.Application;\nimport cache.wind.nfc.nfc.bean.Card;\nimport cache.wind.nfc.nfc.tech.Iso7816;\n@SuppressWarnings(\"unchecked\")\npublic abstract class StandardPboc {\n\tprivate static Class<?>[][] readers = {\n\t\t\t{ BeijingMunicipal.class, WuhanTong.class, CityUnion.class, TUnion.class,\n\t\t\t\t\tShenzhenTong.class, }, { StandardECash.class, } };\n\tpublic static void readCard(IsoDep tech, Card card) throws InstantiationException,\n\t\t\tIllegalAccessException, IOException {\n\t\tfinal Iso7816.StdTag tag = new Iso7816.StdTag(tech);\n\t\ttag.connect();\n\t\tfor (final Class<?> g[] : readers) {\n\t\t\tHINT hint = HINT.RESETANDGONEXT;\n\t\t\tfor (final Class<?> r : g) {\n\t\t\t\tfinal StandardPboc reader = (StandardPboc) r.newInstance();\n\t\t\t\tswitch (hint) {\n\t\t\t\tcase RESETANDGONEXT:\n\t\t\t\t\tif (!reader.resetTag(tag))\n\t\t\t\t\t\tcontinue;\n\t\t\t\tcase GONEXT:\n\t\t\t\t\thint = reader.readCard(tag, card);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (hint == HINT.STOP)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\ttag.close();\n\t}\n\tprotected boolean resetTag(Iso7816.StdTag tag) throws IOException {\n\t\treturn tag.selectByID(DFI_MF).isOkey() || tag.selectByName(DFN_PSE).isOkey();\n\t}\n\tprotected enum HINT {\n\t\tSTOP, GONEXT, RESETANDGONEXT,\n\t}\n\tprotected final static byte[] DFI_MF = { (byte) 0x3F, (byte) 0x00 };\n\tprotected final static byte[] DFI_EP = { (byte) 0x10, (byte) 0x01 };\n\tprotected final static byte[] DFN_PSE = { (byte) '1', (byte) 'P', (byte) 'A', (byte) 'Y',\n\t\t\t(byte) '.', (byte) 'S', (byte) 'Y', (byte) 'S', (byte) '.', (byte) 'D', (byte) 'D',\n\t\t\t(byte) 'F', (byte) '0', (byte) '1', };\n\tprotected final static byte[] DFN_PXX = { (byte) 'P' };\n\tprotected final static int SFI_EXTRA = 21;\n\tprotected static int MAX_LOG = 10;\n\tprotected static int SFI_LOG = 24;\n\tprotected final static byte TRANS_CSU = 6;\n\tprotected final static byte TRANS_CSU_CPX = 9;\n\tprotected abstract Object getApplicationId();\n\tprotected byte[] getMainApplicationId() {\n\t\treturn DFI_EP;\n\t}\n\tprotected SPEC.CUR getCurrency() {\n\t\treturn SPEC.CUR.CNY;\n\t}\n\tprotected boolean selectMainApplication(Iso7816.StdTag tag) throws IOException {\n\t\tfinal byte[] aid = getMainApplicationId();\n\t\treturn ((aid.length == 2) ? tag.selectByID(aid) : tag.selectByName(aid)).isOkey();\n\t}\n\tprotected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {\n\t\t/*--------------------------------------------------------------*/\n\t\t// select Main Application\n\t\t/*--------------------------------------------------------------*/\n\t\tif (!selectMainApplication(tag))\n\t\t\treturn HINT.GONEXT;\n\t\tIso7816.Response INFO, BALANCE;\n\t\t/*--------------------------------------------------------------*/\n\t\t// read card info file, binary (21)\n\t\t/*--------------------------------------------------------------*/\n\t\tINFO = tag.readBinary(SFI_EXTRA);\n\t\t/*--------------------------------------------------------------*/\n\t\t// read balance\n\t\t/*--------------------------------------------------------------*/\n\t\tBALANCE = tag.getBalance(0, true);\n\t\t/*--------------------------------------------------------------*/\n\t\t// read log file, record (24)\n\t\t/*--------------------------------------------------------------*/\n\t\tArrayList<byte[]> LOG = readLog24(tag, SFI_LOG);\n\t\t/*--------------------------------------------------------------*/\n\t\t// build result\n\t\t/*--------------------------------------------------------------*/\n\t\tfinal Application app = createApplication();\n\t\tparseBalance(app, BALANCE);\n\t\tparseInfo21(app, INFO, 4, true);\n\t\tparseLog24(app, LOG);\n\t\tconfigApplication(app);\n\t\tcard.addApplication(app);\n\t\treturn HINT.STOP;\n\t}\n\tprotected float parseBalance(Iso7816.Response data) {\n\t\tfloat ret = 0f;\n\t\tif (data.isOkey() && data.size() >= 4) {\n\t\t\tint n = Util.toInt(data.getBytes(), 0, 4);\n\t\t\tif (n > 1000000 || n < -1000000)\n\t\t\t\tn -= 0x80000000;\n\t\t\tret = n / 100.0f;\n\t\t}\n\t\treturn ret;\n\t}\n\tprotected void parseBalance(Application app, Iso7816.Response... data) {\n\t\tfloat amount = 0f;\n\t\tfor (Iso7816.Response rsp : data)\n\t\t\tamount += parseBalance(rsp);\n\t\tapp.setProperty(SPEC.PROP.BALANCE, amount);\n\t}\n\tprotected void parseInfo21(Application app, Iso7816.Response data, int dec, boolean bigEndian) {\n\t\tif (!data.isOkey() || data.size() < 30) {\n\t\t\treturn;\n\t\t}\n\t\tfinal byte[] d = data.getBytes();\n\t\tif (dec < 1 || dec > 10) {\n\t\t\tapp.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10));\n\t\t} else {\n\t\t\tfinal int sn = bigEndian ? Util.toIntR(d, 19, dec) : Util.toInt(d, 20 - dec, dec);\n\t\t\tapp.setProperty(SPEC.PROP.SERIAL, String.format(\"%d\", 0xFFFFFFFFL & sn));\n\t\t}\n\t\tif (d[9] != 0)\n\t\t\tapp.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9]));\n\t\tapp.setProperty(SPEC.PROP.DATE, String.format(\"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X\",\n\t\t\t\td[20], d[21], d[22], d[23], d[24], d[25], d[26], d[27]));\n\t}\n\tprotected boolean addLog24(final Iso7816.Response r, ArrayList<byte[]> l) {\n\t\tif (!r.isOkey())\n\t\t\treturn false;\n\t\tfinal byte[] raw = r.getBytes();\n\t\tfinal int N = raw.length - 23;\n\t\tif (N < 0)\n\t\t\treturn false;\n\t\tfor (int s = 0, e = 0; s <= N; s = e) {\n\t\t\tl.add(Arrays.copyOfRange(raw, s, (e = s + 23)));\n\t\t}\n\t\treturn true;\n\t}\n\tprotected ArrayList<byte[]> readLog24(Iso7816.StdTag tag, int sfi) throws IOException {\n\t\tfinal ArrayList<byte[]> ret = new ArrayList<byte[]>(MAX_LOG);\n\t\tfinal Iso7816.Response rsp = tag.readRecord(sfi);\n\t\tif (rsp.isOkey()) {\n\t\t\taddLog24(rsp, ret);\n\t\t} else {\nNext line of code:\n"}
{"question_id": 15, "category": "longbench_qasper", "reference": ["Individuals with legal training", "Yes"], "prompt": "You are given a scientific article and a question. Answer the question as concisely as you can, using a single phrase or sentence if possible. If the question cannot be answered based on the information in the article, write \"unanswerable\". If the question is a yes/no question, answer \"yes\", \"no\", or \"unanswerable\". Do not provide any explanation.\n\nArticle: Introduction\nPrivacy policies are the documents which disclose the ways in which a company gathers, uses, shares and manages a user's data. As legal documents, they function using the principle of notice and choice BIBREF0, where companies post their policies, and theoretically, users read the policies and decide to use a company's products or services only if they find the conditions outlined in its privacy policy acceptable. Many legal jurisdictions around the world accept this framework, including the United States and the European Union BIBREF1, BIBREF2. However, the legitimacy of this framework depends upon users actually reading and understanding privacy policies to determine whether company practices are acceptable to them BIBREF3. In practice this is seldom the case BIBREF4, BIBREF5, BIBREF6, BIBREF7, BIBREF8, BIBREF9, BIBREF10. This is further complicated by the highly individual and nuanced compromises that users are willing to make with their data BIBREF11, discouraging a `one-size-fits-all' approach to notice of data practices in privacy documents.\nWith devices constantly monitoring our environment, including our personal space and our bodies, lack of awareness of how our data is being used easily leads to problematic situations where users are outraged by information misuse, but companies insist that users have consented. The discovery of increasingly egregious uses of data by companies, such as the scandals involving Facebook and Cambridge Analytica BIBREF12, have further brought public attention to the privacy concerns of the internet and ubiquitous computing. This makes privacy a well-motivated application domain for NLP researchers, where advances in enabling users to quickly identify the privacy issues most salient to them can potentially have large real-world impact.\n[1]https://play.google.com/store/apps/details?id=com.gotokeep.keep.intl [2]https://play.google.com/store/apps/details?id=com.viber.voip [3]A question might not have any supporting evidence for an answer within the privacy policy.\nMotivated by this need, we contribute PrivacyQA, a corpus consisting of 1750 questions about the contents of privacy policies, paired with over 3500 expert annotations. The goal of this effort is to kickstart the development of question-answering methods for this domain, to address the (unrealistic) expectation that a large population should be reading many policies per day. In doing so, we identify several understudied challenges to our ability to answer these questions, with broad implications for systems seeking to serve users' information-seeking intent. By releasing this resource, we hope to provide an impetus to develop systems capable of language understanding in this increasingly important domain.\nRelated Work\nPrior work has aimed to make privacy policies easier to understand. Prescriptive approaches towards communicating privacy information BIBREF21, BIBREF22, BIBREF23 have not been widely adopted by industry. Recently, there have been significant research effort devoted to understanding privacy policies by leveraging NLP techniques BIBREF24, BIBREF25, BIBREF26, BIBREF27, BIBREF28, especially by identifying specific data practices within a privacy policy. We adopt a personalized approach to understanding privacy policies, that allows users to query a document and selectively explore content salient to them. Most similar is the PolisisQA corpus BIBREF29, which examines questions users ask corporations on Twitter. Our approach differs in several ways: 1) The PrivacyQA dataset is larger, containing 10x as many questions and answers. 2) Answers are formulated by domain experts with legal training. 3) PrivacyQA includes diverse question types, including unanswerable and subjective questions.\nOur work is also related to reading comprehension in the open domain, which is frequently based upon Wikipedia passages BIBREF16, BIBREF17, BIBREF15, BIBREF30 and news articles BIBREF20, BIBREF31, BIBREF32. Table.TABREF4 presents the desirable attributes our dataset shares with past approaches. This work is also tied into research in applying NLP approaches to legal documents BIBREF33, BIBREF34, BIBREF35, BIBREF36, BIBREF37, BIBREF38, BIBREF39. While privacy policies have legal implications, their intended audience consists of the general public rather than individuals with legal expertise. This arrangement is problematic because the entities that write privacy policies often have different goals than the audience. feng2015applying, tan-EtAl:2016:P16-1 examine question answering in the insurance domain, another specialized domain similar to privacy, where the intended audience is the general public.\nData Collection\nWe describe the data collection methodology used to construct PrivacyQA. With the goal of achieving broad coverage across application types, we collect privacy policies from 35 mobile applications representing a number of different categories in the Google Play Store. One of our goals is to include both policies from well-known applications, which are likely to have carefully-constructed privacy policies, and lesser-known applications with smaller install bases, whose policies might be considerably less sophisticated. Thus, setting 5 million installs as a threshold, we ensure each category includes applications with installs on both sides of this threshold. All policies included in the corpus are in English, and were collected before April 1, 2018, predating many companies' GDPR-focused BIBREF41 updates. We leave it to future studies BIBREF42 to look at the impact of the GDPR (e.g., to what extent GDPR requirements contribute to making it possible to provide users with more informative answers, and to what extent their disclosures continue to omit issues that matter to users).\nData Collection ::: Crowdsourced Question Elicitation\nThe intended audience for privacy policies consists of the general public. This informs the decision to elicit questions from crowdworkers on the contents of privacy policies. We choose not to show the contents of privacy policies to crowdworkers, a procedure motivated by a desire to avoid inadvertent biases BIBREF43, BIBREF44, BIBREF45, BIBREF46, BIBREF47, and encourage crowdworkers to ask a variety of questions beyond only asking questions based on practices described in the document.\nInstead, crowdworkers are presented with public information about a mobile application available on the Google Play Store including its name, description and navigable screenshots. Figure FIGREF9 shows an example of our user interface. Crowdworkers are asked to imagine they have access to a trusted third-party privacy assistant, to whom they can ask any privacy question about a given mobile application. We use the Amazon Mechanical Turk platform and recruit crowdworkers who have been conferred “master” status and are located within the United States of America. Turkers are asked to provide five questions per mobile application, and are paid $2 per assignment, taking ~eight minutes to complete the task.\nData Collection ::: Answer Selection\nTo identify legally sound answers, we recruit seven experts with legal training to construct answers to Turker questions. Experts identify relevant evidence within the privacy policy, as well as provide meta-annotation on the question's relevance, subjectivity, OPP-115 category BIBREF49, and how likely any privacy policy is to contain the answer to the question asked.\nData Collection ::: Analysis\nTable.TABREF17 presents aggregate statistics of the PrivacyQA dataset. 1750 questions are posed to our imaginary privacy assistant over 35 mobile applications and their associated privacy documents. As an initial step, we formulate the problem of answering user questions as an extractive sentence selection task, ignoring for now background knowledge, statistical data and legal expertise that could otherwise be brought to bear. The dataset is partitioned into a training set featuring 27 mobile applications and 1350 questions, and a test set consisting of 400 questions over 8 policy documents. This ensures that documents in training and test splits are mutually exclusive. Every question is answered by at least one expert. In addition, in order to estimate annotation reliability and provide for better evaluation, every question in the test set is answered by at least two additional experts.\nTable TABREF14 describes the distribution over first words of questions posed by crowdworkers. We also observe low redundancy in the questions posed by crowdworkers over each policy, with each policy receiving ~49.94 unique questions despite crowdworkers independently posing questions. Questions are on average 8.4 words long. As declining to answer a question can be a legally sound response but is seldom practically useful, answers to questions where a minority of experts abstain to answer are filtered from the dataset. Privacy policies are ~3000 words long on average. The answers to the question asked by the users typically have ~100 words of evidence in the privacy policy document.\nData Collection ::: Analysis ::: Categories of Questions\nQuestions are organized under nine categories from the OPP-115 Corpus annotation scheme BIBREF49:\nFirst Party Collection/Use: What, why and how information is collected by the service provider\nThird Party Sharing/Collection: What, why and how information shared with or collected by third parties\nData Security: Protection measures for user information\nData Retention: How long user information will be stored\nUser Choice/Control: Control options available to users\nUser Access, Edit and Deletion: If/how users can access, edit or delete information\nPolicy Change: Informing users if policy information has been changed\nInternational and Specific Audiences: Practices pertaining to a specific group of users\nOther: General text, contact information or practices not covered by other categories.\nFor each question, domain experts indicate one or more relevant OPP-115 categories. We mark a category as relevant to a question if it is identified as such by at least two annotators. If no such category exists, the category is marked as `Other' if atleast one annotator has identified the `Other' category to be relevant. If neither of these conditions is satisfied, we label the question as having no agreement. The distribution of questions in the corpus across OPP-115 categories is as shown in Table.TABREF16. First party and third party related questions are the largest categories, forming nearly 66.4% of all questions asked to the privacy assistant.\nData Collection ::: Analysis ::: Answer Validation\nWhen do experts disagree? We would like to analyze the reasons for potential disagreement on the annotation task, to ensure disagreements arise due to valid differences in opinion rather than lack of adequate specification in annotation guidelines. It is important to note that the annotators are experts rather than crowdworkers. Accordingly, their judgements can be considered valid, legally-informed opinions even when their perspectives differ. For the sake of this question we randomly sample 100 instances in the test data and analyze them for likely reasons for disagreements. We consider a disagreement to have occurred when more than one expert does not agree with the majority consensus. By disagreement we mean there is no overlap between the text identified as relevant by one expert and another.\nWe find that the annotators agree on the answer for 74% of the questions, even if the supporting evidence they identify is not identical i.e full overlap. They disagree on the remaining 26%. Sources of apparent disagreement correspond to situations when different experts: have differing interpretations of question intent (11%) (for example, when a user asks 'who can contact me through the app', the questions admits multiple interpretations, including seeking information about the features of the app, asking about first party collection/use of data or asking about third party collection/use of data), identify different sources of evidence for questions that ask if a practice is performed or not (4%), have differing interpretations of policy content (3%), identify a partial answer to a question in the privacy policy (2%) (for example, when the user asks `who is allowed to use the app' a majority of our annotators decline to answer, but the remaining annotators highlight partial evidence in the privacy policy which states that children under the age of 13 are not allowed to use the app), and other legitimate sources of disagreement (6%) which include personal subjective views of the annotators (for example, when the user asks `is my DNA information used in any way other than what is specified', some experts consider the boilerplate text of the privacy policy which states that it abides to practices described in the policy document as sufficient evidence to answer this question, whereas others do not).\nExperimental Setup\nWe evaluate the ability of machine learning methods to identify relevant evidence for questions in the privacy domain. We establish baselines for the subtask of deciding on the answerability (§SECREF33) of a question, as well as the overall task of identifying evidence for questions from policies (§SECREF37). We describe aspects of the question that can render it unanswerable within the privacy domain (§SECREF41).\nExperimental Setup ::: Answerability Identification Baselines\nWe define answerability identification as a binary classification task, evaluating model ability to predict if a question can be answered, given a question in isolation. This can serve as a prior for downstream question-answering. We describe three baselines on the answerability task, and find they considerably improve performance over a majority-class baseline.\nSVM: We define 3 sets of features to characterize each question. The first is a simple bag-of-words set of features over the question (SVM-BOW), the second is bag-of-words features of the question as well as length of the question in words (SVM-BOW + LEN), and lastly we extract bag-of-words features, length of the question in words as well as part-of-speech tags for the question (SVM-BOW + LEN + POS). This results in vectors of 200, 201 and 228 dimensions respectively, which are provided to an SVM with a linear kernel.\nCNN: We utilize a CNN neural encoder for answerability prediction. We use GloVe word embeddings BIBREF50, and a filter size of 5 with 64 filters to encode questions.\nBERT: BERT BIBREF51 is a bidirectional transformer-based language-model BIBREF52. We fine-tune BERT-base on our binary answerability identification task with a learning rate of 2e-5 for 3 epochs, with a maximum sequence length of 128.\nExperimental Setup ::: Privacy Question Answering\nOur goal is to identify evidence within a privacy policy for questions asked by a user. This is framed as an answer sentence selection task, where models identify a set of evidence sentences from all candidate sentences in each policy.\nExperimental Setup ::: Privacy Question Answering ::: Evaluation Metric\nOur evaluation metric for answer-sentence selection is sentence-level F1, implemented similar to BIBREF30, BIBREF16. Precision and recall are implemented by measuring the overlap between predicted sentences and sets of gold-reference sentences. We report the average of the maximum F1 from each n$-$1 subset, in relation to the heldout reference.\nExperimental Setup ::: Privacy Question Answering ::: Baselines\nWe describe baselines on this task, including a human performance baseline.\nNo-Answer Baseline (NA) : Most of the questions we receive are difficult to answer in a legally-sound way on the basis of information present in the privacy policy. We establish a simple baseline to quantify the effect of identifying every question as unanswerable.\nWord Count Baseline : To quantify the effect of using simple lexical matching to answer the questions, we retrieve the top candidate policy sentences for each question using a word count baseline BIBREF53, which counts the number of question words that also appear in a sentence. We include the top 2, 3 and 5 candidates as baselines.\nBERT: We implement two BERT-based baselines BIBREF51 for evidence identification. First, we train BERT on each query-policy sentence pair as a binary classification task to identify if the sentence is evidence for the question or not (Bert). We also experiment with a two-stage classifier, where we separately train the model on questions only to predict answerability. At inference time, if the answerable classifier predicts the question is answerable, the evidence identification classifier produces a set of candidate sentences (Bert + Unanswerable).\nHuman Performance: We pick each reference answer provided by an annotator, and compute the F1 with respect to the remaining references, as described in section 4.2.1. Each reference answer is treated as the prediction, and the remaining n-1 answers are treated as the gold reference. The average of the maximum F1 across all reference answers is computed as the human baseline.\nResults and Discussion\nThe results of the answerability baselines are presented in Table TABREF31, and on answer sentence selection in Table TABREF32. We observe that bert exhibits the best performance on a binary answerability identification task. However, most baselines considerably exceed the performance of a majority-class baseline. This suggests considerable information in the question, indicating it's possible answerability within this domain.\nTable.TABREF32 describes the performance of our baselines on the answer sentence selection task. The No-answer (NA) baseline performs at 28 F1, providing a lower bound on performance at this task. We observe that our best-performing baseline, Bert + Unanswerable achieves an F1 of 39.8. This suggest that bert is capable of making some progress towards answering questions in this difficult domain, while still leaving considerable headroom for improvement to reach human performance. Bert + Unanswerable performance suggests that incorporating information about answerability can help in this difficult domain. We examine this challenging phenomena of unanswerability further in Section .\nResults and Discussion ::: Error Analysis\nDisagreements are analyzed based on the OPP-115 categories of each question (Table.TABREF34). We compare our best performing BERT variant against the NA model and human performance. We observe significant room for improvement across all categories of questions but especially for first party, third party and data retention categories.\nWe analyze the performance of our strongest BERT variant, to identify classes of errors and directions for future improvement (Table.8). We observe that a majority of answerability mistakes made by the BERT model are questions which are in fact answerable, but are identified as unanswerable by BERT. We observe that BERT makes 124 such mistakes on the test set. We collect expert judgments on relevance, subjectivity , silence and information about how likely the question is to be answered from the privacy policy from our experts. We find that most of these mistakes are relevant questions. However many of them were identified as subjective by the annotators, and at least one annotator marked 19 of these questions as having no answer within the privacy policy. However, only 6 of these questions were unexpected or do not usually have an answer in privacy policies. These findings suggest that a more nuanced understanding of answerability might help improve model performance in his challenging domain.\nResults and Discussion ::: What makes Questions Unanswerable?\nWe further ask legal experts to identify potential causes of unanswerability of questions. This analysis has considerable implications. While past work BIBREF17 has treated unanswerable questions as homogeneous, a question answering system might wish to have different treatments for different categories of `unanswerable' questions. The following factors were identified to play a role in unanswerability:\nIncomprehensibility: If a question is incomprehensible to the extent that its meaning is not intelligible.\nRelevance: Is this question in the scope of what could be answered by reading the privacy policy.\nIll-formedness: Is this question ambiguous or vague. An ambiguous statement will typically contain expressions that can refer to multiple potential explanations, whereas a vague statement carries a concept with an unclear or soft definition.\nSilence: Other policies answer this type of question but this one does not.\nAtypicality: The question is of a nature such that it is unlikely for any policy policy to have an answer to the question.\nOur experts attempt to identify the different `unanswerable' factors for all 573 such questions in the corpus. 4.18% of the questions were identified as being incomprehensible (for example, `any difficulties to occupy the privacy assistant'). Amongst the comprehendable questions, 50% were identified as likely to have an answer within the privacy policy, 33.1% were identified as being privacy-related questions but not within the scope of a privacy policy (e.g., 'has Viber had any privacy breaches in the past?') and 16.9% of questions were identified as completely out-of-scope (e.g., `'will the app consume much space?'). In the questions identified as relevant, 32% were ill-formed questions that were phrased by the user in a manner considered vague or ambiguous. Of the questions that were both relevant as well as `well-formed', 95.7% of the questions were not answered by the policy in question but it was reasonable to expect that a privacy policy would contain an answer. The remaining 4.3% were described as reasonable questions, but of a nature generally not discussed in privacy policies. This suggests that the answerability of questions over privacy policies is a complex issue, and future systems should consider each of these factors when serving user's information seeking intent.\nWe examine a large-scale dataset of “natural” unanswerable questions BIBREF54 based on real user search engine queries to identify if similar unanswerability factors exist. It is important to note that these questions have previously been filtered, according to a criteria for bad questions defined as “(questions that are) ambiguous, incomprehensible, dependent on clear false presuppositions, opinion-seeking, or not clearly a request for factual information.” Annotators made the decision based on the content of the question without viewing the equivalent Wikipedia page. We randomly sample 100 questions from the development set which were identified as unanswerable, and find that 20% of the questions are not questions (e.g., “all I want for christmas is you mariah carey tour”). 12% of questions are unlikely to ever contain an answer on Wikipedia, corresponding closely to our atypicality category. 3% of questions are unlikely to have an answer anywhere (e.g., `what guides Santa home after he has delivered presents?'). 7% of questions are incomplete or open-ended (e.g., `the south west wind blows across nigeria between'). 3% of questions have an unresolvable coreference (e.g., `how do i get to Warsaw Missouri from here'). 4% of questions are vague, and a further 7% have unknown sources of error. 2% still contain false presuppositions (e.g., `what is the only fruit that does not have seeds?') and the remaining 42% do not have an answer within the document. This reinforces our belief that though they have been understudied in past work, any question answering system interacting with real users should expect to receive such unanticipated and unanswerable questions.\nConclusion\nWe present PrivacyQA, the first significant corpus of privacy policy questions and more than 3500 expert annotations of relevant answers. The goal of this work is to promote question-answering research in the specialized privacy domain, where it can have large real-world impact. Strong neural baselines on PrivacyQA achieve a performance of only 39.8 F1 on this corpus, indicating considerable room for future research. Further, we shed light on several important considerations that affect the answerability of questions. We hope this contribution leads to multidisciplinary efforts to precisely understand user intent and reconcile it with information in policy documents, from both the privacy and NLP communities.\nAcknowledgements\nThis research was supported in part by grants from the National Science Foundation Secure and Trustworthy Computing program (CNS-1330596, CNS-1330214, CNS-15-13957, CNS-1801316, CNS-1914486, CNS-1914444) and a DARPA Brandeis grant on Personalized Privacy Assistants (FA8750-15-2-0277). The US Government is authorized to reproduce and distribute reprints for Governmental purposes not withstanding any copyright notation. The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies or endorsements, either expressed or implied, of the NSF, DARPA, or the US Government. The authors would like to extend their gratitude to Elias Wright, Gian Mascioli, Kiara Pillay, Harrison Kay, Eliel Talo, Alexander Fagella and N. Cameron Russell for providing their valuable expertise and insight to this effort. The authors are also grateful to Eduard Hovy, Lorrie Cranor, Florian Schaub, Joel Reidenberg, Aditya Potukuchi and Igor Shalyminov for helpful discussions related to this work, and to the three anonymous reviewers of this draft for their constructive feedback. Finally, the authors would like to thank all crowdworkers who consented to participate in this study.\n\n Answer the question based on the above article as concisely as you can, using a single phrase or sentence if possible. If the question cannot be answered based on the information in the article, write \"unanswerable\". If the question is a yes/no question, answer \"yes\", \"no\", or \"unanswerable\". Do not provide any explanation.\n\nQuestion: Who were the experts used for annotation?\n\nAnswer:"}
{"question_id": 16, "category": "longbench_multi_news", "reference": ["Four years ago, a chemistry professor got a text from her grad student: If I'm not back in a week, cut me from the doctoral program. Charlotta Turner called him right away: \"He was very sad and crying,” the 48-year-old prof at Lund University in Sweden tells NBC News. \"I could hear that the situation was hopeless and they had to flee.\" The student, Firas Jumaah, was visiting his native Iraq to help family members during a brutal 2014 ISIS attack targeting Yazidis—a religious minority that includes his family. The terror group had just enslaved and massacred Yazidis by the thousand in nearby Sinjar. Now Jumaah and family were planning to flee to the mountains. \"I had no hope at all,\" says Jumaah, per the Local. \"I was desperate.\" But Turner took action. She spoke to Lund University's then-security chief, who contacted a company that sent mercenaries into northern Iraq. Only days later, four armed mercs on two Landcruisers blazed into the place where Jumaah was hiding, and rushed him to Erbil Airport with his wife and two young kids. \"I have never felt so privileged, so VIP,\" he says. \"But at the same time I felt like a coward as I left my mother and sisters behind me.\" Seeing his colleagues back in Sweden, he was speechless: \"I just cried,\" he says. Yet Jumaah finished his PhD and found work at a Malmo pharmaceuticals company, and his family survived. The bill: roughly 60,000 kroner ($6,613), which his family has nearly finished paying. “If they told me to pay 200,000 kronor, I would,” says Jumaah. (The UN is finding fresh ISIS horrors.)"], "prompt": "You are given several news passages. Write a one-page summary of all news. \n\nNews:\nPassage 1:\nCharlotta Turner, professor in Analytical Chemistry, received a text message from her student Firas Jumaah in 2014 telling her to to assume he would not finish his thesis if he had not returned within a week. NEWLINE_CHAR NEWLINE_CHAR He and his family were, he told her, hiding out in a disused bleach factory, with the sounds of gunshots from Isis warriors roaming the town reverberating around them. Jumaah, who is from Iraq, is a member of the ethno-religious group Yazidi hated by Isis. NEWLINE_CHAR NEWLINE_CHAR \"I had no hope then at all,\" Jumaah told Lund's University Magazine LUM . \"I was desperate. I just wanted to tell my supervisor what was happening. I had no idea that a professor would be able to do anything for us.\" NEWLINE_CHAR NEWLINE_CHAR Jumaah had voluntarily entered the war zone after his wife had rung him to say that Isis fighters had taken over the next-door village, killing all the men and taking the women into slavery. NEWLINE_CHAR NEWLINE_CHAR \"My wife was totally panicking. Everyone was shocked at how IS were behaving,\" he said. \"I took the first plane there to be with them. What sort of life would I have if anything had happened to them there?\" NEWLINE_CHAR NEWLINE_CHAR But Turner was not willing to leave her student to die without trying to do something. NEWLINE_CHAR NEWLINE_CHAR \"What was happening was completely unacceptable,\" she told LUM. \"I got so angry that IS was pushing itself into our world, exposing my doctoral student and his family to this, and disrupting the research.\" NEWLINE_CHAR NEWLINE_CHAR She contacted the university's then security chief Per Gustafson. NEWLINE_CHAR NEWLINE_CHAR \"It was almost as if he'd been waiting for this kind of mission,\" Turner said. \"Per Gustafson said that we had a transport and security deal which stretched over the whole world.\" NEWLINE_CHAR NEWLINE_CHAR Over a few days of intense activity, Gustafson hired a security company which then arranged the rescue operation. A few days later two Landcruisers carrying four heavily-armed mercenaries roared into the area where Jumaah was hiding, and sped him away to Erbil Airport together with his wife and two small children. \"I have never felt so privileged, so VIP,\" Jumaah told LUM. \"But at the same time I felt like a coward as I left my mother and sisters behind me.\" NEWLINE_CHAR NEWLINE_CHAR Firas Jumaah and his former PHD supervisor Charlotta Turner. Photo: Kennet Ruona NEWLINE_CHAR NEWLINE_CHAR Luckily the rest of his family survived Isis occupation, while Jumaah back in Sweden completed his PhD and now works for a pharmaceuticals company in Malmö. The family has almost finished paying the university back for the rescue operation. NEWLINE_CHAR NEWLINE_CHAR \"It was a unique event. As far as I know no other university has ever been involved in anything like it,\" Gustafson said.\nPassage 2:\nBreaking News Emails Get breaking news alerts and special reports. The news and stories that matter, delivered weekday mornings. NEWLINE_CHAR NEWLINE_CHAR By Yuliya Talmazan NEWLINE_CHAR NEWLINE_CHAR On an August day four years ago, Swedish chemistry professor Charlotta Turner received a surprising text message that would change the life of one of her graduate students. NEWLINE_CHAR NEWLINE_CHAR Firas Jumaah had returned to his native Iraq days earlier, fearing for the safety of his wife and two children who had traveled there for a family wedding. He had initially stayed behind to complete his lab work at Lund University in southern Sweden. NEWLINE_CHAR NEWLINE_CHAR While with his family in Iraq, Jumaah sent his supervisor a text message asking her to remove him from the doctoral program if he wasn’t back in Sweden within a week. NEWLINE_CHAR NEWLINE_CHAR Firas Jumaah Charlotta Turner NEWLINE_CHAR NEWLINE_CHAR Surprised by the message, Turner, 48, called Jumaah. It was then that she found out that his family was facing a life-and-death situation. NEWLINE_CHAR NEWLINE_CHAR “He was very sad and crying,” Turner told NBC News. “I could hear that the situation was hopeless and they had to flee.” NEWLINE_CHAR NEWLINE_CHAR Jumaah's family had returned to visit their home country of Iraq before violence began. But while he was there the so-called Islamic State conducted a deadly offensive in northern Iraq. NEWLINE_CHAR NEWLINE_CHAR On Aug. 3, ISIS attacked the city of Sinjar near to where Jumaah’s family was, massacring and enslaving thousands of Yazidis — a religious minority to which Jumaah and his family belong. NEWLINE_CHAR NEWLINE_CHAR “He realized one day that things were getting really serious there,” Turner said. “He was very worried and he just left.” NEWLINE_CHAR NEWLINE_CHAR Jumaah’s plan was to go in and bring his family back to Sweden, but when he arrived, most borders were closed because of a mass exodus of refugees. He also couldn’t go back to the airport. So they waited. NEWLINE_CHAR NEWLINE_CHAR But the situation only grew worse because ISIS kept advancing — and, at one point, came within 12 miles of their house. NEWLINE_CHAR NEWLINE_CHAR Over the phone, Jumaah told Turner that he and his family were preparing to go into hiding in Iraq’s northern mountains. She told him not to give up and started looking for ways to rescue the family. NEWLINE_CHAR NEWLINE_CHAR “It was very spontaneous,” she said. “For me, it was obvious that I should help and bring them home.” NEWLINE_CHAR NEWLINE_CHAR She approached the university’s security chief at the time, who found a company that could go in with armed men and rescue Jumaah and his family.\n\n\nNow, write a one-page summary of all the news.\n\nSummary:"}
{"question_id": 17, "category": "longbench_repobench-p", "reference": [" contentValues.put(JobStorage.COLUMN_BACKOFF_MS, JobRequest.DEFAULT_BACKOFF_MS);"], "prompt": "Please complete the code given below. \nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_NETWORK_TYPE = \"networkType\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_TRANSIENT = \"transient\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_ID = \"_id\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_LAST_RUN = \"lastRun\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_FLEX_MS = \"flexMs\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_FLEX_SUPPORT = \"flexSupport\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_REQUIRES_CHARGING = \"requiresCharging\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String DATABASE_NAME = PREF_FILE_NAME + \".db\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_EXACT = \"exact\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_EXTRAS = \"extras\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_SCHEDULED_AT = \"scheduledAt\";\nlibrary/src/main/java/com/evernote/android/job/util/support/PersistableBundleCompat.java\n@SuppressWarnings(\"unused\")\npublic final class PersistableBundleCompat {\n\n private static final JobCat CAT = new JobCat(\"PersistableBundleCompat\");\n private static final String UTF_8 = \"UTF-8\";\n\n private final Map<String, Object> mValues;\n\n public PersistableBundleCompat() {\n this(new HashMap<String, Object>());\n }\n\n public PersistableBundleCompat(PersistableBundleCompat bundle) {\n this(new HashMap<>(bundle.mValues));\n }\n\n private PersistableBundleCompat(Map<String, Object> values) {\n mValues = values;\n }\n\n public void putBoolean(String key, boolean value) {\n mValues.put(key, value);\n }\n\n public boolean getBoolean(String key, boolean defaultValue) {\n Object value = mValues.get(key);\n if (value instanceof Boolean) {\n return (Boolean) value;\n } else {\n return defaultValue;\n }\n }\n\n public void putInt(String key, int value) {\n mValues.put(key, value);\n }\n\n public int getInt(String key, int defaultValue) {\n Object value = mValues.get(key);\n if (value instanceof Integer) {\n return (Integer) value;\n } else {\n return defaultValue;\n }\n }\n\n public void putIntArray(String key, int[] value) {\n mValues.put(key, value);\n }\n\n public int[] getIntArray(String key) {\n Object value = mValues.get(key);\n if (value instanceof int[]) {\n return (int[]) value;\n } else {\n return null;\n }\n }\n\n public void putLong(String key, long value) {\n mValues.put(key, value);\n }\n\n public long getLong(String key, long defaultValue) {\n Object value = mValues.get(key);\n if (value instanceof Long) {\n return (Long) value;\n } else {\n return defaultValue;\n }\n }\n\n public void putLongArray(String key, long[] value) {\n mValues.put(key, value);\n }\n\n public long[] getLongArray(String key) {\n Object value = mValues.get(key);\n if (value instanceof long[]) {\n return (long[]) value;\n } else {\n return null;\n }\n }\n\n public void putDouble(String key, double value) {\n mValues.put(key, value);\n }\n\n public double getDouble(String key, double defaultValue) {\n Object value = mValues.get(key);\n if (value instanceof Double) {\n return (Double) value;\n } else {\n return defaultValue;\n }\n }\n\n public void putDoubleArray(String key, double[] value) {\n mValues.put(key, value);\n }\n\n public double[] getDoubleArray(String key) {\n Object value = mValues.get(key);\n if (value instanceof double[]) {\n return (double[]) value;\n } else {\n return null;\n }\n }\n\n public void putString(String key, String value) {\n mValues.put(key, value);\n }\n\n public String getString(String key, String defaultValue) {\n Object value = mValues.get(key);\n if (value instanceof String) {\n return (String) value;\n } else {\n return defaultValue;\n }\n }\n\n public void putStringArray(String key, String[] value) {\n mValues.put(key, value);\n }\n\n public String[] getStringArray(String key) {\n Object value = mValues.get(key);\n if (value instanceof String[]) {\n return (String[]) value;\n } else {\n return null;\n }\n }\n\n public void putPersistableBundleCompat(String key, PersistableBundleCompat value) {\n mValues.put(key, value == null ? null : value.mValues);\n }\n\n @SuppressWarnings(\"unchecked\")\n public PersistableBundleCompat getPersistableBundleCompat(String key) {\n Object value = mValues.get(key);\n if (value instanceof Map) {\n return new PersistableBundleCompat((Map<String, Object>) value);\n } else {\n return null;\n }\n }\n\n public void clear() {\n mValues.clear();\n }\n\n public boolean containsKey(String key) {\n return mValues.containsKey(key);\n }\n\n public Object get(String key) {\n return mValues.get(key);\n }\n\n public boolean isEmpty() {\n return mValues.isEmpty();\n }\n\n public Set<String> keySet() {\n return mValues.keySet();\n }\n\n public void putAll(PersistableBundleCompat bundle) {\n mValues.putAll(bundle.mValues);\n }\n\n public void remove(String key) {\n mValues.remove(key);\n }\n\n public int size() {\n return mValues.size();\n }\n\n @NonNull\n public String saveToXml() {\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n try {\n XmlUtils.writeMapXml(mValues, outputStream);\n return outputStream.toString(UTF_8);\n\n } catch (XmlPullParserException | IOException e) {\n CAT.e(e);\n // shouldn't happen\n return \"\";\n\n } catch (Error e) {\n // https://gist.github.com/vRallev/9444359f05259e4b6317 and other crashes on rooted devices\n CAT.e(e);\n return \"\";\n\n } finally {\n try {\n outputStream.close();\n } catch (IOException ignored) {\n }\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n @NonNull\n public static PersistableBundleCompat fromXml(@NonNull String xml) {\n ByteArrayInputStream inputStream = null;\n try {\n inputStream = new ByteArrayInputStream(xml.getBytes(UTF_8));\n HashMap<String, ?> map = XmlUtils.readMapXml(inputStream);\n return new PersistableBundleCompat((Map<String, Object>) map);\n\n } catch (XmlPullParserException | IOException e) {\n CAT.e(e);\n return new PersistableBundleCompat();\n\n } catch (VerifyError e) {\n // https://gist.github.com/vRallev/9444359f05259e4b6317\n CAT.e(e);\n return new PersistableBundleCompat();\n\n } finally {\n if (inputStream != null) {\n try {\n inputStream.close();\n } catch (IOException ignored) {\n }\n }\n }\n }\n}\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_NUM_FAILURES = \"numFailures\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_STARTED = \"started\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_TAG = \"tag\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_INTERVAL_MS = \"intervalMs\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_REQUIRES_DEVICE_IDLE = \"requiresDeviceIdle\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_REQUIREMENTS_ENFORCED = \"requirementsEnforced\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_BACKOFF_POLICY = \"backoffPolicy\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_START_MS = \"startMs\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_REQUIRES_STORAGE_NOT_LOW = \"requiresStorageNotLow\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String JOB_TABLE_NAME = \"jobs\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_END_MS = \"endMs\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_BACKOFF_MS = \"backoffMs\";\nlibrary/src/main/java/com/evernote/android/job/JobStorage.java\npublic static final String COLUMN_REQUIRES_BATTERY_NOT_LOW = \"requiresBatteryNotLow\";\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport androidx.annotation.NonNull;\nimport androidx.test.core.app.ApplicationProvider;\nimport com.evernote.android.job.test.JobRobolectricTestRunner;\nimport com.evernote.android.job.util.support.PersistableBundleCompat;\nimport java.util.concurrent.TimeUnit;\nimport org.junit.FixMethodOrder;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.MethodSorters;\nimport static com.evernote.android.job.JobStorage.COLUMN_BACKOFF_MS;\nimport static com.evernote.android.job.JobStorage.COLUMN_BACKOFF_POLICY;\nimport static com.evernote.android.job.JobStorage.COLUMN_END_MS;\nimport static com.evernote.android.job.JobStorage.COLUMN_EXACT;\nimport static com.evernote.android.job.JobStorage.COLUMN_EXTRAS;\nimport static com.evernote.android.job.JobStorage.COLUMN_FLEX_MS;\nimport static com.evernote.android.job.JobStorage.COLUMN_FLEX_SUPPORT;\nimport static com.evernote.android.job.JobStorage.COLUMN_ID;\nimport static com.evernote.android.job.JobStorage.COLUMN_INTERVAL_MS;\nimport static com.evernote.android.job.JobStorage.COLUMN_LAST_RUN;\nimport static com.evernote.android.job.JobStorage.COLUMN_NETWORK_TYPE;\nimport static com.evernote.android.job.JobStorage.COLUMN_NUM_FAILURES;\nimport static com.evernote.android.job.JobStorage.COLUMN_REQUIREMENTS_ENFORCED;\nimport static com.evernote.android.job.JobStorage.COLUMN_REQUIRES_BATTERY_NOT_LOW;\nimport static com.evernote.android.job.JobStorage.COLUMN_REQUIRES_CHARGING;\nimport static com.evernote.android.job.JobStorage.COLUMN_REQUIRES_DEVICE_IDLE;\nimport static com.evernote.android.job.JobStorage.COLUMN_REQUIRES_STORAGE_NOT_LOW;\nimport static com.evernote.android.job.JobStorage.COLUMN_SCHEDULED_AT;\nimport static com.evernote.android.job.JobStorage.COLUMN_STARTED;\nimport static com.evernote.android.job.JobStorage.COLUMN_START_MS;\nimport static com.evernote.android.job.JobStorage.COLUMN_TAG;\nimport static com.evernote.android.job.JobStorage.COLUMN_TRANSIENT;\nimport static com.evernote.android.job.JobStorage.DATABASE_NAME;\nimport static com.evernote.android.job.JobStorage.JOB_TABLE_NAME;\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n assertThat(jobRequest.isPeriodic()).isFalse();\n assertThat(jobRequest.getStartMs()).isEqualTo(60_000L);\n assertThat(jobRequest.isStarted()).isFalse();\n\n jobRequest = JobManager.instance().getJobRequest(2);\n assertThat(jobRequest.isPeriodic()).isTrue();\n assertThat(jobRequest.getIntervalMs()).isEqualTo(JobRequest.MIN_INTERVAL);\n assertThat(jobRequest.getFlexMs()).isEqualTo(jobRequest.getIntervalMs());\n assertThat(jobRequest.isStarted()).isFalse();\n\n jobRequest = JobManager.instance().getJobRequest(3);\n assertThat(jobRequest.isPeriodic()).isTrue();\n assertThat(jobRequest.getIntervalMs()).isEqualTo(TimeUnit.MINUTES.toMillis(20));\n assertThat(jobRequest.getFlexMs()).isEqualTo(jobRequest.getIntervalMs());\n assertThat(jobRequest.isStarted()).isFalse();\n assertThat(jobRequest.isTransient()).isFalse();\n\n JobManager.instance().cancelAll();\n\n int jobId = new JobRequest.Builder(\"Tag\")\n .setExact(90_000L)\n .build()\n .schedule();\n\n assertThat(JobManager.instance().getAllJobRequests()).hasSize(1);\n\n jobRequest = JobManager.instance().getJobRequest(jobId);\n assertThat(jobRequest).isNotNull();\n assertThat(jobRequest.isStarted()).isFalse();\n\n jobRequest.setStarted(true);\n assertThat(JobManager.instance().getAllJobRequests()).isEmpty();\n assertThat(JobManager.instance().getAllJobRequests(null, true, true)).hasSize(1);\n\n JobManager.instance().cancelAll();\n\n assertThat(JobManager.instance().getAllJobRequests()).isEmpty();\n assertThat(JobManager.instance().getAllJobRequests(null, true, true)).isEmpty();\n\n JobManager.instance().destroy();\n }\n\n private abstract static class UpgradeAbleJobOpenHelper extends SQLiteOpenHelper {\n\n private boolean mDatabaseCreated;\n private boolean mDatabaseUpgraded;\n\n UpgradeAbleJobOpenHelper(Context context, int version) {\n super(context, DATABASE_NAME, null, version);\n }\n\n @Override\n public final void onCreate(SQLiteDatabase db) {\n onCreateInner(db);\n mDatabaseCreated = true;\n }\n\n protected abstract void onCreateInner(SQLiteDatabase db);\n\n @Override\n public final void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n while (oldVersion < newVersion) {\n switch (oldVersion) {\n case 1:\n upgradeFrom1To2(db);\n oldVersion++;\n break;\n case 2:\n upgradeFrom2To3(db);\n oldVersion++;\n break;\n case 3:\n upgradeFrom3To4(db);\n oldVersion++;\n break;\n case 4:\n upgradeFrom4To5(db);\n oldVersion++;\n break;\n case 5:\n upgradeFrom5To6(db);\n oldVersion++;\n break;\n default:\n throw new IllegalStateException(\"not implemented\");\n }\n }\n\n mDatabaseCreated = true;\n mDatabaseUpgraded = true;\n }\n\n protected void upgradeFrom1To2(SQLiteDatabase db) {\n // override me\n }\n\n protected void upgradeFrom2To3(SQLiteDatabase db) {\n // override me\n }\n\n protected void upgradeFrom3To4(SQLiteDatabase db) {\n // override me\n }\n\n protected void upgradeFrom4To5(SQLiteDatabase db) {\n // override me\n }\n\n protected void upgradeFrom5To6(SQLiteDatabase db) {\n // override me\n }\n\n protected ContentValues createBaseContentValues(int id) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(JobStorage.COLUMN_ID, id);\n contentValues.put(JobStorage.COLUMN_TAG, \"Tag\");\n\n contentValues.put(JobStorage.COLUMN_START_MS, -1L);\n contentValues.put(JobStorage.COLUMN_END_MS, -1L);\nNext line of code:\n"}
{"question_id": 18, "category": "longbench_lcc", "reference": ["\t\tif(player == null)"], "prompt": "Please complete the code given below. \n/**\n * This class was created by <Vazkii>. It's distributed as\n * part of the Botania Mod. Get the Source Code in github:\n * https://github.com/Vazkii/Botania\n *\n * Botania is Open Source and distributed under the\n * Botania License: http://botaniamod.net/license.php\n *\n * File Created @ [Jan 24, 2014, 8:03:36 PM (GMT)]\n */\npackage vazkii.botania.api.subtile;\nimport java.awt.Color;\nimport java.util.List;\nimport net.minecraft.block.Block;\nimport net.minecraft.block.state.IBlockState;\nimport net.minecraft.client.Minecraft;\nimport net.minecraft.client.gui.ScaledResolution;\nimport net.minecraft.client.resources.I18n;\nimport net.minecraft.entity.EntityLivingBase;\nimport net.minecraft.entity.player.EntityPlayer;\nimport net.minecraft.init.Blocks;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.nbt.NBTTagCompound;\nimport net.minecraft.tileentity.TileEntity;\nimport net.minecraft.util.EnumFacing;\nimport net.minecraft.util.SoundCategory;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.world.World;\nimport net.minecraftforge.fml.relauncher.Side;\nimport net.minecraftforge.fml.relauncher.SideOnly;\nimport vazkii.botania.api.BotaniaAPI;\nimport vazkii.botania.api.internal.IManaNetwork;\nimport vazkii.botania.api.mana.IManaCollector;\nimport vazkii.botania.api.sound.BotaniaSoundEvents;\n/**\n * The basic class for a Generating Flower.\n */\npublic class SubTileGenerating extends SubTileEntity {\n\tpublic static final int LINK_RANGE = 6;\n\tprivate static final String TAG_MANA = \"mana\";\n\tprivate static final String TAG_COLLECTOR_X = \"collectorX\";\n\tprivate static final String TAG_COLLECTOR_Y = \"collectorY\";\n\tprivate static final String TAG_COLLECTOR_Z = \"collectorZ\";\n\tprivate static final String TAG_PASSIVE_DECAY_TICKS = \"passiveDecayTicks\";\n\tprotected int mana;\n\tpublic int redstoneSignal = 0;\n\tint sizeLastCheck = -1;\n\tprotected TileEntity linkedCollector = null;\n\tpublic int knownMana = -1;\n\tpublic int passiveDecayTicks;\n\tBlockPos cachedCollectorCoordinates = null;\n\t/**\n\t * If set to true, redstoneSignal will be updated every tick.\n\t */\n\tpublic boolean acceptsRedstone() {\n\t\treturn false;\n\t}\n\t@Override\n\tpublic void onUpdate() {\n\t\tsuper.onUpdate();\n\t\tlinkCollector();\n\t\tif(canGeneratePassively()) {\n\t\t\tint delay = getDelayBetweenPassiveGeneration();\n\t\t\tif(delay > 0 && ticksExisted % delay == 0 && !supertile.getWorld().isRemote) {\n\t\t\t\tif(shouldSyncPassiveGeneration())\n\t\t\t\t\tsync();\n\t\t\t\taddMana(getValueForPassiveGeneration());\n\t\t\t}\n\t\t}\n\t\temptyManaIntoCollector();\n\t\tif(acceptsRedstone()) {\n\t\t\tredstoneSignal = 0;\n\t\t\tfor(EnumFacing dir : EnumFacing.VALUES) {\n\t\t\t\tint redstoneSide = supertile.getWorld().getRedstonePower(supertile.getPos().offset(dir), dir);\n\t\t\t\tredstoneSignal = Math.max(redstoneSignal, redstoneSide);\n\t\t\t}\n\t\t}\n\t\tif(supertile.getWorld().isRemote) {\n\t\t\tdouble particleChance = 1F - (double) mana / (double) getMaxMana() / 3.5F;\n\t\t\tColor color = new Color(getColor());\n\t\t\tif(Math.random() > particleChance)\n\t\t\t\tBotaniaAPI.internalHandler.sparkleFX(supertile.getWorld(), supertile.getPos().getX() + 0.3 + Math.random() * 0.5, supertile.getPos().getY() + 0.5 + Math.random() * 0.5, supertile.getPos().getZ() + 0.3 + Math.random() * 0.5, color.getRed() / 255F, color.getGreen() / 255F, color.getBlue() / 255F, (float) Math.random(), 5);\n\t\t}\n\t\tboolean passive = isPassiveFlower();\n\t\tif(!supertile.getWorld().isRemote) {\n\t\t\tint muhBalance = BotaniaAPI.internalHandler.getPassiveFlowerDecay();\n\t\t\tif(passive && muhBalance > 0 && passiveDecayTicks > muhBalance) {\n\t\t\t\tIBlockState state = supertile.getWorld().getBlockState(supertile.getPos());\n\t\t\t\tsupertile.getWorld().playEvent(2001, supertile.getPos(), Block.getStateId(state));\n\t\t\t\tif(supertile.getWorld().getBlockState(supertile.getPos().down()).isSideSolid(supertile.getWorld(), supertile.getPos().down(), EnumFacing.UP))\n\t\t\t\t\tsupertile.getWorld().setBlockState(supertile.getPos(), Blocks.DEADBUSH.getDefaultState());\n\t\t\t\telse supertile.getWorld().setBlockToAir(supertile.getPos());\n\t\t\t}\n\t\t}\n\t\tif(passive)\n\t\t\tpassiveDecayTicks++;\n\t}\n\tpublic void linkCollector() {\n\t\tboolean needsNew = false;\n\t\tif(linkedCollector == null) {\n\t\t\tneedsNew = true;\n\t\t\tif(cachedCollectorCoordinates != null) {\n\t\t\t\tneedsNew = false;\n\t\t\t\tif(supertile.getWorld().isBlockLoaded(cachedCollectorCoordinates)) {\n\t\t\t\t\tneedsNew = true;\n\t\t\t\t\tTileEntity tileAt = supertile.getWorld().getTileEntity(cachedCollectorCoordinates);\n\t\t\t\t\tif(tileAt != null && tileAt instanceof IManaCollector && !tileAt.isInvalid()) {\n\t\t\t\t\t\tlinkedCollector = tileAt;\n\t\t\t\t\t\tneedsNew = false;\n\t\t\t\t\t}\n\t\t\t\t\tcachedCollectorCoordinates = null;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tTileEntity tileAt = supertile.getWorld().getTileEntity(linkedCollector.getPos());\n\t\t\tif(tileAt != null && tileAt instanceof IManaCollector)\n\t\t\t\tlinkedCollector = tileAt;\n\t\t}\n\t\tif(needsNew && ticksExisted == 1) { // New flowers only\n\t\t\tIManaNetwork network = BotaniaAPI.internalHandler.getManaNetworkInstance();\n\t\t\tint size = network.getAllCollectorsInWorld(supertile.getWorld()).size();\n\t\t\tif(BotaniaAPI.internalHandler.shouldForceCheck() || size != sizeLastCheck) {\n\t\t\t\tlinkedCollector = network.getClosestCollector(supertile.getPos(), supertile.getWorld(), LINK_RANGE);\n\t\t\t\tsizeLastCheck = size;\n\t\t\t}\n\t\t}\n\t}\n\tpublic void linkToForcefully(TileEntity collector) {\n\t\tlinkedCollector = collector;\n\t}\n\tpublic void addMana(int mana) {\n\t\tthis.mana = Math.min(getMaxMana(), this.mana + mana);\n\t}\n\tpublic void emptyManaIntoCollector() {\n\t\tif(linkedCollector != null && isValidBinding()) {\n\t\t\tIManaCollector collector = (IManaCollector) linkedCollector;\n\t\t\tif(!collector.isFull() && mana > 0) {\n\t\t\t\tint manaval = Math.min(mana, collector.getMaxMana() - collector.getCurrentMana());\n\t\t\t\tmana -= manaval;\n\t\t\t\tcollector.recieveMana(manaval);\n\t\t\t}\n\t\t}\n\t}\n\tpublic boolean isPassiveFlower() {\n\t\treturn false;\n\t}\n\tpublic boolean shouldSyncPassiveGeneration() {\n\t\treturn false;\n\t}\n\tpublic boolean canGeneratePassively() {\n\t\treturn false;\n\t}\n\tpublic int getDelayBetweenPassiveGeneration() {\n\t\treturn 20;\n\t}\n\tpublic int getValueForPassiveGeneration() {\n\t\treturn 1;\n\t}\n\t@Override\n\tpublic List<ItemStack> getDrops(List<ItemStack> list) {\n\t\tList<ItemStack> drops = super.getDrops(list);\n\t\tpopulateDropStackNBTs(drops);\n\t\treturn drops;\n\t}\n\tpublic void populateDropStackNBTs(List<ItemStack> drops) {\n\t\tif(isPassiveFlower() && ticksExisted > 0 && BotaniaAPI.internalHandler.getPassiveFlowerDecay() > 0) {\n\t\t\tItemStack drop = drops.get(0);\n\t\t\tif(!drop.isEmpty()) {\n\t\t\t\tif(!drop.hasTagCompound())\n\t\t\t\t\tdrop.setTagCompound(new NBTTagCompound());\n\t\t\t\tNBTTagCompound cmp = drop.getTagCompound();\n\t\t\t\tcmp.setInteger(TAG_PASSIVE_DECAY_TICKS, passiveDecayTicks);\n\t\t\t}\n\t\t}\n\t}\n\t@Override\n\tpublic void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase entity, ItemStack stack) {\n\t\tsuper.onBlockPlacedBy(world, pos, state, entity, stack);\n\t\tif(isPassiveFlower()) {\n\t\t\tNBTTagCompound cmp = stack.getTagCompound();\n\t\t\tpassiveDecayTicks = cmp.getInteger(TAG_PASSIVE_DECAY_TICKS);\n\t\t}\n\t}\n\t@Override\n\tpublic boolean onWanded(EntityPlayer player, ItemStack wand) {\nNext line of code:\n"}
{"question_id": 19, "category": "longbench_lcc", "reference": [" device = Device(token=deviceToken)"], "prompt": "Please complete the code given below. \n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom HttpUtils import App, buildOpener\nclass Device(object):\n def __init__(self, token):\n self.token = token\n self.app = App()\n def check_inspection(self):\n data = self.app.check__inspection()\n return data\n def notification_postDevicetoken(self, loginId, password,\n token=None, S=\"nosessionid\"):\n if token == None:\n token = self.token\n params = {\n \"S\": S, # magic,don't touch\n \"login_id\": loginId,\n \"password\": password,\n \"token\": token.encode(\"base64\")\n }\n data = self.app.notification_post__devicetoken(params)\n return data\n def newUser(self, loginId, password):\n # self.notification_postDevicetoken(loginId, password)\n return User(self.app, loginId, password)\nclass User(object):\n def __init__(self, app, loginId, password):\n self.login_id = loginId\n self.password = password\n self.app = app\n self.session = None\n self.userId = None\n self.menu = Menu(self.app)\n self.roundtable = RoundTable(self.app)\n self.exploration = Exploration(self.app)\n def login(self):\n params = {\n \"login_id\": self.login_id,\n \"password\": self.password,\n }\n data = self.app.login(params)\n self.session = data.response.header.session_id\n self.userId = data.response.body.login.user_id\n self.cardList = data.response.header.your_data.owner_card_list.user_card\n return data\n def mainmenu(self):\n data = self.app.mainmenu()\n return data\n def endTutorial(self):\n params = {\n \"S\": self.session,\n \"step\": '8000',\n }\n data = self.app.tutorial_next(params)\n return data\n def cardUpdate(self):\n params = {\n \"S\": self.session,\n \"revision\": '0',\n }\n data = self.app.masterdata_card_update(params)\n return data\n def cardCategoryUpdate(self):\n params = {\n \"S\": self.session,\n \"revision\": '0',\n }\n data = self.app.masterdata_card__category_update(params)\n return data\n def cardComboUpdate(self):\n params = {\n \"S\": self.session,\n \"revision\": '0',\n }\n data = self.app.masterdata_combo_update(params)\n return data\nclass RoundTable(object):\n def __init__(self, app):\n self.app = app\n def edit(self):\n params = {\n \"move\": \"1\",\n }\n data = self.app.roundtable_edit(params)\n return data\n def save(self, cards, leader):\n '7803549,15208758,17258743,empty,empty,empty,empty,empty,empty,empty,empty,empty'\n '17258743'\n cards = cards + [\"empty\"]*(12-len(cards))\n params = {\n \"C\": \",\".join(cards),\n \"lr\": leader,\n }\n data = self.app.cardselect_savedeckcard(params)\n return data\nclass Menu(object):\n def __init__(self, app):\n self.app = app\n def menulist(self):\n data = self.app.menu_menulist()\n return data\n def fairyselect(self):\n data = self.app.menu_fairyselect()\n return data\n def friendlist(self, move = \"0\"):\n params = {\n \"move\": \"0\",\n }\n data = self.app.menu_friendlist(params)\n return data\n def likeUser(self, users, dialog = \"1\"):\n users = \",\".join(map(lambda x:str(x),users))\n params = {\n \"dialog\": dialog,\n \"user_id\": users,\n }\n data = self.app.friend_like__user(params)\n return data\nclass Exploration(object):\n def __init__(self, app):\n self.app = app\n def getAreaList(self):\n data = self.app.exploration_area()\n return data\n def getFloorList(self, areaId):\n params = {\n \"area_id\": areaId,\n }\n data = self.app.exploration_floor(params)\n return data\n def getFloorStatus(self, areaID, floorId, check=\"1\"):\n params = {\n \"area_id\": areaID,\n \"floor_id\": floorId,\n \"check\": check, # magic,don't touch\n }\n data = self.app.exploration_get__floor(params)\n return data\n def explore(self, areaId, floorId, autoBuild=\"1\"):\n params = {\n \"area_id\": areaId,\n \"floor_id\": floorId,\n \"auto_build\": autoBuild,\n }\n data = self.app.exploration_explore(params)\n return data\n def fairyFloor(self, serialId, userId, check=\"1\"):\n params = {\n \"serial_id\": serialId,\n \"user_id\": userId,\n \"check\": check, # magic,don't touch\n }\n data = self.app.exploration_fairy__floor(params)\n return data\n def fairybattle(self, serialId, userId):\n params = {\n \"serial_id\": serialId,\n \"user_id\": userId,\n }\n data = self.app.exploration_fairybattle(params)\n return data\n def fairyhistory(self, serialId, userId):\n params = {\n \"serial_id\": serialId,\n \"user_id\": userId,\n }\n data = self.app.exploration_fairyhistory(params)\n return data\n def fairyLose(self, serialId, userId):\n params = {\n \"serial_id\": serialId,\n \"user_id\": userId,\n }\n data = self.app.exploration_fairy__lose(params)\n return data\n def faityWin(self, serialId, userId):\n params = {\n \"serial_id\": serialId,\n \"user_id\": userId,\n }\n data = self.app.exploration_fairy__win(params)\n return data\nif __name__ == \"__main__\":\n from config import deviceToken, loginId, password\nNext line of code:\n"}
{"question_id": 20, "category": "longbench_repobench-p", "reference": [" except TextGridParseError as e:"], "prompt": "Please complete the code given below. \nmontreal_forced_aligner/exceptions.py\nclass TextParseError(CorpusReadError):\n \"\"\"\n Class for errors parsing lab and txt files\n\n Parameters\n ----------\n file_name: str\n File name that had the error\n \"\"\"\n\n def __init__(self, file_name: str):\n super().__init__(\"\")\n self.message_lines = [\n f\"There was an error decoding {self.printer.error_text(file_name)}, \"\n f\"maybe try resaving it as utf8?\"\n ]\nmontreal_forced_aligner/helper.py\ndef output_mapping(mapping: CorpusMappingType, path: str, skip_safe: bool = False) -> None:\n \"\"\"\n Helper function to save mapping information (i.e., utt2spk) in Kaldi scp format\n\n CorpusMappingType is either a dictionary of key to value for\n one-to-one mapping case and a dictionary of key to list of values for one-to-many case.\n\n See Also\n --------\n :func:`~montreal_forced_aligner.helper.save_scp`\n For another function that saves SCPs from lists\n\n Parameters\n ----------\n mapping: CorpusMappingType\n Mapping to output\n path: str\n Path to save mapping\n skip_safe: bool, optional\n Flag for whether to skip over making a string safe\n \"\"\"\n if not mapping:\n return\n with open(path, \"w\", encoding=\"utf8\") as f:\n for k in sorted(mapping.keys()):\n v = mapping[k]\n if isinstance(v, (list, set, tuple)):\n v = \" \".join(map(str, v))\n elif not skip_safe:\n v = make_scp_safe(v)\n f.write(f\"{make_scp_safe(k)} {v}\\n\")\nmontreal_forced_aligner/exceptions.py\nclass TextGridParseError(CorpusReadError):\n \"\"\"\n Class capturing TextGrid reading errors\n\n Parameters\n ----------\n file_name: str\n File name that had the error\n error: str\n Error in TextGrid file\n \"\"\"\n\n def __init__(self, file_name: str, error: str):\n super().__init__(\"\")\n self.file_name = file_name\n self.error = error\n self.message_lines.extend(\n [\n f\"Reading {self.printer.emphasized_text(file_name)} has the following error:\",\n \"\",\n \"\",\n self.error,\n ]\n )\nmontreal_forced_aligner/utils.py\nclass Stopped(object):\n \"\"\"\n Multiprocessing class for detecting whether processes should stop processing and exit ASAP\n\n Attributes\n ----------\n val: :func:`~multiprocessing.Value`\n 0 if not stopped, 1 if stopped\n lock: :class:`~multiprocessing.Lock`\n Lock for process safety\n _source: multiprocessing.Value\n 1 if it was a Ctrl+C event that stopped it, 0 otherwise\n \"\"\"\n\n def __init__(self, initval: Union[bool, int] = False):\n self.val = mp.Value(\"i\", initval)\n self.lock = mp.Lock()\n self._source = mp.Value(\"i\", 0)\n\n def stop(self) -> None:\n \"\"\"Signal that work should stop asap\"\"\"\n with self.lock:\n self.val.value = True\n\n def stop_check(self) -> int:\n \"\"\"Check whether a process should stop\"\"\"\n with self.lock:\n return self.val.value\n\n def set_sigint_source(self) -> None:\n \"\"\"Set the source as a ctrl+c\"\"\"\n with self.lock:\n self._source.value = True\n\n def source(self) -> int:\n \"\"\"Get the source value\"\"\"\n with self.lock:\n return self._source.value\nmontreal_forced_aligner/dictionary/multispeaker.py\nclass MultispeakerSanitizationFunction:\n \"\"\"\n Function for sanitizing text based on a multispeaker dictionary\n\n Parameters\n ----------\n speaker_mapping: dict[str, str]\n Mapping of speakers to dictionary names\n sanitize_function: :class:`~montreal_forced_aligner.dictionary.mixins.SanitizeFunction`\n Function to use for stripping punctuation\n split_functions: dict[str, :class:`~montreal_forced_aligner.dictionary.mixins.SplitWordsFunction`]\n Mapping of dictionary names to functions for splitting compounds and clitics into separate words\n \"\"\"\n\n speaker_mapping: Dict[str, str]\n sanitize_function: SanitizeFunction\n split_functions: Dict[str, SplitWordsFunction]\n\n def get_dict_name_for_speaker(self, speaker_name):\n if speaker_name not in self.speaker_mapping:\n speaker_name = \"default\"\n return self.speaker_mapping[speaker_name]\n\n def get_functions_for_speaker(\n self, speaker_name: str\n ) -> Tuple[SanitizeFunction, SplitWordsFunction]:\n \"\"\"\n Look up functions based on speaker name\n\n Parameters\n ----------\n speaker_name\n Speaker to get functions for\n\n Returns\n -------\n :class:`~montreal_forced_aligner.dictionary.mixins.SanitizeFunction`\n Function for sanitizing text\n :class:`~montreal_forced_aligner.dictionary.mixins.SplitWordsFunction`\n Function for splitting up words\n \"\"\"\n try:\n dict_name = self.get_dict_name_for_speaker(speaker_name)\n split_function = self.split_functions[dict_name]\n except KeyError:\n split_function = None\n return self.sanitize_function, split_function\nmontreal_forced_aligner/corpus/classes.py\nclass SpeakerCollection(Collection):\n \"\"\"\n Utility class for storing collections of speakers\n \"\"\"\n\n CLASS_TYPE = Speaker\n\n def add_speaker(self, speaker: Speaker) -> None:\n \"\"\"\n Add speaker to the collection\n\n Parameters\n ----------\n speaker: :class:`~montreal_forced_aligner.corpus.classes.Speaker`\n Speaker to be added\n \"\"\"\n self[speaker.name] = speaker\n\n def __repr__(self) -> str:\n \"\"\"Object representation\"\"\"\n return f\"<SpeakerCollection of {self._data}>\"\nmontreal_forced_aligner/corpus/classes.py\nclass File(MfaCorpusClass):\n \"\"\"\n File class for representing metadata and associations of Files\n\n Parameters\n ----------\n wav_path: str, optional\n Sound file path\n text_path: str, optional\n Transcription file path\n relative_path: str, optional\n Relative path to the corpus root\n\n Attributes\n ----------\n utterances: :class:`~montreal_forced_aligner.corpus.classes.UtteranceCollection`\n Utterances in the file\n speaker_ordering: list[Speaker]\n Ordering of speakers in the transcription file\n wav_info: :class:`~montreal_forced_aligner.data.SoundFileInformation`\n Information about sound file\n waveform: numpy.array\n Audio samples\n aligned: bool\n Flag for whether a file has alignments\n\n Raises\n ------\n :class:`~montreal_forced_aligner.exceptions.CorpusError`\n If both wav_path and text_path are None\n \"\"\"\n\n textgrid_regex = re.compile(r\"\\.textgrid$\", flags=re.IGNORECASE)\n wav_regex = re.compile(r\"\\.wav$\", flags=re.IGNORECASE)\n\n def __init__(\n self,\n wav_path: Optional[str] = None,\n text_path: Optional[str] = None,\n relative_path: Optional[str] = None,\n name: Optional[str] = None,\n ):\n self.wav_path = wav_path\n self.text_path = text_path\n wav_check = self.wav_path is not None\n text_check = self.text_path is not None\n self._name = name\n if not self._name:\n if wav_check:\n self._name = os.path.splitext(os.path.basename(self.wav_path))[0]\n elif text_check:\n self._name = os.path.splitext(os.path.basename(self.text_path))[0]\n else:\n raise CorpusError(\"File objects must have either a wav_path or text_path\")\n self.relative_path = relative_path\n self.wav_info: Optional[SoundFileInformation] = None\n self.waveform = None\n self.speaker_ordering: List[Speaker] = []\n self.utterances = UtteranceCollection()\n self.aligned = False\n if text_check:\n if self.text_path.lower().endswith(\".textgrid\"):\n self.text_type = TextFileType.TEXTGRID\n else:\n self.text_type = TextFileType.LAB\n else:\n self.text_type = TextFileType.NONE\n if wav_check:\n\n if self.wav_path.lower().endswith(\".wav\"):\n self.sound_type = SoundFileType.WAV\n else:\n self.sound_type = SoundFileType.SOX\n else:\n self.sound_type = SoundFileType.NONE\n\n @property\n def multiprocessing_data(self) -> FileData:\n \"\"\"\n Data object for the file\n \"\"\"\n return FileData(\n self._name,\n self.wav_path,\n self.text_path,\n self.relative_path,\n self.wav_info,\n [s.name for s in self.speaker_ordering],\n [u.multiprocessing_data for u in self.utterances],\n )\n\n @classmethod\n def load_from_mp_data(cls, file_data: FileData) -> File:\n \"\"\"\n Construct a File from a multiprocessing file data class\n\n Parameters\n ----------\n file_data: :class:`~montreal_forced_aligner.data.FileData`\n Data for the loaded file\n\n Returns\n -------\n :class:`~montreal_forced_aligner.corpus.classes.File`\n Loaded file\n \"\"\"\n file = File(\n file_data.wav_path,\n file_data.text_path,\n relative_path=file_data.relative_path,\n name=file_data.name,\n )\n file.wav_info = file_data.wav_info\n for s in file_data.speaker_ordering:\n file.add_speaker(Speaker(s))\n for u in file_data.utterances:\n u = Utterance.load_from_mp_data(u, file)\n file.utterances.add_utterance(u)\n return file\n\n @classmethod\n def parse_file(\n cls,\n file_name: str,\n wav_path: Optional[str],\n text_path: Optional[str],\n relative_path: str,\n speaker_characters: Union[int, str],\n sanitize_function: Optional[MultispeakerSanitizationFunction] = None,\n ):\n \"\"\"\n Parse a collection of sound file and transcription file into a File\n\n Parameters\n ----------\n file_name: str\n File identifier\n wav_path: str\n Full sound file path\n text_path: str\n Full transcription path\n relative_path: str\n Relative path from the corpus directory root\n speaker_characters: int, optional\n Number of characters in the file name to specify the speaker\n sanitize_function: Callable, optional\n Function to sanitize words and strip punctuation\n\n Returns\n -------\n :class:`~montreal_forced_aligner.corpus.classes.File`\n Parsed file\n \"\"\"\n file = File(wav_path, text_path, relative_path=relative_path, name=file_name)\n if file.has_sound_file:\n root = os.path.dirname(wav_path)\n file.wav_info = get_wav_info(wav_path)\n else:\n root = os.path.dirname(text_path)\n if not speaker_characters:\n speaker_name = os.path.basename(root)\n elif isinstance(speaker_characters, int):\n speaker_name = file_name[:speaker_characters]\n elif speaker_characters == \"prosodylab\":\n speaker_name = file_name.split(\"_\")[1]\n else:\n speaker_name = file_name\n root_speaker = None\n if speaker_characters or file.text_type != TextFileType.TEXTGRID:\n root_speaker = Speaker(speaker_name)\n file.load_text(\n root_speaker=root_speaker,\n sanitize_function=sanitize_function,\n )\n return file\n\n def __eq__(self, other: Union[File, str]) -> bool:\n \"\"\"Check if a File is equal to another File\"\"\"\n if isinstance(other, File):\n return other.name == self.name\n if isinstance(other, str):\n return self.name == other\n raise TypeError(\"Files can only be compared to other files and strings.\")\n\n def __lt__(self, other: Union[File, str]) -> bool:\n \"\"\"Check if a File is less than another File\"\"\"\n if isinstance(other, File):\n return other.name < self.name\n if isinstance(other, str):\n return self.name < other\n raise TypeError(\"Files can only be compared to other files and strings.\")\n\n def __gt__(self, other: Union[File, str]) -> bool:\n \"\"\"Check if a File is greater than another File\"\"\"\n if isinstance(other, File):\n return other.name > self.name\n if isinstance(other, str):\n return self.name > other\n raise TypeError(\"Files can only be compared to other files and strings.\")\n\n def __hash__(self) -> hash:\n \"\"\"Get the hash of the file\"\"\"\n return hash(self.name)\n\n @property\n def name(self) -> str:\n \"\"\"Name of the file\"\"\"\n name = self._name\n if self.relative_path:\n prefix = self.relative_path.replace(\"/\", \"\").replace(\"\\\\\", \"\")\n if not name.startswith(prefix):\n name = f\"{prefix}_{name}\"\n return name\n\n @property\n def is_fully_aligned(self) -> bool:\n \"\"\"\n Check if all utterances have been aligned\n \"\"\"\n for u in self.utterances:\n if u.ignored:\n continue\n if u.word_labels is None:\n return False\n if u.phone_labels is None:\n return False\n return True\n\n def __repr__(self) -> str:\n \"\"\"Representation of File objects\"\"\"\n return f'<File {self.name} Sound path=\"{self.wav_path}\" Text path=\"{self.text_path}\">'\n\n def save(\n self,\n output_directory: Optional[str] = None,\n text_type: Optional[TextFileType] = None,\n save_transcription: bool = False,\n ) -> None:\n \"\"\"\n Output File to TextGrid or lab. If ``text_type`` is not specified, the original file type will be used,\n but if there was no text file for the file, it will guess lab format if there is only one utterance, otherwise\n it will output a TextGrid file.\n\n Parameters\n ----------\n output_directory: str, optional\n Directory to output file, if None, then it will overwrite the original file\n backup_output_directory: str, optional\n If specified, then it will check whether it would overwrite an existing file and\n instead use this directory\n text_type: TextFileType, optional\n Text type to save as, if not provided, it will use either the original file type or guess the file type\n save_transcription: bool\n Flag for whether the hypothesized transcription text should be saved instead of the default text\n \"\"\"\n utterance_count = len(self.utterances)\n if text_type is None:\n text_type = self.text_type\n if text_type == TextFileType.NONE:\n if utterance_count == 1:\n text_type = TextFileType.LAB\n else:\n text_type = TextFileType.TEXTGRID\n if text_type == TextFileType.LAB:\n if utterance_count == 0 and os.path.exists(self.text_path) and not save_transcription:\n os.remove(self.text_path)\n return\n elif utterance_count == 0:\n return\n output_path = self.construct_output_path(output_directory, enforce_lab=True)\n with open(output_path, \"w\", encoding=\"utf8\") as f:\n for u in self.utterances:\n if save_transcription:\n f.write(u.transcription_text if u.transcription_text else \"\")\n else:\n f.write(u.text)\n return\n elif text_type == TextFileType.TEXTGRID:\n output_path = self.construct_output_path(output_directory)\n max_time = self.duration\n tiers = {}\n for speaker in self.speaker_ordering:\n if speaker is None:\n tiers[\"speech\"] = textgrid.IntervalTier(\"speech\", [], minT=0, maxT=max_time)\n else:\n tiers[speaker] = textgrid.IntervalTier(speaker.name, [], minT=0, maxT=max_time)\n\n tg = textgrid.Textgrid()\n tg.maxTimestamp = max_time\n for utterance in self.utterances:\n\n if utterance.speaker is None:\n speaker = \"speech\"\n else:\n speaker = utterance.speaker\n if not self.aligned:\n\n if save_transcription:\n tiers[speaker].entryList.append(\n Interval(\n start=utterance.begin,\n end=utterance.end,\n label=utterance.transcription_text\n if utterance.transcription_text\n else \"\",\n )\n )\n else:\n tiers[speaker].entryList.append(\n Interval(\n start=utterance.begin, end=utterance.end, label=utterance.text\n )\n )\n for t in tiers.values():\n tg.addTier(t)\n tg.save(output_path, includeBlankSpaces=True, format=\"long_textgrid\")\n\n @property\n def meta(self) -> Dict[str, Any]:\n \"\"\"Metadata for the File\"\"\"\n return {\n \"wav_path\": self.wav_path,\n \"text_path\": self.text_path,\n \"name\": self._name,\n \"relative_path\": self.relative_path,\n \"wav_info\": self.wav_info.meta,\n \"speaker_ordering\": [x.name for x in self.speaker_ordering],\n }\n\n @property\n def has_sound_file(self) -> bool:\n \"\"\"Flag for whether the File has a sound file\"\"\"\n return self.sound_type != SoundFileType.NONE\n\n @property\n def has_text_file(self) -> bool:\n \"\"\"Flag for whether the File has a text file\"\"\"\n return self.text_type != TextFileType.NONE\n\n @property\n def aligned_data(self) -> Dict[str, Dict[str, List[CtmInterval]]]:\n \"\"\"\n Word and phone alignments for the file\n\n Returns\n -------\n dict[str, dict[str, list[CtmInterval]]]\n Dictionary of word and phone intervals for each speaker in the file\n \"\"\"\n data = {}\n for s in self.speaker_ordering:\n if s.name not in data:\n data[s.name] = {\"words\": [], \"phones\": []}\n for u in self.utterances:\n if u.word_labels is None:\n continue\n data[u.speaker_name][\"words\"].extend(u.word_labels)\n data[u.speaker_name][\"phones\"].extend(u.phone_labels)\n return data\n\n def clean_up(self) -> None:\n \"\"\"\n Recombine words that were split up as part of initial text processing\n \"\"\"\n for u in self.utterances:\n if not u.word_labels:\n continue\n cur_ind = 0\n actual_labels = []\n dictionary = u.speaker.dictionary\n for word in u.text.split():\n splits = dictionary.lookup(word)\n b = 1000000\n e = -1\n for w in splits:\n cur = u.word_labels[cur_ind]\n if w == cur.label or cur.label == dictionary.oov_word:\n if cur.begin < b:\n b = cur.begin\n if cur.end > e:\n e = cur.end\n cur_ind += 1\n lab = CtmInterval(b, e, word, u.name)\n actual_labels.append(lab)\n u.word_labels = actual_labels\n u.phone_labels = [\n x for x in u.phone_labels if x.label != dictionary.optional_silence_phone\n ]\n\n def construct_output_path(\n self,\n output_directory: Optional[str] = None,\n enforce_lab: bool = False,\n ) -> str:\n \"\"\"\n Construct the output path for the File\n\n Parameters\n ----------\n output_directory: str, optional\n Directory to output to, if None, it will overwrite the original file\n enforce_lab: bool\n Flag for whether to enforce generating a lab file over a TextGrid\n\n Returns\n -------\n str\n Output path\n \"\"\"\n if enforce_lab:\n extension = \".lab\"\n else:\n extension = \".TextGrid\"\n if output_directory is None:\n if self.text_path is None:\n return os.path.splitext(self.wav_path)[0] + extension\n return self.text_path\n if self.relative_path:\n relative = os.path.join(output_directory, self.relative_path)\n else:\n relative = output_directory\n tg_path = os.path.join(relative, self._name + extension)\n os.makedirs(os.path.dirname(tg_path), exist_ok=True)\n return tg_path\n\n def load_text(\n self,\n root_speaker: Optional[Speaker] = None,\n sanitize_function: Optional[MultispeakerSanitizationFunction] = None,\n ) -> None:\n \"\"\"\n Load the transcription text from the text_file of the object\n\n Parameters\n ----------\n root_speaker: :class:`~montreal_forced_aligner.corpus.classes.Speaker`, optional\n Speaker derived from the root directory, ignored for TextGrids\n sanitize_function: :class:`~montreal_forced_aligner.dictionary.mixins.SanitizeFunction`, optional\n Function to sanitize words and strip punctuation\n \"\"\"\n if self.text_type == TextFileType.LAB:\n try:\n text = load_text(self.text_path)\n except UnicodeDecodeError:\n raise TextParseError(self.text_path)\n utterance = Utterance(speaker=root_speaker, file=self, text=text)\n utterance.parse_transcription(sanitize_function)\n self.add_utterance(utterance)\n elif self.text_type == TextFileType.TEXTGRID:\n try:\n tg = textgrid.openTextgrid(self.text_path, includeEmptyIntervals=False)\n except Exception:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n raise TextGridParseError(\n self.text_path,\n \"\\n\".join(traceback.format_exception(exc_type, exc_value, exc_traceback)),\n )\n\n num_tiers = len(tg.tierNameList)\n if num_tiers == 0:\n raise TextGridParseError(self.text_path, \"Number of tiers parsed was zero\")\n if self.num_channels > 2:\n raise (Exception(\"More than two channels\"))\n for tier_name in tg.tierNameList:\n ti = tg.tierDict[tier_name]\n if tier_name.lower() == \"notes\":\n continue\n if not isinstance(ti, textgrid.IntervalTier):\n continue\n if not root_speaker:\n speaker_name = tier_name.strip()\n speaker = Speaker(speaker_name)\n self.add_speaker(speaker)\n else:\n speaker = root_speaker\n for begin, end, text in ti.entryList:\n text = text.lower().strip()\n if not text:\n continue\n begin, end = round(begin, 4), round(end, 4)\n end = min(end, self.duration)\n utt = Utterance(speaker=speaker, file=self, begin=begin, end=end, text=text)\n utt.parse_transcription(sanitize_function)\n if not utt.text:\n continue\n self.add_utterance(utt)\n else:\n utterance = Utterance(speaker=root_speaker, file=self)\n self.add_utterance(utterance)\n\n def add_speaker(self, speaker: Speaker) -> None:\n \"\"\"\n Add a speaker to a file\n\n Parameters\n ----------\n speaker: :class:`~montreal_forced_aligner.corpus.classes.Speaker`\n Speaker to add\n \"\"\"\n if speaker not in self.speaker_ordering:\n self.speaker_ordering.append(speaker)\n\n def add_utterance(self, utterance: Utterance) -> None:\n \"\"\"\n Add an utterance to a file\n\n Parameters\n ----------\n utterance: :class:`~montreal_forced_aligner.corpus.classes.Utterance`\n Utterance to add\n \"\"\"\n self.utterances.add_utterance(utterance)\n self.add_speaker(utterance.speaker)\n\n def delete_utterance(self, utterance: Utterance) -> None:\n \"\"\"\n Delete an utterance from the file\n\n Parameters\n ----------\n utterance: :class:`~montreal_forced_aligner.corpus.classes.Utterance`\n Utterance to remove\n \"\"\"\n identifier = utterance.name\n del self.utterances[identifier]\n\n def load_info(self) -> None:\n \"\"\"\n Load sound file info if it hasn't been already\n \"\"\"\n if self.wav_path is not None:\n self.wav_info = get_wav_info(self.wav_path)\n\n @property\n def duration(self) -> float:\n \"\"\"Get the duration of the sound file\"\"\"\n if self.wav_path is None:\n return 0\n if not self.wav_info:\n self.load_info()\n return self.wav_info.duration\n\n @property\n def num_channels(self) -> int:\n \"\"\"Get the number of channels of the sound file\"\"\"\n if self.wav_path is None:\n return 0\n if not self.wav_info:\n self.load_info()\n return self.wav_info.num_channels\n\n @property\n def num_utterances(self) -> int:\n \"\"\"Get the number of utterances for the sound file\"\"\"\n return len(self.utterances)\n\n @property\n def num_speakers(self) -> int:\n \"\"\"Get the number of speakers in the sound file\"\"\"\n return len(self.speaker_ordering)\n\n @property\n def sample_rate(self) -> int:\n \"\"\"Get the sample rate of the sound file\"\"\"\n if self.wav_path is None:\n return 0\n if not self.wav_info:\n self.load_info()\n return self.wav_info.sample_rate\n\n @property\n def format(self) -> str:\n \"\"\"Get the sound file format\"\"\"\n if not self.wav_info:\n self.load_info()\n return self.wav_info.format\n\n @property\n def sox_string(self) -> str:\n \"\"\"String used for converting sound file via SoX within Kaldi\"\"\"\n if not self.wav_info:\n self.load_info()\n return self.wav_info.sox_string\n\n def load_wav_data(self) -> None:\n \"\"\"\n Load the sound file into memory as a numpy array\n \"\"\"\n self.waveform, _ = librosa.load(self.wav_path, sr=None, mono=False)\n\n def normalized_waveform(\n self, begin: float = 0, end: Optional[float] = None\n ) -> Tuple[np.array, np.array]:\n if self.waveform is None:\n self.load_wav_data()\n if end is None or end > self.duration:\n end = self.duration\n\n begin_sample = int(begin * self.sample_rate)\n end_sample = int(end * self.sample_rate)\n if len(self.waveform.shape) > 1 and self.waveform.shape[0] == 2:\n y = self.waveform[:, begin_sample:end_sample] / np.max(\n np.abs(self.waveform[:, begin_sample:end_sample]), axis=0\n )\n y[np.isnan(y)] = 0\n else:\n y = self.waveform[begin_sample:end_sample] / np.max(\n np.abs(self.waveform[begin_sample:end_sample]), axis=0\n )\n x = np.arange(start=begin_sample, stop=end_sample) / self.sample_rate\n return x, y\n\n def for_wav_scp(self) -> str:\n \"\"\"\n Generate the string to use in feature generation\n\n Returns\n -------\n str\n SoX string if necessary, the sound file path otherwise\n \"\"\"\n if self.sox_string:\n return self.sox_string\n return self.wav_path\nmontreal_forced_aligner/corpus/classes.py\nclass UtteranceCollection(Collection):\n \"\"\"\n Utility class for storing collections of speakers\n \"\"\"\n\n CLASS_TYPE = Utterance\n\n def add_utterance(self, utterance: Utterance) -> None:\n \"\"\"\n Add utterance to the collection\n\n Parameters\n ----------\n speaker: :class:`~montreal_forced_aligner.corpus.classes.Utterance`\n Utterance to be added\n \"\"\"\n self[utterance.name] = utterance\n\n def __iter__(self) -> Generator[Utterance]:\n \"\"\"Iterator over the collection\"\"\"\n for v in self._data.values():\n if v.ignored:\n continue\n yield v\n\n def __repr__(self) -> str:\n \"\"\"Object representation\"\"\"\n return f\"<UtteranceCollection of {self._data}>\"\nmontreal_forced_aligner/corpus/classes.py\nclass Utterance(MfaCorpusClass):\n \"\"\"\n Class for information about specific utterances\n\n Parameters\n ----------\n speaker: :class:`~montreal_forced_aligner.corpus.classes.Speaker`\n Speaker of the utterance\n file: :class:`~montreal_forced_aligner.corpus.classes.File`\n File that the utterance belongs to\n begin: float, optional\n Start time of the utterance,\n if None, then the utterance is assumed to start at 0\n end: float, optional\n End time of the utterance,\n if None, then the utterance is assumed to end at the end of the File\n channel: int, optional\n Channel in the file, if None, then assumed to be the first/only channel\n text: str, optional\n Text transcription of the utterance\n\n Attributes\n ----------\n file_name: str\n Saved File.name property for reconstructing objects following serialization\n speaker_name: str\n Saved Speaker.name property for reconstructing objects following serialization\n transcription_text: str, optional\n Output of transcription is saved here\n ignored: bool\n The ignored flag is set if feature generation does not work for this utterance, or it is too short to\n be processed by Kaldi\n features: str, optional\n Feature string reference to the computed features archive\n phone_labels: list[:class:`~montreal_forced_aligner.data.CtmInterval`], optional\n Saved aligned phone labels\n word_labels: list[:class:`~montreal_forced_aligner.data.CtmInterval`], optional\n Saved aligned word labels\n oovs: list[str]\n Words not found in the dictionary for this utterance\n \"\"\"\n\n def __init__(\n self,\n speaker: Speaker,\n file: File,\n begin: Optional[float] = None,\n end: Optional[float] = None,\n channel: Optional[int] = 0,\n text: Optional[str] = None,\n ):\n self.speaker = speaker\n self.file = file\n self.file_name = file.name\n self.speaker_name: str = speaker.name\n if begin is None:\n begin = 0\n if end is None:\n end = self.file.duration\n self.begin = begin\n self.end = end\n self.channel = channel\n self.text = text\n self.transcription_text = None\n self.ignored = False\n self.features = None\n self.phone_labels: Optional[List[CtmInterval]] = None\n self.word_labels: Optional[List[CtmInterval]] = None\n self.reference_phone_labels: Optional[List[CtmInterval]] = []\n self.oovs = set()\n self.normalized_text = []\n self.text_int = []\n self.alignment_log_likelihood = None\n self.word_error_rate = None\n self.character_error_rate = None\n self.phone_error_rate = None\n self.alignment_score = None\n\n def parse_transcription(self, sanitize_function=Optional[MultispeakerSanitizationFunction]):\n \"\"\"\n Parse an orthographic transcription given punctuation and clitic markers\n\n Parameters\n ----------\n sanitize_function: :class:`~montreal_forced_aligner.dictionary.multispeaker.MultispeakerSanitizationFunction`, optional\n Function to sanitize words and strip punctuation\n\n \"\"\"\n self.normalized_text = []\n if sanitize_function is not None:\n try:\n sanitize, split = sanitize_function.get_functions_for_speaker(self.speaker_name)\n except AttributeError:\n sanitize = sanitize_function\n split = None\n words = [\n sanitize(w)\n for w in self.text.split()\n if w and w not in sanitize.clitic_markers + sanitize.compound_markers\n ]\n self.text = \" \".join(words)\n if split is not None:\n for w in words:\n for new_w in split(w):\n if not new_w:\n continue\n if split.word_set is not None and new_w not in split.word_set:\n self.oovs.add(new_w)\n self.normalized_text.append(new_w)\n\n @property\n def multiprocessing_data(self):\n return UtteranceData(\n self.speaker_name,\n self.file_name,\n self.begin,\n self.end,\n self.channel,\n self.text,\n self.normalized_text,\n self.oovs,\n )\n\n @classmethod\n def load_from_mp_data(cls, data: UtteranceData, file: File) -> Utterance:\n utterance = Utterance(\n speaker=Speaker(data.speaker_name),\n file=file,\n begin=data.begin,\n end=data.end,\n channel=data.channel,\n text=data.text,\n )\n if data.normalized_text:\n utterance.normalized_text = data.normalized_text\n utterance.oovs = data.oovs\n return utterance\n\n def __str__(self) -> str:\n \"\"\"String representation\"\"\"\n return self.name\n\n def __repr__(self) -> str:\n \"\"\"Object representation\"\"\"\n return f'<Utterance \"{self.name}\">'\n\n def __eq__(self, other: Union[Utterance, str]) -> bool:\n \"\"\"Check if an Utterance is equal to another Utterance\"\"\"\n if isinstance(other, Utterance):\n return other.name == self.name\n if isinstance(other, str):\n return self.name == other\n raise TypeError(\"Utterances can only be compared to other utterances and strings.\")\n\n def __lt__(self, other: Union[Utterance, str]) -> bool:\n \"\"\"Check if an Utterance is less than another Utterance\"\"\"\n if isinstance(other, Utterance):\n return other.name < self.name\n if isinstance(other, str):\n return self.name < other\n raise TypeError(\"Utterances can only be compared to other utterances and strings.\")\n\n def __gt__(self, other: Union[Utterance, str]) -> bool:\n \"\"\"Check if an Utterance is greater than another Utterance\"\"\"\n if isinstance(other, Utterance):\n return other.name > self.name\n if isinstance(other, str):\n return self.name > other\n raise TypeError(\"Utterances can only be compared to other utterances and strings.\")\n\n def __hash__(self) -> hash:\n \"\"\"Compute the hash of this function\"\"\"\n return hash(self.name)\n\n @property\n def duration(self) -> float:\n \"\"\"Duration of the utterance\"\"\"\n if self.begin is not None and self.end is not None:\n return self.end - self.begin\n return self.file.duration\n\n @property\n def meta(self) -> Dict[str, Any]:\n \"\"\"Metadata dictionary for the utterance\"\"\"\n return {\n \"speaker\": self.speaker.name,\n \"file\": self.file.name,\n \"begin\": self.begin,\n \"end\": self.end,\n \"channel\": self.channel,\n \"text\": self.text,\n \"ignored\": self.ignored,\n \"features\": self.features,\n \"normalized_text\": self.normalized_text,\n \"oovs\": self.oovs,\n \"transcription_text\": self.transcription_text,\n \"reference_phone_labels\": self.reference_phone_labels,\n \"phone_labels\": self.phone_labels,\n \"word_labels\": self.word_labels,\n \"word_error_rate\": self.word_error_rate,\n \"character_error_rate\": self.character_error_rate,\n \"phone_error_rate\": self.phone_error_rate,\n \"alignment_score\": self.alignment_score,\n \"alignment_log_likelihood\": self.alignment_log_likelihood,\n }\n\n def set_speaker(self, speaker: Speaker) -> None:\n \"\"\"\n Set the speaker of the utterance and updates other objects\n\n Parameters\n ----------\n speaker: :class:`~montreal_forced_aligner.corpus.classes.Speaker`\n New speaker\n \"\"\"\n self.speaker = speaker\n self.speaker.add_utterance(self)\n self.file.add_utterance(self)\n\n @property\n def is_segment(self) -> bool:\n \"\"\"Check if this utterance is a segment of a longer file\"\"\"\n return (\n self.begin is not None\n and self.end is not None\n and self.begin != 0\n and self.end != self.file.duration\n )\n\n def add_word_intervals(self, intervals: Union[CtmInterval, List[CtmInterval]]) -> None:\n \"\"\"\n Add aligned word intervals for the utterance\n\n Parameters\n ----------\n intervals: Union[CtmInterval, list[CtmInterval]]\n Intervals to add\n \"\"\"\n if not isinstance(intervals, list):\n intervals = [intervals]\n if self.word_labels is None:\n self.word_labels = []\n if self.is_segment:\n for interval in intervals:\n interval.shift_times(self.begin)\n self.word_labels = intervals\n\n def add_phone_intervals(self, intervals: Union[CtmInterval, List[CtmInterval]]) -> None:\n \"\"\"\n Add aligned phone intervals for the utterance\n\n Parameters\n ----------\n intervals: Union[CtmInterval, list[CtmInterval]]\n Intervals to add\n \"\"\"\n if not isinstance(intervals, list):\n intervals = [intervals]\n if self.phone_labels is None:\n self.phone_labels = []\n if self.is_segment:\n for interval in intervals:\n interval.shift_times(self.begin)\n self.phone_labels = intervals\n\n def text_for_scp(self) -> List[str]:\n \"\"\"\n Generate the text for exporting to Kaldi's text scp\n\n Returns\n -------\n list[str]\n List of words\n \"\"\"\n return self.text.split()\n\n def text_int_for_scp(self) -> Optional[List[int]]:\n \"\"\"\n Generate the text for exporting to Kaldi's text int scp\n\n Returns\n -------\n list[int]\n List of word IDs, or None if the utterance's speaker doesn't have an associated dictionary\n \"\"\"\n if self.speaker.dictionary is None:\n return\n if self.text_int:\n return self.text_int\n if self.normalized_text:\n normalized = True\n text = self.normalized_text\n else:\n normalized = False\n text = self.text_for_scp()\n self.text_int = []\n for i, t in enumerate(text):\n lookup = self.speaker.dictionary.to_int(t, normalized)\n if self.speaker.dictionary.oov_int in lookup:\n self.oovs.add(text[i])\n self.text_int.extend(lookup)\n return self.text_int\n\n def segment_for_scp(self) -> List[Any]:\n \"\"\"\n Generate data for Kaldi's segments scp file\n\n Returns\n -------\n list[Any]\n Segment data\n \"\"\"\n return [self.file_name.replace(\" \", \"_MFASPACE_\"), self.begin, self.end, self.channel]\n\n @property\n def name(self) -> str:\n \"\"\"The name of the utterance\"\"\"\n base = f\"{self.file_name}\"\n base = base.replace(\" \", \"-space-\").replace(\".\", \"-\").replace(\"_\", \"-\")\n if not base.startswith(f\"{self.speaker_name}-\"):\n base = f\"{self.speaker_name}-\" + base\n if self.is_segment:\n base = f\"{base}-{self.begin}-{self.end}\"\n return base.replace(\" \", \"-space-\").replace(\".\", \"-\").replace(\"_\", \"-\")\nmontreal_forced_aligner/corpus/classes.py\nclass FileCollection(Collection):\n \"\"\"\n Utility class for storing collections of speakers\n \"\"\"\n\n CLASS_TYPE = File\n\n def __init__(self):\n super(FileCollection, self).__init__()\n self.lab_count = 0\n self.textgrid_count = 0\n self.sound_file_count = 0\n\n def add_file(self, file: File) -> None:\n \"\"\"\n Add file to the collection\n\n Parameters\n ----------\n speaker: :class:`~montreal_forced_aligner.corpus.classes.File`\n File to be added\n \"\"\"\n self[file.name] = file\n if file.text_type == TextFileType.TEXTGRID:\n self.textgrid_count += 1\n elif file.text_type == TextFileType.LAB:\n self.lab_count += 1\n if file.sound_type != SoundFileType.NONE:\n self.sound_file_count += 1\n\n def __repr__(self) -> str:\n \"\"\"Object representation\"\"\"\n return f\"<FileCollection of {self._data}>\"\nimport multiprocessing as mp\nimport os\nimport sys\nimport traceback\nfrom queue import Empty\nfrom typing import TYPE_CHECKING, Any, Collection, Dict, Generator, List, Optional, Set, Union\nfrom montreal_forced_aligner.corpus.classes import (\n File,\n FileCollection,\n SpeakerCollection,\n Utterance,\n UtteranceCollection,\n)\nfrom montreal_forced_aligner.dictionary.multispeaker import MultispeakerSanitizationFunction\nfrom montreal_forced_aligner.exceptions import TextGridParseError, TextParseError\nfrom montreal_forced_aligner.helper import output_mapping\nfrom montreal_forced_aligner.utils import Stopped\n from montreal_forced_aligner.abc import OneToManyMappingType, OneToOneMappingType\n from montreal_forced_aligner.corpus.helper import SoundFileInfoDict\n from montreal_forced_aligner.corpus.classes import Speaker\n from montreal_forced_aligner.dictionary import PronunciationDictionaryMixin\n\"\"\"\nCorpus loading worker\n---------------------\n\"\"\"\nfrom __future__ import annotations\n\n\n\nif TYPE_CHECKING:\n\n FileInfoDict = Dict[\n str, Union[str, SoundFileInfoDict, OneToOneMappingType, OneToManyMappingType]\n ]\n\n\n__all__ = [\"CorpusProcessWorker\", \"Job\"]\n\n\nclass CorpusProcessWorker(mp.Process):\n \"\"\"\n Multiprocessing corpus loading worker\n\n Attributes\n ----------\n job_q: :class:`~multiprocessing.Queue`\n Job queue for files to process\n return_dict: dict\n Dictionary to catch errors\n return_q: :class:`~multiprocessing.Queue`\n Return queue for processed Files\n stopped: :class:`~montreal_forced_aligner.utils.Stopped`\n Stop check for whether corpus loading should exit\n finished_adding: :class:`~montreal_forced_aligner.utils.Stopped`\n Signal that the main thread has stopped adding new files to be processed\n \"\"\"\n\n def __init__(\n self,\n name: int,\n job_q: mp.Queue,\n return_dict: dict,\n return_q: mp.Queue,\n stopped: Stopped,\n finished_adding: Stopped,\n speaker_characters: Union[int, str],\n sanitize_function: Optional[MultispeakerSanitizationFunction],\n ):\n mp.Process.__init__(self)\n self.name = str(name)\n self.job_q = job_q\n self.return_dict = return_dict\n self.return_q = return_q\n self.stopped = stopped\n self.finished_adding = finished_adding\n self.finished_processing = Stopped()\n self.sanitize_function = sanitize_function\n self.speaker_characters = speaker_characters\n\n def run(self) -> None:\n \"\"\"\n Run the corpus loading job\n \"\"\"\n\n while True:\n try:\n file_name, wav_path, text_path, relative_path = self.job_q.get(timeout=1)\n except Empty:\n if self.finished_adding.stop_check():\n break\n continue\n self.job_q.task_done()\n if self.stopped.stop_check():\n continue\n try:\n file = File.parse_file(\n file_name,\n wav_path,\n text_path,\n relative_path,\n self.speaker_characters,\n self.sanitize_function,\n )\n\n self.return_q.put(file.multiprocessing_data)\n except TextParseError as e:\n self.return_dict[\"decode_error_files\"].append(e)\nNext line of code:\n"}