求解HMM模型，所有概率请提前取对数

@param obs     观测序列
@param states  隐状态
@param start_p 初始概率（隐状态）
@param trans_p 转移概率（隐状态）
@param emit_p  发射概率 （隐状态表现为显状态的概率）
@return 最可能的序列
972230
public static int[] compute(int[] obs, int[] states, double[] start_p, double[][] trans_p, double[][] emit_p)
    {
        int _max_states_value = 0;
        for (int s : states)
        {
            _max_states_value = Math.max(_max_states_value, s);
        }
        ++_max_states_value;
        double[][] V = new double[obs.length][_max_states_value];
        int[][] path = new int[_max_states_value][obs.length];

        for (int y : states)
        {
            V[0][y] = start_p[y] + emit_p[y][obs[0]];
            path[y][0] = y;
        }

        for (int t = 1; t < obs.length; ++t)
        {
            int[][] newpath = new int[_max_states_value][obs.length];

            for (int y : states)
            {
                double prob = Double.MAX_VALUE;
                int state;
                for (int y0 : states)
                {
                    double nprob = V[t - 1][y0] + trans_p[y0][y] + emit_p[y][obs[t]];
                    if (nprob < prob)
                    {
                        prob = nprob;
                        state = y0;
                        // 记录最大概率
                        V[t][y] = prob;
                        // 记录路径
                        System.arraycopy(path[state], 0, newpath[y], 0, t);
                        newpath[y][t] = y;
                    }
                }
            }

            path = newpath;
        }

        double prob = Double.MAX_VALUE;
        int state = 0;
        for (int y : states)
        {
            if (V[obs.length - 1][y] < prob)
            {
                prob = V[obs.length - 1][y];
                state = y;
            }
        }

        return path[state];
    }
456814
function _getServerStreamingInterceptor(method_definition, channel, emitter) {
  var deserialize = common.wrapIgnoreNull(
    method_definition.responseDeserialize);
  var serialize = method_definition.requestSerialize;
  return function (options) {
    var batch_state = {
      completed_ops: [],
      deferred_batches: []
    };
    var call = getCall(channel, method_definition.path, options);
    var final_requester = {};
    var first_listener;
    var get_listener = function() {
      return first_listener;
    };
    final_requester.start = function(metadata, listener) {
      first_listener = listener;
      metadata = metadata.clone();
      var metadata_batch = {
        [grpc.opType.SEND_INITIAL_METADATA]: metadata._getCoreRepresentation(),
        [grpc.opType.RECV_INITIAL_METADATA]: true
      };
      var callback = function(err, response) {
        if (err) {
          // The call has stopped for some reason. A non-OK status will arrive
          // in the other batch.
          return;
        }
        first_listener.onReceiveMetadata(
          Metadata._fromCoreRepresentation(response.metadata));
      };
      batch_state = _startBatchIfReady(call, metadata_batch, batch_state,
                                       callback);
      var status_batch = {
        [grpc.opType.RECV_STATUS_ON_CLIENT]: true
      };
      call.startBatch(status_batch, function(err, response) {
        if (err) {
          emitter.emit('error', err);
          return;
        }
        response.status.metadata = Metadata._fromCoreRepresentation(
          response.status.metadata);
        first_listener.onReceiveStatus(response.status);
      });
    };
    final_requester.sendMessage = function(argument) {
      var message = serialize(argument);
      if (options) {
        message.grpcWriteFlags = options.flags;
      }
      var send_batch = {
        [grpc.opType.SEND_MESSAGE]: message
      };
      var callback = function(err, response) {
        if (err) {
          // The call has stopped for some reason. A non-OK status will arrive
          // in the other batch.
          return;
        }
      };
      batch_state = _startBatchIfReady(call, send_batch, batch_state, callback);
    };
    final_requester.halfClose = function() {
      var batch = {
        [grpc.opType.SEND_CLOSE_FROM_CLIENT]: true
      };
      batch_state = _startBatchIfReady(call, batch, batch_state, function() {});
    };
    final_requester.recvMessageWithContext = function(context) {
      var recv_batch = {
        [grpc.opType.RECV_MESSAGE]: true
      };
      var callback = _getStreamReadCallback(emitter, call,
        get_listener, deserialize);
      batch_state = _startBatchIfReady(call, recv_batch, batch_state, callback);
    };
    final_requester.cancel = function() {
      call.cancel();
    };
    final_requester.cancelWithStatus = function(code, details) {
      call.cancelWithStatus(code, details)
    };
    final_requester.getPeer = function() {
      return call.getPeer();
    };
    return new InterceptingCall(null, final_requester);
  };
}
952628
private final State onInit(final Buffer buffer) {
        try {
            while (buffer.hasReadableBytes()) {
                final byte b = buffer.peekByte();
                if (b == SipParser.SP || b == SipParser.HTAB || b == SipParser.CR || b == SipParser.LF) {
                    buffer.readByte();
                } else {
                    start = buffer.getReaderIndex();
                    return State.GET_INITIAL_LINE;
                }
            }
        } catch (final IOException e) {
            throw new RuntimeException("Unable to read from stream due to IOException", e);
        }

        return State.INIT;
    }
