text:
"""
Player (OOC) commands. These are stored on the Player object
and self.caller is thus always a Player, not an Object/Character.

These commands go in the PlayerCmdset and are accessible also
when puppeting a Character (although with lower priority)

These commands use the player_caller property which tells the command
parent (MuxCommand, usually) to setup caller correctly. They use
self.player to make sure to always use the player object rather than
self.caller (which change depending on the level you are calling from)
The property self.character can be used to access the character when
these commands are triggered with a connected character (such as the
case of the @ooc command), it is None if we are OOC.

Note that under MULTISESSION_MODE > 2, Player- commands should use
self.msg() and similar methods to reroute returns to the correct
method. Otherwise all text will be returned to all connected sessions.

"""
from builtins import range

import time
from django.conf import settings
from evennia.server.sessionhandler import SESSIONS
from evennia.utils import utils, create, search, prettytable, evtable

COMMAND_DEFAULT_CLASS = utils.class_from_module(settings.COMMAND_DEFAULT_CLASS)

_MAX_NR_CHARACTERS = settings.MAX_NR_CHARACTERS
_MULTISESSION_MODE = settings.MULTISESSION_MODE

# limit symbol import for API
__all__ = ("CmdOOCLook", "CmdIC", "CmdOOC", "CmdPassword", "CmdQuit",
           "CmdCharCreate", "CmdOption", "CmdSessions", "CmdWho",
           "CmdColorTest", "CmdQuell")

class MuxPlayerLookCommand(COMMAND_DEFAULT_CLASS):
    """
    Custom parent (only) parsing for OOC looking, sets a "playable"
    property on the command based on the parsing.

    """

    def parse(self):
        "Custom parsing"

        super(MuxPlayerLookCommand, self).parse()

        if _MULTISESSION_MODE < 2:
            # only one character allowed - not used in this mode
            self.playable = None
            return

        playable = self.player.db._playable_characters
        if playable is not None:
            # clean up list if character object was deleted in between
            if None in playable:
                playable = [character for character in playable if character]
                self.player.db._playable_characters = playable
        # store playable property
        if self.args:
            self.playable = dict((utils.to_str(char.key.lower()), char)
                         for char in playable).get(self.args.lower(), None)
        else:
            self.playable = playable

# Obs - these are all intended to be stored on the Player, and as such,
# use self.player instead of self.caller, just to be sure. Also self.msg()
# is used to make sure returns go to the right session

# note that this is inheriting from MuxPlayerLookCommand,
# and has the .playable property.
class CmdOOCLook(MuxPlayerLookCommand):
    """
    look while out-of-character

    Usage:
      look

    Look in the ooc state.
    """

    #This is an OOC version of the look command. Since a
    #Player doesn't have an in-game existence, there is no
    #concept of location or "self". If we are controlling
    #a character, pass control over to normal look.

    key = "look"
    aliases = ["l", "ls"]
    locks = "cmd:all()"
    help_category = "General"

    # this is used by the parent
    player_caller = True

    def func(self):
        "implement the ooc look command"

        if _MULTISESSION_MODE < 2:
            # only one character allowed
            self.msg("You are out-of-character (OOC).\nUse {w@ic{n to get back into the game.")
            return

        # call on-player look helper method
        self.msg(self.player.at_look(target=self.playable, session=self.session))

class CmdCharCreate(COMMAND_DEFAULT_CLASS):
    """
    create a new character

    Usage:
      @charcreate <charname> [= desc]

    Create a new character, optionally giving it a description. You
    may use upper-case letters in the name - you will nevertheless
    always be able to access your character using lower-case letters
    if you want.
    """
    key = "@charcreate"
    locks = "cmd:pperm(Players)"
    help_category = "General"

    # this is used by the parent
    player_caller = True

    def func(self):
        "create the new character"
        player = self.player
        if not self.args:
            self.msg("Usage: @charcreate <charname> [= description]")
            return
        key = self.lhs
        desc = self.rhs

        charmax = _MAX_NR_CHARACTERS if _MULTISESSION_MODE > 1 else 1

        if not player.is_superuser and \
            (player.db._playable_characters and
                len(player.db._playable_characters) >= charmax):
            self.msg("You may only create a maximum of %i characters." % charmax)
            return
        from evennia.objects.models import ObjectDB
        typeclass = settings.BASE_CHARACTER_TYPECLASS

        if ObjectDB.objects.filter(db_typeclass_path=typeclass, db_key__iexact=key):
            # check if this Character already exists. Note that we are only
            # searching the base character typeclass here, not any child
            # classes.
            self.msg("{rA character named '{w%s{r' already exists.{n" % key)
            return

        # create the character
        start_location = ObjectDB.objects.get_id(settings.START_LOCATION)
        default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME)
        permissions = settings.PERMISSION_PLAYER_DEFAULT

        new_character = create.create_object(typeclass, key=key,
                                             location=start_location,
                                             home=default_home,
                                             permissions=permissions)
        # only allow creator (and immortals) to puppet this char
        new_character.locks.add("puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" %
                                (new_character.id, player.id))
        player.db._playable_characters.append(new_character)
        if desc:
            new_character.db.desc = desc
        elif not new_character.db.desc:
            new_character.db.desc = "This is a Player."
        self.msg("Created new character %s. Use {w@ic %s{n to enter the game as this character." % (new_character.key, new_character.key))

class CmdIC(COMMAND_DEFAULT_CLASS):
    """
    control an object you have permission to puppet

    Usage:
      @ic <character>

    Go in-character (IC) as a given Character.

    This will attempt to "become" a different object assuming you have
    the right to do so. Note that it's the PLAYER character that puppets
    characters/objects and which needs to have the correct permission!

    You cannot become an object that is already controlled by another
    player. In principle <character> can be any in-game object as long
    as you the player have access right to puppet it.
    """

    key = "@ic"
    # lock must be all() for different puppeted objects to access it.
    locks = "cmd:all()"
    aliases = "@puppet"
    help_category = "General"

    # this is used by the parent
    player_caller = True

    def func(self):
        """
        Main puppet method
        """
        player = self.player
        session = self.session

        new_character = None
        if not self.args:
            new_character = player.db._last_puppet
            if not new_character:
                self.msg("Usage: @ic <character>")
                return
        if not new_character:
            # search for a matching character
            new_character = search.object_search(self.args)
            if new_character:
                new_character = new_character[0]
            else:
                self.msg("That is not a valid character choice.")
                return
        try:
            player.puppet_object(session, new_character)
            player.db._last_puppet = new_character
        except RuntimeError as exc:
            self.msg("{rYou cannot become {C%s{n: %s" % (new_character.name, exc))

# note that this is inheriting from MuxPlayerLookCommand,
# and as such has the .playable property.
class CmdOOC(MuxPlayerLookCommand):
    """
    stop puppeting and go ooc

    Usage:
      @ooc

    Go out-of-character (OOC).

    This will leave your current character and put you in a incorporeal OOC state.
    """

    key = "@ooc"
    locks = "cmd:pperm(Players)"
    aliases = "@unpuppet"
    help_category = "General"

    # this is used by the parent
    player_caller = True

    def func(self):
        "Implement function"

        player = self.player
        session = self.session

        old_char = player.get_puppet(session)
        if not old_char:
            string = "You are already OOC."
            self.msg(string)
            return

        player.db._last_puppet = old_char

        # disconnect
        try:
            player.unpuppet_object(session)
            self.msg("\n{GYou go OOC.{n\n")

            if _MULTISESSION_MODE < 2:
                # only one character allowed
                self.msg("You are out-of-character (OOC).\nUse {w@ic{n to get back into the game.")
                return

            self.msg(player.at_look(target=self.playable, session=session))

        except RuntimeError as exc:
            self.msg("{rCould not unpuppet from {c%s{n: %s" % (old_char, exc))

class CmdSessions(COMMAND_DEFAULT_CLASS):
    """
    check your connected session(s)

    Usage:
      @sessions

    Lists the sessions currently connected to your account.

    """
    key = "@sessions"
    locks = "cmd:all()"
    help_category = "General"

    # this is used by the parent
    player_caller = True

    def func(self):
        "Implement function"
        player = self.player
        sessions = player.sessions.all()

        table = prettytable.PrettyTable(["{wsessid",
                                         "{wprotocol",
                                         "{whost",
                                         "{wpuppet/character",
                                         "{wlocation"])
        for sess in sorted(sessions, key=lambda x: x.sessid):
            char = player.get_puppet(sess)
            table.add_row([str(sess.sessid), str(sess.protocol_key),
                           type(sess.address) == tuple and sess.address[0] or sess.address,
                           char and str(char) or "None",
                           char and str(char.location) or "N/A"])
        string = "{wYour current session(s):{n\n%s" % table
        self.msg(string)

class CmdWho(COMMAND_DEFAULT_CLASS):
    """
    list who is currently online

    Usage:
      who
      doing

    Shows who is currently online. Doing is an alias that limits info
    also for those with all permissions.
    """

    key = "who"
    aliases = "doing"
    locks = "cmd:all()"

    # this is used by the parent
    player_caller = True

    def func(self):
        """
        Get all connected players by polling session.
        """

        player = self.player
        session_list = SESSIONS.get_sessions()

        session_list = sorted(session_list, key=lambda o: o.player.key)

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = player.check_permstring("Immortals") or player.check_permstring("Wizards")

        nplayers = (SESSIONS.player_count())
        if show_session_data:
            # privileged info
            table = prettytable.PrettyTable(["{wPlayer Name",
                                             "{wOn for",
                                             "{wIdle",
                                             "{wPuppeting",
                                             "{wRoom",
                                             "{wCmds",
                                             "{wProtocol",
                                             "{wHost"])
            for session in session_list:
                if not session.logged_in: continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                puppet = session.get_puppet()
                location = puppet.location.key if puppet else "None"
                table.add_row([utils.crop(player.name, width=25),
                               utils.time_format(delta_conn, 0),
                               utils.time_format(delta_cmd, 1),
                               utils.crop(puppet.key if puppet else "None", width=25),
                               utils.crop(location, width=25),
                               session.cmd_total,
                               session.protocol_key,
                               isinstance(session.address, tuple) and session.address[0] or session.address])
        else:
            # unprivileged
            table = prettytable.PrettyTable(["{wPlayer name", "{wOn for", "{wIdle"])
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                table.add_row([utils.crop(player.key, width=25),
                               utils.time_format(delta_conn, 0),
                               utils.time_format(delta_cmd, 1)])

        isone = nplayers == 1
        string = "{wPlayers:{n\n%s\n%s unique account%s logged in." % (table, "One" if isone else nplayers, "" if isone else "s")
        self.msg(string)

