PrintingContextCairo::PrintingContextCairo(const std::string& app_locale)
#if defined(OS_CHROMEOS)
    : PrintingContext(app_locale) {
#else
    : PrintingContext(app_locale),
      print_dialog_(NULL) {
#endif
}

PrintingContextCairo::~PrintingContextCairo() {
  ReleaseContext();

#if !defined(OS_CHROMEOS)
  if (print_dialog_)
    print_dialog_->ReleaseDialog();
#endif
}

#if !defined(OS_CHROMEOS)
void PrintingContextCairo::SetCreatePrintDialogFunction(
    PrintDialogGtkInterface* (*create_dialog_func)(
        PrintingContextCairo* context)) {
  DCHECK(create_dialog_func);
  DCHECK(!create_dialog_func_);
  create_dialog_func_ = create_dialog_func;
}

void PrintingContextCairo::PrintDocument(const Metafile* metafile) {
  DCHECK(print_dialog_);
  DCHECK(metafile);
  print_dialog_->PrintDocument(metafile, document_name_);
}
#endif  // !defined(OS_CHROMEOS)

void PrintingContextCairo::AskUserForSettings(
    gfx::NativeView parent_view,
    int max_pages,
    bool has_selection,
    PrintSettingsCallback* callback) {
#if defined(OS_CHROMEOS)
  callback->Run(OK);
#else
  print_dialog_->ShowDialog(callback);
#endif  // defined(OS_CHROMEOS)
}

PrintingContext::Result PrintingContextCairo::UseDefaultSettings() {
  DCHECK(!in_print_job_);

  ResetSettings();
#if defined(OS_CHROMEOS)
  int dpi = 300;
  gfx::Size physical_size_device_units;
  gfx::Rect printable_area_device_units;
  int32_t width = 0;
  int32_t height = 0;
  UErrorCode error = U_ZERO_ERROR;
  ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);
  if (error != U_ZERO_ERROR) {
    LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: "
                 << error;
    width = static_cast<int>(8.5 * dpi);
    height = static_cast<int>(11 * dpi);
  } else {
    width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi);
    height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi);
  }

  physical_size_device_units.SetSize(width, height);
  printable_area_device_units.SetRect(
      static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),
      static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),
      width - (PrintSettingsInitializerGtk::kLeftMarginInInch +
          PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,
      height - (PrintSettingsInitializerGtk::kTopMarginInInch +
          PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);

  settings_.set_dpi(dpi);
  settings_.SetPrinterPrintableArea(physical_size_device_units,
                                    printable_area_device_units,
                                    dpi);
#else
  if (!print_dialog_) {
    print_dialog_ = create_dialog_func_(this);
    print_dialog_->AddRefToDialog();
  }
  print_dialog_->UseDefaultSettings();
#endif  // defined(OS_CHROMEOS)

  return OK;
}

PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
    const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
  bool landscape = false;

  if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
    return OnError();

  settings_.SetOrientation(landscape);
  settings_.ranges = ranges;

  return OK;
 #else
   DCHECK(!in_print_job_);

   if (!print_dialog_->UpdateSettings(job_settings, ranges))
     return OnError();

  return OK;
#endif
}

PrintingContext::Result PrintingContextCairo::InitWithSettings(
    const PrintSettings& settings) {
  DCHECK(!in_print_job_);

  settings_ = settings;

  return OK;
}

PrintingContext::Result PrintingContextCairo::NewDocument(
    const string16& document_name) {
  DCHECK(!in_print_job_);
  in_print_job_ = true;

#if !defined(OS_CHROMEOS)
  document_name_ = document_name;
#endif  // !defined(OS_CHROMEOS)

  return OK;
}

PrintingContext::Result PrintingContextCairo::NewPage() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  return OK;
}

PrintingContext::Result PrintingContextCairo::PageDone() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  return OK;
}

PrintingContext::Result PrintingContextCairo::DocumentDone() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  ResetSettings();
  return OK;
}

void PrintingContextCairo::Cancel() {
  abort_printing_ = true;
  in_print_job_ = false;
}

void PrintingContextCairo::ReleaseContext() {
}

gfx::NativeDrawingContext PrintingContextCairo::context() const {
  return NULL;
}

}  // namespace printing


static void _bson_init_size( bson *b, int size ) {
    if( size == 0 )
        b->data = NULL;
    else
        b->data = ( char * )bson_malloc( size );
    b->dataSize = size;
    b->cur = b->data + 4;
    _bson_reset( b );
}


static int pf_probe(struct pf_unit *pf)
{
	if (pf->drive == -1) {
		for (pf->drive = 0; pf->drive <= 1; pf->drive++)
			if (!pf_reset(pf)) {
				if (pf->lun != -1)
					return pf_identify(pf);
				else
					for (pf->lun = 0; pf->lun < 8; pf->lun++)
						if (!pf_identify(pf))
							return 0;
			}
	} else {
		if (pf_reset(pf))
			return -1;
		if (pf->lun != -1)
			return pf_identify(pf);
		for (pf->lun = 0; pf->lun < 8; pf->lun++)
			if (!pf_identify(pf))
				return 0;
	}
	return -1;
}


handle_queue_stats_request(struct ofconn *ofconn,
                           const struct ofp_header *rq)
{
    struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
    struct queue_stats_cbdata cbdata;
    struct ofport *port;
    enum ofperr error;
    struct ofputil_queue_stats_request oqsr;

    COVERAGE_INC(ofproto_queue_req);

    ofpmp_init(&cbdata.replies, rq);
    cbdata.now = time_msec();

    error = ofputil_decode_queue_stats_request(rq, &oqsr);
    if (error) {
        return error;
    }

    if (oqsr.port_no == OFPP_ANY) {
        error = OFPERR_OFPQOFC_BAD_QUEUE;
        HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
            if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
                error = 0;
            }
        }
    } else {
        port = ofproto_get_port(ofproto, oqsr.port_no);
        error = (port
                 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
                 : OFPERR_OFPQOFC_BAD_PORT);
    }
    if (!error) {
        ofconn_send_replies(ofconn, &cbdata.replies);
    } else {
        ofpbuf_list_delete(&cbdata.replies);
    }

    return error;
}


int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
    MpegEncContext *s = &ctx->m;
    unsigned startcode, v;
    int ret;
    int vol = 0;

    /* search next start code */
    align_get_bits(gb);

    // If we have not switched to studio profile than we also did not switch bps
    // that means something else (like a previous instance) outside set bps which
    // would be inconsistant with the currect state, thus reset it
    if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
        s->avctx->bits_per_raw_sample = 0;

    if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
        skip_bits(gb, 24);
        if (get_bits(gb, 8) == 0xF0)
            goto end;
    }

    startcode = 0xff;
    for (;;) {
        if (get_bits_count(gb) >= gb->size_in_bits) {
            if (gb->size_in_bits == 8 &&
                (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
                av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
                return FRAME_SKIPPED;  // divx bug
            } else
                return AVERROR_INVALIDDATA;  // end of stream
        }

        /* use the bits after the test */
        v = get_bits(gb, 8);
        startcode = ((startcode << 8) | v) & 0xffffffff;

        if ((startcode & 0xFFFFFF00) != 0x100)
            continue;  // no startcode

        if (s->avctx->debug & FF_DEBUG_STARTCODE) {
            av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
            if (startcode <= 0x11F)
                av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
            else if (startcode <= 0x12F)
                av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
            else if (startcode <= 0x13F)
                av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
            else if (startcode <= 0x15F)
                av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
            else if (startcode <= 0x1AF)
                av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
            else if (startcode == 0x1B0)
                av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
            else if (startcode == 0x1B1)
                av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
            else if (startcode == 0x1B2)
                av_log(s->avctx, AV_LOG_DEBUG, "User Data");
            else if (startcode == 0x1B3)
                av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
            else if (startcode == 0x1B4)
                av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
            else if (startcode == 0x1B5)
                av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
            else if (startcode == 0x1B6)
                av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
            else if (startcode == 0x1B7)
                av_log(s->avctx, AV_LOG_DEBUG, "slice start");
            else if (startcode == 0x1B8)
                av_log(s->avctx, AV_LOG_DEBUG, "extension start");
            else if (startcode == 0x1B9)
                av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
            else if (startcode == 0x1BA)
                av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
            else if (startcode == 0x1BB)
                av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
            else if (startcode == 0x1BC)
                av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
            else if (startcode == 0x1BD)
                av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
            else if (startcode == 0x1BE)
                av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
            else if (startcode == 0x1BF)
                av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
            else if (startcode == 0x1C0)
                av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
            else if (startcode == 0x1C1)
                av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
            else if (startcode == 0x1C2)
                av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
            else if (startcode == 0x1C3)
                av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
            else if (startcode <= 0x1C5)
                av_log(s->avctx, AV_LOG_DEBUG, "reserved");
            else if (startcode <= 0x1FF)
                av_log(s->avctx, AV_LOG_DEBUG, "System start");
            av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
        }

        if (startcode >= 0x120 && startcode <= 0x12F) {
            if (vol) {
                av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
                continue;
            }
            vol++;
            if ((ret = decode_vol_header(ctx, gb)) < 0)
                return ret;
        } else if (startcode == USER_DATA_STARTCODE) {
            decode_user_data(ctx, gb);
        } else if (startcode == GOP_STARTCODE) {
            mpeg4_decode_gop_header(s, gb);
        } else if (startcode == VOS_STARTCODE) {
            int profile, level;
            mpeg4_decode_profile_level(s, gb, &profile, &level);
            if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
                (level > 0 && level < 9)) {
                s->studio_profile = 1;
                next_start_code_studio(gb);
                extension_and_user_data(s, gb, 0);
            } else if (s->studio_profile) {
                avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n");
                return AVERROR_PATCHWELCOME;
            }
            s->avctx->profile = profile;
            s->avctx->level   = level;
        } else if (startcode == VISUAL_OBJ_STARTCODE) {
            if (s->studio_profile) {
                if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
                    return ret;
            } else
                mpeg4_decode_visual_object(s, gb);
        } else if (startcode == VOP_STARTCODE) {
            break;
        }

        align_get_bits(gb);
        startcode = 0xff;
    }

end:
    if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
        s->low_delay = 1;
    s->avctx->has_b_frames = !s->low_delay;

    if (s->studio_profile) {
        if (!s->avctx->bits_per_raw_sample) {
            av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
            return AVERROR_INVALIDDATA;
        }
        return decode_studio_vop_header(ctx, gb);
    } else
        return decode_vop_header(ctx, gb);
}


