text:
<?php

class Object_Class_Data_Localizedfields extends Object_Class_Data
{

    /**
     * Static type of this element
     *
     * @var string
     */
    public $fieldtype = "localizedfields";

    /**
     * Type for the generated phpdoc
     *
     * @var string
     */
    public $phpdocType = "array";

    /**
     * @var array
     */
    public $childs = array();

    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $region;

    /**
     * @var string
     */
    public $layout;

    /**
     * @var string
     */
    public $title;

    /**
     * @var integer
     */
    public $width;

    /**
     * @var integer
     */
    public $height;

    /**
     * @var integer
     */
    public $maxTabs;

    /**
     * contains further localized field definitions if there are more than one localized fields in on class
     * @var array
     */
    protected $referencedFields = array();

    /**
     * @var array
     */
    private $fieldDefinitionsCache;

    /**
     * @see Object_Class_Data::getDataForEditmode
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataForEditmode($data, $object = null)
    {
        $fieldData = array();
        $metaData = array();

        if (!$data instanceof Object_Localizedfield) {
            return array();
        }

        $result = $this->doGetDataForEditMode($data, $object, $fieldData, $metaData, 1);

        return $result;
    }

    private function doGetDataForEditMode($data, $object, &$fieldData, &$metaData, $level = 1) {
        $class = $object->getClass();
        $inheritanceAllowed = $class->getAllowInherit();
        $inherited = false;

        foreach ($data->getItems() as $language => $values) {
            foreach ($this->getFieldDefinitions() as $fd) {
                $key = $fd->getName();
                $fdata = $fd->getDataForEditmode($values[$fd->getName()], $object);

                if (!isset($fieldData[$language][$key]) || $fd->isEmpty($fieldData[$language][$key])) {
                    // never override existing data
                    $fieldData[$language][$key] = $fdata;
                    if (!$fd->isEmpty($fdata)) {
                        $metaData[$language][$key] = array("inherited" => $level > 1, "objectid" => $object->getId());
                    }
                }
            }
        }

        if ($inheritanceAllowed) {
            // check if there is a parent with the same type
            $parent = Object_Service::hasInheritableParentObject($object);
            if ($parent) {
                // same type, iterate over all language and all fields and check if there is something missing
                $validLanguages = Pimcore_Tool::getValidLanguages();
                $foundEmptyValue = false;

                foreach ($validLanguages as $language) {
                    $fieldDefinitions = $this->getFieldDefinitions();
                    foreach ($fieldDefinitions as $fd) {
                        $key = $fd->getName();
                        if ($fd->isEmpty($fieldData[$language][$key])) {
                            $foundEmptyValue = true;
                            $inherited = true;
                            $metaData[$language][$key] = array("inherited" => true, "objectid" => $parent->getId());
                        }
                    }
                }

                if ($foundEmptyValue) {
                    // still some values are passing, ask the parent
                    $parentData = $parent->getLocalizedFields();
                    $parentResult = $this->doGetDataForEditMode($parentData, $parent, $fieldData, $metaData, $level + 1);
                    Logger::debug("merge results");
                }
            }
        }

        $result = array(
            "data" => $fieldData,
            "metaData" => $metaData,
            "inherited" => $inherited
        );

        return $result;
    }

    /**
     * @see Object_Class_Data::getDataFromEditmode
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataFromEditmode($data, $object = null)
    {
        $localizedFields = $this->getDataFromObjectParam($object);

        if(!$localizedFields instanceof Object_Localizedfield) {
            $localizedFields = new Object_Localizedfield();
        }

        if (is_array($data)) {
            foreach ($data as $language => $fields) {
                foreach ($fields as $name => $fdata) {
                    $localizedFields->setLocalizedValue($name, $this->getFielddefinition($name)->getDataFromEditmode($fdata), $language);
                }
            }
        }

        return $localizedFields;
    }

    public function getDataForGrid($data, $object = null) {
        $result = new stdClass();
        foreach ($this->getFieldDefinitions() as $fd) {
            $key = $fd->getName();
            $result->$key = $object->{"get".ucfirst($fd->getName())}();
            if(method_exists($fd, "getDataForGrid")) {
                $result->$key = $fd->getDataForGrid($result->$key);
            }
        }
        return $result;
    }

    /**
     * @see Object_Class_Data::getVersionPreview
     * @param string $data
     * @return string
     */
    public function getVersionPreview($data)
    {
        // this is handled directly in the template
        // /pimcore/modules/admin/views/scripts/object/preview-version.php
        return "LOCALIZED FIELDS";
    }

    /**
     * @param Object_Abstract $object
     * @return string
     */
    public function getForCsvExport($object)
    {
        return "NOT SUPPORTED";
    }

    /**
     * @param string $importValue
     * @return null
     */
    public function getFromCsvImport($importValue)
    {
        return;
    }

    /**
     * @param Object_Abstract $object
     * @return mixed
     */
    public function getForWebserviceExport($object)
    {

        $data = $object->{$this->getName()};
        $wsData = array();

        $items = null;

        if (!$data instanceof Object_Localizedfield) {
            $items = array();
        } else {
            $items = $data->getItems();
        }

        if(Zend_Registry::isRegistered("Zend_Locale")) {
            $localeBak = Zend_Registry::get("Zend_Locale");
        } else {
            $localeBak = null;
        }

        $user = Pimcore_Tool_Admin::getCurrentUser();

        $languagesAllowed = null;
        if ($user && !$user->isAdmin()) {
            $languagesAllowed = Object_Service::getLanguagePermissions($object, $user, "lView");

            if ($languagesAllowed) {
                $languagesAllowed = array_keys($languagesAllowed);
            }
        }

        $validLanguages = Pimcore_Tool::getValidLanguages();

        if ($validLanguages) {

            foreach ($validLanguages as $language) {

                foreach ($this->getFieldDefinitions() as $fd) {
                    Zend_Registry::set("Zend_Locale", new Zend_Locale($language));

                    if ($languagesAllowed && !in_array($language, $languagesAllowed)) {
                        continue;
                    }

                    $el = new Webservice_Data_Object_Element();
                    $el->name = $fd->getName();
                    $el->type = $fd->getFieldType();
                    $el->value = $fd->getForWebserviceExport($object);
                    if ($el->value ==  null && self::$dropNullValues) {
                        continue;
                    }
                    $el->language = $language;
                    $wsData[] = $el;
                }
            }
        }
        if ($localeBak) {
            Zend_Registry::set("Zend_Locale", $localeBak);
        }

        return $wsData;
    }

