text:
<?xml version="1.0" encoding="latin1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

    <copyright>
      <year>1996</year><year>2010</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      The contents of this file are subject to the Erlang Public License,
      Version 1.1, (the "License"); you may not use this file except in
      compliance with the License. You should have received a copy of the
      Erlang Public License along with this software. If not, it can be
      retrieved online at http://www.erlang.org/.

      Software distributed under the License is distributed on an "AS IS"
      basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
      the License for the specific language governing rights and limitations
      under the License.

    </legalnotice>

    <title>application</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>

  <module>application</module>
  <modulesummary>Generic OTP application functions</modulesummary>
  <description>

In OTP, application denotes a component implementing
      some specific functionality, that can be started and stopped as a
      unit, and which can be re-used in other systems as well. This
      module interfaces the application controller, a process
      started at every Erlang runtime system, and contains functions
      for controlling applications (for example starting and stopping
      applications), and functions to access information about
      applications (for example configuration parameters).

An application is defined by an application specification. The specification is normally located in an
      application resource file called <c>Application.app</c>,
      where <c>Application</c> is the name of the application. Refer to
      <seealso marker="app">app(4)</seealso> for more information about
      the application specification.

This module can also be viewed as a behaviour for an application
      implemented according to the OTP design principles as a
      supervision tree. The definition of how to start and stop
      the tree should be located in an application callback module exporting a pre-defined set of functions.

Refer to <seealso marker="doc/design_principles:des_princ">OTP Design Principles</seealso> for more information about
      applications and behaviours.

  </description>
  <funcs>
    <func>
      <name>get_all_env() -> Env</name>
      <name>get_all_env(Application) -> Env</name>
      <fsummary>Get the configuration parameters for an application</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Env = [{Par,Val}]</v>
        <v> Par = atom()</v>
        <v> Val = term()</v>
      </type>
      <desc>

Returns the configuration parameters and their values for
          <c>Application</c>. If the argument is omitted, it defaults to
          the application of the calling process.

If the specified application is not loaded, or if the process
          executing the call does not belong to any application,
          the function returns <c>[]</c>.

      </desc>
    </func>
    <func>
      <name>get_all_key() -> {ok, Keys} | []</name>
      <name>get_all_key(Application) -> {ok, Keys} | undefined </name>
      <fsummary>Get the application specification keys</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Keys = [{Key,Val}]</v>
        <v> Key = atom()</v>
        <v> Val = term()</v>
      </type>
      <desc>

Returns the application specification keys and their values
          for <c>Application</c>. If the argument is omitted, it
          defaults to the application of the calling process.

If the specified application is not loaded, the function
          returns <c>undefined</c>. If the process executing the call
          does not belong to any application, the function returns
          <c>[]</c>.

      </desc>
    </func>
    <func>
      <name>get_application() -> {ok, Application} | undefined</name>
      <name>get_application(Pid | Module) -> {ok, Application} | undefined</name>
      <fsummary>Get the name of an application containing a certain process or module</fsummary>
      <type>
        <v>Pid = pid()</v>
        <v>Module = atom()</v>
        <v>Application = atom()</v>
      </type>
      <desc>

Returns the name of the application to which the process
          <c>Pid</c> or the module <c>Module</c> belongs. Providing no
          argument is the same as calling
          <c>get_application(self())</c>.

If the specified process does not belong to any application,
          or if the specified process or module does not exist,
          the function returns <c>undefined</c>.

      </desc>
    </func>
    <func>
      <name>get_env(Par) -> {ok, Val} | undefined</name>
      <name>get_env(Application, Par) -> {ok, Val} | undefined</name>
      <fsummary>Get the value of a configuration parameter</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Par = atom()</v>
        <v>Val = term()</v>
      </type>
      <desc>

Returns the value of the configuration parameter <c>Par</c>
          for <c>Application</c>. If the application argument is
          omitted, it defaults to the application of the calling
          process.

If the specified application is not loaded, or
          the configuration parameter does not exist, or if the process
          executing the call does not belong to any application,
          the function returns <c>undefined</c>.

      </desc>
    </func>
    <func>
      <name>get_key(Key) -> {ok, Val} | undefined</name>
      <name>get_key(Application, Key) -> {ok, Val} | undefined</name>
      <fsummary>Get the value of an application specification key</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Key = atom()</v>
        <v>Val = term()</v>
      </type>
      <desc>

Returns the value of the application specification key
          <c>Key</c> for <c>Application</c>. If the application
          argument is omitted, it defaults to the application of
          the calling process.

If the specified application is not loaded, or
          the specification key does not exist, or if the process
          executing the call does not belong to any application,
          the function returns <c>undefined</c>.

      </desc>
    </func>
    <func>
      <name>load(AppDescr) -> ok | {error, Reason}</name>
      <name>load(AppDescr, Distributed) -> ok | {error, Reason}</name>
      <fsummary>Load an application</fsummary>
      <type>
        <v>AppDescr = Application | AppSpec</v>
        <v> Application = atom()</v>
        <v> AppSpec = {application,Application,AppSpecKeys}</v>
        <v>  AppSpec = [{Key,Val}]</v>
        <v>   Key = atom()</v>
        <v>   Val = term()</v>
        <v>Distributed = {Application,Nodes} | {Application,Time,Nodes} | default</v>
        <v> Nodes = [node() | {node(),..,node()}]</v>
        <v> Time = integer() > 0</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Loads the application specification for an application into
          the application controller. It will also load the application
          specifications for any included applications. Note that
          the function does not load the actual Erlang object code.

The application can be given by its name <c>Application</c>.
          In this case the application controller will search the code
          path for the application resource file <c>Application.app</c>
          and load the specification it contains.

The application specification can also be given directly as a
          tuple <c>AppSpec</c>. This tuple should have the format and
          contents as described in <c>app(4)</c>.

If <c>Distributed == {Application,[Time,]Nodes}</c>,
          the application will be distributed. The argument overrides
          the value for the application in the Kernel configuration
          parameter <c>distributed</c>. <c>Application</c> must be
          the name of the application (same as in the first argument).
          If a node crashes and <c>Time</c> has been specified, then
          the application controller will wait for <c>Time</c>
          milliseconds before attempting to restart the application on
          another node. If <c>Time</c> is not specified, it will
          default to 0 and the application will be restarted
          immediately.

<c>Nodes</c> is a list of node names where the application
          may run, in priority from left to right. Node names can be
          grouped using tuples to indicate that they have the same
          priority. Example:

Nodes = [cp1@cave, {cp2@cave, cp3@cave}]

This means that the application should preferably be started
          at <c>cp1@cave</c>. If <c>cp1@cave</c> is down,
          the application should be started at either <c>cp2@cave</c>
          or <c>cp3@cave</c>.

If <c>Distributed == default</c>, the value for
          the application in the Kernel configuration parameter
          <c>distributed</c> will be used.

      </desc>
    </func>
    <func>
      <name>loaded_applications() -> [{Application, Description, Vsn}]</name>
      <fsummary>Get the currently loaded applications</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Description = string()</v>
        <v>Vsn = string()</v>
      </type>
      <desc>

Returns a list with information about the applications which
          have been loaded using <c>load/1,2</c>, also included
          applications. <c>Application</c> is the application name.
          <c>Description</c> and <c>Vsn</c> are the values of its
          <c>description</c> and <c>vsn</c> application specification
          keys, respectively.

      </desc>
    </func>
    <func>
      <name>permit(Application, Bool) -> ok | {error, Reason}</name>
      <fsummary>Change an application's permission to run on a node.</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Bool = bool()</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Changes the permission for <c>Application</c> to run at
          the current node. The application must have been loaded using
          <c>load/1,2</c> for the function to have effect.

If the permission of a loaded, but not started, application
          is set to <c>false</c>, <c>start</c> will return <c>ok</c> but
          the application will not be started until the permission is
          set to <c>true</c>.

If the permission of a running application is set to
          <c>false</c>, the application will be stopped. If
          the permission later is set to <c>true</c>, it will be
          restarted.

If the application is distributed, setting the permission to
          <c>false</c> means that the application will be started at, or
          moved to, another node according to how its distribution is
          configured (see <c>load/2</c> above).

The function does not return until the application is
          started, stopped or successfully moved to another node.
          However, in some cases where permission is set to <c>true</c>
          the function may return <c>ok</c> even though the application
          itself has not started. This is true when an application
          cannot start because it has dependencies to other
          applications which have not yet been started. When they have
          been started, <c>Application</c> will be started as well.

By default, all applications are loaded with permission
          <c>true</c> on all nodes. The permission is configurable by
          using the Kernel configuration parameter <c>permissions</c>.

      </desc>
    </func>
    <func>
      <name>set_env(Application, Par, Val) -> ok</name>
      <name>set_env(Application, Par, Val, Timeout) -> ok</name>
      <fsummary>Set the value of a configuration parameter</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Par = atom()</v>
        <v>Val = term()</v>
        <v>Timeout = int() | infinity</v>
      </type>
      <desc>

Sets the value of the configuration parameter <c>Par</c> for
          <c>Application</c>.

<c>set_env/3</c> uses the standard <c>gen_server</c> timeout
          value (5000 ms). A <c>Timeout</c> argument can be provided
          if another timeout value is useful, for example, in situations
          where the application controller is heavily loaded.

        <warning>