134244
public void play2(String oldStreamName, int start, String transition, int length, double offset, String streamName) {
        Map<String, Object> playOptions = new HashMap<String, Object>();
        playOptions.put("oldStreamName", oldStreamName);
        playOptions.put("streamName", streamName);
        playOptions.put("start", start);
        playOptions.put("len", length);
        playOptions.put("offset", offset);
        play2(playOptions);
    }
239015
def get_initial_state(self, source_length: mx.sym.Symbol, source_seq_len: int) -> AttentionState:
        
        dynamic_source = mx.sym.reshape(mx.sym.zeros_like(source_length), shape=(-1, 1, 1))
        # dynamic_source: (batch_size, source_seq_len, num_hidden_dynamic_source)
        dynamic_source = mx.sym.broadcast_to(dynamic_source, shape=(0, source_seq_len, self.dynamic_source_num_hidden))
        return AttentionState(context=None, probs=None, dynamic_source=dynamic_source)
1008205
private void repartitionBroadcastState(
			Map<String, List<Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo>>> broadcastState,
			List<Map<StreamStateHandle, OperatorStateHandle>> mergeMapList) {

		int newParallelism = mergeMapList.size();
		for (int i = 0; i < newParallelism; ++i) {

			final Map<StreamStateHandle, OperatorStateHandle> mergeMap = mergeMapList.get(i);

			// for each name, pick the i-th entry
			for (Map.Entry<String, List<Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo>>> e :
					broadcastState.entrySet()) {

				int previousParallelism = e.getValue().size();

				Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo> handleWithMetaInfo =
					e.getValue().get(i % previousParallelism);

				OperatorStateHandle operatorStateHandle = mergeMap.get(handleWithMetaInfo.f0);
				if (operatorStateHandle == null) {
					operatorStateHandle = new OperatorStreamStateHandle(
						new HashMap<>(broadcastState.size()),
						handleWithMetaInfo.f0);
					mergeMap.put(handleWithMetaInfo.f0, operatorStateHandle);
				}
				operatorStateHandle.getStateNameToPartitionOffsets().put(e.getKey(), handleWithMetaInfo.f1);
			}
		}
	}
613992
function obsFws() {
        return opts.strict ? null : wrap('obs-FWS', star(
            and(invis(opt(crlf)), wsp),
            1
        )());
    }
1298858
protected final synchronized void transitionState(OperationState newState) {
    getLogger().debug("Transitioned state from %s to %s", state, newState);
    state = newState;
    // Discard our buffer when we no longer need it.
    if(state != OperationState.WRITE_QUEUED
        && state != OperationState.WRITING) {
      cmd = null;
    }
    if (state == OperationState.COMPLETE) {
      callback.complete();
    }
  }
