Duplicate will run when copying a page with a block, or editing a block for the first time within a page version (before the save).
160450
public function duplicate($newBID)
    {
        $b = $this->getBlockObject();
        $c = $b->getBlockCollectionObject();

        $db = Database::connection();
        $v = [$this->bID];
        $q = "select * from {$this->btTable} where bID = ? LIMIT 1";
        $r = $db->query($q, $v);
        $row = $r->fetchRow();

        //if the same block exists in multiple collections with the same questionSetID
        if (count($row) > 0) {
            $oldQuestionSetId = $row['questionSetId'];

            //It should only generate a new question set id if the block is copied to a new page,
            //otherwise it will loose all of its answer sets (from all the people who've used the form on this page)
            $questionSetCIDs = $db->getCol("SELECT distinct cID FROM {$this->btTable} AS f, CollectionVersionBlocks AS cvb " .
                        'WHERE f.bID=cvb.bID AND questionSetId=' . intval($row['questionSetId']));

            //this question set id is used on other pages, so make a new one for this page block
            if (count($questionSetCIDs) > 1 || !in_array($c->cID, $questionSetCIDs)) {
                $newQuestionSetId = time();
                $_POST['qsID'] = $newQuestionSetId;
            } else {
                //otherwise the question set id stays the same
                $newQuestionSetId = $row['questionSetId'];
            }

            //duplicate survey block record
            //with a new Block ID and a new Question
            $v = [$newQuestionSetId, $row['surveyName'], $row['submitText'], $newBID, $row['thankyouMsg'], intval($row['notifyMeOnSubmission']), $row['recipientEmail'], $row['displayCaptcha'], $row['addFilesToSet']];
            $q = "insert into {$this->btTable} ( questionSetId, surveyName, submitText, bID,thankyouMsg,notifyMeOnSubmission,recipientEmail,displayCaptcha,addFilesToSet) values (?, ?, ?, ?, ?, ?, ?, ?,?)";
            $result = $db->Execute($q, $v);

            $rs = $db->query("SELECT * FROM {$this->btQuestionsTablename} WHERE questionSetId=$oldQuestionSetId AND bID=" . intval($this->bID));
            while ($row = $rs->fetchRow()) {
                $v = [$newQuestionSetId, intval($row['msqID']), intval($newBID), $row['question'], $row['inputType'], $row['options'], $row['position'], $row['width'], $row['height'], $row['required'], $row['defaultDate']];
                $sql = "INSERT INTO {$this->btQuestionsTablename} (questionSetId,msqID,bID,question,inputType,options,position,width,height,required,defaultDate) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
                $db->Execute($sql, $v);
            }

            return $newQuestionSetId;
        }

        return 0;
    }
148573
void copyFrom(BidiRun run)
    {
        this.start = run.start;
        this.limit = run.limit;
        this.level = run.level;
        this.insertRemove = run.insertRemove;
    }
771886
function copyOwn(source, target, inherits, publicStatic, allowInit, isNOTExtendingNative) {
    for (var
      key,
      noFunctionCheck = typeof source !== 'function',
      names = oK(source),
      i = 0; i < names.length; i++
    ) {
      key = names[i];
      if (
        (noFunctionCheck || indexOf.call(nativeFunctionOPN, key) < 0) &&
        isNotASpecialKey(key, allowInit)
      ) {
        if (hOP.call(target, key)) {
          warn('duplicated: ' + key.toString());
        }
        setProperty(inherits, target, key, gOPD(source, key), publicStatic, isNOTExtendingNative);
      }
    }
  }
940757
def duplicate_lines(self):
        

        cursor = self.textCursor()
        self.__select_text_under_cursor_blocks(cursor)
        text = cursor.selectedText()

        cursor.setPosition(cursor.block().next().position())
        cursor.position() == cursor.document().firstBlock().position() and cursor.setPosition(
            cursor.document().lastBlock().position())

        start_position = cursor.position()
        cursor.insertText(text)
        end_position = cursor.position()
        cursor.insertText(QChar(QChar.ParagraphSeparator))

        cursor.setPosition(start_position, QTextCursor.MoveAnchor)
        cursor.setPosition(end_position, QTextCursor.KeepAnchor)
        self.setTextCursor(cursor)

        return True
