text:
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import PlusIcon from '@strapi/icons/Plus';
import { ModalLayout, ModalBody } from '@strapi/design-system/ModalLayout';
import { Flex } from '@strapi/design-system/Flex';
import { Button } from '@strapi/design-system/Button';
import { Divider } from '@strapi/design-system/Divider';
import { Box } from '@strapi/design-system/Box';
import { useIntl } from 'react-intl';
import { Tabs, Tab, TabGroup, TabPanels, TabPanel } from '@strapi/design-system/Tabs';
import { Badge } from '@strapi/design-system/Badge';
import { Loader } from '@strapi/design-system/Loader';
import { NoPermissions, AnErrorOccurred, useSelectionState } from '@strapi/helper-plugin';
import getTrad from '../../utils/getTrad';
import { SelectedStep } from './SelectedStep';
import { BrowseStep } from './BrowseStep';
import { useMediaLibraryPermissions } from '../../hooks/useMediaLibraryPermissions';
import { useModalAssets } from '../../hooks/useModalAssets';
import useModalQueryParams from '../../hooks/useModalAssets/useModalQueryParams';
import { AssetDefinition } from '../../constants';
import getAllowedFiles from '../../utils/getAllowedFiles';
import { DialogTitle } from './DialogTitle';
import { DialogFooter } from './DialogFooter';
import { EditAssetDialog } from '../EditAssetDialog';
import { EmptyAssets } from '../EmptyAssets';
import { moveElement } from '../../utils/moveElement';

export const AssetDialog = ({
  allowedTypes,
  onClose,
  onAddAsset,
  onValidate,
  multiple,
  initiallySelectedAssets,
  trackedLocation,
}) => {
  const [assetToEdit, setAssetToEdit] = useState(undefined);
  const { formatMessage } = useIntl();
  const {
    canRead,
    canCreate,
    isLoading: isLoadingPermissions,
    canUpdate,
    canCopyLink,
    canDownload,
  } = useMediaLibraryPermissions();
  const [
    { rawQuery, queryObject },
    { onChangeFilters, onChangePage, onChangePageSize, onChangeSort, onChangeSearch },
  ] = useModalQueryParams();
  const { data, isLoading, error } = useModalAssets({ skipWhen: !canRead, rawQuery });

  const [selectedAssets, { selectOne, selectAll, selectOnly, setSelections }] = useSelectionState(
    'id',
    initiallySelectedAssets
  );

  const [initialSelectedTabIndex, setInitialSelectedTabIndex] = useState(
    selectedAssets.length > 0 ? 1 : 0
  );
  const handleSelectAllAssets = () => {
    const hasAllAssets = assets.every(
      asset => selectedAssets.findIndex(curr => curr.id === asset.id) !== -1
    );

    if (hasAllAssets) {
      return multiple ? selectAll(assets) : undefined;
    }

    const allowedAssets = getAllowedFiles(allowedTypes, assets);

    return multiple ? selectAll(allowedAssets) : undefined;
  };
  const handleSelectAsset = asset => {
    return multiple ? selectOne(asset) : selectOnly(asset);
  };

  const loading = isLoadingPermissions || isLoading;
  const assets = data?.results;

  if (loading) {
    return (
      <ModalLayout onClose={onClose} labelledBy="asset-dialog-title" aria-busy>
        <DialogTitle />
        <Flex justifyContent="center" paddingTop={4} paddingBottom={4}>
          <Loader>
            {formatMessage({
              id: getTrad('list.asset.load'),
              defaultMessage: 'How do you want to upload your assets?',
            })}
          </Loader>
        </Flex>
        <DialogFooter onClose={onClose} />
      </ModalLayout>
    );
  }

  if (error) {
    return (
      <ModalLayout onClose={onClose} labelledBy="asset-dialog-title">
        <DialogTitle />
        <AnErrorOccurred />
        <DialogFooter onClose={onClose} />
      </ModalLayout>
    );
  }

  if (!canRead) {
    return (
      <ModalLayout onClose={onClose} labelledBy="asset-dialog-title">
        <DialogTitle />
        <NoPermissions />
        <DialogFooter onClose={onClose} />
      </ModalLayout>
    );
  }

  if (canRead && assets?.length === 0 && !queryObject._q && queryObject.filters.$and.length === 0) {
    return (
      <ModalLayout onClose={onClose} labelledBy="asset-dialog-title">
        <DialogTitle />
        <Box paddingLeft={8} paddingRight={8} paddingBottom={6}>
          <EmptyAssets
            size="S"
            count={6}
            action={
              canCreate ? (
                <Button variant="secondary" startIcon={<PlusIcon />} onClick={onAddAsset}>
                  {formatMessage({
                    id: getTrad('header.actions.add-assets'),
                    defaultMessage: 'Add new assets',
                  })}
                </Button>
              ) : (
                undefined
              )
            }
            content={
              canCreate
                ? formatMessage({
                    id: getTrad('list.assets.empty'),
                    defaultMessage: 'Upload your first assets...',
                  })
                : formatMessage({
                    id: getTrad('list.assets.empty.no-permissions'),
                    defaultMessage: 'The asset list is empty',
                  })
            }
          />
        </Box>
        <DialogFooter onClose={onClose} />
      </ModalLayout>
    );
  }

  if (assetToEdit) {
    return (
      <EditAssetDialog
        onClose={() => setAssetToEdit(undefined)}
        asset={assetToEdit}
        canUpdate={canUpdate}
        canCopyLink={canCopyLink}
        canDownload={canDownload}
        trackedLocation={trackedLocation}
      />
    );
  }

  const handleMoveItem = (hoverIndex, destIndex) => {
    const offset = destIndex - hoverIndex;
    const orderedAssetsClone = selectedAssets.slice();
    const nextAssets = moveElement(orderedAssetsClone, hoverIndex, offset);

    setSelections(nextAssets);
  };

  return (
    <ModalLayout onClose={onClose} labelledBy="asset-dialog-title" aria-busy={loading}>
      <DialogTitle />

      <TabGroup
        label={formatMessage({
          id: getTrad('tabs.title'),
          defaultMessage: 'How do you want to upload your assets?',
        })}
        variant="simple"
        initialSelectedTabIndex={initialSelectedTabIndex}
        onTabChange={() => setInitialSelectedTabIndex(0)}
      >
        <Flex paddingLeft={8} paddingRight={8} paddingTop={6} justifyContent="space-between">
          <Tabs>
            <Tab>
              {formatMessage({
                id: getTrad('modal.nav.browse'),
                defaultMessage: 'Browse',
              })}
            </Tab>
            <Tab>
              {formatMessage({
                id: getTrad('modal.header.select-files'),
                defaultMessage: 'Selected files',
              })}
              <Badge marginLeft={2}>{selectedAssets.length}</Badge>
            </Tab>
          </Tabs>

          <Button onClick={onAddAsset}>
            {formatMessage({
              id: getTrad('modal.upload-list.sub-header.button'),
              defaultMessage: 'Add more assets',
            })}
          </Button>
        </Flex>
        <Divider />
        <TabPanels>
          <TabPanel>
            <ModalBody>
              <BrowseStep
                allowedTypes={allowedTypes}
                assets={assets}
                onSelectAsset={handleSelectAsset}
                selectedAssets={selectedAssets}
                multiple={multiple}
                onSelectAllAsset={handleSelectAllAssets}
                onEditAsset={canUpdate ? setAssetToEdit : undefined}
                pagination={data?.pagination}
                queryObject={queryObject}
                onChangeFilters={onChangeFilters}
                onChangePage={onChangePage}
                onChangePageSize={onChangePageSize}
                onChangeSort={onChangeSort}
                onChangeSearch={onChangeSearch}
              />
            </ModalBody>
          </TabPanel>
          <TabPanel>
            <ModalBody>
              <SelectedStep
                selectedAssets={selectedAssets}
                onSelectAsset={handleSelectAsset}
                onReorderAsset={handleMoveItem}
              />
            </ModalBody>
          </TabPanel>
        </TabPanels>
      </TabGroup>

      <DialogFooter onClose={onClose} onValidate={() => onValidate(selectedAssets)} />
    </ModalLayout>
  );
};

AssetDialog.defaultProps = {
  allowedTypes: [],
  initiallySelectedAssets: [],
  multiple: false,
  trackedLocation: undefined,
};

AssetDialog.propTypes = {
  allowedTypes: PropTypes.arrayOf(PropTypes.string),
  initiallySelectedAssets: PropTypes.arrayOf(AssetDefinition),
  multiple: PropTypes.bool,
  onAddAsset: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired,
  onValidate: PropTypes.func.isRequired,
  trackedLocation: PropTypes.string,
};


text:
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var bb = require('bonescript');

var htmlPage = 'Prog BBB/09_02_pwm.html'; // use this for Angstrom
// var htmlPage = '09_02_pwm.html'; // use this for Debian

app.listen(8085);

function handler (req, res) {
  fs.readFile(htmlPage,
    function (err, data) {
      if (err) {
        res.writeHead(500);
        return res.end('Error loading file: ' + htmlPage);
      }
      res.writeHead(200);
      res.end(data);
    });
}

function onConnect(socket) {
    socket.on('analogWrite', handleAnalogWrite);
}

function handleAnalogWrite(message) {
    var data = JSON.parse(message);
    bb.analogWrite(data.pin, data.value);
}

io.sockets.on('connection', onConnect);

redpajama_set_name: RedPajamaGithub


text:
import nc
import iso
import math

################################################################################
class Creator(iso.Creator):

    def __init__(self):
        iso.Creator.__init__(self)
        self.useCrc = True

################################################################################

nc.creator = Creator()


text:
;(function()
{
	var ns = __namespace( "Libraries.SyntaxHighlighter.Brush" );

    /** @type {Libraries.SyntaxHighlighter} */
    var SyntaxHighlighter = __import( "Libraries.SyntaxHighlighter" );

    /** @type {Libraries.SyntaxHighlighter.Brush} **/
    var Brush = function()
	{
		// Contributed by Patrick Webster
		// http://patrickwebster.blogspot.com/2009/04/javafx-brush-for-syntaxhighlighter.html
		var datatypes =	'Boolean Byte Character Double Duration '
						+ 'Float Integer Long Number Short String Void'
						;

		var keywords = 'abstract after and as assert at before bind bound break catch class '
						+ 'continue def delete else exclusive extends false finally first for from '
						+ 'function if import in indexof init insert instanceof into inverse last '
						+ 'lazy mixin mod nativearray new not null on or override package postinit '
						+ 'protected public public-init public-read replace return reverse sizeof '
						+ 'step super then this throw true try tween typeof var where while with '
						+ 'attribute let private readonly static trigger'
						;

		this.regexList = [
			{ "regex": SyntaxHighlighter.regexLib.singleLineCComments,	"css": 'comments' },
			{ "regex": SyntaxHighlighter.regexLib.multiLineCComments,		"css": 'comments' },
			{ "regex": SyntaxHighlighter.regexLib.singleQuotedString,		"css": 'string' },
			{ "regex": SyntaxHighlighter.regexLib.doubleQuotedString,		"css": 'string' },
			{ "regex": /(-?\.?)(\b(\d*\.?\d+|\d+\.?\d*)(e[+-]?\d+)?|0x[a-f\d]+)\b\.?/gi, "css": 'color2' },	// numbers
			{ "regex": new RegExp(this.getKeywords(datatypes), 'gm'),		"css": 'variable' },	// datatypes
			{ "regex": new RegExp(this.getKeywords(keywords), 'gm'),		"css": 'keyword' }
		];
		this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
	};

	Brush.prototype	= new SyntaxHighlighter.Highlighter();
	Brush.aliases	= ['jfx', 'javafx'];

	SyntaxHighlighter.brushes[ "JavaFX" ] = Brush;

    ns[ NS_EXPORT ]( EX_CLASS, "JavaFX", Brush );
})();