833124
public Packet decodePacket(RTMPConnection conn, RTMPDecodeState state, IoBuffer in) {
        final int position = in.position();
        //if (log.isTraceEnabled()) {
            //log.trace("decodePacket - state: {} buffer: {}", state, in);
            //log.trace("decodePacket: position {}, limit {}, {}", position, in.limit(), Hex.encodeHexString(Arrays.copyOfRange(in.array(), position, in.limit())));
            //log.trace("decodePacket: position {}, limit {}", position, in.limit());
            //int lastTs = lastTimestamp.get() != null ? lastTimestamp.get() : 0;
            //if (lastTs == 0 || lastTs >= (MEDIUM_INT_MAX - 100)) {
                //log.trace("decodePacket:{}\n{}", lastTs, Hex.encodeHexString(Arrays.copyOfRange(in.array(), position, in.limit())));
            //}
        //}
        // get RTMP state holder
        RTMP rtmp = conn.getState();
        // read the chunk header (variable from 1-3 bytes)
        final ChunkHeader chunkHeader = ChunkHeader.read(in);
        // represents "packet" header length via "format" only 1 byte in the chunk header is needed here
        int headerLength = RTMPUtils.getHeaderLength(chunkHeader.getFormat());
        headerLength += chunkHeader.getSize() - 1;
        if (in.remaining() < headerLength) {
            state.bufferDecoding(headerLength - in.remaining());
            in.position(position);
            return null;
        }
        final Header header = decodeHeader(chunkHeader, state, in, rtmp);
        // get the channel id
        final int channelId = header != null ? header.getChannelId() : chunkHeader.getChannelId();
        if (header == null || header.isEmpty()) {
            if (log.isTraceEnabled()) {
                log.trace("Header was null or empty - chh: {}", chunkHeader);
            }
            // clear / compact the input and close the channel
            in.clear();
            in.compact();
            // send a NetStream.Failed message
            StreamService.sendNetStreamStatus(conn, StatusCodes.NS_FAILED, "Bad data on channel: " + channelId, "no-name", Status.ERROR, conn.getStreamIdForChannelId(channelId));
            // close the channel on which the issue occurred, until we find a way to exclude the current data
            conn.closeChannel(channelId);
            return null;
        }
        // store the header based on its channel id
        rtmp.setLastReadHeader(channelId, header);
        // ensure that we dont exceed maximum packet size
        int size = header.getSize();
        if (size > MAX_PACKET_SIZE) {
            // Reject packets that are too big, to protect against OOM when decoding has failed in some way
            log.warn("Packet size exceeded. size={}, max={}, connId={}", header.getSize(), MAX_PACKET_SIZE, conn.getSessionId());
            // send a NetStream.Failed message
            StreamService.sendNetStreamStatus(conn, StatusCodes.NS_FAILED, "Data exceeded maximum allowed by " + (size - MAX_PACKET_SIZE) + " bytes", "no-name", Status.ERROR, conn.getStreamIdForChannelId(channelId));
            throw new ProtocolException(String.format("Packet size exceeded. size: %s", header.getSize()));
        }
        // get the size of our chunks
        int readChunkSize = rtmp.getReadChunkSize();
        // check to see if this is a new packet or continue decoding an existing one
        Packet packet = rtmp.getLastReadPacket(channelId);
        if (packet == null) {
            // create a new packet
            packet = new Packet(header.clone());
            // store the packet based on its channel id
            rtmp.setLastReadPacket(channelId, packet);
        }
        // get the packet data
        IoBuffer buf = packet.getData();
        //if (log.isTraceEnabled()) {
            //log.trace("Source buffer position: {}, limit: {}, packet-buf.position {}, packet size: {}", new Object[] { in.position(), in.limit(), buf.position(), header.getSize() });
        //}
        // read chunk
        int length = Math.min(buf.remaining(), readChunkSize);
        if (in.remaining() < length) {
            //log.debug("Chunk too small, buffering ({},{})", in.remaining(), length);
            // how much more data we need to continue?
            state.bufferDecoding(in.position() - position + length);
            // we need to move back position so header will be available during another decode round
            in.position(position);
            return null;
        }
        // get the chunk from our input
        byte[] chunk = Arrays.copyOfRange(in.array(), in.position(), in.position() + length);
        //if (log.isTraceEnabled()) {
            //log.trace("Read chunkSize: {}, length: {}, chunk: {}", readChunkSize, length, Hex.encodeHexString(chunk));
        //}
        // move the position
        in.skip(length);
        // put the chunk into the packet
        buf.put(chunk);
        if (buf.hasRemaining()) {
            //if (log.isTraceEnabled()) {
                //log.trace("Packet is incomplete ({},{})", buf.remaining(), buf.limit());
            //}
            return null;
        }
        // flip so we can read / decode the packet data into a message
        buf.flip();
        try {
            // timebase + timedelta
            final int timestamp = header.getTimer();
            // store the last ts in thread local for debugging
            //lastTimestamp.set(header.getTimerBase());
            final IRTMPEvent message = decodeMessage(conn, packet.getHeader(), buf);
            // flash will send an earlier time stamp when resetting a video stream with a new key frame. To avoid dropping it, we give it the 
            // minimal increment since the last message. To avoid relative time stamps being mis-computed, we don't reset the header we stored.
            message.setTimestamp(timestamp);
            if (log.isTraceEnabled()) {
                log.trace("Decoded message: {}", message);
            }
            packet.setMessage(message);
            if (message instanceof ChunkSize) {
                ChunkSize chunkSizeMsg = (ChunkSize) message;
                rtmp.setReadChunkSize(chunkSizeMsg.getSize());
            } else if (message instanceof Abort) {
                log.debug("Abort packet detected");
                // client is aborting a message, reset the packet because the next chunk will start a new packet
                Abort abort = (Abort) message;
                rtmp.setLastReadPacket(abort.getChannelId(), null);
                packet = null;
            }
            // collapse the time stamps on the last header after decode is complete
            Header lastHeader = rtmp.getLastReadHeader(channelId);
            lastHeader.setTimerBase(timestamp);
            // clear the delta
            //lastHeader.setTimerDelta(0);
            if (log.isTraceEnabled()) {
                log.trace("Last read header after decode: {}", lastHeader);
            }
        } finally {
            rtmp.setLastReadPacket(channelId, null);
        }
        return packet;
    }
