static void lsr_read_update_value(GF_LASeRCodec *lsr, GF_Node *node, u32 att_tag, u32 fieldType, void *val, u32 node_tag)
{
	u32 is_default, has_escape, escape_val = 0;
	SVG_Number num, *n;

	switch (fieldType) {
	case SVG_Boolean_datatype:
		GF_LSR_READ_INT(lsr, *(SVG_Boolean*)val, 1, "val");
		break;
	case SVG_Paint_datatype:
		lsr_read_paint(lsr, (SVG_Paint*)val, "val");
		break;
	/*
		case SVG_AudioLevel_datatype:
			n = val;
			GF_LSR_READ_INT(lsr, is_default, 1, "isDefaultValue");
			if (is_default) n->type=SVG_NUMBER_INHERIT;
			else {
				n->type = SVG_NUMBER_VALUE;
				n->value = lsr_read_fixed_clamp(lsr, "val");
			}
			break;
	*/
	case SVG_Transform_Scale_datatype:
		((SVG_Point *)val)->x = lsr_read_fixed_16_8(lsr, "scale_x");
		((SVG_Point *)val)->y = lsr_read_fixed_16_8(lsr, "scale_y");
		break;
	case LASeR_Size_datatype:
	case SVG_Transform_Translate_datatype:
		lsr_read_coordinate(lsr, &num, 0, "translation_x");
		((SVG_Point *)val)->x = num.value;
		lsr_read_coordinate(lsr, &num, 0, "translation_y");
		((SVG_Point *)val)->y = num.value;
		break;
	case SVG_Transform_Rotate_datatype:
		GF_LSR_READ_INT(lsr, is_default, 1, "isDefaultValue");
		if (is_default) ((SVG_Point_Angle*)val)->angle = 0;
		else {
			GF_LSR_READ_INT(lsr, has_escape, 1, "escapeFlag");
			if (has_escape) {
				GF_LSR_READ_INT(lsr, escape_val, 2, "escapeEnum");
				((SVG_Point_Angle*)val)->angle = 0;
			}
			else {
				((SVG_Point_Angle*)val)->angle = lsr_read_fixed_16_8(lsr, "rotate");
			}
		}
		break;
	case SVG_Transform_datatype:
		lsr_read_matrix(lsr, val);
		break;
	case SVG_Number_datatype:
	case SVG_FontSize_datatype:
	case SVG_Length_datatype:
		n = (SVG_Number*)val;
		switch (att_tag) {
		/*fractions*/
		case TAG_SVG_ATT_audio_level:
		case TAG_SVG_ATT_fill_opacity:
		case TAG_SVG_ATT_offset:
		case TAG_SVG_ATT_opacity:
		case TAG_SVG_ATT_solid_opacity:
		case TAG_SVG_ATT_stop_opacity:
		case TAG_SVG_ATT_stroke_opacity:
		case TAG_SVG_ATT_viewport_fill_opacity:
			GF_LSR_READ_INT(lsr, is_default, 1, "isDefaultValue");
			if (is_default) n->type=SVG_NUMBER_INHERIT;
			else {
				n->type = SVG_NUMBER_VALUE;
				n->value = lsr_read_fixed_clamp(lsr, "val");
			}
			break;
		case TAG_SVG_ATT_width:
		case TAG_SVG_ATT_height:
			if (node_tag==TAG_SVG_svg) {
				lsr_read_value_with_units(lsr, n, "val");
			} else {
				lsr_read_coordinate(lsr, n, 0, "val");
			}
			break;
		default:
			GF_LSR_READ_INT(lsr, is_default, 1, "isDefaultValue");
			if (is_default) n->type=SVG_NUMBER_INHERIT;
			else {
				GF_LSR_READ_INT(lsr, has_escape, 1, "escapeFlag");
				if (has_escape) {
					GF_LSR_READ_INT(lsr, escape_val, 2, "escapeEnum");
					n->type = SVG_NUMBER_AUTO;//only lineIncrement
				} else {
					n->type = SVG_NUMBER_VALUE;
					n->value = lsr_read_fixed_16_8(lsr, "val");
				}
			}
			break;
		}
		break;
	case SVG_Coordinate_datatype:
		n = (SVG_Number*)val;
		n->type = SVG_NUMBER_VALUE;
		lsr_read_coordinate(lsr, n, 0, "val");
		break;

	case SVG_Rotate_datatype:
		n = (SVG_Number*)val;
		GF_LSR_READ_INT(lsr, is_default, 1, "isDefaultValue");
		if (is_default) n->type=SVG_NUMBER_INHERIT;
		else {
			GF_LSR_READ_INT(lsr, has_escape, 1, "escapeFlag");
			if (has_escape) {
				GF_LSR_READ_INT(lsr, escape_val, 2, "escapeEnum");
				n->type = escape_val ? SVG_NUMBER_AUTO_REVERSE : SVG_NUMBER_AUTO;
			} else {
				n->type = SVG_NUMBER_VALUE;
				n->value = lsr_read_fixed_16_8(lsr, "rotate");
			}
		}
		break;
	case SVG_Coordinates_datatype:
		lsr_read_float_list(lsr, NULL, 0, val, "val");
		break;
	case SVG_ViewBox_datatype:
	{
		u32 count;
		SVG_ViewBox *vb = (SVG_ViewBox *)val;
		GF_LSR_READ_INT(lsr, count, 1, "isDefault");
		if (count) {
			vb->is_set = 0;
		} else {
			vb->is_set = 1;
			GF_LSR_READ_INT(lsr, count, 1, "escapeFlag");
			count = lsr_read_vluimsbf5(lsr, "count");
			if (count) {
				vb->x = lsr_read_fixed_16_8(lsr, "val");
				count--;
			}
			if (count) {
				vb->y = lsr_read_fixed_16_8(lsr, "val");
				count--;
			}
			if (count) {
				vb->width = lsr_read_fixed_16_8(lsr, "val");
				count--;
			}
			if (count) {
				vb->height = lsr_read_fixed_16_8(lsr, "val");
			}
		}
	}
	break;
	case XMLRI_datatype:
	case SVG_Focus_datatype:
		if ((att_tag==TAG_XLINK_ATT_href) || (att_tag==TAG_SVG_ATT_syncReference)) {
			lsr_read_any_uri(lsr, (XMLRI*)val, "val");
		} else {
			Bool is_escape;
			u32 ID;
			escape_val = ID = 0;
			is_escape = 0;
			GF_LSR_READ_INT(lsr, is_default, 1, "isDefault");
			if (!is_default) {
				GF_LSR_READ_INT(lsr, is_escape, 1, "isEscape");
				if (is_escape) {
					GF_LSR_READ_INT(lsr, escape_val, 2, "escapeEnumVal");
				} else {
					ID = lsr_read_vluimsbf5(lsr, "ID");
				}
			}
			if (att_tag==SVG_Focus_datatype) {
				if (is_default) ((SVG_Focus*)val)->type = SVG_FOCUS_AUTO;
				else if (is_escape) ((SVG_Focus*)val)->type = escape_val;
				else {
					((SVG_Focus*)val)->type = SVG_FOCUS_IRI;
					((SVG_Focus*)val)->target.type = XMLRI_ELEMENTID;
					((SVG_Focus*)val)->target.node_id = ID;
				}
			} else {
				if (is_default) ((XMLRI*)val)->type = XMLRI_STRING;
				else {
					((XMLRI *)val)->type = XMLRI_ELEMENTID;
					((XMLRI *)val)->node_id = ID;
				}
			}
		}
		break;

	case DOM_String_datatype:
	case SVG_ContentType_datatype:
	case SVG_LanguageID_datatype:
		lsr_read_byte_align_string(lsr, (char**)val, "val");
		break;
	case SVG_Motion_datatype:
		lsr_read_coordinate(lsr, &num, 0, "pointValueX");
		((GF_Matrix2D*)val)->m[2] = num.value;
		lsr_read_coordinate(lsr, &num, 0, "pointValueY");
		((GF_Matrix2D*)val)->m[5] = num.value;
		break;
	case SVG_Points_datatype:
		lsr_read_point_sequence(lsr, *(GF_List **)val, "val");
		break;
	case SVG_PathData_datatype:
		lsr_read_path_type(lsr, NULL, 0, (SVG_PathData*)val, "val");
		break;
	case SVG_FontFamily_datatype:
	{
		u32 idx;
		SVG_FontFamily *ff = (SVG_FontFamily *)val;
		GF_LSR_READ_INT(lsr, idx, 1, "isDefault");
		ff->type = SVG_FONTFAMILY_INHERIT;
		if (!idx) {
			char *ft;
			GF_LSR_READ_INT(lsr, idx, 1, "escapeFlag");
			idx = lsr_read_vluimsbf5(lsr, "index");
			if (ff->value) gf_free(ff->value);
			ff->value = NULL;
			ft = (char*)gf_list_get(lsr->font_table, idx);
			if (ft) {
				ff->value = gf_strdup(ft);
				ff->type = SVG_FONTFAMILY_VALUE;
			}
		}
	}
		break;
	case LASeR_Choice_datatype:
		GF_LSR_READ_INT(lsr, is_default, 1, "isDefaultValue");
		if (is_default) ((LASeR_Choice *)val)->type = LASeR_CHOICE_ALL;
		else {
			GF_LSR_READ_INT(lsr, has_escape, 1, "escapeFlag");
			if (has_escape) {
				GF_LSR_READ_INT(lsr, escape_val, 2, "escapeEnum");
				((LASeR_Choice *)val)->type = escape_val ? LASeR_CHOICE_NONE : LASeR_CHOICE_ALL;
			} else {
				((LASeR_Choice *)val)->type = LASeR_CHOICE_N;
				((LASeR_Choice *)val)->choice_index = lsr_read_vluimsbf5(lsr, "value");
			}
		}
		break;
	default:
		if ((fieldType>=SVG_FillRule_datatype) && (fieldType<=SVG_LAST_U8_PROPERTY)) {
			/*TODO fixme, check inherit values*/
			GF_LSR_READ_INT(lsr, is_default, 1, "isDefaultValue");
			if (is_default) *(u8 *)val = 0;
			else *(u8 *)val = lsr_read_vluimsbf5(lsr, "val");
		} else {
			GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[LASeR] Warning: update value not supported: fieldType %d - attribute tag %d\n", fieldType, att_tag));
		}
	}
	if (node) {
		//gf_node_dirty_set(node, 0, 0);
		gf_node_changed(node, NULL);
	}
}


static __always_inline unsigned long __mod_tree_val(struct latch_tree_node *n)
{
	struct module_layout *layout = container_of(n, struct module_layout, mtn.node);

	return (unsigned long)layout->base;
}


PHP_FUNCTION(mcrypt_get_iv_size)
 {
 	char *cipher;
 	char *module;
	int   cipher_len, module_len;
 	char *cipher_dir_string;
 	char *module_dir_string;
 	MCRYPT td;

	MCRYPT_GET_INI

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
 		&cipher, &cipher_len, &module, &module_len) == FAILURE) {
 		return;
 	}

 	td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
 	if (td != MCRYPT_FAILED) {
 		RETVAL_LONG(mcrypt_enc_get_iv_size(td));
		mcrypt_module_close(td);
	} else {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
		RETURN_FALSE;
	}
}


static int MagickRealTypeCompare(const void *error_p,const void *error_q)
{
  MagickRealType
    *p,
    *q;

  p=(MagickRealType *) error_p;
  q=(MagickRealType *) error_q;
  if (*p > *q)
    return(1);
  if (fabs((double) (*q-*p)) <= MagickEpsilon)
    return(0);
  return(-1);
}


int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
		unsigned long end, int advice, unsigned long *vm_flags)
{
	struct mm_struct *mm = vma->vm_mm;
	int err;

	switch (advice) {
	case MADV_MERGEABLE:
		/*
		 * Be somewhat over-protective for now!
		 */
		if (*vm_flags & (VM_MERGEABLE | VM_SHARED  | VM_MAYSHARE   |
				 VM_PFNMAP    | VM_IO      | VM_DONTEXPAND |
				 VM_RESERVED  | VM_HUGETLB | VM_INSERTPAGE |
				 VM_NONLINEAR | VM_MIXEDMAP | VM_SAO))
			return 0;		/* just ignore the advice */

		if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
			err = __ksm_enter(mm);
			if (err)
				return err;
		}

		*vm_flags |= VM_MERGEABLE;
		break;

	case MADV_UNMERGEABLE:
		if (!(*vm_flags & VM_MERGEABLE))
			return 0;		/* just ignore the advice */

		if (vma->anon_vma) {
			err = unmerge_ksm_pages(vma, start, end);
			if (err)
				return err;
		}

		*vm_flags &= ~VM_MERGEABLE;
		break;
	}

	return 0;
}


void WebContentsImpl::RunBeforeUnloadConfirm(
    RenderFrameHost* render_frame_host,
    bool is_reload,
    IPC::Message* reply_msg) {
  if (IsFullscreenForCurrentTab())
    ExitFullscreen(true);

  RenderFrameHostImpl* rfhi =
      static_cast<RenderFrameHostImpl*>(render_frame_host);
  if (delegate_)
    delegate_->WillRunBeforeUnloadConfirm();

  base::Callback<void(bool, bool, const base::string16&)> callback =
      base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
                 render_frame_host->GetProcess()->GetID(),
                 render_frame_host->GetRoutingID(), reply_msg);

  bool suppress_this_message = !rfhi->is_active() ||
                               ShowingInterstitialPage() || !delegate_ ||
                               delegate_->ShouldSuppressDialogs(this);
  if (delegate_)
    dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);

  std::vector<protocol::PageHandler*> page_handlers =
      protocol::PageHandler::EnabledForWebContents(this);

  if (suppress_this_message || (!dialog_manager_ && !page_handlers.size())) {
    callback.Run(false, true, base::string16());
    return;
  }

  is_showing_before_unload_dialog_ = true;

  scoped_refptr<CloseDialogCallbackWrapper> wrapper =
      new CloseDialogCallbackWrapper(callback);
  callback = base::Bind(&CloseDialogCallbackWrapper::Run, wrapper);

  GURL frame_url = rfhi->GetLastCommittedURL();
  for (auto* handler : page_handlers) {
    handler->DidRunBeforeUnloadConfirm(frame_url, base::Bind(callback, false));
  }

  if (dialog_manager_) {
    dialog_manager_->RunBeforeUnloadDialog(this, is_reload,
                                           base::Bind(callback, false));
  }
}