lyd_change_leaf(struct lyd_node_leaf_list *leaf, const char *val_str)
{
    const char *backup;
    int val_change, dflt_change;
    struct lyd_node *parent;

    if (!leaf || (leaf->schema->nodetype != LYS_LEAF)) {
        LOGARG;
        return -1;
    }

    backup = leaf->value_str;
    leaf->value_str = lydict_insert(leaf->schema->module->ctx, val_str ? val_str : "", 0);
    /* leaf->value is erased by lyp_parse_value() */

    /* parse the type correctly, makes the value canonical if needed */
    if (!lyp_parse_value(&((struct lys_node_leaf *)leaf->schema)->type, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) {
        lydict_remove(leaf->schema->module->ctx, backup);
        return -1;
    }

    if (!strcmp(backup, leaf->value_str)) {
        /* the value remains the same */
        val_change = 0;
    } else {
        val_change = 1;
    }

    /* value is correct, remove backup */
    lydict_remove(leaf->schema->module->ctx, backup);

    /* clear the default flag, the value is different */
    if (leaf->dflt) {
        for (parent = (struct lyd_node *)leaf; parent; parent = parent->parent) {
            parent->dflt = 0;
        }
        dflt_change = 1;
    } else {
        dflt_change = 0;
    }

    if (val_change) {
        /* make the node non-validated */
        leaf->validity = ly_new_node_validity(leaf->schema);

        /* check possible leafref backlinks */
        check_leaf_list_backlinks((struct lyd_node *)leaf, 2);
    }

    if (val_change && (leaf->schema->flags & LYS_UNIQUE)) {
        for (parent = leaf->parent; parent && (parent->schema->nodetype != LYS_LIST); parent = parent->parent);
        if (parent) {
            parent->validity |= LYD_VAL_UNIQUE;
        } else {
            LOGINT(leaf->schema->module->ctx);
            return -1;
        }
    }

    return (val_change || dflt_change ? 0 : 1);
}


static PHP_INI_MH(OnUpdateTransSid) /* {{{ */
{
	SESSION_CHECK_ACTIVE_STATE;

	if (!strncasecmp(new_value, "on", sizeof("on"))) {
		PS(use_trans_sid) = (zend_bool) 1;
	} else {
		PS(use_trans_sid) = (zend_bool) atoi(new_value);
	}

	return SUCCESS;
}
/* }}} */


userauth_hostbased(struct ssh *ssh)
{
	Authctxt *authctxt = ssh->authctxt;
	struct sshbuf *b;
	struct sshkey *key = NULL;
	char *pkalg, *cuser, *chost;
	u_char *pkblob, *sig;
	size_t alen, blen, slen;
	int r, pktype, authenticated = 0;

	if (!authctxt->valid) {
		debug2("%s: disabled because of invalid user", __func__);
		return 0;
	}
	/* XXX use sshkey_froms() */
	if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 ||
	    (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
	    (r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 ||
	    (r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 ||
	    (r = sshpkt_get_string(ssh, &sig, &slen)) != 0)
		fatal("%s: packet parsing: %s", __func__, ssh_err(r));

	debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__,
	    cuser, chost, pkalg, slen);
#ifdef DEBUG_PK
	debug("signature:");
	sshbuf_dump_data(sig, siglen, stderr);
#endif
	pktype = sshkey_type_from_name(pkalg);
	if (pktype == KEY_UNSPEC) {
		/* this is perfectly legal */
		logit("%s: unsupported public key algorithm: %s",
		    __func__, pkalg);
		goto done;
	}
	if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
		error("%s: key_from_blob: %s", __func__, ssh_err(r));
		goto done;
	}
	if (key == NULL) {
		error("%s: cannot decode key: %s", __func__, pkalg);
		goto done;
	}
	if (key->type != pktype) {
		error("%s: type mismatch for decoded key "
		    "(received %d, expected %d)", __func__, key->type, pktype);
		goto done;
	}
	if (sshkey_type_plain(key->type) == KEY_RSA &&
	    (ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
		error("Refusing RSA key because peer uses unsafe "
		    "signature format");
		goto done;
	}
	if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) {
		logit("%s: key type %s not in HostbasedAcceptedKeyTypes",
		    __func__, sshkey_type(key));
		goto done;
	}

	if ((b = sshbuf_new()) == NULL)
		fatal("%s: sshbuf_new failed", __func__);
	/* reconstruct packet */
	if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
	    (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
	    (r = sshbuf_put_cstring(b, authctxt->user)) != 0 ||
	    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
	    (r = sshbuf_put_cstring(b, "hostbased")) != 0 ||
	    (r = sshbuf_put_string(b, pkalg, alen)) != 0 ||
	    (r = sshbuf_put_string(b, pkblob, blen)) != 0 ||
	    (r = sshbuf_put_cstring(b, chost)) != 0 ||
	    (r = sshbuf_put_cstring(b, cuser)) != 0)
		fatal("%s: buffer error: %s", __func__, ssh_err(r));
#ifdef DEBUG_PK
	sshbuf_dump(b, stderr);
#endif

	auth2_record_info(authctxt,
	    "client user \"%.100s\", client host \"%.100s\"", cuser, chost);

	/* test for allowed key and correct signature */
	authenticated = 0;
	if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) &&
	    PRIVSEP(sshkey_verify(key, sig, slen,
	    sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0)
		authenticated = 1;

	auth2_record_key(authctxt, authenticated, key);
	sshbuf_free(b);
done:
	debug2("%s: authenticated %d", __func__, authenticated);
	sshkey_free(key);
	free(pkalg);
	free(pkblob);
	free(cuser);
	free(chost);
	free(sig);
	return authenticated;
}


GF_WebVTTSampleEntryBox *gf_webvtt_isom_get_description(GF_ISOFile *movie, u32 trackNumber, u32 descriptionIndex)
{
	GF_WebVTTSampleEntryBox *wvtt;
	GF_TrackBox *trak;

	if (!descriptionIndex) return NULL;

	trak = gf_isom_get_track_from_file(movie, trackNumber);
	if (!trak || !trak->Media) return NULL;

	switch (trak->Media->handler->handlerType) {
	case GF_ISOM_MEDIA_TEXT:
		break;
	default:
		return NULL;
	}

	wvtt = (GF_WebVTTSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, descriptionIndex - 1);
	if (!wvtt) return NULL;
	switch (wvtt->type) {
	case GF_ISOM_BOX_TYPE_WVTT:
		break;
	default:
		return NULL;
	}
	return wvtt;
}


int get_unalign_ctl(struct task_struct *tsk, unsigned long adr)
{
	return put_user(tsk->thread.align_ctl, (unsigned int __user *)adr);
}


static int msg_fetch_header(struct Context *ctx, struct ImapHeader *h, char *buf, FILE *fp)
{
  unsigned int bytes;
  int rc = -1; /* default now is that string isn't FETCH response */
  int parse_rc;

  struct ImapData *idata = ctx->data;

  if (buf[0] != '*')
    return rc;

  /* skip to message number */
  buf = imap_next_word(buf);
  if (mutt_str_atoui(buf, &h->data->msn) < 0)
    return rc;

  /* find FETCH tag */
  buf = imap_next_word(buf);
  if (mutt_str_strncasecmp("FETCH", buf, 5) != 0)
    return rc;

  rc = -2; /* we've got a FETCH response, for better or worse */
  buf = strchr(buf, '(');
  if (!buf)
    return rc;
  buf++;

  /* FIXME: current implementation - call msg_parse_fetch - if it returns -2,
   *   read header lines and call it again. Silly. */
  parse_rc = msg_parse_fetch(h, buf);
  if (!parse_rc)
    return 0;
  if (parse_rc != -2 || !fp)
    return rc;

  if (imap_get_literal_count(buf, &bytes) == 0)
  {
    imap_read_literal(fp, idata, bytes, NULL);

    /* we may have other fields of the FETCH _after_ the literal
     * (eg Domino puts FLAGS here). Nothing wrong with that, either.
     * This all has to go - we should accept literals and nonliterals
     * interchangeably at any time. */
    if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
      return rc;

    if (msg_parse_fetch(h, idata->buf) == -1)
      return rc;
  }

  rc = 0; /* success */

  /* subtract headers from message size - unfortunately only the subset of
   * headers we've requested. */
  h->content_length -= bytes;

  return rc;
}


static void longMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
    TestObjectV8Internal::longMethodMethod(info);
    TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}


MatrixMap<Scalar> MapAsMatrixWithLastDimAsRows(Scalar* data,
                                               const RuntimeShape& shape) {
  const int dims_count = shape.DimensionsCount();
  const int rows = shape.Dims(dims_count - 1);
  const int cols = FlatSizeSkipDim(shape, dims_count - 1);
  return MatrixMap<Scalar>(data, rows, cols);
}


void LibRaw::exp_bef(float shift, float smooth)
{
    // params limits
    if(shift>8) shift = 8;
    if(shift<0.25) shift = 0.25;
    if(smooth < 0.0) smooth = 0.0;
    if(smooth > 1.0) smooth = 1.0;

    unsigned short *lut = (ushort*)malloc((TBLN+1)*sizeof(unsigned short));

    if(shift <=1.0)
        {
            for(int i=0;i<=TBLN;i++)
                lut[i] = (unsigned short)((float)i*shift);
        }
    else
        {
            float x1,x2,y1,y2;

            float cstops = log(shift)/log(2.0f);
            float room = cstops*2;
            float roomlin = powf(2.0f,room);
            x2 = (float)TBLN;
            x1 = (x2+1)/roomlin-1;
            y1 = x1*shift;
            y2 = x2*(1+(1-smooth)*(shift-1));
            float sq3x=powf(x1*x1*x2,1.0f/3.0f);
            float B = (y2-y1+shift*(3*x1-3.0f*sq3x)) / (x2+2.0f*x1-3.0f*sq3x);
            float A = (shift - B)*3.0f*powf(x1*x1,1.0f/3.0f);
            float CC = y2 - A*powf(x2,1.0f/3.0f)-B*x2;
            for(int i=0;i<=TBLN;i++)
                {
                    float X = (float)i;
                    float Y = A*powf(X,1.0f/3.0f)+B*X+CC;
                    if(i<x1)
                        lut[i] = (unsigned short)((float)i*shift);
                    else
                        lut[i] = Y<0?0:(Y>TBLN?TBLN:(unsigned short)(Y));
                }
        }
    for(int i=0; i< S.height*S.width; i++)
        {
            imgdata.image[i][0] = lut[imgdata.image[i][0]];
            imgdata.image[i][1] = lut[imgdata.image[i][1]];
            imgdata.image[i][2] = lut[imgdata.image[i][2]];
            imgdata.image[i][3] = lut[imgdata.image[i][3]];
        }

	if(C.data_maximum <=TBLN)
		C.data_maximum = lut[C.data_maximum];
	if(C.maximum <= TBLN)
		C.maximum = lut[C.maximum];
    // no need to adjust the minumum, black is already subtracted
    free(lut);
}


nfsd4_encode_sequence(struct nfsd4_compoundres *resp, __be32 nfserr,
		      struct nfsd4_sequence *seq)
{
	struct xdr_stream *xdr = &resp->xdr;
	__be32 *p;

	if (nfserr)
		return nfserr;

	p = xdr_reserve_space(xdr, NFS4_MAX_SESSIONID_LEN + 20);
	if (!p)
		return nfserr_resource;
	p = xdr_encode_opaque_fixed(p, seq->sessionid.data,
					NFS4_MAX_SESSIONID_LEN);
	*p++ = cpu_to_be32(seq->seqid);
	*p++ = cpu_to_be32(seq->slotid);
	/* Note slotid's are numbered from zero: */
	*p++ = cpu_to_be32(seq->maxslots - 1); /* sr_highest_slotid */
	*p++ = cpu_to_be32(seq->maxslots - 1); /* sr_target_highest_slotid */
	*p++ = cpu_to_be32(seq->status_flags);

	resp->cstate.data_offset = xdr->buf->len; /* DRC cache data pointer */
	return 0;
}


static void U_CALLCONV T_UConverter_fromUnicode_UTF32_BE_OFFSET_LOGIC ( UConverterFromUnicodeArgs * args , UErrorCode * err ) {
 const UChar * mySource = args -> source ;
 unsigned char * myTarget ;
 int32_t * myOffsets ;
 const UChar * sourceLimit = args -> sourceLimit ;
 const unsigned char * targetLimit = ( unsigned char * ) args -> targetLimit ;
 UChar32 ch , ch2 ;
 int32_t offsetNum = 0 ;
 unsigned int indexToWrite ;
 unsigned char temp [ sizeof ( uint32_t ) ] ;
 if ( mySource >= sourceLimit ) {
 return ;
 }
 if ( args -> converter -> fromUnicodeStatus == UCNV_NEED_TO_WRITE_BOM ) {
 static const char bom [ ] = {
 0 , 0 , ( char ) 0xfe , ( char ) 0xff }
 ;
 ucnv_fromUWriteBytes ( args -> converter , bom , 4 , & args -> target , args -> targetLimit , & args -> offsets , - 1 , err ) ;
 args -> converter -> fromUnicodeStatus = 0 ;
 }
 myTarget = ( unsigned char * ) args -> target ;
 myOffsets = args -> offsets ;
 temp [ 0 ] = 0 ;
 if ( args -> converter -> fromUChar32 ) {
 ch = args -> converter -> fromUChar32 ;
 args -> converter -> fromUChar32 = 0 ;
 goto lowsurogate ;
 }
 while ( mySource < sourceLimit && myTarget < targetLimit ) {
 ch = * ( mySource ++ ) ;
 if ( U_IS_SURROGATE ( ch ) ) {
 if ( U_IS_LEAD ( ch ) ) {
 lowsurogate : if ( mySource < sourceLimit ) {
 ch2 = * mySource ;
 if ( U_IS_TRAIL ( ch2 ) ) {
 ch = ( ( ch - SURROGATE_HIGH_START ) << HALF_SHIFT ) + ch2 + SURROGATE_LOW_BASE ;
 mySource ++ ;
 }
 else {
 args -> converter -> fromUChar32 = ch ;
 * err = U_ILLEGAL_CHAR_FOUND ;
 break ;
 }
 }
 else {
 args -> converter -> fromUChar32 = ch ;
 if ( args -> flush ) {
 * err = U_ILLEGAL_CHAR_FOUND ;
 }
 break ;
 }
 }
 else {
 args -> converter -> fromUChar32 = ch ;
 * err = U_ILLEGAL_CHAR_FOUND ;
 break ;
 }
 }
 temp [ 1 ] = ( uint8_t ) ( ch >> 16 & 0x1F ) ;
 temp [ 2 ] = ( uint8_t ) ( ch >> 8 ) ;
 temp [ 3 ] = ( uint8_t ) ( ch ) ;
 for ( indexToWrite = 0 ;
 indexToWrite <= sizeof ( uint32_t ) - 1 ;
 indexToWrite ++ ) {
 if ( myTarget < targetLimit ) {
 * ( myTarget ++ ) = temp [ indexToWrite ] ;
 * ( myOffsets ++ ) = offsetNum ;
 }
 else {
 args -> converter -> charErrorBuffer [ args -> converter -> charErrorBufferLength ++ ] = temp [ indexToWrite ] ;
 * err = U_BUFFER_OVERFLOW_ERROR ;
 }
 }
 offsetNum = offsetNum + 1 + ( temp [ 1 ] != 0 ) ;
 }
 if ( mySource < sourceLimit && myTarget >= targetLimit && U_SUCCESS ( * err ) ) {
 * err = U_BUFFER_OVERFLOW_ERROR ;
 }
 args -> target = ( char * ) myTarget ;
 args -> source = mySource ;
 args -> offsets = myOffsets ;
 }


RemoteDevicePropertiesWidget::RemoteDevicePropertiesWidget(QWidget *parent)
    : QWidget(parent)
    , modified(false)
    , saveable(false)
{
    setupUi(this);
    if (qobject_cast<QTabWidget *>(parent)) {
        verticalLayout->setMargin(4);
    }
    type->addItem(tr("Secure Shell (sshfs)"), (int)Type_SshFs);
    type->addItem(tr("Locally Mounted Folder"), (int)Type_File);
}


mrb_mod_alias(mrb_state *mrb, mrb_value mod)
{
  struct RClass *c = mrb_class_ptr(mod);
  mrb_sym new_name, old_name;

  mrb_get_args(mrb, "nn", &new_name, &old_name);
  mrb_alias_method(mrb, c, new_name, old_name);
  return mrb_nil_value();
}


