Robust as possible

        Attempts to create the page
        If any of the functions used to attach content to the page
        fail, keep going, keep a record of those errors in a context dict
        return the page and the context dict in a tuple
511162
def create_page(self, content, class_, record_keeper=None, logger=None):
        '''
        
        '''
        fields, nested_fields = separate_fields(content)

        foreign_id = content.pop('id')

        # remove unwanted fields
        if 'latest_revision_created_at' in content:
            content.pop('latest_revision_created_at')

        page = class_(**fields)

        # create functions to attach attributes
        function_args_mapping = (
            # add_section_time
            (add_json_dump, ("time", nested_fields, page)),
            # add_tags
            (add_list_of_things, ("tags", nested_fields, page)),
            # add_metadata_tags
            (add_list_of_things, ("metadata_tags", nested_fields, page)),

            # attach_image
            (attach_image, ("image", nested_fields, page, record_keeper)),
            # attach_social_media_image
            (attach_image, ("social_media_image", nested_fields,
                            page, record_keeper)),
            # attach_banner_image
            (attach_image, ("banner", nested_fields, page, record_keeper)),
        )

        for mapping in function_args_mapping:
            function = mapping[0]
            _args = mapping[1]
            try:
                function(*_args)
            except Exception as e:
                if logger:
                    logger.log(
                        ERROR,
                        "Failed to create page content",
                        {
                            "foreign_page_id": foreign_id,
                            "exception": e,
                            "function": function.__name__,
                        })

        # Handle content in nested_fields
        body = add_stream_fields(nested_fields, page)
        # body has not been added as it contains reference to pages
        if body:
            record_keeper.article_bodies[foreign_id] = body

        # Handle relationships in nested_fields
        if record_keeper:
            record_relation_functions = [
                record_keeper.record_nav_tags,
                record_keeper.record_recommended_articles,
                record_keeper.record_reaction_questions,
                record_keeper.record_related_sections,
                record_keeper.record_section_tags,
                record_keeper.record_banner_page_link,
            ]

            for function in record_relation_functions:
                try:
                    function(nested_fields, foreign_id)
                except Exception as e:
                    if logger:
                        logger.log(
                            ERROR,
                            "Failed to record content",
                            {
                                "foreign_page_id": foreign_id,
                                "exception": e,
                                "function": function.__name__,
                            })

        return page
192880
def create_page(pagename):
    
    page = pagename.lstrip("/").rstrip("/")
    _, _ext = os.path.splitext(pagename)

    # If the file doesn't have an extension, we'll just create one
    if not _ext or _ext == "":
        page += ".jade"

    if not page.endswith(PAGE_FORMAT):
        error("Can't create '%s'" % page)
        print("Invalid filename format")
        print("Filename must be in: '%s'" % " | ".join(PAGE_FORMAT))
    else:
        engine = Yass(CWD)
        markup = "jade"
        if page.endswith(".md"):
            markup = "md"
        if page.endswith(".html"):
            markup = "html"

        dest_file = os.path.join(engine.pages_dir, page)
        dest_dir = os.path.dirname(dest_file)

        content = TPL_HEADER
        content += TPL_BODY[markup]

        if os.path.isfile(dest_file):
            error("File exists already")
            print("Location: %s" % dest_file)

        else:
            if not os.path.isdir(dest_dir):
                os.makedirs(dest_dir)
            with open(dest_file, "w") as f:
                f.write(content)

            print("New page created: '%s'" % page)
            print("Location: %s" % dest_file)


    footer()
146125
def build_pages(self):
        
        for root, _, files in os.walk(self.pages_dir):
            base_dir = root.replace(self.pages_dir, "").lstrip("/")
            if not base_dir.startswith("_"):
                for f in files:
                    src_file = os.path.join(base_dir, f)
                    self._build_page(src_file)
183884
def get_page_objects_by_type(context, object_type):
    
    try:
        objects = context['page']['content'][object_type]
    except KeyError:
        raise template.TemplateSyntaxError('wrong content type: {0:>s}'.format(object_type))
    return objects
1138131
def getPage(url, contextFactory=None, *args, **kwargs):
    
    scheme, host, port, path = client._parse(url)
    factory = client.HTTPClientFactory(url, *args, **kwargs)
    if scheme == 'https':
        if contextFactory is None:
            raise RuntimeError, 'must provide a contextFactory'
        conn = reactor.connectSSL(host, port, factory, contextFactory)
    else:
        conn = reactor.connectTCP(host, port, factory)

    return factory
