Create a global notification.

        Create and return a new global notification for an account.
504537
def create_global_notification(self, account_id, account_notification_end_at, account_notification_subject, account_notification_message, account_notification_start_at, account_notification_icon=None, account_notification_roles=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - account_id
        """ID"""
        path["account_id"] = account_id

        # REQUIRED - account_notification[subject]
        """The subject of the notification."""
        data["account_notification[subject]"] = account_notification_subject

        # REQUIRED - account_notification[message]
        """The message body of the notification."""
        data["account_notification[message]"] = account_notification_message

        # REQUIRED - account_notification[start_at]
        """The start date and time of the notification in ISO8601 format.
        e.g. 2014-01-01T01:00Z"""
        data["account_notification[start_at]"] = account_notification_start_at

        # REQUIRED - account_notification[end_at]
        """The end date and time of the notification in ISO8601 format.
        e.g. 2014-01-01T01:00Z"""
        data["account_notification[end_at]"] = account_notification_end_at

        # OPTIONAL - account_notification[icon]
        """The icon to display with the notification.
        Note: Defaults to warning."""
        if account_notification_icon is not None:
            self._validate_enum(account_notification_icon, ["warning", "information", "question", "error", "calendar"])
            data["account_notification[icon]"] = account_notification_icon

        # OPTIONAL - account_notification_roles
        """The role(s) to send global notification to.  Note:  ommitting this field will send to everyone
        Example:
          account_notification_roles: ["StudentEnrollment", "TeacherEnrollment"]"""
        if account_notification_roles is not None:
            data["account_notification_roles"] = account_notification_roles

        self.logger.debug("POST /api/v1/accounts/{account_id}/account_notifications with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("POST", "/api/v1/accounts/{account_id}/account_notifications".format(**path), data=data, params=params, no_data=True)
891197
def _on_notification(self, name, args):
        """"""
        if IS_PYTHON3:
            name = decode_if_bytes(name)
        handler = self._notification_handlers.get(name, None)
        if not handler:
            msg = self._missing_handler_error(name, 'notification')
            error(msg)
            self._on_async_err(msg + "\n")
            return

        debug('calling notification handler for "%s", args: "%s"', name, args)
        handler(*args)
750218
def notifications(self):
        
        if self._notifications is None:
            self._notifications = NotificationList(self._version, account_sid=self._solution['sid'], )
        return self._notifications
1189052
def create(self, id):
        
        resp = self.client.accounts.create(id=id)
        self.display(resp)
989589
function createGlobalFolder() {
        var deferred = Q.defer();

        // Create the results folder if it doesn't exist
        fs.exists(resultsDir, function(exists) {
            if (exists) {
                deferred.resolve();
            } else {
                debug('Creating the global results folder', resultsDir);
                fs.mkdir(resultsDir, function(err) {
                    if (err) {
                        deferred.reject(err);
                    } else {
                        deferred.resolve();
                    }
                });
            }
        });

        return deferred.promise;
    }
592538
def CreateReply(self, **attributes):
        
        return AcctPacket(AccountingResponse, self.id,
            self.secret, self.authenticator, dict=self.dict,
            **attributes)
764225
def open_notified_class
      class_eval do
        prepend NotificationActions
        attr_accessor :message, :notify_flag

        # Define association for the notified model
        has_many :notifications, class_name: 'SimpleNotifications::Record', as: :entity
        has_many :notifiers, through: :notifications, source: :sender, source_type: sender_class(@@options[:sender]).to_s
        has_many :read_deliveries, through: :notifications, source: :read_deliveries
        has_many :unread_deliveries, through: :notifications, source: :unread_deliveries

        # Callbacks
        after_create_commit :create_notification, if: proc {@@options[:callbacks].include?(:create)}
        after_update_commit :update_notification, if: proc {@@options[:callbacks].include?(:update)}
        after_destroy_commit :destroy_notification, if: proc {@@options[:callbacks].include?(:destroy)}

        NotificationActions.module_eval do
          @@options[:actions].each do |action|
            define_method(action) do
              run_callbacks action do
                super()
              end
            end

            define_method("before_#{action}".to_sym) do
            end

            define_method("after_#{action}".to_sym) do
              self.notify(sender: @@options[:sender], receivers: @@options[:receivers], message: default_message(self, @@options[:sender], action.to_s))
            end
          end
        end

        @@options[:actions].each do |action|
          define_model_callbacks action
          send("before_#{action}", "before_#{action}".to_sym)
          send("after_#{action}", "after_#{action}".to_sym)
        end

        #Example
        #post.notify(sender: :author, receivers: :followers, message: 'My Custom logic message')
        #post.create(content: '', notify: false) -> It does not create the notification.
        def notify(options = {})
          options[:sender] ||= @@options[:sender]
          options[:receivers] ||= @@options[:receivers]
          if notify_flag.nil? || (!notify_flag.nil? && !!notify_flag)
            raise 'SimpleNotification::SenderReceiverError' unless @@options[:sender] && @@options[:receivers]
            @message = options[:message] if options[:message]
            notification = notifications.build(entity: self, sender: get_obj(options[:sender]), message: default_message(self, get_obj(options[:sender]), 'created'))
            get_obj(options[:receivers]).each {|receiver| notification.deliveries.build(receiver: receiver)}
            notification.save
          end
        end

        def flush_notifications
          notifications.destroy_all
        end

        # Check if notifications has already been delivered.
        def notified?
          !notifications.blank?
        end

        def notificants
          SimpleNotifications::Record.includes(deliveries: :receiver)
              .collect(&:deliveries).flatten
              .collect(&:receiver)
        end

        def read_marked_notificants
          SimpleNotifications::Record.includes(deliveries: :receiver)
              .collect(&:deliveries).flatten
              .select{|record| record.is_read}
              .collect(&:receiver)
        end

        def unread_marked_notificants
          SimpleNotifications::Record.includes(deliveries: :receiver)
              .collect(&:deliveries).flatten
              .select{|record| !record.is_read}.collect(&:receiver)
        end

        # Mark notifications in read mode.
        # If notificants are provided then only those respective notifications will be marked read.
        # Else all will be marked as read.
        def mark_read(notificants = nil)
          (notificants ? unread_deliveries.where(receiver: notificants) : unread_deliveries).update_all(is_read: true)
        end

        # Mark notifications in unread mode.
        # If notificants are provided then only those respective notifications will be marked unread.
        # Else all will be marked as unread.
        def mark_unread(notificants = nil)
          (notificants ? read_deliveries.where(receiver: notificants) : read_deliveries).update_all(is_read: false)
        end

        def default_message(entity, sender, action)
          @message || (method(@@options[:notify_message]).call if !!@@options[:notify_message]) || "#{get_obj(sender).class.name} #{action} #{entity.class.name} #{entity.name}."
        end

        private

        def get_obj(sender_or_receivers)
          sender_or_receivers.kind_of?(Symbol) ? send(sender_or_receivers) : sender_or_receivers
        end

        def create_notification
          notify({sender: get_obj(@@options[:sender]), receivers: get_obj(@@options[:receivers]), message: default_message(self, get_obj(@@options[:sender]), 'created')})
        end

        def update_notification
          notify({sender: get_obj(@@options[:sender]), receivers: get_obj(@@options[:receivers]), message: default_message(self, get_obj(@@options[:sender]), 'updated')})
        end

        def destroy_notification
          notify({sender: get_obj(@@options[:sender]), receivers: get_obj(@@options[:receivers]), message: default_message(self, get_obj(@@options[:sender]), 'deleted')})
        end
      end
    end
1302082
def WriteUserNotification(self, notification):
    """"""
    if notification.username not in self.users:
      raise db.UnknownGRRUserError(notification.username)

    cloned_notification = notification.Copy()
    if not cloned_notification.timestamp:
      cloned_notification.timestamp = rdfvalue.RDFDatetime.Now()

    self.notifications_by_username.setdefault(cloned_notification.username,
                                              []).append(cloned_notification)
610852
def create_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"):
    '''
    

    '''

    auth = _auth(api_key, profile)
    request_uri = _get_telemetry_base(profile) + "/alerts"

    key = "telemetry.{0}.alerts".format(deployment_id)

    # set the notification channels if not already set
    post_body = {
        "deployment": deployment_id,
        "filter": data.get('filter'),
        "notificationChannel": get_notification_channel_id(data.get('escalate_to')).split(),
        "condition": {
            "metric": metric_name,
            "max": data.get('max'),
            "min": data.get('min')
        }
    }

    try:
        response = requests.post(request_uri, data=salt.utils.json.dumps(post_body), headers=auth)
    except requests.exceptions.RequestException as e:
        # TODO: May be we should retry?
        log.error(six.text_type(e))

    if response.status_code >= 200 and response.status_code < 300:
        # update cache
        log.info('Created alarm on metric: %s in deployment: %s', metric_name, deployment_id)
        log.debug('Updating cache for metric %s in deployment %s: %s',
                  metric_name, deployment_id, response.json())
        _update_cache(deployment_id, metric_name, response.json())
    else:
        log.error(
            'Failed to create alarm on metric: %s in '
            'deployment %s: payload: %s',
            metric_name, deployment_id, salt.utils.json.dumps(post_body)
        )

    return response.status_code >= 200 and response.status_code < 300, response.json()
573778
def WriteUserNotification(self, notification, cursor=None):
    """"""
    # Copy the notification to ensure we don't modify the source object.
    args = {
        "username_hash":
            mysql_utils.Hash(notification.username),
        "notification_state":
            int(notification.state),
        "notification":
            notification.SerializeToString(),
    }
    query = "INSERT INTO user_notification {columns} VALUES {values}".format(
        columns=mysql_utils.Columns(args),
        values=mysql_utils.NamedPlaceholders(args))
    try:
      cursor.execute(query, args)
    except MySQLdb.IntegrityError:
      raise db.UnknownGRRUserError(notification.username)
890694
public function create()
    {
        $entry = $this->collection->newInstance()->set($this->getCriteria());

        $this->data['entry'] = $entry;

        if ($this->request->isPost()) {
            try {
                $result = $entry->set($this->request->getBody())->save();

                h('notification.info', $this->clazz.' created.');

                h('controller.create.success', array(
                    'model' => $entry
                ));
            } catch (Stop $e) {
                throw $e;
            } catch (Exception $e) {
                // no more set notification.error since notificationmiddleware will
                // write this later
                // h('notification.error', $e);

                h('controller.create.error', array(
                    'model' => $entry,
                    'error' => $e,
                ));

                // rethrow error to make sure notificationmiddleware know what todo
                throw $e;
            }
        }

    }
852176
def instance():
        

        if not hasattr(NotificationManager, '_instance') or NotificationManager._instance is None:
            NotificationManager._instance = NotificationManager()
        return NotificationManager._instance
875317
public function notifyCreate()
    {
        if (\Yii::$app->reviews2->notifyEmails) {
            foreach (\Yii::$app->reviews2->notifyEmails as $email) {
                \Yii::$app->mailer->compose('@skeeks/cms/reviews2/mail/new-message', [
                    'model' => $this
                ])
                    ->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName])
                    ->setTo($email)
                    ->setSubject(\Yii::t('skeeks/reviews2', "Added a new review") . " #" . $this->id)
                    ->send();
            }
        }
    }