KURL HTMLInputElement::src() const
{
    return document()->completeURL(fastGetAttribute(srcAttr));
}


static ulong *reg_write(struct x86_emulate_ctxt *ctxt, unsigned nr)
{
	ctxt->regs_valid |= 1 << nr;
	ctxt->regs_dirty |= 1 << nr;
	return &ctxt->_regs[nr];
}


static pfn_t kvm_pin_pages(struct kvm *kvm, struct kvm_memory_slot *slot,
			   gfn_t gfn, unsigned long size)
{
	gfn_t end_gfn;
	pfn_t pfn;

	pfn     = gfn_to_pfn_memslot(kvm, slot, gfn);
	end_gfn = gfn + (size >> PAGE_SHIFT);
	gfn    += 1;

	if (is_error_pfn(pfn))
		return pfn;

	while (gfn < end_gfn)
		gfn_to_pfn_memslot(kvm, slot, gfn++);

	return pfn;
}


bufIsChanged(buf_T *buf)
{
    return
#ifdef FEAT_QUICKFIX
	    !bt_dontwrite(buf) &&
#endif
	    (buf->b_changed || file_ff_differs(buf, TRUE));
}


static void bfq_update_hw_tag(struct bfq_data *bfqd)
{
	struct bfq_queue *bfqq = bfqd->in_service_queue;

	bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver,
				       bfqd->rq_in_driver);

	if (bfqd->hw_tag == 1)
		return;

	/*
	 * This sample is valid if the number of outstanding requests
	 * is large enough to allow a queueing behavior.  Note that the
	 * sum is not exact, as it's not taking into account deactivated
	 * requests.
	 */
	if (bfqd->rq_in_driver + bfqd->queued <= BFQ_HW_QUEUE_THRESHOLD)
		return;

	/*
	 * If active queue hasn't enough requests and can idle, bfq might not
	 * dispatch sufficient requests to hardware. Don't zero hw_tag in this
	 * case
	 */
	if (bfqq && bfq_bfqq_has_short_ttime(bfqq) &&
	    bfqq->dispatched + bfqq->queued[0] + bfqq->queued[1] <
	    BFQ_HW_QUEUE_THRESHOLD &&
	    bfqd->rq_in_driver < BFQ_HW_QUEUE_THRESHOLD)
		return;

	if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES)
		return;

	bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD;
	bfqd->max_rq_in_driver = 0;
	bfqd->hw_tag_samples = 0;

	bfqd->nonrot_with_queueing =
		blk_queue_nonrot(bfqd->queue) && bfqd->hw_tag;


static int lua_ap_requestbody(lua_State *L)
{
    const char     *filename;
    request_rec    *r;
    apr_off_t      maxSize;

    r = ap_lua_check_request_rec(L, 1);
    filename = luaL_optstring(L, 2, 0);
    maxSize = luaL_optint(L, 3, 0);

    if (r) {
        apr_off_t size;
        if (maxSize > 0 && r->remaining > maxSize) {
            lua_pushnil(L);
            lua_pushliteral(L, "Request body was larger than the permitted size.");
            return 2;
        }
        if (r->method_number != M_POST && r->method_number != M_PUT)
            return (0);
        if (!filename) {
            const char     *data;

            if (lua_read_body(r, &data, &size, maxSize) != OK)
                return (0);

            lua_pushlstring(L, data, (size_t) size);
            lua_pushinteger(L, (lua_Integer) size);
            return (2);
        } else {
            apr_status_t rc;
            apr_file_t     *file;

            rc = apr_file_open(&file, filename, APR_CREATE | APR_FOPEN_WRITE,
                               APR_FPROT_OS_DEFAULT, r->pool);
            lua_settop(L, 0);
            if (rc == APR_SUCCESS) {
                rc = lua_write_body(r, file, &size);
                apr_file_close(file);
                if (rc != OK) {
                    lua_pushboolean(L, 0);
                    return 1;
                }
                lua_pushinteger(L, (lua_Integer) size);
                return (1);
            } else
                lua_pushboolean(L, 0);
            return (1);
        }
    }

    return (0);
}


void malloc_write_init(malloc_write *mw) {
  mw->s = nullptr;
  mw->slen = 0;
  mw->smax = 0;
  mw->oom = false;
}


static PyObject *__pyx_pw_17clickhouse_driver_7columns_12stringcolumn_10ByteString_3read_items(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  CYTHON_UNUSED PyObject *__pyx_v_self = 0;
  PyObject *__pyx_v_n_items = 0;
  PyObject *__pyx_v_buf = 0;
  int __pyx_lineno = 0;
  const char *__pyx_filename = NULL;
  int __pyx_clineno = 0;
  PyObject *__pyx_r = 0;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("read_items (wrapper)", 0);
  {
    static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_self,&__pyx_n_s_n_items,&__pyx_n_s_buf,0};
    PyObject* values[3] = {0,0,0};
    if (unlikely(__pyx_kwds)) {
      Py_ssize_t kw_args;
      const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
      switch (pos_args) {
        case  3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
        CYTHON_FALLTHROUGH;
        case  2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
        CYTHON_FALLTHROUGH;
        case  1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
        CYTHON_FALLTHROUGH;
        case  0: break;
        default: goto __pyx_L5_argtuple_error;
      }
      kw_args = PyDict_Size(__pyx_kwds);
      switch (pos_args) {
        case  0:
        if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_self)) != 0)) kw_args--;
        else goto __pyx_L5_argtuple_error;
        CYTHON_FALLTHROUGH;
        case  1:
        if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_n_items)) != 0)) kw_args--;
        else {
          __Pyx_RaiseArgtupleInvalid("read_items", 1, 3, 3, 1); __PYX_ERR(0, 40, __pyx_L3_error)
        }
        CYTHON_FALLTHROUGH;
        case  2:
        if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_buf)) != 0)) kw_args--;
        else {
          __Pyx_RaiseArgtupleInvalid("read_items", 1, 3, 3, 2); __PYX_ERR(0, 40, __pyx_L3_error)
        }
      }
      if (unlikely(kw_args > 0)) {
        if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "read_items") < 0)) __PYX_ERR(0, 40, __pyx_L3_error)
      }
    } else if (PyTuple_GET_SIZE(__pyx_args) != 3) {
      goto __pyx_L5_argtuple_error;
    } else {
      values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
      values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
      values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
    }
    __pyx_v_self = values[0];
    __pyx_v_n_items = values[1];
    __pyx_v_buf = values[2];
  }
  goto __pyx_L4_argument_unpacking_done;
  __pyx_L5_argtuple_error:;
  __Pyx_RaiseArgtupleInvalid("read_items", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 40, __pyx_L3_error)
  __pyx_L3_error:;
  __Pyx_AddTraceback("clickhouse_driver.columns.stringcolumn.ByteString.read_items", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __Pyx_RefNannyFinishContext();
  return NULL;
  __pyx_L4_argument_unpacking_done:;
  __pyx_r = __pyx_pf_17clickhouse_driver_7columns_12stringcolumn_10ByteString_2read_items(__pyx_self, __pyx_v_self, __pyx_v_n_items, __pyx_v_buf);

  /* function exit code */
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}


void __put_task_struct(struct task_struct *tsk)
{
	WARN_ON(!tsk->exit_state);
	WARN_ON(atomic_read(&tsk->usage));
	WARN_ON(tsk == current);

	security_task_free(tsk);
	free_uid(tsk->user);
	put_group_info(tsk->group_info);
	delayacct_tsk_free(tsk);

	if (!profile_handoff_task(tsk))
		free_task(tsk);
}


EXPORTED char *mboxlist_find_uniqueid(const char *uniqueid, const char *userid)
{
    struct _find_uniqueid_data rock = { uniqueid, NULL };
    mboxlist_usermboxtree(userid, _find_uniqueid, &rock, MBOXTREE_PLUS_RACL);
    return rock.mboxname;
}


static int qemuMonitorTextParseBlockJobOne ( const char * text , const char * device , virDomainBlockJobInfoPtr info , const char * * next ) {
 virDomainBlockJobInfo tmp ;
 char * p ;
 unsigned long long speed_bytes ;
 int mismatch = 0 ;
 if ( next == NULL ) return - 1 ;
 * next = NULL ;
 if ( ( text = STRSKIP ( text , "Streaming device " ) ) == NULL ) return - EINVAL ;
 if ( ! STREQLEN ( text , device , strlen ( device ) ) ) mismatch = 1 ;
 if ( ( text = strstr ( text , ": Completed " ) ) == NULL ) return - EINVAL ;
 text += 11 ;
 if ( virStrToLong_ull ( text , & p , 10 , & tmp . cur ) ) return - EINVAL ;
 text = p ;
 if ( ! STRPREFIX ( text , " of " ) ) return - EINVAL ;
 text += 4 ;
 if ( virStrToLong_ull ( text , & p , 10 , & tmp . end ) ) return - EINVAL ;
 text = p ;
 if ( ! STRPREFIX ( text , " bytes, speed limit " ) ) return - EINVAL ;
 text += 20 ;
 if ( virStrToLong_ull ( text , & p , 10 , & speed_bytes ) ) return - EINVAL ;
 text = p ;
 if ( ! STRPREFIX ( text , " bytes/s" ) ) return - EINVAL ;
 if ( mismatch ) {
 * next = STRSKIP ( text , "\n" ) ;
 return - EAGAIN ;
 }
 if ( info ) {
 info -> cur = tmp . cur ;
 info -> end = tmp . end ;
 info -> bandwidth = speed_bytes / 1024ULL / 1024ULL ;
 info -> type = VIR_DOMAIN_BLOCK_JOB_TYPE_PULL ;
 }
 return 1 ;
 }


void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings)
{
  settings->ignore_adler32 = 0;

  settings->custom_zlib = 0;
  settings->custom_inflate = 0;
  settings->custom_context = 0;
}


nameToID(struct rx_call *call, namelist *aname, idlist *aid)
{
    afs_int32 code;
    struct ubik_trans *tt;
    afs_int32 i;
    int size;
    int count = 0;

    /* Initialize return struct */
    aid->idlist_len = 0;
    aid->idlist_val = NULL;

    size = aname->namelist_len;
    if (size == 0)
	return 0;
    if (size < 0)
	return PRTOOMANY;

    aid->idlist_val = (afs_int32 *) malloc(size * sizeof(afs_int32));
    if (!aid->idlist_val)
	return PRNOMEM;

    code = Initdb();
    if (code != PRSUCCESS)
	return code;
    code = ubik_BeginTransReadAny(dbase, UBIK_READTRANS, &tt);
    if (code)
	return code;
    code = ubik_SetLock(tt, 1, 1, LOCKREAD);
    if (code)
	ABORT_WITH(tt, code);
    code = read_DbHeader(tt);
    if (code)
	ABORT_WITH(tt, code);

    for (i = 0; i < aname->namelist_len; i++) {
	char vname[256];
	char *nameinst, *cell;

	strncpy(vname, aname->namelist_val[i], sizeof(vname));
	vname[sizeof(vname)-1] ='\0';

	nameinst = vname;
	cell = strchr(vname, '@');
	if (cell) {
	    *cell = '\0';
	    cell++;
	}

	if (cell && afs_is_foreign_ticket_name(nameinst,NULL,cell,pr_realmName))
	    code = NameToID(tt, aname->namelist_val[i], &aid->idlist_val[i]);
	else
	    code = NameToID(tt, nameinst, &aid->idlist_val[i]);

	if (code != PRSUCCESS)
	    aid->idlist_val[i] = ANONYMOUSID;
        osi_audit(PTS_NmToIdEvent, code, AUD_STR,
		   aname->namelist_val[i], AUD_ID, aid->idlist_val[i],
		   AUD_END);
	ViceLog(125, ("PTS_NameToID: code %d aname %s aid %d\n", code,
		      aname->namelist_val[i], aid->idlist_val[i]));
	if (count++ > 50) {
#ifndef AFS_PTHREAD_ENV
	    IOMGR_Poll();
#endif
	    count = 0;
	}
    }
    aid->idlist_len = aname->namelist_len;

    code = ubik_EndTrans(tt);
    if (code)
	return code;
    return PRSUCCESS;
}