text:
package freestyle

import cats.{ Applicative, Monad }
import cats.data.Coproduct
import cats.free.{Free, FreeApplicative, Inject}

import iota._
import shapeless.Lazy

trait Interpreters {

  implicit def interpretCatsCoproduct[F[_], G[_], M[_]](
      implicit fm: FSHandler[F, M],
      gm: Lazy[FSHandler[G, M]]): FSHandler[Coproduct[F, G, ?], M] =
    fm or gm.value

  implicit def interpretIotaCopK[F[a] <: CopK[_, a], G[_]]: FSHandler[F, G] =
    macro internal.CopKFunctionKMacros.summon[F, G]

  // workaround for https://github.com/typelevel/cats/issues/1505
  implicit def catsFreeRightInjectInstanceLazy[F[_], G[_], H[_]](
      implicit I: Lazy[Inject[F, G]]): Inject[F, Coproduct[H, G, ?]] =
    Inject.catsFreeRightInjectInstance(I.value)

}

trait FreeSInstances {
  implicit def freestyleApplicativeForFreeS[F[_]]: Applicative[FreeS.Par[F, ?]] =
    FreeApplicative.freeApplicative[F]

  implicit def freestyleMonadForFreeS[F[_]]: Monad[FreeS[F, ?]] =
    Free.catsFreeMonadForFree[FreeApplicative[F, ?]]
}

object implicits extends Interpreters with FreeSInstances


text:
<!DOCTYPE html>

<title>Problema</title>
<link rel="StyleSheet" href="estilos.css" type="text/css">

Doble clic para ocultar este recuadro


text:
/* Includes ------------------------------------------------------------------*/
#include "stm8l15x_gpio.h"

/** @addtogroup STM8L15x_StdPeriph_Driver
  * @{
  */

/** @defgroup CLK
  * @brief CLK driver modules
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/** @defgroup GPIO_Private_Functions
  * @{
  */

/** @defgroup GPIO_Group1 Initialization and Configuration
 *  @brief   Initialization and Configuration
 *
@verbatim
 ===============================================================================
                        Initialization and Configuration
 ===============================================================================

@endverbatim
  * @{
  */

/**
  * @brief  Deinitializes the GPIOx peripheral registers to their default reset values.
  * @param  GPIOx: Select the GPIO peripheral number (x = A to I).
  * @retval None
  */
void GPIO_DeInit(GPIO_TypeDef* GPIOx)
{
  GPIOx->CR2 = GPIO_CR2_RESET_VALUE; /* Reset Control Register 2 */
  GPIOx->ODR = GPIO_ODR_RESET_VALUE; /* Reset Output Data Register */
  GPIOx->DDR = GPIO_DDR_RESET_VALUE; /* Reset Data Direction Register */
  GPIOx->CR1 = GPIO_CR1_RESET_VALUE; /* Reset Control Register 1 */
}

/**
  * @brief  Initializes the GPIOx according to the specified parameters.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : This parameter contains the pin number
  *           This parameter can be one of the following values:
  *            @arg GPIO_Pin_0: Pin 0
  *            @arg GPIO_Pin_1: Pin 1
  *            @arg GPIO_Pin_2: Pin 2
  *            @arg GPIO_Pin_3: Pin 3
  *            @arg GPIO_Pin_4: Pin 4
  *            @arg GPIO_Pin_5: Pin 5
  *            @arg GPIO_Pin_6: Pin 6
  *            @arg GPIO_Pin_7: Pin 7
  * @param  GPIO_Mode : This parameter can be a value of the
  *           This parameter can be one of the following values:
  *            @arg GPIO_Mode_In_FL_No_IT: Input floating, no external interrupt
  *            @arg GPIO_Mode_In_PU_No_IT: Input pull-up, no external interrupt
  *            @arg GPIO_Mode_In_FL_IT: Input pull-up, external interrupt
  *            @arg GPIO_Mode_Out_OD_Low_Fast: Output open-drain, low level, 10MHz
  *            @arg GPIO_Mode_Out_PP_Low_Fast: Output push-pull, low level, 10MHz
  *            @arg GPIO_Mode_Out_OD_Low_Slow: Output open-drain, low level, 2MHz
  *            @arg GPIO_Mode_Out_PP_Low_Slow: Output push-pull, low level, 2MHz
  *            @arg GPIO_Mode_Out_OD_HiZ_Fast: Output open-drain, high-impedance level, 10MHz
  *            @arg GPIO_Mode_Out_PP_High_Fast: Output push-pull, high level, 10MHz
  *            @arg GPIO_Mode_Out_OD_HiZ_Slow: Output open-drain, high-impedance level, 2MHz
  *            @arg GPIO_Mode_Out_PP_High_Slow: Output push-pull, high level, 2MHz
  * @retval None
  */

void GPIO_Init(GPIO_TypeDef* GPIOx, uint8_t GPIO_Pin, GPIO_Mode_TypeDef GPIO_Mode)
{
  /*----------------------*/
  /* Check the parameters */
  /*----------------------*/

  assert_param(IS_GPIO_MODE(GPIO_Mode));
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  /* Reset corresponding bit to GPIO_Pin in CR2 register */
  GPIOx->CR2 &= (uint8_t)(~(GPIO_Pin));

  /*-----------------------------*/
  /* Input/Output mode selection */
  /*-----------------------------*/

  if ((((uint8_t)(GPIO_Mode)) & (uint8_t)0x80) != (uint8_t)0x00) /* Output mode */
  {
    if ((((uint8_t)(GPIO_Mode)) & (uint8_t)0x10) != (uint8_t)0x00) /* High level */
    {
      GPIOx->ODR |= GPIO_Pin;
    } else /* Low level */
    {
      GPIOx->ODR &= (uint8_t)(~(GPIO_Pin));
    }
    /* Set Output mode */
    GPIOx->DDR |= GPIO_Pin;
  } else /* Input mode */
  {
    /* Set Input mode */
    GPIOx->DDR &= (uint8_t)(~(GPIO_Pin));
  }

  /*------------------------------------------------------------------------*/
  /* Pull-Up/Float (Input) or Push-Pull/Open-Drain (Output) modes selection */
  /*------------------------------------------------------------------------*/

  if ((((uint8_t)(GPIO_Mode)) & (uint8_t)0x40) != (uint8_t)0x00) /* Pull-Up or Push-Pull */
  {
    GPIOx->CR1 |= GPIO_Pin;
  } else /* Float or Open-Drain */
  {
    GPIOx->CR1 &= (uint8_t)(~(GPIO_Pin));
  }

  /*-----------------------------------------------------*/
  /* Interrupt (Input) or Slope (Output) modes selection */
  /*-----------------------------------------------------*/

  if ((((uint8_t)(GPIO_Mode)) & (uint8_t)0x20) != (uint8_t)0x00) /* Interrupt or Slow slope */
  {
    GPIOx->CR2 |= GPIO_Pin;
  } else /* No external interrupt or No slope control */
  {
    GPIOx->CR2 &= (uint8_t)(~(GPIO_Pin));
  }

}

/**
  * @brief  Configures the external pull-up on GPIOx pins.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : Specifies the pin number
  *           This parameter can be one of the following values:
  *            @arg GPIO_Pin_0: Pin 0
  *            @arg GPIO_Pin_1: Pin 1
  *            @arg GPIO_Pin_2: Pin 2
  *            @arg GPIO_Pin_3: Pin 3
  *            @arg GPIO_Pin_4: Pin 4
  *            @arg GPIO_Pin_5: Pin 5
  *            @arg GPIO_Pin_6: Pin 6
  *            @arg GPIO_Pin_7: Pin 7
  * @param  NewState : The new state of the pull up pin.
  *           Can be ENABLE or DISABLE
  * @retval None
  */
void GPIO_ExternalPullUpConfig(GPIO_TypeDef* GPIOx, uint8_t GPIO_Pin, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_GPIO_PIN(GPIO_Pin));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE) /* External Pull-Up Set*/
  {
    GPIOx->CR1 |= GPIO_Pin;
  } else /* External Pull-Up Reset*/
  {
    GPIOx->CR1 &= (uint8_t)(~(GPIO_Pin));
  }
}

/**
  * @}
  */

/** @defgroup GPIO_Group2 GPIO Read and Write
 *  @brief   GPIO Read and Write
 *
@verbatim
 ===============================================================================
                              GPIO Read and Write
 ===============================================================================

@endverbatim
  * @{
  */

/**
  * @brief  Writes data to the specified GPIO data port.
  * @note   The port must be configured in output mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_PortVal : Specifies the value to be written to the port output
  *         data register.
  * @retval None
  */
void GPIO_Write(GPIO_TypeDef* GPIOx, uint8_t GPIO_PortVal)
{
  GPIOx->ODR = GPIO_PortVal;
}

/**
  * @brief  Sets or clears the selected data port bit.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin: Specifies the port bit to be written.
  *           This parameter can be one of the following values:
  *            @arg GPIO_Pin_0: Pin 0
  *            @arg GPIO_Pin_1: Pin 1
  *            @arg GPIO_Pin_2: Pin 2
  *            @arg GPIO_Pin_3: Pin 3
  *            @arg GPIO_Pin_4: Pin 4
  *            @arg GPIO_Pin_5: Pin 5
  *            @arg GPIO_Pin_6: Pin 6
  *            @arg GPIO_Pin_7: Pin 7
  * @param  GPIO_BitVal: specifies the desired status to be written.
  *         This parameter can be SET or RESET
  * @retval None
  */
void GPIO_WriteBit(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef GPIO_Pin, BitAction GPIO_BitVal)
{
  /* Check the parameters */
  assert_param(IS_GPIO_PIN(GPIO_Pin));
  assert_param(IS_STATE_VALUE(GPIO_BitVal));

  if (GPIO_BitVal != RESET)
  {
    GPIOx->ODR |= GPIO_Pin;

  }
  else
  {
    GPIOx->ODR &= (uint8_t)(~GPIO_Pin);
  }
}