252385
function publish(conn, channel, message) {
  var c = 0
    , indices = []
    , len
    , k
    , re;

  // exact channel match
  for(k in this._channels) {
    // found the channel
    if(k === channel) {
      indices = this._channels[k].slice(0);
      this.emit(
        PUBSUB.PUBLISH, conn, channel, indices,
          [PUBSUB.MESSAGE, channel, message]);
      break;
    }
  }

  len = indices.length;

  // reset indices for patterns
  // required to prevent channel subscribers
  // from also receiving pmessage events
  indices = [];

  // test against pattern channels
  for(k in this._patterns) {
    // pattern should be pre-compiled
    re = this._patterns[k].re;
    if(re.test(channel)) {
      indices = indices.concat(this._patterns[k]);
      this.emit(
        PUBSUB.PUBLISH, conn, channel, indices,
          [PUBSUB.PMESSAGE, k, channel, message]);
    }
  }

  len += indices.length;

  return len;
}
862402
async def receive(self, parameters: RTCRtpReceiveParameters):
        
        if not self.__started:
            for codec in parameters.codecs:
                self.__codecs[codec.payloadType] = codec
            for encoding in parameters.encodings:
                if encoding.rtx:
                    self.__rtx_ssrc[encoding.rtx.ssrc] = encoding.ssrc

            # start decoder thread
            self.__decoder_thread = threading.Thread(
                target=decoder_worker,
                name=self.__kind + '-decoder',
                args=(asyncio.get_event_loop(), self.__decoder_queue, self._track._queue))
            self.__decoder_thread.start()

            self.__transport._register_rtp_receiver(self, parameters)
            self.__rtcp_task = asyncio.ensure_future(self._run_rtcp())
            self.__started = True
