docstring_insert - a decorator to insert API-docparts dynamically.
325319
def dyndoc_insert(src):
    """"""
    # manipulating docstrings this way is tricky due to indentation
    # the JSON needs leading whitespace to be interpreted correctly
    import json
    import re

    def mkblock(d, flag=0):
        # response, pretty formatted
        v = json.dumps(d, indent=2)
        if flag == 1:
            # strip the '[' and ']' in case of a list holding items
            # that stand on their own (example: tick records from a stream)
            nw = re.findall('.*?\[(.*)\]', v, flags=re.S)
            v = nw[0]
        # add leading whitespace for each line and start with a newline
        return "\n{}".format("".join(["{0:>16}{1}\n".format("", L)
                             for L in v.split('\n')]))

    def dec(obj):
        allSlots = re.findall("\{(_v3.*?)\}", obj.__doc__)
        docsub = {}
        sub = {}
        for k in allSlots:
            p = re.findall("^(_v3.*)_(.*)", k)
            p = list(*p)
            sub.update({p[1]: p[0]})

        for v in sub.values():
            for k in sub.keys():
                docsub["{}_url".format(v)] = "{}".format(src[v]["url"])
                if "resp" == k:
                    docsub.update({"{}_resp".format(v):
                                   mkblock(src[v]["response"])})
                if "body" == k:
                    docsub.update({"{}_body".format(v):
                                   mkblock(src[v]["body"])})

                if "params" == k:
                    docsub.update({"{}_params".format(v):
                                   mkblock(src[v]["params"])})
                if "ciresp" == k:
                    docsub.update({"{}_ciresp".format(v):
                                   mkblock(src[v]["response"], 1)})

        obj.__doc__ = obj.__doc__.format(**docsub)

        return obj

    return dec
412720
def insert(collection_name, docs, check_keys, safe, last_error_args):
    
    data = __ZERO
    data += bson._make_c_string(collection_name)
    bson_data = "".join([bson.BSON.encode(doc, check_keys) for doc in docs])
    if not bson_data:
        raise InvalidOperation("cannot do an empty bulk insert")
    data += bson_data
    if safe:
        (_, insert_message) = __pack_message(2002, data)
        (request_id, error_message) = __last_error(last_error_args)
        return (request_id, insert_message + error_message)
    else:
        return __pack_message(2002, data)
503026
function insertComment(data) {
    var parent = stack.top;
    if (foster_parent_mode && isA(parent, tablesectionrowSet)) {
      fosterParent(function(doc) { return doc.createComment(data); });
    } else {
      // "If the adjusted insertion location is inside a template element,
      // let it instead be inside the template element's template contents"
      if (parent instanceof impl.HTMLTemplateElement) {
        parent = parent.content;
      }
      parent._appendChild(parent.ownerDocument.createComment(data));
    }
  }
776456
def insertmap(self,xmltext,lfnpfn_dict):
    

    pmsg = cPickle.dumps(lfnpfn_dict)

    msg = "INSERTMAP\0" + xmltext + "\0" + pmsg + "\0"
    self.sfile.write(msg)

    ret, output = self.__response__()
    reply = str(output[0])

    if ret:
      msg = "Error executing insert on server %d:%s" % (ret, reply)
      raise LDBDClientException, msg

    return reply
589962
def insert_extracted_value(self, doc, extracted_value,
                               output_field, original_output_field=None):
        """"""
        if not extracted_value:
            return doc
        metadata = self.extractor.get_metadata()
        if not self.extractor.get_include_context():
            if isinstance(extracted_value, list):
                result = list()
                for ev in extracted_value:
                    result.append({'value': ev})
            else:
                result = {'value': extracted_value}
        else:
            result = extracted_value
        metadata['result'] = result
        metadata['source'] = str(self.input_fields)

        if original_output_field is not None:
            metadata['original_output_field'] = original_output_field

        if self.name is not None:
            metadata['name'] = self.name

        field_elements = output_field.split('.')
        while len(field_elements) > 1:
            field_element = field_elements.pop(0)
            if '[' in field_element:
                if not field_element.startswith('['):
                    array_field_elements = field_element.split('[', 1)
                    array_field_element = array_field_elements[0]
                    doc = doc[array_field_element]
                    field_element = array_field_elements[1]
                array_elements = field_element.split(']')
                for array_element in array_elements:
                    if not array_element:
                        continue
                    if array_element.startswith('['):
                        array_element = array_element[1:]
                    if array_element.isdigit() and isinstance(doc, list):
                        doc = doc[int(array_element)]
                    else:
                        doc = doc[array_element]
            else:
                if field_element not in doc:
                    doc[field_element] = {}
                doc = doc[field_element]
        field_element = field_elements[0]
        if field_element in doc:
            output = doc[field_element]
            if isinstance(output, dict):
                output = [output, metadata]
            elif isinstance(output, types.ListType):
                output.append(metadata)

        else:
            output = [metadata]
        doc[field_element] = output