class CmdOption(COMMAND_DEFAULT_CLASS):
    """
    Set an account option

    Usage:
      @option[/save] [name = value]

    Switch:
      save - Save the current option settings for future logins.
      clear - Clear the saved options.

    This command allows for viewing and setting client interface
    settings. Note that saved options may not be able to be used if
    later connecting with a client with different capabilities.

    """
    key = "@option"
    aliases = "@options"
    locks = "cmd:all()"

    # this is used by the parent
    player_caller = True

    def func(self):
        """
        Implements the command
        """
        if self.session is None:
            return

        flags = self.session.protocol_flags

        # Display current options
        if not self.args:
            # list the option settings

            if "save" in self.switches:
                # save all options
                self.caller.db._saved_protocol_flags = flags
                self.msg("{gSaved all options. Use @option/clear to remove.{n")
            if "clear" in self.switches:
                # clear all saves
                self.caller.db._saved_protocol_flags = {}
                self.msg("{gCleared all saved options.")

            options = dict(flags) # make a copy of the flag dict
            saved_options = dict(self.caller.attributes.get("_saved_protocol_flags", default={}))

            if "SCREENWIDTH" in options:
                if len(options["SCREENWIDTH"]) == 1:
                    options["SCREENWIDTH"] = options["SCREENWIDTH"][0]
                else:
                    options["SCREENWIDTH"] = "  \n".join("%s : %s" % (screenid, size)
                        for screenid, size in options["SCREENWIDTH"].iteritems())
            if "SCREENHEIGHT" in options:
                if len(options["SCREENHEIGHT"]) == 1:
                    options["SCREENHEIGHT"] = options["SCREENHEIGHT"][0]
                else:
                    options["SCREENHEIGHT"] = "  \n".join("%s : %s" % (screenid, size)
                        for screenid, size in options["SCREENHEIGHT"].iteritems())
            options.pop("TTYPE", None)

            header = ("Name", "Value", "Saved") if saved_options else ("Name", "Value")
            table = evtable.EvTable(*header)
            for key in sorted(options):
                row = [key, options[key]]
                if saved_options:
                    saved = " |YYes|n" if key in saved_options else ""
                    changed = "|y*|n" if key in saved_options and flags[key] != saved_options[key] else ""
                    row.append("%s%s" % (saved, changed))
                table.add_row(*row)

            self.msg("{wClient settings (%s):|n\n%s|n" % (self.session.protocol_key, table))

            return

        if not self.rhs:
            self.msg("Usage: @option [name = [value]]")
            return

        # Try to assign new values

        def validate_encoding(val):
            # helper: change encoding
            try:
                utils.to_str(utils.to_unicode("test-string"), encoding=val)
            except LookupError:
                raise RuntimeError("The encoding '|w%s|n' is invalid. " % val)
            return val

        def validate_size(val):
            return {0: int(val)}

        def validate_bool(val):
            return True if val.lower() in ("true", "on", "1") else False

        def update(name, val, validator):
            # helper: update property and report errors
            try:
                old_val = flags[name]
                new_val = validator(val)
                flags[name] = new_val
                self.msg("Option |w%s|n was changed from '|w%s|n' to '|w%s|n'." % (name, old_val, new_val))
                return {name: new_val}
            except Exception, err:
                self.msg("|rCould not set option |w%s|r:|n %s" % (name, err))
                return False

        validators = {"ANSI": validate_bool,
                      "CLIENTNAME": utils.to_str,
                      "ENCODING": validate_encoding,
                      "MCCP": validate_bool,
                      "MXP": validate_bool,
                      "NOMARKUP": validate_bool,
                      "NOPKEEPALIVE": validate_bool,
                      "OOB": validate_bool,
                      "RAW": validate_bool,
                      "SCREENHEIGHT": validate_size,
                      "SCREENWIDTH": validate_size,
                      "SCREENREADER": validate_bool,
                      "TERM": utils.to_str,
                      "UTF-8": validate_bool,
                      "XTERM256": validate_bool,
                      "INPUTDEBUG": validate_bool}

        name = self.lhs.upper()
        val = self.rhs.strip()
        optiondict = False
        if val and name in validators:
            optiondict = update(name,  val, validators[name])
        else:
            self.session.msg("|rNo option named '|w%s|r'." % name)
        if optiondict:
            # a valid setting
            if "save" in self.switches:
                # save this option only
                saved_options = self.player.attributes.get("_saved_protocol_flags", default={})
                saved_options.update(optiondict)
                self.player.attributes.add("_saved_protocol_flags", saved_options)
                for key in optiondict:
                    self.msg("{gSaved option %s.{n" % key)
            if "clear" in self.switches:
                # clear this save
                for key in optiondict:
                    self.player.attributes.get("_saved_protocol_flags", {}).pop(key, None)
                    self.msg("{gCleared saved %s." % key)

            self.session.update_flags(**optiondict)

class CmdPassword(COMMAND_DEFAULT_CLASS):
    """
    change your password

    Usage:
      @password <old password> = <new password>

    Changes your password. Make sure to pick a safe one.
    """
    key = "@password"
    locks = "cmd:pperm(Players)"

    # this is used by the parent
    player_caller = True

    def func(self):
        "hook function."

        player = self.player
        if not self.rhs:
            self.msg("Usage: @password <oldpass> = <newpass>")
            return
        oldpass = self.lhslist[0]  # this is already stripped by parse()
        newpass = self.rhslist[0]  #               ''
        if not player.check_password(oldpass):
            self.msg("The specified old password isn't correct.")
        elif len(newpass) < 3:
            self.msg("Passwords must be at least three characters long.")
        else:
            player.set_password(newpass)
            player.save()
            self.msg("Password changed.")

class CmdQuit(COMMAND_DEFAULT_CLASS):
    """
    quit the game

    Usage:
      @quit

    Switch:
      all - disconnect all connected sessions

    Gracefully disconnect your current session from the
    game. Use the /all switch to disconnect from all sessions.
    """
    key = "@quit"
    aliases = "quit"
    locks = "cmd:all()"

    # this is used by the parent
    player_caller = True

    def func(self):
        "hook function"
        player = self.player

        if 'all' in self.switches:
            player.msg("{RQuitting{n all sessions. Hope to see you soon again.", session=self.session)
            for session in player.sessions.all():
                player.disconnect_session_from_player(session)
        else:
            nsess = len(player.sessions.all())
            if nsess == 2:
                player.msg("{RQuitting{n. One session is still connected.", session=self.session)
            elif nsess > 2:
                player.msg("{RQuitting{n. %i session are still connected." % (nsess-1), session=self.session)
            else:
                # we are quitting the last available session
                player.msg("{RQuitting{n. Hope to see you again, soon.", session=self.session)
            player.disconnect_session_from_player(self.session)

class CmdColorTest(COMMAND_DEFAULT_CLASS):
    """
    testing which colors your client support

    Usage:
      @color ansi|xterm256

    Prints a color map along with in-mud color codes to use to produce
    them.  It also tests what is supported in your client. Choices are
    16-color ansi (supported in most muds) or the 256-color xterm256
    standard. No checking is done to determine your client supports
    color - if not you will see rubbish appear.
    """
    key = "@color"
    aliases = "color"
    locks = "cmd:all()"
    help_category = "General"

    # this is used by the parent
    player_caller = True

    def table_format(self, table):
       """
       Helper method to format the ansi/xterm256 tables.
       Takes a table of columns [[val,val,...],[val,val,...],...]
       """
       if not table:
           return [[]]

       extra_space = 1
       max_widths = [max([len(str(val)) for val in col]) for col in table]
       ftable = []
       for irow in range(len(table[0])):
           ftable.append([str(col[irow]).ljust(max_widths[icol]) + " " * extra_space
                          for icol, col in enumerate(table)])
       return ftable

    def func(self):
        "Show color tables"

        if self.args.startswith("a"):
            # show ansi 16-color table
            from evennia.utils import ansi
            ap = ansi.ANSI_PARSER
            # ansi colors
            # show all ansi color-related codes
            col1 = ["%s%s|n" % (code, code.replace("|", "||")) for code, _ in ap.ext_ansi_map[48:56]]
            col2 = ["%s%s|n" % (code, code.replace("|", "||")) for code, _ in ap.ext_ansi_map[56:64]]
            col3 = ["%s%s|n" % (code.replace("\\",""), code.replace("|", "||").replace("\\", "")) for code, _ in ap.ext_ansi_map[-8:]]
            col2.extend(["" for i in range(len(col1)-len(col2))])
            table = utils.format_table([col1, col2, col3])
            string = "ANSI colors:"
            for row in table:
                string += "\n " + " ".join(row)
            self.msg(string)
            self.msg("||X : black. ||/ : return, ||- : tab, ||_ : space, ||* : invert, ||u : underline")
            self.msg("To combine background and foreground, add background marker last, e.g. ||r||[B.")

        elif self.args.startswith("x"):
            # show xterm256 table
            table = [[], [], [], [], [], [], [], [], [], [], [], []]
            for ir in range(6):
                for ig in range(6):
                    for ib in range(6):
                        # foreground table
                        table[ir].append("|%i%i%i%s|n" % (ir, ig, ib, "||%i%i%i" % (ir, ig, ib)))
                        # background table
                        table[6+ir].append("|%i%i%i|[%i%i%i%s|n" % (5 - ir, 5 - ig, 5 - ib,
                                                            ir, ig, ib,
                                                        "||[%i%i%i" % (ir, ig, ib)))
            table = self.table_format(table)
            string = "Xterm256 colors (if not all hues show, your client might not report that it can handle xterm256):"
            for row in table:
                string += "\n" + "".join(row)
            self.msg(string)
            #self.msg("(e.g. %%123 and %%[123 also work)")
        else:
            # malformed input
            self.msg("Usage: @color ansi||xterm256")