void ApiTestEnvironment::RegisterModules() {
  v8_schema_registry_.reset(new V8SchemaRegistry);
  const std::vector<std::pair<std::string, int> > resources =
      Dispatcher::GetJsResources();
  for (std::vector<std::pair<std::string, int> >::const_iterator resource =
           resources.begin();
       resource != resources.end();
       ++resource) {
    if (resource->first != "test_environment_specific_bindings")
      env()->RegisterModule(resource->first, resource->second);
  }
  Dispatcher::RegisterNativeHandlers(env()->module_system(),
                                     env()->context(),
                                     NULL,
                                     NULL,
                                     v8_schema_registry_.get());
  env()->module_system()->RegisterNativeHandler(
      "process",
      scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
          env()->context(),
          env()->context()->GetExtensionID(),
          env()->context()->GetContextTypeDescription(),
          false,
          false,
          2,
          false)));
  env()->RegisterTestFile("test_environment_specific_bindings",
                           "unit_test_environment_specific_bindings.js");

   env()->OverrideNativeHandler("activityLogger",
                               "exports.$set('LogAPICall', function() {});");
   env()->OverrideNativeHandler(
       "apiDefinitions",
      "exports.$set('GetExtensionAPIDefinitionsForTest',"
                    "function() { return [] });");
   env()->OverrideNativeHandler(
       "event_natives",
      "exports.$set('AttachEvent', function() {});"
      "exports.$set('DetachEvent', function() {});"
      "exports.$set('AttachFilteredEvent', function() {});"
      "exports.$set('AttachFilteredEvent', function() {});"
      "exports.$set('MatchAgainstEventFilter', function() { return [] });");

   gin::ModuleRegistry::From(env()->context()->v8_context())
       ->AddBuiltinModule(env()->isolate(),
                         mojo::js::Core::kModuleName,
                         mojo::js::Core::GetModule(env()->isolate()));
  gin::ModuleRegistry::From(env()->context()->v8_context())
      ->AddBuiltinModule(env()->isolate(),
                         mojo::js::Support::kModuleName,
                         mojo::js::Support::GetModule(env()->isolate()));
  gin::Handle<TestServiceProvider> service_provider =
      TestServiceProvider::Create(env()->isolate());
  service_provider_ = service_provider.get();
  gin::ModuleRegistry::From(env()->context()->v8_context())
      ->AddBuiltinModule(env()->isolate(),
                         "content/public/renderer/service_provider",
                         service_provider.ToV8());
}


  void OnDone(const net::URLRequestStatus& status,
              int response_code,
              const std::string& response) {
    ASSERT_EQ(MessageLoop::current(), &message_loop_);
    status_ = status;
    response_code_ = response_code;
    response_ = response;
    message_loop_.PostTask(FROM_HERE, MessageLoop::QuitClosure());
  }


spnego_gss_inquire_sec_context_by_oid(
		OM_uint32 *minor_status,
		const gss_ctx_id_t context_handle,
		const gss_OID desired_object,
		gss_buffer_set_t *data_set)
{
	OM_uint32 ret;
	ret = gss_inquire_sec_context_by_oid(minor_status,
			    context_handle,
			    desired_object,
			    data_set);
	return (ret);
}


char* Jsi_ValueNormalPath(Jsi_Interp *interp, Jsi_Value *file, Jsi_DString *dStr) {
    return Jsi_NormalPath(interp, Jsi_ValueString(interp, file, NULL), dStr);
}


static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
                                size_t *num_formats)
{
    /*
     * If we have a custom point format list use it otherwise use default
     */
    if (s->tlsext_ecpointformatlist) {
        *pformats = s->tlsext_ecpointformatlist;
        *num_formats = s->tlsext_ecpointformatlist_length;
    } else {
        *pformats = ecformats_default;
        /* For Suite B we don't support char2 fields */
        if (tls1_suiteb(s))
            *num_formats = sizeof(ecformats_default) - 1;
        else
            *num_formats = sizeof(ecformats_default);
    }
}


static void ByteStringAttributeAttributeSetter(
    v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Isolate* isolate = info.GetIsolate();
  ALLOW_UNUSED_LOCAL(isolate);

  v8::Local<v8::Object> holder = info.Holder();
  ALLOW_UNUSED_LOCAL(holder);

  TestObject* impl = V8TestObject::ToImpl(holder);

  ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "byteStringAttribute");

  V8StringResource<> cpp_value = NativeValueTraits<IDLByteString>::NativeValue(info.GetIsolate(), v8_value, exception_state);
  if (exception_state.HadException())
    return;

  impl->setByteStringAttribute(cpp_value);
}


bool mounted() const { return drivefs_has_mounted_ && !mount_path_.empty(); }


static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
{
	struct block_device *bdev;
	char b[BDEVNAME_SIZE];

	bdev = open_by_devnum(dev, FMODE_READ|FMODE_WRITE);
	if (IS_ERR(bdev))
		goto fail;
	return bdev;

fail:
	ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
			__bdevname(dev, b), PTR_ERR(bdev));
	return NULL;
}


static void __show_regs(const struct pt_regs *regs)
{
	const int field = 2 * sizeof(unsigned long);
	unsigned int cause = regs->cp0_cause;
	int i;

	printk("Cpu %d\n", smp_processor_id());

	/*
	 * Saved main processor registers
	 */
	for (i = 0; i < 32; ) {
		if ((i % 4) == 0)
			printk("$%2d   :", i);
		if (i == 0)
			printk(" %0*lx", field, 0UL);
		else if (i == 26 || i == 27)
			printk(" %*s", field, "");
		else
			printk(" %0*lx", field, regs->regs[i]);

		i++;
		if ((i % 4) == 0)
			printk("\n");
	}

#ifdef CONFIG_CPU_HAS_SMARTMIPS
	printk("Acx    : %0*lx\n", field, regs->acx);
#endif
	printk("Hi    : %0*lx\n", field, regs->hi);
	printk("Lo    : %0*lx\n", field, regs->lo);

	/*
	 * Saved cp0 registers
	 */
	printk("epc   : %0*lx %pS\n", field, regs->cp0_epc,
	       (void *) regs->cp0_epc);
	printk("    %s\n", print_tainted());
	printk("ra    : %0*lx %pS\n", field, regs->regs[31],
	       (void *) regs->regs[31]);

	printk("Status: %08x    ", (uint32_t) regs->cp0_status);

	if (current_cpu_data.isa_level == MIPS_CPU_ISA_I) {
		if (regs->cp0_status & ST0_KUO)
			printk("KUo ");
		if (regs->cp0_status & ST0_IEO)
			printk("IEo ");
		if (regs->cp0_status & ST0_KUP)
			printk("KUp ");
		if (regs->cp0_status & ST0_IEP)
			printk("IEp ");
		if (regs->cp0_status & ST0_KUC)
			printk("KUc ");
		if (regs->cp0_status & ST0_IEC)
			printk("IEc ");
	} else {
		if (regs->cp0_status & ST0_KX)
			printk("KX ");
		if (regs->cp0_status & ST0_SX)
			printk("SX ");
		if (regs->cp0_status & ST0_UX)
			printk("UX ");
		switch (regs->cp0_status & ST0_KSU) {
		case KSU_USER:
			printk("USER ");
			break;
		case KSU_SUPERVISOR:
			printk("SUPERVISOR ");
			break;
		case KSU_KERNEL:
			printk("KERNEL ");
			break;
		default:
			printk("BAD_MODE ");
			break;
		}
		if (regs->cp0_status & ST0_ERL)
			printk("ERL ");
		if (regs->cp0_status & ST0_EXL)
			printk("EXL ");
		if (regs->cp0_status & ST0_IE)
			printk("IE ");
	}
	printk("\n");

	printk("Cause : %08x\n", cause);

	cause = (cause & CAUSEF_EXCCODE) >> CAUSEB_EXCCODE;
	if (1 <= cause && cause <= 5)
		printk("BadVA : %0*lx\n", field, regs->cp0_badvaddr);

	printk("PrId  : %08x (%s)\n", read_c0_prid(),
	       cpu_name_string());
}


mrb_init_gc(mrb_state *mrb)
{
  struct RClass *gc;

  mrb_static_assert(sizeof(RVALUE) <= sizeof(void*) * 6,
                    "RVALUE size must be within 6 words");

  gc = mrb_define_module(mrb, "GC");

  mrb_define_class_method(mrb, gc, "start", gc_start, MRB_ARGS_NONE());
  mrb_define_class_method(mrb, gc, "enable", gc_enable, MRB_ARGS_NONE());
  mrb_define_class_method(mrb, gc, "disable", gc_disable, MRB_ARGS_NONE());
  mrb_define_class_method(mrb, gc, "interval_ratio", gc_interval_ratio_get, MRB_ARGS_NONE());
  mrb_define_class_method(mrb, gc, "interval_ratio=", gc_interval_ratio_set, MRB_ARGS_REQ(1));
  mrb_define_class_method(mrb, gc, "step_ratio", gc_step_ratio_get, MRB_ARGS_NONE());
  mrb_define_class_method(mrb, gc, "step_ratio=", gc_step_ratio_set, MRB_ARGS_REQ(1));
  mrb_define_class_method(mrb, gc, "generational_mode=", gc_generational_mode_set, MRB_ARGS_REQ(1));
  mrb_define_class_method(mrb, gc, "generational_mode", gc_generational_mode_get, MRB_ARGS_NONE());
#ifdef GC_TEST
#ifdef GC_DEBUG
  mrb_define_class_method(mrb, gc, "test", gc_test, MRB_ARGS_NONE());
#endif
#endif
}


  bool HasPermissionsForContentUri(const base::FilePath& file,
                                   int permissions) {
    DCHECK(!file.empty());
    DCHECK(file.IsContentUri());
    if (!permissions)
      return false;
    base::FilePath file_path = file.StripTrailingSeparators();
    FileMap::const_iterator it = file_permissions_.find(file_path);
    if (it != file_permissions_.end())
      return (it->second & permissions) == permissions;
    return false;
  }


void HTMLElement::setOuterHTML(const String& html, ExceptionCode& ec)
{
    Node* p = parentNode();
    if (!p || !p->isHTMLElement()) {
        ec = NO_MODIFICATION_ALLOWED_ERR;
        return;
    }
    RefPtr<HTMLElement> parent = toHTMLElement(p);
     RefPtr<Node> prev = previousSibling();
     RefPtr<Node> next = nextSibling();

    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), ec);
     if (ec)
         return;

    parent->replaceChild(fragment.release(), this, ec);
    RefPtr<Node> node = next ? next->previousSibling() : 0;
    if (!ec && node && node->isTextNode())
        mergeWithNextTextNode(node.release(), ec);

    if (!ec && prev && prev->isTextNode())
        mergeWithNextTextNode(prev.release(), ec);
}


R_API RIOMap *r_io_bank_get_map_at(RIO *io, const ut32 bankid, ut64 addr) {
	RIOBank *bank = r_io_bank_get (io, bankid);
	r_return_val_if_fail (io && bank, NULL);
	RRBNode *node = r_crbtree_find_node (bank->submaps, &addr, _find_sm_by_vaddr_cb, NULL);
	if (!node) {
		return NULL;
	}
	RIOSubMap *sm = (RIOSubMap *)node->data;
	if (!r_io_submap_contain (sm, addr)) {
		return NULL;
	}
	return r_io_map_get_by_ref (io, &sm->mapref);
}


static kbd_layout_t *parse_keyboard_layout(const name2keysym_t *table,

					   const char *language,

					   kbd_layout_t * k)

{

    FILE *f;

    char * filename;

    char line[1024];

    int len;

    filename = qemu_find_file(QEMU_FILE_TYPE_KEYMAP, language);

    if (!k)

	k = g_malloc0(sizeof(kbd_layout_t));

    if (!(filename && (f = fopen(filename, "r")))) {

	fprintf(stderr,

		"Could not read keymap file: '%s'\n", language);

	return NULL;

    }

    g_free(filename);

    for(;;) {

	if (fgets(line, 1024, f) == NULL)

            break;

        len = strlen(line);

        if (len > 0 && line[len - 1] == '\n')

            line[len - 1] = '\0';

        if (line[0] == '#')

	    continue;

	if (!strncmp(line, "map ", 4))

	    continue;

	if (!strncmp(line, "include ", 8)) {

	    parse_keyboard_layout(table, line + 8, k);

        } else {

	    char *end_of_keysym = line;

	    while (*end_of_keysym != 0 && *end_of_keysym != ' ')

		end_of_keysym++;

	    if (*end_of_keysym) {

		int keysym;

		*end_of_keysym = 0;

		keysym = get_keysym(table, line);

		if (keysym == 0) {

                    //		    fprintf(stderr, "Warning: unknown keysym %s\n", line);

		} else {

		    const char *rest = end_of_keysym + 1;

		    char *rest2;

		    int keycode = strtol(rest, &rest2, 0);

		    if (rest && strstr(rest, "numlock")) {

			add_to_key_range(&k->keypad_range, keycode);

			add_to_key_range(&k->numlock_range, keysym);

			//fprintf(stderr, "keypad keysym %04x keycode %d\n", keysym, keycode);

		    }

		    if (rest && strstr(rest, "shift"))

			keycode |= SCANCODE_SHIFT;

		    if (rest && strstr(rest, "altgr"))

			keycode |= SCANCODE_ALTGR;

		    if (rest && strstr(rest, "ctrl"))

			keycode |= SCANCODE_CTRL;

		    add_keysym(line, keysym, keycode, k);

		    if (rest && strstr(rest, "addupper")) {

			char *c;

			for (c = line; *c; c++)

			    *c = qemu_toupper(*c);

			keysym = get_keysym(table, line);

			if (keysym)

			    add_keysym(line, keysym, keycode | SCANCODE_SHIFT, k);

		    }

		}

	    }

	}

    }

    fclose(f);

    return k;

}


TEST_P(DownstreamProtocolIntegrationTest, HeadersOnlyFilterDecodingIntermediateFilters) {
  config_helper_.addFilter(R"EOF(
name: passthrough-filter
)EOF");
  config_helper_.addFilter(R"EOF(
name: decode-headers-only
)EOF");
  config_helper_.addFilter(R"EOF(
name: passthrough-filter
)EOF");
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));
  auto response =
      codec_client_->makeRequestWithBody(Http::TestHeaderMapImpl{{":method", "POST"},
                                                                 {":path", "/test/long/url"},
                                                                 {":scheme", "http"},
                                                                 {":authority", "host"}},
                                         128);
  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "503"}}, false);
  upstream_request_->encodeData(128, true);
  response->waitForEndStream();

  EXPECT_TRUE(response->complete());
  EXPECT_EQ("503", response->headers().Status()->value().getStringView());
  EXPECT_EQ(128, response->body().size());
}


