text:
var fs = require('graceful-fs')
var path = require('path')

var mkdirp = require('mkdirp')
var mr = require('npm-registry-mock')
var osenv = require('osenv')
var rimraf = require('rimraf')
var test = require('tap').test

var common = require('../common-tap.js')

// Install from a tarball that thinks it is underscore@1.5.1
// (but is actually a fork)
var forkPath = path.resolve(
  __dirname, '..', 'fixtures', 'forked-underscore-1.5.1.tgz'
)
var pkg = path.resolve(__dirname, 'cache-shasum-fork')
var cache = path.join(pkg, 'cache')
var server

test('setup', function (t) {
  setup()
  t.comment('test for https://github.com/npm/npm/issues/3265')
  mr({ port: common.port }, function (er, s) {
    server = s
    t.end()
  })
})

test('npm cache - install from fork', function (t) {
  setup()
  common.npm(
    [
      '--loglevel', 'silent',
      '--json',
      '--registry', common.registry,
      'install', forkPath
    ],
    {
      cwd: pkg,
      env: { npm_config_cache: cache }
    },
    function (err, code, stdout, stderr) {
      t.ifErr(err, 'install finished without error')
      t.notOk(stderr, 'Should not get data on stderr: ' + stderr)
      t.equal(code, 0, 'install finished successfully')

      var deps = {}
      JSON.parse(stdout).added.forEach(function (dep) { deps[dep.name] = dep })
      t.equal(deps.underscore && deps.underscore.version, '1.5.1')
      var index = fs.readFileSync(
        path.join(pkg, 'node_modules', 'underscore', 'index.js'),
        'utf8'
      )
      t.equal(index, 'console.log("This is the fork");\n\n')
      t.end()
    }
  )
})

// Now install the real 1.5.1.
test('npm cache - install from origin', function (t) {
  setup()
  common.npm(
    [
      '--loglevel', 'silent',
      '--json',
      '--registry', common.registry,
      'install', 'underscore'
    ],
    {
      cwd: pkg,
      env: { npm_config_cache: cache }
    },
    function (err, code, stdout, stderr) {
      t.ifErr(err, 'install finished without error')
      t.equal(code, 0, 'install finished successfully')
      t.notOk(stderr, 'Should not get data on stderr: ' + stderr)
      var deps = {}
      JSON.parse(stdout).updated.forEach(function (dep) { deps[dep.name] = dep })
      t.equal(deps.underscore && deps.underscore.version, '1.5.1')
      var index = fs.readFileSync(
        path.join(pkg, 'node_modules', 'underscore', 'index.js'),
        'utf8'
      )
      t.equal(index, 'module.exports = require(\'./underscore\');\n')
      t.end()
    }
  )
})

test('cleanup', function (t) {
  server.close()
  cleanup()
  t.end()
})

function cleanup () {
  process.chdir(osenv.tmpdir())
  rimraf.sync(pkg)
}

function setup () {
  mkdirp.sync(cache)
  mkdirp.sync(path.join(pkg, 'node_modules'))
  process.chdir(pkg)
}


text:
(function() {
  var MultipleSelectMatch, PluginSettings;

  MultipleSelectMatch = (function() {
    function MultipleSelectMatch(table_class) {
      var _this = this;
      this.table_class = table_class;
      $(document).on('click', "." + this.table_class + " + .add-next-match", function(event) {
        event.preventDefault();
        return _this.new_user(event.target);
      });
      $(document).on('click', "." + this.table_class + " .remove-match", function(event) {
        event.preventDefault();
        $(event.target).parents('tr').first().remove();
        return _this.update_json_setting();
      });
      $(document).on('change', "." + this.table_class + " select", function() {
        return _this.update_json_setting();
      });
      true;
    }

    MultipleSelectMatch.prototype.new_user = function(link) {
      var template;
      template = $($(link).data('template'));
      $(link).prev().find('tbody').append(template);
      return true;
    };

    MultipleSelectMatch.prototype.update_json_setting = function() {
      var matches,
        _this = this;
      matches = {};
      $("." + this.table_class + " tr").each(function(idx, el) {
        var key, value;
        key = $('select', el).first().val();
        value = $('select', el).last().val();
        if (key.length > 0 && value.length > 0) {
          return matches[key] = value;
        }
      });
      return $("#settings_" + this.table_class).val(JSON.stringify(matches));
    };

    return MultipleSelectMatch;

  })();

  PluginSettings = (function() {
    function PluginSettings() {
      var name, _i, _len, _ref;
      this.select_matches = {};
      _ref = ['default_users', 'default_activity'];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        name = _ref[_i];
        this.select_matches[name] = new MultipleSelectMatch(name);
      }
    }

    return PluginSettings;

  })();

  jQuery(function() {
    return window.pluginSettings = new PluginSettings();
  });

}).call(this);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Form\Processor;

use App\Form\RecurrenceForm;
use App\Repository\RecurrenceRepository;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class RecurrenceFormProcessor extends DefaultFormProcessor
{
    public function __construct(
        RecurrenceRepository $repository,
        FormFactoryInterface $formFactory,
        TokenStorageInterface $tokenStorage
    ) {
        parent::__construct(RecurrenceForm::class, $repository, $formFactory, $tokenStorage);
    }
}


text:
import time
import collections

from util import helper
from Plugin import PluginManager
import ContentDbPlugin

def processAccessLog():
    if access_log:
        content_db = ContentDbPlugin.content_db
        now = int(time.time())
        num = 0
        for site_id in access_log:
            content_db.execute(
                "UPDATE file_optional SET time_accessed = %s WHERE ?" % now,
                {"site_id": site_id, "inner_path": access_log[site_id].keys()}
            )
            num += len(access_log[site_id])
        access_log.clear()

def processRequestLog():
    if request_log:
        content_db = ContentDbPlugin.content_db
        cur = content_db.getCursor()
        num = 0
        cur.execute("BEGIN")
        for site_id in request_log:
            for inner_path, uploaded in request_log[site_id].iteritems():
                content_db.execute(
                    "UPDATE file_optional SET uploaded = uploaded + %s WHERE ?" % uploaded,
                    {"site_id": site_id, "inner_path": inner_path}
                )
                num += 1
        cur.execute("END")
        request_log.clear()

if "access_log" not in locals().keys():  # To keep between module reloads
    access_log = collections.defaultdict(dict)  # {site_id: {inner_path1: 1, inner_path2: 1...}}
    request_log = collections.defaultdict(lambda: collections.defaultdict(int))  # {site_id: {inner_path1: 1, inner_path2: 1...}}
    helper.timer(61, processAccessLog)
    helper.timer(60, processRequestLog)

@PluginManager.registerTo("WorkerManager")
class WorkerManagerPlugin(object):
    def doneTask(self, task):
        if task["optional_hash_id"]:
            content_db = self.site.content_manager.contents.db
            content_db.executeDelayed(
                "UPDATE file_optional SET time_downloaded = :now, is_downloaded = 1, peer = peer + 1 WHERE site_id = :site_id AND inner_path = :inner_path",
                {"now": int(time.time()), "site_id": content_db.site_ids[self.site.address], "inner_path": task["inner_path"]}
            )

        super(WorkerManagerPlugin, self).doneTask(task)

        if task["optional_hash_id"] and not self.tasks:
            content_db.processDelayed()

@PluginManager.registerTo("UiRequest")
class UiRequestPlugin(object):
    def parsePath(self, path):
        global access_log
        path_parts = super(UiRequestPlugin, self).parsePath(path)
        if path_parts:
            site_id = ContentDbPlugin.content_db.site_ids.get(path_parts["request_address"])
            if site_id:
                if ContentDbPlugin.content_db.isOptionalFile(site_id, path_parts["inner_path"]):
                    access_log[site_id][path_parts["inner_path"]] = 1
        return path_parts

@PluginManager.registerTo("FileRequest")
class FileRequestPlugin(object):
    def actionGetFile(self, params):
        stats = super(FileRequestPlugin, self).actionGetFile(params)
        self.recordFileRequest(params["site"], params["inner_path"], stats)
        return stats

    def actionStreamFile(self, params):
        stats = super(FileRequestPlugin, self).actionStreamFile(params)
        self.recordFileRequest(params["site"], params["inner_path"], stats)
        return stats

    def recordFileRequest(self, site_address, inner_path, stats):
        if not stats:
            # Only track the last request of files
            return False
        site_id = ContentDbPlugin.content_db.site_ids[site_address]
        if site_id and ContentDbPlugin.content_db.isOptionalFile(site_id, inner_path):
            request_log[site_id][inner_path] += stats["bytes_sent"]

@PluginManager.registerTo("Site")
class SitePlugin(object):
    def isDownloadable(self, inner_path):
        is_downloadable = super(SitePlugin, self).isDownloadable(inner_path)
        if is_downloadable:
            return is_downloadable

        for path in self.settings.get("optional_help", {}).iterkeys():
            if inner_path.startswith(path):
                return True

        return False

@PluginManager.registerTo("ConfigPlugin")
class ConfigPlugin(object):
    def createArguments(self):
        group = self.parser.add_argument_group("OptionalManager plugin")
        group.add_argument('--optional_limit', help='Limit total size of optional files', default="10%", metavar="GB or free space %")

        return super(ConfigPlugin, self).createArguments()


text:
static NSString * const SpriterRefNoParentValue = @"-1";

/// Use this value if there is no pivot value for a SpriterObject so it will retrieved from the SpriterFile.
static CGFloat const SpriterObjectNoPivotValue = CGFLOAT_MIN;