class CmdQuell(COMMAND_DEFAULT_CLASS):
    """
    use character's permissions instead of player's

    Usage:
      quell
      unquell

    Normally the permission level of the Player is used when puppeting a
    Character/Object to determine access. This command will switch the lock
    system to make use of the puppeted Object's permissions instead. This is
    useful mainly for testing.
    Hierarchical permission quelling only work downwards, thus a Player cannot
    use a higher-permission Character to escalate their permission level.
    Use the unquell command to revert back to normal operation.
    """

    key = "@quell"
    aliases = ["@unquell"]
    locks = "cmd:pperm(Players)"
    help_category = "General"

    # this is used by the parent
    player_caller = True

    def _recache_locks(self, player):
        "Helper method to reset the lockhandler on an already puppeted object"
        if self.session:
            char = self.session.puppet
            if char:
                # we are already puppeting an object. We need to reset
                # the lock caches (otherwise the superuser status change
                # won't be visible until repuppet)
                char.locks.reset()
        player.locks.reset()

    def func(self):
        "Perform the command"
        player = self.player
        permstr = player.is_superuser and " (superuser)" or " (%s)" % (", ".join(player.permissions.all()))
        if self.cmdstring == '@unquell':
            if not player.attributes.get('_quell'):
                self.msg("Already using normal Player permissions%s." % permstr)
            else:
                player.attributes.remove('_quell')
                self.msg("Player permissions%s restored." % permstr)
        else:
            if player.attributes.get('_quell'):
                self.msg("Already quelling Player%s permissions." % permstr)
                return
            player.attributes.add('_quell', True)
            puppet = self.session.puppet
            if puppet:
                cpermstr = " (%s)" % ", ".join(puppet.permissions.all())
                cpermstr = "Quelling to current puppet's permissions%s." % cpermstr
                cpermstr += "\n(Note: If this is higher than Player permissions%s, the lowest of the two will be used.)" % permstr
                cpermstr += "\nUse @unquell to return to normal permission usage."
                self.msg(cpermstr)
            else:
                self.msg("Quelling Player permissions%s. Use @unquell to get them back." % permstr)
        self._recache_locks(player)


text:
'use strict';

var _ = require('lodash'),
    mongoose = require('mongoose'),
    User = mongoose.model('User');

// users in chatroom
var visitors = {};

// only keep track of most recent messages
var messageQueue = (function(size){
  var queue = [];

  queue.push = function(a) {
    if(this.length >= size) this.shift();
    return Array.prototype.push.apply(this, arguments);
  };

  return queue;
})(15);

// placeholder info for user who's not registered
var unauthorizedUser = {
  name: 'unknown',
  profileImg: 'http://bower.io/img/bower-logo.png',
  role: 'guest'
};

// send the user on connection
exports.initUser = function(socket, user) {
  if(user.logged_in === false) {
    return socket.emit('init', {
      user: unauthorizedUser
    });
  }
  socket.emit('init', {
    user: user
  });
};

// update visitors list for everyone
exports.joinRoom = function(socket, user) {
  if(user.logged_in !== false) {
    visitors[user.id] = user;
  }
  var data = {
    visitors: _.toArray(visitors),
    messages: messageQueue
  };
  socket.broadcast.emit('join', data);
  socket.emit('join', data);
};

// broadcast user's message to other users
exports.sendMessage = function(socket, user, data) {
  if(user.logged_in === false) {
    return socket.emit('unauthorized', {
      messages: messageQueue
    });
  }

  messageQueue.push({
    author: user,
    body:   data.body,
    date:   Date.now()
  });
  socket.broadcast.emit('message', messageQueue);
};

// clean up when a user leaves, and broadcast to other users
exports.leaveRoom = function(io, socket, user) {
  if (visitors[user.id]) {
    delete visitors[user.id];
  }

  socket.broadcast.emit('leave', {
    user: user,
    visitors: _.toArray(visitors)
  });
};

redpajama_set_name: RedPajamaGithub


text:
<idea-plugin>
  <extensionPoints>
    <extensionPoint name="lang.refactoringSupport" beanClass="com.intellij.lang.LanguageExtensionPoint" dynamic="true">
      <with attribute="implementationClass" implements="com.intellij.lang.refactoring.RefactoringSupportProvider"/>
    </extensionPoint>

    <extensionPoint name="lang.namesValidator" beanClass="com.intellij.lang.LanguageExtensionPoint" dynamic="true">
      <with attribute="implementationClass" implements="com.intellij.lang.refactoring.NamesValidator"/>
    </extensionPoint>

    <extensionPoint name="renameHandler" interface="com.intellij.refactoring.rename.RenameHandler" dynamic="true"/>
    <extensionPoint name="renamePsiElementProcessor" interface="com.intellij.refactoring.rename.RenamePsiElementProcessorBase" dynamic="true"/>
    <extensionPoint name="renameRefactoringDialogProvider" interface="com.intellij.refactoring.rename.RenameRefactoringDialogProvider" dynamic="true"/>
    <extensionPoint name="updateAddedFileProcessor" interface="com.intellij.psi.impl.file.UpdateAddedFileProcessor" dynamic="true"/>
    <extensionPoint name="automaticRenamerFactory" interface="com.intellij.refactoring.rename.naming.AutomaticRenamerFactory" dynamic="true"/>
    <extensionPoint name="nameSuggestionProvider" interface="com.intellij.refactoring.rename.NameSuggestionProvider" dynamic="true"/>
    <extensionPoint name="vetoRenameCondition" interface="com.intellij.openapi.util.Condition" dynamic="true"/>
    <extensionPoint name="renamerFactory" dynamic="true" interface="com.intellij.refactoring.rename.RenamerFactory"/>
    <extensionPoint name="refactoring.helper" interface="com.intellij.refactoring.RefactoringHelper" dynamic="true"/>
    <extensionPoint name="inlineActionHandler" interface="com.intellij.lang.refactoring.InlineActionHandler" dynamic="true"/>
    <extensionPoint name="refactoring.inlineHandler" beanClass="com.intellij.lang.LanguageExtensionPoint" dynamic="true">
      <with attribute="implementationClass" implements="com.intellij.lang.refactoring.InlineHandler"/>
    </extensionPoint>

    <extensionPoint name="rename.inplace.resolveSnapshotProvider" beanClass="com.intellij.lang.LanguageExtensionPoint" dynamic="true">
      <with attribute="implementationClass" implements="com.intellij.refactoring.rename.ResolveSnapshotProvider"/>
    </extensionPoint>

    <extensionPoint name="renameInputValidator" interface="com.intellij.refactoring.rename.RenameInputValidator" dynamic="true"/>

    <extensionPoint name="refactoring.elementListenerProvider" interface="com.intellij.refactoring.listeners.RefactoringElementListenerProvider" area="IDEA_PROJECT" dynamic="true"/>

    <extensionPoint name="findInProjectSearchEngine" interface="com.intellij.find.FindInProjectSearchEngine" dynamic="true"/>

    <extensionPoint name="qualifiedNameProvider" interface="com.intellij.ide.actions.QualifiedNameProvider" dynamic="true"/>
    <extensionPoint name="virtualFileQualifiedNameProvider" interface="com.intellij.ide.actions.VirtualFileQualifiedNameProvider" dynamic="true"/>

    <extensionPoint name="testSourcesFilter" interface="com.intellij.openapi.roots.TestSourcesFilter" dynamic="true"/>
  </extensionPoints>
</idea-plugin>


