Datasets:
prompt stringclasses 1
value | query stringlengths 18 82 | pos listlengths 1 19 | neg listlengths 1 19 |
|---|---|---|---|
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python resize image if size valid | [
"def resize(self, size):\n \"\"\"Return a new Image instance with the given size.\"\"\"\n return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))",
"def resize(self, size):\n \"\"\"Return a new Image instance with the given size.\"\"\"\n return Image(self.pil_image.resize(size, ... | [
"def _width_is_big_enough(image, width):\n \"\"\"Check that the image width is superior to `width`\"\"\"\n if width > image.size[0]:\n raise ImageSizeError(image.size[0], width)",
"def _width_is_big_enough(image, width):\n \"\"\"Check that the image width is superior to `width`\"\"\"\n if width... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python send dual-format email with sender | [
"def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):\n \"\"\" Send email message via Flask-Sendmail.\n\n Args:\n recipient: Email address or tuple of (Name, Email-address).\n subject: Subject line.\n html_message: Th... | [
"def email_user(self, subject, message, from_email=None):\n \"\"\" Send an email to this User.\"\"\"\n send_mail(subject, message, from_email, [self.email])",
"def __validate_email(self, email):\n \"\"\"Checks if a string looks like an email address\"\"\"\n\n e = re.match(self.EMAIL_AD... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python validate request against schema | [
"def validate(raw_schema, target=None, **kwargs):\n \"\"\"\n Given the python representation of a JSONschema as defined in the swagger\n spec, validate that the schema complies to spec. If `target` is provided,\n that target will be validated against the provided schema.\n \"\"\"\n schema = schem... | [
"def load_schema(schema_path):\n \"\"\"Prepare the api specification for request and response validation.\n\n :returns: a mapping from :class:`RequestMatcher` to :class:`ValidatorMap`\n for every operation in the api specification.\n :rtype: dict\n \"\"\"\n with open(schema_path, 'r') as schem... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python handle null response retry on method safety | [
"def _call_retry(self, force_retry):\n \"\"\"Call request and retry up to max_attempts times (or none if self.max_attempts=1)\"\"\"\n last_exception = None\n for i in range(self.max_attempts):\n try:\n log.info(\"Calling %s %s\" % (self.method, self.url))\n ... | [
"def safe_call(cls, method, *args):\n \"\"\" Call a remote api method but don't raise if an error occurred.\"\"\"\n return cls.call(method, *args, safe=True)",
"def safe_call(cls, method, *args):\n \"\"\" Call a remote api method but don't raise if an error occurred.\"\"\"\n return cls... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python find first 1 in array of 0s and 1s | [
"def find_start_point(self):\n \"\"\"\n Find the first location in our array that is not empty\n \"\"\"\n for i, row in enumerate(self.data):\n for j, _ in enumerate(row):\n if self.data[i, j] != 0: # or not np.isfinite(self.data[i,j]):\n ret... | [
"def _first_and_last_element(arr):\n \"\"\"Returns first and last element of numpy array or sparse matrix.\"\"\"\n if isinstance(arr, np.ndarray) or hasattr(arr, 'data'):\n # numpy array or sparse matrix with .data attribute\n data = arr.data if sparse.issparse(arr) else arr\n return data... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python guess text encoding multilingual | [
"def guess_encoding(text, default=DEFAULT_ENCODING):\n \"\"\"Guess string encoding.\n\n Given a piece of text, apply character encoding detection to\n guess the appropriate encoding of the text.\n \"\"\"\n result = chardet.detect(text)\n return normalize_result(result, default=default)",
"def gu... | [
"def to_string(s, encoding='utf-8'):\n \"\"\"\n Accept unicode(py2) or bytes(py3)\n\n Returns:\n py2 type: str\n py3 type: str\n \"\"\"\n if six.PY2:\n return s.encode(encoding)\n if isinstance(s, bytes):\n return s.decode(encoding)\n return s",
"def _multilingual(... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python average multiple arrays element-wise | [
"def average_arrays(arrays: List[mx.nd.NDArray]) -> mx.nd.NDArray:\n \"\"\"\n Take a list of arrays of the same shape and take the element wise average.\n\n :param arrays: A list of NDArrays with the same shape that will be averaged.\n :return: The average of the NDArrays in the same context as arrays[0... | [
"def average(arr):\n \"\"\"average of the values, must have more than 0 entries.\n\n :param arr: list of numbers\n :type arr: number[] a number array\n :return: average\n :rtype: float\n\n \"\"\"\n if len(arr) == 0:\n sys.stderr.write(\"ERROR: no content in array to take average\\n\")\n sys.exit()\n i... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python reverse sort dict return tuple | [
"def revrank_dict(dict, key=lambda t: t[1], as_tuple=False):\n \"\"\" Reverse sorts a #dict by a given key, optionally returning it as a\n #tuple. By default, the @dict is sorted by it's value.\n\n @dict: the #dict you wish to sorts\n @key: the #sorted key to use\n @as_tuple: returns ... | [
"def __reversed__(self):\n \"\"\"\n Return a reversed iterable over the items in the dictionary. Items are\n iterated over in their reverse sort order.\n\n Iterating views while adding or deleting entries in the dictionary may\n raise a RuntimeError or fail to iterate over all ent... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python map mixed join columns to left right lists | [
"def get_join_cols(by_entry):\n \"\"\" helper function used for joins\n builds left and right join list for join function\n \"\"\"\n left_cols = []\n right_cols = []\n for col in by_entry:\n if isinstance(col, str):\n left_cols.append(col)\n right_cols.append(col)\n else:\n left_cols.appe... | [
"def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n left_as='left', right_as='right'):\n \"\"\" Performs a join using the union join function. \"\"\"\n return join(left, right, how, key, left_key, right_key,\n join_fn=make_union_join(left_as, right_as))",
... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python restore classifier from file | [
"def load(self, filename='classifier.dump'):\n \"\"\"\n Unpickles the classifier used\n \"\"\"\n ifile = open(filename, 'r+')\n self.classifier = pickle.load(ifile)\n ifile.close()",
"def load(self, filename='classifier.dump'):\n \"\"\"\n Unpickles the class... | [
"def _restore_seq_field_pickle(checked_class, item_type, data):\n \"\"\"Unpickling function for auto-generated PVec/PSet field types.\"\"\"\n type_ = _seq_field_types[checked_class, item_type]\n return _restore_pickle(type_, data)"
] |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python reopen connection silent failure rollback | [
"def reopen(self):\n \"\"\"Reopen the tough connection.\n\n It will not complain if the connection cannot be reopened.\n\n \"\"\"\n try:\n self._con.reopen()\n except Exception:\n if self._transcation:\n self._transaction = False\n ... | [
"def rollback(self):\n\t\t\"\"\"\n\t\tRollback MySQL Transaction to database.\n\t\tMySQLDB: If the database and tables support transactions, this rolls \n\t\tback (cancels) the current transaction; otherwise a \n\t\tNotSupportedError is raised.\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 5/12/2008\n\t\t\"\"\"\n\t... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python stream file in chunks memory efficient | [
"def load_streams(chunks):\n \"\"\"\n Given a gzipped stream of data, yield streams of decompressed data.\n \"\"\"\n chunks = peekable(chunks)\n while chunks:\n if six.PY3:\n dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)\n else:\n dc = zlib.decompressobj(zlib.... | [
"def read_full(stream):\n \"\"\"Read the full contents of the given stream into memory.\n\n :return:\n A future containing the complete stream contents.\n \"\"\"\n assert stream, \"stream is required\"\n\n chunks = []\n chunk = yield stream.read()\n\n while chunk:\n chunks.append(... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python find min ignoring nans | [
"def fn_min(self, a, axis=None):\n \"\"\"\n Return the minimum of an array, ignoring any NaNs.\n\n :param a: The array.\n :return: The minimum value of the array.\n \"\"\"\n\n return numpy.nanmin(self._to_ndarray(a), axis=axis)",
"def fn_min(self, a, axis=None):\n ... | [
"def findMin(arr):\n \"\"\"\n in comparison to argrelmax() more simple and reliable peak finder\n \"\"\"\n out = np.zeros(shape=arr.shape, dtype=bool)\n _calcMin(arr, out)\n return out",
"def SegmentMin(a, ids):\n \"\"\"\n Segmented min op.\n \"\"\"\n func = lambda idxs: np.amin(a[i... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python format time to HH:MM:SS | [
"def format_time(time):\n \"\"\" Formats the given time into HH:MM:SS \"\"\"\n h, r = divmod(time / 1000, 3600)\n m, s = divmod(r, 60)\n\n return \"%02d:%02d:%02d\" % (h, m, s)",
"def format_time(time):\n \"\"\" Formats the given time into HH:MM:SS \"\"\"\n h, r = divmod(time / 1000, 3600)\n ... | [
"def format_time(timestamp):\n \"\"\"Formats timestamp to human readable format\"\"\"\n format_string = '%Y_%m_%d_%Hh%Mm%Ss'\n formatted_time = datetime.datetime.fromtimestamp(timestamp).strftime(format_string)\n return formatted_time",
"def solr_to_date(d):\n \"\"\" converts YYYY-MM-DDT00:00:00Z t... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python convert keys to snake case | [
"def keys_to_snake_case(camel_case_dict):\n \"\"\"\n Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on\n each of the keys in the dictionary and returns a new dictionary.\n\n :param camel_case_dict: Dictionary with the keys to convert.\n :type camel... | [
"def _snake_to_camel_case(value):\n \"\"\"Convert snake case string to camel case.\"\"\"\n words = value.split(\"_\")\n return words[0] + \"\".join(map(str.capitalize, words[1:]))",
"def _snake_to_camel_case(value):\n \"\"\"Convert snake case string to camel case.\"\"\"\n words = value.split(\"_\")... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python flush cache age and hash | [
"def Flush(self):\n \"\"\"Flush all items from cache.\"\"\"\n while self._age:\n node = self._age.PopLeft()\n self.KillObject(node.data)\n\n self._hash = dict()",
"def Flush(self):\n \"\"\"Flush all items from cache.\"\"\"\n while self._age:\n node = self._age.PopLeft()\n self.K... | [
"def ExpireObject(self, key):\n \"\"\"Expire a specific object from cache.\"\"\"\n node = self._hash.pop(key, None)\n if node:\n self._age.Unlink(node)\n self.KillObject(node.data)\n\n return node.data",
"def flush(self):\n \"\"\"\n Flush all unwritten data to disk.\n ... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python get assets path from current file | [
"def relpath(path):\n \"\"\"Path helper, gives you a path relative to this file\"\"\"\n return os.path.normpath(\n os.path.join(os.path.abspath(os.path.dirname(__file__)), path)\n )",
"def default_static_path():\n \"\"\"\n Return the path to the javascript bundle\n \"\"\"\n fdir = ... | [
"def _rel(self, path):\n \"\"\"\n Get the relative path for the given path from the current\n file by working around https://bugs.python.org/issue20012.\n \"\"\"\n return os.path.relpath(\n str(path), self._parent).replace(os.path.sep, '/')",
"def rel_path(filename):\... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python find peaks in data | [
"def findMax(arr):\n \"\"\"\n in comparison to argrelmax() more simple and reliable peak finder\n \"\"\"\n out = np.zeros(shape=arr.shape, dtype=bool)\n _calcMax(arr, out)\n return out",
"def findMax(arr):\n \"\"\"\n in comparison to argrelmax() more simple and reliable peak finder\n ... | [
"def view_extreme_groups(token, dstore):\n \"\"\"\n Show the source groups contributing the most to the highest IML\n \"\"\"\n data = dstore['disagg_by_grp'].value\n data.sort(order='extreme_poe')\n return rst_table(data[::-1])",
"def find_frequencies(data, freq=44100, bits=16):\n \"\"\"Conve... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python check row field completeness | [
"def _check_list_len(row, length):\n \"\"\"\n Sanity check for csv parser\n :param row\n :param length\n :return:None\n \"\"\"\n if len(row) != length:\n raise Exception(\n \"row length does not match expected length of \" +\n ... | [
"def selecttrue(table, field, complement=False):\n \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n return select(table, field, lambda v: bool(v), complement=complement)",
"def selecttrue(table, field, complement=False):\n \"\"\"Select rows where the given field evaluates `True`.\"\"\"... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python close HDF5 group object | [
"def _closeResources(self):\n \"\"\" Closes the root Dataset.\n \"\"\"\n logger.info(\"Closing: {}\".format(self._fileName))\n self._h5Group.close()\n self._h5Group = None",
"def _closeResources(self):\n \"\"\" Closes the root Dataset.\n \"\"\"\n logger.info... | [
"def hdf5_to_dict(filepath, group='/'):\n \"\"\"load the content of an hdf5 file to a dict.\n\n # TODO: how to split domain_type_dev : parameter : value ?\n \"\"\"\n if not h5py.is_hdf5(filepath):\n raise RuntimeError(filepath, 'is not a valid HDF5 file.')\n\n with h5py.File(filepath, 'r') as ... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python release resource with error check | [
"def release(self):\n \"\"\"\n Releases this resource back to the pool it came from.\n \"\"\"\n if self.errored:\n self.pool.delete_resource(self)\n else:\n self.pool.release(self)",
"def release(self):\n \"\"\"\n Releases this resource back t... | [
"def _check_update_(self):\n \"\"\"Check if the current version of the library is outdated.\"\"\"\n try:\n data = requests.get(\"https://pypi.python.org/pypi/jira/json\", timeout=2.001).json()\n\n released_version = data['info']['version']\n if parse_version(released_v... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python execute method until false return | [
"def execute_until_false(method, interval_s): # pylint: disable=invalid-name\n \"\"\"Executes a method forever until the method returns a false value.\n\n Args:\n method: The callable to execute.\n interval_s: The number of seconds to start the execution after each method\n finishes.\n Returns:\n ... | [
"def execute_only_once():\n \"\"\"\n Each called in the code to this function is guaranteed to return True the\n first time and False afterwards.\n\n Returns:\n bool: whether this is the first time this function gets called from this line of code.\n\n Example:\n .. code-block:: python\n... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python convert tokens to uppercase | [
"def upcaseTokens(s,l,t):\n \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n return [ tt.upper() for tt in map(_ustr,t) ]",
"def upcaseTokens(s,l,t):\n \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n return [ tt.upper() for tt in map(_ustr,t) ]",
"def upcaseToken... | [
"def downcaseTokens(s,l,t):\n \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n return [ tt.lower() for tt in map(_ustr,t) ]",
"def downcaseTokens(s,l,t):\n \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n return [ tt.lower() for tt in map(_ustr,t) ]",
"def downcas... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python adjust log level at runtime | [
"def init_rotating_logger(level, logfile, max_files, max_bytes):\n \"\"\"Initializes a rotating logger\n\n It also makes sure that any StreamHandler is removed, so as to avoid stdout/stderr\n constipation issues\n \"\"\"\n logging.basicConfig()\n\n root_logger = logging.getLogger()\n log_format = \"[%(asctim... | [
"def set_logging_config(log_level, handlers):\n \"\"\"Set python logging library config.\n\n Run this ONCE at the start of your process. It formats the python logging\n module's output.\n Defaults logging level to INFO = 20)\n \"\"\"\n logging.basicConfig(\n format='%(asctime)s %(levelname)... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python extract hrefs from anchor tags web scraping | [
"def get_anchor_href(markup):\n \"\"\"\n Given HTML markup, return a list of hrefs for each anchor tag.\n \"\"\"\n soup = BeautifulSoup(markup, 'lxml')\n return ['%s' % link.get('href') for link in soup.find_all('a')]",
"def get_anchor_href(markup):\n \"\"\"\n Given HTML markup, return a list... | [
"def strip_querystring(url):\n \"\"\"Remove the querystring from the end of a URL.\"\"\"\n p = six.moves.urllib.parse.urlparse(url)\n return p.scheme + \"://\" + p.netloc + p.path",
"def strip_querystring(url):\n \"\"\"Remove the querystring from the end of a URL.\"\"\"\n p = six.moves.urllib.parse... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python check key in dict lowercase | [
"def __contains__ (self, key):\n \"\"\"Check lowercase key item.\"\"\"\n assert isinstance(key, basestring)\n return dict.__contains__(self, key.lower())",
"def __contains__ (self, key):\n \"\"\"Check lowercase key item.\"\"\"\n assert isinstance(key, basestring)\n return... | [
"def _check_conversion(key, valid_dict):\n \"\"\"Check for existence of key in dict, return value or raise error\"\"\"\n if key not in valid_dict and key not in valid_dict.values():\n # Only show users the nice string values\n keys = [v for v in valid_dict.keys() if isinstance(v, string_types)]\... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python dump spec to yaml file | [
"def _dump_spec(spec):\n \"\"\"Dump bel specification dictionary using YAML\n\n Formats this with an extra indentation for lists to make it easier to\n use cold folding on the YAML version of the spec dictionary.\n \"\"\"\n with open(\"spec.yaml\", \"w\") as f:\n yaml.dump(spec, f, Dumper=MyDu... | [
"def ordered_yaml_dump(data, stream=None, Dumper=None, **kwds):\n \"\"\"Dumps the stream from an OrderedDict.\n Taken from\n\n http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-\n mappings-as-ordereddicts\"\"\"\n Dumper = Dumper or yaml.Dumper\n\n class OrderedDumper(Dumpe... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python store proxy settings | [
"def setup(self, proxystr='', prompting=True):\n \"\"\"\n Sets the proxy handler given the option passed on the command\n line. If an empty string is passed it looks at the HTTP_PROXY\n environment variable.\n \"\"\"\n self.prompting = prompting\n proxy = self.get_p... | [
"def set_proxy(proxy_url, transport_proxy=None):\n \"\"\"Create the proxy to PyPI XML-RPC Server\"\"\"\n global proxy, PYPI_URL\n PYPI_URL = proxy_url\n proxy = xmlrpc.ServerProxy(\n proxy_url,\n transport=RequestsTransport(proxy_url.startswith('https://')),\n allow_none=True)",
"... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python validate type tuple with detailed error | [
"def _assert_is_type(name, value, value_type):\n \"\"\"Assert that a value must be a given type.\"\"\"\n if not isinstance(value, value_type):\n if type(value_type) is tuple:\n types = ', '.join(t.__name__ for t in value_type)\n raise ValueError('{0} must be one of ({1})'.format(n... | [
"def validate_type(self, type_):\n \"\"\"Take an str/unicode `type_` and raise a ValueError if it's not \n a valid type for the object.\n \n A valid type for a field is a value from the types_set attribute of \n that field's class. \n \n \"\"\"\n if type_ is n... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python stream docker logs to stdout stderr | [
"def _stream_docker_logs(self):\n \"\"\"Stream stdout and stderr from the task container to this\n process's stdout and stderr, respectively.\n \"\"\"\n thread = threading.Thread(target=self._stderr_stream_worker)\n thread.start()\n for line in self.docker_client.logs(self.... | [
"def pstd(self, *args, **kwargs):\n \"\"\" Console to STDOUT \"\"\"\n kwargs['file'] = self.out\n self.print(*args, **kwargs)\n sys.stdout.flush()",
"def dump_to_log(self, logger):\n \"\"\"Send the cmd info and collected stdout to logger.\"\"\"\n logger.error(\"Execution ... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python find key by value in dict | [
"def get_key_by_value(dictionary, search_value):\n \"\"\"\n searchs a value in a dicionary and returns the key of the first occurrence\n\n :param dictionary: dictionary to search in\n :param search_value: value to search for\n \"\"\"\n for key, value in dictionary.iteritems():\n if value ==... | [
"def get_key_by_value(dictionary, search_value):\n \"\"\"\n searchs a value in a dicionary and returns the key of the first occurrence\n\n :param dictionary: dictionary to search in\n :param search_value: value to search for\n \"\"\"\n for key, value in dictionary.iteritems():\n if value ==... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python push to max heap with siftdown | [
"def heappush_max(heap, item):\n \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n heap.append(item)\n _siftdown_max(heap, 0, len(heap) - 1)",
"def heappush_max(heap, item):\n \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n heap.append(item)\n _siftdown_max(he... | [
"def _heapreplace_max(heap, item):\n \"\"\"Maxheap version of a heappop followed by a heappush.\"\"\"\n returnitem = heap[0] # raises appropriate IndexError if heap is empty\n heap[0] = item\n _siftup_max(heap, 0)\n return returnitem",
"def _heapify_max(x):\n \"\"\"Transform list into a maxhe... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python check exact case-insensitive match | [
"def contains_case_insensitive(adict, akey):\n \"\"\"Check if key is in adict. The search is case insensitive.\"\"\"\n for key in adict:\n if key.lower() == akey.lower():\n return True\n return False",
"def contains_case_insensitive(adict, akey):\n \"\"\"Check if key is in adict. The... | [
"def _regex_span(_regex, _str, case_insensitive=True):\n \"\"\"Return all matches in an input string.\n :rtype : regex.match.span\n :param _regex: A regular expression pattern.\n :param _str: Text on which to run the pattern.\n \"\"\"\n if case_insensitive:\n flags = regex.IGNORECASE | rege... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python control process lifecycle with delay | [
"def stop_process(self):\n \"\"\"\n Stops the child process.\n \"\"\"\n self._process.terminate()\n if not self._process.waitForFinished(100):\n self._process.kill()",
"async def terminate(self):\n \"\"\"Terminate a running script.\"\"\"\n self.proc.term... | [
"def process_wait(process, timeout=0):\n \"\"\"\n Pauses script execution until a given process exists.\n :param process:\n :param timeout:\n :return:\n \"\"\"\n ret = AUTO_IT.AU3_ProcessWait(LPCWSTR(process), INT(timeout))\n return ret",
"def kill_mprocess(process):\n \"\"\"kill proces... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python detect language from filename | [
"def from_file(filename, mime=False):\n \"\"\" Opens file, attempts to identify content based\n off magic number and will return the file extension.\n If mime is True it will return the mime type instead.\n\n :param filename: path to file\n :param mime: Return mime, not extension\n :return: guesse... | [
"def load_feature(fname, language):\n \"\"\" Load and parse a feature file. \"\"\"\n\n fname = os.path.abspath(fname)\n feat = parse_file(fname, language)\n return feat",
"def load_feature(fname, language):\n \"\"\" Load and parse a feature file. \"\"\"\n\n fname = os.path.abspath(fname)\n fe... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python execute sql and return tuples | [
"def select(self, cmd, *args, **kwargs):\n \"\"\" Execute the SQL command and return the data rows as tuples\n \"\"\"\n self.cursor.execute(cmd, *args, **kwargs)\n return self.cursor.fetchall()",
"def execute_sql(self, query):\n \"\"\"\n Executes a given query string on a... | [
"def execute(self, cmd, *args, **kwargs):\n \"\"\" Execute the SQL command and return the data rows as tuples\n \"\"\"\n self.cursor.execute(cmd, *args, **kwargs)",
"def get_column_keys_and_names(table):\n \"\"\"\n Return a generator of tuples k, c such that k is the name of the python ... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python fill array with nan if compatible | [
"def _maybe_fill(arr, fill_value=np.nan):\n \"\"\"\n if we have a compatible fill_value and arr dtype, then fill\n \"\"\"\n if _isna_compat(arr, fill_value):\n arr.fill(fill_value)\n return arr",
"def _maybe_fill(arr, fill_value=np.nan):\n \"\"\"\n if we have a compatible fill_value an... | [
"def _replace_nan(a, val):\n \"\"\"\n replace nan in a by val, and returns the replaced array and the nan\n position\n \"\"\"\n mask = isnull(a)\n return where_method(val, mask, a), mask",
"def _replace_nan(a, val):\n \"\"\"\n replace nan in a by val, and returns the replaced array and the... |
Given a natural language programming query, retrieve relevant code snippets that correctly implement, solve, or answer the query. | python handle divide-by-zero in log | [
"def _protected_log(x1):\n \"\"\"Closure of log for zero arguments.\"\"\"\n with np.errstate(divide='ignore', invalid='ignore'):\n return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)",
"def _protected_log(x1):\n \"\"\"Closure of log for zero arguments.\"\"\"\n with np.errstate(divide='i... | [
"def filter_symlog(y, base=10.0):\n \"\"\"Symmetrical logarithmic scale.\n\n Optional arguments:\n\n *base*:\n The base of the logarithm.\n \"\"\"\n log_base = np.log(base)\n sign = np.sign(y)\n logs = np.log(np.abs(y) / log_base)\n return sign * logs",
"def filter_symlog(y, base=10... |
SYNTRA data archive
This public repository is an archive for retrieval-training data exports from the SYNTRA research project. Its scope includes synthetic-query data, original-query controls, scale experiments, ablations, alternative export policies and historical versions. Archive paths retain the original experiment directories and filenames; the exports are not a single deduplicated dataset or a definitive mapping of every published result to its final training inputs.
Project resources: paper, code and project page.
Archive scope
The selected payload in the 6 October 2026 server inventory comprises 476 JSONL source files, totalling 44,150,233,434 uncompressed bytes (44.15 GB; 41.12 GiB). The gzip archive totals 16,115,135,137 bytes (16.12 GB). Repository files use the suffix .jsonl.gz; source and compressed sizes are recorded separately in the manifest.
| Repository directory | Files | Uncompressed source bytes |
|---|---|---|
data/syn_data/ |
468 | 44,141,645,044 |
data/additional_exports/spartqa/ |
4 | 4,628,264 |
data/additional_exports/winogrande/ |
4 | 3,960,126 |
data/syn_data/ preserves paths relative to the original synthetic-data export root, with .gz appended to each filename. The additional exports preserve the SpartQA and WinoGrande filenames in the same way, including both generated-query and original-query controls. Each source file is compressed using gzip level 1 with a fixed modification time of zero. Compression does not change the JSONL contents; decompression restores the original source bytes. Selected JSONL files include stage-specific exports such as gen_hnmine, gen_anno and v0-raw, as well as historical versions; not every file is directly usable for training or follows the same schema. Consult the sampled schema keys in the manifest for each file. The separate Main_Pipeline/Results working directory, non-JSONL source files, indices and model files are outside this archive's selected payload.
The audited_batches subset comprises 48 exports from 24 batches selected for a production-time audit, totalling 6,823,388,980 uncompressed bytes. The audit recorded 171,539 training records when counting one export variant per batch. Paired variants share queries and must not be counted as independent production batches. This subset is not claimed to contain every final training input used in the paper.
The metadata layout is:
metadata/manifest.json: selected repository paths, source and compressed file metadata, newline counts and sampled schema keys.source_bytesandsource_sha256describe the uncompressed JSONL;bytesandsha256describe the uploaded gzip file.newline_recordscounts source lines; it is not a count of validated, unique training examples.metadata/audited_batches.json: the 24-batch subset and its verification status against the earlier audit.metadata/viewer_configs.jsonandVIEWER_CONFIGS.md: the complete mapping of 476 loading/Viewer configurations to archived files.
Record format and provenance
The 48 audited files were checked as valid JSONL with these fields:
| Field | Type | Meaning |
|---|---|---|
prompt |
string | Retrieval instruction used with the query |
query |
string | Generated query or an original-query control |
pos |
list of strings | Positive document texts |
neg |
list of strings | Negative document texts selected by the export policy |
Other archived files have not yet undergone the same schema validation. Inspect the selected file before loading or combining exports. Filenames distinguish experimental conditions and export policies. In particular, _exclude_other_pos_save_non_pos retains only the source document as a positive when that document appears in pos; otherwise, it preserves the record. This differs from the hard-negative-only versus easy-negative-fill export policy.
Documents are derived from multiple source benchmarks; queries and relevance labels may be generated or inherited controls. Source text remains subject to its source terms. This archive does not assign a blanket license to all constituent data.
Download and load
Every one of the 476 archived exports has its own loading and Viewer configuration. Select a configuration in the Dataset Viewer or pass its name to load_dataset. Configuration names preserve the experiment directory, condition, version and export-policy suffix from the original path. The existing names audited_cosqa_export and audited_cosqa_filtered are retained for compatibility; the default remains audited_cosqa_export, which loads the 5,140-row CosQA original export.
The configuration index maps each name to its exact source file and source-line count; the machine-readable index provides the same mapping with sizes and checksums. Each configuration uses a train split for loading its file; this split name does not identify a published training run or a train/test partition. Choose the configuration appropriate to the experiment you want to reproduce.
Different query-generation conditions, export policies, nested sample sizes and historical versions are loaded separately. In particular, files in median_pos_splits/splitN directories remain separate export variants and are not concatenated as disjoint row shards. Archived variants overlap, and some files have identical content, so aggregate Viewer row counts do not represent unique queries or unique training examples. Viewer statistics describe its generated Parquet representation; archive sizes above describe the uploaded gzip files. Hugging Face generates previews asynchronously after metadata changes.
For example, load the audited CosQA export or the 320k nested MS MARCO synthetic-query export:
from datasets import load_dataset
cosqa = load_dataset("ZucanLyu/SYNTRA", "audited_cosqa_export", split="train")
msmarco_320k = load_dataset(
"ZucanLyu/SYNTRA",
"rq3-scale__msmarco-gen-nested-320k",
split="train",
)
The archive is publicly accessible without approval. Download a file by its preserved relative path:
hf download ZucanLyu/SYNTRA \
data/syn_data/RQ2-code-retrieve-task/cosqa-0618.jsonl.gz \
--repo-type dataset --local-dir ./syntra_archive
To download one experiment directory with Python:
from huggingface_hub import snapshot_download
snapshot_download(
repo_id="ZucanLyu/SYNTRA",
repo_type="dataset",
allow_patterns=["data/syn_data/RQ2-code-retrieve-task/*"],
local_dir="syntra_archive",
)
The datasets JSON loader reads gzip files directly. Load a specific validated export rather than combining all archive files:
from datasets import load_dataset
data = load_dataset(
"json",
data_files="syntra_archive/data/syn_data/RQ2-code-retrieve-task/cosqa-0618.jsonl.gz",
split="train",
)
For reproducible use, pin downloads to a repository commit with --revision in the CLI or revision in snapshot_download, and retain the selected relative paths.
- Downloads last month
- 36