text:
package com.palantir.atlasdb.sweep;

import com.palantir.atlasdb.encoding.PtBytes;
import com.palantir.atlasdb.keyvalue.api.SweepResults;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.atlasdb.logging.LoggingArgs;
import com.palantir.logsafe.Preconditions;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.UnsafeArg;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.util.Optional;

public final class SweeperServiceImpl implements SweeperService {
    private static final SafeLogger log = SafeLoggerFactory.get(SweeperServiceImpl.class);

    private final SpecificTableSweeper specificTableSweeper;
    private final AdjustableSweepBatchConfigSource sweepBatchConfigSource;

    public SweeperServiceImpl(
            SpecificTableSweeper specificTableSweeper, AdjustableSweepBatchConfigSource sweepBatchConfigSource) {
        this.specificTableSweeper = specificTableSweeper;
        this.sweepBatchConfigSource = sweepBatchConfigSource;
    }

    @Override
    public SweepTableResponse sweepTable(
            String tableName,
            Optional<String> startRow,
            Optional<Boolean> fullSweep,
            Optional<Integer> maxCellTsPairsToExamine,
            Optional<Integer> candidateBatchSize,
            Optional<Integer> deleteBatchSize) {
        TableReference tableRef = getTableRef(tableName);
        checkTableExists(tableName, tableRef);

        byte[] decodedStartRow = startRow.map(PtBytes::decodeHexString).orElse(PtBytes.EMPTY_BYTE_ARRAY);
        SweepBatchConfig config =
                buildConfigWithOverrides(maxCellTsPairsToExamine, candidateBatchSize, deleteBatchSize);

        return SweepTableResponse.from(
                runSweep(fullSweep, tableRef, decodedStartRow, config, SweepTaskRunner.RunType.FULL));
    }

    @Override
    public SweepTableResponse sweepPreviouslyConservativeNowThoroughTable(
            String tableName,
            Optional<String> startRow,
            Optional<Boolean> fullSweep,
            Optional<Integer> maxCellTsPairsToExamine,
            Optional<Integer> candidateBatchSize,
            Optional<Integer> deleteBatchSize) {
        TableReference tableRef = getTableRef(tableName);
        checkTableExists(tableName, tableRef);

        byte[] decodedStartRow = startRow.map(PtBytes::decodeHexString).orElse(PtBytes.EMPTY_BYTE_ARRAY);
        SweepBatchConfig config =
                buildConfigWithOverrides(maxCellTsPairsToExamine, candidateBatchSize, deleteBatchSize);

        return SweepTableResponse.from(runSweep(
                fullSweep, tableRef, decodedStartRow, config, SweepTaskRunner.RunType.WAS_CONSERVATIVE_NOW_THOROUGH));
    }

    private SweepResults runSweep(
            Optional<Boolean> fullSweep,
            TableReference tableRef,
            byte[] decodedStartRow,
            SweepBatchConfig config,
            SweepTaskRunner.RunType runType) {
        if (!fullSweep.isPresent()) {
            log.warn("fullSweep parameter was not specified, defaulting to true");
        }

        if (fullSweep.orElse(true)) {
            log.info(
                    "Running sweep of full table {}, "
                            + "with maxCellTsPairsToExamine: {}, candidateBatchSize: {}, deleteBatchSize: {}, "
                            + "starting from row {}",
                    LoggingArgs.tableRef(tableRef),
                    SafeArg.of("maxCellTsPairsToExamine", config.maxCellTsPairsToExamine()),
                    SafeArg.of("candidateBatchSize", config.candidateBatchSize()),
                    SafeArg.of("deleteBatchSize", config.deleteBatchSize()),
                    UnsafeArg.of("decodedStartRow", decodedStartRow));
            return runFullSweepWithoutSavingResults(tableRef, decodedStartRow, config, runType);
        } else {
            log.info(
                    "Running sweep of a single batch on table {}, "
                            + "with maxCellTsPairsToExamine: {}, candidateBatchSize: {}, deleteBatchSize: {}, "
                            + "starting from row {}",
                    LoggingArgs.tableRef(tableRef),
                    SafeArg.of("maxCellTsPairsToExamine", config.maxCellTsPairsToExamine()),
                    SafeArg.of("candidateBatchSize", config.candidateBatchSize()),
                    SafeArg.of("deleteBatchSize", config.deleteBatchSize()),
                    UnsafeArg.of("decodedStartRow", decodedStartRow));
            return runOneBatchWithoutSavingResults(tableRef, decodedStartRow, config, runType);
        }
    }

    private SweepBatchConfig buildConfigWithOverrides(
            Optional<Integer> maxCellTsPairsToExamine,
            Optional<Integer> candidateBatchSize,
            Optional<Integer> deleteBatchSize) {
        ImmutableSweepBatchConfig.Builder batchConfigBuilder =
                ImmutableSweepBatchConfig.builder().from(sweepBatchConfigSource.getAdjustedSweepConfig());

        maxCellTsPairsToExamine.ifPresent(batchConfigBuilder::maxCellTsPairsToExamine);
        candidateBatchSize.ifPresent(batchConfigBuilder::candidateBatchSize);
        deleteBatchSize.ifPresent(batchConfigBuilder::deleteBatchSize);

        return batchConfigBuilder.build();
    }

    private TableReference getTableRef(String tableName) {
        Preconditions.checkArgument(
                TableReference.isFullyQualifiedName(tableName),
                "Table name is not fully qualified",
                LoggingArgs.safeInternalTableName(tableName));
        return TableReference.createFromFullyQualifiedName(tableName);
    }

    private void checkTableExists(String tableName, TableReference tableRef) {
        Preconditions.checkArgument(
                specificTableSweeper.getKvs().getAllTableNames().contains(tableRef),
                "Table requested to sweep does not exist",
                LoggingArgs.safeInternalTableName(tableName));
    }

    private SweepResults runFullSweepWithoutSavingResults(
            TableReference tableRef,
            byte[] startRow,
            SweepBatchConfig sweepBatchConfig,
            SweepTaskRunner.RunType runType) {
        SweepResults cumulativeResults = SweepResults.createEmptySweepResult(Optional.of(startRow));

        while (cumulativeResults.getNextStartRow().isPresent()) {
            SweepResults results = runOneBatchWithoutSavingResults(
                    tableRef, cumulativeResults.getNextStartRow().get(), sweepBatchConfig, runType);

            specificTableSweeper.updateTimeMetricsOneIteration(
                    results.getTimeInMillis(), results.getTimeElapsedSinceStartedSweeping());
            cumulativeResults = cumulativeResults.accumulateWith(results);
        }

        return cumulativeResults;
    }