void WebGLRenderingContextBase::MarkCompositedAndClearBackbufferIfNeeded() {
  MarkLayerComposited();
  ClearIfComposited();
}


static void tsc210x_reset(TSC210xState *s)
{
    s->state = 0;
    s->pin_func = 2;
    s->enabled = 0;
    s->busy = 0;
    s->nextfunction = 0;
    s->ref = 0;
    s->timing = 0;
    s->irq = 0;
    s->dav = 0;

    s->audio_ctrl1 = 0x0000;
    s->audio_ctrl2 = 0x4410;
    s->audio_ctrl3 = 0x0000;
    s->pll[0] = 0x1004;
    s->pll[1] = 0x0000;
    s->pll[2] = 0x1fff;
    s->volume = 0xffff;
    s->dac_power = 0x8540;
    s->softstep = 1;
    s->volume_change = 0;
    s->powerdown = 0;
    s->filter_data[0x00] = 0x6be3;
    s->filter_data[0x01] = 0x9666;
    s->filter_data[0x02] = 0x675d;
    s->filter_data[0x03] = 0x6be3;
    s->filter_data[0x04] = 0x9666;
    s->filter_data[0x05] = 0x675d;
    s->filter_data[0x06] = 0x7d83;
    s->filter_data[0x07] = 0x84ee;
    s->filter_data[0x08] = 0x7d83;
    s->filter_data[0x09] = 0x84ee;
    s->filter_data[0x0a] = 0x6be3;
    s->filter_data[0x0b] = 0x9666;
    s->filter_data[0x0c] = 0x675d;
    s->filter_data[0x0d] = 0x6be3;
    s->filter_data[0x0e] = 0x9666;
    s->filter_data[0x0f] = 0x675d;
    s->filter_data[0x10] = 0x7d83;
    s->filter_data[0x11] = 0x84ee;
    s->filter_data[0x12] = 0x7d83;
    s->filter_data[0x13] = 0x84ee;

    s->i2s_tx_rate = 0;
    s->i2s_rx_rate = 0;

    s->kb.scan = 1;
    s->kb.debounce = 0;
    s->kb.mask = 0x0000;
    s->kb.mode = 3;
    s->kb.intr = 0;

    qemu_set_irq(s->pint, !s->irq);
    qemu_set_irq(s->davint, !s->dav);
    qemu_irq_raise(s->kbint);
}


static Datum ExecEvalAnd ( BoolExprState * andExpr , ExprContext * econtext , bool * isNull , ExprDoneCond * isDone ) {
 List * clauses = andExpr -> args ;
 ListCell * clause ;
 bool AnyNull ;
 if ( isDone ) * isDone = ExprSingleResult ;
 AnyNull = false ;
 foreach ( clause , clauses ) {
 ExprState * clausestate = ( ExprState * ) lfirst ( clause ) ;
 Datum clause_value ;
 clause_value = ExecEvalExpr ( clausestate , econtext , isNull , NULL ) ;
 if ( * isNull ) AnyNull = true ;
 else if ( ! DatumGetBool ( clause_value ) ) return clause_value ;
 }
 * isNull = AnyNull ;
 return BoolGetDatum ( ! AnyNull ) ;
 }


static GF_Err gf_isom_dump_svg_track(GF_ISOFile *the_file, u32 track, FILE *dump)
{
	char nhmlFileName[1024];
	FILE *nhmlFile;
	u32 i, count, di, ts, cur_frame;
	u64 start, end;
	GF_BitStream *bs;

	GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, track);
	if (!trak) return GF_BAD_PARAM;
	switch (trak->Media->handler->handlerType) {
	case GF_ISOM_MEDIA_TEXT:
	case GF_ISOM_MEDIA_SUBT:
		break;
	default:
		return GF_BAD_PARAM;
	}

	strcpy(nhmlFileName, the_file->fileName);
	strcat(nhmlFileName, ".nhml");
	nhmlFile = gf_fopen(nhmlFileName, "wt");
	fprintf(nhmlFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
	fprintf(nhmlFile, "<NHNTStream streamType=\"3\" objectTypeIndication=\"10\" timeScale=\"%d\" baseMediaFile=\"file.svg\" inRootOD=\"yes\">\n", trak->Media->mediaHeader->timeScale);
	fprintf(nhmlFile, "<NHNTSample isRAP=\"yes\" DTS=\"0\" xmlFrom=\"doc.start\" xmlTo=\"text_1.start\"/>\n");

	ts = trak->Media->mediaHeader->timeScale;
	cur_frame = 0;
	end = 0;

	fprintf(dump, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
	fprintf(dump, "<svg version=\"1.2\" baseProfile=\"tiny\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"%d\" height=\"%d\" fill=\"black\">\n", trak->Header->width >> 16 , trak->Header->height >> 16);
	fprintf(dump, "<g transform=\"translate(%d, %d)\" text-anchor=\"middle\">\n", (trak->Header->width >> 16)/2 , (trak->Header->height >> 16)/2);

	count = gf_isom_get_sample_count(the_file, track);
	for (i=0; i<count; i++) {
		GF_TextSample *txt;
		GF_ISOSample *s = gf_isom_get_sample(the_file, track, i+1, &di);
		if (!s) continue;

		start = s->DTS;
		if (s->dataLength==2) {
			gf_isom_sample_del(&s);
			continue;
		}
		if (i+1<count) {
			GF_ISOSample *next = gf_isom_get_sample_info(the_file, track, i+2, NULL, NULL);
			if (next) {
				end = next->DTS;
				gf_isom_sample_del(&next);
			}
		}

		cur_frame++;
		bs = gf_bs_new(s->data, s->dataLength, GF_BITSTREAM_READ);
		txt = gf_isom_parse_texte_sample(bs);
		gf_bs_del(bs);

		if (!txt->len) continue;

		fprintf(dump, " <text id=\"text_%d\" display=\"none\">%s\n", cur_frame, txt->text);
		fprintf(dump, "  <set attributeName=\"display\" to=\"inline\" begin=\"%g\" end=\"%g\"/>\n", ((s64)start*1.0)/ts, ((s64)end*1.0)/ts);
		fprintf(dump, "  <discard begin=\"%g\"/>\n", ((s64)end*1.0)/ts);
		fprintf(dump, " </text>\n");
		gf_isom_sample_del(&s);
		gf_isom_delete_text_sample(txt);
		fprintf(dump, "\n");
		gf_set_progress("SRT Extract", i, count);

		if (i == count - 2) {
			fprintf(nhmlFile, "<NHNTSample isRAP=\"no\" DTS=\"%f\" xmlFrom=\"text_%d.start\" xmlTo=\"doc.end\"/>\n", ((s64)start*1.0), cur_frame);
		} else {
			fprintf(nhmlFile, "<NHNTSample isRAP=\"no\" DTS=\"%f\" xmlFrom=\"text_%d.start\" xmlTo=\"text_%d.start\"/>\n", ((s64)start*1.0), cur_frame, cur_frame+1);
		}

	}
	fprintf(dump, "</g>\n");
	fprintf(dump, "</svg>\n");

	fprintf(nhmlFile, "</NHNTStream>\n");
	gf_fclose(nhmlFile);

	if (count) gf_set_progress("SRT Extract", i, count);
	return GF_OK;
}


void cil_print_recursive_blockinherit(struct cil_tree_node *bi_node, struct cil_tree_node *terminating_node)
{
	struct cil_list *trace = NULL;
	struct cil_list_item *item = NULL;
	struct cil_tree_node *curr = NULL;

	cil_list_init(&trace, CIL_NODE);

	for (curr = bi_node; curr != terminating_node; curr = curr->parent) {
		if (curr->flavor == CIL_BLOCK) {
			cil_list_prepend(trace, CIL_NODE, curr);
		} else if (curr->flavor == CIL_BLOCKINHERIT) {
			if (curr != bi_node) {
				cil_list_prepend(trace, CIL_NODE, NODE(((struct cil_blockinherit *)curr->data)->block));
			}
			cil_list_prepend(trace, CIL_NODE, curr);
		} else {
			cil_list_prepend(trace, CIL_NODE, curr);
		}
	}
	cil_list_prepend(trace, CIL_NODE, terminating_node);

	cil_list_for_each(item, trace) {
		curr = item->data;
		if (curr->flavor == CIL_BLOCK) {
			cil_tree_log(curr, CIL_ERR, "block %s", DATUM(curr->data)->name);
		} else if (curr->flavor == CIL_BLOCKINHERIT) {
			cil_tree_log(curr, CIL_ERR, "blockinherit %s", ((struct cil_blockinherit *)curr->data)->block_str);
		} else if (curr->flavor == CIL_OPTIONAL) {
			cil_tree_log(curr, CIL_ERR, "optional %s", DATUM(curr->data)->name);
		} else {
			cil_tree_log(curr, CIL_ERR, "%s", cil_node_to_string(curr));
		}
	}

	cil_list_destroy(&trace, CIL_FALSE);
}


void WebContentsImpl::DidStopLoading() {
  scoped_ptr<LoadNotificationDetails> details;

  NavigationEntry* entry = controller_.GetLastCommittedEntry();
  Navigator* navigator = frame_tree_.root()->navigator();

  if (entry) {
    base::TimeDelta elapsed =
        base::TimeTicks::Now() - navigator->GetCurrentLoadStart();

    details.reset(new LoadNotificationDetails(
        entry->GetVirtualURL(),
        entry->GetTransitionType(),
        elapsed,
        &controller_,
        controller_.GetCurrentEntryIndex()));
  }

  SetIsLoading(false, true, details.get());
}


String Range::toString(ExceptionCode& ec) const
{
    if (!m_start.container()) {
        ec = INVALID_STATE_ERR;
        return String();
    }

    StringBuilder builder;

    Node* pastLast = pastLastNode();
    for (Node* n = firstNode(); n != pastLast; n = n->traverseNextNode()) {
        if (n->nodeType() == Node::TEXT_NODE || n->nodeType() == Node::CDATA_SECTION_NODE) {
            String data = static_cast<CharacterData*>(n)->data();
            int length = data.length();
            int start = (n == m_start.container()) ? min(max(0, m_start.offset()), length) : 0;
            int end = (n == m_end.container()) ? min(max(start, m_end.offset()), length) : length;
            builder.append(data.characters() + start, end - start);
        }
    }

    return builder.toString();
}


static MagickBooleanType DecodeImage(Image *image,unsigned char *luma,
  unsigned char *chroma1,unsigned char *chroma2)
{
#define IsSync(sum)  ((sum & 0xffffff00UL) == 0xfffffe00UL)
#define PCDGetBits(n) \
{  \
  sum=(sum << n) & 0xffffffff; \
  bits-=n; \
  while (bits <= 24) \
  { \
    if (p >= (buffer+0x800)) \
      { \
        count=ReadBlob(image,0x800,buffer); \
        p=buffer; \
      } \
    sum|=((unsigned int) (*p) << (24-bits)); \
    bits+=8; \
    p++; \
  } \
}

  typedef struct PCDTable
  {
    unsigned int
      length,
      sequence;

    MagickStatusType
      mask;

    unsigned char
      key;
  } PCDTable;

  PCDTable
    *pcd_table[3];

  register ssize_t
    i,
    j;

  register PCDTable
    *r;

  register unsigned char
    *p,
    *q;

  size_t
    bits,
    length,
    plane,
    pcd_length[3],
    row,
    sum;

  ssize_t
    count,
    quantum;

  unsigned char
    *buffer;

  /*
    Initialize Huffman tables.
  */
  assert(image != (const Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  assert(luma != (unsigned char *) NULL);
  assert(chroma1 != (unsigned char *) NULL);
  assert(chroma2 != (unsigned char *) NULL);
  buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer));
  if (buffer == (unsigned char *) NULL)
    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
      image->filename);
  sum=0;
  bits=32;
  p=buffer+0x800;
  for (i=0; i < 3; i++)
  {
    pcd_table[i]=(PCDTable *) NULL;
    pcd_length[i]=0;
  }
  for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
  {
    PCDGetBits(8);
    length=(sum & 0xff)+1;
    pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length,
      sizeof(*pcd_table[i]));
    if (pcd_table[i] == (PCDTable *) NULL)
      {
        buffer=(unsigned char *) RelinquishMagickMemory(buffer);
        ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
          image->filename);
      }
    r=pcd_table[i];
    for (j=0; j < (ssize_t) length; j++)
    {
      PCDGetBits(8);
      r->length=(unsigned int) (sum & 0xff)+1;
      if (r->length > 16)
        {
          buffer=(unsigned char *) RelinquishMagickMemory(buffer);
          return(MagickFalse);
        }
      PCDGetBits(16);
      r->sequence=(unsigned int) (sum & 0xffff) << 16;
      PCDGetBits(8);
      r->key=(unsigned char) (sum & 0xff);
      r->mask=(~((1U << (32-r->length))-1));
      r++;
    }
    pcd_length[i]=(size_t) length;
  }
  /*
    Search for Sync byte.
  */
  for (i=0; i < 1; i++)
    PCDGetBits(16);
  for (i=0; i < 1; i++)
    PCDGetBits(16);
  while ((sum & 0x00fff000UL) != 0x00fff000UL)
    PCDGetBits(8);
  while (IsSync(sum) == 0)
    PCDGetBits(1);
  /*
    Recover the Huffman encoded luminance and chrominance deltas.
  */
  count=0;
  length=0;
  plane=0;
  row=0;
  q=luma;
  for ( ; ; )
  {
    if (IsSync(sum) != 0)
      {
        /*
          Determine plane and row number.
        */
        PCDGetBits(16);
        row=((sum >> 9) & 0x1fff);
        if (row == image->rows)
          break;
        PCDGetBits(8);
        plane=sum >> 30;
        PCDGetBits(16);
        switch (plane)
        {
          case 0:
          {
            q=luma+row*image->columns;
            count=(ssize_t) image->columns;
            break;
          }
          case 2:
          {
            q=chroma1+(row >> 1)*image->columns;
            count=(ssize_t) (image->columns >> 1);
            plane--;
            break;
          }
          case 3:
          {
            q=chroma2+(row >> 1)*image->columns;
            count=(ssize_t) (image->columns >> 1);
            plane--;
            break;
          }
          default:
          {
            ThrowBinaryException(CorruptImageError,"CorruptImage",
              image->filename);
          }
        }
        length=pcd_length[plane];
        continue;
      }
    /*
      Decode luminance or chrominance deltas.
    */
    r=pcd_table[plane];
    for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++)
      r++;
    if ((row > image->rows) || (r == (PCDTable *) NULL))
      {
        (void) ThrowMagickException(&image->exception,GetMagickModule(),
          CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
        while ((sum & 0x00fff000) != 0x00fff000)
          PCDGetBits(8);
        while (IsSync(sum) == 0)
          PCDGetBits(1);
        continue;
      }
    if (r->key < 128)
      quantum=(ssize_t) (*q)+r->key;
    else
      quantum=(ssize_t) (*q)+r->key-256;
    *q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum);
    q++;
    PCDGetBits(r->length);
    count--;
  }
  /*
    Relinquish resources.
  */
  for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
    pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]);
  buffer=(unsigned char *) RelinquishMagickMemory(buffer);
  return(MagickTrue);
}