text:
namespace DAVA
{
namespace SceneUtilsDetails
{
void RetainRenderEntitiesRecursive(Entity* node, Vector<Entity*>& entities)
{
    for (Entity* child : node->children)
        RetainRenderEntitiesRecursive(child, entities);

    if (GetRenderObject(node) != nullptr)
        entities.push_back(SafeRetain(node));
}

bool VerifyNames(const List<Entity*>& lodNodes, const String& lodSubString)
{
    bool allNamesAreDifferent = true;

    Map<String, String> validationMap;
    for (Entity* oneLodNode : lodNodes)
    {
        const String lodName(oneLodNode->GetName().c_str());
        const String nodeWithoutLodsName(lodName, 0, lodName.find(lodSubString));

        if (validationMap.count(nodeWithoutLodsName) != 0)
        {
            Logger::Error("Geometry Error: %s will overwrite geometry of %s", lodName.c_str(), validationMap[nodeWithoutLodsName].c_str());
            allNamesAreDifferent = false;
        }
        else
        {
            validationMap[nodeWithoutLodsName] = lodName;
        }
    }

    return allNamesAreDifferent;
}

bool RemoveEmptyEntitiesRecursive(Entity* entity)
{
    for (int32 c = 0; c < entity->GetChildrenCount(); ++c)
    {
        Entity* childNode = entity->GetChild(c);
        bool removed = RemoveEmptyEntitiesRecursive(childNode);
        if (removed)
        {
            c--;
        }
    }

    if ((entity->GetChildrenCount() == 0) && (typeid(*entity) == typeid(Entity)))
    {
        KeyedArchive* customProperties = GetCustomPropertiesArchieve(entity);
        bool doNotRemove = customProperties && customProperties->IsKeyExists("editor.donotremove");

        uint32 componentCount = entity->GetComponentCount();

        Component* tr = entity->GetComponent(Type::Instance<TransformComponent>());
        Component* cp = entity->GetComponent(Type::Instance<CustomPropertiesComponent>());
        if (((componentCount == 2) && (!cp || !tr)) || (componentCount > 2))
        {
            doNotRemove = true;
        }

        if (entity->GetName().find("dummy") != String::npos)
        {
            doNotRemove = true;
        }

        if (!doNotRemove)
        {
            Entity* parent = entity->GetParent();
            if (parent)
            {
                parent->RemoveNode(entity);
                return true;
            }
        }
    }
    return false;
}
} //SceneUtilsDetails

bool SceneUtils::CombineLods(Scene* scene)
{
    bool result = true;
    Vector<Entity*> childrenCopy = scene->children;

    for (Entity* child : childrenCopy)
        child->Retain();

    for (Entity* child : childrenCopy)
        result &= CombineEntityLods(child);

    for (Entity* child : childrenCopy)
        child->Release();

    return result;
}

String SceneUtils::LodNameForIndex(const String& pattern, uint32 lodIndex)
{
    return Format(pattern.c_str(), lodIndex);
}

bool SceneUtils::CombineEntityLods(Entity* forRootNode)
{
    const String lodNamePattern("_lod%d");
    const String dummyLodNamePattern("_lod%ddummy");

    List<Entity*> lod0Nodes;

    // try to find nodes which have lodNamePattrn.
    const String lod0 = LodNameForIndex(lodNamePattern, 0);
    if (!forRootNode->FindNodesByNamePart(lod0, lod0Nodes))
    {
        // There is no lods.
        return true;
    }

    //model validation step: we should ignore combination of lods if we found several geometry meshes per lod
    if (SceneUtilsDetails::VerifyNames(lod0Nodes, lod0) == false)
    {
        return false;
    }

    // ok. We have some nodes with lod 0 in the name. Try to find other lods for same name.
    for (Entity* oneLodNode : lod0Nodes)
    {
        // node name which contains lods
        const String lodName(oneLodNode->GetName().c_str());
        const String nodeWithLodsName(lodName, 0, lodName.find(lod0));

        Entity* oldParent = oneLodNode->GetParent();

        ScopedPtr<Entity> newNodeWithLods(new Entity());
        newNodeWithLods->SetName(nodeWithLodsName.c_str());

        Array<Vector<Entity*>, LodComponent::MAX_LOD_LAYERS> lodEntities;

        int32 lodCount = 0;
        for (int32 lodNo = 0; lodNo < LodComponent::MAX_LOD_LAYERS; ++lodNo)
        {
            // Try to find node with same name but with other lod
            const FastName lodIName(nodeWithLodsName + LodNameForIndex(lodNamePattern, lodNo));
            Entity* ln = oldParent->FindByName(lodIName.c_str());

            if (nullptr != ln)
            {
                SceneUtilsDetails::RetainRenderEntitiesRecursive(ln, lodEntities[lodNo]);
                CollapseAnimationsUpToFarParent(ln, newNodeWithLods);

                oldParent->RemoveNode(ln);

                ++lodCount;
            }

            // Try to find dummy lod node
            const FastName dummyLodName(nodeWithLodsName + LodNameForIndex(dummyLodNamePattern, lodNo));
            ln = oldParent->FindByName(dummyLodName.c_str());

            if (nullptr != ln)
            {
                // Remove dummy nodes
                ln->RemoveAllChildren();
                oldParent->RemoveNode(ln);
            }
        }

        if (lodCount > 0)
        {
            LodComponent* lc = new LodComponent();
            newNodeWithLods->AddComponent(lc);
            if (lodCount < LodComponent::MAX_LOD_LAYERS && lodCount > LodComponent::INVALID_LOD_LAYER)
            {
                // Fix max lod distance for max used lod index
                lc->SetLodLayerDistance(lodCount, LodComponent::MAX_LOD_DISTANCE);
            }
        }

        SkeletonComponent* skeleton = nullptr;
        for (int32 lodNo = 0; lodNo < LodComponent::MAX_LOD_LAYERS; ++lodNo)
        {
            for (Entity* node : lodEntities[lodNo])
            {
                //Search any skeleton. Skeleton should be the same in all lods
                skeleton = GetSkeletonComponent(node);
                if (skeleton)
                {
                    node->DetachComponent(skeleton);
                    newNodeWithLods->AddComponent(skeleton);
                    break;
                }
            }
            if (skeleton)
                break;
        }

        RenderObject* newMesh = nullptr;
        if (skeleton)
        {
            newMesh = new SkinnedMesh();
        }
        else
        {
            newMesh = new Mesh();
        }

        for (int32 lodNo = 0; lodNo < LodComponent::MAX_LOD_LAYERS; ++lodNo)
        {
            for (Entity* node : lodEntities[lodNo])
            {
                RenderObject* lodRenderObject = GetRenderObject(node);

                while (lodRenderObject->GetRenderBatchCount() > 0)
                {
                    ScopedPtr<RenderBatch> batch(SafeRetain(lodRenderObject->GetRenderBatch(0)));

                    lodRenderObject->RemoveRenderBatch(batch);
                    newMesh->AddRenderBatch(batch, lodNo, -1);

                    if (lodRenderObject->GetType() == RenderObject::TYPE_SKINNED_MESH)
                    {
                        SkinnedMesh* newSkinnedMesh = static_cast<SkinnedMesh*>(newMesh);
                        SkinnedMesh* lodSkinnedMesh = static_cast<SkinnedMesh*>(lodRenderObject);

                        SkinnedMesh::JointTargets targets = lodSkinnedMesh->GetJointTargets(batch);
                        if (!targets.empty())
                        {
                            newSkinnedMesh->SetJointTargets(batch, targets);
                        }
                    }
                };

                SafeRelease(node);
            }
        }

        RenderComponent* rc = new RenderComponent();
        rc->SetRenderObject(newMesh);
        SafeRelease(newMesh);

        newNodeWithLods->AddComponent(rc);
        oldParent->AddNode(newNodeWithLods);

        DVASSERT(oldParent->GetScene());
        DVASSERT(newNodeWithLods->GetScene());
    }

    return true;
}

void SceneUtils::BakeTransformsUpToFarParent(Entity* parent, Entity* currentNode)
{
    for (Entity* child : currentNode->children)
    {
        BakeTransformsUpToFarParent(parent, child);
    }

    // Bake transforms to geometry
    RenderObject* ro = GetRenderObject(currentNode);
    if (ro)
    {
        // Get actual transformation for current entity
        Matrix4 totalTransform = currentNode->AccamulateTransformUptoFarParent(parent);
        ro->BakeGeometry(totalTransform);
    }

    // Set local transform as Ident because transform is already baked up into geometry
    TransformComponent* transform = currentNode->GetComponent<TransformComponent>();
    transform->SetLocalTransform(TransformUtils::IDENTITY);
}

void SceneUtils::CollapseAnimationsUpToFarParent(Entity* node, Entity* parent)
{
    for (Entity* child : parent->children)
    {
        CollapseAnimationsUpToFarParent(child, parent);
    }

    Component* ac = GetAnimationComponent(node);
    if (ac)
    {
        node->DetachComponent(ac);
        parent->AddComponent(ac);
    }
}

bool SceneUtils::RemoveEmptyEntities(Scene* scene)
{
    return SceneUtilsDetails::RemoveEmptyEntitiesRecursive(scene);
}

} //namespace DAVA


text:
<?xml version="1.0" encoding="UTF-8"?>

