_run_op_kind (FlatpakTransaction           *self,
              FlatpakTransactionOperation  *op,
              FlatpakRemoteState           *remote_state, /* nullable */
              gboolean                     *out_needs_prune,
              gboolean                     *out_needs_triggers,
              gboolean                     *out_needs_cache_drop,
              GCancellable                 *cancellable,
              GError                      **error)
{
  FlatpakTransactionPrivate *priv = flatpak_transaction_get_instance_private (self);
  gboolean res = TRUE;

  g_return_val_if_fail (remote_state != NULL || op->kind == FLATPAK_TRANSACTION_OPERATION_UNINSTALL, FALSE);

  if (op->kind == FLATPAK_TRANSACTION_OPERATION_INSTALL)
    {
      g_autoptr(FlatpakTransactionProgress) progress = flatpak_transaction_progress_new ();
      FlatpakTransactionResult result_details = 0;
      g_autoptr(GError) local_error = NULL;

      emit_new_op (self, op, progress);

      g_assert (op->resolved_commit != NULL); /* We resolved this before */

      if (op->resolved_metakey && !flatpak_check_required_version (flatpak_decomposed_get_ref (op->ref),
                                                                   op->resolved_metakey, &local_error))
        res = FALSE;
      else
        res = flatpak_dir_install (priv->dir,
                                   priv->no_pull,
                                   priv->no_deploy,
                                   priv->disable_static_deltas,
                                   priv->reinstall,
                                   priv->max_op >= APP_UPDATE,
                                   op->pin_on_deploy,
                                   remote_state, op->ref,
                                   op->resolved_commit,
                                   (const char **) op->subpaths,
                                   (const char **) op->previous_ids,
                                   op->resolved_sideload_path,
                                   op->resolved_metadata,
                                   op->resolved_token,
                                   progress->progress_obj,
                                   cancellable, &local_error);

      flatpak_transaction_progress_done (progress);

      /* Handle noop-installs (maybe we raced, or this was installed in install-authenticator)
       * We do initial checks and fail with already installed in add_ref() for other cases. */
      if (!res && g_error_matches (local_error, FLATPAK_ERROR, FLATPAK_ERROR_ALREADY_INSTALLED))
        {
          res = TRUE;
          g_clear_error (&local_error);

          result_details |= FLATPAK_TRANSACTION_RESULT_NO_CHANGE;
        }
      else if (!res)
        {
          g_propagate_error (error, g_steal_pointer (&local_error));
        }

      if (res)
        {
          emit_op_done (self, op, result_details);

          /* Normally we don't need to prune after install, because it makes no old objects
             stale. However if we reinstall, that is not true. */
          if (!priv->no_pull && priv->reinstall)
            *out_needs_prune = TRUE;

          if (flatpak_decomposed_is_app (op->ref))
            *out_needs_triggers = TRUE;

          if (op->pin_on_deploy)
            *out_needs_cache_drop = TRUE;
        }
    }
  else if (op->kind == FLATPAK_TRANSACTION_OPERATION_UPDATE)
    {
      g_assert (op->resolved_commit != NULL); /* We resolved this before */

      if (flatpak_dir_needs_update_for_commit_and_subpaths (priv->dir, op->remote, op->ref,
                                                            op->resolved_commit, (const char **) op->subpaths))
        {
          g_autoptr(FlatpakTransactionProgress) progress = flatpak_transaction_progress_new ();
          FlatpakTransactionResult result_details = 0;
          g_autoptr(GError) local_error = NULL;

          emit_new_op (self, op, progress);

          if (op->resolved_metakey && !flatpak_check_required_version (flatpak_decomposed_get_ref (op->ref),
                                                                       op->resolved_metakey, &local_error))
            res = FALSE;
          else if (op->update_only_deploy)
            res = flatpak_dir_deploy_update (priv->dir, op->ref,
                                             op->resolved_commit,
                                             (const char **) op->subpaths,
                                             (const char **) op->previous_ids,
                                             cancellable, &local_error);
          else
            res = flatpak_dir_update (priv->dir,
                                      priv->no_pull,
                                      priv->no_deploy,
                                      priv->disable_static_deltas,
                                      op->commit != NULL, /* Allow downgrade if we specify commit */
                                      priv->max_op >= APP_UPDATE,
                                      priv->max_op == APP_INSTALL || priv->max_op == RUNTIME_INSTALL,
                                      remote_state,
                                      op->ref,
                                      op->resolved_commit,
                                      (const char **) op->subpaths,
                                      (const char **) op->previous_ids,
                                      op->resolved_sideload_path,
                                      op->resolved_metadata,
                                      op->resolved_token,
                                      progress->progress_obj,
                                      cancellable, &local_error);
          flatpak_transaction_progress_done (progress);

          /* Handle noop-updates */
          if (!res && g_error_matches (local_error, FLATPAK_ERROR, FLATPAK_ERROR_ALREADY_INSTALLED))
            {
              res = TRUE;
              g_clear_error (&local_error);

              result_details |= FLATPAK_TRANSACTION_RESULT_NO_CHANGE;
            }
          else if (!res)
            {
              g_propagate_error (error, g_steal_pointer (&local_error));
            }

          if (res)
            {
              emit_op_done (self, op, result_details);

              if (!priv->no_pull)
                *out_needs_prune = TRUE;

              if (flatpak_decomposed_is_app (op->ref))
                *out_needs_triggers = TRUE;
            }
        }
      else
        g_debug ("%s need no update", flatpak_decomposed_get_ref (op->ref));
    }
  else if (op->kind == FLATPAK_TRANSACTION_OPERATION_INSTALL_BUNDLE)
    {
      g_autoptr(FlatpakTransactionProgress) progress = flatpak_transaction_progress_new ();
      emit_new_op (self, op, progress);
      if (op->resolved_metakey && !flatpak_check_required_version (flatpak_decomposed_get_ref (op->ref),
                                                                   op->resolved_metakey, error))
        res = FALSE;
      else
        res = flatpak_dir_install_bundle (priv->dir, op->bundle,
                                          op->remote, NULL,
                                          cancellable, error);
      flatpak_transaction_progress_done (progress);

      if (res)
        {
          emit_op_done (self, op, 0);
          *out_needs_prune = TRUE;
          *out_needs_triggers = TRUE;
        }
    }
  else if (op->kind == FLATPAK_TRANSACTION_OPERATION_UNINSTALL)
    {
      g_autoptr(FlatpakTransactionProgress) progress = flatpak_transaction_progress_new ();
      FlatpakHelperUninstallFlags flags = 0;

      if (priv->disable_prune)
        flags |= FLATPAK_HELPER_UNINSTALL_FLAGS_KEEP_REF;

      if (priv->force_uninstall)
        flags |= FLATPAK_HELPER_UNINSTALL_FLAGS_FORCE_REMOVE;

      emit_new_op (self, op, progress);

      res = flatpak_dir_uninstall (priv->dir, op->ref, flags,
                                   cancellable, error);

      flatpak_transaction_progress_done (progress);

      if (res)
        {
          emit_op_done (self, op, 0);
          *out_needs_prune = TRUE;

          if (flatpak_decomposed_is_app (op->ref))
            *out_needs_triggers = TRUE;
        }
    }
  else
    g_assert_not_reached ();

  return res;
}


 int main(int argc, char *argv[]) {
	p_fm_config_conx_hdlt	hdl;
 	int						instance = 0;
 	fm_mgr_config_errno_t	res;
 	char					*rem_addr = NULL;
	char					*community = "public";
	char            		Opts[256];
    int             		arg;
	char 					*command;
	int						i;

	/* Get options at the command line (overide default values) */
    strcpy(Opts, "i:d:h-");

    while ((arg = getopt(argc, argv, Opts)) != EOF) {
        switch (arg) {
		case 'h':
		case '-':
			usage(argv[0]);
			return(0);
		case 'i':
			instance = atol(optarg);
			break;
		case 'd':
			rem_addr = optarg;
			break;
		default:
			usage(argv[0]);
			return(-1);
		}
	}

	if(optind >= argc){
        fprintf(stderr, "Command required\n");
		usage(argv[0]);
		return -1;
	}

	command = argv[optind++];
	printf("Connecting to %s FM instance %d\n", (rem_addr==NULL) ? "LOCAL":rem_addr, instance);
 	if((res = fm_mgr_config_init(&hdl,instance, rem_addr, community)) != FM_CONF_OK)
 	{
 		fprintf(stderr, "Failed to initialize the client handle: %d\n", res);
		goto die_clean;
 	}

 	if((res = fm_mgr_config_connect(hdl)) != FM_CONF_OK)
 	{
 		fprintf(stderr, "Failed to connect: (%d) %s\n",res,fm_mgr_get_error_str(res));
		goto die_clean;
 	}

 	for(i=0;i<commandListLen;i++){
 		if(strcmp(command,commandList[i].name) == 0){
			return commandList[i].cmdPtr(hdl, commandList[i].mgr, (argc - optind), &argv[optind]);
 		}
 	}

 	fprintf(stderr, "Command (%s) is not valid\n",command);
 	usage(argv[0]);
 	res = -1;

die_clean:
	if (hdl) free(hdl);
 	return res;
 }


	Mode(User* source, Channel* Chantarget, User* Usertarget, const Modes::ChangeList& changelist, Modes::ChangeList::List::const_iterator beginiter)
		: ClientProtocol::Message("MODE", source)
		, chantarget(Chantarget)
		, usertarget(Usertarget)
		, beginit(beginiter)
	{
		PushParamRef(GetStrTarget());
		PushParam(ToModeLetters(changelist.getlist(), 450, beginit, lastit));
		PushModeParams();
	}


static int mime_header_encoder_block_collector ( int c , void * data ) {
 int n ;
 struct mime_header_encoder_data * pe = ( struct mime_header_encoder_data * ) data ;
 switch ( pe -> status2 ) {
 case 1 : pe -> prevpos = pe -> outdev . pos ;
 mbfl_convert_filter_copy ( pe -> conv2_filter , pe -> conv2_filter_backup ) ;
 mbfl_convert_filter_copy ( pe -> encod_filter , pe -> encod_filter_backup ) ;
 ( * pe -> conv2_filter -> filter_function ) ( c , pe -> conv2_filter ) ;
 ( * pe -> conv2_filter -> filter_flush ) ( pe -> conv2_filter ) ;
 ( * pe -> encod_filter -> filter_flush ) ( pe -> encod_filter ) ;
 n = pe -> outdev . pos - pe -> linehead + pe -> firstindent ;
 pe -> outdev . pos = pe -> prevpos ;
 mbfl_convert_filter_copy ( pe -> conv2_filter_backup , pe -> conv2_filter ) ;
 mbfl_convert_filter_copy ( pe -> encod_filter_backup , pe -> encod_filter ) ;
 if ( n >= 74 ) {
 ( * pe -> conv2_filter -> filter_flush ) ( pe -> conv2_filter ) ;
 ( * pe -> encod_filter -> filter_flush ) ( pe -> encod_filter ) ;
 mbfl_memory_device_strncat ( & pe -> outdev , "\x3f\x3d" , 2 ) ;
 mbfl_memory_device_strncat ( & pe -> outdev , pe -> lwsp , pe -> lwsplen ) ;
 pe -> linehead = pe -> outdev . pos ;
 pe -> firstindent = 0 ;
 mbfl_memory_device_strncat ( & pe -> outdev , pe -> encname , pe -> encnamelen ) ;
 c = ( * pe -> conv2_filter -> filter_function ) ( c , pe -> conv2_filter ) ;
 }
 else {
 c = ( * pe -> conv2_filter -> filter_function ) ( c , pe -> conv2_filter ) ;
 }
 break ;
 default : mbfl_memory_device_strncat ( & pe -> outdev , pe -> encname , pe -> encnamelen ) ;
 c = ( * pe -> conv2_filter -> filter_function ) ( c , pe -> conv2_filter ) ;
 pe -> status2 = 1 ;
 break ;
 }
 return c ;
 }


int wc_ecc_init_id(ecc_key* key, unsigned char* id, int len, void* heap,
                   int devId)
{
    int ret = 0;

    if (key == NULL)
        ret = BAD_FUNC_ARG;
    if (ret == 0 && (len < 0 || len > ECC_MAX_ID_LEN))
        ret = BUFFER_E;

    if (ret == 0)
        ret = wc_ecc_init_ex(key, heap, devId);

    if (ret == 0 && id != NULL && len != 0) {
        XMEMCPY(key->id, id, len);
        key->idLen = len;
    }

    return ret;
}


PHP_METHOD(Phar, delMetadata)
{
	char *error;

	PHAR_ARCHIVE_OBJECT();

	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
		return;
	}

	if (Z_TYPE(phar_obj->archive->metadata) != IS_UNDEF) {
		zval_ptr_dtor(&phar_obj->archive->metadata);
		ZVAL_UNDEF(&phar_obj->archive->metadata);
		phar_obj->archive->is_modified = 1;
		phar_flush(phar_obj->archive, 0, 0, 0, &error);

		if (error) {
			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
			efree(error);
			RETURN_FALSE;
		} else {
			RETURN_TRUE;
		}

	} else {
		RETURN_TRUE;
	}
}


