text:
package ch.epfl.fbhack.geddit;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

import ch.epfl.fbhack.geddit.data.ApiRequester;
import ch.epfl.fbhack.geddit.data.ApiRequesterVote;
import ch.epfl.fbhack.geddit.data.ApiResponse;

public class Activity_Threads extends ActionBarActivity  implements AdapterView.OnItemClickListener{

    private String subgedditID;
    private final ArrayList<String> threadsTitles = new ArrayList<>();
    private final ArrayList<String> threadsScores = new ArrayList<>();
    private CustomAdapterThread adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_threads);

        ListView list = (ListView) findViewById(R.id.threads_list);
        adapter = new CustomAdapterThread(this, threadsTitles, threadsScores);
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);

        subgedditID = getIntent().getStringExtra("subgeddit-id");
        buildThreadsList();
    }

    @Override
    protected void onResume() {
        // This launch the request to the API => function processApiResponse is called when completed
        new ApiRequester(this).execute();

        super.onResume();
    }

    private void buildThreadsList() {
        threadsTitles.clear();
        threadsTitles.addAll(ApiResponse.getInstance().getThreadsTitlesFor(subgedditID));
        threadsScores.clear();
        threadsScores.addAll(ApiResponse.getInstance().getThreadsScoresFor(subgedditID));
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_threads, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if(id==R.id.action_add) {
            Intent intent = new Intent(Activity_Threads.this, Activity_Add_Thread.class);
            intent.putExtra(Activity_Add_Thread.SUBGEDDIT_ID_EXTRA, subgedditID);
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(Activity_Threads.this, Activity_Comments.class);
        intent.putExtra("subgedditID", subgedditID);
        intent.putExtra("threadIndex", position);
        startActivity(intent);
    }

    public void onUpvote(AdapterView<?> parent, View view, int position, long id) {
        ArrayList<String> threadsIDs = ApiResponse.getInstance().getThreadsIDsFor(subgedditID);
        new ApiRequesterVote(subgedditID, threadsIDs.get(position), "", true).execute();

        new ApiRequester(this).execute();
    }

    public void onDownvote(AdapterView<?> parent, View view, int position, long id) {
        ArrayList<String> threadsIDs = ApiResponse.getInstance().getThreadsIDsFor(subgedditID);
        new ApiRequesterVote(subgedditID, threadsIDs.get(position), "", false).execute();

        new ApiRequester(this).execute();
    }

    public void processApiResponse() {
        buildThreadsList();
    }
}


text:
package weatherhandler.data;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author Marijn Pool
 * @author René Kooi
 *
 *         MeasurementCache will create a LinkedList of Measurements for every
 *         station that exists
 */
public class MeasurementsCache {
    private static Map<Integer, List<Measurement>> cache = new HashMap<>();

    /**
     * Init the MeasurementCache
     */
    public static void init() {
        for (Station station : Stations.getStations()) {
            // TODO use a custom List class that also updates averages for every
            // data point whenever a new Measurement is added
            cache.put(station.getID(), new LinkedList<Measurement>());
        }
    }