    /**
     * @param mixed $value
     * @return mixed
     */
    public function getFromWebserviceImport($value, $object = null, $idMapper = null)
    {
        if (is_array($value)) {

            $validLanguages = Pimcore_Tool::getValidLanguages();

            if (!$idMapper || !$idMapper->ignoreMappingFailures()) {
                foreach($value as $v){
                    if (!in_array($v->language, $validLanguages)) {
                        throw new Exception("Invalid language in localized fields");
                    }
                }
            }

            $localizedFields = $object->getLocalizedFields();
            if (!$localizedFields) {
                $localizedFields = new Object_Localizedfield();
            }

            if($object instanceof Object_Concrete) {
                $localizedFields->setObject($object);
            }

            $user = Pimcore_Tool_Admin::getCurrentUser();

            $languagesAllowed = null;
            if ($user && !$user->isAdmin()) {
                $languagesAllowed = Object_Service::getLanguagePermissions($object, $user, "lEdit");

                if ($languagesAllowed) {
                    $languagesAllowed = array_keys($languagesAllowed);
                }
            }

            foreach ($value as $field) {
                if ($field instanceof stdClass) {
                    $field = Pimcore_Tool_Cast::castToClass("Webservice_Data_Object_Element", $field);
                }

                if ($idMapper && $idMapper->ignoreMappingFailures()){
                    if (!in_array($field->language, $validLanguages)) {
                        continue;
                    }
                }

                if ($languagesAllowed && !in_array($field->language, $languagesAllowed)) {
                    //TODO needs to be discussed. Maybe it is better to throw an exception instead of ignoring
                    //the language
                    continue;
                }

                if(!$field instanceof Webservice_Data_Object_Element){
                    throw new Exception("Invalid import data in field [ $field->name ] for language [ $field->language ] in localized fields [ ".$this->getName()." ]");
                }
                $fd = $this->getFielddefinition($field->name);
                if (!$fd instanceof Object_Class_Data) {
                    if ($idMapper && $idMapper->ignoreMappingFailures()){
                        continue;
                    }
                    throw new Exception("Unknown field [ $field->name ] for language [ $field->language ] in localized fields [ ".$this->getName()." ] ");
                } else if ($fd->getFieldtype() != $field->type){
                    throw new Exception("Type mismatch for field [ $field->name ] for language [ $field->language ] in localized fields [ ".$this->getName()." ]. Should be [ ".$fd->getFieldtype()." ], but is [ ".$field->type." ] ");
                }

                $localizedFields->setLocalizedValue($field->name, $this->getFielddefinition($field->name)->getFromWebserviceImport($field->value, $object, $idMapper), $field->language);
            }

            return $localizedFields;
        } else if (!empty($value)) {
            throw new Exception("Invalid data in localized fields");
        } else return null;
    }

    /**
     * @return array
     */
    public function getChilds()
    {
        return $this->childs;
    }

    /**
     * @param array $childs
     * @return void
     */
    public function setChilds($childs)
    {
        $this->childs = $childs;
        return $this;
    }

    /**
     * @return boolean
     */
    public function hasChilds()
    {
        if (is_array($this->childs) && count($this->childs) > 0) {
            return true;
        }
        return false;
    }

    /**
     * @param mixed $child
     * @return void
     */
    public function addChild($child)
    {
        $this->childs[] = $child;
    }

    /**
     * @param array $referencedFields
     */
    public function setReferencedFields($referencedFields)
    {
        $this->referencedFields = $referencedFields;
    }

    /**
     * @return array
     */
    public function getReferencedFields()
    {
        return $this->referencedFields;
    }

    /**
     * @param $field
     */
    public function addReferencedField($field) {
        $this->referencedFields[] = $field;
    }

    /**
     * @param mixed $data
     * @param array $blockedKeys
     * @return void
     */
    public function setValues($data = array(), $blockedKeys = array())
    {
        foreach ($data as $key => $value) {
            if (!in_array($key, $blockedKeys)) {
                $method = "set" . $key;
                if (method_exists($this, $method)) {
                    $this->$method($value);
                }
            }
        }
        return $this;
    }

    public function save($object, $params = array())
    {
        $localizedFields = $this->getDataFromObjectParam($object);
        if ($localizedFields instanceof Object_Localizedfield) {
            $localizedFields->setObject($object);
            $localizedFields->save();
        }
    }

    public function load($object, $params = array())
    {
        $localizedFields = new Object_Localizedfield();
        $localizedFields->setObject($object);
        $localizedFields->load();

        return $localizedFields;
    }

    public function delete($object)
    {
        $localizedFields = $this->getDataFromObjectParam($object);

        if ($localizedFields instanceof Object_Localizedfield) {
            $localizedFields->setObject($object);
            $localizedFields->delete();
        }
    }

    /**
     * This method is called in Object_Class::save() and is used to create the database table for the localized data
     * @return void
     */
    public function classSaved($class)
    {
        $localizedFields = new Object_Localizedfield();
        $localizedFields->setClass($class);
        $localizedFields->createUpdateTable();
    }

    public function preGetData($object, $params = array())
    {
        if(!$object instanceof Object_Concrete) {
            throw new \Exception("Localized Fields are only valid in Objects");
        }

        if (!$object->localizedfields instanceof Object_Localizedfield) {
            $lf = new Object_Localizedfield();
            $lf->setObject($object);

            $object->localizedfields = $lf;
        }
        return $object->localizedfields;
    }

    public function getGetterCode($class)
    {

        $code = "";
        $code .= parent::getGetterCode($class);

        foreach ($this->getFieldDefinitions() as $fd) {

            /**
             * @var $fd Object_Class_Data
             */
            $code .= $fd->getGetterCodeLocalizedfields($class);

        }

        return $code;
    }

    public function getSetterCode($class)
    {

        $code = "";
        $code .= parent::getSetterCode($class);

        foreach ($this->getFieldDefinitions() as $fd) {

            /**
             * @var $fd Object_Class_Data
             */
            $code .= $fd->getSetterCodeLocalizedfields($class);
        }

        return $code;
    }

    public function getFielddefinition($name)
    {
        $fds = $this->getFieldDefinitions();
        if ($fds[$name]) {
            return $fds[$name];
        }
        return;
    }

    public function getFieldDefinitions()
    {
        if(empty($this->fieldDefinitionsCache)) {
            $definitions = $this->doGetFieldDefinitions();
            foreach($this->getReferencedFields() as $rf) {
                if($rf instanceof Object_Class_Data_Localizedfields) {
                    $definitions = array_merge($definitions, $this->doGetFieldDefinitions($rf->getChilds()));
                }
            }

            $this->fieldDefinitionsCache = $definitions;
        }

        return $this->fieldDefinitionsCache;
    }

    public function doGetFieldDefinitions($def = null, $fields = array())
    {

        if ($def === null) {
            $def = $this->getChilds();
        }

        if (is_array($def)) {
            foreach ($def as $child) {
                $fields = array_merge($fields, $this->doGetFieldDefinitions($child, $fields));
            }
        }

        if ($def instanceof Object_Class_Layout) {
            if ($def->hasChilds()) {
                foreach ($def->getChilds() as $child) {
                    $fields = array_merge($fields, $this->doGetFieldDefinitions($child, $fields));
                }
            }
        }

        if ($def instanceof Object_Class_Data) {
            $fields[$def->getName()] = $def;
        }

        return $fields;
    }

    /**
     * @param mixed $data
     * @param Object_Concrete $ownerObject
     * @param array $blockedTags
     */
    public function getCacheTags($data, $ownerObject, $tags = array())
    {
        $tags = is_array($tags) ? $tags : array();

        if (!$data instanceof Object_Localizedfield) {
            return $tags;
        }

        foreach ($data->getItems() as $language => $values) {
            foreach ($this->getFieldDefinitions() as $fd) {
                $tags = $fd->getCacheTags($values[$fd->getName()], $ownerObject, $tags);
            }
        }

        return $tags;
    }

    /**
     * @param mixed $data
     */
    public function resolveDependencies($data)
    {
        $dependencies = array();

        if (!$data instanceof Object_Localizedfield) {
            return array();
        }

        foreach ($data->getItems() as $language => $values) {
            foreach ($this->getFieldDefinitions() as $fd) {
                $dependencies = array_merge($dependencies, $fd->resolveDependencies($values[$fd->getName()]));
            }
        }

        return $dependencies;
    }

    public function setHeight($height)
    {
        $this->height = $this->getAsIntegerCast($height);
        return $this;
    }

    public function getHeight()
    {
        return $this->height;
    }

    public function setLayout($layout)
    {
        $this->layout = $layout;
        return $this;
    }

    public function getLayout()
    {
        return $this->layout;
    }

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setRegion($region)
    {
        $this->region = $region;
        return $this;
    }

    public function getRegion()
    {
        return $this->region;
    }