GF_Err gf_isom_remove_sample_group(GF_ISOFile *movie, u32 track, u32 grouping_type)
{
	GF_Err e;
	GF_TrackBox *trak;
	u32 count, i;

	e = CanAccessMovie(movie, GF_ISOM_OPEN_WRITE);
	if (e) return e;

	trak = gf_isom_get_track_from_file(movie, track);
	if (!trak) return GF_BAD_PARAM;

	if (trak->Media->information->sampleTable->sampleGroupsDescription) {
		count = gf_list_count(trak->Media->information->sampleTable->sampleGroupsDescription);
		for (i=0; i<count; i++) {
			GF_SampleGroupDescriptionBox *sgdesc = (GF_SampleGroupDescriptionBox*)gf_list_get(trak->Media->information->sampleTable->sampleGroupsDescription, i);
			if (sgdesc->grouping_type==grouping_type) {
				gf_isom_box_del_parent(&trak->Media->information->sampleTable->child_boxes, (GF_Box*)sgdesc);
				gf_list_rem(trak->Media->information->sampleTable->sampleGroupsDescription, i);
				i--;
				count--;
			}
		}
	}
	if (trak->Media->information->sampleTable->sampleGroups) {
		count = gf_list_count(trak->Media->information->sampleTable->sampleGroups);
		for (i=0; i<count; i++) {
			GF_SampleGroupBox *sgroup = gf_list_get(trak->Media->information->sampleTable->sampleGroups, i);
			if (sgroup->grouping_type==grouping_type) {
				gf_isom_box_del_parent(&trak->Media->information->sampleTable->child_boxes, (GF_Box*)sgroup);
				gf_list_rem(trak->Media->information->sampleTable->sampleGroups, i);
				i--;
				count--;
			}
		}
	}
	return GF_OK;
}


LogLuvInitState(TIFF* tif)
{
	static const char module[] = "LogLuvInitState";
	TIFFDirectory* td = &tif->tif_dir;
	LogLuvState* sp = DecoderState(tif);

	assert(sp != NULL);
	assert(td->td_photometric == PHOTOMETRIC_LOGLUV);

	/* for some reason, we can't do this in TIFFInitLogLuv */
	if (td->td_planarconfig != PLANARCONFIG_CONTIG) {
		TIFFErrorExt(tif->tif_clientdata, module,
		    "SGILog compression cannot handle non-contiguous data");
		return (0);
	}
	if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
		sp->user_datafmt = LogLuvGuessDataFmt(td);
	switch (sp->user_datafmt) {
	case SGILOGDATAFMT_FLOAT:
		sp->pixel_size = 3*sizeof (float);
		break;
	case SGILOGDATAFMT_16BIT:
		sp->pixel_size = 3*sizeof (int16);
		break;
	case SGILOGDATAFMT_RAW:
		sp->pixel_size = sizeof (uint32);
		break;
	case SGILOGDATAFMT_8BIT:
		sp->pixel_size = 3*sizeof (uint8);
		break;
	default:
		TIFFErrorExt(tif->tif_clientdata, module,
		    "No support for converting user data format to LogLuv");
		return (0);
	}
        if( isTiled(tif) )
            sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
        else
            sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
	if (multiply_ms(sp->tbuflen, sizeof (uint32)) == 0 ||
	    (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (uint32))) == NULL) {
		TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer");
		return (0);
	}
	return (1);
}


static int deliver_response(struct ipmi_smi *intf, struct ipmi_recv_msg *msg)
{
	int rv = 0;

	if (!msg->user) {
		/* Special handling for NULL users. */
		if (intf->null_user_handler) {
			intf->null_user_handler(intf, msg);
		} else {
			/* No handler, so give up. */
			rv = -EINVAL;
		}
		ipmi_free_recv_msg(msg);
	} else if (oops_in_progress) {
		/*
		 * If we are running in the panic context, calling the
		 * receive handler doesn't much meaning and has a deadlock
		 * risk.  At this moment, simply skip it in that case.
		 */
		ipmi_free_recv_msg(msg);
	} else {
		int index;
		struct ipmi_user *user = acquire_ipmi_user(msg->user, &index);

		if (user) {
			user->handler->ipmi_recv_hndl(msg, user->handler_data);
			release_ipmi_user(user, index);
		} else {
			/* User went away, give up. */
			ipmi_free_recv_msg(msg);
			rv = -EINVAL;
		}
	}

	return rv;
}


gsm_xsmp_client_new (IceConn ice_conn)
{
        GsmXSMPClient *xsmp;

        xsmp = g_object_new (GSM_TYPE_XSMP_CLIENT,
                             "ice-connection", ice_conn,
                             NULL);

        return GSM_CLIENT (xsmp);
}


randomize_range(unsigned long start, unsigned long end, unsigned long len)
{
	unsigned long range = end - len - start;

	if (end <= start + len)
		return 0;
	return PAGE_ALIGN(get_random_int() % range + start);
}


static int coolkey_apdu_io(sc_card_t *card, int cla, int ins, int p1, int p2,
	const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen,
	const u8 *nonce, size_t nonce_len)
{
	int r;
	sc_apdu_t apdu;
	u8 rbufinitbuf[COOLKEY_MAX_SIZE];
	u8 rsendbuf[COOLKEY_MAX_SIZE];
	u8 *rbuf;
	size_t rbuflen;
	int cse = 0;

	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);

	sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
		 "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
		 ins, p1, p2, sendbuflen, card->max_send_size,
		 card->max_recv_size);

	rbuf = rbufinitbuf;
	rbuflen = sizeof(rbufinitbuf);

	/* if caller provided a buffer and length */
	if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) {
		rbuf = *recvbuf;
		rbuflen = *recvbuflen;
	}

	if (sendbuf || nonce) {
		if (recvbuf) {
			cse = SC_APDU_CASE_4_SHORT;
		} else {
			cse = SC_APDU_CASE_3_SHORT;
		}
	} else {
		if (recvbuf) {
			cse = SC_APDU_CASE_2_SHORT;
		} else {
			cse = SC_APDU_CASE_1;
		}
	}

	/* append the nonce if we have it. Coolkey just blindly puts this at the end
	 * of the APDU (while adjusting lc). This converts case 1 to case 3. coolkey
	 * also always drops le in case 4 (which happens when proto = T0). nonces are
	 * never used on case 2 commands, so we can simply append the nonce to the data
	 * and we should be fine */
	if (nonce) {
		u8 *buf = rsendbuf;
		if (sendbuf) {
			sendbuflen = MIN(sendbuflen,sizeof(rsendbuf)-nonce_len);
			memcpy(rsendbuf, sendbuf, sendbuflen);
			buf += sendbuflen;
		}
		memcpy(buf, nonce, nonce_len);
		sendbuflen += nonce_len;
		sendbuf =rsendbuf;
	}

	sc_format_apdu(card, &apdu, cse, ins, p1, p2);

	apdu.lc = sendbuflen;
	apdu.datalen = sendbuflen;
	apdu.data = sendbuf;

	/* coolkey uses non-standard classes */
	apdu.cla = cla;

	if (recvbuf) {
		apdu.resp = rbuf;
		apdu.le = (rbuflen > 255) ? 255 : rbuflen;
		apdu.resplen = rbuflen;
	} else {
		 apdu.resp =  rbuf;
		 apdu.le = 0;
		 apdu.resplen = 0;
	}

	sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
		 "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p",
		 apdu.flags, apdu.le, apdu.resplen, apdu.resp);

	/* with new adpu.c and chaining, this actually reads the whole object */
	r = sc_transmit_apdu(card, &apdu);

	sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
		 "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x",
		 r, apdu.resplen, apdu.sw1, apdu.sw2);

	if (r < 0) {
		sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed");
		goto err;
	}
	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
	if (r < 0) {
		sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed");
		goto err;
	}

	if (recvbuflen) {
		if (recvbuf && *recvbuf == NULL) {
			*recvbuf =  malloc(apdu.resplen);
			if (*recvbuf == NULL) {
				r = SC_ERROR_OUT_OF_MEMORY;
				goto err;
			}
			memcpy(*recvbuf, rbuf, apdu.resplen);
		}
		*recvbuflen =  apdu.resplen;
		r = *recvbuflen;
	}

err:
	SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}


static int packet_create(struct net *net, struct socket *sock, int protocol,
			 int kern)
{
	struct sock *sk;
	struct packet_sock *po;
	__be16 proto = (__force __be16)protocol; /* weird, but documented */
	int err;

	if (!capable(CAP_NET_RAW))
		return -EPERM;
	if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
	    sock->type != SOCK_PACKET)
		return -ESOCKTNOSUPPORT;

	sock->state = SS_UNCONNECTED;

	err = -ENOBUFS;
	sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto);
	if (sk == NULL)
		goto out;

	sock->ops = &packet_ops;
	if (sock->type == SOCK_PACKET)
		sock->ops = &packet_ops_spkt;

	sock_init_data(sock, sk);

	po = pkt_sk(sk);
	sk->sk_family = PF_PACKET;
	po->num = proto;

	sk->sk_destruct = packet_sock_destruct;
	sk_refcnt_debug_inc(sk);

	/*
	 *	Attach a protocol block
	 */

	spin_lock_init(&po->bind_lock);
	mutex_init(&po->pg_vec_lock);
	po->prot_hook.func = packet_rcv;

	if (sock->type == SOCK_PACKET)
		po->prot_hook.func = packet_rcv_spkt;

	po->prot_hook.af_packet_priv = sk;

	if (proto) {
		po->prot_hook.type = proto;
		dev_add_pack(&po->prot_hook);
		sock_hold(sk);
		po->running = 1;
	}

	spin_lock_bh(&net->packet.sklist_lock);
	sk_add_node_rcu(sk, &net->packet.sklist);
	sock_prot_inuse_add(net, &packet_proto, 1);
	spin_unlock_bh(&net->packet.sklist_lock);

	return 0;
out:
	return err;
}


static void pdf_run_cs ( fz_context * ctx , pdf_processor * proc , const char * name , fz_colorspace * colorspace ) {
 pdf_run_processor * pr = ( pdf_run_processor * ) proc ;
 pr -> dev -> flags &= ~ FZ_DEVFLAG_FILLCOLOR_UNDEFINED ;
 if ( ! strcmp ( name , "Pattern" ) ) pdf_set_pattern ( ctx , pr , PDF_FILL , NULL , NULL ) ;
 else pdf_set_colorspace ( ctx , pr , PDF_FILL , colorspace ) ;
 }


void HTTP2Codec::onHeader(const folly::fbstring& name,
                          const folly::fbstring& value) {
  if (decodeInfo_.onHeader(name, value)) {
    if (name == "user-agent" && userAgent_.empty()) {
      userAgent_ = value.toStdString();
    }
  } else {
    VLOG(4) << "dir=" << uint32_t(transportDirection_) <<
      decodeInfo_.parsingError << " codec=" << headerCodec_;
  }
}


void WebMediaPlayerImpl::OnPause() {
  client_->RequestPause();
}


static int make_cdt16_entry(int p1, int p2, int16_t *cdt)

{

    int r, b, lo;

    b = cdt[p2];

    r = cdt[p1] << 11;

    lo = b + r;

    return (lo + (lo << 16)) << 1;

}


static char* mpjpeg_get_boundary(AVIOContext* pb)

{

    uint8_t *mime_type = NULL;

    const char *start;

    const char *end;

    uint8_t *res = NULL;

    int     len;

    /* get MIME type, and skip to the first parameter */

    av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type);

    start = mime_type;

    while (start != NULL && *start != '\0') {

        start = strchr(start, ';');

        if (start)

            start = start+1;

        while (av_isspace(*start))

            start++;

        if (!av_stristart(start, "boundary=", &start)) {

            end = strchr(start, ';');

            if (end)

                len = end - start - 1;

            else

                len = strlen(start);

            res = av_strndup(start, len);

            break;

        }

    }

    av_freep(&mime_type);

    return res;

}


  tt_sbit_decoder_load_compound( TT_SBitDecoder  decoder,
                                 FT_Byte*        p,
                                 FT_Byte*        limit,
                                 FT_Int          x_pos,
                                 FT_Int          y_pos )
  {
    FT_Error  error = FT_Err_Ok;
    FT_UInt   num_components, nn;

    FT_Char  horiBearingX = (FT_Char)decoder->metrics->horiBearingX;
    FT_Char  horiBearingY = (FT_Char)decoder->metrics->horiBearingY;
    FT_Byte  horiAdvance  = (FT_Byte)decoder->metrics->horiAdvance;
    FT_Char  vertBearingX = (FT_Char)decoder->metrics->vertBearingX;
    FT_Char  vertBearingY = (FT_Char)decoder->metrics->vertBearingY;
    FT_Byte  vertAdvance  = (FT_Byte)decoder->metrics->vertAdvance;

    if ( p + 2 > limit )
      goto Fail;

    num_components = FT_NEXT_USHORT( p );
    if ( p + 4 * num_components > limit )
    {
      FT_TRACE1(( "tt_sbit_decoder_load_compound: broken table\n" ));
      goto Fail;
    }

    FT_TRACE3(( "tt_sbit_decoder_load_compound: loading %d components\n",
                num_components ));

    for ( nn = 0; nn < num_components; nn++ )
    {
      FT_UInt  gindex = FT_NEXT_USHORT( p );
      FT_Byte  dx     = FT_NEXT_BYTE( p );
      FT_Byte  dy     = FT_NEXT_BYTE( p );

      /* NB: a recursive call */
      error = tt_sbit_decoder_load_image( decoder, gindex,
                                          x_pos + dx, y_pos + dy );
      if ( error )
        break;
    }

    FT_TRACE3(( "tt_sbit_decoder_load_compound: done\n" ));

    decoder->metrics->horiBearingX = horiBearingX;
    decoder->metrics->horiBearingY = horiBearingY;
    decoder->metrics->horiAdvance  = horiAdvance;
    decoder->metrics->vertBearingX = vertBearingX;
    decoder->metrics->vertBearingY = vertBearingY;
    decoder->metrics->vertAdvance  = vertAdvance;
    decoder->metrics->width        = (FT_Byte)decoder->bitmap->width;
    decoder->metrics->height       = (FT_Byte)decoder->bitmap->rows;

  Exit:
    return error;

  Fail:
    error = FT_THROW( Invalid_File_Format );
    goto Exit;
  }