    /**
     * @param station
     *            The station ID for the list that is returned
     * @return The List of Measurements that is returned based on the station ID
     */
    public static List<Measurement> getCache(Integer station) {
        return cache.get(station);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!-- Just need to instantiate the controller, and it will take care of showing the modal dialog -->
<span ng-controller="KisBpmAssignmentCtrl">
</span>


text:
import time
from behave import given, when, then

@given(u'update {id} {table} URL')  # noqa
def step_impl(context, id, table):
    context.driver.get(
        context.URL + '{}/update/id/{}'.format(table, id))

@given(u'create {table} URL')  # noqa
def step_impl(context, table):
    context.driver.get(
        context.URL + '{}/create/'.format(table, id))

@given(u'list {table} URL')  # noqa
def step_impl(context, table):
    context.driver.get(
        context.URL + '{}/'.format(table, id))

@given(u'User {name} form')  # noqa
def step_impl(context, name):
    user = context.dbsession.query(
        context.models['user']).filter_by(name=name).one()
    context.driver.get(context.URL + 'user/update/id/{}'.format(user.id))

@when(u'Change user name to {name}')  # noqa
def step_impl(context, name):
    name_field = context.driver.find_element_by_xpath(
        ".//*[starts-with(@id, 'deformField') and @name='name']"
    )
    name_field.clear()
    name_field.send_keys(name)
    context.driver.find_element_by_xpath(
        "//*[@name = 'form.submitted']"
    ).click()
    context.user = context.dbsession.query(
        context.models['user']).filter_by(name=name).one()

@when(u'Change {name} to {value}')  # noqa
def step_impl(context, name, value):
    field = context.driver.find_element_by_xpath(
        ".//*[starts-with(@id, 'deformField') and @name='{}']".format(name)
    )
    if value.lower() == 'toggle':
        field.click()
    else:
        field.clear()
        field.send_keys(value)

@then(u'{field} == {value}')  # noqa
def step_impl(context, field, value):
    field = context.driver.find_element_by_xpath(
        ".//*[starts-with(@id, 'deformField') and @name='{}']".format(field)
    )
    field_value = field.get_attribute('value')
    if value.lower() == 'true':
        assert field.is_selected()
    elif value.lower() == 'false':
        assert not field.is_selected()
    else:
        assert value == field_value

@when('Submitt')  # noqa
def step_impl(context):
    context.driver.find_element_by_xpath(
        "//*[@name = 'form.submitted']"
    ).click()

@when(u'Delete user {name}')  # noqa
def step_impl(context, name):
    user = context.dbsession.query(
        context.models['user']).filter_by(name=name).one()
    context.user_id = user.id
    context.driver.get(context.URL + 'user/delete/id/{}'.format(user.id))

@then(u'I should find user in user table')  # noqa
def step_impl(context):
    user = context.user
    time.sleep(2)
    context.driver.get(context.URL + 'user/update/id/{}'.format(user.id))
    assert user.name in context.driver.page_source

@then(u"I don't want find user in user table")  # noqa
def step_impl(context):
    user_id = context.user_id
    user = context.dbsession.query(
        context.models['user']).filter_by(id=user_id).first()
    assert user is None
    context.driver.get(context.URL + 'user/update/id/{}'.format(user_id))
    assert '404' in context.driver.page_source


text:
'use strict';
var po = require("./po");

describe('Privilege API', function () {

  var privilegeElem, privilegeForm;

  var expectPrivilegeFormOpened = function () {
    expect(privilegeElem.getCssValue('display')).not.toEqual('none');
    expect(privilegeForm.isPresent()).toBe(true);
    expect(privilegeForm.getCssValue('display')).not.toEqual('none');
  }
  var expectPrivilegeFormClosedWithNoPrivilege = function () {
    expect(privilegeElem.getCssValue('display')).not.toEqual('none');
    expect(privilegeForm.isPresent()).toBe(false);
  }
  var expectPrivilegeFormClosedWithPrivilege = function () {
    expect(privilegeElem.getCssValue('display')).toEqual('none');
    expect(privilegeForm.isPresent()).toBe(false);
  }

  var openPrivilegeForm = function () {
    expectPrivilegeFormClosedWithNoPrivilege();
    privilegeElem.click();
    expectPrivilegeFormOpened();
  }

  var getPrivilege = function () {
    openPrivilegeForm();
    privilegeForm.$$('button').get(0).click();
    expectPrivilegeFormClosedWithPrivilege();
  }

  beforeEach(function () {
    browser.manage().deleteAllCookies();
    browser.get('http://localhost:9000/');
    privilegeElem = po.getPrivilegeButton();
    privilegeForm = po.getPrivilegeForm();
  });

  describe("Open the privilege form", function () {
    it("should be able to open the privilege form", function () {
      openPrivilegeForm();
    });
    describe("Close the privilege form", function () {
      it('should close the privilege pop over, when clicking again over the privilege button', function () {
        openPrivilegeForm();
        privilegeElem.click();
        expectPrivilegeFormClosedWithNoPrivilege();
      });

      it('should close the privilege pop over, when clicking outside of privilege form', function () {
        openPrivilegeForm();
        browser.actions().mouseMove({x: -500, y: 400}).click().perform()
        expectPrivilegeFormClosedWithNoPrivilege();
      });

      it('should close the privilege pop over and get privilege for some time', function () {
        getPrivilege();
      });
    });
  });

  it('in privilege mode, if delete cookie, and refresh screen, privilege mode should be gone', function () {
    getPrivilege();
    browser.manage().deleteAllCookies();
    po.getRefreshButton().click();
    browser.waitForAngular();
    expectPrivilegeFormClosedWithNoPrivilege();
  });
});


text: start ms-settings:windowsupdate


text:
"""
Class to help creating a source detection pipeline with sep
by creating 'steps' with different configurations.
"""
import os
import numpy as np
from scipy import ndimage
from astropy.table import Table
from astropy.convolution import Gaussian2DKernel
from astropy.stats import gaussian_fwhm_to_sigma, gaussian_sigma_to_fwhm
import sep

from . import utils
from .utils import check_kwargs_defaults, check_random_state
from .log import logger

__all__ = ['SepStepperBase', 'SepLsstStepper', 'sep_ellipse_mask']

def _byteswap(arr):
    """
    If array is in big-endian byte order (as astropy.io.fits
    always returns), swap to little-endian for SEP.
    """
    if arr.dtype.byteorder=='>':
        arr = arr.byteswap().newbyteorder()
    return arr

def sep_ellipse_mask(sources, image_shape, scale=5.0):

    logger.info('building ellipse mask')

    mask = np.zeros(image_shape, dtype=bool)
    sep.mask_ellipse(mask, sources['x'], sources['y'], sources['a'],
                     sources['b'], sources['theta'], scale)

    logger.info('{:.2f}% of patch masked'.format(100 * mask.sum()/mask.size))

    return mask

class SepStepperBase(object):

    SEP_EXTRACT_DEFAULTS = dict(
        thresh=5.0, minarea=10, deblend_nthresh=32,
        deblend_cont=0.005, clean=True, clean_param=1.0,
        filter_type='conv', filter_num_fwhm=1.0
    )

    SEP_BACK_DEFAULTS = dict(bw=64, bh=64, fw=3, fh=3, fthresh=0.0)

    def __init__(self, config_fn=None, config={}):

        if config_fn is not None:
            config = utils.read_config(config_fn)

        self.extract_pixstack = config.pop('extract_pixstack', 300000)
        sep.set_extract_pixstack(self.extract_pixstack)
        self.step_kws = config
        self.sources = {}

    def setup_image(self, image_object, **kwargs):
        """
        Must make the followiing attributes:
            - image
            - noise_image (ndarray or number)
            - psf_fwhm (pixels)
        """
        raise NotImplementedError

    def _measure(self, img, sources, mask=None):

        logger.info('measuring source parameters')

        # HACK: issues with numerical precision
        # must have pi/2 <= theta <= npi/2
        sources[np.abs(np.abs(sources['theta']) - np.pi/2) < 1e-6] = np.pi/2

        for p in ['x', 'y', 'a', 'b', 'theta']:
            sources = sources[~np.isnan(sources[p])]

        # calculate "AUTO" parameters
        kronrad, krflag = sep.kron_radius(
            img, sources['x'], sources['y'], sources['a'], sources['b'],
            sources['theta'], 6.0, mask=mask)

        flux, fluxerr, flag = sep.sum_ellipse(
            img, sources['x'], sources['y'], sources['a'], sources['b'],
            sources['theta'], 2.5*kronrad, subpix=5, mask=mask)
        flag |= krflag  # combine flags into 'flag'

        sources = sources[~np.isnan(flux)]
        flux = flux[~np.isnan(flux)]
        sources = sources[flux > 0]
        flux = flux[flux > 0]

        mag_auto = utils.zpt - 2.5*np.log10(flux)
        r, flag = sep.flux_radius(
            img, sources['x'], sources['y'], 6.*sources['a'], 0.5,
            normflux=flux, subpix=5, mask=mask)

        sources['mag_auto'] = mag_auto
        sources['flux_auto'] = flux
        sources['flux_radius'] = r * utils.pixscale

        # approximate fwhm
        r_squared = sources['a']**2 + sources['b']**2
        sources['fwhm'] = 2 * np.sqrt(np.log(2) * r_squared) *  utils.pixscale

        q = sources['b'] / sources['a']
        area = np.pi * q * sources['flux_radius']**2
        sources['mu_ave_auto'] = sources['mag_auto']  + 2.5 * np.log10(2*area)

        area_arcsec = np.pi * (self.psf_fwhm/2)**2 * utils.pixscale**2
        flux, fluxerr, flag = sep.sum_circle(
            img, sources['x'], sources['y'], self.psf_fwhm/2,
            subpix=5, mask=mask)
        flux[flux<=0] = np.nan
        mu_0 = utils.zpt - 2.5*np.log10(flux / area_arcsec)

        sources['mu_0_aper'] = mu_0

        return sources

    def apply_mask(self, image, mask, inplace=True):
        img = image if inplace else image.copy()
        if type(self.noise_image) == np.ndarray:
            img[mask] = self.noise_image[mask]
        else:
            img[mask] = self.noise_image
        return img

    def run(self, step_name, mask=None):

        try:
            img = self.image.copy()
        except AttributeError:
            logger.error('You must setup image before running pipeline!')
            exit(1)

        logger.info('running ' + step_name)

        kws = self.step_kws[step_name].copy()

        sep_extract_kws = kws.pop('sep_extract_kws', {})
        sep_extract_kws = check_kwargs_defaults(sep_extract_kws,
                                                self.SEP_EXTRACT_DEFAULTS)

        sep_back_kws = kws.pop('sep_back_kws', {})
        sep_back_kws = check_kwargs_defaults(sep_back_kws,
                                             self.SEP_BACK_DEFAULTS)

        if mask is not None:
            logger.info('applying mask')
            sep_extract_kws['mask'] = mask
            sep_back_kws['mask'] = mask

        # define gaussian kernel for detection
        # TODO: make filter shape optional
        num_fwhm = sep_extract_kws.pop('filter_num_fwhm', 1)
        kernel_fwhm = self.psf_fwhm * num_fwhm
        logger.info('smoothing with kernel with fwhm = {:.2f} arcsec'.\
                    format(kernel_fwhm * utils.pixscale))
        kern = Gaussian2DKernel(kernel_fwhm * gaussian_fwhm_to_sigma,
                                mode='oversample')
        kern.normalize()
        sep_extract_kws['filter_kernel'] = kern.array

        # estimate background and subtract from image
        bkg = sep.Background(img, **sep_back_kws)
        img_sub = img - bkg

        # extract sources
        logger.info('detecting with a threshold of {} x background'.\
                    format(sep_extract_kws['thresh']))
        sources, segmap =  sep.extract(
            img_sub, err=bkg.rms(), segmentation_map=True, **sep_extract_kws)

        sources = Table(sources)
        sources = sources[sources['flux'] > 0]

        logger.info('found {} sources'.format(len(sources)))

        if kws['do_measure']:
            sources = self._measure(img, sources, mask)

        sources['seg_label'] = np.arange(1, len(sources) + 1)
        self.sources[step_name] = sources

        return sources, segmap

class SepLsstStepper(SepStepperBase):

    def setup_image(self, exposure, random_state=None):
        self.image = exposure.getImage().getArray()
        self.psf_fwhm = utils.get_psf_sigma(exposure) * gaussian_sigma_to_fwhm
        self.noise_image =  utils.make_noise_image(exposure.getMaskedImage(),
                                                    random_state)


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace SwitchAppDesign.AniListAPI.v2.Models
{
    public class MediaStreamingEpisode
    {
        /// <summary>
        /// Title of the episode
        /// </summary>
        public string title { get; set; }

        /// <summary>
        /// Url of episode image thumbnail
        /// </summary>
        public string thumbnail { get; set; }

        /// <summary>
        /// The url of the episode
        /// </summary>
        public string url { get; set; }

        /// <summary>
        /// The site location of the streaming episodes
        /// </summary>
        public string site { get; set; }
    }
}


text:
import { logging, schema, virtualFs } from '@angular-devkit/core';
import { EMPTY, Observable, Subject, concat, from, of, throwError } from 'rxjs';
import { concatMap, defaultIfEmpty, ignoreElements, last, map, tap } from 'rxjs/operators';
import { Engine, EngineHost, SchematicEngine } from '../engine';
import { UnsuccessfulWorkflowExecution } from '../exception/exception';
import { standardFormats } from '../formats';
import { DryRunEvent, DryRunSink } from '../sink/dryrun';
import { HostSink } from '../sink/host';
import { Sink } from '../sink/sink';
import { HostTree } from '../tree/host-tree';
import { Tree } from '../tree/interface';
import {
  LifeCycleEvent,
  RequiredWorkflowExecutionContext,
  Workflow,
  WorkflowExecutionContext,
} from './interface';

export interface BaseWorkflowOptions {
  host: virtualFs.Host;
  engineHost: EngineHost<{}, {}>;
  registry?: schema.CoreSchemaRegistry;

  force?: boolean;
  dryRun?: boolean;
}

/**
 * Base class for workflows. Even without abstract methods, this class should not be used without
 * surrounding some initialization for the registry and host. This class only adds life cycle and
 * dryrun/force support. You need to provide any registry and task executors that you need to
 * support.
 * See {@see NodeWorkflow} implementation for how to make a specialized subclass of this.
 * TODO: add default set of CoreSchemaRegistry transforms. Once the job refactor is done, use that
 *       as the support for tasks.
 *
 * @public
 */
export abstract class BaseWorkflow implements Workflow {
  protected _engine: Engine<{}, {}>;
  protected _engineHost: EngineHost<{}, {}>;
  protected _registry: schema.CoreSchemaRegistry;

  protected _host: virtualFs.Host;

  protected _reporter: Subject<DryRunEvent> = new Subject();
  protected _lifeCycle: Subject<LifeCycleEvent> = new Subject();

  protected _context: WorkflowExecutionContext[];

  protected _force: boolean;
  protected _dryRun: boolean;

  constructor(options: BaseWorkflowOptions) {
    this._host = options.host;
    this._engineHost = options.engineHost;

    if (options.registry) {
      this._registry = options.registry;
    } else {
      this._registry = new schema.CoreSchemaRegistry(standardFormats);
      this._registry.addPostTransform(schema.transforms.addUndefinedDefaults);
    }

    this._engine = new SchematicEngine(this._engineHost, this);

    this._context = [];

    this._force = options.force || false;
    this._dryRun = options.dryRun || false;
  }

  get context(): Readonly<WorkflowExecutionContext> {
    const maybeContext = this._context[this._context.length - 1];
    if (!maybeContext) {
      throw new Error('Cannot get context when workflow is not executing...');
    }

    return maybeContext;
  }
  get engine(): Engine<{}, {}> {
    return this._engine;
  }
  get engineHost(): EngineHost<{}, {}> {
    return this._engineHost;
  }
  get registry(): schema.SchemaRegistry {
    return this._registry;
  }
  get reporter(): Observable<DryRunEvent> {
    return this._reporter.asObservable();
  }
  get lifeCycle(): Observable<LifeCycleEvent> {
    return this._lifeCycle.asObservable();
  }

  protected _createSinks(): Sink[] {
    let error = false;

    const dryRunSink = new DryRunSink(this._host, this._force);
    const dryRunSubscriber = dryRunSink.reporter.subscribe(event => {
      this._reporter.next(event);
      error = error || (event.kind == 'error');
    });

    // We need two sinks if we want to output what will happen, and actually do the work.
    return [
      dryRunSink,
      // Add a custom sink that clean ourselves and throws an error if an error happened.
      {
        commit() {
          dryRunSubscriber.unsubscribe();
          if (error) {
            return throwError(new UnsuccessfulWorkflowExecution());
          }

          return of();
        },
      },

      // Only add a HostSink if this is not a dryRun.
      ...(!this._dryRun ? [new HostSink(this._host, this._force)] : []),
    ];
  }

  execute(
    options: Partial<WorkflowExecutionContext> & RequiredWorkflowExecutionContext,
  ): Observable<void> {
    const parentContext = this._context[this._context.length - 1];

    if (!parentContext) {
      this._lifeCycle.next({ kind: 'start' });
    }

    /** Create the collection and the schematic. */
    const collection = this._engine.createCollection(options.collection);
    // Only allow private schematics if called from the same collection.
    const allowPrivate = options.allowPrivate
      || (parentContext && parentContext.collection === options.collection);
    const schematic = collection.createSchematic(options.schematic, allowPrivate);

    const sinks = this._createSinks();

    this._lifeCycle.next({ kind: 'workflow-start' });

    const context = {
      ...options,
      debug: options.debug || false,
      logger: options.logger || (parentContext && parentContext.logger) || new logging.NullLogger(),
      parentContext,
    };
    this._context.push(context);

    return schematic.call(
      options.options,
      of(new HostTree(this._host)),
      { logger: context.logger },
    ).pipe(
      concatMap((tree: Tree) => {
        // Process all sinks.
        return concat(
          from(sinks).pipe(
            concatMap(sink => sink.commit(tree)),
            ignoreElements(),
          ),
          of(tree),
        );
      }),
      concatMap(() => {
        if (this._dryRun) {
          return EMPTY;
        }

        this._lifeCycle.next({ kind: 'post-tasks-start' });

        return this._engine.executePostTasks()
          .pipe(
            tap({ complete: () => this._lifeCycle.next({ kind: 'post-tasks-end' }) }),
            defaultIfEmpty(),
            last(),
          );
      }),
      tap({ complete: () => {
          this._lifeCycle.next({ kind: 'workflow-end' });
          this._context.pop();

          if (this._context.length == 0) {
            this._lifeCycle.next({ kind: 'end' });
          }
        }}),
    );
  }
}


text:
// The MIT License (MIT)
// Copyright © 2012 Mechanobiology Institute, National University of Singapore.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 * @fileoverview Homologene data.
 *
 * @link http://www.ncbi.nlm.nih.gov/homologene
 * @author mbikt@nus.edu.sg (Kyaw Tun)
 */

goog.provide('mbi.bi.HomoloGene');

/**
 * Create a new homologene.
 * @param {number} homologeneId
 * URL to gene.
 * @constructor
 */
mbi.bi.HomoloGene = function(homologeneId) {
  if (goog.DEBUG && (!goog.isNumber(homologeneId) || isNaN(homologeneId))) {
    throw new Error('Invalid homologeneId ' + homologeneId);
  }

  /**
   * @final
   * @private
   */
  this.id_ = homologeneId;
  /**
   * @final
   * @private
   */
  this.genes_ = {};
  /**
   * @type {Array.<string>}
   * @private
   */
  this.gene_ids_ = null;
};

/**
 * @type {number}
 * @private
 */
mbi.bi.HomoloGene.prototype.id_;

/**
 * @type {!Object.<!mbi.bi.Gene>}
 * @private
 */
mbi.bi.HomoloGene.prototype.genes_;

/**
 * Homologene id.
 * @return {number}
 */
mbi.bi.HomoloGene.prototype.getId = function() {
  return this.id_;
};

/**
 * List of ordered gene ids.
 * @type {Array.<string>}
 * @private
 */
mbi.bi.HomoloGene.prototype.gene_ids_ = null;

/**
 * Add a homologene. If the gene already exist, this will update it.
 * @param {!mbi.bi.Gene} gene
 */
mbi.bi.HomoloGene.prototype.putGene = function(gene) {

  this.genes_[gene.getGeneId()] = gene;
  this.gene_ids_ = null;

};

/**
 * Add a homologene. If the gene exist, update the data.
 * @param {GeneData} gene_data
 * @return {boolean} true if updated.
 */
mbi.bi.HomoloGene.prototype.updateGene = function(gene_data) {
  if (this.genes_[gene_data.geneId]) {
    this.genes_[gene_data.geneId].update(gene_data);
    return true;
  }
  return false;
};

/**
 * Get gene by gene id.
 * @param {string} gene_id
 * @return {mbi.bi.Gene}
 */
mbi.bi.HomoloGene.prototype.getGene = function(gene_id) {
  return this.genes_[gene_id] || null;
};

/**
 * Get gene by gene id.
 * @param {number} taxon
 * @return {mbi.bi.Gene}
 */
mbi.bi.HomoloGene.prototype.getGeneByTaxon = function(taxon) {
  goog.asserts.assertNumber(taxon, 'taxon must be a number');
  for (var id in this.genes_) {
    if (this.genes_[id].getTaxon() == taxon) {
      return this.genes_[id];
    }
  }
  return null;
};

/**
 * @return {number} number of genes.
 */
mbi.bi.HomoloGene.prototype.getCount = function() {
  if (this.gene_ids_) {
    return this.gene_ids_.length;
  } else {
    return this.getGeneIds().length;
  }
};

/**
 * @param {number} idx index of gene ids as return by {@link #getGeneIds}.
 * @return {mbi.bi.Gene} gene at index.
 */
mbi.bi.HomoloGene.prototype.gene = function(idx) {
  var ids = this.gene_ids_ || this.getGeneIds();
  return this.genes_[ids[idx]] || null;
};

/**
 * @return {!Array.<string>} list of all gene ids. genes id are ordered
 * according to specie complexity starting from human.
 */
mbi.bi.HomoloGene.prototype.getGeneIds = function() {
  if (!this.gene_ids_) {
    this.gene_ids_ = goog.object.getKeys(this.genes_);
    var taxon_order = goog.object.getKeys(mbi.bi.taxon.taxons);
    var me = this;
    goog.array.sort(this.gene_ids_, function(a, b) {
      return taxon_order.indexOf(me.getGene(a).getTaxon()) >
          taxon_order.indexOf(me.getGene(b).getTaxon()) ? 1 : -1;
    });
  }
  return goog.array.clone(this.gene_ids_);
};

/**
 * @inheritDoc
 */
mbi.bi.HomoloGene.prototype.toString = function() {
  var s = this.genes_[0] ? this.genes_[0].getName() : '';
  return 'HomoloGene:' + this.getId() + '(' + s + ')';
};

/**
 * Compare two gene by gene id.
 * @param {mbi.bi.HomoloGene} a
 * @param {mbi.bi.HomoloGene} b
 * @return {number} 1 if hg id of a is larget than b, otherwise -1.
 */
mbi.bi.HomoloGene.compare = function(a, b) {
  if (!!a && !!b) {
    if (a.getId() > b.getId()) {
      return 1;
    } else if (a.getId() < b.getId()) {
      return -1;
    } else {
      return 0;
    }
  } else if (a) {
    return 1;
  } else if (b) {
    return -1;
  } else {
    return 0;
  }
};

/**
 * Retrieve homologene.
 * @param {number} hg_id homolo gene id.
 * @return {goog.async.Deferred}
 */
mbi.bi.HomoloGene.get = function(hg_id) {
  goog.asserts.assertNumber(hg_id, 'HomoloGeneID must be number, but ' +
      hg_id + ' of ' + (typeof hg_id) + ' found');
  goog.asserts.assert(!isNaN(hg_id), 'HomoloGeneID must not be NaN');
  var storage = mbi.utils.storage.getStorage();
  var df = new goog.async.Deferred();
  storage.get('homologene', hg_id).addCallbacks(function(x) {
    if (x) {
      var data = /** @type {HomoloGeneData} */ (x);
      var hg = new mbi.bi.HomoloGene(data['homologId']);
      var ids = data['geneIds'];
      goog.asserts.assertArray(ids, 'list of genes id missing for ' +
          data['homologId']);
      storage.values('gene', ids).addCallbacks(function(genes) {
        for (var i = 0; i < genes.length; i++) {
          if (genes[i]) {
            var gene = new mbi.bi.Gene(genes[i]);
            hg.putGene(gene);
          }
        }
        df.callback(hg);
      }, function(e) {
        df.errback(e);
      });
    } else {
      df.callback(null);
    }
  }, function(e) {
    df.errback(e);
  });
  return df;
};

/**
 * Retrieve homologene.
 * @param {!Array.<number>} hg_ids homolo gene id.
 * @return {goog.async.Deferred}
 */
mbi.bi.HomoloGene.list = function(hg_ids) {
  var storage = mbi.utils.storage.getStorage();
  var df = new goog.async.Deferred();
  storage.values('homologene', hg_ids).addCallbacks(function(hgs_data) {
    var hgs = [];
    var done_count = 0;
    var total = hgs_data.length;
    var check = function() {
      if (done_count == total) {
        df.callback(hgs);
      }
    };
    for (var i = 0; i < total; i++) {
      var data = /** @type {HomoloGeneData} */ (hgs_data[i]);
      if (data && data['homologId']) {
        var hg = new mbi.bi.HomoloGene(data['homologId']);
        storage.values('gene', data['geneIds']).addCallbacks(function(genes) {
          for (var i = 0; i < genes.length; i++) {
            this.putGene(new mbi.bi.Gene(genes[i]));
          }
          done_count++;
          check();
        }, function(e) {
          done_count++;
          check();
          throw e;
        }, hg);
        hgs.push(hg);
      }
    }
    check();
  }, function(e) {
    df.errback(e);
  });
  return df;
};


text:
FROM cloudfoundry/golang-ci
MAINTAINER https://github.com/cloudfoundry-incubator/diego-dockerfiles

# pull in dependencies for the server
RUN apt-get update && apt-get -y install iptables quota protobuf-compiler ulogd

# pull in the prebuilt rootfs
ADD warden-test-rootfs.tar /opt/warden/rootfs
ADD ubuntu-test-rootfs.tar /opt/warden/nestable-rootfs
ADD fuse-test-rootfs.tar /opt/warden/fuse-rootfs
ADD docker-registry-test-rootfs.tar /opt/warden/docker-registry-rootfs

# install the binary for generating the protocol
RUN go get code.google.com/p/gogoprotobuf/protoc-gen-gogo

# debugging utilities
RUN apt-get -y install strace lsof psmisc


text:
<?php

class BetweenFieldFilter {
    private $startValue;
    private $endValue;

    public function  __construct($startValue, $endValue)
    {
        $this->startValue = $startValue;
        $this->endValue = $endValue;
    }

    public function GetStartValue()
    {
        return $this->startValue;
    }

    public function GetEndValue()
    {
        return $this->endValue;
    }

    /**
     * @param FilterConditionGenerator $filterVisitor
     * @return void
     */
    public function Accept($filterVisitor)
    {
        $filterVisitor->VisitBetweenFieldFilter($this);
    }
}


text:
namespace Priority_Queue
{
    public class StablePriorityQueueNode : FastPriorityQueueNode
    {
        /// <summary>
        /// Represents the order the node was inserted in
        /// </summary>
        public long InsertionIndex { get; internal set; }
    }
}


text:
namespace iv {
namespace lv5 {

inline  Accessor* StoredSlot::accessor() const {
  assert(attributes_.IsAccessor());
  return static_cast<Accessor*>(value_.cell());
}

inline JSVal StoredSlot::Get(Context* ctx, JSVal this_binding, Error* e) const {
  if (attributes_.IsData()) {
    return value_;
  }
  return accessor()->InvokeGetter(ctx, this_binding, e);
}

inline PropertyDescriptor StoredSlot::ToDescriptor() const {
  if (attributes().IsData()) {
    return PropertyDescriptor(value(), attributes());
  } else {
    assert(attributes_.IsAccessor());
    Accessor* ac = accessor();
    return PropertyDescriptor(ac->getter(), ac->setter(), attributes());
  }
}

// ECMA262 section 8.12.9 [[DefineOwnProperty]] step 5 and after
// this returns [[DefineOwnProperty]] descriptor is accepted or not,
// if you see return value of [[DefineOwnProperty]],
// see bool argument returned
//
// current is currently set PropertyDescriptor, and desc is which we try to set.
inline bool StoredSlot::IsDefineOwnPropertyAccepted(
    const PropertyDescriptor& desc, bool throwable, bool* returned, Error* e) const {
#define REJECT(str)\
  do {\
    if (throwable) {\
      e->Report(Error::Type, str);\
    }\
    *returned = false;\
    return false;\
  } while (0)

  // step 5
  if (desc.IsAbsent()) {
    *returned = true;
    return false;
  }

  // step 6
  if (MergeWithNoEffect(desc)) {
    *returned = true;
    return false;
  }

  // step 7
  if (!attributes().IsConfigurable()) {
    if (desc.IsConfigurable()) {
      REJECT(
          "changing [[Configurable]] of unconfigurable property not allowed");
    }
    if (!desc.IsEnumerableAbsent() &&
        attributes().IsEnumerable() != desc.IsEnumerable()) {
      REJECT("changing [[Enumerable]] of unconfigurable property not allowed");
    }
  }

  // step 9
  if (desc.IsGeneric()) {
    // no further validation
  } else if (attributes().IsData() != desc.IsData()) {
    if (!attributes().IsConfigurable()) {
      REJECT("changing descriptor type of unconfigurable property not allowed");
    }
    assert(attributes().IsData() ? desc.IsAccessor() : desc.IsData());
  } else {
    // step 10
    if (attributes().IsData()) {
      assert(desc.IsData());
      if (!attributes().IsConfigurable()) {
        if (!attributes().IsWritable()) {
          const DataDescriptor* const data = desc.AsDataDescriptor();
          if (data->IsWritable()) {
            REJECT(
                "changing [[Writable]] of unconfigurable property not allowed");
          }
          // Value:Absent and Configurable/Enumerable/Writable test passed
          // Descriptor is unreachable because MergeWithNoEffect returns true
          assert(!data->IsValueAbsent());
          if (!JSVal::SameValue(value(), data->value())) {
            REJECT("changing [[Value]] of readonly property not allowed");
          }
        }
      }
    } else {
      // step 11
      assert(attributes().IsAccessor());
      assert(desc.IsAccessor());
      if (!attributes().IsConfigurable()) {
        Accessor* lhs = accessor();
        const AccessorDescriptor* const rhs = desc.AsAccessorDescriptor();
        if ((!rhs->IsSetterAbsent() && (lhs->setter() != rhs->set())) ||
            (!rhs->IsGetterAbsent() && (lhs->getter() != rhs->get()))) {
          REJECT("changing [[Set]] or [[Get]] "
                 "of unconfigurable property not allowed");
        }
      }
    }
  }
  *returned = true;
  return true;
#undef REJECT
}

// if desc merged to current and has no effect, return true
inline bool StoredSlot::MergeWithNoEffect(
    const PropertyDescriptor& desc) const {
  if (!desc.IsConfigurableAbsent() &&
      desc.IsConfigurable() != attributes().IsConfigurable()) {
    return false;
  }
  if (!desc.IsEnumerableAbsent() && desc.IsEnumerable() != attributes().IsEnumerable()) {
    return false;
  }
  if (desc.type() != attributes().type()) {
    return false;
  }
  if (desc.IsData()) {
    const DataDescriptor* data = desc.AsDataDescriptor();
    if (!data->IsWritableAbsent() &&
        data->IsWritable() != attributes().IsWritable()) {
      return false;
    }
    if (data->IsValueAbsent()) {
      return true;
    }
    return JSVal::SameValue(data->value(), value());
  } else if (desc.IsAccessor()) {
    Accessor* ac = accessor();
    return desc.value_.accessor_.getter_ == ac->getter() &&
        desc.value_.accessor_.setter_ == ac->setter();
  } else {
    assert(desc.IsGeneric());
    return true;
  }
}

inline void StoredSlot::Merge(Context* ctx, const PropertyDescriptor& desc) {
  Attributes::External attr(attributes().raw());

  if (!desc.IsConfigurableAbsent()) {
    attr.set_configurable(desc.IsConfigurable());
  }
  if (!desc.IsEnumerableAbsent()) {
    attr.set_enumerable(desc.IsEnumerable());
  }

  if (desc.IsGeneric()) {
    attributes_ = Attributes::Safe::UnSafe(attr);
    return;
  }

  if (desc.IsData()) {
    attr.set_data();
    const DataDescriptor* const data = desc.AsDataDescriptor();
    if (!data->IsValueAbsent()) {
      value_ = data->value();
    }
    if (!data->IsWritableAbsent()) {
      attr.set_writable(data->IsWritable());
    }
    attributes_ = Attributes::Safe::UnSafe(attr);
  } else {
    assert(desc.IsAccessor());
    attr.set_accessor();
    const AccessorDescriptor* const accs = desc.AsAccessorDescriptor();

    Accessor* ac = nullptr;
    if (attributes().IsAccessor()) {
      ac = accessor();
    } else {
      ac = Accessor::New(ctx, nullptr, nullptr);
      value_ = JSVal::Cell(ac);
    }

    if (accs->IsGetterAbsent()) {
      // Accessor Descriptor should have get or set
      assert(!accs->IsSetterAbsent());
      ac->set_setter(accs->set());
    } else if (accs->IsSetterAbsent()) {
      assert(!accs->IsGetterAbsent());
      ac->set_getter(accs->get());
    } else {
      ac->set_getter(accs->get());
      ac->set_setter(accs->set());
    }
    attributes_ = Attributes::Safe::UnSafe(attr);
  }
}

const DataDescriptor* PropertyDescriptor::AsDataDescriptor() const {
  assert(IsData());
  return core::BitCast<const DataDescriptor*>(this);
}

DataDescriptor* PropertyDescriptor::AsDataDescriptor() {
  assert(IsData());
  return core::BitCast<DataDescriptor*>(this);
}

const AccessorDescriptor* PropertyDescriptor::AsAccessorDescriptor() const {
  assert(IsAccessor());
  return core::BitCast<const AccessorDescriptor*>(this);
}

AccessorDescriptor* PropertyDescriptor::AsAccessorDescriptor() {
  assert(IsAccessor());
  return core::BitCast<AccessorDescriptor*>(this);
}

inline StoredSlot::StoredSlot(Context* ctx, const PropertyDescriptor& desc)
    : value_(JSUndefined),
      attributes_(Attributes::Safe::NotFound()) {
  Attributes::External attributes(ATTR::NONE);
  attributes.set_configurable(desc.IsConfigurable());
  attributes.set_enumerable(desc.IsEnumerable());
  if (desc.IsData()) {
    const DataDescriptor* const data = desc.AsDataDescriptor();
    if (!data->IsValueAbsent()) {
      value_ = data->value();
    }
    attributes.set_writable(data->IsWritable());
    attributes_ = Attributes::CreateData(attributes);
  } else if (desc.IsAccessor()) {
    const AccessorDescriptor* const ac = desc.AsAccessorDescriptor();
    Accessor* accessor = Accessor::New(ctx, ac->get(), ac->set());
    value_ = JSVal::Cell(accessor);
    attributes_ = Attributes::CreateAccessor(attributes);
  } else {
    assert(desc.IsGeneric());
    attributes_ = Attributes::CreateData(attributes);
  }
}

} }  // namespace iv::lv5
#endif  // IV_LV5_PROPERTY_FWD_H_


text:
const sum = require("lodash/sum")
const difference = require("lodash/difference")
const create = require("lodash/create")
const isFunction = require("lodash/isFunction")
const seq = require("reaks/seq")
const child = require("reaks/child")
const style = require("reaks/style")
const onEvent = require("reaks/onEvent")
const { observable } = require("kobs")
const withSize = require("./withSize")

const { autorun } = require("kobs")
const sizeDetector = require("./sizeDetector")

const attrDefer = (attr, getValue) => domNode =>
  autorun(() => {
    const val = getValue()
    setTimeout(() => (domNode[attr] = val))
  })

const diffArrays = (oldArray, newArray) => {
  return [
    { removed: true, value: difference(oldArray, newArray) },
    { added: true, value: difference(newArray, oldArray) },
  ]
}

const diffRanges = (oldRange, newRange) => {
  const [oldStart, oldEnd] = oldRange
  const [newStart, newEnd] = newRange

  // A) ranges don't intersect
  if (newEnd < oldStart || oldEnd < newStart) {
    return [
      { removed: true, value: oldRange },
      { added: true, value: newRange },
    ]
  }

  let diff = []
  // B) ranges intersect
  if (oldStart < newStart) {
    diff.push({
      removed: true,
      value: [oldStart, newStart],
    })
  }
  if (newEnd < oldEnd) {
    diff.push({
      removed: true,
      value: [newEnd, oldEnd],
    })
  }
  if (newStart < oldStart) {
    diff.push({
      added: true,
      value: [newStart, oldStart],
    })
  }
  if (oldEnd < newEnd) {
    diff.push({
      added: true,
      value: [oldEnd, newEnd],
    })
  }
  return diff
}

const listWindow =
  ({ getItemIds, getRange, createCmp, itemHeight, getItemTop }) =>
  parentNode => {
    const createItem = id =>
      seq([
        style({
          position: "absolute",
          minWidth: "100%",
          boxSizing: "border-box",
        }),
        style(
          isFunction(itemHeight)
            ? () => ({
                height: itemHeight(id),
              })
            : { height: itemHeight }
        ),
        style(() => ({
          top: getItemTop(id) + "px",
        })),
        createCmp(id),
      ])

    const domNodes = new Map()
    const cmps = new Map()
    let currentFullIds
    let currentIds = []
    let currentRange = [0, 0]

    let nodeRecycling = []
    const flushRecycling = () => {
      nodeRecycling.forEach(n => parentNode.removeChild(n))
      nodeRecycling = []
    }

    const addItem = id => {
      //if (cmps.has(id)) return
      let domNode = nodeRecycling.pop()
      if (!domNode) {
        domNode = document.createElement("div")
        parentNode.appendChild(domNode)
      }
      const cmp = createItem(id)
      cmps.set(id, cmp(domNode))
      domNodes.set(id, domNode)
    }

    const removeItem = id => {
      const unmount = cmps.get(id)
      unmount()
      cmps.delete(id)
      const domNode = domNodes.get(id)
      domNodes.delete(id)
      nodeRecycling.push(domNode)
    }

    let cancelRangeObservation
    const cancelValueObservation = autorun(() => {
      const newFullIds = getItemIds() || []
      const newIds = newFullIds.slice(currentRange[0], currentRange[1])

      // console.time("value change : diffArrays")
      const diff = diffArrays(currentIds, newIds)
      // add/remove items
      diff.forEach(part => {
        if (part.added || part.removed) {
          part.value.forEach(part.added ? addItem : removeItem)
        }
      })
      flushRecycling()
      // console.timeEnd("value change = diffArrays")

      currentFullIds = newFullIds
      currentIds = newIds

      if (!cancelRangeObservation) {
        cancelRangeObservation = autorun(() => {
          const newRange = getRange()

          // console.time("range change = diffRanges")
          // console.info(
          //   "diffRanges",
          //   "new = ",
          //   newRange,
          //   "current = ",
          //   currentRange
          // )
          const diff = diffRanges(currentRange, newRange)
          diff.forEach(part => {
            for (
              let idx = Math.min(part.value[0], currentFullIds.length);
              idx < Math.min(part.value[1], currentFullIds.length);
              idx++
            ) {
              ;(part.added ? addItem : removeItem)(currentFullIds[idx])
            }
          })
          flushRecycling()
          // console.timeEnd("range change = diffRanges")

          currentRange = newRange
          currentIds = currentFullIds.slice(currentRange[0], currentRange[1])
        }, "listWindowGetRange")
      }
    }, "listWindowGetValue")
    return () => {
      cancelValueObservation()
      cancelRangeObservation()
      cmps.forEach(unmount => unmount())
      domNodes.forEach(domNode => parentNode.removeChild(domNode))
    }
  }

// pré-rendu avant et après exprimé en px (hauteurs variables)
const overscanPx = 500

module.exports = ({
  itemHeight,
  item,
  getDefaultVisibleItem: getDefaultVisibleItemGetter,
  disableEnsureItemVisible: getDisableEnsureItemVisibleFn,
  onScroll,
  listAvailWidthObs, // observable à fournir pour activer l'option
}) => {
  return withSize(ctx => {
    const onScrollCb = onScroll && onScroll(ctx)
    const listAvailWidth = listAvailWidthObs && listAvailWidthObs(ctx)

    const getItemIds = observable(
      isFunction(ctx.value) ? () => ctx.value() || [] : ctx.value || []
    )
    itemHeight = isFunction(itemHeight) ? itemHeight(ctx) : itemHeight
    const getItemTop = isFunction(itemHeight)
      ? id => {
          const idx = getItemIds().indexOf(id)
          if (idx === -1) return

          return sum(getItemIds().slice(0, idx).map(itemHeight))
        }
      : id => {
          const idx = getItemIds().indexOf(id)
          if (idx === -1) return
          return idx * itemHeight
        }

    let getDefaultVisibleItem =
        getDefaultVisibleItemGetter && getDefaultVisibleItemGetter(ctx),
      disableEnsureItemVisible,
      scrollTop = 0,
      defaultScrollTop = () => 0
    if (getDefaultVisibleItem) {
      disableEnsureItemVisible = getDisableEnsureItemVisibleFn(ctx)

      defaultScrollTop = () => {
        const scrollWindowTop = scrollTop
        const itemId = getDefaultVisibleItem()
        if (itemId == null) {
          return scrollWindowTop
        }

        const itemTop = getItemTop(itemId)
        const itemBottom =
          itemTop + (isFunction(itemHeight) ? itemHeight(itemId) : itemHeight)
        const containerHeight = ctx.size().height || 0
        const scrollWindowBottom = scrollWindowTop + containerHeight

        if (itemTop >= scrollWindowTop && itemBottom <= scrollWindowBottom) {
          // item already visible
          return scrollWindowTop
        } else if (itemBottom > scrollWindowTop) {
          return itemBottom - containerHeight
        } else if (itemTop < scrollWindowTop) {
          return itemTop
        }

        // in other cases, don't scroll
        return scrollWindowTop
      }
    }

    const scrollTopObs = observable()
    const setScrollTop = value => {
      // console.log("scroll event", Math.abs(scrollTop - value))
      scrollTop = value
      scrollTopObs(value)
    }

    let programmaticScroll = false

    const getRange = isFunction(itemHeight)
      ? () => {
          const containerHeight = ctx.size().height
          const scrollTop = scrollTopObs()
          let idx = 0
          let heightSum = 0
          const ids = getItemIds()
          while (heightSum < Math.max(0, scrollTop - overscanPx)) {
            heightSum += itemHeight(ids[idx])
            idx++
          }
          const startIndex = idx
          while (
            heightSum < scrollTop + containerHeight + overscanPx &&
            idx < ids.length
          ) {
            heightSum += itemHeight(ids[idx])
            idx++
          }
          const endIndex = idx
          return [startIndex, endIndex]
        }
      : () => {
          const overscanNbItems = Math.floor(overscanPx / itemHeight)
          const containerHeight = ctx.size().height

          let nbItemsRendered = containerHeight
            ? Math.ceil(containerHeight / itemHeight) + overscanNbItems * 2
            : 0

          const scrollTop = scrollTopObs()
          // start index = index du premier élément rendu
          const startIndex = Math.max(
            Math.floor(scrollTop / itemHeight) - overscanNbItems,
            0
          )
          const maxIndex = getItemIds().length
          return [
            Math.min(startIndex, maxIndex),
            Math.min(startIndex + nbItemsRendered, maxIndex),
          ]
        }

    return seq([
      () => scrollTopObs(defaultScrollTop()),
      style({
        position: "relative",
        willChange: "transform",
        overflow: "auto",
      }),
      onEvent("scroll", ev => {
        setScrollTop(ev.target.scrollTop)
        if (programmaticScroll) {
          programmaticScroll = false
        } else if (getDefaultVisibleItem) {
          getDefaultVisibleItem() != null && disableEnsureItemVisible()
        }
        onScrollCb && onScrollCb(ev)
      }),
      child(
        seq([
          // si option activée, détection dynamique de la largeur disponible pour le contenu, hors scrollbar
          listAvailWidth &&
            sizeDetector(node => {
              const currentWidth = listAvailWidth()
              const newWidth = node.offsetWidth
              if (newWidth !== currentWidth) {
                listAvailWidth(newWidth)
              }
            }),
          style({
            position: "relative",
            //overflow: "hidden", // retiré pour permettre le scroll horizontal si les lignes sont plus larges, à voir si ça peut poser pb dans certains cas ?
          }),
          style(
            isFunction(itemHeight)
              ? () => ({
                  height: sum(
                    getItemIds()
                      .map(itemHeight)
                      .filter(v => v)
                  ),
                })
              : () => ({
                  height: getItemIds().length * itemHeight,
                })
          ),
          listWindow({
            getItemIds,
            getRange,
            createCmp: id => item(create(ctx, { value: id })),
            itemHeight,
            getItemTop,
          }),
        ])
      ),
      getDefaultVisibleItem &&
        attrDefer("scrollTop", () => {
          // on utilise attrDefer pour être sûr que le scrollTop est appliqué après l'application du height (ci-dessus)
          // sinon le scroll ne fonctionnera pas si la hauteur scrollable n'a pas d'abord été mise à jour et que l'on veut scroller au maximum (en bas)
          programmaticScroll = true
          return defaultScrollTop()
        }),
    ])
  })
}


text:
package alluxio.master.job;

import alluxio.HealthCheckClient;
import alluxio.RuntimeConstants;
import alluxio.conf.AlluxioConfiguration;
import alluxio.conf.InstancedConfiguration;
import alluxio.master.AlluxioMasterMonitor;
import alluxio.master.MasterHealthCheckClient;
import alluxio.util.ConfigurationUtils;
import alluxio.util.network.NetworkAddressUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Alluxio job_master monitor for inquiring AlluxioJobMaster service availability.
 */
public final class AlluxioJobMasterMonitor {
  private static final Logger LOG = LoggerFactory.getLogger(AlluxioJobMasterMonitor.class);

  /**
   * Starts the Alluxio job_master monitor.
   *
   * @param args command line arguments, should be empty
   */
  public static void main(String[] args) {
    if (args.length != 0) {
      LOG.info("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR,
          AlluxioJobMasterMonitor.class.getCanonicalName());
      LOG.warn("ignoring arguments");
    }
    AlluxioConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults());
    HealthCheckClient client;
    // Only the primary master serves RPCs, so if we're configured for HA, fall back to simply
    // checking for the running process.
    if (ConfigurationUtils.isHaMode(conf)) {
      client = new MasterHealthCheckClient.Builder(conf)
          .withAlluxioMasterType(MasterHealthCheckClient.MasterType.JOB_MASTER)
          .build();
    } else {
      client = new JobMasterRpcHealthCheckClient(NetworkAddressUtils
          .getConnectAddress(NetworkAddressUtils.ServiceType.JOB_MASTER_RPC, conf),
          AlluxioMasterMonitor.TWO_MIN_EXP_BACKOFF, conf);
    }

    if (!client.isServing()) {
      System.exit(1);
    }
    System.exit(0);
  }

  private AlluxioJobMasterMonitor() {} // prevent instantiation
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Owin.Routing
{
	internal static class CustomAttributeProviderExtensions
	{
		public static T[] GetAttributes<T>(this ICustomAttributeProvider provider, bool inherit = true) where T : Attribute
		{
			return provider.GetCustomAttributes(typeof(T), inherit).Cast<T>().ToArray();
		}

		public static T GetAttribute<T>(this ICustomAttributeProvider provider, bool inherit = true) where T : Attribute
		{
			var attrs = provider.GetAttributes<T>(inherit);
			return attrs.Length > 0 ? attrs[0] : null;
		}

		public static bool HasAttribute<T>(this ICustomAttributeProvider provider, bool inherit = true) where T : Attribute
		{
			return provider.GetAttribute<T>(inherit) != null;
		}
	}

	internal static class DictionaryExtensions
	{
		public static T Get<T>(this IDictionary<string, object> dictionary, string key) where T : class
		{
			object value;
			return dictionary.TryGetValue(key, out value) ? value.ToType<T>() : null;
		}
	}

	internal static class ConvertExtensions
	{
		public static object ToType(this object value, Type type)
		{
			if (null == value)
				return type.DefaultValue();

			if (type.IsInstanceOfType(value))
			{
				return value;
			}

			if (type == typeof(Guid))
			{
				return new Guid(Convert.ToString(value, CultureInfo.InvariantCulture));
			}

			if (type.IsEnum)
			{
				return value.ToEnum(type);
			}

			var c = value as IConvertible;
			if (c != null && !type.IsNullable())
			{
				return Convert.ChangeType(value, type);
			}

			var converter = TypeDescriptor.GetConverter(type);
			return converter.ConvertFrom(value);
		}

		public static T ToType<T>(this object value)
		{
			return (T)value.ToType(typeof(T));
		}

		public static object ToEnum(this object value, Type type)
		{
			if (value == null)
			{
				return Activator.CreateInstance(type);
			}

			var s = value as string;
			if (s != null)
			{
				var converter = TypeDescriptor.GetConverter(type);
				return converter.ConvertFrom(value);
			}
			return Enum.ToObject(type, value);
		}

		public static T ToEnum<T>(this object value)
		{
			return (T)value.ToEnum(typeof(T));
		}

		public static Array ToArrayOfType(this IEnumerable<object> enumerable, Type type)
		{
			var arr = enumerable.ToArray();
			var result = Array.CreateInstance(type, arr.Length);
			Array.Copy(arr, result, arr.Length);
			return result;
		}

		public static object DefaultValue(this Type type)
		{
			return type.IsValueType ? Activator.CreateInstance(type) : null;
		}

		public static bool IsNullable(this Type type)
		{
			return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
		}
	}

	internal static class StreamExtensions
	{
		public static byte[] ToByteArray(this Stream stream)
		{
			if (stream.CanSeek)
			{
				stream.Seek(0, SeekOrigin.Begin);
			}

			var buffer = new byte[16 * 1024];
			using (var ms = new MemoryStream())
			{
				int read;
				while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
				{
					ms.Write(buffer, 0, read);
				}
				return ms.ToArray();
			}
		}
	}
}


text:
import Ember from 'ember';

export default Ember.Mixin.create(Ember.Evented, {
    rootURL: '',
    rootKey: '',
    url: '',
    primaryKey: '_id',
    api: function() {
        return this.rootURL + this.url;
    }.property('url'),
    save: function(model) {
        var $this = this;
        var primaryKey = this.get('primaryKey');
        var record = {};

        //filter model data
        Ember.$.each(Ember.keys(model), function(index, key) {
            if ($this.model.hasOwnProperty(key)) {
                record[key] = model[key];
            }
        });

        //check if is new data
        var url = this.get('api');
        var method = 'post';
        if (model[primaryKey]) {
            record[primaryKey] = model[primaryKey];
            url = this.get('api') + '/' + model[primaryKey];
            method = 'put';
        }

        return Ember.$.ajax({
            type: method,
            url: url,
            data: record,
            dataType: 'json',
            traditional: true
        }).then(function(data) {
            return data;
        });
    },
    createRecord: function() {
        return Ember.Object.create(this.model);
    },
    deleteRecord: function(model) {
        var $this = this;
        var _id = $this.get('primaryKey');
        return Ember.$.ajax({
            type: 'delete',
            url: $this.get('api') + '/' + model.get(_id),
            dataType: 'json'
        }).then(function(data) {
            return data;
        });
    },
    find: function(params) {
        var $this = this;
        params = $this._filterParams(params);
        return Ember.$.getJSON(this.get('api'), params || {}).then(function(data) {
            var dataList = [];
            Ember.$.each(data.res[$this.get('rootKey')], function(index, i) {
                dataList.push(Ember.Object.create(i));
            });
            return dataList;
        });
    },
    findOne: function(id) {
        var $this = this;
        return Ember.$.getJSON($this.get('api') + '/' + id).then(function(data) {
            return Ember.Object.create(data.res[$this.get('rootKey')]);
        });
    },
    _filterParams: function(params) {
        if (!params) {return;}
        for (var k in params) {
            if (params.hasOwnProperty(k) && !params[k]) {
                delete params[k];
            }
        }
        return params;
    }
});


text:
import pym from '../controller/pym';
import template from '../../view/app.html';
import overview from './overview';

export default {
    components: {
        overview: overview
    },
    el: '#sharedReductions',
    render: template.render,
    staticRenderFns: template.staticRenderFns,
    created() {
        pym.init();
    }
};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  	<modelVersion>4.0.0</modelVersion>
   	<groupId>org.mokey.mapping</groupId>
    <artifactId>fuzzymapping</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
    	<dependency>
		    <groupId>dom4j</groupId>
		    <artifactId>dom4j</artifactId>
		    <version>1.6</version>
		</dependency>
		<dependency>
	      	<groupId>jaxen</groupId>
	      	<artifactId>jaxen</artifactId>
	      	<version>1.1-beta-4</version>
    	</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>
    </dependencies>
</project>


text:
'use strict';

module.exports = {
  normalizeEntityName: function() {},
  afterInstall: function() {
    return this.addBowerPackageToProject('localforage', '~1.2.1');
  }
};


text:
TinyMCE - The JavaScript Rich Text editor
==========================================

Building TinyMCE
-----------------
1. Install Node.js
2. Open a console and go to the project directory
3. Write "npm i -g grunt-cli" to install the grunt command line tool globally.
4. Write "npm i" to install all package dependencies.
4. Build TinyMCE by writing "grunt"

Build tasks
------------
`grunt`
Lints, minified, unit tests and creates release packages for TinyMCE.

`grunt minify`
Minifies all JS and CSS files.

`grunt test`
Runs all qunit tests on PhantomJS.

`grunt lint`
Runs all source files though various JS linters.

`grunt sc-test`
Runs all qunit tests on Saucelabs.

`grunt --help`
Displays the various build tasks.

Bundle themes and plugins into a single file
---------------------------------------------
`grunt bundle --themes modern --plugins table,paste`
Minifies the core, adds the modern theme and adds the table and paste plugin into tinymce.min.js.

Contributing to the TinyMCE project
------------------------------------
You can read more about how to contribute to this project at [http://www.tinymce.com/develop/contributing.php](http://www.tinymce.com/develop/contributing.php)

[![Build Status](https://travis-ci.org/tinymce/tinymce.png?branch=master)](https://travis-ci.org/tinymce/tinymce)


text:
<?php

declare(strict_types=1);

namespace SandFox\Bencode\Tests;

use Brick\Math\BigInteger;
use PHPUnit\Framework\TestCase;
use SandFox\Bencode\Exceptions\InvalidArgumentException;
use SandFox\Bencode\Types\BigIntType;

class BigIntTypeTest extends TestCase
{
    public function testPositiveNumericString(): void
    {
        $int = new BigIntType('123');
        self::assertEquals('123', $int->value);
    }

    public function testNegativeNumericString(): void
    {
        $int = new BigIntType('-123');
        self::assertEquals('-123', $int->getValue());
    }

    public function testZero(): void
    {
        $int = new BigIntType('0');
        self::assertEquals('0', (string)$int);
    }

    public function testNoPlus(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage("Invalid integer string: '+123'");

        new BigIntType('+123');
    }

    public function testNoLeadingZero(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage("Invalid integer string: '0123'");

        new BigIntType('0123');
    }

    public function testNoNegLeadingZero(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage("Invalid integer string: '-0123'");

        new BigIntType('-0123');
    }

    public function testNoNegZero(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage("Invalid integer string: '-0'");

        new BigIntType('-0');
    }

    public function testNoFloat(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage("Invalid integer string: '12.34'");

        new BigIntType('12.34');
    }

    public function testNoHex(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage("Invalid integer string: '0x1234'");

        new BigIntType('0x1234'); // @phpcs:ignore PHPCompatibility.Miscellaneous.ValidIntegers.HexNumericStringFound
    }

    public function testExport(): void
    {
        $int = new BigIntType('123');

        self::assertEquals(\gmp_init('123'), $int->toGMP());
        self::assertTrue((new \Math_BigInteger('123'))->equals($int->toPear()));
        self::assertTrue(BigInteger::of('123')->isEqualTo($int->toBrickMath()));
    }
}


text:
package io.katharsis.client.response;

import java.util.List;

import io.katharsis.response.LinksInformation;
import io.katharsis.response.MetaInformation;
import io.katharsis.utils.WrappedList;

/**
 * Holds links and meta information next to the actual list.
 *
 * Currently only the generic {@link JsonLinksInformation} and {@link JsonMetaInformation} are used. Support
 * for proper unmarshalling into application-specific meta and links objects will be supported in the future.
 * Support for  {@link JsonLinksInformation} and {@link JsonMetaInformation} will remain in the future
 * given that they are requested by {@link #getLinksInformation(Class)} or {@link #getMetaInformation(Class)}.
 */
public class ResourceList<T> extends WrappedList<T> {

	private LinksInformation links;

	private MetaInformation meta;

	public ResourceList(List<T> list, LinksInformation links, MetaInformation meta) {
		super(list);
		this.links = links;
		this.meta = meta;
	}

	public LinksInformation getLinksInformation() {
		return links;
	}

	public MetaInformation getMetaInformation() {
		return meta;
	}

	@SuppressWarnings("unchecked")
	public <L extends LinksInformation> L getLinksInformation(Class<L> linksClass) {
		if(linksClass != JsonLinksInformation.class){
			throw new IllegalArgumentException(linksClass.getName() + " not supported yet");
		}
		return (L) getLinksInformation();
	}

	@SuppressWarnings("unchecked")
	public <M extends MetaInformation> M getMetaInformation(Class<M> metaClass) {
		if(metaClass != JsonMetaInformation.class){
			throw new IllegalArgumentException(metaClass.getName() + " not supported yet");
		}
		return (M) getMetaInformation();
	}
}


text:
	#define new DEBUG_NEW
#endif
#endif

INIT_LOGGING
INIT_TIMING
INIT_COUNTING

using namespace SPH;
using namespace std;
using namespace Utilities;

// main
int main( int argc, char **argv )
{
	REPORT_MEMORY_LEAKS;

	PartioViewer viewer;
	return viewer.run(argc, argv);
}


text:
<?php

/**
 * The internal representation of throwables.
 *
 * @package log4php
 * @since 2.1
 */
class LoggerThrowableInformation {

	/** @var Exception Throwable to log */
	private $throwable;

	/** @var array Array of throwable messages */
	private $throwableArray;

	/**
	 * Create a new instance
	 *
	 * @param $throwable - a throwable as a exception
	 * @param $logger - Logger reference
	 */
	public function __construct(Exception $throwable) {
		$this->throwable = $throwable;
	}

	/**
	* Return source exception
	*
	* @return Exception
	*/
	public function getThrowable() {
		return $this->throwable;
	}

	/**
	 * @desc Returns string representation of throwable
	 *
	 * @return array
	 */
	public function getStringRepresentation() {
		if (!is_array($this->throwableArray)) {
			$renderer = new LoggerRendererException();

			$this->throwableArray = explode("\n", $renderer->render($this->throwable));
		}

		return $this->throwableArray;
	}
}


text:
/* ###
 * IP: GHIDRA
 *
 * 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 agent.frida.model.impl;

import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.CompletableFuture;

import agent.frida.frida.FridaRegionInfo;
import agent.frida.manager.*;
import agent.frida.manager.cmd.FridaReadMemoryCommand;
import agent.frida.manager.cmd.FridaWriteMemoryCommand;
import agent.frida.manager.impl.FridaManagerImpl;
import agent.frida.model.iface2.*;
import agent.frida.model.methods.*;
import ghidra.dbg.error.DebuggerMemoryAccessException;
import ghidra.dbg.error.DebuggerModelAccessException;
import ghidra.dbg.target.TargetObject;
import ghidra.dbg.target.schema.*;
import ghidra.dbg.target.schema.TargetObjectSchema.ResyncMode;
import ghidra.program.model.address.*;
import ghidra.util.Msg;
import ghidra.util.datastruct.WeakValueHashMap;

@TargetObjectSchemaInfo(
	name = "Memory",
	elementResync = ResyncMode.ALWAYS,
	elements = {
		@TargetElementType(type = FridaModelTargetMemoryRegionImpl.class)
	},
	attributes = {
		@TargetAttributeType(type = Object.class)
	},
	canonicalContainer = true)
public class FridaModelTargetMemoryContainerImpl extends FridaModelTargetObjectImpl
		implements FridaModelTargetMemoryContainer {

	protected final FridaModelTargetProcess process;
	protected final FridaModelTargetMemoryScanImpl scan;
	protected final FridaModelTargetMemoryPatchImpl patch;
	protected final FridaModelTargetMemoryProtectImpl prot;
	protected final FridaModelTargetMemoryWatchImpl watch;
	protected final FridaModelTargetUnloadScriptImpl unload;

	protected final Map<String, FridaModelTargetMemoryRegionImpl> memoryRegions =
		new WeakValueHashMap<>();

	public FridaModelTargetMemoryContainerImpl(FridaModelTargetProcess process) {
		super(process.getModel(), process, "Memory", "MemoryContainer");
		this.process = process;

		this.scan = new FridaModelTargetMemoryScanImpl(this, false);
		this.patch = new FridaModelTargetMemoryPatchImpl(this);
		this.prot = new FridaModelTargetMemoryProtectImpl(this, false);
		this.watch = new FridaModelTargetMemoryWatchImpl(this);
		this.unload = new FridaModelTargetUnloadScriptImpl(this, watch.getName());
		this.changeAttributes(List.of(), List.of(), Map.of( //
			scan.getName(), scan, //
			patch.getName(), patch, //
			prot.getName(), prot, //
			watch.getName(), watch, //
			unload.getName(), unload //
		), "Initialized");

		getManager().addEventsListener(this);
		requestElements(true);
	}

	public FridaModelTargetMemoryContainerImpl(FridaModelTargetProcess process, String name) {
		super(process.getModel(), process, name, "MemoryContainer");
		this.process = process;

		this.scan = new FridaModelTargetMemoryScanImpl(this, false);
		this.patch = new FridaModelTargetMemoryPatchImpl(this);
		this.prot = new FridaModelTargetMemoryProtectImpl(this, false);
		this.watch = new FridaModelTargetMemoryWatchImpl(this);
		this.unload = new FridaModelTargetUnloadScriptImpl(this, watch.getName());
		this.changeAttributes(List.of(), List.of(), Map.of( //
			scan.getName(), scan, //
			patch.getName(), patch, //
			prot.getName(), prot, //
			watch.getName(), watch, //
			unload.getName(), unload //
		), "Initialized");

		requestElements(false);
	}

	@Override
	public CompletableFuture<Void> requestElements(boolean refresh) {
		if (refresh) {
			broadcast().invalidateCacheRequested(this);
		}
		return getManager().listMemory(process.getProcess());
	}

	@Override
	public synchronized FridaModelTargetMemoryRegion getTargetMemory(FridaMemoryRegionInfo region) {
		TargetObject targetObject = getMapObject(region);
		if (targetObject != null) {
			FridaModelTargetMemoryRegion targetRegion = (FridaModelTargetMemoryRegion) targetObject;
			targetRegion.setModelObject(region);
			return targetRegion;
		}
		return new FridaModelTargetMemoryRegionImpl(this, region);
	}

	private byte[] readAssist(Address address, ByteBuffer buf, AddressSetView set) {
		if (set == null) {
			return new byte[0];
		}
		AddressRange range = set.getRangeContaining(address);
		if (range == null) {
			throw new DebuggerMemoryAccessException("Cannot read at " + address);
		}
		broadcast().memoryUpdated(getProxy(), address, buf.array());
		return Arrays.copyOf(buf.array(), (int) range.getLength());
	}

	private void writeAssist(Address address, byte[] data) {
		broadcast().memoryUpdated(getProxy(), address, data);
	}

	@Override
	public CompletableFuture<byte[]> readMemory(Address address, int length) {
		return model.gateFuture(doReadMemory(address, length));
	}

	protected CompletableFuture<byte[]> doReadMemory(Address address, int length) {
		FridaManagerImpl manager = getManager();
		if (manager.isWaiting()) {
			throw new DebuggerModelAccessException(
				"Cannot process command readMemory while engine is waiting for events");
		}
		ByteBuffer buf = ByteBuffer.allocate(length);
		if (!manager.isKernelMode() || address.getAddressSpace().getName().equals("ram")) {
			return manager
					.execute(new FridaReadMemoryCommand(manager, address, buf, buf.remaining()))
					.thenApply(set -> {
						return readAssist(address, buf, set);
					});
		}
		return CompletableFuture.completedFuture(new byte[length]);
	}

	@Override
	public CompletableFuture<Void> writeMemory(Address address, byte[] data) {
		return model.gateFuture(doWriteMemory(address, data));
	}

	protected CompletableFuture<Void> doWriteMemory(Address address, byte[] data) {
		FridaManagerImpl manager = getManager();
		if (manager.isWaiting()) {
			throw new DebuggerModelAccessException(
				"Cannot process command writeMemory while engine is waiting for events");
		}
		ByteBuffer buf = ByteBuffer.wrap(data);
		if (!manager.isKernelMode() || address.getAddressSpace().getName().equals("ram")) {
			return manager
					.execute(new FridaWriteMemoryCommand(manager, address, buf, buf.remaining()))
					.thenAccept(___ -> {
						writeAssist(address, data);
					});
		}
		return CompletableFuture.completedFuture(null);
	}

	@Override
	public void regionAdded(FridaProcess proc, FridaRegionInfo info, int index, FridaCause cause) {
		FridaModelTargetMemoryRegion targetRegion;
		FridaMemoryRegionInfo region = info.getRegion(index);
		synchronized (this) {
			/**
			 * It's not a good idea to remove "stale" entries. If the entry's already present, it's
			 * probably because several modules were loaded at once, at it has already had its
			 * sections loaded. Removing it will cause it to load all module sections again!
			 */
			//modulesByName.remove(name);
			targetRegion = getTargetMemory(region);
		}
		if (targetRegion == null) {
			Msg.error(this, "Region " + region.getRangeAddress() + " not found!");
			return;
		}
		changeElements(List.of(), List.of(targetRegion), Map.of(), "Added");
	}

	@Override
	public void regionReplaced(FridaProcess proc, FridaRegionInfo info, int index,
			FridaCause cause) {
		FridaMemoryRegionInfo region = info.getRegion(index);
		changeElements(List.of(), List.of(getTargetMemory(region)), Map.of(), "Replaced");
		FridaModelTargetMemoryRegion targetRegion = getTargetMemory(region);
		changeElements(List.of(), List.of(targetRegion), Map.of(), "Replaced");
	}

	@Override
	public void regionRemoved(FridaProcess proc, FridaRegionInfo info, int index,
			FridaCause cause) {
		FridaModelTargetMemoryRegion targetRegion = getTargetMemory(info.getRegion(index));
		if (targetRegion != null) {
			FridaModelImpl impl = (FridaModelImpl) model;
			impl.deleteModelObject(targetRegion.getModelObject());
		}
		changeElements(List.of(targetRegion.getName()), List.of(), Map.of(), "Removed");
	}
}


text:
package uk.co.omegaprime.mdbi;

/**
 * Given a context describing how to obtain arbitrary SQL types from Java ones, describes how a particular
 * SQL type should be derived from a Java type.
 *

 * Useful instances of this can be obtained from {@link Writes}.
 */
public interface Write<T> {
    BoundWrite<? super T> bind(Context ctxt);

    /** An immutable description of how to obtain specific SQL types from Java. */
    interface Context {
        <T> Write<? super T> get(Class<T> klass);
    }
}


text:
/**
 * Contains the API (classes and interfaces) for the jKool LLC TNT4J-Streams custom streams components implementations.
 *
 * @author akausinis
 * @version 1.0
 */

package com.jkoolcloud.tnt4j.streams.custom;


text:
BASEDIR=$(dirname $0)
echo "NOTE: This script assumes you've cloned druid-vagrant-cluster to ~/git/druid-vagrant-cluster"
echo "If it is not in that location, you'll need to edit this script."
scp -i ~/git/druid-vagrant-cluster/.vagrant/machines/druid/virtualbox/private_key  $BASEDIR/../data/data.csv vagrant@192.168.50.4:/home/vagrant/druid/


text:
set -o errexit
set -o nounset
set -o pipefail

OS_ROOT=$(dirname "${BASH_SOURCE}")/../..
source "${OS_ROOT}/hack/util.sh"
source "${OS_ROOT}/hack/cmd_util.sh"
os::log::install_errexit

# This test validates the new-app command

os::cmd::expect_success 'oc create -f examples/image-streams/image-streams-centos7.json'

os::cmd::expect_success_and_text 'oc new-app library/php mysql -o yaml' '3306'
os::cmd::expect_failure 'oc new-app unknownhubimage -o yaml'
# verify we can generate a Docker image based component "mongodb" directly
os::cmd::expect_success_and_text 'oc new-app mongo -o yaml' 'library/mongo'
# the local image repository takes precedence over the Docker Hub "mysql" image
os::cmd::expect_success "tryuntil 'oc get imagestreamtags mysql:latest'"
os::cmd::expect_success "tryuntil 'oc get imagestreamtags mysql:5.5'"
os::cmd::expect_success "tryuntil 'oc get imagestreamtags mysql:5.6'"
os::cmd::expect_success_and_text 'oc new-app mysql -o yaml' 'mysql'
os::cmd::expect_success "tryuntil 'oc get imagestreamtags php:latest'"
os::cmd::expect_success "tryuntil 'oc get imagestreamtags php:5.5'"
os::cmd::expect_success "tryuntil 'oc get imagestreamtags php:5.6'"

# check label creation
os::cmd::expect_success 'oc new-app php mysql -l no-source=php-mysql'
os::cmd::expect_success 'oc delete all -l no-source=php-mysql'
os::cmd::expect_success 'oc new-app php mysql'
os::cmd::expect_success 'oc delete all -l app=php'
os::cmd::expect_failure 'oc get dc/mysql'
os::cmd::expect_failure 'oc get dc/php'

# check if we can create from a stored template
os::cmd::expect_success 'oc create -f examples/sample-app/application-template-stibuild.json'
os::cmd::expect_success 'oc get template ruby-helloworld-sample'
os::cmd::expect_success_and_text 'oc new-app ruby-helloworld-sample -o yaml' 'MYSQL_USER'
os::cmd::expect_success_and_text 'oc new-app ruby-helloworld-sample -o yaml' 'MYSQL_PASSWORD'
os::cmd::expect_success_and_text 'oc new-app ruby-helloworld-sample -o yaml' 'ADMIN_USERNAME'
os::cmd::expect_success_and_text 'oc new-app ruby-helloworld-sample -o yaml' 'ADMIN_PASSWORD'

# check search
os::cmd::expect_success_and_text 'oc new-app --search mysql' "Tags:\s+5.5, 5.6, latest"
os::cmd::expect_success_and_text 'oc new-app --search ruby-helloworld-sample' 'ruby-helloworld-sample'
# check search - partial matches
os::cmd::expect_success_and_text 'oc new-app --search ruby-hellow' 'ruby-helloworld-sample'
os::cmd::expect_success_and_text 'oc new-app --search --template=ruby-hel' 'ruby-helloworld-sample'
os::cmd::expect_success_and_text 'oc new-app --search --template=ruby-helloworld-sam -o yaml' 'ruby-helloworld-sample'
os::cmd::expect_success_and_text 'oc new-app --search rub' "Tags:\s+2.0, 2.2, latest"
os::cmd::expect_success_and_text 'oc new-app --search --image-stream=rub' "Tags:\s+2.0, 2.2, latest"
# check search - check correct usage of filters
os::cmd::expect_failure_and_not_text 'oc new-app --search --image-stream=ruby-heloworld-sample' 'application-template-stibuild'
os::cmd::expect_failure 'oc new-app --search --template=php'
os::cmd::expect_failure 'oc new-app -S --template=nodejs'
os::cmd::expect_failure 'oc new-app -S --template=perl'
# check search - filtered, exact matches
os::cmd::expect_success_and_text 'oc new-app --search --image-stream=mongodb' "Tags:\s+2.4, 2.6, latest"
os::cmd::expect_success_and_text 'oc new-app --search --image-stream=mysql' "Tags:\s+5.5, 5.6, latest"
os::cmd::expect_success_and_text 'oc new-app --search --image-stream=nodejs' "Tags:\s+0.10, latest"
os::cmd::expect_success_and_text 'oc new-app --search --image-stream=perl' "Tags:\s+5.16, 5.20, latest"
os::cmd::expect_success_and_text 'oc new-app --search --image-stream=php' "Tags:\s+5.5, 5.6, latest"
os::cmd::expect_success_and_text 'oc new-app --search --image-stream=postgresql' "Tags:\s+9.2, 9.4, latest"
os::cmd::expect_success_and_text 'oc new-app -S --image-stream=python' "Tags:\s+2.7, 3.3, 3.4, latest"
os::cmd::expect_success_and_text 'oc new-app -S --image-stream=ruby' "Tags:\s+2.0, 2.2, latest"
os::cmd::expect_success_and_text 'oc new-app -S --image-stream=wildfly' "Tags:\s+8.1, latest"
os::cmd::expect_success_and_text 'oc new-app --search --template=ruby-helloworld-sample' 'ruby-helloworld-sample'
# check search - no matches
os::cmd::expect_failure_and_text 'oc new-app -S foo-the-bar' 'no matches found'
os::cmd::expect_failure_and_text 'oc new-app --search winter-is-coming' 'no matches found'
# check search - mutually exclusive flags
os::cmd::expect_failure_and_text 'oc new-app -S mysql --env=FOO=BAR' "can't be used"
os::cmd::expect_failure_and_text 'oc new-app --search mysql --code=https://github.com/openshift/ruby-hello-world' "can't be used"
os::cmd::expect_failure_and_text 'oc new-app --search mysql --param=FOO=BAR' "can't be used"
# set context-dir
os::cmd::expect_success_and_text 'oc new-app https://github.com/openshift/sti-ruby.git --context-dir="2.0/test/puma-test-app" -o yaml' 'contextDir: 2.0/test/puma-test-app'
os::cmd::expect_success_and_text 'oc new-app ruby~https://github.com/openshift/sti-ruby.git --context-dir="2.0/test/puma-test-app" -o yaml' 'contextDir: 2.0/test/puma-test-app'
# set strategy
os::cmd::expect_success_and_text 'oc new-app ruby~https://github.com/openshift/ruby-hello-world.git --strategy=docker -o yaml' 'dockerStrategy'
os::cmd::expect_success_and_text 'oc new-app https://github.com/openshift/ruby-hello-world.git --strategy=source -o yaml' 'sourceStrategy'

os::cmd::expect_success 'oc delete imageStreams --all'
# check that we can create from the template without errors
os::cmd::expect_success_and_text 'oc new-app ruby-helloworld-sample -l app=helloworld' 'Service "frontend" created'
os::cmd::expect_success 'oc delete all -l app=helloworld'
os::cmd::expect_success_and_text 'oc new-app ruby-helloworld-sample -l app=helloworld -o name' 'Service/frontend'
os::cmd::expect_success 'oc delete all -l app=helloworld'
# create from template with code explicitly set is not supported
os::cmd::expect_failure 'oc new-app ruby-helloworld-sample~git@github.com:mfojtik/sinatra-app-example'
os::cmd::expect_success 'oc delete template ruby-helloworld-sample'
# override component names
os::cmd::expect_success_and_text 'oc new-app mysql --name=db' 'db'
os::cmd::expect_success 'oc new-app https://github.com/openshift/ruby-hello-world -l app=ruby'
os::cmd::expect_success 'oc delete all -l app=ruby'

# check new-build
os::cmd::expect_failure_and_text 'oc new-build mysql -o yaml' 'you must specify at least one source repository URL'
os::cmd::expect_success_and_text 'oc new-build mysql --binary -o yaml --to mysql:bin' 'type: Binary'
os::cmd::expect_success_and_text 'oc new-build mysql https://github.com/openshift/ruby-hello-world --strategy=docker -o yaml' 'type: Docker'
os::cmd::expect_failure_and_text 'oc new-build mysql https://github.com/openshift/ruby-hello-world --binary' 'specifying binary builds and source repositories at the same time is not allowed'

# do not allow use of non-existent image (should fail)
os::cmd::expect_failure_and_text 'oc new-app  openshift/bogusImage https://github.com/openshift/ruby-hello-world.git -o yaml' "no match for"
# allow use of non-existent image (should succeed)
os::cmd::expect_success 'oc new-app openshift/bogusImage https://github.com/openshift/ruby-hello-world.git -o yaml --allow-missing-images'

os::cmd::expect_success 'oc create -f test/fixtures/installable-stream.yaml'

project=$(oc project -q)
os::cmd::expect_success 'oc policy add-role-to-user edit test-user'
os::cmd::expect_success 'oc login -u test-user -p anything'
os::cmd::expect_success "tryuntil 'oc project ${project}'"

os::cmd::expect_success "tryuntil 'oc get imagestreamtags installable:file'"
os::cmd::expect_success "tryuntil 'oc get imagestreamtags installable:token'"
os::cmd::expect_success "tryuntil 'oc get imagestreamtags installable:serviceaccount'"
os::cmd::expect_failure 'oc new-app installable:file'
os::cmd::expect_failure_and_text 'oc new-app installable:file' 'requires that you grant the image access'
os::cmd::expect_failure_and_text 'oc new-app installable:serviceaccount' "requires an 'installer' service account with project editor access"
os::cmd::expect_success_and_text 'oc new-app installable:file --grant-install-rights -o yaml' '/var/run/openshift.secret.token'
os::cmd::expect_success_and_text 'oc new-app installable:file --grant-install-rights -o yaml' 'activeDeadlineSeconds: 14400'
os::cmd::expect_success_and_text 'oc new-app installable:file --grant-install-rights -o yaml' 'openshift.io/generated-job: "true"'
os::cmd::expect_success_and_text 'oc new-app installable:file --grant-install-rights -o yaml' 'openshift.io/generated-job.for: installable:file'
os::cmd::expect_success_and_text 'oc new-app installable:token --grant-install-rights -o yaml' 'name: TOKEN_ENV'
os::cmd::expect_success_and_text 'oc new-app installable:token --grant-install-rights -o yaml' 'openshift/origin@sha256:'
os::cmd::expect_success_and_text 'oc new-app installable:serviceaccount --grant-install-rights -o yaml' 'serviceAccountName: installer'
os::cmd::expect_success_and_text 'oc new-app installable:serviceaccount --grant-install-rights -o yaml' 'fieldPath: metadata.namespace'
os::cmd::expect_success_and_text 'oc new-app installable:serviceaccount --grant-install-rights -o yaml A=B' 'name: A'

# Ensure output is valid JSON
os::cmd::expect_success 'oc new-app mongo -o json | python -m json.tool'

echo "new-app: ok"


text:
@name

I'm a twenty-something UX developer and designer living in Leeds, UK. I love semantic code, great design, good food and robots. I make up one half of Waffle Works.

© Copyright @name @current_year RSS


text:
jetpack-laravel-connector
=========================

DreamFactory Services Platform(tm) Laravel Connector


text:
'use strict';

const { DiagConsoleLogger, DiagLogLevel, diag } = require('@opentelemetry/api');
const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-http');
// const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-grpc');
// const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-proto');
const { MeterProvider, PeriodicExportingMetricReader } = require('@opentelemetry/sdk-metrics');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');

// Optional and only needed to see the internal diagnostic logging (during development)
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);

const metricExporter = new OTLPMetricExporter({});

const meterProvider = new MeterProvider({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: 'basic-metric-service',
  }),
});