1018466
protected function createMessage()
    {
        $message = new Message(new Swift_Message);

        // If a global from address has been specified we will set it on every message
        // instances so the developer does not have to repeat themselves every time
        // they create a new message. We will just go ahead and push the address.
        if (isset($this->from['address'])) {
            $message->from($this->from['address'], $this->from['name']);
        }

        return $message;
    }
490095
public function sendGlobalUserActivated()
    {
        if ($this->_sendMails) {
            $row = $this->getModel()->getKwfUserRowById($this->id);
            $mail = new Kwf_User_Mail_GlobalUserActivated($row);
            $mail->send();
            $this->writeLog('user_mail_GlobalUserActivation');
        }
    }
1084431
def add_global(self, **values):
        """"""
        with self._lock:
            self._ensure_global()
            self._gpayload.update(**values)
483825
def CreateApproval(self,
                     reason=None,
                     notified_users=None,
                     email_cc_addresses=None):
    """"""

    if not reason:
      raise ValueError("reason can't be empty")

    if not notified_users:
      raise ValueError("notified_users list can't be empty.")

    approval = user_pb2.ApiHuntApproval(
        reason=reason,
        notified_users=notified_users,
        email_cc_addresses=email_cc_addresses or [])
    args = user_pb2.ApiCreateHuntApprovalArgs(
        hunt_id=self.hunt_id, approval=approval)

    data = self._context.SendRequest("CreateHuntApproval", args)
    return HuntApproval(
        data=data, username=self._context.username, context=self._context)