text:
1. Install [R](https://www.r-project.org/) on your machine.
2. [Install](http://jupyter.readthedocs.org/en/latest/install.html) the Jupyter environment.
3. [Install](https://github.com/IRkernel/IRkernel) the R kernel for Jupyter.
4. Install the following R packages, at the R prompt: install.packages(c("rPython", "scatterplot3d", "tidyr", "ggplot2", "xtable", "purrr")).

### Install SimpleITK

A devtools based installer is [available on github](https://github.com/SimpleITK/SimpleITKRInstaller). It requires that you have the [CMake tool](https://cmake.org/) and the git version control system installed on your machine.

The manual approach to compiling and installing SimpleITK with the R wrapping turned on is described [here](https://simpleitk.readthedocs.io/en/master/building.html).

### Downloading Data

The data can be automatically downloaded to the "Data" directory when you execute the notebooks.

Alternatively, to download all the data before hand:

    cd SimpleITK-Notebooks
    ./downloaddata.py Data/ Data/manifest.json

### Working offline

In some situations, such as a tutorial session, you may not have internet access. This requires that you:

1. Download the data in advance - see above.

# View Static Converted Pages

Static views of all pages are available on the [html site of this repository](https://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/).


text:
TSubclassOf<AActor> FRTSProductionQueue::operator[](int32 Index) const
{
	return Queue[Index];
}

void FRTSProductionQueue::Add(TSubclassOf<AActor> Product)
{
	Queue.Add(Product);
}

int32 FRTSProductionQueue::Num() const
{
	return Queue.Num();
}

void FRTSProductionQueue::RemoveAt(int32 Index)
{
	// Advance all products.
	int32 Slots = Queue.Num();

	for (int32 SlotToUpdate = Index; SlotToUpdate < Slots - 1; ++SlotToUpdate)
	{
		Queue[SlotToUpdate] = Queue[SlotToUpdate + 1];
	}

	Queue.RemoveAt(Slots - 1);
}


text:
using System.Linq;
using Microsoft.Xaml.Interactivity;
using Template10.Utils;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace Template10.Behaviors
{
    // DOCS: https://github.com/Windows-XAML/Template10/wiki/Behaviors-and-Actions
    [TypeConstraint(typeof(CommandBar))]
    public class EllipsisBehavior : DependencyObject, IBehavior
    {
        private CommandBar _commandBar => AssociatedObject as CommandBar;

        public DependencyObject AssociatedObject { get; private set; }

        public void Attach(DependencyObject associatedObject)
        {
            AssociatedObject = associatedObject;
            _commandBar.Loaded += CommandBar_Loaded;
            _commandBar.PrimaryCommands.VectorChanged += Commands_VectorChanged;
            _commandBar.SecondaryCommands.VectorChanged += Commands_VectorChanged;
            Update();
        }

        public void Detach()
        {
            _commandBar.Loaded -= CommandBar_Loaded;
            _commandBar.PrimaryCommands.VectorChanged -= Commands_VectorChanged;
            _commandBar.SecondaryCommands.VectorChanged -= Commands_VectorChanged;
        }

        private void CommandBar_Loaded(object sender, RoutedEventArgs e) => Update();

        private void Commands_VectorChanged(IObservableVector<ICommandBarElement> sender, IVectorChangedEventArgs @event) => Update();

        public enum Visibilities { Visible, Collapsed, Auto }
        public Visibilities Visibility
        {
            get { return (Visibilities)GetValue(VisibilityProperty); }
            set { SetValue(VisibilityProperty, value); }
        }
        public static readonly DependencyProperty VisibilityProperty =
            DependencyProperty.Register(nameof(Visibility), typeof(Visibilities),
                typeof(EllipsisBehavior), new PropertyMetadata(Visibilities.Auto));

        private Button FindButtonByName()
        {
            if (VisualTreeHelper.GetChildrenCount(_commandBar) > 0)
            {
                var child = VisualTreeHelper.GetChild(_commandBar, 0) as FrameworkElement; /* Templated root */
                return child?.FindName("MoreButton") as Button;
            }
            return null;
        }

        private Button FindButtonByTreeEnum()
        {
            var controls = _commandBar.AllChildren().OfType<Control>();
            return controls.OfType<Button>().FirstOrDefault(x => x.Name.Equals("MoreButton"));
        }

        private Button FindButton()
        {
            if (_commandBar == null)
            {
                return null;
            }
            var r = FindButtonByName(); // try find button by name from templated root
                                        // minimized WinRT interop calls (3 calls) for MUCH better performance
            if (r != null)
            {
                return r;
            }
            return FindButtonByTreeEnum(); // fallback method - many WinRT interop calls so it is very expensive
        }

        private void Update()
        {
            var button = FindButton();
            if (button == null)
                return;
            switch (Visibility)
            {
                case Visibilities.Visible:
                    button.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    break;
                case Visibilities.Collapsed:
                    button.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    break;
                case Visibilities.Auto:
                    var count = _commandBar.PrimaryCommands.OfType<Control>().Count(x => x.Visibility.Equals(Windows.UI.Xaml.Visibility.Visible));
                    count += _commandBar.SecondaryCommands.OfType<Control>().Count(x => x.Visibility.Equals(Windows.UI.Xaml.Visibility.Visible));
                    button.Visibility = (count > 0) ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;
                    break;
            }
        }
    }
}


text:
using Sdl.Web.Common.Configuration;

namespace Sdl.Web.Tridion.Mapping
{
    /// <summary>
    /// Interface used by <see cref="Sdl.Web.Tridion.Navigation.StaticNavigationProvider"/> to access Navigation.json
    /// </summary>
    public interface IRawDataProvider
    {
        string GetPageContent(string urlPath, Localization localization);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Leo McLay - Aspiring Web Developer</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="../normalize.css">
  <link rel="stylesheet" href="../skeleton.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
  <link rel="stylesheet" href="../main.css">

Leo McLay

Aspiring Web Developer

      <button class="button-primary" id="projects-link" >PROJECTS</button>

      <button class="button-primary" id="blog-link" >BLOG</button>

Motivation

    Chapter 6 of "Search Inside Yourself" is "The Art of Self Motivation". It describes three "types of happiness": Please, passion, and higher purpose. Each type has varying levels of sustainability.

        Pleasure - Chasing the next high.

        Passion - Peak performance meets peak engagement (ie. the previously discussed "flow").

        Higher Purpose: Being part of something bigger than yourself that has meaning to you. The most sustainable type.

    This reminds me of a lecture I had during my Bachelors studies, in which we learnt that the two ingredients required to achieve happiness was meaningful love and meaningul work, a thought that has resonated with me since hearing it. Both of those ingredients would fit into the higher purpose category.

        Recent Entries

        Control

        Javascript Language

        Problem Solving

        Self Confidence

        Daily Mindfulness


text:
app.component('acuserconsoleReqs', {

  templateUrl: './comps/acuserconsole_reqs/acuserconsole_reqs.view.html',

  controller: function ($scope, $http, userService, navlinksService, dateformatService, notificationService) {

    $scope.pendingRequests = [];
    $scope.fulfilledRequests = [];
    $scope.rejectedRequests = [];
    $scope.newRequests = [];

    $scope.format = function (req) {
      return dateformatService.format(req);
    };

    $scope.handleReq = function (req) {
      $http.get('/acuser/alumnirequests/'+req._id+'/handle', {
        headers: {
          'user-token': userService.getToken()
        }
      }).then(function (response) {
        var data = response.data;
        if(data.success) {
          console.log("Successfully handledRequest");
          notificationService.setNotif("Successfully handled successfully");
          $scope.reload();
        }
        else {
          console.error(data.msg);
        }
      });
    };

    $scope.reload = function () {

      $http.get('/acuser/alumnirequests/all', {
        headers: {
          'user-token': userService.getToken()
        }
      }).then(function (response) {
        var data = response.data;
        if(data.success) {
          $scope.pendingRequests = data.pendingRequests;
          $scope.fulfilledRequests = data.fulfilledRequests;
          $scope.rejectedRequests = data.rejectedRequests;
          $scope.newRequests = data.newRequests;
        }
        else {
          console.error(data.msg);
        }
      });
    };

    $scope.start = function () {
      navlinksService.setNavlinks(['Manage Student Organizations'], ['/#/acuserconsole_sos']);

      $scope.reload();
    };

    // Call on component initialized
    $scope.start();
  }
})


text:
TARGET=mweb
LIBNAME=$(addprefix lib, $(TARGET)).a

LIBOBJS+=./deps/http-parser/http_parser.o
LIBOBJS+=./src/connection.o
LIBOBJS+=./src/response.o
LIBOBJS+=./src/request.o
LIBOBJS+=./src/server.o

PREFIX=/usr/local
CFLAGS+=-std=gnu99 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -Wall -O2 -fPIC -I./include -I./src -I./deps/http-parser -I$(HOME)/usr/local/include
LDFLAGS= -L$(HOME)/usr/local/lib
CC=gcc
AR=ar
RANLIB=ranlib
ARFLAGS=rcu
STRIP=strip
LIBS+=uv lua pthread m

all:./deps/http-parser samples

./deps/http-parser:
	git clone --depth 1 https://github.com/joyent/http-parser.git ./deps/http-parser
	@mkdir -p ./lib
$(LIBNAME):$(LIBOBJS)
	@$(AR) $(ARFLAGS) ./lib/$(LIBNAME) $(LIBOBJS)
samples:$(LIBNAME) miniserver webserver

miniserver:$(LIBNAME)
	@echo "Compiling $@"
	@$(CC) -I./include $(CFLAGS) -I./src -c ./samples/miniserver/miniserver.c -o ./samples/miniserver/miniserver.o
	@$(CC) -I./include $(CFLAGS) ./samples/miniserver/miniserver.o -L./lib $(LDFLAGS) -l${TARGET} $(addprefix -l,$(LIBS)) -o ./samples/miniserver/$@
	@$(STRIP) ./samples/miniserver/$@
webserver:$(LIBNAME)
	@echo "Compiling $@"
	@$(CC) -I./include $(CFLAGS) -I./src -c ./samples/webserver/webserver.c -o ./samples/webserver/webserver.o
	@$(CC) -I./include $(CFLAGS) ./samples/webserver/webserver.o -L./lib $(LDFLAGS) -l${TARGET} $(addprefix -l,$(LIBS)) -o ./samples/webserver/$@
	@$(STRIP) ./samples/webserver/$@
install:
	cp ./include/*.h ${PREFIX}/include/
	cp ./lib/*.a ${PREFIX}/lib/
uninstall:
	@echo "rm '$(TARGET)' form '${PREFIX}/bin'"
	@rm -f ${PREFIX}/bin/$(TARGET)
	@rm -f ${PREFIX}/lib/$(LIBNAME)
touch:
	touch $(SRCS)
distclean:clean
	@rm -rf ./deps/http-parser
clean:
	@echo "Clean ..."
	@rm -f ./deps/http-parser/*.o
	@rm -f ./samples/webserver/*.o ./samples/webserver/webserver
	@rm -f ./samples/miniserver/*.o ./samples/miniserver/miniserver
	@rm -f ./$(TARGET)
	@rm -f ./lib/*.a
	@rm -f ./src/*.o
	@rm -f *~ */*~

.SECONDARY    :%.o
# Compiling to object files.
%.o:%.c
	@echo "CC $<"
	@$(CC) $(CFLAGS) -c $< -o $@

.PHONY: test


text:
//
//  AppDelegate.m
//  YYKitDemoCoding
//
//  Created by 超杨 on 16/1/18.
//  Copyright © 2016年 杨超. All rights reserved.
//

#import "YCAppDelegate.h"
#import "YCRootViewController.h"
/** 自定义导航条便于版本适配 */
@interface YCExampleNavBar : UINavigationBar
@end

@implementation YCExampleNavBar{
    CGSize _previousSize;
}

/** 适配不同导航栏状态 */
- (CGSize)sizeThatFits:(CGSize)size {
    size = [super sizeThatFits:size];
    /** 如果状态栏影藏,导航条高为64 */
    if ([UIApplication sharedApplication].statusBarHidden) {
        size.height = 64;
    }
    return size;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    /** 一旦发现当前的尺寸与之前的尺寸不一致,则在这个方法中做出调整 */
    if (!CGSizeEqualToSize(self.bounds.size, _previousSize)) {
        _previousSize = self.bounds.size;
        /** 如果前后尺寸不一致,则移除所有导航条上的动画 */
        [self.layer removeAllAnimations];
        [self.layer.sublayers enumerateObjectsUsingBlock:^(CALayer * _Nonnull layer, NSUInteger idx, BOOL * _Nonnull stop) {
            [layer removeAllAnimations];
        }];
    }
}

@end

/** 定义例子导航栏 */
@interface YCExampleNavController : UINavigationController
@end
@implementation YCExampleNavController

/** 设置当前控制器的view是否自动旋转
    此处我们设置为旋转,其实默认就是旋转,这里的代码是为了适配ios5,因为ios5默认为不旋转。
 */
- (BOOL)shouldAutorotate {
    return YES;
}

/** 控制模态 且 根控制器 的旋转方向 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

/** 控制器 非跟控制器且模态控制器的旋转方向 */
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

@end

@interface YCAppDelegate ()

@end

@implementation YCAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    YCRootViewController *root1 = [[YCRootViewController alloc] init];

    YCExampleNavController *nav1 = [[YCExampleNavController alloc] initWithNavigationBarClass:[YCExampleNavBar class] toolbarClass:[UIToolbar class]];

    /** 防止崩溃 */
    if ([nav1 respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        /** 设置不能使用导航栏或者toolbar或者tabbar 去调整scrollView的内边距,即设置这些为手动控制 */
        nav1.automaticallyAdjustsScrollViewInsets = NO;
    }
    [nav1 pushViewController:root1 animated:YES];

    self.rootViewController = nav1;
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = self.rootViewController;
    self.window.backgroundColor = [UIColor grayColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Auth::routes();

Route::get('/', 'HomeController@index')->name('home');
Route::get('/{pageId}', function($pageId){
    return view('page',['pageId' => $pageId]);
});
Route::get('comments/{pageId}', 'CommentController@index');
Route::post('comments', 'CommentController@store');
Route::post('comments/{commentId}/{type}', 'CommentController@update');


text:
package org.thepredicate;

import java.util.ArrayList;
import java.util.List;

/**
 * An implementation of Robert Aumann and Michael Maschler's  algoritm for estate distribution
 * as outlined in 'Game Theoretic Analysis of a Bankrupcy Problem from the Talmud'. The paper
 * is available here:
 * http://www.sscnet.ucla.edu/polisci/faculty/chwe/austen/aumann1985.pdf
 *
 * A good explanation of the scenario here:
 * http://www.sscnet.ucla.edu/polisci/faculty/chwe/austen/aumann1985.pdf
 *
 * @author aioffe
 *
 */
public class BankrupcySolution {

	/**
	 * Run the full Aumann/Maschler algorithm. See {@link #upwardFiller(List, double)}
	 * and {@link #downwardFiller(List, double)} for more details.
	 *
	 * @param claimants The estate creditors
	 * @param totalEstate The total value of the estate
	 * @return amount of estate left after all the distributions are done
	 */
	public static double runScenario(List<Claimant> claimants, double totalEstate) {
		double remaining = BankrupcySolution.upwardFiller(claimants, totalEstate);
		remaining = BankrupcySolution.downwardFiller(claimants, remaining);
		return remaining;
	}

	/**
	 * Run the second part of the Aumann/Maschler algorithm which is roughly described as:
	 *
	 *

	 *
Start giving the highest-claim money from the estate until the loss, the difference between the claim and the
	 * award, equals the loss for the next highest creditor.

	 *
Then divide the estate equally among the highest creditors until the loss of the highest creditors equals the loss of the next highest.
	 *
Continue until all money has been awarded.
	 *

	 *
	 * @param claimants The estate creditors
	 * @param totalEstate The total value of the estate
	 * @return amount of estate left
	 */
	static double downwardFiller(List<Claimant> claimants, double totalEstate) {
		// produce a list of the claimants, highest to lowest
		List<Claimant> downardClaimants = new ArrayList<Claimant>(claimants);
		double accountLeft = totalEstate;

		// remove the highest value claimant and add to the 'compenseers' list, we start
		// by putting the highest claimant into that list
		List<Claimant> compenseers = new ArrayList<Claimant>();
		addFirstFromLast(compenseers, downardClaimants);

		// while the estate has money and there are more claimants to be compensated
		while (downardClaimants.size() > 0 && accountLeft > 0) {

			// get their difference with the next-lowest claimant (if next-lowest claimant doesn't exist it's zero)
			double upwardDifference = findUpwardDifference(downardClaimants, compenseers);

			// compensate this difference to all the compenseers (if no money left at this point then exit)
			accountLeft = redeemClaimantsEquallyUpToAmount(compenseers, upwardDifference, accountLeft, false);

			// put the next lowest into the compenseers (beginning of the array) and continue
			addFirstFromLast(compenseers, downardClaimants);
		}

		// at this point we need to distribute to the lowest claimant (downwardClaimants is zero)
		// and his updardDifference is compared to zero but the findUpwardDifference method can do that
		double upwardDifference = findUpwardDifference(downardClaimants, compenseers);
		accountLeft = redeemClaimantsEquallyUpToAmount(compenseers, upwardDifference, accountLeft, false);

		return accountLeft;
	}

	static void addFirstFromLast(List<Claimant> toAddTo, List<Claimant> toRemoveFrom) {
		toAddTo.add(0, toRemoveFrom.remove(toRemoveFrom.size() - 1));
	}

	static double findUpwardDifference(List<Claimant> downwardClaimants, List<Claimant> compenseers) {
		Claimant lowestCompenseer = compenseers.get(0);

		if (downwardClaimants.size() == 0) {
			return lowestCompenseer.getLoss();
		}

		Claimant highestUnpaidClaimant = downwardClaimants.get(downwardClaimants.size() - 1);

		return lowestCompenseer.getLoss() - highestUnpaidClaimant.getLoss();
	}

	/**
	 * Run the first part of the Aumann/Maschler algorithm which is roughly described as:
	 *
	 *

	 *
Order the creditors from lowest to highest claims (does not do this, assumes the creditors are already sorted)
	 *
Divide the estate equally among all parties until the lowest creditor receives one half of the claim.
	 *
Divide the estate equally among all parties except the lowest creditor until the next lowest creditor receives one half of the claim.
	 *
Proceed until each creditor has reached one-half of the original claim.
	 *

	 *
	 * As I mentioned above, this assumes claimants are sorted, lowest-claim claimant to higher claim claimant
	 * @param claimants The estate creditors
	 * @param totalEstate The total value of the estate
	 * @return amount of estate left
	 */
	static double upwardFiller(List<Claimant> claimants, double totalEstate) {
		ArrayList<Claimant> upwardClaimants = new ArrayList<Claimant>(claimants);
		double remainingEstate = totalEstate;
		while (remainingEstate > 0 && upwardClaimants.size() > 0) {
			remainingEstate = upwardIncrementSplitter(upwardClaimants, remainingEstate);
			upwardClaimants.remove(0);
		}
		return remainingEstate;
	}

	static double upwardIncrementSplitter(List<Claimant> claimants, double totalEstate) {
		// special case if there are no claimants
		if (claimants.size() == 0) {
			return totalEstate;
		}

		// special case if there is one claimant then the standard procedure
		// below should still work

		Claimant lowestClaimant = claimants.get(0);

		// get the lowest-claim claimant's half payout
		double lowestHalfClaim = lowestClaimant.halfClaim();

		// find the difference between what they have NOW (i.e. already), and their half payment
		double lowestDifferenceInterval = lowestHalfClaim - lowestClaimant.getPayout();

		// redeem the claimants from the estate up to that amount
		double remainingEstate = redeemClaimantsEquallyUpToAmount(claimants, lowestDifferenceInterval, totalEstate, true);

		return remainingEstate;
	}

	public static double redeemClaimantsEquallyUpToAmount(List<Claimant> claimants, double redeemAmount, double totalAccount, boolean isFirstPass) {
		// find the total sum that would be owed to the claimants
		double totalRedeemAmount = redeemAmount * claimants.size();

		// if the estate has enough to pay them equally, do that... and then return amount of money left
		if (totalAccount >= totalRedeemAmount) {
			redeemClaimantsEqually(claimants, redeemAmount, isFirstPass);
			return (totalAccount - totalRedeemAmount);
		}

		// otherwise split the money equally... and return 0
		double insufficientRedeemAmount = totalAccount / claimants.size();
		redeemClaimantsEqually(claimants, insufficientRedeemAmount, isFirstPass);

		return 0;
	}

	private static void redeemClaimantsEqually(List<Claimant> claimants, double redeemAmount, boolean isFirstPass) {
		for (Claimant claimant : claimants) {

			if (isFirstPass) {
				claimant.setFirstPassPayout(claimant.getFirstPassPayout() + redeemAmount);
			} else {
				claimant.setSecondPassPayout(claimant.getSecondPassPayout() + redeemAmount);
			}
		}
	}

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE483_Incorrect_Block_Delimitation__semicolon_12.c
Label Definition File: CWE483_Incorrect_Block_Delimitation.label.xml
Template File: point-flaw-12.tmpl.c
*/
/*
 * @description
 * CWE: 483 Incorrect Block Delimitation
 * Sinks: semicolon
 *    GoodSink: Absence of suspicious semicolon
 *    BadSink : Suspicious semicolon before the if statement brace
 * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE483_Incorrect_Block_Delimitation__semicolon_12_bad()
{
    if(globalReturnsTrueOrFalse())
    {
        {
            int x = (rand() % 3);
            int y = 0;
            /* FLAW: Suspicious semicolon before the if statement brace */
            if (x == 0);
            {
                printLine("x == 0");
                y = 1;
            }
            if (y)
            {
                printLine("x was 0\n");
            }
        }
    }
    else
    {
        {
            int x = (rand() % 3);
            int y = 0;
            /* FIX: Removed suspicious semicolon before the if statement brace */
            if (x == 0)
            {
                printLine("x == 0");
                y = 1;
            }
            if (y)
            {
                printLine("x was 0\n");
            }
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses the GoodSink on both sides of the "if" statement */
static void good1()
{
    if(globalReturnsTrueOrFalse())
    {
        {
            int x = (rand() % 3);
            int y = 0;
            /* FIX: Removed suspicious semicolon before the if statement brace */
            if (x == 0)
            {
                printLine("x == 0");
                y = 1;
            }
            if (y)
            {
                printLine("x was 0\n");
            }
        }
    }
    else
    {
        {
            int x = (rand() % 3);
            int y = 0;
            /* FIX: Removed suspicious semicolon before the if statement brace */
            if (x == 0)
            {
                printLine("x == 0");
                y = 1;
            }
            if (y)
            {
                printLine("x was 0\n");
            }
        }
    }
}

void CWE483_Incorrect_Block_Delimitation__semicolon_12_good()
{
    good1();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE483_Incorrect_Block_Delimitation__semicolon_12_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE483_Incorrect_Block_Delimitation__semicolon_12_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
require 'spec_helper'

describe Blog::Filters do

  # A sample filter.
  class HelloFilter < Blog::Filters::Base
    register_filter :hello

    def process(text, options)
      attrs =
        if options[:class] then " class=\"#{options[:class]}\"" else "" end
      name = if text then ", #{text}" else "" end
      "
Hello#{name}!
"
    end
  end

  describe ".find" do
    it "returns the filter registered for a name" do
      Blog::Filters.find(:hello).should be_kind_of(HelloFilter)
    end
  end

  describe ".apply_all_to" do
    %w(filter macro typo).each do |tag|
      it "applies registered filters to empty '#{tag}' tags" do
        Blog::Filters.apply_all_to(<<"END_OF_INPUT").should == <<END_OF_OUTPUT
<#{tag}:hello/>
<#{tag}:hello class="example" />
END_OF_INPUT

Hello!

Hello!

END_OF_OUTPUT
      end

      it "applies registered filters to '#{tag}' tags with content" do
        Blog::Filters.apply_all_to(<<"END_OF_INPUT").should == <<END_OF_OUTPUT
<#{tag}:hello>Judy</#{tag}:hello>
<#{tag}:hello class='example' extra="" >Mike
Smith</#{tag}:hello>
END_OF_INPUT

Hello, Judy!

Hello, Mike
Smith!

END_OF_OUTPUT
      end
    end

    it "reports errors inline" do
        Blog::Filters.apply_all_to(<<END_OF_INPUT).should == <<END_OF_OUTPUT
<filter:invalid/>
<filter:hello class= >Mike</filter:hello>
END_OF_INPUT

Text filter not installed: invalid

Can't parse filter arguments: {{ class= }}

END_OF_OUTPUT
    end
  end
end


text:
#ifndef TENSORFLOW_CONTRIB_MPI_MPI_UTILS_H_
#define TENSORFLOW_CONTRIB_MPI_MPI_UTILS_H_

#ifdef TENSORFLOW_USE_MPI

#include <map>
#include <string>
#include <vector>

#include "tensorflow/core/lib/strings/str_util.h"

#include "third_party/mpi/mpi.h"
#define MPI_CHECK(cmd)                                                \
  do {                                                                \
    int mpi_errno = cmd;                                              \
    if (MPI_SUCCESS != mpi_errno) {                                   \
      fprintf(stderr, "[%s:%d] MPI call failed with %d \n", __FILE__, \
              __LINE__, mpi_errno);                                   \
      exit(EXIT_FAILURE);                                             \
    }                                                                 \
    assert(MPI_SUCCESS == mpi_errno);                                 \
  } while (false)

namespace tensorflow {
class MPIUtils {
 public:
  explicit MPIUtils(const std::string& worker_name);

  const int GetSourceID(const std::string& task_id) const {
    auto it = name_to_id_.find(task_id);
    if (it == name_to_id_.end()) {
      LOG(FATAL) << "Failed to convert worker name to MPI index: " << task_id;
    }
    return it->second;
  }

 private:
  void InitMPI();

  std::map<std::string, int> name_to_id_;
};
}  // namespace tensorflow

#endif  // TENSORFLOW_USE_MPI
#endif  // TENSORFLOW_CONTRIB_MPI_MPI_UTILS_H_


text:
//
//  admin_AllUsersApp.m
//  HHSD
//
//  Created by alain serge on 5/11/17.
//  Copyright © 2017 Alain Serge. All rights reserved.
//

#import "admin_AllUsersApp.h"
#import "MainView_C.h"
#import "SWTableViewCell.h"
#import "IMQuickSearch.h"
#import "userAddGraduteMajor.h"
#import "MainView_C.h"
#define kNumberOfObjects 200
#define imageStartX 60
#define textFieldStartX 25
#define H4 SCREEN_HEIGHT/4
#define TL SCREEN_WIDTH-4*textFieldStartX
#define SW2 SCREEN_WIDTH/2
#define SW3 SCREEN_WIDTH/3

#define D 50
#import "CityViewSelectCell.h"
#import "ecoleSearch.h"
#import "SearchModel.h"
#import "UsersModel.h"
#import "MJRefreshGifHeader.h"
#import "GYHHeadeRefreshController.h"

#import "NOOrderView.h"

@interface admin_AllUsersApp ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate,SWTableViewCellDelegate,MyUsersListDelegate>
{
    int _page;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *recordList;
@property (nonatomic, strong) IMQuickSearch *QuickSearch;
@property (nonatomic, strong) NSArray *People;
@property (nonatomic, strong) NSArray *Animals;
@property (weak, nonatomic) IBOutlet UITableView *searchTableView;
@property (nonatomic, strong) UITextField *searchText;
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) NSArray *FilteredResults;
@property (nonatomic, retain) UIButton *selectedBtn;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, retain) NSString *Islike;
@property (nonatomic, retain) NSString *hidden;
@property (nonatomic, retain) NSString *SID;
@property (nonatomic, strong) UIButton *rightNavBtn;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, copy) NSString *c_id;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) All_Province_List *province_list;
@property (nonatomic, strong) Province_List_details *province_details;
@property (nonatomic, strong) NOOrderView *orderView;
@property (nonatomic , assign)int                           count;

@property (nonatomic, strong) All_Users_list *usersList;
@property (nonatomic, strong) All_Users_list *allusers_list;

@end

@implementation admin_AllUsersApp

- (NOOrderView *)orderView {
    if(!_orderView) {
        _orderView = [[NOOrderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
        [self.view addSubview:_orderView];
        _orderView.titleLabel.text = @"Error Loading";
        _orderView.orderLabel.text = @"\U0000e601";
    }
    return _orderView;
}
- (instancetype)init
{
    self = [super init];
    if(!self)
    {
        return nil;
    }
    return self;
}

#pragma mark - init
- (UITableView *)tableView
{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT -64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.backgroundColor = KCOLOR_CLEAR;
        [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];  // hide separtor line

        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Users";

    _page = 1;
    [self tableView];
    [self getAllData:NO];
    [self initUI];

    [self addSearchBtnRight];

}

- (void)initUI
{
    IMP_BLOCK_SELF(admin_AllUsersApp);
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        block_self.count = 0;
        [block_self getAllData:NO];
    }];

    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    self.tableView.header = header;
    [header beginRefreshing];

    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [block_self getAllData:YES];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    DLog(@"%@",self.title);
}

-(void)addSearchBtnRight {
    UIButton *barButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 30)];
    [barButton setTitle:@"\U0000e662" forState:UIControlStateNormal];
    barButton.titleLabel.font = KICON_FONT_(20);
    [barButton addTarget:self action:@selector(ecoleSearch) forControlEvents:UIControlEventTouchUpInside];
    [barButton setTitleColor:[PublicMethod getNaviBarItemColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:barButton];
}

// serach clikc
-(void)ecoleSearch
{
    ecoleSearch *vc = [[ecoleSearch alloc] init];
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark
#pragma mark otherAction
- (void)rightNavBtnClick:(UIButton *)sender
{
    DLog(@"City click");
    sender.selected = !sender.selected;
    if(sender.selected)
    {
        [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
            self.collectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 44);
        } completion:^(BOOL finished) {

        }];
    }else
    {
        [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
            self.collectionView.frame = CGRectMake(0, - SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 44);
        } completion:^(BOOL finished) {

        }];
    }
}

#pragma mark
#pragma mark TableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return (SW2-60)+90;
    }
    else{
        return SW2-60;
    }
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    School_Details *detailsSchool = _searchList.school[indexPath.row];
//    MainView_C *vc = [[MainView_C alloc] init];
//    vc.schoolId = detailsSchool.id;
//
//    School_data *stats = _searchList.school[indexPath.row];
//    NSString *hidden;
//    hidden = stats.hidden;
//
//    if ([hidden isEqualToString:@"1"])  // its coming soon
//    {
//
//    } else if ([hidden isEqualToString:@"0"])  // open new page
//    {
//        [self.navigationController pushViewController:vc animated:YES];
//
//    }
//

}

- (void)setClickView
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.sess_id forKey:@"sess_id"];
    //[params setObject:tmp.SID forKey:@"id"];
    NSMutableString *string = [NSMutableString stringWithString:urlHeader];
    [string appendString:@"Schools/addView"];
    [[NetWork shareInstance] netWorkWithUrl:string params:params isPost:YES sucessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        if([[responseObject objectForKey:@"code"] isEqual:@200])
        {

        }
        if([[responseObject objectForKey:@"code"] isEqual:@500])
        {
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *eror) {

    }];

}

-(void)addItem:(UIButton*) sender
{

}

#pragma mark
#pragma mark UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentity = @"cells";
    adminAllUsersListCell *cells = [_tableView dequeueReusableCellWithIdentifier:cellIdentity];
    if (cells == nil) {
        cells = [[adminAllUsersListCell alloc] initWithStyle:UITableViewCellStyleDefault
                                              reuseIdentifier:cellIdentity];
    }
    if (_allusers_list.users.count >0) {
        Users_view_data *mode =_allusers_list.users[indexPath.row];
        [cells setInfoWith:mode];
    }
    cells.selectionStyle = UITableViewCellSelectionStyleNone;

    NSMutableArray *rightUtilityButtons = [NSMutableArray new];

    Users_view_data *tmp =  _allusers_list.users[indexPath.row];
    _hidden = [NSString stringWithFormat:@"%@",tmp.deleted];

    // Delted/ Live
    if ([_hidden isEqualToString:@"1"])
    {
        [rightUtilityButtons sw_addUtilityButtonWithColor:KCOLOR_RED  title:@"Deleted"];
    }
    else if ([_hidden isEqualToString:@"0"])
    {
        [rightUtilityButtons sw_addUtilityButtonWithColor:KCOLOR_BLUE title:@"Live"];
    }
    [cells setRightUtilityButtons:rightUtilityButtons WithButtonWidth:80.0];

    cells.delegate = self;
    cells.tag = indexPath.row;
    return cells;
}

#pragma mark
#pragma mark ----- SWCellDelegate -----
// click event on right utility button
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
    ;

    NSLog(@" Like click");
    Users_view_data *tmp =  _allusers_list.users[cell.tag];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.sess_id forKey:@"sess_id"];
    [params setObject:tmp.id forKey:@"id"];
    NSMutableString *string = [NSMutableString stringWithString:urlHeader];
    [string appendString:@"Manager/delete_user"];
    [[NetWork shareInstance] netWorkWithUrl:string params:params isPost:YES sucessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        if([[responseObject objectForKey:@"code"] isEqual:@200])
        {
            //[_allusers_list.users removeObjectAtIndex:tmp.indexPath.row];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmp.indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        if([[responseObject objectForKey:@"code"] isEqual:@500])
        {
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *eror) {

    }];
}

