Beispiel #1
0
static void push_node(lua_State *L, const GumboNode *node) {
    luaL_checkstack(L, 10, "Unable to allocate Lua stack space");
    switch (node->type) {
    case GUMBO_NODE_ELEMENT: {
        const GumboElement *element = &node->v.element;
        lua_createtable(L, 0, 7);
        set_tag(L, element);
        set_sourcepos(L, element->start_pos);
        if (node->parse_flags != GUMBO_INSERTION_NORMAL) {
            set_integer(L, "parseFlags", node->parse_flags);
        }
        set_attributes(L, &element->attributes);
        set_children(L, &element->children, 1);
        setmetatable(L, Element);
        return;
    }
    case GUMBO_NODE_TEMPLATE: {
        const GumboElement *element = &node->v.element;
        lua_createtable(L, 0, 8);
        set_literal(L, "localName", "template");
        set_sourcepos(L, element->start_pos);
        set_attributes(L, &element->attributes);
        lua_createtable(L, 0, 0);
        setmetatable(L, NodeList);
        lua_setfield(L, -2, "childNodes");
        lua_createtable(L, 0, 1);
        set_children(L, &element->children, 1);
        setmetatable(L, DocumentFragment);
        lua_setfield(L, -2, "content");
        setmetatable(L, Element);
        return;
    }
    case GUMBO_NODE_TEXT:
        create_text_node(L, &node->v.text, Text);
        return;
    case GUMBO_NODE_WHITESPACE:
        create_text_node(L, &node->v.text, Text);
        set_literal(L, "type", "whitespace");
        return;
    case GUMBO_NODE_COMMENT:
        create_text_node(L, &node->v.text, Comment);
        return;
    case GUMBO_NODE_CDATA:
        create_text_node(L, &node->v.text, Text);
        set_literal(L, "type", "cdata");
        return;
    default:
        luaL_error(L, "GumboNodeType value out of bounds: %d", node->type);
        return;
    }
}
Beispiel #2
0
/***********************************************************************//**
 * @brief Read energy boundaries from XML element
 *
 * @param[in] xml XML element.
 *
 * @exception GException::invalid_value
 *            Invalid XML format encountered.
 *
 * Read energy boundaries from an XML element. The format of the energy
 * boundaries is
 *
 *     <parameter name="EnergyBoundaries" emin="0.1" emax="10.0"/>
 *
 * The units of the @a emin and @a emax parameters are MeV.
 ***************************************************************************/
void GEbounds::read(const GXmlElement& xml)
{
    // Clear energy boundaries
    clear();

    // Get energy boundaries parameter
    const GXmlElement* par = gammalib::xml_get_par(G_READ_XML, xml,
                             "EnergyBoundaries");

    // Extract position attributes
    if (par->has_attribute("emin") && par->has_attribute("emax")) {
        double emin = gammalib::todouble(par->attribute("emin"));
        double emax = gammalib::todouble(par->attribute("emax"));
        append(GEnergy(emin, "MeV"), GEnergy(emax, "MeV"));
    }
    else {
        std::string msg = "Attributes \"emin\" and/or \"emax\" not found"
                          " in XML parameter \"EnergyBoundaries\"."
                          " Please verify the XML format.";
        throw GException::invalid_value(G_READ_XML, msg);
    }

    // Set attribues
    set_attributes();

    // Return
    return;
}
Beispiel #3
0
/***********************************************************************//**
 * @brief Set logarithmically spaced energy intervals
 *
 * @param[in] num Number of energy intervals.
 * @param[in] emin Minimum energy of first interval.
 * @param[in] emax Maximum energy of last interval.
 *
 * Creates @p num logarithmically spaced energy boundaries running from
 * @p emin to @p emax.
 ***************************************************************************/
void GEbounds::set_log(const int& num, const GEnergy& emin, const GEnergy& emax)
{
    // Initialise members
    clear();

    // Compute bin width
    double elogmin = std::log10(emin.MeV());
    double elogmax = std::log10(emax.MeV());
    double elogbin = (elogmax - elogmin)/double(num);

    // Append boundaries
    GEnergy min;
    GEnergy max;
    for (int i = 0; i < num; ++i) {
        min.MeV(std::pow(10.0, double(i)*elogbin   + elogmin));
        max.MeV(std::pow(10.0, double(i+1)*elogbin + elogmin));
        append(min, max);
    }

    // Set attributes
    set_attributes();

    // Return
    return;
}
Beispiel #4
0
void
InputParameters::applyParameters(const InputParameters & common)
{
  // Loop through the common parameters
  for (InputParameters::const_iterator it = common.begin(); it != common.end(); ++it)
  {
    // Common parameter name
    const std::string & common_name = it->first;

    // Extract the properties from the local parameter for the current common parameter name
    bool local_exist = _values.find(common_name) != _values.end();
    bool local_set   = _set_by_add_param.find(common_name) == _set_by_add_param.end();
    bool local_priv  = isPrivate(common_name);
    bool local_valid = isParamValid(common_name);

    // Extract the properties from the common parameter
    bool common_valid = common.isParamValid(common_name);
    bool common_priv  = common.isPrivate(common_name);

    /* In order to apply common parameter 4 statements must be satisfied
     * (1) A local parameter must exist with the same name as common parameter
     * (2) Common parameter must valid
     * (3) Local parameter must be invalid OR not have been set from its default
     * (4) Neither may be private
     */
    if ( local_exist && common_valid && (!local_valid || !local_set) && (!common_priv || !local_priv))
    {
      delete _values[common_name];
      _values[common_name] = it->second->clone();
      set_attributes(common_name, false);
    }
  }
}
Beispiel #5
0
/***********************************************************************//**
 * @brief Read Good Time Intervals and time reference from FITS table
 *
 * @param[in] table FITS table.
 *
 * Reads the Good Time Intervals and time reference from a FITS table.
 ***************************************************************************/
void GGti::read(const GFitsTable& table)
{
    // Free members
    free_members();

    // Initialise attributes
    init_members();

    // Read time reference
    m_reference.read(table);

    // Extract GTI information from FITS table
    m_num = table.integer("NAXIS2");
    if (m_num > 0) {

        // Set GTIs
        m_start = new GTime[m_num];
        m_stop  = new GTime[m_num];
        for (int i = 0; i < m_num; ++i) {
            m_start[i].set(table["START"]->real(i), m_reference);
            m_stop[i].set(table["STOP"]->real(i), m_reference);
        }

        // Set attributes
        set_attributes();

    }

    // Return
    return;
}
Beispiel #6
0
		Character::Character()
		{
			set_attributes();
			set_resources();
			set_behaviour();
			set_abilities();
			set_event_listeners();
		}
Beispiel #7
0
/***********************************************************************//**
 * @brief Insert energy interval
 *
 * @param[in] index Index after with interval is inserted.
 * @param[in] emin Minimum energy of interval.
 * @param[in] emax Maximum energy of interval.
 *
 * @exception GException::invalid_argument
 *            Minimum energy larger than maximum energy
 *
 * Inserts an energy interval after the specified @p index in the energy
 * boundaries. The method does not reorder the intervals by energy, instead
 * the client needs to determine the approriate @p index.
 *
 * Invalid parameters do not produce any exception, but are handled
 * transparently. If the interval is invalid (i.e. @p emin > @p emax) an
 * exception is thrown. If the @p index is out of the valid range, the
 * index will be adjusted to either the first or the last element.
 ***************************************************************************/
