# modifies olditem in place
968642
def update_retrieved_if_new(olditem, newitem, days=180, retrieved_pid='P813'):
    
    def ref_overwrite(oldref, newref, days):
        """
        If the newref is the same as the oldref except the retrieved date is `days` newer, return True
                                                       the retrieved date is NOT `days` newer, return False
        the refs are different, return True
        """
        if len(oldref) != len(newref):
            return True
        oldref_minus_retrieved = [x for x in oldref if x.get_prop_nr() != retrieved_pid]
        newref_minus_retrieved = [x for x in newref if x.get_prop_nr() != retrieved_pid]
        if not all(x in oldref_minus_retrieved for x in newref_minus_retrieved):
            return True
        oldref_retrieved = [x for x in oldref if x.get_prop_nr() == retrieved_pid]
        newref_retrieved = [x for x in newref if x.get_prop_nr() == retrieved_pid]
        if (len(newref_retrieved) != len(oldref_retrieved)) or not (
                len(newref_retrieved) == len(oldref_retrieved) == 1):
            return True
        datefmt = '+%Y-%m-%dT%H:%M:%SZ'
        retold = list([datetime.strptime(r.get_value()[0], datefmt) for r in oldref if r.get_prop_nr() == retrieved_pid])[0]
        retnew = list([datetime.strptime(r.get_value()[0], datefmt) for r in newref if r.get_prop_nr() == retrieved_pid])[0]
        return (retnew - retold).days >= days

    newrefs = newitem.references
    oldrefs = olditem.references
    if not (len(newrefs) == len(oldrefs) == 1):
        #print("overwriting refs, not 1")
        olditem.references = copy.deepcopy(newitem.references)
        return None
    overwrite = ref_overwrite(oldrefs[0], newrefs[0], days)
    if overwrite:
        #print("updating ref")
        olditem.references = newrefs
    else:
        #print("don't change")
        pass
471161
function increaseItemDepth(opts: Options, change: Change): Change {
    const previousItem = getPreviousItem(opts, change.value);
    const currentItem = getCurrentItem(opts, change.value);

    if (!previousItem) {
        return change;
    }

    if (!currentItem) {
        return change;
    }

    // Move the item in the sublist of previous item
    return moveAsSubItem(opts, change, currentItem, previousItem.key);
}
1209779
def move_item_up(self, item):
        
        prev_iter = self._prev_iter_for(item)
        if prev_iter is not None:
            self.model.swap(prev_iter, self._iter_for(item))
197597
def move_to(self, id_):
        """"""
        if self.items:
            try:
                self.current_item = self.items[id_]
            except (StopIteration, IndexError, NoSuchItem):
                raise NoSuchItem
            for f in self._hooks["select"]:
                f(self, id_)
        return self
1243267
function applyPatch (oldStr, uniDiff) {
  var diffstr = uniDiff.split('\n');
  var diff = [];
  var remEOFNL = false,
      addEOFNL = false;

  // i = 4 in order to skip diff headers.
  for (var i = 4; i < diffstr.length; i++) {
    if(diffstr[i][0] === '@') {
      var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
      diff.unshift({
        start:meh[3],
        oldlength:meh[2],
        oldlines:[],
        newlength:meh[4],
        newlines:[]
      });
    } else if(diffstr[i][0] === '+') {
      diff[0].newlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === '-') {
      diff[0].oldlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === ' ') {
      diff[0].newlines.push(diffstr[i].substr(1));
      diff[0].oldlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === '\\') {
      if (diffstr[i-1][0] === '+') {
        remEOFNL = true;
      } else if(diffstr[i-1][0] === '-') {
        addEOFNL = true;
      }
    }
  }

  var str = oldStr.split('\n');
  for (i = diff.length - 1; i >= 0; i--) {
    var d = diff[i];
    for (var j = 0; j < d.oldlength; j++) {
      if(str[d.start-1+j] !== d.oldlines[j]) {
        return false;
      }
    }
    Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
  }

  if (remEOFNL) {
    while (!str[str.length-1]) {
      str.pop();
    }
  } else if (addEOFNL) {
    str.push('');
  }
  return str.join('\n');
}
350013
def rename(self, oldkey, newkey):
        
        if oldkey in self.scalars:
            the_list = self.scalars
        elif oldkey in self.sections:
            the_list = self.sections
        else:
            raise KeyError('Key "%s" not found.' % oldkey)
        pos = the_list.index(oldkey)
        #
        val = self[oldkey]
        dict.__delitem__(self, oldkey)
        dict.__setitem__(self, newkey, val)
        the_list.remove(oldkey)
        the_list.insert(pos, newkey)
        comm = self.comments[oldkey]
        inline_comment = self.inline_comments[oldkey]
        del self.comments[oldkey]
        del self.inline_comments[oldkey]
        self.comments[newkey] = comm
        self.inline_comments[newkey] = inline_comment
721404
function removeThis()
    {
        $exportItems = $this->fetchItems();

        $db = eZDB::instance();
        $db->begin();
        foreach ( $exportItems as $item )
        {
            $item->remove();
        }
        $this->remove();
        $db->commit();
    }
175013
private void addLeftItems() {
        // Log.w(TAG,"addLeftItems() {.... (0)");

        if (leftItems.size() == 0) {
            return;
        }
        // Log.w(TAG,"addLeftItems() {.... (1)");
        ArrayList<T> currentLeftItems = new ArrayList<T>();
        currentLeftItems.addAll(leftItems);
        // Log.w(TAG,"addLeftItems() {.... (2)");

        synchronized (leftItems) {
            // Log.w(TAG,"addLeftItems() {.... (3.1)");
            leftItems.clear();
            // Log.w(TAG,"addLeftItems() {.... (3.1)");
        }
        // Log.w(TAG,"addLeftItems() {.... (4)");
        for (T currentLeftItem : currentLeftItems) {
            // Log.w(TAG,"addLeftItems() {.... (5.1)");
            addItem(currentLeftItem);
            // Log.w(TAG,"addLeftItems() {.... (5.2)");
        }
    }
