Preview an harvesting from a source created with the given parameters
541283
def preview_from_config(name, url, backend,
                        description=None,
                        frequency=DEFAULT_HARVEST_FREQUENCY,
                        owner=None,
                        organization=None,
                        config=None,
                        ):
    ''''''
    if owner and not isinstance(owner, User):
        owner = User.get(owner)

    if organization and not isinstance(organization, Organization):
        organization = Organization.get(organization)

    source = HarvestSource(
        name=name,
        url=url,
        backend=backend,
        description=description,
        frequency=frequency or DEFAULT_HARVEST_FREQUENCY,
        owner=owner,
        organization=organization,
        config=config,
    )
    cls = backends.get(current_app, source.backend)
    max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS']
    backend = cls(source, dryrun=True, max_items=max_items)
    return backend.harvest()
448718
def create_generate(kind, project, resource, offset):
    
    generate = eval('Generate' + kind.title())
    return generate(project, resource, offset)
1116733
function() {
                    var name, args;

                    if (!(name = /^([\w\-]+|%)\(/.exec(chunks[j]))) return;

                    name = name[1];

                    if (name === 'url') {
                        // url() is handled by the url parser instead
                        return null;
                    } else {
                        i += name.length;
                    }

                    $('('); // Parse the '(' and consume whitespace.

                    args = $(this.entities['arguments']);

                    if (!$(')')) return;

                    if (name) {
                        return new tree.Call(name, args, env.filename, i);
                    }
                }
880152
def load_parameters(self, source):
        """"""
        with open(source) as parameters_source:
            return json.loads(parameters_source.read())
1235790
function (param, options, callback) {
              embedProcessor.log(param.worker + ' started with parameters = ', param);
              param.status = true;
              param.duration = false;
              param.duration_formatted = false;
              param.thumbnail_url = false;
              param.favicon_url = '';
              param.service_name = '';
              param.provider_url = '';
              param.html = false;
              param.views = false;
              if (embedProcessor._sources[param.source] && embedProcessor._sources[param.source].prepareEmbedCode) {
                param = embedProcessor._sources[param.source].prepareEmbedCode(param);
              }
              param = embedProcessor._paramEmbedCodeNormalizer(param);
              embedProcessor.log(param.worker + ' receive parameters = ', param);
              callback(param);
            }
602538
def show_preview(viewer_path, pdf_file_name):
    """"""
    try:
        cmd = [viewer_path, pdf_file_name]
        run_external_subprocess_in_background(cmd)
    except (subprocess.CalledProcessError, OSError, IOError) as e:
        print("\nWarning from pdfCropMargins: The argument to the '--viewer' option:"
              "\n   ", viewer_path, "\nwas not found or failed to execute correctly.\n",
              file=sys.stderr)
    return
536979
def harvest(self, text):
        """"""
        for match in self.harvest_regex.finditer(text):
            # TODO: optionally validate before yielding?
            # TODO: keep a list of harvested but not validated?
            yield match.group().replace('..', '.')
452940
private String[] getProduces( Produces baseProduces, ExecutableElement method ) {
        Produces localProduces = method.getAnnotation( Produces.class );
        return localProduces != null ? localProduces.value() : baseProduces != null ? baseProduces.value() : null;
    }
234035
def scrape(cls, start, end, output):
        
        # Logger setting
        logging.basicConfig(
            level=logging.INFO,
            format="time:%(asctime)s.%(msecs)03d" + "\tmessage:%(message)s",
            datefmt="%Y-%m-%d %H:%M:%S"
        )

        # validate
        for param_day in ({'name': 'Start Day', 'value': start}, {'name': 'End Day', 'value': end}):
            try:
                cls._validate_datetime(param_day['value'])
            except (validators.Invalid, MlbAmException) as e:
                raise MlbAmException('{msg} a {name}.'.format(name=param_day['name'], msg=e.msg))
        cls._validate_datetime_from_to(start, end)

        # Download
        logging.info('->- MLBAM dataset download start')
        mlb = MlbAm(os.path.dirname(os.path.abspath(__file__)), output, cls._days(start, end))
        mlb.download()
        logging.info('-<- MLBAM dataset download end')
11050
def previewed_data(hosts, commands)
      @commands = commands
      hosts.map do |each|
        @host_param = each
        # [for a host] operation
        ready_to_open_host_session do |spawn_cmd|
          whole_previewed_parameters(spawn_cmd)
        end
      end
    end
845022
public void actionPreview() throws IOException, JspException {

        try {
            // save content of the editor only to the temporary file
            setEditorValues(getElementLocale());
            writeContent();
            CmsObject cloneCms = getCloneCms();
            CmsUUID tempProjectId = OpenCms.getWorkplaceManager().getTempFileProjectId();
            cloneCms.getRequestContext().setCurrentProject(getCms().readProject(tempProjectId));
            // remove eventual release & expiration date from temporary file to make preview work
            cloneCms.setDateReleased(getParamTempfile(), CmsResource.DATE_RELEASED_DEFAULT, false);
            cloneCms.setDateExpired(getParamTempfile(), CmsResource.DATE_EXPIRED_DEFAULT, false);

        } catch (CmsException e) {
            // show error page
            showErrorPage(this, e);
        }

        // get preview uri from content handler
        String previewUri = m_content.getHandler().getPreview(getCms(), m_content, getParamTempfile());

        // create locale request parameter
        StringBuffer param = new StringBuffer(8);
        if (previewUri.indexOf('?') != -1) {
            param.append("&");
        } else {
            param.append("?");
        }
        param.append(CmsLocaleManager.PARAMETER_LOCALE);
        param.append("=");
        param.append(getParamElementlanguage());

        // redirect to the temporary file with currently active element language or to the specified preview uri
        sendCmsRedirect(previewUri + param);
    }
1108870
static function preview( $args )
    {
        $http = eZHTTPTool::instance();
        $handler = self::getHandler( $args );
        if ( !$handler->canUpload() )
        {
            throw new RuntimeException(
                ezpI18n::tr(
                    'extension/ezjscore/ajaxuploader',
                    'You are not allowed to upload a file.'
                )
            );
        }

        $file = $http->postVariable( 'UploadFile', false );
        $fileHandler = eZClusterFileHandler::instance();
        if ( $file === false
                || !$fileHandler->fileExists( $file )
                || !$fileHandler->fileFetch( $file ) )
        {
            throw new RuntimeException(
                ezpI18n::tr(
                    'extension/ezjscore/ajaxuploader', 'Unable to retrieve the uploaded file.'
                )
            );
        }
        else
        {
            $tmpFile = eZSys::cacheDirectory() . '/' .
                        eZINI::instance()->variable( 'FileSettings', 'TemporaryDir' ) . '/' .
                        str_replace(
                            array( '/', '\\' ), '_',
                            $http->postVariable( 'UploadOriginalFilename' )
                        );
            eZFile::rename( $file, $tmpFile, true );
            $fileHandler->fileDelete( $file );
            $fileHandler->fileDeleteLocal( $file );
        }

        $contentObject = $handler->createObject(
            $tmpFile,
            $http->postVariable( 'UploadLocation', false ),
            $http->postVariable( 'UploadName', '' )
        );
        unlink( $tmpFile );

        $tpl = eZTemplate::factory();
        $tpl->setVariable( 'object', $contentObject );
        return array(
            'meta_data' => $handler->serializeObject( $contentObject ),
            'html' => $tpl->fetch( 'design:ajaxuploader/preview.tpl' )
        );
    }
1211301
def _view(self, filepath, format):
        """"""
        methodnames = [
            '_view_%s_%s' % (format, backend.PLATFORM),
            '_view_%s' % backend.PLATFORM,
        ]
        for name in methodnames:
            view_method = getattr(self, name, None)
            if view_method is not None:
                break
        else:
            raise RuntimeError('%r has no built-in viewer support for %r '
                'on %r platform' % (self.__class__, format, backend.PLATFORM))
        view_method(filepath)
367752
def produceResource(self, request, segments, webViewer):
        
        def thunk():
            cr = getattr(self, 'createResource', None)
            if cr is not None:
                return cr()
            else:
                return self.createResourceWith(webViewer)
        return self._produceIt(segments, thunk)
861128
def _createReservoir(self, linkResult, replaceParamFile):
        
        # Extract header variables from link result object
        header = linkResult['header']

        # Cases
        if linkResult['type'] == 'LAKE':
            # Lake handler
            initWSE = vrp(header['initwse'], replaceParamFile)
            minWSE = vrp(header['minwse'], replaceParamFile)
            maxWSE = vrp(header['maxwse'], replaceParamFile)
            numPts = header['numpts']

        elif linkResult['type'] == 'RESERVOIR':
            # Reservoir handler
            initWSE = vrp(header['res_initwse'], replaceParamFile)
            minWSE = vrp(header['res_minwse'], replaceParamFile)
            maxWSE = vrp(header['res_maxwse'], replaceParamFile)
            numPts = header['res_numpts']

        # Initialize GSSHAPY Reservoir object
        reservoir = Reservoir(initWSE=initWSE,
                              minWSE=minWSE,
                              maxWSE=maxWSE)

        # Initialize GSSHAPY StreamLink object
        link = StreamLink(linkNumber=int(header['link']),
                          type=linkResult['type'],
                          numElements=numPts)

        # Associate StreamLink with ChannelInputFile
        link.channelInputFile = self

        # Associate Reservoir with StreamLink
        reservoir.streamLink = link

        # Create ReservoirPoint objects
        for p in linkResult['points']:
            # Initialize GSSHAPY ReservoirPoint object
            resPoint = ReservoirPoint(i=p['i'],
                                      j=p['j'])

            # Associate ReservoirPoint with Reservoir
            resPoint.reservoir = reservoir

        return link
1144507
def harvest(lancet, config_section):
    """"""
    url, username, password = lancet.get_credentials(
        config_section, credentials_checker
    )

    project_id_getter = lancet.get_instance_from_config(
        "timer", "project_id_getter", lancet
    )
    task_id_getter = lancet.get_instance_from_config(
        "timer", "task_id_getter", lancet
    )

    client = HarvestPlatform(
        server=url,
        basic_auth=(username, password),
        project_id_getter=project_id_getter,
        task_id_getter=task_id_getter,
    )
    lancet.call_on_close(client.close)
    return client
1016130
def get_params_from_page(path, file_name, method_count):
    
    # open the rendered file.
    file_name = file_name.replace(".rst", "")
    file_path = "{0}/../_build/html/endpoints/{1}/index.html".format(
        path, file_name)
    soup = bs4.BeautifulSoup(open(file_path))

    # Pull out the relevant section
    section = soup.find_all('div', class_='section')[method_count]

    # get the tbody of the params table
    tbody = section.find('tbody')
    params = []
    if tbody is not None:
        for row in tbody.find_all('tr'):
            name, param_type, required, description = row.find_all('td')
            required = required.text == 'Yes'
            param = dict(
                name=name.text,
                type=param_type.text,
                required=required,
                description=description.text
            )
            params.append(param)
    params = sorted(params, key=lambda k: not k['required'])
    return params