static int opfnsave(RAsm *a, ut8 *data, const Opcode *op) {
	int l = 0;
	switch (op->operands_count) {
	case 1:
		if ( op->operands[0].type & OT_MEMORY &&
		     op->operands[0].type & OT_DWORD ) {
			data[l++] = 0xdd;
			data[l++] = 0x30 | op->operands[0].regs[0];
		} else {
			return -1;
		}
		break;
	default:
		return -1;
	}
	return l;
}


Buffer::InstancePtr& ActiveStreamEncoderFilter::bufferedData() {
  return parent_.buffered_response_data_;
}


bool MockContentSettingsClient::allowScriptFromSource(
    bool enabled_per_settings,
    const blink::WebURL& script_url) {
  bool allowed = enabled_per_settings && flags_->scripts_allowed();
  if (flags_->dump_web_content_settings_client_callbacks() && delegate_) {
    delegate_->PrintMessage(
        std::string("MockContentSettingsClient: allowScriptFromSource(") +
        NormalizeLayoutTestURL(script_url.string().utf8()) + "): " +
        (allowed ? "true" : "false") + "\n");
  }
  return allowed;
}


void ClrFormatPromptHook(void) {
	UnhookWinEvent(fp_weh);
	fp_weh = NULL;
}


int src_parser_cpp(const char *src, const struct trans_config cfg)
{
    int tmp_fd;
    char fname[TMP_FILE_NAME_SIZE];

    strncpy(fname, TMP_FILE_NAME, TMP_FILE_NAME_SIZE);
    tmp_fd = mkstemp(fname);
    if (tmp_fd == -1) {
        fprintf(stderr, "**Error: could not create a working file.\n");
        return -1;
    }

    src_parser_trans_stage_1_2_3(tmp_fd, src, cfg);

    print_file_full(tmp_fd);

    unlink(fname);
}


gfx::Size RootWindow::GetHostSize() const {
  return host_->GetBounds().size();
}


static int setcos_set_security_env(sc_card_t *card,
				   const sc_security_env_t *env, int se_num)
{
	if (env->flags & SC_SEC_ENV_ALG_PRESENT) {
		sc_security_env_t tmp;

		tmp = *env;
		tmp.flags &= ~SC_SEC_ENV_ALG_PRESENT;
		tmp.flags |= SC_SEC_ENV_ALG_REF_PRESENT;
		if (tmp.algorithm != SC_ALGORITHM_RSA) {
			sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Only RSA algorithm supported.\n");
			return SC_ERROR_NOT_SUPPORTED;
		}
		switch (card->type) {
		case SC_CARD_TYPE_SETCOS_PKI:
		case SC_CARD_TYPE_SETCOS_FINEID:
		case SC_CARD_TYPE_SETCOS_FINEID_V2_2048:
		case SC_CARD_TYPE_SETCOS_NIDEL:
		case SC_CARD_TYPE_SETCOS_44:
		case SC_CARD_TYPE_SETCOS_EID_V2_0:
		case SC_CARD_TYPE_SETCOS_EID_V2_1:
			break;
		default:
			sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card does not support RSA.\n");
			return SC_ERROR_NOT_SUPPORTED;
			break;
		}
		tmp.algorithm_ref = 0x00;
		/* potential FIXME: return an error, if an unsupported
		 * pad or hash was requested, although this shouldn't happen.
		 */
		if (env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)
			tmp.algorithm_ref = 0x02;
		if (tmp.algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1)
			tmp.algorithm_ref |= 0x10;
		return setcos_set_security_env2(card, &tmp, se_num);
	}
	return setcos_set_security_env2(card, env, se_num);
}


int getFinestScale() const CV_OVERRIDE { return finest_scale; }


static struct ip_esp_hdr *esp_output_set_esn(struct sk_buff *skb,
					     struct xfrm_state *x,
					     struct ip_esp_hdr *esph,
					     struct esp_output_extra *extra)
{
	/* For ESN we move the header forward by 4 bytes to
	 * accomodate the high bits.  We will move it back after
	 * encryption.
	 */
	if ((x->props.flags & XFRM_STATE_ESN)) {
		__u32 seqhi;
		struct xfrm_offload *xo = xfrm_offload(skb);

		if (xo)
			seqhi = xo->seq.hi;
		else
			seqhi = XFRM_SKB_CB(skb)->seq.output.hi;

		extra->esphoff = (unsigned char *)esph -
				 skb_transport_header(skb);
		esph = (struct ip_esp_hdr *)((unsigned char *)esph - 4);
		extra->seqhi = esph->spi;
		esph->seq_no = htonl(seqhi);
	}

	esph->spi = x->id.spi;

	return esph;
}


static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat)
{
	struct file *file = kiocb->ki_filp;
	ssize_t ret = 0;

	switch (kiocb->ki_opcode) {
	case IOCB_CMD_PREAD:
		ret = -EBADF;
		if (unlikely(!(file->f_mode & FMODE_READ)))
			break;
		ret = -EFAULT;
		if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,
			kiocb->ki_left)))
			break;
		ret = aio_setup_single_vector(READ, file, kiocb);
		if (ret)
			break;
		ret = -EINVAL;
		if (file->f_op->aio_read)
			kiocb->ki_retry = aio_rw_vect_retry;
		break;
	case IOCB_CMD_PWRITE:
		ret = -EBADF;
		if (unlikely(!(file->f_mode & FMODE_WRITE)))
			break;
		ret = -EFAULT;
		if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,
			kiocb->ki_left)))
			break;
		ret = aio_setup_single_vector(WRITE, file, kiocb);
		if (ret)
			break;
		ret = -EINVAL;
		if (file->f_op->aio_write)
			kiocb->ki_retry = aio_rw_vect_retry;
		break;
	case IOCB_CMD_PREADV:
		ret = -EBADF;
		if (unlikely(!(file->f_mode & FMODE_READ)))
			break;
		ret = aio_setup_vectored_rw(READ, kiocb, compat);
		if (ret)
			break;
		ret = -EINVAL;
		if (file->f_op->aio_read)
			kiocb->ki_retry = aio_rw_vect_retry;
		break;
	case IOCB_CMD_PWRITEV:
		ret = -EBADF;
		if (unlikely(!(file->f_mode & FMODE_WRITE)))
			break;
		ret = aio_setup_vectored_rw(WRITE, kiocb, compat);
		if (ret)
			break;
		ret = -EINVAL;
		if (file->f_op->aio_write)
			kiocb->ki_retry = aio_rw_vect_retry;
		break;
	case IOCB_CMD_FDSYNC:
		ret = -EINVAL;
		if (file->f_op->aio_fsync)
			kiocb->ki_retry = aio_fdsync;
		break;
	case IOCB_CMD_FSYNC:
		ret = -EINVAL;
		if (file->f_op->aio_fsync)
			kiocb->ki_retry = aio_fsync;
		break;
	default:
		dprintk("EINVAL: io_submit: no operation provided\n");
		ret = -EINVAL;
	}

	if (!kiocb->ki_retry)
		return ret;

	return 0;
}


static inline unsigned d_count(const struct dentry *dentry)
{
	return dentry->d_lockref.count;
}


bool mobi_indx_has_tag(const MOBIIndx *indx, const size_t tagid) {
    if (indx) {
        for (size_t i = 0; i < indx->entries_count; i++) {
            MOBIIndexEntry entry = indx->entries[i];
            for(size_t j = 0; j < entry.tags_count; j++) {
                if (entry.tags[j].tagid == tagid) {
                    return true;
                }
            }
        }
    }
    return false;
}


fire_sched_out_preempt_notifiers(struct task_struct *curr,
				 struct task_struct *next)
{
}


static UPNP_INLINE void glob_alias_init(void)
{
	struct xml_alias_t *alias = &gAliasDoc;

	membuffer_init(&alias->doc);
	membuffer_init(&alias->name);
	alias->ct = NULL;
	alias->last_modified = 0;
}


int gnutls_x509_ext_import_proxy(const gnutls_datum_t * ext, int *pathlen,
			      char **policyLanguage, char **policy,
			      size_t * sizeof_policy)
{
	ASN1_TYPE c2 = ASN1_TYPE_EMPTY;
	int result;
	gnutls_datum_t value = { NULL, 0 };

	if ((result = asn1_create_element
	     (_gnutls_get_pkix(), "PKIX1.ProxyCertInfo",
	      &c2)) != ASN1_SUCCESS) {
		gnutls_assert();
		return _gnutls_asn2err(result);
	}

	result = _asn1_strict_der_decode(&c2, ext->data, ext->size, NULL);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	if (pathlen) {
		result = _gnutls_x509_read_uint(c2, "pCPathLenConstraint",
						(unsigned int *)
						pathlen);
		if (result == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND)
			*pathlen = -1;
		else if (result != GNUTLS_E_SUCCESS) {
			gnutls_assert();
			result = _gnutls_asn2err(result);
			goto cleanup;
		}
	}

	result = _gnutls_x509_read_value(c2, "proxyPolicy.policyLanguage",
					 &value);
	if (result < 0) {
		gnutls_assert();
		goto cleanup;
	}

	if (policyLanguage) {
		*policyLanguage = (char *)value.data;
	} else {
		gnutls_free(value.data);
		value.data = NULL;
	}

	result = _gnutls_x509_read_value(c2, "proxyPolicy.policy", &value);
	if (result == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND) {
		if (policy)
			*policy = NULL;
		if (sizeof_policy)
			*sizeof_policy = 0;
	} else if (result < 0) {
		gnutls_assert();
		goto cleanup;
	} else {
		if (policy) {
			*policy = (char *)value.data;
			value.data = NULL;
		}
		if (sizeof_policy)
			*sizeof_policy = value.size;
	}

	result = 0;
 cleanup:
	gnutls_free(value.data);
	asn1_delete_structure(&c2);

	return result;
}