void GEbounds::insert_eng(const int&     index,
                          const GEnergy& emin,
                          const GEnergy& emax)
{
    // Throw an exception if energy interval is invalid
    if (emin > emax) {
        std::string msg = "Invalid energy interval specified. Minimum"
                          " energy "+emin.print(NORMAL)+" can not be"
                          " larger than maximum energy "+
                          emax.print(NORMAL)+".";
        throw GException::invalid_argument(G_INSERT_ENG, msg);
    }

    // Set index
    int inx = index;

    // If inx is out of range then adjust it
    if (inx < 0)     inx = 0;
    if (inx > m_num) inx = m_num;

    // Allocate new intervals
    int      num = m_num+1;
    GEnergy* min = new GEnergy[num];
    GEnergy* max = new GEnergy[num];

    // Copy intervals before index to be inserted
    for (int i = 0; i < inx; ++i) {
        min[i] = m_min[i];
        max[i] = m_max[i];
    }

    // Insert interval
    min[inx] = emin;
    max[inx] = emax;

    // Copy intervals after index to be inserted
    for (int i = inx+1; i < num; ++i) {
        min[i] = m_min[i-1];
        max[i] = m_max[i-1];
    }

    // Free memory
    if (m_min != NULL) delete [] m_min;
    if (m_max != NULL) delete [] m_max;

    // Set new memory
    m_min = min;
    m_max = max;

    // Set number of elements
    m_num = num;

    // Set attributes
    set_attributes();

    // Return
    return;
}
Beispiel #8
0
int
send_clear_command ()
{
  set_nl_header (SR_C_CLEAR);
  set_attributes ();
  if (sendto_fd (sd, (char *) &req, req.n.nlmsg_len) < 0)
    return -1;
  receive_response ();
  return 0;
}
Beispiel #9
0
static void do_extract(char *devname)
{
   struct stat statp;

   enable_backup_privileges(NULL, 1);

   jcr = setup_jcr("bextract", devname, bsr, director, VolumeName, 1); /* acquire for read */
   if (!jcr) {
      exit(1);
   }
   dev = jcr->read_dcr->dev;
   if (!dev) {
      exit(1);
   }
   dcr = jcr->read_dcr;

   /* Make sure where directory exists and that it is a directory */
   if (stat(where, &statp) < 0) {
      berrno be;
      Emsg2(M_ERROR_TERM, 0, _("Cannot stat %s. It must exist. ERR=%s\n"),
         where, be.bstrerror());
   }
   if (!S_ISDIR(statp.st_mode)) {
      Emsg1(M_ERROR_TERM, 0, _("%s must be a directory.\n"), where);
   }

   free(jcr->where);
   jcr->where = bstrdup(where);
   attr = new_attr(jcr);

   compress_buf = get_memory(compress_buf_size);

   acl_data.last_fname = get_pool_memory(PM_FNAME);
   xattr_data.last_fname = get_pool_memory(PM_FNAME);

   read_records(dcr, record_cb, mount_next_read_volume);
   /* If output file is still open, it was the last one in the
    * archive since we just hit an end of file, so close the file.
    */
   if (is_bopen(&bfd)) {
      set_attributes(jcr, attr, &bfd);
   }
   free_attr(attr);

   free_pool_memory(acl_data.last_fname);
   free_pool_memory(xattr_data.last_fname);

   clean_device(jcr->dcr);
   dev->term();
   free_dcr(dcr);
   free_jcr(jcr);

   printf(_("%u files restored.\n"), num_files);
   return;
}
Beispiel #10
0
/***********************************************************************//**
 * @brief Insert Good Time Interval
 *
 * @param[in] index Index after which interval is inserted.
 * @param[in] tstart Start time of interval.
 * @param[in] tstop Stop time of interval.
 *
 * @exception GException::invalid_argument
 *            Start time later than stop time
 *
 * Inserts a Good Time Interval after the specified @p index in the Good
 * Time Intervals. The method does not reorder the intervals by time,
 * instead the client needs to determine the approriate @p index.
 *
 * Invalid parameters do not produce any exception, but are handled
 * transparently. If the interval is invalid (i.e. @p tstart > @p tstop)
 * an exception is thrown. If the @p index is out of the valid range, the
 * index will be adjusted to either the first or the last element.
 ***************************************************************************/