/**
  * @brief  Writes high level to the specified GPIO pins.
  * @note   The port must be configured in output mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : Specifies the pins to be turned high.
  *           This parameter can be one of the following values:
  *            @arg GPIO_Pin_0: Pin 0
  *            @arg GPIO_Pin_1: Pin 1
  *            @arg GPIO_Pin_2: Pin 2
  *            @arg GPIO_Pin_3: Pin 3
  *            @arg GPIO_Pin_4: Pin 4
  *            @arg GPIO_Pin_5: Pin 5
  *            @arg GPIO_Pin_6: Pin 6
  *            @arg GPIO_Pin_7: Pin 7
  * @retval None
  */
void GPIO_SetBits(GPIO_TypeDef* GPIOx, uint8_t GPIO_Pin)
{
  GPIOx->ODR |= GPIO_Pin;
}

/**
  * @brief  Writes low level to the specified GPIO pins.
  * @note   The port must be configured in output mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : Specifies the pins to be turned low
  *           This parameter can be one of the following values:
  *            @arg GPIO_Pin_0: Pin 0
  *            @arg GPIO_Pin_1: Pin 1
  *            @arg GPIO_Pin_2: Pin 2
  *            @arg GPIO_Pin_3: Pin 3
  *            @arg GPIO_Pin_4: Pin 4
  *            @arg GPIO_Pin_5: Pin 5
  *            @arg GPIO_Pin_6: Pin 6
  *            @arg GPIO_Pin_7: Pin 7
  * @retval None
  */
void GPIO_ResetBits(GPIO_TypeDef* GPIOx, uint8_t GPIO_Pin)
{
  GPIOx->ODR &= (uint8_t)(~GPIO_Pin);
}

/**
  * @brief  Toggles the specified GPIO pins.
  * @note   The port must be configured in output mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : Specifies the pins to be toggled.
  * @retval None
  */
void GPIO_ToggleBits(GPIO_TypeDef* GPIOx, uint8_t GPIO_Pin)
{
  GPIOx->ODR ^= GPIO_Pin;
}

/**
  * @brief  Reads the specified GPIO input data port.
  * @note   The port must be configured in input mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @retval The GPIOx input data port value.
  */
uint8_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx)
{
  return ((uint8_t)GPIOx->IDR);
}

/**
  * @brief  Reads the specified GPIO output data port.
  * @note   The port must be configured in input mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @retval The GPIOx  output data port value.
  */
uint8_t GPIO_ReadOutputData(GPIO_TypeDef* GPIOx)
{
  return ((uint8_t)GPIOx->ODR);
}

/**
  * @brief  Reads the specified GPIO input data pin.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : Specifies the pin number.
  *           This parameter can be one of the following values:
  *            @arg GPIO_Pin_0: Pin 0
  *            @arg GPIO_Pin_1: Pin 1
  *            @arg GPIO_Pin_2: Pin 2
  *            @arg GPIO_Pin_3: Pin 3
  *            @arg GPIO_Pin_4: Pin 4
  *            @arg GPIO_Pin_5: Pin 5
  *            @arg GPIO_Pin_6: Pin 6
  *            @arg GPIO_Pin_7: Pin 7
  * @retval BitStatus : GPIO input pin status.
  */
BitStatus GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef GPIO_Pin)
{
  return ((BitStatus)(GPIOx->IDR & (uint8_t)GPIO_Pin));
}

/**
  * @brief  Reads the specified GPIO Output data pin.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : Specifies the pin number
  * @retval BitStatus : GPIO output pin status.
  */
BitStatus GPIO_ReadOutputDataBit(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef GPIO_Pin)
{
  return ((BitStatus)(GPIOx->ODR & (uint8_t)GPIO_Pin));
}

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/


text:
package com.gemstone.gemfire.management.internal.security;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

import junit.framework.TestCase;

import org.json.JSONException;
import org.junit.experimental.categories.Category;

import com.gemstone.gemfire.management.internal.security.JSONAuthorization.User;
import com.gemstone.gemfire.util.test.TestUtil;
import com.gemstone.junit.UnitTest;

@Category(UnitTest.class)
public class JSONAuthorizationTest extends TestCase {

  public static String makePath(String[] strings) {
    StringBuilder sb = new StringBuilder();
    for(int i=0;i<strings.length;i++){
      sb.append(strings[i]);
      sb.append(File.separator);
    }
    return sb.toString();
  }

	public void testSimpleUserAndRole() throws IOException, JSONException {
		String json = readFile(TestUtil.getResourcePath(getClass(), "testSimpleUserAndRole.json"));
		JSONAuthorization authorization = new JSONAuthorization(json);
		Map<String, User> acl = authorization.getAcl();
		assertNotNull(acl);
		assertEquals(1, acl.size());
		User user = acl.get("tushark");
		assertNotNull(user);
		assertNotNull(user.roles);
		assertEquals(1,user.roles.length);
		assertEquals("jmxReader", user.roles[0].name);
		assertEquals(1, user.roles[0].permissions.length);
		assertEquals("QUERY", user.roles[0].permissions[0]);
	}

	public void testUserAndRoleRegionServerGroup() throws IOException, JSONException {
		String json = readFile(TestUtil.getResourcePath(getClass(), "testUserAndRoleRegionServerGroup.json"));
		JSONAuthorization authorization = new JSONAuthorization(json);
		Map<String, User> acl = authorization.getAcl();
		assertNotNull(acl);
		assertEquals(1, acl.size());
		User user = acl.get("tushark");
		assertNotNull(user);
		assertNotNull(user.roles);
		assertEquals(1,user.roles.length);
		assertEquals("jmxReader", user.roles[0].name);
		assertEquals(1, user.roles[0].permissions.length);
		assertEquals("QUERY", user.roles[0].permissions[0]);

		assertEquals("secureRegion", user.roles[0].regionName);
		assertEquals("SG2", user.roles[0].serverGroup);
	}

	public void testUserMultipleRole()throws IOException, JSONException {
		String json = readFile(TestUtil.getResourcePath(getClass(), "testUserMultipleRole.json"));
		JSONAuthorization authorization = new JSONAuthorization(json);
		Map<String, User> acl = authorization.getAcl();
		assertNotNull(acl);
		assertEquals(1, acl.size());
		User user = acl.get("tushark");
		assertNotNull(user);
		assertNotNull(user.roles);
		assertEquals(2,user.roles.length);

		JSONAuthorization.Role role = user.roles[0];
		if(role.name.equals("jmxReader")){
			assertEquals(1, role.permissions.length);
			assertEquals("QUERY", role.permissions[0]);
		} else {
			assertEquals(7, role.permissions.length);
			assertEquals("sysMonitors", role.name);
		}

		role = user.roles[1];
		if(role.name.equals("jmxReader")){
			assertEquals(1, role.permissions.length);
			assertEquals("QUERY", role.permissions[0]);
		} else {
			assertEquals(7, role.permissions.length);
			assertEquals("sysMonitors", role.name);
			assertTrue(contains(role.permissions, "CMD_EXORT_LOGS"));
			assertTrue(contains(role.permissions, "CMD_STACK_TRACES"));
			assertTrue(contains(role.permissions, "CMD_GC"));
			assertTrue(contains(role.permissions, "CMD_NETSTAT"));
			assertTrue(contains(role.permissions, "CMD_SHOW_DEADLOCKS"));
			assertTrue(contains(role.permissions, "CMD_SHOW_LOG"));
			assertTrue(contains(role.permissions, "SHOW_METRICS"));
		}
	}

	private boolean contains(String[] permissions, String string) {
		for(String str : permissions)
			if(str.equals(string))
					return true;
		return false;
	}

	public void testInheritRole() throws IOException, JSONException {
		String json = readFile(TestUtil.getResourcePath(getClass(), "testInheritRole.json"));
		JSONAuthorization authorization = new JSONAuthorization(json);
		Map<String, User> acl = authorization.getAcl();
		assertNotNull(acl);
		assertEquals(3, acl.size());
		User user = acl.get("tushark");
		assertNotNull(user);
		assertNotNull(user.roles);
		assertEquals(1,user.roles.length);
		assertEquals("jmxReader", user.roles[0].name);
		assertEquals(1, user.roles[0].permissions.length);
		assertEquals("QUERY", user.roles[0].permissions[0]);

		User admin1 = acl.get("admin1");
		assertNotNull(admin1);
		assertNotNull(admin1.roles);
		assertEquals(1,admin1.roles.length);
		assertEquals("adminSG1", admin1.roles[0].name);
		assertEquals("SG1", admin1.roles[0].serverGroup);
		assertEquals(1, admin1.roles[0].permissions.length);
		assertEquals("CMD_SHUTDOWN", admin1.roles[0].permissions[0]);

		User admin2 = acl.get("admin2");
		assertNotNull(admin2);
		assertNotNull(admin2.roles);
		assertEquals(1,admin2.roles.length);
		assertEquals("adminSG2", admin2.roles[0].name);
		assertEquals("SG2", admin2.roles[0].serverGroup);
		assertEquals(2, admin2.roles[0].permissions.length);
		assertTrue(contains(admin2.roles[0].permissions, "CHANGE_LOG_LEVEL"));
		assertTrue(contains(admin2.roles[0].permissions, "CMD_SHUTDOWN"));
	}

	private String readFile(String name) throws IOException, JSONException {
		File file = new File(name);
		FileReader reader = new FileReader(file);
		char[] buffer = new char[(int) file.length()];
		reader.read(buffer);
		String json = new String(buffer);
		reader.close();
		return json;
	}

}


text:
<?php

namespace Composer\Installers;

class RoundcubeInstaller extends BaseInstaller
{
    /** @var array<string, string> */
    protected $locations = array(
        'plugin' => 'plugins/{$name}/',
    );

    /**
     * Lowercase name and changes the name to a underscores
     */
    public function inflectPackageVars(array $vars): array
    {
        $vars['name'] = strtolower(str_replace('-', '_', $vars['name']));

        return $vars;
    }
}


text:
layout: post
title: Sistemas empotrados I
author: Juanma Gomez  < jmgomez@iaa.es >
categories: Teoria Embebidos RaspberryPi
---

## Introducción
Un **sistema embebido** es una combinación de hardware y software diseñado para un tipo de _aplicación especifica_, cuyo software por lo general enfrenta a una tarea de _tiempo real_. Al tratarse de sistemas de proposito especifico, en la mayoria de las ocasiones, todos los componentes se encuentran incluidos en la placa base y no suelen permitir ampliaciones de hardware.

![Image Ejemplos de sistemas empotrados, lavadoras, microondas, controles de acceso, televisiones](images/Embedded-System-and-Its-Real-Time-Applications-Image-3.jpg)

Por lo general, un sistema embebido incluye un pequeño procesador con una memoria acorde al mismo. La comunicacion es un aspecto fundamental de los mismos, suelen incluir puertos de comunicaciones que soportan los protocolos mas comunes, 1Wire, I2C, SPI, CAN, UART. Al igual, que las comunicaciones se suelen incluir modulos de control, generalmente PWM y Timers para manejar actuadores (motores, reles, leds, etc).

