/*
The source of Slack message can be either Json asset or  process variable.
1774
public JSONObject getMessage() throws ActivityException {
        String message = null;
        String slackMessageName = getAttributeValueSmart(SLACK_MESSAGE);
        if (slackMessageName == null)
            throw new ActivityException("slack message attribute is not set");
        Asset template = AssetCache.getAsset(slackMessageName);

        if (template == null) {
            message = slackMessageName;
        }
        else {
            message = context.evaluateToString(template.getStringContent());
        }

        JSONObject json = new JSONObject();
        String env = ApplicationContext.getRuntimeEnvironment().toUpperCase();
        json.put("text", env + " - " + getSlackPrefix() + " - " + message);

        String altText = null;
        if (json.has("text")) {
            String text = json.getString("text");
            if (text.length() > 200)
                altText = text.substring(0, 197) + "...";
        }
        if (altText != null)
            json.put("text", altText);
        return json;
    }
476798
def send_slack_message(message):
    """"""

    if 'SLACK_WEB_HOOK' not in os.environ:
        raise EnvironmentError("Could not find SLACK_WEB_HOOK environment variable")

    webhook = os.environ['SLACK_WEB_HOOK']

    r = requests.post(webhook, json={'text':message, 'username': 'Release Bot'})
    if r.status_code != 200:
        raise RuntimeError("Could not post message to slack channel")
1039018
function processJsonpUrl( requestSettings ) {
		if ( requestSettings.type.toUpperCase() === "GET" ) {
			if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {
				requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +
					(requestSettings.jsonp || "callback") + "=?";
			}
		} else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {
			requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";
		}
	}
968332
function pushListener(event) {
    var jsonString = event.data && event.data.text() ? event.data.text() : null;

    if (!jsonString) {
      console.log('Leanplum: Push received without payload, skipping display.');
      return;
    }

    // noinspection JSCheckFunctionSignatures
    var options = JSON.parse(jsonString);

    /** @namespace options.title The title of the push notification. **/
    /** @namespace options.tag The id of the push notification **/
    if (!options || !options.title || !options.tag) {
      console.log('Leanplum: No options, title or tag/id received, skipping ' + 'display.');
      return;
    }

    // Extract open action url. We only support open url action for now.
    /** @namespace options.data.openAction The openAction of the push notification. **/
    if (options.data && options.data.openAction && options.data.openAction.hasOwnProperty(ACTION_NAME_KEY) && options.data.openAction[ACTION_NAME_KEY] === OPEN_URL_ACTION && options.data.openAction.hasOwnProperty(ARG_URL)) {
      openActions[options.tag] = options.data.openAction[ARG_URL];
    }

    // Extract title and delete from options.
    var title = options.title;
    Reflect.deleteProperty(options, 'title');
    /** @namespace self.registration **/
    /** @namespace self.registration.showNotification **/
    event.waitUntil(self.registration.showNotification(title, options));
  }
604416
function processMultiBytePacketStop (o) {
  processMultiBytePacket(o);
  const str = o.multiPacketBuffer.toString();
  o.multiPacketBuffer = null;
  return {
    'message': str
  };
}
714098
function onFileReady(err, data) {
    if (err) {
      if (onDone) onDone(err)
      else console.error('>>>' + err);
      return;
    }

    var fileContent = data.toString();

    var msg = {
      text:    fileContent,
      mode:    flavor,
      context: context
    };

    var jsonMsg = JSON.stringify(msg);

    var options = {
      method: 'POST',
      preambleCRLF: true,
      postambleCRLF: true,
      uri: 'https://api.github.com/markdown',
      'content-type': 'application/json',
      headers: {
        'User-Agent' : userName
      },
      body: jsonMsg
    };

    //=======================================================
    // Call the Github Markdown API to parse the file content
    //=======================================================
    request(options, handleResponse.bind(this));

    //======================================================
    // Enhance the output of the Github Markdown API with
    // optional header or trailer.
    //======================================================
    function handleResponse(err, response, body) {
      if (this.debug) console.error('>>>handling response...');
      if (err) {
        if (onDone) onDone(err)
        else console.error('>>>upload to github failed: ', err);
        return;
      }

      if (stylesheet || title) {
        if (titleText == null) titleText = fileName;
        this.cat('<!DOCTYPE html>\n' +
                 '<html>\n' +
                 '<head>\n' +
                 '  <title>' + titleText + '</title>\n' +
                 '  <link rel="stylesheet" href="' + stylesheet + '">\n' +
                 '</head>\n' +
                 '<body>\n' );
      }

      this.cat(body);
      this.cat('\n');

      if (stylesheet || title) {
        this.cat( '</body>\n</html>\n' );
      }

      if (this.debug) console.error('>>>finished getting code');
      this.done = true;
      if (onDone) onDone();
    } // end handleResponse
  }