512116
def pages_breadcrumb(context, page, url='/'):
    
    lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
    page = get_page_from_string_or_id(page, lang)
    pages_navigation = None
    if page:
        pages_navigation = page.get_ancestors()
    context.update({'pages_navigation': pages_navigation, 'page': page})
    return context
1371874
def get_pagination_context(
    page, pages_to_show=11, url=None, size=None, extra=None, parameter_name="page"
):
    
    pages_to_show = int(pages_to_show)
    if pages_to_show < 1:
        raise ValueError(
            "Pagination pages_to_show should be a positive integer, you specified {pages}".format(
                pages=pages_to_show
            )
        )
    num_pages = page.paginator.num_pages
    current_page = page.number
    half_page_num = int(floor(pages_to_show / 2))
    if half_page_num < 0:
        half_page_num = 0
    first_page = current_page - half_page_num
    if first_page <= 1:
        first_page = 1
    if first_page > 1:
        pages_back = first_page - half_page_num
        if pages_back < 1:
            pages_back = 1
    else:
        pages_back = None
    last_page = first_page + pages_to_show - 1
    if pages_back is None:
        last_page += 1
    if last_page > num_pages:
        last_page = num_pages
    if last_page < num_pages:
        pages_forward = last_page + half_page_num
        if pages_forward > num_pages:
            pages_forward = num_pages
    else:
        pages_forward = None
        if first_page > 1:
            first_page -= 1
        if pages_back is not None and pages_back > 1:
            pages_back -= 1
        else:
            pages_back = None
    pages_shown = []
    for i in range(first_page, last_page + 1):
        pages_shown.append(i)
        # Append proper character to url
    if url:
        # Remove existing page GET parameters
        url = force_text(url)
        url = re.sub(r"\?{0}\=[^\&]+".format(parameter_name), "?", url)
        url = re.sub(r"\&{0}\=[^\&]+".format(parameter_name), "", url)
        # Append proper separator
        if "?" in url:
            url += "&"
        else:
            url += "?"
            # Append extra string to url
    if extra:
        if not url:
            url = "?"
        url += force_text(extra) + "&"
    if url:
        url = url.replace("?&", "?")
    # Set CSS classes, see http://getbootstrap.com/components/#pagination
    pagination_css_classes = ["pagination"]
    if size == "small":
        pagination_css_classes.append("pagination-sm")
    elif size == "large":
        pagination_css_classes.append("pagination-lg")
        # Build context object
    return {
        "bootstrap_pagination_url": url,
        "num_pages": num_pages,
        "current_page": current_page,
        "first_page": first_page,
        "last_page": last_page,
        "pages_shown": pages_shown,
        "pages_back": pages_back,
        "pages_forward": pages_forward,
        "pagination_css_classes": " ".join(pagination_css_classes),
        "parameter_name": parameter_name,
    }
310086
def get_page(url):
    
    response = requests.get(url)
    handle_error(response, 200)
    data = response.json()
    return data
846553
async function createPages({ actions: { createPage } }) {
  if (includeDevPages) {
    createPage({
      path: '/dev/logos',
      component: require.resolve('./frontend/components/development/logo-page'),
    })
  }

  categories.forEach(category => {
    const { id } = category
    createPage({
      path: `/category/${id}`,
      component: require.resolve('./frontend/components/main'),
      // `context` provided here becomes `props.pageContext` on the page.
      context: { category },
    })
  })
}
360212
def page(content, pagecallback=prompt):
    
    width = getwidth()
    height = getheight()
    pagenum = 1

    try:
        try:
            line = content.next().rstrip("\r\n")
        except AttributeError:
            # Python 3 compatibility
            line = content.__next__().rstrip("\r\n")
    except StopIteration:
        pagecallback(pagenum)
        return

    while True:     # page cycle
        linesleft = height-1 # leave the last line for the prompt callback
        while linesleft:
            linelist = [line[i:i+width] for i in range(0, len(line), width)]
            if not linelist:
                linelist = ['']
            lines2print = min(len(linelist), linesleft)
            for i in range(lines2print):
                if WINDOWS and len(line) == width:
                    # avoid extra blank line by skipping linefeed print
                    echo(linelist[i])
                else:
                    print((linelist[i]))
            linesleft -= lines2print
            linelist = linelist[lines2print:]

            if linelist: # prepare symbols left on the line for the next iteration
                line = ''.join(linelist)
                continue
            else:
                try:
                    try:
                        line = content.next().rstrip("\r\n")
                    except AttributeError:
                        # Python 3 compatibility
                        line = content.__next__().rstrip("\r\n")
                except StopIteration:
                    pagecallback(pagenum)
                    return
        if pagecallback(pagenum) == False:
            return
        pagenum += 1