static int kvm_s390_register_io_adapter(S390FLICState *fs, uint32_t id,

                                        uint8_t isc, bool swap,

                                        bool is_maskable)

{

    struct kvm_s390_io_adapter adapter = {

        .id = id,

        .isc = isc,

        .maskable = is_maskable,

        .swap = swap,

    };

    KVMS390FLICState *flic = KVM_S390_FLIC(fs);

    int r, ret;

    struct kvm_device_attr attr = {

        .group = KVM_DEV_FLIC_ADAPTER_REGISTER,

        .addr = (uint64_t)&adapter,

    };

    if (!kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING)) {

        /* nothing to do */

        return 0;

    }

    r = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);

    ret = r ? -errno : 0;

    return ret;

}


LayoutUnit RenderFlexibleBox::mainAxisExtent() const
{
    return isHorizontalFlow() ? width() : height();
}


int64 KaxInternalBlock::GetDataPosition(size_t FrameNumber)
{
  int64 _Result = -1;

  if (ValueIsSet() && FrameNumber < SizeList.size()) {
    _Result = FirstFrameLocation;

    size_t _Idx = 0;
    while(FrameNumber--) {
      _Result += SizeList[_Idx++];
    }
  }

  return _Result;
}


void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
				    enum kvm_apicv_inhibit reason, bool set)
{
	if (!enable_apicv)
		return;

	down_write(&kvm->arch.apicv_update_lock);
	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
	up_write(&kvm->arch.apicv_update_lock);
}


static ExitStatus trans_fop_dew_0e(DisasContext *ctx, uint32_t insn,

                                   const DisasInsn *di)

{

    unsigned rt = extract32(insn, 0, 5);

    unsigned ra = assemble_ra64(insn);

    return do_fop_dew(ctx, rt, ra, di->f_dew);

}


static UINT dvcman_receive_channel_data(drdynvcPlugin* drdynvc,
                                        IWTSVirtualChannelManager* pChannelMgr,
                                        UINT32 ChannelId, wStream* data)
{
	UINT status = CHANNEL_RC_OK;
	DVCMAN_CHANNEL* channel;
	size_t dataSize = Stream_GetRemainingLength(data);
	channel = (DVCMAN_CHANNEL*) dvcman_find_channel_by_id(pChannelMgr, ChannelId);

	if (!channel)
	{
		/* Windows 8.1 tries to open channels not created.
				 * Ignore cases like this. */
		WLog_Print(drdynvc->log, WLOG_ERROR, "ChannelId %"PRIu32" not found!", ChannelId);
		return CHANNEL_RC_OK;
	}

 	if (channel->dvc_data)
 	{
 		/* Fragmented data */
		if (Stream_GetPosition(channel->dvc_data) + dataSize > (UINT32) Stream_Capacity(
		        channel->dvc_data))
 		{
 			WLog_Print(drdynvc->log, WLOG_ERROR, "data exceeding declared length!");
 			Stream_Release(channel->dvc_data);
 			channel->dvc_data = NULL;
 			return ERROR_INVALID_DATA;
 		}

		Stream_Write(channel->dvc_data, Stream_Pointer(data), dataSize);

 		if (Stream_GetPosition(channel->dvc_data) >= channel->dvc_data_length)
 		{
			Stream_SealLength(channel->dvc_data);
			Stream_SetPosition(channel->dvc_data, 0);
			status = channel->channel_callback->OnDataReceived(channel->channel_callback,
			         channel->dvc_data);
			Stream_Release(channel->dvc_data);
			channel->dvc_data = NULL;
		}
	}
	else
	{
		status = channel->channel_callback->OnDataReceived(channel->channel_callback,
		         data);
	}

	return status;
}


const PermissionSet* PermissionsData::GetTabSpecificPermissions(
    int tab_id) const {
  runtime_lock_.AssertAcquired();
  TabPermissionsMap::const_iterator iter =
      tab_specific_permissions_.find(tab_id);
  return iter != tab_specific_permissions_.end() ? iter->second.get() : nullptr;
}


xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
	    xmlNodePtr inst, xsltStylePreCompPtr castedComp)
{
#ifdef XSLT_REFACTORED
    xsltStyleItemForEachPtr comp = (xsltStyleItemForEachPtr) castedComp;
#else
    xsltStylePreCompPtr comp = castedComp;
#endif
    int i;
    xmlXPathObjectPtr res = NULL;
    xmlNodePtr cur, curInst;
    xmlNodeSetPtr list = NULL;
    xmlNodeSetPtr oldList;
    int oldXPProximityPosition, oldXPContextSize;
    xmlNodePtr oldContextNode;
    xsltTemplatePtr oldCurTemplRule;
    xmlDocPtr oldXPDoc;
    xsltDocumentPtr oldDocInfo;
    xmlXPathContextPtr xpctxt;

    if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL)) {
	xsltGenericError(xsltGenericErrorContext,
	    "xsltForEach(): Bad arguments.\n");
	return;
    }

    if (comp == NULL) {
        xsltTransformError(ctxt, NULL, inst,
	    "Internal error in xsltForEach(): "
	    "The XSLT 'for-each' instruction was not compiled.\n");
        return;
    }
    if ((comp->select == NULL) || (comp->comp == NULL)) {
	xsltTransformError(ctxt, NULL, inst,
	    "Internal error in xsltForEach(): "
	    "The selecting expression of the XSLT 'for-each' "
	    "instruction was not compiled correctly.\n");
	return;
    }
    xpctxt = ctxt->xpathCtxt;

#ifdef WITH_XSLT_DEBUG_PROCESS
    XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
	 "xsltForEach: select %s\n", comp->select));
#endif

    /*
    * Save context states.
    */
    oldDocInfo = ctxt->document;
    oldList = ctxt->nodeList;
    oldContextNode = ctxt->node;
    /*
    * The "current template rule" is cleared for the instantiation of
    * xsl:for-each.
    */
    oldCurTemplRule = ctxt->currentTemplateRule;
    ctxt->currentTemplateRule = NULL;

     oldXPDoc = xpctxt->doc;
     oldXPProximityPosition = xpctxt->proximityPosition;
     oldXPContextSize = xpctxt->contextSize;
    /*
    * Set up XPath.
    */
    xpctxt->node = contextNode;
#ifdef XSLT_REFACTORED
    if (comp->inScopeNs != NULL) {
	xpctxt->namespaces = comp->inScopeNs->list;
	xpctxt->nsNr = comp->inScopeNs->xpathNumber;
    } else {
	xpctxt->namespaces = NULL;
	xpctxt->nsNr = 0;
    }
#else
    xpctxt->namespaces = comp->nsList;
    xpctxt->nsNr = comp->nsNr;
#endif

     /*
     * Evaluate the 'select' expression.
     */
    res = xmlXPathCompiledEval(comp->comp, ctxt->xpathCtxt);

     if (res != NULL) {
 	if (res->type == XPATH_NODESET)
	    list = res->nodesetval;
	else {
	    xsltTransformError(ctxt, NULL, inst,
		"The 'select' expression does not evaluate to a node set.\n");

#ifdef WITH_XSLT_DEBUG_PROCESS
	    XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
		"xsltForEach: select didn't evaluate to a node list\n"));
#endif
	    goto error;
	}
    } else {
	xsltTransformError(ctxt, NULL, inst,
	    "Failed to evaluate the 'select' expression.\n");
	ctxt->state = XSLT_STATE_STOPPED;
	goto error;
    }

    if ((list == NULL) || (list->nodeNr <= 0))
	goto exit;

#ifdef WITH_XSLT_DEBUG_PROCESS
    XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
 	"xsltForEach: select evaluates to %d nodes\n", list->nodeNr));
 #endif

    /*
    * Restore XPath states for the "current node".
    */
    xpctxt->contextSize = oldXPContextSize;
    xpctxt->proximityPosition = oldXPProximityPosition;
    xpctxt->node = contextNode;
     /*
     * Set the list; this has to be done already here for xsltDoSortFunction().
     */
    ctxt->nodeList = list;
    /*
    * Handle xsl:sort instructions and skip them for further processing.
    * BUG TODO: We are not using namespaced potentially defined on the
    * xsl:sort element; XPath expression might fail.
    */
    curInst = inst->children;
    if (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) {
	int nbsorts = 0;
	xmlNodePtr sorts[XSLT_MAX_SORT];

	sorts[nbsorts++] = curInst;

#ifdef WITH_DEBUGGER
	if (xslDebugStatus != XSLT_DEBUG_NONE)
	    xslHandleDebugger(curInst, contextNode, NULL, ctxt);
#endif

	curInst = curInst->next;
	while (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) {
	    if (nbsorts >= XSLT_MAX_SORT) {
		xsltTransformError(ctxt, NULL, curInst,
		    "The number of xsl:sort instructions exceeds the "
		    "maximum (%d) allowed by this processor.\n",
		    XSLT_MAX_SORT);
		goto error;
	    } else {
		sorts[nbsorts++] = curInst;
	    }

#ifdef WITH_DEBUGGER
	    if (xslDebugStatus != XSLT_DEBUG_NONE)
		xslHandleDebugger(curInst, contextNode, NULL, ctxt);
#endif
	    curInst = curInst->next;
	}
	xsltDoSortFunction(ctxt, sorts, nbsorts);
    }
    xpctxt->contextSize = list->nodeNr;
    /*
    * Instantiate the sequence constructor for each selected node.
    */
    for (i = 0; i < list->nodeNr; i++) {
	cur = list->nodeTab[i];
	/*
	* The selected node becomes the "current node".
	*/
	ctxt->node = cur;
	/*
	* An xsl:for-each can change the current context doc.
	* OPTIMIZE TODO: Get rid of the need to set the context doc.
	*/
	if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL))
	    xpctxt->doc = cur->doc;

	xpctxt->proximityPosition = i + 1;

	xsltApplySequenceConstructor(ctxt, cur, curInst, NULL);
    }

exit:
error:
    if (res != NULL)
	xmlXPathFreeObject(res);
    /*
    * Restore old states.
    */
    ctxt->document = oldDocInfo;
    ctxt->nodeList = oldList;
    ctxt->node = oldContextNode;
    ctxt->currentTemplateRule = oldCurTemplRule;

    xpctxt->doc = oldXPDoc;
    xpctxt->contextSize = oldXPContextSize;
    xpctxt->proximityPosition = oldXPProximityPosition;
}


static uint32_t m5206_mbar_readl(void *opaque, target_phys_addr_t offset)

{

    m5206_mbar_state *s = (m5206_mbar_state *)opaque;

    int width;

    offset &= 0x3ff;

    if (offset > 0x200) {

        hw_error("Bad MBAR read offset 0x%x", (int)offset);

    }

    width = m5206_mbar_width[offset >> 2];

    if (width < 4) {

        uint32_t val;

        val = m5206_mbar_readw(opaque, offset) << 16;

        val |= m5206_mbar_readw(opaque, offset + 2);

        return val;

    }

    return m5206_mbar_read(s, offset, 4);

}


R_API int r_core_anal_refs(RCore *core, const char *input) {
	int cfg_debug = r_config_get_i (core->config, "cfg.debug");
	ut64 from, to;
	char *ptr;
	int rad, n;
	if (*input == '?') {
		r_core_cmd_help (core, help_msg_aar);
		return 0;
	}

	if (*input == 'j' || *input == '*') {
		rad = *input;
		input++;
	} else {
		rad = 0;
	}

	from = to = 0;
	ptr = r_str_trim_head (strdup (input));
	n = r_str_word_set0 (ptr);
	if (!n) {
		// get boundaries of current memory map, section or io map
		if (cfg_debug) {
			RDebugMap *map = r_debug_map_get (core->dbg, core->offset);
			if (map) {
				from = map->addr;
				to = map->addr_end;
			}
		} else {
			RList *list = r_core_get_boundaries_prot (core, R_IO_EXEC, NULL, "anal");
			RListIter *iter;
			RIOMap* map;
			r_list_foreach (list, iter, map) {
				from = map->itv.addr;
				to = r_itv_end (map->itv);
				if (r_cons_is_breaked ()) {
					break;
				}
				if (!from && !to) {
					eprintf ("Cannot determine xref search boundaries\n");
				} else if (to - from > UT32_MAX) {
					eprintf ("Skipping huge range\n");
				} else {
					r_core_anal_search_xrefs (core, from, to, rad);
				}
			}
			free (ptr);
			return 1;
		}
	} else if (n == 1) {
		from = core->offset;
		to = core->offset + r_num_math (core->num, r_str_word_get0 (ptr, 0));
	} else {
		eprintf ("Invalid number of arguments\n");
	}
	free (ptr);

	if (from == UT64_MAX && to == UT64_MAX) {
		return false;
	}
	if (!from && !to) {
		return false;
	}
	if (to - from > r_io_size (core->io)) {
		return false;
	}
	return r_core_anal_search_xrefs (core, from, to, rad);
}


XpmCreateDataFromImage(
    Display		  *display,
    char		***data_return,
    XImage		  *image,
    XImage		  *shapeimage,
    XpmAttributes	  *attributes)
{
    XpmImage xpmimage;
    XpmInfo info;
    int ErrorStatus;

    /* initialize return value */
    if (data_return)
	*data_return = NULL;

    /* create an XpmImage from the image */
    ErrorStatus = XpmCreateXpmImageFromImage(display, image, shapeimage,
					     &xpmimage, attributes);
    if (ErrorStatus != XpmSuccess)
	return (ErrorStatus);

    /* create the data from the XpmImage */
    if (attributes) {
	xpmSetInfo(&info, attributes);
	ErrorStatus = XpmCreateDataFromXpmImage(data_return, &xpmimage, &info);
    } else
	ErrorStatus = XpmCreateDataFromXpmImage(data_return, &xpmimage, NULL);

    /* free the XpmImage */
    XpmFreeXpmImage(&xpmimage);

    return (ErrorStatus);
}