meterProvider.addMetricReader(new PeriodicExportingMetricReader({
  exporter: metricExporter,
  exportIntervalMillis: 1000,
}));

const meter = meterProvider.getMeter('example-exporter-collector');

const requestCounter = meter.createCounter('requests', {
  description: 'Example of a Counter',
});

const upDownCounter = meter.createUpDownCounter('test_up_down_counter', {
  description: 'Example of a UpDownCounter',
});

const histogram = meter.createHistogram('test_histogram', {
  description: 'Example of a Histogram',
});

const attributes = { pid: process.pid, environment: 'staging' };

setInterval(() => {
  requestCounter.add(1, attributes);
  upDownCounter.add(Math.random() > 0.5 ? 1 : -1, attributes);
  histogram.record(Math.random(), attributes);
}, 1000);


text:
<?php

namespace ApplicationLibraryTest\Pagination\SLFactory;

use ApplicationLibrary\Pagination\SLFactory\PaginatorInfoFactorySLFactory;
use BusinessLogicLibrary\Pagination\PaginatorInfoFactory;
use Test\Bootstrap;

class PaginatorInfoFactorySLFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var PaginatorInfoFactorySLFactory
     */
    private $testedObj;

    public function setUp()
    {
        $this->testedObj = new PaginatorInfoFactorySLFactory();
    }

    public function testCreateService()
    {
        $result = $this->testedObj->createService(Bootstrap::getServiceManager());

        $this->assertInstanceOf(PaginatorInfoFactory::class, $result);
    }
}


