Remove all duplicate categories available in system.

@command acm_sku:remove-category-duplicates

@validate-module-enabled acm_sku

@aliases acccrd,commerce-cats-remove-duplicates

@usage drush acccrd
Remove all duplicate categories available in system.
324511
public function removeCategoryDuplicates() {
    $this->output->writeln(dt('Cleaning all commerce categories, please wait...'));

    $db = $this->connection;

    /** @var \Drupal\taxonomy\TermStorageInterface $termStorage */
    $termStorage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');

    /** @var \Drupal\node\NodeStorageInterface $nodeStorage */
    $nodeStorage = \Drupal::entityTypeManager()->getStorage('node');

    $query = $db->select('taxonomy_term__field_commerce_id', 'ttfci');
    $query->addField('ttfci', 'field_commerce_id_value', 'commerce_id');
    $query->groupBy('commerce_id');
    $query->having('count(*) > 1');
    $result = $query->execute()->fetchAllKeyed(0, 0);

    if (empty($result)) {
      $this->output->writeln(dt('No duplicate categories found.'));
      return;
    }

    foreach ($result as $commerce_id) {
      $this->output->writeln(dt('Duplicate categories found for commerce id: @commerce_id.', [
        '@commerce_id' => $commerce_id,
      ]));

      $query = $db->select('taxonomy_term__field_commerce_id', 'ttfci');
      $query->addField('ttfci', 'entity_id', 'tid');
      $query->condition('ttfci.field_commerce_id_value', $commerce_id);
      $query->orderBy('tid', 'DESC');
      $tids = $query->execute()->fetchAllKeyed(0, 0);

      foreach ($tids as $tid) {
        $query = $nodeStorage->getQuery();
        $query->condition('field_category', $tid);
        $nodes = $query->execute();

        if (empty($nodes)) {
          $this->output->writeln(dt('No nodes found for tid: @tid for commerce id: @commerce_id. Deleting', [
            '@commerce_id' => $commerce_id,
            '@tid' => $tid,
          ]));

          $term = $termStorage->load($tid);
          $term->delete();

          unset($tids[$tid]);

          // Break the loop if only one left now, we might not have any products
          // added yet and categories are synced which means there will be no
          // nodes for any term.
          if (count($tids) == 1) {
            break;
          }
        }
        else {
          $this->output->writeln(dt('@count nodes found for tid: @tid for commerce id: @commerce_id. Not Deleting', [
            '@commerce_id' => $commerce_id,
            '@tid' => $tid,
            '@count' => count($nodes),
          ]));
        }
      }
    }

    $this->output->writeln(dt('Done.'));
  }
717994
def admin_remove_from_category
      return if !user_is_allowed('products', 'edit')
      cat_id = params[:category_id]
      product_id = params[:id]
      
      if CategoryMembership.exists?(:category_id => cat_id, :product_id => product_id)
        CategoryMembership.where(:category_id => cat_id, :product_id => product_id).destroy_all
      end        
      render :json => true
    end
1063143
function merge(acc, item) {
  if (!item) {
    return acc;
  }

  return deepmerge(acc, item, {
    clone: false, // No need to clone deep, it's way faster.
  });
}
618172
def remove_duplicates(apps, schema_editor):
    

    # Get the model
    EntityRelationship = apps.get_model('entity', 'EntityRelationship')

    # Find the duplicates
    duplicates = EntityRelationship.objects.all().order_by(
        'sub_entity_id',
        'super_entity_id'
    ).values(
        'sub_entity_id',
        'super_entity_id'
    ).annotate(
        Count('sub_entity_id'),
        Count('super_entity_id'),
        max_id=Max('id')
    ).filter(
        super_entity_id__count__gt=1
    )

    # Loop over the duplicates and delete
    for duplicate in duplicates:
        EntityRelationship.objects.filter(
            sub_entity_id=duplicate['sub_entity_id'],
            super_entity_id=duplicate['super_entity_id']
        ).exclude(
            id=duplicate['max_id']
        ).delete()
720227
def _clean_item(self, item):
        '''
        
        '''
        item_copy = dict(item)
        del item_copy['body']
        del item_copy['links']
        del item_copy['response_headers']
        del item_copy['request_headers']
        del item_copy['status_code']
        del item_copy['status_msg']
        item_copy['action'] = 'ack'
        item_copy['logger'] = self.logger.name
        item_copy

        return item_copy
254731
def remove(self, items):
        """"""
        # Remove the ack ID from lease management, and decrement the
        # byte counter.
        for item in items:
            if self._leased_messages.pop(item.ack_id, None) is not None:
                self._bytes -= item.byte_size
            else:
                _LOGGER.debug("Item %s was not managed.", item.ack_id)

        if self._bytes < 0:
            _LOGGER.debug("Bytes was unexpectedly negative: %d", self._bytes)
            self._bytes = 0
606619
function removeThis()
    {
        $itemOptionList = eZProductCollectionItemOption::fetchList( $this->attribute( 'id' ) );

        $db = eZDB::instance();
        $db->begin();
        foreach( $itemOptionList as $itemOption )
        {
            $itemOption->remove();
        }
        $this->remove();
        $db->commit();
    }