<sect1 id="learning.form.decorators.individual">
    <title>Rendu individuel des décorateurs</title>

    <para>
        Dans la <link linkend="learning.form.decorators.layering">section précédente</link>, nous
        avons vu comment combiner les décorateurs afin de créer un rendu complexe. Ceci est très fléxible
        mais rajoute tout de même un part de compléxité à l'ensemble. Dans ce chapitre, nous allons
        inspecter le rendu individuel des décorateurs afin de créer du contenu visuel pour des
        formulaires ou des éléments.
    </para>

    <para>
        Une fois des décorateurs enregistrés, vous pouvez les récupérer via leur nom depuis l'élément.
        Revoyons l'exemple précédent:
    </para>

    <programlisting language="php"><![CDATA[
$element = new Zend_Form_Element('foo', array(
    'label'      => 'Foo',
    'belongsTo'  => 'bar',
    'value'      => 'test',
    'prefixPath' => array('decorator' => array(
        'My_Decorator' => 'path/to/decorators/',
    )),
    'decorators' => array(
        'SimpleInput'
        array('SimpleLabel', array('placement' => 'append')),
    ),
));
]]></programlisting>

    <para>
        Si nous voulons récupérer le décorateur <classname>SimpleInput</classname>, nous passons
        par la méthode <methodname>getDecorator()</methodname>:
    </para>

    <programlisting language="php"><![CDATA[
$decorator = $element->getDecorator('SimpleInput');
echo $decorator->render('');
]]></programlisting>

    <para>
        C'est simple et ça peut l'être encore plus; ré-écrivons le tout sur une seule ligne:
    </para>

    <programlisting language="php"><![CDATA[
echo $element->getDecorator('SimpleInput')->render('');
]]></programlisting>

    <para>
        Pas mauvais, mais toujours un peu compliqué. Pour simplifier, une notation raccourcie a été
        introduite dans <classname>Zend_Form</classname> en 1.7: vous pouvez rendre n'importe quel
        décorateur enregistré en appelant une méthode de la forme
        <methodname>renderDecoratorName()</methodname>.
        Ceci effectue le rendu et fait en sorte que <varname>$content</varname> soit optionnel ce qui
        simplifie l'utilisation:
    </para>

    <programlisting language="php"><![CDATA[
echo $element->renderSimpleInput();
]]></programlisting>

    <para>
        C'est une simplification astucieuse, mais comment et pourquoi l'utiliser?
    </para>

    <para>
        Beaucoup de développeurs ont des besoins très précis en affichage des formulaires. Ils préfèrent
        avoir un contrôle complet sur tout l'affichage plutôt que d'utiliser une solution automatisée
        qui peut s'écarter de leur but initial. Dans d'autres cas, les formulaires peuvent demander
        un affichage extrêmement spécifique, en groupant des éléments alors que d'autres doivent
        pouvoir être invisibles avant que l'on n'effectue telle action sur la page, etc.
    </para>

    <para>
        Utilisons la possibilité de rendre un seul décorateur pour créer un affichage précis.
    </para>

    <para>
        D'abord, définissons un formulaire. Celui-ci récupèrera des détails démographiques sur l'utilisateur.
        Le rendu sera hautement personnalisé et dans certains cas il utilisera les aides de vue directement
        plutôt que les éléments. Voici une définition simple du formulaire:
    </para>

    <programlisting language="php"><![CDATA[
class My_Form_UserDemographics extends Zend_Form
{
    public function init()
    {
        // Ajoute un chemin pour les décorateurs personnalisés
        $this->addElementPrefixPaths(array(
            'decorator' => array('My_Decorator' => 'My/Decorator'),
        ));

        $this->addElement('text', 'firstName', array(
            'label' => 'First name: ',
        ));
        $this->addElement('text', 'lastName', array(
            'label' => 'Last name: ',
        ));
        $this->addElement('text', 'title', array(
            'label' => 'Title: ',
        ));
        $this->addElement('text', 'dateOfBirth', array(
            'label' => 'Date of Birth (DD/MM/YYYY): ',
        ));
        $this->addElement('text', 'email', array(
            'label' => 'Your email address: ',
        ));
        $this->addElement('password', 'password', array(
            'label' => 'Password: ',
        ));
        $this->addElement('password', 'passwordConfirmation', array(
            'label' => 'Confirm Password: ',
        ));
    }
}
]]></programlisting>

    <note>
        <para>
            Nous n'utilisons pas de validateurs ou de filtres ici, car ils n'ont rien à voir avec le
            rendu visuel qui nous interesse. En réalité, il y en aurait.
        </para>
    </note>

    <para>
        Maintenant réfléchissons au rendu visuel du formulaire. Une communalité concernant les nom
        et prénom est qu'on les affiche l'un à coté de l'autre, à coté de leur titre, si présent.
        Les dates, si elles n'utilisent pas Javascript, affichent souvent des champs séparés pour
        chaque segment de la date.
    </para>

    <para>
        Utilisons la possibilité de rendre des décorateurs un par un pour accomplir notre tâche.
        D'abord, notez qu'aucun décorateur spécifique n'a été renseigné dans les éléments.
        Rappelons donc les décorateurs par défaut de la plupart des éléments:
    </para>

    <itemizedlist>
        <listitem>
            <para>
                <classname>ViewHelper</classname>: utilise une aide de vue pour rendre l'élément
                balise de formulaire à proprement parlé.
            </para>
        </listitem>

        <listitem>
            <para>
                <classname>Errors</classname>: utilise l'aide de vue <classname>FormErrors</classname>
                pour afficher les erreurs de validation éventuelles.
            </para>
        </listitem>

        <listitem>
            <para>
                <classname>Description</classname>: utilise l'aide de vue <classname>FormNote</classname>
                afin de rendre la description éventuelle de l'élément.
            </para>
        </listitem>

        <listitem>
            <para>
                <classname>HtmlTag</classname>: encapsule les trois objets ci-dessus dans un tag
                <emphasis><dd></emphasis>.
            </para>
        </listitem>

        <listitem>
            <para>
                <classname>Label</classname>: rend l'intitulé de l'élément en utilisant l'aide de vue
                <classname>FormLabel</classname> (et en encapsulant le tout dans un tag
                <emphasis><dt></emphasis>).
            </para>
        </listitem>
    </itemizedlist>

    <para>
        Nous vous rappelons aussi que vous pouvez accéder à tout élément individuellement en tant
        qu'attribut du formulaire représentant son nom.
    </para>

    <para>
        Notre script de vue ressemblerait à cela:
    </para>

    <programlisting language="php"><![CDATA[
<?php
$form = $this->form;
// Enlève le
 depuis l'intitulé
foreach ($form->getElements() as $element) {
    $element->getDecorator('label')->setOption('tag', null);
}
?>
<form method="<?php echo $form->getMethod() ?>" action="<?php echo
    $form->getAction()?>">

        <?php echo $form->title->renderLabel()
              . $form->title->renderViewHelper() ?>
        <?php echo $form->firstName->renderLabel()
              . $form->firstName->renderViewHelper() ?>
        <?php echo $form->lastName->renderLabel()
              . $form->lastName->renderViewHelper() ?>

        <?php echo $form->dateOfBirth->renderLabel() ?>
        <?php echo $this->formText('dateOfBirth[day]', '', array(
            'size' => 2, 'maxlength' => 2)) ?>
        /
        <?php echo $this->formText('dateOfBirth[month]', '', array(
            'size' => 2, 'maxlength' => 2)) ?>
        /
        <?php echo $this->formText('dateOfBirth[year]', '', array(
            'size' => 4, 'maxlength' => 4)) ?>

        <?php echo $form->password->renderLabel()
              . $form->password->renderViewHelper() ?>

        <?php echo $form->passwordConfirmation->renderLabel()
              . $form->passwordConfirmation->renderViewHelper() ?>

    <?php echo $this->formSubmit('submit', 'Save') ?>
</form>
]]></programlisting>

    <para>
        Si vous utilisez le script ci-dessus, vous verrez un code HTML ressemblant à ceci:
    </para>

    <programlisting language="html"><![CDATA[
<form method="post" action="">

        Title:
        <input type="text" name="title" id="title" value=""/>

        First name:
        <input type="text" name="firstName" id="firstName" value=""/>

        Last name:
        <input type="text" name="lastName" id="lastName" value=""/>

        Date of Birth
            (DD/MM/YYYY):
        <input type="text" name="dateOfBirth[day]" id="dateOfBirth-day"
            value="" size="2" maxlength="2"/>
        /
        <input type="text" name="dateOfBirth[month]" id="dateOfBirth-month"
            value="" size="2" maxlength="2"/>
        /
        <input type="text" name="dateOfBirth[year]" id="dateOfBirth-year"
            value="" size="4" maxlength="4"/>

        Password:
        <input type="password" name="password" id="password" value=""/>

</form>
]]></programlisting>

    <para>
        Ca peut ne pas ressembler à quelque chose de terminé, mais avec un peu de CSS, cela peut
        ressembler exactement à ce que vous cherchez. Le point important ici, c'est que le formulaire
        a été généré en utilisant de la décoration manuelle personnalisée (ainsi que l'utilisation
        d'échappement avec htmlentities).
    </para>

    <para>
        Grâce à cette partie du tutoriel, vous devriez être à l'aise avec les possibilité de rendu de
        <classname>Zend_Form</classname>. Dans la section suivante, nous verrons comment monter un
        élément de date grâce à des éléments et des décorateur uniques assemblés main.
    </para>
</sect1>


text:
package me.lachlanap.pacandroid.view.fonts;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;

import java.util.HashMap;
import java.util.Map;

public class FontRenderer {

    private Map<String, BitmapFont> fonts;
    private GlyphLayout glyphLayout;
    private BitmapFont font;

    public FontRenderer() {
        fonts = new HashMap<String, BitmapFont>();
        glyphLayout = new GlyphLayout();
        loadFonts();
    }

    private void loadFonts() {
        FreeTypeFontGenerator benderGenerator = new FreeTypeFontGenerator(
                Gdx.files.internal("fonts/arial.ttf"));

        BitmapFont benderSolid = benderGenerator.generateFont(50);
        benderSolid.setColor(1f, 1f, 1f, 1f);
        fonts.put("BenderSolid", benderSolid);

        benderGenerator.dispose();

        font = benderSolid;
    }

    public void setFont(String font) {
        this.font = fonts.get(font);
    }

    public BitmapFont getFont() {
        return font;
    }

    public void setColor(Color c) {
        font.setColor(c);
    }

    public void setAlpha(float alpha) {
        font.setColor(font.getColor().r, font.getColor().g, font.getColor().b,
                      alpha);
    }

    public void drawString(String string, SpriteBatch batch, int x, int y) {
        if (font == null)
            throw new IllegalStateException("Font must be set");

        font.draw(batch, string, x, y);
    }

    public void drawStringCentred(String string, SpriteBatch batch, int x, int y) {
        glyphLayout.setText(font, string);
        x -= glyphLayout.width / 2;
        y -= glyphLayout.height / 2;

        drawString(string, batch, x, y);
    }
}


text:
import Base.isempty
export enum, enumbreadthfirst, enumdepthfirst, enumlikelyfirst

type Stack
    store
    Stack() = new(Any[])
end

# I doubt enq!/deq! will run in constant time for this. Perhaps look
# at DataStructures.jl.
type Queue
    store
    Queue() = new(Any[])
end

# Provide a minimal common interface over Stack, Queue, PriorityQueue.

enq!(a::Union(Stack,Queue), item) = push!(a.store, item)

deq!(a::Stack) = pop!(a.store)
deq!(a::Queue) = shift!(a.store)

isempty(a::Union(Stack,Queue)) = isempty(a.store)

enq!(q::PriorityQueue, item) = enqueue!(q, item, -item[1])
deq!(q::PriorityQueue) = dequeue!(q)

type Enum <: Ctx
    score::Float64
    path
    unexplored
    Enum(queuetype) = new(0, Any[], queuetype())
end

# @pp
function sample(s::Store, k::Function, a, e::ERP, ctx::Enum)
    for val in support(e)
        enq!(ctx.unexplored, (ctx.score + score(e, val), () -> k(s,val), [ctx.path, val]))
    end
    runnext(ctx)
end

# @pp
function factor(s::Store, k::Function, a, score, ctx::Enum)
    ctx.score += score
    k(s, nothing)
end

function runnext(ctx::Ctx)
    score, cont, path = deq!(ctx.unexplored)
    ctx.score = score
    ctx.path = path
    cont()
end

# @pp
enum(s::Store, k::Function, a, comp::Function, maximumexec::Int64=0) = enumbreadthfirst(s, k, a, comp, maximumexec)

enumdepthfirst(s::Store, k::Function, a, comp::Function, maximumexec::Int64=0) = enum(s, k, a, comp, Stack, maximumexec)
enumbreadthfirst(s::Store, k::Function, a, comp::Function, maximumexec::Int64=0) = enum(s, k, a, comp, Queue, maximumexec)
enumlikelyfirst(s::Store, k::Function, a, comp::Function, maximumexec::Int64=0) = enum(s, k, a, comp, PriorityQueue, maximumexec)

function enum(store::Store, k::Function, address, comp::Function, queuetype::DataType, maximumexec::Int64=0)
    global ctx
    returns = Dict{Any,Float64}()
    ctxold, ctx = ctx, Enum(queuetype)
    try
        currentexec = 0
        trampoline() do
            partial(comp,store)(address) do _store, value
                currentexec += 1
                returns[value] = get(returns, value, 0) + exp(ctx.score)
                if maximumexec > 0 && currentexec == maximumexec
                    info("Maximum executions reached.")
                elseif !isempty(ctx.unexplored)
                    runnext(ctx)
                end
            end
        end
    finally
        ctx = ctxold
    end
    # Note: The context must be restored before calling k.
    k(store, Discrete(returns))
end


text:
@interface UILabel(JustifiedText)

-(void)setJustifiedText:(NSString *)text;
-(void)setJustifiedText:(NSString *)text firstLineHeadIndent:(CGFloat)firstLineHeadIndent;

@end

#endif


text:
'use strict';

describe('Controller: ChartController', function() {
  var $controller,
    $httpBackend,
    $interval,
    $location,
    $mdDialog,
    $rootScope,
    $stateParams,
    EagleEyeWebService,
    EEDialogService;

  var ChartController,
    getChartByIdRequestHandler;

  // load main module
  beforeEach(module('eagleeye'));

  // load ngMaterial mock module
  beforeEach(module('ngMaterialMock'));

  // load EagleEyeWebService mock module
  beforeEach(module('EagleEyeWebServiceMock'));

  // mock dependent services
  beforeEach(module(function($provide) {
    $provide.factory('$stateParams', function() {
      return { id: '1' };
    });
  }));

  // reset router
  beforeEach(module(function($urlRouterProvider) {
    $urlRouterProvider.otherwise(function() { return false; });
  }));

  beforeEach(inject(function(
      _$controller_, _$mdDialog_, _$rootScope_, _$stateParams_, _$httpBackend_,
      _$location_, _$interval_, _EagleEyeWebService_, _EEDialogService_) {

    $controller = _$controller_;
    $mdDialog = _$mdDialog_;
    $rootScope = _$rootScope_;
    $stateParams = _$stateParams_;
    $httpBackend = _$httpBackend_;
    $location = _$location_;
    $interval = _$interval_;
    EagleEyeWebService = _EagleEyeWebService_;
    EEDialogService = _EEDialogService_;
  }));

  beforeEach(function() {
    getChartByIdRequestHandler =
      $httpBackend.when('GET', '/api/v1/charts/1').respond({});
  });

  beforeEach(function() {
    ChartController = $controller('ChartController', {
      $stateParams: $stateParams,
      $location: $location,
      $interval: $interval,
      EagleEyeWebService: EagleEyeWebService,
      EEDialogService: EEDialogService
    });
  });

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it('should be able to create controller', function() {
    expect(ChartController).toBeDefined();
    $httpBackend.flush();
  });

  describe('on initialize', function() {

    afterEach(function() {
      $httpBackend.flush();
    });

    it('should initialize `id` model', function() {
      expect(ChartController.id).toBe('1');
    });

    it('should initialize `DELAY` model to one minute', function() {
      expect(ChartController.DELAY).toBe(60 * 1000);
    });

    it('should initialize `chart` model', function() {
      expect(ChartController.chart).not.toBeNull();
      expect(typeof ChartController.chart).toBe('object');
    });
  });

  describe('on bootstrap', function() {

    it('should fetch chart with id', function() {
      $httpBackend.expect('GET', '/api/v1/charts/1');
      $httpBackend.flush();
    });

    it('should set `chart` model when request success', function() {
      getChartByIdRequestHandler.respond({ _id: '1' });
      $httpBackend.flush();

      expect(ChartController.chart).toEqual({ _id: '1' });
    });

    it('should do nothing when request error', function() {
      ChartController.chart = {};

      getChartByIdRequestHandler.respond(500);
      $httpBackend.flush();

      expect(ChartController.chart).toEqual({});
    });

    it('should generate data table download link', function() {
      getChartByIdRequestHandler.respond({ _id: '1' });
      $httpBackend.flush();

      expect(ChartController.downloadLink)
        .toBe('http://localhost/api/v1/charts/1/datatable?format=xlsx');
    });
  });

  describe('on runtime', function() {

    beforeEach(function() {
      $httpBackend.flush();
    });

    describe('init()', function() {

      it('should call `loadChart()` with `ChartController.id`', function() {
        spyOn(ChartController, 'loadChart');
        ChartController.id = '1';

        ChartController.init();

        expect(ChartController.loadChart).toHaveBeenCalledWith('1');
      });
    });

    describe('loadChart()', function() {

      it('should fetch chart with given id', function() {
        ChartController.loadChart('1');

        $httpBackend.expect('GET', '/api/v1/charts/1');
        $httpBackend.flush();
      });

      it('should set `chart` model when request success', function() {
        ChartController.loadChart('1');
        getChartByIdRequestHandler.respond({ _id: '1' });
        $httpBackend.flush();

        expect(ChartController.chart).toEqual({ _id: '1' });
      });

      it('should do nothing when request error', function() {
        ChartController.chart = {};

        ChartController.loadChart('1');
        getChartByIdRequestHandler.respond(500);
        $httpBackend.flush();

        expect(ChartController.chart).toEqual({});
      });
    });

    describe('showShare()', function() {

      it('should use EEDialogService to show a sharing dialog', function() {
        spyOn($location, 'absUrl').and.returnValue('eagleeye');

        ChartController.showShare('title');

        expect($mdDialog.show).toHaveBeenCalledWith({
          locals: {
            sharedTitle: 'title',
            sharedLink: 'eagleeye'
          },
          controller: 'ShareDialogController as ctrl',
          templateUrl: 'scripts/templates/share.tmpl.html',
          parent: angular.element(document.body),
          clickOutsideToClose: true,
          fullscreen: true
        });
      });
    });

    describe('generateDownloadLink()', function() {

      it('should generate a download link', function() {
        var id = '123';
        var format = 'xlsx';
        ChartController.downloadLink = '';

        ChartController.generateDownloadLink(id, format)
          .then(function(link) {
            expect(link).toBe('http://localhost/api/v1/charts/'
                              + id + '/datatable?format=' + format);
          })
          .catch(function(error) {
            fail(error);
          });

        $rootScope.$digest();
      });
    });
  });
});


text:
class Libmodplug < Formula
  desc "Library from the Modplug-XMMS project"
  homepage "http://modplug-xmms.sourceforge.net/"
  url "https://downloads.sourceforge.net/modplug-xmms/libmodplug/0.8.8.5/libmodplug-0.8.8.5.tar.gz"
  sha256 "77462d12ee99476c8645cb5511363e3906b88b33a6b54362b4dbc0f39aa2daad"

  bottle do
    cellar :any
    revision 1
    sha1 "0901d9ad6b88c87cffaf2e9f7c2e38159f0c4c68" => :yosemite
    sha1 "82462ed1591281bc461165071b7479417c9f3493" => :mavericks
    sha1 "ecddcd3abd6d223334c2404f14f1f79eb93b08ba" => :mountain_lion
  end

  def install
    system "./configure", "--disable-debug",
                          "--disable-dependency-tracking",
                          "--disable-silent-rules",
                          "--prefix=#{prefix}"

    system "make", "install"
  end

  resource "testmod" do
    # Most favourited song on modarchive:
    # http://modarchive.org/index.php?request=view_by_moduleid&query=60395
    url "http://api.modarchive.org/downloads.php?moduleid=60395#2ND_PM.S3M"
    sha256 "f80735b77123cc7e02c4dad6ce8197bfefcb8748b164a66ffecd206cc4b63d97"
  end

  test do
    # First a basic test just that we can link on the library
    # and call an initialization method.
    (testpath/"test_null.cpp").write <<-EOS.undent
      #include "libmodplug/modplug.h"
      int main() {
        ModPlugFile* f = ModPlug_Load((void*)0, 0);
        if (!f) {
          // Expecting a null pointer, as no data supplied.
          return 0;
        } else {
          return -1;
        }
      }
    EOS
    system ENV.cc, "test_null.cpp", "-lmodplug", "-o", "test_null"
    system "./test_null"

    # Second, acquire an actual music file from a popular internet
    # source and attempt to parse it.
    resource("testmod").stage testpath
    (testpath/"test_mod.cpp").write <<-EOS.undent
      #include "libmodplug/modplug.h"
      #include <fstream>
      #include <sstream>

      int main() {
        std::ifstream in("downloads.php");
        std::stringstream buffer;
        buffer << in.rdbuf();
        int length = buffer.tellp();
        ModPlugFile* f = ModPlug_Load(buffer.str().c_str(), length);
        if (f) {
          // Expecting success
          return 0;
        } else {
          return -1;
        }
      }
    EOS
    system ENV.cc, "test_mod.cpp", "-lmodplug", "-lstdc++", "-o", "test_mod"
    system "./test_mod"
  end
end


text:
<!DOCTYPE html>

      <meta charset="utf-8">

      <title>DSSG EUROPE - SUSTAINABLE TOURISM IN FLORENCE</title>
      <meta name="description" content="">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <link href="./css/flexslider.min.css" rel="stylesheet" type="text/css" media="all"/>
      <link href="./css/line-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
      <link href="./css/elegant-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
      <link href="./css/lightbox.min.css" rel="stylesheet" type="text/css" media="all"/>
      <link href="./css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
      <link href="./css/theme.css" rel="stylesheet" type="text/css" media="all"/>
      <link href="./css/custom.css" rel="stylesheet" type="text/css" media="all"/>

      <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700%7CRaleway:700' rel='stylesheet' type='text/css'>

Home

FirenzeCard

Telecom

Flows

						Leveraging Data to Improve Our Cities

Towards a More Sustainable Future of Tourism in Florence

            Data Science for Social Good Europe 2017

          Data-Driven Planning for Sustainable Tourism in Tuscany

					Mass tourism is at a tipping point. High-speed trains and low-cost airlines allow larger amounts of people to travel faster, and more frequently than ever before. Tourism is of great economic benefit to communities worldwide, however many touristic destinations are insufficiently equipped to react to the increasing flux of visitors.

          New methods combining data mining, machine learning, and data science are beginning to be used to understand the impact of mass tourism on cities and find solutions to better accommodate tourists. Data Science for Social Good Europe is a yearly summer initiative to use such techniques to tackle key issues with a social impact. This past summer 2017, a team data science fellows assisted several partner organisations in shedding light on tourism patterns in the city of Florence. This work using digital traces created by tourists to continue current work in progress by the municipality of Florence, with the aim of providing tools that can improve both the management of crowds and the quality experience for tourists and residents alike.

Created by Cristina Lozano, Io Flament, and Momin Malik.

            Report
            DSSG Europe
            Github

All analysis and opinions contained here are the authors' own, and are not necessarily held or endorsed by any of the partners or data-providing agencies.

Acknowledgements

              Toscana Promozione Turistica
             |
              Comune di Firenze, Assessorato al Turismo e Direzione Cultura
             |
              Linea Comune S.p.A
             |
              The Ufficio di Statistica at Ministero dei Beni e delle Attività Culturali e del Turismo
             |
              Centro Studi Turistici di Firenze
             |
              Toscana Aeroporti
             |
              Uffici informazioni turistiche della Città Metropolitana di Firenze
             |
              Uffici Informazioni Turistiche del Comune di Firenze
             |
              Servizi alla Strada S.p.A.
             |
              Istituto Regionale Programmazione Economica Toscana
              |
              Vodafone Italy
             |
              Collective Sensing (CS) Research Foundation
             |
              Nova School of Business and Economics
             |
              The University of Chicago
             |
              Amazon Web Services


text:
static char const rcsid[] = "$Id: batch.cc 171 2008-04-17 22:57:24Z lacroute $";

#include <stdexcept>
#include <iostream>
#include <sstream>

extern "C" {
#include <string.h>
#include <sys/time.h>
#include <sys/errno.h>
}

#include "batch.hh"

using std::runtime_error;
using std::logic_error;
using std::ostringstream;
using std::endl;

StubBatchSystem::StubBatchSystem ():
    nextJobId_(1)
{
}

// return true if job is submitted without problems
bool
StubBatchSystem::submit (Job& job)
{
    JobState state;
    state.submitTime = currentTime();
    unsigned jobCnt = 0;
    for (JobMap::iterator iter = jobs_.begin(); iter != jobs_.end(); ++iter) {
	if (iter->second.endTime > state.submitTime) {
	    ++jobCnt;
	}
    }
    state.schedTime = state.submitTime + 20;
    if (jobCnt > 35) {
	state.startTime = state.schedTime + 120;
    } else {
	state.startTime = state.schedTime;
    }
    state.endTime = state.startTime + 60;
    jobs_[nextJobId_] = state;
    job.setJobId(nextJobId_);
    job.changeStatus(Job::Dispatched);
    ++nextJobId_;
    return true;
}

void
StubBatchSystem::kill (Job& job)
{
    if (job.status() == Job::Dispatched ||
	job.status() == Job::Running) {
	job.changeStatus(Job::Failed);
    }
}

// return true if status changes
bool
StubBatchSystem::checkStatus (Job& job)
{
    JobMap::iterator iter = jobs_.find(job.jobId());
    if (iter == jobs_.end()) {
	throw logic_error("invalid job " + job.name());
    }
    unsigned now = currentTime();
    if (now > iter->second.endTime) {
	if (job.status() != Job::Done) {
	    job.changeStatus(Job::Done);
	    job.setCpuTime(5);
	    job.setWallclockTime(7);
	    job.setMemoryUsage(200);
	    job.setSwapUsage(250);
	    return true;
	}
    } else if (now > iter->second.startTime) {
	if (job.status() == Job::Dispatched || job.status() == Job::Pending) {
	    job.changeStatus(Job::Running);
	    return true;
	}
    } else if (now > iter->second.schedTime) {
	if (job.status() == Job::Dispatched) {
	    job.changeStatus(Job::Pending);
	    return true;
	}
    }
    return false;
}

// return true iff batch system supports the wait call
bool
StubBatchSystem::canWait ()
{
    return false;
}

// wait for a job to finish or exit
Job *
StubBatchSystem::wait (JobGraph& jobs, unsigned timeout_sec)
{
    return 0;
}

// return current time in seconds
unsigned
StubBatchSystem::currentTime ()
{
    struct timeval tv;
    if (gettimeofday(&tv, 0) < 0) {
	ostringstream err;
	err << "gettimeofday failed: " << strerror(errno);
	throw runtime_error(err.str());
    }
    return tv.tv_sec;
}

void
StubBatchSystem::cleanup ()
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:orientation="horizontal"
    android:paddingBottom="10dp"
    android:paddingTop="10dp"
    android:layout_marginTop="5dp"
    android:background="@drawable/layer_card_background">

    <ImageView
        android:id="@+id/list_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <LinearLayout
        android:id="@+id/list_item_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_weight="1">

        <TextView
            android:id="@+id/list_item_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/text_margin"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/list_item_posterName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/text_margin"
            android:textAppearance="?attr/textAppearanceListItem" />

    </LinearLayout>

</LinearLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/tmp/tmp-deduplicated8863231811913961175/blaze-out/gcc-4.X.Y-crosstool-v18-hybrid-grtev4-k8-opt/genfiles/java/com/google/android/gmscore/integ/client/admob/res/values-el/strings.xml -->
    <eat-comment/>
    <string msgid="6361267646005304214" name="accept">"Αποδοχή"</string>
    <string msgid="6585634416571795096" name="create_calendar_message">"Να επιτραπεί στη διαφήμιση να δημιουργήσει ένα συμβάν στο ημερολόγιο;"</string>
    <string msgid="5763102366548941325" name="create_calendar_title">"Δημιουργία συμβάντος στο ημερολόγιο"</string>
    <string msgid="6520798050439307862" name="decline">"Απόρριψη"</string>
    <string msgid="9018493135943017231" name="store_picture_message">"Να επιτραπεί στη διαφήμιση να αποθηκεύσει την εικόνα στο gallery φωτογραφιών;"</string>
    <string msgid="3745622764880844111" name="store_picture_title">"Αποθήκευση εικόνας"</string>
</resources>


text:
//
//   Copyright 2015 Blu Age Corporation - Plano, Texas
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

// This file has been modified.
// Original copyright notice :

using System;
using System.Runtime.Serialization;

namespace Summer.Batch.Infrastructure.Item.File
{
    /// <summary>
    /// Exception thrown when errors are encountered with the underlying resource.
    /// </summary>
    [Serializable]
    public class NonTransientFlatFileException : NonTransientResourceException
    {
        /// <summary>
        /// The original input.
        /// </summary>
        public string Input { get; private set; }

        /// <summary>
        /// The number of the line read when the error occured.
        /// </summary>
        public int LineNumber { get; private set; }

        /// <summary>
        /// Constructs a new <see cref="T:NonTransientFlatFileException"/> with the specified message and input.
        /// </summary>
        /// <param name="message">the detail message</param>
        /// <param name="input">the read input</param>
        public NonTransientFlatFileException(string message, string input) : base(message)
        {
            Input = input;
        }

        /// <summary>
        /// Constructs a new <see cref="T:NonTransientFlatFileException"/> with the specified message, input, and line number.
        /// </summary>
        /// <param name="message">the detail message</param>
        /// <param name="input">the read input</param>
        /// <param name="lineNumber">the number of the read line</param>
        public NonTransientFlatFileException(string message, string input, int lineNumber) : base(message)
        {
            Input = input;
            LineNumber = lineNumber;
        }

        /// <summary>
        /// Constructs a new <see cref="T:NonTransientFlatFileException"/> with the specified message, input, line number, and parent exception.
        /// </summary>
        /// <param name="message">the detail message</param>
        /// <param name="exception">the parent exception</param>
        /// <param name="input">the read input</param>
        /// <param name="lineNumber">the number of the read line</param>
        public NonTransientFlatFileException(string message, Exception exception, string input, int lineNumber) : base(message, exception)
        {
            Input = input;
            LineNumber = lineNumber;
        }

        /// <summary>
        /// Constructor for deserialization.
        /// </summary>
        /// <param name="info">the info holding the serialization data</param>
        /// <param name="context">the serialization context</param>
        public NonTransientFlatFileException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
            Input = info.GetString("Input");
            LineNumber = info.GetInt32("LineNumber");
        }

        #region ISerializable member

        /// <summary>
        /// Sets the <see cref="SerializationInfo"/> with information about the exception.
        /// </summary>
        /// <param name="info">
        /// The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.
        /// </param>
        /// <param name="context">
        /// The <see cref="StreamingContext"/> that contains contextual information about the source or destination.
        /// </param>
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
            info.AddValue("Input", Input);
            info.AddValue("LineNumber", LineNumber);
        }

        #endregion
    }
}


