text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="deburr">
        <note>
            Automatically created based on framefiles: eviscerate (10.8)
        </note>
        <roleset id="deburr.01" name="remove burrs" vncls="10.8">
            <roles>
                <role descr="remover" n="0">
                    <vnrole vncls="10.8" vntheta="Agent"/>
                </role>
                <role descr="victim" n="1">
                    <vnrole vncls="10.8" vntheta="Source"/>
                </role>
                <role descr="burr, thing removed" n="2">
                    <vnrole vncls="10.8" vntheta="Theme"/>
                </role>
            </roles>
            <example name="Transitive" src="web usage" type="">
                <text>I deburred the edges of the left elevator understructure</text>
                <note/>
                <arg f="" n="0">I</arg>
                <rel f="">deburred</rel>
                <arg f="" n="1">the edges of the left elevator understructure</arg>
            </example>
            <note>Edited by hwangd</note>
        </roleset>
    </predicate>
</frameset>


text:
package executor

import (
	"strings"
)

// SetFromString constructs a slice of strings from a comma separated string.
// It is assumed that there is no duplicated entry. You could use addToSet to maintain this property.
// It is exported for tests. I HOPE YOU KNOW WHAT YOU ARE DOING.
func SetFromString(value string) []string {
	if len(value) == 0 {
		return nil
	}
	return strings.Split(value, ",")
}

func setToString(set []string) string {
	return strings.Join(set, ",")
}

// addToSet add a value to the set, e.g:
// addToSet("Select,Insert,Update", "Update") returns "Select,Insert,Update".
func addToSet(set []string, value string) []string {
	for _, v := range set {
		if v == value {
			return set
		}
	}
	return append(set, value)
}

// deleteFromSet delete the value from the set, e.g:
// deleteFromSet("Select,Insert,Update", "Update") returns "Select,Insert".
func deleteFromSet(set []string, value string) []string {
	for i, v := range set {
		if v == value {
			copy(set[i:], set[i+1:])
			return set[:len(set)-1]
		}
	}
	return set
}

// batchRetrieverHelper is a helper for batch returning data with known total rows. This helps implementing memtable
// retrievers of some information_schema tables. Initialize `batchSize` and `totalRows` fields to use it.
type batchRetrieverHelper struct {
	// When retrieved is true, it means retrieving is finished.
	retrieved bool
	// The index that the retrieving process has been done up to (exclusive).
	retrievedIdx int
	batchSize    int
	totalRows    int
}

// nextBatch calculates the index range of the next batch. If there is such a non-empty range, the `retrieveRange` func
// will be invoked and the range [start, end) is passed to it. Returns error if `retrieveRange` returns error.
func (b *batchRetrieverHelper) nextBatch(retrieveRange func(start, end int) error) error {
	if b.retrievedIdx >= b.totalRows {
		b.retrieved = true
	}
	if b.retrieved {
		return nil
	}
	start := b.retrievedIdx
	end := b.retrievedIdx + b.batchSize
	if end > b.totalRows {
		end = b.totalRows
	}

	err := retrieveRange(start, end)
	if err != nil {
		b.retrieved = true
		return err
	}
	b.retrievedIdx = end
	if b.retrievedIdx == b.totalRows {
		b.retrieved = true
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
namespace avalanche {

const char* AttackRecipe::s_Name = "recipe";
s32 AttackRecipe::s_BookPages = 3000;
s32 AttackRecipe::s_SendPerTick = 1;
s32 AttackRecipe::s_ReturnCount = 1;
s32 AttackRecipe::s_PrepareCount = 1;
mc::inventory::Slot AttackRecipe::s_AttackItem;

AttackRecipe::AttackRecipe(mc::core::Client* client, mc::protocol::Version version)
    : mc::protocol::packets::PacketHandler(client->GetDispatcher()),
      m_Client(client),
      m_Version(version),
      m_TransactionIndex(1),
      m_Finished(false),
      m_Transaction(false)
{

}

AttackRecipe::~AttackRecipe() {

}

void AttackRecipe::HandlePacket(mc::protocol::packets::in::ConfirmTransactionPacket* packet) {
    m_Transaction = false;
}

void AttackRecipe::OnCreate() {
    m_Client->RegisterListener(this);
    GetDispatcher()->RegisterHandler(mc::protocol::State::Play, mc::protocol::play::ConfirmTransaction, this);

    m_Finished = false;
    m_Transaction = false;
}

void AttackRecipe::OnDestroy() {
    m_Client->UnregisterListener(this);
    GetDispatcher()->UnregisterHandler(this);
}

void AttackRecipe::CreateAttack() {
    mc::nbt::NBT nbt;
    auto tag = &nbt.GetRoot();

    tag->SetName(L"tag");

    mc::nbt::TagPtr generation = std::make_shared<mc::nbt::TagInt>(L"generation", 0);
    mc::nbt::TagPtr author = std::make_shared<mc::nbt::TagString>(L"author", L"aaaaaa");
    mc::nbt::TagPtr title = std::make_shared<mc::nbt::TagString>(L"title", L"bbbbbb");

    auto pages = std::make_shared<mc::nbt::TagList>(L"pages", mc::nbt::TagType::String);

    for (s32 i = 0; i < s_BookPages; ++i) {
        std::wstring pageText = L"t";
        pages->AddItem(std::make_shared<mc::nbt::TagString>(L"", pageText));
    }

    tag->AddItem(mc::nbt::TagType::Int, generation);
    tag->AddItem(mc::nbt::TagType::String, author);
    tag->AddItem(mc::nbt::TagType::String, title);
    tag->AddItem(mc::nbt::TagType::List, pages);

    mc::DataBuffer buffer;
    mc::inventory::Slot book(387, 1, 0, nbt);
    buffer << book;

    s_AttackItem = mc::inventory::Slot(387, 1, 0, nbt);
}

void AttackRecipe::OnTick() {
    // Only start doing the attack once the world data is received.
    if (!m_Client->GetWorld()->GetChunk(mc::ToVector3i(m_Client->GetPlayerController()->GetPosition())))
        return;

    static std::vector<mc::protocol::packets::out::PrepareCraftingGridPacket::Entry> returnEntries;
    static std::vector<mc::protocol::packets::out::PrepareCraftingGridPacket::Entry> prepareEntries;

    if (s_AttackItem.GetItemId() == -1) {
        CreateAttack();

        mc::protocol::packets::out::PrepareCraftingGridPacket::Entry entry;
        entry.craftingSlot = 0;
        entry.playerSlot = 0;
        entry.item = s_AttackItem;

        for (s32 i = 0; i < s_ReturnCount; ++i) {
            returnEntries.push_back(entry);
        }

        for (s32 i = 0; i < s_PrepareCount; ++i) {
            prepareEntries.push_back(entry);
        }
    }

    if (m_Transaction) return;

    for (s32 i = 0; i < s_SendPerTick; ++i) {
        mc::protocol::packets::out::PrepareCraftingGridPacket packet(0, m_TransactionIndex++, returnEntries, prepareEntries);
        m_Client->GetConnection()->SendPacket(&packet);

        m_Transaction = true;
    }

    m_Finished = true;
}

bool AttackRecipe::ReadJSON(const Json::Value& attackNode) {
    if (m_Version != mc::protocol::Version::Minecraft_1_12_0) {
        throw std::runtime_error("AttackRecipe requires protocol 1.12.0.");
    }

    auto&& methodNode = attackNode["method"];
    if (!methodNode.isString() || methodNode.asString() != s_Name)
        return false;

    auto&& pagesNode = attackNode["pages"];
    if (!pagesNode.isNull()) {
        s_BookPages = pagesNode.asInt();
    }

    auto&& sendPerTickNode = attackNode["send-per-tick"];
    if (!sendPerTickNode.isNull()) {
        s_SendPerTick = sendPerTickNode.asInt();
    }

    auto&& returnCountNode = attackNode["return-count"];
    if (returnCountNode.isInt()) {
        s_ReturnCount = returnCountNode.asInt();
    }

    auto&& prepareCountNode = attackNode["prepare-count"];
    if (prepareCountNode.isInt()) {
        s_PrepareCount = prepareCountNode.asInt();
    }

    return true;
}

} // ns avalanche


text:
'''
Copyright (c) 2011-2017, Agora Games, LLC All rights reserved.

https://github.com/agoragames/haigha/blob/master/LICENSE.txt
'''

from haigha.writer import Writer
from haigha.frames.frame import Frame

class ContentFrame(Frame):

    '''
    Frame for reading in content.
    '''

    @classmethod
    def type(cls):
        return 3

    @property
    def payload(self):
        return self._payload

    @classmethod
    def parse(self, channel_id, payload):
        return ContentFrame(channel_id, payload)

    @classmethod
    def create_frames(self, channel_id, buf, frame_max):
        '''
        A generator which will create frames from a buffer given a max
        frame size.
        '''
        size = frame_max - 8   # 8 bytes overhead for frame header and footer
        offset = 0
        while True:
            payload = buf[offset:(offset + size)]
            if len(payload) == 0:
                break
            offset += size

            yield ContentFrame(channel_id, payload)
            if offset >= len(buf):
                break

    def __init__(self, channel_id, payload):
        Frame.__init__(self, channel_id)
        self._payload = payload

    def __str__(self):
        if isinstance(self._payload, str):
            payload = ''.join(['\\x%s' % (c.encode('hex'))
                               for c in self._payload])
        else:
            payload = str(self._payload)

        return "%s[channel: %d, payload: %s]" % (
            self.__class__.__name__, self.channel_id, payload)

    def write_frame(self, buf):
        '''
        Write the frame into an existing buffer.
        '''
        writer = Writer(buf)

        writer.write_octet(self.type()).\
            write_short(self.channel_id).\
            write_long(len(self._payload)).\
            write(self._payload).\
            write_octet(0xce)

ContentFrame.register()


text:
.block {
  height: 300px;
  text-align: center;
  border: 5%;
  margin: 20px;
  width: 100%;
}

.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */

  /* For visualization
  background: #808080; width: 5px;
  */
}

.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
  padding: 10px 15px;
  border: 5%;
}


text:
package gce

import (
	compute "google.golang.org/api/compute/v1"

	"k8s.io/kubernetes/pkg/cloudprovider/providers/gce/cloud"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/gce/cloud/meta"
)

func newTargetPoolMetricContext(request, region string) *metricContext {
	return newGenericMetricContext("targetpool", request, region, unusedMetricLabel, computeV1Version)
}

// GetTargetPool returns the TargetPool by name.
func (g *Cloud) GetTargetPool(name, region string) (*compute.TargetPool, error) {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newTargetPoolMetricContext("get", region)
	v, err := g.c.TargetPools().Get(ctx, meta.RegionalKey(name, region))
	return v, mc.Observe(err)
}

// CreateTargetPool creates the passed TargetPool
func (g *Cloud) CreateTargetPool(tp *compute.TargetPool, region string) error {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newTargetPoolMetricContext("create", region)
	return mc.Observe(g.c.TargetPools().Insert(ctx, meta.RegionalKey(tp.Name, region), tp))
}