static int cmd_interpret(void *data, const char *input) {
	char *str, *ptr, *eol, *rbuf, *filter, *inp;
	const char *host, *port, *cmd;
	RCore *core = (RCore *)data;

	switch (*input) {
	case '\0':
		r_core_cmd_repeat (core, 0);
		break;
	case ':':
		if ((ptr = strchr (input + 1, ' '))) {
			/* .:port cmd */
			/* .:host:port cmd */
			cmd = ptr + 1;
			*ptr = 0;
			eol = strchr (input + 1, ':');
			if (eol) {
				*eol = 0;
				host = input + 1;
				port = eol + 1;
			} else {
				host = "localhost";
				port = input + ((input[1] == ':')? 2: 1);
			}
			rbuf = r_core_rtr_cmds_query (core, host, port, cmd);
			if (rbuf) {
				r_cons_print (rbuf);
				free (rbuf);
			}
		} else {
			r_core_rtr_cmds (core, input + 1);
		}
		break;
	case '.': // same as \n
		r_core_cmd_repeat (core, 1);
		break;
	case '-':
		if (input[1] == '?') {
			r_cons_printf ("Usage: '-' '.-' '. -' do the same\n");
		} else {
			r_core_run_script (core, "-");
		}
		break;
	case ' ':
		if (!r_core_run_script (core, input + 1)) {
			eprintf ("Cannot find script '%s'\n", input + 1);
			core->num->value = 1;
		} else {
			core->num->value = 0;
		}
		break;
	case '!':
		/* from command */
		r_core_cmd_command (core, input + 1);
		break;
	case '(':
		r_cmd_macro_call (&core->rcmd->macro, input + 1);
		break;
	case '?':{
		const char* help_msg[] = {
		"Usage:", ".[r2cmd] | [file] | [!command] | [(macro)]", " # define macro or load r2, cparse or rlang file",
		".", "", "repeat last command backward",
		".", "r2cmd", "interpret the output of the command as r2 commands",
		"..", "", "repeat last command forward (same as \\n)",
		".:", "8080", "listen for commands on given tcp port",
		".", " foo.r2", "interpret r2 script",
		".-", "", "open cfg.editor and interpret tmp file",
		".!", "rabin -ri $FILE", "interpret output of command",
		".", "(foo 1 2 3)", "run macro 'foo' with args 1, 2, 3",
		"./", " ELF", "interpret output of command /m ELF as r. commands",
		NULL};
		r_core_cmd_help (core, help_msg);
		}
		break;
	default:
		if (*input >= 0 && *input <= 9) {
			eprintf ("|ERROR| No .[0..9] to avoid infinite loops\n");
			break;
		}
		inp = strdup (input);
		filter = strchr (inp, '~');
		if (filter) {
			*filter = 0;
		}
		ptr = str = r_core_cmd_str (core, inp);
		if (filter) {
			*filter = '~';
		}
		r_cons_break_push (NULL, NULL);
		if (ptr) {
			for (;;) {
				if (r_cons_is_breaked ()) {
					break;
				}
				eol = strchr (ptr, '\n');
				if (eol) *eol = '\0';
				if (*ptr) {
					char *p = r_str_append (strdup (ptr), filter);
					r_core_cmd0 (core, p);
					free (p);
				}
				if (!eol) break;
				ptr = eol + 1;
			}
		}
		r_cons_break_pop ();
		free (str);
		free (inp);
		break;
	}
	return 0;
}


void RenderViewImpl::willSendRequest(WebFrame* frame,
                                     unsigned identifier,
                                     WebURLRequest& request,
                                     const WebURLResponse& redirect_response) {
  WebFrame* top_frame = frame->top();
  if (!top_frame)
    top_frame = frame;
  WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
  WebDataSource* top_data_source = top_frame->dataSource();
  WebDataSource* data_source =
      provisional_data_source ? provisional_data_source : top_data_source;

  content::PageTransition transition_type = content::PAGE_TRANSITION_LINK;
  DocumentState* document_state = DocumentState::FromDataSource(data_source);
  DCHECK(document_state);
  NavigationState* navigation_state = document_state->navigation_state();
  transition_type = navigation_state->transition_type();

  GURL request_url(request.url());
  GURL new_url;
  if (content::GetContentClient()->renderer()->WillSendRequest(
      frame, transition_type, request_url, &new_url)) {
    request.setURL(WebURL(new_url));
  }

  if (document_state->is_cache_policy_override_set())
    request.setCachePolicy(document_state->cache_policy_override());

  WebKit::WebReferrerPolicy referrer_policy;
  if (document_state && document_state->is_referrer_policy_set()) {
    referrer_policy = document_state->referrer_policy();
    document_state->clear_referrer_policy();
  } else {
    referrer_policy = frame->document().referrerPolicy();
  }

  WebString custom_user_agent;
  if (request.extraData()) {
    webkit_glue::WebURLRequestExtraDataImpl* old_extra_data =
        static_cast<webkit_glue::WebURLRequestExtraDataImpl*>(
            request.extraData());
    custom_user_agent = old_extra_data->custom_user_agent();

    if (!custom_user_agent.isNull()) {
      if (custom_user_agent.isEmpty())
        request.clearHTTPHeaderField("User-Agent");
      else
        request.setHTTPHeaderField("User-Agent", custom_user_agent);
    }
  }

  request.setExtraData(
      new RequestExtraData(referrer_policy,
                           custom_user_agent,
                           (frame == top_frame),
                           frame->identifier(),
                           frame->parent() == top_frame,
                           frame->parent() ? frame->parent()->identifier() : -1,
                           navigation_state->allow_download(),
                           transition_type,
                           navigation_state->transferred_request_child_id(),
                           navigation_state->transferred_request_request_id()));

  DocumentState* top_document_state =
      DocumentState::FromDataSource(top_data_source);
  if (top_document_state &&
      request.targetType() == WebURLRequest::TargetIsPrefetch)
    top_document_state->set_was_prefetcher(true);

  request.setRequestorID(routing_id_);
  request.setHasUserGesture(frame->isProcessingUserGesture());

  if (!renderer_preferences_.enable_referrers)
    request.clearHTTPHeaderField("Referer");
}


static ut64 baddr(RBinFile *arch) {
	return 0;
}


PHP_FUNCTION(dom_document_import_node)
{
	zval *id, *node;
	xmlDocPtr docp;
	xmlNodePtr nodep, retnodep;
	dom_object *intern, *nodeobj;
	int ret;
	long recursive = 0;

	if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &id, dom_document_class_entry, &node, dom_node_class_entry, &recursive) == FAILURE) {
		return;
	}

	DOM_GET_OBJ(docp, id, xmlDocPtr, intern);

	DOM_GET_OBJ(nodep, node, xmlNodePtr, nodeobj);

	if (nodep->type == XML_HTML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_NODE
		|| nodep->type == XML_DOCUMENT_TYPE_NODE) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot import: Node Type Not Supported");
		RETURN_FALSE;
	}

	if (nodep->doc == docp) {
		retnodep = nodep;
	} else {
		if ((recursive == 0) && (nodep->type == XML_ELEMENT_NODE)) {
			recursive = 2;
		}
		retnodep = xmlDocCopyNode(nodep, docp, recursive);
		if (!retnodep) {
			RETURN_FALSE;
		}

		if ((retnodep->type == XML_ATTRIBUTE_NODE) && (nodep->ns != NULL)) {
			xmlNsPtr nsptr = NULL;
			xmlNodePtr root = xmlDocGetRootElement(docp);

			nsptr = xmlSearchNsByHref (nodep->doc, root, nodep->ns->href);
			if (nsptr == NULL) {
				int errorcode;
				nsptr = dom_get_ns(root, (char *) nodep->ns->href, &errorcode, (char *) nodep->ns->prefix);
			}
			xmlSetNs(retnodep, nsptr);
		}
	}

	DOM_RET_OBJ((xmlNodePtr) retnodep, &ret, intern);
}


static void crs_replace_with_free_ranges(GPtrArray *ranges,

                                         uint64_t start, uint64_t end)

{

    GPtrArray *free_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    uint64_t free_base = start;

    int i;

    g_ptr_array_sort(ranges, crs_range_compare);

    for (i = 0; i < ranges->len; i++) {

        CrsRangeEntry *used = g_ptr_array_index(ranges, i);

        if (free_base < used->base) {

            crs_range_insert(free_ranges, free_base, used->base - 1);

        }

        free_base = used->limit + 1;

    }

    if (free_base < end) {

        crs_range_insert(free_ranges, free_base, end);

    }

    g_ptr_array_set_size(ranges, 0);

    for (i = 0; i < free_ranges->len; i++) {

        g_ptr_array_add(ranges, g_ptr_array_index(free_ranges, i));

    }

    g_ptr_array_free(free_ranges, false);

}


static int ff_estimate_motion_b(MpegEncContext * s,

                       int mb_x, int mb_y, int16_t (*mv_table)[2], Picture *picture, int f_code)

{

    int mx, my, range, dmin;

    int xmin, ymin, xmax, ymax;

    int rel_xmin, rel_ymin, rel_xmax, rel_ymax;

    int pred_x=0, pred_y=0;

    int P[10][2];

    const int shift= 1+s->quarter_sample;

    const int mot_stride = s->mb_width + 2;

    const int mot_xy = (mb_y + 1)*mot_stride + mb_x + 1;

    uint8_t * const ref_picture= picture->data[0];

    uint16_t * const mv_penalty= s->me.mv_penalty[f_code] + MAX_MV;

    int mv_scale;

    s->me.penalty_factor    = get_penalty_factor(s, s->avctx->me_cmp);

    s->me.sub_penalty_factor= get_penalty_factor(s, s->avctx->me_sub_cmp);

    s->me.mb_penalty_factor = get_penalty_factor(s, s->avctx->mb_cmp);

    get_limits(s, &range, &xmin, &ymin, &xmax, &ymax, f_code);

    rel_xmin= xmin - mb_x*16;

    rel_xmax= xmax - mb_x*16;

    rel_ymin= ymin - mb_y*16;

    rel_ymax= ymax - mb_y*16;

    switch(s->me_method) {

    case ME_ZERO:

    default:

	no_motion_search(s, &mx, &my);

        dmin = 0;

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_FULL:

	dmin = full_motion_search(s, &mx, &my, range, xmin, ymin, xmax, ymax, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_LOG:

	dmin = log_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_PHODS:

	dmin = phods_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_X1:

    case ME_EPZS:

       {

            P_LEFT[0]        = mv_table[mot_xy - 1][0];

            P_LEFT[1]        = mv_table[mot_xy - 1][1];

            if(P_LEFT[0]       > (rel_xmax<<shift)) P_LEFT[0]       = (rel_xmax<<shift);

            /* special case for first line */

            if (mb_y) {

                P_TOP[0] = mv_table[mot_xy - mot_stride             ][0];

                P_TOP[1] = mv_table[mot_xy - mot_stride             ][1];

                P_TOPRIGHT[0] = mv_table[mot_xy - mot_stride + 1         ][0];

                P_TOPRIGHT[1] = mv_table[mot_xy - mot_stride + 1         ][1];

                if(P_TOP[1] > (rel_ymax<<shift)) P_TOP[1]= (rel_ymax<<shift);

                if(P_TOPRIGHT[0] < (rel_xmin<<shift)) P_TOPRIGHT[0]= (rel_xmin<<shift);

                if(P_TOPRIGHT[1] > (rel_ymax<<shift)) P_TOPRIGHT[1]= (rel_ymax<<shift);

                P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);

                P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);

            }

            pred_x= P_LEFT[0];

            pred_y= P_LEFT[1];

        }

        if(mv_table == s->b_forw_mv_table){

            mv_scale= (s->pb_time<<16) / (s->pp_time<<shift);

        }else{

            mv_scale= ((s->pb_time - s->pp_time)<<16) / (s->pp_time<<shift);

        }

        dmin = s->me.motion_search[0](s, 0, &mx, &my, P, pred_x, pred_y, rel_xmin, rel_ymin, rel_xmax, rel_ymax,

                                      picture, s->p_mv_table, mv_scale, mv_penalty);

        break;

    }

    dmin= s->me.sub_motion_search(s, &mx, &my, dmin, rel_xmin, rel_ymin, rel_xmax, rel_ymax,

				   pred_x, pred_y, picture, 0, 0, mv_penalty);

    if(s->avctx->me_sub_cmp != s->avctx->mb_cmp && !s->me.skip)

        dmin= s->me.get_mb_score(s, mx, my, pred_x, pred_y, picture, mv_penalty);