1004235
function last(newitem) {
    if (newitem) {
      this.mappings.push({});
    }

    var m = this.mappings[this.mappings.length - 1];

    if (m && m.attribute && m.value && m.dataKey && m.replace) {
      m.re = new RegExp(m.attribute + '=([\'"]?)' + m.value + '\\1');
    } else if (m) {
      delete m.re;
    }

    return m;
  }
1061293
def replaceItem(self, child, href):
        """"""
        assert isinstance(child, Base), "child item must be a hypercat Catalogue or Resource"
        for i in range(len(self.items)):
            if(self.items[i].href == href):
                self.items[i] = child   # Replace existing
                return
        assert False, "No such child item to replace as "+href
1335925
function (mMap, sPath, oItem) {
			if (oItem) {
				if (!mMap[sPath]) {
					mMap[sPath] = [oItem];
				} else if (mMap[sPath].indexOf(oItem) < 0) {
					mMap[sPath].push(oItem);
				}
			}
		}
787335
def removeItem(self, item):
        """"""
        try:
            self.tree.removeItem(item)
        except AttributeError, e:
            raise VersionError('Saved versions are immutable')
423346
function ( e, item ) {
            var res = { 
                id:    this._conf().fieldID,
                meta:  this._meta(),
                value: {}
            };
            var oldValue = getOrDefault( this, 'props.config.value', [] );
            res.value[ res.id ] = _.contains(oldValue, item.id ) 
                ? _.without( oldValue, item.id ) : oldValue.concat([ item.id ]);

            this.handleEvent( 'change')( e );
            this._conf().onChange( res );
        }
18443
private void popLastItem() {
        KeyValue<K,V> lastKV = items.last();
        items.remove(lastKV);
        index.remove(lastKV.key);
    }
92443
function (item/*, index*/) {
		var old = item;
		var Constructor;
		if (!(item instanceof ok.Base)) {
			Constructor = this.getConstructor(item);
			item = new Constructor(item);
		}
		var identified = this.identify(item);
		if (identified) {
			identified.set(old);
		}
		else {
			var index = this.findInsertIndex(item);
			this.items.insert(index + 1, item);
		}
	}
550173
public function editItem()
    {
        $this->defaultData();

        $itemClass = $this->getCurrentClass();
        $item = $this->getCurrentInstance();

        if(!$this->isLocked($item, 'item_locked.tpl')){

            // my lock
            $lock = LockManager::getImplementation()->getLockData($item);
            if (!is_null($lock) && $lock->getOwnerId() == $this->getSession()->getUser()->getIdentifier()) {
                $this->setData('lockDate', $lock->getCreationTime());
                $this->setData('id', $item->getUri());
            }

            $formContainer = new SignedFormInstance($itemClass, $item);
            $myForm = $formContainer->getForm();

            $itemUri = $item->getUri();
            if ($this->hasWriteAccess($itemUri)) {
                if($myForm->isSubmited() && $myForm->isValid()){
                    $this->validateInstanceRoot($itemUri);

                    $properties = $myForm->getValues();
                    if (array_key_exists('warning', $properties)) {
                        $this->logWarning('Warning property is still in use', ['backend']);
                        unset($properties['warning']);
                    }

                    //bind item properties and set default content:
                    $binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($item);
                    $item = $binder->bind($properties);

                    $this->getEventManager()->trigger(new ItemUpdatedEvent($item->getUri(), $properties));
                    $this->getEventManager()->trigger(new ItemRdfUpdatedEvent($item->getUri(), $properties));

                    //if item label has been changed, do not use getLabel() to prevent cached value from lazy loading
                    $label = $item->getOnePropertyValue(new core_kernel_classes_Property(OntologyRdfs::RDFS_LABEL));
                    $this->setData("selectNode", tao_helpers_Uri::encode($item->getUri()));
                    $this->setData('label', ($label != null) ? $label->literal : '');
                    $this->setData('message', __('Item saved'));
                    $this->setData('reload', true);
                }
            } else {
                $myForm->setActions([]);
            }

            $currentModel = $this->getClassService()->getItemModel($item);
            $hasPreview = false;
            $hasModel   = false;
            if(!empty($currentModel)) {
                $hasModel = true;
                $isDeprecated = $this->getClassService()->hasModelStatus($item, array(ItemModelStatus::INSTANCE_DEPRECATED));
                $hasPreview = !$isDeprecated && $this->getClassService()->hasItemContent($item);
            }

            $updatedAt = $this->getServiceLocator()->get(ResourceWatcher::SERVICE_ID)->getUpdatedAt($item);
            $this->setData('isPreviewEnabled', $hasPreview);
            $this->setData('updatedAt', $updatedAt);
            $this->setData('isAuthoringEnabled', $hasModel);

            $this->setData('formTitle', __('Edit Item'));
            $this->setData('myForm', $myForm->render());

            $this->setView('Items/editItem.tpl');
        }
    }
548226
function () {
    var items = Array.prototype.slice.call(arguments);
    this.source.push.apply(this.source, items);
    this._updateInfo();

    // DEPRECATED
    this.emit("insert", items[0], this.length - 1);
    this.emit("update", { insert: items, index: this.length - 1});
  }