void GGti::insert_gti(const int& index, const GTime& tstart, const GTime& tstop)
{
    // Throw an exception if time interval is invalid
    if (tstart > tstop) {
        std::string msg = "Invalid time interval specified. Start time "+
                          tstart.print(NORMAL)+" can not be later than "
                          "stop time "+tstop.print(NORMAL)+".";
        throw GException::invalid_argument(G_INSERT_GTI, msg);
    }

    // Set index
    int inx = index;

    // If inx is out of range then adjust it
    if (inx < 0)     inx = 0;
    if (inx > m_num) inx = m_num;

    // Allocate new intervals
    int    num   = m_num+1;
    GTime* start = new GTime[num];
    GTime* stop  = new GTime[num];

    // Copy intervals before GTI to be inserted
    for (int i = 0; i < inx; ++i) {
        start[i] = m_start[i];
        stop[i]  = m_stop[i];
    }

    // Insert GTI
    start[inx] = tstart;
    stop[inx]  = tstop;

    // Copy intervals after GTI to be inserted
    for (int i = inx+1; i < num; ++i) {
        start[i] = m_start[i-1];
        stop[i]  = m_stop[i-1];
    }

    // Free memory
    if (m_start != NULL) delete [] m_start;
    if (m_stop  != NULL) delete [] m_stop;

    // Set new memory
    m_start = start;
    m_stop  = stop;

    // Set number of elements
    m_num = num;
    
    // Set attributes
    set_attributes();

    // Return
    return;
}
// Recursively set the attributes that will be printed starting at a tree root
void set_attributes_recur (astree *root) {
   if (root == NULL) return;
   if (root->children.empty()) {
      return;
   } else {
      for (auto &child : root->children) {
         set_attributes(child);
         set_attributes_recur(child);
      }
   }
}
Beispiel #12
0
static int search_iterator(lua_State *L)
{
  LDAPMessage *result, *message, *entry;
  lua_apr_ldap_object *object;
  struct timeval *timeout;
  int status, msgid;

  object = lua_touserdata(L, lua_upvalueindex(1));
  msgid = lua_tointeger(L, lua_upvalueindex(2));
  timeout = lua_touserdata(L, lua_upvalueindex(3));
  status = ldap_result(object->ldap, msgid, LDAP_MSG_ONE, timeout, &result);

  if (status == 0)
    raise_error_status(L, APR_TIMEUP);
  else if (status == -1)
    /* TODO Can we get a more specific error (message) here? ld_errno? */
    raise_error_message(L, "Unspecified error");
  else if (status == LDAP_RES_SEARCH_RESULT) {
    /* end of search results */
    return 0;
  } else {
    message = ldap_first_message(object->ldap, result);
    switch (ldap_msgtype(message)) {
      case LDAP_RES_SEARCH_ENTRY:
        entry = ldap_first_entry(object->ldap, message);
        push_distinguished_name(L, object->ldap, entry);
        lua_newtable(L);
        set_attributes(L, object->ldap, entry, lua_gettop(L));
        ldap_msgfree(result);
        return 2;
      /* No reference to LDAP_RES_SEARCH_REFERENCE on MSDN. Maybe is has a replacement? */
#     ifdef LDAP_RES_SEARCH_REFERENCE
      case LDAP_RES_SEARCH_REFERENCE: {
        LDAPMessage *reference = ldap_first_reference(object->ldap, message);
        push_distinguished_name(L, object->ldap, reference); /* is this supposed to work? */
        ldap_msgfree(result);
        return 1;
      }
#     endif
      case LDAP_RES_SEARCH_RESULT:
        /* end of search results */
        ldap_msgfree(result);
        return 0;
      default:
        ldap_msgfree(result);
        raise_error_message(L, "unhandled message type in search results");
    }
  }

  /* shouldn't be reached. */
  ldap_msgfree(result);
  return 0;
}
Beispiel #13
0
void
InputParameters::applyParameters(const InputParameters & common)
{
  // Disable the display of deprecated message when applying common parameters, this avoids a dump of messages
  _show_deprecated_message = false;

  // Loop through the common parameters
  for (InputParameters::const_iterator it = common.begin(); it != common.end(); ++it)
  {
    // Common parameter name
    const std::string & common_name = it->first;

    // Extract the properties from the local parameter for the current common parameter name
    bool local_exist = _values.find(common_name) != _values.end();
    bool local_set   = _set_by_add_param.find(common_name) == _set_by_add_param.end();
    bool local_priv  = isPrivate(common_name);
    bool local_valid = isParamValid(common_name);

    // Extract the properties from the common parameter
    bool common_valid = common.isParamValid(common_name);
    bool common_priv  = common.isPrivate(common_name);

    /* In order to apply common parameter 4 statements must be satisfied
     * (1) A local parameter must exist with the same name as common parameter
     * (2) Common parameter must valid
     * (3) Local parameter must be invalid OR not have been set from its default
     * (4) Neither may be private
     */
    if ( local_exist && common_valid && (!local_valid || !local_set) && (!common_priv || !local_priv))
    {
      delete _values[common_name];
      _values[common_name] = it->second->clone();
      set_attributes(common_name, false);
    }
  }

  // Loop through the coupled variables
  for (std::set<std::string>::const_iterator it = common.coupledVarsBegin(); it != common.coupledVarsEnd(); ++it)
  {
    // If the local parameters has a coupled variable, populate it with the value from the common parameters
    const std::string var_name = *it;
    if (hasCoupledValue(var_name))
    {
      if (common.hasDefaultCoupledValue(var_name))
        addCoupledVar(var_name, common.defaultCoupledValue(var_name), common.getDocString(var_name));
      else
        addCoupledVar(var_name, common.getDocString(var_name));
    }
  }

  // Enable deprecated message printing
  _show_deprecated_message = true;
}
Beispiel #14
0
int ansi_buf::overflow(int c)
{
    if(c == EOF)
        return 0;

    if(m_processing_ansi == 1)
    {
        if( c == '[' )	// Code terminator
        {
            m_code = "";
            m_attributes = 0;
            m_processing_ansi = 2;
            return(0);
        }
        else
            m_processing_ansi = 0;
    }

    if(m_processing_ansi == 2)
    {
        if( c == ';' )	// Code terminator
        {
            process_code();
            m_code = "";
            return(0);
        }
        else if( c == 'm' )
        {
            m_processing_ansi = false;
            process_code();
            set_attributes();
            return(0);
        }
        else
        {
            m_code.append(reinterpret_cast<char*>(&c), 1);
            return(0);
        }
    }

    if(c == '\033')
    {
        m_processing_ansi = 1;
        m_code = "";
        return(0);
    }

    return m_streambuf->sputc(c);
}
void Dectree_class::train(const cv::Mat& training_data, const cv::Mat& labels, int depth_thresh, unsigned int samples_thresh)
{
	//determine the number of classes based on the training data
	get_classes(labels);
	//std::cout << "Classes:\n" << classes << std::endl;
	//make a vector giving an id to each attribute
	set_attributes(training_data);
	//for debbugging
	/*
	for(std::vector<int>::iterator it = attributes.begin(); it != attributes.end(); ++it)
		std::cout << *it << " ";
	std::cout << std::endl;
	*/
	//compute the initial impurity just fot debugging
	//double hgoal = compute_entropy(labels);
	//std::cout << "Initial entropy: " << hgoal << std::endl;
	//grow a decision tree
	depth_limit = depth_thresh;
	min_samples = samples_thresh;
	int depth = 1;
	dbst.set_root(learn_dectree(cv::Mat(),labels, training_data, attributes, depth));
	find_depth(dbst.get_root());
	std::cout << "min depth: " << min_depth << std::endl;
	//for debugging
	//print the obtained tree
	/*
	std::cout<< "\ninOrder traversal: " << std::endl;
	dbst.inOrder(dbst.get_root());
	std::cout << std::endl;
	std::cout<< "\npostOrder traversal: " << std::endl;
	dbst.postOrder(dbst.get_root());	
	std::cout << std::endl;
	*/

	//only for testing
	/*
	int a = plurality(labels);
	std::cout << "Best class: " << a << std::endl;
	bool b = check_classif(labels);
	std::cout << "All same class?: " << b << std::endl;
	dectree_split* t = best_split(attributes, training_data, labels);
	std::cout << "Best attr: " << t->attr_name << " Pos: " << t->attr_idx << std::endl;
	std::cout << t->neg_attr_labels << std::endl;
	std::cout << t->neg_attr_data << std::endl;
	std::cout << t->pos_attr_labels << std::endl;
	std::cout << t->pos_attr_data << std::endl;
	*/
}
Beispiel #16
0
static bool first_open(
	rtems_termios_tty *tty,
	rtems_termios_device_context *base,
	struct termios *term,
	rtems_libio_open_close_args_t *args
)
{
	struct apbuart_priv *uart = base_get_priv(base);

	uart->tty = tty;

	/* Inherit UART hardware parameters from bootloader on system console */
	if (uart->condev.flags & CONSOLE_FLAG_SYSCON_GRANT) {
		get_attributes(base, term);
		term->c_oflag |= ONLCR;
		set_attributes(base, term);
	}

	/* Enable TX/RX */
	uart->regs->ctrl |= APBUART_CTRL_RE | APBUART_CTRL_TE;

	if (uart->mode != TERMIOS_POLLED) {
		int ret;
		uint32_t ctrl;

		/* Register interrupt and enable it */
		ret = drvmgr_interrupt_register(
			uart->dev, 0, uart->devName, apbuart_cons_isr, tty
		);
		if (ret) {
			return false;
		}

		uart->sending = 0;

		/* Turn on RX interrupts */
		ctrl = uart->regs->ctrl;
		ctrl |= APBUART_CTRL_RI;
		if (uart->cap & CAP_DI) {
			/* Use RX FIFO interrupt only if delayed interrupt available. */
			ctrl |= (APBUART_CTRL_DI | APBUART_CTRL_RF);
		}
		uart->regs->ctrl = ctrl;
	}

	return true;
}
Beispiel #17
0
/***********************************************************************//**
 * @brief Append Good Time Intervals
 *
 * @param[in] gti Good Time Intervals.
 *
 * Append Good Time Intervals to the container. The method performs automatic
 * time reference conversion in case that the specified Good Time Intervals
 * @p gti have a time reference that differs from that of the current
 * instance.
 ***************************************************************************/
void GGti::extend(const GGti& gti)
{
    // Do nothing if Good Time Intervals are empty
    if (!gti.is_empty()) {

        // Allocate new intervals
        int    num   = m_num+gti.size();
        GTime* start = new GTime[num];
        GTime* stop  = new GTime[num];

        // Initialise index
        int inx = 0;
        
        // Copy existing intervals
        for (; inx < m_num; ++inx) {
            start[inx] = m_start[inx];
            stop[inx]  = m_stop[inx];
        }

        // Append intervals. Convert to GTI reference on the fly.
        for (int i = 0; i < gti.size(); ++i, ++inx) {
            double tstart = gti.m_start[i].convert(gti.reference());
            double tstop  = gti.m_stop[i].convert(gti.reference());
            start[inx].set(tstart, this->reference());
            stop[inx].set(tstop,   this->reference());
        }

        // Free memory
        if (m_start != NULL) delete [] m_start;
        if (m_stop  != NULL) delete [] m_stop;

        // Set new memory
        m_start = start;
        m_stop  = stop;

        // Set number of elements
        m_num = num;

        // Set attributes
        set_attributes();

    } // endif: Good Time Intervals were not empty

    // Return
    return;
}
//main method to train the decision treee
void Dectree_class::train(const cv::Mat& training_data, const cv::Mat& labels, int depth_thresh, unsigned int samples_thresh, int vars_per_node)
{
	//---(1)initialize random generator if no external is given---//
	if(!is_ext_rng)
	{
		rng = cv::RNG(time(NULL));
		//std::cout << "No ext rng" << std::endl;
	}

	//---(2)determine the number of classes based on the training data---//
	set_classes(labels);
	//std::cout << "Classes:\n" << classes << std::endl;

	//---(3)make a vector giving an id to each attribute---//
	set_attributes(training_data);
	//for debbugging
	/*
	for(std::vector<int>::iterator it = attributes.begin(); it != attributes.end(); ++it)
		std::cout << *it << " ";
	std::cout << std::endl;
	*/

	//---(4)verify constraints---//
	//maximum depth
	if(depth_thresh < 0)
		depth_limit = std::numeric_limits<int>::max();
	else
		depth_limit = depth_thresh;
	//minimum samples
	min_samples = samples_thresh;
	//active variables
	if(attributes.size() < (unsigned)vars_per_node)
		active_vars = attributes.size();
	else
		active_vars = vars_per_node;
	//maximum number of split fails
	max_split_fail = attributes.size();

	//---(5)train the tree---//
	int depth = 1;
	int no_split_fail = 0;
	dbst.set_root(learn_dectree(cv::Mat(),labels, training_data, depth, no_split_fail));
	find_depth(dbst.get_root()); //to find the real-true depth of the created tree

}
Beispiel #19
0
/***********************************************************************//**
 * @brief Append energy boundaries
 *
 * @param[in] ebds Energy boundaries.
 *
 * Append energy boundaries to the container.
 ***************************************************************************/