XGetDeviceControl(
    register Display	*dpy,
    XDevice		*dev,
    int			 control)
{
    XDeviceControl *Device = NULL;
    XDeviceControl *Sav = NULL;
    xDeviceState *d = NULL;
    xDeviceState *sav = NULL;
    xGetDeviceControlReq *req;
    xGetDeviceControlReply rep;
    XExtDisplayInfo *info = XInput_find_display(dpy);

    LockDisplay(dpy);
    if (_XiCheckExtInit(dpy, XInput_Add_XChangeDeviceControl, info) == -1)
        return NULL;

    GetReq(GetDeviceControl, req);
    req->reqType = info->codes->major_opcode;
    req->ReqType = X_GetDeviceControl;
    req->deviceid = dev->device_id;
    req->control = control;

    if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
	goto out;

     if (rep.length > 0) {
 	unsigned long nbytes;
 	size_t size = 0;
	if (rep.length < (INT_MAX >> 2) &&
	    (rep.length << 2) >= sizeof(xDeviceState)) {
 	    nbytes = (unsigned long) rep.length << 2;
 	    d = Xmalloc(nbytes);
 	}
	    _XEatDataWords(dpy, rep.length);
	    goto out;
	}
	sav = d;
	_XRead(dpy, (char *)d, nbytes);

        /* In theory, we should just be able to use d->length to get the size.
         * Turns out that a number of X servers (up to and including server
         * 1.4) sent the wrong length value down the wire. So to not break
         * apps that run against older servers, we have to calculate the size
         * manually.
         */
	switch (d->control) {
	case DEVICE_RESOLUTION:
	{
	    xDeviceResolutionState *r;
	    size_t val_size;
 	    size_t val_size;

 	    r = (xDeviceResolutionState *) d;
	    if (sizeof(xDeviceResolutionState) > nbytes ||
		r->num_valuators >= (INT_MAX / (3 * sizeof(int))))
 		goto out;
 	    val_size = 3 * sizeof(int) * r->num_valuators;
 	    if ((sizeof(xDeviceResolutionState) + val_size) > nbytes)
	    break;
	}
        case DEVICE_ABS_CALIB:
        {
            if (sizeof(xDeviceAbsCalibState) > nbytes)
                goto out;
            size = sizeof(XDeviceAbsCalibState);
            break;
        }
        case DEVICE_ABS_AREA:
        {
            if (sizeof(xDeviceAbsAreaState) > nbytes)
                goto out;
            size = sizeof(XDeviceAbsAreaState);
            break;
        }
        case DEVICE_CORE:
        {
            if (sizeof(xDeviceCoreState) > nbytes)
                goto out;
            size = sizeof(XDeviceCoreState);
            break;
        }
	default:
	    if (d->length > nbytes)
		goto out;
	    size = d->length;
	    break;
	}

	Device = Xmalloc(size);
	if (!Device)
	    goto out;

	Sav = Device;

	d = sav;
	switch (control) {
	case DEVICE_RESOLUTION:
	{
	    int *iptr, *iptr2;
	    xDeviceResolutionState *r;
	    XDeviceResolutionState *R;
	    unsigned int i;

	    r = (xDeviceResolutionState *) d;
	    R = (XDeviceResolutionState *) Device;

	    R->control = DEVICE_RESOLUTION;
	    R->length = sizeof(XDeviceResolutionState);
	    R->num_valuators = r->num_valuators;
	    iptr = (int *)(R + 1);
	    iptr2 = (int *)(r + 1);
	    R->resolutions = iptr;
	    R->min_resolutions = iptr + R->num_valuators;
	    R->max_resolutions = iptr + (2 * R->num_valuators);
	    for (i = 0; i < (3 * R->num_valuators); i++)
		*iptr++ = *iptr2++;
	    break;
	}
        case DEVICE_ABS_CALIB:
        {
            xDeviceAbsCalibState *c = (xDeviceAbsCalibState *) d;
            XDeviceAbsCalibState *C = (XDeviceAbsCalibState *) Device;

            C->control = DEVICE_ABS_CALIB;
            C->length = sizeof(XDeviceAbsCalibState);
            C->min_x = c->min_x;
            C->max_x = c->max_x;
            C->min_y = c->min_y;
            C->max_y = c->max_y;
            C->flip_x = c->flip_x;
            C->flip_y = c->flip_y;
            C->rotation = c->rotation;
            C->button_threshold = c->button_threshold;

            break;
        }
        case DEVICE_ABS_AREA:
        {
            xDeviceAbsAreaState *a = (xDeviceAbsAreaState *) d;
            XDeviceAbsAreaState *A = (XDeviceAbsAreaState *) Device;

            A->control = DEVICE_ABS_AREA;
            A->length = sizeof(XDeviceAbsAreaState);
            A->offset_x = a->offset_x;
            A->offset_y = a->offset_y;
            A->width = a->width;
            A->height = a->height;
            A->screen = a->screen;
            A->following = a->following;

            break;
        }
        case DEVICE_CORE:
        {
            xDeviceCoreState *c = (xDeviceCoreState *) d;
            XDeviceCoreState *C = (XDeviceCoreState *) Device;

            C->control = DEVICE_CORE;
            C->length = sizeof(XDeviceCoreState);
            C->status = c->status;
            C->iscore = c->iscore;

            break;
        }
        case DEVICE_ENABLE:
        {
            xDeviceEnableState *e = (xDeviceEnableState *) d;
            XDeviceEnableState *E = (XDeviceEnableState *) Device;

            E->control = DEVICE_ENABLE;
            E->length = sizeof(E);
            E->enable = e->enable;

            break;
        }
	default:
	    break;
	}
    }


bool SetCookie(BrowserContext* browser_context,
               const GURL& url,
               const std::string& value) {
  bool result = false;
  base::RunLoop run_loop;
  network::mojom::CookieManagerPtr cookie_manager;
  BrowserContext::GetDefaultStoragePartition(browser_context)
      ->GetNetworkContext()
      ->GetCookieManager(mojo::MakeRequest(&cookie_manager));
  std::unique_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create(
      url, value, base::Time::Now(), net::CookieOptions()));
  DCHECK(cc.get());

  cookie_manager->SetCanonicalCookie(
      *cc.get(), true /* secure_source */, true /* modify_http_only */,
      base::BindOnce(&SetCookieCallback, &result, &run_loop));
  run_loop.Run();
  return result;
}


f_prevnonblank(typval_T *argvars, typval_T *rettv)
{
    linenr_T	lnum;

    lnum = tv_get_lnum(argvars);
    if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
	lnum = 0;
    else
	while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
	    --lnum;
    rettv->vval.v_number = lnum;
}


void GLES2DecoderImpl::DoBlitFramebufferCHROMIUM(
    GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
    GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
    GLbitfield mask, GLenum filter) {
  DCHECK(!ShouldDeferReads() && !ShouldDeferDraws());

  if (!CheckBoundFramebuffersValid("glBlitFramebufferCHROMIUM")) {
    return;
  }

  state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false);
  ScopedRenderTo do_render(framebuffer_state_.bound_draw_framebuffer.get());
  BlitFramebufferHelper(
      srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
  state_.SetDeviceCapabilityState(GL_SCISSOR_TEST,
                                  state_.enable_flags.scissor_test);
}


int validate_camera_metadata_structure(const camera_metadata_t *metadata,
 const size_t *expected_size) {

 if (metadata == NULL) {
        ALOGE("%s: metadata is null!", __FUNCTION__);
 return ERROR;
 }

 {
 static const struct {
 const char *name;
 size_t alignment;
 } alignments[] = {
 {
 .name = "camera_metadata",
 .alignment = METADATA_ALIGNMENT
 },
 {
 .name = "camera_metadata_buffer_entry",
 .alignment = ENTRY_ALIGNMENT
 },
 {
 .name = "camera_metadata_data",
 .alignment = DATA_ALIGNMENT
 },
 };

 for (size_t i = 0; i < sizeof(alignments)/sizeof(alignments[0]); ++i) {
 uintptr_t aligned_ptr = ALIGN_TO(metadata, alignments[i].alignment);

 if ((uintptr_t)metadata != aligned_ptr) {
                ALOGE("%s: Metadata pointer is not aligned (actual %p, "
 "expected %p) to type %s",
                      __FUNCTION__, metadata,
 (void*)aligned_ptr, alignments[i].name);
 return ERROR;
 }
 }
 }

 /**
     * Check that the metadata contents are correct
     */

 if (expected_size != NULL && metadata->size > *expected_size) {
        ALOGE("%s: Metadata size (%" PRIu32 ") should be <= expected size (%zu)",
              __FUNCTION__, metadata->size, *expected_size);
 return ERROR;
 }

 if (metadata->entry_count > metadata->entry_capacity) {
        ALOGE("%s: Entry count (%" PRIu32 ") should be <= entry capacity "
 "(%" PRIu32 ")",
              __FUNCTION__, metadata->entry_count, metadata->entry_capacity);

         return ERROR;
     }

    if (metadata->data_count > metadata->data_capacity) {
        ALOGE("%s: Data count (%" PRIu32 ") should be <= data capacity "
              "(%" PRIu32 ")",
              __FUNCTION__, metadata->data_count, metadata->data_capacity);
        android_errorWriteLog(SN_EVENT_LOG_ID, "30591838");
        return ERROR;
    }

    const metadata_uptrdiff_t entries_end = metadata->entries_start + metadata->entry_capacity;
     if (entries_end < metadata->entries_start || // overflow check
         entries_end > metadata->data_start) {

        ALOGE("%s: Entry start + capacity (%" PRIu32 ") should be <= data start "
 "(%" PRIu32 ")",
               __FUNCTION__,
 (metadata->entries_start + metadata->entry_capacity),
              metadata->data_start);
 return ERROR;
 }

 const metadata_uptrdiff_t data_end =
        metadata->data_start + metadata->data_capacity;
 if (data_end < metadata->data_start || // overflow check
        data_end > metadata->size) {

        ALOGE("%s: Data start + capacity (%" PRIu32 ") should be <= total size "
 "(%" PRIu32 ")",
               __FUNCTION__,
 (metadata->data_start + metadata->data_capacity),
              metadata->size);
 return ERROR;
 }

 const metadata_size_t entry_count = metadata->entry_count;
 camera_metadata_buffer_entry_t *entries = get_entries(metadata);

 for (size_t i = 0; i < entry_count; ++i) {

 if ((uintptr_t)&entries[i] != ALIGN_TO(&entries[i], ENTRY_ALIGNMENT)) {
            ALOGE("%s: Entry index %zu had bad alignment (address %p),"
 " expected alignment %zu",
                  __FUNCTION__, i, &entries[i], ENTRY_ALIGNMENT);
 return ERROR;
 }

 camera_metadata_buffer_entry_t entry = entries[i];

 if (entry.type >= NUM_TYPES) {
            ALOGE("%s: Entry index %zu had a bad type %d",
                  __FUNCTION__, i, entry.type);
 return ERROR;
 }

 uint32_t tag_section = entry.tag >> 16;
 int tag_type = get_camera_metadata_tag_type(entry.tag);
 if (tag_type != (int)entry.type && tag_section < VENDOR_SECTION) {
            ALOGE("%s: Entry index %zu had tag type %d, but the type was %d",
                  __FUNCTION__, i, tag_type, entry.type);
 return ERROR;
 }

 size_t data_size;
 if (validate_and_calculate_camera_metadata_entry_data_size(&data_size, entry.type,
                entry.count) != OK) {
            ALOGE("%s: Entry data size is invalid. type: %u count: %u", __FUNCTION__, entry.type,
                    entry.count);
 return ERROR;
 }

 if (data_size != 0) {
 camera_metadata_data_t *data =
 (camera_metadata_data_t*) (get_data(metadata) +
                                               entry.data.offset);

 if ((uintptr_t)data != ALIGN_TO(data, DATA_ALIGNMENT)) {
                ALOGE("%s: Entry index %zu had bad data alignment (address %p),"
 " expected align %zu, (tag name %s, data size %zu)",
                      __FUNCTION__, i, data, DATA_ALIGNMENT,
                      get_camera_metadata_tag_name(entry.tag) ?: "unknown",
                      data_size);
 return ERROR;
 }

 size_t data_entry_end = entry.data.offset + data_size;
 if (data_entry_end < entry.data.offset || // overflow check
                data_entry_end > metadata->data_capacity) {

                ALOGE("%s: Entry index %zu data ends (%zu) beyond the capacity "
 "%" PRIu32, __FUNCTION__, i, data_entry_end,
                      metadata->data_capacity);
 return ERROR;
 }

 } else if (entry.count == 0) {
 if (entry.data.offset != 0) {
                ALOGE("%s: Entry index %zu had 0 items, but offset was non-0 "
 "(%" PRIu32 "), tag name: %s", __FUNCTION__, i, entry.data.offset,
                        get_camera_metadata_tag_name(entry.tag) ?: "unknown");
 return ERROR;
 }
 } // else data stored inline, so we look at value which can be anything.
 }

 return OK;
}