// AllSchoolListCell
#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_allusers_list.users.count>0) {
        return 1;
    }
    else
        return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  _allusers_list.users.count;
      //return  self.usersList.users.count;
    //All_Users_list
}

#pragma mark - getAllData
//- (void)getAllData
- (void)getAllData:(BOOL)more
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (more) {
        _page++;
    }
    NSString *currentPage = [NSString stringWithFormat:@"%d",_page];
    kSetDict(currentPage, @"page");
    NSMutableString *string = [NSMutableString stringWithString:urlHeader];
    [string appendString:@"manager/users"];
    [[NetWork shareInstance] netWorkWithUrl:string params:params isPost:NO sucessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        if([[responseObject objectForKey:@"code"] isEqual:@200])
        {

            _allusers_list = [All_Users_list objectWithKeyValues:responseObject[@"data"]];
            if (_allusers_list.users.count == 0 ) {
                [self orderView];
                self.orderView.hidden = NO;
            }
            [self.tableView reloadData];
            [self tableView ];

            if (_allusers_list.users.count<15)
            {
                [self.tableView.footer noticeNoMoreData];
            }

           }else
          {
            _allusers_list = nil;
            _allusers_list = [All_Users_list objectWithKeyValues:responseObject[@"data"]];

            [self.tableView reloadData];
            [self tableView ];
            if([[responseObject objectForKey:@"code"] isEqual:@500])
            {
                [self orderView];
                self.orderView.hidden = NO;
            }else
            {
                [self orderView];
                self.orderView.hidden = NO;
            }
        }
        if([[responseObject objectForKey:@"code"] isEqual:@500])
        {
            [self orderView];
            self.orderView.hidden = NO;
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *eror) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
}