void GEbounds::extend(const GEbounds& ebds)
{
    // Do nothing if energy boundaries are empty
    if (!ebds.is_empty()) {

        // Allocate new intervals
        int      num = m_num+ebds.size();
        GEnergy* min = new GEnergy[num];
        GEnergy* max = new GEnergy[num];

        // Initialise index
        int inx = 0;

        // Copy existing intervals
        for (; inx < m_num; ++inx) {
            min[inx] = m_min[inx];
            max[inx] = m_max[inx];
        }

        // Append intervals
        for (int i = 0; i < ebds.size(); ++i, ++inx) {
            min[inx] = ebds.m_min[i];
            max[inx] = ebds.m_max[i];
        }

        // Free memory
        if (m_min != NULL) delete [] m_min;
        if (m_max != NULL) delete [] m_max;

        // Set new memory
        m_min = min;
        m_max = max;

        // Set number of elements
        m_num = num;

        // Set attributes
        set_attributes();

    } // endif: energy boundaries were not empty

    // Return
    return;
}
Beispiel #20
0
/***********************************************************************//**
 * @brief Read energy boundaries from FITS table
 *
 * @param[in] table FITS table.
 *
 * Reads the energy boundaries from a FITS table. The method interprets the
 * energy units provide in the FITS header. If no energy units are found it
 * is assumed that the energies are stored in units of keV.
 ***************************************************************************/
void GEbounds::read(const GFitsTable& table)
{
    // Free members
    free_members();

    // Initialise attributes
    init_members();

    // Extract energy boundary information from FITS table
    m_num = table.integer("NAXIS2");
    if (m_num > 0) {

        // Allocate memory
        m_min = new GEnergy[m_num];
        m_max = new GEnergy[m_num];

        // Get units
        std::string emin_unit = table["E_MIN"]->unit();
        std::string emax_unit = table["E_MAX"]->unit();
        if (emin_unit.empty()) {
            emin_unit = "keV";
        }
        if (emax_unit.empty()) {
            emax_unit = "keV";
        }

        // Copy information
        for (int i = 0; i < m_num; ++i) {
            m_min[i](table["E_MIN"]->real(i), emin_unit);
            m_max[i](table["E_MAX"]->real(i), emax_unit);
        }

        // Set attributes
        set_attributes();

    } // endif: there were channels to read

    // Return
    return;
}
Beispiel #21
0
void WidgetWindow::bind() {

/*
    WindowRep& wr = *rep();
    Display& d = *wr.display_;

    if (xbound(xwindow_)) {
	display_->unbind(xwindow_);
    }
    set_attributes();

    (*GlyphwidgetClassRec.core_class.superclass->core_class.realize)(
	(Widget)widget_, &xattrmask_, &xattrs_
    );

    xwindow_ = widget_->core.window;
    display_->bind(xwindow_, this);
*/

    WindowRep& wr = *((Window*)this)->rep();
    CanvasRep& c = *wr.canvas_->rep();
    Display& d = *wr.display_;
    WindowTable& t = *d.rep()->wtable_;

    if (wr.xwindow_ != WindowRep::unbound) {
        t.remove(wr.xwindow_);
    }
    set_attributes();

    (*GlyphwidgetClassRec.core_class.superclass->core_class.realize)(
	(Widget)widget_, &wr.xattrmask_, &wr.xattrs_
    );
    wr.xwindow_ = widget_->core.window;

    c.xdrawable_ = wr.xwindow_;
    t.insert(wr.xwindow_, this);
    wr.xtoplevel_ = wr.toplevel_->rep()->xwindow_;
}
Beispiel #22
0
/***********************************************************************//**
 * @brief Set linearly spaced energy intervals
 *
 * @param[in] num Number of energy intervals.
 * @param[in] emin Minimum energy of first interval.
 * @param[in] emax Maximum energy of last interval.
 *
 * Creates @p num linearly spaced energy boundaries running from @p emin to
 * @p emax.
 ***************************************************************************/
void GEbounds::set_lin(const int& num, const GEnergy& emin, const GEnergy& emax)
{
    // Initialise members
    clear();

    // Compute bin width
    GEnergy ebin = (emax - emin)/double(num);

    // Append boundaries
    GEnergy min = emin;
    GEnergy max = emin + ebin;
    for (int i = 0; i < num; ++i) {
        append(min, max);
        min += ebin;
        max += ebin;
    }

    // Set attributes
    set_attributes();

    // Return
    return;
}
Beispiel #23
0
/***********************************************************************//**
 * @brief Remove energy interval
 *
 * @param[in] index Energy interval index (0,...,size()-1).
 *
 * Removes energy interval at @p index from the energy boundaries container.
 * All intervals after the specified @p index are moved forward by one
 * position.
 *
 * Note that the method does not actually reduce the memory size but just
 * updates the information on the number of elements in the array.
 ***************************************************************************/
void GEbounds::remove(const int& index)
{
#if defined(G_RANGE_CHECK)
    // If index is outside boundary then throw an error
    if (index < 0 || index >= m_num) {
        throw GException::out_of_range(G_REMOVE, index, 0, m_num-1);
    }
#endif

    // Move all elements located after index forward
    for (int i = index+1; i < m_num; ++i) {
        m_min[i-1] = m_min[i];
        m_min[i-1] = m_max[i];
    }

    // Reduce number of elements by one
    m_num--;

    // Update attributes
    set_attributes();

    // Return
    return;
}
Beispiel #24
0
int console_putchar(int c)
{
    static short saved_x = 0;
    static short saved_y = 0;
    static int esc_seq = 0;
    static int esc_num = 0;
    static int prefix_pit = 0;
    static int esc_arg[MAX_ESC_ARGS + 1];

    c &= 0xff;

    if (esc_seq == 1) {
	if (c == '[') {
	    esc_seq++;
	    esc_num = 0;
	    prefix_pit = 0;
	} else
	    esc_seq = 0;
	return 0;
    } else if (esc_seq) {
	if (_isdigit(c)) {
	    if (!esc_num) {
		esc_num = (esc_num + 1) % MAX_ESC_ARGS;
		if (esc_num == 0) esc_num++;
		esc_arg[esc_num] = 0;
	    }
	    esc_arg[esc_num] = esc_arg[esc_num] * 10 + (c - '0');
	    return 0;
	} else {
	    if (c == ';') {
		esc_num = (esc_num + 1) % MAX_ESC_ARGS;
		if (esc_num == 0) esc_num++;
		esc_arg[esc_num] = 0;
		return 0;
	    }
	    switch (c) {
	    case '?':
		if (prefix_pit)
		    break;
		prefix_pit = 1;
		return 0;
	    case 'h':
		if (prefix_pit && esc_arg[1] == 25)
		    screen_cursor_enable(1);
		break;
	    case 'l':
		if (prefix_pit && esc_arg[1] == 25)
		    screen_cursor_enable(0);
		break;
	    case 'm':
		set_attributes(esc_num, esc_arg);
		break;
	    case 'H':
	    case 'f':
		if (esc_num > 1) {
		    con_y = esc_arg[1] - 1;
		    con_x = esc_arg[2] - 1;
		}
		break;
	    case 'A':
		con_y -= (esc_num >= 1)?esc_arg[1]:1;
		break;
	    case 'B':
		con_y += (esc_num >= 1)?esc_arg[1]:1;
		break;
	    case 'C':
		con_x += (esc_num >= 1)?esc_arg[1]:1;
		break;
	    case 'D':
		con_x -= (esc_num >= 1)?esc_arg[1]:1;
		break;
	    case 'J':
		if (esc_num >= 1) {
		    con_x = 0;
		    con_y = 0;
		    screen_clear();
		}
		break;
	    case 'K':
		break;
	    case 's':
		saved_x = con_x;
		saved_y = con_y;
		break;
	    case 'u':
		con_x = saved_x;
		con_y = saved_y;
		break;
	    }
	    esc_seq = 0;
	}
	if (con_x < 0) con_x = 0;
	if (con_x >= con_width) con_x = con_width - 1;
	if (con_y < 0) con_y = 0;
	if (con_y >= con_height) con_y = con_height - 1;
    } else {
	if (c == '\n') {
	    con_y++;
	    /* con_x = 0; */
	} else if (c == '\r')
	    con_x = 0;
	else if (c == '\t')
	    con_x += CON_TAB_WIDTH;
	else if (c == 0x1b) {
	    esc_seq = 1;
	    return 0;
	} else
	    screen_putchar(c, con_x++, con_y);
    }

    if (con_x >= con_width) {
	con_x = 0;
	con_y++;
    }
    if (con_y == con_height) {
	con_y--;
	/* vertical scroll */
	screen_scroll_up();
    }
    screen_cursor(con_x, con_y);
    return 0;
}
Beispiel #25
0
/*
 * Called here for each record from read_records()
 */