size_t FBSerializer<V>::serializedSizeList(
  const Vector& vec,
  size_t depth) {
  // List code + stop code
  size_t ret = CODE_SIZE + CODE_SIZE;

  ret += serializedSizeInt64(V::vectorSize(vec));

  for (auto it = V::vectorIterator(vec);
       V::vectorNotEnd(vec, it);
       V::vectorNext(it)) {
    ret += serializedSizeThing(V::vectorValue(it), depth + 1);
  }

  return ret;
}


static enum d_walk_ret detach_and_collect(void *_data, struct dentry *dentry)
{
	struct detach_data *data = _data;

	if (d_mountpoint(dentry)) {
		__dget_dlock(dentry);
		data->mountpoint = dentry;
		return D_WALK_QUIT;
	}

	return select_collect(&data->select, dentry);
}


static void q35_host_initfn(Object *obj)

{

    Q35PCIHost *s = Q35_HOST_DEVICE(obj);

    PCIHostState *phb = PCI_HOST_BRIDGE(obj);

    memory_region_init_io(&phb->conf_mem, obj, &pci_host_conf_le_ops, phb,

                          "pci-conf-idx", 4);

    memory_region_init_io(&phb->data_mem, obj, &pci_host_data_le_ops, phb,

                          "pci-conf-data", 4);

    object_initialize(&s->mch, sizeof(s->mch), TYPE_MCH_PCI_DEVICE);

    object_property_add_child(OBJECT(s), "mch", OBJECT(&s->mch), NULL);

    qdev_prop_set_uint32(DEVICE(&s->mch), "addr", PCI_DEVFN(0, 0));

    qdev_prop_set_bit(DEVICE(&s->mch), "multifunction", false);

    object_property_add(obj, PCI_HOST_PROP_PCI_HOLE_START, "int",

                        q35_host_get_pci_hole_start,

                        NULL, NULL, NULL, NULL);

    object_property_add(obj, PCI_HOST_PROP_PCI_HOLE_END, "int",

                        q35_host_get_pci_hole_end,

                        NULL, NULL, NULL, NULL);

    object_property_add(obj, PCI_HOST_PROP_PCI_HOLE64_START, "int",

                        q35_host_get_pci_hole64_start,

                        NULL, NULL, NULL, NULL);

    object_property_add(obj, PCI_HOST_PROP_PCI_HOLE64_END, "int",

                        q35_host_get_pci_hole64_end,

                        NULL, NULL, NULL, NULL);

    object_property_add(obj, PCIE_HOST_MCFG_SIZE, "int",

                        q35_host_get_mmcfg_size,

                        NULL, NULL, NULL, NULL);

    object_property_add_link(obj, MCH_HOST_PROP_RAM_MEM, TYPE_MEMORY_REGION,

                             (Object **) &s->mch.ram_memory,

                             qdev_prop_allow_set_link_before_realize, 0, NULL);

    object_property_add_link(obj, MCH_HOST_PROP_PCI_MEM, TYPE_MEMORY_REGION,

                             (Object **) &s->mch.pci_address_space,

                             qdev_prop_allow_set_link_before_realize, 0, NULL);

    object_property_add_link(obj, MCH_HOST_PROP_SYSTEM_MEM, TYPE_MEMORY_REGION,

                             (Object **) &s->mch.system_memory,

                             qdev_prop_allow_set_link_before_realize, 0, NULL);

    object_property_add_link(obj, MCH_HOST_PROP_IO_MEM, TYPE_MEMORY_REGION,

                             (Object **) &s->mch.address_space_io,

                             qdev_prop_allow_set_link_before_realize, 0, NULL);

    /* Leave enough space for the biggest MCFG BAR */

    /* TODO: this matches current bios behaviour, but

     * it's not a power of two, which means an MTRR

     * can't cover it exactly.

     */

    s->mch.pci_hole.begin = MCH_HOST_BRIDGE_PCIEXBAR_DEFAULT +

        MCH_HOST_BRIDGE_PCIEXBAR_MAX;

    s->mch.pci_hole.end = IO_APIC_DEFAULT_ADDRESS;

}


static u16 transaction_id_pick ( void ) {
 for ( ;
 ;
 ) {
 const struct request * req = req_head , * started_at ;
 u16 trans_id = trans_id_function ( ) ;
 if ( trans_id == 0xffff ) continue ;
 req = started_at = req_head ;
 if ( req ) {
 do {
 if ( req -> trans_id == trans_id ) break ;
 req = req -> next ;
 }
 while ( req != started_at ) ;
 }
 if ( req == started_at ) return trans_id ;
 }
 }


void decoder_DeleteSubpicture ( decoder_t * p_decoder , subpicture_t * p_subpicture ) {
 p_decoder -> pf_spu_buffer_del ( p_decoder , p_subpicture ) ;
 }


void Pack<WebGLImageConversion::kDataFormatRGBA8,
          WebGLImageConversion::kAlphaDoPremultiply,
          uint8_t,
          uint8_t>(const uint8_t* source,
                   uint8_t* destination,
                   unsigned pixels_per_row) {
  for (unsigned i = 0; i < pixels_per_row; ++i) {
    float scale_factor = source[3] / 255.0f;
    uint8_t source_r =
        static_cast<uint8_t>(static_cast<float>(source[0]) * scale_factor);
    uint8_t source_g =
        static_cast<uint8_t>(static_cast<float>(source[1]) * scale_factor);
    uint8_t source_b =
        static_cast<uint8_t>(static_cast<float>(source[2]) * scale_factor);
    destination[0] = source_r;
    destination[1] = source_g;
    destination[2] = source_b;
    destination[3] = source[3];
    source += 4;
    destination += 4;
  }
}


static void on_custom_search_toggled(GtkToggleButton *btn, gpointer user_data)
{
    const gboolean custom_search = gtk_toggle_button_get_active(btn);
    gtk_widget_set_sensitive(GTK_WIDGET(g_search_entry_bt), custom_search);

    if (custom_search)
        highlight_search(g_search_entry_bt);
}


param_set_pool_mode(const char *val, struct kernel_param *kp)
{
	int *ip = (int *)kp->arg;
	struct svc_pool_map *m = &svc_pool_map;
	int err;

	mutex_lock(&svc_pool_map_mutex);

	err = -EBUSY;
	if (m->count)
		goto out;

	err = 0;
	if (!strncmp(val, "auto", 4))
		*ip = SVC_POOL_AUTO;
	else if (!strncmp(val, "global", 6))
		*ip = SVC_POOL_GLOBAL;
	else if (!strncmp(val, "percpu", 6))
		*ip = SVC_POOL_PERCPU;
	else if (!strncmp(val, "pernode", 7))
		*ip = SVC_POOL_PERNODE;
	else
		err = -EINVAL;

out:
	mutex_unlock(&svc_pool_map_mutex);
	return err;
}


void CLASS canon_rmf_load_raw()
{
  int row, col, bits, orow, ocol, c;

  for (row=0; row < raw_height; row++)
  {
#ifdef LIBRAW_LIBRARY_BUILD
    checkCancel();
#endif
    for (col=0; col < raw_width-2; col+=3) {
      bits = get4();
      FORC3 {
	orow = row;
	if ((ocol = col+c-4) < 0) {
	  ocol += raw_width;
	  if ((orow -= 2) < 0)
	    orow += raw_height;
	}
	RAW(orow,ocol) = bits >> (10*c+2) & 0x3ff;
      }
    }
  }
  maximum = 0x3ff;
}


static void uhci_reset(void *opaque)

{

    UHCIState *s = opaque;

    uint8_t *pci_conf;

    int i;

    UHCIPort *port;

    DPRINTF("uhci: full reset\n");

    pci_conf = s->dev.config;

    pci_conf[0x6a] = 0x01; /* usb clock */

    pci_conf[0x6b] = 0x00;

    s->cmd = 0;

    s->status = 0;

    s->status2 = 0;

    s->intr = 0;

    s->fl_base_addr = 0;

    s->sof_timing = 64;

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

        port = &s->ports[i];

        port->ctrl = 0x0080;

        if (port->port.dev) {

            usb_attach(&port->port, port->port.dev);

        }

    }

    uhci_async_cancel_all(s);

}


void AutocompleteEditModel::OpenMatch(const AutocompleteMatch& match,
                                      WindowOpenDisposition disposition,
                                      const GURL& alternate_nav_url,
                                      size_t index) {
  if (popup_->IsOpen()) {
    AutocompleteLog log(
        autocomplete_controller_->input().text(),
        just_deleted_text_,
        autocomplete_controller_->input().type(),
        popup_->selected_line(),
        -1,  // don't yet know tab ID; set later if appropriate
        ClassifyPage(controller_->GetTabContentsWrapper()->
                     web_contents()->GetURL()),
        base::TimeTicks::Now() - time_user_first_modified_omnibox_,
        0,  // inline autocomplete length; possibly set later
        result());
    DCHECK(user_input_in_progress_) << "We didn't get here through the "
        "expected series of calls.  time_user_first_modified_omnibox_ is "
        "not set correctly and other things may be wrong.";
    if (index != AutocompletePopupModel::kNoMatch)
      log.selected_index = index;
    else if (!has_temporary_text_)
      log.inline_autocompleted_length = inline_autocomplete_text_.length();
    if (disposition == CURRENT_TAB) {
       log.tab_id = controller_->GetTabContentsWrapper()->
           restore_tab_helper()->session_id().id();
     }
     content::NotificationService::current()->Notify(
         chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
         content::Source<Profile>(profile_),
        content::Details<AutocompleteLog>(&log));
  }

  TemplateURL* template_url = match.GetTemplateURL(profile_);
  if (template_url) {
    if (match.transition == content::PAGE_TRANSITION_KEYWORD) {

      if (template_url->IsExtensionKeyword()) {
        AutocompleteMatch current_match;
        GetInfoForCurrentText(&current_match, NULL);

        const AutocompleteMatch& match =
            (index == AutocompletePopupModel::kNoMatch) ?
                current_match : result().match_at(index);

        size_t prefix_length = match.keyword.length() + 1;
        extensions::ExtensionOmniboxEventRouter::OnInputEntered(profile_,
            template_url->GetExtensionId(),
            UTF16ToUTF8(match.fill_into_edit.substr(prefix_length)));
        view_->RevertAll();
        return;
      }

      content::RecordAction(UserMetricsAction("AcceptedKeyword"));
      TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
          template_url);
    } else {
      DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition);
    }

    UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine",
        template_url->prepopulate_id(),
        TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
  }

  if (disposition != NEW_BACKGROUND_TAB) {
    in_revert_ = true;
    view_->RevertAll();  // Revert the box to its unedited state
  }

  if (match.type == AutocompleteMatch::EXTENSION_APP) {
    extensions::LaunchAppFromOmnibox(match, profile_, disposition);
  } else {
    controller_->OnAutocompleteAccept(match.destination_url, disposition,
                                      match.transition, alternate_nav_url);
  }

  if (match.starred)
    bookmark_utils::RecordBookmarkLaunch(bookmark_utils::LAUNCH_OMNIBOX);

  InstantController* instant = controller_->GetInstant();
  if (instant && !popup_->IsOpen())
    instant->DestroyPreviewContents();
  in_revert_ = false;
}


  void HandleCompleteLogin(const base::ListValue* args) {
#if defined(OS_CHROMEOS)
    oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
    oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
        oauth2_delegate_.get(), profile_->GetRequestContext()));
    oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
    const base::DictionaryValue* dict = NULL;
    string16 email;
    string16 password;
    if (!args->GetDictionary(0, &dict) || !dict ||
        !dict->GetString("email", &email) ||
        !dict->GetString("password", &password)) {
      NOTREACHED();
      return;
    }

    new OneClickSigninSyncStarter(
        profile_, NULL, "0" /* session_index 0 for the default user */,
         UTF16ToASCII(email), UTF16ToASCII(password),
         OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
         true /* force_same_tab_navigation */,
        OneClickSigninSyncStarter::NO_CONFIRMATION,
        SyncPromoUI::SOURCE_UNKNOWN);
     web_ui()->CallJavascriptFunction("inline.login.closeDialog");
 #endif
   }


void LayerTreeCoordinator::removeTile(WebLayerID layerID, int tileID)
{
    m_shouldSyncFrame = true;
    m_webPage->send(Messages::LayerTreeCoordinatorProxy::RemoveTileForLayer(layerID, tileID));
}


static bool is_split_required_for_discard(struct dm_target *ti)
{
	return ti->split_discard_bios;
}


static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl)
{
	unsigned short acl_entry = 0;
	while(acl) {
		int key = acl->key_ref;
		int method = acl->method;
		switch(method) {
		case SC_AC_NEVER:
			return 0xFFFF;
		/* Ignore... other items overwrite these */
		case SC_AC_NONE:
		case SC_AC_UNKNOWN:
			break;
		case SC_AC_CHV:
			acl_entry |= (1 << key); /* Assuming key 0 == SO */
			break;
		case SC_AC_AUT:
		case SC_AC_TERM:
		case SC_AC_PRO:
		default:
			/* Ignored */
			break;
		}
		acl = acl->next;
	}
	return acl_entry;
}


toggle_dac_capability(int writable, int enable)
{
	return 0;
}


uint32_t smb1cli_conn_server_session_key(struct smbXcli_conn *conn)
{
	return conn->smb1.server.session_key;
}


static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
{
	struct vcpu_vmx *vmx = to_vmx(vcpu);
	int r;

	if (pi_test_and_set_pir(vector, &vmx->pi_desc))
		return;

	r = pi_test_and_set_on(&vmx->pi_desc);
	kvm_make_request(KVM_REQ_EVENT, vcpu);
#ifdef CONFIG_SMP
	if (!r && (vcpu->mode == IN_GUEST_MODE))
		apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
				POSTED_INTR_VECTOR);
	else