// DeleteTargetPool deletes TargetPool by name.
func (g *Cloud) DeleteTargetPool(name, region string) error {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newTargetPoolMetricContext("delete", region)
	return mc.Observe(g.c.TargetPools().Delete(ctx, meta.RegionalKey(name, region)))
}

// AddInstancesToTargetPool adds instances by link to the TargetPool
func (g *Cloud) AddInstancesToTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	req := &compute.TargetPoolsAddInstanceRequest{
		Instances: instanceRefs,
	}
	mc := newTargetPoolMetricContext("add_instances", region)
	return mc.Observe(g.c.TargetPools().AddInstance(ctx, meta.RegionalKey(name, region), req))
}

// RemoveInstancesFromTargetPool removes instances by link to the TargetPool
func (g *Cloud) RemoveInstancesFromTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	req := &compute.TargetPoolsRemoveInstanceRequest{
		Instances: instanceRefs,
	}
	mc := newTargetPoolMetricContext("remove_instances", region)
	return mc.Observe(g.c.TargetPools().RemoveInstance(ctx, meta.RegionalKey(name, region), req))
}


text:
<?php

namespace ch\makae\makaegallery;

use ch\makae\makaegallery\security\Authentication;

abstract class Utils
{

  public static function mapImagesToArray(array $images)
  {
    return array_map(
      "\ch\makae\makaegallery\Utils::mapImageToArray",
      $images);
  }

  public static function mapImageToArray(Image $image)
  {
    return [
      'id' => $image->getIdentifier(),
      'thumbnail_url' => $image->getThumbnailUrl(),
      'optimized_url' => $image->getOptimizedUrl(),
      'original_url' => $image->getOriginalUrl(),
      'dimensions' => ['width' => $image->getWidth(), 'height' => $image->getHeight()]
    ];
  }

  public static function arraySearch(array $array, callable $comparitor)
  {
    return array_filter(
      $array,
      function ($element) use ($comparitor) {
        if ($comparitor($element)) {
          return $element;
        }
      }
    );
  }

  public static function rmDir($dir)
  {
    if (!file_exists($dir)) {
      return true;
    }

    if (!is_dir($dir)) {
      return Utils::rmFile($dir);
    }

    foreach (scandir($dir) as $item) {
      if ($item == '.' || $item == '..') {
        continue;
      }

      if (!Utils::rmDir($dir . DIRECTORY_SEPARATOR . $item)) {
        return false;
      }

    }

    return rmdir($dir);
  }

  public static function rmFile($file)
  {
    if (!file_exists($file)) {
      return true;
    }

    if (is_dir($file)) {
      throw new \InvalidArgumentException("Can not delete a directory via this method");
    }

    return unlink($file);
  }

  public static function getUriComponents($uri = null)
  {
    $uri = explode("/", $uri);
    foreach ($uri as $k => $v) {
      if ($v == '') {
        unset($uri[$k]);
      }
    }

    return array_values($uri);
  }

  public static function getRequestUri($url = null): string
  {
    $url = is_null($url) ? $_SERVER["REQUEST_URI"] : $url;
    $url = str_replace('/' . WWW_SUB_ROOT . '/', '', $url);
    $url = preg_replace('/([^?]+).*/', '$1', $url);
    $url = preg_replace('/(.*)\.php/', '$1', $url);
    preg_match_all("/(.*)(\?.+)?/", $url, $uri, PREG_PATTERN_ORDER);

    if (count($uri[0]) > 0) {
      $uri = $uri[1][0];
    } else {
      $uri = $_SERVER['REQUEST_URI'];
    }
    return $uri;
  }

  public static function getHomeUrl()
  {
    return self::getAbsoluteUrlRoot() . self::getServerRoot();
  }

  public static function getAbsoluteUrlRoot()
  {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'];
    return $protocol . $domainName;
  }

  public static function getServerRoot()
  {
    $root = str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT']);
    $dir = str_replace("\\", "/", dirname($_SERVER['SCRIPT_NAME']));
    $ext = str_replace($root, '', $dir);
    if (substr($ext, strlen($ext) - 1) != '/') {
      $ext .= "/";
    }
    return $ext;
  }

  public static function unTrailingSlashIt($url)
  {
    if (substr($url, 0, -1) == '/') {
      return substr($url, 0, -1);
    }
    return $url;
  }

  public static function getAllHeaders()
  {
    foreach ($_SERVER as $K => $V) {
      $a = explode('_', $K);
      if (array_shift($a) == 'HTTP') {
        array_walk($a, function (&$v) {
          $v = ucfirst(strtolower($v));
        });
        $retval[join('-', $a)] = $V;
      }
    }
    return $retval;
  }

  public static function getAccessLevelName(int $level): string
  {
    switch ($level) {
      case Authentication::ACCESS_LEVEL_ADMIN:
        return "ADMIN";
      case Authentication::ACCESS_LEVEL_TENANT_ADMIN:
        return "TENANT_ADMIN";
      case Authentication::ACCESS_LEVEL_USER:
        return "USER";
      case Authentication::ACCESS_LEVEL_GUEST:
        return "GUEST";
      case Authentication::ACCESS_LEVEL_PUBLIC:
      default:
        return "PUBLIC";
    }
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
This file is subject to the terms and conditions defined in the
files 'LICENSE' and 'NOTICE', which are part of this source
code package.
-->
<entity-engine-xml>
    <!-- assert data for service setRollbackOnly revert/reset test; exactly the same as in the original test data file -->
    <TestingType testingTypeId="SVC_SRBO" description="Original description for SVC_SRBO; this is how it should be because of the tx rollback"/>
</entity-engine-xml>


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Course;

/**
 * CourseSearch represents the model behind the search form about `common\models\Course`.
 */
class CourseSearch extends Course
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id',  'price', 'typecourse_id', 'teacher_id'], 'integer'],
            [['name','cod_id', 'detail', 'date_s', 'date_c', 'photos'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Course::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'cod_id'=>$this->cod_id,
            'price' => $this->price,
            'date_s' => $this->date_s,
            'date_c' => $this->date_c,
            'typecourse_id' => $this->typecourse_id,
            'teacher_id' => $this->teacher_id,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'detail', $this->detail])
            ->andFilterWhere(['like', 'cod_id', $this->cod_id])
        ->andFilterWhere(['like', 'photos', $this->photos]);

        return $dataProvider;
    }
}


text:
/* $Id: ClpEventHandler.hpp 1825 2011-11-20 16:02:57Z forrest $ */
// Copyright (C) 2004, International Business Machines
// Corporation and others.  All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).

#ifndef ClpEventHandler_H
#define ClpEventHandler_H

#include "ClpSimplex.hpp"
/** Base class for Clp event handling

This is just here to allow for event handling.  By event I mean a Clp event
e.g. end of values pass.

One use would be to let a user handle a system event e.g. Control-C.  This could be done
by deriving a class MyEventHandler which knows about such events.  If one occurs
MyEventHandler::event() could clear event status and return 3 (stopped).

Clp would then return to user code.

As it is called every iteration this should be fine grained enough.

User can derive and construct from CbcModel  - not pretty

*/

class ClpEventHandler  {

public:
     /** enums for what sort of event.

         These will also be returned in ClpModel::secondaryStatus() as int
     */
     enum Event {
          endOfIteration = 100, // used to set secondary status
          endOfFactorization, // after gutsOfSolution etc
          endOfValuesPass,
          node, // for Cbc
          treeStatus, // for Cbc
          solution, // for Cbc
          theta, // hit in parametrics
          pivotRow, // used to choose pivot row
	  presolveStart, // ClpSolve presolve start
	  presolveSize, // sees if ClpSolve presolve too big or too small
	  presolveInfeasible, // ClpSolve presolve infeasible
	  presolveBeforeSolve, // ClpSolve presolve before solve
	  presolveAfterFirstSolve, // ClpSolve presolve after solve
	  presolveAfterSolve, // ClpSolve presolve after solve
	  presolveEnd, // ClpSolve presolve end
	  goodFactorization, // before gutsOfSolution
	  complicatedPivotIn, // in modifyCoefficients
	  noCandidateInPrimal, // tentative end
	  looksEndInPrimal, // About to declare victory (or defeat)
	  endInPrimal, // Victory (or defeat)
	  beforeStatusOfProblemInPrimal,
	  startOfStatusOfProblemInPrimal,
	  complicatedPivotOut, // in modifyCoefficients
	  noCandidateInDual, // tentative end
	  looksEndInDual, // About to declare victory (or defeat)
	  endInDual, // Victory (or defeat)
	  beforeStatusOfProblemInDual,
	  startOfStatusOfProblemInDual,
	  startOfIterationInDual,
	  updateDualsInDual,
	  endOfCreateRim,
	  slightlyInfeasible,
	  modifyMatrixInMiniPresolve,
	  moreMiniPresolve,
	  modifyMatrixInMiniPostsolve,
	  noTheta // At end (because no pivot)
     };
     /**@name Virtual method that the derived classes should provide.
      The base class instance does nothing and as event() is only useful method
      it would not be very useful NOT providing one!
     */
     //@{
     /** This can do whatever it likes.  If return code -1 then carries on
         if 0 sets ClpModel::status() to 5 (stopped by event) and will return to user.
         At present if <-1 carries on and if >0 acts as if 0 - this may change.
	 For ClpSolve 2 -> too big return status of -2 and -> too small 3
     */
     virtual int event(Event whichEvent);
     /** This can do whatever it likes.  Return code -1 means no action.
	 This passes in something
     */
     virtual int eventWithInfo(Event whichEvent, void * info) ;
     //@}

     /**@name Constructors, destructor */

     //@{
     /** Default constructor. */
     ClpEventHandler(ClpSimplex * model = NULL);
     /** Destructor */
     virtual ~ClpEventHandler();
     // Copy
     ClpEventHandler(const ClpEventHandler&);
     // Assignment
     ClpEventHandler& operator=(const ClpEventHandler&);
     /// Clone
     virtual ClpEventHandler * clone() const;

     //@}

     /**@name Sets/gets */

     //@{
     /** set model. */
     void setSimplex(ClpSimplex * model);
     /// Get model
     inline ClpSimplex * simplex() const {
          return model_;
     }
     //@}

protected:
     /**@name Data members
        The data members are protected to allow access for derived classes. */
     //@{
     /// Pointer to simplex
     ClpSimplex * model_;
     //@}
};
/** Base class for Clp disaster handling

This is here to allow for disaster handling.  By disaster I mean that Clp
would otherwise give up

*/

class ClpDisasterHandler  {

public:
     /**@name Virtual methods that the derived classe should provide.
     */
     //@{
     /// Into simplex
     virtual void intoSimplex() = 0;
     /// Checks if disaster
     virtual bool check() const = 0;
     /// saves information for next attempt
     virtual void saveInfo() = 0;
     /// Type of disaster 0 can fix, 1 abort
     virtual int typeOfDisaster();
     //@}

     /**@name Constructors, destructor */

     //@{
     /** Default constructor. */
     ClpDisasterHandler(ClpSimplex * model = NULL);
     /** Destructor */
     virtual ~ClpDisasterHandler();
     // Copy
     ClpDisasterHandler(const ClpDisasterHandler&);
     // Assignment
     ClpDisasterHandler& operator=(const ClpDisasterHandler&);
     /// Clone
     virtual ClpDisasterHandler * clone() const = 0;

