Converts a KAF object to NAF (in memory). You will have to use the method dump later to save it as a new NAF file
483330
def to_naf(self):
        
        if self.type == 'KAF':
            self.root.tag = self.type = 'NAF'

        ## Convert the header
        if self.header is not None:
            self.header.to_naf()

        ## Convert the token layer
        if self.text_layer is not None:
            self.text_layer.to_naf()


        ## Convert the term layer
        if self.term_layer is not None:
            self.term_layer.to_naf()

        ## Convert the chunk layer
        if self.chunk_layer is not None:
            self.chunk_layer.to_naf()

        ## Convert the entity layer
        if self.entity_layer is not None:
            self.entity_layer.to_naf()

        ## Convert the features layer
        ## There is no feature layer defined in NAF, but we assumed
        ## that is defined will be followin the same rules
        if self.features_layer is not None:
            self.features_layer.to_naf()


        ##Convert the opinion layer
        if self.opinion_layer is not None:
            self.opinion_layer.to_naf()


        ## Convert the constituency layer
        ## This layer is exactly the same in KAF/NAF
        if self.constituency_layer is not None:
            self.constituency_layer.to_naf()    #Does nothing...


        ## Convert the dedepency layer
        ## It is not defined on KAF so we assume both will be similar
        if self.dependency_layer is not None:
            self.dependency_layer.to_naf()      #Does nothing...

        if self.coreference_layer is not None:
            self.coreference_layer.to_naf()

        ## Convert the temporalRelations layer
        ## It is not defined on KAF so we assume both will be similar
        if self.temporalRelations_layer is not None:
            self.temporalRelations_layer.to_naf()    #Does nothing...

        ## Convert the causalRelations layer
        ## It is not defined on KAF so we assume both will be similar
        if self.causalRelations_layer is not None:
            self.causalRelations_layer.to_naf()    #Does nothing...

        ## Convert the factuality layer
        ## It is not defined on KAF so we assume both will be similar
        if self.factuality_layer is not None:
            self.factuality_layer.to_naf()        #Does nothing...


        ## Convert the markable layer
        ## It is not defined on KAF so we assume both will be similar
        if self.markable_layer is not None:
            self.markable_layer.to_naf()        #Changes identifier attribute nothing else...


        ## Convert the attribution_layer
        ## It is not defined on KAF so we assme both will be similar
        if self.attribution_layer is not None:
            self.attribution_layer.to_naf()
1149747
static Frame toFrame(Vector v, Key key) {
    final int log_rows_per_chunk = Math.max(1, FileVec.DFLT_LOG2_CHUNK_SIZE - (int) Math.floor(Math.log(1) / Math.log(2.)));
    Vec vv = makeCon(0, v.size(), log_rows_per_chunk, false /* no rebalancing! */);
    Frame f = new Frame(key, new Vec[]{vv}, true);
    try( Vec.Writer vw = f.vecs()[0].open() ) {
      for (int r = 0; r < v.size(); ++r)
        vw.set(r, v.get(r));
    }
    DKV.put(key, f);
    return f;
  }
417973
def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
      if buffer.respond_to?(:put_hash)
        buffer.put_hash(self, validating_keys)
      else
        position = buffer.length
        buffer.put_int32(0)
        each do |field, value|
          buffer.put_byte(value.bson_type)
          buffer.put_cstring(field.to_bson_key(validating_keys))
          value.to_bson(buffer, validating_keys)
        end
        buffer.put_byte(NULL_BYTE)
        buffer.replace_int32(position, buffer.length - position)
      end
    end
147029
function convert(source) {
  let currentKey = "",
      currentValue = "",
      objectNames = [],
      output = {},
      parentObj = {},
      lines = source.split(NEW_LINE),
      splitAt;

  let currentObj = output;
  let parents = [];

  for (let i = 0; i < lines.length; i++) {
    let line = lines[i];
    if (line.charAt(0) === " ") {
      currentObj[currentKey] += line.substr(1);

    } else {
      splitAt = line.indexOf(":");

      if (splitAt < 0) {
        continue;
      }

      currentKey = line.substr(0, splitAt);
      currentValue = line.substr(splitAt + 1);

      switch (currentKey) {
        case "BEGIN":
          parents.push(parentObj);
          parentObj = currentObj;
          if (parentObj[currentValue] == null) {
            parentObj[currentValue] = [];
          }
          // Create a new object, store the reference for future uses
          currentObj = {};
          parentObj[currentValue].push(currentObj);
          break;
        case "END":
          currentObj = parentObj;
          parentObj = parents.pop();
          break;
        default:
          if(currentObj[currentKey]) {
            if(!Array.isArray(currentObj[currentKey])) {
              currentObj[currentKey] = [currentObj[currentKey]];
            }
            currentObj[currentKey].push(currentValue);
          } else {
            currentObj[currentKey] = currentValue;
          }
      }
    }
  }
  return output;
}
283102
def to_kaf(self):
        
        if self.type == 'NAF':
            self.type = 'KAF'
            for node in self.__get_node_terms():
                node.set('cid', node.get('id'))
                del node.attrib['id']