#endif
		kvm_vcpu_kick(vcpu);
}


void ff_h264_filter_mb ( H264Context * h , int mb_x , int mb_y , uint8_t * img_y , uint8_t * img_cb , uint8_t * img_cr , unsigned int linesize , unsigned int uvlinesize ) {
 const int mb_xy = mb_x + mb_y * h -> mb_stride ;
 const int mb_type = h -> cur_pic . mb_type [ mb_xy ] ;
 const int mvy_limit = IS_INTERLACED ( mb_type ) ? 2 : 4 ;
 int first_vertical_edge_done = 0 ;
 av_unused int dir ;
 int chroma = ! ( CONFIG_GRAY && ( h -> flags & CODEC_FLAG_GRAY ) ) ;
 int qp_bd_offset = 6 * ( h -> sps . bit_depth_luma - 8 ) ;
 int a = h -> slice_alpha_c0_offset - qp_bd_offset ;
 int b = h -> slice_beta_offset - qp_bd_offset ;
 if ( FRAME_MBAFF && IS_INTERLACED ( mb_type ^ h -> left_type [ LTOP ] ) && h -> left_type [ LTOP ] ) {
 DECLARE_ALIGNED ( 8 , int16_t , bS ) [ 8 ] ;
 int qp [ 2 ] ;
 int bqp [ 2 ] ;
 int rqp [ 2 ] ;
 int mb_qp , mbn0_qp , mbn1_qp ;
 int i ;
 first_vertical_edge_done = 1 ;
 if ( IS_INTRA ( mb_type ) ) {
 AV_WN64A ( & bS [ 0 ] , 0x0004000400040004ULL ) ;
 AV_WN64A ( & bS [ 4 ] , 0x0004000400040004ULL ) ;
 }
 else {
 static const uint8_t offset [ 2 ] [ 2 ] [ 8 ] = {
 {
 {
 3 + 4 * 0 , 3 + 4 * 0 , 3 + 4 * 0 , 3 + 4 * 0 , 3 + 4 * 1 , 3 + 4 * 1 , 3 + 4 * 1 , 3 + 4 * 1 }
 , {
 3 + 4 * 2 , 3 + 4 * 2 , 3 + 4 * 2 , 3 + 4 * 2 , 3 + 4 * 3 , 3 + 4 * 3 , 3 + 4 * 3 , 3 + 4 * 3 }
 , }
 , {
 {
 3 + 4 * 0 , 3 + 4 * 1 , 3 + 4 * 2 , 3 + 4 * 3 , 3 + 4 * 0 , 3 + 4 * 1 , 3 + 4 * 2 , 3 + 4 * 3 }
 , {
 3 + 4 * 0 , 3 + 4 * 1 , 3 + 4 * 2 , 3 + 4 * 3 , 3 + 4 * 0 , 3 + 4 * 1 , 3 + 4 * 2 , 3 + 4 * 3 }
 , }
 }
 ;
 const uint8_t * off = offset [ MB_FIELD ] [ mb_y & 1 ] ;
 for ( i = 0 ;
 i < 8 ;
 i ++ ) {
 int j = MB_FIELD ? i >> 2 : i & 1 ;
 int mbn_xy = h -> left_mb_xy [ LEFT ( j ) ] ;
 int mbn_type = h -> left_type [ LEFT ( j ) ] ;
 if ( IS_INTRA ( mbn_type ) ) bS [ i ] = 4 ;
 else {
 bS [ i ] = 1 + ! ! ( h -> non_zero_count_cache [ 12 + 8 * ( i >> 1 ) ] | ( ( ! h -> pps . cabac && IS_8x8DCT ( mbn_type ) ) ? ( h -> cbp_table [ mbn_xy ] & ( ( ( MB_FIELD ? ( i & 2 ) : ( mb_y & 1 ) ) ? 8 : 2 ) << 12 ) ) : h -> non_zero_count [ mbn_xy ] [ off [ i ] ] ) ) ;
 }
 }
 }
 mb_qp = h -> cur_pic . qscale_table [ mb_xy ] ;
 mbn0_qp = h -> cur_pic . qscale_table [ h -> left_mb_xy [ 0 ] ] ;
 mbn1_qp = h -> cur_pic . qscale_table [ h -> left_mb_xy [ 1 ] ] ;
 qp [ 0 ] = ( mb_qp + mbn0_qp + 1 ) >> 1 ;
 bqp [ 0 ] = ( get_chroma_qp ( h , 0 , mb_qp ) + get_chroma_qp ( h , 0 , mbn0_qp ) + 1 ) >> 1 ;
 rqp [ 0 ] = ( get_chroma_qp ( h , 1 , mb_qp ) + get_chroma_qp ( h , 1 , mbn0_qp ) + 1 ) >> 1 ;
 qp [ 1 ] = ( mb_qp + mbn1_qp + 1 ) >> 1 ;
 bqp [ 1 ] = ( get_chroma_qp ( h , 0 , mb_qp ) + get_chroma_qp ( h , 0 , mbn1_qp ) + 1 ) >> 1 ;
 rqp [ 1 ] = ( get_chroma_qp ( h , 1 , mb_qp ) + get_chroma_qp ( h , 1 , mbn1_qp ) + 1 ) >> 1 ;
 tprintf ( h -> avctx , "filter mb:%d/%d MBAFF, QPy:%d/%d, QPb:%d/%d QPr:%d/%d ls:%d uvls:%d" , mb_x , mb_y , qp [ 0 ] , qp [ 1 ] , bqp [ 0 ] , bqp [ 1 ] , rqp [ 0 ] , rqp [ 1 ] , linesize , uvlinesize ) ;
 {
 int i ;
 for ( i = 0 ;
 i < 8 ;
 i ++ ) tprintf ( h -> avctx , " bS[%d]:%d" , i , bS [ i ] ) ;
 tprintf ( h -> avctx , "\n" ) ;
 }
 if ( MB_FIELD ) {
 filter_mb_mbaff_edgev ( h , img_y , linesize , bS , 1 , qp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgev ( h , img_y + 8 * linesize , linesize , bS + 4 , 1 , qp [ 1 ] , a , b , 1 ) ;
 if ( chroma ) {
 if ( CHROMA444 ) {
 filter_mb_mbaff_edgev ( h , img_cb , uvlinesize , bS , 1 , bqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgev ( h , img_cb + 8 * uvlinesize , uvlinesize , bS + 4 , 1 , bqp [ 1 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgev ( h , img_cr , uvlinesize , bS , 1 , rqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgev ( h , img_cr + 8 * uvlinesize , uvlinesize , bS + 4 , 1 , rqp [ 1 ] , a , b , 1 ) ;
 }
 else if ( CHROMA422 ) {
 filter_mb_mbaff_edgecv ( h , img_cb , uvlinesize , bS , 1 , bqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cb + 8 * uvlinesize , uvlinesize , bS + 4 , 1 , bqp [ 1 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cr , uvlinesize , bS , 1 , rqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cr + 8 * uvlinesize , uvlinesize , bS + 4 , 1 , rqp [ 1 ] , a , b , 1 ) ;
 }
 else {
 filter_mb_mbaff_edgecv ( h , img_cb , uvlinesize , bS , 1 , bqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cb + 4 * uvlinesize , uvlinesize , bS + 4 , 1 , bqp [ 1 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cr , uvlinesize , bS , 1 , rqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cr + 4 * uvlinesize , uvlinesize , bS + 4 , 1 , rqp [ 1 ] , a , b , 1 ) ;
 }
 }
 }
 else {
 filter_mb_mbaff_edgev ( h , img_y , 2 * linesize , bS , 2 , qp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgev ( h , img_y + linesize , 2 * linesize , bS + 1 , 2 , qp [ 1 ] , a , b , 1 ) ;
 if ( chroma ) {
 if ( CHROMA444 ) {
 filter_mb_mbaff_edgev ( h , img_cb , 2 * uvlinesize , bS , 2 , bqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgev ( h , img_cb + uvlinesize , 2 * uvlinesize , bS + 1 , 2 , bqp [ 1 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgev ( h , img_cr , 2 * uvlinesize , bS , 2 , rqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgev ( h , img_cr + uvlinesize , 2 * uvlinesize , bS + 1 , 2 , rqp [ 1 ] , a , b , 1 ) ;
 }
 else {
 filter_mb_mbaff_edgecv ( h , img_cb , 2 * uvlinesize , bS , 2 , bqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cb + uvlinesize , 2 * uvlinesize , bS + 1 , 2 , bqp [ 1 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cr , 2 * uvlinesize , bS , 2 , rqp [ 0 ] , a , b , 1 ) ;
 filter_mb_mbaff_edgecv ( h , img_cr + uvlinesize , 2 * uvlinesize , bS + 1 , 2 , rqp [ 1 ] , a , b , 1 ) ;
 }
 }
 }
 }
 # if CONFIG_SMALL for ( dir = 0 ;
 dir < 2 ;
 dir ++ ) filter_mb_dir ( h , mb_x , mb_y , img_y , img_cb , img_cr , linesize , uvlinesize , mb_xy , mb_type , mvy_limit , dir ? 0 : first_vertical_edge_done , a , b , chroma , dir ) ;
 # else filter_mb_dir ( h , mb_x , mb_y , img_y , img_cb , img_cr , linesize , uvlinesize , mb_xy , mb_type , mvy_limit , first_vertical_edge_done , a , b , chroma , 0 ) ;
 filter_mb_dir ( h , mb_x , mb_y , img_y , img_cb , img_cr , linesize , uvlinesize , mb_xy , mb_type , mvy_limit , 0 , a , b , chroma , 1 ) ;
 # endif }


WebPlugin* RenderViewImpl::createPluginReplacement(
    WebFrame* frame,
    const WebPluginParams& params) {
  webkit::WebPluginInfo info;
  std::string mime_type;
  GetPluginInfo(params.url, frame->top()->document().url(),
                params.mimeType.utf8(), &info, &mime_type);
  return content::GetContentClient()->renderer()->CreatePluginReplacement(
      this, info.path);
}


static int ffs_ep0_release(struct inode *inode, struct file *file)
{
	struct ffs_data *ffs = file->private_data;

	ENTER();

	ffs_data_closed(ffs);

	return 0;
}


static int ogg_restore ( AVFormatContext * s , int discard ) {
 struct ogg * ogg = s -> priv_data ;
 AVIOContext * bc = s -> pb ;
 struct ogg_state * ost = ogg -> state ;
 int i , err ;
 if ( ! ost ) return 0 ;
 ogg -> state = ost -> next ;
 if ( ! discard ) {
 for ( i = 0 ;
 i < ogg -> nstreams ;
 i ++ ) av_freep ( & ogg -> streams [ i ] . buf ) ;
 avio_seek ( bc , ost -> pos , SEEK_SET ) ;
 ogg -> page_pos = - 1 ;
 ogg -> curidx = ost -> curidx ;
 ogg -> nstreams = ost -> nstreams ;
 if ( ( err = av_reallocp_array ( & ogg -> streams , ogg -> nstreams , sizeof ( * ogg -> streams ) ) ) < 0 ) {
 ogg -> nstreams = 0 ;
 return err ;
 }
 else memcpy ( ogg -> streams , ost -> streams , ost -> nstreams * sizeof ( * ogg -> streams ) ) ;
 }
 av_free ( ost ) ;
 return 0 ;
 }


pqDropServerData(PGconn *conn)
{
	PGnotify   *notify;
	pgParameterStatus *pstatus;

	/* Forget pending notifies */
	notify = conn->notifyHead;
	while (notify != NULL)
	{
		PGnotify   *prev = notify;

		notify = notify->next;
		free(prev);
	}
	conn->notifyHead = conn->notifyTail = NULL;

	pqFreeCommandQueue(conn->cmd_queue_head);
	conn->cmd_queue_head = conn->cmd_queue_tail = NULL;

	pqFreeCommandQueue(conn->cmd_queue_recycle);
	conn->cmd_queue_recycle = NULL;

	/* Reset ParameterStatus data, as well as variables deduced from it */
	pstatus = conn->pstatus;
	while (pstatus != NULL)
	{
		pgParameterStatus *prev = pstatus;

		pstatus = pstatus->next;
		free(prev);
	}
	conn->pstatus = NULL;
	conn->client_encoding = PG_SQL_ASCII;
	conn->std_strings = false;
	conn->default_transaction_read_only = PG_BOOL_UNKNOWN;
	conn->in_hot_standby = PG_BOOL_UNKNOWN;
	conn->sversion = 0;

	/* Drop large-object lookup data */
	if (conn->lobjfuncs)
		free(conn->lobjfuncs);
	conn->lobjfuncs = NULL;

	/* Reset assorted other per-connection state */
	conn->last_sqlstate[0] = '\0';
	conn->auth_req_received = false;
	conn->password_needed = false;
	conn->write_failed = false;
	if (conn->write_err_msg)
		free(conn->write_err_msg);
	conn->write_err_msg = NULL;
	conn->be_pid = 0;
	conn->be_key = 0;
}


static inline void io_dismantle_req(struct io_kiocb *req)
{
	unsigned int flags = req->flags;

	if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
		io_clean_op(req);
	if (!(flags & REQ_F_FIXED_FILE))
		io_put_file(req->file);
}


void LockScreenMediaControlsView::SetArtwork(
    base::Optional<gfx::ImageSkia> img) {
  if (!img.has_value()) {
    session_artwork_->SetImage(nullptr);
     return;
   }

  session_artwork_->SetImageSize(ScaleSizeToFitView(
      img->size(), gfx::Size(kArtworkViewWidth, kArtworkViewHeight)));
   session_artwork_->SetImage(*img);
 }


static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
					    struct kvm_cpuid2 __user *cpuid_arg)
{
	struct kvm_cpuid2 cpuid;
	int r;

	r = -EFAULT;
	if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
		return r;

	r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
	if (r)
		return r;

	r = -EFAULT;
	if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
		return r;

	return 0;
}


static float vorbisfloat2float ( unsigned val ) {
 double mant = val & 0x1fffff ;
 long exp = ( val & 0x7fe00000L ) >> 21 ;
 if ( val & 0x80000000 ) mant = - mant ;
 return ldexp ( mant , exp - 20 - 768 ) ;
 }


static int __tty_fasync(int fd, struct file *filp, int on)
{
	struct tty_struct *tty = file_tty(filp);
	unsigned long flags;
	int retval = 0;

	if (tty_paranoia_check(tty, filp->f_path.dentry->d_inode, "tty_fasync"))
		goto out;

	retval = fasync_helper(fd, filp, on, &tty->fasync);
	if (retval <= 0)
		goto out;

	if (on) {
		enum pid_type type;
		struct pid *pid;
		if (!waitqueue_active(&tty->read_wait))
			tty->minimum_to_wake = 1;
		spin_lock_irqsave(&tty->ctrl_lock, flags);
		if (tty->pgrp) {
			pid = tty->pgrp;
			type = PIDTYPE_PGID;
		} else {
			pid = task_pid(current);
			type = PIDTYPE_PID;
		}
		get_pid(pid);
		spin_unlock_irqrestore(&tty->ctrl_lock, flags);
		retval = __f_setown(filp, pid, type, 0);
		put_pid(pid);
		if (retval)
			goto out;
	} else {
		if (!tty->fasync && !waitqueue_active(&tty->read_wait))
			tty->minimum_to_wake = N_TTY_BUF_SIZE;
	}
	retval = 0;
out:
	return retval;
}


bool ZeroSuggestProvider::StoreSuggestionResponse(
    const std::string& json_data,
    const base::Value& parsed_data) {
  if (!OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() ||
      json_data.empty())
    return false;
  client()->GetPrefs()->SetString(omnibox::kZeroSuggestCachedResults,
                                  json_data);

  const base::ListValue* root_list = NULL;
  const base::ListValue* results_list = NULL;
  if (parsed_data.GetAsList(&root_list) &&
      root_list->GetList(1, &results_list) &&
      results_list->empty())
    return false;

  if (results_from_cache_)
    done_ = true;

  return results_from_cache_;
}


void WebGL2RenderingContextBase::renderbufferStorageMultisample(
    GLenum target,
    GLsizei samples,
    GLenum internalformat,
    GLsizei width,
    GLsizei height) {
  const char* function_name = "renderbufferStorageMultisample";
  if (isContextLost())
    return;
  if (target != GL_RENDERBUFFER) {
    SynthesizeGLError(GL_INVALID_ENUM, function_name, "invalid target");
    return;
  }
  if (!renderbuffer_binding_ || !renderbuffer_binding_->Object()) {
    SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                      "no bound renderbuffer");
    return;
  }
  if (!ValidateSize("renderbufferStorage", width, height))
    return;
  if (samples < 0) {
    SynthesizeGLError(GL_INVALID_VALUE, function_name, "samples < 0");
    return;
  }
  RenderbufferStorageImpl(target, samples, internalformat, width, height,
                          function_name);
  ApplyStencilTest();
}


void sockerror(const char *txt) { /* socket error */
    log_error(LOG_ERR, get_last_socket_error(), txt);
}


uint64_t qcow2_alloc_cluster_offset(BlockDriverState *bs,

                                    uint64_t offset,

                                    int n_start, int n_end,

                                    int *num, QCowL2Meta *m)

{

    BDRVQcowState *s = bs->opaque;

    int l2_index, ret;

    uint64_t l2_offset, *l2_table, cluster_offset;

    int nb_clusters, i = 0;

    QCowL2Meta *old_alloc;

    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);

    if (ret == 0)

        return 0;

    nb_clusters = size_to_clusters(s, n_end << 9);

    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    /* We keep all QCOW_OFLAG_COPIED clusters */

    if (cluster_offset & QCOW_OFLAG_COPIED) {

        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], 0, 0);

        cluster_offset &= ~QCOW_OFLAG_COPIED;

        m->nb_clusters = 0;

        goto out;

    }

    /* for the moment, multiple compressed clusters are not managed */

    if (cluster_offset & QCOW_OFLAG_COMPRESSED)

        nb_clusters = 1;

    /* how many available clusters ? */

    while (i < nb_clusters) {

        i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,

                &l2_table[l2_index], i, 0);

        if(be64_to_cpu(l2_table[l2_index + i]))

            break;

        i += count_contiguous_free_clusters(nb_clusters - i,

                &l2_table[l2_index + i]);

        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);

        if ((cluster_offset & QCOW_OFLAG_COPIED) ||

                (cluster_offset & QCOW_OFLAG_COMPRESSED))

            break;

    }

    nb_clusters = i;

    /*

     * Check if there already is an AIO write request in flight which allocates

     * the same cluster. In this case we need to wait until the previous

     * request has completed and updated the L2 table accordingly.

     */

    QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {

        uint64_t end_offset = offset + nb_clusters * s->cluster_size;

        uint64_t old_offset = old_alloc->offset;

        uint64_t old_end_offset = old_alloc->offset +

            old_alloc->nb_clusters * s->cluster_size;

        if (end_offset < old_offset || offset > old_end_offset) {

            /* No intersection */

        } else {

            if (offset < old_offset) {

                /* Stop at the start of a running allocation */

                nb_clusters = (old_offset - offset) >> s->cluster_bits;

            } else {

                nb_clusters = 0;

            }

            if (nb_clusters == 0) {

                /* Set dependency and wait for a callback */

                m->depends_on = old_alloc;

                m->nb_clusters = 0;

                *num = 0;

                return 0;

            }

        }

    }

    if (!nb_clusters) {

        abort();

    }

    QLIST_INSERT_HEAD(&s->cluster_allocs, m, next_in_flight);

    /* allocate a new cluster */

    cluster_offset = qcow2_alloc_clusters(bs, nb_clusters * s->cluster_size);

    /* save info needed for meta data update */

    m->offset = offset;

    m->n_start = n_start;

    m->nb_clusters = nb_clusters;

out:

    m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);

    *num = m->nb_available - n_start;

    return cluster_offset;

}


void RendererSchedulerImpl::SetHasVisibleRenderWidgetWithTouchHandler(
    bool has_visible_render_widget_with_touch_handler) {
  helper_.CheckOnValidThread();
  if (has_visible_render_widget_with_touch_handler ==
      main_thread_only().has_visible_render_widget_with_touch_handler)
    return;

  main_thread_only().has_visible_render_widget_with_touch_handler =
      has_visible_render_widget_with_touch_handler;

  base::AutoLock lock(any_thread_lock_);
  UpdatePolicyLocked(UpdateType::kForceUpdate);
}


static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
    struct iovec *l2_hdr, *l3_hdr;
    size_t bytes_read;
    size_t full_ip6hdr_len;
    uint16_t l3_proto;

    assert(pkt);

    l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
    l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];

     bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
                             ETH_MAX_L2_HDR_LEN);
    if (bytes_read < sizeof(struct eth_header)) {
        l2_hdr->iov_len = 0;
        return false;
    }

    l2_hdr->iov_len = sizeof(struct eth_header);
    switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) {
    case ETH_P_VLAN:
        l2_hdr->iov_len += sizeof(struct vlan_header);
        break;
    case ETH_P_DVLAN:
        l2_hdr->iov_len += 2 * sizeof(struct vlan_header);
        break;
    }

    if (bytes_read < l2_hdr->iov_len) {
         l2_hdr->iov_len = 0;
         return false;
     }

     l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
        l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
        pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;

        /* copy optional IPv4 header data */
        bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,
                                l2_hdr->iov_len + sizeof(struct ip_header),
                                l3_hdr->iov_base + sizeof(struct ip_header),
                                l3_hdr->iov_len - sizeof(struct ip_header));
        if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {
            l3_hdr->iov_len = 0;
            return false;
        }
        break;

    case ETH_P_IPV6:
        if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
                               &pkt->l4proto, &full_ip6hdr_len)) {
            l3_hdr->iov_len = 0;
            return false;
        }

        l3_hdr->iov_base = g_malloc(full_ip6hdr_len);

        bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
                                l3_hdr->iov_base, full_ip6hdr_len);

        if (bytes_read < full_ip6hdr_len) {
            l3_hdr->iov_len = 0;
            return false;
        } else {
            l3_hdr->iov_len = full_ip6hdr_len;
        }
        break;

    default:
        l3_hdr->iov_len = 0;
        break;
    }