349563
def parse_docstring(docstring, cls=None):
    
    def_arg_dict = lambda: {'description': None,
                            'type_name': None,
                            'required': False,
                            }
    description, fields_lines = split_docstring(docstring)
    arguments_dict = defaultdict(def_arg_dict)
    return_value_types = []
    #parse fields
    return_description = ''
    for docstring_line in fields_lines:
        if _ignored_field(docstring_line):
            continue
        #parse inherits
        if docstring_line.startswith('@inherits'):
            if not cls:
                raise MethodParsingException()
            inherit_tmp = docstring_line.split(None, 1)[1]
            inherit_str = inherit_tmp.split(':class:', 1)[1]
            result = _parse_inherit(cls, inherit_str)

            description = description or result['description']
            for arg_name, update_dict in result['arguments'].items():
                arguments_dict[arg_name].update(update_dict)
            return_value_types = result['return']['type_name']
            return_description = result['return']['description']
        #parse return value
        elif docstring_line.startswith(':rtype:'):
            class_name = __get_class_name(cls)
            types_str = docstring_line.split(None, 1)[1]
            return_value_types = types_str.replace('\n', '').strip(':').strip()
            if return_value_types.startswith('class:`.'):
                return_value_types = return_value_types.replace('class:`.', 'class:`'+class_name+'.')
        #parse return description
        elif docstring_line.startswith(':return:'):
            return_description = docstring_line.split(None, 1)[1].strip()
        #parse arguments
        else:
            arg_name, update_dict = _parse_docstring_field(cls, docstring_line)
            arguments_dict[arg_name].update(update_dict)
    #check fields
    _check_arguments_dict(arguments_dict)
    if not return_value_types:
        raise MethodParsingException('Can not get return types for method')
    return {'description': description,
            'arguments': arguments_dict,
            'return': {'description': return_description,
                       'type_name': return_value_types}}
65463
function(apiKey, templateId, pieceTitle,
        category, fromAddress, toAddress, ccAddress, bccAddresses, subject,
        textBody, htmlBody, contentType, mergeContext) {}
322791
def insert(self, **kwargs):
        
        if self.is_valid:
            before = self.before_insert()
            if before:
                return before

            try:
                self._document['_id'] = self.insert_one(self._document)

                self.after_insert()

                return self._document
            except PyMongoException as exc:
                return PyMongoError(
                    error_message=exc.details.get(
                        'errmsg', exc.details.get('err', 'PyMongoError.')
                    ),
                    operation='insert', collection=type(self).__name__,
                    document=self._document,
                )

        return self._errors
512653
def insert(self, i, x):
        """"""
        if not isinstance(x, str):
            raise TypeError(
                'Members of this object must be strings. '
                'You supplied \"%s\"' % type(x))
        list.insert(self, i, x)
72182
def insert_file(self, f, namespace, timestamp):
        
        doc = f.get_metadata()
        doc["content"] = f.read()
        self.doc_dict[f._id] = Entry(doc=doc, ns=namespace, ts=timestamp)
197302
def insert(self, collection_name, instance):
        
        assert isinstance(instance, SiteStatistics)
        collection = self.ds.connection(collection_name)
        return collection.insert_one(instance.document).inserted_id