    public function setTitle($title)
    {
        $this->title = $title;
        return $this;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setWidth($width)
    {
        $this->width = $this->getAsIntegerCast($width);
        return $this;
    }

    public function getWidth()
    {
        return $this->width;
    }

    /**
     * Checks if data is valid for current data field
     *
     * @param mixed $data
     * @param boolean $omitMandatoryCheck
     * @throws Exception
     */
    public function checkValidity($data, $omitMandatoryCheck = false){

        $data = $data->getItems();
        $conf = Pimcore_Config::getSystemConfig();
        if($conf->general->validLanguages) {
            $languages = explode(",",$conf->general->validLanguages);
        }

        if(!$omitMandatoryCheck){
            foreach ($languages as $language) {
                foreach ($this->getFieldDefinitions() as $fd) {
                    $fd->checkValidity($data[$language][$fd->getName()]);
                }
            }
        }
    }

    /** See parent class.
     * @param mixed $data
     * @param null $object
     * @return array|null
     */
    public function getDiffDataForEditmode($data, $object = null)
    {
        $return = array();

        $myname = $this->getName();

        if (!$data instanceof Object_Localizedfield) {
            return array();
        }

        foreach ($data->getItems() as $language => $values) {
            foreach ($this->getFieldDefinitions() as $fd) {
                $fieldname = $fd->getName();

                $subdata = $fd->getDiffDataForEditmode($values[$fieldname], $object);

                foreach ($subdata as $item) {
                    $diffdata["field"] = $this->getName();
                    $diffdata["key"] = $this->getName() . "~" . $fieldname . "~" . $item["key"] . "~". $language;

                    $diffdata["type"] = $item["type"];
                    $diffdata["value"] = $item["value"];

                    // this is not needed anymoe
                    unset($item["type"]);
                    unset($item["value"]);

                    $diffdata["title"] = $this->getName() . " / " . $item["title"];
                    $diffdata["lang"] = $language;
                    $diffdata["data"] = $item;
                    $diffdata["extData"] = array(
                        "fieldname" => $fieldname
                    );

                    $diffdata["disabled"] = $item["disabled"];
                    $return[] = $diffdata;
                }
            }
        }

        return $return;
    }

    /** See parent class.
     * @param $data
     * @param null $object
     * @return null|Pimcore_Date
     */

    public function getDiffDataFromEditmode($data, $object = null)
    {
        $localFields = $this->getDataFromObjectParam($object);
        $localData = array();

        // get existing data
        if($localFields instanceof Object_Localizedfield) {
            $localData = $localFields->getItems();
        }

        $mapping = array();
        foreach ($data as $item) {
            $extData = $item["extData"];
            $fieldname = $extData["fieldname"];
            $language = $item["lang"];
            $values = $mapping[$fieldname];

            $itemdata = $item["data"];

            if ($itemdata) {
                if (!$values) {
                    $values = array();
                }

                $values[] = $itemdata;
            }

            $mapping[$language][$fieldname] = $values;
        }

        foreach ($mapping as $language => $fields) {

            foreach ($fields as $key => $value) {

                $fd = $this->getFielddefinition($key);
                if ($fd & $fd->isDiffChangeAllowed()) {

                    if ($value == null) {
                        unset($localData[$language][$key]);
                    } else {
                        $localData[$language][$key] = $fd->getDiffDataFromEditmode($value);
                    }
                }
            }
        }

        $localizedFields = new Object_Localizedfield($localData);
        return $localizedFields;
    }

    /** True if change is allowed in edit mode.
     * @return bool
     */
    public function isDiffChangeAllowed() {
        return true;
    }

    public function __sleep() {
        $vars = get_object_vars($this);
        unset($vars['fieldDefinitionsCache']);
        return array_keys($vars);
    }

    /**
     * Rewrites id from source to target, $idMapping contains
     * array(
     *  "document" => array(
     *      SOURCE_ID => TARGET_ID,
     *      SOURCE_ID => TARGET_ID
     *  ),
     *  "object" => array(...),
     *  "asset" => array(...)
     * )
     * @param mixed $object
     * @param array $idMapping
     * @param array $params
     * @return Element_Interface
     */
    public function rewriteIds($object, $idMapping, $params = array()) {
        $data = $this->getDataFromObjectParam($object, $params);

        $validLanguages = Pimcore_Tool::getValidLanguages();

        foreach ($validLanguages as $language) {
            foreach ($this->getFieldDefinitions() as $fd) {
                if(method_exists($fd, "rewriteIds")) {
                    $d = $fd->rewriteIds($data, $idMapping, array("language" => $language));
                    $data->setLocalizedValue($fd->getName(), $d, $language);
                }
            }
        }

        return $data;
    }

    /**
     * @param int $maxTabs
     */
    public function setMaxTabs($maxTabs)
    {
        $this->maxTabs = $maxTabs;
    }

    /**
     * @return int
     */
    public function getMaxTabs()
    {
        return $this->maxTabs;
    }
}


text:
'use strict';

// Helpers.
const { createTestBuilder } = require('../../../../../test/helpers/builder');
const { createStrapiInstance } = require('../../../../../test/helpers/strapi');
const { createAuthRequest } = require('../../../../../test/helpers/request');

const builder = createTestBuilder();
let strapi;
let rq;
let uid = 'api::single-type-model.single-type-model';

const ct = {
  kind: 'singleType',
  displayName: 'single-type-model',
  singularName: 'single-type-model',
  pluralName: 'single-type-models',
  attributes: {
    title: {
      type: 'string',
    },
  },
};

describe('Content Manager single types', () => {
  beforeAll(async () => {
    await builder.addContentType(ct).build();

    strapi = await createStrapiInstance();
    rq = await createAuthRequest({ strapi });
  });

  afterAll(async () => {
    await strapi.destroy();
    await builder.cleanup();
  });

  test('find single type content returns 404 when not created', async () => {
    const res = await rq({
      url: `/content-manager/single-types/${uid}`,
      method: 'GET',
    });

    expect(res.statusCode).toBe(404);
  });

  test('Create content', async () => {
    const res = await rq({
      url: `/content-manager/single-types/${uid}`,
      method: 'PUT',
      body: {
        title: 'Title',
      },
    });

    expect(res.statusCode).toBe(200);
    expect(res.body).toMatchObject({
      id: expect.anything(),
      title: 'Title',
    });
  });

  test('find single type content returns an object ', async () => {
    const res = await rq({
      url: `/content-manager/single-types/${uid}`,
      method: 'GET',
    });

    expect(res.statusCode).toBe(200);
    expect(res.body).toMatchObject({
      id: expect.anything(),
      title: 'Title',
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
package freemarker.log;

/**
 * Don't use this class; it's only public to work around Google App Engine Java
 * compliance issues. FreeMarker developers only: treat this class as package-visible.
 */
public class _SLF4JLoggerFactory extends SLF4JLoggerFactory {

}


text:
from twisted.internet import defer
from synapse.api.constants import EventTypes
from synapse.api.errors import AuthError

from synapse.util.logutils import log_function
from synapse.util.async import run_on_reactor, ObservableDeferred
from synapse.types import StreamToken
import synapse.metrics

import logging

logger = logging.getLogger(__name__)

metrics = synapse.metrics.get_metrics_for(__name__)

notified_events_counter = metrics.register_counter("notified_events")

# TODO(paul): Should be shared somewhere
def count(func, l):
    """Return the number of items in l for which func returns true."""
    n = 0
    for x in l:
        if func(x):
            n += 1
    return n

class _NotificationListener(object):
    """ This represents a single client connection to the events stream.
    The events stream handler will have yielded to the deferred, so to
    notify the handler it is sufficient to resolve the deferred.
    """
    __slots__ = ["deferred"]

    def __init__(self, deferred):
        self.deferred = deferred

class _NotifierUserStream(object):
    """This represents a user connected to the event stream.
    It tracks the most recent stream token for that user.
    At a given point a user may have a number of streams listening for
    events.

    This listener will also keep track of which rooms it is listening in
    so that it can remove itself from the indexes in the Notifier class.
    """

    def __init__(self, user, rooms, current_token, time_now_ms,
                 appservice=None):
        self.user = str(user)
        self.appservice = appservice
        self.rooms = set(rooms)
        self.current_token = current_token
        self.last_notified_ms = time_now_ms

        self.notify_deferred = ObservableDeferred(defer.Deferred())

    def notify(self, stream_key, stream_id, time_now_ms):
        """Notify any listeners for this user of a new event from an
        event source.
        Args:
            stream_key(str): The stream the event came from.
            stream_id(str): The new id for the stream the event came from.
            time_now_ms(int): The current time in milliseconds.
        """
        self.current_token = self.current_token.copy_and_advance(
            stream_key, stream_id
        )
        self.last_notified_ms = time_now_ms
        noify_deferred = self.notify_deferred
        self.notify_deferred = ObservableDeferred(defer.Deferred())
        noify_deferred.callback(self.current_token)

    def remove(self, notifier):
        """ Remove this listener from all the indexes in the Notifier
        it knows about.
        """

        for room in self.rooms:
            lst = notifier.room_to_user_streams.get(room, set())
            lst.discard(self)

        notifier.user_to_user_stream.pop(self.user)

        if self.appservice:
            notifier.appservice_to_user_streams.get(
                self.appservice, set()
            ).discard(self)

    def count_listeners(self):
        return len(self.notify_deferred.observers())

    def new_listener(self, token):
        """Returns a deferred that is resolved when there is a new token
        greater than the given token.
        """
        if self.current_token.is_after(token):
            return _NotificationListener(defer.succeed(self.current_token))
        else:
            return _NotificationListener(self.notify_deferred.observe())

class Notifier(object):
    """ This class is responsible for notifying any listeners when there are
    new events available for it.

    Primarily used from the /events stream.
    """

    UNUSED_STREAM_EXPIRY_MS = 10 * 60 * 1000

    def __init__(self, hs):
        self.hs = hs

        self.user_to_user_stream = {}
        self.room_to_user_streams = {}
        self.appservice_to_user_streams = {}

        self.event_sources = hs.get_event_sources()
        self.store = hs.get_datastore()
        self.pending_new_room_events = []

        self.clock = hs.get_clock()

        hs.get_distributor().observe(
            "user_joined_room", self._user_joined_room
        )

        self.clock.looping_call(
            self.remove_expired_streams, self.UNUSED_STREAM_EXPIRY_MS
        )

        # This is not a very cheap test to perform, but it's only executed
        # when rendering the metrics page, which is likely once per minute at
        # most when scraping it.
        def count_listeners():
            all_user_streams = set()

            for x in self.room_to_user_streams.values():
                all_user_streams |= x
            for x in self.user_to_user_stream.values():
                all_user_streams.add(x)
            for x in self.appservice_to_user_streams.values():
                all_user_streams |= x

            return sum(stream.count_listeners() for stream in all_user_streams)
        metrics.register_callback("listeners", count_listeners)

        metrics.register_callback(
            "rooms",
            lambda: count(bool, self.room_to_user_streams.values()),
        )
        metrics.register_callback(
            "users",
            lambda: len(self.user_to_user_stream),
        )
        metrics.register_callback(
            "appservices",
            lambda: count(bool, self.appservice_to_user_streams.values()),
        )

    @log_function
    @defer.inlineCallbacks
    def on_new_room_event(self, event, room_stream_id, max_room_stream_id,
                          extra_users=[]):
        """ Used by handlers to inform the notifier something has happened
        in the room, room event wise.

        This triggers the notifier to wake up any listeners that are
        listening to the room, and any listeners for the users in the
        `extra_users` param.

        The events can be peristed out of order. The notifier will wait
        until all previous events have been persisted before notifying
        the client streams.
        """
        yield run_on_reactor()

        self.pending_new_room_events.append((
            room_stream_id, event, extra_users
        ))
        self._notify_pending_new_room_events(max_room_stream_id)

    def _notify_pending_new_room_events(self, max_room_stream_id):
        """Notify for the room events that were queued waiting for a previous
        event to be persisted.
        Args:
            max_room_stream_id(int): The highest stream_id below which all
                events have been persisted.
        """
        pending = self.pending_new_room_events
        self.pending_new_room_events = []
        for room_stream_id, event, extra_users in pending:
            if room_stream_id > max_room_stream_id:
                self.pending_new_room_events.append((
                    room_stream_id, event, extra_users
                ))
            else:
                self._on_new_room_event(event, room_stream_id, extra_users)

    def _on_new_room_event(self, event, room_stream_id, extra_users=[]):
        """Notify any user streams that are interested in this room event"""
        # poke any interested application service.
        self.hs.get_handlers().appservice_handler.notify_interested_services(
            event
        )

        app_streams = set()

        for appservice in self.appservice_to_user_streams:
            # TODO (kegan): Redundant appservice listener checks?
            # App services will already be in the room_to_user_streams set, but
            # that isn't enough. They need to be checked here in order to
            # receive *invites* for users they are interested in. Does this
            # make the room_to_user_streams check somewhat obselete?
            if appservice.is_interested(event):
                app_user_streams = self.appservice_to_user_streams.get(
                    appservice, set()
                )
                app_streams |= app_user_streams

        self.on_new_event(
            "room_key", room_stream_id,
            users=extra_users,
            rooms=[event.room_id],
            extra_streams=app_streams,
        )

    @defer.inlineCallbacks
    @log_function
    def on_new_event(self, stream_key, new_token, users=[], rooms=[],
                     extra_streams=set()):
        """ Used to inform listeners that something has happend event wise.

        Will wake up all listeners for the given users and rooms.
        """
        yield run_on_reactor()
        user_streams = set()

        for user in users:
            user_stream = self.user_to_user_stream.get(str(user))
            if user_stream is not None:
                user_streams.add(user_stream)

        for room in rooms:
            user_streams |= self.room_to_user_streams.get(room, set())

        time_now_ms = self.clock.time_msec()
        for user_stream in user_streams:
            try:
                user_stream.notify(stream_key, new_token, time_now_ms)
            except:
                logger.exception("Failed to notify listener")

    @defer.inlineCallbacks
    def wait_for_events(self, user, timeout, callback, room_ids=None,
                        from_token=StreamToken("s0", "0", "0", "0", "0")):
        """Wait until the callback returns a non empty response or the
        timeout fires.
        """
        user = str(user)
        user_stream = self.user_to_user_stream.get(user)
        if user_stream is None:
            appservice = yield self.store.get_app_service_by_user_id(user)
            current_token = yield self.event_sources.get_current_token()
            if room_ids is None:
                rooms = yield self.store.get_rooms_for_user(user)
                room_ids = [room.room_id for room in rooms]
            user_stream = _NotifierUserStream(
                user=user,
                rooms=room_ids,
                appservice=appservice,
                current_token=current_token,
                time_now_ms=self.clock.time_msec(),
            )
            self._register_with_keys(user_stream)

        result = None
        if timeout:
            # Will be set to a _NotificationListener that we'll be waiting on.
            # Allows us to cancel it.
            listener = None

            def timed_out():
                if listener:
                    listener.deferred.cancel()
            timer = self.clock.call_later(timeout/1000., timed_out)

            prev_token = from_token
            while not result:
                try:
                    current_token = user_stream.current_token

                    result = yield callback(prev_token, current_token)
                    if result:
                        break

                    # Now we wait for the _NotifierUserStream to be told there
                    # is a new token.
                    # We need to supply the token we supplied to callback so
                    # that we don't miss any current_token updates.
                    prev_token = current_token
                    listener = user_stream.new_listener(prev_token)
                    yield listener.deferred
                except defer.CancelledError:
                    break

            self.clock.cancel_call_later(timer, ignore_errs=True)
        else:
            current_token = user_stream.current_token
            result = yield callback(from_token, current_token)

        defer.returnValue(result)

    @defer.inlineCallbacks
    def get_events_for(self, user, pagination_config, timeout,
                       only_room_events=False,
                       is_guest=False, guest_room_id=None):
        """ For the given user and rooms, return any new events for them. If
        there are no new events wait for up to `timeout` milliseconds for any
        new events to happen before returning.

        If `only_room_events` is `True` only room events will be returned.
        """
        from_token = pagination_config.from_token
        if not from_token:
            from_token = yield self.event_sources.get_current_token()

        limit = pagination_config.limit

        room_ids = []
        if is_guest:
            if guest_room_id:
                if not self._is_world_readable(guest_room_id):
                    raise AuthError(403, "Guest access not allowed")
                room_ids = [guest_room_id]
        else:
            rooms = yield self.store.get_rooms_for_user(user.to_string())
            room_ids = [room.room_id for room in rooms]

        @defer.inlineCallbacks
        def check_for_updates(before_token, after_token):
            if not after_token.is_after(before_token):
                defer.returnValue(None)

            events = []
            end_token = from_token

            for name, source in self.event_sources.sources.items():
                keyname = "%s_key" % name
                before_id = getattr(before_token, keyname)
                after_id = getattr(after_token, keyname)
                if before_id == after_id:
                    continue
                if only_room_events and name != "room":
                    continue
                new_events, new_key = yield source.get_new_events(
                    user=user,
                    from_key=getattr(from_token, keyname),
                    limit=limit,
                    is_guest=is_guest,
                    room_ids=room_ids,
                )

                if name == "room":
                    room_member_handler = self.hs.get_handlers().room_member_handler
                    new_events = yield room_member_handler._filter_events_for_client(
                        user.to_string(),
                        new_events,
                        is_guest=is_guest,
                        require_all_visible_for_guests=False
                    )

                events.extend(new_events)
                end_token = end_token.copy_and_replace(keyname, new_key)

            if events:
                defer.returnValue((events, (from_token, end_token)))
            else:
                defer.returnValue(None)

        result = yield self.wait_for_events(
            user, timeout, check_for_updates, room_ids=room_ids, from_token=from_token
        )

        if result is None:
            result = ([], (from_token, from_token))

        defer.returnValue(result)

    @defer.inlineCallbacks
    def _is_world_readable(self, room_id):
        state = yield self.hs.get_state_handler().get_current_state(
            room_id,
            EventTypes.RoomHistoryVisibility
        )
        if state and "history_visibility" in state.content:
            defer.returnValue(state.content["history_visibility"] == "world_readable")
        else:
            defer.returnValue(False)

    @log_function
    def remove_expired_streams(self):
        time_now_ms = self.clock.time_msec()
        expired_streams = []
        expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
        for stream in self.user_to_user_stream.values():
            if stream.count_listeners():
                continue
            if stream.last_notified_ms < expire_before_ts:
                expired_streams.append(stream)

        for expired_stream in expired_streams:
            expired_stream.remove(self)

    @log_function
    def _register_with_keys(self, user_stream):
        self.user_to_user_stream[user_stream.user] = user_stream

        for room in user_stream.rooms:
            s = self.room_to_user_streams.setdefault(room, set())
            s.add(user_stream)

        if user_stream.appservice:
            self.appservice_to_user_stream.setdefault(
                user_stream.appservice, set()
            ).add(user_stream)

    def _user_joined_room(self, user, room_id):
        user = str(user)
        new_user_stream = self.user_to_user_stream.get(user)
        if new_user_stream is not None:
            room_streams = self.room_to_user_streams.setdefault(room_id, set())
            room_streams.add(new_user_stream)
            new_user_stream.rooms.add(room_id)


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>DiscoverHer</title>

	<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
	<link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
	<link rel="stylesheet" type="text/css" href="css/styles.css" />

	                <form class="form-signin" action="#">

	                    <input type="text" class="form-control" placeholder="Email" required autofocus />

	                    <input type="password" class="form-control" placeholder="Password" required />

	                    <input type="checkbox" value="remember-me" />
	                    Keep me signed in

	                <button class="btn btn-lg btn-block purple-bg" type="submit">
	                    Sign in</button>
	                </form>
	                Forget your password?

	                            Create New Account


text:
package msgpack

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func TestBufferedEncoderReset(t *testing.T) {
	encoder := testBufferedEncoder()
	inputs := []interface{}{1, 2.0, "foo", byte(8)}

	// Encode for the first time.
	for _, input := range inputs {
		err := encoder.Encode(input)
		require.NoError(t, err)
	}
	encoded := encoder.Bytes()
	results := make([]byte, len(encoded))
	copy(results, encoded)

	// Reset the encoder.
	encoder.Reset()

	// Encode for the second time.
	for _, input := range inputs {
		err := encoder.Encode(input)
		require.NoError(t, err)
	}
	encoded = encoder.Bytes()
	results2 := make([]byte, len(encoded))
	copy(results2, encoded)

	require.Equal(t, results, results2)
}

func TestBufferedEncoderClose(t *testing.T) {
	encoder := testBufferedEncoder()
	require.False(t, encoder.closed)

	// Close the encoder should set the flag.
	encoder.Close()
	require.True(t, encoder.closed)

	// Close the encoder again should be a no-op.
	encoder.Close()
	require.True(t, encoder.closed)
}

func testBufferedEncoder() *bufferedEncoder {
	return NewBufferedEncoder().(*bufferedEncoder)
}


text:
package com.dci.intellij.dbn.code.common.style.options;

import com.dci.intellij.dbn.common.options.CompositeConfiguration;
import com.dci.intellij.dbn.common.options.Configuration;
import com.dci.intellij.dbn.common.options.ui.CompositeConfigurationEditorForm;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;

public abstract class CodeStyleCustomSettings<T extends CompositeConfigurationEditorForm> extends CompositeConfiguration<T>{
    protected CodeStyleCaseSettings caseSettings;
    protected CodeStyleFormattingSettings formattingSettings;

    protected CodeStyleCustomSettings() {
        caseSettings = createCaseSettings();
        formattingSettings = createAttributeSettings();
    }

    protected abstract CodeStyleCaseSettings createCaseSettings();
    protected abstract CodeStyleFormattingSettings createAttributeSettings();

    public CodeStyleCaseSettings getCaseSettings() {
        return caseSettings;
    }

    public CodeStyleFormattingSettings getFormattingSettings() {
        return formattingSettings;
    }

    /*********************************************************
    *                     Configuration                     *
    *********************************************************/
    protected Configuration[] createConfigurations() {
        return new Configuration[] {
                caseSettings,
                formattingSettings};
    }

    protected abstract String getElementName();

    public void readConfiguration(Element element) throws InvalidDataException {
        Element child = element.getChild(getElementName());
        if (child != null) {
            readConfiguration(child, caseSettings);
            readConfiguration(child, formattingSettings);
        }
    }

    public void writeConfiguration(Element element) throws WriteExternalException {
         Element child = new Element(getElementName());
         element.addContent(child);
         writeConfiguration(child, caseSettings);
         writeConfiguration(child, formattingSettings);
     }

}


text:
package engine

// I really want this to live in /senders but engine doesn't work then.. hrmm

import (
	"github.com/nyaruka/junebug/disp"
	"github.com/nyaruka/junebug/store"
	"log"
	"fmt"
	"sync"
	"time"
	"strconv"
	"errors"
)

// EchoSender is a dummy sender that takes 5 seconds to send anything, then returns an
// echo of the sent message back through our connection.
//
// It is an implementation of MsgSender
//

const PAUSE = "pause"

type EchoSender struct {
	id               int
	connection       store.Connection
	readySenders     chan disp.MsgSender
	pendingMsg       chan uint64
	incoming         chan uint64 // for receiving out our echos
	done             chan int
	wg               *sync.WaitGroup
	pause            uint
}

func (s EchoSender) Send(id uint64) {
	s.pendingMsg <- id
}

// Starts our sender, this starts a goroutine that blocks on receiving a message to send
func (s EchoSender) Start() {
	go func() {
		s.wg.Add(1)
		defer s.wg.Done()
		var id uint64

		for {
			// mark ourselves as ready for work, this never blocks
			s.readySenders <- s

			// wait for a job to come in, or for us to be shut down
			select {
			case id = <-s.pendingMsg:
			case <- s.done:
			  return
			}

			var msgLog = ""

			// load our msg
			msg, err := store.MsgFromId(s.connection.Uuid, id)
			if err != nil {
				msgLog = fmt.Sprintf("[%s][%d] Error sending msg (%d): %s", s.connection.Uuid, s.id, id, err.Error())
			} else {
				// sleep a bit to slow things down
				time.Sleep(time.Second * 5)
				msgLog = fmt.Sprintf("XXXX YYYY ZZZZ AAAA This is a log.\n" +
				                     "XXXX YYYY ZZZZ BBBB It is fake.")
			}

			// mark the message as sent
			err = msg.MarkSent(msgLog)
			if err != nil {
				log.Printf("[%s][%d] Error marking msg sent (%d)", s.connection.Uuid, s.id, id)
			} else {
				log.Printf("[%s][%d] Sent msg (%d)", s.connection.Uuid, s.id, id)
			}

			// release our message back to the pool
			msg.Release()

			// create a new incoming msg
			incoming := store.MsgFromText(s.connection.Uuid, msg.Address, "echo: "+msg.Text)
			err = incoming.WriteToInbox()
			if err != nil {
				log.Printf("[%s][%d] Error adding incoming msg (%d)", s.connection.Uuid, s.id, id)
			}

			// schedule it to go out
			s.incoming <- incoming.Id

			// release our msg back to the pool
			incoming.Release()
		}
	}()
}

func CreateEchoSender(id int, conn *store.Connection, dispatcher *disp.Dispatcher) (e *EchoSender, err error) {
	echo := EchoSender{
		id: id,
		connection:       *conn,
		readySenders:     dispatcher.Senders,
		incoming:         dispatcher.Incoming,
		pendingMsg:       make(chan uint64),
		done:             dispatcher.Done,
		wg:               dispatcher.WaitGroup }

	pause, _ := strconv.ParseInt(conn.Senders.Config[PAUSE], 10, 8)
	if pause < 0 {
		return e, errors.New(fmt.Sprintf("Pause must be 0 or a positive integer, was: %d", pause))
	}
	echo.pause = uint(pause)
	return &echo, err
}


text:
<?php

namespace App\Helpers\Journal;

use App\Article;
use App\Model\RefererMediumLabel;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Remp\Journal\AggregateRequest;
use Remp\Journal\ConcurrentsRequest;
use Remp\Journal\JournalContract;
use Remp\Journal\ListRequest;

class JournalHelpers
{
    const CATEGORY_ACTION_SEPARATOR = '::';

    private $journal;

    private $cachedRefererMediumLabels;

    public function __construct(JournalContract $journal)
    {
        $this->journal = $journal;
    }

    public function currentConcurrentsCount(callable $conditions = null, Carbon $now = null): Collection
    {
        $timeBefore = $now;
        if ($timeBefore === null) {
            $timeBefore = Carbon::now()->microsecond(0);
        }

        $timeAfter = (clone $timeBefore)->subSeconds(600); // Last 10 minutes
        $req = new ConcurrentsRequest();
        $req->setTimeAfter($timeAfter);
        $req->setTimeBefore($timeBefore);

        if ($conditions) {
            $conditions($req);
        }

        return collect($this->journal->concurrents($req));
    }

    /**
     * Get available referer mediums in pageviews segments storage per last $hoursAgo
     * Useful for filtering in data tables
     * @param int $hoursAgo
     *
     * @return Collection
     */
    public function derivedRefererMediumGroups(int $hoursAgo = 12): Collection
    {
        $ar = (new AggregateRequest('pageviews', 'load'))
            ->setTime(Carbon::now()->subHours($hoursAgo), Carbon::now())
            ->addGroup('derived_referer_medium');

        $results = collect($this->journal->count($ar));
        return $results->pluck('tags.derived_referer_medium');
    }

    /**
     * Load unique users count per each article
     *
     * @param Collection $articles
     *
     * @return Collection containing mapping of articles' external_ids to unique users count
     */
    public function uniqueBrowsersCountForArticles(Collection $articles): Collection
    {
        $minimalPublishedTime = Carbon::now();
        foreach ($articles as $article) {
            if ($minimalPublishedTime->gt($article->published_at)) {
                $minimalPublishedTime = $article->published_at;
            }
        }

        // sort article IDs to help journal caching mechanism cache this payload
        $externalArticleIds = $articles->pluck('external_id')->sortDesc(SORT_NUMERIC)->toArray();

        $r = (new AggregateRequest('pageviews', 'load'))
            ->setTime($minimalPublishedTime, Carbon::now())
            ->addGroup('article_id')
            ->addFilter('article_id', ...$externalArticleIds);

        $result = collect($this->journal->unique($r));
        return $result
            ->filter(function ($item) {
                return $item->tags !== null;
            })
            ->mapWithKeys(function ($item) {
                return [$item->tags->article_id => $item->count];
            });
    }

    /**
     * Load timespent count per each article
     *
     * @param Collection $articles
     * @param Carbon     $since
     *
     * @return Collection containing mapping of articles' external_ids to timespent in seconds
     */
    public function timespentForArticles(Collection $articles, Carbon $since): Collection
    {
        $externalArticleIds = $articles->pluck('external_id')->toArray();

        $request = new AggregateRequest('pageviews', 'timespent');
        $request->setTimeAfter($since);
        $request->setTimeBefore(Carbon::now());
        $request->addGroup('article_id');

        $request->addFilter('article_id', ...$externalArticleIds);

        $result = collect($this->journal->avg($request));
        return $result
            ->filter(function ($item) {
                return $item->tags !== null;
            })
            ->mapWithKeys(function ($item) {
                return [$item->tags->article_id => $item->avg];
            });
    }

    /**
     * Load a/b test flags for articles
     *
     * @param Collection $articles
     * @param Carbon     $since
     *
     * @return Collection containing mapping of articles' external_ids to a/b test flags
     */
    public function abTestFlagsForArticles(Collection $articles, Carbon $since): Collection
    {
        $externalArticleIds = $articles->pluck('external_id')->toArray();

        $request = new AggregateRequest('pageviews', 'load');
        $request->setTimeAfter($since);
        $request->setTimeBefore(Carbon::now());
        $request->addGroup('article_id', 'title_variant', 'image_variant');

        $request->addFilter('article_id', ...$externalArticleIds);

        $result = collect($this->journal->count($request));
        $articles = collect();

        foreach ($result as $item) {
            $key = $item->tags->article_id;
            if (!$articles->has($key)) {
                $articles->put($key, (object) [
                    'title_variants' => collect(),
                    'image_variants' => collect()
                ]);
            }
            $articles[$key]->title_variants->push($item->tags->title_variant);
            $articles[$key]->image_variants->push($item->tags->image_variant);
        }

        return $articles->map(function ($item) {
            $hasTitleTest = $item->title_variants->filter(function ($variant) {
                return $variant !== '';
            })->unique()->count() > 1;

            $hasImageTest = $item->image_variants->filter(function ($variant) {
                return $variant !== '';
            })->unique()->count() > 1;

            return (object) [
                'has_title_test' => $hasTitleTest,
                'has_image_test' => $hasImageTest
            ];
        });
    }

    /**
     * Get time iterator, which is the earliest point of time (Carbon instance) that when
     * interval of length $intervalMinutes is added,
     * the resulting Carbon instance is greater or equal to $timeAfter
     *
     * This is useful for preparing data for histogram graphs
     *
     * @param Carbon                $timeAfter
     * @param int                   $intervalMinutes
     * @param \DateTimeZone|string  $tz                 Default value is `UTC`.
     *
     * @return Carbon
     */
    public static function getTimeIterator(Carbon $timeAfter, int $intervalMinutes, $tz = 'UTC'): Carbon
    {
        $timeIterator = (clone $timeAfter)->tz($tz)->startOfDay();
        while ($timeIterator->lessThanOrEqualTo($timeAfter)) {
            $timeIterator->addMinutes($intervalMinutes);
        }
        return $timeIterator->subMinutes($intervalMinutes);
    }

    public function refererMediumLabel(string $medium, bool $cached = true): string
    {
        if (!$cached || !$this->cachedRefererMediumLabels) {
            $this->cachedRefererMediumLabels = RefererMediumLabel::all();
        }

        foreach ($this->cachedRefererMediumLabels as $row) {
            if ($medium === $row->referer_medium) {
                return $row->label;
            }
        }

        // TODO: extract to seeders
        // Built-in labels
        switch ($medium) {
            case 'direct':
                return 'direct/IM';
            default:
                return $medium;
        }
    }

    /**
     * Returns list of all categories and actions for stored events
     * @param Article|null $article if provided, load events data only for particular article
     *
     * @return array array of objects having category and action parameters
     */
    public function eventsCategoriesActions(?Article $article = null): array
    {
        $r = AggregateRequest::from('events')->addGroup('category', 'action');

        if ($article !== null) {
            $r->addFilter('article_id', $article->external_id);
        }

        $results = [];

        foreach ($this->journal->count($r) as $item) {
            if (!empty($item->tags->action) && !empty($item->tags->category)) {
                $results[] = (object) $item->tags;
            }
        }
        return $results;
    }

    /**
     * @param JournalInterval $journalInterval load events only for particular interval
     * @param string[]        $requestedCategoryActionEvents array of strings having format 'category::action'
     * @param Article|null    $article if provided, load only events linked to particular article
     *
     * @return array List of events as provided by Journal API
     */
    public function loadEvents(JournalInterval $journalInterval, array $requestedCategoryActionEvents, ?Article $article = null): array
    {
        if (!$requestedCategoryActionEvents) {
            return [];
        }

        $categories = [];
        $categoryActions = [];
        foreach ($requestedCategoryActionEvents as $item) {
            [$category, $action] = explode(self::CATEGORY_ACTION_SEPARATOR, $item);
            $categories[] = $category;
            if (! array_key_exists($category, $categoryActions)) {
                $categoryActions[$category] = [];
            }
            $categoryActions[$category][] = $action;
        }

        $r = ListRequest::from('events')
            ->setTime($journalInterval->timeAfter, $journalInterval->timeBefore)
            ->addFilter('category', ...$categories);

        if ($article) {
            $r->addFilter('article_id', $article->external_id);
        }

        $response = $this->journal->list($r);

        $events = [];

        foreach ($response[0]->events ?? [] as $event) {
            if (! in_array($event->action, $categoryActions[$event->category], true)) {
                // ATM Journal API doesn't provide way to simultaneously check for category and action on the same record,
                // therefore check first category in the request and check action here
                continue;
            }
            $events[] = $event;
        }
        return $events;
    }
}


text:
import React from 'react'
import { expect } from 'chai'
import { shallow } from 'enzyme'

import Header from './Header'
import styles from './styles.module.css'

describe('<Header />', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<Header />)
  });

  it('contains a title component with yelp', () => {
    expect(wrapper.find('h1').first().text())
        .to.equal('<%= title %>')
  });

  it('contains topbar styling', () => {
    expect(wrapper.find(`.${styles.topbar}`))
      .to.have.length(1);
  })

  it('contains a section menu with the title', () => {
    expect(wrapper.find('section').first().text())
        .to.equal('Fullstack.io')
  });

})


text:
import { MutateOp } from '../enums/mutate-op';

export interface IMutateOptions {
  chance?: number;
  op?: MutateOp;
}


text:
<?php

namespace Nenad\TestBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class NenadTestBundle extends Bundle
{
}


text:
**Passage Examples**
===================
[Slide Deck](https://docs.google.com/presentation/d/1HYfUZLRZRJovQpv5mYxox9bz9erxj7Ak_ZovENMvM90/edit?usp=sharing) & [Video](https://www.youtube.com/watch?v=VINCQghQRuM)

[Passage Gender Classification](https://github.com/IndicoDataSolutions/Passage/blob/master/examples/gender.py) With [Blogger Dataset](http://goo.gl/EbWA1u)

[Passage Newsgroup Classification Example](https://github.com/IndicoDataSolutions/Passage/blob/master/examples/newsgroup.py)


text:
package org.apache.groovy.contracts.ast.visitor;

import org.apache.groovy.contracts.generation.Configurator;
import org.apache.groovy.contracts.util.Validate;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.expr.StaticMethodCallExpression;
import org.objectweb.asm.Opcodes;

import static org.codehaus.groovy.ast.tools.GeneralUtils.args;
import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.constX;

/**
 * Makes some initialization in order to use the {@link Configurator} for determining
 * which assertions in what packages will be executed.
 *
 * @see Configurator
 */
public class ConfigurationSetup {

    /**
     * Adds an instance field which allows to control whether GContract assertions
     * are enabled or not. Before assertions are evaluated this field will be checked.
     *
     * @param type the current {@link ClassNode}
     * @see Configurator
     */
    public void init(final ClassNode type) {
        Validate.notNull(type);
        StaticMethodCallExpression checkAssertionsEnabledMethodCall = callX(ClassHelper.makeWithoutCaching(Configurator.class), "checkAssertionsEnabled", args(constX(type.getName())));
        final FieldNode fieldNode = type.addField(BaseVisitor.GCONTRACTS_ENABLED_VAR, Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_FINAL, ClassHelper.boolean_TYPE, checkAssertionsEnabledMethodCall);
        fieldNode.setSynthetic(true);
    }
}


text:
/* @lazyspec (remove to manage manually) */
/* eslint-disable */
import PersonalStatus from '../PersonalStatus.jsx';

describe('PersonalStatus', () => {
  it('exists', () => {
    expect(PersonalStatus).toBeTruthy();
  });
});


text:
from operator import itemgetter

__author__ = 'Simon Hofmann'

from math import log

class NaiveBayesClassifier:
    __prior = None
    __conditional = None
    __classes = None
    __vocabulary = None
    __total_docs = 0
    __trained = False

    def __init__(self):
        print("Naive Bayes classification")
        self.__prior = {}
        self.__classes = {}
        self.__conditional = {}
        self.__vocabulary = set()

    @property
    def conditionals(self):
        return self.__conditional

    @property
    def classes(self):
        return self.__classes

    @property
    def priors(self):
        return self.__prior

    def train(self, documents, label):
        """
        Trains a decision function for classification.
        """
        assert (len(documents) == len(label))
        # Build vocabulary
        for docs in documents:
            self.__total_docs += len(docs)
            for doc in docs:
                [self.__vocabulary.add(t) for t in doc]

        print('Vocabulary size: ' + str(len(self.__vocabulary)))
        # Used to store no. of appearance
        cnt = {}

        for idx, docClass in enumerate(label):
            self.__classes[docClass] = 0
            self.__prior[docClass] = len(documents[idx]) / self.__total_docs
            self.__conditional[docClass] = {}
            total_text = 0
            cnt[idx] = {}
            # Build tf value for document class idx
            for docs in documents[idx]:
                for t in docs:
                    total_text += 1
                    if t in self.__vocabulary:
                        try:
                            cnt[idx][t] += 1
                        except KeyError:
                            cnt[idx][t] = 1

            # Build feature vector
            for token in self.__vocabulary:
                count = 0
                try:
                    count = cnt[idx][token]
                except KeyError:
                    pass

                self.__conditional[docClass][token] = (count + 1) / (total_text + len(self.__vocabulary))

        self.__trained = True

    def predict(self, documents):
        """
        Classifies a documents using the trained model.
        """
        if not self.__trained:
            print("Classifier not trained yet, classification not possible!")
            return None

        for docClass in self.__classes:
            self.__classes[docClass] = log(self.__prior[docClass])
            for document in documents:
                try:
                    for token in document:
                        self.__classes[docClass] += log(self.__conditional[docClass][token])
                except KeyError:
                    continue

        # print(self.__classes)
        return max(self.__classes, key=lambda i: self.__classes[i])

    def info(self, n):
        """
        Prints an overview of n most important vocabulary words for each class.
        """
        if not self.__trained:
            print('This feature is only available after the classifier has been trained!')
            return

        importance_map = {}

        for doc_class in self.__classes:
            importance_map[doc_class] = sorted(self.__conditional[doc_class].items(), key=itemgetter(1), reverse=True)

        for entry in importance_map.keys():
            print('The %d most important tokens for document class: %s' % (n, entry))
            print('*****')
            for item in importance_map[entry][:n]:
                print('Token: ' + item[0] + '\t\t\t\t| Importance: ' + str(item[1]) + ' %')


text:
package com.intellij.codeInsight.daemon.impl;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.TextRange;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.List;

// IMPL class hardcoding logic to react to errors/warnings found during highlighting
// DO NOT USE directly
public abstract class HighlightInfoProcessor {
  // HInfos for visible part of file/block are produced.
  // Will remove all range-highlighters from there and replace them with passed infos
  public void highlightsInsideVisiblePartAreProduced(@Nonnull HighlightingSession session,
                                                     @Nullable Editor editor,
                                                     @Nonnull List<? extends HighlightInfo> infos,
                                                     @Nonnull TextRange priorityRange,
                                                     @Nonnull TextRange restrictRange, int groupId) {
  }

  public void highlightsOutsideVisiblePartAreProduced(@Nonnull HighlightingSession session,
                                                      @Nullable Editor editor,
                                                      @Nonnull List<? extends HighlightInfo> infos,
                                                      @Nonnull TextRange priorityRange,
                                                      @Nonnull TextRange restrictedRange, int groupId) {
  }

  // new HInfo became available during highlighting.
  // Incrementally add this HInfo in EDT iff there were nothing there before.
  public void infoIsAvailable(@Nonnull HighlightingSession session, @Nonnull HighlightInfo info, @Nonnull TextRange priorityRange, @Nonnull TextRange restrictedRange, int groupId) {
  }

  // this range is over.
  // Can queue to EDT to remove abandoned bijective highlighters from this range. All the rest abandoned highlighters have to wait until *AreProduced().
  public void allHighlightsForRangeAreProduced(@Nonnull HighlightingSession session, @Nonnull TextRange elementRange, @Nullable List<? extends HighlightInfo> infos) {
  }

  public void progressIsAdvanced(@Nonnull HighlightingSession highlightingSession, @Nullable Editor editor, double progress) {
  }

  private static final HighlightInfoProcessor EMPTY = new HighlightInfoProcessor() {
  };

  @Nonnull
  public static HighlightInfoProcessor getEmpty() {
    return EMPTY;
  }
}


text:
author: "Brandon Giesing"
title: "Welcome to the new BrandonGiesing.com!"
draft: false
date: 2016-09-19T10:01:12Z
slug: "welcome-to-the-new-site"
layout: blog
categories:
  - Announcements
tags:
  - Update

---

So if you know me, I have a "habit" of constantly moving my site cause
"reasons". This time, hopefully this will be permanent now that I got great
software and money to keep it alive!

--------------------------------------------------------------------------------

## Great Software: Ghost

In the past I have done many different CMS, Blog, and Static services for my
sites. Wordpress, Blogger, Weebly, Webs, and even Tumblr are some of those many.

Another one I used is Jekyll. I used it more than the others as it's static (aka
fast) and can be freely hosted via GitHub Pages. While this is nice, one big
issue is Mobile publishing. Git on phones is not the easiest to do and managing
the site became an issue but of course, I'm not going back to the other ones as
while they have great mobile tools, many of them are really slow.

Now I'm using [Ghost][ghost] which is different in a few ways!

 1. Node.js (instead of PHP) means it's faster like Static pages but still with
    the interactivity of CMS platforms like Wordpress.
 2. Use Markdown just like most Static sites like Jekyll.
 3. No mobile app but the website is mobile-friendly and it's open source with
    an API so there's awesome 3rd-party clients like Quill.

The major issue with Ghost though has to do with that first point some...

### Let's Talk About The $$$

PHP has lots of hosts that are free. (Yes they maybe really limited but for a
simple personal site with rarely any views, not a big deal) Node.js however
basically has none. Heroku and OpenShift exists but are super complicated to set
up or can't run newer versions easily.

Just under a month ago (August 24th, 2016 to be exact) I started doing some
money sites. Yeah, I know you are going to say "They are scams aren't they?"
(Not all are) or "Those things can't pay out enough for a server". Well you
would be right normally for the second point except 1 key detail... I have no
job.

That means I'm at home 24/7 doing these but what's even better is I'm not really
doing anything! All the ones I use are passive video apps. This means I open it
up, let it run on my old devices, and forget it. (Well mostly, sometimes there's
a broken ad that needs manually closed but otherwise all automatic). On average
for just 1 of the 3 main ones I use (and I do experiment with others), I get on
average $3 a day. Add the other 2 sites and each does about $2 on average. So $7
just for having videos run while I'm doing other things!

How much does hosting Ghost cost? Well for that...

### Ghost Host: [Ghosted][ghosted]

[Ghosted][ghosted] is an interesting host made specifically for Ghost! They cost
$5 a month which is really inexpensive for web hosting at $60 per year.  However
if you buy that full year, it's 20% off at only $50. In not even a full month
with those sites (and the few others outside the main 3), I've redeemed around
$55 and have another $25 I can cash out in a few days on only the one site! I
already spent most of that initial $55 for phone stuff on Amazon but still, I
can get the $50 pretty fast!

[Ghosted][ghosted] manages the server and everything for you so all I have to do
is make the content.

--------------------------------------------------------------------------------

# About The New Site

Now that all that is out of the way... What about my side of it? The content?
Well here's how the site is going to work.

* Occasionally I post long-form content here about things I'm interested in.
  Whether it be about tech products, talking about new food items, or anything
  else, if it needs lots of words, it will most likely be here.
  * I'll share links to them on existing social accounts like my Twitter.
* Want to find info about my projects? I'll have dedicated pages in the Menu.
  Currently I have a "Support Me" page where you can find ways to support me via
  donations or using my referral links.
* More may happen but the main thing is unlike my past personal sites, I will
  not do a scheduled post series! I always forget about them or don't have
  enough things to make one each week! So I may do post series but they won't be
  "Every Sunday" or something, just when I get to them!

--------------------------------------------------------------------------------

The site is currently being actively worked on so please be patient as things
could be wonky, stuff missing/broken, or offline at times! So for the meantime,
you can find the old website [here][old].

Please tell me any feedback by commenting below with Disqus or emailing me at
me@brandongiesing.com! Thanks!

[ghost]: https://ghost.org
[ghosted]: https://ghosted.it
[old]: https://brandongiesing.com