text:
package io.netty.handler.codec.http;

import io.netty.handler.codec.EmptyHeaders;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.NoSuchElementException;

public class EmptyHttpHeaders extends EmptyHeaders<CharSequence, CharSequence, HttpHeaders> implements HttpHeaders {
    public static final EmptyHttpHeaders INSTANCE = new EmptyHttpHeaders();
    private static final Iterator<Entry<String, String>> EMPTY_STRING_ITERATOR =
            new Iterator<Entry<String, String>>() {
                @Override
                public boolean hasNext() {
                    return false;
                }

                @Override
                public Entry<String, String> next() {
                    throw new NoSuchElementException();
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException("remove");
                }
    };

    protected EmptyHttpHeaders() {
    }

    @Override
    public String getAsString(CharSequence name) {
        return null;
    }

    @Override
    public List<String> getAllAsString(CharSequence name) {
        return Collections.emptyList();
    }

    @Override
    public Iterator<Entry<String, String>> iteratorAsString() {
        return EMPTY_STRING_ITERATOR;
    }

    @Override
    public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) {
        return false;
    }
}


text:
package com.mars.food.entity;

/**
 * Created by Mars on 2015/12/7.
 */
public interface Stomach {
}


text:
<?xml version="1.0" encoding="us-ascii"?>

	<CreateObjectDie xmlns="uri:ea.com:eala:asset"
		id="ModuleTag_CreateOccupiedSuicide"
		CreationList="OCL_ConyardGDIBuildingSuicide" >
		<DieMuxData DeathTypes="SUICIDED" />
	</CreateObjectDie>