981955
def create_insert():
    
    insert = upkey("insert").setResultsName("action")

    # VALUES
    attrs = Group(delimitedList(var)).setResultsName("attrs")
    value_group = Group(Suppress("(") + delimitedList(value) + Suppress(")"))
    values = Group(delimitedList(value_group)).setResultsName("list_values")
    values_insert = Suppress("(") + attrs + Suppress(")") + upkey("values") + values

    # KEYWORDS
    keyword = Group(var + Suppress("=") + value)
    item = Group(Suppress("(") + delimitedList(keyword) + Suppress(")"))
    keyword_insert = delimitedList(item).setResultsName("map_values")

    return insert + into + table + (values_insert | keyword_insert) + Optional(throttle)
944778
def _do_batched_insert(collection_name, docs, check_keys,
                       safe, last_error_args, continue_on_error, opts,
                       ctx):
    
    def _insert_message(insert_message, send_safe):
        """Build the insert message with header and GLE.
        """
        request_id, final_message = __pack_message(2002, insert_message)
        if send_safe:
            request_id, error_message, _ = __last_error(collection_name,
                                                        last_error_args)
            final_message += error_message
        return request_id, final_message

    send_safe = safe or not continue_on_error
    last_error = None
    data = StringIO()
    data.write(struct.pack("<i", int(continue_on_error)))
    data.write(_make_c_string(collection_name))
    message_length = begin_loc = data.tell()
    has_docs = False
    to_send = []
    encode = _dict_to_bson  # Make local
    compress = ctx.compress and not (safe or send_safe)
    for doc in docs:
        encoded = encode(doc, check_keys, opts)
        encoded_length = len(encoded)
        too_large = (encoded_length > ctx.max_bson_size)

        message_length += encoded_length
        if message_length < ctx.max_message_size and not too_large:
            data.write(encoded)
            to_send.append(doc)
            has_docs = True
            continue

        if has_docs:
            # We have enough data, send this message.
            try:
                if compress:
                    rid, msg = None, data.getvalue()
                else:
                    rid, msg = _insert_message(data.getvalue(), send_safe)
                ctx.legacy_bulk_insert(
                    rid, msg, 0, send_safe, to_send, compress)
            # Exception type could be OperationFailure or a subtype
            # (e.g. DuplicateKeyError)
            except OperationFailure as exc:
                # Like it says, continue on error...
                if continue_on_error:
                    # Store exception details to re-raise after the final batch.
                    last_error = exc
                # With unacknowledged writes just return at the first error.
                elif not safe:
                    return
                # With acknowledged writes raise immediately.
                else:
                    raise

        if too_large:
            _raise_document_too_large(
                "insert", encoded_length, ctx.max_bson_size)

        message_length = begin_loc + encoded_length
        data.seek(begin_loc)
        data.truncate()
        data.write(encoded)
        to_send = [doc]

    if not has_docs:
        raise InvalidOperation("cannot do an empty bulk insert")

    if compress:
        request_id, msg = None, data.getvalue()
    else:
        request_id, msg = _insert_message(data.getvalue(), safe)
    ctx.legacy_bulk_insert(request_id, msg, 0, safe, to_send, compress)

    # Re-raise any exception stored due to continue_on_error
    if last_error is not None:
        raise last_error
842793
function Insert (str, position) {
    if (!this || this.constructor !== SimpleTextOperation) {
      // => function was called without 'new'
      return new Insert(str, position);
    }
    this.str = str;
    this.position = position;
  }
1042674
def insert(self,xmltext):
    

    msg = "INSERT\0" + xmltext + "\0"
    self.sfile.write(msg)

    ret, output = self.__response__()
    reply = str(output[0])

    if ret:
      msg = "Error executing insert on server %d:%s" % (ret, reply)
      raise LDBDClientException, msg

    return reply
1007364
def kwinsert(clas,pool_or_cursor,**kwargs):
    ""
    returning = kwargs.pop('returning',None)
    fields,vals = zip(*kwargs.items())
    # note: don't do SpecialField resolution here; clas.insert takes care of it
    return clas.insert(pool_or_cursor,fields,vals,returning=returning)
457664
def _onDocstring( self, docstr, line ):
        "  "
        if self.objectsStack:
            self.objectsStack[ -1 ].docstring = \
                                 Docstring( trim_docstring( docstr ), line )
            return

        self.docstring = Docstring( trim_docstring( docstr ), line )
        return