Use this function only if you know what you are doing,
            that is, on your own applications. It is very application
            and configuration parameter dependent when and how often
            the value is read by the application, and careless use
            of this function may put the application in a
            weird, inconsistent, and malfunctioning state.

        </warning>
      </desc>
    </func>
    <func>
      <name>start(Application) -> ok | {error, Reason}</name>
      <name>start(Application, Type) -> ok | {error, Reason}</name>
      <fsummary>Load and start an application</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Type = permanent | transient | temporary</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Starts <c>Application</c>. If it is not loaded,
          the application controller will first load it using
          <c>load/1</c>. It will make sure any included applications
          are loaded, but will not start them. That is assumed to be
          taken care of in the code for <c>Application</c>.

The application controller checks the value of
          the application specification key <c>applications</c>, to
          ensure that all applications that should be started before
          this application are running. If not,
          <c>{error,{not_started,App}}</c> is returned, where <c>App</c>
          is the name of the missing application.

The application controller then creates an application master for the application. The application master is
          the group leader of all the processes in the application.
          The application master starts the application by calling
          the application callback function <c>Module:start/2</c> as
          defined by the application specification key <c>mod</c>.

The <c>Type</c> argument specifies the type of
          the application. If omitted, it defaults to <c>temporary</c>.

        <list type="bulleted">
          <item>If a permanent application terminates, all other
           applications and the entire Erlang node are also terminated.</item>
          <item>If a transient application terminates with <c>Reason == normal</c>, this is reported but no other applications are
           terminated. If a transient application terminates
           abnormally, all other applications and the entire Erlang
           node are also terminated.</item>
          <item>If a temporary application terminates, this is reported
           but no other applications are terminated.</item>
        </list>

Note that it is always possible to stop an application
          explicitly by calling <c>stop/1</c>. Regardless of the type of
          the application, no other applications will be affected.

Note also that the transient type is of little practical use,
          since when a supervision tree terminates, the reason is set to
          <c>shutdown</c>, not <c>normal</c>.

      </desc>
    </func>
    <func>
      <name>start_type() -> StartType | local | undefined</name>
      <fsummary>Get the start type of an ongoing application startup.</fsummary>
      <type>
        <v>StartType = normal | {takeover,Node} | {failover,Node}</v>
        <v> Node = node()</v>
      </type>
      <desc>

This function is intended to be called by a process belonging
          to an application, when the application is being started, to
          determine the start type which is either <c>StartType</c> or
          <c>local</c>.

See <c>Module:start/2</c> for a description of
          <c>StartType</c>.

<c>local</c> is returned if only parts of the application is
          being restarted (by a supervisor), or if the function is
          called outside a startup.

If the process executing the call does not belong to any
          application, the function returns <c>undefined</c>.

      </desc>
    </func>
    <func>
      <name>stop(Application) -> ok | {error, Reason}</name>
      <fsummary>Stop an application</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Stops <c>Application</c>. The application master calls
          <c>Module:prep_stop/1</c>, if such a function is defined, and
          then tells the top supervisor of the application to shutdown
          (see <c>supervisor(3)</c>). This means that the entire
          supervision tree, including included applications, is
          terminated in reversed start order. After the shutdown,
          the application master calls <c>Module:stop/1</c>.
          <c>Module</c> is the callback module as defined by
          the application specification key <c>mod</c>.

Last, the application master itself terminates. Note that all
          processes with the application master as group leader, i.e.
          processes spawned from a process belonging to the application,
          thus are terminated as well.

When stopped, the application is still loaded.

In order to stop a distributed application, <c>stop/1</c>
          has to be called on all nodes where it can execute (that is,
          on all nodes where it has been started). The call to
          <c>stop/1</c> on the node where the application currently
          executes will stop its execution. The application will not be
          moved between nodes due to <c>stop/1</c> being called on
          the node where the application currently executes before
          <c>stop/1</c> is called on the other nodes.

      </desc>
    </func>
    <func>
      <name>takeover(Application, Type) -> ok | {error, Reason}</name>
      <fsummary>Take over a distributed application</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Type = permanent | transient | temporary</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Performs a takeover of the distributed application
          <c>Application</c>, which executes at another node
          <c>Node</c>. At the current node, the application is
          restarted by calling
          <c>Module:start({takeover,Node},StartArgs)</c>. <c>Module</c>
          and <c>StartArgs</c> are retrieved from the loaded application
          specification. The application at the other node is not
          stopped until the startup is completed, i.e. when
          <c>Module:start/2</c> and any calls to
          <c>Module:start_phase/3</c> have returned.

Thus two instances of the application will run simultaneously
          during the takeover, which makes it possible to transfer data
          from the old to the new instance. If this is not acceptable
          behavior, parts of the old instance may be shut down when
          the new instance is started. Note that the application may
          not be stopped entirely however, at least the top supervisor
          must remain alive.

See <c>start/1,2</c> for a description of <c>Type</c>.

      </desc>
    </func>
    <func>
      <name>unload(Application) -> ok | {error, Reason}</name>
      <fsummary>Unload an application</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Unloads the application specification for <c>Application</c>
          from the application controller. It will also unload
          the application specifications for any included applications.
          Note that the function does not purge the actual Erlang
          object code.

      </desc>
    </func>
    <func>
      <name>unset_env(Application, Par) -> ok</name>
      <name>unset_env(Application, Par, Timeout) -> ok</name>
      <fsummary>Unset the value of a configuration parameter</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Par = atom()</v>
        <v>Timeout = int() | infinity</v>
      </type>
      <desc>

Removes the configuration parameter <c>Par</c> and its value
          for <c>Application</c>.

<c>unset_env/2</c> uses the standard <c>gen_server</c>
          timeout value (5000 ms). A <c>Timeout</c> argument can be
          provided if another timeout value is useful, for example, in
          situations where the application controller is heavily loaded.

        <warning>

Use this function only if you know what you are doing,
            that is, on your own applications. It is very application
            and configuration parameter dependent when and how often
            the value is read by the application, and careless use
            of this function may put the application in a
            weird, inconsistent, and malfunctioning state.

        </warning>
      </desc>
    </func>
    <func>
      <name>which_applications() -> [{Application, Description, Vsn}]</name>
      <name>which_applications(Timeout) -> [{Application, Description, Vsn}]</name>
      <fsummary>Get the currently running applications</fsummary>
      <type>
        <v>Application = atom()</v>
        <v>Description = string()</v>
        <v>Vsn = string()</v>
        <v>Timeout = int() | infinity</v>
      </type>
      <desc>

Returns a list with information about the applications which
          are currently running. <c>Application</c> is the application
          name. <c>Description</c> and <c>Vsn</c> are the values of its
          <c>description</c> and <c>vsn</c> application specification
          keys, respectively.

<c>which_applications/0</c> uses the standard
          <c>gen_server</c> timeout value (5000 ms). A <c>Timeout</c>
          argument can be provided if another timeout value is useful,
          for example, in situations where the application controller
          is heavily loaded.

      </desc>
    </func>
  </funcs>

    <title>CALLBACK MODULE</title>

The following functions should be exported from an
      <c>application</c> callback module.

  <funcs>
    <func>
      <name>Module:start(StartType, StartArgs) -> {ok, Pid} | {ok, Pid, State} | {error, Reason}</name>
      <fsummary>Start an application</fsummary>
      <type>
        <v>StartType = normal | {takeover,Node} | {failover,Node}</v>
        <v> Node = node()</v>
        <v>StartArgs = term()</v>
        <v>Pid = pid()</v>
        <v>State = term()</v>
      </type>
      <desc>

This function is called whenever an application is started
          using <c>application:start/1,2</c>, and should start
          the processes of the application. If the application is
          structured according to the OTP design principles as a
          supervision tree, this means starting the top supervisor of
          the tree.

<c>StartType</c> defines the type of start:

        <list type="bulleted">
          <item><c>normal</c> if it's a normal startup.</item>
          <item><c>normal</c> also if the application is distributed and
           started at the current node due to a failover from another
           node, and the application specification key <c>start_phases == undefined</c>.</item>
          <item><c>{takeover,Node}</c> if the application is
           distributed and started at the current node due to a
           takeover from <c>Node</c>, either because
          <c>application:takeover/2</c> has been called or because
           the current node has higher priority than <c>Node</c>.</item>
          <item><c>{failover,Node}</c> if the application is
           distributed and started at the current node due to a
           failover from <c>Node</c>, and the application
           specification key <c>start_phases /= undefined</c>.</item>
        </list>

<c>StartArgs</c> is the <c>StartArgs</c> argument defined by
          the application specification key <c>mod</c>.

The function should return <c>{ok,Pid}</c> or
          <c>{ok,Pid,State}</c> where <c>Pid</c> is the pid of the top
          supervisor and <c>State</c> is any term. If omitted,
          <c>State</c> defaults to <c>[]</c>. If later the application
          is stopped, <c>State</c> is passed to
          <c>Module:prep_stop/1</c>.

      </desc>
    </func>
    <func>
      <name>Module:start_phase(Phase, StartType, PhaseArgs) -> ok | {error, Reason}</name>
      <fsummary>Extended start of an application</fsummary>
      <type>
        <v>Phase = atom()</v>
        <v>StartType = normal | {takeover,Node} | {failover,Node}</v>
        <v> Node = node()</v>
        <v>PhaseArgs = term()</v>
        <v>Pid = pid()</v>
        <v>State = state()</v>
      </type>
      <desc>