//printf("%d %d %d %d//", s->mb_x, s->mb_y, mx, my);

//    s->mb_type[mb_y*s->mb_width + mb_x]= mb_type;

    mv_table[mot_xy][0]= mx;

    mv_table[mot_xy][1]= my;

    return dmin;

}


void AppCacheHost::DoPendingGetStatus() {
  DCHECK_EQ(false, pending_get_status_callback_.is_null());

  pending_get_status_callback_.Run(GetStatus(), pending_callback_param_);
  pending_get_status_callback_.Reset();
  pending_callback_param_ = NULL;
}


vmxnet3_io_bar1_write(void *opaque,

                      hwaddr addr,

                      uint64_t val,

                      unsigned size)

{

    VMXNET3State *s = opaque;

    switch (addr) {

    /* Vmxnet3 Revision Report Selection */

    case VMXNET3_REG_VRRS:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_VRRS] = %" PRIx64 ", size %d",

                  val, size);

        break;

    /* UPT Version Report Selection */

    case VMXNET3_REG_UVRS:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_UVRS] = %" PRIx64 ", size %d",

                  val, size);

        break;

    /* Driver Shared Address Low */

    case VMXNET3_REG_DSAL:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_DSAL] = %" PRIx64 ", size %d",

                  val, size);

        /*

         * Guest driver will first write the low part of the shared

         * memory address. We save it to temp variable and set the

         * shared address only after we get the high part

         */

        if (val == 0) {

            s->device_active = false;

        }

        s->temp_shared_guest_driver_memory = val;

        s->drv_shmem = 0;

        break;

    /* Driver Shared Address High */

    case VMXNET3_REG_DSAH:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_DSAH] = %" PRIx64 ", size %d",

                  val, size);

        /*

         * Set the shared memory between guest driver and device.

         * We already should have low address part.

         */

        s->drv_shmem = s->temp_shared_guest_driver_memory | (val << 32);

        break;

    /* Command */

    case VMXNET3_REG_CMD:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_CMD] = %" PRIx64 ", size %d",

                  val, size);

        vmxnet3_handle_command(s, val);

        break;

    /* MAC Address Low */

    case VMXNET3_REG_MACL:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_MACL] = %" PRIx64 ", size %d",

                  val, size);

        s->temp_mac = val;

        break;

    /* MAC Address High */

    case VMXNET3_REG_MACH:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_MACH] = %" PRIx64 ", size %d",

                  val, size);

        vmxnet3_set_variable_mac(s, val, s->temp_mac);

        break;

    /* Interrupt Cause Register */

    case VMXNET3_REG_ICR:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_ICR] = %" PRIx64 ", size %d",

                  val, size);

        g_assert_not_reached();

        break;

    /* Event Cause Register */

    case VMXNET3_REG_ECR:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_ECR] = %" PRIx64 ", size %d",

                  val, size);

        vmxnet3_ack_events(s, val);

        break;

    default:

        VMW_CBPRN("Unknown Write to BAR1 [%" PRIx64 "] = %" PRIx64 ", size %d",

                  addr, val, size);

        break;

    }

}


static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
  const ssize_t type,const PSDCompressionType compression,
  const size_t compact_size,ExceptionInfo *exception)
{
  MagickBooleanType
    status;

  register unsigned char
    *p;

  size_t
    count,
    length,
    packet_size,
    row_size;

  ssize_t
    y;

  unsigned char
    *compact_pixels,
    *pixels;

  z_stream
    stream;

  if (image->debug != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
       "      layer data is ZIP compressed");

  compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
    sizeof(*compact_pixels));
  if (compact_pixels == (unsigned char *) NULL)
    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
      image->filename);

  packet_size=GetPSDPacketSize(image);
  row_size=image->columns*packet_size;
  count=image->rows*row_size;

  pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
  if (pixels == (unsigned char *) NULL)
    {
      compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
      ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
        image->filename);
    }
  if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size)
    {
      compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
      ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
        image->filename);
    }

  ResetMagickMemory(&stream,0,sizeof(stream));
  stream.data_type=Z_BINARY;
  stream.next_in=(Bytef *)compact_pixels;
  stream.avail_in=(uInt) compact_size;
  stream.next_out=(Bytef *)pixels;
  stream.avail_out=(uInt) count;

  if (inflateInit(&stream) == Z_OK)
    {
      int
        ret;

      while (stream.avail_out > 0)
      {
        ret=inflate(&stream, Z_SYNC_FLUSH);
        if ((ret != Z_OK) && (ret != Z_STREAM_END))
          {
            (void) inflateEnd(&stream);
            compact_pixels=(unsigned char *) RelinquishMagickMemory(
              compact_pixels);
            pixels=(unsigned char *) RelinquishMagickMemory(pixels);
            return(MagickFalse);
          }
      }
      (void) inflateEnd(&stream);
    }

  if (compression == ZipWithPrediction)
  {
     p=pixels;
     while (count > 0)
     {
       length=image->columns;
       while (--length)
       {
         if (packet_size == 2)
           {
             p[2]+=p[0]+((p[1]+p[3]) >> 8);
             p[3]+=p[1];
           }
         else
          *(p+1)+=*p;
         p+=packet_size;
       }
       p+=packet_size;
       count-=row_size;
     }
  }

  status=MagickTrue;
  p=pixels;
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
    if (status == MagickFalse)
      break;

    p+=row_size;
  }

  compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
  pixels=(unsigned char *) RelinquishMagickMemory(pixels);
  return(status);
}


		func_ptr_to_num(void *func_ptr)
{
	uintptr_t offset = (uintptr_t)func_ptr;

#ifdef CONFIG_SANDBOX
	offset -= (uintptr_t)&_init;
#else
	if (gd->flags & GD_FLG_RELOC)
		offset -= gd->relocaddr;
	else
		offset -= CONFIG_SYS_TEXT_BASE;
#endif
	return offset / FUNC_SITE_SIZE;
}


int ioinst_handle_stsch(CPUS390XState *env, uint64_t reg1, uint32_t ipb)

{

    int cssid, ssid, schid, m;

    SubchDev *sch;

    uint64_t addr;

    int cc;

    SCHIB *schib;

    hwaddr len = sizeof(*schib);

    if (ioinst_disassemble_sch_ident(reg1, &m, &cssid, &ssid, &schid)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return -EIO;

    }

    trace_ioinst_sch_id("stsch", cssid, ssid, schid);

    addr = decode_basedisp_s(env, ipb);

    if (addr & 3) {

        program_interrupt(env, PGM_SPECIFICATION, 2);

        return -EIO;

    }

    schib = s390_cpu_physical_memory_map(env, addr, &len, 1);

    if (!schib || len != sizeof(*schib)) {

        program_interrupt(env, PGM_ADDRESSING, 2);

        cc = -EIO;

        goto out;

    }

    sch = css_find_subch(m, cssid, ssid, schid);

    if (sch) {

        if (css_subch_visible(sch)) {

            css_do_stsch(sch, schib);

            cc = 0;

        } else {

            /* Indicate no more subchannels in this css/ss */

            cc = 3;

        }

    } else {

        if (css_schid_final(m, cssid, ssid, schid)) {

            cc = 3; /* No more subchannels in this css/ss */

        } else {

            /* Store an empty schib. */

            memset(schib, 0, sizeof(*schib));

            cc = 0;

        }

    }

out:

    s390_cpu_physical_memory_unmap(env, schib, len, 1);

    return cc;

}


TEST_F ( TemplateURLTest , ReplaceCurrentPageUrl ) {
 struct TestData {
 const base : : string16 search_term ;
 const std : : string current_page_url ;
 const std : : string url ;
 const std : : string expected_result ;
 }
 test_data [ ] = {
 {
 ASCIIToUTF16 ( "foo" ) , "http://www.google.com/" , "{
google:baseURL}
?{
searchTerms}
&{
google:currentPageUrl}
" , "http://www.google.com/?foo&url=http%3A%2F%2Fwww.google.com%2F&" }
 , {
 ASCIIToUTF16 ( "foo" ) , "" , "{
google:baseURL}
?{
searchTerms}
&{
google:currentPageUrl}
" , "http://www.google.com/?foo&" }
 , {
 ASCIIToUTF16 ( "foo" ) , "http://g.com/+-/*&=" , "{
google:baseURL}
?{
searchTerms}
&{
google:currentPageUrl}
" , "http://www.google.com/?foo&url=http%3A%2F%2Fg.com%2F%2B-%2F*%26%3D&" }
 , }
 ;
 TemplateURLData data ;
 data . input_encodings . push_back ( "UTF-8" ) ;
 for ( size_t i = 0 ;
 i < arraysize ( test_data ) ;
 ++ i ) {
 data . SetURL ( test_data [ i ] . url ) ;
 TemplateURL url ( data ) ;
 EXPECT_TRUE ( url . url_ref ( ) . IsValid ( search_terms_data_ ) ) ;
 ASSERT_TRUE ( url . url_ref ( ) . SupportsReplacement ( search_terms_data_ ) ) ;
 TemplateURLRef : : SearchTermsArgs search_terms_args ( test_data [ i ] . search_term ) ;
 search_terms_args . current_page_url = test_data [ i ] . current_page_url ;
 GURL result ( url . url_ref ( ) . ReplaceSearchTerms ( search_terms_args , search_terms_data_ ) ) ;
 ASSERT_TRUE ( result . is_valid ( ) ) ;
 EXPECT_EQ ( test_data [ i ] . expected_result , result . spec ( ) ) ;
 }
 }


ar6000_disconnect(struct ar6_softc *ar)
{
    if ((ar->arConnected == true) || (ar->arConnectPending == true)) {
        wmi_disconnect_cmd(ar->arWmi);
        /*
         * Disconnect cmd is issued, clear connectPending.
         * arConnected will be cleard in disconnect_event notification.
         */
        ar->arConnectPending = false;
    }

    return 0;
}


void RenderFrameImpl::ExtractSmartClipData(
    const gfx::Rect& rect,
    ExtractSmartClipDataCallback callback) {
#if defined(OS_ANDROID)
  blink::WebString clip_text;
  blink::WebString clip_html;
  GetWebFrame()->ExtractSmartClipData(rect, clip_text, clip_html);
  std::move(callback).Run(clip_text.Utf16(), clip_html.Utf16());
#endif  // defined(OS_ANDROID)
}


static void f_midi_transmit(struct f_midi *midi)
{
	struct usb_ep *ep = midi->in_ep;
	int ret;
	unsigned long flags;

	/* We only care about USB requests if IN endpoint is enabled */
	if (!ep || !ep->enabled)
		goto drop_out;

	spin_lock_irqsave(&midi->transmit_lock, flags);

	do {
		ret = f_midi_do_transmit(midi, ep);
		if (ret < 0) {
			spin_unlock_irqrestore(&midi->transmit_lock, flags);
			goto drop_out;
		}
	} while (ret);

	spin_unlock_irqrestore(&midi->transmit_lock, flags);

	return;

drop_out:
	f_midi_drop_out_substreams(midi);
}


Eina_Bool ewk_frame_visible_content_geometry_get(const Evas_Object* ewkFrame, Eina_Bool includeScrollbars, int* x, int* y, int* width, int* height)
{
    if (x)
        *x = 0;
    if (y)
        *y = 0;
    if (width)
        *width = 0;
    if (height)
        *height = 0;
    EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData, false);
    EINA_SAFETY_ON_NULL_RETURN_VAL(smartData->frame, false);
    EINA_SAFETY_ON_NULL_RETURN_VAL(smartData->frame->view(), false);
    WebCore::IntRect rect = smartData->frame->view()->visibleContentRect(includeScrollbars);
    if (x)
        *x = rect.x();
    if (y)
        *y = rect.y();
    if (width)
        *width = rect.width();
    if (height)
        *height = rect.height();
    return true;
}


void drm_mode_probed_add(struct drm_connector *connector,
			 struct drm_display_mode *mode)
{
	list_add(&mode->head, &connector->probed_modes);
}


void AppCacheHost::SetSpawningHostId(
    int spawning_process_id, int spawning_host_id) {
  spawning_process_id_ = spawning_process_id;
  spawning_host_id_ = spawning_host_id;
}


static av_cold int cinvideo_decode_init(AVCodecContext *avctx)

{

    CinVideoContext *cin = avctx->priv_data;

    unsigned int i;

    cin->avctx = avctx;

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

    cin->frame.data[0] = NULL;

    cin->bitmap_size = avctx->width * avctx->height;

    for (i = 0; i < 3; ++i) {

        cin->bitmap_table[i] = av_mallocz(cin->bitmap_size);

        if (!cin->bitmap_table[i])

            av_log(avctx, AV_LOG_ERROR, "Can't allocate bitmap buffers.\n");

    }

    return 0;

}


static int mwifiex_pm_wakeup_card_complete(struct mwifiex_adapter *adapter)
{
	mwifiex_dbg(adapter, CMD,
		    "cmd: Wakeup device completed\n");

	return 0;
}