294337
private int tryReserveEventSizeAndLock(long state, int size)
  {
    Preconditions.checkArgument(size > 0);
    int bufferWatermark = bufferWatermark(state);
    while (true) {
      if (compareAndSetState(state, state + size + PARTY)) {
        return bufferWatermark;
      }
      state = getState();
      if (isSealed(state)) {
        return -1;
      }
      bufferWatermark = bufferWatermark(state);
      int newBufferWatermark = bufferWatermark + size;
      Preconditions.checkState(newBufferWatermark > 0);
      if (newBufferWatermark > emitter.maxBufferWatermark) {
        return -1;
      }
    }
  }
1228171
private EConvResult transConv(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags, Ptr resultPositionPtr) {
        // null check

        if (elements[0].lastResult == EConvResult.AfterOutput) elements[0].lastResult = EConvResult.SourceBufferEmpty;

        for (int i = numTranscoders - 1; 0 <= i; i--) {
            switch (elements[i].lastResult) {
            case InvalidByteSequence:
            case IncompleteInput:
            case UndefinedConversion:
            case AfterOutput:
            case Finished:
                return transConvNeedReport(in, inPtr, inStop, out, outPtr, outStop, flags, resultPositionPtr, i + 1, i);
            case DestinationBufferFull:
            case SourceBufferEmpty:
                break;
            default:
                throw new InternalException("unexpected transcode last result");
            }
        }

        /* /^[sd]+$/ is confirmed. but actually /^s*d*$/. */

        if (elements[numTranscoders - 1].lastResult == EConvResult.DestinationBufferFull && (flags & AFTER_OUTPUT) != 0) {
            EConvResult res = transConv(NULL_STRING, Ptr.NULL, 0, out, outPtr, outStop, (flags & ~AFTER_OUTPUT) | PARTIAL_INPUT, resultPositionPtr);
            return res.isSourceBufferEmpty() ? EConvResult.AfterOutput : res;
        }

        return transConvNeedReport(in, inPtr, inStop, out, outPtr, outStop, flags, resultPositionPtr, 0, -1);
    }
1054133
function emitScopeProc (env, args) {
    var scope = env.proc('scope', 3)
    env.batchId = 'a2'

    var shared = env.shared
    var CURRENT_STATE = shared.current

    emitContext(env, scope, args.context)

    if (args.framebuffer) {
      args.framebuffer.append(env, scope)
    }

    sortState(Object.keys(args.state)).forEach(function (name) {
      var defn = args.state[name]
      var value = defn.append(env, scope)
      if (isArrayLike(value)) {
        value.forEach(function (v, i) {
          scope.set(env.next[name], '[' + i + ']', v)
        })
      } else {
        scope.set(shared.next, '.' + name, value)
      }
    })

    emitProfile(env, scope, args, true, true)

    ;[S_ELEMENTS, S_OFFSET, S_COUNT, S_INSTANCES, S_PRIMITIVE].forEach(
      function (opt) {
        var variable = args.draw[opt]
        if (!variable) {
          return
        }
        scope.set(shared.draw, '.' + opt, '' + variable.append(env, scope))
      })

    Object.keys(args.uniforms).forEach(function (opt) {
      scope.set(
        shared.uniforms,
        '[' + stringStore.id(opt) + ']',
        args.uniforms[opt].append(env, scope))
    })

    Object.keys(args.attributes).forEach(function (name) {
      var record = args.attributes[name].append(env, scope)
      var scopeAttrib = env.scopeAttrib(name)
      Object.keys(new AttributeRecord()).forEach(function (prop) {
        scope.set(scopeAttrib, '.' + prop, record[prop])
      })
    })

    function saveShader (name) {
      var shader = args.shader[name]
      if (shader) {
        scope.set(shared.shader, '.' + name, shader.append(env, scope))
      }
    }
    saveShader(S_VERT)
    saveShader(S_FRAG)

    if (Object.keys(args.state).length > 0) {
      scope(CURRENT_STATE, '.dirty=true;')
      scope.exit(CURRENT_STATE, '.dirty=true;')
    }

    scope('a1(', env.shared.context, ',a0,', env.batchId, ');')
  }