    private SweepResults runOneBatchWithoutSavingResults(
            TableReference tableRef,
            byte[] startRow,
            SweepBatchConfig sweepBatchConfig,
            SweepTaskRunner.RunType runType) {
        return specificTableSweeper.runOneIteration(tableRef, startRow, sweepBatchConfig, runType);
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

redpajama_set_name: RedPajamaGithub


text:
'use strict'
import yo from 'yo-yo'

const menuFlotante = yo`

1 Etapa

2 Etapa

3 Etapa

`
module.exports = menuFlotante


text:
import { css } from '@emotion/css';
import { faPlusCircle } from '@fortawesome/free-solid-svg-icons';
import { uniq } from 'lodash';
import * as React from 'react';
import { useLocation, useRouteMatch } from 'react-router-dom';
import { IAbstractAccount, IGameModelWithId } from 'wegas-ts-api';
import { getGameModels, getShadowUserByIds } from '../../API/api';
import { getDisplayName, mapByKey, match } from '../../helper';
import useTranslations from '../../i18n/I18nContext';
import { useLocalStorageState } from '../../preferences';
import { useAccountsByUserIds, useCurrentUser } from '../../selectors/userSelector';
import { MINE_OR_ALL, useEditableGameModels } from '../../selectors/wegasSelector';
import { useAppDispatch } from '../../store/hooks';
import { WindowedContainer } from '../common/CardContainer';
import DebouncedInput from '../common/DebouncedInput';
import DropDownMenu, { itemStyle } from '../common/DropDownMenu';
import DropDownPanel from '../common/DropDownPanel';
import FitSpace from '../common/FitSpace';
import Flex from '../common/Flex';
import IconButton from '../common/IconButton';
import InlineLoading from '../common/InlineLoading';
import SortBy, { SortByOption } from '../common/SortBy';
import { successColor } from '../styling/color';
import { panelPadding } from '../styling/style';
import CreateModel from './CreateModel';
import CreateScenario from './CreateScenario';
import GameModelCard from './GameModelCard';
import InferModel from './InferModel';

interface SortBy {
  createdByName: string;
  name: string;
  createdTime: number;
}

const matchSearch =
  (accountMap: Record<number, IAbstractAccount>, search: string) =>
  (gameModel: IGameModelWithId | 'LOADING') => {
    return match(search, regex => {
      if (gameModel != 'LOADING') {
        const username =
          gameModel.createdById != null ? getDisplayName(accountMap[gameModel.createdById]) : '';
        return (
          (gameModel.name && gameModel.name.match(regex) != null) || username.match(regex) != null
        );
      } else {
        return false;
      }
    });
  };

export interface ScenaristTabProps {
  gameModelType: IGameModelWithId['type'];
}

export default function ScenaristTab({ gameModelType }: ScenaristTabProps): JSX.Element {
  const i18n = useTranslations();
  const dispatch = useAppDispatch();
  const { currentUser, isAdmin } = useCurrentUser();
  const currentUserId = currentUser != null ? currentUser.id : undefined;

  const [statusFilter, setStatusFilter] = useLocalStorageState<IGameModelWithId['status']>(
    'scenarist-status',
    'LIVE',
  );
  const [mineFilter, setMineFilter] = useLocalStorageState<MINE_OR_ALL>(
    'scenarist-mineOrAll',
    isAdmin ? 'MINE' : 'ALL',
  );

  const gamemodels = useEditableGameModels(
    currentUserId,
    gameModelType,
    !isAdmin && statusFilter === 'DELETE' ? 'BIN' : statusFilter,
    isAdmin ? mineFilter : 'MINE',
  );

  React.useEffect(() => {
    if (!isAdmin && statusFilter === 'DELETE') {
      setStatusFilter('BIN');
    }
  }, [isAdmin, statusFilter, setStatusFilter]);

  const [createPanelViewMode, setCreatePanelViewMode] = React.useState<'EXPANDED' | 'COLLAPSED'>(
    'COLLAPSED',
  );
  const [inferModelViewMode, setInferModelViewMode] = React.useState<'EXPANDED' | 'COLLAPSED'>(
    'COLLAPSED',
  );

  const [sortBy, setSortBy] = useLocalStorageState<{ key: keyof SortBy; asc: boolean }>(
    'scenarist-sortby',
    {
      key: 'createdTime',
      asc: false,
    },
  );

  //  const onSortChange = React.useCallback(({ key, asc }: { key: keyof SortBy; asc: boolean }) => {
  //    setSortBy({ key, asc });
  //  }, []);

  const [filter, setFilter] = React.useState('');

  const onFilterChange = React.useCallback((filter: string) => {
    setFilter(filter);
  }, []);

  const sortOptions: SortByOption<SortBy>[] = [
    { key: 'createdTime', label: i18n.date },
    { key: 'name', label: i18n.name },
  ];
  if (isAdmin) {
    sortOptions.push({ key: 'createdByName', label: i18n.createdBy });
  }

  const status = gamemodels.status[gameModelType][statusFilter];

  React.useEffect(() => {
    if (status === 'NOT_INITIALIZED') {
      dispatch(getGameModels({ status: statusFilter, type: gameModelType }));
    }
  }, [statusFilter, gameModelType, status, dispatch]);

  const userIds = uniq(
    gamemodels.gamemodels.flatMap(gm => (gm.createdById != null ? [gm.createdById] : [])),
  );
  const accountsState = useAccountsByUserIds(userIds);
  const accounts = mapByKey(accountsState.accounts, 'parentId');

  const buildCardCb = React.useCallback(
    (gameModel: IGameModelWithId) => <GameModelCard key={gameModel.id} gameModel={gameModel} />,
    [],
  );

  React.useEffect(() => {
    if (isAdmin && accountsState.unknownUsers.length > 0) {
      dispatch(getShadowUserByIds(accountsState.unknownUsers));
    }
  }, [isAdmin, accountsState, dispatch]);

  // Detect any gameModel id in URL
  const location = useLocation();
  const match = useRouteMatch();

  const selectedId = Number.parseInt(location.pathname.replace(match.path + '/', ''));

  if (gamemodels.status[gameModelType][statusFilter] === 'NOT_INITIALIZED') {
    return <InlineLoading />;
  } else {
    const selected = gamemodels.gamemodels.find(gm => gm.id === selectedId);
    const filtered = filter
      ? gamemodels.gamemodels.filter(matchSearch(accounts, filter))
      : gamemodels.gamemodels;

    const sorted = filtered.sort((a, b) => {
      const reverse = sortBy.asc ? 1 : -1;
      if (sortBy.key === 'createdTime') {
        return reverse * (a.createdTime! - b.createdTime!);
      } else if (sortBy.key === 'name') {
        return reverse * (a.name || '').localeCompare(b.name || '');
      } else if (sortBy.key === 'createdByName') {
        const aName = a.createdById != null ? getDisplayName(accounts[a.createdById]) : '';
        const bName = b.createdById != null ? getDisplayName(accounts[b.createdById]) : '';

        return reverse * aName.localeCompare(bName);
      }
      return 0;
    });

    const statusFilterEntries: { value: IGameModelWithId['status']; label: React.ReactNode }[] = [
      {
        value: 'LIVE',
        label:
{i18n.liveGameModels}
,
      },
      {
        value: 'BIN',
        label:
{i18n.archivedGameModels}
,
      },
    ];

    if (isAdmin) {
      statusFilterEntries.push({
        value: 'DELETE',
        label:
{i18n.deletedGameModels}
,
      });
    }
    const dropDownStatus = (
      <DropDownMenu
        menuIcon="CARET"
        entries={statusFilterEntries}
        value={statusFilter}
        onSelect={setStatusFilter}
      />
    );

    const mineFilterEntries: { value: MINE_OR_ALL; label: React.ReactNode }[] = [
      {
        value: 'MINE',
        label:
{i18n.mine}
,
      },
      {
        value: 'ALL',
        label:
{i18n.all}
,
      },
    ];

    const dropDownMine = isAdmin ? (
      <DropDownMenu
        menuIcon="CARET"
        entries={mineFilterEntries}
        value={mineFilter}
        onSelect={setMineFilter}
      />
    ) : null;

    return (
      <FitSpace direction="column" overflow="auto" className={css({ position: 'relative' })}>
        <DropDownPanel
          state={createPanelViewMode}
          onClose={() => {
            setCreatePanelViewMode('COLLAPSED');
          }}
        >
          {createPanelViewMode === 'EXPANDED' ? (
            gameModelType === 'SCENARIO' ? (
              <CreateScenario
                close={() => {
                  setCreatePanelViewMode('COLLAPSED');
                }}
              />
            ) : (
              <CreateModel
                close={() => {
                  setCreatePanelViewMode('COLLAPSED');
                }}
              />
            )
          ) : null}
        </DropDownPanel>

        {gameModelType === 'MODEL' ? (
          <DropDownPanel
            state={inferModelViewMode}
            onClose={() => {
              setInferModelViewMode('COLLAPSED');
            }}
          >
            {inferModelViewMode === 'EXPANDED' ? (
              <InferModel
                close={() => {
                  setInferModelViewMode('COLLAPSED');
                }}
              />
            ) : null}
          </DropDownPanel>
        ) : null}

        <FitSpace direction="column" overflow="auto" className={panelPadding}>
          <Flex
            justify="space-between"
            align="center"
            className={css({
              flexShrink: 0,
              height: '80px',
            })}
          >
            <IconButton
              icon={faPlusCircle}
              iconColor={successColor.toString()}
              onClick={() => {
                setCreatePanelViewMode('EXPANDED');
              }}
              title={gameModelType === 'SCENARIO' ? i18n.createGameModel : i18n.createModel}
            >
              {gameModelType === 'SCENARIO' ? i18n.createGameModel : i18n.createModel}
            </IconButton>

            {gameModelType === 'MODEL' ? (
              <IconButton
                icon={faPlusCircle}
                iconColor={successColor.toString()}
                onClick={() => {
                  setInferModelViewMode('EXPANDED');
                }}
                title={i18n.inferModel}
              >
                {i18n.inferModel}
              </IconButton>
            ) : null}

            <SortBy options={sortOptions} current={sortBy} onChange={setSortBy} />

            {dropDownStatus}
            {dropDownMine}

            <DebouncedInput
              size="SMALL"
              value={filter}
              placeholder={i18n.search}
              onChange={onFilterChange}
            />
          </Flex>
          {status === 'READY' ? (
            <>
              <WindowedContainer
                items={sorted}
                scrollTo={selected}
                emptyMessage={

                    {filter
                      ? gameModelType === 'SCENARIO'
                        ? i18n.noScenariosFound
                        : i18n.noModelsFound
                      : gameModelType === 'SCENARIO'
                      ? i18n.noScenarios
                      : i18n.noModels}

                }
              >
                {buildCardCb}
              </WindowedContainer>
            </>
          ) : (
            <InlineLoading />
          )}
        </FitSpace>
      </FitSpace>
    );
  }
}

//
//<CardContainer>
//          {sorted.map(gameModel => (
//            <GameModelCard key={gameModel.id} gameModel={gameModel} />
//          ))}
//</CardContainer>


text:
package hmm;

import gnu.trove.TIntArrayList;
import optimization.gradientBasedMethods.ProjectedGradientDescent;
import optimization.gradientBasedMethods.ProjectedObjective;
import optimization.gradientBasedMethods.stats.OptimizerStats;
import optimization.linesearch.ArmijoLineSearchMinimizationAlongProjectionArc;
import optimization.linesearch.InterpolationPickFirstStep;
import optimization.linesearch.LineSearchMethod;
import optimization.projections.SimplexProjection;
import optimization.stopCriteria.CompositeStopingCriteria;
import optimization.stopCriteria.ProjectedGradientL2Norm;
import optimization.stopCriteria.StopingCriteria;
import optimization.stopCriteria.ValueDifference;

public class HMMObjective extends ProjectedObjective{

	private static final double GRAD_DIFF = 3;
	public static double INIT_STEP_SIZE=10;
	public static double VAL_DIFF=1000;

	private HMM hmm;
	double[] newPoint  ;

	//posterior[sent num][tok num][tag]=index into lambda
	private int posteriorMap[][][];
	//projection[word][tag].get(occurence)=index into lambda
	private TIntArrayList projectionMap[][];

	//Size of the simplex
	public double scale=10;
	private SimplexProjection projection;

	private int wordFreq[];
	private static int MIN_FREQ=10;
	private int numWordsToProject=0;

	private int n_param;

	public  double loglikelihood;

	public HMMObjective(HMM h){
		hmm=h;

		countWords();
		buildMap();

		gradient=new double [n_param];
		projection = new SimplexProjection(scale);
		newPoint  = new double[n_param];
		setInitialParameters(new double[n_param]);

	}

	/**@brief counts word frequency in the corpus
	 *
	 */
	private void countWords(){
		wordFreq=new int [hmm.emit[0].length];
		for(int i=0;i<hmm.data.length;i++){
			for(int j=0;j<hmm.data[i].length;j++){
				wordFreq[hmm.data[i][j]]++;
			}
		}
	}

	/**@brief build posterior and projection indices
	 *
	 */
	private void buildMap(){
		//number of sentences hidden states and words
		int n_states=hmm.trans.length;
		int n_words=hmm.emit[0].length;
		int n_sents=hmm.data.length;

		n_param=0;
		posteriorMap=new int[n_sents][][];
		projectionMap=new TIntArrayList[n_words][];
		for(int sentNum=0;sentNum<n_sents;sentNum++){
			int [] data=hmm.data[sentNum];
			posteriorMap[sentNum]=new int[data.length][n_states];
			numWordsToProject=0;
			for(int i=0;i<data.length;i++){
				int word=data[i];
				for(int state=0;state<n_states;state++){
					if(wordFreq[word]>MIN_FREQ){
						if(projectionMap[word]==null){
							projectionMap[word]=new TIntArrayList[n_states];
						}
			//			if(posteriorMap[sentNum][i]==null){
			//				posteriorMap[sentNum][i]=new int[n_states];
			//			}

						posteriorMap[sentNum][i][state]=n_param;
						if(projectionMap[word][state]==null){
							projectionMap[word][state]=new TIntArrayList();
							numWordsToProject++;
						}
						projectionMap[word][state].add(n_param);
						n_param++;
					}
					else{
						posteriorMap[sentNum][i][state]=-1;
					}
				}
			}
		}
	}

	@Override
	public double[] projectPoint(double[] point) {
		// TODO Auto-generated method stub
		for(int i=0;i<projectionMap.length;i++){

			if(projectionMap[i]==null){
				//this word is not constrained
				continue;
			}

			for(int j=0;j<projectionMap[i].length;j++){
				TIntArrayList instances=projectionMap[i][j];
				double[] toProject = new double[instances.size()];

				for (int k = 0; k < toProject.length; k++) {
					//	System.out.print(instances.get(k) + " ");
						toProject[k] = point[instances.get(k)];
				}

				projection.project(toProject);
				for (int k = 0; k < toProject.length; k++) {
					newPoint[instances.get(k)]=toProject[k];
				}
			}
		}
		return newPoint;
	}

	@Override
	public double[] getGradient() {
		// TODO Auto-generated method stub
		gradientCalls++;
		return gradient;
	}

	@Override
	public double getValue() {
		// TODO Auto-generated method stub
		functionCalls++;
		return loglikelihood;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < parameters.length; i++) {
			sb.append(parameters[i]+" ");
			if(i%100==0){
				sb.append("\n");
			}
		}
		sb.append("\n");
		/*
		for (int i = 0; i < gradient.length; i++) {
			sb.append(gradient[i]+" ");
			if(i%100==0){
				sb.append("\n");
			}
		}
		sb.append("\n");
		*/
		return sb.toString();
	}

	/**
	 * @param seq
	 * @return posterior probability of each transition
	 */
	public double [][][]forwardBackward(int sentNum){
		int [] seq=hmm.data[sentNum];
		int n_states=hmm.trans.length;
		double a[][]=new double [seq.length][n_states];
		double b[][]=new double [seq.length][n_states];

		int len=seq.length;

		boolean  constrained=
			(projectionMap[seq[0]]!=null);

		//initialize the first step
		for(int i=0;i<n_states;i++){
			a[0][i]=hmm.emit[i][seq[0]]*hmm.pi[i];
			if(constrained){
				a[0][i]*=
					Math.exp(- parameters[ posteriorMap[sentNum][0][i] ] );
			}
			b[len-1][i]=1;
		}

		loglikelihood+=Math.log(hmm.l1norm(a[0]));
		hmm.l1normalize(a[0]);
		hmm.l1normalize(b[len-1]);

		//forward
		for(int n=1;n<len;n++){

			constrained=
				(projectionMap[seq[n]]!=null);

			for(int i=0;i<n_states;i++){
				for(int j=0;j<n_states;j++){
					a[n][i]+=hmm.trans[j][i]*a[n-1][j];
				}
				a[n][i]*=hmm.emit[i][seq[n]];

				if(constrained){
					a[n][i]*=
						Math.exp(- parameters[ posteriorMap[sentNum][n][i] ] );
				}

			}
			loglikelihood+=Math.log(hmm.l1norm(a[n]));
			hmm.l1normalize(a[n]);
		}

		//temp variable for e^{-\lambda}
		double factor=1;
		//backward
		for(int n=len-2;n>=0;n--){

			constrained=
				(projectionMap[seq[n+1]]!=null);

			for(int i=0;i<n_states;i++){
				for(int j=0;j<n_states;j++){

					if(constrained){
						factor=
							Math.exp(- parameters[ posteriorMap[sentNum][n+1][j] ] );
					}else{
						factor=1;
					}

					b[n][i]+=hmm.trans[i][j]*b[n+1][j]*hmm.emit[j][seq[n+1]]*factor;

				}
			}
			hmm.l1normalize(b[n]);
		}

		//expected transition
		double p[][][]=new double [seq.length][n_states][n_states];
		for(int n=0;n<len-1;n++){

			constrained=
				(projectionMap[seq[n+1]]!=null);

			for(int i=0;i<n_states;i++){
				for(int j=0;j<n_states;j++){

					if(constrained){
						factor=
							Math.exp(- parameters[ posteriorMap[sentNum][n+1][j] ] );
					}else{
						factor=1;
					}

					p[n][i][j]=a[n][i]*hmm.trans[i][j]*
						hmm.emit[j][seq[n+1]]*b[n+1][j]*factor;

				}
			}

			hmm.l1normalize(p[n]);
		}
		return p;
	}

	public void optimizeWithProjectedGradientDescent(){
		LineSearchMethod ls =
			new ArmijoLineSearchMinimizationAlongProjectionArc
				(new InterpolationPickFirstStep(INIT_STEP_SIZE));

		OptimizerStats stats = new OptimizerStats();

		ProjectedGradientDescent optimizer = new ProjectedGradientDescent(ls);
		StopingCriteria stopGrad = new ProjectedGradientL2Norm(GRAD_DIFF);
		StopingCriteria stopValue = new ValueDifference(VAL_DIFF);
		CompositeStopingCriteria compositeStop = new CompositeStopingCriteria();
		compositeStop.add(stopGrad);
		compositeStop.add(stopValue);

		optimizer.setMaxIterations(10);
		updateFunction();
		boolean succed = optimizer.optimize(this,stats,compositeStop);
		System.out.println("Ended optimzation Projected Gradient Descent\n" + stats.prettyPrint(1));
		if(succed){
			System.out.println("Ended optimization in " + optimizer.getCurrentIteration());
		}else{
			System.out.println("Failed to optimize");
		}
	}

	@Override
	public void setParameters(double[] params) {
		super.setParameters(params);
		updateFunction();
	}

	private void updateFunction(){

		updateCalls++;
		loglikelihood=0;

		for(int sentNum=0;sentNum<hmm.data.length;sentNum++){
			double [][][]p=forwardBackward(sentNum);

			for(int n=0;n<p.length-1;n++){
				for(int i=0;i<p[n].length;i++){
					if(projectionMap[hmm.data[sentNum][n]]!=null){
						double posterior=0;
						for(int j=0;j<p[n][i].length;j++){
							posterior+=p[n][i][j];
						}
						gradient[posteriorMap[sentNum][n][i]]=-posterior;
					}
				}
			}

			//the last state
			int n=p.length-2;
			for(int i=0;i<p[n].length;i++){
				if(projectionMap[hmm.data[sentNum][n+1]]!=null){

					double posterior=0;
					for(int j=0;j<p[n].length;j++){
						posterior+=p[n][j][i];
					}
					gradient[posteriorMap[sentNum][n+1][i]]=-posterior;

				}
			}
		}

	}

}


text:
import { Action } from '@ngrx/store';
import { WorkItemType } from '../models/work-item-type';

export const GET = '[wi-state] Get';
export const GET_SUCCESS = '[wi-state] GetSuccess';
export const GET_ERROR = '[wi-state] GetError';

export class Get implements Action {
  readonly type = GET;
}

export class GetSuccess implements Action {
  payload: WorkItemType[];
  constructor(payload: WorkItemType[]) {
    this.payload = payload;
  }
  readonly type = GET_SUCCESS;
}

export class GetError implements Action {
  readonly type = GET_ERROR;
}

export type All = Get | GetSuccess | GetError;


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

namespace angeldnd.dap {
    public sealed class DebugHook : RootHook {
        public DebugHook(RootHooks owner, int index) : base(owner, index) {
            Setup(
                "DebugHook",
                (IContext context) => {
                    context.Debugging = true;
            });
        }

