/*
When recording snapshot completion we also record DR remote DC unique ids
as JSON. Need to merge our unique ids with existing numbers
since multiple replicas will submit the unique ids
492313
private void mergeConsumerDrIdTrackerToZK(JSONObject jsonObj) throws JSONException {
        //DR ids/unique ids for remote partitions indexed by remote datacenter id,
        //each DC has a full partition set
        JSONObject dcIdMap;
        if (jsonObj.has("drMixedClusterSizeConsumerState")) {
            dcIdMap = jsonObj.getJSONObject("drMixedClusterSizeConsumerState");
        } else {
            dcIdMap = new JSONObject();
            jsonObj.put("drMixedClusterSizeConsumerState", dcIdMap);
        }

        for (Map.Entry<Integer, JSONObject> dcEntry : m_drMixedClusterSizeConsumerState.entrySet()) {
            //Last seen ids for a specific data center
            final String consumerPartitionString = dcEntry.getKey().toString();
            if (!dcIdMap.has(consumerPartitionString)) {
                dcIdMap.put(consumerPartitionString, dcEntry.getValue());
            }
        }
    }
703457
def snapshots_to_send(source_snaps, dest_snaps):
    """"""
    if len(source_snaps) == 0:
        raise AssertionError("No snapshots exist locally!")
    if len(dest_snaps) == 0:
        # nothing on the remote side, send everything
        return None, source_snaps[-1]
    last_remote = dest_snaps[-1]
    for snap in reversed(source_snaps):
        if snap == last_remote:
            # found a common snapshot
            return last_remote, source_snaps[-1]
    # sys.stderr.write("source:'{}', dest:'{}'".format(source_snaps, dest_snaps))
    raise AssertionError("Latest snapshot on destination doesn't exist on source!")
953231
function (docId, name, value, changedByUserId, destroyedAt, recordedAt, updatedAt,
  seq, quorum, userUUID, colId, docUUID, forUserId, forUserUUID,
  recordedByUserId, colName, recordedByUUID) {
  this.docId = docId;
  this.name = name;
  this.value = value;
  this.changedByUserId = changedByUserId;
  this.destroyedAt = destroyedAt;
  this.recordedAt = recordedAt;
  this.updatedAt = updatedAt;
  this.seq = seq;
  this.quorum = quorum;
  this.userUUID = userUUID;
  this.colId = colId;
  this.docUUID = docUUID;
  this.forUserId = forUserId;
  this.forUserUUID = forUserUUID;
  this.recordedByUserId = recordedByUserId;
  this.colName = colName;
  this.recordedByUUID = recordedByUUID;
}
271770
function (ndefRecords) {

        var encoded = [],
            tnf_byte,
            record_type,
            payload_length,
            id_length,
            i,
            mb, me, // messageBegin, messageEnd
            cf = false, // chunkFlag TODO implement
            sr, // boolean shortRecord
            il; // boolean idLengthFieldIsPresent

        for(i = 0; i < ndefRecords.length; i++) {

            mb = (i === 0);
            me = (i === (ndefRecords.length - 1));
            sr = (ndefRecords[i].payload.length < 0xFF);
            il = (ndefRecords[i].id.length > 0);
            tnf_byte = ndef.encodeTnf(mb, me, cf, sr, il, ndefRecords[i].tnf);
            encoded.push(tnf_byte);

            // type is stored as String, converting to bytes for storage
            record_type = util.stringToBytes(ndefRecords[i].type);
            encoded.push(record_type.length);

            if (sr) {
                payload_length = ndefRecords[i].payload.length;
                encoded.push(payload_length);
            } else {
                payload_length = ndefRecords[i].payload.length;
                // 4 bytes
                encoded.push((payload_length >> 24));
                encoded.push((payload_length >> 16));
                encoded.push((payload_length >> 8));
                encoded.push((payload_length & 0xFF));
            }

            if (il) {
                id_length = ndefRecords[i].id.length;
                encoded.push(id_length);
            }

            encoded = encoded.concat(record_type);

            if (il) {
                encoded = encoded.concat(ndefRecords[i].id);
            }

            encoded = encoded.concat(ndefRecords[i].payload);
        }

        return encoded;
    }
1245121
@InterfaceAudience.Private
    private void refreshRemoteCheckpointDoc() {
        Log.i(Log.TAG_SYNC, "%s: Refreshing remote checkpoint to get its _rev...", this);
        Future future = sendAsyncRequest("GET", "_local/" + remoteCheckpointDocID(), null, new RemoteRequestCompletion() {
            @Override
            public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
                if (db == null) {
                    Log.w(Log.TAG_SYNC, "%s: db == null while refreshing remote checkpoint.  aborting", this);
                    return;
                }
                if (e != null && Utils.getStatusFromError(e) != Status.NOT_FOUND) {
                    Log.e(Log.TAG_SYNC, "%s: Error refreshing remote checkpoint", e, this);
                } else {
                    Log.d(Log.TAG_SYNC, "%s: Refreshed remote checkpoint: %s", this, result);
                    remoteCheckpoint = (Map<String, Object>) result;
                    lastSequenceChanged = true;
                    saveLastSequence();  // try saving again
                }
            }
        });
        pendingFutures.add(future);
    }
924305
@SuppressWarnings("PMD")
    private List<RepoBranch> getGitRepoBranch(JSONObject buildJson) {
        List<RepoBranch> list = new ArrayList<>();        
        
        JSONArray actions = getJsonArray(buildJson, "actions");
        for (Object action : actions) {
            JSONObject jsonAction = (JSONObject) action;
            if (jsonAction.size() > 0) {
                JSONObject lastBuiltRevision = null;
                JSONArray branches = null;
                JSONArray remoteUrls = getJsonArray ((JSONObject) action, "remoteUrls");       
                if (!remoteUrls.isEmpty()) {
                	lastBuiltRevision = (JSONObject) jsonAction.get("lastBuiltRevision");
                }
                if (lastBuiltRevision != null) {
                	branches = getJsonArray (lastBuiltRevision, "branch");
                }
                // As of git plugin 3.0.0, when multiple repos are configured in the git plugin itself instead of MultiSCM plugin, 
            	// they are stored unordered in a HashSet. So it's buggy and we cannot associate the correct branch information.
                // So for now, we loop through all the remoteUrls and associate the built branch(es) with all of them.
                if (branches != null && !branches.isEmpty()) {
                	for (Object url : remoteUrls) {
                		String sUrl = (String) url;
                		if (sUrl != null && !sUrl.isEmpty()) {
                			sUrl = removeGitExtensionFromUrl(sUrl);
		                	for (Object branchObj : branches) {
		                		String branchName = getString((JSONObject) branchObj, "name");
		                		if (branchName != null) {
		                			String unqualifiedBranchName = getUnqualifiedBranch(branchName);
		                			RepoBranch grb = new RepoBranch(sUrl, unqualifiedBranchName, RepoBranch.RepoType.GIT);
		                			list.add(grb);
		                		}
		                	}
                		}
                	}
                }
            }
        }
        return list;
    }
1125953
def deleted_ids
      sql = <<-DR.squish
        SELECT object_id
        FROM rails_redshift_replicator_deleted_ids
        WHERE source_table = '#{replicable.source_table}'
      DR
      ActiveRecord::Base.connection.execute(sql).map{ |r| r['object_id'] }
    end
1085663
def create_snapshot(self, volume_id, notes='', **kwargs):
        

        return self.client.call('Network_Storage', 'createSnapshot',
                                notes, id=volume_id, **kwargs)
115460
@Override
    public void replayCompletion(String globalId) {
        if (rc == null) {
            // Find a factory to create the RecoveryCoordinator
            try {
                rc = getRecoveryCoordinator();
            } catch (RecoveryCoordinatorNotAvailableException e) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "replayCompletion", e);
            }
        }

        if (rc != null) {
            rc.replayCompletion(globalId);
        }
    }
256056
@InterfaceAudience.Private
    public void saveLastSequence() {
        if (!lastSequenceChanged) {
            return;
        }

        if (savingCheckpoint) {
            // If a save is already in progress, don't do anything. (The completion block will trigger
            // another save after the first one finishes.)
            overdueForCheckpointSave = true;
            return;
        }

        lastSequenceChanged = false;
        overdueForCheckpointSave = false;

        Log.d(Log.TAG_SYNC, "%s: saveLastSequence() called. lastSequence: %s remoteCheckpoint: %s",
                this, lastSequence, remoteCheckpoint);
        final Map<String, Object> body = new HashMap<String, Object>();
        if (remoteCheckpoint != null) {
            body.putAll(remoteCheckpoint);
        }
        body.put("lastSequence", lastSequence);

        savingCheckpoint = true;
        final String remoteCheckpointDocID = remoteCheckpointDocID();
        if (remoteCheckpointDocID == null) {
            Log.w(Log.TAG_SYNC, "%s: remoteCheckpointDocID is null, aborting saveLastSequence()", this);
            return;
        }

        final String checkpointID = remoteCheckpointDocID;
        Log.d(Log.TAG_SYNC, "%s: start put remote _local document.  checkpointID: %s body: %s",
                this, checkpointID, body);
        Future future = sendAsyncRequest("PUT", "_local/" + checkpointID, false, body, new RemoteRequestCompletion() {

            @Override
            public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {

                Log.d(Log.TAG_SYNC,
                        "%s: put remote _local document request finished.  checkpointID: %s body: %s",
                        this, checkpointID, body);

                try {

                    if (e != null) {
                        // Failed to save checkpoint:
                        switch (Utils.getStatusFromError(e)) {
                            case Status.NOT_FOUND:
                                Log.i(Log.TAG_SYNC, "%s: could not save remote checkpoint: 404 NOT FOUND", this);
                                remoteCheckpoint = null;  // doc deleted or db reset
                                overdueForCheckpointSave = true; // try saving again
                                break;
                            case Status.CONFLICT:
                                Log.i(Log.TAG_SYNC, "%s: could not save remote checkpoint: 409 CONFLICT", this);
                                refreshRemoteCheckpointDoc();
                                break;
                            default:
                                Log.i(Log.TAG_SYNC, "%s: could not save remote checkpoint: %s", this, e);
                                // TODO: On 401 or 403, and this is a pull, remember that remote
                                // TODo: is read-only & don't attempt to read its checkpoint next time.
                                break;
                        }
                    } else {
                        // Saved checkpoint:
                        Map<String, Object> response = (Map<String, Object>) result;
                        body.put("_rev", response.get("rev"));
                        remoteCheckpoint = body;
                        if (db != null && db.isOpen()) {
                            Log.d(Log.TAG_SYNC,
                                    "%s: saved remote checkpoint, updating local checkpoint. RemoteCheckpoint: %s",
                                    this, remoteCheckpoint);
                            setLastSequenceFromWorkExecutor(lastSequence, checkpointID);
                        } else {
                            Log.w(Log.TAG_SYNC, "%s: Database is null or closed, not calling db.setLastSequence() ", this);
                        }
                    }
                } finally {
                    savingCheckpoint = false;
                    if (overdueForCheckpointSave) {
                        Log.i(Log.TAG_SYNC, "%s: overdueForCheckpointSave == true, calling saveLastSequence()", this);
                        overdueForCheckpointSave = false;
                        saveLastSequence();
                    }
                }
            }
        });
        pendingFutures.add(future);
    }
691910
private void sendSnapshotTxnId(SnapshotInfo toRestore) {
        long txnId = toRestore != null ? toRestore.txnId : 0;
        String jsonData = toRestore != null ? toRestore.toJSONObject().toString() : "{}";
        LOG.debug("Sending snapshot ID " + txnId + " for restore to other nodes");
        try {
            m_zk.create(VoltZK.restore_snapshot_id, jsonData.getBytes(Constants.UTF8ENCODING),
                        Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        } catch (Exception e) {
            VoltDB.crashGlobalVoltDB("Failed to create Zookeeper node: " + e.getMessage(),
                                     false, e);
        }
    }
413534
def cli(env, volume_id, notes):
    """"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    snapshot = block_manager.create_snapshot(volume_id, notes=notes)

    if 'id' in snapshot:
        click.echo('New snapshot created with id: %s' % snapshot['id'])
    else:
        click.echo('Error occurred while creating snapshot.\n'
                   'Ensure volume is not failed over or in another '
                   'state which prevents taking snapshots.')
1159070
void replicationComplete() {
        reloadTasksFromModel();
        Toast.makeText(getApplicationContext(),
                R.string.replication_completed,
                Toast.LENGTH_LONG).show();
        dismissDialog(DIALOG_PROGRESS);
    }
1176329
def record_get(self, creative_ids, nick=None):
        ''''''
        request = TOPRequest('xxxxx.xxxxx.creatives.record.get')
        request['creative_ids'] = creative_ids
        if nick!=None: request['nick'] = nick
        self.create(self.execute(request), models = {'result':CreativeRecord})
        return self.result
700574
private String createRequestNode(SnapshotInitiationInfo snapInfo)
    {
        String requestId = null;

        try {
            requestId = java.util.UUID.randomUUID().toString();
            if (!snapInfo.isTruncationRequest()) {
                final JSONObject jsObj = snapInfo.getJSONObjectForZK();
                jsObj.put("requestId", requestId);
                String zkString = jsObj.toString(4);
                byte zkBytes[] = zkString.getBytes("UTF-8");

                m_zk.create(VoltZK.user_snapshot_request, zkBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            else {
                m_zk.create(VoltZK.request_truncation_snapshot_node, null,
                        Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
            }
        } catch (KeeperException.NodeExistsException e) {
            return null;
        } catch (Exception e) {
            VoltDB.crashLocalVoltDB("Exception while attempting to create user snapshot request in ZK", true, e);
        }

        return requestId;
    }
341924
def snapshot(self) -> Tuple[Hash32, UUID]:
        
        return self.state_root, self._account_db.record()
1159002
function populateSnapshot(app, uid, cb) {
  logger.debug('populateSnapshot entry');

  app.models.snapshot.create(
    { id: uid,
      refcount: '1',
      current: 'false' },
    function(err, mymodel) {
      if (err) {
        logger.error('populateSnapshot error');
        cb(err);
        return;
      }
      logger.debug('populateSnapshot exit: %j', mymodel);
      cb();
    });
}