static Image *ReadTEXTImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  char
    filename[MaxTextExtent],
    geometry[MaxTextExtent],
    *p,
    text[MaxTextExtent];

  DrawInfo
    *draw_info;

  Image
    *image,
    *texture;

  MagickBooleanType
    status;

  PointInfo
    delta;

  RectangleInfo
    page;

  ssize_t
    offset;

  TypeMetric
    metrics;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  (void) ResetMagickMemory(text,0,sizeof(text));
  (void) ReadBlobString(image,text);
  /*
    Set the page geometry.
  */
  delta.x=DefaultResolution;
  delta.y=DefaultResolution;
  if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
    {
      GeometryInfo
        geometry_info;

      MagickStatusType
        flags;

      flags=ParseGeometry(PSDensityGeometry,&geometry_info);
      image->x_resolution=geometry_info.rho;
      image->y_resolution=geometry_info.sigma;
      if ((flags & SigmaValue) == 0)
        image->y_resolution=image->x_resolution;
    }
  page.width=612;
  page.height=792;
  page.x=43;
  page.y=43;
  if (image_info->page != (char *) NULL)
    (void) ParseAbsoluteGeometry(image_info->page,&page);
  /*
    Initialize Image structure.
  */
  image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
    delta.x)+0.5);
  image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
    delta.y)+0.5);
  status=SetImageExtent(image,image->columns,image->rows);
  if (status == MagickFalse)
    {
      InheritException(exception,&image->exception);
      return(DestroyImageList(image));
    }
  image->page.x=0;
  image->page.y=0;
  texture=(Image *) NULL;
  if (image_info->texture != (char *) NULL)
    {
      ImageInfo
        *read_info;

      read_info=CloneImageInfo(image_info);
      SetImageInfoBlob(read_info,(void *) NULL,0);
      (void) CopyMagickString(read_info->filename,image_info->texture,
        MaxTextExtent);
      texture=ReadImage(read_info,exception);
      read_info=DestroyImageInfo(read_info);
    }
  /*
    Annotate the text image.
  */
  (void) SetImageBackgroundColor(image);
  draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
  (void) CloneString(&draw_info->text,image_info->filename);
  (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
    image->columns,(double) image->rows,(double) page.x,(double) page.y);
  (void) CloneString(&draw_info->geometry,geometry);
  status=GetTypeMetrics(image,draw_info,&metrics);
  if (status == MagickFalse)
    ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
  page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
  (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
    image->columns,(double) image->rows,(double) page.x,(double) page.y);
  (void) CloneString(&draw_info->geometry,geometry);
  (void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
  if (*draw_info->text != '\0')
    *draw_info->text='\0';
  p=text;
  for (offset=2*page.y; p != (char *) NULL; )
  {
    /*
      Annotate image with text.
    */
    (void) ConcatenateString(&draw_info->text,text);
    (void) ConcatenateString(&draw_info->text,"\n");
    offset+=(ssize_t) (metrics.ascent-metrics.descent);
    if (image->previous == (Image *) NULL)
      {
        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset,
          image->rows);
        if (status == MagickFalse)
          break;
      }
    p=ReadBlobString(image,text);
    if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
      continue;
    if (texture != (Image *) NULL)
      {
        MagickProgressMonitor
          progress_monitor;

        progress_monitor=SetImageProgressMonitor(image,
          (MagickProgressMonitor) NULL,image->client_data);
        (void) TextureImage(image,texture);
        (void) SetImageProgressMonitor(image,progress_monitor,
          image->client_data);
      }
    (void) AnnotateImage(image,draw_info);
    if (p == (char *) NULL)
      break;
    /*
      Page is full-- allocate next image structure.
    */
    *draw_info->text='\0';
    offset=2*page.y;
    AcquireNextImage(image_info,image);
    if (GetNextImageInList(image) == (Image *) NULL)
      {
        image=DestroyImageList(image);
        return((Image *) NULL);
      }
    image->next->columns=image->columns;
    image->next->rows=image->rows;
    image=SyncNextImageInList(image);
    (void) CopyMagickString(image->filename,filename,MaxTextExtent);
    (void) SetImageBackgroundColor(image);
    status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
      GetBlobSize(image));
    if (status == MagickFalse)
      break;
  }
  if (texture != (Image *) NULL)
    {
      MagickProgressMonitor
        progress_monitor;

      progress_monitor=SetImageProgressMonitor(image,
        (MagickProgressMonitor) NULL,image->client_data);
      (void) TextureImage(image,texture);
      (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
    }
  (void) AnnotateImage(image,draw_info);
  if (texture != (Image *) NULL)
    texture=DestroyImage(texture);
  draw_info=DestroyDrawInfo(draw_info);
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}


vimrc_found(char_u *fname, char_u *envname)
{
    int		opt_idx;
    int		dofree = FALSE;
    char_u	*p;

    if (!option_was_set((char_u *)"cp"))
    {
	p_cp = FALSE;
	for (opt_idx = 0; !istermoption(&options[opt_idx]); opt_idx++)
	    if (!(options[opt_idx].flags & (P_WAS_SET|P_VI_DEF)))
		set_option_default(opt_idx, OPT_FREE, FALSE);
	didset_options();
	didset_options2();
    }

    if (fname != NULL)
    {
	p = vim_getenv(envname, &dofree);
	if (p == NULL)
	{
	    /* Set $MYVIMRC to the first vimrc file found. */
	    p = FullName_save(fname, FALSE);
	    if (p != NULL)
	    {
		vim_setenv(envname, p);
		vim_free(p);
	    }
	}
	else if (dofree)
	    vim_free(p);
    }
}


void ConfirmInfoBar::ButtonPressed(views::Button* sender,
                                   const ui::Event& event) {
  if (!owner())
    return;  // We're closing; don't call anything, it might access the owner.
  ConfirmInfoBarDelegate* delegate = GetDelegate();
  if (sender == ok_button_) {
    if (delegate->Accept())
      RemoveSelf();
  } else if (sender == cancel_button_) {
    if (delegate->Cancel())
      RemoveSelf();
  } else {
    InfoBarView::ButtonPressed(sender, event);
  }
}


static int string_num_dots ( const char * s ) {
 int count = 0 ;
 while ( ( s = strchr ( s , '.' ) ) ) {
 s ++ ;
 count ++ ;
 }
 return count ;
 }


int CServer::LoadMap(const char *pMapName)
{
	//DATAFILE *df;
	char aBuf[512];
	str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName);

	/*df = datafile_load(buf);
	if(!df)
		return 0;*/

	// check for valid standard map
	if(!m_MapChecker.ReadAndValidateMap(Storage(), aBuf, IStorage::TYPE_ALL))
	{
		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapchecker", "invalid standard map");
		return 0;
	}

	if(!m_pMap->Load(aBuf))
		return 0;

	// stop recording when we change map
	m_DemoRecorder.Stop();

	// reinit snapshot ids
	m_IDPool.TimeoutIDs();

	// get the crc of the map
	m_CurrentMapCrc = m_pMap->Crc();
	char aBufMsg[256];
	str_format(aBufMsg, sizeof(aBufMsg), "%s crc is %08x", aBuf, m_CurrentMapCrc);
	Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBufMsg);

	str_copy(m_aCurrentMap, pMapName, sizeof(m_aCurrentMap));
	//map_set(df);

	// load complete map into memory for download
	{
		IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);
		m_CurrentMapSize = (int)io_length(File);
		if(m_pCurrentMapData)
			mem_free(m_pCurrentMapData);
		m_pCurrentMapData = (unsigned char *)mem_alloc(m_CurrentMapSize, 1);
		io_read(File, m_pCurrentMapData, m_CurrentMapSize);
		io_close(File);
	}
	return 1;
}


int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)
{
	struct super_block *sb;
	int err;
	int rc;

	if (!ext4_handle_valid(handle)) {
		ext4_put_nojournal(handle);
		return 0;
	}
	sb = handle->h_transaction->t_journal->j_private;
	err = handle->h_err;
	rc = jbd2_journal_stop(handle);

	if (!err)
		err = rc;
	if (err)
		__ext4_std_error(sb, where, line, err);
	return err;
}


static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np)
{
	struct platform_device *pdev = cqspi->pdev;
	struct device *dev = &pdev->dev;
	struct cqspi_flash_pdata *f_pdata;
	struct spi_nor *nor;
	struct mtd_info *mtd;
	unsigned int cs;
	int i, ret;

	/* Get flash device data */
	for_each_available_child_of_node(dev->of_node, np) {
		if (of_property_read_u32(np, "reg", &cs)) {
			dev_err(dev, "Couldn't determine chip select.\n");
			goto err;
		}

		if (cs > CQSPI_MAX_CHIPSELECT) {
			dev_err(dev, "Chip select %d out of range.\n", cs);
			goto err;
		}

		f_pdata = &cqspi->f_pdata[cs];
		f_pdata->cqspi = cqspi;
		f_pdata->cs = cs;

		ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np);
		if (ret)
			goto err;

		nor = &f_pdata->nor;
		mtd = &nor->mtd;

		mtd->priv = nor;

		nor->dev = dev;
		spi_nor_set_flash_node(nor, np);
		nor->priv = f_pdata;

		nor->read_reg = cqspi_read_reg;
		nor->write_reg = cqspi_write_reg;
		nor->read = cqspi_read;
		nor->write = cqspi_write;
		nor->erase = cqspi_erase;
		nor->prepare = cqspi_prep;
		nor->unprepare = cqspi_unprep;

		mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d",
					   dev_name(dev), cs);
		if (!mtd->name) {
			ret = -ENOMEM;
			goto err;
		}

		ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD);
		if (ret)
			goto err;

		ret = mtd_device_register(mtd, NULL, 0);
		if (ret)
			goto err;

		f_pdata->registered = true;
	}

	return 0;

err:
	for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++)
		if (cqspi->f_pdata[i].registered)
			mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd);
	return ret;
}


void virtio_gpu_cleanup_mapping_iov(struct iovec *iov, uint32_t count)
{
    int i;

    for (i = 0; i < count; i++) {
        cpu_physical_memory_unmap(iov[i].iov_base, iov[i].iov_len, 1,
                                  iov[i].iov_len);
    }
    g_free(iov);
}


static void set_result_format_version ( ulong new_version ) {
 switch ( new_version ) {
 case 1 : break ;
 case 2 : break ;
 default : die ( "Version format %lu has not yet been implemented" , new_version ) ;
 break ;
 }
 opt_result_format_version = new_version ;
 }


sasl_user_can_login(struct sasl_session *const restrict p)
{
	// source_mu is the user whose credentials we verified ("authentication id" / authcid)
	// target_mu is the user who will be ultimately logged in ("authorization id" / authzid)
	struct myuser *source_mu;
	struct myuser *target_mu;

	if (! *p->authceid || ! (source_mu = myuser_find_uid(p->authceid)))
		return NULL;

	if (! *p->authzeid)
	{
		target_mu = source_mu;

		(void) mowgli_strlcpy(p->authzid, p->authcid, sizeof p->authzid);
		(void) mowgli_strlcpy(p->authzeid, p->authceid, sizeof p->authzeid);
	}
	else if (! (target_mu = myuser_find_uid(p->authzeid)))
		return NULL;

	if (! sasl_may_impersonate(source_mu, target_mu))
	{
		(void) logcommand(p->si, CMDLOG_LOGIN, "denied IMPERSONATE by \2%s\2 to \2%s\2",
		                                       entity(source_mu)->name, entity(target_mu)->name);
		return NULL;
	}

	if (! (target_mu->flags & MU_LOGINNOLIMIT)
		&& !has_priv_myuser(target_mu, PRIV_LOGIN_NOLIMIT)
		&& MOWGLI_LIST_LENGTH(&target_mu->logins) >= me.maxlogins)
	{
		(void) logcommand(p->si, CMDLOG_LOGIN, "failed LOGIN to \2%s\2 (too many logins)",
		                                       entity(target_mu)->name);
		return NULL;
	}

	/* We just did SASL authentication for a user.  With IRCds which do not
	 * have unique UIDs for users, we will likely be expecting the login
	 * data to be bursted.  As a result, we should give the core a heads'
	 * up that this is going to happen so that hooks will be properly
	 * fired...
	 */
	if (ircd->flags & IRCD_SASL_USE_PUID)
	{
		target_mu->flags &= ~MU_NOBURSTLOGIN;
		target_mu->flags |= MU_PENDINGLOGIN;
	}

	if (target_mu != source_mu)
		(void) logcommand(p->si, CMDLOG_LOGIN, "allowed IMPERSONATE by \2%s\2 to \2%s\2",
		                                       entity(source_mu)->name, entity(target_mu)->name);

	return target_mu;
}


 SuggestionState::SuggestionState()
     : visible(false) {}


sraRectangleIterator *sraRgnGetReverseIterator(sraRegion *s,rfbBool reverseX,rfbBool reverseY)
{
  sraRectangleIterator *i = sraRgnGetIterator(s);
  if(reverseY) {
    i->sPtrs[1] = &(s->front);
    i->sPtrs[0] = &(s->back);
  }
  i->reverseX = reverseX;
  i->reverseY = reverseY;
  return(i);
}