#pragma mark
#pragma mark getAllData
// get province select
/*****
- (void)getCityData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSMutableString *string = [NSMutableString stringWithString:urlHeader];
    [string appendString:@"Schools/provinces"];
    [[NetWork shareInstance] netWorkWithUrl:string params:params isPost:YES sucessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.collectionView = nil;
        if([[responseObject objectForKey:@"code"] isEqual:@200])
        {
            self.province_list = [All_Province_List objectWithKeyValues:responseObject[@"data"]];
            [self.collectionView reloadData];
        }
        if([[responseObject objectForKey:@"code"] isEqual:@500])
        {

        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *eror) {
        [self.tableView.header endRefreshing];
    }];

}

- (void)AddViewActionBtnClick:(Users_view_data *)mode;
{
    DLog(@"cell Click");
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    kSetDict(mode.id, @"id");
    NSMutableString *string = [NSMutableString stringWithString:urlHeader];
    [string appendString:@"schools/addView"];
    [[NetWork shareInstance] netWorkWithUrl:string params:params isPost:YES sucessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.tableView.header endRefreshing];

        if([[responseObject objectForKey:@"code"] isEqual:@200])
        {
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[mode.indexPath copy], nil] withRowAnimation:UITableViewRowAnimationFade];
        }
        if([[responseObject objectForKey:@"code"] isEqual:@500])
        {
            [self MBShowHint:responseObject[@"message"]];
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *eror) {

    }];

}

*****/

