Post changes back to DocumentCloud
774225
def put(self, method, params):
        
        # Prepare the params, first by adding a custom command to
        # simulate a PUT request even though we are actually POSTing.
        # This is something DocumentCloud expects.
        params['_method'] = 'put'
        # Some special case handling of the document_ids list, if it exists
        if params.get("document_ids", None):
            # Pull the document_ids out of the params
            document_ids = params.get("document_ids")
            del params['document_ids']
            params = urllib.parse.urlencode(params, doseq=True)
            # These need to be specially formatted in the style documentcloud
            # expects arrays. The example they provide is:
            # ?document_ids[]=28-boumediene&document_ids[]=\
            # 207-academy&document_ids[]=30-insider-trading
            params += "".join([
                '&document_ids[]=%s' % id for id in document_ids
            ])
        # More special case handler of key/value data tags, if they exist
        elif params.get("data", None):
            # Pull them out of the dict
            data = params.get("data")
            del params['data']
            params = urllib.parse.urlencode(params, doseq=True)
            # Format them in the style documentcloud expects
            # ?data['foo']=bar&data['tit']=tat
            params += "".join([
                '&data[%s]=%s' % (
                    urllib.parse.quote_plus(key.encode("utf-8")),
                    urllib.parse.quote_plus(value.encode("utf-8"))
                ) for key, value in
                data.items()
            ])
        else:
            # Otherwise, we can just use the vanilla urllib prep method
            params = urllib.parse.urlencode(params, doseq=True)

        # Make the request
        self._make_request(
            self.BASE_URI + method,
            params.encode("utf-8"),
        )
463078
@RequirePOST
    public synchronized HttpResponse doConfigSubmit( StaplerRequest req) throws IOException, ServletException, FormException {
        BulkChange bc = new BulkChange(MONITORS_OWNER);
        try {
            Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
            monitors.rebuild(req,req.getSubmittedForm(),getNodeMonitorDescriptors());

            // add in the rest of instances are ignored instances
            for (Descriptor<NodeMonitor> d : NodeMonitor.all())
                if(monitors.get(d)==null) {
                    NodeMonitor i = createDefaultInstance(d, true);
                    if(i!=null)
                        monitors.add(i);
                }

            // recompute the data
            for (NodeMonitor nm : monitors) {
                nm.triggerUpdate();
            }

            return FormApply.success(".");
        } finally {
            bc.commit();
        }
    }
286723
def publish_for_collection(self, collection_name):
        
        self.revisions = BaseAsyncMotorDocument("%s_revisions" % collection_name, self.settings)

        changes = yield self.__get_pending_revisions()

        if len(changes) > 0:

            self.logger.info("%s revisions will be actioned" % len(changes))

            for change in changes:
                try:
                    self.logger.info("Applying %s action %s - %s to document: %s/%s" % (change.get("action"), change.get("id"), change.get("meta",{}).get("comment", "No Comment"), change.get("collection"), change.get("master_id")))

                    stack = AsyncSchedulableDocumentRevisionStack(
                        change.get("collection"),
                        self.settings,
                        master_id=change.get("master_id")
                    )

                    revision = yield stack.pop()

                    self.logger.debug(revision)

                except Exception as ex:
                    self.logger.error(ex)
969430
def change(self, event):
        """"""

        try:
            data, schema, user, client = self._get_args(event)
        except AttributeError:
            return

        try:
            uuid = data['uuid']
            change = data['change']
            field = change['field']
            new_data = change['value']
        except KeyError as e:
            self.log("Update request with missing arguments!", data, e,
                     lvl=critical)
            self._cancel_by_error(event, 'missing_args')
            return

        storage_object = None

        try:
            storage_object = objectmodels[schema].find_one({'uuid': uuid})
        except Exception as e:
            self.log('Change for unknown object requested:', schema, data, lvl=warn)

        if storage_object is None:
            self._cancel_by_error(event, 'not_found')
            return

        if not self._check_permissions(user, 'write', storage_object):
            self._cancel_by_permission(schema, data, event)
            return

        self.log("Changing object:", storage_object._fields, lvl=debug)
        storage_object._fields[field] = new_data

        self.log("Storing object:", storage_object._fields, lvl=debug)
        try:
            storage_object.validate()
        except ValidationError:
            self.log("Validation of changed object failed!",
                     storage_object, lvl=warn)
            self._cancel_by_error(event, 'invalid_object')
            return

        storage_object.save()

        self.log("Object stored.")

        result = {
            'component': 'hfos.events.objectmanager',
            'action': 'change',
            'data': {
                'schema': schema,
                'uuid': uuid
            }
        }

        self._respond(None, result, event)
