Marks selected news items as published
349685
def make_published(self, request, queryset):
        
        rows_updated = queryset.update(is_published=True)
        self.message_user(request,
                          ungettext('%(count)d newsitem was published',
                                    '%(count)d newsitems were published',
                                    rows_updated) % {'count': rows_updated})
1189539
def publish(self):
        
        if self.published is False:
            self.published = True
        else:
            raise Warning(self.title + ' is already published.')
440216
protected function NewsTab()
    {
        /** General news settings */
        return Tab::create(
            'News', _t('NewsSiteConfigExtension.NEWS', 'News'), CheckboxField::create('UseAbstract', _t('NewsSiteConfigExtension.ABSTRACT', 'Use abstract/summary')), CheckboxField::create('TweetOnPost', _t('NewsSiteConfigExtension.TWEETPOST', 'Tweet after posting a new item')), // Requires Firesphere/silverstripe-social
            NumericField::create('PostsPerPage', _t('NewsSiteConfigExtension.PPP', 'Amount of posts per page')), UploadField::create('DefaultImage', _t('NewsSiteConfigExtension.DEFAULTIMPRESSION', 'Default impression image for newsitems'))
        );
    }
1353368
def print
      list.each do |entry|
        entry.headline ? print_headline(entry) : print_task_description(entry)
      end
    end
92439
def mark_seen(self):
        
        data = self.get_selected_item()
        if data['is_new']:
            with self.term.loader('Marking as read'):
                data['object'].mark_as_read()
            if not self.term.loader.exception:
                data['is_new'] = False
        else:
            with self.term.loader('Marking as unread'):
                data['object'].mark_as_unread()
            if not self.term.loader.exception:
                data['is_new'] = True
1036629
private function setNews()
    {
        $Params = $this->getURLParams();
        /** @var array $segmentFilter Array containing the filter for current or any item */
        $segmentFilter = $this->setupFilter($Params);
        $news = $this->Newsitems()
            ->filter($segmentFilter)
            ->exclude(array('PublishFrom:GreaterThan' => SS_Datetime::now()->format('Y-m-d')))
            ->first();
        $this->current_item = $news;
    }
129746
def SearchList(items, message="Select an item:", title='FontParts'):
    
    return dispatcher["SearchList"](items=items, message=message, title=title)
35862
def setcontents(source, identifier, pointer):
    """"""
    record = Record.get_record(identifier)
    Document(record, pointer).setcontents(source)
826778
def setArticleThreshold(self, value):
        
        assert isinstance(value, int)
        assert value >= 0
        self.topicPage["articleTreshWgt"] = value
279407
def instant_articles(self, **kwargs):
        
        eqs = self.search(**kwargs).sort('-last_modified', '-published')
        return eqs.filter(InstantArticle())
319569
def list_publications():
    
    publications = search_publications(
        DBPublication(is_public=True)
    )

    return SimpleTemplate(INDEX_TEMPLATE).render(
        publications=publications,
        compose_path=web_tools.compose_path,
        delimiter=":",
    )
586945
def publications(columns, n_results, queries):
    """"""
    if not isinstance(queries, dict):
        query_dict = {}
        for q in queries:
            key, value = q.split('=')
            if key == 'distinct':
                if value in ['True', 'true']:
                    query_dict.update({key: True})
                    continue
            try:
                value = int(value)
                query_dict.update({key: value})
            except BaseException:
                query_dict.update({key: '{0}'.format(value)})
    if 'sort' not in query_dict:
        query_dict.update({'order': '-year'})
    data = query.query(table='publications',
                       columns=columns,
                       n_results=n_results,
                       queries=query_dict)
    table = []
    headers = []
    for row in data['publications']['edges']:
        value = list(row['node'].values())
        for n, v in enumerate(value):
            if isinstance(v, str) and len(v) > 20:
                splited = v.split(' ')
                size = 0
                sentence = ''
                for word in splited:
                    if size < 20:
                        size += len(word)
                        sentence += ' ' + word
                    else:
                        sentence += '\n' + word
                        size = 0
                sentence += '\n'
                value[n] = sentence

        table += [value]

    headers = list(row['node'].keys())
    print(tabulate(table, headers, tablefmt="grid") + '\n')
1252951
public function index() {

        /**
         * set lastUpdatedPage
         */
        $query = TableRegistry::get('CmsContent')->find();
        $query->where(['content_type' => 'page']);
        $query->order(['modified' => 'DESC']);
        $this->set('last_page', $query);

        /**
         * set lastUpdatedNews
         */
        $query = TableRegistry::get('CmsContent')->find();
        $query->where(['content_type' => 'news']);
        $query->order(['modified' => 'DESC']);
        $this->set('last_news', $query);

        /**
         * set view
         */
        $this->viewBuilder()->template('dashboard');
    }