758535
private void removeStoredBlock(Block block, DatanodeDescriptor node) {
    if (NameNode.stateChangeLog.isDebugEnabled()) {
      NameNode.stateChangeLog.debug("BLOCK* NameSystem.removeStoredBlock: "
        + block + " from " + node.getName());
    }
    if (!blocksMap.removeNode(block, node)) {
      if (NameNode.stateChangeLog.isDebugEnabled()) {
        NameNode.stateChangeLog.debug("BLOCK* NameSystem.removeStoredBlock: "
          + block + " has already been removed from node " + node);
      }
      return;
    }

    //
    // if file is being actively written to and it is the last block, 
    // then do not check replication-factor here.
    //
    BlockInfo storedBlock = blocksMap.getStoredBlock(block);
    INodeFile fileINode = (storedBlock == null) ? null : storedBlock.getINode();
    if (fileINode != null && 
        fileINode.isUnderConstruction() && fileINode.isLastBlock(storedBlock)) {
      decrementSafeBlockCount(block);
      return;
    }      

    //
    // It's possible that the block was removed because of a datanode
    // failure.  If the block is still valid, check if replication is
    // necessary.  In that case, put block on a possibly-will-
    // be-replicated list.
    //
    if (fileINode != null) {
      decrementSafeBlockCount(block);
      // handle under replication
      // Use storedBlock here because block maybe a deleted block with size DELETED
      if (isPopulatingReplQueuesInternal()) {
        NumberReplicas num = countNodes(storedBlock);
        int numCurrentReplicas = num.liveReplicas()
            +
        pendingReplications.getNumReplicas(storedBlock);
        updateNeededReplicationQueue(storedBlock, -1, numCurrentReplicas,
            num.decommissionedReplicas, node, 
            fileINode.getBlockReplication(storedBlock));
      }
    }

    //
    // We've removed a block from a node, so it's definitely no longer
    // in "excess" there.
    //
    removeFromExcessReplicateMap(block, node);

    // Remove the replica from corruptReplicas
    corruptReplicas.removeFromCorruptReplicasMap(block, node);
  }
582976
private HashMap<String, TagLibTag> duplicate(HashMap<String, TagLibTag> tags, boolean deepCopy) {
	if (deepCopy) throw new PageRuntimeException(new ExpressionException("deep copy not supported"));

	Iterator<Entry<String, TagLibTag>> it = tags.entrySet().iterator();
	HashMap<String, TagLibTag> cm = new HashMap<String, TagLibTag>();
	Entry<String, TagLibTag> entry;
	while (it.hasNext()) {
	    entry = it.next();
	    cm.put(entry.getKey(), deepCopy ? entry.getValue() : // TODO add support for deepcopy ((TagLibTag)entry.getValue()).duplicate(deepCopy):
		    entry.getValue());
	}
	return cm;
    }
669013
def _copy(self):
        
        ins = copy.copy(self)
        ins._fire_page_number(self.page_number + 1)
        return ins
153125
void metaSave(PrintWriter out) {
    synchronized (pendingReplications) {
      out.println("Metasave: Blocks being replicated: " +
                  pendingReplications.size());
      Iterator iter = pendingReplications.entrySet().iterator();
      while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        PendingInfo pendingBlock = (PendingInfo) entry.getValue();
        Path filename = (Path) entry.getKey();
        out.println(filename + 
                    " StartTime: " + new Time(pendingBlock.timeStamp));
      }
    }
  }
1076050
private void replicateLastBlock(String src, INodeFileUnderConstruction file) {
    BlockInfo[] blks = file.getBlocks();
    if (blks == null || blks.length == 0)
      return;
    BlockInfo block = blks[blks.length-1];
    DatanodeDescriptor[] targets = file.getValidTargets();
    final int numOfTargets = targets == null ? 0 : targets.length;
    NumberReplicas status = countNodes(block);
    int totalReplicas = status.getTotal();
    if (numOfTargets > totalReplicas) {
      pendingReplications.add(block, numOfTargets-totalReplicas);
    }
    int expectedReplicas = file.getReplication();
    if (numOfTargets < expectedReplicas || 
        status.decommissionedReplicas != 0 ||
        status.corruptReplicas != 0) {
      LOG.info("Add " + block + " of " + src + " to needReplication queue: " + 
          " numOfTargets = " + numOfTargets +
          " decomissionedReplicas = " + status.decommissionedReplicas +
          " corruptReplicas = " + status.corruptReplicas);
      neededReplications.add(block, status.liveReplicas, 
          status.decommissionedReplicas, expectedReplicas);
    }
    
    // update metrics
    if (numOfTargets < expectedReplicas) {
      if (numOfTargets == 1) {
        myFSMetrics.numNewBlocksWithOneReplica.inc();
      }
    } else {
      myFSMetrics.numNewBlocksWithoutFailure.inc();
    }
    myFSMetrics.numNewBlocks.inc();
  }