368538
private void changeDocumentToThis(NodeImpl node) {
        Map<String, UserData> userData = node.document.getUserDataMapForRead(node);
        if (!userData.isEmpty()) {
            getUserDataMap(node).putAll(userData);
        }
        node.document = this;

        // change the document on all child nodes
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            changeDocumentToThis((NodeImpl) list.item(i));
        }

        // change the document on all attribute nodes
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            NamedNodeMap attributes = node.getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                changeDocumentToThis((AttrImpl) attributes.item(i));
            }
        }
    }
857792
function handleEditorChange(session, document, previousDocument) {

        if (!currentModule) {
            currentModule = new TernModule();
        }
        
        return currentModule.handleEditorChange(session, document, previousDocument);
    }
1313705
function clipPostChange(doc, change, pos) {
    if (!posLess(change.from, pos)) return clipPos(doc, pos);
    var diff = (change.text.length - 1) - (change.to.line - change.from.line);
    if (pos.line > change.to.line + diff) {
      var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
      if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
      return clipToLen(pos, getLine(doc, preLine).text.length);
    }
    if (pos.line == change.to.line + diff)
      return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
                       getLine(doc, change.to.line).text.length - change.to.ch);
    var inside = pos.line - change.from.line;
    return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
  }
989194
def push_doc(self, document):
        ''' 

        '''
        msg = self._protocol.create('PUSH-DOC', document)
        reply = self._send_message_wait_for_reply(msg)
        if reply is None:
            raise RuntimeError("Connection to server was lost")
        elif reply.header['msgtype'] == 'ERROR':
            raise RuntimeError("Failed to push document: " + reply.content['text'])
        else:
            return reply
55308
private ChangeEvent<BsonDocument> getSynthesizedRemoteChangeEventForDocument(
      final CoreRemoteMongoCollection<BsonDocument> remoteColl,
      final BsonValue documentId
  ) {
    return getSynthesizedRemoteChangeEventForDocument(
        remoteColl.getNamespace(),
        documentId,
        remoteColl.find(getDocumentIdFilter(documentId)).first());
  }
44851
function update(form) {
      // refuse to work with invalid data
      if (!vm.clientModelDoc._id || form && !form.$valid) {
        return;
      }

      ClientModelDocService.update(vm.clientModelDoc)
        .then(updateClientModelDocSuccess)
        .catch(updateClientModelDocCatch);

      function updateClientModelDocSuccess(updatedClientModelDoc) {
        // update the display name after successful save
        vm.displayName = updatedClientModelDoc.name;
        Toast.show({text: 'ClientModelDoc ' + vm.displayName + ' updated'});
        if (form) {
          form.$setPristine();
        }
      }

      function updateClientModelDocCatch(err) {
        Toast.show({
          type: 'warn',
          text: 'Error while updating ClientModelDoc ' + vm.displayName,
          link: {state: $state.$current, params: $stateParams}
        });

        if (form && err) {
          form.setResponseErrors(err.data);
        }
      }
    }
707160
function processRetrievedContent(content, filePrismicMetadata, queryKey, ctx) {
            if (content.results != null && content.results.length > 0) {
                var queryMetadata = filePrismicMetadata[queryKey];
                for (var i = 0; i < content.results.length; i++) {
                    var result = processRetrievedDocument(content.results[i], filePrismicMetadata, queryKey, ctx);
                    filePrismicMetadata[queryKey].results.push(result);
                }
            }
        }