text:
/**
 * @desc  This file contains used user roles within application. These are used to authorize user access to application
 *        routes - for more information see one of those ***.routes.js files on sources.
 * @name  UserRoles
 *
 * @type {{
 *    ROLE_ANON: string,
 *    ROLE_LOGGED: string,
 *    ROLE_USER: string,
 *    ROLE_ADMIN: string,
 *    ROLE_ROOT: string
 *  }}
 */
const UserRoles = {
  ROLE_ANON: 'ROLE_ANON',
  ROLE_LOGGED: 'ROLE_LOGGED',
  ROLE_USER: 'ROLE_USER',
  ROLE_ADMIN: 'ROLE_ADMIN',
  ROLE_ROOT: 'ROLE_ROOT',
};

export default UserRoles;


text:
import { Status, Options } from '../';

/**
 * Yields action objects used in signalling that a notice is to be created.
 *
 * @param [status='info'] - Notice status.
 * @param content - Notice message.
 * @param [options={}] - Notice options.
 */
export function createNotice(status: Status | undefined, content: string, options?: Partial<Options>): void;

/**
 * Dispatches an action signalling that an error notice is to be created.
 *
 * @param content - Notice message.
 * @param [options] - Optional notice options.
 */
export function createErrorNotice(content: string, options?: Partial<Options>): void;