        private List<UriMatcher> _AspectPathMatchers = new List<UriMatcher>();
        public int AspectMatchersCount {
            get { return _AspectPathMatchers.Count; }
        }

        public void AddAspectPattern(string contextPathPattern, string aspectPathPattern) {
            UriMatcher matcher = new UriMatcher(contextPathPattern, aspectPathPattern);
            if (matcher.CanMatchAspect()) {
                _AspectPathMatchers.Add(matcher);
            } else {
                Error("Invalid AspectPattern: {0}, {1}", contextPathPattern, aspectPathPattern);
            }
        }

        // Should only be called from IAspect.OnAdded();
        public void _OnAspectAdded(IAspect aspect, string[] contextPathSegments, string[] aspectPathSegments) {
            for (int i = 0; i < _AspectPathMatchers.Count; i++) {
                if (_AspectPathMatchers[i].IsMatched(contextPathSegments, aspectPathSegments)) {
                    aspect.Debugging = true;
                    return;
                }
            }
        }

        protected override void AddSummaryExtraPatterns(Data patterns) {
            for (int i = 0; i < _AspectPathMatchers.Count; i++) {
                patterns.S("aspect_" + i.ToString(),
                        string.Format("{0}:{1}",
                            _AspectPathMatchers[i].ContextPathPatternMatcher.Pattern,
                            _AspectPathMatchers[i].AspectPathPatternMatcher.Pattern));
            }
        }
    }
}


text:
import EventDispatcher = require('../event/EventDispatcher');
import LoaderEvent = require('../event/LoaderEvent');
import URLRequest = require('./URLRequest');
import URLLoaderDataFormat = require('./URLLoaderDataFormat');

/**
 * The URLLoader...
 *
 * @class URLLoader
 * @extends EventDispatcher
 * @module StructureJS
 * @submodule net
 * @param [request=null] {URLRequest}
 * @requires Extend
 * @requires EventDispatcher
 * @requires LoaderEvent
 * @requires URLLoaderDataFormat
 * @requires jQuery
 * @constructor
 * @author Robert S. (www.codeBelt.com)
 */
class URLLoader extends EventDispatcher
{
    /**
     * TODO: YUIDoc_comment
     *
     * @property dataFormat
     * @type {string}
     * @default URLLoaderDataFormat.TEXT
     */
    public dataFormat:string = URLLoaderDataFormat.TEXT;

    /**
     * TODO: YUIDoc_comment
     *
     * @property data
     * @type {any}
     * @default null
     */
    public data:any = null;

    /**
     * TODO: YUIDoc_comment
     *
     * @property complete
     * @type {boolean}
     * @default false
     */
    public complete:boolean = false;

    /**
     * TODO: YUIDoc_comment
     *
     * @property _xhr
     * @type {JQueryXHR}
     * @default null
     * @protected
     */
    protected _xhr:JQueryXHR = null;

    constructor(request:URLRequest = null)
    {
        super();

        if (request)
        {
            this.load(request);
        }
    }

    /**
     * TODO: YUIDoc_comment
     *
     * @method load
     * @param request {URLRequest}
     * @public
     */
    public load(request:URLRequest):void
    {
        this.complete = false;
        var self:URLLoader = this;

        this._xhr = jQuery.ajax({
            url: request.url,
            type: request.method,
            data: request.data,
            contentType: request.contentType,
            dataType: self.dataFormat,
            jsonp: 'callback'
        });
        this._xhr.done(self.onSuccess.bind(this));
        this._xhr.fail(self.onError.bind(this));
    }

    /**
     * @overridden EventDispatcher.destroy
     */
    public destroy():void
    {
        this.abort();

        super.destroy();
    }

    /**
     * TODO: YUIDoc_comment
     *
     * @method abort
     * @public
     */
    public abort():void
    {
        if (this._xhr != null)
        {
            this._xhr.abort();
        }
    }

    /**
     * TODO: YUIDoc_comment
     *
     * @method onError
     * @protected
     */
    protected onError():void
    {
        console.log("[URLLoader] - onError", arguments);
        this.dispatchEvent(new LoaderEvent(LoaderEvent.ERROR));
    }

