TODO: implement synchronize replica
        http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000vv000000
547124
def synchronizeReplica(self,
                           replicaID,
                           transportType="esriTransportTypeUrl",
                           replicaServerGen=None,
                           returnIdsForAdds=False,
                           edits=None,
                           returnAttachmentDatabyURL=False,
                           async=False,
                           syncDirection="snapshot",
                           syncLayers="perReplica",
                           editsUploadID=None,
                           editsUploadFormat=None,
                           dataFormat="json",
                           rollbackOnFailure=True):
        
        params = {
            "f" : "json",
            "replicaID" : replicaID,
            "transportType" : transportType,
            "dataFormat" : dataFormat,
            "rollbackOnFailure" : rollbackOnFailure,
            "async" : async,
            "returnIdsForAdds": returnIdsForAdds,
            "syncDirection" : syncDirection,
            "returnAttachmentDatabyURL" : returnAttachmentDatabyURL
        }
        return
703061
function sync() {
    syncDom.setAttribute('data-sync-state', 'syncing');
    var opts = {continuous: true, complete: syncError};
    db.replicate.to(remoteCouch, opts);
    db.replicate.from(remoteCouch, opts);
  }
359499
public ActionFuture<UpdateResponse>
    upsertDataASyncWithObjectMapper(Object sourceObject, String index,
            String type, String id) {
        return upsertDataAsync(
                JMElasticsearchUtil.buildSourceByJsonMapper(sourceObject),
                index, type, id);
    }
609055
def sync(self, json_obj=None):
        
        LOGGER.debug("Transport.sync")
        if json_obj is None:
            params = None
            if self.id is not None:
                params = SessionService.complete_transactional_req({'ID': self.id})

            if params is not None:
                if MappingService.driver_type != DriverFactory.DRIVER_REST:
                    params['OPERATION'] = 'getTransport'
                    args = {'properties': params}
                else:
                    args = {'http_operation': 'GET', 'operation_path': 'get', 'parameters': params}

                response = TransportService.requester.call(args)

                if MappingService.driver_type != DriverFactory.DRIVER_REST:
                    response = response.get()

                if response.rc == 0:
                    json_obj = response.response_content
                else:
                    err_msg = 'Transport.sync - Problem while syncing transport (id: ' + str(self.id) + '). ' \
                              'Reason: ' + str(response.response_content) + ' - ' + str(response.error_message) + \
                              " (" + str(response.rc) + ")"
                    LOGGER.warning(err_msg)
                    if response.rc == 500 and ArianeMappingOverloadError.ERROR_MSG in response.error_message:
                        raise ArianeMappingOverloadError("Transport.sync",
                                                         ArianeMappingOverloadError.ERROR_MSG)
                    # traceback.print_stack()
        elif 'transportID' not in json_obj:
            err_msg = 'Transport.sync - Problem while syncing transport (id: ' + str(self.id) + '). ' \
                      'Reason: inconsistent json_obj' + str(json_obj) + " from : \n"
            LOGGER.warning(err_msg)
            # traceback.print_stack()

        if json_obj is not None:
            self.id = json_obj['transportID']
            self.name = json_obj['transportName']
            if MappingService.driver_type != DriverFactory.DRIVER_REST:
                if 'transportProperties' in json_obj:
                    self.properties = DriverTools.json2properties(json_obj['transportProperties'])
                else:
                    self.properties = None
            else:
                self.properties = json_obj['transportProperties'] if 'transportProperties' in json_obj else None
512937
function queryReplication (id, opts0, callback0) {
    const { opts, callback } = getCallback(opts0, callback0)
    return relax({ db: '_replicator', method: 'GET', path: id, qs: opts }, callback)
  }
1082489
private void adjustReplicationFactorForURI(HttpPut httpPut) throws URISyntaxException{
        String queryString = httpPut.getURI().getQuery();
        if(!StringUtils.isEmpty(queryString) && queryString.contains("op=CREATE") && (queryString.contains("replication=") || !StringUtils.isEmpty(m_blockReplication))){
            rateLimitedLogWarn(m_logger, "Set block replication factor in the target system.");
            if(!StringUtils.isEmpty(m_blockReplication) && !queryString.contains("replication=")){
                StringBuilder builder = new StringBuilder(128);
                builder.append(queryString).append("&replication=").append(m_blockReplication);
                URI oldUri = httpPut.getURI();
                URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(),oldUri.getPath(), builder.toString(), oldUri.getFragment());
                httpPut.setURI(newUri);
            }
        }
    }