@end

@implementation adminAllUsersListCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self) {
        self.backgroundColor=KCOLOR_WHITE;
        [self addContent];
    }
    return  self;
}

-(void)addContent {
    _logoImageView = [[UIImageView alloc] init];
    _maintenance = [[UIImageView alloc] init];
    _fbook = [[UIImageView alloc] init];
    _google = [[UIImageView alloc] init];
    _linkedln = [[UIImageView alloc] init];
    _countryCode = [[UIImageView alloc] init];
    _province = [[UILabel alloc] init];
    _cityTypeIcone = [[UIImageView alloc] init];
     _userAdressIcone = [[UILabel alloc] init];
    _userAdressIconeNow = [[UILabel alloc] init];
    _cityTypeName = [[UILabel alloc] init];
    _climateTypeIcone = [[UIImageView alloc] init];
    _userIconeLocationChina = [[UILabel alloc] init];
    _climateTypeName = [[UILabel alloc] init];
    _livingTypeIcone = [[UIImageView alloc] init];
    _userLocationChina = [[UILabel alloc] init];
    _livingTypeName = [[UILabel alloc] init];
    _lineOne = [[UILabel alloc] init];
    _lineTwo = [[UILabel alloc] init];
    _iconeUserSex = [[UILabel alloc] init];
    _SchoolName = [[UILabel alloc] init];
    _cityName = [[UILabel alloc] init];
    _detailLabel = [[UILabel alloc] init];
    _integralLabel = [[UILabel alloc] init];
    _userFullname = [[UILabel alloc] init];
    _userBirthday = [[UILabel alloc] init];
    _userMobile = [[UILabel alloc] init];

    _logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, SW2/2, SW2/2)];
    _logoImageView.backgroundColor = KCOLOR_WHITE;
    _logoImageView.layer.cornerRadius = _logoImageView.size.height/2;
    _logoImageView.layer.masksToBounds = YES;
    _logoImageView.image = [UIImage imageNamed:NSLocalizedString(@"COMMUN_HOLDER_IMG",comment:"")];
    _logoImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.cellScrollView addSubview:_logoImageView ];

    // smallAvatar

    //maintenance
    _maintenance = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-50,45,30,30)];
    _maintenance.backgroundColor = KCOLOR_CLEAR;
    _maintenance.layer.cornerRadius = _maintenance.size.height/2;
    _maintenance.layer.masksToBounds = YES;
    _maintenance.backgroundColor = KCOLOR_CLEAR;
    _maintenance.contentMode = UIViewContentModeScaleAspectFill;
    [self.cellScrollView addSubview:_maintenance ];

    // name Icone
   _iconeUserSex  = [UILabel createLabelWithFrame:CGRectMake(_logoImageView.right+10,13,20,20)
                                  backgroundColor:KCOLOR_CLEAR
                                        textColor:KTHEME_COLOR
                                             font:KICON_FONT_(15)
                                    textalignment:NSTextAlignmentLeft
                                             text:@"\U0000e634"];
    [self.cellScrollView addSubview:_iconeUserSex];

    // userFullname
        _userFullname = [UILabel createLabelWithFrame:CGRectMake(_iconeUserSex.right+5,10,SCREEN_WIDTH-(((SW2/2)+10)+50),30)
                              backgroundColor:KCOLOR_CLEAR
                                    textColor:KTHEME_COLOR
                                         font:kAutoFont_(13)
                                textalignment:NSTextAlignmentLeft
                                         text:@""];
    _userFullname.numberOfLines= 2;
    [self.cellScrollView addSubview:_userFullname];

    // Birthday Icone
    UILabel *birthdayIcone  = [UILabel createLabelWithFrame:CGRectMake(_logoImageView.right+10,_userFullname.bottom+2,20,20)
                                        backgroundColor:KCOLOR_CLEAR
                                              textColor:KTHEME_COLOR
                                                   font:KICON_FONT_(15)
                                          textalignment:NSTextAlignmentLeft
                                                   text:@"\U0000e771"];
    [self.cellScrollView addSubview:birthdayIcone];

    // userBirthday
    _userBirthday = [UILabel createLabelWithFrame:CGRectMake(birthdayIcone.right+5,_userFullname.bottom,(SCREEN_WIDTH-(((SW2/2)+10)+50))/2.8,30)
                                  backgroundColor:KCOLOR_CLEAR
                                        textColor:KTHEME_COLOR
                                             font:kAutoFont_(10)
                                    textalignment:NSTextAlignmentLeft
                                             text:@""];
    [self.cellScrollView addSubview:_userBirthday];

    // mobile Icone
    UILabel *mobileIcone  = [UILabel createLabelWithFrame:CGRectMake(_logoImageView.right+10,_userBirthday.bottom+2,20,20)
                                            backgroundColor:KCOLOR_CLEAR
                                                  textColor:KTHEME_COLOR
                                                       font:KICON_FONT_(15)
                                              textalignment:NSTextAlignmentLeft
                                                       text:@"\U0000e624"];
    [self.cellScrollView addSubview:mobileIcone];

    // userMobile
    _userMobile = [UILabel createLabelWithFrame:CGRectMake(mobileIcone.right+5,_userBirthday.bottom,(SCREEN_WIDTH-(((SW2/2)+10)+20))/2.8,30)
                                  backgroundColor:KCOLOR_CLEAR
                                        textColor:KCOLOR_BLUE
                                             font:kAutoFont_(10)
                                    textalignment:NSTextAlignmentLeft
                                             text:@""];
    [self.cellScrollView addSubview:_userMobile];

    _countryCode = [[UIImageView alloc] initWithFrame:CGRectMake(_userBirthday.right+2, _userFullname.bottom,20,17)];
    _countryCode.backgroundColor = KCOLOR_CLEAR;
    _countryCode.contentMode = UIViewContentModeScaleToFill;
    [self.cellScrollView  addSubview:_countryCode ];

    // Country user
    _province = [UILabel createLabelWithFrame:CGRectMake(_countryCode.right+5, _userFullname.bottom,(SCREEN_WIDTH-(((SW2/2)+10)+50))/2,20)
                              backgroundColor:KCOLOR_CLEAR
                                    textColor:KCOLOR_Black_343434
                                         font:kAutoFont_(10)
                                textalignment:NSTextAlignmentLeft
                                         text:@""];
    _province.numberOfLines= 2;
    [self.cellScrollView addSubview:_province];

    // City Name

    _cityName = [UILabel createLabelWithFrame:CGRectMake(_province.right+5, _SchoolName.bottom+1,(SCREEN_WIDTH-135)/2,20)
                              backgroundColor:KCOLOR_CLEAR
                                    textColor:KCOLOR_Black_343434
                                         font:kAutoFont_(12)
                                textalignment:NSTextAlignmentLeft
                                         text:@""];
    [self.cellScrollView addSubview:_cityName];

    // Foreigner students total
    _effective = [[ColorLabel alloc] initWithFrame:CGRectMake(_logoImageView.right+10, _cityName.bottom+1,SCREEN_WIDTH-(_logoImageView.right+50),20)];
    _effective.backgroundColor = KCOLOR_CLEAR;
    [self.cellScrollView addSubview:_effective];

    // Description
    _detailLabel =[UILabel createLabelWithFrame:CGRectMake(SCREEN_WIDTH-25,10,20,20)
                                backgroundColor:KCOLOR_CLEAR
                                      textColor:KCOLOR_RED
                                           font:KICON_FONT_(15)
                                  textalignment:NSTextAlignmentLeft
                                           text:nil];
    _detailLabel.numberOfLines = 12;
    _detailLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [self.cellScrollView addSubview:_detailLabel];

    _integralLabel =[UILabel createLabelWithFrame:CGRectMake(SCREEN_WIDTH - 120, 70, 110, 20)
                                  backgroundColor:KCOLOR_CLEAR
                                        textColor:KCOLOR_GRAY_999999
                                             font:kAutoFont_(12)
                                    textalignment:NSTextAlignmentRight
                                             text:@""];
    [self.cellScrollView addSubview:_integralLabel];
    _integralLabel.hidden = YES; //hidden

    // Facebook Icone
    _cityTypeIcone = [[UIImageView alloc] initWithFrame:CGRectMake((SW3/2)-12,(SW2-60),20,20)];
    _cityTypeIcone.backgroundColor = KCOLOR_WHITE;
    _cityTypeIcone.image = [UIImage imageNamed:NSLocalizedString(@"COMMUN_HOLDER_IMG",comment:"")];
    _cityTypeIcone.contentMode = UIViewContentModeScaleAspectFill;
    [self.cellScrollView addSubview:_cityTypeIcone ];

    // City Name
    _cityTypeName = [UILabel resizeFrameWithLabel:_cityTypeName
                                            frame:CGRectMake(0,_cityTypeIcone.bottom,SW3,30)
                                  backgroundColor:KCOLOR_WHITE
                                        textColor:KCOLOR_BLACK
                                             font:KICON_FONT_(11)
                                    textalignment:NSTextAlignmentCenter
                                             text:@""];
    _cityTypeName.numberOfLines =3;
    [self.cellScrollView addSubview:_cityTypeName];

    // Linkedln Icone
    _climateTypeIcone = [[UIImageView alloc] initWithFrame:CGRectMake(SW3+((SW3/2)-12),(SW2-60),20,20)];
    _climateTypeIcone.backgroundColor = KCOLOR_WHITE;
    _climateTypeIcone.image = [UIImage imageNamed:NSLocalizedString(@"COMMUN_HOLDER_IMG",comment:"")];
    _climateTypeIcone.contentMode = UIViewContentModeScaleAspectFill;
    [self.cellScrollView addSubview:_climateTypeIcone ];

    // Climate Name
    _climateTypeName = [UILabel resizeFrameWithLabel:_climateTypeName
                                               frame:CGRectMake(SW3,_climateTypeIcone.bottom,SW3,30)
                                     backgroundColor:KCOLOR_WHITE
                                           textColor:KCOLOR_BLACK
                                                font:KICON_FONT_(11)
                                       textalignment:NSTextAlignmentCenter
                                                text:@""];
    _climateTypeName.numberOfLines =3;
    [self.cellScrollView addSubview:_climateTypeName];

    // Google Icone
    _livingTypeIcone = [[UIImageView alloc] initWithFrame:CGRectMake(2*SW3+((SW3/2)-12),(SW2-60),20,20)];
    _livingTypeIcone.backgroundColor = KCOLOR_WHITE;
    _livingTypeIcone.image = [UIImage imageNamed:NSLocalizedString(@"COMMUN_HOLDER_IMG",comment:"")];
    _livingTypeIcone.contentMode = UIViewContentModeScaleAspectFill;
    [self.cellScrollView addSubview:_livingTypeIcone ];

    // Living Name

    _livingTypeName = [UILabel resizeFrameWithLabel:_livingTypeName
                                              frame:CGRectMake(2*SW3,_livingTypeIcone.bottom,SW3,20)
                                    backgroundColor:KCOLOR_WHITE
                                          textColor:KCOLOR_BLACK
                                               font:KICON_FONT_(11)
                                      textalignment:NSTextAlignmentCenter
                                               text:@""];
    _livingTypeName.numberOfLines =3;
    [self.cellScrollView addSubview:_livingTypeName];

    _lineOne = [UILabel resizeFrameWithLabel:_lineOne
                                       frame:CGRectMake(SW3-0.5,_cityTypeIcone.bottom,0.5,40)
                             backgroundColor:KCOLOR_GRAY_Cell
                                   textColor:KCOLOR_GRAY_Cell
                                        font:KICON_FONT_(11)
                               textalignment:NSTextAlignmentCenter
                                        text:@""];
    [self.cellScrollView addSubview:_lineOne];

    _lineTwo = [UILabel resizeFrameWithLabel:_lineTwo
                                       frame:CGRectMake(_climateTypeName.right-0.5,_climateTypeIcone.bottom,0.5,40)
                             backgroundColor:KCOLOR_GRAY_Cell
                                   textColor:KCOLOR_GRAY_Cell
                                        font:KICON_FONT_(11)
                               textalignment:NSTextAlignmentCenter
                                        text:@""];
    [self.cellScrollView addSubview:_lineTwo];

    // userLocationChina
    _userLocationChina = [UILabel resizeFrameWithLabel:_userLocationChina
                                              frame:CGRectMake(10,_lineTwo.bottom+5,SW2-35,20)
                                    backgroundColor:KCOLOR_WHITE
                                          textColor:KCOLOR_BLACK
                                               font:KICON_FONT_(10)
                                      textalignment:NSTextAlignmentLeft
                                               text:@""];
    [self.cellScrollView addSubview:_userLocationChina];

    //userAdressIcone
    _userAdressIcone = [UILabel resizeFrameWithLabel:_userAdressIcone
                                                      frame:CGRectMake(_userLocationChina.right+1,_lineTwo.bottom+5,SW2-10,20)
                                            backgroundColor:KCOLOR_WHITE
                                                  textColor:KCOLOR_BLACK
                                                       font:KICON_FONT_(11)
                                              textalignment:NSTextAlignmentLeft
                                                       text:@""];
    [self.cellScrollView addSubview:_userAdressIcone];

    UIView *lineView = [UIView createViewWithFrame:CGRectMake(25, 0, SCREEN_WIDTH-50, 0.5)
                                   backgroundColor:KCOLOR_RED];
    [self.cellScrollView addSubview:lineView];

    _actionBtn = [UIButton createButtonwithFrame:CGRectMake(0,0,SCREEN_WIDTH, SW2-40)
                                 backgroundColor:KCOLOR_CLEAR
                                      titleColor:KCOLOR_CLEAR
                                            font:KSYSTEM_FONT_(11)
                                           title:nil];
    [_actionBtn addTarget:self action:@selector(actionAddviewClick) forControlEvents:UIControlEventTouchUpInside];
    // [self.cellScrollView addSubview:_actionBtn];

}