static bool record_cb(DCR *dcr, DEV_RECORD *rec)
{
   int status;
   JCR *jcr = dcr->jcr;

   if (rec->FileIndex < 0) {
      return true;                    /* we don't want labels */
   }

   /* File Attributes stream */

   switch (rec->maskedStream) {
   case STREAM_UNIX_ATTRIBUTES:
   case STREAM_UNIX_ATTRIBUTES_EX:

      /* If extracting, it was from previous stream, so
       * close the output file.
       */
      if (extract) {
         if (!is_bopen(&bfd)) {
            Emsg0(M_ERROR, 0, _("Logic error output file should be open but is not.\n"));
         }
         set_attributes(jcr, attr, &bfd);
         extract = false;
      }

      if (!unpack_attributes_record(jcr, rec->Stream, rec->data, rec->data_len, attr)) {
         Emsg0(M_ERROR_TERM, 0, _("Cannot continue.\n"));
      }

      if (file_is_included(ff, attr->fname) && !file_is_excluded(ff, attr->fname)) {
         attr->data_stream = decode_stat(attr->attr, &attr->statp, sizeof(attr->statp), &attr->LinkFI);
         if (!is_restore_stream_supported(attr->data_stream)) {
            if (!non_support_data++) {
               Jmsg(jcr, M_ERROR, 0, _("%s stream not supported on this Client.\n"),
                  stream_to_ascii(attr->data_stream));
            }
            extract = false;
            return true;
         }

         build_attr_output_fnames(jcr, attr);

         if (attr->type == FT_DELETED) { /* TODO: choose the right fname/ofname */
            Jmsg(jcr, M_INFO, 0, _("%s was deleted.\n"), attr->fname);
            extract = false;
            return true;
         }

         extract = false;
         status = create_file(jcr, attr, &bfd, REPLACE_ALWAYS);
         switch (status) {
         case CF_ERROR:
         case CF_SKIP:
            break;
         case CF_EXTRACT:
            extract = true;
            print_ls_output(jcr, attr);
            num_files++;
            fileAddr = 0;
            break;
         case CF_CREATED:
            set_attributes(jcr, attr, &bfd);
            print_ls_output(jcr, attr);
            num_files++;
            fileAddr = 0;
            break;
         }
      }
      break;

   case STREAM_RESTORE_OBJECT:
      /* nothing to do */
      break;

   /* Data stream and extracting */
   case STREAM_FILE_DATA:
   case STREAM_SPARSE_DATA:
   case STREAM_WIN32_DATA:

      if (extract) {
         if (rec->maskedStream == STREAM_SPARSE_DATA) {
            ser_declare;
            uint64_t faddr;
            wbuf = rec->data + OFFSET_FADDR_SIZE;
            wsize = rec->data_len - OFFSET_FADDR_SIZE;
            ser_begin(rec->data, OFFSET_FADDR_SIZE);
            unser_uint64(faddr);
            if (fileAddr != faddr) {
               fileAddr = faddr;
               if (blseek(&bfd, (boffset_t)fileAddr, SEEK_SET) < 0) {
                  berrno be;
                  Emsg2(M_ERROR_TERM, 0, _("Seek error on %s: %s\n"),
                     attr->ofname, be.bstrerror());
               }
            }
         } else {
            wbuf = rec->data;
            wsize = rec->data_len;
         }
         total += wsize;
         Dmsg2(8, "Write %u bytes, total=%u\n", wsize, total);
         store_data(&bfd, wbuf, wsize);
         fileAddr += wsize;
      }
      break;

   /* GZIP data stream */
   case STREAM_GZIP_DATA:
   case STREAM_SPARSE_GZIP_DATA:
   case STREAM_WIN32_GZIP_DATA:
#ifdef HAVE_LIBZ
      if (extract) {
         uLong compress_len = compress_buf_size;
         int status = Z_BUF_ERROR;

         if (rec->maskedStream == STREAM_SPARSE_GZIP_DATA) {
            ser_declare;
            uint64_t faddr;
            char ec1[50];
            wbuf = rec->data + OFFSET_FADDR_SIZE;
            wsize = rec->data_len - OFFSET_FADDR_SIZE;
            ser_begin(rec->data, OFFSET_FADDR_SIZE);
            unser_uint64(faddr);
            if (fileAddr != faddr) {
               fileAddr = faddr;
               if (blseek(&bfd, (boffset_t)fileAddr, SEEK_SET) < 0) {
                  berrno be;
                  Emsg3(M_ERROR, 0, _("Seek to %s error on %s: ERR=%s\n"),
                     edit_uint64(fileAddr, ec1), attr->ofname, be.bstrerror());
                  extract = false;
                  return true;
               }
            }
         } else {
            wbuf = rec->data;
            wsize = rec->data_len;
         }

         while (compress_len < 10000000 && (status = uncompress((Byte *)compress_buf, &compress_len,
                                 (const Byte *)wbuf, (uLong)wsize)) == Z_BUF_ERROR) {
            /* The buffer size is too small, try with a bigger one */
            compress_len = 2 * compress_len;
            compress_buf = check_pool_memory_size(compress_buf,
                                                  compress_len);
         }
         if (status != Z_OK) {
            Emsg1(M_ERROR, 0, _("Uncompression error. ERR=%d\n"), status);
            extract = false;
            return true;
         }

         Dmsg2(100, "Write uncompressed %d bytes, total before write=%d\n", compress_len, total);
         store_data(&bfd, compress_buf, compress_len);
         total += compress_len;
         fileAddr += compress_len;
         Dmsg2(100, "Compress len=%d uncompressed=%d\n", rec->data_len,
            compress_len);
      }
#else
      if (extract) {
         Emsg0(M_ERROR, 0, _("GZIP data stream found, but GZIP not configured!\n"));
         extract = false;
         return true;
      }
#endif
      break;

   /* Compressed data stream */
   case STREAM_COMPRESSED_DATA:
   case STREAM_SPARSE_COMPRESSED_DATA:
   case STREAM_WIN32_COMPRESSED_DATA:
      if (extract) {
         uint32_t comp_magic, comp_len;
         uint16_t comp_level, comp_version;
#ifdef HAVE_LZO
         lzo_uint compress_len;
         const unsigned char *cbuf;
         int r, real_compress_len;
#endif

         if (rec->maskedStream == STREAM_SPARSE_COMPRESSED_DATA) {
            ser_declare;
            uint64_t faddr;
            char ec1[50];
            wbuf = rec->data + OFFSET_FADDR_SIZE;
            wsize = rec->data_len - OFFSET_FADDR_SIZE;
            ser_begin(rec->data, OFFSET_FADDR_SIZE);
            unser_uint64(faddr);
            if (fileAddr != faddr) {
               fileAddr = faddr;
               if (blseek(&bfd, (boffset_t)fileAddr, SEEK_SET) < 0) {
                  berrno be;
                  Emsg3(M_ERROR, 0, _("Seek to %s error on %s: ERR=%s\n"),
                     edit_uint64(fileAddr, ec1), attr->ofname, be.bstrerror());
                  extract = false;
                  return true;
               }
            }
         } else {
            wbuf = rec->data;
            wsize = rec->data_len;
         }

         /* read compress header */
         unser_declare;
         unser_begin(wbuf, sizeof(comp_stream_header));
         unser_uint32(comp_magic);
         unser_uint32(comp_len);
         unser_uint16(comp_level);
         unser_uint16(comp_version);
         Dmsg4(200, "Compressed data stream found: magic=0x%x, len=%d, level=%d, ver=0x%x\n", comp_magic, comp_len,
                                 comp_level, comp_version);

         /* version check */
         if (comp_version != COMP_HEAD_VERSION) {
            Emsg1(M_ERROR, 0, _("Compressed header version error. version=0x%x\n"), comp_version);
            return false;
         }
         /* size check */
         if (comp_len + sizeof(comp_stream_header) != wsize) {
            Emsg2(M_ERROR, 0, _("Compressed header size error. comp_len=%d, msglen=%d\n"),
                 comp_len, wsize);
            return false;
         }

          switch(comp_magic) {
#ifdef HAVE_LZO
            case COMPRESS_LZO1X:
               compress_len = compress_buf_size;
               cbuf = (const unsigned char*) wbuf + sizeof(comp_stream_header);
               real_compress_len = wsize - sizeof(comp_stream_header);
               Dmsg2(200, "Comp_len=%d msglen=%d\n", compress_len, wsize);
               while ((r=lzo1x_decompress_safe(cbuf, real_compress_len,
                                               (unsigned char *)compress_buf, &compress_len, NULL)) == LZO_E_OUTPUT_OVERRUN)
               {

                  /* The buffer size is too small, try with a bigger one */
                  compress_len = 2 * compress_len;
                  compress_buf = check_pool_memory_size(compress_buf,
                                                  compress_len);
               }
               if (r != LZO_E_OK) {
                  Emsg1(M_ERROR, 0, _("LZO uncompression error. ERR=%d\n"), r);
                  extract = false;
                  return true;
               }
               Dmsg2(100, "Write uncompressed %d bytes, total before write=%d\n", compress_len, total);
               store_data(&bfd, compress_buf, compress_len);
               total += compress_len;
               fileAddr += compress_len;
               Dmsg2(100, "Compress len=%d uncompressed=%d\n", rec->data_len, compress_len);
               break;
#endif
            default:
               Emsg1(M_ERROR, 0, _("Compression algorithm 0x%x found, but not supported!\n"), comp_magic);
               extract = false;
               return true;
         }

      }
      break;

   case STREAM_MD5_DIGEST:
   case STREAM_SHA1_DIGEST:
   case STREAM_SHA256_DIGEST:
   case STREAM_SHA512_DIGEST:
      break;

   case STREAM_SIGNED_DIGEST:
   case STREAM_ENCRYPTED_SESSION_DATA:
      // TODO landonf: Investigate crypto support in the storage daemon
      break;

   case STREAM_PROGRAM_NAMES:
   case STREAM_PROGRAM_DATA:
      if (!prog_name_msg) {
         Pmsg0(000, _("Got Program Name or Data Stream. Ignored.\n"));
         prog_name_msg++;
      }
      break;

   case STREAM_UNIX_ACCESS_ACL:          /* Deprecated Standard ACL attributes on UNIX */
   case STREAM_UNIX_DEFAULT_ACL:         /* Deprecated Default ACL attributes on UNIX */
   case STREAM_ACL_AIX_TEXT:
   case STREAM_ACL_DARWIN_ACCESS_ACL:
   case STREAM_ACL_FREEBSD_DEFAULT_ACL:
   case STREAM_ACL_FREEBSD_ACCESS_ACL:
   case STREAM_ACL_HPUX_ACL_ENTRY:
   case STREAM_ACL_IRIX_DEFAULT_ACL:
   case STREAM_ACL_IRIX_ACCESS_ACL:
   case STREAM_ACL_LINUX_DEFAULT_ACL:
   case STREAM_ACL_LINUX_ACCESS_ACL:
   case STREAM_ACL_TRU64_DEFAULT_ACL:
   case STREAM_ACL_TRU64_DEFAULT_DIR_ACL:
   case STREAM_ACL_TRU64_ACCESS_ACL:
   case STREAM_ACL_SOLARIS_ACLENT:
   case STREAM_ACL_SOLARIS_ACE:
   case STREAM_ACL_AFS_TEXT:
   case STREAM_ACL_AIX_AIXC:
   case STREAM_ACL_AIX_NFS4:
   case STREAM_ACL_FREEBSD_NFS4_ACL:
   case STREAM_ACL_HURD_DEFAULT_ACL:
   case STREAM_ACL_HURD_ACCESS_ACL:
      if (extract) {
         wbuf = rec->data;
         wsize = rec->data_len;
         pm_strcpy(acl_data.last_fname, attr->fname);

         parse_acl_streams(jcr, &acl_data, rec->maskedStream, wbuf, wsize);
      }
      break;

   case STREAM_XATTR_HURD:
   case STREAM_XATTR_IRIX:
   case STREAM_XATTR_TRU64:
   case STREAM_XATTR_AIX:
   case STREAM_XATTR_OPENBSD:
   case STREAM_XATTR_SOLARIS_SYS:
   case STREAM_XATTR_SOLARIS:
   case STREAM_XATTR_DARWIN:
   case STREAM_XATTR_FREEBSD:
   case STREAM_XATTR_LINUX:
   case STREAM_XATTR_NETBSD:
      if (extract) {
         wbuf = rec->data;
         wsize = rec->data_len;
         pm_strcpy(xattr_data.last_fname, attr->fname);

         parse_xattr_streams(jcr, &xattr_data, rec->maskedStream, wbuf, wsize);
      }
      break;

   case STREAM_NDMP_SEPERATOR:
      break;

   default:
      /* If extracting, weird stream (not 1 or 2), close output file anyway */
      if (extract) {
         if (!is_bopen(&bfd)) {
            Emsg0(M_ERROR, 0, _("Logic error output file should be open but is not.\n"));
         }
         set_attributes(jcr, attr, &bfd);
         extract = false;
      }
      Jmsg(jcr, M_ERROR, 0, _("Unknown stream=%d ignored. This shouldn't happen!\n"),
         rec->Stream);
      break;

   } /* end switch */
   return true;
}
Beispiel #26
0
/*
 * Update the ADV in an existing installation.
 */