Puesto que se suelen fabricar miles o cientos de miles el costo es un factor de gran importarcia.

Hasta no hace mucho, no era habitual, que los fabricantes dieran un gran soporte. El empleo de arquitecturas exoticas, alejaba a estos sistemas de los metodos estandars de desarrollo. De echo, no es extraño que el software de los sistemas empotrados sea programado en Ensamblador. Sin embargo, en la actualidad los fabricantes de procesadores tratan de aproximarse lo maximo posible al estandard, creando forks de GGC o LLVM y para proporcionar una toolchain decente.

En resumen, podemos decir que entre las principales caracteristicas de los sistema empotrados podemos destacar:
* Diseñados a medida.
* Costes muy ajustados.
* Recursos limitados.
 * Cantidad de memoria.
 * Potencia de cálculo.
 * Perifericos disponibles.
 * Puertos de E/S.

## Tendencias en los sistemas empotrados
El incremento en la capacidad de integracion en la fabricacion de Circuitos Integrados, origino un movimiento de los fabricantes hacia la inclusion de mas componentes dentro del mismo circuitos integrado. De esta forma se consegue reducir costes y construir sistemas mas reducidos.

Este movimiento se ha llevado al extremo, ahora practicamente todo el sistema esta integrado dentro del mismo chip. Dentro del mismo chip se incluye el microprocesador, la memoria, los controladores de las interfaces, timers y pwms conformando un *system on chip* (SoC).

Dependiendo de la tirada es posible que el costo de fabricar un SoC no sea abarcable y entonces se suele recurrir a System in Package (SIP). En la que varias chips comparten encapsulado.

![Image of ARM System-on-chip Block Diagram]({{ site.baseurl }}/images/500px-ARMSoCBlockDiagram.svg.png)

La mayoría de SoC son desarrollados a partir de módulos de hardware básicos previamente probados para la construcción de diversos elementos más complejos junto con los controladores de software que proporcionan las instrucciones para su manejo. Estos elementos constitutivos suelen estar interconectados mediante el empleo de buses.

## Raspberry Pi

![Raspberry Pi3 Board]({{ site.baseurl }}/images/board_rpi3.jpg)

Raspberry Pi es un pequeño computador del tamañano de una tarjeta de crédito, el cual podemos conectar fácilmente a una televisión vía HDMI. Además, podemos utilizarla, con un teclado y un ratón. Tiene conexión a Internet y unos pines GPIO (General Purpose Input/Output), para que podamos interactuar con nuestra placa con sensores, botones, o lo que queramos.

![Raspberry pi 3 BlockDiagram Curso pag 22](rpi3_blk_diagram.jpg)

Los sistemas Raspberry Pi 3 estan basados en el SOC BCM2837. Este SoC del fabricante Broadcom incluye una CPU con juego de instrucciones de 64bit de la familia ARMv8. Se trata de un procesador es Quad Core, o sea, de cuatro núcleos y de tipo Cortex-A53 con una velocidad de 1.2GHz, dispone de 32kB de memoria caché de nivel 1 y 512kB de caché de nivel 2. Por otro lado, el SoC incluye una GPU con dual core VideoCore IV a 400MHz y que soporta OpenGL ES 2.0.

El ARM Cortex-A53 es un procesador de altas prestaciones y alta eficiciencia energetica. Permite dos modos de ejecucion, AArch32 y AArch64, con lo que puede ejecutar tanto aplicaciones de 32 como de 64 bits.
[Ampliar Cortex-A53](https://developer.arm.com/products/processors/cortex-a/cortex-a53)

### Instalar Raspbian
El sistema Raspberry Pi 3, incluye una interfaz microSD desde la cual el sistema es capaz de arrancar el Sistema Operativo. Muchos de los sistema empotrados (de cierta potencia), disponibles en el mercado estan soportados por el SO **Linux**.

La fundación Raspberry nos proporciona una distribucion del SO Linux precompilada y lista para ser instalada en nuestra Raspberry. Nos proporcionan un fichero de imagen, que debemos descargar y grabar en una tarjeta microSD. Esta tarjeta micro SD una vez insertada en el zocalo para tarjetas micro SD, __J9__, permitira arrancar nuestro Raspbian.

A continuacion vamos a poner en practica esto. Necesitaremos el siguiente material:
* __Tarjeta micro SD__ de al menos 4 GB.
* __Herramientas descompresion__ como PeaZIP, 7Zip.
* __Herramientas grabacion micro SD__ como Image Write Tool, Rufus o el clasico dd.
* __Lector de tarjetas micro SD__ y si es necesario el adaptador de micro SD a SD.

En primer lugar vamos a descargar la imagen de Raspbian de la web de raspberry y descomprimirla:

{% highlight bash %}
~]$ wget -O rasbian_lite_latest.zip
~]$ unzip raspbian_lite_latest.zip
~]$ ls

raspbian_lite_latest.zip
2018-04-18-raspbian-stretch-lite.img

{% endhighlight %}

Insertamos nuestra tarjeta micro SD en el lector y mostramos los dispositivos de bloques del sistema para localizar nuestra micro SD.

{% highlight bash %}
~]$ lsblk
mmcblk0                179:0    0  14,9G  0 disk
└─mmcblk0p1            179:1    0  14,9G  0 part
{% endhighlight %}

Y finalmente copiamos la imagen a la tarjeta:

{%highlight bash %}
#Copiamos la imagen al dispositivo sdc. Precaución todos los datos se borraran.
~]$ su
~]$ dd if=2018-04-18-raspbian-stretch.img | pv -tpreb | dd of=/dev/sdXX bs=128M
~]$ sync
{% endhighlight %}

### Conexion con la Raspberry Pi
A partir de 2016, las imágenes de Raspbian, el servicio ssh viene por defecto desactivado. Dadas las limitaciones de material disponible, para poder trabajar con nuestro sistema empotrado vamos a activar el servicio ssh.
La documentación indica que debemos crear un fichero llamado ssh en la partición boot. Asi que repetimos el proceso anterior y montamos la partición /boot en nuestro sistema host.
{%highlight bash %}
~]$ su
~]$ mkdir -p stretch/boot
~]$ mount /dev/mmcblk0p1 stretch/boot
{% endhighlight %}

Vamos a crear el fichero y activar el servidor ssh.
{%highlight bash %}
~]$ touch stretch/boot/ssh
~]$ umount stretch/boot
{% endhighlight %}

Debemos localizar nuestra rpi3
`~]$ namp -sn 10.9.0.11/24`

Y finalmente conectamos:
{%highlight bash %}
~]$ ssh pi@10.9.0.104
ECDSA key fingerprint is SHA256:6p2Ot94wyN63G+/h2eBx0eoCqCCZxrPgbvIBNiHzX+I.
ECDSA key fingerprint is MD5:3f:b1:39:05:25:5d:a6:7a:12:f3:fb:ac:6d:e4:15:fe.
Are you sure you want to continue connecting (yes/no)? yes

pi@10.9.0.104's password:  raspberry
Linux raspberrypi 4.14.34-v7+ #1110 SMP Mon Apr 16 15:18:51 BST 2018 armv7l

{% endhighlight %}

# Objetivos

* Manejar  herramientas de desarrollo para construir sistemas embebidos.
* Configurar un sistema embebido basado en micropocesador.

>"The most important factor for me is that the device must be supported in upstream Linux (preferably stable, but mainline will do) and U-Boot"
>Juan M. Gómez

> "Dive into the hardware from a linux and you will have the key to to rule them all"
> Juan P. Cobos

Next : Instalación del sistema operativo.

[raspbian_web]: https://www.raspberrypi.org/downloads/raspbian/


text:
from django.contrib import admin
from models import Invitation, InvitationStats

class InvitationAdmin(admin.ModelAdmin):
    list_display = ('user', 'email', 'expiration_date')
admin.site.register(Invitation, InvitationAdmin)

class InvitationStatsAdmin(admin.ModelAdmin):
    list_display = ('user', 'available', 'sent', 'accepted', 'performance')

    def performance(self, obj):
        return '%0.2f' % obj.performance
admin.site.register(InvitationStats, InvitationStatsAdmin)


text:
<?php

namespace Xeeo\Services\Authenticate\Components;

use \Xeeo\Services\Authenticate\Exceptions\Authenticate as AuthenticateException;

trait HashAlgorithm {

	private $hashAlgorithm = PASSWORD_DEFAULT;
	private $hashSalt      = '';
	private $hashCost      = 10;

	public function getHashAlgorithm() {
		return (int) $this->hashAlgorithm;
	}

	public function setHashAlgorithm($hashAlgorithm) {
		$this->hashAlgorithm = (int) $hashAlgorithm;

        return $this;
	}

	public function getHashSalt() {
		return (string) $this->hashSalt;
	}

	public function setHashSalt($hashSalt) {
		$this->hashSalt = (string) $hashSalt;

		return $this;
	}

	public function getHashCost() {
		return (int) $this->hashCost;
	}

	public function setHashCost($hashCost) {
		$this->hashCost = (int) $hashCost;

		return $this;
	}

    public function hashPassword($plainPassword) {
        return password_hash($plainPassword, $this->getHashAlgorithm());
    }

    /**
     * Generates a random Password
     *
     * @param int $length password length
     *
     * @return string
     */
    public function generatePassword($length = 10)
    {
        $password    = '';
        $values      = array_merge(range(0, 9), range('a', 'z'), array('$', ':', '?', '%', '&'));
        $countValues = count($values) - 1;

        for ($i = 1; $i <= $length; $i++) {
            $password .= $values[rand(0, $countValues)];
        }

        return $password;
    }

    public function validatePassword($plainPassword, $hashedPassword) {
        if (false === password_verify($plainPassword, $hashedPassword)) {
            throw new AuthenticateException(
                AuthenticateException::MSG_WRONG_PASSWORD,
                AuthenticateException::CODE_WRONG_PASSWORD
            );
        }

        return true;
    }

}


text:
package org.apache.ignite.internal.processors.cache.distributed.dht;

import org.apache.ignite.*;
import org.apache.ignite.cache.affinity.*;
import org.apache.ignite.cache.affinity.rendezvous.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.events.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.spi.discovery.tcp.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
import org.apache.ignite.testframework.junits.common.*;
import org.apache.ignite.transactions.*;

import javax.cache.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

import static org.apache.ignite.cache.CacheDistributionMode.*;
import static org.apache.ignite.cache.CacheMode.*;
import static org.apache.ignite.cache.CacheRebalanceMode.*;
import static org.apache.ignite.events.EventType.*;
import static org.apache.ignite.transactions.TransactionConcurrency.*;
import static org.apache.ignite.transactions.TransactionIsolation.*;

/**
 * Tests that new transactions do not start until partition exchange is completed.
 */
public class GridCachePartitionedTopologyChangeSelfTest extends GridCommonAbstractTest {
    /** Partition does not belong to node. */
    private static final int PARTITION_READER = 0;