1156470
@Override
    public List<Integer> getReplicatingPartitionList(int index) {
        List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas());
        List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas());

        // Copy Zone based Replication Factor
        HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>();
        requiredRepFactor.putAll(zoneReplicationFactor);

        // Cross-check if individual zone replication factor equals global
        int sum = 0;
        for(Integer zoneRepFactor: requiredRepFactor.values()) {
            sum += zoneRepFactor;
        }

        if(sum != getNumReplicas())
            throw new IllegalArgumentException("Number of zone replicas is not equal to the total replication factor");

        if(getPartitionToNode().length == 0) {
            return new ArrayList<Integer>(0);
        }

        for(int i = 0; i < getPartitionToNode().length; i++) {
            // add this one if we haven't already, and it can satisfy some zone
            // replicationFactor
            Node currentNode = getNodeByPartition(index);
            if(!preferenceNodesList.contains(currentNode)) {
                preferenceNodesList.add(currentNode);
                if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId()))
                    replicationPartitionsList.add(index);
            }

            // if we have enough, go home
            if(replicationPartitionsList.size() >= getNumReplicas())
                return replicationPartitionsList;
            // move to next clockwise slot on the ring
            index = (index + 1) % getPartitionToNode().length;
        }

        // we don't have enough, but that may be okay
        return replicationPartitionsList;
    }
595233
private static void waitForRecoveriesToFinish(CloudSolrClient server, String collection) throws KeeperException, InterruptedException {
        ZkStateReader zkStateReader = server.getZkStateReader();
        try {
            boolean cont = true;

            while (cont) {
                boolean sawLiveRecovering = false;
                zkStateReader.updateClusterState(true);
                ClusterState clusterState = zkStateReader.getClusterState();
                Map<String, Slice> slices = clusterState.getSlicesMap(collection);
                Preconditions.checkNotNull("Could not find collection:" + collection, slices);

               // change paths for Replica.State per Solr refactoring
               // remove SYNC state per: http://tinyurl.com/pag6rwt
               for (Map.Entry<String, Slice> entry : slices.entrySet()) {
                    Map<String, Replica> shards = entry.getValue().getReplicasMap();
                    for (Map.Entry<String, Replica> shard : shards.entrySet()) {
                        String state = shard.getValue().getStr(ZkStateReader.STATE_PROP);
                        if ((state.equals(Replica.State.RECOVERING) || state.equals(Replica.State.DOWN))
                                && clusterState.liveNodesContain(shard.getValue().getStr(
                                ZkStateReader.NODE_NAME_PROP))) {
                            sawLiveRecovering = true;
                        }
                    }
                }


                if (!sawLiveRecovering) {
                    cont = false;
                } else {
                    Thread.sleep(1000);
                }
            }
        } finally {
            logger.info("Exiting solr wait");
        }
    }
797442
function(opt_syncRateSeconds, callback) {
      var query = misc.parseUrlQuery();
      var url = (query.hftUrl || window.location.href).replace("ws:", "http:");

      var syncRateMS = (opt_syncRateSeconds || 10) * 1000;
      var timeOffset = 0;

      var syncToServer = function(queueNext) {
        var sendTime = getLocalTime();
        io.sendJSON(url, {cmd: 'time'}, function(exception, obj) {
          if (exception) {
            console.error("syncToServer: " + exception);
          } else {
            var receiveTime = getLocalTime();
            var duration = receiveTime - sendTime;
            var serverTime = obj.time + duration * 0.5;
            timeOffset = serverTime - receiveTime;
            if (callback) {
              callback();
              callback = undefined;
            }
            //g_services.logger.log("duration: ", duration, " timeOff:", timeOffset);
          }

          if (queueNext) {
            setTimeout(function() {
              syncToServer(true);
            }, syncRateMS);
          }
        });
      };
      var syncToServerNoQueue = function() {
        syncToServer(false);
      };
      syncToServer(true);
      setTimeout(syncToServerNoQueue, 1000);
      setTimeout(syncToServerNoQueue, 2000);
      setTimeout(syncToServerNoQueue, 4000);

      /**
       * Gets the current time in seconds.
       * @private
       */
      this.getTime = function() {
        return getLocalTime() + timeOffset;
      };

    }
346387
public void clearReplicaSyncRequest(int partitionId, ServiceNamespace namespace, int replicaIndex) {
        ReplicaFragmentSyncInfo syncInfo = new ReplicaFragmentSyncInfo(partitionId, namespace, replicaIndex, null);
        if (!replicaSyncRequests.remove(syncInfo)) {
            return;
        }

        if (logger.isFinestEnabled()) {
            logger.finest("Clearing sync replica request for partitionId=" + partitionId + ", replicaIndex="
                    + replicaIndex + ", namespace=" + namespace);
        }
        releaseReplicaSyncPermits(1);
        replicaSyncTimeoutScheduler.cancelIfExists(syncInfo, null);
    }