1256767
def do_page_wrap(self, args: List[str]):
        
        if not args:
            self.perror('page_wrap requires a path to a file as an argument', traceback_war=False)
            return
        self.page_file(args[0], chop=False)
250603
function createPage(casper) {
    /*eslint max-statements:0*/
    "use strict";
    var mainPage = require('webpage').create();
    mainPage.isPopup = false;

    var onClosing = function onClosing(closedPopup) {
        if (closedPopup.isPopup) {
            if (casper.page !== null && casper.page.id === closedPopup.id) {
                casper.page = casper.mainPage;
            }
            casper.popups.clean();
            casper.emit('popup.closed', closedPopup);
        } else {
            casper.page = null;
            casper.emit('page.closed', closedPopup);
        }
    };

    var onLoadFinished = function onLoadFinished(status) {
        this.windowNameBackUp = this.windowName;
        /*eslint max-statements:0*/
        if (status !== "success") {
            casper.emit('load.failed', {
                status:      status,
                http_status: casper.currentHTTPStatus,
                url:         this.url
            });
            var message = 'Loading resource failed with status=' + status;
            if (casper.currentHTTPStatus) {
                message += f(' (HTTP %d)', casper.currentHTTPStatus);
            }
            message += ': ' + casper.requestUrl;
            casper.log(message, "warning");
            casper.navigationRequested = false;
            this.browserInitializing = false;
            if (utils.isFunction(casper.options.onLoadError)) {
                casper.options.onLoadError.call(casper, casper, casper.requestUrl, status);
            }
        }

        var index = 0, currentPage = casper.page;
        casper.page = this;
        this.switchToMainFrame();
        for (var l = this.frames.length; index < l ; index++) {
            try {
                casper.switchToChildFrame(this.frames[index]);
            } catch(e) {
                break;
            }
        }
        this.framesReloaded = this.frames.slice(index);
        this.frames = this.frames.slice(0, index);

        if (this.framesReloaded.length !== 0) {
            casper.emit('frame.reset', this.framesReloaded);
        }
        casper.page = currentPage;

        // local client scripts
        casper.injectClientScripts(this);
        // remote client scripts
        casper.includeRemoteScripts(this);
        // Client-side utils injection
        casper.injectClientUtils(this);
        // history
        casper.history.push(casper.getCurrentUrl());
        casper.emit('load.finished', status);
        this.loadInProgress = false;
        if (this.isPopup) {
            casper.emit('popup.loaded', this);
        } else {
            casper.emit('page.loaded', this);
        }
    };

    var onLoadStarted = function onLoadStarted() {
        // in some case, there is no navigation requested event, so
        // be sure that browserInitializing is false to not block checkStep()
        this.browserInitializing = false;
        this.loadInProgress = true;
        casper.emit('load.started');
    };

    var onNavigationRequested = function onNavigationRequested(url, type, willNavigate, isMainFrame) {
        casper.log(f('Navigation requested: url=%s, type=%s, willNavigate=%s, isMainFrame=%s',
                     url, type, willNavigate, isMainFrame), "debug");
        this.browserInitializing = false;
        casper.page.switchToMainFrame();
        if (isMainFrame && casper.requestUrl !== url) {
            var currentUrl = casper.requestUrl;
            var newUrl = url;
            var pos = currentUrl.indexOf('#');
            if (pos !== -1) {
                currentUrl = currentUrl.substring(0, pos);
            }
            pos = newUrl.indexOf('#');
            if (pos !== -1) {
                newUrl = newUrl.substring(0, pos);
            }
            // for URLs that are only different by their hash part
            // or if navigation locked (willNavigate == false)
            // don't turn navigationRequested to true, because
            // there will not be loadStarted, loadFinished events
            // so it could cause issues (for exemple, checkStep that
            // do no execute the next step -> infinite loop on checkStep)
            if (willNavigate && currentUrl !== newUrl) {
                casper.navigationRequested = true;
            }
            if (willNavigate) {
                casper.requestUrl = url;
            }
        }
        casper.emit('navigation.requested', url, type, willNavigate, isMainFrame);
    };
    
    var onPageCreated = function onPageCreated(page) {
        page.isPopup = (typeof page.isPopup === "undefined") ? true : false;
        page.id = new Date().getTime();
        page.browserInitializing = false;
        page.loadInProgress = false; 
        page.windowNameBackUp = page.windowName;
        page.frames = [];
        page.framesReloaded = [];
        page.context = {
            "x": 0,
            "y": 0
        };

        page.settings.loadImagesValue = page.settings.loadImages;
        Object.defineProperty(page.settings,'loadImages', {
            get: function() { 
                return page.settings.loadImagesValue;
            },
            set: function(newValue) {
                page.settings.loadImagesValue = newValue;
                if (typeof page.clearMemoryCache === 'function') {
                    page.clearMemoryCache();
                }
            }
        });

        page.onClosing =  function() {
            var p = page;
            return function() {
                return onClosing.apply(p, arguments);
            };
        }();
        page.onLoadFinished = function() {
            var p = page;
            return function() {
                return onLoadFinished.apply(p, arguments);
            };
        }();
        page.onLoadStarted = function() {
            var p = page;
            return function() {
                return onLoadStarted.apply(p, arguments);
            };
        }();
        page.onNavigationRequested = function() {
            var p = page;
            return function() {
                return onNavigationRequested.apply(p, arguments);
            };
        }();
        page.onPageCreated = onPageCreated;

        page.onAlert = function onAlert(message) {
            casper.log('[alert] ' + message, "info", "remote");
            casper.emit('remote.alert', message);
            if (utils.isFunction(casper.options.onAlert)) {
                casper.options.onAlert.call(casper, casper, message);
            }
        };
        page.onConfirm = function onConfirm(message) {
            if ('page.confirm' in casper._filters) {
                return casper.filter('page.confirm', message);
            }
            return true;
        };
        page.onConsoleMessage = function onConsoleMessage(msg) {
            // client utils casper console message
            var consoleTest = /^\[casper\.echo\]\s?([\s\S]*)/.exec(msg);
            if (consoleTest && consoleTest.length === 2) {
                casper.echo(consoleTest[1]);
                return; // don't trigger remote.message event for these
            }
            // client utils log messages
            var logLevel = "info",
                logTest = /^\[casper:(\w+)\]\s?([\s\S]*)/m.exec(msg);
            if (logTest && logTest.length === 3) {
                logLevel = logTest[1];
                msg = logTest[2];
                casper.log(msg, logLevel, "remote");
            } else {
                casper.emit('remote.message', msg);
            }
        };

        page.onCallback = function onCallback(data){
            casper.emit('remote.callback', data);
        };
        page.onError = function onError(msg, trace) {
            casper.emit('page.error', msg, trace);
        };
        page.onFilePicker = function onFilePicker(olderFile) {
            return casper.filter('page.filePicker', olderFile);
        };
        page.onFileDownload = function onFileDownload(url, data) {
            if ('fileDownload' in casper._filters) {
                return casper.filter('fileDownload', url, data);
            }
            casper.log("File to download : aborted", "debug");
            return null;
        };
        page.onFileDownloadError = function onFileDownloadError(error) {
            return casper.emit('fileDownloadError', error);
        };
        page.onInitialized = function onInitialized() {
            casper.emit('page.initialized', page);
            if (utils.isFunction(casper.options.onPageInitialized)) {
                casper.log("Post-configuring WebPage instance", "debug");
                casper.options.onPageInitialized.call(casper, page);
            }
        };
        page.onLongRunningScript = function onLongRunningScript(message) {
            casper.emit('remote.longRunningScript', page, message);
        };
        page.onPrompt = function onPrompt(message, value) {
            return casper.filter('page.prompt', message, value);
        };
        page.onResourceReceived = function onResourceReceived(resource) {
            http.augmentResponse(resource);
            casper.emit('resource.received', resource);
            if (utils.isFunction(casper.options.onResourceReceived)) {
                casper.options.onResourceReceived.call(casper, casper, resource);
            }
            casper.handleReceivedResource(resource);
        };
        page.onResourceRequested = function onResourceRequested(requestData, request) {
            casper.emit('resource.requested', requestData, request);
            var checkUrl = ((phantom.casperEngine === 'phantomjs' && utils.ltVersion(phantom.version, '2.1.0')) ||
                       (phantom.casperEngine === 'slimerjs' && utils.ltVersion(slimer.version, '0.10.0'))) ? utils.decodeUrl(requestData.url) : requestData.url;
            if (checkUrl === casper.requestUrl) {
                casper.emit('page.resource.requested', requestData, request);
            }
            if (utils.isFunction(casper.options.onResourceRequested)) {
                casper.options.onResourceRequested.call(casper, casper, requestData, request);
            }
            casper.requestData[requestData.id] = requestData;
        };
        page.onResourceError = function onResourceError(resourceError) {
            casper.emit('resource.error', resourceError);
        };
        page.onResourceTimeout = function onResourceTimeout(resourceError) {
            casper.emit('resource.timeout', resourceError);
        };
        page.onUrlChanged= function onUrlChanged(url) {
            casper.log(f('url changed to "%s"', url), "debug");
            casper.navigationRequested= false;
            casper.emit('url.changed', url);
        };

        if (page.isPopup) {
            casper.emit('popup.created', page);
            if (casper.options.pageSettings.userAgent !== defaultUserAgent) {
                page.customHeaders = {"User-Agent": casper.options.pageSettings.userAgent};
            }
            page.settings = utils.mergeObjects(page.settings, casper.options.pageSettings);
            if (utils.isClipRect(casper.options.clipRect)) {
                page.clipRect = casper.options.clipRect;
            }
            if (utils.isObject(casper.options.viewportSize)) {
                page.viewportSize = casper.options.viewportSize;
            }
            casper.popups.push(page);
        } else {
            casper.emit('page.created', page);
        }
    };
    onPageCreated(mainPage);
    return mainPage;
}
1366816
def create_page(title, space, parrent_page_id=nil)
            params = { 'type' => 'page',
                'title' => title,
                'space' => {'key' => space},
                'body' => {
                    'storage' => {
                        'value' => ("#{ @body_message.to_json.gsub("&&", "&amp;&amp;").gsub(/\\u001b.../, "   ") }").force_encoding('UTF-8'),
                        'representation' => 'storage'
                        }
                    }
                }
            if parrent_page_id
                params['ancestors'] = [{'type' => 'page', 'id' => parrent_page_id}]
            end

            uri = URI.parse(@base_url)
            https = Net::HTTP.new(uri.host,uri.port)
            https.use_ssl = true
            # https.set_debug_output $stderr
            req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
            req.basic_auth(@user, @password)
            req['Accept'] = 'application/json'
            req.body = "#{params.to_json}"
            response = https.request(req)
            response = JSON.parse(response.body)
            if response["statusCode"] == 400
                puts response.inspect
                puts req.body.inspect
                puts "Create page: Error reporting to confluence: #{response["message"]}"
                raise "Create page: Error reporting to confluence: #{response["message"]}"
            else
                puts "Reported page creation."
            end
        end