1103478
function sink (msg, done) {
    var metric = msg.metric
    var as_text = JSON.stringify(metric, null, 1)

    console.log(as_text)

    done()
  }
904164
function onStringMessage(data)
    {
        try
        {
            data = (scope.encode) ? JSON.parse(atob(data)) : JSON.parse(data);
        
            switch(data.ev)
            {
                case InternalEvents.REDIRECT:
                {
                    changeServer(data.data);
                    break;
                }
                case InternalEvents.CONNECTED:
                {
                    scope.id = data.data;
                    if(scope.onConnected)
                    {
                        scope.onConnected(scope.id);
                    }
                    break;
                }
                case InternalEvents.JOINED_ROOM:
                {
                    scope.roomUsers   = data.data.users;
                    scope.room        = data.data.room;
                    scope.params      = data.data.params;
                    scope.rtcId       = data.data.rtcId;
                    scope.useRTC      = data.data.useRTC;
                    scope.rtcFallback = data.data.rtcFallback;
                    scope.byteType    = data.data.byteType;

                    if(scope.onJoinedRoom)
                    {
                        scope.onJoinedRoom(scope.room,scope.params);
                    }
                    break;
                }
                case InternalEvents.ROOM_PARAMS:
                {
                    scope.params = data.data;
                    if(scope.onRoomUpdate)
                    {
                        scope.onRoomUpdate(scope.params);
                    }
                    break;
                }
                case InternalEvents.USER_JOINED_ROOM:
                {
                    if(scope.roomUsers)
                    {
                        var hasObject = false;
                        for(var num = 0; num < scope.roomUsers.length; num++)
                        {
                            if(scope.roomUsers[num].id==data.data.id)
                            {
                                hasObject = true;
                                break;
                            }
                        }
                        if(hasObject == false)
                        {
                            scope.roomUsers.push(data.data);
                        }
                    }
                    if(scope.onClientJoinedRoom)
                    {
                        scope.onClientJoinedRoom(data.data.id);
                    }
                    break;
                }
                case InternalEvents.LEFT_ROOM:
                {
                    if(scope.roomUsers)
                    {
                        scope.roomUsers = [];
                    }
                    if(scope.onLeftRoom)
                    {
                        scope.onLeftRoom();
                    }
                    break;
                }
                case InternalEvents.USER_LEFT_ROOM:
                {
                    if(scope.roomUsers)
                    {
                        for(var num = 0; num < scope.roomUsers.length; num++)
                        {
                            if(scope.roomUsers[num].id==data.data)
                            {
                                scope.roomUsers.splice(num,1);
                                break;
                            }
                        }
                    }
                    if(scope.onClientLeftRoom)
                    {
                        scope.onClientLeftRoom(data.data);
                    }
                    break;
                }
                case InternalEvents.SDP_DESCRIPTION:
                {
                    if(scope.onSDPDescription)
                    {
                        scope.onSDPDescription(data.id,data.rtcId,data.data);
                    }
                    break;
                }
                case InternalEvents.ICE_CANDIDATE:
                {
                    if(scope.onIceCandidate)
                    {
                        scope.onIceCandidate(data.id,data.data);
                    }
                    break;
                }
                case InternalEvents.RTC_FALLBACK_LIST:
                {
                    scope.fallbackUsers = data.data;
                    
                    break;
                }
                case InternalEvents.RTC_FALLBACK:
                {
                    if(scope.onRTCFallback)
                    {
                        scope.onRTCFallback(data.from,data.data,false);
                    }
                    break;
                }
                case InternalEvents.PING:
                {
                    scope.send("0",MessageType.PING);
                    break;
                }
                default:
                {
                    if(data.ev)
                    {
                        if(scope.onMessage)
                        {
                            scope.onMessage(data);
                        }
                    }
                    else
                    {
                        if(scope.onRawMessage)
                        {
                            scope.onRawMessage(data);
                        }
                    }
                    break;
                }
            }
        }
        catch(e)
        {
            if(scope.onRawMessage)
            {
                scope.onRawMessage(data);
            }
        }
    }