843946
def pretty_print_list_info(num_results, page_info=None, suffix=None):
    """"""
    num_results_fg = "green" if num_results else "red"
    num_results_text = click.style(str(num_results), fg=num_results_fg)

    if page_info and page_info.is_valid:
        page_range = page_info.calculate_range(num_results)
        page_info_text = "page: %(page)s/%(page_total)s, page size: %(page_size)s" % {
            "page": click.style(str(page_info.page), bold=True),
            "page_size": click.style(str(page_info.page_size), bold=True),
            "page_total": click.style(str(page_info.page_total), bold=True),
        }
        range_results_text = "%(from)s-%(to)s (%(num_results)s) of %(total)s" % {
            "num_results": num_results_text,
            "from": click.style(str(page_range[0]), fg=num_results_fg),
            "to": click.style(str(page_range[1]), fg=num_results_fg),
            "total": click.style(str(page_info.count), fg=num_results_fg),
        }
    else:
        page_info_text = ""
        range_results_text = num_results_text

    click.secho(
        "Results: %(range_results)s %(suffix)s%(page_info)s"
        % {
            "range_results": range_results_text,
            "page_info": " (%s)" % page_info_text if page_info_text else "",
            "suffix": suffix or "item(s)",
        }
    )
406005
def recent_articles(limit=10, exclude=None):
    """"""
    queryset = Article.objects.filter(published=True).order_by('-modified')
    if exclude:
        if hasattr(exclude, '__iter__'):
            queryset = queryset.exclude(pk__in=exclude)
        else:
            queryset = queryset.exclude(pk=exclude)
    return queryset