1137026
@SuppressWarnings("unchecked")
	@Override
	public <K, V> BroadcastState<K, V> getBroadcastState(final MapStateDescriptor<K, V> stateDescriptor) throws StateMigrationException {

		Preconditions.checkNotNull(stateDescriptor);
		String name = Preconditions.checkNotNull(stateDescriptor.getName());

		BackendWritableBroadcastState<K, V> previous =
			(BackendWritableBroadcastState<K, V>) accessedBroadcastStatesByName.get(name);

		if (previous != null) {
			checkStateNameAndMode(
					previous.getStateMetaInfo().getName(),
					name,
					previous.getStateMetaInfo().getAssignmentMode(),
					OperatorStateHandle.Mode.BROADCAST);
			return previous;
		}

		stateDescriptor.initializeSerializerUnlessSet(getExecutionConfig());
		TypeSerializer<K> broadcastStateKeySerializer = Preconditions.checkNotNull(stateDescriptor.getKeySerializer());
		TypeSerializer<V> broadcastStateValueSerializer = Preconditions.checkNotNull(stateDescriptor.getValueSerializer());

		BackendWritableBroadcastState<K, V> broadcastState =
			(BackendWritableBroadcastState<K, V>) registeredBroadcastStates.get(name);

		if (broadcastState == null) {
			broadcastState = new HeapBroadcastState<>(
					new RegisteredBroadcastStateBackendMetaInfo<>(
							name,
							OperatorStateHandle.Mode.BROADCAST,
							broadcastStateKeySerializer,
							broadcastStateValueSerializer));
			registeredBroadcastStates.put(name, broadcastState);
		} else {
			// has restored state; check compatibility of new state access

			checkStateNameAndMode(
					broadcastState.getStateMetaInfo().getName(),
					name,
					broadcastState.getStateMetaInfo().getAssignmentMode(),
					OperatorStateHandle.Mode.BROADCAST);

			RegisteredBroadcastStateBackendMetaInfo<K, V> restoredBroadcastStateMetaInfo = broadcastState.getStateMetaInfo();

			// check whether new serializers are incompatible
			TypeSerializerSchemaCompatibility<K> keyCompatibility =
				restoredBroadcastStateMetaInfo.updateKeySerializer(broadcastStateKeySerializer);
			if (keyCompatibility.isIncompatible()) {
				throw new StateMigrationException("The new key typeSerializer for broadcast state must not be incompatible.");
			}

			TypeSerializerSchemaCompatibility<V> valueCompatibility =
				restoredBroadcastStateMetaInfo.updateValueSerializer(broadcastStateValueSerializer);
			if (valueCompatibility.isIncompatible()) {
				throw new StateMigrationException("The new value typeSerializer for broadcast state must not be incompatible.");
			}

			broadcastState.setStateMetaInfo(restoredBroadcastStateMetaInfo);
		}

		accessedBroadcastStatesByName.put(name, broadcastState);
		return broadcastState;
	}
1224079
def begin_stream(self, command: Command) -> Reply:
        '''
        '''
        yield from self._control_stream.write_command(command)
        reply = yield from self._control_stream.read_reply()

        self.raise_if_not_match(
            'Begin stream',
            (
                ReplyCodes.file_status_okay_about_to_open_data_connection,
                ReplyCodes.data_connection_already_open_transfer_starting,
            ),
            reply
        )

        return reply
749748
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  if (!isBuf) {
    chunk = decodeChunk(state, chunk, encoding);
    if (Buffer.isBuffer(chunk)) encoding = 'buffer';
  }
  var len = state.objectMode ? 1 : chunk.length;

  state.length += len;

  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret) state.needDrain = true;

  if (state.writing || state.corked) {
    var last = state.lastBufferedRequest;
    state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
    if (last) {
      last.next = state.lastBufferedRequest;
    } else {
      state.bufferedRequest = state.lastBufferedRequest;
    }
    state.bufferedRequestCount += 1;
  } else {
    doWrite(stream, state, false, len, chunk, encoding, cb);
  }

  return ret;
}