    /**
     * TODO: YUIDoc_comment
     *
     * @method onSuccess
     * @protected
     */
    protected onSuccess(data):void
    {
        this.complete = true;
        this.dispatchEvent(new LoaderEvent(LoaderEvent.COMPLETE, false, false, this.data));
    }
}

export = URLLoader;


text:
title: A new, open, community-driven Foodsoft platform
categories: hosting
---
As you know, the Foodsoft hosting at [app.foodcoops.net](http://app.foodcoops.net/)
will end this month. But what does that mean?

Benni, who maintained the services over the last years, has no resources for it
anymore. Caused by that the current app.foodcoops.net will be shut down and all
food co-ops using that service need to find a new hosting provider and
transferring their data to them.

We, a small group of people from various food co-ops consisting of Willem from
the Netherlands, Patrick from Austria and André from Germany see the problem
and suggest the following.

## For German and Dutch food cooperatives (and others)

_We want to develop a sustainable process where the users of the Foodsoft-using
food cooperatives are maintaining and developing the infrastructure and their
software._ Basically the online ecosystem needs to be driven by these folks
instead of unknown third parties.

We are interested to work with you to build an open, community-driven and
centrally hosted Foodsoft platform, which will be in place for existing and new
food co-ops. This not only involves the software! It's also about bringing the
people from the cooperatives together to exchange information, discuss topics
and help each other. The new online platform will help us to do so.

What we need and expect from each group

* A permanent contact person plus a fallback person to be able to get in
  contact with your food co-op easily (that needs to be part of your co-op task
  list).
* If you have members in your group that are interested in information
  technology, please ask them if they want to contribute to the central
  platform to bring in their skills.
* A (small) fee to pay the hardware, electricity etc.
* Helping to create a forum where the members of various food co-op discuss
  topics, answering support questions etc.

The next steps (for food co-ops which do not want to use the Austrian hosting)

* The current hardware and infrastructure (at app.foodcoops.net) will be shut
  down, therefore we have to migrate your data to our new systems.
* **Very Important To-Do:** You have to send an email to foodsoft[ät]foodcoops.net
  (plus CC to transition[ät]foodcoops.nl) that your group wants to transition as
  laid out here. Tell your group name which can be identified by your Foodsoft
  internet address e.g. `https://app.foodcoops.net/schalottchen`. The group name
  in this example is _schalottchen_. The email should contain the title
  _"Transition (your group name) to foodcoops.nl"_.  If you don't send an email,
  you agree that no data will be handed over to us.
* Co-ops, which agreed to the transition, will be migrated and hosted by a
  new IT team which is currently forming (Willem, André and more). Please send
  us an email to transition[ät]foodcoops.net if you want to join. The transition
  will start end of July beginning of August. (The current Foodsoft will be hosted
  until we migrated everyone who contacted us.)

## For the Austrian food cooperatives

In Austria an alternative hosting provider is already set under
[foodcoops.at](https://foodcoops.at/). It will be maintained by a working group of the
upcoming "IG FoodCoops" and therefore integrated in the same structure, which
will be used for all other food co-op related issues in Austria. Martin and
Patrick from Austria are already in contact with most of the Austrian
cooperatives since months and cleared up the process for most of them already.

If there was no communication about the Foodsoft transition yet, please contact
them via info[ät]foodcoops.at with the wish for transition. If you want to
continue with your existing data (users, suppliers, articles, ...) you need to
write a mail to support[ät]foodcoops.net with the wish for handing over the
existing data to Martin/Patrick from Austria and put info[ät]foodcoops.at into
CC if you haven't done it yet.

It's also possible for non-Austrian food co-ops to use the infrastructure, but
it will cost €2/user/year. The money which exceeds the hosting costs will be
used to promote the idea of food cooperatives (e.g. with flyers, discussion
forums) in Austria.

Why is there a different hosting for Austrians and others? Austrian food co-ops
already built an environment, processes and infrastructure which works
basically how we wish to have it on a global level. The Austrian platform is a
national platform, which provides various tools, like Foodsoft (ordering and
more), Discourse (forum in German) and others, and may provide information of
interest specifically for the region or country. So we can learn from the
Austrian groups.

We hope that helps,
Willem, Patrick and André


text:
package org.python.exceptions;

public class NotImplementedError extends org.python.exceptions.RuntimeError {
    public NotImplementedError() {
        super();
    }

    public NotImplementedError(String msg) {
        super(msg);
    }
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\WorkSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Works');
$this->params['breadcrumbs'][] = $this->title;
?>

<?php if ($model==null):?>

<?php else:?>

<?php endif;?>

  		List of Works

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

<?php
	$gridColumns = [
	/*
	['header'=>'Put Photo',
	'format'=>'raw',
	  'value'=>function($model,$key,$index,$column)
	            {
	               return Html::a('click','gpsphu://w'.$model->id);
	            }
	],
	*/
            ['class' => '\yii\grid\SerialColumn'],

        'workid',
		['header'=>'Division',
			'attribute'=>'division_id',
		 'value'=>function($model,$key,$index,$column){return $model->division?$model->division->name_en:'';},
         'filter'=>\yii\helpers\ArrayHelper::map(\app\modules\work\models\Division::find()->asArray()->all(),'id','name_en')
			 ],

            'name_'.Yii::$app->language.':ntext',
		 ['header'=>'Work Type','attribute'=>'work_type_id','value'=>function($model,$key,$index,$column){
		$name='name_'.Yii::$app->language;
		return $model->workType?$model->workType->$name:'';},
		'filter'=>\yii\helpers\ArrayHelper::map(\app\modules\work\models\WorkType::find()->asArray()->all(),'id','name_en'),
		],

            /*
			['header'=>'Department','value'=>function($model,$key,$index,$column){
		$name='name_'.Yii::$app->language;
		return $model->dept?$model->dept->$name:'';}],
			*/
			'totvalue',
			//'dateofsanction',

            ['class' => '\yii\grid\ActionColumn'

			 ],

    ];
	//$model1=new \app\models\WorkSearch;
	$filters='';//to be identified later
	?>
	<?php     echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,

    'columns' => $gridColumns,
		'tableOptions'=>['class'=>'small table table-striped'],

    ]);?>

<?php if ($model!=null):?>

<?=$this->render('_form',['model'=>$model]) ?>

<?php endif;?>


text:
<?php

namespace JMS\SerializerBundle\Tests\Fixtures;

use JMS\SerializerBundle\Annotation\XmlRoot;
use JMS\SerializerBundle\Annotation\Type;

/**
 * @XmlRoot("person_location")
 */
class PersonLocation
{
    /**
     * @Type("JMS\SerializerBundle\Tests\Fixtures\Person")
     */
    public $person;

    /**
     * @Type("string")
     */
    public $location;
}


text:
police-stats-scraper
====================

The police stats are released in an unusable format. This scraper fixes that.

Usage: ./scrape.py <police stats.xls> <start year> <end year>

Currently the police stats are released per police station in a way that doesn't allow for pivoting or any sort of analysis. This scraper outputs the data in a saner format with the following headings:

Province,Police Station,Crime,Year,Incidents


text:
#pragma once
#ifndef THRILL_NET_TCP_SOCKET_HEADER
#define THRILL_NET_TCP_SOCKET_HEADER

#include <thrill/common/logger.hpp>
#include <thrill/common/string.hpp>
#include <thrill/common/system_exception.hpp>
#include <thrill/net/tcp/socket_address.hpp>

#include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

#include <cassert>
#include <cerrno>
#include <cstring>
#include <string>
#include <utility>

namespace thrill {
namespace net {
namespace tcp {

//! \addtogroup net_tcp TCP Socket API
//! \ingroup net
//! \{

/*!
 * Socket is a light-weight wrapper around the BSD socket API. Functions all
 * have plain return values and do not through exceptions.
 *
 * Not all functions in this class follow the normal naming conventions, because
 * they are wrappers around the equally named functions of the socket API.
 */
class Socket
{
    static constexpr bool debug = false;
    static constexpr bool debug_data = false;

public:
    //! \name Creation
    //! \{

    //! construct new Socket object from existing file descriptor.
    explicit Socket(int fd)
        : fd_(fd) {
        SetNoDelay(true);
        SetSndBuf(128 * 1024);
        SetRcvBuf(128 * 1024);
    }

    //! default constructor: invalid socket.
    Socket() : fd_(-1) { }

    //! non-copyable: delete copy-constructor
    Socket(const Socket&) = delete;
    //! non-copyable: delete assignment operator
    Socket& operator = (const Socket&) = delete;
    //! move-constructor: move file descriptor
    Socket(Socket&& s) noexcept : fd_(s.fd_) { s.fd_ = -1; }
    //! move-assignment operator: move file descriptor
    Socket& operator = (Socket&& s) {
        if (this == &s) return *this;
        if (fd_ >= 0) close();
        fd_ = s.fd_;
        s.fd_ = -1;
        return *this;
    }

    ~Socket() {
        if (fd_ >= 0) close();
    }

    //! Create a new stream socket.
    static Socket Create() {
#ifdef SOCK_CLOEXEC
        int fd = ::socket(PF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
#else
        int fd = ::socket(PF_INET, SOCK_STREAM, 0);
#endif
        if (fd < 0) {
            LOG << "Socket::Create()"
                << " fd=" << fd
                << " error=" << strerror(errno);
        }

#ifndef SOCK_CLOEXEC
        if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
            throw common::ErrnoException(
                      "Error setting FD_CLOEXEC on network socket");
        }
#endif

        return Socket(fd);
    }

    //! Create a pair of connected stream sockets. Use this for internal local
    //! test connection pairs.
    static std::pair<Socket, Socket> CreatePair() {
        int fds[2];
#ifdef SOCK_CLOEXEC
        int r = ::socketpair(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fds);
#else
        int r = ::socketpair(PF_UNIX, SOCK_STREAM, 0, fds);
#endif
        if (r != 0) {
            LOG1 << "Socket::CreatePair()"
                 << " error=" << strerror(errno);
            abort();
        }

#ifndef SOCK_CLOEXEC
        if (fcntl(fds[0], F_SETFD, FD_CLOEXEC) != 0) {
            throw common::ErrnoException(
                      "Error setting FD_CLOEXEC on network socket");
        }
        if (fcntl(fds[1], F_SETFD, FD_CLOEXEC) != 0) {
            throw common::ErrnoException(
                      "Error setting FD_CLOEXEC on network socket");
        }
#endif
        return std::make_pair(Socket(fds[0]), Socket(fds[1]));
    }

    //! \}

    //! \name Status
    //! \{

    //! Check whether the contained file descriptor is valid.
    bool IsValid() const
    { return fd_ >= 0; }

    //! Return the associated file descriptor
    int fd() const { return fd_; }

    //! Query socket for its current error state.
    int GetError() const {
        int socket_error = -1;
        socklen_t len = sizeof(socket_error);
        getsockopt(SOL_SOCKET, SO_ERROR, &socket_error, &len);
        return socket_error;
    }

    //! Turn socket into non-blocking state.
    bool SetNonBlocking(bool non_blocking) {
        assert(IsValid());

        if (non_blocking == non_blocking_) return true;

        int old_opts = fcntl(fd_, F_GETFL);

        int new_opts = non_blocking
                       ? (old_opts | O_NONBLOCK) : (old_opts & ~O_NONBLOCK);

        if (fcntl(fd_, F_SETFL, new_opts) != 0)
        {
            LOG << "Socket::SetNonBlocking()"
                << " fd_=" << fd_
                << " non_blocking=" << non_blocking
                << " error=" << strerror(errno);
            return false;
        }

        non_blocking_ = non_blocking;
        return true;
    }

    //! Return the current local socket address.
    SocketAddress GetLocalAddress() const {
        assert(IsValid());

        struct sockaddr_in6 sa;
        socklen_t salen = sizeof(sa);

        if (getsockname(
                fd_, reinterpret_cast<struct sockaddr*>(&sa), &salen) != 0)
        {
            LOG << "Socket::GetLocalAddress()"
                << " fd_=" << fd_
                << " error=" << strerror(errno);
            return SocketAddress();
        }

        return SocketAddress(reinterpret_cast<struct sockaddr*>(&sa), salen);
    }

    //! Return the current peer socket address.
    SocketAddress GetPeerAddress() const {
        assert(IsValid());

        struct sockaddr_in6 sa;
        socklen_t salen = sizeof(sa);

        if (getpeername(
                fd_, reinterpret_cast<struct sockaddr*>(&sa), &salen) != 0)
        {
            LOG << "Socket::GetPeerAddress()"
                << " fd_=" << fd_
                << " error=" << strerror(errno);
            return SocketAddress();
        }

        return SocketAddress(reinterpret_cast<struct sockaddr*>(&sa), salen);
    }

    //! \}

    //! \name Close
    //! \{

    //! Close socket.
    bool close() {
        assert(IsValid());

        if (::close(fd_) != 0)
        {
            LOG << "Socket::close()"
                << " fd_=" << fd_
                << " error=" << strerror(errno);
            return false;
        }

        LOG << "Socket::close()"
            << " fd_=" << fd_
            << " closed";

        fd_ = -1;

        return true;
    }

    //! \}

    //! \name Connect, Bind and Accept Functions
    //! \{

    //! Bind socket to given SocketAddress for listening or connecting.
    bool bind(const SocketAddress& sa) {
        assert(IsValid());
        assert(sa.IsValid());

        int r = ::bind(fd_, sa.sockaddr(), sa.socklen());

        if (r != 0) {
            LOG << "Socket::bind()"
                << " fd_=" << fd_
                << " sa=" << sa
                << " return=" << r
                << " error=" << strerror(errno);
        }

        return (r == 0);
    }

    //! Initial socket connection to address
    int connect(const SocketAddress& sa) {
        assert(IsValid());
        assert(sa.IsValid());

        int r = ::connect(fd_, sa.sockaddr(), sa.socklen());

        if (r == 0)
            return r;

        LOG << "Socket::connect()"
            << " fd_=" << fd_
            << " sa=" << sa
            << " return=" << r
            << " error=" << strerror(errno);

        return r;
    }

    //! Turn socket into listener state to accept incoming connections.
    bool listen(int backlog = 0) {
        assert(IsValid());

        if (backlog == 0) backlog = SOMAXCONN;

        int r = ::listen(fd_, backlog);

        if (r == 0) {
            LOG << "Socket::listen()"
                << " fd_=" << fd_;
        }
        else {
            LOG << "Socket::listen()"
                << " fd_=" << fd_
                << " error=" << strerror(errno);
        }
        return (r == 0);
    }

    //! Wait on socket until a new connection comes in.
    Socket accept() const {
        assert(IsValid());

        struct sockaddr_in6 sa;
        socklen_t salen = sizeof(sa);

        int newfd = ::accept(fd_,
                             reinterpret_cast<struct sockaddr*>(&sa), &salen);
        if (newfd < 0) {
            LOG << "Socket::accept()"
                << " fd_=" << fd_
                << " error=" << strerror(errno);
            return Socket();
        }

        LOG << "Socket::accept()"
            << " fd_=" << fd_
            << " newfd=" << newfd;

        return Socket(newfd);
    }

    //! \}

    //! \name Send and Recv Functions
    //! \{

    //! Send (data,size) to socket (BSD socket API function wrapper), for
    //! blocking sockets one should probably use send() instead of this
    //! lower-layer functions.
    ssize_t send_one(const void* data, size_t size, int flags = 0) {
        assert(IsValid());

        if (debug) {
            LOG << "Socket::send_one()"
                << " fd_=" << fd_
                << " size=" << size
                << " data=" << MaybeHexdump(data, size)
                << " flags=" << flags;
        }

        ssize_t r = ::send(fd_, data, size, flags);

        LOG << "done Socket::send_one()"
            << " fd_=" << fd_
            << " return=" << r;

        return r;
    }

    //! Send (data,size) to socket, retry sends if short-sends occur.
    ssize_t send(const void* data, size_t size, int flags = 0) {
        assert(IsValid());

        if (debug) {
            LOG << "Socket::send()"
                << " fd_=" << fd_
                << " size=" << size
                << " data=" << MaybeHexdump(data, size)
                << " flags=" << flags;
        }

        const char* cdata = static_cast<const char*>(data);
        size_t wb = 0; // written bytes

        while (wb < size)
        {
            ssize_t r = ::send(fd_, cdata + wb, size - wb, flags);

            if (r <= 0) {
                // an error occured, check errno.
                if (errno == EAGAIN) continue;

                LOG << "done Socket::send()"
                    << " fd_=" << fd_
                    << " return=" << r
                    << " errno=" << strerror(errno);

                return r;
            }

            wb += r;
        }

        LOG << "done Socket::send()"
            << " fd_=" << fd_
            << " return=" << wb;

        return wb;
    }

    //! Send (data,size) to destination
    ssize_t sendto(const void* data, size_t size, int flags,
                   const SocketAddress& dest) {
        assert(IsValid());

        if (debug) {
            LOG << "Socket::sendto()"
                << " fd_=" << fd_
                << " size=" << size
                << " data=" << MaybeHexdump(data, size)
                << " flags=" << flags
                << " dest=" << dest;
        }

        ssize_t r = ::sendto(fd_, data, size, flags,
                             dest.sockaddr(), dest.socklen());

        LOG << "done Socket::sendto()"
            << " fd_=" << fd_
            << " return=" << r;

        return r;
    }

    //! Recv (out_data,max_size) from socket (BSD socket API function wrapper)
    ssize_t recv_one(void* out_data, size_t max_size, int flags = 0) {
        assert(IsValid());

        // this is a work-around, since on errno is spontaneously == EINVAL,
        // with no relationship to recv() -tb 2015-08-28
        errno = 0;

        LOG << "Socket::recv_one()"
            << " fd_=" << fd_
            << " max_size=" << max_size
            << " flags=" << flags
            << " errno=" << errno;

        ssize_t r = ::recv(fd_, out_data, max_size, flags);

        if (debug) {
            LOG << "done Socket::recv_one()"
                << " fd_=" << fd_
                << " return=" << r
                << " errno=" << errno
                << " data=" << (r >= 0 ? MaybeHexdump(out_data, r) : "<error>");
        }

        return r;
    }

    //! Receive (data,size) from socket, retry recvs if short-reads occur.
    ssize_t recv(void* out_data, size_t size, int flags = 0) {
        assert(IsValid());

        LOG << "Socket::recv()"
            << " fd_=" << fd_
            << " size=" << size
            << " flags=" << flags;

        char* cdata = static_cast<char*>(out_data);
        size_t rb = 0; // read bytes

        while (rb < size)
        {
            ssize_t r = ::recv(fd_, cdata + rb, size - rb, flags);

            if (r <= 0) {
                // an error occured, check errno.
                if (errno == EAGAIN) continue;

                LOG << "done Socket::recv()"
                    << " fd_=" << fd_
                    << " size=" << size
                    << " return=" << r
                    << " errno=" << strerror(errno);

                return r;
            }

            rb += r;
        }

        if (debug) {
            LOG << "done Socket::recv()"
                << " fd_=" << fd_
                << " return=" << rb
                << " data=" << MaybeHexdump(out_data, rb);
        }

        return rb;
    }

    //! Recv (out_data,max_size) and source address from socket (BSD socket API
    //! function wrapper)
    ssize_t recvfrom(void* out_data, size_t max_size, int flags = 0,
                     SocketAddress* out_source = nullptr) {
        assert(IsValid());

        LOG << "Socket::recvfrom()"
            << " fd_=" << fd_
            << " max_size=" << max_size
            << " flags=" << flags
            << " out_socklen=" << (out_source ? out_source->socklen() : 0);

        socklen_t out_socklen = out_source ? out_source->socklen() : 0;

        ssize_t r = ::recvfrom(fd_, out_data, max_size, flags,
                               out_source ? out_source->sockaddr() : nullptr,
                               &out_socklen);

        if (debug) {
            LOG << "done Socket::recvfrom()"
                << " fd_=" << fd_
                << " return=" << r
                << " data="
                << (r >= 0 ? MaybeHexdump(out_data, r) : "<error>")
                << " out_source="
                << (out_source ? out_source->ToStringHostPort() : "<null>");
        }

        return r;
    }

    //! \}

    //! \name Socket Options and Accelerations
    //! \{

    //! Perform raw getsockopt() operation on socket.
    int getsockopt(int level, int optname,
                   void* optval, socklen_t* optlen) const {
        assert(IsValid());

        int r = ::getsockopt(fd_, level, optname, optval, optlen);

        if (r != 0)
            LOG << "Socket::getsockopt()"
                << " fd_=" << fd_
                << " level=" << level
                << " optname=" << optname
                << " optval=" << optval
                << " optlen=" << optlen
                << " error=" << strerror(errno);

        return r;
    }

    //! Perform raw setsockopt() operation on socket.
    int setsockopt(int level, int optname,
                   const void* optval, socklen_t optlen) {
        assert(IsValid());

        int r = ::setsockopt(fd_, level, optname, optval, optlen);

        if (r != 0)
            LOG << "Socket::setsockopt()"
                << " fd_=" << fd_
                << " level=" << level
                << " optname=" << optname
                << " optval=" << optval
                << " optlen=" << optlen
                << " error=" << strerror(errno);

        return r;
    }

    //! Enable sending of keep-alive messages on connection-oriented sockets.
    void SetKeepAlive(bool activate = true);

    //! Enable SO_REUSEADDR, which allows the socket to be bound more quickly to
    //! previously used ports.
    void SetReuseAddr(bool activate = true);

    //! If set, disable the Nagle algorithm. This means that segments are always
    //! sent as soon as possible, even if there is only a small amount of data.
    void SetNoDelay(bool activate = true);

    //! Set SO_SNDBUF socket option.
    void SetSndBuf(size_t size);

    //! Set SO_RCVBUF socket option.
    void SetRcvBuf(size_t size);

    //! \}

private:
    //! the file descriptor of the socket.
    int fd_;

    //! flag whether the socket is set to non-blocking
    bool non_blocking_ = false;

    //! return hexdump or just [data] if not debugging
    static std::string MaybeHexdump(const void* data, size_t size) {
        if (debug_data)
            return common::Hexdump(data, size);
        else
            return "[data]";
    }
};

// \}

} // namespace tcp
} // namespace net
} // namespace thrill

#endif // !THRILL_NET_TCP_SOCKET_HEADER

/******************************************************************************/


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>pygccxml.declarations.declaration.location_t</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

pygccxml

        Package pygccxml ::
        Package declarations ::
        Module declaration ::
        Class location_t

type location_t

source code

object --+
         |
        location_t

provides information about the location of the declaration within the
  source file

    Instance Methods

          __init__(self,
        file_name='',
        line=-1)

            source code

          __eq__(self,
        other)

            source code

          __ne__(self,
        other)

            source code

          __lt__(self,
        other)

            source code

          as_tuple(self)

      return tuple(self.file_name, self.line)

            source code

    Properties

        file_name

      absolute source file name, type string

        line

      line number, type int

    Method Details

__init__(self,
        file_name='',
        line=-1)

(Constructor)

  	source code

Overrides:
        object.__init__

(inherited documentation)

    Property Details

file_name

absolute source file name, type string

Get Method:

_get_file_name(self)

Set Method:

_set_file_name(self,
        new_file_name)

line

line number, type int

Get Method:

_get_line(self)

Set Method:

_set_line(self,
        new_line)

         Home

         Trees

         Indices

         Help

pygccxml

    Generated by Epydoc 3.0.1
    on Mon Oct 20 09:00:19 2008

      http://epydoc.sourceforge.net


text:
namespace ipc_fuzzer {

struct FileHeader {
  static const uint32_t kMagicValue = 0x1bcf11ee;
  static const uint32_t kCurrentVersion = 1;

  uint32_t magic;
  uint32_t version;
  uint32_t message_count;
  uint32_t name_count;
};

struct NameTableEntry {
  uint32_t type;
  uint32_t string_table_offset;
};

}  // namespace ipc_fuzzer

#endif  // TOOLS_IPC_FUZZER_MESSAGE_LIB_MESSAGE_FILE_FORMAT_H_


text:
package org.eclipse.bpmn2.modeler.examples.customtask;

import org.eclipse.bpmn2.modeler.core.adapters.ExtendedPropertiesAdapter;
import org.eclipse.bpmn2.modeler.examples.customtask.MyModel.MyEventDefinition;
import org.eclipse.emf.common.notify.AdapterFactory;

public class MyEventDefinitionPropertiesAdapter extends ExtendedPropertiesAdapter<MyEventDefinition> {

	public MyEventDefinitionPropertiesAdapter(AdapterFactory adapterFactory, MyEventDefinition object) {
		super(adapterFactory, object);
	}

}


text:
id: security-architecture
title: Security Architecture
---

Hydra is built with tough security in mind.

<!-- toc -->

## OAuth 2.0 Security Overview

Hydra is an implementation of the security-first Fosite OAuth 2.0 SDK
([https://github.com/ory/fosite](https://github.com/ory/fosite)). Fosite
respects the
[OAuth 2.0 Threat Model and Security Considerations](https://tools.ietf.org/html/rfc6819#section-5.1.5.3)
by the IETF, specifically:

- No Cleartext Storage of Credentials
- Encryption of Credentials
- Use Short Expiration Time
- Limit Number of Usages or One-Time Usage
- Bind Token to Client id
- Automatic Revocation of Derived Tokens If Abuse Is Detected
- Binding of Refresh Token to "client_id"
- Refresh Token Rotation
- Revocation of Refresh Tokens
- Validate Pre-Registered "redirect_uri"
- Binding of Authorization "code" to "client_id"
- Binding of Authorization "code" to "redirect_uri"
- Opaque access tokens
- Opaque refresh tokens
- Ensure Confidentiality of Requests
- Use of Asymmetric Cryptography
- Enforcing random states: Without a random-looking state or OpenID Connect
  nonce the request will fail.

Additionally these safeguards are implemented:

- Advanced Token Validation: Tokens are laid out as
  <key>.<signature> where <signature> is created using
  HMAC-SHA256 using a global secret.

### Advanced Token Validation (Datastore Security)

For a OAuth2 access token, refresh token or authorize code to be valid, one
requires both the key and the signature (formatted as
<key>.<signature>). Only the signature is stored in the datastore
(SQL), thus a compromised datastore will not allow an attacker to gain access to
any valid authorize codes, access tokens, or refresh tokens.

Because HMAC-SHA256 is used, the System Secret is required to create valid
key-signature pairs, rendering an attacker unable to inject new codes or tokens
into a compromised datastore.

## Cryptography

Hydra uses different cryptographic methods, this is an overview of all of them.

### AES-GCM

AES-GCM is used to encrypt JWKs at rest using a key size of 256 bit which
exceeds requirements by Lenstra, ECRYPT II, NIST, ANSSI, and BSI, see
[https://www.keylength.com/en/compare/](https://www.keylength.com/en/compare/).

GCM (Galois/Counter Mode) is an authenticated encryption algorithm designed to
provide both data authenticity (integrity) and confidentiality. GCM uses a nonce
("IV") that has an upper limit of 2^32 nonces. If more nonces are used, there is
risk of repeats. This means that you risk collisions when storing more than 2^32
documents authenticated with GCM. Because AES-GCM is only used to encrypt data
at rest, this is might only impose a problem if

1. more than 2^32 documents are stored using AES-GCM
2. an attacker gains access to the datastore where > 2^32 documents are
   stored
3. the attacker is able to exploit repeats, for example by authenticating
   malicious documents

### RS256

RSASSA-PKCS1-v1_5 using SHA-256 (RS256) is used to sign JWTs. Its use is
recommended by the JWA specification, see
[https://www.rfc-editor.org/rfc/rfc7518.txt](https://www.rfc-editor.org/rfc/rfc7518.txt)

The RSA Key size is 4096 bit long, exceeding the minimum requirement of 2048 bit
by
[https://www.rfc-editor.org/rfc/rfc7518.txt](https://www.rfc-editor.org/rfc/rfc7518.txt).

Recommendations from NIST, ANSSI, IAD-NSA, BSI, Lenstra and others vary between
1300 and 2048 bit key lengths for asymmetric cryptography based on discrete
logarithms (RSA). 4096 exceeds all recommendations for 2017 from all
authorities, see
[https://www.keylength.com/en/compare/](https://www.keylength.com/en/compare/).

### HMAC-SHA256

HMAC (FIPS 198) with SHA256 (FIPS 180-4) is used to sign access tokens,
authorize codes and refresh tokens. SHA-2 (with 256 bit) is encouraged by NIST,
see
[http://csrc.nist.gov/groups/ST/hash/policy.html](http://csrc.nist.gov/groups/ST/hash/policy.html)

### BCrypt

BCrypt is used to hash client credentials at rest. It is not officially
recommended by NIST as it is not based on hashing primitives such as SHA-2, but
rather on Blowfish. However, BCrypt is much stronger than any other (salted)
hashing method for passwords, has wide adoption and is an official golang/x
library.

I recommend reading this thread on Security Stack Exchange on BCrypt, SCrypt and
PBKDF2:
[https://security.stackexchange.com/questions/4781/do-any-security-experts-recommend-bcrypt-for-password-storage](https://security.stackexchange.com/questions/4781/do-any-security-experts-recommend-bcrypt-for-password-storage)

Be aware that BCrypt causes very high CPU loads, depending on the Workload
Factor. We strongly advise reducing the number of requests that use Basic
Authorization.

## How does Access Control work with Hydra?

See [OAuth 2.0 Token Introspection](guides/oauth2-token-introspection).


text:
package logsearchForCloudFoundry;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.cluster.State;
import io.searchbox.indices.aliases.AddAliasMapping;
import io.searchbox.indices.aliases.AliasMapping;
import io.searchbox.indices.aliases.ModifyAliases;
import io.searchbox.indices.aliases.RemoveAliasMapping;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.cloudfoundry.client.lib.CloudCredentials;
import org.cloudfoundry.client.lib.CloudFoundryClient;
import org.cloudfoundry.client.lib.domain.CloudSpace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.stereotype.Component;

import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class TenantAliasCreator {
	@Autowired
	private OAuth2ClientContext oauth2Context;

	@Autowired
	private SimpleUAAClient uaaClient = null;

	@Value("${cloudfoundry.cloudControllerUri}")
    private String cloudControllerUri;

	@Value("${logsearch.elasticsearchAdminUri}")
    private String elasticsearchAdminUri;

	static Logger log = Logger.getLogger(TenantAliasCreator.class.getName());
	private CloudFoundryClient cloudFoundryClient = null;
	private JestClient jestClient = null;
	private Map<UUID, String> authorizedSpaces = new HashMap<UUID, String> ();
	private Map<String, String> tenantIndexAliases = new HashMap<String, String> ();

	private String tenantUsername;

	private URL getCloudControllerUrl() {
		URL cloudControllerUrl = null;
		try {
			cloudControllerUrl = new URL(cloudControllerUri);
		} catch (MalformedURLException e) {
			log.error(e);
			e.printStackTrace();
		}
		return cloudControllerUrl;
	}

	public String fetchTenantAlias(String originalIndexName) {
		setupTenantAliases();
		if (tenantIndexAliases.containsKey(originalIndexName)) {
			return tenantIndexAliases.get(originalIndexName);
		}
		return tenantUsername + "-" + originalIndexName;
	}

	private void setupTenantAliases() {
		if (!tenantIndexAliases.isEmpty())
			return; //Only setup Tenant Aliases once / session

		tenantUsername = uaaClient.getUserInfo().getUserName();

		log.debug("Setting up tenant aliases for: " + tenantUsername);

		tenantIndexAliases.put(".kibana", ".kibana"); //Shared kibana index

		Map<String, Object> authorisedSpaceFilter = createAuthorisedSpacesFilter();
		ArrayList<String> indexNames = getIndexNames();

		ArrayList<AliasMapping> removeAliasActions = new ArrayList<AliasMapping>();
		ArrayList<AliasMapping> addAliasActions = new ArrayList<AliasMapping>();
		for (String indexName : indexNames) {
			if (indexName.contains("logstash-")) {
				String aliasName = tenantUsername + "-" + indexName;

				log.debug("Adding alias: " + aliasName + " for index: " + indexName);

				removeAliasActions.add(new RemoveAliasMapping.Builder(indexName, aliasName).build());
				addAliasActions.add(new AddAliasMapping.Builder(indexName, aliasName).setFilter(authorisedSpaceFilter).build());
				tenantIndexAliases.put(indexName, aliasName);
			}
		}
		ModifyAliases modifyAliases = new ModifyAliases.Builder(removeAliasActions).addAlias(addAliasActions).build();

		try {
			log.debug("Sending alias commands to ES: " + modifyAliases.toString());
			JestResult result = getJestClient().execute(modifyAliases);
	        if (!result.isSucceeded()) {
	        	throw new Exception(result.getErrorMessage());
	        }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e);
			e.printStackTrace();
		}

	}

	private ArrayList<String> getIndexNames() {
		ArrayList<String> indexNames = new ArrayList<String>();
		try {
			JestResult result = getJestClient().execute(new State.Builder().build());
			JsonObject indiciesJson = result.getJsonObject().getAsJsonObject("metadata").getAsJsonObject("indices");
			for (Entry<String, JsonElement> index : indiciesJson.entrySet()) {
				indexNames.add(index.getKey());
			}
		} catch (Exception e1) {
			log.error(e1);
			e1.printStackTrace();
		}
		return indexNames;
	}

	private Map<String, Object> createAuthorisedSpacesFilter() {
		fetchAuthorisedSpaces();
		Map<String, Object> authorizedSpaceFilter = ImmutableMap.<String, Object>builder()
	            .put("terms", ImmutableMap.<String, Set<UUID>>builder()
	                    .put("cf_space_id", authorizedSpaces.keySet())
	                    .build())
	            .build();
		return authorizedSpaceFilter;
	}

	private void fetchAuthorisedSpaces() {
		if (!authorizedSpaces.isEmpty())
			return; //Only lookup spaces once / session

		for (CloudSpace space : getCloudFoundryClient().getSpaces()) {
				authorizedSpaces.put(space.getMeta().getGuid(), space.getName());
		}
	}

	private JestClient getJestClient() {
		 if (this.jestClient == null) {
			 JestClientFactory factory = new JestClientFactory();
			 factory.setHttpClientConfig(new HttpClientConfig
			                        .Builder(elasticsearchAdminUri)
			                        .multiThreaded(true)
			                        .build());
			 this.jestClient = factory.getObject();
		 }
		 return this.jestClient;
	}

	private CloudFoundryClient getCloudFoundryClient() {
		if (this.cloudFoundryClient == null) {
			CloudCredentials credentials = new CloudCredentials(oauth2Context.getAccessToken());
			this.cloudFoundryClient = new CloudFoundryClient(credentials, getCloudControllerUrl());
		}
		return this.cloudFoundryClient;
	}

}


text:
module ReconciledRecordsHelper
end


text:
/*
* (C) 2015 Yandex LLC (https://yandex.com/)
*
* The source code of Java SDK for Yandex.Disk REST API
* is available to use under terms of Apache License,
* Version 2.0. See the file LICENSE for the details.
*/

package com.yandex.disk.rest.example;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;

abstract class ContextMenuDialogFragment extends DialogFragment {

    protected static final String CREDENTIALS = "example.credentials";
    protected static final String LIST_ITEM = "example.list.item";

    protected Credentials credentials;
    protected ListItem listItem;

    protected static <T extends ContextMenuDialogFragment> T newInstance(T fragment, Credentials credentials, ListItem listItem) {
        Bundle args = new Bundle();
        args.putParcelable(CREDENTIALS, credentials);
        args.putParcelable(LIST_ITEM, listItem);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        credentials = getArguments().getParcelable(CREDENTIALS);
        listItem = getArguments().getParcelable(LIST_ITEM);
    }
}


text:
<!DOCTYPE html>

  <title>Sage - A Collaboration Tool</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

SAGE

"By Students, for students"

<button class="btn btn-default pull-left hvr-underline-from-center" style ='background-color: #488957'; contenteditable="false">About</button>

<button onclick="GoToLI()" class="btn btn-default pull-left hvr-underline-from-center" style ='background-color: #488957'; contenteditable="false">Login</button>

  <form id="nlk-search-form" method="get" action="/" target="_self">

    <button style='background-color: #488957; height: 30px;'; class="btn btn-info dropdown-toggle-something" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="adv-search-drop">

    </button>

Related Threads

Related Resources

  <input id="nlk-search-str" name="s" type="text" maxlength="200" class="form-control" placeholder="Left - Select an option" data-def="Left - Required option and/or terms" required>

  <button class="btn btn-primary-ice" style='background-color: #488957; outline: 0 none; border: none' type="button" id="nlk-search-submit">

  </button>

  </form>

Copyright © 2017 Sage.io. All Rights Reserved. Patents Pending.


text:
using System.Collections.Concurrent;
using System.IO;

namespace System.Reflection.Tests
{
    internal static partial class TestUtils
    {
        // Given a runtime Type, load up the equivalent in the Test MetataLoadContext. This is for test-writing convenience so
        // that tests can write "typeof(TestClass).Project()" and get the benefits of compile-time typename checking and Intellisense.
        // It also opens the possibility of sharing Reflection tests between different type providers with minimal fuss.
        public static Type Project(this Type type)
        {
            if (type == null)
                return null;

            Assembly assembly = type.Assembly;
            string location = assembly.Location;
            if (location == null || location == string.Empty)
            {
                throw new Exception("Could not find the IL for assembly " + type.Assembly + " on disk. The most likely cause " +
                    "is that you built the tests for a Jitted runtime but are running them on an AoT runtime.");
            }

            Assembly projectedAssembly = s_assemblyDict.GetOrAdd(assembly,
                delegate (Assembly a)
                {
                    // The core assembly we're using might not be the one powering the runtime. Make sure we project to the core assembly the MetataLoadContext
                    // is using.
                    if (a == typeof(object).Assembly)
                        return TestMetadataLoadContext.LoadFromStream(CreateStreamForCoreAssembly());

                    return TestMetadataLoadContext.LoadFromAssemblyPath(a.Location);
                });

            Type projectedType = s_typeDict.GetOrAdd(type, (t) => projectedAssembly.GetType(t.FullName, throwOnError: true, ignoreCase: false));

            if (s_useRuntimeTypesForTests.Value)
                return type;

            return projectedType;
        }

        private static readonly ConcurrentDictionary<Assembly, Assembly> s_assemblyDict = new ConcurrentDictionary<Assembly, Assembly>();
        private static readonly ConcurrentDictionary<Type, Type> s_typeDict = new ConcurrentDictionary<Type, Type>();

        public static Stream CreateStreamForCoreAssembly()
        {
            // We need a core assembly in IL form. Since this version of this code is for Jitted platforms, the System.Private.Corelib
            // of the underlying runtime will do just fine.
            string assumedLocationOfCoreLibrary = typeof(object).Assembly.Location;
            if (assumedLocationOfCoreLibrary == null || assumedLocationOfCoreLibrary == string.Empty)
            {
                throw new Exception("Could not find a core assembly to use for tests as 'typeof(object).Assembly.Location` returned " +
                    "a null or empty value. The most likely cause is that you built the tests for a Jitted runtime but are running them " +
                    "on an AoT runtime.");
            }

            return File.OpenRead(GetPathToCoreAssembly());
        }

        public static string GetPathToCoreAssembly()
        {
            return typeof(object).Assembly.Location;
        }

        public static string GetNameOfCoreAssembly()
        {
            return typeof(object).Assembly.GetName().Name;
        }
    }
}


text:
namespace content {

class EyeDropper;
class EyeDropperListener;

class EyeDropperChooserImpl final
    : public FrameServiceBase<blink::mojom::EyeDropperChooser>,
      public EyeDropperListener {
 public:
  static void Create(RenderFrameHost*,
                     mojo::PendingReceiver<blink::mojom::EyeDropperChooser>);

  // EyeDropperChooser:
  void Choose(ChooseCallback) override;

  // EyeDropperListener:
  void ColorSelected(SkColor color) override;
  void ColorSelectionCanceled() override;

 private:
  EyeDropperChooserImpl(RenderFrameHost*,
                        mojo::PendingReceiver<blink::mojom::EyeDropperChooser>);

  ~EyeDropperChooserImpl() override;

  ChooseCallback callback_;
  std::unique_ptr<EyeDropper> eye_dropper_;

  DISALLOW_COPY_AND_ASSIGN(EyeDropperChooserImpl);
};

}  // namespace content

#endif  // CONTENT_BROWSER_EYE_DROPPER_CHOOSER_IMPL_H_


text:
package rapture.plugin.validators;

import java.util.List;

import rapture.common.RaptureLockConfig;
import rapture.common.RaptureURI;

public class LockValidator extends JsonValidator<RaptureLockConfig> {
    public static final Validator singleton = new LockValidator(RaptureLockConfig.class);

    public static final Validator getValidator() {
        return singleton;
    }

    public LockValidator(Class<RaptureLockConfig> clazz) {
        super(clazz);
    }

    @Override
    void validateObject(RaptureLockConfig thing, RaptureURI uri, List<Note> errors) {
    }

    @Override
    void validateRaw(String content, RaptureURI uri, List<Note> errors) {
    }
}


text:
package fr.laas.fape.anml.model.ir

import fr.laas.fape.anml.model.abs.AbstractChronicle

class IROrderedStatementGroup(parts: List[IRStatementGroup]) extends IRStatementGroup {
  override def firsts: List[IRStatement] = parts.head.firsts
  override def lasts: List[IRStatement] = parts.last.lasts
  override def statements: List[IRStatement] = parts.flatMap(_.statements)
  override def process(f: (IRStatement) => AbstractChronicle): AbstractChronicleGroup =
    new OrderedChronicleGroup(parts.map(_.process(f)))
}


text:
using System;

namespace org.apache.etch.examples.example
{
	///Main implementation for ExampleClient.
	public class MainExampleClient : ExampleHelper.ExampleClientFactory
	{
		///Main for ExampleClient
		///<param name="args">Command Line Arguments</param>
		public static void Main(String[] args)
		{
			// TODO: Change to correct URI
			string uri = "tcp://localhost:4002";

			RemoteExampleServer server = ExampleHelper.NewServer( uri, null, new MainExampleClient());

			// Connect to the service
			server._StartAndWaitUp( 4000 );

			// TODO: Insert Your Code Here

			// Disconnect from the service
			server._StopAndWaitDown( 4000 );
		}

		///Return a new instance of ExampleClient.
		///<param name="server">Reference to remote service</param>
		///<returns>Client Implementation</returns>
		public ExampleClient NewExampleClient( RemoteExampleServer server )
		{
			return new ImplExampleClient( server );
		}
	}
}


text:
package main;

import gameAuthoring.view.MainPanel;

public class Main {
    public static void main (String[] args) {
        MainPanel main = new MainPanel();
        main.show();
    }
}


text:
using base::UTF8ToUTF16;

namespace ash {

const gfx::VectorIcon& GetSupervisedUserIcon() {
  SessionControllerImpl* session_controller =
      Shell::Get()->session_controller();

  if (session_controller->IsUserSupervised() &&
      session_controller->IsUserChild())
    return kSystemMenuSupervisedUserIcon;

  return kSystemMenuLegacySupervisedUserIcon;
}

base::string16 GetSupervisedUserMessage() {
  SessionControllerImpl* session_controller =
      Shell::Get()->session_controller();
  DCHECK(session_controller->IsUserSupervised());
  DCHECK(session_controller->IsActiveUserSessionStarted());

  // Get the active user session.
  const UserSession* const user_session = session_controller->GetUserSession(0);
  DCHECK(user_session);

  base::string16 first_custodian = UTF8ToUTF16(user_session->custodian_email);
  base::string16 second_custodian =
      UTF8ToUTF16(user_session->second_custodian_email);

  // Regular supervised user. The "manager" is the first custodian.
  if (!Shell::Get()->session_controller()->IsUserChild()) {
    return l10n_util::GetStringFUTF16(IDS_ASH_USER_IS_SUPERVISED_BY_NOTICE,
                                      first_custodian);
  }

  // Child supervised user.
  if (second_custodian.empty()) {
    return l10n_util::GetStringFUTF16(
        IDS_ASH_CHILD_USER_IS_MANAGED_BY_ONE_PARENT_NOTICE, first_custodian);
  }
  return l10n_util::GetStringFUTF16(
      IDS_ASH_CHILD_USER_IS_MANAGED_BY_TWO_PARENTS_NOTICE, first_custodian,
      second_custodian);
}

}  // namespace ash


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Regulations on the Management and Application of the Marine Wild Animal Conservation Donation Account</英文法規名稱>
<中文法規名稱>海洋野生動物保育捐助專戶管理及運用辦法</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=D0090063</法規網址>
<最新英文異動日期>20190725</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件 />
<沿革內容><![CDATA[1.10 articles promulgated by Ocean Conservation Administration order on July 25, 2019]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[For the purpose of bringing together social resources to conserve marine wild animal, the donation account for marine wild animal conservation (hereinafter referred to as "the Account") is created and the Regulations are adopted pursuant to Article 7, Paragraph 2 of the Wildlife Conservation Act (hereinafter referred to as "the Act").]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The Ocean Affairs Council (hereinafter referred to as the "OAC") serves as the competent authority for the Regulations, and the Ocean Conservation Administration is the enforcing authority.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[Matters such as management and auditing receipts and expenditure pertaining to donations to the Account shall be subject to the Charity Donations Destined for Social Welfare Funds Implementation Regulations and applicable accounting regulations.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[Donations to the Account from any individuals, juridical persons, or other unincorporated bodies that have designated representatives or managers are accepted, and donation receipts shall be issued.
In the event that the donor set forth in the preceding paragraph is a natural person, the donation receipt shall contain the name and National Identification Card number of the donor, the amount donated, designated purpose, and other particulars. If the donoar is a juridical person or any other unincorporated bodies that has designated a representative or manager, the donation receipt shall contain the juridical person or unincorporated body's name and business administration number or tax identification number assigned by a finance or tax authority, the amount donated, designated purpose, and other particulars.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[The sources of funds for the Account include the following:
1.Private donations from individuals, juridical persons, or unincorporated bodies;
2.Interest income from the Account;
3.Other incomes.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[The Account may be used for the following purposes:
1.Surveys, research, operations, and management in respect of marine wild animal resources;
2.Acquisition of land, protection, and improvement of the habitats for marine wild animal;
3.Compensation for any losses in accordance with Paragraph 4 of Article 12 of the Act;
4.The necessary intervention and handling measures set forth in Paragraph 1 of Article 14 and Article 15 of the Act;
5.Assistance or rewards for civil groups and individuals taking part in promoting marine wild animal conservation;
6.Purchase of marine wild animal in accordance with Paragraph 4 of Article 31 of the Act;
7.Education and promotions regarding marine wild animal conservation;
8.Education and training for personnel engagement in marine wild animal conservation;
9.International technical cooperation in marine wild animal conservation;
10.Other matters pertaining to marine wild animal conservation;
11.The administrative expenses incurred by the Account.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 7</條號>
    <條文內容><![CDATA[To manage and utilize the Account, the competent authority shall set up a committee for management of the donation account for marine wild animal conservation (hereinafter referred to as "the Committee"), which shall review the following:
1.Annual utilization plans and the report of implementation regarding the Account;
2.Management and spending of the Account;
3.Budgets, final accounts, and accounting reports regarding the Account;
4.Other matters to be reviewed, as requested by the chairperson.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 8</條號>
    <條文內容><![CDATA[The Committee shall have seven to eleven committee members, all of whom shall be appointed by the OAC from the following personnel. A chairperson shall be elected from among the members:
1.Three representatives of administrative agencies;
2.Three to five experts and scholars;
3.One to three marine conservation enthusiasts.
All members of the Committee shall serve a term of two years, and they may be reappointed after their term expires. However, representatives of adminsitrative agencies shall hold office or be removed from office when their original position changes. Any vacancies in the Committee may be filled, and the successor shall serve until the term of the original member expires.
All members of the Commtee are unpaid positions.
As for the members set forth in Paragraph 1, the number of such members of any gender shall not be less than one third of the total number of the members.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 9</條號>
    <條文內容><![CDATA[The Committee shall convene a meeting each year. It may convene a special meeting and invite personnel from related agencies to be present when necessary.
The meeting set forth in the preceding paragraph shall be convened and chaired by the chairperson. If the chairperson is unable to attend the meeting for any reason, the chairperson shall appoint one of the members to chair the meeting.
Resolutions shall be passed by majority vote at a meeting where more than half of the members are present. In the event of a tie, the chair shall have a casting vote.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 10</條號>
    <條文內容><![CDATA[The Regulations shall enter into force on the date of promulgation.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
title: Tooltips
page_title: Tooltips RadSparkline
description: The Sparkline control is an information graphic, which is characterized by small size, excellent performance
slug: radsparkline-tooltips
tags: sparkline, tooltips
published: True
position: 8
---

# Tooltips

The tooltips are supported out of the box and you just need to enable them.

#### Enable tooltips

{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=EnableTooltips}}
{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=EnableTooltips}}

{{endregion}}

The default tooltips will displayed when hovering over a particular data point.

![](images/sparkline-tooltips001.png)

## Customizing Tooltip Text

You can use the __DataPointTooltipTextNeeded__ event to set custom tooltip text. The following snippet shows how you can access the event.

#### Subscribing to DataPointTooltipTextNeeded

{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=TooltipController}}
{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=TooltipController}}

{{endregion}}

The following example shows how you can set the text in the event handler.

#### Customizing the Tooltip Text

{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=TooltipTextEvent}}
{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=TooltipTextEvent}}

{{endregion}}


text:
@interface PodsDummy_Pods_ShareKit_Swift_Demo_App__CocoaPods_ : NSObject
@end
@implementation PodsDummy_Pods_ShareKit_Swift_Demo_App__CocoaPods_
@end


text:
package edu.psu.cse.siis.coal;

import java.util.Iterator;
import java.util.Map;

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

import soot.Scene;
import soot.SceneTransformer;
import soot.SootMethod;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG;
import edu.psu.cse.siis.coal.arguments.StringValueAnalysis;

/**
 * The scene transformer for the propagation problem.
 */
public class PropagationSceneTransformer extends SceneTransformer {
  private static final int MAX_ITERATIONS = 15;

  private final Logger logger = LoggerFactory.getLogger(getClass());
  private final ResultBuilder resultBuilder;
  private final PropagationSceneTransformerPrinter printer;

  /**
   * Constructor for the scene transformer.
   *
   * @param resultBuilder A {@link ResultBuilder} that describes how the result is generated once
   *          the problem solution is found.
   * @param printer A {@link PropagationSceneTransformerPrinter} that prints the output of the
   *          analysis when debugging is enabled. If null, nothing gets printed.
   */
  public PropagationSceneTransformer(ResultBuilder resultBuilder,
      PropagationSceneTransformerPrinter printer) {
    this.resultBuilder = resultBuilder;
    this.printer = printer;
  }

  @Override
  protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
    PropagationTimers.v().totalTimer.start();
    PropagationTimers.v().misc.start();
    StringValueAnalysis.initialize();

    JimpleBasedInterproceduralCFG iCfg = new PropagationIcfg();
    AnalysisParameters.v().setIcfg(iCfg);
    PropagationProblem problem = new PropagationProblem(iCfg);
    for (SootMethod ep : Scene.v().getEntryPoints()) {
      if (ep.isConcrete()) {
        problem.getInitialSeeds().add(ep.getActiveBody().getUnits().getFirst());
      }
    }

    int iterationCounter = 0;
    PropagationSolver solver = null;

    while (iterationCounter < MAX_ITERATIONS) {
      IterationSolver.v().initialize(solver);
      PropagationTimers.v().misc.end();

      PropagationTimers.v().problemGeneration.start();
      solver = new PropagationSolver(problem);
      PropagationTimers.v().problemGeneration.end();

      PropagationTimers.v().ideSolution.start();
      logger.info("Solving propagation problem (iteration " + iterationCounter + ")");
      solver.solve();
      PropagationTimers.v().ideSolution.end();

      PropagationTimers.v().misc.start();
      if (!AnalysisParameters.v().isIterative() || IterationSolver.v().hasFoundFixedPoint()) {
        iterationCounter = MAX_ITERATIONS;
      } else {
        ++iterationCounter;
      }
    }
    PropagationTimers.v().misc.end();

    logger.info("Reached a fixed point");

    Results.addResult(resultBuilder.buildResult(solver));

    PropagationTimers.v().totalTimer.end();

    if (logger.isDebugEnabled()) {
      CallGraph cg = Scene.v().getCallGraph();

      Iterator<Edge> it = cg.listener();
      while (it.hasNext()) {
        soot.jimple.toolkits.callgraph.Edge e = (soot.jimple.toolkits.callgraph.Edge) it.next();
        logger.debug("" + e.src() + e.srcStmt() + " =" + e.kind() + "=> " + e.tgt());
      }

      if (printer != null) {
        printer.print(solver);
      }
    }
  }
}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;

namespace RucheHome.Threading
{
    /// <summary>
    /// SemaphoreSlim による排他制御を簡潔に行うためのクラス。
    /// </summary>
    public class SemaphoreSlimLock : IDisposable
    {
        /// <summary>
        /// コンストラクタ。
        /// </summary>
        /// <param name="count">同時に許可する SemaphoreSlim 移行要求数。</param>
        public SemaphoreSlimLock(int count = 1) =>
            this.Semaphore = new SemaphoreSlim(count, count);

        /// <summary>
        /// デストラクタ。
        /// </summary>
        ~SemaphoreSlimLock() => this.Dispose(false);

        /// <summary>
        /// 現在同時に許可可能な移行要求数を取得する。
        /// </summary>
        public int CurrentCount => this.Semaphore.CurrentCount;

        /// <summary>
        /// SemaphoreSlim に移行するために待機し、
        /// その解放を行う IDisposable オブジェクトを返す。
        /// </summary>
        /// <returns>SemaphoreSlim の解放を行う IDisposable オブジェクト。</returns>
        public IDisposable Wait()
        {
            this.Semaphore.Wait();
            return new ReleaseOnDispose(this.Semaphore);
        }

        /// <summary>
        /// SemaphoreSlim に移行するために待機し、
        /// その解放を行う IDisposable オブジェクトを返す。
        /// </summary>
        /// <param name="millisecondsTimeout">待機するミリ秒数。</param>
        /// <returns>
        /// SemaphoreSlim の解放を行う IDisposable オブジェクト。
        /// 待機がタイムアウトした場合は null 。
        /// </returns>
        public IDisposable Wait(int millisecondsTimeout)
        {
            var ok = this.Semaphore.Wait(millisecondsTimeout);
            return ok ? (new ReleaseOnDispose(this.Semaphore)) : null;
        }

        /// <summary>
        /// SemaphoreSlim に移行するために待機し、
        /// その解放を行う IDisposable オブジェクトを返す。
        /// </summary>
        /// <param name="timeout">待機する時間。</param>
        /// <returns>
        /// SemaphoreSlim の解放を行う IDisposable オブジェクト。
        /// 待機がタイムアウトした場合は null 。
        /// </returns>
        public IDisposable Wait(TimeSpan timeout)
        {
            var ok = this.Semaphore.Wait(timeout);
            return ok ? (new ReleaseOnDispose(this.Semaphore)) : null;
        }

        /// <summary>
        /// SemaphoreSlim に移行するために非同期に待機し、
        /// その解放を行う IDisposable オブジェクトを返す。
        /// </summary>
        /// <returns>SemaphoreSlim の解放を行う IDisposable オブジェクト。</returns>
        public async Task<IDisposable> WaitAsync()
        {
            await this.Semaphore.WaitAsync();
            return new ReleaseOnDispose(this.Semaphore);
        }

        /// <summary>
        /// SemaphoreSlim に移行するために非同期に待機し、
        /// その解放を行う IDisposable オブジェクトを返す。
        /// </summary>
        /// <param name="millisecondsTimeout">待機するミリ秒数。</param>
        /// <returns>
        /// SemaphoreSlim の解放を行う IDisposable オブジェクト。
        /// 待機がタイムアウトした場合は null 。
        /// </returns>
        public async Task<IDisposable> WaitAsync(int millisecondsTimeout)
        {
            var ok = await this.Semaphore.WaitAsync(millisecondsTimeout);
            return ok ? (new ReleaseOnDispose(this.Semaphore)) : null;
        }

        /// <summary>
        /// SemaphoreSlim に移行するために非同期に待機し、
        /// その解放を行う IDisposable オブジェクトを返す。
        /// </summary>
        /// <param name="timeout">待機する時間。</param>
        /// <returns>
        /// SemaphoreSlim の解放を行う IDisposable オブジェクト。
        /// 待機がタイムアウトした場合は null 。
        /// </returns>
        public async Task<IDisposable> WaitAsync(TimeSpan timeout)
        {
            var ok = await this.Semaphore.WaitAsync(timeout);
            return ok ? (new ReleaseOnDispose(this.Semaphore)) : null;
        }

        /// <summary>
        /// SemaphoreSlim インスタンスを取得する。
        /// </summary>
        private SemaphoreSlim Semaphore { get; }

        #region IDisposable の実装

        /// <summary>
        /// リソースの破棄を行う。
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// リソース破棄の実処理を行う。
        /// </summary>
        /// <param name="disposing">
        /// Dispose メソッドから呼び出された場合は true 。
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.Semaphore.Dispose();
            }
        }

        #endregion

        #region ReleaseOnDispose クラス

        /// <summary>
        /// Dispose メソッド呼び出しにより
        /// SemaphoreSlim インスタンスの Release メソッドを呼び出すクラス。
        /// </summary>
        private sealed class ReleaseOnDispose : IDisposable
        {
            /// <summary>
            /// コンストラクタ。
            /// </summary>
            /// <param name="semaphore">SemaphoreSlim インスタンス。</param>
            public ReleaseOnDispose(SemaphoreSlim semaphore) => this.Semaphore = semaphore;

            /// <summary>
            /// SemaphoreSlim インスタンスの Release メソッドを呼び出す。
            /// </summary>
            [SuppressMessage("Design", "CA1031")]
            public void Dispose()
            {
                if (this.Semaphore != null)
                {
                    try
                    {
                        this.Semaphore.Release();
                    }
                    catch (ObjectDisposedException) { }
                }
                this.Semaphore = null;
            }

            /// <summary>
            /// SemaphoreSlim インスタンスを取得または設定する。
            /// </summary>
            private SemaphoreSlim Semaphore { get; set; }
        }

        #endregion
    }
}


text:
@protocol cdaAnalyticsDelegate <NSObject>

@required
-(void)trackPage:(NSString*)pageName;;
-(void)trackEvent:(NSString *)eventName inCategory:(NSString*)categoryName withLabel:(NSString*)labelName andValue:(int)value;

@optional
-(void)startTracker;
-(void)stopTracker;
-(void)logError:(NSString*)error withMessage:(NSString*)msg andException:(NSException*)exception;
-(void)setCustomVariableAtIndex:(NSUInteger)index name:(NSString *)name value:(NSString *)value scope:(GANCVScope)scope;
-(void)addTransaction:(NSString *)orderID totalPrice:(double)totalPrice storeName:(NSString *)storeName;
-(void)addItem:(NSString *)orderId itemSKU:(NSString*)item itemName:(NSString *)itemName itemPrice:(double)price;
-(void)trackTransactions;
-(void)clearTransactions;
-(void)applicationWillEnterForeground;
-(void)setSessionReportsOnCloseEnabled:(BOOL)reportOnClose;
@end

#if defined DEBUG || defined ENTERPRISE
static NSString* const cdaAnalyticKeyType = @"test";
#else
static NSString* const cdaAnalyticKeyType = @"live";
#endif

@interface cdaAnalytics : NSObject <cdaAnalyticsDelegate> {
    NSMutableArray* trackers;
    NSMutableDictionary*timers;
}

+(cdaAnalytics*) sharedInstance;

//initialize api keys
-(void)registerProvider:(id)tracker;
-(void)registerProvider:(id<cdaAnalyticsDelegate>)tracker setSessionReportsOnCloseEnabled:(BOOL)reportOnClose;

//tracking
-(void)trackPage:(NSString*)pageName;
-(void)trackEvent:(NSString *)eventName;
-(void)trackEvent:(NSString *)eventName inCategory:(NSString*)categoryName withLabel:(NSString*)labelName andValue:(int)value;

-(void)trackEvent:(NSString *)eventName timed:(BOOL)isEventTimed;
-(void)trackEvent:(NSString *)eventName inCategory:(NSString*)categoryName withLabel:(NSString*)labelName timed:(BOOL)isEventTimed;
-(void)endTimedEvent:(NSString *)eventName;

-(void)setCustomVariableAtIndex:(NSUInteger)index name:(NSString *)name value:(NSString *)value scope:(GANCVScope)scope;

-(void)addTransaction:(NSString *)orderID totalPrice:(double)totalPrice storeName:(NSString *)storeName;
-(void)addItem:(NSString *)orderId itemSKU:(NSString*)item itemName:(NSString *)itemName itemPrice:(double)price;
-(void)trackTransactions;
-(void)clearTransactions;

-(void)logError:(NSString*)error withMessage:(NSString*)msg andException:(NSException*)exception;
-(void)stopTracker;

-(void)applicationWillEnterForeground:(NSNotification*)notification;
-(void)applicationDidEnterBackgroundNotification:(NSNotification*)notification;
@end