static int get_php_tiff_bytes_per_format(int format) {
  int size = sizeof(php_tiff_bytes_per_format)/sizeof(int);
  if (format >= size) {
    raise_warning("Invalid format %d", format);
    format = 0;
  }
  return php_tiff_bytes_per_format[format];
}


bool bpf_opcode_in_insntable(u8 code)
{
#define BPF_INSN_2_TBL(x, y)    [BPF_##x | BPF_##y] = true
#define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
	static const bool public_insntable[256] = {
		[0 ... 255] = false,
		/* Now overwrite non-defaults ... */
		BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
	};
#undef BPF_INSN_3_TBL
#undef BPF_INSN_2_TBL
	return public_insntable[code];
}


static int dnxhd_decode_dct_block_12(const DNXHDContext *ctx,
                                     RowContext *row, int n)
{
    return dnxhd_decode_dct_block(ctx, row, n, 6, 8, 4, 2);
}


static void hid_keyboard_event(DeviceState *dev, QemuConsole *src,

                               InputEvent *evt)

{

    HIDState *hs = (HIDState *)dev;

    int scancodes[3], i, count;

    int slot;

    count = qemu_input_key_value_to_scancode(evt->key->key,

                                             evt->key->down,

                                             scancodes);

    if (hs->n + count > QUEUE_LENGTH) {

        fprintf(stderr, "usb-kbd: warning: key event queue full\n");

        return;

    }

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

        slot = (hs->head + hs->n) & QUEUE_MASK; hs->n++;

        hs->kbd.keycodes[slot] = scancodes[i];

    }

    hs->event(hs);

}


void GLES2Implementation::BindTextureHelper(GLenum target, GLuint texture) {
  bool changed = false;
  TextureUnit& unit = texture_units_[active_texture_unit_];
  switch (target) {
    case GL_TEXTURE_2D:
      if (unit.bound_texture_2d != texture) {
        unit.bound_texture_2d = texture;
        changed = true;
      }
      break;
    case GL_TEXTURE_CUBE_MAP:
      if (unit.bound_texture_cube_map != texture) {
        unit.bound_texture_cube_map = texture;
        changed = true;
      }
      break;
    case GL_TEXTURE_EXTERNAL_OES:
      if (unit.bound_texture_external_oes != texture) {
        unit.bound_texture_external_oes = texture;
        changed = true;
      }
      break;
    case GL_TEXTURE_RECTANGLE_ARB:
      if (unit.bound_texture_rectangle_arb != texture) {
        unit.bound_texture_rectangle_arb = texture;
        changed = true;
      }
      break;
    default:
      changed = true;
      break;
  }
  if (changed) {
    GetIdHandler(SharedIdNamespaces::kTextures)
        ->MarkAsUsedForBind(this, target, texture,
                            &GLES2Implementation::BindTextureStub);
  }
}


lyd_difflist_add(struct lyd_difflist *diff, unsigned int *size, unsigned int index,
                 LYD_DIFFTYPE type, struct lyd_node *first, struct lyd_node *second)
{
    void *new;
    struct ly_ctx *ctx = (first ? first->schema->module->ctx : second->schema->module->ctx);

    assert(diff);
    assert(size && *size);

    if (index + 1 == *size) {
        /* it's time to enlarge */
        *size = *size + 16;
        new = realloc(diff->type, *size * sizeof *diff->type);
        LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
        diff->type = new;

        new = realloc(diff->first, *size * sizeof *diff->first);
        LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
        diff->first = new;

        new = realloc(diff->second, *size * sizeof *diff->second);
        LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
        diff->second = new;
    }

    /* insert the item */
    diff->type[index] = type;
    diff->first[index] = first;
    diff->second[index] = second;

    /* terminate the arrays */
    index++;
    diff->type[index] = LYD_DIFF_END;
    diff->first[index] = NULL;
    diff->second[index] = NULL;

    return EXIT_SUCCESS;
}


static void doubleArrayAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
{
    INC_STATS("DOM.TestObj.doubleArray._set");
    TestObj* imp = V8TestObj::toNative(info.Holder());
    Vector<double> v = v8NumberArrayToVector<double>(value);
    imp->setDoubleArray(v);
    return;
}