/**
 * Dispatches an action signalling that an info notice is to be created.
 *
 * @param content - Notice message.
 * @param [options] - Optional notice options.
 */
export function createInfoNotice(content: string, options?: Partial<Options>): void;

/**
 * Dispatches an action signalling that a success notice is to be created.
 *
 * @param content - Notice message.
 * @param [options] - Optional notice options.
 */
export function createSuccessNotice(content: string, options?: Partial<Options>): void;

/**
 * Dispatches an action signalling that a warning notice is to be created.
 *
 * @param content - Notice message.
 * @param [options] - Optional notice options.
 */
export function createWarningNotice(content: string, options?: Partial<Options>): void;

/**
 * Dispatches an action signalling that a notice is to be removed.
 *
 * @param id - Notice's unique identifier.
 * @param [context] - Optional context (grouping) in which the notice is intended to appear.
 */
export function removeNotice(id: string, context?: string): void;


text:
<?php
/**
 * BuddyPress Common Admin Functions.
 *
 * @package BuddyPress
 * @subpackage CoreAdministration
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/** Menu **********************************************************************/

/**
 * Initializes the wp-admin area "BuddyPress" menus and sub menus.
 *
 * @package BuddyPress Core
 * @uses bp_current_user_can() returns true if the current user is a site admin, false if not
 */
function bp_core_admin_menu_init() {
	add_action( bp_core_admin_hook(), 'bp_core_add_admin_menu', 9 );
}

/**
 * In BP 1.6, the top-level admin menu was removed. For backpat, this function
 * keeps the top-level menu if a plugin has registered a menu into the old
 * 'bp-general-settings' menu.
 *
 * The old "bp-general-settings" page was renamed "bp-components".
 *
 * @global array $_parent_pages
 * @global array $_registered_pages
 * @global array $submenu
 * @since 1.6.0
 */
function bp_core_admin_backpat_menu() {
	global $_parent_pages, $_registered_pages, $submenu;

	// If there's no bp-general-settings menu (perhaps because the current
	// user is not an Administrator), there's nothing to do here
	if ( ! isset( $submenu['bp-general-settings'] ) ) {
		return;
	}

	/**
	 * By default, only the core "Help" submenu is added under the top-level BuddyPress menu.
	 * This means that if no third-party plugins have registered their admin pages into the
	 * 'bp-general-settings' menu, it will only contain one item. Kill it.
	 */
	if ( 1 != count( $submenu['bp-general-settings'] ) ) {
		return;
	}

	// This removes the top-level menu
	remove_submenu_page( 'bp-general-settings', 'bp-general-settings' );
	remove_menu_page( 'bp-general-settings' );

	// These stop people accessing the URL directly
	unset( $_parent_pages['bp-general-settings'] );
	unset( $_registered_pages['toplevel_page_bp-general-settings'] );
}
add_action( bp_core_admin_hook(), 'bp_core_admin_backpat_menu', 999 );

/**
 * This tells WP to highlight the Settings > BuddyPress menu item,
 * regardless of which actual BuddyPress admin screen we are on.
 *
 * The conditional prevents the behaviour when the user is viewing the
 * backpat "Help" page, the Activity page, or any third-party plugins.
 *
 * @global string $plugin_page
 * @global array $submenu
 * @since 1.6.0
 */
function bp_core_modify_admin_menu_highlight() {
	global $plugin_page, $submenu_file;

	// This tweaks the Settings subnav menu to show only one BuddyPress menu item
	if ( ! in_array( $plugin_page, array( 'bp-activity', 'bp-general-settings', ) ) ) {
		$submenu_file = 'bp-components';
	}

	// Network Admin > Tools
	if ( in_array( $plugin_page, array( 'bp-tools', 'available-tools' ) ) ) {
		$submenu_file = $plugin_page;
	}
}

/**
 * Generates markup for a fallback top-level BuddyPress menu page, if the site is running
 * a legacy plugin which hasn't been updated. If the site is up to date, this page
 * will never appear.
 *
 * @see bp_core_admin_backpat_menu()
 * @since 1.6.0
 * @todo Add convenience links into the markup once new positions are finalised.
 */
function bp_core_admin_backpat_page() {
	$url          = bp_core_do_network_admin() ? network_admin_url( 'settings.php' ) : admin_url( 'options-general.php' );
	$settings_url = add_query_arg( 'page', 'bp-components', $url ); ?>

<?php _e( 'Why have all my BuddyPress menus disappeared?', 'buddypress' ); ?>

<?php _e( "Don't worry! We've moved the BuddyPress options into more convenient and easier to find locations. You're seeing this page because you are running a legacy BuddyPress plugin which has not been updated.", 'buddypress' ); ?>

<?php printf( __( 'Components, Pages, Settings, and Forums, have been moved to Settings > BuddyPress. Profile Fields has been moved into the Users menu.', 'buddypress' ), esc_url( $settings_url ), bp_get_admin_url( 'users.php?page=bp-profile-setup' ) ); ?>

	<?php
}

/** Notices *******************************************************************/

/**
 * Print admin messages to admin_notices or network_admin_notices.
 *
 * BuddyPress combines all its messages into a single notice, to avoid a preponderance of yellow
 * boxes.
 *
 * @since 1.5.0
 *
 * @uses bp_current_user_can() to check current user permissions before showing the notices.
 * @uses bp_is_root_blog()
 */