static void handle_rx(struct vhost_net *net)
{
	struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX];
	struct vhost_virtqueue *vq = &nvq->vq;
	unsigned uninitialized_var(in), log;
	struct vhost_log *vq_log;
	struct msghdr msg = {
		.msg_name = NULL,
		.msg_namelen = 0,
		.msg_control = NULL, /* FIXME: get and handle RX aux data. */
		.msg_controllen = 0,
		.msg_iov = vq->iov,
		.msg_flags = MSG_DONTWAIT,
	};
	struct virtio_net_hdr_mrg_rxbuf hdr = {
		.hdr.flags = 0,
		.hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE
	};
	size_t total_len = 0;
	int err, mergeable;
	s16 headcount;
	size_t vhost_hlen, sock_hlen;
	size_t vhost_len, sock_len;
	/* TODO: check that we are running from vhost_worker? */
	struct socket *sock = rcu_dereference_check(vq->private_data, 1);

	if (!sock)
		return;

	mutex_lock(&vq->mutex);
	vhost_disable_notify(&net->dev, vq);
	vhost_hlen = nvq->vhost_hlen;
	sock_hlen = nvq->sock_hlen;

	vq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ?
		vq->log : NULL;
	mergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF);

	while ((sock_len = peek_head_len(sock->sk))) {
		sock_len += sock_hlen;
		vhost_len = sock_len + vhost_hlen;
		headcount = get_rx_bufs(vq, vq->heads, vhost_len,
					&in, vq_log, &log,
					likely(mergeable) ? UIO_MAXIOV : 1);
		/* On error, stop handling until the next kick. */
		if (unlikely(headcount < 0))
			break;
		/* OK, now we need to know about added descriptors. */
		if (!headcount) {
			if (unlikely(vhost_enable_notify(&net->dev, vq))) {
				/* They have slipped one in as we were
				 * doing that: check again. */
				vhost_disable_notify(&net->dev, vq);
				continue;
			}
			/* Nothing new?  Wait for eventfd to tell us
			 * they refilled. */
			break;
		}
		/* We don't need to be notified again. */
		if (unlikely((vhost_hlen)))
			/* Skip header. TODO: support TSO. */
			move_iovec_hdr(vq->iov, nvq->hdr, vhost_hlen, in);
		else
			/* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF:
			 * needed because recvmsg can modify msg_iov. */
			copy_iovec_hdr(vq->iov, nvq->hdr, sock_hlen, in);
		msg.msg_iovlen = in;
		err = sock->ops->recvmsg(NULL, sock, &msg,
					 sock_len, MSG_DONTWAIT | MSG_TRUNC);
		/* Userspace might have consumed the packet meanwhile:
		 * it's not supposed to do this usually, but might be hard
		 * to prevent. Discard data we got (if any) and keep going. */
		if (unlikely(err != sock_len)) {
			pr_debug("Discarded rx packet: "
				 " len %d, expected %zd\n", err, sock_len);
			vhost_discard_vq_desc(vq, headcount);
			continue;
		}
		if (unlikely(vhost_hlen) &&
		    memcpy_toiovecend(nvq->hdr, (unsigned char *)&hdr, 0,
				      vhost_hlen)) {
			vq_err(vq, "Unable to write vnet_hdr at addr %p\n",
			       vq->iov->iov_base);
			break;
		}
		/* TODO: Should check and handle checksum. */
		if (likely(mergeable) &&
		    memcpy_toiovecend(nvq->hdr, (unsigned char *)&headcount,
				      offsetof(typeof(hdr), num_buffers),
				      sizeof hdr.num_buffers)) {
			vq_err(vq, "Failed num_buffers write");
			vhost_discard_vq_desc(vq, headcount);
			break;
		}
		vhost_add_used_and_signal_n(&net->dev, vq, vq->heads,
					    headcount);
		if (unlikely(vq_log))
			vhost_log_write(vq, vq_log, log, vhost_len);
		total_len += vhost_len;
		if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
			vhost_poll_queue(&vq->poll);
			break;
		}
	}

	mutex_unlock(&vq->mutex);
}


void oe_set_default_socket_devid(uint64_t devid)
{
    oe_spin_lock(&_default_socket_devid_lock);
    _default_socket_devid = devid;
    oe_spin_unlock(&_default_socket_devid_lock);
}


hstore_ne(PG_FUNCTION_ARGS)
{
	int			res = DatumGetInt32(DirectFunctionCall2(hstore_cmp,
														PG_GETARG_DATUM(0),
														PG_GETARG_DATUM(1)));

	PG_RETURN_BOOL(res != 0);
}


void TemplateURL::CopyFrom(const TemplateURL& other) {
  if (this == &other)
    return;

  data_ = other.data_;
  ResizeURLRefVector();
  InvalidateCachedValues();
  SetPrepopulateId(other.data_.prepopulate_id);
}


ASessionDescription::ASessionDescription()
 : mIsValid(false) {
}


  FakeURLFetcher(const GURL& url, RequestType request_type, Delegate* d,
                 const std::string& response_data, bool success)
    : URLFetcher(url, request_type, d),
      url_(url),
      response_data_(response_data),
      success_(success),
      ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
  }


static void addrconf_add_mroute(struct net_device *dev)
{
	struct fib6_config cfg = {
		.fc_table = RT6_TABLE_LOCAL,
		.fc_metric = IP6_RT_PRIO_ADDRCONF,
		.fc_ifindex = dev->ifindex,
		.fc_dst_len = 8,
		.fc_flags = RTF_UP,
		.fc_nlinfo.nl_net = dev_net(dev),
	};

	ipv6_addr_set(&cfg.fc_dst, htonl(0xFF000000), 0, 0, 0);

	ip6_route_add(&cfg);
}


static void recalc_intercepts(struct vcpu_svm *svm)
{
	struct vmcb_control_area *c, *h;
	struct nested_state *g;

	mark_dirty(svm->vmcb, VMCB_INTERCEPTS);

	if (!is_guest_mode(&svm->vcpu))
		return;

	c = &svm->vmcb->control;
	h = &svm->nested.hsave->control;
	g = &svm->nested;

	c->intercept_cr = h->intercept_cr | g->intercept_cr;
	c->intercept_dr = h->intercept_dr | g->intercept_dr;
	c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
	c->intercept = h->intercept | g->intercept;
}


SPL_METHOD ( SplDoublyLinkedList , setIteratorMode ) {
 long value ;
 spl_dllist_object * intern ;
 if ( zend_parse_parameters ( ZEND_NUM_ARGS ( ) TSRMLS_CC , "l" , & value ) == FAILURE ) {
 return ;
 }
 intern = ( spl_dllist_object * ) zend_object_store_get_object ( getThis ( ) TSRMLS_CC ) ;
 if ( intern -> flags & SPL_DLLIST_IT_FIX && ( intern -> flags & SPL_DLLIST_IT_LIFO ) != ( value & SPL_DLLIST_IT_LIFO ) ) {
 zend_throw_exception ( spl_ce_RuntimeException , "Iterators' LIFO/FIFO modes for SplStack/SplQueue objects are frozen" , 0 TSRMLS_CC ) ;
 return ;
 }
 intern -> flags = value & SPL_DLLIST_IT_MASK ;
 RETURN_LONG ( intern -> flags ) ;
 }


static int dev_set_geometry(struct file *filp, struct dm_ioctl *param, size_t param_size)
{
	int r = -EINVAL, x;
	struct mapped_device *md;
	struct hd_geometry geometry;
	unsigned long indata[4];
	char *geostr = (char *) param + param->data_start;
	char dummy;

	md = find_device(param);
	if (!md)
		return -ENXIO;

	if (geostr < param->data ||
	    invalid_str(geostr, (void *) param + param_size)) {
		DMWARN("Invalid geometry supplied.");
		goto out;
	}

	x = sscanf(geostr, "%lu %lu %lu %lu%c", indata,
		   indata + 1, indata + 2, indata + 3, &dummy);

	if (x != 4) {
		DMWARN("Unable to interpret geometry settings.");
		goto out;
	}

	if (indata[0] > 65535 || indata[1] > 255 ||
	    indata[2] > 255 || indata[3] > ULONG_MAX) {
		DMWARN("Geometry exceeds range limits.");
		goto out;
	}

	geometry.cylinders = indata[0];
	geometry.heads = indata[1];
	geometry.sectors = indata[2];
	geometry.start = indata[3];

	r = dm_set_geometry(md, &geometry);

	param->data_size = 0;

out:
	dm_put(md);
	return r;
}


static int dissect_h245_SEQUENCE_SIZE_1_256_OF_ModeDescription ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_constrained_sequence_of ( tvb , offset , actx , tree , hf_index , ett_h245_SEQUENCE_SIZE_1_256_OF_ModeDescription , SEQUENCE_SIZE_1_256_OF_ModeDescription_sequence_of , 1 , 256 , FALSE ) ;
 return offset ;
 }


static char *get_ver_flags(ut32 flags) {
	if (!flags) {
		return "none";
	}
	static char buff[32];
	buff[0] = 0;
	if (flags & VER_FLG_BASE) {
		strcpy (buff, "BASE ");
	}
	if (flags & VER_FLG_WEAK) {
		if (flags & VER_FLG_BASE) {
			strcat (buff, "| ");
		}
		strcat (buff, "WEAK ");
	}
	if (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)) {
		strcat (buff, "| <unknown>");
	}
	return buff;
}


static void blendXor(SplashColorPtr src, SplashColorPtr dest,
		     SplashColorPtr blend, SplashColorMode cm) {
  int i;

  for (i = 0; i < splashColorModeNComps[cm]; ++i) {
    blend[i] = src[i] ^ dest[i];
  }
}


xsltFreeCompMatchList(xsltCompMatchPtr comp) {
    xsltCompMatchPtr cur;

    while (comp != NULL) {
	cur = comp;
	comp = comp->next;
	xsltFreeCompMatch(cur);
    }
}


LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
{
    return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style()->logicalHeight(), heightType), -1);
}


static void mini_header_set_msg_size(SpiceDataHeaderOpaque *header, uint32_t size)
{
    ((SpiceMiniDataHeader *)header->data)->size = size;
}


void ScriptController::installFunctionsForPagePopup(Frame* frame, PagePopupClient* popupClient)
{
    ASSERT(frame);
    ASSERT(popupClient);
    v8::HandleScope handleScope;
    v8::Handle<v8::Context> context = V8Proxy::mainWorldContext(frame);
    if (context.IsEmpty()) {
        ASSERT_NOT_REACHED();
        return;
    }
    v8::Context::Scope scope(context);
    DOMWindowPagePopup::install(frame->existingDOMWindow(), popupClient);
    v8::Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(setValueAndClosePopupCallback, V8DOMWindow::wrap(frame->existingDOMWindow()));
    context->Global()->Set(v8::String::New("setValueAndClosePopup"), v8::Handle<v8::Function>(templ->GetFunction()));
}


void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
{
	(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
}


static v8::Handle<v8::Value> methodWithNonOptionalArgAndOptionalArgCallback(const v8::Arguments& args)
 {
     INC_STATS("DOM.TestObj.methodWithNonOptionalArgAndOptionalArg");
     if (args.Length() < 1)
        return V8Proxy::throwNotEnoughArgumentsError();
     TestObj* imp = V8TestObj::toNative(args.Holder());
     EXCEPTION_BLOCK(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
     if (args.Length() <= 1) {
        imp->methodWithNonOptionalArgAndOptionalArg(nonOpt);
        return v8::Handle<v8::Value>();
    }
    EXCEPTION_BLOCK(int, opt, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)));
    imp->methodWithNonOptionalArgAndOptionalArg(nonOpt, opt);
    return v8::Handle<v8::Value>();
}


static void renameTableFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  sqlite3 *db = sqlite3_context_db_handle(context);
  const char *zDb = (const char*)sqlite3_value_text(argv[0]);
  const char *zInput = (const char*)sqlite3_value_text(argv[3]);
  const char *zOld = (const char*)sqlite3_value_text(argv[4]);
  const char *zNew = (const char*)sqlite3_value_text(argv[5]);
  int bTemp = sqlite3_value_int(argv[6]);
  UNUSED_PARAMETER(NotUsed);

  if( zInput && zOld && zNew ){
    Parse sParse;
    int rc;
    int bQuote = 1;
    RenameCtx sCtx;
    Walker sWalker;

#ifndef SQLITE_OMIT_AUTHORIZATION
    sqlite3_xauth xAuth = db->xAuth;
    db->xAuth = 0;
#endif

    sqlite3BtreeEnterAll(db);

    memset(&sCtx, 0, sizeof(RenameCtx));
    sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
    memset(&sWalker, 0, sizeof(Walker));
    sWalker.pParse = &sParse;
    sWalker.xExprCallback = renameTableExprCb;
    sWalker.xSelectCallback = renameTableSelectCb;
    sWalker.u.pRename = &sCtx;

    rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);

    if( rc==SQLITE_OK ){
      int isLegacy = (db->flags & SQLITE_LegacyAlter);
      if( sParse.pNewTable ){
        Table *pTab = sParse.pNewTable;

        if( pTab->pSelect ){
          if( isLegacy==0 ){
            Select *pSelect = pTab->pSelect;
            NameContext sNC;
            memset(&sNC, 0, sizeof(sNC));
            sNC.pParse = &sParse;

            assert( pSelect->selFlags & SF_View );
            pSelect->selFlags &= ~SF_View;
            sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
            if( sParse.nErr ) rc = sParse.rc;
            sqlite3WalkSelect(&sWalker, pTab->pSelect);
          }
        }else{
          /* Modify any FK definitions to point to the new table. */
#ifndef SQLITE_OMIT_FOREIGN_KEY
          if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
            FKey *pFKey;
            for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
              if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
                renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
              }
            }
          }
