text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * Base module class for text based modules
 */
class BxBaseModTextModule extends BxBaseModGeneralModule implements iBxDolContentInfoService
{
    function __construct(&$aModule)
    {
        parent::__construct($aModule);
    }

    // ====== ACTIONS METHODS
    public function actionEmbedPoll($iPollId = 0)
    {
        if(empty($iPollId) && bx_get('poll_id') !== false)
            $iPollId = (int)bx_get('poll_id');

        $aParams = bx_get_with_prefix('param');
        array_walk($aParams, function(&$sValue) {
            $sValue = bx_process_input($sValue);
        });

        $this->_oTemplate->embedPollItem($iPollId, $aParams);
    }

    public function actionEmbedPolls($iId = 0)
    {
        list($iContentId, $aContentInfo) = $this->_getContent($iId);
        if($iContentId === false)
            return;

        $aParams = bx_get_with_prefix('param');
        array_walk($aParams, function(&$sValue) {
            $sValue = bx_process_input($sValue);
        });

        $this->_oTemplate->embedPollItems($aContentInfo, $aParams);
    }

    public function actionGetPoll()
    {
        $iPollId = (int)bx_get('poll_id');
        $sView = bx_process_input(bx_get('view'));

        $sMethod = 'serviceGetBlockPoll' . bx_gen_method_name($sView);
        if(!method_exists($this, $sMethod))
            return echoJson(array());

        $aBlock = $this->$sMethod($iPollId, true);
        if(empty($aBlock) || !is_array($aBlock))
            return echoJson(array());

        return echoJson(array(
            'content' => $aBlock['content']
        ));
    }
    public function actionDeletePoll()
    {
        $CNF = &$this->_oConfig->CNF;

        $iId = bx_process_input(bx_get('id'), BX_DATA_INT);
        if(empty($iId))
            return echoJson(array());

        $aResult = array();
        if($this->_oDb->deletePolls(array($CNF['FIELD_POLL_ID'] => $iId)))
            $aResult = array('code' => 0);
        else
            $aResult = array('code' => 1, 'message' => _t($CNF['txt_err_cannot_perform_action']));

        echoJson($aResult);
    }

    public function actionGetPollForm()
    {
        echo $this->_oTemplate->getPollForm();
    }

    public function actionSubmitPollForm()
    {
        echoJson($this->getPollForm());
    }

    public function actionFileEmbedVideo($iFileId)
    {
        $this->_oTemplate->embedVideo($iFileId);
    }

    public function actionFileEmbedSound($iFileId)
    {
        $this->_oTemplate->embedSound($iFileId);
    }

    // ====== SERVICE METHODS