This function is used to start an application with included
          applications, when there is a need for synchronization between
          processes in the different applications during startup.

The start phases is defined by the application specification
          key <c>start_phases == [{Phase,PhaseArgs}]</c>. For included
          applications, the set of phases must be a subset of the set of
          phases defined for the including application.

The function is called for each start phase (as defined for
          the primary application) for the primary application and all
          included applications, for which the start phase is defined.

See <c>Module:start/2</c> for a description of
          <c>StartType</c>.

      </desc>
    </func>
    <func>
      <name>Module:prep_stop(State) -> NewState</name>
      <fsummary>Prepare an application for termination</fsummary>
      <type>
        <v>State = NewState = term()</v>
      </type>
      <desc>

This function is called when an application is about to be
          stopped, before shutting down the processes of
          the application.

<c>State</c> is the state returned from
          <c>Module:start/2</c>, or <c>[]</c> if no state was returned.
          <c>NewState</c> is any term and will be passed to
          <c>Module:stop/1</c>.

The function is optional. If it is not defined, the processes
          will be terminated and then <c>Module:stop(State)</c> is
          called.

      </desc>
    </func>
    <func>
      <name>Module:stop(State)</name>
      <fsummary>Clean up after termination of an application</fsummary>
      <type>
        <v>State = term()</v>
      </type>
      <desc>

This function is called whenever an application has stopped.
          It is intended to be the opposite of <c>Module:start/2</c>
          and should do any necessary cleaning up. The return value is
          ignored.

<c>State</c> is the return value of
          <c>Module:prep_stop/1</c>, if such a function exists.
          Otherwise <c>State</c> is taken from the return value of
          <c>Module:start/2</c>.

      </desc>
    </func>
    <func>
      <name>Module:config_change(Changed, New, Removed) -> ok</name>
      <fsummary>Update the configuration parameters for an application.</fsummary>
      <type>
        <v>Changed = [{Par,Val}]</v>
        <v>New = [{Par,Val}]</v>
        <v>Removed = [Par]</v>
        <v> Par = atom()</v>
        <v> Val = term()</v>
      </type>
      <desc>

This function is called by an application after a code
          replacement, if there are any changes to the configuration
          parameters.

<c>Changed</c> is a list of parameter-value tuples with all
          configuration parameters with changed values, <c>New</c> is
          a list of parameter-value tuples with all configuration
          parameters that have been added, and <c>Removed</c> is a list
          of all parameters that have been removed.

      </desc>
    </func>
  </funcs>

    <title>SEE ALSO</title>

<seealso marker="doc/design_principles:des_princ">OTP Design Principles</seealso>,
      <seealso marker="kernel_app">kernel(6)</seealso>,
      <seealso marker="app">app(4)</seealso>

</erlref>