#endif

          /* If this is the table being altered, fix any table refs in CHECK
          ** expressions. Also update the name that appears right after the
          ** "CREATE [VIRTUAL] TABLE" bit. */
          if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
            sCtx.pTab = pTab;
            if( isLegacy==0 ){
              sqlite3WalkExprList(&sWalker, pTab->pCheck);
            }
            renameTokenFind(&sParse, &sCtx, pTab->zName);
          }
        }
      }

      else if( sParse.pNewIndex ){
        renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
        if( isLegacy==0 ){
          sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
        }
      }

#ifndef SQLITE_OMIT_TRIGGER
      else{
        Trigger *pTrigger = sParse.pNewTrigger;
        TriggerStep *pStep;
        if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
            && sCtx.pTab->pSchema==pTrigger->pTabSchema
          ){
          renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
        }

        if( isLegacy==0 ){
          rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
          if( rc==SQLITE_OK ){
            renameWalkTrigger(&sWalker, pTrigger);
            for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
              if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
                renameTokenFind(&sParse, &sCtx, pStep->zTarget);
              }
            }
          }
        }
      }
#endif
    }

    if( rc==SQLITE_OK ){
      rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
    }
    if( rc!=SQLITE_OK ){
      if( sParse.zErrMsg ){
        renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
      }else{
        sqlite3_result_error_code(context, rc);
      }
    }

    renameParseCleanup(&sParse);
    renameTokenFree(db, sCtx.pList);
    sqlite3BtreeLeaveAll(db);
#ifndef SQLITE_OMIT_AUTHORIZATION
    db->xAuth = xAuth;
#endif
  }

  return;
}


UkmPageLoadMetricsObserver::ObservePolicy UkmPageLoadMetricsObserver::OnHidden(
    const page_load_metrics::mojom::PageLoadTiming& timing,
    const page_load_metrics::PageLoadExtraInfo& info) {
  if (!was_hidden_) {
    RecordPageLoadExtraInfoMetrics(
        info, base::TimeTicks() /* no app_background_time */);
    RecordTimingMetrics(timing, info);
    was_hidden_ = true;
  }
  return CONTINUE_OBSERVING;
}


static int ati_remote2_get_channel_mask(char *buffer,
					const struct kernel_param *kp)
{
	pr_debug("%s()\n", __func__);

	return sprintf(buffer, "0x%04x", *(unsigned int *)kp->arg);
}


String StringUtil::Base64Encode(const String& input) {
  int len = input.size();
  return string_base64_encode(input.data(), len);
}


ASC_requestAssociation(T_ASC_Network * network,
                       T_ASC_Parameters * params,
                       T_ASC_Association ** assoc,
                       void **associatePDU,
                       unsigned long *associatePDUlength,
                       DUL_BLOCKOPTIONS block,
                       int timeout)
{
    OFCondition cond = EC_Normal;
    long sendLen;
    int retrieveRawPDU = 0;
    if (associatePDU && associatePDUlength) retrieveRawPDU = 1;

    if (network == NULL) return ASC_NULLKEY;
    if (params == NULL) return ASC_NULLKEY;

    if (ASC_countPresentationContexts(params) == 0)
    {
      return makeDcmnetCondition(ASCC_CODINGERROR, OF_error, "ASC Coding error in ASC_requestAssociation: missing presentation contexts");
    }

    *assoc = (T_ASC_Association *) malloc(sizeof(**assoc));
    if (*assoc == NULL) return EC_MemoryExhausted;
    memset((char*)*assoc, 0, sizeof(**assoc));

    (*assoc)->params = params;
    (*assoc)->nextMsgID = 1;
    (*assoc)->sendPDVLength = 0;
    (*assoc)->sendPDVBuffer = NULL;

    params->DULparams.maxPDU = params->ourMaxPDUReceiveSize;
    OFStandard::strlcpy(params->DULparams.callingImplementationClassUID,
        params->ourImplementationClassUID, DICOM_UI_LENGTH + 1);
    OFStandard::strlcpy(params->DULparams.callingImplementationVersionName,
        params->ourImplementationVersionName, 16+1);

    cond = DUL_RequestAssociation(&network->network, block, timeout,
                                  &(*assoc)->params->DULparams,
                                  &(*assoc)->DULassociation,
                                  retrieveRawPDU);

    if (retrieveRawPDU && assoc && ((*assoc)->DULassociation))
    {
      DUL_returnAssociatePDUStorage((*assoc)->DULassociation, *associatePDU, *associatePDUlength);
    }

    if (cond.good())
    {
       /*
        * The params->DULparams.peerMaxPDU parameter contains the
        * max-pdu-length value in the a-associate-ac (i.e. the max-pdu-length
        * that the remote AE is prepared to accept).
        */
        params->theirMaxPDUReceiveSize = params->DULparams.peerMaxPDU;

        if (!((params->theirMaxPDUReceiveSize & DUL_MAXPDUCOMPAT) ^ DUL_DULCOMPAT))
        {
          /* activate compatibility with DCMTK releases prior to 3.0 */
          DUL_activateCompatibilityMode((*assoc)->DULassociation, dcmEnableBackwardCompatibility.get() | DUL_DULCOMPAT | DUL_DIMSECOMPAT);
          if (params->modeCallback) params->modeCallback->callback(params->theirMaxPDUReceiveSize);
        }

        /* create a sendPDVBuffer */
        sendLen = params->theirMaxPDUReceiveSize;
        if (sendLen < 1) {
            /* the length is unlimited, choose a suitable buffer len */
            sendLen = ASC_MAXIMUMPDUSIZE;
        } else if (sendLen > ASC_MAXIMUMPDUSIZE) {
            sendLen = ASC_MAXIMUMPDUSIZE;
        }
        /* make sure max pdv length is even */
        if ((sendLen % 2) != 0)
        {
          DCMNET_WARN("ASSOC: PDV send length " << sendLen
                << " is odd (using " << (sendLen-1) << ")");
          sendLen--;
        }
        /* length is minus PDU and PDV header bytes */
        sendLen -= 12;
        if (sendLen < 1)
        {
            DCMNET_WARN("ASSOC: PDV send length " << sendLen << " (using default)");
            sendLen = ASC_MINIMUMPDUSIZE - 12;
        }
        if (sendLen < 12)
        {
            /* if sendLen is < 12, dcmdata will fail because it needs to put
             * up to 12 bytes into the send PDV buffer at once (tag header).
             * We use a larger value on this level and let the Upper Layer FSM
             * split the buffer for us into many small PDVs.
             */
            DCMNET_WARN("ASSOC: PDV send length too small, using DUL to split larger PDVs.");
            sendLen = ASC_MINIMUMPDUSIZE - 12;
        }
        (*assoc)->sendPDVLength = sendLen;
        (*assoc)->sendPDVBuffer = (unsigned char*)malloc(size_t(sendLen));
        if ((*assoc)->sendPDVBuffer == NULL) return EC_MemoryExhausted;
        OFStandard::strlcpy(params->theirImplementationClassUID,
           params->DULparams.calledImplementationClassUID, sizeof(params->theirImplementationClassUID));
        OFStandard::strlcpy(params->theirImplementationVersionName,
           params->DULparams.calledImplementationVersionName, sizeof(params->theirImplementationVersionName));

        /* make sure accepted PCs are marked as such in the requested PC list */
        cond = updateRequestedPCListFromAcceptedPCList(&params->DULparams);
    }
    return cond;
}


static void vmxnet3_deactivate_device(VMXNET3State *s)
{
    if (s->device_active) {
        VMW_CBPRN("Deactivating vmxnet3...");
        net_tx_pkt_reset(s->tx_pkt);
        net_tx_pkt_uninit(s->tx_pkt);
        net_rx_pkt_uninit(s->rx_pkt);
        s->device_active = false;
    }
}


static void pirq_query_unmask(int irq)
{
	struct physdev_irq_status_query irq_status;
	struct irq_info *info = info_for_irq(irq);

	BUG_ON(info->type != IRQT_PIRQ);

	irq_status.irq = pirq_from_irq(irq);
	if (HYPERVISOR_physdev_op(PHYSDEVOP_irq_status_query, &irq_status))
		irq_status.flags = 0;

	info->u.pirq.flags &= ~PIRQ_NEEDS_EOI;
	if (irq_status.flags & XENIRQSTAT_needs_eoi)
		info->u.pirq.flags |= PIRQ_NEEDS_EOI;
}


c_pdf14trans_is_closing(const gs_composite_t * composite_action, gs_composite_t ** ppcte,
                        gx_device *dev)
{
    gs_pdf14trans_t *pct0 = (gs_pdf14trans_t *)composite_action;
    int op0 = pct0->params.pdf14_op;

    switch (op0) {
        default: return_error(gs_error_unregistered); /* Must not happen. */
        case PDF14_PUSH_DEVICE:
            return COMP_ENQUEUE;
        case PDF14_ABORT_DEVICE:
            return COMP_ENQUEUE;
        case PDF14_POP_DEVICE:
            if (*ppcte == NULL)
                return COMP_ENQUEUE;
            else {
                gs_compositor_closing_state state = find_opening_op(PDF14_PUSH_DEVICE, ppcte, COMP_EXEC_IDLE);

                if (state == COMP_EXEC_IDLE)
                    return COMP_DROP_QUEUE;
                return state;
            }
        case PDF14_BEGIN_TRANS_GROUP:
            return COMP_ENQUEUE;
        case PDF14_END_TRANS_GROUP:
            if (*ppcte == NULL)
                return COMP_EXEC_QUEUE;
            return find_opening_op(PDF14_BEGIN_TRANS_GROUP, ppcte, COMP_MARK_IDLE);
        case PDF14_BEGIN_TRANS_MASK:
            return COMP_ENQUEUE;
        case PDF14_PUSH_TRANS_STATE:
            return COMP_ENQUEUE;
        case PDF14_POP_TRANS_STATE:
            return COMP_ENQUEUE;
        case PDF14_PUSH_SMASK_COLOR:
            return COMP_ENQUEUE;
            break;
        case PDF14_POP_SMASK_COLOR:
            return COMP_ENQUEUE;
            break;
        case PDF14_END_TRANS_MASK:
            if (*ppcte == NULL)
                return COMP_EXEC_QUEUE;
            return find_opening_op(PDF14_BEGIN_TRANS_MASK, ppcte, COMP_MARK_IDLE);
        case PDF14_SET_BLEND_PARAMS:
            if (*ppcte == NULL)
                return COMP_ENQUEUE;
            /* hack : ignore csel - here it is always zero : */
            return find_same_op(composite_action, PDF14_SET_BLEND_PARAMS, ppcte);
    }
}


static int http_transform_header(struct session* s, struct http_msg *msg, const char* name, uint name_len,
                                 char* buf, struct hdr_idx* idx, struct list *fmt, struct my_regex *re,
                                 struct hdr_ctx* ctx, int action)
{
	ctx->idx = 0;

	while (http_find_full_header2(name, name_len, buf, idx, ctx)) {
		struct hdr_idx_elem *hdr = idx->v + ctx->idx;
		int delta;
		char* val = (char*)ctx->line + name_len + 2;
		char* val_end = (char*)ctx->line + hdr->len;
		char* reg_dst_buf;
		uint reg_dst_buf_size;
		int n_replaced;

		trash.len = build_logline(s, trash.str, trash.size, fmt);

		if (trash.len >= trash.size - 1)
			return -1;

		reg_dst_buf = trash.str + trash.len + 1;
		reg_dst_buf_size = trash.size - trash.len - 1;

		switch (action) {
		case HTTP_REQ_ACT_REPLACE_VAL:
		case HTTP_RES_ACT_REPLACE_VAL:
			n_replaced = http_replace_value(re, reg_dst_buf, reg_dst_buf_size, val, val_end-val, ',', trash.str);
			break;
		case HTTP_REQ_ACT_REPLACE_HDR:
		case HTTP_RES_ACT_REPLACE_HDR:
			n_replaced = http_replace_header(re, reg_dst_buf, reg_dst_buf_size, val, val_end-val, trash.str);
			break;
		default: /* impossible */
			return -1;
		}

		switch (n_replaced) {
		case -1: return -1;
		case -2: continue;
		}

		delta = buffer_replace2(msg->chn->buf, val, val_end, reg_dst_buf, n_replaced);

		hdr->len += delta;
		http_msg_move_end(msg, delta);
	}

	return 0;
}


void ActiveTabWithServiceTest::SetUp() {
  ExtensionServiceTestBase::SetUp();
  content::BrowserSideNavigationSetUp();
}


static bool perms_include(int fmode, mode_t req_mode)
{
	mode_t r;

	switch (req_mode & O_ACCMODE) {
	case O_RDONLY:
		r = S_IROTH;
		break;
	case O_WRONLY:
		r = S_IWOTH;
		break;
	case O_RDWR:
		r = S_IROTH | S_IWOTH;
		break;
	default:
		return false;
	}
	return ((fmode & r) == r);
}


static int get_qPy_pred(HEVCContext *s, int xC, int yC,

                        int xBase, int yBase, int log2_cb_size)