    /** Node is primary for partition. */
    private static final int PARTITION_PRIMARY = 1;

    /** Node is backup for partition. */
    private static final int PARTITION_BACKUP = 2;

    /** */
    private static final TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
        IgniteConfiguration c = super.getConfiguration(gridName);

        // Discovery.
        TcpDiscoverySpi disco = new TcpDiscoverySpi();

        disco.setIpFinder(ipFinder);

        c.setDiscoverySpi(disco);

        CacheConfiguration cc = defaultCacheConfiguration();

        cc.setCacheMode(PARTITIONED);
        cc.setAffinity(new CacheRendezvousAffinityFunction(false, 18));
        cc.setBackups(1);
        cc.setRebalanceMode(SYNC);
        cc.setDistributionMode(PARTITIONED_ONLY);

        c.setCacheConfiguration(cc);

        return c;
    }

    /**
     * @throws Exception If failed.
     */
    public void testNearTxNodeJoined() throws Exception {
        checkTxNodeJoined(PARTITION_READER);
    }

    /**
     * @throws Exception If failed.
     */
    public void testPrimaryTxNodeJoined() throws Exception {
        checkTxNodeJoined(PARTITION_PRIMARY);
    }

    /**
     * @throws Exception If failed.
     */
    public void testBackupTxNodeJoined() throws Exception {
        checkTxNodeJoined(PARTITION_BACKUP);
    }

    /**
     * @throws Exception If failed.
     */
    public void testNearTxNodeLeft() throws Exception {
        checkTxNodeLeft(PARTITION_READER);
    }

    /**
     * @throws Exception If failed.
     */
    public void testPrimaryTxNodeLeft() throws Exception {
        // This test does not make sense because if node is primary for some partition,
        // it will reside on node until node leaves grid.
    }

    /**
     * @throws Exception If failed.
     */
    public void testBackupTxNodeLeft() throws Exception {
        checkTxNodeLeft(PARTITION_BACKUP);
    }

    /**
     * @throws Exception If failed.
     */
    public void testExplicitLocks() throws Exception {
        try {
            startGridsMultiThreaded(2);

            IgniteKernal[] nodes = new IgniteKernal[] {(IgniteKernal)grid(0), (IgniteKernal)grid(1)};

            Collection<IgniteInternalFuture> futs = new ArrayList<>();

            final CountDownLatch startLatch = new CountDownLatch(1);

            for (final IgniteKernal node : nodes) {
                List<Integer> parts = partitions(node, PARTITION_PRIMARY);

                Map<Integer, Integer> keyMap = keysFor(node, parts);

                for (final Integer key : keyMap.values()) {
                    futs.add(multithreadedAsync(new Runnable() {
                        @Override public void run() {
                            try {
                                Lock lock = node.jcache(null).lock(key);

                                lock.lock();

                                try {

                                    info(">>> Acquired explicit lock for key: " + key);

                                    startLatch.await();

                                    info(">>> Acquiring explicit lock for key: " + key * 10);

                                    Lock lock10 = node.jcache(null).lock(key * 10);

                                    lock10.lock();

                                    try {
                                        info(">>> Releasing locks [key1=" + key + ", key2=" + key * 10 + ']');
                                    }
                                    finally {
                                        lock10.unlock();
                                    }
                                }
                                finally {
                                    lock.unlock();
                                }
                            }
                            catch (CacheException e) {
                                info(">>> Failed to perform lock [key=" + key + ", e=" + e + ']');
                            }
                            catch (InterruptedException ignored) {
                                info(">>> Interrupted while waiting for start latch.");

                                Thread.currentThread().interrupt();
                            }
                        }
                    }, 1));
                }
            }

            IgniteInternalFuture<?> startFut = multithreadedAsync(new Runnable() {
                @Override public void run() {
                    try {
                        startGrid(2);

                        info(">>> Started grid2.");
                    }
                    catch (Exception e) {
                        info(">>> Failed to start grid: " + e);
                    }
                }
            }, 1);

            U.sleep(5000);

            assertFalse(startFut.isDone());

            info(">>> Waiting for all locks to be released.");

            startLatch.countDown();

            for (IgniteInternalFuture fut : futs)
                fut.get(1000);

            startFut.get();
        }
        finally {
            stopAllGrids();
        }
    }

    /**
     * @throws Exception If failed.
     */
    private void checkTxNodeJoined(int nodeType) throws Exception {
        startGrids(3);

        final IgniteKernal g0 = (IgniteKernal)grid(0);
        final IgniteKernal g1 = (IgniteKernal)grid(1);
        final IgniteKernal g2 = (IgniteKernal)grid(2);

        IgniteKernal[] nodes = new IgniteKernal[] {g0, g1, g2};

        try {
            info(">>> Started nodes [g0=" + g0.localNode().id() + ", g1=" + g1.localNode().id() + ", g2=" +
                g2.localNode().id() + ']');

            final CountDownLatch commitLatch = new CountDownLatch(1);

            Collection<IgniteInternalFuture> futs = new ArrayList<>();

            for (final IgniteKernal node : nodes) {
                printDistribution(node);

                // Get partitions that does not reside on g0.
                List<Integer> parts = partitions(node, nodeType);

                info(">>> Partitions for node [nodeId=" + node.localNode().id() + ", parts=" + parts +
                   ", type=" + nodeType + ']');

                final Map<Integer, Integer> keysMap = keysFor(node, parts);

                info(">>> Generated keys for node [nodeId=" + node.localNode().id() + ", keysMap=" + keysMap + ']');

                // Start tx for every key in map.
                for (final Integer key : keysMap.values()) {
                    futs.add(multithreadedAsync(new Runnable() {
                        @Override public void run() {
                            IgniteCache<Integer, Integer> cache = node.jcache(null);

                            try {
                                try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
                                    cache.put(key, key);

                                    info(">>> Locked key, waiting for latch: " + key);

                                    commitLatch.await();

                                    tx.commit();
                                }
                            }
                            catch (CacheException e) {
                                info("Failed to run tx for key [key=" + key + ", e=" + e + ']');
                            }
                            catch (InterruptedException ignored) {
                                Thread.currentThread().interrupt();

                                info("Got interrupted while waiting for commit latch: " + key);
                            }
                        }
                    }, 1));
                }
            }

            final CountDownLatch joinLatch = new CountDownLatch(1);

            g0.events().localListen(new IgnitePredicate<Event>() {
                @Override public boolean apply(Event evt) {
                    assert evt.type() == EVT_NODE_JOINED;

                    info(">>> Node has joined: " + evt.node().id());

                    joinLatch.countDown();

                    g0.events().stopLocalListen(this, EVT_NODE_JOINED);

                    return true;
                }
            }, EVT_NODE_JOINED);

            // Now start new node. We do it in a separate thread since startGrid
            // should block until partition exchange completes.
            IgniteInternalFuture startFut = multithreadedAsync(new Runnable() {
                @Override public void run() {
                    try {
                        Ignite g3 = startGrid(3);

                        info(">>> Started grid g3: " + g3.cluster().localNode().id());
                    }
                    catch (Exception e) {
                        info(">>> Failed to start 4th node: " + e);
                    }
                }
            }, 1);

            joinLatch.await();

            Thread.sleep(100);

            assertFalse("Node was able to join the grid while there exist pending transactions.", startFut.isDone());

            // Now check that new transactions will wait for new topology version to become available.
            Collection<IgniteInternalFuture> txFuts = new ArrayList<>(nodes.length);

            for (final Ignite g : nodes) {
                txFuts.add(multithreadedAsync(new Runnable() {
                    @Override public void run() {
                        IgniteCache<Integer, Integer> cache = g.jcache(null);

                        int key = (int)Thread.currentThread().getId();

                        try {
                            try (Transaction tx = g.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
                                // This method should block until all previous transactions are completed.
                                cache.put(key, key);

                                info(">>> Acquired second lock for key: " + key);

                                tx.commit();
                            }
                        }
                        catch (CacheException e) {
                            info(">>> Failed to execute tx on new topology [key=" + key + ", e=" + e + ']');
                        }
                    }
                }, 1));
            }

            Thread.sleep(500);

            for (IgniteInternalFuture txFut : txFuts)
                assertFalse("New transaction was completed before new node joined topology", txFut.isDone());

            info(">>> Committing pending transactions.");

            commitLatch.countDown();

            for (IgniteInternalFuture fut : futs)
                fut.get(1000);

            startFut.get(1000);

            for (IgniteInternalFuture txFut : txFuts)
                txFut.get(1000);
        }
        finally {
            stopAllGrids();
        }
    }

    /**
     * @throws Exception If failed.
     */
    private void checkTxNodeLeft(int nodeType) throws Exception {
        startGridsMultiThreaded(4);

        final IgniteKernal g0 = (IgniteKernal)grid(0);
        final IgniteKernal g1 = (IgniteKernal)grid(1);
        final IgniteKernal g2 = (IgniteKernal)grid(2);
        final IgniteKernal g3 = (IgniteKernal)grid(3);

        IgniteKernal[] nodes = new IgniteKernal[] {g0, g1, g2};

        final CountDownLatch commitLatch = new CountDownLatch(1);

        UUID leftNodeId = g3.localNode().id();

        try {
            info(">>> Started nodes [g0=" + g0.localNode().id() + ", g1=" + g1.localNode().id() + ", g2=" +
                g2.localNode().id() + ", g3=" + g3.localNode().id() + ']');

            Collection<IgniteInternalFuture> futs = new ArrayList<>();

            printDistribution(g3);

            for (final IgniteKernal node : nodes) {
                printDistribution(node);

                // Get partitions that does not reside on g0.
                List<Integer> parts = partitions(node, nodeType);

                info(">>> Partitions for node [nodeId=" + node.localNode().id() + ", parts=" + parts +
                    ", type=" + nodeType + ']');

                final Map<Integer, Integer> keysMap = keysFor(node, parts);

                info(">>> Generated keys for node [nodeId=" + node.localNode().id() + ", keysMap=" + keysMap + ']');

                // Start tx for every key in map.
                for (final Integer key : keysMap.values()) {
                    futs.add(multithreadedAsync(new Runnable() {
                        @Override public void run() {
                            IgniteCache<Integer, Integer> cache = node.jcache(null);

                            try {
                                try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
                                    cache.put(key, key);

                                    commitLatch.await();

                                    tx.commit();
                                }
                            }
                            catch (CacheException e) {
                                info("Failed to run tx for key [key=" + key + ", e=" + e + ']');
                            }
                            catch (InterruptedException ignored) {
                                Thread.currentThread().interrupt();

                                info("Got interrupted while waiting for commit latch: " + key);
                            }
                        }
                    }, 1));
                }
            }

            final CountDownLatch leaveLatch = new CountDownLatch(1);

            g0.events().localListen(new IgnitePredicate<Event>() {
                @Override public boolean apply(Event evt) {
                    assert evt.type() == EVT_NODE_LEFT || evt.type() == EVT_NODE_FAILED;

                    info(">>> Node has left: " + evt.node().id());

                    leaveLatch.countDown();

                    g0.events().stopLocalListen(this, EVT_NODE_LEFT, EVT_NODE_FAILED);

                    return true;
                }
            }, EVT_NODE_LEFT, EVT_NODE_FAILED);

            // Now stop the node.
            stopGrid(getTestGridName(3), true);

            leaveLatch.await();

            // Now check that new transactions will wait for new topology version to become available.
            Collection<IgniteInternalFuture> txFuts = new ArrayList<>(nodes.length);

            for (final Ignite g : nodes) {
                txFuts.add(multithreadedAsync(new Runnable() {
                    @Override public void run() {
                        IgniteCache<Integer, Integer> cache = g.jcache(null);

                        int key = (int)Thread.currentThread().getId();

                        try {
                            try (Transaction tx = g.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
                                // This method should block until all previous transactions are completed.
                                cache.put(key, key);

                                tx.commit();
                            }
                        }
                        catch (CacheException e) {
                            info(">>> Failed to execute tx on new topology [key=" + key + ", e=" + e + ']');
                        }
                    }
                }, 1));
            }

            Thread.sleep(500);

            for (IgniteInternalFuture txFut : txFuts)
                assertFalse("New transaction was completed before old transactions were committed", txFut.isDone());

            info(">>> Committing pending transactions.");

            commitLatch.countDown();

            for (IgniteInternalFuture fut : futs)
                fut.get(1000);

            for (IgniteInternalFuture txFut : txFuts)
                txFut.get(1000);

            for (int i = 0; i < 3; i++) {
                CacheAffinity affinity = grid(i).affinity(null);

                ConcurrentMap addedNodes = U.field(affinity, "addedNodes");

                assertFalse(addedNodes.containsKey(leftNodeId));
            }
        }
        finally {
            info(">>> Shutting down the test.");

            commitLatch.countDown();

            U.sleep(1000);

            stopAllGrids();
        }
    }

    /**
     * Prints partition distribution for node.
     *
     * @param node Node to detect partitions for.
     */
    private void printDistribution(IgniteKernal node) {
        List<Integer> primary = partitions(node, PARTITION_PRIMARY);
        List<Integer> backup = partitions(node, PARTITION_BACKUP);
        List<Integer> reader = partitions(node, PARTITION_READER);

        info(">>> Partitions distribution calculated [nodeId=" + node.localNode().id() + ", primary=" + primary +
            ", backup=" + backup + ", reader=" + reader + ']');
    }

    /**
     * For each partition given calculates a key that belongs to this partition. Generated keys are
     * in ascending order.
     *
     * @param node Node to use.
     * @param parts Partitions to get keys for.
     * @return Map from partition to key.
     */
    private Map<Integer, Integer> keysFor(IgniteKernal node, Iterable<Integer> parts) {
        GridCacheContext<Object, Object> ctx = node.internalCache().context();

        Map<Integer, Integer> res = new HashMap<>();

        int key = 0;

        for (Integer part : parts) {
            while (ctx.affinity().partition(key) != part)
                key++;

            res.put(part, key);
        }

        return res;
    }

    /**
     * Gets partitions that are not resided on given node (neither as primary nor as backup).
     *
     * @param node Node to calculate partitions for.
     * @return List of partitions.
     */
    private List<Integer> partitions(Ignite node, int partType) {
        List<Integer> res = new LinkedList<>();

        CacheAffinity<Object> aff = node.affinity(null);

        for (int partCnt = aff.partitions(), i = 0; i < partCnt; i++) {
            ClusterNode locNode = node.cluster().localNode();

            switch (partType) {
                // Near, partition should not belong to node.
                case PARTITION_READER: {
                    if (!aff.isPrimaryOrBackup(locNode, i))
                        res.add(i);

                    break;
                }

                // Node should be primary for partition.
                case PARTITION_PRIMARY: {
                    if (aff.isPrimary(locNode, i))
                        res.add(i);

                    break;
                }

                // Node should be backup for partition.
                case PARTITION_BACKUP: {
                    if (aff.isPrimaryOrBackup(locNode, i) && !aff.isPrimary(locNode, i))
                        res.add(i);

                    break;
                }

                default: {
                    assert false;
                }
            }
        }

        return res;
    }
}