55891
@Override
	protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData)
			throws IOException {
		
		if(status.getProcessingType().equals(BundleProcessingStatus.FILE_PROCESSING_TYPE)
				&& status.getJawrConfig().getResourceType().equals(JawrConstant.JS_TYPE)){
			if (bundleData.toString().trim().endsWith(")")) {
				bundleData.append(";");
			}
		}
		
		return bundleData;
	}
975276
def message(text, options = {}, env = :prod, type = :normal)
      if type == :normal
        data = normal_notification(text, options)
      elsif type == :silent
        data = silent_notification(text, options)
      elsif type == :nosound
        data = nosound_notification(text, options)
      end
      return dev_json(data) if env == :dev
      prod_json(data)
    end
682887
public static void postJsonMessage(StringEntity input) {
		String pageToken = FbBotMillContext.getInstance().getPageToken();
		// If the page token is invalid, returns.
		if (!validatePageToken(pageToken)) {
			return;
		}

		String url = FbBotMillNetworkConstants.FACEBOOK_BASE_URL
				+ FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken;
		postInternal(url, input);
	}
204782
function (input, readCallback) {
    if (compileStandard !== null) {
      return compileStandard(input, readCallback);
    }

    function formatFatalError (message) {
      return JSON.stringify({
        errors: [
          {
            'type': 'SOLCError',
            'component': 'dsolcjs',
            'severity': 'error',
            'message': message,
            'formattedMessage': 'Error: ' + message
          }
        ]
      });
    }

    if (readCallback !== undefined && typeof readCallback !== 'function') {
      return formatFatalError('Invalid import callback supplied');
    }

    try {
      input = JSON.parse(input);
    } catch (e) {
      return formatFatalError('Invalid JSON supplied: ' + e.message);
    }

    if (input['language'] !== 'Solidity') {
      return formatFatalError('Only Solidity sources are supported');
    }

    // NOTE: this is deliberately `== null`
    if (input['sources'] == null || input['sources'].length === 0) {
      return formatFatalError('No input specified');
    }

    // Bail out early
    if ((input['sources'].length > 1) && (compileJSONMulti === null)) {
      return formatFatalError('Multiple sources provided, but compiler only supports single input');
    }

    function isOptimizerEnabled (input) {
      return input['settings'] && input['settings']['optimizer'] && input['settings']['optimizer']['enabled'];
    }

    function translateSources (input) {
      var sources = {};
      for (var source in input['sources']) {
        if (input['sources'][source]['content'] !== null) {
          sources[source] = input['sources'][source]['content'];
        } else {
          // force failure
          return null;
        }
      }
      return sources;
    }

    function librariesSupplied (input) {
      if (input['settings'] !== null) {
        return input['settings']['libraries'];
      }
    }

    function translateOutput (output, libraries) {
      try {
        output = JSON.parse(output);
      } catch (e) {
        return formatFatalError('Compiler returned invalid JSON: ' + e.message);
      }
      output = translate.translateJsonCompilerOutput(output, libraries);
      if (output == null) {
        return formatFatalError('Failed to process output');
      }
      return JSON.stringify(output);
    }

    var sources = translateSources(input);
    if (sources === null || Object.keys(sources).length === 0) {
      return formatFatalError('Failed to process sources');
    }

    // Try linking if libraries were supplied
    var libraries = librariesSupplied(input);

    // Try to wrap around old versions
    if (compileJSONCallback !== null) {
      return translateOutput(compileJSONCallback(JSON.stringify({ 'sources': sources }), isOptimizerEnabled(input), readCallback), libraries);
    }

    if (compileJSONMulti !== null) {
      return translateOutput(compileJSONMulti(JSON.stringify({ 'sources': sources }), isOptimizerEnabled(input)), libraries);
    }

    // Try our luck with an ancient compiler
    if (compileJSON !== null) {
      return translateOutput(compileJSON(sources[Object.keys(sources)[0]], isOptimizerEnabled(input)), libraries);
    }

    return formatFatalError('Compiler does not support any known interface.');
  }