773531
function _onDocumentSaved(event, doc) {
        if (!Inspector.connected() || !_server) {
            return;
        }

        var absolutePath            = doc.file.fullPath,
            liveDocument            = absolutePath && _server.get(absolutePath),
            liveEditingEnabled      = liveDocument && liveDocument.isLiveEditingEnabled  && liveDocument.isLiveEditingEnabled();

        // Skip reload if the saved document has live editing enabled
        if (liveEditingEnabled) {
            return;
        }

        var documentUrl     = _server.pathToUrl(absolutePath),
            wasRequested    = agents.network && agents.network.wasURLRequested(documentUrl);

        if (wasRequested) {
            reload();
        }
    }
809538
private void documentChanged() {
    // View of the component has not been updated at the time
    // the DocumentEvent is fired

    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          int endPos = component.getDocument().getLength();
          Rectangle rect = component.modelToView(endPos);

          if (rect != null && rect.y != lastHeight) {
            setPreferredWidth();
            repaint();
            lastHeight = rect.y;
          }
        } catch (BadLocationException ex) {
          /* nothing to do */
        }
      }
    });
  }
1152730
def _post_document_batch(self, batch):
          # noqa
        target_batch = '/2013-01-01/documents/batch'
        url = self.endpoint_url + target_batch
        return requests.post(url, data=batch, headers={'Content-type': 'application/json'})
594012
def put_changes_document_stream_with_http_info(request)
      raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesDocumentStreamRequest

      @api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_document_stream ...' if @api_client.config.debugging
      # resource path
      local_var_path = '/comparison/compareDocuments/changes/stream'

      # query parameters
      query_params = {}

      # header parameters
      header_params = {}
      # HTTP header 'Accept' (if needed)
      header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
      # HTTP header 'Content-Type'
      header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])

      # form parameters
      form_params = {}

      # http body (model)
      post_body = @api_client.object_to_http_body(request.request)
      data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
                                                        header_params: header_params,
                                                        query_params: query_params,
                                                        form_params: form_params,
                                                        body: post_body,
                                                        access_token: get_access_token,
                                                        return_type: 'File')
      if @api_client.config.debugging
        @api_client.config.logger.debug "API called:
        ChangesApi#put_changes_document_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
      end
      [data, status_code, headers]
    end
804043
def response_change(self, request, obj):
        """"""
        opts = self.opts.app_label, self.opts.model_name
        pk_value = obj._get_pk_val()

        if '_continue' in request.POST:
            msg = _(
                'The %(name)s block was changed successfully. You may edit it again below.'
            ) % {'name': force_text(self.opts.verbose_name)}

            self.message_user(request, msg, messages.SUCCESS)

            # We redirect to the save and continue page, which updates the
            # parent window in javascript and redirects back to the edit page
            # in javascript.
            return HttpResponseRedirect(reverse(
                'admin:%s_%s_continue' % opts,
                args=(pk_value,),
                current_app=self.admin_site.name
            ))

        # Update column and close popup - don't bother with a message as they won't see it
        return self.response_rerender(request, obj, 'admin/glitter/update_column.html')
347026
function sendAnyChanges() {
                // Get all changes after syncedRevision that was not performed by the client we're talkin' to.
                var changes = db.changes.filter(function (change) { return change.rev > syncedRevision && change.source !== conn.clientIdentity; });
                // Compact changes so that multiple changes on same object is merged into a single change.
                var reducedSet = reduceChanges(changes, conn.clientIdentity);
                // Convert the reduced set into an array again.
                var reducedArray = Object.keys(reducedSet).map(function (key) { return reducedSet[key]; });
                // Notice the current revision of the database. We want to send it to client so it knows what to ask for next time.
                var currentRevision = db.revision;

                conn.sendText(JSON.stringify({
                    type: "changes",
                    changes: reducedArray,
                    currentRevision: currentRevision,
                    partial: false // Tell client that these are the only changes we are aware of. Since our mem DB is syncronous, we got all changes in one chunk.
                }));

                syncedRevision = currentRevision; // Make sure we only send revisions coming after this revision next time and not resend the above changes over and over.
            }