     //@}

     /**@name Sets/gets */

     //@{
     /** set model. */
     void setSimplex(ClpSimplex * model);
     /// Get model
     inline ClpSimplex * simplex() const {
          return model_;
     }
     //@}

protected:
     /**@name Data members
        The data members are protected to allow access for derived classes. */
     //@{
     /// Pointer to simplex
     ClpSimplex * model_;
     //@}
};
#endif


text:
dnscript is a Mac OS X user agent that allows for simple integration into Mac
OS X's [distributed notification system][dns] - for example, running shell scripts when
they are dispatched.

The specific use case this tool was developed for was
refreshing [GeekTool][gt] "geeklets"; I have a set of geeklets displaying the
currently playing artist/track/album in iTunes. As wonderful of a program as
GeekTool is, it only allows geeklets to be updated on a timer, which forces a
compromise between having song info update less immediately and having constant
small drain on the CPU. This program allows the distributed notifications sent
by iTunes (and other music players) to be set to run shell scripts that update
the geeklet display *immediately*.

## Configuration

dnscript reads its configuration from a `.dnscriptrc` file in the current user's
home directory. As an example, my `.dnscriptrc` file is as follows:

    # refresh geektool on music change
    ;com.apple.iTunes.playerInfo
    ;com.catpigstudios.Radium.stateChange
    ;VLCPlayerStateDidChange
    osascript ~/scripts/refreshall.scpt

Lines preceeded with `#`'s are, as you could've guessed, comments. Lines
beginning with `;` contain names of notifications to listen for; all other lines
are read as single-line shell commands. Notifications names are associated with
each other by alternating groups; so, ignoring comments and empty lines, a group
of consecutive notification names will be associated with the following
consecutive group of shell commands, and the next notification line found will
start a new group. To make this more concrete, if you wanted to rewrite my
`.dnscriptrc` to run a separate script for each of the music player notifications
instead of of one for all three, you could rewrite it as:

    ;com.apple.iTunes.playerInfo
    osascript ~/scripts/refreshitunes.scpt

    ;com.catpigstudios.Radium.stateChange
    osascript ~/scripts/refreshradium.scpt

    ;VLCPlayerStateDidChange
    osascript ~/scripts/refreshvlc.scpt

I'll be the first to admit that this format is somewhat bizaare - the semicolon
was chosen to denote notification names because I could see no reason for it
to need to be at the start of a shell command. The format is also inherently
broken, in that it eschews support for certain pathological examples of
notification names - for example, names containing newlines, though I have yet
to see anything of the sort.

As a bonus, because I was interested in how it would be implemented, dnscript
will listen for any changes to `.dnscriptrc` and process them automatically -
all configuration changes will be refelcted immediately.

## Installation

To install dnscript from the Xcode project, you need to run `xcodebuild install`
from the project directory, which will generate a `dnscript.pkg` installer that
you can run to install. Or, you can just download the installer from GitHub.
dnscript only needs two files: the `dnscript` binary itself, which is installed
to `/usr/local/bin`, and a configuration file `com.github.stephanwilliams.dnscript`,
installed to `/Library/LaunchAgents`, which will tell `launchd` how to manage
the `dnscript` process. After installation you should restart your computer.

## Other Files

Since the use case I've presented here for dnscript is using it in conjunction
with GeekTool, it seems appropriate to include the relevant GeekTool scripts -
these are located in the `scripts` directory. `refreshall.scpt` is a dead-simple
script that simply tells GeekTool to refresh all geeklets. `musicinfo.scpt` is
more complicated, being a one-stop-shop to get the name, artist, or album of the
currently playing song, from iTunes, Radium, or VLC (though, I couldn't figure
out how to get an album name from VLC). The latter script can be used in a shell
geeklet with the command `osascript path/to/musicinfo.scpt name`, for `name`,
`artist`, or `album`.

## Future Improvement

It's unlikely I'll ever get around to doing this, but dnscript would definitely
benefit from being able to pass the [`userInfo`][info] dictionary in the NSNotification
object to the scripts being executed. iTunes, for example, passes a large amount
track info as part of its notifications - if this could be passed in as some
sort of JSON or something, perhaps it could be parsed by some Perl/Python/Ruby/etc.
script to do some interesting stuff. Though, most of the same information should
also be obtainable through AppleScript, at least in iTunes' case. Also useful
would be a mode where dnscript would simply print out names of **all** distributed
notifications, which is about the only way to discover what notifications are
being dispatched by applications.

[dns]: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Notifications/Articles/NotificationCenters.html
[gt]: http://projects.tynsoe.org/en/geektool/
[info]: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNotification/userInfo