380169
function notifySlack ({ channel, text, webhook }) {
  return fetch(webhook, {
    body: JSON.stringify({
      channel,
      text
    }),
    headers: {
      'Content-Type': 'application/json'
    },
    method: 'POST'
  })
    .then(response => response.text())
    .catch(err => {
      logToErrorConsole('Error posting to Slack webhook')
      logToErrorConsole(err)
      return err
    })
}
1188207
function receiveMessageWithApiai(messageText, senderID, event) {
    var trequest = apiaiapp.textRequest(messageText, {
        sessionId: senderID
    });
    trequest.on('response', function(response) {
      
        var message = janis.convertFromApiaiResponseToMessage(response);
        var messageData = {
            recipient: {
                id: senderID
            },
            message: message
        }
        callSendAPI(messageData);

        if (response.result.action == "human") {
            // send a janis alert to your slack channel
            // that the user could use assistance
            janis.assistanceRequested(event);
        } else if (response.result.action == "input.unknown" ||
            (response.result.metadata.intentId == null && response.result.fulfillment.speech == "")) {
            //associate an action in api.ai with your fallback intents so you can catch them.
            //in this example, "input.unknown" is the action set in api.ai on the Default Fallback Intent.
          
            //capture conversational ‘dead-ends’ 
            //and send janis an alert to your slack channel
            janis.logUnknownIntent(event);
        }
    });
    trequest.on('error', function(error) {
        console.log(error);
        //capture conversational ‘dead-ends’ 
        //and send janis an alert to your slack channel
        janis.logUnkownIntent(event);
        sendTextMessage(senderID, error.message);
    });
    trequest.end();
}
562751
private ObjectJS jsonMessage(String message, StringifierFactory jsonStringifierFactory) {
		ObjectJS timelineJS = new ObjectJS();
		timelineJS.setSimpleAttribute("message", message, jsonStringifierFactory.getStringifier(String.class));
		return timelineJS;
	}