static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,

                               int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf     = avpkt->data;

    int buf_size           = avpkt->size;

    MP3On4DecodeContext *s = avctx->priv_data;

    MPADecodeContext *m;

    int fsize, len = buf_size, out_size = 0;

    uint32_t header;

    OUT_INT *out_samples;

    OUT_INT *outptr, *bp;

    int fr, j, n, ch, ret;

    /* get output buffer */

    s->frame->nb_samples = MPA_FRAME_SIZE;

    if ((ret = avctx->get_buffer(avctx, s->frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    out_samples = (OUT_INT *)s->frame->data[0];

    // Discard too short frames

    if (buf_size < HEADER_SIZE)

    // If only one decoder interleave is not needed

    outptr = s->frames == 1 ? out_samples : s->decoded_buf;

    avctx->bit_rate = 0;

    ch = 0;

    for (fr = 0; fr < s->frames; fr++) {

        fsize = AV_RB16(buf) >> 4;

        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);

        m     = s->mp3decctx[fr];

        assert(m != NULL);

        header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header

        if (ff_mpa_check_header(header) < 0) // Bad header, discard block

            break;

        avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);

        if (ch + m->nb_channels > avctx->channels) {

            av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "

                                        "channel count\n");

        ch += m->nb_channels;

        out_size += mp_decode_frame(m, outptr, buf, fsize);

        buf      += fsize;

        len      -= fsize;

        if (s->frames > 1) {

            n = m->avctx->frame_size*m->nb_channels;

            /* interleave output data */

            bp = out_samples + s->coff[fr];

            if (m->nb_channels == 1) {

                for (j = 0; j < n; j++) {

                    *bp = s->decoded_buf[j];

                    bp += avctx->channels;

            } else {

                for (j = 0; j < n; j++) {

                    bp[0] = s->decoded_buf[j++];

                    bp[1] = s->decoded_buf[j];

                    bp   += avctx->channels;

        avctx->bit_rate += m->bit_rate;

    /* update codec info */

    avctx->sample_rate = s->mp3decctx[0]->sample_rate;

    s->frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));

    *got_frame_ptr   = 1;

    *(AVFrame *)data = *s->frame;

    return buf_size;


bool SiteInstanceImpl::HasRelatedSiteInstance(const GURL& url) {
  return browsing_instance_->HasSiteInstance(url);
}


flatpak_bwrap_add_fd (FlatpakBwrap *bwrap,
                      int           fd)
{
  g_array_append_val (bwrap->fds, fd);
}


static int bfi_read_header(AVFormatContext * s)

{

    BFIContext *bfi = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *vstream;

    AVStream *astream;

    int fps, chunk_header;

    /* Initialize the video codec... */

    vstream = avformat_new_stream(s, NULL);

    if (!vstream)

        return AVERROR(ENOMEM);

    /* Initialize the audio codec... */

    astream = avformat_new_stream(s, NULL);

    if (!astream)

        return AVERROR(ENOMEM);

    /* Set the total number of frames. */

    avio_skip(pb, 8);

    chunk_header           = avio_rl32(pb);

    bfi->nframes           = avio_rl32(pb);

    avio_rl32(pb);

    avio_rl32(pb);

    avio_rl32(pb);

    fps                    = avio_rl32(pb);

    avio_skip(pb, 12);

    vstream->codecpar->width  = avio_rl32(pb);

    vstream->codecpar->height = avio_rl32(pb);

    /*Load the palette to extradata */

    avio_skip(pb, 8);

    vstream->codecpar->extradata      = av_malloc(768);

    if (!vstream->codecpar->extradata)

        return AVERROR(ENOMEM);

    vstream->codecpar->extradata_size = 768;

    avio_read(pb, vstream->codecpar->extradata,

               vstream->codecpar->extradata_size);

    astream->codecpar->sample_rate = avio_rl32(pb);

    if (astream->codecpar->sample_rate <= 0) {

        av_log(s, AV_LOG_ERROR, "Invalid sample rate %d\n", astream->codecpar->sample_rate);

        return AVERROR_INVALIDDATA;

    }

    /* Set up the video codec... */

    avpriv_set_pts_info(vstream, 32, 1, fps);

    vstream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;

    vstream->codecpar->codec_id   = AV_CODEC_ID_BFI;

    vstream->codecpar->format     = AV_PIX_FMT_PAL8;

    vstream->nb_frames            =

    vstream->duration             = bfi->nframes;

    /* Set up the audio codec now... */

    astream->codecpar->codec_type      = AVMEDIA_TYPE_AUDIO;

    astream->codecpar->codec_id        = AV_CODEC_ID_PCM_U8;

    astream->codecpar->channels        = 1;

    astream->codecpar->channel_layout  = AV_CH_LAYOUT_MONO;

    astream->codecpar->bits_per_coded_sample = 8;

    astream->codecpar->bit_rate        =

        astream->codecpar->sample_rate * astream->codecpar->bits_per_coded_sample;

    avio_seek(pb, chunk_header - 3, SEEK_SET);

    avpriv_set_pts_info(astream, 64, 1, astream->codecpar->sample_rate);

    return 0;

}


static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  mz_uint flags;
  mz_uint8 *pLZ_codes;
  mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  mz_uint64 bit_buffer = d->m_bit_buffer;
  mz_uint bits_in = d->m_bits_in;

#define TDEFL_PUT_BITS_FAST(b, l)                \
  {                                              \
    bit_buffer |= (((mz_uint64)(b)) << bits_in); \
    bits_in += (l);                              \
  }

  flags = 1;
  for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
       flags >>= 1) {
    if (flags == 1) flags = *pLZ_codes++ | 0x100;

    if (flags & 1) {
      mz_uint s0, s1, n0, n1, sym, num_extra_bits;
      mz_uint match_len = pLZ_codes[0],
              match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
      pLZ_codes += 3;

      MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
      TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
                          d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
      TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
                          s_tdefl_len_extra[match_len]);

      // This sequence coaxes MSVC into using cmov's vs. jmp's.
      s0 = s_tdefl_small_dist_sym[match_dist & 511];
      n0 = s_tdefl_small_dist_extra[match_dist & 511];
      s1 = s_tdefl_large_dist_sym[match_dist >> 8];
      n1 = s_tdefl_large_dist_extra[match_dist >> 8];
      sym = (match_dist < 512) ? s0 : s1;
      num_extra_bits = (match_dist < 512) ? n0 : n1;

      MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
      TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
                          d->m_huff_code_sizes[1][sym]);
      TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
                          num_extra_bits);
    } else {
      mz_uint lit = *pLZ_codes++;
      MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
      TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
                          d->m_huff_code_sizes[0][lit]);

      if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
        flags >>= 1;
        lit = *pLZ_codes++;
        MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
        TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
                            d->m_huff_code_sizes[0][lit]);

        if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
          flags >>= 1;
          lit = *pLZ_codes++;
          MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
          TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
                              d->m_huff_code_sizes[0][lit]);
        }
      }
    }

    if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE;

    *(mz_uint64 *)pOutput_buf = bit_buffer;
    pOutput_buf += (bits_in >> 3);
    bit_buffer >>= (bits_in & ~7);
    bits_in &= 7;
  }

#undef TDEFL_PUT_BITS_FAST

  d->m_pOutput_buf = pOutput_buf;
  d->m_bits_in = 0;
  d->m_bit_buffer = 0;

  while (bits_in) {
    mz_uint32 n = MZ_MIN(bits_in, 16);
    TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
    bit_buffer >>= n;
    bits_in -= n;
  }

  TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);

  return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}


emacs_tags_file_eof(findtags_state_T *st)
{
    if (!incstack_idx)	// reached end of file. stop processing.
	return FALSE;

    // reached the end of an included tags file. pop it.
    --incstack_idx;
    fclose(st->fp);	// end of this file ...
    st->fp = incstack[incstack_idx].fp;
    STRCPY(st->tag_fname, incstack[incstack_idx].etag_fname);
    vim_free(incstack[incstack_idx].etag_fname);
    st->is_etag = TRUE;	// (only etags can include)

    return TRUE;
}


static void
typebuilder_setup_events (MonoClass *klass, MonoError *error)
{
	MonoReflectionTypeBuilder *tb = klass->reflection_info;
	MonoReflectionEventBuilder *eb;
	MonoImage *image = klass->image;
	MonoEvent *events;
	int i, j;

	mono_error_init (error);

	if (!klass->ext)
		klass->ext = image_g_new0 (image, MonoClassExt, 1);

	klass->ext->event.count = tb->events ? mono_array_length (tb->events) : 0;
	klass->ext->event.first = 0;

	events = image_g_new0 (image, MonoEvent, klass->ext->event.count);
	klass->ext->events = events;
	for (i = 0; i < klass->ext->event.count; ++i) {
		eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
		events [i].parent = klass;
		events [i].attrs = eb->attrs;
		events [i].name = mono_string_to_utf8_image (image, eb->name, error);
		if (!mono_error_ok (error))
			return;
		if (eb->add_method)
			events [i].add = eb->add_method->mhandle;
		if (eb->remove_method)
			events [i].remove = eb->remove_method->mhandle;
		if (eb->raise_method)
			events [i].raise = eb->raise_method->mhandle;

		if (eb->other_methods) {
			events [i].other = image_g_new0 (image, MonoMethod*, mono_array_length (eb->other_methods) + 1);
			for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
				MonoReflectionMethodBuilder *mb =
					mono_array_get (eb->other_methods,
									MonoReflectionMethodBuilder*, j);
				events [i].other [j] = mb->mhandle;
			}
		}
		mono_save_custom_attrs (klass->image, &events [i], eb->cattrs);
	}


GF_Err gf_odf_get_ui_config(GF_DefaultDescriptor *dsi, GF_UIConfig *cfg)
{
	u32 len, i;
	GF_BitStream *bs;
	if (!dsi || !dsi->data || !dsi->dataLength || !cfg) return GF_BAD_PARAM;
	memset(cfg, 0, sizeof(GF_UIConfig));
	cfg->tag = GF_ODF_UI_CFG_TAG;
	bs = gf_bs_new(dsi->data, dsi->dataLength, GF_BITSTREAM_READ);
	len = gf_bs_read_int(bs, 8);
	cfg->deviceName = (char*)gf_malloc(sizeof(char) * (len+1));
	for (i=0; i<len; i++) cfg->deviceName[i] = gf_bs_read_int(bs, 8);
	cfg->deviceName[i] = 0;

	if (!stricmp(cfg->deviceName, "StringSensor") && gf_bs_available(bs)) {
		cfg->termChar = gf_bs_read_int(bs, 8);
		cfg->delChar = gf_bs_read_int(bs, 8);
	}
	gf_bs_del(bs);
	return GF_OK;
}


lyp_ctx_add_module(struct lys_module *module)
{
    struct lys_module **newlist = NULL;
    int i;

    assert(!lyp_ctx_check_module(module));

#ifndef NDEBUG
    int j;
    /* check that all augments are resolved */
    for (i = 0; i < module->augment_size; ++i) {
        assert(module->augment[i].target);
    }
    for (i = 0; i < module->inc_size; ++i) {
        for (j = 0; j < module->inc[i].submodule->augment_size; ++j) {
            assert(module->inc[i].submodule->augment[j].target);
        }
    }
#endif

    /* add to the context's list of modules */
    if (module->ctx->models.used == module->ctx->models.size) {
        newlist = realloc(module->ctx->models.list, (2 * module->ctx->models.size) * sizeof *newlist);
        LY_CHECK_ERR_RETURN(!newlist, LOGMEM(module->ctx), -1);
        for (i = module->ctx->models.size; i < module->ctx->models.size * 2; i++) {
            newlist[i] = NULL;
        }
        module->ctx->models.size *= 2;
        module->ctx->models.list = newlist;
    }
    module->ctx->models.list[module->ctx->models.used++] = module;
    module->ctx->models.module_set_id++;

    return 0;
}


static int efx_pci_probe_main(struct efx_nic *efx)
{
	int rc;

	/* Do start-of-day initialisation */
	rc = efx_probe_all(efx);
	if (rc)
		goto fail1;

	efx_init_napi(efx);

	rc = efx->type->init(efx);
	if (rc) {
		netif_err(efx, probe, efx->net_dev,
			  "failed to initialise NIC\n");
		goto fail3;
	}

	rc = efx_init_port(efx);
	if (rc) {
		netif_err(efx, probe, efx->net_dev,
			  "failed to initialise port\n");
		goto fail4;
	}

	efx_init_channels(efx);

	rc = efx_nic_init_interrupt(efx);
	if (rc)
		goto fail5;

	return 0;

 fail5:
	efx_fini_channels(efx);
	efx_fini_port(efx);
 fail4:
	efx->type->fini(efx);
 fail3:
	efx_fini_napi(efx);
	efx_remove_all(efx);
 fail1:
	return rc;
}


static const struct nft_expr_type *nft_expr_type_get(u8 family,
						     struct nlattr *nla)
{
	const struct nft_expr_type *type;

	if (nla == NULL)
		return ERR_PTR(-EINVAL);

	type = __nft_expr_type_get(family, nla);
	if (type != NULL && try_module_get(type->owner))
		return type;

#ifdef CONFIG_MODULES
	if (type == NULL) {
		nfnl_unlock(NFNL_SUBSYS_NFTABLES);
		request_module("nft-expr-%u-%.*s", family,
			       nla_len(nla), (char *)nla_data(nla));
		nfnl_lock(NFNL_SUBSYS_NFTABLES);
		if (__nft_expr_type_get(family, nla))
			return ERR_PTR(-EAGAIN);

		nfnl_unlock(NFNL_SUBSYS_NFTABLES);
		request_module("nft-expr-%.*s",
			       nla_len(nla), (char *)nla_data(nla));
		nfnl_lock(NFNL_SUBSYS_NFTABLES);
		if (__nft_expr_type_get(family, nla))
			return ERR_PTR(-EAGAIN);
	}
#endif
	return ERR_PTR(-ENOENT);
}


const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s,
                                        unsigned int *len)
{
    if (len)
        *len = s->session_id_length;
    return s->session_id;
}


static void test_bug9992()
{
  MYSQL *mysql1;
  MYSQL_RES* res ;
  int   rc;

  myheader("test_bug9992");

  if (!opt_silent)
    printf("Establishing a connection with option CLIENT_MULTI_STATEMENTS..\n");

  mysql1= mysql_client_init(NULL);

  if (!mysql_real_connect(mysql1, opt_host, opt_user, opt_password,
                          opt_db ? opt_db : "test", opt_port, opt_unix_socket,
                          CLIENT_MULTI_STATEMENTS))
  {
    fprintf(stderr, "Failed to connect to the database\n");
    DIE_UNLESS(0);
  }

  /* Sic: SHOW DATABASE is incorrect syntax. */
  rc= mysql_query(mysql1, "SHOW TABLES; SHOW DATABASE; SELECT 1;");

  if (rc)
  {
    fprintf(stderr, "[%d] %s\n", mysql_errno(mysql1), mysql_error(mysql1));
    DIE_UNLESS(0);
  }

  if (!opt_silent)
    printf("Testing mysql_store_result/mysql_next_result..\n");

  res= mysql_store_result(mysql1);
  DIE_UNLESS(res);
  mysql_free_result(res);
  rc= mysql_next_result(mysql1);
  DIE_UNLESS(rc == 1);                         /* Got errors, as expected */

  if (!opt_silent)
    fprintf(stdout, "Got error, as expected:\n [%d] %s\n",
            mysql_errno(mysql1), mysql_error(mysql1));

  mysql_close(mysql1);
}


PP_Resource PPB_URLLoader_Impl::Create(PP_Instance pp_instance) {
  PluginInstance* instance = ResourceTracker::Get()->GetInstance(pp_instance);
  if (!instance)
    return 0;

  PPB_URLLoader_Impl* loader = new PPB_URLLoader_Impl(instance, false);
  return loader->GetReference();
}