125069
def to_data(self, obj, partitioning_strategy=None):
        
        if obj is None:
            return None

        if isinstance(obj, Data):
            return obj

        out = self._create_data_output()
        try:
            serializer = self._registry.serializer_for(obj)
            partitioning_hash = self._calculate_partitioning_hash(obj, partitioning_strategy)

            out.write_int_big_endian(partitioning_hash)
            out.write_int_big_endian(serializer.get_type_id())
            serializer.write(out, obj)
            return Data(out.to_byte_array())
        except:
            handle_exception(sys.exc_info()[1], sys.exc_info()[2])
        finally:
            pass
907265
def to_kaf(self):
        
        if self.type == 'NAF':
            for node in self.__get_opinion_nodes():
                node.set('oid',node.get('id'))
                del node.attrib['id']
389736
function amf0decObject(buf) { // TODO: Implement references!
    var obj = {};
    var iBuf = buf.slice(1);
    var len = 1;
//    console.log('ODec',iBuf.readUInt8(0));
    while (iBuf.readUInt8(0) != 0x09) {
        // console.log('Field', iBuf.readUInt8(0), iBuf);
        var prop = amf0decUString(iBuf);
        // console.log('Got field for property', prop);
        len += prop.len;
        if (iBuf.slice(prop.len).readUInt8(0) == 0x09) {
            len++;
            // console.log('Found the end property');
            break;
        } // END Object as value, we shall leave
        if (prop.value == '') break;
        var val = amf0DecodeOne(iBuf.slice(prop.len));
        // console.log('Got field for value', val);
        obj[prop.value] = val.value;
        len += val.len;
        iBuf = iBuf.slice(prop.len + val.len);
    }
    return { len: len, value: obj }
}
1271277
def save(self):
        

        kf = self._kf

        # force all attributes to be computed. this is only necessary
        # if the class uses properties that compute data only when
        # accessed
        for prop in self.properties:
            self._DL[prop[0]].append(getattr(kf, prop[0]))

        v = copy.deepcopy(kf.__dict__)

        if self._skip_private:
            for key in list(v.keys()):
                if key.startswith('_'):
                    print('deleting', key)
                    del v[key]

        if self._skip_callable:
            for key in list(v.keys()):
                if callable(v[key]):
                    del v[key]

        for ig in self._ignore:
            if ig in v:
                del v[ig]

        for key in list(v.keys()):
            self._DL[key].append(v[key])

        self.__dict__.update(self._DL)
        self._len += 1
1296048
public static NFSFileVec make(File f, Futures fs) {
    if( !f.exists() ) throw new IllegalArgumentException("File not found: "+f.toString());
    long size = f.length();
    Key k = Vec.newKey(PersistNFS.decodeFile(f));
    // Insert the top-level FileVec key into the store
    NFSFileVec nfs = new NFSFileVec(k,size);
    DKV.put(k,nfs,fs);
    return nfs;
  }
599027
def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None,
           append=None, **kwargs):
    

    if append:
        f = lambda store: store.append(key, value, **kwargs)
    else:
        f = lambda store: store.put(key, value, **kwargs)

    path_or_buf = _stringify_path(path_or_buf)
    if isinstance(path_or_buf, str):
        with HDFStore(path_or_buf, mode=mode, complevel=complevel,
                      complib=complib) as store:
            f(store)
    else:
        f(path_or_buf)