function bp_core_print_admin_notices() {

	// Only the super admin should see messages
	if ( ! bp_current_user_can( 'bp_moderate' ) ) {
		return;
	}

	// On multisite installs, don't show on a non-root blog, unless
	// 'do_network_admin' is overridden.
	if ( is_multisite() && bp_core_do_network_admin() && ! bp_is_root_blog() ) {
		return;
	}

	$notice_types = array();
	foreach ( buddypress()->admin->notices as $notice ) {
		$notice_types[] = $notice['type'];
	}
	$notice_types = array_unique( $notice_types );

	foreach ( $notice_types as $type ) {
		$notices = wp_list_filter( buddypress()->admin->notices, array( 'type' => $type ) );
		printf( '
', sanitize_html_class( $type ) );

		foreach ( $notices as $notice ) {
			printf( '
%s
', $notice['message'] );
		}

		printf( '
' );
	}
}
add_action( 'admin_notices',         'bp_core_print_admin_notices' );
add_action( 'network_admin_notices', 'bp_core_print_admin_notices' );

/**
 * Add an admin notice to the BP queue.
 *
 * Messages added with this function are displayed in BuddyPress's general purpose admin notices
 * box. It is recommended that you hook this function to admin_init, so that your messages are
 * loaded in time.
 *
 * @since 1.5.0
 *
 * @param string $notice The notice you are adding to the queue.
 * @param string $type   The notice type; optional. Usually either "updated" or "error".
 */
function bp_core_add_admin_notice( $notice = '', $type = 'updated' ) {

	// Do not add if the notice is empty
	if ( empty( $notice ) ) {
		return;
	}

	// Double check the object before referencing it
	if ( ! isset( buddypress()->admin->notices ) ) {
		buddypress()->admin->notices = array();
	}

	// Add the notice
	buddypress()->admin->notices[] = array(
		'message' => $notice,
		'type'    => $type,
	);
}

/**
 * Verify that some BP prerequisites are set up properly, and notify the admin if not.
 *
 * On every Dashboard page, this function checks the following:
 *   - that pretty permalinks are enabled.
 *   - that every BP component that needs a WP page for a directory has one.
 *   - that no WP page has multiple BP components associated with it.
 * The administrator will be shown a notice for each check that fails.
 *
 * @global WPDB $wpdb WordPress DB object
 * @global WP_Rewrite $wp_rewrite
 * @since 1.2.0
 */
function bp_core_activation_notice() {
	global $wp_rewrite, $wpdb;

	// Only the super admin gets warnings
	if ( ! bp_current_user_can( 'bp_moderate' ) ) {
		return;
	}

	// Bail in user admin
	if ( is_user_admin() ) {
		return;
	}

	// On multisite installs, don't load on a non-root blog, unless do_network_admin is overridden
	if ( is_multisite() && bp_core_do_network_admin() && ! bp_is_root_blog() ) {
		return;
	}

	// Bail if in network admin, and BuddyPress is not network activated
	if ( is_network_admin() && ! bp_is_network_activated() ) {
		return;
	}

	/**
	 * Check to make sure that the blog setup routine has run. This can't
	 * happen during the wizard because of the order which the components
	 * are loaded.
	 */
	if ( bp_is_active( 'blogs' ) ) {
		$bp    = buddypress();
		$count = $wpdb->get_var( "SELECT COUNT(*) FROM {$bp->blogs->table_name}" );

		if ( empty( $count ) ) {
			bp_blogs_record_existing_blogs();
		}
	}

	// Add notice if no rewrite rules are enabled
	if ( empty( $wp_rewrite->permalink_structure ) ) {
		bp_core_add_admin_notice( sprintf( __( 'BuddyPress is almost ready. You must update your permalink structure to something other than the default for it to work.', 'buddypress' ), admin_url( 'options-permalink.php' ) ), 'error' );
	}

	// Get BuddyPress instance
	$bp = buddypress();

	/**
	 * Check for orphaned BP components (BP component is enabled, no WP page exists)
	 */
	$orphaned_components = array();
	$wp_page_components  = array();

	// Only components with 'has_directory' require a WP page to function
	foreach( array_keys( $bp->loaded_components ) as $component_id ) {
		if ( !empty( $bp->{$component_id}->has_directory ) ) {
			$wp_page_components[] = array(
				'id'   => $component_id,
				'name' => isset( $bp->{$component_id}->name ) ? $bp->{$component_id}->name : ucwords( $bp->{$component_id}->id )
			);
		}
	}

	// Activate and Register are special cases. They are not components but they need WP pages.
	// If user registration is disabled, we can skip this step.
	if ( bp_get_signup_allowed() ) {
		$wp_page_components[] = array(
			'id'   => 'activate',
			'name' => __( 'Activate', 'buddypress' )
		);

		$wp_page_components[] = array(
			'id'   => 'register',
			'name' => __( 'Register', 'buddypress' )
		);
	}

	// On the first admin screen after a new installation, this isn't set, so grab it to suppress a misleading error message.
	if ( empty( $bp->pages->members ) ) {
		$bp->pages = bp_core_get_directory_pages();
	}

	foreach( $wp_page_components as $component ) {
		if ( !isset( $bp->pages->{$component['id']} ) ) {
			$orphaned_components[] = $component['name'];
		}
	}

	// Special case: If the Forums component is orphaned, but the bbPress 1.x installation is
	// not correctly set up, don't show a nag. (In these cases, it's probably the case that the
	// user is using bbPress 2.x; see https://buddypress.trac.wordpress.org/ticket/4292
	if ( isset( $bp->forums->name ) && in_array( $bp->forums->name, $orphaned_components ) && !bp_forums_is_installed_correctly() ) {
		$forum_key = array_search( $bp->forums->name, $orphaned_components );
		unset( $orphaned_components[$forum_key] );
		$orphaned_components = array_values( $orphaned_components );
	}

	if ( !empty( $orphaned_components ) ) {
		$admin_url = bp_get_admin_url( add_query_arg( array( 'page' => 'bp-page-settings' ), 'admin.php' ) );
		$notice    = sprintf( __( 'The following active BuddyPress Components do not have associated WordPress Pages: %2$s. Repair', 'buddypress' ), esc_url( $admin_url ), '' . implode( ', ', $orphaned_components ) . '' );

		bp_core_add_admin_notice( $notice );
	}

	// BP components cannot share a single WP page. Check for duplicate assignments, and post a message if found.
	$dupe_names = array();
	$page_ids   = (array)bp_core_get_directory_page_ids();
	$dupes      = array_diff_assoc( $page_ids, array_unique( $page_ids ) );

	if ( !empty( $dupes ) ) {
		foreach( array_keys( $dupes ) as $dupe_component ) {
			$dupe_names[] = $bp->pages->{$dupe_component}->title;
		}

		// Make sure that there are no duplicate duplicates :)
		$dupe_names = array_unique( $dupe_names );
	}

	// If there are duplicates, post a message about them
	if ( !empty( $dupe_names ) ) {
		$admin_url = bp_get_admin_url( add_query_arg( array( 'page' => 'bp-page-settings' ), 'admin.php' ) );
		$notice    = sprintf( __( 'Each BuddyPress Component needs its own WordPress page. The following WordPress Pages have more than one component associated with them: %2$s. Repair', 'buddypress' ), esc_url( $admin_url ), '' . implode( ', ', $dupe_names ) . '' );

		bp_core_add_admin_notice( $notice );
	}
}

/**
 * Redirect user to BuddyPress's What's New page on activation.
 *
 * @since 1.7.0
 *
 * @internal Used internally to redirect BuddyPress to the about page on activation.
 *
 * @uses get_transient() To see if transient to redirect exists.
 * @uses delete_transient() To delete the transient if it exists.
 * @uses is_network_admin() To bail if being network activated.
 * @uses wp_safe_redirect() To redirect.
 * @uses add_query_arg() To help build the URL to redirect to.
 * @uses admin_url() To get the admin URL to index.php.
 */
function bp_do_activation_redirect() {

	// Bail if no activation redirect
	if ( ! get_transient( '_bp_activation_redirect' ) ) {
		return;
	}

	// Delete the redirect transient
	delete_transient( '_bp_activation_redirect' );

	// Bail if activating from network, or bulk
	if ( isset( $_GET['activate-multi'] ) ) {
		return;
	}

	$query_args = array( 'page' => 'bp-about' );
	if ( get_transient( '_bp_is_new_install' ) ) {
		$query_args['is_new_install'] = '1';
		delete_transient( '_bp_is_new_install' );
	}

	// Redirect to BuddyPress about page
	wp_safe_redirect( add_query_arg( $query_args, bp_get_admin_url( 'index.php' ) ) );
}

/** UI/Styling ****************************************************************/

/**
 * Output the tabs in the admin area.
 *
 * @since 1.5.0
 *
 * @param string $active_tab Name of the tab that is active. Optional.
 */
function bp_core_admin_tabs( $active_tab = '' ) {
	$tabs_html    = '';
	$idle_class   = 'nav-tab';
	$active_class = 'nav-tab nav-tab-active';

	/**
	 * Filters the admin tabs to be displayed.
	 *
	 * @since 1.9.0
	 *
	 * @param array $value Array of tabs to output to the admin area.
	 */
	$tabs         = apply_filters( 'bp_core_admin_tabs', bp_core_get_admin_tabs( $active_tab ) );

	// Loop through tabs and build navigation
	foreach ( array_values( $tabs ) as $tab_data ) {
		$is_current = (bool) ( $tab_data['name'] == $active_tab );
		$tab_class  = $is_current ? $active_class : $idle_class;
		$tabs_html .= '' . esc_html( $tab_data['name'] ) . '';
	}

	echo $tabs_html;

	/**
	 * Fires after the output of tabs for the admin area.
	 *
	 * @since 1.5.0
	 */
	do_action( 'bp_admin_tabs' );
}

/**
 * Get the data for the tabs in the admin area.
 *
 * @since 2.2.0
 *
 * @param string $active_tab Name of the tab that is active. Optional.
 *
 * @return string
 */
function bp_core_get_admin_tabs( $active_tab = '' ) {
	$tabs = array(
		'0' => array(
			'href' => bp_get_admin_url( add_query_arg( array( 'page' => 'bp-components' ), 'admin.php' ) ),
			'name' => __( 'Components', 'buddypress' )
		),
		'1' => array(
			'href' => bp_get_admin_url( add_query_arg( array( 'page' => 'bp-page-settings' ), 'admin.php' ) ),
			'name' => __( 'Pages', 'buddypress' )
		),
		'2' => array(
			'href' => bp_get_admin_url( add_query_arg( array( 'page' => 'bp-settings' ), 'admin.php' ) ),
			'name' => __( 'Settings', 'buddypress' )
		),
	);

	// If forums component is active, add additional tab
	if ( bp_is_active( 'forums' ) && class_exists( 'BP_Forums_Component' ) ) {

		// enqueue thickbox
		wp_enqueue_script( 'thickbox' );
		wp_enqueue_style( 'thickbox' );

		$tabs['3'] = array(
			'href' => bp_get_admin_url( add_query_arg( array( 'page' => 'bb-forums-setup'  ), 'admin.php' ) ),
			'name' => __( 'Forums', 'buddypress' )
		);
	}

	/**
	 * Filters the tab data used in our wp-admin screens.
	 *
	 * @since 2.2.0
	 *
	 * @param array $tabs Tab data.
	 */
	return apply_filters( 'bp_core_get_admin_tabs', $tabs );
}

/** Help **********************************************************************/

/**
 * adds contextual help to BuddyPress admin pages.
 *
 * @since 1.7.0
 * @todo Make this part of the BP_Component class and split into each component
 *
 * @param string $screen
 */
function bp_core_add_contextual_help( $screen = '' ) {

	$screen = get_current_screen();

	switch ( $screen->id ) {

		// Component page
		case 'settings_page_bp-components' :

			// help tabs
			$screen->add_help_tab( array(
				'id'      => 'bp-comp-overview',
				'title'   => __( 'Overview', 'buddypress' ),
				'content' => bp_core_add_contextual_help_content( 'bp-comp-overview' ),
			) );

			// help panel - sidebar links
			$screen->set_help_sidebar(
				'
' . __( 'For more information:', 'buddypress' ) . '
' .
				'
' . __( 'Managing Components', 'buddypress' ) . '
' .
				'
' . __( 'Support Forums', 'buddypress' ) . '
'
			);
			break;

		// Pages page
		case 'settings_page_bp-page-settings' :

			// Help tabs
			$screen->add_help_tab( array(
				'id' => 'bp-page-overview',
				'title' => __( 'Overview', 'buddypress' ),
				'content' => bp_core_add_contextual_help_content( 'bp-page-overview' ),
			) );

			// Help panel - sidebar links
			$screen->set_help_sidebar(
				'
' . __( 'For more information:', 'buddypress' ) . '
' .
				'
' . __( 'Managing Pages', 'buddypress' ) . '
' .
				'
' . __( 'Support Forums', 'buddypress' ) . '
'
			);

			break;

		// Settings page
		case 'settings_page_bp-settings' :

			// Help tabs
			$screen->add_help_tab( array(
				'id'      => 'bp-settings-overview',
				'title'   => __( 'Overview', 'buddypress' ),
				'content' => bp_core_add_contextual_help_content( 'bp-settings-overview' ),
			) );

			// Help panel - sidebar links
			$screen->set_help_sidebar(
				'
' . __( 'For more information:', 'buddypress' ) . '
' .
				'
' . __( 'Managing Settings', 'buddypress' ) . '
' .
				'
' . __( 'Support Forums', 'buddypress' ) . '
'
			);

			break;

		// Profile fields page
		case 'users_page_bp-profile-setup' :

			// Help tabs
			$screen->add_help_tab( array(
				'id'      => 'bp-profile-overview',
				'title'   => __( 'Overview', 'buddypress' ),
				'content' => bp_core_add_contextual_help_content( 'bp-profile-overview' ),
			) );

			// Help panel - sidebar links
			$screen->set_help_sidebar(
				'
' . __( 'For more information:', 'buddypress' ) . '
' .
				'
' . __( 'Managing Profile Fields', 'buddypress' ) . '
' .
				'
' . __( 'Support Forums', 'buddypress' ) . '
'
			);

			break;
	}
}
add_action( 'contextual_help', 'bp_core_add_contextual_help' );

/**
 * renders contextual help content to contextual help tabs.
 *
 * @since 1.7.0
 *
 * @param string $tab
 *
 * @return string
 */
function bp_core_add_contextual_help_content( $tab = '' ) {

	switch ( $tab ) {
		case 'bp-comp-overview' :
			$retval = __( 'By default, all but four of the BuddyPress components are enabled. You can selectively enable or disable any of the components by using the form below. Your BuddyPress installation will continue to function. However, the features of the disabled components will no longer be accessible to anyone using the site.', 'buddypress' );
			break;

		case 'bp-page-overview' :
			$retval = __( 'BuddyPress Components use WordPress Pages for their root directory/archive pages. You can change the page associations for each active component by using the form below.', 'buddypress' );
			break;

		case 'bp-settings-overview' :
			$retval = __( 'Extra configuration settings are provided and activated. You can selectively enable or disable any setting by using the form on this screen.', 'buddypress' );
			break;

		case 'bp-profile-overview' :
			$retval = __( 'Your users will distinguish themselves through their profile page. Create relevant profile fields that will show on each users profile.', 'buddypress' ) . '

' . __( 'Note: Any fields in the first group will appear on the signup page.', 'buddypress' );
			break;

		default:
			$retval = false;
			break;
	}

	// Wrap text in a paragraph tag
	if ( !empty( $retval ) ) {
		$retval = '
' . $retval . '
';
	}

	return $retval;
}

/** Separator *****************************************************************/

/**
 * Add a separator to the WordPress admin menus.
 *
 * @since 1.7.0
 *
 * @uses bp_current_user_can() To check users capability on root blog.
 */
function bp_admin_separator() {

	// Bail if BuddyPress is not network activated and viewing network admin
	if ( is_network_admin() && ! bp_is_network_activated() ) {
		return;
	}

	// Bail if BuddyPress is network activated and viewing site admin
	if ( ! is_network_admin() && bp_is_network_activated() ) {
		return;
	}

	// Prevent duplicate separators when no core menu items exist
	if ( ! bp_current_user_can( 'bp_moderate' ) ) {
		return;
	}

	// Bail if there are no components with admin UI's. Hardcoded for now, until
	// there's a real API for determining this later.
	if ( ! bp_is_active( 'activity' ) && ! bp_is_active( 'groups' ) ) {
		return;
	}

	global $menu;

	$menu[] = array( '', 'read', 'separator-buddypress', '', 'wp-menu-separator buddypress' );
}

/**
 * Tell WordPress we have a custom menu order.
 *
 * @since 1.7.0
 * @uses bp_current_user_can() To check users capability on root blog.
 *
 * @param bool $menu_order Menu order.
 *
 * @return bool Always true
 */
function bp_admin_custom_menu_order( $menu_order = false ) {

	// Bail if user cannot see admin pages
	if ( ! bp_current_user_can( 'bp_moderate' ) ) {
		return $menu_order;
	}

	return true;
}

/**
 * Move our custom separator above our custom post types.
 *
 * @since 1.7.0
 * @uses bp_current_user_can() To check users capability on root blog.
 *
 * @param array $menu_order Menu Order.
 *
 * @return array Modified menu order
 */
function bp_admin_menu_order( $menu_order = array() ) {

	// Bail if user cannot see admin pages
	if ( empty( $menu_order ) || ! bp_current_user_can( 'bp_moderate' ) ) {
		return $menu_order;
	}

	// Initialize our custom order array
	$bp_menu_order = array();

	// Menu values
	$last_sep     = is_network_admin() ? 'separator1' : 'separator2';

	/**
	 * Filters the custom admin menus.
	 *
	 * @since 1.7.0
	 *
	 * @param array $value Empty array.
	 */
	$custom_menus = (array) apply_filters( 'bp_admin_menu_order', array() );

	// Bail if no components have top level admin pages
	if ( empty( $custom_menus ) ) {
		return $menu_order;
	}

	// Add our separator to beginning of array
	array_unshift( $custom_menus, 'separator-buddypress' );

	// Loop through menu order and do some rearranging
	foreach ( (array) $menu_order as $item ) {

		// Position BuddyPress menus above appearance
		if ( $last_sep == $item ) {

			// Add our custom menus
			foreach( (array) $custom_menus as $custom_menu ) {
				if ( array_search( $custom_menu, $menu_order ) ) {
					$bp_menu_order[] = $custom_menu;
				}
			}

			// Add the appearance separator
			$bp_menu_order[] = $last_sep;

		// Skip our menu items
		} elseif ( ! in_array( $item, $custom_menus ) ) {
			$bp_menu_order[] = $item;
		}
	}

	// Return our custom order
	return $bp_menu_order;
}

/** Utility  *****************************************************************/

/**
 * When using a WP_List_Table, get the currently selected bulk action.
 *
 * WP_List_Tables have bulk actions at the top and at the bottom of the tables,
 * and the inputs have different keys in the $_REQUEST array. This function
 * reconciles the two values and returns a single action being performed.
 *
 * @since 1.7.0
 *
 * @return string
 */
function bp_admin_list_table_current_bulk_action() {

	$action = ! empty( $_REQUEST['action'] ) ? $_REQUEST['action'] : '';

	// If the bottom is set, let it override the action
	if ( ! empty( $_REQUEST['action2'] ) && $_REQUEST['action2'] != "-1" ) {
		$action = $_REQUEST['action2'];
	}

	return $action;
}

/** Menus *********************************************************************/

/**
 * Register meta box and associated JS for BuddyPress WP Nav Menu.
 *
 * @since 1.9.0
 */
function bp_admin_wp_nav_menu_meta_box() {
	if ( ! bp_is_root_blog() ) {
		return;
	}

	add_meta_box( 'add-buddypress-nav-menu', __( 'BuddyPress', 'buddypress' ), 'bp_admin_do_wp_nav_menu_meta_box', 'nav-menus', 'side', 'default' );

	add_action( 'admin_print_footer_scripts', 'bp_admin_wp_nav_menu_restrict_items' );
}

/**
 * Build and populate the BuddyPress accordion on Appearance > Menus.
 *
 * @since 1.9.0
 *
 * @global $nav_menu_selected_id
 */
function bp_admin_do_wp_nav_menu_meta_box() {
	global $nav_menu_selected_id;

	$walker = new BP_Walker_Nav_Menu_Checklist( false );
	$args   = array( 'walker' => $walker );

	$post_type_name = 'buddypress';

	$tabs = array();

	$tabs['loggedin']['label']  = __( 'Logged-In', 'buddypress' );
	$tabs['loggedin']['pages']  = bp_nav_menu_get_loggedin_pages();

	$tabs['loggedout']['label'] = __( 'Logged-Out', 'buddypress' );
	$tabs['loggedout']['pages'] = bp_nav_menu_get_loggedout_pages();

	?>

<?php _e( 'Logged-In', 'buddypress' ) ?>

<?php _e( 'Logged-In links are relative to the current user, and are not visible to visitors who are not logged in.', 'buddypress' ) ?>

		<div id="tabs-panel-posttype-<?php echo $post_type_name; ?>-loggedin" class="tabs-panel tabs-panel-active">

				<?php echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $tabs['loggedin']['pages'] ), 0, (object) $args );?>

<?php _e( 'Logged-Out', 'buddypress' ) ?>

<?php _e( 'Logged-Out links are not visible to users who are logged in.', 'buddypress' ) ?>

		<div id="tabs-panel-posttype-<?php echo $post_type_name; ?>-loggedout" class="tabs-panel tabs-panel-active">

				<?php echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $tabs['loggedout']['pages'] ), 0, (object) $args );?>

				<input type="submit"<?php if ( function_exists( 'wp_nav_menu_disabled_check' ) ) : wp_nav_menu_disabled_check( $nav_menu_selected_id ); endif; ?> class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu', 'buddypress' ); ?>" name="add-custom-menu-item" id="submit-buddypress-menu" />

	<?php
}