void visit(Ignore & /*ope*/) override { name = "Ignore"; }


const StreamInfo::StreamInfoImpl& streamInfo() const { return stream_info_; }


static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)

{

    int j, k, l, sb_x, sb_y;

    int coding_mode;

    int motion_x[6];

    int motion_y[6];

    int last_motion_x = 0;

    int last_motion_y = 0;

    int prior_last_motion_x = 0;

    int prior_last_motion_y = 0;

    int current_macroblock;

    int current_fragment;

    if (s->keyframe)

        return 0;

    memset(motion_x, 0, 6 * sizeof(int));

    memset(motion_y, 0, 6 * sizeof(int));

    /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */

    coding_mode = get_bits1(gb);

    /* iterate through all of the macroblocks that contain 1 or more

     * coded fragments */

    for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {

        for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {

        for (j = 0; j < 4; j++) {

            int mb_x = 2*sb_x +   (j>>1);

            int mb_y = 2*sb_y + (((j>>1)+j)&1);

            current_macroblock = mb_y * s->macroblock_width + mb_x;

            if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||

                (s->macroblock_coding[current_macroblock] == MODE_COPY))

                continue;

            switch (s->macroblock_coding[current_macroblock]) {

            case MODE_INTER_PLUS_MV:

            case MODE_GOLDEN_MV:

                /* all 6 fragments use the same motion vector */

                if (coding_mode == 0) {

                    motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                    motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                } else {

                    motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];

                    motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];

                }

                /* vector maintenance, only on MODE_INTER_PLUS_MV */

                if (s->macroblock_coding[current_macroblock] ==

                    MODE_INTER_PLUS_MV) {

                    prior_last_motion_x = last_motion_x;

                    prior_last_motion_y = last_motion_y;

                    last_motion_x = motion_x[0];

                    last_motion_y = motion_y[0];

                }

                break;

            case MODE_INTER_FOURMV:

                /* vector maintenance */

                prior_last_motion_x = last_motion_x;

                prior_last_motion_y = last_motion_y;

                /* fetch 4 vectors from the bitstream, one for each

                 * Y fragment, then average for the C fragment vectors */

                motion_x[4] = motion_y[4] = 0;

                for (k = 0; k < 4; k++) {

                    current_fragment = BLOCK_Y*s->fragment_width + BLOCK_X;

                    for (l = 0; l < s->coded_fragment_list_index; l++)

                        if (s->coded_fragment_list[l] == current_fragment)

                            break;

                    if (l < s->coded_fragment_list_index) {

                        if (coding_mode == 0) {

                            motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                            motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                        } else {

                            motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];

                            motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];

                        }

                        last_motion_x = motion_x[k];

                        last_motion_y = motion_y[k];

                    } else {

                        motion_x[k] = 0;

                        motion_y[k] = 0;

                    }

                    motion_x[4] += motion_x[k];

                    motion_y[4] += motion_y[k];

                }

                motion_x[5]=

                motion_x[4]= RSHIFT(motion_x[4], 2);

                motion_y[5]=

                motion_y[4]= RSHIFT(motion_y[4], 2);

                break;

            case MODE_INTER_LAST_MV:

                /* all 6 fragments use the last motion vector */

                motion_x[0] = last_motion_x;

                motion_y[0] = last_motion_y;

                /* no vector maintenance (last vector remains the

                 * last vector) */

                break;

            case MODE_INTER_PRIOR_LAST:

                /* all 6 fragments use the motion vector prior to the

                 * last motion vector */

                motion_x[0] = prior_last_motion_x;

                motion_y[0] = prior_last_motion_y;

                /* vector maintenance */

                prior_last_motion_x = last_motion_x;

                prior_last_motion_y = last_motion_y;

                last_motion_x = motion_x[0];

                last_motion_y = motion_y[0];

                break;

            default:

                /* covers intra, inter without MV, golden without MV */

                motion_x[0] = 0;

                motion_y[0] = 0;

                /* no vector maintenance */

                break;

            }

            /* assign the motion vectors to the correct fragments */

            for (k = 0; k < 4; k++) {

                current_fragment =

                    BLOCK_Y*s->fragment_width + BLOCK_X;

                if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {

                    s->all_fragments[current_fragment].motion_x = motion_x[k];

                    s->all_fragments[current_fragment].motion_y = motion_y[k];

                } else {

                    s->all_fragments[current_fragment].motion_x = motion_x[0];

                    s->all_fragments[current_fragment].motion_y = motion_y[0];

                }

            }

            for (k = 0; k < 2; k++) {

                current_fragment = s->fragment_start[k+1] +

                    mb_y*(s->fragment_width>>1) + mb_x;

                if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {

                    s->all_fragments[current_fragment].motion_x = motion_x[k+4];

                    s->all_fragments[current_fragment].motion_y = motion_y[k+4];

                } else {

                    s->all_fragments[current_fragment].motion_x = motion_x[0];

                    s->all_fragments[current_fragment].motion_y = motion_y[0];

                }

            }

        }

        }

    }

    return 0;

}


DECLAREwriteFunc(writeBufferToSeparateTiles)
{
	uint32 imagew = TIFFScanlineSize(out);
	tsize_t tilew  = TIFFTileRowSize(out);
	uint32 iimagew = TIFFRasterScanlineSize(out);
	int iskew = iimagew - tilew*spp;
	tsize_t tilesize = TIFFTileSize(out);
	tdata_t obuf;
	uint8* bufp = (uint8*) buf;
	uint32 tl, tw;
	uint32 row;
	uint16 bps, bytes_per_sample;

	obuf = _TIFFmalloc(TIFFTileSize(out));
	if (obuf == NULL)
		return 0;
	_TIFFmemset(obuf, 0, tilesize);
	(void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
	(void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
	(void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
	assert( bps % 8 == 0 );
	bytes_per_sample = bps/8;

	for (row = 0; row < imagelength; row += tl) {
		uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
		uint32 colb = 0;
		uint32 col;

		for (col = 0; col < imagewidth; col += tw) {
			tsample_t s;
			for (s = 0; s < spp; s++) {
				/*
				 * Tile is clipped horizontally.  Calculate
				 * visible portion and skewing factors.
				 */
				if (colb + tilew > imagew) {
					uint32 width = (imagew - colb);
					int oskew = tilew - width;

					cpContigBufToSeparateBuf(obuf,
					    bufp + (colb*spp) + s,
					    nrow, width/bytes_per_sample,
					    oskew, (oskew*spp)+iskew, spp,
					    bytes_per_sample);
				} else
					cpContigBufToSeparateBuf(obuf,
					    bufp + (colb*spp) + s,
					    nrow, tilewidth,
					    0, iskew, spp,
					    bytes_per_sample);
				if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) {
					TIFFError(TIFFFileName(out),
					    "Error, can't write tile at %lu %lu "
					    "sample %lu",
					    (unsigned long) col,
					    (unsigned long) row,
					    (unsigned long) s);
					_TIFFfree(obuf);
					return 0;
				}
			}
			colb += tilew;
		}
		bufp += nrow * iimagew;
	}
	_TIFFfree(obuf);
	return 1;
}


static void thread_pool_cancel(BlockDriverAIOCB *acb)

{

    ThreadPoolElement *elem = (ThreadPoolElement *)acb;

    ThreadPool *pool = elem->pool;

    trace_thread_pool_cancel(elem, elem->common.opaque);

    qemu_mutex_lock(&pool->lock);

    if (elem->state == THREAD_QUEUED &&

        /* No thread has yet started working on elem. we can try to "steal"

         * the item from the worker if we can get a signal from the

         * semaphore.  Because this is non-blocking, we can do it with

         * the lock taken and ensure that elem will remain THREAD_QUEUED.

         */

        qemu_sem_timedwait(&pool->sem, 0) == 0) {

        QTAILQ_REMOVE(&pool->request_list, elem, reqs);

        elem->state = THREAD_CANCELED;

        event_notifier_set(&pool->notifier);

    } else {

        pool->pending_cancellations++;

        while (elem->state != THREAD_CANCELED && elem->state != THREAD_DONE) {

            qemu_cond_wait(&pool->check_cancel, &pool->lock);

        }

        pool->pending_cancellations--;

    }

    qemu_mutex_unlock(&pool->lock);

    event_notifier_ready(&pool->notifier);

}


static void scsi_command_complete(void *opaque, int ret)

{

    SCSIGenericReq *r = (SCSIGenericReq *)opaque;

    SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, r->req.dev);

    r->req.aiocb = NULL;

    s->driver_status = r->io_header.driver_status;

    if (s->driver_status & SG_ERR_DRIVER_SENSE)

        s->senselen = r->io_header.sb_len_wr;

    if (ret != 0)

        r->req.status = BUSY;

    else {

        if (s->driver_status & SG_ERR_DRIVER_TIMEOUT) {

            r->req.status = BUSY;

            BADF("Driver Timeout\n");

        } else if (r->io_header.status)

            r->req.status = r->io_header.status;

        else if (s->driver_status & SG_ERR_DRIVER_SENSE)

            r->req.status = CHECK_CONDITION;

        else

            r->req.status = GOOD;

    }

    DPRINTF("Command complete 0x%p tag=0x%x status=%d\n",

            r, r->req.tag, r->req.status);

    scsi_req_complete(&r->req);

}


static int dissect_h225_T_messageContent ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence_of ( tvb , offset , actx , tree , hf_index , ett_h225_T_messageContent , T_messageContent_sequence_of ) ;
 return offset ;
 }


unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
			int tag, unsigned int nr_pages, struct page **pages)
{
	unsigned int i;
	unsigned int ret;

	read_lock_irq(&mapping->tree_lock);
	ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
				(void **)pages, *index, nr_pages, tag);
	for (i = 0; i < ret; i++)
		page_cache_get(pages[i]);
	if (ret)
		*index = pages[ret - 1]->index + 1;
	read_unlock_irq(&mapping->tree_lock);
	return ret;
}


magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
{
	if (ms == NULL)
		return NULL;
	if (file_reset(ms) == -1)
		return NULL;
	/*
	 * The main work is done here!
	 * We have the file name and/or the data buffer to be identified.
	 */
	if (file_buffer(ms, -1, NULL, buf, nb) == -1) {
		return NULL;
	}
	return file_getbuffer(ms);
}


void V8Window::namedPropertyGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{

    DOMWindow* window = V8Window::toNative(info.Holder());
    if (!window)
        return;

    Frame* frame = window->frame();
    if (!frame)
        return;

    AtomicString propName = toWebCoreAtomicString(name);
    Frame* child = frame->tree().scopedChild(propName);
    if (child) {
        v8SetReturnValueFast(info, child->domWindow(), window);
        return;
    }

    if (!info.Holder()->GetRealNamedProperty(name).IsEmpty())
        return;

     Document* doc = frame->document();

     if (doc && doc->isHTMLDocument()) {
        if (toHTMLDocument(doc)->hasNamedItem(propName) || doc->hasElementWithId(propName.impl())) {
             RefPtr<HTMLCollection> items = doc->windowNamedItems(propName);
             if (!items->isEmpty()) {
                 if (items->hasExactlyOneItem()) {
                    v8SetReturnValueFast(info, items->item(0), window);
                    return;
                }
                v8SetReturnValueFast(info, items.release(), window);
                return;
            }
        }
    }
}


DriverClose(Sock *sockPtr)
{
    NS_NONNULL_ASSERT(sockPtr != NULL);
    (*sockPtr->drvPtr->closeProc)((Ns_Sock *) sockPtr);
}


int git_pkt_buffer_done(git_buf *buf)
{
	return git_buf_puts(buf, pkt_done_str);
}