1088397
private void processOverReplicatedBlock(Block block, short replication,
                                          DatanodeDescriptor addedNode, DatanodeDescriptor delNodeHint) {

    List<DatanodeID> excessReplicateTmp = new ArrayList<DatanodeID>();
    List<DatanodeID> originalDatanodes = new ArrayList<DatanodeID>();

    // find all replicas that can possibly be deleted.
    // The results are returned in excessReplicateTmp.
    findOverReplicatedReplicas(block, replication,
      addedNode, delNodeHint,
      excessReplicateTmp, originalDatanodes);
    if (excessReplicateTmp.size() <= 0) {
      return;
    }

    writeLock();                     // acquire write lock,
    try {
      BlockInfo storedBlock = blocksMap.getBlockInfo(block);
      INodeFile inode = (storedBlock == null) ? null : storedBlock.getINode(); 
      if (inode == null) {
        return; // file has been deleted already, nothing to do.
      }

      //
      // if the state of replicas of this block has changed since the time
      // when we released and reacquired the lock, then all the decisions
      // that we have made so far might not be correct. Do not delete excess
      // replicas in this case.

      int live = 0;
      Collection<DatanodeDescriptor> nodesCorrupt = corruptReplicas.getNodes(block);
      for (Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(block);
           it.hasNext();) {
        DatanodeDescriptor node = it.next();
        if (((nodesCorrupt != null) && (nodesCorrupt.contains(node))) ||
          node.isDecommissionInProgress() || node.isDecommissioned()) {
          // do nothing
        } else {
          live++;            // number of live nodes
          originalDatanodes.remove(node);
        }
      }

      if (originalDatanodes.size() > 0) {
        NameNode.stateChangeLog.info("Unable to delete excess replicas for block " +
          block +
          " because the state of the original replicas have changed." +
          " Will retry later.");
        overReplicatedBlocks.add(block);
        return;
      }
      
      short blockReplication = inode.getBlockReplication(storedBlock);

      // loop through datanodes that have excess-replicas of this block
      for (ListIterator<DatanodeID> iter = excessReplicateTmp.listIterator();
           iter.hasNext();) {
        DatanodeID datanodeId = iter.next();

        // re-check that block still has excess replicas.
        // If not, then there is nothing more to do.
        if (live <= blockReplication) {
          break;
        }

        // find the DatanodeDescriptor for this datanode
        DatanodeDescriptor datanode = null;
        try {
          datanode = getDatanode(datanodeId);
        } catch (IOException e) {
        }
        if (datanode == null) {
          NameNode.stateChangeLog.info("No datanode found while processing " +
            "overreplicated block " + block);
          continue;              // dead datanode?
        }

        // insert into excessReplicateMap
        LightWeightHashSet<Block> excessBlocks = excessReplicateMap.get(datanodeId.getStorageID());
        if (excessBlocks == null) {
          excessBlocks = new LightWeightHashSet<Block>();
          excessReplicateMap.put(datanodeId.getStorageID(), excessBlocks);
        }

        if (excessBlocks.add(block)) {
          excessBlocksCount++;
          if (NameNode.stateChangeLog.isDebugEnabled()) {
            NameNode.stateChangeLog.debug("BLOCK* NameSystem.chooseExcessReplicates: "
              + "(" + datanodeId.getName() + ", " + block
              + ") is added to excessReplicateMap");
          }
        }
        //
        // The 'excessblocks' tracks blocks until we get confirmation
        // that the datanode has deleted them; the only way we remove them
        // is when we get a "removeBlock" message.
        //
        // The 'invalidate' list is used to inform the datanode the block
        // should be deleted.  Items are removed from the invalidate list
        // upon giving instructions to the namenode.
        //
        addToInvalidatesNoLog(block, datanode, true);
        live--;
        if (NameNode.stateChangeLog.isDebugEnabled()) {
          NameNode.stateChangeLog.debug("BLOCK* NameSystem.chooseExcessReplicates: "
            + "(" + datanode.getName() + ", " + block + ") is added to recentInvalidateSets");
        }
      }
    } finally {
      writeUnlock();
    }
  }