text:
package org.platanios.tensorflow.api.ops.variables

import org.platanios.tensorflow.api.core.{Graph, Shape}
import org.platanios.tensorflow.api.core.exception.{InvalidDataTypeException, ShapeMismatchException}
import org.platanios.tensorflow.api.core.types.{DataType, TF}
import org.platanios.tensorflow.api.ops.{Op, OpSpecification}
import org.platanios.tensorflow.api.ops.variables.Variable.VariableGetter

/** Variable scope that carries default settings to provide to `getVariable`.
  *
  * A variable scope allows to create new variables and to share already created ones while providing checks to not
  * create or share by accident.
  *
  * Many of the arguments we need for `getVariable` in a variable store are most easily handled with a context.
  * [[VariableScope]] objects are used for the defaults.
  *
  * @param  reuse            [[Reuse]] value indicating whether to re-use an existing variable with the same name,
  *                          create a new variable, or do either.
  * @param  name             Name of the variable scope, used as a prefix in `getVariable`.
  * @param  initializer      Default initializer passed to `getVariable`.
  * @param  regularizer      Default regularizer passed to `getVariable`.
  * @param  cachingDevice    Default caching device passed to `getVariable`.
  * @param  nameScope        Default name scope passed to `getVariable`.
  * @param  underlyingGetter Default underlying variable getter passed to `getVariable`.
  *
  * @author Emmanouil Antonios Platanios
  */
case class VariableScope private[variables](
    reuse: Reuse,
    name: String = "",
    initializer: Initializer = null,
    regularizer: Regularizer = null,
    cachingDevice: OpSpecification => String = null,
    nameScope: String = "",
    underlyingGetter: VariableGetter = null
) {
  /** Gets an existing variable with the specified name or creates a new one.
    *
    * @param  store         Variable store currently being used to store variables.
    * @param  name          Variable name.
    * @param  shape         Variable shape.
    * @param  initializer   Variable initializer. If `initializer` is `null` (the default), the default initializer
    *                       passed in the constructor is used. If that one is `null` too, then we use a new
    *                       `glorotUniformInitializer`. The initializer will be called for each part of the partitioned
    *                       variable separately.
    * @param  regularizer   Variable regularizer.
    * @param  trainable     If `true`, the default, the variable is added to the graph collection
    *                       `Graph.Keys.TRAINABLE_VARIABLES`. This collection is used as the default set of variables
    *                       to use by the optimizers.
    * @param  reuse         [[Reuse]] value indicating whether to re-use an existing variable with the same name, create
    *                       a new variable, or do either.
    *                       - If `reuse` is `null` (the default), both new and existing variables are returned.
    * @param  collections   Set of graph collections keys. The variable is added to these collections. Defaults to
    *                       `Set(Graph.Keys.GLOBAL_VARIABLES)`.
    * @param  cachingDevice Device specification describing where the variable should be cached for reading. Defaults
    *                       to the variable's device. Typical use is to cache on the device where the ops using the
    *                       variable reside, to deduplicate copying through `Switch` and other conditional statements.
    * @tparam T             Variable data type.
    * @return Requested variable.
    * @throws IllegalArgumentException If any of the provided arguments are not compatible with each other, or with the
    *                                  variables stored in this variable store.
    * @throws ShapeMismatchException   If the provided shape does not match the shape of the corresponding variable
    *                                  stored in this variable store (if there exists one).
    * @throws InvalidDataTypeException If the provided data type does not match the data type of the corresponding
    *                                  variable stored in this variable store (if there exists one).
    */
  @throws[IllegalArgumentException]
  @throws[ShapeMismatchException]
  @throws[InvalidDataTypeException]
  def getVariable[T: TF](
      store: VariableStore,
      name: String,
      shape: Shape,
      initializer: Initializer = this.initializer,
      regularizer: Regularizer = this.regularizer,
      trainable: Boolean = true,
      reuse: Reuse = this.reuse,
      collections: Set[Graph.Key[Variable[Any]]] = Set.empty,
      cachingDevice: OpSpecification => String = this.cachingDevice
  ): Variable[T] = {
    val fullName = {
      if (this.name != null && this.name != "")
        s"${this.name}/$name"
      else
        name
    }
    // Variable names only depend on the variable scope and not the name scope, so we reset it below for the time of
    // variable creation.
    Op.nameScope("") {
      store.getVariable(
        fullName, shape, initializer, regularizer,
        trainable, reuse, collections, cachingDevice)
    }
  }
}