text:
"""SoX-based audio transform functions for the purpose of data augmentation."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import math
import random
import subprocess
import tempfile

from magenta.contrib import training as contrib_training
import sox
import tensorflow.compat.v1 as tf

# The base pipeline is a list of stages, each of which consists of a name
# (corresponding to a SoX function) and a dictionary of parameters with name
# (corresponding to an argument to the SoX function) and min and max values
# along with the scale (linear or log) used to sample values. The min and max
# values can be overridden with hparams.
AUDIO_TRANSFORM_PIPELINE = [
    # Pitch shift.
    ('pitch', {
        'n_semitones': (-0.1, 0.1, 'linear'),
    }),

    # Contrast (simple form of compression).
    ('contrast', {
        'amount': (0.0, 100.0, 'linear'),
    }),

    # Two independent EQ modifications.
    ('equalizer', {
        'frequency': (32.0, 4096.0, 'log'),
        'width_q': (2.0, 2.0, 'linear'),
        'gain_db': (-10.0, 5.0, 'linear'),
    }),
    ('equalizer', {
        'frequency': (32.0, 4096.0, 'log'),
        'width_q': (2.0, 2.0, 'linear'),
        'gain_db': (-10.0, 5.0, 'linear'),
    }),

    # Reverb (for now just single-parameter).
    ('reverb', {
        'reverberance': (0.0, 70.0, 'linear'),
    }),
]

# Default hyperparameter values from the above pipeline. Note the additional
# `transform_audio` hparam that defaults to False, i.e. by default no audio
# transformation will be performed.
DEFAULT_AUDIO_TRANSFORM_HPARAMS = contrib_training.HParams(
    transform_audio=False,
    audio_transform_noise_type='pinknoise',
    audio_transform_min_noise_vol=0.0,
    audio_transform_max_noise_vol=0.04,
    **dict(('audio_transform_%s_%s_%s' % (m, stage_name, param_name), value)
           for stage_name, params_dict in AUDIO_TRANSFORM_PIPELINE
           for param_name, (min_value, max_value, _) in params_dict.items()
           for m, value in [('min', min_value), ('max', max_value)]))

class AudioTransformParameter(object):
  """An audio transform parameter with min and max value."""

  def __init__(self, name, min_value, max_value, scale):
    """Initialize an AudioTransformParameter.

    Args:
      name: The name of the parameter. Should be the same as the name of the
          parameter passed to sox.
      min_value: The minimum value of the parameter, a float.
      max_value: The maximum value of the parameter, a float.
      scale: 'linear' or 'log', the scale with which to sample the parameter
          value.

    Raises:
      ValueError: If `scale` is not 'linear' or 'log'.
    """
    if scale not in ('linear', 'log'):
      raise ValueError('invalid parameter scale: %s' % scale)

    self.name = name
    self.min_value = min_value
    self.max_value = max_value
    self.scale = scale

  def sample(self):
    """Sample the parameter, returning a random value in its range.

    Returns:
      A value drawn uniformly at random between `min_value` and `max_value`.
    """
    if self.scale == 'linear':
      return random.uniform(self.min_value, self.max_value)
    else:
      log_min_value = math.log(self.min_value)
      log_max_value = math.log(self.max_value)
      return math.exp(random.uniform(log_min_value, log_max_value))

class AudioTransformStage(object):
  """A stage in an audio transform pipeline."""

  def __init__(self, name, params):
    """Initialize an AudioTransformStage.

    Args:
      name: The name of the stage. Should be the same as the name of the method
          called on a sox.Transformer object.
      params: A list of AudioTransformParameter objects.
    """
    self.name = name
    self.params = params

  def apply(self, transformer):
    """Apply this stage to a sox.Transformer object.

    Args:
      transformer: The sox.Transformer object to which this pipeline stage
          should be applied. No audio will actually be transformed until the
          `build` method is called on `transformer`.
    """
    args = dict((param.name, param.sample()) for param in self.params)
    getattr(transformer, self.name)(**args)

def construct_pipeline(hparams, pipeline):
  """Construct an audio transform pipeline from hyperparameters.

  Args:
    hparams: A tf.contrib.training.HParams object specifying hyperparameters to
        use for audio transformation. These hyperparameters affect the min and
        max values for audio transform parameters.
    pipeline: A list of pipeline stages, each specified as a tuple of stage
        name (SoX method) and a dictionary of parameters.

  Returns:
    The resulting pipeline, a list of AudioTransformStage objects.
  """
  return [
      AudioTransformStage(
          name=stage_name,
          params=[
              AudioTransformParameter(
                  param_name,
                  getattr(hparams, 'audio_transform_min_%s_%s' % (stage_name,
                                                                  param_name)),
                  getattr(hparams, 'audio_transform_max_%s_%s' % (stage_name,
                                                                  param_name)),
                  scale)
              for param_name, (_, _, scale) in params_dict.items()
          ]) for stage_name, params_dict in pipeline
  ]

def run_pipeline(pipeline, input_filename, output_filename):
  """Run an audio transform pipeline.

  This will run the pipeline on an input audio file, producing an output audio
  file. Transform parameters will be sampled at each stage.

  Args:
    pipeline: The pipeline to run, a list of AudioTransformStage objects.
    input_filename: Path to the audio file to be transformed.
    output_filename: Path to the resulting output audio file.
  """
  transformer = sox.Transformer()
  transformer.set_globals(guard=True)
  for stage in pipeline:
    stage.apply(transformer)
  transformer.build(input_filename, output_filename)

def add_noise(input_filename, output_filename, noise_vol, noise_type):
  """Add noise to a wav file using sox.

  Args:
    input_filename: Path to the original wav file.
    output_filename: Path to the output wav file that will consist of the input
        file plus noise.
    noise_vol: The volume of the noise to add.
    noise_type: One of "whitenoise", "pinknoise", "brownnoise".

  Raises:
    ValueError: If `noise_type` is not one of "whitenoise", "pinknoise", or
        "brownnoise".
  """
  if noise_type not in ('whitenoise', 'pinknoise', 'brownnoise'):
    raise ValueError('invalid noise type: %s' % noise_type)

  args = ['sox', input_filename, '-p', 'synth', noise_type, 'vol',
          str(noise_vol), '|', 'sox', '-m', input_filename, '-',
          output_filename]
  command = ' '.join(args)
  tf.logging.info('Executing: %s', command)

  process_handle = subprocess.Popen(
      command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  process_handle.communicate()

def transform_wav_audio(wav_audio, hparams, pipeline=None):
  """Transform the contents of a wav file based on hyperparameters.

  Args:
    wav_audio: The contents of a wav file; this will be written to a temporary
        file and transformed via SoX.
    hparams: The tf.contrib.training.HParams object to use to construct the
        audio transform pipeline.
    pipeline: A list of pipeline stages, each specified as a tuple of stage
        name (SoX method) and a dictionary of parameters. If None, uses
        `AUDIO_TRANSFORM_PIPELINE`.

  Returns:
    The contents of the wav file that results from applying the audio transform
    pipeline to the input audio.
  """
  if not hparams.transform_audio:
    return wav_audio

  pipeline = construct_pipeline(
      hparams, pipeline if pipeline is not None else AUDIO_TRANSFORM_PIPELINE)

  with tempfile.NamedTemporaryFile(suffix='.wav') as temp_input_with_noise:
    with tempfile.NamedTemporaryFile(suffix='.wav') as temp_input:
      temp_input.write(wav_audio)
      temp_input.flush()

      # Add noise before all other pipeline steps.
      noise_vol = random.uniform(hparams.audio_transform_min_noise_vol,
                                 hparams.audio_transform_max_noise_vol)
      add_noise(temp_input.name, temp_input_with_noise.name, noise_vol,
                hparams.audio_transform_noise_type)

    with tempfile.NamedTemporaryFile(suffix='.wav') as temp_output:
      run_pipeline(pipeline, temp_input_with_noise.name, temp_output.name)
      return temp_output.read()


text:
package com.nickelsoftware.bettercare4me.utils

/**
 * Root level exception of all application level exception
 */
case class NickelException(message: String) extends Exception(message)


text:
import Mongoose from 'mongoose';

let semesterSchema = new Mongoose.Schema({
  key: String,
  // defined in C1
  beginners: {male: Number, female: Number},
  beginners_first_semester_at_university: {male: Number, female: Number},
  students_higher_semester: {male: Number, female: Number},
  students_higher_semester_sabbatical: {male: Number, female: Number},
  guest_students: {male: Number, female: Number},
  // defined in C2
  capacity: Number,
  candidates_total: {male: Number, female: Number},
  candidates_admission_legitimated: {male: Number, female: Number},
  admissions: {male: Number, female: Number},
  admissions_in_first_semester_of_studying: {male: Number, female: Number},
  count_of_acceptance: {male: Number, female: Number},
  refusals: {male: Number, female: Number},
  // defined in P2
  semester_needed: Number,
  graduated_per_semester: [{male: Number, female: Number}], // idx+1 is the semester,
  graduated_total: {male: Number, female: Number},
  graduated_in_semesters_needed: {male: Number, female: Number},
  graduated_mean_value: {male: Number, female: Number}
});

/**
 * Merges two semesters
 *
 * @param {Semester} semester
 * @returns {Semester}
 */
semesterSchema.methods.merge = function(semester) {
  let paths = Object.keys(semester._doc);
  let values = paths.map((path) => [path, semester.get(path)]);
  values = values.filter((e) => {
    let isEmptyObject = Object.keys(e[1]).length === 0 && e[1].constructor === Object;
    let isIdField = e[0] === '_id';
    let isTruthy = !!e[1];
    let isEmptyArray = Array.isArray(e[1]) && e[1].length === 0;
    return !isEmptyObject && !isIdField && isTruthy && !isEmptyArray;
  });
  values.forEach((e) => this.set(e[0], e[1]));
  return this;
};

/**
 * @class Semester
 */
export default Mongoose.model('Semester', semesterSchema);


text:
package com.amazonaws.services.ecs.model;

import java.io.Serializable;

/**
 *
 */
public class DescribeTasksResult implements Serializable, Cloneable {

    /**
     *

     * The list of tasks.
     *

     */
    private com.amazonaws.internal.SdkInternalList<Task> tasks;
    /**
     *

     * Any failures associated with the call.
     *

     */
    private com.amazonaws.internal.SdkInternalList<Failure> failures;

    /**
     *

     * The list of tasks.
     *

     *
     * @return The list of tasks.
     */

    public java.util.List<Task> getTasks() {
        if (tasks == null) {
            tasks = new com.amazonaws.internal.SdkInternalList<Task>();
        }
        return tasks;
    }

    /**
     *

     * The list of tasks.
     *

     *
     * @param tasks
     *        The list of tasks.
     */

    public void setTasks(java.util.Collection<Task> tasks) {
        if (tasks == null) {
            this.tasks = null;
            return;
        }

        this.tasks = new com.amazonaws.internal.SdkInternalList<Task>(tasks);
    }

    /**
     *

     * The list of tasks.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setTasks(java.util.Collection)} or
     * {@link #withTasks(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param tasks
     *        The list of tasks.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeTasksResult withTasks(Task... tasks) {
        if (this.tasks == null) {
            setTasks(new com.amazonaws.internal.SdkInternalList<Task>(
                    tasks.length));
        }
        for (Task ele : tasks) {
            this.tasks.add(ele);
        }
        return this;
    }

    /**
     *

     * The list of tasks.
     *

     *
     * @param tasks
     *        The list of tasks.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeTasksResult withTasks(java.util.Collection<Task> tasks) {
        setTasks(tasks);
        return this;
    }

    /**
     *

     * Any failures associated with the call.
     *

     *
     * @return Any failures associated with the call.
     */

    public java.util.List<Failure> getFailures() {
        if (failures == null) {
            failures = new com.amazonaws.internal.SdkInternalList<Failure>();
        }
        return failures;
    }

    /**
     *

     * Any failures associated with the call.
     *

     *
     * @param failures
     *        Any failures associated with the call.
     */

    public void setFailures(java.util.Collection<Failure> failures) {
        if (failures == null) {
            this.failures = null;
            return;
        }

        this.failures = new com.amazonaws.internal.SdkInternalList<Failure>(
                failures);
    }

    /**
     *

     * Any failures associated with the call.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setFailures(java.util.Collection)} or
     * {@link #withFailures(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param failures
     *        Any failures associated with the call.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeTasksResult withFailures(Failure... failures) {
        if (this.failures == null) {
            setFailures(new com.amazonaws.internal.SdkInternalList<Failure>(
                    failures.length));
        }
        for (Failure ele : failures) {
            this.failures.add(ele);
        }
        return this;
    }

    /**
     *

     * Any failures associated with the call.
     *

     *
     * @param failures
     *        Any failures associated with the call.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeTasksResult withFailures(
            java.util.Collection<Failure> failures) {
        setFailures(failures);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getTasks() != null)
            sb.append("Tasks: " + getTasks() + ",");
        if (getFailures() != null)
            sb.append("Failures: " + getFailures());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeTasksResult == false)
            return false;
        DescribeTasksResult other = (DescribeTasksResult) obj;
        if (other.getTasks() == null ^ this.getTasks() == null)
            return false;
        if (other.getTasks() != null
                && other.getTasks().equals(this.getTasks()) == false)
            return false;
        if (other.getFailures() == null ^ this.getFailures() == null)
            return false;
        if (other.getFailures() != null
                && other.getFailures().equals(this.getFailures()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getTasks() == null) ? 0 : getTasks().hashCode());
        hashCode = prime * hashCode
                + ((getFailures() == null) ? 0 : getFailures().hashCode());
        return hashCode;
    }

    @Override
    public DescribeTasksResult clone() {
        try {
            return (DescribeTasksResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
	value: true
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _user = require('./user');

var _user2 = _interopRequireDefault(_user);

var _message = require('./message');

var _message2 = _interopRequireDefault(_message);

var _data = require('./data');

var _data2 = _interopRequireDefault(_data);

exports['default'] = function install(db) {
	var conf = arguments.length <= 1 || arguments[1] === undefined ? { clean: true, prod: false } : arguments[1];
	var userTable, messageTable, clean, prod;
	return regeneratorRuntime.async(function install$(context$1$0) {
		while (1) switch (context$1$0.prev = context$1$0.next) {
			case 0:
				userTable = new _user2['default'](db);
				messageTable = new _message2['default'](db);
				clean = conf.clean;
				prod = conf.prod;
				context$1$0.prev = 4;

				if (!clean) {
					context$1$0.next = 10;
					break;
				}

				context$1$0.next = 8;
				return regeneratorRuntime.awrap(messageTable.clean());

			case 8:
				context$1$0.next = 10;
				return regeneratorRuntime.awrap(userTable.clean());

			case 10:
				context$1$0.next = 12;
				return regeneratorRuntime.awrap(userTable.install());

			case 12:
				context$1$0.next = 14;
				return regeneratorRuntime.awrap(messageTable.install());

			case 14:
				context$1$0.next = 16;
				return regeneratorRuntime.awrap((0, _data2['default'])(prod));

			case 16:
				console.log('Database Setup completed.');
				context$1$0.next = 22;
				break;

			case 19:
				context$1$0.prev = 19;
				context$1$0.t0 = context$1$0['catch'](4);

				console.log('Error on Database setup:', context$1$0.t0);

			case 22:
			case 'end':
				return context$1$0.stop();
		}
	}, null, this, [[4, 19]]);
};

module.exports = exports['default'];


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

namespace Vista.Controls {
	/// <summary>
	///
	/// </summary>
	public class BreadcrumbDropDownItem : ExplorerNavigationHistoryItem {
		/// <summary>
		/// Initializes a new instance of the <see cref="BreadcrumbDropDownItem"/> class.
		/// </summary>
		public BreadcrumbDropDownItem ()
			: this ( string.Empty ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="BreadcrumbDropDownItem"/> class.
		/// </summary>
		/// <param name="text">The text.</param>
		public BreadcrumbDropDownItem ( string text )
			: this ( text, null ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="BreadcrumbDropDownItem"/> class.
		/// </summary>
		/// <param name="text">The text.</param>
		/// <param name="click">The click.</param>
		public BreadcrumbDropDownItem ( string text, EventHandler click )
			: this ( text, null, click, null ) {
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="BreadcrumbDropDownItem"/> class.
		/// </summary>
		/// <param name="text">The text.</param>
		/// <param name="image">The image.</param>
		/// <param name="click">The click.</param>
		public BreadcrumbDropDownItem ( string text, Image image, EventHandler click )
			: this ( text, image, click, null ) {
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="BreadcrumbDropDownItem"/> class.
		/// </summary>
		/// <param name="text">The text.</param>
		/// <param name="image">The image.</param>
		/// <param name="click">The click.</param>
		/// <param name="tag">The tag.</param>
		public BreadcrumbDropDownItem ( string text, Image image, EventHandler click, object tag )
			: base ( text, image, click, tag ) {
		}

	}
}


text:
<!DOCTYPE html>

    <title>Cateva reguli pentru a scrie cod frumos in limbajul C – Scoala de padawani a lui tudurom – De la padawan la Jedi</title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <meta name="description" content="Din regulile de programare in limbajul C de pe Algopedia, am gasit acestea fiind foarte importante.
" />
    <meta property="og:description" content="Din regulile de programare in limbajul C de pe Algopedia, am gasit acestea fiind foarte importante.
" />

    <meta name="author" content="Scoala de padawani a lui tudurom" />

    <meta property="og:title" content="Cateva reguli pentru a scrie cod frumos in limbajul C" />
    <meta property="twitter:title" content="Cateva reguli pentru a scrie cod frumos in limbajul C" />

    <link rel="stylesheet" type="text/css" href="/padawans/style.css" />
    <link rel="alternate" type="application/rss+xml" title="Scoala de padawani a lui tudurom - De la padawan la Jedi" href="/padawans/feed.xml" />

Scoala de padawani a lui tudurom

De la padawan la Jedi

            Blog
            About

Cateva reguli pentru a scrie cod frumos in limbajul C

Din regulile de programare in limbajul C de pe Algopedia, am gasit acestea fiind foarte importante.

Indentarea

Codul trebuie sa fie indentat frumos (aliniat), ca sa poata fi citit de oricine.

Cateva reguli de indentare:

Pentru fiecare nivel intr-un bloc de cod, codul trebuie indentat cu inca o unitate

Denumim o unitate caracterul sau caracterele care sunt inserate cand apesi pe Tab in Code::Blocks. Implicit, o unitate corespunde cu 4 spatii. Eu recomand 2 spatii, ca sa nu migreze prea mult codul spre partea dreapta a monitorului. Chiar daca majoritatea monitoarelor care se vand in ziua de azi sunt destul de late, cu raportul dintre latime si lungime fiind 16:9 sau chiar 16:10 la unele, daca codul migreaza prea la dreapta, o sa fie obositor sa iti plimbi ochii din stanga in dreapta monitorului.

Exemplu:

#include <stdio.h>

int v[100]; // Suntem in nivelul 0; nu suntem in nici un bloc de cod
            // De aceea, indentam cu 0 unitati (0 unitati * 2 spatii = 0 spatii)

int main() {
  printf("Hello World!"); // Suntem in nivelul 1. (1 unitate * 2 spatii = 2 spatii)

  while (1) {
    printf("Ciclu infiniiiit!\n"); // Un bloc while in interiorul blocului functiei main => nivelul 2 => 2 * 2 = 4 spatii.

    for (i = 0; i < 3; i++) {
      printf("%d\n", i); // Nivelul 3 => 3 * 2 = 6 spatii
    }
  }

  return 0;
}

IMPORTANT: NU SE INDENTEAZA CU TAB

De ce? Pentru ca lungimea unui caracter tab depinde de editorul de texte pe care il folosim.

Acolada deschisa se pune pe acelasi rand cu instructiunea precedenta

De ce? Pentru ca economisim spatiu pe verticala. Cum am zis mai sus, raportul dintre latime si lungime al monitoarelor din comert este 16:9 => verticala e foarte mica in comparatie cu latimea.

Exemplu:

// Corect:
if (maDoareCeva()) {
  mergLaDoctor();
  sperCaMaVindec();
}

//Gresit:
if(maDoareCeva())
{
  maRog();
}

// Corect:
void mergLaDoctor() {
  ...
}

// Gresit:
void maRog()
{
  ...
}

Nu zic ca nu e bine sa te rogi, dar e doar un exemplu.

Acolada inchisa se pune pe randul urmator aliniata sub instructiunea de care apartine

// Corect:
if (maDoareCeva()) {
  mergLaDoctor();
  sperCaMaVindec();
}

// Gresit:
if(maDoareCeva())
{
  maRog();
  }

// Si mai gresit:
if(maDoareCeva())
{
  maRog();}

Dacă după else urmează un if atunci if-ul se pune imediat după else pe aceeași linie

Din nou, economisim spatiu pe verticala.

Exemplu:

// Corect:
if (maDoareCeva()) {
  mergLaDoctor();
} else if (maDoareCapul()) {
  iauUnNurofen();
} else {
  ...
}

// Gresit:
if (maDoareCeva()) {
  mergLaDoctor();
}
else if (maDoareCapul()) {
  iauUnNurofen();
}
else {
  ...
}

// Mai gresit:
if (maDoareCeva()) {
  mergLaDoctor();
}
if (maDoareCapul()) {
  iauUnNurofen();
}
else {
  ...
}

Variabilele trebuie sa aiba nume clare

Nu cred ca e nevoie de exemplu.

Lucrul cu fisiere in C

FILE *fin, *fout; // Am declarat doua fisiere, fin si fout. Steluta e obligatorie

fin = fopen("in.txt", "r"); // fin reprezinta fisierul in.txt, deschis pentru citire
fout = fopen("out.txt", "w"); // fout reprezinta fisierul out.txt, deschis pentru scriere

fscanf(fin, "%d", &n); // Citim din fin un numar intreg "n". Obligatoriu &
fprintf(fout, "%d", n - 1); // Afisam la fout n - 1

// INCHIDEREA FISIERELOR - FOARTE IMPORTANTA
// Cand inchizi un fisier, se salveaza modificarile care nu s-au salvat si se inchid, facandu-se disponibile altor programe.
fclose(fin);
fclose(fout);

Tema: un program simplu care foloseste toate lucrurile invatate din aceasta lectie. PANA VINERI, 9 octombrie 2015

    Written on October  6, 2015


text: echo noop > /sys/block/sdb/queue/scheduler


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Movable unit tests</title>
    <link rel="stylesheet" type="text/css" href="/jsunit/css/jsUnitStyle.css">
	 <link rel="stylesheet" type="text/css" href="../../css/effects.css">

Heading
 Content of this box. More content Content of this box. More content Content of this box. More content
		 Content of this box. More content Content of this box. More content Content of this box. More content


text:
package com.sequenceiq.flow.reactor.api.handler;

import java.util.Objects;

import com.sequenceiq.cloudbreak.common.event.Payload;
import com.sequenceiq.cloudbreak.common.event.Selectable;
import com.sequenceiq.cloudbreak.eventbus.Event;

/**
 * Support class to make unit testing of {@link ExceptionCatcherEventHandler} easier.
 * @param <T> request event payload type
 */
public class ExceptionCatcherEventHandlerTestSupport<T extends Payload> {

    private final ExceptionCatcherEventHandler<T> eventHandler;

    /**
     * Creates a new {@code ExceptionCatcherEventHandlerTestSupport} instance wrapping {@code eventHandler}.
     * @param eventHandler {@link ExceptionCatcherEventHandler} instance to wrap; must not be {@code null}
     * @throws NullPointerException if {@code eventHandler == null}
     */
    public ExceptionCatcherEventHandlerTestSupport(ExceptionCatcherEventHandler<T> eventHandler) {
        this.eventHandler = Objects.requireNonNull(eventHandler);
    }

    /**
     * Delegates to {@link ExceptionCatcherEventHandler#doAccept(HandlerEvent)}.
     * @param event reactor event
     * @return response event payload
     */
    public Selectable doAccept(Event<T> event) {
        return eventHandler.doAccept(new HandlerEvent(event));
    }

}


text:
<?php

// Protect from unauthorized access
defined('F0F_INCLUDED') or die;

/**
 * FrameworkOnFramework View class. The View is the MVC component which gets the
 * raw data from a Model and renders it in a way that makes sense. The usual
 * rendering is HTML, but you can also output JSON, CSV, XML, or even media
 * (images, videos, ...) and documents (Word, PDF, Excel...).
 *
 * @package  FrameworkOnFramework
 * @since    1.0
 */
abstract class F0FView extends F0FUtilsObject
{
	/**
	 * The name of the view
	 *
	 * @var    array
	 */
	protected $_name = null;

	/**
	 * Registered models
	 *
	 * @var    array
	 */
	protected $_models = array();

	/**
	 * The base path of the view
	 *
	 * @var    string
	 */
	protected $_basePath = null;

	/**
	 * The default model
	 *
	 * @var	string
	 */
	protected $_defaultModel = null;

	/**
	 * Layout name
	 *
	 * @var    string
	 */
	protected $_layout = 'default';

	/**
	 * Layout extension
	 *
	 * @var    string
	 */
	protected $_layoutExt = 'php';

	/**
	 * Layout template
	 *
	 * @var    string
	 */
	protected $_layoutTemplate = '_';

	/**
	 * The set of search directories for resources (templates)
	 *
	 * @var array
	 */
	protected $_path = array('template' => array(), 'helper' => array());

	/**
	 * The name of the default template source file.
	 *
	 * @var string
	 */
	protected $_template = null;

	/**
	 * The output of the template script.
	 *
	 * @var string
	 */
	protected $_output = null;

	/**
	 * Callback for escaping.
	 *
	 * @var string
	 * @deprecated 13.3
	 */
	protected $_escape = 'htmlspecialchars';

	/**
	 * Charset to use in escaping mechanisms; defaults to urf8 (UTF-8)
	 *
	 * @var string
	 */
	protected $_charset = 'UTF-8';

	/**
	 * The available renderer objects we can use to render views
	 *
	 * @var    array  Contains objects of the F0FRenderAbstract class
	 */
	public static $renderers = array();

	/**
	 * Cache of the configuration array
	 *
	 * @var    array
	 */
	protected $config = array();

	/**
	 * The input object of this view
	 *
	 * @var    F0FInput
	 */
	protected $input = null;

	/**
	 * The chosen renderer object
	 *
	 * @var    F0FRenderAbstract
	 */
	protected $rendererObject = null;

	/**
	 * Should I run the pre-render step?
	 *
	 * @var    boolean
	 */
	protected $doPreRender = true;

	/**
	 * Should I run the post-render step?
	 *
	 * @var    boolean
	 */
	protected $doPostRender = true;

	/**
	 * Public constructor. Instantiates a F0FView object.
	 *
	 * @param   array  $config  The configuration data array
	 */
	public function __construct($config = array())
	{
		// Make sure $config is an array
		if (is_object($config))
		{
			$config = (array) $config;
		}
		elseif (!is_array($config))
		{
			$config = array();
		}

		// Get the input
		if (array_key_exists('input', $config))
		{
			if ($config['input'] instanceof F0FInput)
			{
				$this->input = $config['input'];
			}
			else
			{
				$this->input = new F0FInput($config['input']);
			}
		}
		else
		{
			$this->input = new F0FInput;
		}

		parent::__construct($config);

		$component = 'com_foobar';

		// Get the component name
		if (array_key_exists('input', $config))
		{
			if ($config['input'] instanceof F0FInput)
			{
				$tmpInput = $config['input'];
			}
			else
			{
				$tmpInput = new F0FInput($config['input']);
			}

			$component = $tmpInput->getCmd('option', '');
		}
		else
		{
			$tmpInput = $this->input;
		}

		if (array_key_exists('option', $config))
		{
			if ($config['option'])
			{
				$component = $config['option'];
			}
		}

		$config['option'] = $component;

		// Get the view name
		$view = null;
		if (array_key_exists('input', $config))
		{
			$view = $tmpInput->getCmd('view', '');
		}

		if (array_key_exists('view', $config))
		{
			if ($config['view'])
			{
				$view = $config['view'];
			}
		}

		$config['view'] = $view;

		// Set the component and the view to the input array

		if (array_key_exists('input', $config))
		{
			$tmpInput->set('option', $config['option']);
			$tmpInput->set('view', $config['view']);
		}

		// Set the view name

		if (array_key_exists('name', $config))
		{
			$this->_name = $config['name'];
		}
		else
		{
			$this->_name = $config['view'];
		}

		$tmpInput->set('view', $this->_name);
		$config['input'] = $tmpInput;
		$config['name'] = $this->_name;
		$config['view'] = $this->_name;

		// Get the component directories
		$componentPaths = F0FPlatform::getInstance()->getComponentBaseDirs($config['option']);

		// Set the charset (used by the variable escaping functions)

		if (array_key_exists('charset', $config))
		{
			F0FPlatform::getInstance()->logDeprecated('Setting a custom charset for escaping in F0FView\'s constructor is deprecated. Override F0FView::escape() instead.');
			$this->_charset = $config['charset'];
		}

		// User-defined escaping callback

		if (array_key_exists('escape', $config))
		{
			$this->setEscape($config['escape']);
		}

		// Set a base path for use by the view

		if (array_key_exists('base_path', $config))
		{
			$this->_basePath = $config['base_path'];
		}
		else
		{
			$this->_basePath = $componentPaths['main'];
		}

		// Set the default template search path

		if (array_key_exists('template_path', $config))
		{
			// User-defined dirs
			$this->_setPath('template', $config['template_path']);
		}
		else
		{
			$altView = F0FInflector::isSingular($this->getName()) ? F0FInflector::pluralize($this->getName()) : F0FInflector::singularize($this->getName());
			$this->_setPath('template', $this->_basePath . '/views/' . $altView . '/tmpl');
			$this->_addPath('template', $this->_basePath . '/views/' . $this->getName() . '/tmpl');
		}

		// Set the default helper search path

		if (array_key_exists('helper_path', $config))
		{
			// User-defined dirs
			$this->_setPath('helper', $config['helper_path']);
		}
		else
		{
			$this->_setPath('helper', $this->_basePath . '/helpers');
		}

		// Set the layout

		if (array_key_exists('layout', $config))
		{
			$this->setLayout($config['layout']);
		}
		else
		{
			$this->setLayout('default');
		}

		$this->config = $config;

		if (!F0FPlatform::getInstance()->isCli())
		{
			$this->baseurl = F0FPlatform::getInstance()->URIbase(true);

			$fallback = F0FPlatform::getInstance()->getTemplateOverridePath($component) . '/' . $this->getName();
			$this->_addPath('template', $fallback);
		}
	}

	/**
	 * Loads a template given any path. The path is in the format:
	 * [admin|site]:com_foobar/viewname/templatename
	 * e.g. admin:com_foobar/myview/default
	 *
	 * This function searches for Joomla! version override templates. For example,
	 * if you have run this under Joomla! 3.0 and you try to load
	 * admin:com_foobar/myview/default it will automatically search for the
	 * template files default.j30.php, default.j3.php and default.php, in this
	 * order.
	 *
	 * @param   string  $path         See above
	 * @param   array   $forceParams  A hash array of variables to be extracted in the local scope of the template file
	 *
	 * @return  boolean  False if loading failed
	 */
	public function loadAnyTemplate($path = '', $forceParams = array())
	{
		// Automatically check for a Joomla! version specific override
		$throwErrorIfNotFound = true;

		$suffixes = F0FPlatform::getInstance()->getTemplateSuffixes();

		foreach ($suffixes as $suffix)
		{
			if (substr($path, -strlen($suffix)) == $suffix)
			{
				$throwErrorIfNotFound = false;
				break;
			}
		}

		if ($throwErrorIfNotFound)
		{
			foreach ($suffixes as $suffix)
			{
				$result = $this->loadAnyTemplate($path . $suffix, $forceParams);

				if ($result !== false)
				{
					return $result;
				}
			}
		}

		$layoutTemplate = $this->getLayoutTemplate();

		// Parse the path
		$templateParts = $this->_parseTemplatePath($path);

		// Get the paths
		$componentPaths = F0FPlatform::getInstance()->getComponentBaseDirs($templateParts['component']);
		$templatePath   = F0FPlatform::getInstance()->getTemplateOverridePath($templateParts['component']);

		// Get the default paths
		$paths = array();
		$paths[] = $templatePath . '/' . $templateParts['view'];
		$paths[] = ($templateParts['admin'] ? $componentPaths['admin'] : $componentPaths['site']) . '/views/' . $templateParts['view'] . '/tmpl';

		if (isset($this->_path) || property_exists($this, '_path'))
		{
			$paths = array_merge($paths, $this->_path['template']);
		}
		elseif (isset($this->path) || property_exists($this, 'path'))
		{
			$paths = array_merge($paths, $this->path['template']);
		}

		// Look for a template override

		if (isset($layoutTemplate) && $layoutTemplate != '_' && $layoutTemplate != $template)
		{
			$apath = array_shift($paths);
			array_unshift($paths, str_replace($template, $layoutTemplate, $apath));
		}

		$filetofind = $templateParts['template'] . '.php';
        $filesystem = F0FPlatform::getInstance()->getIntegrationObject('filesystem');

		$this->_tempFilePath = $filesystem->pathFind($paths, $filetofind);

		if ($this->_tempFilePath)
		{
			// Unset from local scope
			unset($template);
			unset($layoutTemplate);
			unset($paths);
			unset($path);
			unset($filetofind);

			// Never allow a 'this' property

			if (isset($this->this))
			{
				unset($this->this);
			}

			// Force parameters into scope

			if (!empty($forceParams))
			{
				extract($forceParams);
			}

			// Start capturing output into a buffer
			ob_start();

			// Include the requested template filename in the local scope (this will execute the view logic).
			include $this->_tempFilePath;

			// Done with the requested template; get the buffer and clear it.
			$this->_output = ob_get_contents();
			ob_end_clean();

			return $this->_output;
		}
		else
		{
			if ($throwErrorIfNotFound)
			{
				return new Exception(JText::sprintf('JLIB_APPLICATION_ERROR_LAYOUTFILE_NOT_FOUND', $path), 500);
			}

			return false;
		}
	}

	/**
	 * Overrides the default method to execute and display a template script.
	 * Instead of loadTemplate is uses loadAnyTemplate which allows for automatic
	 * Joomla! version overrides. A little slice of awesome pie!
	 *
	 * @param   string  $tpl  The name of the template file to parse
	 *
	 * @return  mixed  A string if successful, otherwise a JError object.
	 */
	public function display($tpl = null)
	{
		F0FPlatform::getInstance()->setErrorHandling(E_ALL, 'ignore');

		$result = $this->loadTemplate($tpl);

		if ($result instanceof Exception)
		{
            F0FPlatform::getInstance()->raiseError($result->getCode(), $result->getMessage());

			return $result;
		}

		echo $result;
	}

	/**
	 * Assigns variables to the view script via differing strategies.
	 *
	 * This method is overloaded; you can assign all the properties of
	 * an object, an associative array, or a single value by name.
	 *
	 * You are not allowed to set variables that begin with an underscore;
	 * these are either private properties for F0FView or private variables
	 * within the template script itself.
	 *
	 * @return  boolean  True on success, false on failure.
	 *
	 * @deprecated  13.3 Use native PHP syntax.
	 */
	public function assign()
	{
		F0FPlatform::getInstance()->logDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated. Use native PHP syntax.');

		// Get the arguments; there may be 1 or 2.
		$arg0 = @func_get_arg(0);
		$arg1 = @func_get_arg(1);

		// Assign by object

		if (is_object($arg0))
		{
			// Assign public properties
			foreach (get_object_vars($arg0) as $key => $val)
			{
				if (substr($key, 0, 1) != '_')
				{
					$this->$key = $val;
				}
			}

			return true;
		}

		// Assign by associative array

		if (is_array($arg0))
		{
			foreach ($arg0 as $key => $val)
			{
				if (substr($key, 0, 1) != '_')
				{
					$this->$key = $val;
				}
			}

			return true;
		}

		// Assign by string name and mixed value. We use array_key_exists() instead of isset()
		// because isset() fails if the value is set to null.

		if (is_string($arg0) && substr($arg0, 0, 1) != '_' && func_num_args() > 1)
		{
			$this->$arg0 = $arg1;

			return true;
		}

		// $arg0 was not object, array, or string.
		return false;
	}

	/**
	 * Assign variable for the view (by reference).
	 *
	 * You are not allowed to set variables that begin with an underscore;
	 * these are either private properties for F0FView or private variables
	 * within the template script itself.
	 *
	 * @param   string  $key   The name for the reference in the view.
	 * @param   mixed   &$val  The referenced variable.
	 *
	 * @return  boolean  True on success, false on failure.
	 *
	 * @deprecated  13.3  Use native PHP syntax.
	 */
	public function assignRef($key, &$val)
	{
		F0FPlatform::getInstance()->logDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated. Use native PHP syntax.');

		if (is_string($key) && substr($key, 0, 1) != '_')
		{
			$this->$key = &$val;

			return true;
		}

		return false;
	}

	/**
	 * Escapes a value for output in a view script.
	 *
	 * If escaping mechanism is either htmlspecialchars or htmlentities, uses
	 * {@link $_encoding} setting.
	 *
	 * @param   mixed  $var  The output to escape.
	 *
	 * @return  mixed  The escaped value.
	 */
	public function escape($var)
	{
		if (in_array($this->_escape, array('htmlspecialchars', 'htmlentities')))
		{
			return call_user_func($this->_escape, $var, ENT_COMPAT, $this->_charset);
		}

		return call_user_func($this->_escape, $var);
	}

	/**
	 * Method to get data from a registered model or a property of the view
	 *
	 * @param   string  $property  The name of the method to call on the model or the property to get
	 * @param   string  $default   The name of the model to reference or the default value [optional]
	 *
	 * @return  mixed  The return value of the method
	 */
	public function get($property, $default = null)
	{
		// If $model is null we use the default model
		if (is_null($default))
		{
			$model = $this->_defaultModel;
		}
		else
		{
			$model = strtolower($default);
		}

		// First check to make sure the model requested exists
		if (isset($this->_models[$model]))
		{
			// Model exists, let's build the method name
			$method = 'get' . ucfirst($property);

			// Does the method exist?
			if (method_exists($this->_models[$model], $method))
			{
				// The method exists, let's call it and return what we get
				$result = $this->_models[$model]->$method();

				return $result;
			}
		}

		// Degrade to F0FUtilsObject::get
		$result = parent::get($property, $default);

		return $result;
	}

	/**
	 * Method to get the model object
	 *
	 * @param   string  $name  The name of the model (optional)
	 *
	 * @return  mixed  F0FModel object
	 */
	public function getModel($name = null)
	{
		if ($name === null)
		{
			$name = $this->_defaultModel;
		}

		return $this->_models[strtolower($name)];
	}

	/**
	 * Get the layout.
	 *
	 * @return  string  The layout name
	 */
	public function getLayout()
	{
		return $this->_layout;
	}

	/**
	 * Get the layout template.
	 *
	 * @return  string  The layout template name
	 */
	public function getLayoutTemplate()
	{
		return $this->_layoutTemplate;
	}

	/**
	 * Method to get the view name
	 *
	 * The model name by default parsed using the classname, or it can be set
	 * by passing a $config['name'] in the class constructor
	 *
	 * @return  string  The name of the model
	 */
	public function getName()
	{
		if (empty($this->_name))
		{
			$classname = get_class($this);
			$viewpos = strpos($classname, 'View');

			if ($viewpos === false)
			{
				throw new Exception(JText::_('JLIB_APPLICATION_ERROR_VIEW_GET_NAME'), 500);
			}

			$this->_name = strtolower(substr($classname, $viewpos + 4));
		}

		return $this->_name;
	}

	/**
	 * Method to add a model to the view.
	 *
	 * @param   F0FMOdel  $model    The model to add to the view.
     * @param   boolean   $default  Is this the default model?
     * @param   String    $name     optional index name to store the model
	 *
	 * @return  object   The added model.
	 */
	public function setModel($model, $default = false, $name = null)
	{
		if (is_null($name))
		{
			$name = $model->getName();
		}

		$name = strtolower($name);

		$this->_models[$name] = $model;

		if ($default)
		{
			$this->_defaultModel = $name;
		}

		return $model;
	}

	/**
	 * Sets the layout name to use
	 *
	 * @param   string  $layout  The layout name or a string in format <template>:<layout file>
	 *
	 * @return  string  Previous value.
	 */
	public function setLayout($layout)
	{
		$previous = $this->_layout;

		if (strpos($layout, ':') === false)
		{
			$this->_layout = $layout;
		}
		else
		{
			// Convert parameter to array based on :
			$temp = explode(':', $layout);
			$this->_layout = $temp[1];

			// Set layout template
			$this->_layoutTemplate = $temp[0];
		}

		return $previous;
	}

	/**
	 * Allows a different extension for the layout files to be used
	 *
	 * @param   string  $value  The extension.
	 *
	 * @return  string   Previous value
	 */
	public function setLayoutExt($value)
	{
		$previous = $this->_layoutExt;

		if ($value = preg_replace('#[^A-Za-z0-9]#', '', trim($value)))
		{
			$this->_layoutExt = $value;
		}

		return $previous;
	}

	/**
	 * Sets the _escape() callback.
	 *
	 * @param   mixed  $spec  The callback for _escape() to use.
	 *
	 * @return  void
	 *
	 * @deprecated  2.1  Override F0FView::escape() instead.
	 */
	public function setEscape($spec)
	{
		F0FPlatform::getInstance()->logDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated. Override F0FView::escape() instead.');

		$this->_escape = $spec;
	}

	/**
	 * Adds to the stack of view script paths in LIFO order.
	 *
	 * @param   mixed  $path  A directory path or an array of paths.
	 *
	 * @return  void
	 */
	public function addTemplatePath($path)
	{
		$this->_addPath('template', $path);
	}

	/**
	 * Adds to the stack of helper script paths in LIFO order.
	 *
	 * @param   mixed  $path  A directory path or an array of paths.
	 *
	 * @return  void
	 */
	public function addHelperPath($path)
	{
		$this->_addPath('helper', $path);
	}

	/**
	 * Overrides the built-in loadTemplate function with an F0F-specific one.
	 * Our overriden function uses loadAnyTemplate to provide smarter view
	 * template loading.
	 *
	 * @param   string   $tpl     The name of the template file to parse
	 * @param   boolean  $strict  Should we use strict naming, i.e. force a non-empty $tpl?
	 *
	 * @return  mixed  A string if successful, otherwise a JError object
	 */
	public function loadTemplate($tpl = null, $strict = false)
	{
		$paths = F0FPlatform::getInstance()->getViewTemplatePaths(
			$this->input->getCmd('option', ''),
			$this->input->getCmd('view', ''),
			$this->getLayout(),
			$tpl,
			$strict
		);

		foreach ($paths as $path)
		{
			$result = $this->loadAnyTemplate($path);

			if (!($result instanceof Exception))
			{
				break;
			}
		}

		if ($result instanceof Exception)
		{
            F0FPlatform::getInstance()->raiseError($result->getCode(), $result->getMessage());
		}

		return $result;
	}

	/**
	 * Parses a template path in the form of admin:/component/view/layout or
	 * site:/component/view/layout to an array which can be used by
	 * loadAnyTemplate to locate and load the view template file.
	 *
	 * @param   string  $path  The template path to parse
	 *
	 * @return  array  A hash array with the parsed path parts
	 */
	private function _parseTemplatePath($path = '')
	{
		$parts = array(
			'admin'		 => 0,
			'component'	 => $this->config['option'],
			'view'		 => $this->config['view'],
			'template'	 => 'default'
		);

		if (substr($path, 0, 6) == 'admin:')
		{
			$parts['admin'] = 1;
			$path = substr($path, 6);
		}
		elseif (substr($path, 0, 5) == 'site:')
		{
			$path = substr($path, 5);
		}

		if (empty($path))
		{
			return;
		}

		$pathparts = explode('/', $path, 3);

		switch (count($pathparts))
		{
			case 3:
				$parts['component'] = array_shift($pathparts);

			case 2:
				$parts['view'] = array_shift($pathparts);

			case 1:
				$parts['template'] = array_shift($pathparts);
				break;
		}

		return $parts;
	}

	/**
	 * Get the renderer object for this view
	 *
	 * @return  F0FRenderAbstract
	 */
	public function &getRenderer()
	{
		if (!($this->rendererObject instanceof F0FRenderAbstract))
		{
			$this->rendererObject = $this->findRenderer();
		}

		return $this->rendererObject;
	}

	/**
	 * Sets the renderer object for this view
	 *
	 * @param   F0FRenderAbstract  &$renderer  The render class to use
	 *
	 * @return  void
	 */
	public function setRenderer(F0FRenderAbstract &$renderer)
	{
		$this->rendererObject = $renderer;
	}

	/**
	 * Finds a suitable renderer
	 *
	 * @return  F0FRenderAbstract
	 */
	protected function findRenderer()
	{
        $filesystem     = F0FPlatform::getInstance()->getIntegrationObject('filesystem');

		// Try loading the stock renderers shipped with F0F

		if (empty(self::$renderers) || !class_exists('F0FRenderJoomla', false))
		{
			$path = dirname(__FILE__) . '/../render/';
			$renderFiles = $filesystem->folderFiles($path, '.php');

			if (!empty($renderFiles))
			{
				foreach ($renderFiles as $filename)
				{
					if ($filename == 'abstract.php')
					{
						continue;
					}

					@include_once $path . '/' . $filename;

					$camel = F0FInflector::camelize($filename);
					$className = 'F0FRender' . ucfirst(F0FInflector::getPart($camel, 0));
					$o = new $className;

					self::registerRenderer($o);
				}
			}
		}

		// Try to detect the most suitable renderer
		$o = null;
		$priority = 0;

		if (!empty(self::$renderers))
		{
			foreach (self::$renderers as $r)
			{
				$info = $r->getInformation();

				if (!$info->enabled)
				{
					continue;
				}

				if ($info->priority > $priority)
				{
					$priority = $info->priority;
					$o = $r;
				}
			}
		}

		// Return the current renderer
		return $o;
	}

	/**
	 * Registers a renderer object with the view
	 *
	 * @param   F0FRenderAbstract  &$renderer  The render object to register
	 *
	 * @return  void
	 */
	public static function registerRenderer(F0FRenderAbstract &$renderer)
	{
		self::$renderers[] = $renderer;
	}

	/**
	 * Sets the pre-render flag
	 *
	 * @param   boolean  $value  True to enable the pre-render step
	 *
	 * @return  void
	 */
	public function setPreRender($value)
	{
		$this->doPreRender = $value;
	}

	/**
	 * Sets the post-render flag
	 *
	 * @param   boolean  $value  True to enable the post-render step
	 *
	 * @return  void
	 */
	public function setPostRender($value)
	{
		$this->doPostRender = $value;
	}

	/**
	 * Load a helper file
	 *
	 * @param   string  $hlp  The name of the helper source file automatically searches the helper paths and compiles as needed.
	 *
	 * @return  void
	 */
	public function loadHelper($hlp = null)
	{
		// Clean the file name
		$file = preg_replace('/[^A-Z0-9_\.-]/i', '', $hlp);

		// Load the template script using the default Joomla! features
        $filesystem = F0FPlatform::getInstance()->getIntegrationObject('filesystem');

		$helper = $filesystem->pathFind($this->_path['helper'], $this->_createFileName('helper', array('name' => $file)));

		if ($helper == false)
		{
			$componentPaths = F0FPlatform::getInstance()->getComponentBaseDirs($this->config['option']);
			$path = $componentPaths['main'] . '/helpers';
			$helper = $filesystem->pathFind($path, $this->_createFileName('helper', array('name' => $file)));

			if ($helper == false)
			{
				$path = $path = $componentPaths['alt'] . '/helpers';
				$helper = $filesystem->pathFind($path, $this->_createFileName('helper', array('name' => $file)));
			}
		}

		if ($helper != false)
		{
			// Include the requested template filename in the local scope
			include_once $helper;
		}
	}

	/**
	 * Returns the view's option (component name) and view name in an
	 * associative array.
	 *
	 * @return  array
	 */
	public function getViewOptionAndName()
	{
		return array(
			'option' => $this->config['option'],
			'view'	 => $this->config['view'],
		);
	}

	/**
	 * Sets an entire array of search paths for templates or resources.
	 *
	 * @param   string  $type  The type of path to set, typically 'template'.
	 * @param   mixed   $path  The new search path, or an array of search paths.  If null or false, resets to the current directory only.
	 *
	 * @return  void
	 */
	protected function _setPath($type, $path)
	{
		// Clear out the prior search dirs
		$this->_path[$type] = array();

		// Actually add the user-specified directories
		$this->_addPath($type, $path);

		// Always add the fallback directories as last resort
		switch (strtolower($type))
		{
			case 'template':
				// Set the alternative template search dir

				if (!F0FPlatform::getInstance()->isCli())
				{
					$fallback = F0FPlatform::getInstance()->getTemplateOverridePath($this->input->getCmd('option', '')) . '/' . $this->getName();
					$this->_addPath('template', $fallback);
				}

				break;
		}
	}

	/**
	 * Adds to the search path for templates and resources.
	 *
	 * @param   string  $type  The type of path to add.
	 * @param   mixed   $path  The directory or stream, or an array of either, to search.
	 *
	 * @return  void
	 */
	protected function _addPath($type, $path)
	{
		// Just force to array
		settype($path, 'array');

		// Loop through the path directories
		foreach ($path as $dir)
		{
			// No surrounding spaces allowed!
			$dir = trim($dir);

			// Add trailing separators as needed
			if (substr($dir, -1) != DIRECTORY_SEPARATOR)
			{
				// Directory
				$dir .= DIRECTORY_SEPARATOR;
			}

			// Add to the top of the search dirs
			array_unshift($this->_path[$type], $dir);
		}
	}

	/**
	 * Create the filename for a resource
	 *
	 * @param   string  $type   The resource type to create the filename for
	 * @param   array   $parts  An associative array of filename information
	 *
	 * @return  string  The filename
	 */
	protected function _createFileName($type, $parts = array())
	{
		$filename = '';

		switch ($type)
		{
			case 'template':
				$filename = strtolower($parts['name']) . '.' . $this->_layoutExt;
				break;

			default:
				$filename = strtolower($parts['name']) . '.php';
				break;
		}

		return $filename;
	}
}


text:
<?php

namespace Component\Lesson\Fetcher;

use Component\Lesson\Model\Lesson;

class UnrememberedElements
{
    public function fetchUnremembered(Lesson $lesson)
    {
        $questions = [];

        foreach ($lesson->getMarkableElements() as $element) {
            if ($element->remembered()) {
                continue;
            }

            $questions[] = $questions;
        }

        return $questions;
    }
}


text:
<?php

/**
 * Order payment entity resource model
 *
 * @category   Mage
 * @package    Mage_Sales
 * @author      Magento Core Team <core@magentocommerce.com>
 */

class Mage_Sales_Model_Entity_Order_Payment extends Mage_Eav_Model_Entity_Abstract
{

    public function __construct()
    {
        $resource = Mage::getSingleton('core/resource');
        $this->setType('order_payment')->setConnection(
            $resource->getConnection('sales_read'),
            $resource->getConnection('sales_write')
        );
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Hattori bot. Lab. 43: 297 (1977)

#### Original name
Stereocaulon ramulosum var. acuminatum Müll. Arg.

### Remarks
null


text:
class ApiAbility
  include CanCan::Ability
  def initialize(user)
    return unless user
    alias_action :view, :create, :update, :delete, to: :crud

    can :update_profile, user
    can :view, Models::User
    can :update, Models::User, { id: user.id }

    if user.role == :admin
      can :crud, :all
    end
  end
end


text:
'use strict';

/**
* A list of familiar American-English words.
*
* @module @stdlib/datasets/dale-chall-new
*
* @example
* var words = require( '@stdlib/datasets/dale-chall-new' );
*
* var data = words();
* // returns [ 'a', 'able', 'aboard', 'about', 'above', ... ]
*/

// MODULES //

var main = require( './main.js' );

// EXPORTS //

module.exports = main;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.tensorics.core.analysis.lang (tensorics-core API)</title>
<meta name="date" content="2019-07-29">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.tensorics.core.analysis.lang

Interfaces

IterableBooleanConversion

Classes

OngoingAllBooleanCondition

OngoingAllBooleanExcludableCondition

OngoingAnalysisEnabler

OngoingAnyBooleanCondition

OngoingBooleanCondition

OngoingCondition

OngoingNamedCondition

OngoingPrecondition


text:
package org.apache.ignite.internal.processors.cache.verify;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.visor.VisorDataTransferObject;
import org.jetbrains.annotations.Nullable;

/**
 * Record containing partition checksum, primary flag and consistent ID of owner.
 */
public class PartitionHashRecordV2 extends VisorDataTransferObject {
    /** */
    private static final long serialVersionUID = 0L;

    /** Moving partition size. */
    public static final long MOVING_PARTITION_SIZE = Long.MIN_VALUE;

    /** Partition key. */
    @GridToStringExclude
    private PartitionKeyV2 partKey;

    /** Is primary flag. */
    private boolean isPrimary;

    /** Consistent id. */
    @GridToStringInclude
    private Object consistentId;

    /** Partition hash. */
    @GridToStringExclude
    private int partHash;

    /** Update counter. */
    private long updateCntr;

    /** Size. */
    @GridToStringExclude
    private long size;

    /** Partition state. */
    private PartitionState partitionState;

    /**
     * @param partKey Partition key.
     * @param isPrimary Is primary.
     * @param consistentId Consistent id.
     * @param partHash Partition hash.
     * @param updateCntr Update counter.
     * @param size Size.
     * @param partitionState Partition state.
     */
    public PartitionHashRecordV2(PartitionKeyV2 partKey, boolean isPrimary,
        Object consistentId, int partHash, long updateCntr, long size, PartitionState partitionState) {
        this.partKey = partKey;
        this.isPrimary = isPrimary;
        this.consistentId = consistentId;
        this.partHash = partHash;
        this.updateCntr = updateCntr;
        this.size = size;
        this.partitionState = partitionState;
    }

    /**
     * Default constructor for Externalizable.
     */
    public PartitionHashRecordV2() {
    }

    /**
     * @return Partition key.
     */
    public PartitionKeyV2 partitionKey() {
        return partKey;
    }

    /**
     * @return Is primary.
     */
    public boolean isPrimary() {
        return isPrimary;
    }

    /**
     * @return Consistent id.
     */
    public Object consistentId() {
        return consistentId;
    }

    /**
     * @return Partition hash.
     */
    public int partitionHash() {
        return partHash;
    }

    /**
     * @return Update counter.
     */
    public long updateCounter() {
        return updateCntr;
    }

    /**
     * @return Size.
     */
    public long size() {
        return size;
    }

    /**
     * @return Partitions state.
     */
    public PartitionState partitionState() {
        return partitionState;
    }

    /** {@inheritDoc} */
    @Override protected void writeExternalData(ObjectOutput out) throws IOException {
        out.writeObject(partKey);
        out.writeBoolean(isPrimary);
        out.writeObject(consistentId);
        out.writeInt(partHash);
        out.writeLong(updateCntr);
        out.writeLong(size);
        U.writeEnum(out, partitionState);
    }

    /** {@inheritDoc} */
    @Override protected void readExternalData(byte protoVer,
        ObjectInput in) throws IOException, ClassNotFoundException {
        partKey = (PartitionKeyV2)in.readObject();
        isPrimary = in.readBoolean();
        consistentId = in.readObject();
        partHash = in.readInt();
        updateCntr = in.readLong();
        size = in.readLong();

        if (protoVer >= V2)
            partitionState = PartitionState.fromOrdinal(in.readByte());
        else
            partitionState = size == MOVING_PARTITION_SIZE ? PartitionState.MOVING : PartitionState.OWNING;
    }

    /** {@inheritDoc} */
    @Override public byte getProtocolVersion() {
        return V2;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return size == MOVING_PARTITION_SIZE ?
            S.toString(PartitionHashRecordV2.class, this, "state", "MOVING") :
            S.toString(PartitionHashRecordV2.class, this, "size", size, "partHash", partHash);
    }

    /** {@inheritDoc} */
    @Override public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        PartitionHashRecordV2 record = (PartitionHashRecordV2)o;

        return consistentId.equals(record.consistentId);
    }

    /** {@inheritDoc} */
    @Override public int hashCode() {
        return consistentId.hashCode();
    }

    /** **/
    public enum PartitionState {
        /** */
        OWNING,
        /** */
        MOVING,
        /** */
        LOST;

        /** Enumerated values. */
        private static final PartitionState[] VALS = values();

        /**
         * Efficiently gets enumerated value from its ordinal.
         *
         * @param ord Ordinal value.
         * @return Enumerated value or {@code null} if ordinal out of range.
         */
        public static @Nullable PartitionState fromOrdinal(int ord) {
            return ord >= 0 && ord < VALS.length ? VALS[ord] : null;
        }
    }
}


text:
class AddProjectBranchIdToBuilds < ActiveRecord::Migration
  def change
    add_column :builds, :project_branch_id, :integer
  end
end


text:
id: doc2
title: document number 2
---

This is a link to [another document.](doc3.md)
This is a link to an [external page.](http://www.example.com)


text:
import React from "react";
import Link from "gatsby-link";
import Helmet from "react-helmet";

import Nav from "../../components/Nav";
import Title from "../../components/Title";
import Intro from "../../components/Intro";
import Item from "../../components/Item";
import A from "../../components/A";
import Quote from "../../components/Quote";
import Outro from "../../components/Outro";

const IssueContent = () => (

      <Link to="/" className="link dim blue fw5">
        ← Home
      </Link>
      <Title>Issue 05</Title>
      <Intro>
        This week we compare two efforts to define Design Systems, get treated
        to three awesome talks from the NYC Design Systems Coalition meetup,
        deep dive into how 18F created a design system for the U.S Government,
        and more.
      </Intro>
      <Item
        headline="Distilling How We Think About Design Systems [Article]"
        href="https://medium.com/design-systems/distilling-how-we-think-about-design-systems-b26432eefef9"
      >

          Sarah Federman, developer and designer working on design systems at
          Adobe, takes on the tendency for people to get hung up on definitions
          of what design systems are.

        <Quote>
          Focusing on vocabulary creates tribal knowledge and cognitive debt for
          newcomers.
        </Quote>

          She explores the relationship between product and operation in this
          piece, but her focus is on explaining a particular mental model rather
          than putting forward a definition. Importantly, she stresses that{" "}
          whatever works for your team is the right answer. I maxed out
          my Medium claps on this one.

      </Item>
      <Item
        headline="Defining Design Systems [Article]"
        href="https://medium.com/eightshapes-llc/defining-design-systems-6dd4b03e0ff6"
      >

          Nathan Curtis of Eightshapes also weighed into the ongoing discussion
          around definitions, sharing a few of his own as well as a really
          useful template to help teams understand the composition of their
          design system.

      </Item>
      <Item
        headline="How A Design System Was Created For The U.S. Government [Case Study]"
        href="https://www.smashingmagazine.com/2017/10/large-scale-design-system-us-government/"
      >

          Currently there are nearly 30,000 U.S. federal websites with almost no
          consistency between them. 18F and the U.S. Digital Services have been
          working on the mammoth task of creating a common design language that
          will enable cohesive and easy-to-use experiences across all government
          systems and services, and have shared some insights into their process
          here.

      </Item>
      <Item
        headline="Design Systems are for People [Article]"
        href="https://medium.com/design-systems/design-systems-are-for-people-a484620b6988?source=userActivityShare-1874983674f0-1507582635"
      >

          Jina Anne needs no introduction if you're interested in this space.
          She's an amazing community leader, and she used this talk to reinforce
          the importance of focusing on empowering people and growing community.
          I've linked the transcript of her talk on Medium, but it's actually a
          fantastic watch if you've got the time.

        <Quote>
          Remember our purpose. We create design systems to grow our products.
          But those products serve people.
        </Quote>
      </Item>
      <Item
        headline="Why Design Systems Fail [Talk]"
        href="https://www.youtube.com/watch?v=ANX_PxqZayU&feature=youtu.be"
      >

          Una Kravets, senior UI engineer at Digital Ocean, speaks to those
          situations where multiple design systems may be competing, or a new
          design system rises up through the ashes of previous attempts and
          declares itself to be the new single source of truth. She asks the
          question: if there is a design system already, why aren't people using
          it?

      </Item>
      <Item
        headline="Scaling Products with Design Systems [Talk]"
        href="https://www.youtube.com/watch?v=D5JjLcP2Kw0"
      >

          Luke Patton from DoSomething.org explains how his team's design system
          enables all team members to make design decisions, which is especially
          important since he's the only product designer on a team with many
          engineers.

          It's a reminder that design systems don't just benefit large orgs that
          are struggling with design consistency – scaling design is a problem
          for small teams as well.

      </Item>
      <Item
        headline="How our new design principles have shaped the way we work at Domain [Article]"
        href="https://medium.com/design-domain/how-our-new-design-principles-have-shaped-the-way-we-work-at-domain-68597b0a697f"
      >

          Jon Hollamby, Senior Designer at Australian property app Domain,
          shares how their design team created design principles. If your team
          is in the process of coming up with your own principles, you'll likely
          find some value in having a peek into the workshops they ran in the
          discovery phase, as well as the activities the team used to reinforce
          their principles once they'd decided on them.

      </Item>
      <Outro />

);

const Issue05 = () => (

    <Helmet title="Issue 05 | Design Systems Digest" />

    <IssueContent />

);

export default Issue05;