1216717
protected function resetSKUs(){
        foreach($this->options as $op=>$junk){
            if(preg_match("#SellerSKUList#",$op)){
                unset($this->options[$op]);
            }
        }
        //remove Category-specific name
        unset($this->options['SellerSKU']);
    }
623887
protected function clearListByCategory($arAttachedIDList)
    {
        if ($this->sRelationName != 'additional_category') {
            return;
        }

        foreach ($arAttachedIDList as $iCategoryID) {
            BrandListStore::instance()->category->clear($iCategoryID);
            ProductListStore::instance()->category->clear($iCategoryID);

            $obCategoryItem = CategoryItem::make($iCategoryID);
            if ($obCategoryItem->isNotEmpty()) {
                $obCategoryItem->clearProductCount();
            }
        }
    }
88333
def remove_duplicates(self, ws):
        
        for analysis in ws.objectValues():
            if IDuplicateAnalysis.providedBy(analysis) \
                    and analysis.getAnalysis().UID() == self.UID():
                ws.removeAnalysis(analysis)
1205874
protected function checkIfFoldersExist() {
        $arrFilePath = explode(DIRECTORY_SEPARATOR, $this->filePath);
        array_pop($arrFilePath); //Remove filename
        if (count($arrFilePath) > 0) {
            $folderPath = implode(DIRECTORY_SEPARATOR, $arrFilePath);
            $folder = new Folder();
            $folder->createFolderIfNotExists($folderPath);
        }
    }
671792
def merge_dupes(self):
        """"""
        for dupe in self.dupe_of:
            if dupe in self.catalog.entries:
                if self.catalog.entries[dupe]._stub:
                    # merge = False to avoid infinite recursion
                    self.catalog.load_entry_from_name(
                        dupe, delete=True, merge=False)
                self.catalog.copy_entry_to_entry(self.catalog.entries[dupe],
                                                 self)
                del self.catalog.entries[dupe]
        self.dupe_of = []
1131782
@Override
	public void removeByCPOptionCategoryId(long CPOptionCategoryId) {
		for (CPSpecificationOption cpSpecificationOption : findByCPOptionCategoryId(
				CPOptionCategoryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(cpSpecificationOption);
		}
	}
1303876
public function removeCatFromDel()
    {
        $aChosenCat = $this->_getActionIds('oxobject2delivery.oxid');

        // removing all
        if (\OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('all')) {
            $sQ = $this->_addFilter("delete oxobject2delivery.* " . $this->_getQuery());
            \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->Execute($sQ);
        } elseif (is_array($aChosenCat)) {
            $sChosenCategoriess = implode(", ", \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->quoteArray($aChosenCat));
            $sQ = "delete from oxobject2delivery where oxobject2delivery.oxid in (" . $sChosenCategoriess . ") ";
            \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->Execute($sQ);
        }
    }
1333819
def remove_duplicate_entities(self):
        
        entity_hashes = np.array([hash(i) for i in self.entities])
        unique, inverse = grouping.unique_rows(entity_hashes)
        if len(unique) != len(self.entities):
            self.entities = self.entities[unique]
1117237
def _remove_duplicate_slices(dicoms):
    
    # Loop overall files and build dict

    dicoms_dict = {}
    filtered_dicoms = []
    for dicom_ in dicoms:
        if tuple(dicom_.ImagePositionPatient) not in dicoms_dict:
            dicoms_dict[tuple(dicom_.ImagePositionPatient)] = dicom_
            filtered_dicoms.append(dicom_)
        else:
            if numpy.array_equal(dicom_.pixel_array,
                                 dicoms_dict[tuple(dicom_.ImagePositionPatient)].pixel_array):
                logger.warning('Removing duplicate slice from series')
            else:
                filtered_dicoms.append(dicom_)
    return filtered_dicoms
901162
public function removeCat()
    {
        $categoriesToRemove = $this->_getActionIds('oxcategories.oxid');

        $oxId = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('oxid');
        $dataBase = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();

        // adding
        if (\OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('all')) {
            $categoriesTable = $this->_getViewName('oxcategories');
            $categoriesToRemove = $this->_getAll($this->_addFilter("select {$categoriesTable}.oxid " . $this->_getQuery()));
        }

        // removing all
        if (is_array($categoriesToRemove) && count($categoriesToRemove)) {
            $query = "delete from oxobject2category where oxobject2category.oxobjectid= "
                  . \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->quote($oxId) . " and ";
            $query = $this->updateQueryForRemovingArticleFromCategory($query);
            $query .= " oxcatnid in (" . implode(', ', \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->quoteArray($categoriesToRemove)) . ')';
            $dataBase->Execute($query);

            // updating oxtime values
            $this->_updateOxTime($oxId);
        }

        $this->resetArtSeoUrl($oxId, $categoriesToRemove);
        $this->resetContentCache();

        $this->onCategoriesRemoval($categoriesToRemove, $oxId);
    }