int write_adv(const char *path, const char *cfg)
{
    unsigned char advtmp[2 * ADV_SIZE];
    char *file;
    int fd = -1;
    struct stat st, xst;
    int err = 0;
    int rv;

    rv = asprintf(&file, "%s%s%s", path,
		  path[0] && path[strlen(path) - 1] == '/' ? "" : "/", cfg);

    if (rv < 0 || !file) {
	perror(program);
	return -1;
    }

    fd = open(file, O_RDONLY);
    if (fd < 0) {
	err = -1;
    } else if (fstat(fd, &st)) {
	err = -1;
    } else if (st.st_size < 2 * ADV_SIZE) {
	/* Too small to be useful */
	err = -2;
    } else if (xpread(fd, advtmp, 2 * ADV_SIZE,
		      st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
	err = -1;
    } else {
	/* We got it... maybe? */
	err = syslinux_validate_adv(advtmp) ? -2 : 0;
	if (!err) {
	    /* Got a good one, write our own ADV here */
	    clear_attributes(fd);

	    /* Need to re-open read-write */
	    close(fd);
	    fd = open(file, O_RDWR | O_SYNC);
	    if (fd < 0) {
		fprintf(stderr, "Cannot open file '%s' in read/write mode !\nFatal error, exiting.\n", file);
		return -EACCES;
	    } else if (fstat(fd, &xst) || xst.st_ino != st.st_ino ||
		       xst.st_dev != st.st_dev || xst.st_size != st.st_size) {
		fprintf(stderr, "%s: race condition on write\n", file);
		err = -2;
	    }
	    /* Write our own version ... */
	    if (xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
			st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
		err = -1;
	    }

	    sync();
	    set_attributes(fd);
	}
    }

    if (err == -2)
	fprintf(stderr, "%s: cannot write auxiliary data (need --update)?\n",
		file);
    else if (err == -1)
	perror(file);

    if (fd >= 0)
	close(fd);
    if (file)
	free(file);

    return err;
}
Beispiel #27
0
	FFifo & operator << (const FFifoAttributes & attributes){
		set_attributes(attributes);
		return *this;
	}
Beispiel #28
0
	int set_attr(const MutexAttributes & attr){ return set_attributes(attr); }
static gint
mergeit (EContactMergingLookup *lookup)
{
	GtkWidget *scrolled_window, *label, *hbox, *dropdown;
	GtkWidget *content_area;
	GtkWidget *dialog;
	GtkTable *table;
	EContactField field;
	gchar *string = NULL, *string1 = NULL;
	GList *use_email_attr_list, *contact_email_attr_list, *match_email_attr_list;
	GList *use_tel_attr_list, *contact_tel_attr_list, *match_tel_attr_list;
	GList *use_im_attr_list, *contact_im_attr_list, *match_im_attr_list;
	GList *use_sip_attr_list, *contact_sip_attr_list, *match_sip_attr_list;
	gint row = -1;
	gint value = 0, result;

	dialog = gtk_dialog_new ();
	gtk_window_set_title (GTK_WINDOW (dialog), _("Merge Contact"));
	gtk_container_set_border_width (GTK_CONTAINER (dialog), 5);

	content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog));

	scrolled_window = gtk_scrolled_window_new (NULL, NULL);
	gtk_scrolled_window_set_policy (
		GTK_SCROLLED_WINDOW (scrolled_window),
		GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);

	table = (GtkTable *) gtk_table_new (20, 2, FALSE);
	gtk_container_set_border_width ((GtkContainer *) table, 12);
	gtk_table_set_row_spacings (table, 6);
	gtk_table_set_col_spacings (table, 2);

	gtk_dialog_add_buttons (
		GTK_DIALOG (dialog),
		_("_Cancel"), GTK_RESPONSE_CANCEL,
		_("_Merge"), GTK_RESPONSE_OK,
		NULL);


	/*we match all the string fields of the already existing contact and the new contact.*/
	for (field = E_CONTACT_FULL_NAME; field != (E_CONTACT_LAST_SIMPLE_STRING -1); field++) {
		dropdown_data *data = NULL;
		string = (gchar *) e_contact_get_const (lookup->contact, field);
		string1 = (gchar *) e_contact_get_const (lookup->match, field);

		/*the field must exist in the new as well as the duplicate contact*/
		if (string && *string) {
			if ((field >= E_CONTACT_FIRST_EMAIL_ID && field <= E_CONTACT_LAST_EMAIL_ID) ||
			    (field >= E_CONTACT_FIRST_PHONE_ID && field <= E_CONTACT_LAST_PHONE_ID) ||
			    (field >= E_CONTACT_IM_AIM_HOME_1 && field <= E_CONTACT_IM_ICQ_WORK_3) ) {
				/* ignore multival attributes, they are compared after this for-loop */
				continue;
			}

			if (!(string1 && *string1) || (g_ascii_strcasecmp (string, string1))) {
				row++;
				label = gtk_label_new (e_contact_pretty_name (field));
				hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
				gtk_box_pack_start (GTK_BOX (hbox), (GtkWidget *) label, FALSE, FALSE, 0);
				gtk_table_attach_defaults (table, (GtkWidget *) hbox, 0, 1, row, row + 1);
				data = g_new0 (dropdown_data, 1);
				dropdown = gtk_combo_box_text_new ();
				gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (dropdown), string);

				if (string1 && *string1)
					gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (dropdown), string1);
				else
					gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (dropdown), "");

				data->field = field;
				data->match = lookup->match;

				g_signal_connect (
					dropdown, "changed",
					G_CALLBACK (dropdown_changed), data);
				g_object_set_data_full (G_OBJECT (dropdown), "eab-contact-merging::dropdown-data", data, g_free);

				if (field == E_CONTACT_NICKNAME || field == E_CONTACT_GIVEN_NAME || field == E_CONTACT_FAMILY_NAME || field == E_CONTACT_FULL_NAME)
					gtk_combo_box_set_active (GTK_COMBO_BOX (dropdown), 1);
				else
					gtk_combo_box_set_active (GTK_COMBO_BOX (dropdown), 0);

				hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
				gtk_box_pack_start (GTK_BOX (hbox), (GtkWidget *) dropdown, FALSE, FALSE, 0);
				gtk_table_attach_defaults (table, (GtkWidget *) hbox, 1, 2, row, row + 1);
				gtk_widget_show_all ((GtkWidget *) dropdown);
			}
		}
	}

	match_email_attr_list = e_contact_get_attributes (lookup->match, E_CONTACT_EMAIL);
	contact_email_attr_list = e_contact_get_attributes (lookup->contact, E_CONTACT_EMAIL);
	use_email_attr_list = NULL;
	create_dropdowns_for_multival_attr (match_email_attr_list, contact_email_attr_list,
	                                   &use_email_attr_list, &row, table, _("Email"));

	match_tel_attr_list = e_contact_get_attributes (lookup->match, E_CONTACT_TEL);
	contact_tel_attr_list = e_contact_get_attributes (lookup->contact, E_CONTACT_TEL);
	use_tel_attr_list = NULL;
	create_dropdowns_for_multival_attr (match_tel_attr_list, contact_tel_attr_list,
	                                   &use_tel_attr_list, &row, table, _("Phone"));

	match_sip_attr_list = e_contact_get_attributes (lookup->match, E_CONTACT_SIP);
	contact_sip_attr_list = e_contact_get_attributes (lookup->contact, E_CONTACT_SIP);
	use_sip_attr_list = NULL;
	create_dropdowns_for_multival_attr (match_sip_attr_list, contact_sip_attr_list,
	                                   &use_sip_attr_list, &row, table, _("SIP"));

	match_im_attr_list = e_contact_get_attributes_set (lookup->match, im_fetch_set, G_N_ELEMENTS (im_fetch_set));
	contact_im_attr_list = e_contact_get_attributes_set (lookup->contact, im_fetch_set, G_N_ELEMENTS (im_fetch_set));
	use_im_attr_list = NULL;
	create_dropdowns_for_multival_attr (match_im_attr_list, contact_im_attr_list,
	                                   &use_im_attr_list, &row, table, _("IM"));

	gtk_window_set_default_size (GTK_WINDOW (dialog), 420, 300);
	gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (scrolled_window), GTK_WIDGET (table));
	gtk_box_pack_start (GTK_BOX (content_area), GTK_WIDGET (scrolled_window), TRUE, TRUE, 0);
	gtk_widget_show (scrolled_window);
	g_signal_connect (
		dialog, "map-event",
		G_CALLBACK (dialog_map), table);
	gtk_widget_show_all ((GtkWidget *) table);
	result = gtk_dialog_run (GTK_DIALOG (dialog));

	switch (result) {
		gint ii;
		GList *ll;
	case GTK_RESPONSE_OK:
		set_attributes (lookup->match, E_CONTACT_EMAIL, use_email_attr_list);
		set_attributes (lookup->match, E_CONTACT_TEL, use_tel_attr_list);
		set_attributes (lookup->match, E_CONTACT_SIP, use_sip_attr_list);

		for (ii = 0; ii < G_N_ELEMENTS (im_fetch_set); ii++) {
			e_contact_set_attributes (lookup->match, im_fetch_set[ii], NULL);
		}

		for (ll = use_im_attr_list; ll; ll = ll->next) {
			EVCard *vcard;
			vcard = E_VCARD (lookup->match);
			e_vcard_append_attribute (vcard, e_vcard_attribute_copy ((EVCardAttribute *) ll->data));
		}

		g_object_unref (lookup->contact);
		lookup->contact = g_object_ref (lookup->match);
		e_book_client_remove_contact (
			lookup->book_client,
			lookup->match, NULL,
			remove_contact_ready_cb, lookup);
		value = 1;
		break;
	case GTK_RESPONSE_CANCEL:
	default:
		value = 0;
		break;
	}
	gtk_widget_destroy (dialog);

	g_list_free_full (match_email_attr_list, (GDestroyNotify) e_vcard_attribute_free);
	g_list_free_full (contact_email_attr_list, (GDestroyNotify) e_vcard_attribute_free);
	g_list_free (use_email_attr_list);

	g_list_free_full (match_tel_attr_list, (GDestroyNotify) e_vcard_attribute_free);
	g_list_free_full (contact_tel_attr_list, (GDestroyNotify) e_vcard_attribute_free);
	g_list_free (use_tel_attr_list);

	g_list_free_full (match_im_attr_list, (GDestroyNotify) e_vcard_attribute_free);
	g_list_free_full (contact_im_attr_list, (GDestroyNotify) e_vcard_attribute_free);
	g_list_free (use_im_attr_list);

	g_list_free_full (match_sip_attr_list, (GDestroyNotify) e_vcard_attribute_free);
	g_list_free_full (contact_sip_attr_list, (GDestroyNotify) e_vcard_attribute_free);
	g_list_free (use_sip_attr_list);

	return value;
}
Beispiel #30
0
int create_inode(char *pathname, unsigned int start_block, unsigned int offset, squashfs_super_block *sBlk)
{
	long long start = sBlk->inode_table_start + start_block;
	squashfs_inode_header header;
	char *block_ptr;
	int bytes = lookup_entry(inode_table_hash, start), file_fd;

	TRACE("create_inode: pathname %s, start 0x%llx, offset %d\n", pathname, start, offset);

	if(bytes == -1) {
		ERROR("create_inode: inode block 0x%llx out of range!\n", start);
		return FALSE;
	}
	block_ptr = inode_table + bytes + offset;

	if(swap) {
		squashfs_base_inode_header sinode;
		memcpy(&sinode, block_ptr, sizeof(header.base));
		SQUASHFS_SWAP_BASE_INODE_HEADER(&header.base, &sinode, sizeof(squashfs_base_inode_header));
	} else
		memcpy(&header.base, block_ptr, sizeof(header.base));

	if(created_inode[header.base.inode_number - 1]) {
		TRACE("create_inode: hard link\n");
		if(link(created_inode[header.base.inode_number - 1], pathname) == -1) {
			ERROR("create_inode: failed to create hardlink, because %s\n", strerror(errno));
			return FALSE;
		}

		return TRUE;
	}

	switch(header.base.inode_type) {
		case SQUASHFS_FILE_TYPE: {
			unsigned int frag_bytes;
			unsigned int blocks;
			unsigned int offset;
			long long start;
			squashfs_reg_inode_header *inode = &header.reg;

			if(swap) {
				squashfs_reg_inode_header sinode;
				memcpy(&sinode, block_ptr, sizeof(sinode));
				SQUASHFS_SWAP_REG_INODE_HEADER(inode, &sinode);
			} else
				memcpy(inode, block_ptr, sizeof(*inode));

			frag_bytes = inode->fragment == SQUASHFS_INVALID_FRAG ? 0 : inode->file_size % sBlk->block_size;
			offset = inode->offset;
			blocks = inode->fragment == SQUASHFS_INVALID_FRAG ? (inode->file_size
				+ sBlk->block_size - 1) >> sBlk->block_log : inode->file_size >>
				sBlk->block_log;
			start = inode->start_block;

			TRACE("create_inode: regular file, file_size %lld, blocks %d\n", inode->file_size, blocks);

			if(write_file(pathname, inode->fragment, frag_bytes, offset, blocks, start,
					block_ptr + sizeof(*inode), inode->mode)) {
				set_attributes(pathname, inode->mode, inode->uid, inode->guid, inode->mtime, FALSE);
				file_count ++;
			}
			break;
		}	
		case SQUASHFS_LREG_TYPE: {
			unsigned int frag_bytes;
			unsigned int blocks;
			unsigned int offset;
			long long start;
			squashfs_lreg_inode_header *inode = &header.lreg;

			if(swap) {
				squashfs_lreg_inode_header sinode;
				memcpy(&sinode, block_ptr, sizeof(sinode));
				SQUASHFS_SWAP_LREG_INODE_HEADER(inode, &sinode);
			} else
				memcpy(inode, block_ptr, sizeof(*inode));

			frag_bytes = inode->fragment == SQUASHFS_INVALID_FRAG ? 0 : inode->file_size % sBlk->block_size;
			offset = inode->offset;
			blocks = inode->fragment == SQUASHFS_INVALID_FRAG ? (inode->file_size
				+ sBlk->block_size - 1) >> sBlk->block_log : inode->file_size >>
				sBlk->block_log;
			start = inode->start_block;

			TRACE("create_inode: regular file, file_size %lld, blocks %d\n", inode->file_size, blocks);

			if(write_file(pathname, inode->fragment, frag_bytes, offset, blocks, start,
					block_ptr + sizeof(*inode), inode->mode)) {
				set_attributes(pathname, inode->mode, inode->uid, inode->guid, inode->mtime, FALSE);
				file_count ++;
			}
			break;
		}	
		case SQUASHFS_SYMLINK_TYPE: {
			squashfs_symlink_inode_header *inodep = &header.symlink;
			char name[65536];

			if(swap) {
				squashfs_symlink_inode_header sinodep;
				memcpy(&sinodep, block_ptr, sizeof(sinodep));
				SQUASHFS_SWAP_SYMLINK_INODE_HEADER(inodep, &sinodep);
			} else
				memcpy(inodep, block_ptr, sizeof(*inodep));

			TRACE("create_inode: symlink, symlink_size %d\n", inodep->symlink_size);

			strncpy(name, block_ptr + sizeof(squashfs_symlink_inode_header), inodep->symlink_size);
			name[inodep->symlink_size] = '\0';

			if(symlink(name, pathname) == -1) {
				ERROR("create_inode: failed to create symlink %s, because %s\n", pathname,
					strerror(errno));
				break;
			}

			if(geteuid() == 0) {
				uid_t uid_value = (uid_t) uid_table[inodep->uid];
				uid_t guid_value = inodep->guid == SQUASHFS_GUIDS ? uid_value : (uid_t) guid_table[inodep->guid];

				if(lchown(pathname, uid_value, guid_value) == -1)
					ERROR("create_inode: failed to change uid and gids on %s, because %s\n", pathname, strerror(errno));
			}

			sym_count ++;
			break;
		}
 		case SQUASHFS_BLKDEV_TYPE:
	 	case SQUASHFS_CHRDEV_TYPE: {
			squashfs_dev_inode_header *inodep = &header.dev;

			if(swap) {
				squashfs_dev_inode_header sinodep;
				memcpy(&sinodep, block_ptr, sizeof(sinodep));
				SQUASHFS_SWAP_DEV_INODE_HEADER(inodep, &sinodep);
			} else
				memcpy(inodep, block_ptr, sizeof(*inodep));

			TRACE("create_inode: dev, rdev 0x%x\n", inodep->rdev);

			if(geteuid() == 0) {
				if(mknod(pathname, inodep->inode_type == SQUASHFS_CHRDEV_TYPE ? S_IFCHR : S_IFBLK,
							makedev((inodep->rdev >> 8) & 0xff, inodep->rdev & 0xff))
							== -1) {
					ERROR("create_inode: failed to create %s device %s, because %s\n",
						inodep->inode_type == SQUASHFS_CHRDEV_TYPE ? "character" : "block",
						pathname, strerror(errno));
					break;
				}
				set_attributes(pathname, inodep->mode, inodep->uid, inodep->guid, inodep->mtime, TRUE);
				dev_count ++;
			} else
				ERROR("create_inode: could not create %s device %s, because you're not superuser!\n",
					inodep->inode_type == SQUASHFS_CHRDEV_TYPE ? "character" : "block",
					pathname, strerror(errno));
			break;
			}
		case SQUASHFS_FIFO_TYPE:
			TRACE("create_inode: fifo\n");

			if(mknod(pathname, S_IFIFO, 0) == -1) {
				ERROR("create_inode: failed to create fifo %s, because %s\n",
					pathname, strerror(errno));
				break;
			}
			set_attributes(pathname, header.base.mode, header.base.uid, header.base.guid,
				header.base.mtime, TRUE);
			fifo_count ++;
			break;
		case SQUASHFS_SOCKET_TYPE:
			TRACE("create_inode: socket\n");
			ERROR("create_inode: socket %s ignored\n", pathname);
			break;
		default:
			ERROR("Unknown inode type %d in create_inode_table!\n", header.base.inode_type);
			return FALSE;
	}