private[api] object VariableScope {
  /** Returns the current variable scope. */
  def current: VariableScope = {
    VariableScopeStore.current.scope
  }

  /** Sets the variable scope to use for op creation context, for all code in `block`.
    *
    * @param  name             Variable scope name, that may also change the name scope of the op creation context,
    *                          depending on the value of `isPure`.
    * @param  reuse            [[Reuse]] value indicating whether to re-use an existing variable with the same name, or
    *                          do either. Note that this argument cannot be set to [[CreateNewOnly]] in this function.
    *                          If set to [[ReuseOrCreateNew]], then the parent variable scope `reuse` value is used
    *                          (i.e., propagated).
    * @param  initializer      Default initializer for variables within the scope.
    * @param  regularizer      Default regularizer for variables within the scope.
    * @param  cachingDevice    Default caching device for variables within the scope.
    * @param  underlyingGetter Default variable getter for variables within the scope.
    * @param  isDefaultName    Boolean value indicating whether `name` is a default name or not. If `true`, then `name`
    *                          will be made unique before being used. `isDefaultName` cannot be set to `true` when
    *                          `reuse` is set to [[ReuseExistingOnly]].
    * @param  isPure           Boolean value indicating whether to use a "pure" variable scope. That is, a variable
    *                          scope that does not affect the name scope of the current op creation context.
    * @param  block            Code block to run using the provided options.
    * @tparam R Return type of the code block.
    * @return Return value of the code block.
    */
  private[api] def scope[R](
      name: String,
      reuse: Reuse = ReuseOrCreateNew,
      initializer: Initializer = null,
      regularizer: Regularizer = null,
      cachingDevice: OpSpecification => String = null,
      underlyingGetter: VariableGetter = null,
      isDefaultName: Boolean = false,
      isPure: Boolean = false
  )(block: => R): R = {
    if (reuse == ReuseExistingOnly && isDefaultName)
      throw new IllegalArgumentException(
        "'reuse' cannot be set to 'ReuseExistingOnly' with 'isDefaultName' set to 'true'.")
    val variableScopeStore = VariableScopeStore.current
    val oldVariableScope = variableScopeStore.scope
    val newName = {
      val uniqueName = if (isDefaultName) VariableScope.unique(name) else name
      if (oldVariableScope.name != null && oldVariableScope.name != "")
        s"${oldVariableScope.name}/$uniqueName"
      else
        uniqueName
    }
    variableScopeStore.enterVariableScope(newName)
    val newVariableScope = VariableScope(
      reuse = if (reuse == ReuseOrCreateNew) oldVariableScope.reuse else reuse,
      name = newName,
      initializer = if (initializer == null) oldVariableScope.initializer else initializer,
      regularizer = if (regularizer == null) oldVariableScope.regularizer else regularizer,
      cachingDevice = if (cachingDevice == null) oldVariableScope.cachingDevice else cachingDevice,
      nameScope = name,
      underlyingGetter = {
        if (underlyingGetter == null)
          oldVariableScope.underlyingGetter
        else
          maybeWrapCustomVariableGetter(underlyingGetter, oldVariableScope.underlyingGetter)
      })
    variableScopeStore.scope = newVariableScope
    val result = if (isPure) block else Op.nameScope(name)(block)
    variableScopeStore.closeVariableSubScopes(newName)
    variableScopeStore.scope = oldVariableScope
    result
  }

  /** Sets the variable scope to use for op creation context, for all code in `block`.
    *
    * @param  variableScope    Default variable scope to use. Other arguments of this function can override the
    *                          corresponding parameters of `variableScope`.
    * @param  reuse            [[Reuse]] value indicating whether to re-use an existing variable with the same name, or
    *                          do either. Note that this argument cannot be set to [[CreateNewOnly]] in this function.
    *                          If set to [[ReuseOrCreateNew]], then the parent variable scope `reuse` value is used
    *                          (i.e., propagated).
    * @param  initializer      Default initializer for variables within the scope.
    * @param  regularizer      Default regularizer for variables within the scope.
    * @param  cachingDevice    Default caching device for variables within the scope.
    * @param  underlyingGetter Default variable getter for variables within the scope.
    * @param  isPure           Boolean value indicating whether to use a "pure" variable scope. That is, a variable
    *                          scope that does not affect the name scope of the current op creation context.
    * @param  block            Code block to run using the provided options.
    * @tparam R Return type of the code block.
    * @return Return value of the code block.
    */
  private[api] def updatedScope[R](
      variableScope: VariableScope = VariableScope.current,
      reuse: Reuse = ReuseOrCreateNew,
      initializer: Initializer = null,
      regularizer: Regularizer = null,
      cachingDevice: OpSpecification => String = null,
      underlyingGetter: VariableGetter = null,
      isPure: Boolean = false
  )(block: => R): R = {
    val variableScopeStore = VariableScopeStore.current
    val oldVariableScope = variableScopeStore.scope
    val oldVariableScopeCounts = variableScopeStore.variableScopeCounts
    variableScopeStore.enterVariableScope(variableScope.name)
    val newVariableScope = VariableScope(
      reuse = if (reuse == ReuseOrCreateNew) variableScope.reuse else reuse,
      name = variableScope.name,
      initializer = if (initializer == null) variableScope.initializer else initializer,
      regularizer = if (regularizer == null) variableScope.regularizer else regularizer,
      cachingDevice = if (cachingDevice == null) variableScope.cachingDevice else cachingDevice,
      nameScope = variableScope.nameScope,
      underlyingGetter = {
        if (underlyingGetter == null)
          variableScope.underlyingGetter
        else
          maybeWrapCustomVariableGetter(underlyingGetter, variableScope.underlyingGetter)
      })
    variableScopeStore.scope = newVariableScope
    val result = if (isPure) block else Op.nameScope(variableScope.name.split("/").last)(block)
    variableScopeStore.closeVariableSubScopes(variableScope.name)
    variableScopeStore.variableScopeCounts = oldVariableScopeCounts
    variableScopeStore.scope = oldVariableScope
    result
  }

  /** If a new getter is provided, it wraps around the old one and the new wrapped getter is returned. Otherwise, the
    * old getter is returned.
    *
    * @param  getter    New variable getter.
    * @param  oldGetter Old variable getter.
    * @return Variable getter to use.
    */
  private[api] def maybeWrapCustomVariableGetter(
      getter: VariableGetter,
      oldGetter: VariableGetter
  ): VariableGetter = {
    if (getter == null) {
      oldGetter
    } else {
      new VariableGetter {
        override def apply[T: TF](
            name: String,
            dataType: DataType[T],
            shape: Shape,
            initializer: Initializer,
            regularizer: Regularizer,
            trainable: Boolean,
            reuse: Reuse,
            collections: Set[Graph.Key[Variable[Any]]],
            cachingDevice: OpSpecification => String,
            underlyingGetter: VariableGetter
        ): Variable[T] = {
          val baseGetter: VariableGetter = new VariableGetter {
            override def apply[R: TF](
                name: String,
                dataType: DataType[R],
                shape: Shape,
                initializer: Initializer,
                regularizer: Regularizer,
                trainable: Boolean,
                reuse: Reuse,
                collections: Set[Graph.Key[Variable[Any]]],
                cachingDevice: OpSpecification => String,
                underlyingGetter: VariableGetter
            ): Variable[R] = {
              oldGetter(
                name, dataType, shape, initializer, regularizer, trainable,
                reuse, collections, cachingDevice, underlyingGetter)
            }
          }
          getter(
            name, dataType, shape, initializer, regularizer, trainable,
            reuse, collections, cachingDevice, baseGetter)
        }
      }
    }
  }

  /** Gets a name with the provided prefix that is unique in the current variable scope.
    *
    * @param  prefix Prefix.
    * @return Unique name with the provided prefix.
    */
  private[api] def unique(prefix: String): String = {
    val currentScopeStore = VariableScopeStore.current
    val currentScope = Op.convertNameScopeToName(VariableScope.current.name)
    val name = {
      if (currentScope == null || currentScope == "")
        prefix
      else
        s"$currentScope/$prefix"
    }
    if (currentScopeStore.variableScopeCount(name) == 0) {
      prefix
    } else {
      var uniqueName = name
      var count = 1
      while (currentScopeStore.variableScopeCount(uniqueName) > 0) {
        uniqueName = s"${name}_$count"
        count += 1
      }
      uniqueName
    }
  }
}


text:
package com.wenyu.rtmp.camera;

import android.annotation.TargetApi;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;

import com.wenyu.rtmp.camera.exception.CameraHardwareException;
import com.wenyu.rtmp.camera.exception.CameraNotSupportException;
import com.wenyu.rtmp.configuration.CameraConfiguration;
import com.wenyu.rtmp.utils.SopCastLog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@TargetApi(14)
public class CameraHolder {
    private static final String TAG = "CameraHolder";
    private final static int FOCUS_WIDTH = 80;
    private final static int FOCUS_HEIGHT = 80;

    private List<CameraData> mCameraDatas;
    private Camera mCameraDevice;
    private CameraData mCameraData;
    private State mState;
    private SurfaceTexture mTexture;
    private boolean isTouchMode = false;
    private boolean isOpenBackFirst = false;
    private CameraConfiguration mConfiguration = CameraConfiguration.createDefault();

    public enum State {
        INIT,
        OPENED,
        PREVIEW
    }

    private static CameraHolder sHolder;
    public static synchronized CameraHolder instance() {
        if (sHolder == null) {
            sHolder = new CameraHolder();
        }
        return sHolder;
    }

    private CameraHolder() {
        mState = State.INIT;
    }

    public int getNumberOfCameras() {
        return Camera.getNumberOfCameras();
    }

    public CameraData getCameraData() {
        return mCameraData;
    }

    public boolean isLandscape() {
        return (mConfiguration.orientation != CameraConfiguration.Orientation.PORTRAIT);
    }

    public synchronized Camera openCamera()
            throws CameraHardwareException, CameraNotSupportException {
        if(mCameraDatas == null || mCameraDatas.size() == 0) {
            mCameraDatas = CameraUtils.getAllCamerasData(isOpenBackFirst);
        }
        CameraData cameraData = mCameraDatas.get(0);
        if(mCameraDevice != null && mCameraData == cameraData) {
            return mCameraDevice;
        }
        if (mCameraDevice != null) {
            releaseCamera();
        }
        try {
            SopCastLog.d(TAG, "open camera " + cameraData.cameraID);
            mCameraDevice = Camera.open(cameraData.cameraID);
        } catch (RuntimeException e) {
            SopCastLog.e(TAG, "fail to connect Camera");
            throw new CameraHardwareException(e);
        }
        if(mCameraDevice == null) {
            throw new CameraNotSupportException();
        }
        try {
            CameraUtils.initCameraParams(mCameraDevice, cameraData, isTouchMode, mConfiguration);
        } catch (Exception e) {
            e.printStackTrace();
            mCameraDevice.release();
            mCameraDevice = null;
            throw new CameraNotSupportException();
        }
        mCameraData = cameraData;
        mState = State.OPENED;
        return mCameraDevice;
    }

    public void setSurfaceTexture(SurfaceTexture texture) {
        mTexture = texture;
        if(mState == State.PREVIEW && mCameraDevice != null && mTexture != null) {
            try {
                mCameraDevice.setPreviewTexture(mTexture);
            } catch (IOException e) {
                releaseCamera();
            }
        }
    }

    public State getState() {
        return mState;
    }

    public void setConfiguration(CameraConfiguration configuration) {
        isTouchMode = (configuration.focusMode != CameraConfiguration.FocusMode.AUTO);
        isOpenBackFirst = (configuration.facing != CameraConfiguration.Facing.FRONT);
        mConfiguration = configuration;
    }

    public synchronized void startPreview() {
        if(mState != State.OPENED) {
            return;
        }
        if(mCameraDevice == null) {
            return;
        }
        if(mTexture == null) {
            return;
        }
        try {
            mCameraDevice.setPreviewTexture(mTexture);
            mCameraDevice.startPreview();
            mState = State.PREVIEW;
        } catch (Exception e) {
            releaseCamera();
            e.printStackTrace();
        }
    }