984323
private DataFrame createDataFrame(ByteBuf buf) {
        if (buf.readableBytes() > 3) {
            byte messageType = buf.getByte(buf.readerIndex() + 3);

            switch (messageType) {
                case Version.ID:
                    return new Version(buf);
                case MemoryGetId.ID:
                    return new MemoryGetId(buf);
                case InitData.ID:
                    return new InitData(buf);
                case NodeProtocolInfo.ID:
                    return new NodeProtocolInfo(buf);
                case SendData.ID:
                    return new SendData(buf);
                case ApplicationCommand.ID:
                    return new ApplicationCommand(buf);
                case ApplicationUpdate.ID:
                    return new ApplicationUpdate(buf);
                case RequestNodeInfo.ID:
                    return new RequestNodeInfo(buf);
                case GetRoutingInfo.ID:
                    return new GetRoutingInfo(buf);
                case GetSUCNodeId.ID:
                    return new GetSUCNodeId(buf);
                case AddNodeToNetwork.ID:
                    return new AddNodeToNetwork(buf);
                case RemoveNodeFromNetwork.ID:
                    return new RemoveNodeFromNetwork(buf);
                case SetDefault.ID:
                    return new SetDefault(buf);
            }
        }
        return null;
    }
446774
def convert(f, output=sys.stdout):
    

    r = f.read(11)
    if r == 'compressed\n':
        png(output, *decompress(f))
    else:
        png(output, *glue(f, r))
409244
def hdf5write(h5file, obj, root=''):
    
    dic = node_to_dict(obj_to_node(obj))
    h5file.save(dic, root)
65584
def save(self, obj):
        
        if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
            # Compute a hash of the object
            # The update function of the hash requires a c_contiguous buffer.
            if obj.shape == ():
                # 0d arrays need to be flattened because viewing them as bytes
                # raises a ValueError exception.
                obj_c_contiguous = obj.flatten()
            elif obj.flags.c_contiguous:
                obj_c_contiguous = obj
            elif obj.flags.f_contiguous:
                obj_c_contiguous = obj.T
            else:
                # Cater for non-single-segment arrays: this creates a
                # copy, and thus aleviates this issue.
                # XXX: There might be a more efficient way of doing this
                obj_c_contiguous = obj.flatten()

            # memoryview is not supported for some dtypes, e.g. datetime64, see
            # https://github.com/numpy/numpy/issues/4983. The
            # workaround is to view the array as bytes before
            # taking the memoryview.
            self._hash.update(
                self._getbuffer(obj_c_contiguous.view(self.np.uint8)))

            # We store the class, to be able to distinguish between
            # Objects with the same binary content, but different
            # classes.
            if self.coerce_mmap and isinstance(obj, self.np.memmap):
                # We don't make the difference between memmap and
                # normal ndarrays, to be able to reload previously
                # computed results with memmap.
                klass = self.np.ndarray
            else:
                klass = obj.__class__
            # We also return the dtype and the shape, to distinguish
            # different views on the same data with different dtypes.

            # The object will be pickled by the pickler hashed at the end.
            obj = (klass, ('HASHED', obj.dtype, obj.shape, obj.strides))
        elif isinstance(obj, self.np.dtype):
            # Atomic dtype objects are interned by their default constructor:
            # np.dtype('f8') is np.dtype('f8')
            # This interning is not maintained by a
            # pickle.loads + pickle.dumps cycle, because __reduce__
            # uses copy=True in the dtype constructor. This
            # non-deterministic behavior causes the internal memoizer
            # of the hasher to generate different hash values
            # depending on the history of the dtype object.
            # To prevent the hash from being sensitive to this, we use
            # .descr which is a full (and never interned) description of
            # the array dtype according to the numpy doc.
            klass = obj.__class__
            obj = (klass, ('HASHED', obj.descr))
        Hasher.save(self, obj)
961082
def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
      position = buffer.length
      buffer.put_int32(0)
      buffer.put_byte(SUBTYPES[type])
      buffer.put_int32(data.bytesize) if type == :old
      buffer.put_bytes(data.force_encoding(BINARY))
      buffer.replace_int32(position, buffer.length - position - 5)
    end
422540
def to_dade_matrix(M, annotations="", filename=None):
    

    n, m = M.shape
    A = np.zeros((n + 1, m + 1))
    A[1:, 1:] = M
    if not annotations:
        annotations = np.array(["" for _ in n], dtype=str)
    A[0, :] = annotations
    A[:, 0] = annotations.T
    if filename:
        try:
            np.savetxt(filename, A, fmt='%i')
            print("I saved input matrix in dade format as " + str(filename))
        except ValueError as e:
            print("I couldn't save input matrix.")
            print(str(e))
        finally:
            return A

    return A