text:
package engine.gameobject.weapon.upgradetree;

import java.util.List;
import engine.gameobject.weapon.upgradetree.upgradebundle.UpgradeBundle;

@Deprecated
public interface MultipleTrees extends UpgradeTree {

    /**
     *
     * @return next available upgrades to be purchased (if not final). Will be called by the shop to
     *         display what can be bought.
     */
    @Override
    public List<UpgradeBundle> getNextUpgrades ();

    /**
     *
     * @param toUpdate tree that will be updated
     */
    public void updateCurrent (SingleTree toUpdate);

}


text:
package test

import (
	"encoding/xml"
	"errors"
	"fmt"
	"log"
	"math"
	"os"
	"path/filepath"
	"strings"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"

	"github.com/servehub/serve/manifest"
	"github.com/servehub/serve/tools/github"
	"github.com/servehub/utils"
)

func init() {
	manifest.PluginRegestry.Add("test.coverage", CoverageUpload{})
}

type CoverageUpload struct{}

func (p CoverageUpload) Run(data manifest.Manifest) error {
	// get repo, commit information
	meta := Meta{
		Repo:     data.GetString("repo"),
		Branch:   data.GetString("branch"),
		Ref:      data.GetString("ref"),
		Version:  data.GetString("version"),
		TestType: data.GetString("test-type"),
	}

	execFilePath := data.GetString("exec-file")
	if _, err := os.Stat(execFilePath); os.IsNotExist(err) {
		log.Printf("coverage report file doesn't exist - skipping: %s", execFilePath)
		return nil
	}

	classfilesExist := false
	for _, classFiles := range data.GetArrayForce("generate.classfiles") {
		if _, err := os.Stat(fmt.Sprintf("%s", classFiles)); !os.IsNotExist(err) {
			classfilesExist = true
			break
		}
	}

	if !classfilesExist {
		log.Printf("coverage classfiles doesn't exist - skipping: %v", data.GetArrayForce("generate.classfiles"))
		return nil
	}

	coveragePercent, err := generateReportsAndGetCoveragePercent([]string{execFilePath}, data)
	if err != nil {
		return err
	}

	// main branch name
	mainBranchName := data.GetStringOr("main-branch", "master")

	connectionUrl := os.Getenv(data.GetString("database-connection-env"))
	db, err := gorm.Open(postgres.Open(connectionUrl), &gorm.Config{})
	if err != nil {
		return fmt.Errorf("failed to connect to database: %w", err)
	}

	// Migrate the DB schema
	if err := db.AutoMigrate(&CoverageReport{}); err != nil {
		return fmt.Errorf("failed to apply database migration: %w", err)
	}

	if meta.Branch == mainBranchName {
		coverageData, err := os.ReadFile(execFilePath)
		if err != nil {
			return fmt.Errorf("failed to read coverage exec file: %w", err)
		}

		reportRecord := CoverageReport{
			Meta:            meta,
			CoveragePercent: coveragePercent,
			CoverageFile:    coverageData,
		}
		if err := db.Create(&reportRecord).Error; err != nil {
			return fmt.Errorf("failed to upload coverage exec file: %w", err)
		}

		if err := db.Unscoped().Where(&CoverageReport{Meta: Meta{
			Repo:     meta.Repo,
			Branch:   mainBranchName,
			TestType: meta.TestType,
		}}).Where("id != ?", reportRecord.ID).Delete(&CoverageReport{}).Error; err != nil {
			log.Printf("failed to removed outdated records: %s", err)
		}

		return nil
	}

	// check mode
	accessToken := os.Getenv("GITHUB_TOKEN")
	if accessToken == "" {
		return errors.New("`GITHUB_TOKEN` is required")
	}

	targetUrl := data.GetString("check.target-url")
	statusContext := data.GetStringOr("check.context", "coverage")

	// allow a small tolerance for decrease in coverage
	coverageTolerance := data.GetFloat("check.tolerance")

	// get latest coverage report from database
	var latestCoverage CoverageReport

	if err := db.Where(&CoverageReport{Meta: Meta{
		Repo:     meta.Repo,
		Branch:   mainBranchName,
		TestType: meta.TestType,
	}}).Last(&latestCoverage).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return github.SendStatus(accessToken, meta.Repo, meta.Ref, "success",
				"No previous coverage exists - check skipped ",
				statusContext, targetUrl)
		}
		return err
	}

	diff := latestCoverage.CoveragePercent - coveragePercent

	if diff < 0 {
		return github.SendStatus(accessToken, meta.Repo, meta.Ref, "success",
			fmt.Sprintf("Thank you for increasing the test coverage by %.2f%%", -diff),
			statusContext, targetUrl)
	} else if diff < coverageTolerance {
		return github.SendStatus(accessToken, meta.Repo, meta.Ref, "success",
			fmt.Sprintf("Coverage changed by %.2f%%", diff),
			statusContext, targetUrl)
	} else {
		return github.SendStatus(accessToken, meta.Repo, meta.Ref, "failure",
			fmt.Sprintf("Please increase test coverage at least by %.2f%%", math.Max(diff, 1)),
			statusContext, targetUrl)
	}
}