    public synchronized void stopPreview() {
        if(mState != State.PREVIEW) {
            return;
        }
        if(mCameraDevice == null) {
            return;
        }
        mCameraDevice.setPreviewCallback(null);
        Camera.Parameters cameraParameters = mCameraDevice.getParameters();
        if (cameraParameters != null && cameraParameters.getFlashMode() != null
                && !cameraParameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF)) {
            cameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        }
        mCameraDevice.setParameters(cameraParameters);
        mCameraDevice.stopPreview();
        mState = State.OPENED;
    }

    public synchronized void releaseCamera() {
        if(mState == State.PREVIEW) {
            stopPreview();
        }
        if(mState != State.OPENED) {
            return;
        }
        if(mCameraDevice == null) {
            return;
        }
        mCameraDevice.release();
        mCameraDevice = null;
        mCameraData = null;
        mState = State.INIT;
    }

    public void release() {
        mCameraDatas = null;
        mTexture = null;
        isTouchMode = false;
        isOpenBackFirst = false;
        mConfiguration = CameraConfiguration.createDefault();
    }

    public void setFocusPoint(int x, int y) {
        if(mState != State.PREVIEW || mCameraDevice == null) {
            return;
        }
        if (x < -1000 || x > 1000 || y < -1000 || y > 1000) {
            SopCastLog.w(TAG, "setFocusPoint: values are not ideal " + "x= " + x + " y= " + y);
            return;
        }
        Camera.Parameters params = mCameraDevice.getParameters();

        if (params != null && params.getMaxNumFocusAreas() > 0) {
            List<Camera.Area> focusArea = new ArrayList<Camera.Area>();
            focusArea.add(new Camera.Area(new Rect(x, y, x + FOCUS_WIDTH, y + FOCUS_HEIGHT), 1000));

            params.setFocusAreas(focusArea);

            try {
                mCameraDevice.setParameters(params);
            } catch (Exception e) {
                // Ignore, we might be setting it too
                // fast since previous attempt
            }
        } else {
            SopCastLog.w(TAG, "Not support Touch focus mode");
        }
    }

    public boolean doAutofocus(Camera.AutoFocusCallback focusCallback) {
        if(mState != State.PREVIEW || mCameraDevice == null) {
            return false;
        }
        // Make sure our auto settings aren't locked
        Camera.Parameters params = mCameraDevice.getParameters();
        if (params.isAutoExposureLockSupported()) {
            params.setAutoExposureLock(false);
        }

        if (params.isAutoWhiteBalanceLockSupported()) {
            params.setAutoWhiteBalanceLock(false);
        }

        mCameraDevice.setParameters(params);
        mCameraDevice.cancelAutoFocus();
        mCameraDevice.autoFocus(focusCallback);
        return true;
    }

    public void changeFocusMode(boolean touchMode) {
        if(mState != State.PREVIEW || mCameraDevice == null || mCameraData == null) {
            return;
        }
        isTouchMode = touchMode;
        mCameraData.touchFocusMode = touchMode;
        if(touchMode) {
            CameraUtils.setTouchFocusMode(mCameraDevice);
        } else {
            CameraUtils.setAutoFocusMode(mCameraDevice);
        }
    }

    public void switchFocusMode() {
        changeFocusMode(!isTouchMode);
    }

    public float cameraZoom(boolean isBig) {
        if(mState != State.PREVIEW || mCameraDevice == null || mCameraData == null) {
            return -1;
        }
        Camera.Parameters params = mCameraDevice.getParameters();
        if(isBig) {
            params.setZoom(Math.min(params.getZoom() + 1, params.getMaxZoom()));
        } else {
            params.setZoom(Math.max(params.getZoom() - 1, 0));
        }
        mCameraDevice.setParameters(params);
        return (float) params.getZoom()/params.getMaxZoom();
    }

    public boolean switchCamera() {
        if(mState != State.PREVIEW) {
            return false;
        }
        try {
            CameraData camera = mCameraDatas.remove(1);
            mCameraDatas.add(0, camera);
            openCamera();
            startPreview();
            return true;
        } catch (Exception e) {
            CameraData camera = mCameraDatas.remove(1);
            mCameraDatas.add(0, camera);
            try {
                openCamera();
                startPreview();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            return false;
        }
    }

    public boolean switchLight() {
        if(mState != State.PREVIEW || mCameraDevice == null || mCameraData == null) {
            return false;
        }
        if(!mCameraData.hasLight) {
            return false;
        }
        Camera.Parameters cameraParameters = mCameraDevice.getParameters();
        if (cameraParameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF)) {
            cameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        } else {
            cameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        }
        try {
            mCameraDevice.setParameters(cameraParameters);
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}


text:
require 'fog/core/model'

module Fog
  module Compute
    class SakuraCloud
      class Server < Fog::Model
        identity :id, :aliases => 'ID'
        attribute :name, :aliases => 'Name'
        attribute :server_plan, :aliases => 'ServerPlan'
        attribute :instance, :aliases => 'Instance'
        attribute :disks, :aliases => 'Disks'
        attribute :interfaces, :aliases => 'Interfaces'

        def save
          requires :name, :server_plan
          data = service.create_server(@attributes[:name], @attributes[:server_plan]).body["Server"]
          merge_attributes(data)
          true
        end

        def boot
          requires :id
          service.boot_server(@attributes[:id])
        end

        def stop(force = false)
          requires :id
          service.stop_server(@attributes[:id], force)
        end

        def delete(disks = [])
          requires :id
          service.delete_server(@attributes[:id], disks)
          true
        end
        alias_method :destroy, :delete
      end
    end
  end
end


text:
setup_environment() {
    rm -r .home/
    mkdir .home/

    # clear journal entries
    curl -X "DELETE" http://localhost:8888/api/v2/journal
}


text:
<?php

declare(strict_types=1);

namespace Gedmo\Tests\Blameable\Fixture\Entity;

use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity
 */
#[ORM\Entity]
class WithoutInterface
{
    /**
     * @var int|null
     *
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: Types::INTEGER)]
    private $id;

    /**
     * @var string|null
     *
     * @ORM\Column(type="string", length=128)
     */
    #[ORM\Column(type: Types::STRING, length: 128)]
    private $title;

    /**
     * @var string|null
     *
     * @Gedmo\Blameable(on="create")
     * @ORM\Column(type="string")
     */
    #[ORM\Column(type: Types::STRING)]
    #[Gedmo\Blameable(on: 'create')]
    private $created;

    /**
     * @var string|null
     *
     * @ORM\Column(type="string")
     * @Gedmo\Blameable(on="update")
     */
    #[ORM\Column(type: Types::STRING)]
    #[Gedmo\Blameable(on: 'update')]
    private $updated;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function setTitle(?string $title): void
    {
        $this->title = $title;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function getCreated(): ?string
    {
        return $this->created;
    }

    public function getUpdated(): ?string
    {
        return $this->updated;
    }
}


text:
package model;

import java.awt.Point;

public class CellWrapper {
	private Cell cell;
	private int xOffset;
	private int yOffset;

	public CellWrapper(Cell cell, int xOffset, int yOffset) {
		this.cell = cell;
		this.xOffset = xOffset;
		this.yOffset = yOffset;
	}

	public Cell getCell() {
		return cell;
	}

	public int getxOffset() {
		return xOffset;
	}

	public int getyOffset() {
		return yOffset;
	}
}


text:
//
//  GeneratePreviewForURL.m
//  qlplayground
//
//  Created by 野村 憲男 on 9/19/15.
//
//  Copyright (c) 2015 Norio Nomura
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//
@import CoreFoundation;
@import CoreServices;
@import QuickLook;
@import Foundation;
#include "qlplayground-Swift.h"

OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options);
void CancelPreviewGeneration(void *thisInterface, QLPreviewRequestRef preview);

/* -----------------------------------------------------------------------------
   Generate a preview for file

   This function's job is to create preview for designated file
   ----------------------------------------------------------------------------- */

OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options)
{
    // To complete your generator please implement the function GeneratePreviewForURL in GeneratePreviewForURL.c
    CFDataRef data = (__bridge CFDataRef)[Highlight dataWithURL:(__bridge NSURL * _Nonnull)(url)];
    if (data) {
        QLPreviewRequestSetDataRepresentation(preview, data, kUTTypeHTML, (__bridge CFDictionaryRef)(@{}));
    }
    return noErr;
}

void CancelPreviewGeneration(void *thisInterface, QLPreviewRequestRef preview)
{
    // Implement only if supported
}


text:
var handlebars = require('handlebars');
var fs = require('fs');
var path = require('path');
var notamLoader = require('./notamloader.js')

module.exports.formPage = function () {
	return new Promise(function (resolve, reject) {
		var data = fs.readFileSync("data.json");
		//console.log("fefwave");
		var source = fs.readFileSync(path.join(__dirname, '../views/index.hbs'), 'utf-8');
		var template = handlebars.compile(source);
		var html = template(JSON.parse(data));
		fs.writeFile(path.join(__dirname, '../views/index.html'), html, 'utf8', function (err) {
			if (err) {
				//console.log("failed to save");
				reject();
			} else {
				//console.log("succeeded in saving");
				resolve();
			}
		});

	})
}


text:
angular.module('umbraco.mocks').
    factory('variantContentMocks', ['$httpBackend', 'mocksUtils', function ($httpBackend, mocksUtils) {
    'use strict';

    function returnEmptyVariantNode(status, data, headers) {

        if (!mocksUtils.checkAuth()) {
            return [401, null, null];
        }

        var response = returnVariantNodebyId(200, "", null);
        var node = response[1];
        var parentId = mocksUtils.getParameterByName(data, "parentId") || 1234;

        node.name = "";
        node.id = 0;
        node.parentId = parentId;

        node.tabs.forEach(function(tab) {
            tab.properties.forEach(function(property) {
                property.value = "";
            });
        });

        return response;
    }

    function returnVariantNodebyId(status, data, headers) {

        if (!mocksUtils.checkAuth()) {
            return [401, null, null];
        }

        var id = mocksUtils.getParameterByName(data, "id") || "1234";
        id = parseInt(id, 10);

        var node = mocksUtils.getMockVariantContent(id);

        return [200, node, null];
    }

    return {
        register: function () {

            $httpBackend
                .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/Content/GetById?'))
                .respond(returnVariantNodebyId);

            $httpBackend
                .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/Content/GetEmpty'))
                .respond(returnEmptyVariantNode);

        }
    };
}]);


text:
package roulette.wheel;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.LinkedList;

import org.junit.Test;

import roulette.bin.Bin;
import roulette.bin.BinBuilder;
import roulette.outcome.Outcome;
import roulette.outcome.RouletteOutcome;

public class WheelTest {

	@Test
	public void binsMayBeSet() {
		Outcome outcomeA = new RouletteOutcome("outcome A", 1, 1);
		Outcome outcomeB = new RouletteOutcome("outcome B", 1, 1);

		Bin binA = new Bin();
		binA.add(outcomeA);
		Bin binB = new Bin();
		binB.add(outcomeA);
		binB.add(outcomeB);

		long seed = Integer.MAX_VALUE;
		Wheel wheel = new Wheel(new NonRandom(seed));
		wheel.addBin(binA);
		wheel.addBin(binB);

		assertEquals(binA,wheel.getBin(38));
		assertEquals(binB,wheel.getBin(39));
	}

	@Test
	public void outcomesMayBeRegistered() {
		long seed = Integer.MAX_VALUE;
		Wheel wheel = new Wheel(new NonRandom(seed));
		BinBuilder.buildBins(wheel);

		LinkedList<Outcome> outcomes = wheel.getBin(37).getOutcomes();
		assertEquals(2,outcomes.size());
		int[] fiveBins = {0,1,2,3,37};
		assertTrue(wheel.getBin(37).getOutcomes().contains(new RouletteOutcome("Five", 6, fiveBins)));
		assertTrue(wheel.getBin(37).getOutcomes().contains(new RouletteOutcome("Straight", 35, 37)));
	}

}