text:
void BKP_DeInit(void)
{
    RCC_BackupResetCmd(ENABLE);
    RCC_BackupResetCmd(DISABLE);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Configures the Tamper Pin active level.
/// @param  tamper_pin_level: specifies the Tamper Pin active level.
///         This parameter can be one of the following values:
/// @arg    BKP_TamperPinLevel_High: Tamper pin active on high level
/// @arg    BKP_TamperPinLevel_Low: Tamper pin active on low level
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void BKP_TamperPinLevelConfig(BKPTPAL_Typedef tamper_pin_level)
{
    BKP->CR = tamper_pin_level;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Enables or disables the Tamper Pin activation.
/// @param  state: new state of the Tamper Pin activation.
///         This parameter can be: ENABLE or DISABLE.
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void BKP_TamperPinCmd(FunctionalState state)
{
    (state) ? SET_BIT(BKP->CR, BKP_CR_TPE) : CLEAR_BIT(BKP->CR, BKP_CR_TPE);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Enables or disables the Tamper Pin Interrupt.
/// @param  state: new state of the Tamper Pin Interrupt.
///         This parameter can be: ENABLE or DISABLE.
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void BKP_ITConfig(FunctionalState state)
{
    (state) ? SET_BIT(BKP->CSR, BKP_CSR_TPIE) : CLEAR_BIT(BKP->CSR, BKP_CSR_TPIE);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Select the RTC output source to output on the Tamper pin.
/// @param  rtc_output_source: specifies the RTC output source.
///         This parameter can be one of the following values:
/// @arg    BKP_RTCOutputSource_None: no RTC output on the Tamper pin.
/// @arg    BKP_RTCOutputSource_CalibClock: output the RTC clock with frequency
///                                          divided by 64 on the Tamper pin.
/// @arg    BKP_RTCOutputSource_Alarm: output the RTC Alarm pulse signal on
///                                     the Tamper pin.
/// @arg    BKP_RTCOutputSource_Second: output the RTC Second pulse signal on
///                                      the Tamper pin.
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void BKP_RTCOutputConfig(BKPRTCOUTPUTSRC_Typedef rtc_output_source)
{
    MODIFY_REG(BKP->RTCCR, BKP_RTCCR_CCO | BKP_RTCCR_ASOE | BKP_RTCCR_ASOS, rtc_output_source);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Sets RTC Clock Calibration value.
/// @param  calibration_value: specifies the RTC Clock Calibration value.
///         This parameter must be a number between 0 and 0x7F.
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void BKP_SetRTCCalibrationValue(u8 calibration_value)
{
    MODIFY_REG(BKP->RTCCR, BKP_RTCCR_CAL, calibration_value);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Checks whether the Tamper Pin Event flag is set or not.
/// @param  None.
/// @retval State: The new state of the Tamper Pin Event flag (SET or RESET).
////////////////////////////////////////////////////////////////////////////////
FlagStatus BKP_GetFlagStatus(void)
{
    return ((BKP->CSR & BKP_CSR_TEF) ? SET : RESET);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Clears Tamper Pin Event pending flag.
/// @param  None.
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void BKP_ClearFlag(void)
{
    SET_BIT(BKP->CSR, BKP_CSR_CTE);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Checks whether the Tamper Pin Interrupt has occurred or not.
/// @param  None.
/// @retval State: The new state of the Tamper Pin Interrupt (SET or RESET).
////////////////////////////////////////////////////////////////////////////////
ITStatus BKP_GetITStatus(void)
{
    return ((BKP->CSR & BKP_CSR_TIF) ? SET : RESET);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Clears Tamper Pin Interrupt pending bit.
/// @param  None.
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void BKP_ClearITPendingBit(void)
{
    SET_BIT(BKP->CSR, BKP_CSR_CTI);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Writes user data to the specified data Backup Register.
/// @param  bkp_dr: specifies the data Backup Register.
///         This parameter can be BKP_DRx where x:[1, 10]
/// @param  data: data to write
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void BKP_WriteBackupRegister(BKPDR_Typedef bkp_dr, u16 data)
{
    *(vu16*)(BKP_BASE + bkp_dr) = data;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Reads data from the specified data Backup Register.
/// @param  bkp_dr: specifies the data Backup Register.
///         This parameter can be BKP_DRx where x:[1, 10]
/// @retval data: The content of the specified data Backup Register
////////////////////////////////////////////////////////////////////////////////
u16 BKP_ReadBackupRegister(BKPDR_Typedef bkp_dr)
{
    return (*(vu16*)(BKP_BASE + bkp_dr));
}
////////////////////////////////////////////////////////////////////////////////
//          Extended function interface
////////////////////////////////////////////////////////////////////////////////
/// @brief  Initializes the BKP peripheral, enable access to the backup
///         registers.
/// @param  None.
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void exBKP_Init(void)
{
    RCC_APB1PeriphClockCmd(RCC_APB1ENR_PWR, ENABLE);
    //COMMON_EnableIpClock(emCLOCK_PWR);
    RCC_APB1PeriphClockCmd(RCC_APB1ENR_BKP, ENABLE);
    //COMMON_EnableIpClock(emCLOCK_BKP);

    RCC->BDCR |= RCC_BDCR_DBP;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Writes user data to the specified data Backup Register immediately.
/// @param  bkp_dr: specifies the data Backup Register.
///         This parameter can be BKP_DRx where x:[1, 10]
/// @param  data: data to write
/// @retval None.
////////////////////////////////////////////////////////////////////////////////
void exBKP_ImmWrite(BKPDR_Typedef bkp_dr, u16 dat)
{
    RCC->BDCR |= RCC_BDCR_DBP;
    *(vu16*)(BKP_BASE + bkp_dr) = dat;
    RCC->BDCR &= ~RCC_BDCR_DBP;

}

////////////////////////////////////////////////////////////////////////////////
/// @brief  Reads data from the specified data Backup Register immediately.
/// @param  bkp_dr: specifies the data Backup Register.
///         This parameter can be BKP_DRx where x:[1, 10]
/// @retval data: The content of the specified data Backup Register
////////////////////////////////////////////////////////////////////////////////
u16 exBKP_ImmRead(BKPDR_Typedef bkp_dr)
{
    u16 dat;
    RCC->BDCR |= RCC_BDCR_DBP;
    dat = (*(vu16*)(BKP_BASE + bkp_dr));
    RCC->BDCR &= ~RCC_BDCR_DBP;
    return dat;
}

/// @}

/// @}

/// @}

redpajama_set_name: RedPajamaGithub


text:
require 'active_support/concern'
require 'action_controller'
require 'pundit'
require 'ransack'
require 'will_paginate'

module NaturalResource
  module Controller
    extend ActiveSupport::Concern
    include Pundit

    class_methods do
      def resource(resource_name, display_notices: true)
        after_action :verify_authorized, except: :index
        after_action :verify_policy_scoped

        helper_method :current_context, :query, :resource_class, :resource, :resources

        rescue_from ActiveRecord::RecordInvalid, with: :handle_invalid_create_or_update

        # GET /:controller_name/new
        define_method :new do; end

        # GET /:controller_name/edit
        define_method :edit do; end

        # GET /:controller_name
        define_method :index do; end

        # POST /:controller_name
        define_method :create do
          resource.update! resource_params
          success_redirect(:created)
        end

        # PUT /:controller_name/:id
        define_method :update do
          resource.tap { |r| r.update! resource_params }.touch
          success_redirect(:updated)
        end

        # DELETE /:controller_name/:id
        define_method :destroy do
          resource.destroy
          success_redirect(:deleted)
        end

        private

        unless instance_methods.include?(:current_context)
          define_method :current_context do; end
        end

        # Resource allocation methods
        define_method :query do
          @query ||= policy_scope(resource_scope).ransack(params[:q])
        end

        define_method :resource_class do
          resource_name.to_s.singularize.camelcase.constantize
        end

        define_method :resource do
          @resource ||= if ['new', 'create'].include?(action_name)
                          policy_scope(resource_scope).new
                        else
                          policy_scope(resource_scope).find(params[:id])
                        end.tap(&method(:authorize))
        end

        define_method :resources do
          @resources ||= query.result.paginate(page: params[:page])
        end

        define_method :resource_scope do
          resource_class.all
        end

        define_method :success_path do
          url_for(action: :index)
        end

        define_method :success_redirect do |action|
          redirect_options = {}
          redirect_options.merge!({notice: "#{resource} was #{action}."}) if display_notices

          redirect_to success_path, redirect_options
        end
      end
    end

    def handle_invalid_create_or_update
      case action_name
      when 'create' then render :new
      when 'update' then render :edit
      else raise NotImplementedError
      end
    end
  end
end

ActionController::Base.send :include, NaturalResource::Controller


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Asynchronous on popc0rn</title>
    <link>http://popc0rn.me/tags/asynchronous/index.xml</link>
    <description>Recent content in Asynchronous on popc0rn</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-US</language>
    <atom:link href="http://popc0rn.me/tags/asynchronous/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Promise resolve everything</title>
      <link>http://popc0rn.me/blog/promise-resolve-everything/</link>
      <pubDate>Fri, 05 May 2017 17:33:16 +0200</pubDate>

      <guid>http://popc0rn.me/blog/promise-resolve-everything/</guid>
      <description>
Ever had a block of code that, based on a condition can fetch data asynchronosuly or synchronously?

In one case you'll need to wait for the results, and in the other the results will be available at the very next "line".

Simple trick that circles around the internet every once in a while, but I think many people oversee is this:

const data = 'test'

// synchronous
function getData() {
  return data;
}

// asynchronous
function getDataAsync() {
  return new Promise((resolve, reject) =&gt; {
    setTimeout(() =&gt; resolve(data))
  })
}

let response

// let's imagine we are fetching data based on environment variable
if (ENV_ASYNC) {
  response = getDataAsync()
} else {
  response = getData()
}

// you can see in one case response is a promise and in the other it's the data itself
// how to handle both in unified way? Use Promise.resolve

Promise.resolve(response)
  .then(responseData =&gt; {
    // collect money here! we get the extracted data!
  })

If you can't understand this completely look up on how Promises work with returns and especially cases when nothing is returned(undefined), data reference, or another promise.

Cheers!

</description>
    </item>

  </channel>
</rss>


text:
package io.katharsis.legacy.registry;

import io.katharsis.resource.information.ResourceInformationBuilder;
import io.katharsis.resource.information.ResourceInformationBuilderContext;

public class DefaultResourceInformationBuilderContext implements ResourceInformationBuilderContext {

	private ResourceInformationBuilder builder;

	public DefaultResourceInformationBuilderContext(ResourceInformationBuilder builder) {
		this.builder = builder;
	}

	@Override
	public String getResourceType(Class<?> clazz) {
		return builder.getResourceType(clazz);
	}

	@Override
	public boolean accept(Class<?> type) {
		return builder.accept(type);
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.plugin.jdbc;

import com.google.common.base.VerifyException;
import io.airlift.log.Logger;
import io.airlift.slice.Slice;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.connector.ConnectorSession;
import io.prestosql.spi.connector.RecordCursor;
import io.prestosql.spi.type.Type;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.prestosql.plugin.jdbc.JdbcErrorCode.JDBC_ERROR;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

public class JdbcRecordCursor
        implements RecordCursor
{
    private static final Logger log = Logger.get(JdbcRecordCursor.class);

    private final JdbcColumnHandle[] columnHandles;
    private final BooleanReadFunction[] booleanReadFunctions;
    private final DoubleReadFunction[] doubleReadFunctions;
    private final LongReadFunction[] longReadFunctions;
    private final SliceReadFunction[] sliceReadFunctions;
    private final BlockReadFunction[] blockReadFunctions;

    private final JdbcClient jdbcClient;
    private final Connection connection;
    private final PreparedStatement statement;
    private final ResultSet resultSet;
    private boolean closed;

    public JdbcRecordCursor(JdbcClient jdbcClient, ConnectorSession session, JdbcSplit split, JdbcTableHandle table, List<JdbcColumnHandle> columnHandles)
    {
        this.jdbcClient = requireNonNull(jdbcClient, "jdbcClient is null");

        this.columnHandles = columnHandles.toArray(new JdbcColumnHandle[0]);

        booleanReadFunctions = new BooleanReadFunction[columnHandles.size()];
        doubleReadFunctions = new DoubleReadFunction[columnHandles.size()];
        longReadFunctions = new LongReadFunction[columnHandles.size()];
        sliceReadFunctions = new SliceReadFunction[columnHandles.size()];
        blockReadFunctions = new BlockReadFunction[columnHandles.size()];

        try {
            connection = jdbcClient.getConnection(JdbcIdentity.from(session), split);

            for (int i = 0; i < this.columnHandles.length; i++) {
                ColumnMapping columnMapping = jdbcClient.toPrestoType(session, connection, columnHandles.get(i).getJdbcTypeHandle())
                        .orElseThrow(() -> new VerifyException("Unsupported column type"));
                Class<?> javaType = columnMapping.getType().getJavaType();
                ReadFunction readFunction = columnMapping.getReadFunction();

                if (javaType == boolean.class) {
                    booleanReadFunctions[i] = (BooleanReadFunction) readFunction;
                }
                else if (javaType == double.class) {
                    doubleReadFunctions[i] = (DoubleReadFunction) readFunction;
                }
                else if (javaType == long.class) {
                    longReadFunctions[i] = (LongReadFunction) readFunction;
                }
                else if (javaType == Slice.class) {
                    sliceReadFunctions[i] = (SliceReadFunction) readFunction;
                }
                else if (javaType == Block.class) {
                    blockReadFunctions[i] = (BlockReadFunction) readFunction;
                }
                else {
                    throw new IllegalStateException(format("Unsupported java type %s", javaType));
                }
            }

            statement = jdbcClient.buildSql(session, connection, split, table, columnHandles);
            log.debug("Executing: %s", statement.toString());
            resultSet = statement.executeQuery();
        }
        catch (SQLException | RuntimeException e) {
            throw handleSqlException(e);
        }
    }

    @Override
    public long getReadTimeNanos()
    {
        return 0;
    }

    @Override
    public long getCompletedBytes()
    {
        return 0;
    }

    @Override
    public Type getType(int field)
    {
        return columnHandles[field].getColumnType();
    }

    @Override
    public boolean advanceNextPosition()
    {
        if (closed) {
            return false;
        }

        try {
            return resultSet.next();
        }
        catch (SQLException | RuntimeException e) {
            throw handleSqlException(e);
        }
    }

    @Override
    public boolean getBoolean(int field)
    {
        checkState(!closed, "cursor is closed");
        try {
            return booleanReadFunctions[field].readBoolean(resultSet, field + 1);
        }
        catch (SQLException | RuntimeException e) {
            throw handleSqlException(e);
        }
    }

    @Override
    public long getLong(int field)
    {
        checkState(!closed, "cursor is closed");
        try {
            return longReadFunctions[field].readLong(resultSet, field + 1);
        }
        catch (SQLException | RuntimeException e) {
            throw handleSqlException(e);
        }
    }

    @Override
    public double getDouble(int field)
    {
        checkState(!closed, "cursor is closed");
        try {
            return doubleReadFunctions[field].readDouble(resultSet, field + 1);
        }
        catch (SQLException | RuntimeException e) {
            throw handleSqlException(e);
        }
    }

    @Override
    public Slice getSlice(int field)
    {
        checkState(!closed, "cursor is closed");
        try {
            return sliceReadFunctions[field].readSlice(resultSet, field + 1);
        }
        catch (SQLException | RuntimeException e) {
            throw handleSqlException(e);
        }
    }

    @Override
    public Object getObject(int field)
    {
        checkState(!closed, "cursor is closed");
        try {
            return blockReadFunctions[field].readBlock(resultSet, field + 1);
        }
        catch (SQLException | RuntimeException e) {
            throw handleSqlException(e);
        }
    }

    @Override
    public boolean isNull(int field)
    {
        checkState(!closed, "cursor is closed");
        checkArgument(field < columnHandles.length, "Invalid field index");

        try {
            // JDBC is kind of dumb: we need to read the field and then ask
            // if it was null, which means we are wasting effort here.
            // We could save the result of the field access if it matters.
            resultSet.getObject(field + 1);

            return resultSet.wasNull();
        }
        catch (SQLException | RuntimeException e) {
            throw handleSqlException(e);
        }
    }

    @SuppressWarnings("UnusedDeclaration")
    @Override
    public void close()
    {
        if (closed) {
            return;
        }
        closed = true;

        // use try with resources to close everything properly
        try (Connection connection = this.connection;
                Statement statement = this.statement;
                ResultSet resultSet = this.resultSet) {
            if (connection != null) {
                jdbcClient.abortReadConnection(connection);
            }
        }
        catch (SQLException e) {
            // ignore exception from close
        }
    }

    private RuntimeException handleSqlException(Exception e)
    {
        try {
            close();
        }
        catch (Exception closeException) {
            // Self-suppression not permitted
            if (e != closeException) {
                e.addSuppressed(closeException);
            }
        }
        return new PrestoException(JDBC_ERROR, e);
    }
}


text:
'use strict';

const express = require('express');
let router = express.Router();
let controller = require('../controllers/movie');

router.get('/', controller.index);

router.get('/search', controller.search);

router.get('/:page', controller.index);

module.exports = router;


text:
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define(["jquery", "underscore", "backbone", "collections/UnitList", "models/Property", "models/Unit", "models/Lease", "views/lease/New"], function($, _, Parse, UnitList, Property, Unit, Lease, NewLeaseView, i18nCommon, i18nLease) {
    var AddLeaseToPropertyView, _ref;

    return AddLeaseToPropertyView = (function(_super) {
      __extends(AddLeaseToPropertyView, _super);

      function AddLeaseToPropertyView() {
        _ref = AddLeaseToPropertyView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      AddLeaseToPropertyView.prototype.el = ".content";

      AddLeaseToPropertyView.prototype.initialize = function(attrs) {
        var vars;

        this.on("view:change", this.clear);
        this.baseUrl = attrs.baseUrl;
        this.forNetwork = attrs.forNetwork;
        this.params = attrs.params;
        vars = {
          property: this.model,
          profile: this.model.get("profile"),
          network: this.model.get("network")
        };
        if (attrs.params && attrs.params.unit) {
          vars.unit = {
            __type: "Pointer",
            className: "Unit",
            objectId: attrs.params.unit.id
          };
        }
        return this.lease = new Lease(vars);
      };

      AddLeaseToPropertyView.prototype.render = function() {
        var vars;

        vars = {
          model: this.lease,
          property: this.model,
          baseUrl: this.baseUrl,
          forNetwork: this.forNetwork
        };
        if (this.params) {
          vars.unitId = this.params.unitId;
        }
        this.form = new NewLeaseView(vars).render();
        return this;
      };

      AddLeaseToPropertyView.prototype.clear = function() {
        this.form.stopListening();
        this.form.undelegateEvents();
        delete this.form;
        this.stopListening();
        this.undelegateEvents();
        return delete this;
      };

      return AddLeaseToPropertyView;

    })(Parse.View);
  });

}).call(this);


text:
package io.netty.channel;

import org.junit.Test;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

public class SucceededChannelFutureTest {
    @Test
    public void testConstantProperties() {
        Channel channel = createMock(Channel.class);
        SucceededChannelFuture future = new SucceededChannelFuture(channel, null);

        assertTrue(future.isSuccess());
        assertNull(future.cause());
    }
}


text:
#define SUSBCRequest_SetBaudRateParityAndStopBits       1
#define SUSBCR_SBR_MASK				0xFF00
#define SUSBCR_SBR_1200				0x0100
#define SUSBCR_SBR_9600				0x0200
#define SUSBCR_SBR_19200			0x0400
#define SUSBCR_SBR_28800			0x0800
#define SUSBCR_SBR_38400			0x1000
#define SUSBCR_SBR_57600			0x2000
#define SUSBCR_SBR_115200			0x4000

#define SUSBCR_SPASB_MASK			0x0070
#define SUSBCR_SPASB_NoParity			0x0010
#define SUSBCR_SPASB_OddParity			0x0020
#define SUSBCR_SPASB_EvenParity			0x0040

#define SUSBCR_SPASB_STPMASK			0x0003
#define SUSBCR_SPASB_1StopBit			0x0001
#define SUSBCR_SPASB_2StopBits			0x0002

#define SUSBCRequest_SetStatusLinesOrQueues	2
#define SUSBCR_SSL_SETRTS			0x0001
#define SUSBCR_SSL_CLRRTS			0x0002
#define SUSBCR_SSL_SETDTR			0x0004
#define SUSBCR_SSL_CLRDTR			0x0010

/* Kill the pending/current writes to the comm port. */
#define SUSBCR_SSL_PURGE_TXABORT		0x0100
/* Kill the pending/current reads to the comm port. */
#define SUSBCR_SSL_PURGE_RXABORT		0x0200
/* Kill the transmit queue if there. */
#define SUSBCR_SSL_PURGE_TXCLEAR		0x0400
/* Kill the typeahead buffer if there. */
#define SUSBCR_SSL_PURGE_RXCLEAR		0x0800

#define SUSBCRequest_GetStatusLineState		4
/* Any Character received */
#define SUSBCR_GSL_RXCHAR			0x0001
/* Transmitt Queue Empty */
#define SUSBCR_GSL_TXEMPTY			0x0004
/* CTS changed state */
#define SUSBCR_GSL_CTS				0x0008
/* DSR changed state */
#define SUSBCR_GSL_DSR				0x0010
/* RLSD changed state */
#define SUSBCR_GSL_RLSD				0x0020
/* BREAK received */
#define SUSBCR_GSL_BREAK			0x0040
/* Line status error occurred */
#define SUSBCR_GSL_ERR				0x0080
/* Ring signal detected */
#define SUSBCR_GSL_RING				0x0100

#define SUSBCRequest_Misc			8
/* use a predefined reset sequence */
#define SUSBCR_MSC_ResetReader			0x0001
/* use a predefined sequence to reset the internal queues */
#define SUSBCR_MSC_ResetAllQueues		0x0002

#define SUSBCRequest_GetMisc			0x10

/*
 * get the firmware version from device, coded like this 0xHHLLBBPP with
 * HH = Firmware Version High Byte
 * LL = Firmware Version Low Byte
 * BB = Build Number
 * PP = Further Attributes
 */
#define SUSBCR_MSC_GetFWVersion			0x0001

/*
 * get the hardware version from device coded like this 0xHHLLPPRR with
 * HH = Software Version High Byte
 * LL = Software Version Low Byte
 * PP = Further Attributes
 * RR = Reserved for the hardware ID
 */
#define SUSBCR_MSC_GetHWVersion			0x0002


text:
function varargout = respcolor(varargin);
%RESPCOLOR creates a color/linestyle/marker string for Response Object menus
%    LEGENDSTR = RESPCOLOR(RespObj,PlotStr) returns a suitable legend string
%    for the color, linestyle, and marker contained in the string PlotStr.
%    If PlotStr is empty, RESPCOLOR uses a default plot string.

%    LEGENDSTR = RESPCOLOR(RespObj,PlotStr,NumSys,FRDflag) is useful when PlotStr
%    is empty, to override the default plot string.  NumSys indicates the Systems
%    index on the plot. RESPCOLOR chooses a color based on NumSys.
%    FRDflag indicates if the system is an FRD (1), or not (0).
%    If the system is an FRD, the plots do not use a linestyle and cycle through
%    the marker styles, as well as the colors. All other LTI Objects cycle through
%    only the color, using a solid line and no marker.
%
%    [LEGENDSTR,CC,LL,MM] = RESPCOLOR(RespObj,PlotStr,NumSys,FRDflag) also returns
%    a color, linestyle, and marker to use when plotting the response

%   Copyright (c) 1986-98 by The MathWorks, Inc.
% $Revision: 1.3 $
%   Karen Gondoly 4-13-98.

ni = nargin;
no = nargout;
%---At least a color has to be entered
error(nargchk(2,4,ni));

ScreenDepth = get(0,'ScreenDepth');

RespObj = varargin{1};
PlotStr = varargin{2};

Cvals = RespObj.ColorOrder;
numC=size(Cvals,1);
Lvals = RespObj.LinestyleOrder;
numL = size(Lvals,1);
Mvals = RespObj.MarkerOrder;

%---Prepare markers for FRDs
MMsys = Mvals{1};
%Mvals(find(strcmpi('none',Mvals)))=[];
numM = size(Mvals,1);

if ni>2,
   NumSys=varargin{3};
else
   NumSys=1;
end

if ni>3,
   FRDflag=varargin{4};
else
   FRDflag=0;
end

AllColors = {'blue';'green';'red';'cyan';'magenta';'yellow';'black';'white'};
AllLines = {'solid';'dashed';'dash-dot';'dotted'};
Lstr='';
Mstr='';

if ~isempty(PlotStr)
   [LL,CC,MM,msg]=colstyle(PlotStr);
   if isempty(CC),
      CC=Cvals(NumSys-(numC*floor((NumSys-1)/numC)),:);
   end
   if isempty(MM);
      MM='none';
   elseif isempty(LL),
      LL='none';
   end
   if isempty(LL);
      LL='-';
   end
else
   %---Do some optimizing based on LTI-type and ScreenDepth
   CC = Cvals(NumSys-(numC*floor((NumSys-1)/numC)),:);
   if FRDflag
      LL='-';
      MM = Mvals{NumSys-(numM*floor((NumSys-1)/numM))};
   else
      if isequal(ScreenDepth,1); % Monochrome screen
         LL=Lvals{NumSys-(numL*floor((NumSys-1)/numL))};
      else
         LL=Lvals{1};
      end
      MM = MMsys;
   end

end % if/else ~isempty(PlotStr)

if ischar(CC), % Working with a string
   NiceRGBs = {[0 0 1];[0 0.5 0];[1 0 0];[0 .75 .75];[.75 0 .75];[.75 .75 0];[.25 .25 .25];[1 1 1]};
   if iscell(CC) | ~isequal(length(CC),1),
      error('The color must be a single character.')
   end

   colorind = strmatch(CC,AllColors);
   if isempty(colorind) & strcmp(CC,'k'),
      Cstr = 'black';
      CC = [.25 .25 .25];
   elseif length(colorind)>1,
      Cstr = 'blue';
      CC=[0 0 1];
   elseif ~isempty(colorind),
      Cstr = AllColors{colorind};
      CC = NiceRGBs{colorind};
   else
      error('Invalid color specification')
   end % if/else isempty(colorind...
else
   %---Have to figure out the RGB combination
   %---As a first cut, round the triplet and look at which indices contain ones
   roundCC = round(CC);
   AllRGBs = {[0 0 1];[0 1 0];[1 0 0];[0 1 1];[1 0 1];[1 1 0];[0 0 0];[1 1 1]};
   for ct=1:length(AllRGBs),
      if isequal(roundCC,AllRGBs{ct}),
         colorind = ct;
      end
   end
   if ~isempty(colorind),
      Cstr = AllColors{colorind};
   else
      error('Invalid RGB triplet')
   end
end % if/else ischar
LegendStr = Cstr;

Lind = find(strcmpi(LL,{'-';'--';'-.';':'}));
if isempty(Lind) & strcmp(LL,'none'),
   Lstr='';
elseif isempty(Lind)
   error(sprintf('Invalid linestyle specification: %s',varargin{2}))
else
   Lstr = AllLines{Lind};
end

Mstr = MM;
if strcmp(Mstr,'none'), % Don't bother showing empty markerstyles
   Mstr='';
end

if ~isempty(Lstr)
   LegendStr = [LegendStr,',',Lstr];
end

if ~isempty(Mstr),
   LegendStr = [LegendStr,',',Mstr];
end

if no>=1,
   varargout{1}=LegendStr;
end
varargout{2}=CC;
varargout{3}=LL;
varargout{4}=MM;


text:
package org.apache.hadoop.hbase.io.hfile.bucket;

import org.apache.hadoop.hbase.testclassification.IOTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.io.hfile.BlockCacheKey;
import org.apache.hadoop.hbase.io.hfile.Cacheable;
import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache.BucketEntry;
import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache.RAMQueueEntry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@Category({IOTests.class, SmallTests.class})
public class TestBucketWriterThread {
  private BucketCache bc;
  private BucketCache.WriterThread wt;
  private BlockingQueue<RAMQueueEntry> q;
  private Cacheable plainCacheable;
  private BlockCacheKey plainKey;

  /** A BucketCache that does not start its writer threads. */
  private static class MockBucketCache extends BucketCache {

    public MockBucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
      int writerThreadNum, int writerQLen, String persistencePath, int ioErrorsTolerationDuration)
      throws FileNotFoundException, IOException {
      super(ioEngineName, capacity, blockSize, bucketSizes, writerThreadNum, writerQLen,
        persistencePath, ioErrorsTolerationDuration);
    }

    @Override
    protected void startWriterThreads() {
      // intentional noop
    }
  }

  /**
   * Set up variables and get BucketCache and WriterThread into state where tests can  manually
   * control the running of WriterThread and BucketCache is empty.
   * @throws Exception
   */
  @Before
  public void setUp() throws Exception {
    // Arbitrary capacity.
    final int capacity = 16;
    // Run with one writer thread only. Means there will be one writer queue only too.  We depend
    // on this in below.
    final int writerThreadsCount = 1;
    this.bc = new MockBucketCache("heap", capacity, 1, new int [] {1}, writerThreadsCount,
      capacity, null, 100/*Tolerate ioerrors for 100ms*/);
    assertEquals(writerThreadsCount, bc.writerThreads.length);
    assertEquals(writerThreadsCount, bc.writerQueues.size());
    // Get reference to our single WriterThread instance.
    this.wt = bc.writerThreads[0];
    this.q = bc.writerQueues.get(0);

    wt.disableWriter();
    this.plainKey = new BlockCacheKey("f", 0);
    this.plainCacheable = Mockito.mock(Cacheable.class);

    assertThat(bc.ramCache.isEmpty(), is(true));
    assertTrue(q.isEmpty());
  }

  @After
  public void tearDown() throws Exception {
    if (this.bc != null) this.bc.shutdown();
  }

  /**
   * Test non-error case just works.
   * @throws FileNotFoundException
   * @throws IOException
   * @throws InterruptedException
   */
  @Test (timeout=30000)
  public void testNonErrorCase() throws IOException, InterruptedException {
    bc.cacheBlock(this.plainKey, this.plainCacheable);
    doDrainOfOneEntry(this.bc, this.wt, this.q);
  }

  /**
   * Pass through a too big entry and ensure it is cleared from queues and ramCache.
   * Manually run the WriterThread.
   * @throws InterruptedException
   */
  @Test
  public void testTooBigEntry() throws InterruptedException {
    Cacheable tooBigCacheable = Mockito.mock(Cacheable.class);
    Mockito.when(tooBigCacheable.getSerializedLength()).thenReturn(Integer.MAX_VALUE);
    this.bc.cacheBlock(this.plainKey, tooBigCacheable);
    doDrainOfOneEntry(this.bc, this.wt, this.q);
  }

  /**
   * Do IOE. Take the RAMQueueEntry that was on the queue, doctor it to throw exception, then
   * put it back and process it.
   * @throws IOException
   * @throws InterruptedException
   */
  @SuppressWarnings("unchecked")
  @Test (timeout=30000)
  public void testIOE() throws IOException, InterruptedException {
    this.bc.cacheBlock(this.plainKey, plainCacheable);
    RAMQueueEntry rqe = q.remove();
    RAMQueueEntry spiedRqe = Mockito.spy(rqe);
    Mockito.doThrow(new IOException("Mocked!")).when(spiedRqe).
      writeToCache((IOEngine)Mockito.any(), (BucketAllocator)Mockito.any(),
        (UniqueIndexMap<Integer>)Mockito.any(), (AtomicLong)Mockito.any());
    this.q.add(spiedRqe);
    doDrainOfOneEntry(bc, wt, q);
    // Cache disabled when ioes w/o ever healing.
    assertTrue(!bc.isCacheEnabled());
  }

  /**
   * Do Cache full exception
   * @throws IOException
   * @throws InterruptedException
   */
  @Test (timeout=30000)
  public void testCacheFullException()
      throws IOException, InterruptedException {
    this.bc.cacheBlock(this.plainKey, plainCacheable);
    RAMQueueEntry rqe = q.remove();
    RAMQueueEntry spiedRqe = Mockito.spy(rqe);
    final CacheFullException cfe = new CacheFullException(0, 0);
    BucketEntry mockedBucketEntry = Mockito.mock(BucketEntry.class);
    Mockito.doThrow(cfe).
      doReturn(mockedBucketEntry).
      when(spiedRqe).writeToCache((IOEngine)Mockito.any(), (BucketAllocator)Mockito.any(),
        (UniqueIndexMap<Integer>)Mockito.any(), (AtomicLong)Mockito.any());
    this.q.add(spiedRqe);
    doDrainOfOneEntry(bc, wt, q);
  }

  private static void doDrainOfOneEntry(final BucketCache bc, final BucketCache.WriterThread wt,
      final BlockingQueue<RAMQueueEntry> q)
  throws InterruptedException {
    List<RAMQueueEntry> rqes = BucketCache.getRAMQueueEntries(q, new ArrayList<>(1));
    wt.doDrain(rqes);
    assertTrue(q.isEmpty());
    assertTrue(bc.ramCache.isEmpty());
    assertEquals(0, bc.heapSize());
  }
}


text:
#ifndef __INET_DEF_SERVICE_H__
#define __INET_DEF_SERVICE_H__

#ifdef __cplusplus
extern "C" {
#endif

struct os_eventq;

void inet_def_service_init(struct os_eventq *evq);

#ifdef __cplusplus
}
#endif

#endif /* __INET_DEF_SERVICE_H__ */


text:
#include "trigonometry-gen.h"

#include "sol-flow-internal.h"

#include <sol-util.h>
#include <math.h>
#include <float.h>
#include <errno.h>

struct trigonometry {
    double min;
    double max;
    uint16_t port;
    double (*func) (double value);
};

static int
_trigonometry_calculate(struct sol_flow_node *node, const struct sol_flow_packet *packet, const struct trigonometry *trig)
{
    struct sol_drange value;
    double angle;
    int r;

    r = sol_flow_packet_get_drange_value(packet, &angle);
    SOL_INT_CHECK(r, < 0, r);

    value.val = trig->func(angle);
    if (isnan(value.val)) {
        SOL_WRN("Angle out of domain");
        return -errno;
    }

    value.min = trig->min;
    value.max = trig->max;
    value.step = 0;

    return sol_flow_send_drange_packet(node, trig->port, &value);
}

static int
cosine_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    static const struct trigonometry trig = {
        .min = -1,
        .max = 1,
        .port = SOL_FLOW_NODE_TYPE_TRIGONOMETRY_COSINE__OUT__OUT,
        .func = cos,
    };

    return _trigonometry_calculate(node, packet, &trig);
}

static int
sine_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    static const struct trigonometry trig = {
        .min = -1,
        .max = 1,
        .port = SOL_FLOW_NODE_TYPE_TRIGONOMETRY_SINE__OUT__OUT,
        .func = sin,
    };

    return _trigonometry_calculate(node, packet, &trig);
}

static int
tangent_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    static const struct trigonometry trig = {
        .min = -DBL_MAX,
        .max = DBL_MAX,
        .port = SOL_FLOW_NODE_TYPE_TRIGONOMETRY_TANGENT__OUT__OUT,
        .func = tan,
    };

    return _trigonometry_calculate(node, packet, &trig);
}

static const double RAD_MAX = 2 * M_PI;
static const double DEGREES_MAX = 360;

static double
_radian_to_degrees(double radian)
{
    const double degrees_per_rad = DEGREES_MAX / RAD_MAX;

    return fmod(radian * degrees_per_rad, DEGREES_MAX);
}

static int
radian_to_degrees_convert(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    const struct trigonometry trig = {
        .min = 0,
        .max = RAD_MAX,
        .port = SOL_FLOW_NODE_TYPE_TRIGONOMETRY_RADIAN_TO_DEGREES__OUT__OUT,
        .func = _radian_to_degrees,
    };

    return _trigonometry_calculate(node, packet, &trig);
}

static double
_degrees_to_radian(double degrees)
{
    const double rad_per_degrees = RAD_MAX / DEGREES_MAX;

    return fmod(degrees * rad_per_degrees, RAD_MAX);
}

static int
degrees_to_radian_convert(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    const struct trigonometry trig = {
        .min = 0,
        .max = DEGREES_MAX,
        .port = SOL_FLOW_NODE_TYPE_TRIGONOMETRY_DEGREES_TO_RADIAN__OUT__OUT,
        .func = _degrees_to_radian,
    };

    return _trigonometry_calculate(node, packet, &trig);
}

#include "trigonometry-gen.c"


text:
source ./open-nti.params
echo "$(tput setaf 5)this script (docker.update.sh) is deprecated, it's been replaced with 'make update' $(tput sgr0)"

echo "OpenNTI - Update the files from Github"
git pull

echo "OpenNTI - Update the containers from Docker Hub"
docker pull $MAIN_IMAGE_NAME:latest
docker pull $INPUT_JTI_IMAGE_NAME:latest
docker pull $INPUT_SYSLOG_IMAGE_NAME:latest


text:
<?php
/*
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'coretech_coretech40';
$dbconfig = mysqli_connect($host,$username,$password,$database);
mysqli_set_charset($dbconfig, "utf8");
*/

$host = 'localhost';
$username = 'coretech';
$password = 'C123456c';
$database = 'coretech_coretech40';
$dbconfig = mysqli_connect($host,$username,$password,$database);
mysqli_set_charset($dbconfig, "utf8");

?>


text:
layout: default
title: Home
about: 'about.html'
---

            {% if page.logo %}

            {% endif %}
        Subscribe

{{ site.name }}

                {% if site.description %} {{ site.description }}. {% endif %}
                {% if page.about %}  About me  {% endif %}

    Scroll Down

        {% include pagination.html %}

    {% for post in paginator.posts %}

{{ post.title }}

            {{ post.excerpt }} »

            {% if post.author_name %}

        	{% if post.author_url %}
        	    {{ post.author_name }}
        	{% else %}
            	    {{ post.author_name }}
            	{% endif%}
            {% elsif site.author %}

                {{ site.author }}
            {% endif %}

            {% if post.categories.size > 0 %}
                {{ post.categories | array_to_sentence_string | prepend: 'on ' }}
            {% endif %}

            <time class="post-date" datetime="{{ post.date | date:"%Y-%m-%d" }}">
                {{ post.date | date_to_string }}
                {% if post.update %}
	            {% capture temp_day_created %}{{ post.date | date:"%Y-%m-%d" }}{% endcapture %}
	            {% capture temp_day_updated %}{{ post.update | date:"%Y-%m-%d" }}{% endcapture %}
            	    {% if temp_day_created != temp_day_updated %}
            		{{ post.update | date_to_string | prepend: ', updated ' }}
            	    {% endif %}
                {% endif %}
            </time>

    {% endfor %}

    {% include pagination.html %}


text:
/**
 * @fileoverview Rule to flag when IIFE is not wrapped in parens
 * @author Ilya Volodin
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("./utils/ast-utils");
const eslintUtils = require("eslint-utils");

//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------

/**
 * Check if the given node is callee of a `NewExpression` node
 * @param {ASTNode} node node to check
 * @returns {boolean} True if the node is callee of a `NewExpression` node
 * @private
 */
function isCalleeOfNewExpression(node) {
    const maybeCallee = node.parent.type === "ChainExpression"
        ? node.parent
        : node;

    return (
        maybeCallee.parent.type === "NewExpression" &&
        maybeCallee.parent.callee === maybeCallee
    );
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "layout",

        docs: {
            description: "Require parentheses around immediate `function` invocations",
            recommended: false,
            url: "https://eslint.org/docs/rules/wrap-iife"
        },

        schema: [
            {
                enum: ["outside", "inside", "any"]
            },
            {
                type: "object",
                properties: {
                    functionPrototypeMethods: {
                        type: "boolean",
                        default: false
                    }
                },
                additionalProperties: false
            }
        ],

        fixable: "code",
        messages: {
            wrapInvocation: "Wrap an immediate function invocation in parentheses.",
            wrapExpression: "Wrap only the function expression in parens.",
            moveInvocation: "Move the invocation into the parens that contain the function."
        }
    },

    create(context) {

        const style = context.options[0] || "outside";
        const includeFunctionPrototypeMethods = context.options[1] && context.options[1].functionPrototypeMethods;

        const sourceCode = context.getSourceCode();

        /**
         * Check if the node is wrapped in any (). All parens count: grouping parens and parens for constructs such as if()
         * @param {ASTNode} node node to evaluate
         * @returns {boolean} True if it is wrapped in any parens
         * @private
         */
        function isWrappedInAnyParens(node) {
            return astUtils.isParenthesised(sourceCode, node);
        }

        /**
         * Check if the node is wrapped in grouping (). Parens for constructs such as if() don't count
         * @param {ASTNode} node node to evaluate
         * @returns {boolean} True if it is wrapped in grouping parens
         * @private
         */
        function isWrappedInGroupingParens(node) {
            return eslintUtils.isParenthesized(1, node, sourceCode);
        }

        /**
         * Get the function node from an IIFE
         * @param {ASTNode} node node to evaluate
         * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist
         */
        function getFunctionNodeFromIIFE(node) {
            const callee = astUtils.skipChainExpression(node.callee);

            if (callee.type === "FunctionExpression") {
                return callee;
            }

            if (includeFunctionPrototypeMethods &&
                callee.type === "MemberExpression" &&
                callee.object.type === "FunctionExpression" &&
                (astUtils.getStaticPropertyName(callee) === "call" || astUtils.getStaticPropertyName(callee) === "apply")
            ) {
                return callee.object;
            }

            return null;
        }

        return {
            CallExpression(node) {
                const innerNode = getFunctionNodeFromIIFE(node);

                if (!innerNode) {
                    return;
                }

                const isCallExpressionWrapped = isWrappedInAnyParens(node),
                    isFunctionExpressionWrapped = isWrappedInAnyParens(innerNode);

                if (!isCallExpressionWrapped && !isFunctionExpressionWrapped) {
                    context.report({
                        node,
                        messageId: "wrapInvocation",
                        fix(fixer) {
                            const nodeToSurround = style === "inside" ? innerNode : node;

                            return fixer.replaceText(nodeToSurround, `(${sourceCode.getText(nodeToSurround)})`);
                        }
                    });
                } else if (style === "inside" && !isFunctionExpressionWrapped) {
                    context.report({
                        node,
                        messageId: "wrapExpression",
                        fix(fixer) {

                            // The outer call expression will always be wrapped at this point.

                            if (isWrappedInGroupingParens(node) && !isCalleeOfNewExpression(node)) {

                                /*
                                 * Parenthesize the function expression and remove unnecessary grouping parens around the call expression.
                                 * Replace the range between the end of the function expression and the end of the call expression.
                                 * for example, in `(function(foo) {}(bar))`, the range `(bar))` should get replaced with `)(bar)`.
                                 */

                                const parenAfter = sourceCode.getTokenAfter(node);

                                return fixer.replaceTextRange(
                                    [innerNode.range[1], parenAfter.range[1]],
                                    `)${sourceCode.getText().slice(innerNode.range[1], parenAfter.range[0])}`
                                );
                            }

                            /*
                             * Call expression is wrapped in mandatory parens such as if(), or in necessary grouping parens.
                             * These parens cannot be removed, so just parenthesize the function expression.
                             */

                            return fixer.replaceText(innerNode, `(${sourceCode.getText(innerNode)})`);
                        }
                    });
                } else if (style === "outside" && !isCallExpressionWrapped) {
                    context.report({
                        node,
                        messageId: "moveInvocation",
                        fix(fixer) {

                            /*
                             * The inner function expression will always be wrapped at this point.
                             * It's only necessary to replace the range between the end of the function expression
                             * and the call expression. For example, in `(function(foo) {})(bar)`, the range `)(bar)`
                             * should get replaced with `(bar))`.
                             */
                            const parenAfter = sourceCode.getTokenAfter(innerNode);

                            return fixer.replaceTextRange(
                                [parenAfter.range[0], node.range[1]],
                                `${sourceCode.getText().slice(parenAfter.range[1], node.range[1])})`
                            );
                        }
                    });
                }
            }
        };

    }
};


text:
<?php

namespace ZawidawieInfo\CoreBundle\Controller;

use JMS\SecurityExtraBundle\Annotation\Secure;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\DependencyInjection\ContainerAware;

use ZawidawieInfo\CoreBundle\Entity\Ad;
use ZawidawieInfo\CoreBundle\Form\AdType;

class AdController extends ContainerAware
{
    public function indexAction()
    {
        $page = $this->container->get('request')->query->get('page', 1);
        $ad = $this->container->get('doctrine')->getRepository('ZawidawieInfoCoreBundle:Ad')->findAll(true);
        $ad->setCurrentPage($page);
        $ad->setMaxPerPage(10);

        return $this->container->get('templating')->renderResponse('ZawidawieInfoCoreBundle:Ad:index.html.twig', array('ads' => $ad));
    }

    public function showAction($id)
    {
        $ad = $this->container->get('doctrine')
            ->getRepository('ZawidawieInfoCoreBundle:Ad')
            ->findPk($id);

        if (!$ad)
            throw new NotFoundHttpException('Ogłoszenie nie istnieje.');

        return $this->container->get('templating')->renderResponse('ZawidawieInfoCoreBundle:Ad:show.html.twig', array('ad' => $ad));
    }

    /**
     * @Secure(roles="ROLE_USER")
     */
    public function newAction()
    {
        $ad = new Ad();

        return $this->renderForm($ad, 'ads_new');
    }

    /**
     * @Secure(roles="ROLE_USER")
     */
    public function editAction($id)
    {
        $ad = $this->container->get('doctrine')->getRepository('ZawidawieInfoCoreBundle:Ad')->findPk($id);

        if (!$ad)
            throw new NotFoundHttpException('Ogłoszenie nie istnieje.');

        return $this->renderForm($ad, 'ads_edit');
    }

    protected function renderForm($ad, $action)
    {
        $form = $this->container->get('form.factory')->create(new AdType(), $ad);

        if ($this->container->get('request')->getMethod() === 'POST') {
            $form->bindRequest($this->container->get('request'));
            if ($form->isValid()) {
                $ad->setUser($this->container->get('security.context')->getToken()->getUser());
                $ad->setExpiresAt(new \DateTime('today +1 month'));
                $em = $this->container->get('doctrine')->getEntityManager();
                $em->persist($ad);
                $em->flush();

                $this->container->get('session')->setFlash('notice', 'Ogłoszenie zostało dodane.');
                return new RedirectResponse($this->container->get('router')->generate('ads_show', array('id' => $ad->getId())));
            }
        }

        return $this->container->get('templating')->renderResponse('ZawidawieInfoCoreBundle:Ad:new.html.twig', array(
            'form' => $form->createView(),
            'action' => $action,
            'ad' => $ad,
        ));
    }

    /**
     * @Secure(roles="ROLE_SUPER_ADMIN")
     */
    public function deleteAction($id)
    {
        $repo = $this->container->get('doctrine')->getRepository('ZawidawieInfoCoreBundle:Ad');
        $em = $this->container->get('doctrine')->getEntityManager();

        $ad = $repo->findPk($id);
        $em->remove($ad);
        $em->flush();

        $this->container->get('session')->setFlash('notice', 'Ogłoszenie zostało usunięte.');

        return new RedirectResponse($this->container->get('router')->generate('ad_index'));
    }
}


text:
JMOpenFilePanel::JMOpenFilePanel(BMessage* message = NULL, uint32 node_flavors = B_FILE_NODE)
	: BFilePanel(
		B_OPEN_PANEL,
		NULL,
		NULL,             // No specific wishes for where the dialog starts
		node_flavors,
		false,            // No multiple selection
		message,
		NULL,			// We want all files
		true,			// Modal panel
		true)			// Hide when done
{
	//fWindow = Window(); //this panel's window
	Window()->Lock();
	BView* background = Window()->ChildAt(0);
	BRect r;
	r = background->Bounds();
	r.top = r.bottom - 30;
	r.right += 15;
	r.right = r.left + 130;
	fRelPathBox = new BCheckBox(r, "rel path checkbox", "Store absolute path",
		 new BMessage('1234'), B_FOLLOW_LEFT | B_FOLLOW_BOTTOM);
	background->AddChild(fRelPathBox);
	Window()->Unlock();
}

void
JMOpenFilePanel::SendMessage(const BMessenger *messenger, BMessage *message)
{
	DPRINT("JMOpenFilePanel::SendMessage: fRelPathBox->Value() == " << fRelPathBox->Value());
	//add checkbox value to the message being sent
	bool relpath;
	if (fRelPathBox->Value() == 0)
		relpath = true;
	else
		relpath = false;
	message->AddBool("relpath", relpath);
	BFilePanel::SendMessage(messenger, message);
}


text:
require 'spec_helper'

describe Vx::Builder::BuildConfiguration::Deploy do
  let(:params) { { "shell" => '/bin/true' } }
  let(:deploy) { described_class.new params }
  subject { deploy }

  context "attributes" do
    subject { deploy.attributes }

    context "when is hash" do
      let(:params) { { "shell" => '/bin/true' } }
      it { should eq [{"shell" => "/bin/true"}] }
    end

    context "when is array" do
      let(:params) { [{"shell" => '/bin/true'}] }
      it { should eq [{"shell" => "/bin/true"}] }
    end

    context "when is nil" do
      let(:params) { nil }
      it { should eq [] }
    end
  end

  context "find_modules" do
    let(:branch) { 'master' }
    subject { deploy.find_modules branch }

    context "when deploy branch is empty array" do
      let(:params) { {'shell' => 'true'} }
      it { should_not be_empty }
    end

    context "when deploy branch is array" do
      let(:params) { {'shell' => 'true', 'branch' => ['master', 'production']} }

      it "should be true if branch found" do
        expect(deploy.find_modules 'master').to_not be_empty
        expect(deploy.find_modules 'production').to_not be_empty
      end

      it "should be false if branch not found" do
        expect(deploy.find_modules 'staging').to eq []
      end
    end
  end

  context "restore_modules" do
    let(:attrs) { [
      { "shell" => "/bin/true" }
    ] }
    it "should build deploy module instances" do
      list = described_class.restore_modules(attrs)
      expect(list).to have(1).item
      expect(list.first).to be_an_instance_of(Vx::Builder::BuildConfiguration::Deploy::Shell)
    end
  end

end


text:
#include "EFpp/Port/Atmel/ASF_wrapper/CSpi.h"

#include "ASpiInterface.h"

using namespace Driver;

ASpiInterface::ASpiInterface(Peripherial::CSpi* spiInstance, ASerialInterface* serialIf) :
	serial(serialIf),
	spi(spiInstance) {

	uint i = 0;

	for(auto &device : dev) {
		device.id = i++;
	}
}

void ASpiInterface::addDevice(uint8_t ndev,
							  spi_flags_t flags,
							  uint32_t baudrate,
							  uint32_t chipSelectBehaviour /*= SPI_CS_KEEP_LOW*/) {

	spi_master_setup_device(spi->getPeripherialInstance(), &(dev[ndev]), flags, baudrate, static_cast<board_spi_select_id_t>(0));
	spi_configure_cs_behavior(spi->getPeripherialInstance(), ndev, chipSelectBehaviour);
}

void ASpiInterface::selectDevice(uint8_t ndev) {

	getAccess();
	spi_select_device(spi->getPeripherialInstance(), &(dev[ndev]));
}

void ASpiInterface::deselectDevice(uint8_t ndev) {

	spi_deselect_device(spi->getPeripherialInstance(), &(dev[ndev]));
	release();
}