{

    HEVCLocalContext *lc     = s->HEVClc;

    int ctb_size_mask        = (1 << s->sps->log2_ctb_size) - 1;

    int MinCuQpDeltaSizeMask = (1 << (s->sps->log2_ctb_size -

                                      s->pps->diff_cu_qp_delta_depth)) - 1;

    int xQgBase              = xBase - (xBase & MinCuQpDeltaSizeMask);

    int yQgBase              = yBase - (yBase & MinCuQpDeltaSizeMask);

    int min_cb_width         = s->sps->min_cb_width;

    int min_cb_height        = s->sps->min_cb_height;

    int x_cb                 = xQgBase >> s->sps->log2_min_cb_size;

    int y_cb                 = yQgBase >> s->sps->log2_min_cb_size;

    int availableA           = (xBase   & ctb_size_mask) &&

                               (xQgBase & ctb_size_mask);

    int availableB           = (yBase   & ctb_size_mask) &&

                               (yQgBase & ctb_size_mask);

    int qPy_pred, qPy_a, qPy_b;

    // qPy_pred

    if (lc->first_qp_group || (!xQgBase && !yQgBase)) {

        lc->first_qp_group = !lc->tu.is_cu_qp_delta_coded;

        qPy_pred = s->sh.slice_qp;

    } else {

        qPy_pred = lc->qp_y;

        if (log2_cb_size < s->sps->log2_ctb_size -

                           s->pps->diff_cu_qp_delta_depth) {

            static const int offsetX[8][8] = {

                { -1, 1, 3, 1, 7, 1, 3, 1 },

                {  0, 0, 0, 0, 0, 0, 0, 0 },

                {  1, 3, 1, 3, 1, 3, 1, 3 },

                {  2, 2, 2, 2, 2, 2, 2, 2 },

                {  3, 5, 7, 5, 3, 5, 7, 5 },

                {  4, 4, 4, 4, 4, 4, 4, 4 },

                {  5, 7, 5, 7, 5, 7, 5, 7 },

                {  6, 6, 6, 6, 6, 6, 6, 6 }

            };

            static const int offsetY[8][8] = {

                { 7, 0, 1, 2, 3, 4, 5, 6 },

                { 0, 1, 2, 3, 4, 5, 6, 7 },

                { 1, 0, 3, 2, 5, 4, 7, 6 },

                { 0, 1, 2, 3, 4, 5, 6, 7 },

                { 3, 0, 1, 2, 7, 4, 5, 6 },

                { 0, 1, 2, 3, 4, 5, 6, 7 },

                { 1, 0, 3, 2, 5, 4, 7, 6 },

                { 0, 1, 2, 3, 4, 5, 6, 7 }

            };

            int xC0b = (xC - (xC & ctb_size_mask)) >> s->sps->log2_min_cb_size;

            int yC0b = (yC - (yC & ctb_size_mask)) >> s->sps->log2_min_cb_size;

            int idxX = (xQgBase  & ctb_size_mask)  >> s->sps->log2_min_cb_size;

            int idxY = (yQgBase  & ctb_size_mask)  >> s->sps->log2_min_cb_size;

            int idx_mask = ctb_size_mask >> s->sps->log2_min_cb_size;

            int x, y;

            x = FFMIN(xC0b +  offsetX[idxX][idxY],             min_cb_width  - 1);

            y = FFMIN(yC0b + (offsetY[idxX][idxY] & idx_mask), min_cb_height - 1);

            if (xC0b == (lc->start_of_tiles_x >> s->sps->log2_min_cb_size) &&

                offsetX[idxX][idxY] == -1) {

                x = (lc->end_of_tiles_x >> s->sps->log2_min_cb_size) - 1;

                y = yC0b - 1;

            }

            qPy_pred = s->qp_y_tab[y * min_cb_width + x];

        }

    }

    // qPy_a

    if (availableA == 0)

        qPy_a = qPy_pred;

    else

        qPy_a = s->qp_y_tab[(x_cb - 1) + y_cb * min_cb_width];

    // qPy_b

    if (availableB == 0)

        qPy_b = qPy_pred;

    else

        qPy_b = s->qp_y_tab[x_cb + (y_cb - 1) * min_cb_width];

    av_assert2(qPy_a >= -s->sps->qp_bd_offset && qPy_a < 52);

    av_assert2(qPy_b >= -s->sps->qp_bd_offset && qPy_b < 52);

    return (qPy_a + qPy_b + 1) >> 1;

}


void PropertiesWidget::showPiecesDownloaded(bool show)
{
    downloaded_pieces_lbl->setVisible(show);
    downloaded_pieces->setVisible(show);
    progress_lbl->setVisible(show);
    if (show || !pieces_availability->isVisible())
        line_2->setVisible(show);
}


void tasklet_hrtimer_init(struct tasklet_hrtimer *ttimer,
			  enum hrtimer_restart (*function)(struct hrtimer *),
			  clockid_t which_clock, enum hrtimer_mode mode)
{
	hrtimer_init(&ttimer->timer, which_clock, mode);
	ttimer->timer.function = __hrtimer_tasklet_trampoline;
	tasklet_init(&ttimer->tasklet, __tasklet_hrtimer_trampoline,
		     (unsigned long)ttimer);
	ttimer->function = function;
}


BlockGroup::BlockGroup(
    Cluster* pCluster,
    long idx,
    long long block_start,
    long long block_size,
    long long prev,
    long long next,
    long long duration,
    long long discard_padding) :
    BlockEntry(pCluster, idx),
    m_block(block_start, block_size, discard_padding),
    m_prev(prev),
    m_next(next),
    m_duration(duration)
{
}


static void assemble_neg_contexts(struct smb2_negotiate_req *req)
{
	return;
}


static void hda_audio_command(HDACodecDevice *hda, uint32_t nid, uint32_t data)

{

    HDAAudioState *a = HDA_AUDIO(hda);

    HDAAudioStream *st;

    const desc_node *node = NULL;

    const desc_param *param;

    uint32_t verb, payload, response, count, shift;

    if ((data & 0x70000) == 0x70000) {

        /* 12/8 id/payload */

        verb = (data >> 8) & 0xfff;

        payload = data & 0x00ff;

    } else {

        /* 4/16 id/payload */

        verb = (data >> 8) & 0xf00;

        payload = data & 0xffff;

    }

    node = hda_codec_find_node(a->desc, nid);

    if (node == NULL) {

        goto fail;

    }

    dprint(a, 2, "%s: nid %d (%s), verb 0x%x, payload 0x%x\n",

           __FUNCTION__, nid, node->name, verb, payload);

    switch (verb) {

    /* all nodes */

    case AC_VERB_PARAMETERS:

        param = hda_codec_find_param(node, payload);

        if (param == NULL) {

            goto fail;

        }

        hda_codec_response(hda, true, param->val);

        break;

    case AC_VERB_GET_SUBSYSTEM_ID:

        hda_codec_response(hda, true, a->desc->iid);

        break;

    /* all functions */

    case AC_VERB_GET_CONNECT_LIST:

        param = hda_codec_find_param(node, AC_PAR_CONNLIST_LEN);

        count = param ? param->val : 0;

        response = 0;

        shift = 0;

        while (payload < count && shift < 32) {

            response |= node->conn[payload] << shift;

            payload++;

            shift += 8;

        }

        hda_codec_response(hda, true, response);

        break;

    /* pin widget */

    case AC_VERB_GET_CONFIG_DEFAULT:

        hda_codec_response(hda, true, node->config);

        break;

    case AC_VERB_GET_PIN_WIDGET_CONTROL:

        hda_codec_response(hda, true, node->pinctl);

        break;

    case AC_VERB_SET_PIN_WIDGET_CONTROL:

        if (node->pinctl != payload) {

            dprint(a, 1, "unhandled pin control bit\n");

        }

        hda_codec_response(hda, true, 0);

        break;

    /* audio in/out widget */

    case AC_VERB_SET_CHANNEL_STREAMID:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        hda_audio_set_running(st, false);

        st->stream = (payload >> 4) & 0x0f;

        st->channel = payload & 0x0f;

        dprint(a, 2, "%s: stream %d, channel %d\n",

               st->node->name, st->stream, st->channel);

        hda_audio_set_running(st, a->running_real[st->output * 16 + st->stream]);

        hda_codec_response(hda, true, 0);

        break;

    case AC_VERB_GET_CONV:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        response = st->stream << 4 | st->channel;

        hda_codec_response(hda, true, response);

        break;

    case AC_VERB_SET_STREAM_FORMAT:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        st->format = payload;

        hda_codec_parse_fmt(st->format, &st->as);

        hda_audio_setup(st);

        hda_codec_response(hda, true, 0);

        break;

    case AC_VERB_GET_STREAM_FORMAT:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        hda_codec_response(hda, true, st->format);

        break;

    case AC_VERB_GET_AMP_GAIN_MUTE:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        if (payload & AC_AMP_GET_LEFT) {

            response = st->gain_left | (st->mute_left ? AC_AMP_MUTE : 0);

        } else {

            response = st->gain_right | (st->mute_right ? AC_AMP_MUTE : 0);

        }

        hda_codec_response(hda, true, response);

        break;

    case AC_VERB_SET_AMP_GAIN_MUTE:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        dprint(a, 1, "amp (%s): %s%s%s%s index %d  gain %3d %s\n",

               st->node->name,

               (payload & AC_AMP_SET_OUTPUT) ? "o" : "-",

               (payload & AC_AMP_SET_INPUT)  ? "i" : "-",

               (payload & AC_AMP_SET_LEFT)   ? "l" : "-",

               (payload & AC_AMP_SET_RIGHT)  ? "r" : "-",

               (payload & AC_AMP_SET_INDEX) >> AC_AMP_SET_INDEX_SHIFT,

               (payload & AC_AMP_GAIN),

               (payload & AC_AMP_MUTE) ? "muted" : "");

        if (payload & AC_AMP_SET_LEFT) {

            st->gain_left = payload & AC_AMP_GAIN;

            st->mute_left = payload & AC_AMP_MUTE;

        }

        if (payload & AC_AMP_SET_RIGHT) {

            st->gain_right = payload & AC_AMP_GAIN;

            st->mute_right = payload & AC_AMP_MUTE;

        }

        hda_audio_set_amp(st);

        hda_codec_response(hda, true, 0);

        break;

    /* not supported */

    case AC_VERB_SET_POWER_STATE:

    case AC_VERB_GET_POWER_STATE:

    case AC_VERB_GET_SDI_SELECT:

        hda_codec_response(hda, true, 0);

        break;

    default:

        goto fail;

    }

    return;

fail:

    dprint(a, 1, "%s: not handled: nid %d (%s), verb 0x%x, payload 0x%x\n",

           __FUNCTION__, nid, node ? node->name : "?", verb, payload);

    hda_codec_response(hda, true, 0);

}


static void qcms_transform_module_matrix_translate ( struct qcms_modular_transform * transform , float * src , float * dest , size_t length ) {
 size_t i ;
 struct matrix mat ;
 mat . m [ 0 ] [ 0 ] = transform -> matrix . m [ 0 ] [ 0 ] ;
 mat . m [ 1 ] [ 0 ] = transform -> matrix . m [ 0 ] [ 1 ] ;
 mat . m [ 2 ] [ 0 ] = transform -> matrix . m [ 0 ] [ 2 ] ;
 mat . m [ 0 ] [ 1 ] = transform -> matrix . m [ 1 ] [ 0 ] ;
 mat . m [ 1 ] [ 1 ] = transform -> matrix . m [ 1 ] [ 1 ] ;
 mat . m [ 2 ] [ 1 ] = transform -> matrix . m [ 1 ] [ 2 ] ;
 mat . m [ 0 ] [ 2 ] = transform -> matrix . m [ 2 ] [ 0 ] ;
 mat . m [ 1 ] [ 2 ] = transform -> matrix . m [ 2 ] [ 1 ] ;
 mat . m [ 2 ] [ 2 ] = transform -> matrix . m [ 2 ] [ 2 ] ;
 for ( i = 0 ;
 i < length ;
 i ++ ) {
 float in_r = * src ++ ;
 float in_g = * src ++ ;
 float in_b = * src ++ ;
 float out_r = mat . m [ 0 ] [ 0 ] * in_r + mat . m [ 1 ] [ 0 ] * in_g + mat . m [ 2 ] [ 0 ] * in_b + transform -> tx ;
 float out_g = mat . m [ 0 ] [ 1 ] * in_r + mat . m [ 1 ] [ 1 ] * in_g + mat . m [ 2 ] [ 1 ] * in_b + transform -> ty ;
 float out_b = mat . m [ 0 ] [ 2 ] * in_r + mat . m [ 1 ] [ 2 ] * in_g + mat . m [ 2 ] [ 2 ] * in_b + transform -> tz ;
 * dest ++ = clamp_float ( out_r ) ;
 * dest ++ = clamp_float ( out_g ) ;
 * dest ++ = clamp_float ( out_b ) ;
 }
 }


static void unpause_activation_timed_cancel ( ActivateParameters * parameters ) {
 if ( ! parameters -> timed_wait_active ) {
 activation_start_timed_cancel ( parameters ) ;
 }
 }


static void uint8ArrayAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
    TestObjectPythonV8Internal::uint8ArrayAttributeAttributeGetter(info);
    TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}