static MagickBooleanType sixel_encode_impl(unsigned char *pixels, size_t width,size_t height,
                  unsigned char *palette, size_t ncolors, int keycolor,
                  sixel_output_t *context)
{
#define RelinquishNodesAndMap \
    while ((np = context->node_free) != NULL) { \
        context->node_free = np->next; \
        np=(sixel_node_t *) RelinquishMagickMemory(np); \
    } \
    map = (unsigned char *) RelinquishMagickMemory(map)

    int x, y, i, n, c;
    int left, right;
    int pix;
    unsigned char *map;
    sixel_node_t *np, *tp, top;
    int nwrite;
    size_t len;

    context->pos = 0;

    if (ncolors < 1) {
        return (MagickFalse);
    }
    len = ncolors * width;
    context->active_palette = (-1);

    if ((map = (unsigned char *)AcquireQuantumMemory(len, sizeof(unsigned char))) == NULL) {
        return (MagickFalse);
    }
    (void) ResetMagickMemory(map, 0, len);

    if (context->has_8bit_control) {
        nwrite = sprintf((char *)context->buffer, "\x90" "0;0;0" "q");
    } else {
        nwrite = sprintf((char *)context->buffer, "\x1bP" "0;0;0" "q");
    }
    if (nwrite <= 0) {
        return (MagickFalse);
    }
    sixel_advance(context, nwrite);
    nwrite = sprintf((char *)context->buffer + context->pos, "\"1;1;%d;%d", (int) width, (int) height);
    if (nwrite <= 0) {
        RelinquishNodesAndMap;
        return (MagickFalse);
    }
    sixel_advance(context, nwrite);

    if (ncolors != 2 || keycolor == -1) {
        for (n = 0; n < (ssize_t) ncolors; n++) {
            /* DECGCI Graphics Color Introducer  # Pc ; Pu; Px; Py; Pz */
            nwrite = sprintf((char *)context->buffer + context->pos, "#%d;2;%d;%d;%d",
                             n,
                             (palette[n * 3 + 0] * 100 + 127) / 255,
                             (palette[n * 3 + 1] * 100 + 127) / 255,
                             (palette[n * 3 + 2] * 100 + 127) / 255);
            if (nwrite <= 0) {
                RelinquishNodesAndMap;
                return (MagickFalse);
            }
            sixel_advance(context, nwrite);
            if (nwrite <= 0) {
                RelinquishNodesAndMap;
                return (MagickFalse);
            }
        }
    }

    for (y = i = 0; y < (ssize_t) height; y++) {
        for (x = 0; x < (ssize_t) width; x++) {
            pix = pixels[y * width + x];
            if (pix >= 0 && pix < (ssize_t) ncolors && pix != keycolor) {
                map[pix * width + x] |= (1 << i);
            }
        }

        if (++i < 6 && (y + 1) < (ssize_t) height) {
            continue;
        }

        for (c = 0; c < (ssize_t) ncolors; c++) {
            for (left = 0; left < (ssize_t) width; left++) {
                if (*(map + c * width + left) == 0) {
                    continue;
                }

                for (right = left + 1; right < (ssize_t) width; right++) {
                    if (*(map + c * width + right) != 0) {
                        continue;
                    }

                    for (n = 1; (right + n) < (ssize_t) width; n++) {
                        if (*(map + c * width + right + n) != 0) {
                            break;
                        }
                    }

                    if (n >= 10 || right + n >= (ssize_t) width) {
                        break;
                    }
                    right = right + n - 1;
                }

                if ((np = context->node_free) != NULL) {
                    context->node_free = np->next;
                } else if ((np = (sixel_node_t *)AcquireMagickMemory(sizeof(sixel_node_t))) == NULL) {
                    RelinquishNodesAndMap;
                    return (MagickFalse);
                }

                np->color = c;
                np->left = left;
                np->right = right;
                np->map = map + c * width;

                top.next = context->node_top;
                tp = ⊤

                while (tp->next != NULL) {
                    if (np->left < tp->next->left) {
                        break;
                    }
                    if (np->left == tp->next->left && np->right > tp->next->right) {
                        break;
                    }
                    tp = tp->next;
                }

                np->next = tp->next;
                tp->next = np;
                context->node_top = top.next;

                left = right - 1;
            }

        }

        for (x = 0; (np = context->node_top) != NULL;) {
            if (x > np->left) {
                /* DECGCR Graphics Carriage Return */
                context->buffer[context->pos] = '$';
                sixel_advance(context, 1);
                x = 0;
            }

            x = sixel_put_node(context, x, np, (int) ncolors, keycolor);
            sixel_node_del(context, np);
            np = context->node_top;

            while (np != NULL) {
                if (np->left < x) {
                    np = np->next;
                    continue;
                }

                x = sixel_put_node(context, x, np, (int) ncolors, keycolor);
                sixel_node_del(context, np);
                np = context->node_top;
            }
        }

        /* DECGNL Graphics Next Line */
        context->buffer[context->pos] = '-';
        sixel_advance(context, 1);
        if (nwrite <= 0) {
            RelinquishNodesAndMap;
            return (MagickFalse);
        }

        i = 0;
        (void) ResetMagickMemory(map, 0, len);
    }

    if (context->has_8bit_control) {
        context->buffer[context->pos] = 0x9c;
        sixel_advance(context, 1);
    } else {
        context->buffer[context->pos] = 0x1b;
        context->buffer[context->pos + 1] = '\\';
        sixel_advance(context, 2);
    }
    if (nwrite <= 0) {
        RelinquishNodesAndMap;
        return (MagickFalse);
    }

    /* flush buffer */
    if (context->pos > 0) {
        WriteBlob(context->image,context->pos,context->buffer);
    }

    RelinquishNodesAndMap;

    return(MagickTrue);
}


int CLASS median4(int *p)
{
  int min, max, sum, i;

  min = max = sum = p[0];
  for (i = 1; i < 4; i++)
  {
    sum += p[i];
    if (min > p[i])
      min = p[i];
    if (max < p[i])
      max = p[i];
  }
  return (sum - min - max) >> 1;
}


bool RenderFrameHostImpl::CanExecuteJavaScript() {
  return g_allow_injecting_javascript ||
         !frame_tree_node_->current_url().is_valid() ||
         frame_tree_node_->current_url().SchemeIs(kChromeDevToolsScheme) ||
         ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
             GetProcess()->GetID()) ||
         (frame_tree_node_->current_url().spec() == url::kAboutBlankURL) ||
         (delegate_->GetAsWebContents() == nullptr);
}


static int has_valid_directory_prefix(wchar_t *wfilename)
{
	int n = wcslen(wfilename);

	while (n > 0) {
		wchar_t c = wfilename[--n];
		DWORD attributes;

		if (!is_dir_sep(c))
			continue;

		wfilename[n] = L'\0';
		attributes = GetFileAttributesW(wfilename);
		wfilename[n] = c;
		if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
				attributes == FILE_ATTRIBUTE_DEVICE)
			return 1;
		if (attributes == INVALID_FILE_ATTRIBUTES)
			switch (GetLastError()) {
			case ERROR_PATH_NOT_FOUND:
				continue;
			case ERROR_FILE_NOT_FOUND:
				/* This implies parent directory exists. */
				return 1;
			}
		return 0;
	}
	return 1;
}


static int set_metadata_float ( AVDictionary * * dict , const char * key , float value , int allow_zero ) {
 if ( value != 0 || allow_zero ) {
 char tmp [ 64 ] ;
 snprintf ( tmp , sizeof ( tmp ) , "%f" , value ) ;
 return av_dict_set ( dict , key , tmp , 0 ) ;
 }
 return 0 ;
 }


static int __unmap_and_move(struct page *page, struct page *newpage,
				int force, enum migrate_mode mode)
{
	int rc = -EAGAIN;
	int page_was_mapped = 0;
	struct anon_vma *anon_vma = NULL;
	bool is_lru = !__PageMovable(page);

	if (!trylock_page(page)) {
		if (!force || mode == MIGRATE_ASYNC)
			goto out;

		/*
		 * It's not safe for direct compaction to call lock_page.
		 * For example, during page readahead pages are added locked
		 * to the LRU. Later, when the IO completes the pages are
		 * marked uptodate and unlocked. However, the queueing
		 * could be merging multiple pages for one bio (e.g.
		 * mpage_readpages). If an allocation happens for the
		 * second or third page, the process can end up locking
		 * the same page twice and deadlocking. Rather than
		 * trying to be clever about what pages can be locked,
		 * avoid the use of lock_page for direct compaction
		 * altogether.
		 */
		if (current->flags & PF_MEMALLOC)
			goto out;

		lock_page(page);
	}

	if (PageWriteback(page)) {
		/*
		 * Only in the case of a full synchronous migration is it
		 * necessary to wait for PageWriteback. In the async case,
		 * the retry loop is too short and in the sync-light case,
		 * the overhead of stalling is too much
		 */
		if (mode != MIGRATE_SYNC) {
			rc = -EBUSY;
			goto out_unlock;
		}
		if (!force)
			goto out_unlock;
		wait_on_page_writeback(page);
	}

	/*
	 * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
	 * we cannot notice that anon_vma is freed while we migrates a page.
	 * This get_anon_vma() delays freeing anon_vma pointer until the end
	 * of migration. File cache pages are no problem because of page_lock()
	 * File Caches may use write_page() or lock_page() in migration, then,
	 * just care Anon page here.
	 *
	 * Only page_get_anon_vma() understands the subtleties of
	 * getting a hold on an anon_vma from outside one of its mms.
	 * But if we cannot get anon_vma, then we won't need it anyway,
	 * because that implies that the anon page is no longer mapped
	 * (and cannot be remapped so long as we hold the page lock).
	 */
	if (PageAnon(page) && !PageKsm(page))
		anon_vma = page_get_anon_vma(page);

	/*
	 * Block others from accessing the new page when we get around to
	 * establishing additional references. We are usually the only one
	 * holding a reference to newpage at this point. We used to have a BUG
	 * here if trylock_page(newpage) fails, but would like to allow for
	 * cases where there might be a race with the previous use of newpage.
	 * This is much like races on refcount of oldpage: just don't BUG().
	 */
	if (unlikely(!trylock_page(newpage)))
		goto out_unlock;

	if (unlikely(!is_lru)) {
		rc = move_to_new_page(newpage, page, mode);
		goto out_unlock_both;
	}

	/*
	 * Corner case handling:
	 * 1. When a new swap-cache page is read into, it is added to the LRU
	 * and treated as swapcache but it has no rmap yet.
	 * Calling try_to_unmap() against a page->mapping==NULL page will
	 * trigger a BUG.  So handle it here.
	 * 2. An orphaned page (see truncate_complete_page) might have
	 * fs-private metadata. The page can be picked up due to memory
	 * offlining.  Everywhere else except page reclaim, the page is
	 * invisible to the vm, so the page can not be migrated.  So try to
	 * free the metadata, so the page can be freed.
	 */
	if (!page->mapping) {
		VM_BUG_ON_PAGE(PageAnon(page), page);
		if (page_has_private(page)) {
			try_to_free_buffers(page);
			goto out_unlock_both;
		}
	} else if (page_mapped(page)) {
		/* Establish migration ptes */
		VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
				page);
		try_to_unmap(page,
			TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
		page_was_mapped = 1;
	}

	if (!page_mapped(page))
		rc = move_to_new_page(newpage, page, mode);

	if (page_was_mapped)
		remove_migration_ptes(page,
			rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);

out_unlock_both:
	unlock_page(newpage);
out_unlock:
	/* Drop an anon_vma reference if we took one */
	if (anon_vma)
		put_anon_vma(anon_vma);
	unlock_page(page);
out:
	/*
	 * If migration is successful, decrease refcount of the newpage
	 * which will not free the page because new page owner increased
	 * refcounter. As well, if it is LRU page, add the page to LRU
	 * list in here.
	 */
	if (rc == MIGRATEPAGE_SUCCESS) {
		if (unlikely(__PageMovable(newpage)))
			put_page(newpage);
		else
			putback_lru_page(newpage);
	}

	return rc;
}


smp_prefetch_http(struct proxy *px, struct session *s, void *l7, unsigned int opt,
                  const struct arg *args, struct sample *smp, int req_vol)
{
	struct http_txn *txn = l7;
	struct http_msg *msg = &txn->req;

	/* Note: hdr_idx.v cannot be NULL in this ACL because the ACL is tagged
	 * as a layer7 ACL, which involves automatic allocation of hdr_idx.
	 */

	if (unlikely(!s || !txn))
		return 0;

	/* Check for a dependency on a request */
	smp->type = SMP_T_BOOL;

	if ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) {
		if (unlikely(!s->req))
			return 0;

		/* If the buffer does not leave enough free space at the end,
		 * we must first realign it.
		 */
		if (s->req->buf->p > s->req->buf->data &&
		    s->req->buf->i + s->req->buf->p > s->req->buf->data + s->req->buf->size - global.tune.maxrewrite)
			buffer_slow_realign(s->req->buf);

		if (unlikely(txn->req.msg_state < HTTP_MSG_BODY)) {
			if (msg->msg_state == HTTP_MSG_ERROR)
				return 0;

			/* Try to decode HTTP request */
			if (likely(msg->next < s->req->buf->i))
				http_msg_analyzer(msg, &txn->hdr_idx);

			/* Still no valid request ? */
			if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
				if ((msg->msg_state == HTTP_MSG_ERROR) ||
				    buffer_full(s->req->buf, global.tune.maxrewrite)) {
					return 0;
				}
				/* wait for final state */
				smp->flags |= SMP_F_MAY_CHANGE;
				return 0;
			}

			/* OK we just got a valid HTTP request. We have some minor
			 * preparation to perform so that further checks can rely
			 * on HTTP tests.
			 */

			/* If the request was parsed but was too large, we must absolutely
			 * return an error so that it is not processed. At the moment this
			 * cannot happen, but if the parsers are to change in the future,
			 * we want this check to be maintained.
			 */
			if (unlikely(s->req->buf->i + s->req->buf->p >
				     s->req->buf->data + s->req->buf->size - global.tune.maxrewrite)) {
				msg->msg_state = HTTP_MSG_ERROR;
				smp->data.uint = 1;
				return 1;
			}

			txn->meth = find_http_meth(msg->chn->buf->p, msg->sl.rq.m_l);
			if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
				s->flags |= SN_REDIRECTABLE;

			if (unlikely(msg->sl.rq.v_l == 0) && !http_upgrade_v09_to_v10(txn))
				return 0;
		}

		if (req_vol && txn->rsp.msg_state != HTTP_MSG_RPBEFORE) {
			return 0;  /* data might have moved and indexes changed */
		}

		/* otherwise everything's ready for the request */
	}
	else {
		/* Check for a dependency on a response */
		if (txn->rsp.msg_state < HTTP_MSG_BODY) {
			smp->flags |= SMP_F_MAY_CHANGE;
			return 0;
		}
	}

	/* everything's OK */
	smp->data.uint = 1;
	return 1;
}


static int tight_fill_palette(VncState *vs, int x, int y,

                              size_t count, uint32_t *bg, uint32_t *fg,

                              struct QDict **palette)

{

    int max;

    max = count / tight_conf[vs->tight_compression].idx_max_colors_divisor;

    if (max < 2 &&

        count >= tight_conf[vs->tight_compression].mono_min_rect_size) {

        max = 2;

    }

    if (max >= 256) {

        max = 256;

    }

    switch(vs->clientds.pf.bytes_per_pixel) {

    case 4:

        return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);

    case 2:

        return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);

    default:

        max = 2;

        return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);

    }

    return 0;

}