168688
int getReplication(Block block) {
    BlockInfo storedBlock = blocksMap.getBlockInfo(block);
    INodeFile fileINode = (storedBlock == null) ? null : storedBlock.getINode();
    if (fileINode == null) { // block does not belong to any file
      return 0;
    }
    assert !fileINode.isDirectory() : "Block cannot belong to a directory.";
    return fileINode.getBlockReplication(storedBlock);
  }
1209249
function FileMaker_Command_Duplicate($fm, $layout, $recordId)
    {
        $this->_impl = new FileMaker_Command_Duplicate_Implementation($fm, $layout, $recordId);
    }
89824
def initialize_copy(other)
      @options = other.options.dup
      @errors = other.errors.dup
      @data, @strings = [], {}
      @entries = Hash.new { |h,k| h.fetch(k.to_s, nil) }

      other.each do |element|
        add element.dup
      end

      self
    end
646059
def duplicate(page, parent = nil)
      new_element = self.class.new(self.attributes)
      case parent.class.to_s
      when ChoiceField
        new_element.conditional_id = parent.id
      when QuestionGrid, QuestionGridWithTotal
        new_element.question_grid_id = parent.id
      end
      new_element.save(:validate => false)
      PageElement.create(:element => new_element, :page => page) unless parent
      
      # duplicate children
      if respond_to?(:elements) && elements.present?
        elements.each {|e| e.duplicate(page, new_element)}
      end
      
      new_element
    end
638745
protected function _duplicate()
    {
        $this->dupAllDocComments();
        if ($this->node instanceof Stmt\Class_) {
            $this->setModifier($this->node->flags);
            if ($this->node->extends) {
                $this->extend($this->node->extends);
            }
            exec_method_array($this, 'implement', $this->node->implements);
        }
        $this->addStmts($this->node->stmts);
    }
9516
private void checkDuplicate() {
		KeyboardShortcut ks = this.getDuplicate();
		if (ks != null) {
			this.setFieldValue(FIELD_INFO, Constant.messages.getString("keyboard.dialog.warning.dup", ks.getName()));
		} else {
			this.setFieldValue(FIELD_INFO, "");
		}
	}
1195116
def duplicate_template(template)
        input = gets.chomp.strip
        case
        when input.downcase == "b"
          jumpstart_menu
        when input.downcase == "x"
          exit_normal
        when JumpStart.existing_templates.include?(input)
          puts "  The template ".red + input.red_bold + " already exists. Please enter a unique name for the duplicate.".red
          duplicate_template(template)
        when input.length < 3
          puts "  The template name ".red + input.red_bold + " is too short. Please enter a name that is at least 3 characters long.".red
          duplicate_template(template)
        when input.match(/^\W|\W$/)
          puts "  The template name ".red + input.red_bold + " begins or ends with an invalid character. Please enter a name that begins with a letter or a number.".red
          duplicate_template(template)
        else
          files_and_dirs = FileUtils.sort_contained_files_and_dirs(FileUtils.join_paths(JumpStart.templates_path, template))
          FileUtils.mkdir_p(FileUtils.join_paths(JumpStart.templates_path, input, "jumpstart_config"))
          FileUtils.touch(FileUtils.join_paths(JumpStart.templates_path, input, "jumpstart_config", "#{input}.yml"))
          files_and_dirs[:dirs].each {|x| FileUtils.mkdir_p(FileUtils.join_paths(JumpStart.templates_path, input, x))}
          files_and_dirs[:files].each do |x|
            if x.match(/\/jumpstart_config\/#{template}\.yml/)
              FileUtils.copy_file(FileUtils.join_paths(JumpStart.templates_path, template, x), FileUtils.join_paths(JumpStart.templates_path, input, "jumpstart_config", "#{input}.yml") )
            else
              FileUtils.cp(FileUtils.join_paths(JumpStart.templates_path, template, x), FileUtils.join_paths(JumpStart.templates_path, input, x))
            end
          end
          puts "\n  Duplication complete!".green_bold
          puts "  Template " + template.green + " has been duplicated to " + input.green
          jumpstart_menu
        end
      end