/**
 * Restrict various items from view if editing a BuddyPress menu.
 *
 * If a person is editing a BP menu item, that person should not be able to
 * see or edit the following fields:
 *
 * - CSS Classes - We use the 'bp-menu' CSS class to determine if the
 *   menu item belongs to BP, so we cannot allow manipulation of this field to
 *   occur.
 * - URL - This field is automatically generated by BP on output, so this
 *   field is useless and can cause confusion.
 *
 * Note: These restrictions are only enforced if JavaScript is enabled.
 *
 * @since 1.9.0
 */
function bp_admin_wp_nav_menu_restrict_items() {
?>

<?php
}

/**
 * Add "Mark as Spam/Ham" button to user row actions.
 *
 * @since 2.0.0
 *
 * @param array  $actions     User row action links.
 * @param object $user_object Current user information.
 *
 * @return array $actions User row action links.
 */
function bp_core_admin_user_row_actions( $actions, $user_object ) {

	// Setup the $user_id variable from the current user object
	$user_id = 0;
	if ( !empty( $user_object->ID ) ) {
		$user_id = absint( $user_object->ID );
	}

	// Bail early if user cannot perform this action, or is looking at themselves
	if ( current_user_can( 'edit_user', $user_id ) && ( bp_loggedin_user_id() !== $user_id ) ) {

		// Admin URL could be single site or network
		$url = bp_get_admin_url( 'users.php' );

		// If spammed, create unspam link
		if ( bp_is_user_spammer( $user_id ) ) {
			$url             = add_query_arg( array( 'action' => 'ham', 'user' => $user_id ), $url );
			$unspam_link     = wp_nonce_url( $url, 'bp-spam-user' );
			$actions['ham']  = sprintf( '%2$s', esc_url( $unspam_link ), esc_html__( 'Not Spam', 'buddypress' ) );

		// If not already spammed, create spam link
		} else {
			$url             = add_query_arg( array( 'action' => 'spam', 'user' => $user_id ), $url );
			$spam_link       = wp_nonce_url( $url, 'bp-spam-user' );
			$actions['spam'] = sprintf( '%2$s', esc_url( $spam_link ), esc_html__( 'Spam', 'buddypress' ) );
		}
	}

	// Create a "View" link
	$url             = bp_core_get_user_domain( $user_id );
	$actions['view'] = sprintf( '%2$s', esc_url( $url ), esc_html__( 'View', 'buddypress' ) );

	// Return new actions
	return $actions;
}

/**
 * Catch requests to mark individual users as spam/ham from users.php.
 *
 * @since 2.0.0
 */
function bp_core_admin_user_manage_spammers() {

	// Print our inline scripts on non-Multisite
	add_action( 'admin_footer', 'bp_core_admin_user_spammed_js' );

	$action  = isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : false;
	$updated = isset( $_REQUEST['updated'] ) ? $_REQUEST['updated'] : false;
	$mode    = isset( $_POST['mode'] ) ? $_POST['mode'] : false;

	// if this is a multisite, bulk request, stop now!
	if ( 'list' == $mode ) {
		return;
	}

	// Process a spam/ham request
	if ( ! empty( $action ) && in_array( $action, array( 'spam', 'ham' ) ) ) {

		check_admin_referer( 'bp-spam-user' );

		$user_id = ! empty( $_REQUEST['user'] ) ? intval( $_REQUEST['user'] ) : false;

		if ( empty( $user_id ) ) {
			return;
		}

		$redirect = wp_get_referer();

		$status = ( $action == 'spam' ) ? 'spam' : 'ham';

		// Process the user
		bp_core_process_spammer_status( $user_id, $status );

		$redirect = add_query_arg( array( 'updated' => 'marked-' . $status ), $redirect );

		wp_redirect( $redirect );
	}

	// Display feedback
	if ( ! empty( $updated ) && in_array( $updated, array( 'marked-spam', 'marked-ham' ) ) ) {

		if ( 'marked-spam' === $updated ) {
			$notice = __( 'User marked as spammer. Spam users are visible only to site admins.', 'buddypress' );
		} else {
			$notice = __( 'User removed from spam.', 'buddypress' );
		}

		bp_core_add_admin_notice( $notice );
	}
}

/**
 * Inline script that adds the 'site-spammed' class to spammed users.
 *
 * @since 2.0.0
 */
function bp_core_admin_user_spammed_js() {
	?>

	<?php
}


text:
#include "example.hpp"

void Player::Attack(Creature &creature)
{
    creature.Damage(m_attack_damage * .7);
}

void Player::SpellHit(Creature &creature)
{
    creature.Damage(m_ability_power * 1.2);
}


text:
START_ATF_NAMESPACE
    typedef const char **PZPCSTR;
END_ATF_NAMESPACE