771911
function sync (state, docsOrIds) {
  var syncedObjects = []
  var errors = state.db.constructor.Errors

  return Promise.resolve(state.remote)

  .then(function (remote) {
    return new Promise(function (resolve, reject) {
      if (Array.isArray(docsOrIds)) {
        docsOrIds = docsOrIds.map(toId)
      } else {
        docsOrIds = docsOrIds && [toId(docsOrIds)]
      }

      if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) {
        return Promise.reject(errors.NOT_AN_OBJECT)
      }

      var replication = state.db.sync(remote, {
        doc_ids: docsOrIds,
        include_docs: true
      })

      /* istanbul ignore next */
      replication.catch(function () {
        // handled trough 'error' event
      })

      replication.on('complete', function () {
        resolve(syncedObjects)
      })
      replication.on('error', reject)

      replication.on('change', function (change) {
        syncedObjects = syncedObjects.concat(change.change.docs)

        for (var i = 0; i < change.change.docs.length; i++) {
          state.emitter.emit(change.direction, change.change.docs[i])
        }
      })
    })
  })
}
1161630
public boolean syncDashboards(NewRelicCache cache)
    {
        boolean ret = true;

        if(apiClient == null)
            throw new IllegalArgumentException("null API client");

        // Get the dashboard configuration using the REST API
        if(cache.isInsightsEnabled())
        {
            ret = false;

            logger.info("Getting the dashboards");
            cache.dashboards().set(apiClient.dashboards().list());
            cache.setUpdatedAt();

            ret = true;
        }

        return ret;
    }
211942
private void synchronizeHosts(final AsyncCallback<Boolean> callback) {
        ModelNode op = new ModelNode();
        op.get(ADDRESS).setEmptyList();
        op.get(OP).set(READ_CHILDREN_RESOURCES_OPERATION);
        op.get(CHILD_TYPE).set("host");

        Footer.PROGRESS_ELEMENT.reset();

        dispatcher.execute(new DMRAction(op), new AsyncCallback<DMRResponse>() {
            @Override
            public void onFailure(Throwable caught) {
                Footer.PROGRESS_ELEMENT.finish();
                callback.onFailure(caught);
            }

            @Override
            public void onSuccess(DMRResponse result) {
                ModelNode response = result.get();
                if (response.isFailure()) {
                    Footer.PROGRESS_ELEMENT.finish();
                    callback.onFailure(new RuntimeException("Failed to synchronize host model: " + response.getFailureDescription()));
                } else {
                    List<Property> properties = response.get(RESULT).asPropertyList();
                    List<String> hostNames = new ArrayList<String>(properties.size());
                    for (Property property : properties) {
                        hostNames.add(property.getName());
                        if (property.getValue().hasDefined("master") && property.getValue().get("master").asBoolean()) {
                            domainController = property.getName();
                        }
                    }

                    Footer.PROGRESS_ELEMENT.finish();

                    // synchronize servers
                    synchronizeServerModel(hostNames, callback);
                }
            }

        });

    }
280224
def updateReplicationMetadata(
        self, pid, replicaMetadata, serialVersion, vendorSpecific=None
    ):
        
        response = self.updateReplicationMetadataResponse(
            pid, replicaMetadata, serialVersion, vendorSpecific
        )
        return self._read_boolean_response(response)
954868
public void sync() {
    if (getPipelinedResponseLength() > 0) {
      List<Object> unformatted = client.getMany(getPipelinedResponseLength());
      for (Object o : unformatted) {
        generateResponse(o);
      }
    }
  }
1200266
public void sync() throws Exception {
        try {
            JedisClusterPipeline pipeline = new JedisClusterPipeline(clusterInfoCache);
            execute(pipeline);
            pipeline.sync();
        } catch (JedisMovedDataException jre) {
            // if MOVED redirection occurred, rebuilds cluster's slot cache,
            // recommended by Redis cluster specification
            connectionHandler.renewSlotCache();
            if (maxAttempts > 0) {
                maxAttempts--;
                sync();
                return;
            }
            throw jre;
        } catch (Exception e) {
            throw e;
        }
    }
694054
private static boolean isMappingExist(RestHighLevelClient client, String index) throws Exception {
        GetMappingsResponse mapping = client.indices().getMapping(new GetMappingsRequest().indices(index), RequestOptions.DEFAULT);
        // Let's get the default mapping
        if (mapping.mappings().isEmpty()) {
            return false;
        }
        MappingMetaData doc = mapping.mappings().values().iterator().next();
        return !doc.getSourceAsMap().isEmpty();
    }