    public function serviceGetSafeServices()
    {
        $a = parent::serviceGetSafeServices();
        return array_merge($a, array (
            'GetBlockPollAnswers' => '',
            'GetBlockPollResults' => '',
            'GetMenuAddonManageToolsProfileStats' => '',
            'BrowsePublic' => '',
            'BrowsePopular' => '',
            'BrowseTop' => '',
            'BrowseUpdated' => '',
            'BrowseAuthor' => '',
            'CategoriesMultiList' => ''
        ));
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-polls Polls Blocks
     * @subsubsection bx_base_text-get_block_poll_answers get_block_poll_answers
     *
     * @code bx_srv('bx_posts', 'get_block_poll_answers', [...]); @endcode
     *
     * Get block with poll answers
     * @param $iPollId poll ID
     *
     * @see BxBaseModTextModule::serviceGetBlockPollAnswers
     */
    /**
     * @ref bx_base_text-get_block_poll_answers "get_block_poll_answers"
     */
    public function serviceGetBlockPollAnswers($iPollId, $bForceDisplay = false)
    {
        if(!$iPollId)
            return false;

        if(!$bForceDisplay && $this->isPollPerformed($iPollId))
            return $this->serviceGetBlockPollResults($iPollId);

        return $this->_serviceTemplateFunc('entryPollAnswers', $iPollId, 'getPollInfoById');
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-polls Polls Blocks
     * @subsubsection bx_base_text-get_block_poll_results get_block_poll_results
     *
     * @code bx_srv('bx_posts', 'get_block_poll_results', [...]); @endcode
     *
     * Get block with poll results
     * @param $iPollId poll ID
     *
     * @see BxBaseModTextModule::serviceGetBlockPollResults
     */
    /**
     * @ref bx_base_text-get_block_poll_results "get_block_poll_results"
     */
    public function serviceGetBlockPollResults($iPollId)
    {
        return $this->_serviceTemplateFunc('entryPollResults', $iPollId, 'getPollInfoById');
    }

    /**
     * Display media EXIF information.
     * @param $iMediaId media ID, if it's omitted then it's taken from 'id' GET variable.
     * @return HTML string with EXIF info. On error empty string is returned.
     */
    public function serviceMediaExif ($iMediaId = 0)
    {
        $CNF = &$this->_oConfig->CNF;
        return $this->_serviceTemplateFunc ('mediaExif', $iMediaId, $CNF['FUNCTION_FOR_GET_ITEM_INFO']);
    }

    public function serviceGetThumb ($iContentId, $sTranscoder = '')
    {
        $CNF = &$this->_oConfig->CNF;

        if(empty($sTranscoder) && !empty($CNF['OBJECT_IMAGES_TRANSCODER_GALLERY']))
            $sTranscoder = $CNF['OBJECT_IMAGES_TRANSCODER_GALLERY'];

        $mixedResult = $this->_getFieldValueThumb('FIELD_THUMB', $iContentId, $sTranscoder);
        return $mixedResult !== false ? $mixedResult : '';
    }

    public function serviceGetMenuAddonManageTools()
    {
        bx_import('SearchResult', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SearchResult';
        $o = new $sClass();
        $o->unsetPaginate();
        $iNumTotal = $o->getNum();

        $o->fillFilters(array(
			'status' => 'hidden'
        ));
        $iNum1 = $o->getNum();

        $iNum2 = 0;
        $CNF = &$this->_oConfig->CNF;
        if (isset($CNF['OBJECT_REPORTS'])){
            $o->fillFilters(array('status' => ''));
            $o->fillFiltersByObjects(array('reported' => array('value' => '0', 'field' => 'reports', 'operator' => '>')));
            $iNum2 = $o->getNum();
        }
        return array('counter1_value' => $iNum1, 'counter2_value' => $iNum2, 'counter3_value' => $iNumTotal );
	}

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-other Other
     * @subsubsection bx_base_text-get_menu_addon_manage_tools_profile_stats get_menu_addon_manage_tools_profile_stats
     *
     * @code bx_srv('bx_posts', 'get_menu_addon_manage_tools_profile_stats', []); @endcode
     *
     * Get number of posts for currently logged in user
     *
     * @see BxBaseModTextModule::serviceGetMenuAddonManageToolsProfileStats
     */
    /**
     * @ref bx_base_text-get_menu_addon_manage_tools_profile_stats "get_menu_addon_manage_tools_profile_stats"
     */
	public function serviceGetMenuAddonManageToolsProfileStats()
	{
		bx_import('SearchResult', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SearchResult';
        $o = new $sClass();
        $o->fillFilters(array(
			'author' => bx_get_logged_profile_id()
        ));
        $o->unsetPaginate();

        return $o->getNum();
	}

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-browse Browse
     * @subsubsection bx_base_text-browse_public browse_public
     *
     * @code bx_srv('bx_posts', 'browse_public', [...]); @endcode
     *
     * Display public posts
     * @param $sUnitView unit view, such as: full, extended, gallery, showcase
     * @param $bEmptyMessage display or not "empty" message when there is no content
     * @param $bAjaxPaginate use AJAX paginate or not
     *
     * @see BxBaseModTextModule::serviceBrowsePublic
     */
    /**
     * @ref bx_base_text-browse_public "browse_public"
     */
    public function serviceBrowsePublic ($sUnitView = false, $bEmptyMessage = true, $bAjaxPaginate = true)
    {
        return $this->_serviceBrowse ('public', $sUnitView ? array('unit_view' => $sUnitView) : false, BX_DB_PADDING_DEF, $bEmptyMessage, $bAjaxPaginate);
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-browse Browse
     * @subsubsection bx_base_text-browse_popular browse_popular
     *
     * @code bx_srv('bx_posts', 'browse_popular', [...]); @endcode
     *
     * Display popular posts
     * @param $sUnitView unit view, such as: full, extended, gallery, showcase
     * @param $bEmptyMessage display or not "empty" message when there is no content
     * @param $bAjaxPaginate use AJAX paginate or not
     *
     * @see BxBaseModTextModule::serviceBrowsePopular
     */
    /**
     * @ref bx_base_text-browse_popular "browse_popular"
     */
    public function serviceBrowsePopular ($sUnitView = false, $bEmptyMessage = true, $bAjaxPaginate = true)
    {
        return $this->_serviceBrowse ('popular', $sUnitView ? array('unit_view' => $sUnitView) : false, BX_DB_PADDING_DEF, $bEmptyMessage, $bAjaxPaginate);
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-browse Browse
     * @subsubsection bx_base_text-browse_top browse_top
     *
     * @code bx_srv('bx_posts', 'browse_top', [...]); @endcode
     *
     * Display top posts
     * @param $sUnitView unit view, such as: full, extended, gallery, showcase
     * @param $bEmptyMessage display or not "empty" message when there is no content
     * @param $bAjaxPaginate use AJAX paginate or not
     *
     * @see BxBaseModTextModule::serviceBrowseTop
     */
    /**
     * @ref bx_base_text-browse_top "browse_top"
     */
    public function serviceBrowseTop ($sUnitView = false, $bEmptyMessage = true, $bAjaxPaginate = true)
    {
        return $this->_serviceBrowse ('top', $sUnitView ? array('unit_view' => $sUnitView) : false, BX_DB_PADDING_DEF, $bEmptyMessage, $bAjaxPaginate);
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-browse Browse
     * @subsubsection bx_base_text-browse_updated browse_updated
     *
     * @code bx_srv('bx_posts', 'browse_updated', [...]); @endcode
     *
     * Display recently updated posts
     * @param $sUnitView unit view, such as: full, extended, gallery, showcase
     * @param $bEmptyMessage display or not "empty" message when there is no content
     * @param $bAjaxPaginate use AJAX paginate or not
     *
     * @see BxBaseModTextModule::serviceBrowseUpdated
     */
    /**
     * @ref bx_base_text-browse_updated "browse_updated"
     */
    public function serviceBrowseUpdated ($sUnitView = false, $bEmptyMessage = true, $bAjaxPaginate = true)
    {
        return $this->_serviceBrowse ('updated', $sUnitView ? array('unit_view' => $sUnitView) : false, BX_DB_PADDING_DEF, $bEmptyMessage, $bAjaxPaginate);
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-browse Browse
     * @subsubsection bx_base_text-browse_author browse_author
     *
     * @code bx_srv('bx_posts', 'browse_author', [...]); @endcode
     *
     * Display posts of specified author
     * @param $iProfileId profile ID
     * @param $aParams additional params, see BxBaseModGeneralModule::serviceBrowse
     *
     * @see BxBaseModTextModule::serviceBrowseAuthor
     */
    /**
     * @ref bx_base_text-browse_author "browse_author"
     */
    public function serviceBrowseAuthor ($iProfileId = 0, $aParams = array())
    {
        return $this->_serviceBrowseWithParam ('author', 'profile_id', $iProfileId, $aParams);
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-page_blocks Page Blocks
     * @subsubsection bx_base_text-entity_author entity_author
     *
     * @code bx_srv('bx_posts', 'entity_author', [...]); @endcode
     *
     * Display author block for the specified post
     * @param $iContentId content ID
     *
     * @see BxBaseModTextModule::serviceEntityAuthor
     */
    /**
     * @ref bx_base_text-entity_author "entity_author"
     */
    public function serviceEntityAuthor ($iContentId = 0)
    {
        return $this->_serviceTemplateFunc ('entryAuthor', $iContentId);
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-page_blocks Page Blocks
     * @subsubsection bx_base_text-entity_polls entity_polls
     *
     * @code bx_srv('bx_posts', 'entity_polls', [...]); @endcode
     *
     * Display polls for the specified post
     * @param $iContentId content ID
     *
     * @see BxBaseModTextModule::serviceEntityPolls
     */
    /**
     * @ref bx_base_text-entity_polls "entity_polls"
     */
    public function serviceEntityPolls ($iContentId = 0)
    {
        return $this->_serviceTemplateFunc ('entryPolls', $iContentId);
    }

    /**
     * @page service Service Calls
     * @section bx_base_text Base Text
     * @subsection bx_base_text-page_blocks Page Blocks
     * @subsubsection bx_base_text-entity_breadcrumb entity_breadcrumb
     *
     * @code bx_srv('bx_forum', 'entity_breadcrumb', [...]); @endcode
     *
     * Display breadcrumb for the specified post
     * @param $iContentId content ID
     *
     * @see BxBaseModTextModule::serviceEntityBreadcrumb
     */
    /**
     * @ref bx_base_text-entity_breadcrumb "entity_breadcrumb"
     */
    public function serviceEntityBreadcrumb ($iContentId = 0)
    {
        return $this->_serviceTemplateFunc ('entryBreadcrumb', $iContentId);
    }

    /**
     * Delete all content by profile
     * @param $iProfileId profile id
     * @return number of deleted items
     */
    public function serviceDeleteEntitiesByAuthor ($iProfileId)
    {
        $a = $this->_oDb->getEntriesByAuthor((int)$iProfileId);
        if (!$a)
            return 0;

        $iCount = 0;
        foreach ($a as $aContentInfo)
            $iCount += ('' == $this->serviceDeleteEntity($aContentInfo[$this->_oConfig->CNF['FIELD_ID']]) ? 1 : 0);

        return $iCount;
    }

    // ====== PERMISSION METHODS

    /**
     * @return CHECK_ACTION_RESULT_ALLOWED if access is granted or error message if access is forbidden. So make sure to make strict(===) checking.
     */
    public function checkAllowedSetThumb ($iContentId = 0)
    {
        // check ACL
        $aCheck = checkActionModule($this->_iProfileId, 'set thumb', $this->getName(), false);
        if ($aCheck[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED)
            return $aCheck[CHECK_ACTION_MESSAGE];
        return CHECK_ACTION_RESULT_ALLOWED;
    }

    public function isPollPerformed($iObjectId, $iAuthorId = 0, $iAuthorIp = 0)
    {
        if(empty($iAuthorId)) {
            $iAuthorId = bx_get_logged_profile_id();
            $iAuthorIp = ip2long(getVisitorIP());
        }

        return $this->_oDb->isPollPerformed($iObjectId, $iAuthorId, $iAuthorIp);
    }

    // ====== COMMON METHODS
    public function alertAfterAdd($aContentInfo)
    {
        $CNF = &$this->_oConfig->CNF;

        $iId = (int)$aContentInfo[$CNF['FIELD_ID']];
        $iAuthorId = (int)$aContentInfo[$CNF['FIELD_AUTHOR']];

        $sAction = 'added';
        if(isset($CNF['FIELD_STATUS']) && isset($aContentInfo[$CNF['FIELD_STATUS']]) && $aContentInfo[$CNF['FIELD_STATUS']] == 'awaiting')
            $sAction = 'deferred';

        $aParams = $this->_alertParams($aContentInfo);
        bx_alert('system', 'prepare_alert_params', 0, 0, array('unit'=> $this->getName(), 'action' => $sAction, 'object_id' => $iId, 'sender_id' => $iAuthorId, 'extras' => &$aParams));
        bx_alert($this->getName(), $sAction, $iId, $iAuthorId, $aParams);
    }

    public function alertAfterEdit($aContentInfo)
    {
        $CNF = &$this->_oConfig->CNF;

        $iId = (int)$aContentInfo[$CNF['FIELD_ID']];

        $aParams = $this->_alertParams($aContentInfo);
        bx_alert($this->getName(), 'edited', $iId, false, $aParams);
    }

    /**
     * Get array of params to be passed in Add/Edit Alert.
     */
    protected function _alertParams($aContentInfo)
    {
        $aParams = parent::_alertParams($aContentInfo);

        $CNF = &$this->_oConfig->CNF;

        if(!empty($CNF['FIELD_ALLOW_VIEW_TO']) && isset($aContentInfo[$CNF['FIELD_ALLOW_VIEW_TO']]))
            $aParams['privacy_view'] = $aContentInfo[$CNF['FIELD_ALLOW_VIEW_TO']];

        if(!empty($CNF['OBJECT_METATAGS']))
            $aParams['timeline_group'] = array(
                'by' => $this->getName() . '_' . (int)$aContentInfo[$CNF['FIELD_AUTHOR']] . '_' . (int)$aContentInfo[$CNF['FIELD_ID']],
                'field' => 'owner_id'
            );

        return $aParams;
    }

    public function isEntryActive($aContentInfo)
    {
        $CNF = &$this->_oConfig->CNF;

        if($aContentInfo[$CNF['FIELD_AUTHOR']] == bx_get_logged_profile_id() || $this->_isModerator())
            return true;

        if(isset($CNF['FIELD_STATUS']) && $aContentInfo[$CNF['FIELD_STATUS']] != 'active')
            return false;

        if(isset($CNF['FIELD_STATUS_ADMIN']) && $aContentInfo[$CNF['FIELD_STATUS_ADMIN']] != 'active')
            return false;

        return true;
    }

    public function getPollForm()
    {
        $CNF = &$this->_oConfig->CNF;

        if(empty($CNF['OBJECT_FORM_POLL']))
            return array('code' => 1, 'message' => '_sys_txt_error_occured');

        $iProfileId = bx_get_logged_profile_id();

        $oForm = BxDolForm::getObjectInstance($CNF['OBJECT_FORM_POLL'], $CNF['OBJECT_FORM_POLL_DISPLAY_ADD'], $this->_oTemplate);
        $oForm->aFormAttrs['action'] = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'submit_poll_form/';

        $oForm->initChecker();
        if($oForm->isSubmittedAndValid()) {
            $iId = $oForm->insert();
            if($iId)
                return array('code' => 0, 'id' => $iId, 'item' => $this->_oTemplate->getPollItem($iId, $iProfileId, array(
                    'manage' => true
                )));
            else
                return array('code' => 2, 'message' => '_sys_txt_error_entry_creation');
        }

        return array('form' => $oForm->getCode(), 'form_id' => $oForm->id);
    }

    public function getEntryImageData($aContentInfo, $sField = 'FIELD_THUMB', $aTranscoders = array())
    {
        $CNF = &$this->_oConfig->CNF;

        $mResult = parent::getEntryImageData($aContentInfo, $sField, $aTranscoders);
        if ($mResult === false &&  isset($CNF['PARAM_USE_GALERY_AS_COVER']) && getParam($CNF['PARAM_USE_GALERY_AS_COVER']) == 'on'){
            if(!empty($CNF['OBJECT_STORAGE_PHOTOS']) && !empty($CNF['OBJECT_IMAGES_TRANSCODER_PREVIEW_PHOTOS'])){
				$sStorage = $CNF['OBJECT_STORAGE_PHOTOS'];
				$oStorage = BxDolStorage::getObjectInstance($sStorage);
				$aGhostFiles = $oStorage->getGhosts ($this->serviceGetContentOwnerProfileId($aContentInfo[$CNF['FIELD_ID']]), $aContentInfo[$CNF['FIELD_ID']]);
				if ($aGhostFiles){
					foreach ($aGhostFiles as $k => $a) {
                        return array('id' => $a['id'], 'transcoder' => $CNF['OBJECT_IMAGES_TRANSCODER_PREVIEW_PHOTOS']);
					}
				}

			}
        }

        return $mResult;
    }

    // ====== PROTECTED METHODS

    protected function _getImagesForTimelinePost($aEvent, $aContentInfo, $sUrl, $aBrowseParams = array())
    {
        $CNF = &$this->_oConfig->CNF;
        $aResults = parent::_getImagesForTimelinePost($aEvent, $aContentInfo, $sUrl, $aBrowseParams);
        if (count($aResults) == 0 && isset($CNF['PARAM_USE_GALERY_AS_COVER']) && getParam($CNF['PARAM_USE_GALERY_AS_COVER']) == 'on'){
            $aResults = $this->_getImagesForTimelinePostAttachInner($aEvent, $aContentInfo, $sUrl, $aBrowseParams);
            if (count($aResults) > 1){
                $aResults = array_slice($aResults, 0, 1);
            }
        }
        return $aResults;
    }

    protected function _getImagesForTimelinePostAttach($aEvent, $aContentInfo, $sUrl, $aBrowseParams = array())
    {
        $CNF = &$this->_oConfig->CNF;
        $aTmp = parent::_getImagesForTimelinePost($aEvent, $aContentInfo, $sUrl, $aBrowseParams);
        $aResults = $this->_getImagesForTimelinePostAttachInner($aEvent, $aContentInfo, $sUrl, $aBrowseParams);
        if (count($aTmp) == 0 && count($aResults) > 0 && isset($CNF['PARAM_USE_GALERY_AS_COVER']) && getParam($CNF['PARAM_USE_GALERY_AS_COVER']) == 'on'){
            $aResults = array_slice($aResults, 1);
        }
        return $aResults;
    }

    protected function _getImagesForTimelinePostAttachInner($aEvent, $aContentInfo, $sUrl, $aBrowseParams = array())
    {
        $CNF = &$this->_oConfig->CNF;

        $aResults = parent::_getImagesForTimelinePostAttach($aEvent, $aContentInfo, $sUrl, $aBrowseParams);
        if(!$this->_oConfig->isAttachmentsInTimeline() || empty($CNF['OBJECT_STORAGE_PHOTOS']) || empty($CNF['OBJECT_IMAGES_TRANSCODER_GALLERY_PHOTOS']))
            return $aResults;

        $iContentId = (int)$aContentInfo[$CNF['FIELD_ID']];
        $oStorage = BxDolStorage::getObjectInstance($CNF['OBJECT_STORAGE_PHOTOS']);

        $aGhostFiles = $oStorage->getGhosts($this->serviceGetContentOwnerProfileId($iContentId), $iContentId);
        if(!$aGhostFiles)
            return array();

        $oTranscoder = BxDolTranscoderImage::getObjectInstance($CNF['OBJECT_IMAGES_TRANSCODER_GALLERY_PHOTOS']);

        foreach ($aGhostFiles as $k => $a) {
            $sPhotoSrc = $oTranscoder->getFileUrl($a['id']);
            if(empty($sPhotoSrc))
                continue;

            $aResults[] = array(
                'id' => $a['id'],
                'src' => $sPhotoSrc,
                'src_medium' => $sPhotoSrc,
                'src_orig' => $oStorage->getFileUrlById($a['id']),
            );
        }
        return $aResults;
    }

    protected function _getVideosForTimelinePostAttach($aEvent, $aContentInfo, $sUrl, $aBrowseParams = array())
    {
        $CNF = &$this->_oConfig->CNF;

        $aResults = parent::_getVideosForTimelinePostAttach($aEvent, $aContentInfo, $sUrl, $aBrowseParams);
        if(!$this->_oConfig->isAttachmentsInTimeline() || empty($CNF['OBJECT_STORAGE_VIDEOS']) || empty($CNF['OBJECT_VIDEOS_TRANSCODERS']))
            return $aResults;

        $iContentId = (int)$aContentInfo[$CNF['FIELD_ID']];
        $oStorage = BxDolStorage::getObjectInstance($CNF['OBJECT_STORAGE_VIDEOS']);

        $aGhostFiles = $oStorage->getGhosts($this->serviceGetContentOwnerProfileId($iContentId), $iContentId);
        if(!$aGhostFiles)
            return array();

        $oTcPoster = BxDolTranscoderVideo::getObjectInstance($CNF['OBJECT_VIDEOS_TRANSCODERS']['poster']);
        $oTcMp4 = BxDolTranscoderVideo::getObjectInstance($CNF['OBJECT_VIDEOS_TRANSCODERS']['mp4']);
        $oTcMp4Hd = BxDolTranscoderVideo::getObjectInstance($CNF['OBJECT_VIDEOS_TRANSCODERS']['mp4_hd']);
        if(!$oTcPoster || !$oTcMp4 || !$oTcMp4Hd)
            return array();

        $aResults = array();
        foreach ($aGhostFiles as $k => $a) {
            $sVideoUrl = $oStorage->getFileUrlById($a['id']);
            $aVideoFile = $oStorage->getFile($a['id']);

            $sVideoUrlHd = '';
            if (!empty($aVideoFile['dimensions']) && $oTcMp4Hd->isProcessHD($aVideoFile['dimensions']))
                $sVideoUrlHd = $oTcMp4Hd->getFileUrl($a['id']);

            $aResults[$a['id']] = array(
                'id' => $a['id'],
                'src_poster' => $oTcPoster->getFileUrl($a['id']),
                'src_mp4' => $oTcMp4->getFileUrl($a['id']),
                'src_mp4_hd' => $sVideoUrlHd,
            );
        }

        return $aResults;
    }

    protected function _getFilesForTimelinePostAttach($aEvent, $aContentInfo, $sUrl, $aBrowseParams = array())
    {
        $CNF = &$this->_oConfig->CNF;

        $aResults = parent::_getFilesForTimelinePostAttach($aEvent, $aContentInfo, $sUrl, $aBrowseParams);
        if(!$this->_oConfig->isAttachmentsInTimeline() || empty($CNF['OBJECT_STORAGE_FILES']))
            return $aResults;

        $iContentId = (int)$aContentInfo[$CNF['FIELD_ID']];
        $oStorage = BxDolStorage::getObjectInstance($CNF['OBJECT_STORAGE_FILES']);

        $aGhostFiles = $oStorage->getGhosts($this->serviceGetContentOwnerProfileId($iContentId), $iContentId);
        if(!$aGhostFiles)
            return array();

        $oTranscoder = null;
        if(!empty($CNF['OBJECT_IMAGES_TRANSCODER_GALLERY_FILES']))
            $oTranscoder = BxDolTranscoderImage::getObjectInstance($CNF['OBJECT_IMAGES_TRANSCODER_GALLERY_FILES']);

        foreach ($aGhostFiles as $k => $a) {
            $bImage = in_array($a['ext'], array('jpg', 'jpeg', 'png', 'gif'));

            $sPhotoSrc = '';
            if($bImage && $oTranscoder)
                $sPhotoSrc = $oTranscoder->getFileUrl($a['id']);

            if(empty($sPhotoSrc) && $oStorage)
                $sPhotoSrc = $this->_oTemplate->getIconUrl($oStorage->getIconNameByFileName($a['file_name']));

            $sUrl = $oStorage->getFileUrlById($a['id']);

            $aResults[] = array(
                'id' => $a['id'],
                'src' => $sPhotoSrc,
                'src_medium' => $sPhotoSrc,
                'src_orig' => $bImage ? $sUrl : '',
                'url' => !$bImage ? $sUrl : ''
            );
        }

        return $aResults;
    }

    protected function _getContentForTimelinePost($aEvent, $aContentInfo, $aBrowseParams = array())
    {
        $aResult = parent::_getContentForTimelinePost($aEvent, $aContentInfo, $aBrowseParams);
        if(!$this->_oConfig->isAttachmentsInTimeline())
            return $aResult;

        $CNF = &$this->_oConfig->CNF;

        $bDynamic = isset($aBrowseParams['dynamic_mode']) && (bool)$aBrowseParams['dynamic_mode'] === true;
		if(!empty($CNF['PARAM_POLL_ENABLED']) && $CNF['PARAM_POLL_ENABLED'] == true)
        	$aPolls = $this->_oDb->getPolls(array('type' => 'content_id', 'content_id' => (int)$aContentInfo[$CNF['FIELD_ID']]));
        if(!empty($aPolls) && is_array($aPolls)) {
            $sInclude = $this->_oTemplate->addCss(array('polls.css'), $bDynamic);

            $aResult['raw'] = ($bDynamic ? $sInclude : '') . $this->_oTemplate->parseHtmlByName('poll_items_embed.html', array(
                'embed_url' => BX_DOL_URL_ROOT . bx_append_url_params($this->_oConfig->getBaseUri() . 'embed_polls/', array(
                    'id' => (int)$aContentInfo[$CNF['FIELD_ID']],
                    'param_switch_menu' => 0,
                    'param_showcase' => 1
                ))
            ));
/*
            if((!empty($aResult['videos']) && is_array($aResult['videos'])) || (!empty($aResult['videos_attach']) && is_array($aResult['videos_attach'])))
                $aResult['_cache'] = false;
 */
        }
        return $aResult;
    }

    protected function _buildRssParams($sMode, $aArgs)
    {
        $aParams = array ();
        $sMode = bx_process_input($sMode);
        switch ($sMode) {
            case 'author':
                $aParams = array('author' => isset($aArgs[0]) ? (int)$aArgs[0] : '');
                break;
        }

        return $aParams;
    }
}

/** @} */


text:
using System;
using System.Collections.Generic;
using Mono.Unix;

using Hyena;

using Banshee.ServiceStack;
using Banshee.Configuration;
using Banshee.Preferences;
using Banshee.Hardware;
using Banshee.Gui;

namespace Banshee.AudioCd
{
    public class AudioCdService : IExtensionService, IDisposable
    {
        private Dictionary<string, AudioCdSource> sources;
        private List<DeviceCommand> unhandled_device_commands;
        private SourcePage pref_page;
        private Section pref_section;
        private uint global_interface_id;

        public AudioCdService ()
        {
        }

        public void Initialize ()
        {
            lock (this) {
                InstallPreferences ();

                sources = new Dictionary<string, AudioCdSource> ();

                foreach (ICdromDevice device in ServiceManager.HardwareManager.GetAllCdromDevices ()) {
                    MapCdromDevice (device);
                }

                ServiceManager.HardwareManager.DeviceAdded += OnHardwareDeviceAdded;
                ServiceManager.HardwareManager.DeviceRemoved += OnHardwareDeviceRemoved;
                ServiceManager.HardwareManager.DeviceCommand += OnDeviceCommand;

                SetupActions ();
            }
        }

        public void Dispose ()
        {
            lock (this) {
                UninstallPreferences ();

                ServiceManager.HardwareManager.DeviceAdded -= OnHardwareDeviceAdded;
                ServiceManager.HardwareManager.DeviceRemoved -= OnHardwareDeviceRemoved;
                ServiceManager.HardwareManager.DeviceCommand -= OnDeviceCommand;

                foreach (AudioCdSource source in sources.Values) {
                    source.Dispose ();
                    ServiceManager.SourceManager.RemoveSource (source);
                }

                sources.Clear ();
                sources = null;

                DisposeActions ();
            }
        }

        private void MapCdromDevice (ICdromDevice device)
        {
            lock (this) {
                foreach (IVolume volume in device) {
                    if (volume is IDiscVolume) {
                        MapDiscVolume ((IDiscVolume)volume);
                    }
                }
            }
        }

        private void MapDiscVolume (IDiscVolume volume)
        {
            lock (this) {
                if (!sources.ContainsKey (volume.Uuid) && volume.HasAudio) {
                    AudioCdSource source = new AudioCdSource (this, new AudioCdDiscModel (volume));
                    sources.Add (volume.Uuid, source);
                    ServiceManager.SourceManager.AddSource (source);

                    // If there are any queued device commands, see if they are to be
                    // handled by this new volume (e.g. --device-activate-play=cdda://sr0/)
                    try {
                        if (unhandled_device_commands != null) {
                            foreach (DeviceCommand command in unhandled_device_commands) {
                                if (DeviceCommandMatchesSource (source, command)) {
                                    HandleDeviceCommand (source, command.Action);
                                    unhandled_device_commands.Remove (command);
                                    if (unhandled_device_commands.Count == 0) {
                                        unhandled_device_commands = null;
                                    }
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        Log.Exception (e);
                    }

                    Log.DebugFormat ("Mapping audio CD ({0})", volume.Uuid);
                }
            }
        }

        internal void UnmapDiscVolume (string uuid)
        {
            lock (this) {
                if (sources.ContainsKey (uuid)) {
                    AudioCdSource source = sources[uuid];
                    source.StopPlayingDisc ();
                    ServiceManager.SourceManager.RemoveSource (source);
                    sources.Remove (uuid);
                    Log.DebugFormat ("Unmapping audio CD ({0})", uuid);
                }
            }
        }

        private void OnHardwareDeviceAdded (object o, DeviceAddedArgs args)
        {
            lock (this) {
                if (args.Device is ICdromDevice) {
                    MapCdromDevice ((ICdromDevice)args.Device);
                } else if (args.Device is IDiscVolume) {
                    MapDiscVolume ((IDiscVolume)args.Device);
                }
            }
        }

        private void OnHardwareDeviceRemoved (object o, DeviceRemovedArgs args)
        {
            lock (this) {
                UnmapDiscVolume (args.DeviceUuid);
            }
        }

#region DeviceCommand Handling

        private bool DeviceCommandMatchesSource (AudioCdSource source, DeviceCommand command)
        {
            if (command.DeviceId.StartsWith ("cdda:")) {
                try {
                    Uri uri = new Uri (command.DeviceId);
                    string match_device_node = String.Format ("{0}{1}", uri.Host,
                        uri.AbsolutePath).TrimEnd ('/', '\\');
                    string device_node = source.DiscModel.Volume.DeviceNode;
                    return device_node.EndsWith (match_device_node);
                } catch {
                }
            }

            return false;
        }

        private void HandleDeviceCommand (AudioCdSource source, DeviceCommandAction action)
        {
            if ((action & DeviceCommandAction.Activate) != 0) {
                ServiceManager.SourceManager.SetActiveSource (source);
            }

            if ((action & DeviceCommandAction.Play) != 0) {
                ServiceManager.PlaybackController.NextSource = source;
                if (!ServiceManager.PlayerEngine.IsPlaying ()) {
                    ServiceManager.PlaybackController.Next ();
                }
            }
        }

        private void OnDeviceCommand (object o, DeviceCommand command)
        {
            lock (this) {
                // Check to see if we have an already mapped disc volume that should
                // handle this incoming command; if not, queue it for later discs
                foreach (AudioCdSource source in sources.Values) {
                    if (DeviceCommandMatchesSource (source, command)) {
                        HandleDeviceCommand (source, command.Action);
                        return;
                    }
                }

                if (unhandled_device_commands == null) {
                    unhandled_device_commands = new List<DeviceCommand> ();
                }
                unhandled_device_commands.Add (command);
            }
        }

#endregion

#region Preferences

        private void InstallPreferences ()
        {
            PreferenceService service = ServiceManager.Get<PreferenceService> ();
            if (service == null) {
                return;
            }

            service.InstallWidgetAdapters += OnPreferencesServiceInstallWidgetAdapters;

            pref_page = new Banshee.Preferences.SourcePage ("audio-cd", Catalog.GetString ("Audio CDs"), "media-cdrom", 400);

            pref_section = pref_page.Add (new Section ("audio-cd", Catalog.GetString ("Audio CD Importing"), 20));
            pref_section.ShowLabel = false;

            pref_section.Add (new VoidPreference ("import-profile",  Catalog.GetString ("_Import format")));
            pref_section.Add (new VoidPreference ("import-profile-desc"));

            pref_section.Add (new SchemaPreference<bool> (AutoRip,
                Catalog.GetString ("_Automatically import audio CDs when inserted"),
                Catalog.GetString ("When an audio CD is inserted, automatically begin importing it " +
                    "if metadata can be found and it is not already in the library.")));

            pref_section.Add (new SchemaPreference<bool> (EjectAfterRipped,
                Catalog.GetString ("_Eject when done importing"),
                Catalog.GetString ("When an audio CD has been imported, automatically eject it.")));

            pref_section.Add (new SchemaPreference<bool> (ErrorCorrection,
                Catalog.GetString ("Use error correction when importing"),
                Catalog.GetString ("Error correction tries to work around problem areas on a disc, such " +
                    "as surface scratches, but will slow down importing substantially.")));
        }

        private void UninstallPreferences ()
        {
            PreferenceService service = ServiceManager.Get<PreferenceService> ();
            if (service == null || pref_page == null) {
                return;
            }

            service.InstallWidgetAdapters -= OnPreferencesServiceInstallWidgetAdapters;

            pref_page.Dispose ();
            pref_page = null;
            pref_section = null;
        }

        private void OnPreferencesServiceInstallWidgetAdapters (object o, EventArgs args)
        {
            if (pref_section == null) {
                return;
            }

            Gtk.HBox description_box = new Gtk.HBox ();
            Banshee.MediaProfiles.Gui.ProfileComboBoxConfigurable chooser
                = new Banshee.MediaProfiles.Gui.ProfileComboBoxConfigurable (ServiceManager.MediaProfileManager,
                    "cd-importing", description_box);

            pref_section["import-profile"].DisplayWidget = chooser;
            pref_section["import-profile"].MnemonicWidget = chooser.Combo;
            pref_section["import-profile-desc"].DisplayWidget = description_box;
        }

        public static readonly SchemaEntry<bool> ErrorCorrection = new SchemaEntry<bool> (
            "import", "audio_cd_error_correction",
            false,
            "Enable error correction",
            "When importing an audio CD, enable error correction (paranoia mode)"
        );

        public static readonly SchemaEntry<bool> AutoRip = new SchemaEntry<bool> (
            "import", "auto_rip_cds",
            false,
            "Enable audio CD auto ripping",
            "When an audio CD is inserted, automatically begin ripping it."
        );

        public static readonly SchemaEntry<bool> EjectAfterRipped = new SchemaEntry<bool> (
            "import", "eject_after_ripped",
            false,
            "Eject audio CD after ripped",
            "After an audio CD has been ripped, automatically eject it."
        );

#endregion

#region UI Actions

        private void SetupActions ()
        {
            InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
            if (uia_service == null) {
                return;
            }

            uia_service.GlobalActions.AddImportant (new Gtk.ActionEntry [] {
                new Gtk.ActionEntry ("RipDiscAction", null,
                    Catalog.GetString ("Import CD"), null,
                    Catalog.GetString ("Import this audio CD to the library"),
                    OnImportDisc)
            });

            uia_service.GlobalActions.AddImportant (
                new Gtk.ActionEntry ("DuplicateDiscAction", null,
                    Catalog.GetString ("Duplicate CD"), null,
                    Catalog.GetString ("Duplicate this audio CD"),
                    OnDuplicateDisc)
            );

            global_interface_id = uia_service.UIManager.AddUiFromResource ("GlobalUI.xml");
        }

        private void DisposeActions ()
        {
            InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
            if (uia_service == null) {
                return;
            }

            uia_service.GlobalActions.Remove ("RipDiscAction");
            uia_service.GlobalActions.Remove ("DuplicateDiscAction");
            uia_service.UIManager.RemoveUi (global_interface_id);
        }

        private void OnImportDisc (object o, EventArgs args)
        {
            ImportOrDuplicateDisc (true);
        }

        private void OnDuplicateDisc (object o, EventArgs args)
        {
            ImportOrDuplicateDisc (false);
        }

        private void ImportOrDuplicateDisc (bool import)
        {
            InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
            if (uia_service == null) {
                return;
            }

            AudioCdSource source = uia_service.SourceActions.ActionSource as AudioCdSource;
            if (source != null) {
                if (import) {
                    source.ImportDisc ();
                } else {
                    source.DuplicateDisc ();
                }
            }
        }

#endregion

        string IService.ServiceName {
            get { return "AudioCdService"; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInita8ba4af287a23e89ab92eedebdb48655::getLoader();


text:
require 'spec_helper'

describe Webex::User::Partner do
  custom_attributes = { webex_id: 'test', password: 'yeh',back_type: 'GoBack', back_url: 'localhost:4567', email: 'bird1204@gmail.com' }

  context '[PARAMS]login' do
    api_type = 'LI'

    it '#api /p.php with ENV set' do
      params = Webex::User::Partner.new.login
      expect(params['AT']).to eq api_type
      expect(params['ST']).to eq 'SUCCESS'
    end
  end

  context '[ERROR]login' do
    api_type = 'LI'

    it '#api /p.php with custom set' do
      params = Webex::User::Partner.new(custom_attributes).login
      expect(params['AT']).to eq api_type
      expect(params['ST']).to eq 'FAIL'
    end
  end

  context '[PARAMS]logout' do
    api_type = 'LO'

    it '#api /p.php with custom set' do
      params = Webex::User::Partner.new(custom_attributes).logout
      expect(params['AT']).to eq api_type
      expect(params['ST']).to eq 'SUCCESS'
    end

    it '#api /p.php with ENV set' do
      params = Webex::User::Partner.new.logout
      expect(params['AT']).to eq api_type
      expect(params['ST']).to eq 'SUCCESS'
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DiscordAstroBot.Objects.Config;

namespace DiscordAstroBot.Mappers.Config
{
    /// <summary>
    /// Mapper for the server commands config
    /// Acts as a proxy class to define default settings
    /// </summary>
    public static class MadUsers
    {
        /// <summary>
        /// Path to the config file
        /// </summary>
        public const string XmlFile = "config/MadUsers.xml";

        /// <summary>
        /// The default per server config
        /// </summary>
        public static List<MadUser> DefaultConfig => new List<MadUser>()
        {

        };

        /// <summary>
        /// The configuration of the commands per server
        /// </summary>
        public static Objects.Config.MadUsers Config { get; set; }

        /// <summary>
        /// Loads the config
        /// </summary>
        public static void LoadConfig()
        {
            Config = XmlSerialization.XmlStateController.LoadObject<Objects.Config.MadUsers>(XmlFile);

            // Default values
            SetDefaultValues(Config);
        }

        /// <summary>
        /// Sets the default values on a given server
        /// </summary>
        /// <param name="serverCfg"></param>
        public static void SetDefaultValues(Objects.Config.MadUsers config)
        {
            foreach (var defaultValue in DefaultConfig)
            {
                if (!config.Users.Any(x => x.Server == defaultValue.Server && x.User == defaultValue.User))
                    config.Users.Add(defaultValue);
            }
        }

        /// <summary>
        /// Saves the config to the xml file
        /// </summary>
        public static void SaveConfig()
        {
            XmlSerialization.XmlStateController.SaveObject(Config, XmlFile);
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_address"
        android:padding="@dimen/activity_vertical_margin" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="@dimen/activity_vertical_margin"
        android:text="@string/getAddress"
        android:textColor="#F1F1e1"
        android:theme="@style/AppTheme.Button"/>

    <com.filippudak.ProgressPieView.ProgressPieView
        android:id="@+id/progressbar"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center"
        android:layout_margin="8dp"
        android:textColor="#FF3300"
        android:textSize="6sp" />

    <!--<ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />-->

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rv" />
</LinearLayout>


text:
<?php
namespace TYPO3\Flow\I18n\Xliff\Exception;

/**
 * An "Invalid XLIFF Data" exception
 *
 * @api
 */
class InvalidXliffDataException extends \TYPO3\Flow\I18n\Exception\InvalidXmlFileException
{
}


text:
struct Obj;
struct ObjString;

enum ValueType
{
    VAL_NIL,
    VAL_BOOL,
    VAL_NUMBER,
    VAL_OBJ,
};

struct Value
{
    ValueType type;
    union
    {
        bool boolean;
        double number;
        Obj* obj;
    };
};

constexpr Value nil_val()
{
    Value value{ VAL_NIL };
    return value;
};

constexpr Value bool_val(bool v)
{
    Value value{ VAL_BOOL };
    value.boolean = v;
    return value;
};

constexpr Value number_val(double v)
{
    Value value{ VAL_NUMBER };
    value.number = v;
    return value;
};

template<typename TObj>
constexpr Value obj_val(TObj* obj)
{
    Value value{ VAL_OBJ };
    value.obj = reinterpret_cast<Obj*>(obj);
    return value;
}

constexpr bool as_bool(Value value) { return value.boolean; }
constexpr double as_number(Value value) { return value.number; }
constexpr Obj* as_obj(Value value) { return value.obj; }

constexpr bool is_nil(Value value) { return value.type == VAL_NIL; }
constexpr bool is_bool(Value value) { return value.type == VAL_BOOL; }
constexpr bool is_number(Value value) { return value.type == VAL_NUMBER; }
constexpr bool is_obj(Value value) { return value.type == VAL_OBJ; }

bool values_equal(Value a, Value b);

void print_value(Value value);

struct ValueArray
{
    int capacity;
    int count;
    Value* values;
};

void init_value_array(ValueArray& valarray);
void free_value_array(ValueArray& valarray);
void write_value_array(ValueArray& valarray, Value value);


text:
import functools
import os

class TemporaryEnvironment:
    """Allow temporary changes to environment variables."""

    def __init__(self):
        self.__old_env = None

    def __enter__(self):
        self.__old_env = os.environ.copy()
        return self

    def __exit__(self, t, v, tb):
        # Update keys manually to make sure putenv gets called
        for key, value in self.__old_env.items():
            os.environ[key] = value
        # Remove added keys
        env_keys = tuple(os.environ)
        for key in env_keys:
            if key not in self.__old_env:
                del os.environ[key]
        self.__old_env = None

def sandbox_environment_variables(func):
    """Decorate a function to give it a temporary environment."""

    @functools.wraps(func)
    def wrapper_func(*args, **kwargs):
        with TemporaryEnvironment():
            func(*args, **kwargs)

    return wrapper_func


text:
<refentry xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          id="[[NAME]]">
<refmeta>
<refentrytitle>[[NAME]]</refentrytitle>
<refmiscinfo role="type"></refmiscinfo>
</refmeta>
<refnamediv>
<refname>[[NAME]]</refname>
<refpurpose></refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment id='[[NAME]].frag'>
<xsl:param name="[[NAME]]" select=""/>
</src:fragment>
</refsynopsisdiv>

<refsect1><title>Description</title>

<para>FIXME:</para>

</refsect1>
</refentry>


text:
    <form class="form-signin">

用户登录

        <input type="text" class="form-control" name="username" placeholder="用户名" required="" autofocus="" ng-model="user.loginname"/>
        <input type="password" class="form-control" name="password" placeholder="密码" required="" ng-model="user.loginpass"/>

            <input type="checkbox" value="remember-me" id="rememberMe" name="rememberMe" disabled> Remember me

        <button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="doVerify()">登录</button>
    </form>


text:
package at.fishkog.als.sim.component;

public interface Processable {

	public void process();

}


text:
class DailyMoodViewModel
  include ActiveModel::Model
  include ActiveModel::Validations

  has_many :daily_moods
  attr_accessor :date, :daily_moods
  validates :date, presence: true
  validates_associated :daily_moods

  def initialize(params = nil)
    return if params == nil
    @date = params[:date]
    @daily_moods = params[:daily_moods]
  end

end


text:
Model Designer

                        {{step.step = ($index + 1)}}
                        {{step.title}}

                        <button class="btn btn-prev" ng-click="preView()" ng-show="curStep.title!='Model Info'">

                            Prev
                        </button>
                        <button id="nextButton" class="btn btn-success btn-next" ng-disabled="forms[curStep.form].$invalid" ng-click="checkForm($index)?nextView():''"
                                ng-show="curStep.title!='Settings'">
                            Next

                        </button>
                        <button class="btn btn-primary"  ng-click="checkForm($index)?saveModel():''"
                                ng-if="curStep.title=='Settings' && state.mode=='edit'">
                            Save
                        </button>

No models

                Click here to create your model

No model selected

               Select your model


text:
"use strict";

/**
* SERVICE - `datepicker$`
* - Exposes the Angular Strap `Datepicker` service
* - Requires `angular-strap`
*
* @module Extension->UI-Datepicker-Service
*/

import ngStrapVendorService from "~/app/extension/ui/ng-strap.vendor.service.js";

const bootstrapDatepickerService = function bootstrapDatepickerService($datepicker) {
	return $datepicker;
};

export default angular
	.module("ui.datepicker.service", [ngStrapVendorService.name])
	.factory("datepicker$", bootstrapDatepickerService)
;


text:
using System;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using SIL.PlatformUtilities;
using SIL.Reporting;

namespace SIL.IO
{
	public static class FileUtils
	{
		public static StringCollection TextFileExtensions
		{
			get { return Properties.Settings.Default.TextFileExtensions; }
		}

		public static StringCollection AudioFileExtensions
		{
			get { return Properties.Settings.Default.AudioFileExtensions; }
		}

		public static StringCollection VideoFileExtensions
		{
			get { return Properties.Settings.Default.VideoFileExtensions; }
		}

		public static StringCollection ImageFileExtensions
		{
			get { return Properties.Settings.Default.ImageFileExtensions; }
		}

		public static StringCollection DatasetFileExtensions
		{
			  get { return Properties.Settings.Default.DatasetFileExtensions; }
		}

		public static StringCollection SoftwareAndFontFileExtensions
		{
			  get { return Properties.Settings.Default.SoftwareAndFontFileExtensions; }
		}

		public static StringCollection PresentationFileExtensions
		{
			  get { return Properties.Settings.Default.PresentationFileExtensions; }
		}

		public static StringCollection MusicalNotationFileExtensions
		{
			  get { return Properties.Settings.Default.MusicalNotationFileExtensions; }
		}

		public static StringCollection ZipFileExtensions
		{
			  get { return Properties.Settings.Default.ZipFileExtensions; }
		}

		public static bool GetIsZipFile(string path)
		{
			return GetIsSpecifiedFileType(ZipFileExtensions, path);
		}

		public static bool GetIsText(string path)
		{
			return GetIsSpecifiedFileType(TextFileExtensions, path);
		}

		public static bool GetIsAudio(string path)
		{
			return GetIsSpecifiedFileType(AudioFileExtensions, path);
		}

		public static bool GetIsVideo(string path)
		{
			return GetIsSpecifiedFileType(VideoFileExtensions, path);
		}

		public static bool GetIsMusicalNotation(string path)
		{
			return GetIsSpecifiedFileType(MusicalNotationFileExtensions, path);
		}

		public static bool GetIsDataset(string path)
		{
			return GetIsSpecifiedFileType(DatasetFileExtensions, path);
		}

		public static bool GetIsSoftwareOrFont(string path)
		{
			return GetIsSpecifiedFileType(SoftwareAndFontFileExtensions, path);
		}

		public static bool GetIsPresentation(string path)
		{
			return GetIsSpecifiedFileType(PresentationFileExtensions, path);
		}

		public static bool GetIsImage(string path)
		{
			return GetIsSpecifiedFileType(ImageFileExtensions, path);
		}

		private static bool GetIsSpecifiedFileType(StringCollection extensions, string path)
		{
			var extension = Path.GetExtension(path);
			return (extension != null) && extensions.Contains(extension.ToLower());
		}

		public static bool IsFileLocked(string filePath)
		{
			if (filePath == null || !File.Exists(filePath))
				return false;

			try
			{
				File.OpenWrite(filePath).Close();
				return false;
			}
			catch
			{
				return true;
			}
		}

		/// <summary>
		/// NB: This will show a dialog if the file writing can't be done (subject to Palaso.Reporting settings).
		/// It will throw whatever exception was encountered, if the user can't resolve it.
		/// </summary>
		/// <param name="inputPath"></param>
		/// <param name="pattern"></param>
		/// <param name="replaceWith"></param>
		public static void GrepFile(string inputPath, string pattern, string replaceWith)
		{
			Regex regex = new Regex(pattern, RegexOptions.Compiled);
			string tempPath = inputPath + ".tmp";

			using (StreamReader reader = File.OpenText(inputPath))
			{
				using (StreamWriter writer = new StreamWriter(tempPath))
				{
					while (!reader.EndOfStream)
					{
						writer.WriteLine(regex.Replace(reader.ReadLine(), replaceWith));
					}
					writer.Close();
				}
				reader.Close();
			}
			//string backupPath = GetUniqueFileName(inputPath);
			string backupPath = inputPath + ".bak";

			ReplaceFileWithUserInteractionIfNeeded(tempPath, inputPath, backupPath);
		}

		public static bool GrepFile(string inputPath, string pattern)
		{
			Regex regex = new Regex(pattern, RegexOptions.Compiled);

			using (StreamReader reader = File.OpenText(inputPath))
			{
				while (!reader.EndOfStream)
				{
					if (regex.IsMatch(reader.ReadLine()))
					{
						return true;
					}
				}
				reader.Close();
			}
			return false;
		}

		/// <summary>
		/// Make sure the given <paramref name="pathToFile"/> file is 'valid'.
		///
		/// Valid means that
		///		1. <paramref name="pathToFile"/> must not be null or an empty string
		///		2. <paramref name="pathToFile"/> must exist, and
		///		3. The extension for <paramref name="pathToFile"/> must equal <paramref name="expectedExtension"/>
		///			(Or both must be null)
		/// </summary>
		public static bool CheckValidPathname(string pathToFile, string expectedExtension)
		{
			var extension = ((expectedExtension == null) || (expectedExtension.Trim() == String.Empty))
								? null
								: expectedExtension.StartsWith(".") ? expectedExtension.Substring(1) : expectedExtension;

			if (string.IsNullOrEmpty(pathToFile) || !File.Exists(pathToFile))
				return false;

			var actualExtension = Path.GetExtension(pathToFile);
			if (actualExtension == String.Empty)
				actualExtension = null;
			return (actualExtension == null && extension == null) || (actualExtension != null && extension != null &&
				   actualExtension.ToLowerInvariant() == "." + extension.ToLowerInvariant());
		}

		/// <summary>
		/// If there is a problem doing the replace, a dialog is shown which tells the user
		/// what happened, and lets them try to fix it.  It also lets them "Give up", in
		/// which case this returns False.
		///
		/// To help with situations where something may temporarily be holding on to the file,
		/// this will retry for up to 5 seconds.
		/// </summary>
		/// <param name="sourcePath"></param>
		/// <param name="destinationPath"></param>
		/// <param name="backupPath">can be null if you don't want a replacement</param>
		/// <returns>if the user gives up, throws whatever exception the file system gave</returns>
		public static void ReplaceFileWithUserInteractionIfNeeded(string sourcePath,
																  string destinationPath,
																  string backupPath)
		{
			bool succeeded = false;
			do
			{
				try
				{
					if (UnsafeForFileReplaceMethod(sourcePath) || UnsafeForFileReplaceMethod(destinationPath)
						||
						(!string.IsNullOrEmpty(backupPath) && !PathUtilities.PathsAreOnSameVolume(sourcePath,backupPath))
						||
						!PathUtilities.PathsAreOnSameVolume(sourcePath, destinationPath)
						||
						!File.Exists(destinationPath)
						)
					{
						//can't use File.Replace or File.Move across volumes (sigh)
						ReplaceByCopyDelete(sourcePath, destinationPath, backupPath);
					}
					else
					{
						var giveUpTime = DateTime.Now.AddSeconds(5);
						Exception theProblem;
						do
						{
							theProblem = null;
							try
							{
								File.Replace(sourcePath, destinationPath, backupPath);
							}
							catch (UnauthorizedAccessException uae)
							{
								// We were getting this while trying to Replace on a JAARS network drive.
								// The network drive is U:\ which maps to \\waxhaw\users\{username},
								// so it doesn't get caught by the checks above.
								// Both files were in the same directory and there were no permissions issues,
								// but the Replace command was failing with "Access to the path is denied." anyway.
								// I never could figure out why. See http://issues.bloomlibrary.org/youtrack/issue/BL-4179
								try
								{
									ReplaceByCopyDelete(sourcePath, destinationPath, backupPath);
								}
								catch
								{
									// Though it probably doesn't matter, report the original exception since we prefer Replace to CopyDelete.
									theProblem = uae;
									Thread.Sleep(100);
								}
							}
							catch (Exception e)
							{
								theProblem = e;
								Thread.Sleep(100);
							}

						} while (theProblem != null && DateTime.Now < giveUpTime);
						if (theProblem != null)
							throw theProblem;
					}
					succeeded = true;
				}
				catch (UnauthorizedAccessException error)
				{
					ReportFailedReplacement(destinationPath, error);
				}
				catch (IOException error)
				{
					ReportFailedReplacement(destinationPath, error);
				}
			}
			while (!succeeded);
		}

		private static void ReplaceByCopyDelete(string sourcePath, string destinationPath, string backupPath)
		{
			if (!string.IsNullOrEmpty(backupPath) && File.Exists(destinationPath))
			{
				File.Copy(destinationPath, backupPath, true);
			}
			File.Copy(sourcePath, destinationPath, true);
			File.Delete(sourcePath);
		}

		// NB: I don't actually know for sure that we can't do the replace on these paths; this dev doesn't
		// have a network to test on. What I do know is that the code checking to see if they are on the
		// same drive fails for UNC paths, so this at least gets us past that problem
		private static bool UnsafeForFileReplaceMethod(string path)
		{
#if !MONO
			return path.StartsWith("//") || path.StartsWith("\\\\");
#else
			return false; // we will soon be requesting some testing with networks on Linux;
			//as a result of that, we might need to do something here, too. Or maybe not.
#endif
		}

		private static void ReportFailedReplacement(string destinationPath, Exception error)
		{
			var message = string.Format("{0} was unable to update the file '{1}'.\n"+
			                                  "Possible causes:\n"+
			                                  "* Another copy of this program could be running, or some other program might have the file open or locked (including things like Dropbox and antivirus software).\n" +
			                                  "* The file may be set to 'Read Only'\n"+
			                                  "* The security permissions of this file may be set to deny you access to it.\n\n" +
			                                  "The error was: \n{2}",
				EntryAssembly.ProductName, destinationPath, error.Message);
			message = message.Replace("\n", Environment.NewLine);
			//enhance: this would be clearer if the "OK" button read "Retry", but that's not easily changable.
			var result = ErrorReport.NotifyUserOfProblem(new ShowAlwaysPolicy(), "Give Up", ErrorResult.No,
				message);
			if (result == ErrorResult.No)
			{
				throw error; // pass it up to the caller
			}
		}

#if !MONO
		[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		static extern uint GetShortPathName(
		   [MarshalAs(UnmanagedType.LPTStr)]string lpszLongPath,
		   [MarshalAs(UnmanagedType.LPTStr)]StringBuilder lpszShortPath,
		   uint cchBuffer);
#endif

		/// <summary>
		/// When calling external exe's on Windows any non-ascii characters can get converted to '?'. This
		/// will convert them to 8.3 format which is all ascii (and do nothing on Linux).
		/// </summary>
		public static string MakePathSafeFromEncodingProblems(string path)
		{
#if MONO
			return path;//Linux doesn't have these problems, far as I know
#else
			const int MAXPATH = 260;
			var shortBuilder = new StringBuilder(MAXPATH);
			GetShortPathName(path, shortBuilder, (uint)shortBuilder.Capacity);
			return shortBuilder.ToString();
#endif
		}

		/// <summary>
		/// Normalize the path so that it uses forward slashes instead of backslashes. This is
		/// useful when a path gets read from a file that gets shared between Windows and Linux -
		/// if the path contains backslashes it can't be found on Linux.
		/// </summary>
		public static string NormalizePath(string path)
		{
			return path.Replace('\\', '/');
		}

		/// <summary>
		/// Strips file URI prefix from the beginning of a file URI string, and keeps
		/// a beginning slash if in Linux.
		/// eg "file:///C:/Windows" becomes "C:/Windows" in Windows, and
		/// "file:///usr/bin" becomes "/usr/bin" in Linux.
		/// Returns the input unchanged if it does not begin with "file:".
		///
		/// Does not convert the result into a valid path or a path using current platform
		/// path separators.
		///
		/// See uri.LocalPath, http://en.wikipedia.org/wiki/File_URI , and
		/// http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx .
		/// </summary>
		public static string StripFilePrefix(string fileString)
		{
			if (String.IsNullOrEmpty(fileString))
				return fileString;

			var prefix = Uri.UriSchemeFile + ":";

			if (!fileString.StartsWith(prefix))
				return fileString;

			var path = fileString.Substring(prefix.Length);
			// Trim any number of beginning slashes
			path = path.TrimStart('/');
			// Prepend slash on Linux
			if (Platform.IsUnix)
				path = '/' + path;

			return path;
		}

	}
}


text:
export class Category {
    category: string;
}


text:
/*.ApplicationProcessViewerWindow application-window-content {
}*/


text:
package com.jebware.keypadviewdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.main_btn_numeric)
    void onClickNumeric() {
        Intent intent = new Intent(this, GenericKeypadActivity.class)
                .putExtra(GenericKeypadActivity.EXTRA_KEYPAD_LAYOUT_RESOURCE_ID, R.layout.kpv_numeric_keypad);
        startActivity(intent);
    }

    @OnClick(R.id.main_btn_telephone)
    void onClickPin() {
        Intent intent = new Intent(this, GenericKeypadActivity.class)
                .putExtra(GenericKeypadActivity.EXTRA_KEYPAD_LAYOUT_RESOURCE_ID, R.layout.kpv_telephone_keypad);
        startActivity(intent);
    }
}


text: yum -y install ntp


text:
import { mount } from '@vue/test-utils';
import router from '../../../router';
import store from '../../../store';
import { RouterNames } from '../../../constants';
import UserTable from '../UserTable';

const loadUsers = jest.fn().mockReturnValue(Promise.resolve());
const userList = ['test', 'user', 'table'];
function makeWrapper() {
  router.replace({ name: RouterNames.USERS });
  return mount(UserTable, {
    router,
    store,
    sync: false,
    computed: {
      count() {
        return 10;
      },
      users() {
        return userList;
      },
    },
    methods: {
      loadUsers,
    },
    stubs: {
      UserItem: true,
      EmailUsersDialog: true,
    },
  });
}

describe('userTable', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = makeWrapper();
  });
  describe('filters', () => {
    it('changing filter should set query params', () => {
      wrapper.vm.filter = 'administrator';
      expect(router.currentRoute.query.is_admin).toBe(true);
    });
    it('changing location should set query params', () => {
      wrapper.vm.location = 'Afghanistan';
      expect(router.currentRoute.query.location).toBe('Afghanistan');
    });
    it('changing search text should set query params', () => {
      wrapper.vm.keywords = 'keyword test';
      expect(router.currentRoute.query.keywords).toBe('keyword test');
    });
  });
  describe('selection', () => {
    it('selectAll should set selected to channel list', () => {
      wrapper.vm.selectAll = true;
      expect(wrapper.vm.selected).toEqual(userList);
    });
    it('removing selectAll should set selected to empty list', () => {
      wrapper.vm.selected = userList;
      wrapper.vm.selectAll = false;
      wrapper.vm.$nextTick(() => {
        expect(wrapper.vm.selected).toEqual([]);
      });
    });
    it('selectedCount should match the selected length', () => {
      wrapper.vm.selected = ['test'];
      expect(wrapper.vm.selectedCount).toBe(1);
    });
    it('selected should clear on query changes', () => {
      wrapper.vm.selected = ['test'];
      router.push({
        ...wrapper.vm.$route,
        query: {
          param: 'test',
        },
      });
      wrapper.vm.$nextTick(() => {
        expect(wrapper.vm.selected).toEqual([]);
      });
    });
  });
  describe('bulk actions', () => {
    it('should be hidden if no items are selected', () => {
      expect(wrapper.find('[data-test="email"]').exists()).toBe(false);
    });
    it('should be visible if items are selected', () => {
      wrapper.vm.selected = userList;
      wrapper.vm.$nextTick(() => {
        expect(wrapper.find('[data-test="email"]').exists()).toBe(true);
      });
    });
    it('email should open email dialog', () => {
      wrapper.vm.selected = userList;
      wrapper.vm.$nextTick(() => {
        wrapper.find('[data-test="email"] .v-btn').trigger('click');
        expect(wrapper.vm.showEmailDialog).toBe(true);
      });
    });
  });
});


text:
If you have a resource you would like to add, please [edit this page](edit/master/RESOURCES.md) and submit a pull request.

## Documentation
- [High-performance audio guide](https://developer.android.com/ndk/guides/audio/index.html)
- [Android Audio architecture](https://source.android.com/devices/audio/)

## Codelabs
- [Making Waves Part 1 - Build a synthesizer for Android](https://codelabs.developers.google.com/codelabs/making-waves-1-synth)

## Latency Testing Apps

- [WALT](https://github.com/google/walt)
- Dr Rick O'Rang Loopback app ([source](https://github.com/gkasten/drrickorang/tree/master/LoopbackApp) | [binary](https://play.google.com/store/apps/details?id=org.drrickorang.loopback))

## Other code samples
- [Android NDK native-audio](https://github.com/googlesamples/android-ndk/tree/master/native-audio) - Uses OpenSL ES to show how to perform simple playback
- [Android NDK audio-echo ](https://github.com/googlesamples/android-ndk/tree/master/audio-echo) - Uses OpenSL ES to demonstrate recording and playback
- [Phil Burk's MIDI samples](https://github.com/philburk/android-midisuite)

## Videos

- [Best Practices for Android Audio (Google I/O '17)](https://www.youtube.com/watch?v=C0BPXZIvG-Q) (19 May 2017)
- [Whats New In Android Audio, Don Turner & Phil Burk (Android)](https://www.youtube.com/watch?v=dAyeEN21FbM) (17 Nov 2016)
- [Android high-performance audio - Google I/O 2016](https://www.youtube.com/watch?v=F2ZDp-eNrh4) (19 May 2016)
- [Developing Android Apps with High Performance Audio, JUCE Summit 2015](https://www.youtube.com/watch?v=vPc7zvfpUos) (18 Feb 2016)
- [Audio latency: buffer sizes](https://www.youtube.com/watch?v=PnDK17zP9BI) (13 Jul 2015)
- [Sample rates and resampling: Why can't we all just agree?](https://www.youtube.com/watch?v=6Dl6BdrA-sQ) (25 Jun 2014)
- [Will it float? The glory and shame of floating-point audio](https://www.youtube.com/watch?v=sIcieUqMml8) (25 Jun 2014)
- [Google I/O 2013 - High Performance Audio](https://www.youtube.com/watch?v=d3kfEeMZ65c) (18 May 2013)


text:
package com.twitter.finatra.thrift

import com.twitter.finagle.http.Request
import com.twitter.finagle.http.Response
import com.twitter.finagle.http.Status
import com.twitter.finatra.http.exceptions.ExceptionMapper
import com.twitter.finatra.http.response.ResponseBuilder
import com.twitter.inject.utils.ExceptionUtils._
import com.twitter.inject.thrift.ThriftClientException
import com.twitter.inject.thrift.ThriftClientExceptionSource
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class ThriftClientExceptionMapper @Inject() (
  response: ResponseBuilder,
  source: ThriftClientExceptionSource)
    extends ExceptionMapper[ThriftClientException] {

  override def toResponse(
    request: Request,
    exception: ThriftClientException
  ): Response = {
    response
      .status(Status.ServiceUnavailable)
      .jsonError
      .failure(
        request,
        source(exception),
        details = Seq(
          exception.method.serviceName,
          exception.method.name,
          toExceptionDetails(exception.cause)
        ),
        message = toExceptionMessage(exception.cause)
      )
  }
}


text:
"""
Replaces underscores by spaces
"""

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def rep(value):
    return value.replace("_", " ")


text:
class GM2D3AutoControlInput : public Fl_Input
{
public:
    GM2D3AutoControlInput(int x, int y, int w, int h, Axis _axis);

    const Axis axis;
};

class GM2D3AutoControlGUI
{
public:
    GM2D3AutoControlGUI(int x, int y, int w, int h);

    void disable_input(Axis axis);
    void enable_input(Axis axis);

    void activate(std::set<Axis> axes);
    void deactivate();

    std::unique_ptr<Fl_Button> calibrate_button;
    std::unique_ptr<Fl_Button> go_button;
    std::unique_ptr<Fl_Button> kill_button;

private:
    std::unique_ptr<Fl_Box> auto_control_box;

    std::unique_ptr<Fl_Pack> horizontal_pack;
    std::unique_ptr<Fl_Pack> input_box_pack;
    std::unique_ptr<Fl_Pack> auto_button_pack;

    std::map<Axis, std::unique_ptr<GM2D3AutoControlInput>> user_position_inputs;

    std::unique_ptr<Fl_Menu_Button> preset_positions_menu;
};


text:
var transac = require('client-transac-redline')
  , async = require('async')
  , path = require('path')
  , glob = require('glob')
  , spawn = require('child_process').spawn;

//00 5  * * 0 cd /home/eric/works && ./updategit > /tmp/syncgit 2>&1

function update(transac){
  return function(dir, cb){
    process.chdir(dir);

    var cmd = spawn("git", ['pull'])
      , res = [ '
# ' + "cd " + dir + " && git pull"  + "
" ]
      , error = false;

    cmd.stdout.on('data', function(data){
      res.push(data.toString());
    });

    cmd.stderr.on('data', function(data){
      error = true;
      res.push(data.toString());
    });

    cmd.on('close', function(code){
      if(error) transac.error(path.basename(dir), res.join("\n"));
      else transac.info(path.basename(dir), res.join("\n"));
      cb();
    });

    cmd.on('error', function(data){
      transac.error(path.basename(dir), res.join("\n"));
      cb();
    });
  }
}

function run(transac, cb){
  var pwd = process.cwd();
  glob("/home/redpelicans/redline/git-sync/repos/*", function(err, files){
    async.mapSeries(files, update(transac), cb);
  });
}

transac.exec('git Sync', 'http://localhost:3002', run, {locked: false});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="broadcasts">Weşanên Zindî</string>
  <string name="liveBroadcasts">Weşanên Turnûva yên Zindî</string>
  <string name="newBroadcast">Weşana Zindî ya nû</string>
  <string name="addRound">Raundek zêde bike</string>
  <string name="ongoing">Didome</string>
  <string name="upcoming">Yên tên</string>
  <string name="completed">Yên Qediya</string>
  <string name="roundName">Navê raundê</string>
  <string name="roundNumber">Hejmara roundê</string>
  <string name="tournamentName">Navê pêşbirkê</string>
  <string name="tournamentDescription">Bi kurtasî di derbqrê pêşbirkî da</string>
  <string name="resetRound">Vî raundî bîne serî</string>
  <string name="deleteRound">Vî raundî jê bibe</string>
  <string name="broadcastUrl">Lînka Weşanê</string>
  <string name="currentRoundUrl">Lînka raundê niha</string>
  <string name="currentGameUrl">Lînka lîstika niha</string>
</resources>


text:
<?php

namespace l3l0\Bundle\OpenSocialBundle\Factory\Auth;

interface FactoryInterface extends \l3l0\Bundle\OpenSocialBundle\Factory\FactoryInterface
{
}


text:
/*
 * Source code generated by Celerio, a Jaxio product.
 * Documentation: http://www.jaxio.com/documentation/celerio/
 * Follow us on twitter: @jaxiosoft
 * Need commercial support ? Contact us: info@jaxio.com
 * Template angular-lab:springboot/src/main/java/searchrepository/EntitySearchRepository.e.vm.java
 */
package com.jaxio.demo.searchrepository;

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import com.jaxio.demo.domain.AppAuthority;

/**
 * Spring Data ElasticSearch repository for the entity named: AppAuthority.
 */
public interface AppAuthoritySearchRepository extends ElasticsearchRepository<AppAuthority, Integer> {
}


text:
package models.renewal

import cats.data.Validated.{Invalid, Valid}
import jto.validation.{From, Path, Rule, To, ValidationError, Write}
import jto.validation.forms.UrlFormEncoded
import models.FormTypes.{basicPunctuationPattern, notEmptyStrip}
import models.ValidationRule
import play.api.libs.json._

case class BankMoneySource(bankNames : String)

case class WholesalerMoneySource(wholesalerNames : String)

case object CustomerMoneySource

case class MoneySources(bankMoneySource: Option[BankMoneySource] = None,
                        wholesalerMoneySource: Option[WholesalerMoneySource] = None,
                        customerMoneySource: Option[Boolean] = None) {

  def size = List(this.bankMoneySource, this.wholesalerMoneySource, this.customerMoneySource).flatten.size

}

object MoneySources {
  import jto.validation.forms.Rules._
  import utils.MappingUtils.Implicits._

  private def nameType(fieldName: String) = {
    notEmptyStrip andThen
      minLength(1).withMessage(s"error.invalid.renewal.msb.wc.$fieldName") andThen
      maxLength(140).withMessage(s"error.invalid.maxlength.140.$fieldName") andThen
      basicPunctuationPattern(s"error.invalid.characters.renewal.msb.wc.$fieldName")
  }

  type MoneySourceValidation = (Option[BankMoneySource], Option[WholesalerMoneySource], Option[Boolean])

  private val validateMoneySources: ValidationRule[MoneySourceValidation] = Rule[MoneySourceValidation, MoneySourceValidation] {
    case x@(Some(_), _, _) => Valid(x)
    case x@(_, Some(_), _) => Valid(x)
    case x@(_, _, Some(true)) => Valid(x)
    case _ => Invalid(Seq((Path \ "WhoWillSupply") -> Seq(ValidationError("error.invalid.renewal.msb.wc.moneySources"))))
  }

  implicit def formRule: Rule[UrlFormEncoded, MoneySources] = From[UrlFormEncoded] { __ =>
    import jto.validation.forms._

    val bankMoneySource: Rule[UrlFormEncoded, Option[BankMoneySource]] =
      (__ \ "bankMoneySource").read[Option[String]] flatMap {
        case Some("Yes") => (__ \ "bankNames")
          .read(nameType("bankNames"))
          .map(names => Some(BankMoneySource(names)))
        case _ => Rule[UrlFormEncoded, Option[BankMoneySource]](_ => Valid(None))
      }

    val wholesalerMoneySource: Rule[UrlFormEncoded, Option[WholesalerMoneySource]] =
      (__ \ "wholesalerMoneySource").read[Option[String]] flatMap {
        case Some("Yes") => (__ \ "wholesalerNames")
          .read(nameType("wholesalerNames"))
          .map(names => Some(WholesalerMoneySource(names)))
        case _ => Rule[UrlFormEncoded, Option[WholesalerMoneySource]](_ => Valid(None))
      }

    val customerMoneySource: Rule[UrlFormEncoded, Option[Boolean]] =
      (__ \ "customerMoneySource").read[Option[String]] map {
        case Some("Yes") => Some(true)
        case _ => None
      }

    val validatedMs = (bankMoneySource ~ wholesalerMoneySource ~ customerMoneySource).tupled andThen validateMoneySources

    validatedMs map { msv: MoneySourceValidation =>
      (msv._1, msv._2, msv._3) match{
        case (b, w, c) => MoneySources(b,w,c)
      }
    }
  }

  implicit val formWrite: Write[MoneySources, UrlFormEncoded] = To[UrlFormEncoded] { __ =>
    import jto.validation.forms.Writes._

    ((__ \ "bankMoneySource").write[Option[String]] ~
      (__ \ "bankNames").write[Option[String]] ~
      (__ \ "wholesalerMoneySource").write[Option[String]] ~
      (__ \ "wholesalerNames").write[Option[String]] ~
      (__ \ "customerMoneySource").write[Option[String]]).apply(ms =>
      (ms.bankMoneySource.map(_ => "Yes"),
        ms.bankMoneySource.map(bms => bms.bankNames),
        ms.wholesalerMoneySource.map(_ => "Yes"),
        ms.wholesalerMoneySource.map(bms => bms.wholesalerNames),
        ms.customerMoneySource.map(_ => "Yes")))
  }

  val bankMoneySourceWriter = new Writes[Option[BankMoneySource]] {
    override def writes(o: Option[BankMoneySource]): JsValue = o match {
      case Some(x) => Json.obj("bankMoneySource" -> "Yes",
        "bankNames" -> x.bankNames)
      case _ => Json.obj()
    }
  }

  val wholesalerMoneySourceWriter = new Writes[Option[WholesalerMoneySource]] {
    override def writes(o: Option[WholesalerMoneySource]): JsValue = o match {
      case Some(x) => Json.obj("wholesalerMoneySource" -> "Yes",
        "wholesalerNames" -> x.wholesalerNames)
      case _ => Json.obj()
    }
  }

  val customerMoneySourceWriter = new Writes[Option[Boolean]] {
    override def writes(o: Option[Boolean]): JsValue = o match {
      case Some(true) => Json.obj("customerMoneySource" -> JsString("Yes"))
      case _ => Json.obj()
    }
  }

  val readBanks = {
    import play.api.libs.functional.syntax._
    import play.api.libs.json._

    ((__ \ "bankMoneySource").readNullable[String] and
      (__ \ "bankNames").readNullable[String])((a, b) => (a, b) match {
      case (Some("Yes"), Some(names)) => Some(BankMoneySource(names))
      case _ => None
    })
  }

  val readWholesalers = {
    import play.api.libs.functional.syntax._
    import play.api.libs.json._

    ((__ \ "wholesalerMoneySource").readNullable[String] and
      (__ \ "wholesalerNames").readNullable[String])((a, b) => (a, b) match {
      case (Some("Yes"), Some(names)) => Some(WholesalerMoneySource(names))
      case _ => None
    })
  }

  val readCustomerMoney = {

    import play.api.libs.json._

    (__ \ "customerMoneySource").readNullable[String] map {
      case Some("Yes") => Some(true)
      case _ => None
    }
  }

  implicit val jsonReads: Reads[MoneySources] = {
    import play.api.libs.functional.syntax._
    (
      readBanks and readWholesalers and readCustomerMoney)((bms, wms, cms) => MoneySources(bms, wms, cms))
  }

  implicit val jsonWrites: Writes[MoneySources] = {
    import play.api.libs.functional.syntax._
    import play.api.libs.json._

    (__.write(bankMoneySourceWriter) and
      __.write(wholesalerMoneySourceWriter) and
      __.write(customerMoneySourceWriter))(x => (x.bankMoneySource, x.wholesalerMoneySource, x.customerMoneySource))
  }
}


text:
package testing.splitPanel;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import thobe.widgets.decoratorPanel.DecoratorPanelException;
import thobe.widgets.splitPanel.SPComponentDecorator;
import thobe.widgets.splitPanel.SPComponentDecoratorListener;

/**
 * @author Thomas Obenaus
 * @source SplitPanelDemo.java
 * @date 06.02.2012
 */
@SuppressWarnings ( "serial")
public class SPComponentDemo extends JFrame implements SPComponentDecoratorListener
{
	private SPComponentDecorator	spc;

	public SPComponentDemo( )
	{
		this.buildGUI( );
		this.setSize( 300, 250 );
		this.addWindowListener( new WindowAdapter( )
		{
			@Override
			public void windowClosing( WindowEvent e )
			{
				System.exit( 0 );
			}
		} );
	}

	private void buildGUI( )
	{
		this.setLayout( new BorderLayout( ) );

		JPanel pa_toOverlay = new JPanel( );
		pa_toOverlay.setLayout( new BorderLayout( ) );
		pa_toOverlay.add( new JLabel( "ein Label" ), BorderLayout.NORTH );
		pa_toOverlay.add( new JTextArea( "Etwas Text .....\n....\nnoch mehr Text...." ), BorderLayout.CENTER );

		try
		{
			this.spc = new SPComponentDecorator( pa_toOverlay );
			this.spc.addListener( this );
			this.add( spc, BorderLayout.CENTER );

			JButton bu_out = new JButton( "out" );
			bu_out.addActionListener( new ActionListener( )
			{
				@Override
				public void actionPerformed( ActionEvent e )
				{
					System.out.println( "SplitPanelDemo.buildGUI().new ActionListener() {...}.actionPerformed()" );
				}
			} );
			pa_toOverlay.add( bu_out, BorderLayout.SOUTH );
		}
		catch ( DecoratorPanelException e )
		{
			System.err.println( "Error: " + e.getLocalizedMessage( ) );
		}
	}

	public static void main( String[] args )
	{
		SPComponentDemo olpd = new SPComponentDemo( );
		olpd.setVisible( true );
	}

	@Override
	public void onVerticalSplit( )
	{
		this.spc.setWaiting( !this.spc.isWaiting( ) );
		System.out.println( "SplitPanelDemo.onVerticalSplit()" );
	}

	@Override
	public void onHorizontalSplit( )
	{
		System.out.println( "SplitPanelDemo.onHorizontalSplit()" );
	}

	@Override
	public void onMaximize( )
	{
		System.out.println( "SplitPanelDemo.onMaximize()" );

	}

	@Override
	public void onClose( )
	{
		System.out.println( "SplitPanelDemo.onClose()" );

	}

	@Override
	public void onMinimize( )
	{
		System.out.println( "SplitPanelDemo.onMinimize()" );

	}

}


text:
#ifndef ENSMETACOORDINATE_H
#define ENSMETACOORDINATE_H

/* ========================================================================= */
/* ============================= include files ============================= */
/* ========================================================================= */

#include "enscoordsystem.h"

AJ_BEGIN_DECLS

/* ========================================================================= */
/* =============================== constants =============================== */
/* ========================================================================= */

/* ========================================================================= */
/* ============================== public data ============================== */
/* ========================================================================= */

/* @data EnsPMetacoordinateadaptor ********************************************
**
** Ensembl Meta-Coordinate Adaptor.
**
** @alias EnsSMetacoordinateadaptor
** @alias EnsOMetacoordinateadaptor
**
** @attr Adaptor [EnsPDatabaseadaptor] Ensembl Database Adaptor.
** @attr CacheByName [AjPTable] Ensembl Feature name (i.e. table name) cache.
** @attr CacheByLength [AjPTable] Maximum length cache.
** @@
******************************************************************************/

typedef struct EnsSMetacoordinateadaptor
{
    EnsPDatabaseadaptor Adaptor;
    AjPTable CacheByName;
    AjPTable CacheByLength;
} EnsOMetacoordinateadaptor;

#define EnsPMetacoordinateadaptor EnsOMetacoordinateadaptor*

/* ========================================================================= */
/* =========================== public functions ============================ */
/* ========================================================================= */

/*
** Prototype definitions
*/

/* Ensembl Meta-Coordinate Adaptor */

EnsPMetacoordinateadaptor ensRegistryGetMetacoordinateadaptor(
    EnsPDatabaseadaptor dba);

EnsPMetacoordinateadaptor ensMetacoordinateadaptorNew(
    EnsPDatabaseadaptor dba);

void ensMetacoordinateadaptorDel(EnsPMetacoordinateadaptor *Pmca);

EnsPDatabaseadaptor ensMetacoordinateadaptorGetDatabaseadaptor(
    EnsPMetacoordinateadaptor mca);

AjBool ensMetacoordinateadaptorRetrieveAllCoordsystems(
    EnsPMetacoordinateadaptor mca,
    const AjPStr name,
    AjPList css);

AjBool ensMetacoordinateadaptorRetrieveMaximumlength(
    EnsPMetacoordinateadaptor mca,
    const EnsPCoordsystem cs,
    const AjPStr name,
    ajint *Pmaxlength);

/*
** End of prototype definitions
*/

AJ_END_DECLS

#endif /* !ENSMETACOORDINATE_H */


text:
/*
 * 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.
 */

package com.google.devtools.j2objc.translate;

import com.google.common.collect.Lists;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.ast.Assignment;
import com.google.devtools.j2objc.ast.BooleanLiteral;
import com.google.devtools.j2objc.ast.CStringLiteral;
import com.google.devtools.j2objc.ast.CharacterLiteral;
import com.google.devtools.j2objc.ast.Expression;
import com.google.devtools.j2objc.ast.FieldAccess;
import com.google.devtools.j2objc.ast.FunctionInvocation;
import com.google.devtools.j2objc.ast.InfixExpression;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.NullLiteral;
import com.google.devtools.j2objc.ast.NumberLiteral;
import com.google.devtools.j2objc.ast.PrefixExpression;
import com.google.devtools.j2objc.ast.QualifiedName;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.StringLiteral;
import com.google.devtools.j2objc.ast.ThisExpression;
import com.google.devtools.j2objc.ast.TreeNode;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.TreeVisitor;
import com.google.devtools.j2objc.types.Types;
import com.google.devtools.j2objc.util.BindingUtil;
import com.google.devtools.j2objc.util.NameTable;
import com.google.devtools.j2objc.util.UnicodeUtils;

import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;

import java.util.List;

/**
 * Rewrites certain operators, such as object assignment, into appropriate
 * method calls.
 *
 * @author Keith Stanger
 */
public class OperatorRewriter extends TreeVisitor {

  private static Expression getTarget(Expression node, IVariableBinding var) {
    if (node instanceof QualifiedName) {
      return ((QualifiedName) node).getQualifier();
    } else if (node instanceof FieldAccess) {
      return ((FieldAccess) node).getExpression();
    }
    return new ThisExpression(var.getDeclaringClass());
  }

  @Override
  public void endVisit(Assignment node) {
    Assignment.Operator op = node.getOperator();
    Expression lhs = node.getLeftHandSide();
    Expression rhs = node.getRightHandSide();
    ITypeBinding lhsType = lhs.getTypeBinding();
    ITypeBinding rhsType = rhs.getTypeBinding();
    if (op == Assignment.Operator.ASSIGN) {
      IVariableBinding var = TreeUtil.getVariableBinding(lhs);
      if (var == null || var.getType().isPrimitive() || !Options.useReferenceCounting()
          || var.isEnumConstant()) {
        return;
      }
      if (BindingUtil.isStatic(var)) {
        node.replaceWith(newStaticAssignInvocation(var, rhs));
      } else if (var.isField() && !BindingUtil.isWeakReference(var) && !inDeallocMethod(lhs)) {
        Expression target = getTarget(lhs, var);
        node.replaceWith(newFieldSetterInvocation(var, target, rhs));
      }
    } else {
      String funcName = getOperatorAssignFunction(op, lhsType, rhsType);
      if (funcName != null) {
        FunctionInvocation invocation = new FunctionInvocation(funcName, lhsType, lhsType, null);
        List<Expression> args = invocation.getArguments();
        args.add(new PrefixExpression(PrefixExpression.Operator.ADDRESS_OF, TreeUtil.remove(lhs)));
        args.add(TreeUtil.remove(rhs));
        node.replaceWith(invocation);
      }
    }
  }

  private boolean inDeallocMethod(TreeNode node) {
    MethodDeclaration method = TreeUtil.getOwningMethod(node);
    if (method == null) {
      return false;
    }
    String methodName = method.getName().getIdentifier();
    return (methodName.equals(NameTable.DEALLOC_METHOD)
        || methodName.equals(NameTable.FINALIZE_METHOD))
        && method.getParameters().isEmpty();
  }

  public void endVisit(InfixExpression node) {
    InfixExpression.Operator op = node.getOperator();
    ITypeBinding nodeType = node.getTypeBinding();
    String funcName = getInfixFunction(op, nodeType);
    if (funcName != null) {
      FunctionInvocation invocation = new FunctionInvocation(funcName, nodeType, nodeType, null);
      List<Expression> args = invocation.getArguments();
      args.add(TreeUtil.remove(node.getLeftOperand()));
      args.add(TreeUtil.remove(node.getRightOperand()));
      node.replaceWith(invocation);
    } else if (op == InfixExpression.Operator.PLUS && Types.isStringType(nodeType)) {
      rewriteStringConcatenation(node);
    }
  }

  private static boolean isFloatingPoint(ITypeBinding type) {
    return type.getName().equals("double") || type.getName().equals("float");
  }

  private FunctionInvocation newStaticAssignInvocation(IVariableBinding var, Expression value) {
    String assignFunc =
        TreeUtil.retainResult(value) ? "JreStrongAssignAndConsume" : "JreStrongAssign";
    FunctionInvocation invocation = new FunctionInvocation(
        assignFunc, value.getTypeBinding(), Types.resolveIOSType("id"), null);
    List<Expression> args = invocation.getArguments();
    args.add(new PrefixExpression(PrefixExpression.Operator.ADDRESS_OF, new SimpleName(var)));
    args.add(new NullLiteral());
    args.add(TreeUtil.remove(value));
    return invocation;
  }

  private static FunctionInvocation newFieldSetterInvocation(
      IVariableBinding var, Expression instance, Expression value) {
    ITypeBinding varType = var.getType();
    ITypeBinding declaringType = var.getDeclaringClass().getTypeDeclaration();
    String setterFormat = "%s_set_%s";
    if (TreeUtil.retainResult(value)) {
      setterFormat = "%s_setAndConsume_%s";
    }
    String setterName = String.format(setterFormat, NameTable.getFullName(declaringType),
        NameTable.javaFieldToObjC(NameTable.getName(var)));
    FunctionInvocation invocation = new FunctionInvocation(
        setterName, varType, varType, declaringType);
    invocation.getArguments().add(TreeUtil.remove(instance));
    invocation.getArguments().add(TreeUtil.remove(value));
    return invocation;
  }

  private static String intOrLong(ITypeBinding type) {
    switch (type.getBinaryName().charAt(0)) {
      case 'I':
        return "32";
      case 'J':
        return "64";
      default:
        throw new AssertionError("Type expected to be int or long but was: " + type.getName());
    }
  }

  private static String getInfixFunction(InfixExpression.Operator op, ITypeBinding nodeType) {
    switch (op) {
      case REMAINDER:
        if (isFloatingPoint(nodeType)) {
          return nodeType.getName().equals("float") ? "fmodf" : "fmod";
        }
        return null;
      case LEFT_SHIFT:
        return "LShift" + intOrLong(nodeType);
      case RIGHT_SHIFT_SIGNED:
        return "RShift" + intOrLong(nodeType);
      case RIGHT_SHIFT_UNSIGNED:
        return "URShift" + intOrLong(nodeType);
      default:
        return null;
    }
  }

  private static String getOperatorAssignFunction(
      Assignment.Operator op, ITypeBinding lhsType, ITypeBinding rhsType) {
    String lhsName = NameTable.capitalize(lhsType.getName());
    switch (op) {
      case LEFT_SHIFT_ASSIGN:
        return "LShiftAssign" + lhsName;
      case RIGHT_SHIFT_SIGNED_ASSIGN:
        return "RShiftAssign" + lhsName;
      case RIGHT_SHIFT_UNSIGNED_ASSIGN:
        return "URShiftAssign" + lhsName;
      case REMAINDER_ASSIGN:
        if (isFloatingPoint(lhsType) || isFloatingPoint(rhsType)) {
          return "ModAssign" + lhsName;
        }
        return null;
      default:
        return null;
    }
  }

  private static void rewriteStringConcatenation(InfixExpression node) {
    List<Expression> extendedOperands = node.getExtendedOperands();
    List<Expression> operands = Lists.newArrayListWithCapacity(extendedOperands.size() + 2);
    operands.add(TreeUtil.remove(node.getLeftOperand()));
    operands.add(TreeUtil.remove(node.getRightOperand()));
    TreeUtil.moveList(extendedOperands, operands);

    operands = coalesceStringLiterals(operands);
    if (operands.size() == 1 && Types.isStringType(operands.get(0).getTypeBinding())) {
      node.replaceWith(operands.get(0));
      return;
    }

    ITypeBinding stringType = Types.resolveIOSType("NSString");
    FunctionInvocation invocation =
        new FunctionInvocation("JreStrcat", stringType, stringType, null);
    List<Expression> args = invocation.getArguments();
    StringBuilder typeArg = new StringBuilder();
    for (Expression expr : operands) {
      typeArg.append(getStringConcatenationTypeCharacter(expr));
    }
    args.add(new CStringLiteral(typeArg.toString()));
    for (Expression expr : operands) {
      args.add(expr);
    }
    node.replaceWith(invocation);
  }

  private static List<Expression> coalesceStringLiterals(List<Expression> rawOperands) {
    List<Expression> operands = Lists.newArrayListWithCapacity(rawOperands.size());
    String currentLiteral = null;
    for (Expression expr : rawOperands) {
      String literalValue = getLiteralStringValue(expr);
      if (literalValue != null) {
        currentLiteral = currentLiteral == null ? literalValue : currentLiteral + literalValue;
      } else {
        if (currentLiteral != null) {
          addStringLiteralArgument(operands, currentLiteral);
          currentLiteral = null;
        }
        operands.add(expr);
      }
    }
    if (currentLiteral != null) {
      addStringLiteralArgument(operands, currentLiteral);
    }
    return operands;
  }

  private static void addStringLiteralArgument(List<Expression> args, String literal) {
    if (literal.length() == 0) {
      return;  // Skip it.
    } else if (literal.length() == 1) {
      args.add(new CharacterLiteral(literal.charAt(0)));
    } else {
      args.add(new StringLiteral(literal));
    }
  }

  private static String getLiteralStringValue(Expression expr) {
    switch (expr.getKind()) {
      case STRING_LITERAL:
        String literalValue = ((StringLiteral) expr).getLiteralValue();
        if (UnicodeUtils.hasValidCppCharacters(literalValue)) {
          return literalValue;
        } else {
          return null;
        }
      case BOOLEAN_LITERAL:
        return String.valueOf(((BooleanLiteral) expr).booleanValue());
      case CHARACTER_LITERAL:
        return String.valueOf(((CharacterLiteral) expr).charValue());
      case NUMBER_LITERAL:
        return ((NumberLiteral) expr).getValue().toString();
      default:
        return null;
    }
  }

  /**
   * Returns a character to indicate the type of an argument.
   * '$' for String, '@' for other objects, and the binary name character for
   * the primitives.
   */
  private static char getStringConcatenationTypeCharacter(Expression operand) {
    ITypeBinding operandType = operand.getTypeBinding();
    if (operandType.isPrimitive()) {
      return operandType.getBinaryName().charAt(0);
    } else if (Types.isStringType(operandType)) {
      return '$';
    } else {
      return '@';
    }
  }
}