text:
[![License](https://img.shields.io/badge/License-APACHE2-brightgreen.svg)](https://github.com/centreon/centreon-plugins/blob/master/LICENSE.txt)
[![GitHub stars](https://img.shields.io/github/stars/centreon/centreon-plugins.svg)](https://github.com/centreon/centreon-plugins/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/centreon/centreon-plugins.svg)](https://github.com/centreon/centreon-plugins/network)

"centreon-plugins" is a free and open source project to monitor systems. The project can be used with Centreon and all monitoring softwares compatible with Nagios plugins.

You can monitor many systems:
* application: Apache, Asterisk, Elasticsearch, Github, Jenkins, Kafka, Nginx, Pfsense, Redis, Tomcat, Varnish,...
* cloud: AWS, Azure, Docker, Office365, Nutanix, Prometheus,...
* database: Firebird, Informix, MS SQL, MySQL, Oracle, Postgres, Cassandra
* hardware: printers (rfc3805), UPS (Powerware, Mge, Standard), Sun Hardware, Cisco UCS, SensorIP, HP Proliant, HP Bladechassis, Dell Openmanage, Dell CMC, Raritan,...
* network: Aruba, Brocade, Bluecoat, Brocade, Checkpoint, Cisco AP/IronPort/ASA/Standard, Extreme, Fortigate, H3C, Hirschmann, HP Procurve, F5 BIG-IP, Juniper, PaloAlto, Redback, Riverbed, Ruggedcom, Stonesoft,...
* os: Linux (SNMP, NRPE), Freebsd (SNMP), AIX (SNMP), Solaris (SNMP)...
* storage: EMC Clariion, Netapp, Nimble, HP MSA p2000, Dell EqualLogic, Qnap, Panzura, Synology...

## Basic Usage

We'll use a basic example to show you how to monitor a system. I have finished the install section and i want to monitor a Linux in SNMP.
First, i need to find the plugin to use in the list:

    $ perl centreon_plugins.pl --list-plugin | grep -i linux | grep 'PLUGIN'
    PLUGIN: os::linux::local::plugin
    PLUGIN: os::linux::snmp::plugin

It seems that 'os::linux::snmp::plugin' is the good one. So i verify with the option ``--help`` to be sure:

    $ perl centreon_plugins.pl --plugin=os::linux::snmp::plugin --help
    ...
    Plugin Description:
      Check Linux operating systems in SNMP.

It's exactly what i need. Now i'll add the option ``--list-mode`` to know what can i do with it:

    $ perl centreon_plugins.pl --plugin=os::linux::snmp::plugin --list-mode
    ...
    Modes Available:
     processcount
     time
     list-storages
     disk-usage
     diskio
     uptime
     swap
     cpu-detailed
     load
     traffic
     cpu
     inodes
     list-diskspath
     list-interfaces
     packet-errors
     memory
     tcpcon
     storage

I would like to test the 'load' mode:

    $ perl centreon_plugins.pl --plugin=os::linux::snmp::plugin --mode=load
    UNKNOWN: Missing parameter --hostname.

It's not working because some options are missing. I can have a description of the mode and options with the option ``--help``:

    $ perl centreon_plugins.pl --plugin=os::linux::snmp::plugin --mode=load --help

Eventually, i have to configure some SNMP options:

    $ perl centreon_plugins.pl --plugin=os::linux::snmp::plugin --mode=load --hostname=127.0.0.1 --snmp-version=2c --snmp-community=public
    OK: Load average: 0.00, 0.00, 0.00 | 'load1'=0.00;;;0; 'load5'=0.00;;;0; 'load15'=0.00;;;0;

I can set threshold with options ``--warning`` and ``--critical``:

    $ perl centreon_plugins.pl --plugin=os::linux::snmp::plugin --mode=load --hostname=127.0.0.1 --snmp-version=2c --snmp-community=public --warning=1,2,3 --critical=2,3,4
    OK: Load average: 0.00, 0.00, 0.00 | 'load1'=0.00;0:1;0:2;0; 'load5'=0.00;0:2;0:3;0; 'load15'=0.00;0:3;0:4;0;

For more information or help, please read 'docs/user/guide.rst' or go to http://documentation.centreon.com/docs/centreon-plugins/en/latest/


text:
using System;
using System.ComponentModel;
using System.Globalization;

namespace Sigma
{
    /// <summary>
    /// The unit type; a type with no value and no alternative possible states.
    /// </summary>
    [TypeConverter(typeof(UnitTypeConverter))]
    public class Unit
    {
        public static readonly Unit Value = new Unit();
        public override string ToString() { return Conversion.ValueToString(this); }
        private Unit() { }
    }

    /// <summary>
    /// A type converter for the Unit type.
    /// </summary>
    public class UnitTypeConverter : TypeConverter
    {
        public UnitTypeConverter(Type pointType)
        {
            this.pointType = pointType;
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return
                sourceType == pointType ||
                sourceType == typeof(string);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var sourceType = value.GetType();
            if (sourceType == pointType) return value;
            if (sourceType == typeof(string))
            {
                var valueStr = (string)value;
                if (valueStr.Trim() == nameof(Unit)) return Unit.Value;
                throw new ArgumentException($"Conversion source string '{valueStr}' should be '{nameof(Unit)}'.");
            }
            throw new ArgumentException($"Cannot convert from '{value.GetType().FullName}' type to Unit.");
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return
                destinationType == pointType ||
                destinationType == typeof(string);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == pointType) return value;
            if (destinationType == typeof(string)) return nameof(Unit);
            throw new ArgumentException($"Cannot convert Unit to type '{destinationType.FullName}'.");
        }

        private readonly Type pointType;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>SerializerException xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

View Javadoc

1
16  package org.yaml.snakeyaml.serializer;
17
18  import org.yaml.snakeyaml.error.YAMLException;
19
20  public class SerializerException extends YAMLException {
21      private static final long serialVersionUID = 2632638197498912433L;
22
23      public SerializerException(String message) {
24          super(message);
25      }
26  }

This page was automatically generated by Maven


text:
import os
import csv
import pickle
import operator
from math import log
from mystructs import Rel, RelProb, WordProb

#### path prefix
path_prefix = "/Users/liangchen/Documents/Projects/NLI/data/essays/dev"

#### paths
in_path = path_prefix + "/parsed"

train_label_path = "/Users/liangchen/Documents/Projects/NLI/data/labels/train/labels.train.csv"
eval_label_path = "/Users/liangchen/Documents/Projects/NLI/data/labels/dev/labels.dev.csv"

eval_output_path = "/Users/liangchen/Documents/Projects/NLI/output/logistic_prob_full.txt"

#### global variables
labels = []
file_label_dict = {}
file_log_prob = {}

####
def pause():
    raw_input("")

####
def read_labels():
    with open(train_label_path, "rb") as csvfile:
        reader = csv.reader(csvfile)
        next(reader, None)
        for row in reader:
            if row[-1] not in labels:
                labels.append(row[-1])

    with open(eval_label_path, "rb") as csvfile:
        reader = csv.reader(csvfile)
        next(reader, None)
        for row in reader:
            file_label_dict[row[0]] = row[-1]

####
def extract_single_sent_prob(line_index, file_index):
    label = file_label_dict[file_index]
    label_index = int(labels.index(label))
    log_prob = [0] * len(labels)
    global file_log_prob
    with open(eval_output_path, "r") as output_file:
        for i, line in enumerate(output_file):
            if i == line_index:
                data = line.strip().split()
                data = [log(float(x)) for x in data[1:]]
                log_prob = map(operator.add, log_prob, data)
        if file_index in file_log_prob:
            file_log_prob[file_index] = map(operator.add, file_log_prob[file_index], log_prob)
        else:
            file_log_prob[file_index] = log_prob

#### program entry point
if __name__ == "__main__":
    read_labels()
    line_index = 1
    for subdir, dirs, files in os.walk(in_path):
        for filename in files:
            in_filename = os.path.join(subdir, filename)
            print("Processing {} ...".format(in_filename))
            log_prob = extract_single_sent_prob(line_index, filename[:5])
            line_index = line_index + 1

    #### generate confusion matrix
    test_dict = {}
    for label in labels:
        test_dict[label] = {}
        for label_var in labels:
            test_dict[label][label_var] = 0

    correct_count = 0
    for file_index in file_log_prob:
        predicts = file_log_prob[file_index]
        true_label = file_label_dict[file_index]
        true_label_index = int(labels.index(true_label))
        predict_label_index = predicts.index(max(predicts))
        predict_label = labels[predict_label_index]

        test_dict[true_label][predict_label] = test_dict[true_label][predict_label] + 1

        if predict_label == true_label:
            correct_count = correct_count + 1
        else:
            print true_label
            print predicts

    for label in test_dict:
        confusion_row = label + "\t"
        for label_var in test_dict[label]:
            confusion_row = confusion_row + str(test_dict[label][label_var]) + "\t"
        print confusion_row
        print

    print correct_count, len(file_label_dict.keys())


text:
require 'aws-sdk'
require 'awspec/helper/finder/vpc'
require 'awspec/helper/finder/ec2'
require 'awspec/helper/finder/security_group'
require 'awspec/helper/finder/rds'
require 'awspec/helper/finder/route53'
require 'awspec/helper/finder/s3'
require 'awspec/helper/finder/auto_scaling'
require 'awspec/helper/finder/ebs'
require 'awspec/helper/finder/elb'
require 'awspec/helper/finder/lambda'
require 'awspec/helper/finder/iam'
require 'awspec/helper/finder/elasticache'
require 'awspec/helper/finder/cloudwatch'
require 'awspec/helper/finder/ses'

module Awspec::Helper
  module Finder
    attr_reader :ec2_client
    include Awspec::Helper::Finder::Vpc
    include Awspec::Helper::Finder::Ec2
    include Awspec::Helper::Finder::SecurityGroup
    include Awspec::Helper::Finder::Rds
    include Awspec::Helper::Finder::Route53
    include Awspec::Helper::Finder::S3
    include Awspec::Helper::Finder::AutoScaling
    include Awspec::Helper::Finder::Ebs
    include Awspec::Helper::Finder::Elb
    include Awspec::Helper::Finder::Lambda
    include Awspec::Helper::Finder::Iam
    include Awspec::Helper::Finder::Elasticache
    include Awspec::Helper::Finder::Cloudwatch
    include Awspec::Helper::Finder::Ses

    # rubocop:disable all
    def initialize(id = nil)
      @ec2_client = Aws::EC2::Client.new
      @rds_client = Aws::RDS::Client.new
      @route53_client = Aws::Route53::Client.new
      @s3_client = Aws::S3::Client.new
      @auto_scaling_client = Aws::AutoScaling::Client.new
      @elb_client = Aws::ElasticLoadBalancing::Client.new
      @lambda_client = Aws::Lambda::Client.new
      @iam_client = Aws::IAM::Client.new
      @elasticache_client = Aws::ElastiCache::Client.new
      @cloudwatch_client = Aws::CloudWatch::Client.new
      @ses_client = Aws::SES::Client.new
    end
  end
end


text:
require 'whatlanguage'

class EnhancerWorker
  include Sidekiq::Worker

  def perform(key)
    petition = JSON.parse(REDIS.get(key))
    Rails.logger.info "Enhancing record #{key}. Payload: #{petition.inspect}"

    title_and_body = "#{petition['attributes']['title']}  #{petition['attributes']['body']}"

    petition_language = title_and_body.language.to_s
    if petition_language.downcase == 'english'
      open_calais_result = OpenCalaisHelper.enhance title_and_body
      semantria_result = SemantriaHelper.enhance_document({:id => key, :text => title_and_body})

      petition['semantria'] = semantria_result
      petition['open_calais'] = open_calais_result
    else
      error_message = "Couldn't analyze petition #{key} because it's not in English. Petition language was found to be #{petition_language}"
      petition['analysis_error'] = error_message
      Rails.logger.warn error_message
    end

    petition['analysis_complete'] = true
    REDIS.set(key, petition.to_json)
  end
end


text:
@implementation RKLIBRMProject

- (instancetype)projectWithName:(NSString *)name
                 withIdentifier:(NSString *)identifier
                withDescription:(NSString *)description {
	//required
	NSParameterAssert(name);
	NSParameterAssert(identifier);

	RKLIBRMProject *project = [RKLIBRMProject new];
	if (project) {
		project.name = name;
		project.identifier = identifier;
		project.descriptionString = description;
	}
	return project;
}

@end