1062750
public function startIndexing()
    {
        $content = '';
        $table = 'tx_news_domain_model_news';

        // get the pages from where to index the news
        $indexPids = $this->getPidList(
            $this->indexerConfig['startingpoints_recursive'],
            $this->indexerConfig['sysfolder'],
            $table
        );

        // add the tags of each page to the global page array
        if ($this->indexerConfig['index_use_page_tags']) {
            $this->pageRecords = $this->getPageRecords($indexPids);
            $this->addTagsToRecords($indexPids);
        }

        // get all the news entries to index, don't index hidden or
        // deleted news, BUT  get the news with frontend user group
        // access restrictions or time (start / stop) restrictions.
        // Copy those restrictions to the index.
        $fields = '*';
        $queryBuilder = Db::getQueryBuilder('tx_kesearch_index');
        $where = [];
        $where[] = $queryBuilder->expr()->in('pid', implode(',', $indexPids));

        // index archived news
        // 0: index all news
        // 1: index only active (not archived) news
        // 2: index only archived news
        if ($this->indexerConfig['index_news_archived'] == 1) {
            $where[] = $queryBuilder->expr()->orX(
                $queryBuilder->expr()->eq(
                    'archive',
                    $queryBuilder->quote(0, \PDO::PARAM_INT)
                ),
                $queryBuilder->expr()->gt(
                    'archive',
                    $queryBuilder->quote(time(), \PDO::PARAM_INT)
                )
            );
        } elseif ($this->indexerConfig['index_news_archived'] == 2) {
            $where[] = $queryBuilder->expr()->andX(
                $queryBuilder->expr()->gt(
                    'archive',
                    $queryBuilder->quote(0, \PDO::PARAM_INT)
                ),
                $queryBuilder->expr()->lt(
                    'archive',
                    $queryBuilder->quote(time(), \PDO::PARAM_INT)
                )
            );
        }

        $res = $queryBuilder
            ->select($fields)
            ->from($table)
            ->where(...$where)
            ->execute();

        $indexedNewsCounter = 0;
        $resCount = $res->rowCount();

        if ($resCount) {
            while (($newsRecord = $res->fetch())) {

                $this->pObj->logger->debug('Indexing news record "' . $newsRecord['title'] .'"', [
                    'uid' => $newsRecord['uid'],
                    'pid' => $newsRecord['pid']
                ]);

                // get category data for this news record (list of
                // assigned categories and single view from category, if it exists)
                $categoryData = $this->getCategoryData($newsRecord);

                // If mode equals 2 ('choose categories for indexing')
                // check if the current news record has one of the categories
                // assigned that should be indexed.
                // mode 1 means 'index all news no matter what category
                // they have'
                if ($this->indexerConfig['index_news_category_mode'] == '2') {
                    $isInList = false;
                    foreach ($categoryData['uid_list'] as $catUid) {
                        // if category was found in list, set isInList
                        // to true and break further processing.
                        if (GeneralUtility::inList(
                            $this->indexerConfig['index_extnews_category_selection'],
                            $catUid
                        )
                        ) {
                            $isInList = true;
                            break;
                        }
                    }

                    // if category was not fount stop further processing
                    // and continue with next news record
                    if (!$isInList) {
                        continue;
                    }
                }

                // compile the information which should go into the index:
                // title, teaser, bodytext
                $type = 'news';
                $title = strip_tags($newsRecord['title']);
                $abstract = strip_tags($newsRecord['teaser']);
                $content = strip_tags($newsRecord['bodytext']);

                // add additional fields to the content:
                // alternative_title, author, author_email, keywords
                if (isset($newsRecord['author'])) {
                    $content .= "\n" . strip_tags($newsRecord['author']);
                }
                if (isset($newsRecord['author_email'])) {
                    $content .= "\n" . strip_tags($newsRecord['author_email']);
                }
                if (!empty($newsRecord['keywords'])) {
                    $content .= "\n" . $newsRecord['keywords'];
                }

                // index attached content elements
                $contentElements = $this->getAttachedContentElements($newsRecord);
                $content .= $this->getContentFromContentElements($contentElements);

                // create content
                $fullContent = '';
                if (isset($abstract)) {
                    $fullContent .= $abstract . "\n";
                }
                $fullContent .= $content;

                // make it possible to modify the indexerConfig via hook
                $indexerConfig = $this->indexerConfig;

                // create params and custom single view page:
                // if it is a default news (type = 0), add params
                // if it is an internal page (type = 1), put that into the "targetpid" field
                // if it is an external url (type = 2), put that into the "params" field
                if ($newsRecord['type'] == 1) {
                    $indexerConfig['targetpid'] = $newsRecord['internalurl'];
                    $params = '';
                } else {
                    if ($newsRecord['type'] == 2) {
                        $type = 'external:news';
                        $params = $newsRecord['externalurl'];
                    } else {
                        // overwrite the targetpid if there is a category assigned
                        // which has its own single view page
                        if ($categoryData['single_pid']) {
                            $indexerConfig['targetpid'] = $categoryData['single_pid'];
                        }

                        // create params for news single view, example:
                        // index.php?id=123&tx_news_pi1[news]=9&tx_news_pi1[controller]=News&tx_news_pi1[action]=detail
                        // NOTE that translated news records are linked by their l10n_parent uid (and overlaid later)
                        $paramsSingleView['tx_news_pi1']['news'] = $newsRecord['l10n_parent']
                            ? $newsRecord['l10n_parent']
                            : $newsRecord['uid'];
                        $paramsSingleView['tx_news_pi1']['controller'] = 'News';
                        $paramsSingleView['tx_news_pi1']['action'] = 'detail';
                        $params = '&' . http_build_query($paramsSingleView, null, '&');
                        $params = rawurldecode($params);
                    }
                }

                // add tags from pages
                if ($indexerConfig['index_use_page_tags']) {
                    $tags = $this->pageRecords[intval($newsRecord['pid'])]['tags'];
                } else {
                    $tags = '';
                }

                // add keywords from ext:news as tags
                $tags = $this->addTagsFromNewsKeywords($tags, $newsRecord);

                // add tags from ext:news as tags
                $tags = $this->addTagsFromNewsTags($tags, $newsRecord);

                // add categories from from ext:news as tags
                $tags = $this->addTagsFromNewsCategories($tags, $categoryData);

                // add system categories as tags
                SearchHelper::makeSystemCategoryTags($tags, $newsRecord['uid'], $table);

                // set additional fields
                $additionalFields = array();
                $additionalFields['orig_uid'] = $newsRecord['uid'];
                $additionalFields['orig_pid'] = $newsRecord['pid'];
                $additionalFields['sortdate'] = $newsRecord['crdate'];
                if (isset($newsRecord['datetime']) && $newsRecord['datetime'] > 0) {
                    $additionalFields['sortdate'] = $newsRecord['datetime'];
                }

                // hook for custom modifications of the indexed data, e.g. the tags
                if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['modifyExtNewsIndexEntry'])) {
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['modifyExtNewsIndexEntry'] as
                             $_classRef) {
                        $_procObj = &\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($_classRef);
                        $_procObj->modifyExtNewsIndexEntry(
                            $title,
                            $abstract,
                            $fullContent,
                            $params,
                            $tags,
                            $newsRecord,
                            $additionalFields,
                            $indexerConfig,
                            $categoryData,
                            $this
                        );
                    }
                }

                // store this record to the index
                $this->pObj->storeInIndex(
                    $indexerConfig['storagepid'],    // storage PID
                    $title,                          // page title
                    $type,                           // content type
                    $indexerConfig['targetpid'],     // target PID: where is the single view?
                    $fullContent,                    // indexed content, includes the title (linebreak after title)
                    $tags,                           // tags
                    $params,                         // typolink params for singleview
                    $abstract,                       // abstract
                    $newsRecord['sys_language_uid'], // language uid
                    $newsRecord['starttime'],        // starttime
                    $newsRecord['endtime'],          // endtime
                    $newsRecord['fe_group'],         // fe_group
                    false,                           // debug only?
                    $additionalFields                // additional fields added by hooks
                );
                $indexedNewsCounter++;
            }

            $logMessage = 'Indexer "' . $this->indexerConfig['title'] . '" finished'
                . ' ('.$indexedNewsCounter.' records processed)';
            $this->pObj->logger->info($logMessage);
            $content = '<p><b>Indexer "' . $this->indexerConfig['title'] . '":</b><br />' . "\n"
                . $indexedNewsCounter . ' News have been indexed .</p> ' . "\n";

            $content .= $this->showErrors();
            $content .= $this->showTime();
        }
        return $content;
    }
1366102
def positioning_headlines(headlines):
    
    left_just = False
    for row in headlines:
        if row[-1] == 1:
            left_just = True
            break
    if not left_just:
        for row in headlines:
            row[-1] -= 1
    return headlines