475850
function SlackWebOut(n) {
    RED.nodes.createNode(this, n);

    var node = this;
    this.client = n.client;
    this.clientNode = RED.nodes.getNode(this.client);

    node.status(statuses.disconnected);

    if (node.client) {
      SetConfigNodeConnectionListeners(node);

      node.on("input", function(msg) {
        SlackDebug("slack-web-out incomiming message", msg);

        var method = msg.topic;
        var options = msg.payload;

        if (
          !method ||
          typeof method !== "string" ||
          !method instanceof String
        ) {
          node.error("invalid msg.topic");
          return null;
        }

        /**
         * Try to help with common use case, set channel based on lookup if starts with @ or #
         *
         * https://api.slack.com/methods/chat.postMessage
         */
        if (
          method == "chat.postMessage" ||
          method == "chat.postEphemeral" ||
          method == "chat.meMessage"
        ) {
          if (options.channel[0] == "@" || options.channel[0] == "#") {
            var channel = node.clientNode.findChannelByName(options.channel);
            if (channel && channel.id) {
              options.channel = channel.id;
            }
          }
        }

        /**
         * special handling for simple use-case
         */
        if (method[0] == "@" || method[0] == "#") {
          var channel = node.clientNode.findChannelByName(method);
          if (!channel || !channel.id) {
            node.error("invalid channel: " + method);
            return null;
          }
          method = "chat.postMessage";
          options = {
            channel: channel.id,
            text: msg.payload
            //as_user: true
          };
        }

        /**
         * custom per-method logic
         */
        switch (method) {
          case "chat.postMessage":
          case "chat.postEphemeral":
          case "chat.meMessage":
            // force text to be a string
            options.text = ValueToString(options.text);
            break;
        }

        node.status(statuses.sending);
        msg.slackState = node.clientNode.state;

        SlackDebug("slack-web-out call", method, options);
        node.clientNode.webClient
          .apiCall(method, options)
          .then(res => {
            SlackDebug("slack-web-out call response", res);
            msg.payload = node.clientNode.dressResponseMessage(res);
            node.send(msg);
            node.status(statuses.connected);
          })
          .catch(e => {
            SlackDebug("slack-web-out error response", e.data);
            msg.payload = e.data;
            node.send(msg);
            node.status(statuses.connected);
          });
      });
    } else {
      node.status(statuses.misconfigured);
    }
  }
579360
function buildJSONSource() {

  var data = getModularSource();

  addCorePackage();
  prepareData();
  outputJSON('source.json', data);

  function addCorePackage() {
    data.modules.unshift({
      name: 'Core'
    });
    data.packages.unshift({
      name: 'Sugar',
      type: 'core',
      module: 'Core',
      dependencies: [],
      bodyWithComments: readFile('lib/core.js').trim()
    });
  }

  function bundleSetPackages() {
    var packages = [], handledSets = {}, p;

    for (var i = 0; i < data.packages.length; i++) {
      p = data.packages[i];
      if (p.set) {
        // If the package has been handled already then just skip.
        if (!handledSets[p.namespace + p.setName]) {
          packages.push({
            setName: p.setName,
            name: p.setName.replace(/[\[\]]/g, ''),
            sample: p.set.slice(0, 3).concat('...').join(', '),
            type: p.type,
            alias: p.alias,
            module: p.module,
            namespace: p.namespace,
            dependencies: p.dependencies,
            bodyWithComments: p.bodyWithComments
          });
          handledSets[p.namespace + p.setName] = true;
        }
      } else {
        packages.push(p);
      }
    }

    return packages;
  }

  function prepareData() {
    var bundledPackages = bundleSetPackages();
    data.modules.forEach(function(m) {
      indentField(m, 'comment');
    });
    bundledPackages.forEach(function(p) {

      // Pre-indenting all packages rather than doing it on compile to
      // save some cycles and also correctly calculate the package size.
      indentField(p, 'blockStart');
      indentField(p, 'blockEnd');
      indentField(p, 'bodyWithComments');

      cleanSourcePackage(p);
    });
    data.packages = bundledPackages;
  }

  function indentField(p, field) {
    if (p[field]) {
      p[field] = p[field].replace(/^(?=.)/gm, '  ');
    }
  }

  function cleanSourcePackage(p) {
    if (sourcePackageIsDependency(p)) {
      delete p.type;
    }
    delete p.vars;
    delete p.target;
    delete p.body;
    delete p.path;
    delete p.assigns;
    delete p.comments;
    delete p.defineMethod;
    delete p.varDependencies;
    compactField(p, 'bodyWithComments');
    compactField(p, 'dependencies');
  }

  function compactField(p, field) {
    var val = p[field];
    if (!val || (Array.isArray(val) && !val.length)) {
      delete p[field];
    }
  }

}