1147056
function createPage(filename) {
        let page = {
            path: filename,
            rawContent: fs.readFileSync(filename, "utf8"),
            name: path.basename(filename).replace(/\.[^/.]+$/, ""),
            filename: path.basename(filename),
            folder: path.dirname(filename),
            ext: path.extname(filename),
            userData: {}
        };
        page.isMarkdown = page.ext.toLocaleUpperCase() == ".MD";
        if (page.isMarkdown)
            page.ext = ".html";
        page.template = doT.template(page.rawContent, null, page.userData);
        page.outPath = path.join(path.relative(CONTENT, page.folder), page.name + page.ext);
        page.href = CONFIG.prefix + page.outPath;
        return page;
    }
382915
def storepage(self, page):
    
    try:
      return self._api_entrypoint.storePage(self._session_token, page)
    except XMLRPCError as e:
      log.error('Failed to store page %s: %s' % (page.get('title', '[unknown title]'), e))
      return None
890357
def pages(request, path=None, instance=None):
    

    if instance and instance.active:
        p = instance
    else:
        raise Http404()

    return render(request, p.tpl, get_page_tpl_ctx(p, request))
298103
def iterall(cls, connection=None, **kwargs):
        

        try:
            limit = kwargs['limit']
        except KeyError:
            limit = None

        try:
            page = kwargs['page']
        except KeyError:
            page = None

        def _all_responses():
            page = 1  # one based
            params = kwargs.copy()

            while True:
                params.update(page=page, limit=250)
                rsp = cls._make_request('GET', cls._get_all_path(), connection, params=params)
                if rsp:
                    yield rsp
                    page += 1
                else:
                    yield []  # needed for case where there is no objects
                    break

        if not (limit or page):
            for rsp in _all_responses():
                for obj in rsp:
                    yield cls._create_object(obj, connection=connection)

        else:
            response = cls._make_request('GET', cls._get_all_path(), connection, params=kwargs)
            for obj in cls._create_object(response, connection=connection):
                yield obj