type Meta struct {
	Repo     string `json:"repo"   gorm:"index"`
	Branch   string `json:"branch" gorm:"index"`
	Ref      string `json:"ref"`
	Version  string `json:"version"`
	TestType string `json:"test_type"`
}

type CoverageReport struct {
	gorm.Model
	Meta
	// coverage percentage in the range [0.0, 100.0]
	CoveragePercent float64
	CoverageFile    []byte
}

type CounterXML struct {
	XMLName xml.Name `xml:"counter"`
	Type    string   `xml:"type,attr"`
	Missed  int      `xml:"missed,attr"`
	Covered int      `xml:"covered,attr"`
}

type CoverageReportXML struct {
	XMLName xml.Name     `xml:"report"`
	Counter []CounterXML `xml:"counter"`
}

func generateReportsAndGetCoveragePercent(execCoverageFiles []string, data manifest.Manifest) (float64, error) {
	builder := strings.Builder{}
	builder.WriteString(fmt.Sprintf("java -jar %s report %s",
		data.GetStringOr("generate.jacococli-jar", "jacococli.jar"),
		strings.Join(execCoverageFiles, " "),
	))

	if data.Has("generate.sourcefiles") {
		for _, sourceFiles := range data.GetArrayForce("generate.sourcefiles") {
			if _, err := os.Stat(fmt.Sprintf("%s", sourceFiles)); !os.IsNotExist(err) {
				builder.WriteString(fmt.Sprintf(" --sourcefiles '%s'", sourceFiles))
			}
		}
	}

	for _, classFiles := range data.GetArrayForce("generate.classfiles") {
		if _, err := os.Stat(fmt.Sprintf("%s", classFiles)); !os.IsNotExist(err) {
			builder.WriteString(fmt.Sprintf(" --classfiles '%s'", classFiles))
		}
	}

	if data.Has("generate.html-output-dir") {
		htmlOutputDir := data.GetString("generate.html-output-dir")
		if htmlOutputDir != "" {
			builder.WriteString(fmt.Sprintf(" --html %s", htmlOutputDir))
		}
	}

	dirName, err := os.MkdirTemp("", "xml-report")
	if err != nil {
		return 0, errors.New("failed to create directory for temporary XML report file")
	}

	defer func(path string) {
		err := os.RemoveAll(path)
		if err != nil {
			log.Fatal(err)
		}
	}(dirName)

	xmlReportFile := filepath.Join(dirName, "coverage.xml")
	builder.WriteString(fmt.Sprintf(" --xml '%s'", xmlReportFile))

	if err = utils.RunCmd(builder.String()); err != nil {
		return 0, err
	}

	return getCoveragePercent(xmlReportFile)
}

func getCoveragePercent(xmlReportFile string) (float64, error) {
	coverageXml, err := os.ReadFile(xmlReportFile)
	if err != nil {
		return 0, fmt.Errorf("failed to read xml coverage report file: %w", err)
	}

	// (partially) unmarshall report from xml
	var coverageReportXml CoverageReportXML
	if err = xml.Unmarshal(coverageXml, &coverageReportXml); err != nil {
		return 0, fmt.Errorf("failed to parse xml coverage report file: %w", err)
	}

	// search for the XML counter matching the desired coverage metric
	var coverageCounter CounterXML
	for _, counter := range coverageReportXml.Counter {
		if counter.Type == "INSTRUCTION" {
			coverageCounter = counter
			break
		}
	}

	total := coverageCounter.Covered + coverageCounter.Missed
	if total == 0 {
		return 0, err
	}
	return 100 * float64(coverageCounter.Covered) / float64(total), nil
}