- (void)setInfoWith:(Users_view_data *)users_data {

    if(users_data) {
        if([users_data.avatar_user hasPrefix:@"http"]) {
            [_logoImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",users_data.avatar_user]] placeholderImage:[UIImage imageNamed:@"6000"] options:SDWebImageRetryFailed];
        }

        _cityTypeLabel.text = users_data.total_comments;
         _climateTypeLabel.text = users_data.total_forms;
         _livingTypeLabel.text = users_data.total_like;
        _userFullname.text = users_data.fullName;
         _userBirthday.text = [PublicMethod getYMDUsingCreatedTimestamp:users_data.birthday ];
        _province.text = users_data.country;
        _userMobile.text = users_data.mobile;
        _userLocationChina.text = [NSString stringWithFormat:@"\U0000e677 %@/%@/%@",users_data.province_name,users_data.city_name,users_data.area_name];
        _userAdressIcone.text = [NSString stringWithFormat:@"\U0000e66d %@",users_data.homeAdress];

        //  users_data.province_name,users_data.city_name,users_data.area_name

        // Flag view
        NSString *imagePath = [NSString stringWithFormat:@"CountryPicker.bundle/%@",users_data.Codecountry];

        if(users_data.Codecountry) {
            _countryCode.image = [UIImage imageNamed:imagePath];
        }
        else
        {
            _countryCode.image = [UIImage imageNamed:@""];
        }

        // Facebook
        if ([users_data.facebook isEqualToString:@"1"])
        {
            _cityTypeIcone.image = [UIImage imageNamed:@"fbook"];
            _cityTypeName.text = @"Logged";

        }
        else if ([users_data.facebook isEqualToString:@"0"])
        {
            _cityTypeIcone.image = [UIImage imageNamed:@"fbook"];
            _cityTypeName.text = @"log out";
            _cityTypeName.textColor = KCOLOR_RED;
        }

        //linkedinBtn
        if ([users_data.linkedln isEqualToString:@"1"])
        {
            _climateTypeIcone.image = [UIImage imageNamed:@"linkedinBtn"];
            _livingTypeName.text = @"Logged";

        }
          else if ([users_data.facebook isEqualToString:@"0"])
        {
            _climateTypeIcone.image = [UIImage imageNamed:@"linkedinBtn"];
            _livingTypeName.text = @"log out";
            _livingTypeName.textColor = KCOLOR_RED;
        }

        //Google
        if ([users_data.google isEqualToString:@"1"])
        {
            _livingTypeIcone.image = [UIImage imageNamed:@"googleBtn"];
            _climateTypeName.text = @"Logged";

        }
          else if ([users_data.google isEqualToString:@"0"])
        {
            _livingTypeIcone.image = [UIImage imageNamed:@"googleBtn"];
            _climateTypeName.text = @"Log out";
            _climateTypeName.textColor = KCOLOR_RED;

        }

        //_iconeUserSex

        // Sex
        if ([users_data.sex isEqualToString:@"0"])
        {
            _iconeUserSex.text = @"\U0000e634";

        }
        else if ([users_data.sex isEqualToString:@"1"])
        {
            _iconeUserSex.text = @"\U0000e60f";
            _iconeUserSex.textColor = KCOLOR_RED;

        }
        else if ([users_data.sex isEqualToString:@"2"])
        {
            _iconeUserSex.text = @"\U0000e690";
            _iconeUserSex.textColor = KCOLOR_BLUE;

        }else
        {
            _iconeUserSex.text = @"\U0000e634";

        }

    }
}

-(void)actionAddviewClick
{

}

@end


text:
    1 npm install
    2 npm start
    3 gulp & gulp watch

## API
    TODO

## Usage
    As react start template.

## Others

[Markdown is edited online](http://mahua.jser.me/)

## License
    MIT. See LICENSE.md for details.