int spapr_h_cas_compose_response(sPAPRMachineState *spapr,
                                 target_ulong addr, target_ulong size,
                                 sPAPROptionVector *ov5_updates)
{
    void *fdt, *fdt_skel;
    sPAPRDeviceTreeUpdateHeader hdr = { .version_id = 1 };
    if (spapr_hotplugged_dev_before_cas()) {
        return 1;
    size -= sizeof(hdr);
    /* Create skeleton */
    fdt_skel = g_malloc0(size);
    _FDT((fdt_create(fdt_skel, size)));
    _FDT((fdt_begin_node(fdt_skel, "")));
    _FDT((fdt_end_node(fdt_skel)));
    _FDT((fdt_finish(fdt_skel)));
    fdt = g_malloc0(size);
    _FDT((fdt_open_into(fdt_skel, fdt, size)));
    g_free(fdt_skel);
    /* Fixup cpu nodes */
    _FDT((spapr_fixup_cpu_dt(fdt, spapr)));
    if (spapr_dt_cas_updates(spapr, fdt, ov5_updates)) {
        return -1;
    /* Pack resulting tree */
    _FDT((fdt_pack(fdt)));
    if (fdt_totalsize(fdt) + sizeof(hdr) > size) {
        trace_spapr_cas_failed(size);
        return -1;
    cpu_physical_memory_write(addr, &hdr, sizeof(hdr));
    cpu_physical_memory_write(addr + sizeof(hdr), fdt, fdt_totalsize(fdt));
    trace_spapr_cas_continue(fdt_totalsize(fdt) + sizeof(hdr));
    g_free(fdt);
    return 0;


void Run() { message_loop_runner_->Run(); }


static int mailimf_plus_parse(const char * message, size_t length,
			      size_t * indx)
{
  return mailimf_unstrict_char_parse(message, length, indx, '+');
}


void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData,
				    int srcWidth, int srcHeight,
				    SplashCoord *mat, GBool glyphMode) {
  SplashBitmap *scaledMask;
  SplashClipResult clipRes, clipRes2;
  SplashPipe pipe;
  int scaledWidth, scaledHeight, t0, t1;
  SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11;
  SplashCoord vx[4], vy[4];
  int xMin, yMin, xMax, yMax;
  ImageSection section[3];
  int nSections;
  int y, xa, xb, x, i, xx, yy;

  vx[0] = mat[4];                    vy[0] = mat[5];
  vx[1] = mat[2] + mat[4];           vy[1] = mat[3] + mat[5];
  vx[2] = mat[0] + mat[2] + mat[4];  vy[2] = mat[1] + mat[3] + mat[5];
  vx[3] = mat[0] + mat[4];           vy[3] = mat[1] + mat[5];

  xMin = imgCoordMungeLowerC(vx[0], glyphMode);
  xMax = imgCoordMungeUpperC(vx[0], glyphMode);
  yMin = imgCoordMungeLowerC(vy[0], glyphMode);
  yMax = imgCoordMungeUpperC(vy[0], glyphMode);
  for (i = 1; i < 4; ++i) {
    t0 = imgCoordMungeLowerC(vx[i], glyphMode);
    if (t0 < xMin) {
      xMin = t0;
    }
    t0 = imgCoordMungeUpperC(vx[i], glyphMode);
    if (t0 > xMax) {
      xMax = t0;
    }
    t1 = imgCoordMungeLowerC(vy[i], glyphMode);
    if (t1 < yMin) {
      yMin = t1;
    }
    t1 = imgCoordMungeUpperC(vy[i], glyphMode);
    if (t1 > yMax) {
      yMax = t1;
    }
  }
  clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1);
  opClipRes = clipRes;
  if (clipRes == splashClipAllOutside) {
    return;
  }

  if (mat[0] >= 0) {
    t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) -
         imgCoordMungeLowerC(mat[4], glyphMode);
  } else {
    t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
         imgCoordMungeLowerC(mat[0] + mat[4], glyphMode);
  }
  if (mat[1] >= 0) {
    t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) -
         imgCoordMungeLowerC(mat[5], glyphMode);
  } else {
    t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
         imgCoordMungeLowerC(mat[1] + mat[5], glyphMode);
  }
  scaledWidth = t0 > t1 ? t0 : t1;
  if (mat[2] >= 0) {
    t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) -
         imgCoordMungeLowerC(mat[4], glyphMode);
  } else {
    t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
         imgCoordMungeLowerC(mat[2] + mat[4], glyphMode);
  }
  if (mat[3] >= 0) {
    t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) -
         imgCoordMungeLowerC(mat[5], glyphMode);
  } else {
    t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
         imgCoordMungeLowerC(mat[3] + mat[5], glyphMode);
  }
  scaledHeight = t0 > t1 ? t0 : t1;
  if (scaledWidth == 0) {
    scaledWidth = 1;
  }
  if (scaledHeight == 0) {
    scaledHeight = 1;
  }

  r00 = mat[0] / scaledWidth;
  r01 = mat[1] / scaledWidth;
  r10 = mat[2] / scaledHeight;
  r11 = mat[3] / scaledHeight;
  det = r00 * r11 - r01 * r10;
  if (splashAbs(det) < 1e-6) {
    return;
  }
  ir00 = r11 / det;
  ir01 = -r01 / det;
  ir10 = -r10 / det;
  ir11 = r00 / det;

   scaledMask = scaleMask(src, srcData, srcWidth, srcHeight,
 			 scaledWidth, scaledHeight);

   i = (vy[2] <= vy[3]) ? 2 : 3;
  }


static inline void e1000e_process_ts_option ( E1000ECore * core , struct e1000_tx_desc * dp ) {
 if ( le32_to_cpu ( dp -> upper . data ) & E1000_TXD_EXTCMD_TSTAMP ) {
 trace_e1000e_wrn_no_ts_support ( ) ;
 }
 }


JSValue jsTestObjMutablePoint(ExecState* exec, JSValue slotBase, const Identifier&)
{
    JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(slotBase));
    UNUSED_PARAM(exec);
    TestObj* impl = static_cast<TestObj*>(castedThis->impl());
    JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(SVGStaticPropertyTearOff<TestObj, FloatPoint>::create(impl, impl->mutablePoint(), &TestObj::updateMutablePoint)));
    return result;
}


fstring_compile_expr(const char *expr_start, const char *expr_end,
                     struct compiling *c, const node *n)

{
    PyCompilerFlags cf;
    node *mod_n;
    mod_ty mod;
    char *str;
    Py_ssize_t len;
    const char *s;

    assert(expr_end >= expr_start);
    assert(*(expr_start-1) == '{');
    assert(*expr_end == '}' || *expr_end == '!' || *expr_end == ':');

    /* If the substring is all whitespace, it's an error.  We need to catch this
       here, and not when we call PyParser_SimpleParseStringFlagsFilename,
       because turning the expression '' in to '()' would go from being invalid
       to valid. */
    for (s = expr_start; s != expr_end; s++) {
        char c = *s;
        /* The Python parser ignores only the following whitespace
           characters (\r already is converted to \n). */
        if (!(c == ' ' || c == '\t' || c == '\n' || c == '\f')) {
            break;
        }
    }
    if (s == expr_end) {
        ast_error(c, n, "f-string: empty expression not allowed");
        return NULL;
    }

    len = expr_end - expr_start;
    /* Allocate 3 extra bytes: open paren, close paren, null byte. */
    str = PyMem_RawMalloc(len + 3);
    if (str == NULL) {
        PyErr_NoMemory();
        return NULL;
    }

    str[0] = '(';
    memcpy(str+1, expr_start, len);
    str[len+1] = ')';
    str[len+2] = 0;

    cf.cf_flags = PyCF_ONLY_AST;
    mod_n = PyParser_SimpleParseStringFlagsFilename(str, "<fstring>",
                                                    Py_eval_input, 0);
    if (!mod_n) {
        PyMem_RawFree(str);
        return NULL;
    }
    /* Reuse str to find the correct column offset. */
    str[0] = '{';
    str[len+1] = '}';
    fstring_fix_node_location(n, mod_n, str);
    mod = PyAST_FromNode(mod_n, &cf, "<fstring>", c->c_arena);
    PyMem_RawFree(str);
    PyNode_Free(mod_n);
    if (!mod)
        return NULL;
    return mod->v.Expression.body;
}


IntRect RenderLayerScrollableArea::visibleContentRect(IncludeScrollbarsInRect scrollbarInclusion) const
{
    int verticalScrollbarWidth = 0;
    int horizontalScrollbarHeight = 0;
    if (scrollbarInclusion == IncludeScrollbars) {
        verticalScrollbarWidth = (verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0;
        horizontalScrollbarHeight = (horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar()) ? horizontalScrollbar()->height() : 0;
    }

    return IntRect(IntPoint(scrollXOffset(), scrollYOffset()),
        IntSize(max(0, layer()->size().width() - verticalScrollbarWidth), max(0, layer()->size().height() - horizontalScrollbarHeight)));
}


int64_t DataReductionProxySettings::GetDataReductionLastUpdateTime() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(data_reduction_proxy_service_->compression_stats());
  return
      data_reduction_proxy_service_->compression_stats()->GetLastUpdateTime();
}


static Bool vvc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
{
	u32 val;
	val = gf_bs_read_int_log(bs, 1, "forbidden_zero");
	if (val) return GF_FALSE;
	val = gf_bs_read_int_log(bs, 1, "resevred0");
	if (val) return GF_FALSE;

	val = gf_bs_read_int_log(bs, 6, "layerID");
	if (layer_id) *layer_id = val;

	val = gf_bs_read_int_log(bs, 5, "nuh_type");
	if (nal_unit_type) *nal_unit_type = val;

	val = gf_bs_read_int_log(bs, 3, "temporalID");
	if (!val) return GF_FALSE;
	val -= 1;
	if (temporal_id) *temporal_id = val;
	return GF_TRUE;
}


struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
					   size_t pg_offset, u64 start, u64 len,
					   int create)
{
	struct extent_map *em;
	struct extent_map *hole_em = NULL;
	u64 range_start = start;
	u64 end;
	u64 found;
	u64 found_end;
	int err = 0;

	em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
	if (IS_ERR(em))
		return em;
	if (em) {
		/*
		 * if our em maps to a hole, there might
		 * actually be delalloc bytes behind it
		 */
		if (em->block_start != EXTENT_MAP_HOLE)
			return em;
		else
			hole_em = em;
	}

	/* check to see if we've wrapped (len == -1 or similar) */
	end = start + len;
	if (end < start)
		end = (u64)-1;
	else
		end -= 1;

	em = NULL;

	/* ok, we didn't find anything, lets look for delalloc */
	found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
				 end, len, EXTENT_DELALLOC, 1);
	found_end = range_start + found;
	if (found_end < range_start)
		found_end = (u64)-1;

	/*
	 * we didn't find anything useful, return
	 * the original results from get_extent()
	 */
	if (range_start > end || found_end <= start) {
		em = hole_em;
		hole_em = NULL;
		goto out;
	}

	/* adjust the range_start to make sure it doesn't
	 * go backwards from the start they passed in
	 */
	range_start = max(start,range_start);
	found = found_end - range_start;

	if (found > 0) {
		u64 hole_start = start;
		u64 hole_len = len;

		em = alloc_extent_map();
		if (!em) {
			err = -ENOMEM;
			goto out;
		}
		/*
		 * when btrfs_get_extent can't find anything it
		 * returns one huge hole
		 *
		 * make sure what it found really fits our range, and
		 * adjust to make sure it is based on the start from
		 * the caller
		 */
		if (hole_em) {
			u64 calc_end = extent_map_end(hole_em);

			if (calc_end <= start || (hole_em->start > end)) {
				free_extent_map(hole_em);
				hole_em = NULL;
			} else {
				hole_start = max(hole_em->start, start);
				hole_len = calc_end - hole_start;
			}
		}
		em->bdev = NULL;
		if (hole_em && range_start > hole_start) {
			/* our hole starts before our delalloc, so we
			 * have to return just the parts of the hole
			 * that go until  the delalloc starts
			 */
			em->len = min(hole_len,
				      range_start - hole_start);
			em->start = hole_start;
			em->orig_start = hole_start;
			/*
			 * don't adjust block start at all,
			 * it is fixed at EXTENT_MAP_HOLE
			 */
			em->block_start = hole_em->block_start;
			em->block_len = hole_len;
		} else {
			em->start = range_start;
			em->len = found;
			em->orig_start = range_start;
			em->block_start = EXTENT_MAP_DELALLOC;
			em->block_len = found;
		}
	} else if (hole_em) {
		return hole_em;
	}
out:

	free_extent_map(hole_em);
	if (err) {
		free_extent_map(em);
		return ERR_PTR(err);
	}
	return em;
}


 void RenderProcessHostImpl::RegisterProcessHostForSite(
    BrowserContext* browser_context,
    RenderProcessHost* process,
    const GURL& url) {
   SiteProcessMap* map =
       GetSiteProcessMapForBrowserContext(browser_context);

  // Only register valid, non-empty sites.  Empty or invalid sites will not
  // use process-per-site mode.  We cannot check whether the process has
  // appropriate bindings here, because the bindings have not yet been granted.
   std::string site = SiteInstance::GetSiteForURL(browser_context, url)
       .possibly_invalid_spec();
  if (!site.empty())
    map->RegisterProcess(site, process);
 }


static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
                                            mz_zip_array *pArray,
                                            size_t min_new_capacity,
                                            mz_uint growing) {
  void *pNew_p;
  size_t new_capacity = min_new_capacity;
  MZ_ASSERT(pArray->m_element_size);
  if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;
  if (growing) {
    new_capacity = MZ_MAX(1, pArray->m_capacity);
    while (new_capacity < min_new_capacity) new_capacity *= 2;
  }
  if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
                                         pArray->m_element_size, new_capacity)))
    return MZ_FALSE;
  pArray->m_p = pNew_p;
  pArray->m_capacity = new_capacity;
  return MZ_TRUE;
}