text:
"use strict";

var applicationSettingsModule = require("application-settings");
var view = require("ui/core/view");
var searchViewModelModule = require("./search-view-model");
var navigationModule = require("../../common/navigation");

var viewModel;
function navigatingTo(args) {
    var page = args.object;
    viewModel = new searchViewModelModule.SearchViewModel();
    viewModel.minSlider = view.getViewById(page, "minSlider");
    viewModel.maxSlider = view.getViewById(page, "maxSlider");
    page.bindingContext = viewModel;
}

function navigatedTo(args) {
    if (!args.isBackNavigation) {
        var username = applicationSettingsModule.getString("username");
        viewModel.showInfo("Hello " + username + '!');
    }
}

function findButtonTap() {
    viewModel.find();
}

function getMyLocationTap() {
    viewModel.getMyLocationTap();
}

exports.navigatingTo = navigatingTo;
exports.findButtonTap = findButtonTap;
exports.navigatedTo = navigatedTo;
exports.getMyLocationTap = getMyLocationTap;
exports.settingsButtonTap = navigationModule.goToSettings;
exports.favButtonTap = navigationModule.goToFavourites;

redpajama_set_name: RedPajamaGithub


text:
class Printout < ActiveRecord::Base
  belongs_to :user
end


text:
var newrelic = require('newrelic');

module.exports = function(options) {
  if (!options) options = {};
  if (!options.path) options.path = '$newrelic';

  return function (req, res, next) {
    var model = req.getModel();
    var script = newrelic.getBrowserTimingHeader();
    model.at(options.path).set('script', script);
    next();
  };
};


text:
package de.codecentric.boot.admin.server.utils.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import de.codecentric.boot.admin.server.domain.values.BuildVersion;

import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;

public class BuildVersionMixinTest {

	private final ObjectMapper objectMapper;

	public BuildVersionMixinTest() {
		AdminServerModule adminServerModule = new AdminServerModule(new String[] { ".*password$" });
		JavaTimeModule javaTimeModule = new JavaTimeModule();
		objectMapper = Jackson2ObjectMapperBuilder.json().modules(adminServerModule, javaTimeModule).build();
	}

	@Test
	public void verifyDeserialize() throws JSONException, JsonProcessingException {
		BuildVersion buildVersion = objectMapper.readValue("\"1.0.0\"", BuildVersion.class);
		assertThat(buildVersion).isEqualTo(BuildVersion.valueOf("1.0.0"));
	}

	@Test
	public void verifySerialize() throws JsonProcessingException {
		BuildVersion buildVersion = BuildVersion.valueOf("1.0.0");

		String result = objectMapper.writeValueAsString(buildVersion);
		assertThat(result).isEqualTo("\"1.0.0\"");
	}

	@Test
	public void verifySerializeWithMapEntryVersion() throws JsonProcessingException {
		BuildVersion buildVersion = BuildVersion.from(singletonMap("version", "1.0.0"));

		String result = objectMapper.writeValueAsString(buildVersion);
		assertThat(result).isEqualTo("\"1.0.0\"");
	}

	@Test
	public void verifySerializeWithNestedMapEntryVersion() throws JsonProcessingException {
		BuildVersion buildVersion = BuildVersion.from(singletonMap("build", singletonMap("version", "1.0.0")));

		String result = objectMapper.writeValueAsString(buildVersion);
		assertThat(result).isEqualTo("\"1.0.0\"");
	}

}


text:
package rename

// TODO(matloob):
// - think about what happens if the package is moving across version control systems.
// - think about windows, which uses "\" as its directory separator.
// - dot imports are not supported. Make sure it's clearly documented.

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/build"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"text/template"

	"golang.org/x/tools/go/buildutil"
	"golang.org/x/tools/go/loader"
	"golang.org/x/tools/refactor/importgraph"
)

// Move, given a package path and a destination package path, will try
// to move the given package to the new path. The Move function will
// first check for any conflicts preventing the move, such as a
// package already existing at the destination package path. If the
// move can proceed, it builds an import graph to find all imports of
// the packages whose paths need to be renamed. This includes uses of
// the subpackages of the package to be moved as those packages will
// also need to be moved. It then renames all imports to point to the
// new paths, and then moves the packages to their new paths.
func Move(ctxt *build.Context, from, to, moveTmpl string) error {
	srcDir, err := srcDir(ctxt, from)
	if err != nil {
		return err
	}

	// This should be the only place in the program that constructs
	// file paths.
	// TODO(matloob): test on Microsoft Windows.
	fromDir := buildutil.JoinPath(ctxt, srcDir, filepath.FromSlash(from))
	toDir := buildutil.JoinPath(ctxt, srcDir, filepath.FromSlash(to))
	toParent := filepath.Dir(toDir)
	if !buildutil.IsDir(ctxt, toParent) {
		return fmt.Errorf("parent directory does not exist for path %s", toDir)
	}

	// Build the import graph and figure out which packages to update.
	fwd, rev, errors := importgraph.Build(ctxt)
	if len(errors) > 0 {
		fmt.Fprintf(os.Stderr, "While scanning Go workspace:\n")
		for path, err := range errors {
			fmt.Fprintf(os.Stderr, "Package %q: %s.\n", path, err)
		}
		return fmt.Errorf("failed to construct import graph")
	}

	// Determine the affected packages---the set of packages whose import
	// statements need updating.
	affectedPackages := map[string]bool{from: true}
	destinations := map[string]string{} // maps old dir to new dir
	for pkg := range subpackages(ctxt, srcDir, from) {
		for r := range rev[pkg] {
			affectedPackages[r] = true
		}
		destinations[pkg] = strings.Replace(pkg,
			// Ensure directories have a trailing "/".
			filepath.Join(from, ""), filepath.Join(to, ""), 1)
	}

	// Load all the affected packages.
	iprog, err := loadProgram(ctxt, affectedPackages)
	if err != nil {
		return err
	}

	// Prepare the move command, if one was supplied.
	var cmd string
	if moveTmpl != "" {
		if cmd, err = moveCmd(moveTmpl, fromDir, toDir); err != nil {
			return err
		}
	}

	m := mover{
		ctxt:             ctxt,
		fwd:              fwd,
		rev:              rev,
		iprog:            iprog,
		from:             from,
		to:               to,
		fromDir:          fromDir,
		toDir:            toDir,
		affectedPackages: affectedPackages,
		destinations:     destinations,
		cmd:              cmd,
	}

	if err := m.checkValid(); err != nil {
		return err
	}

	m.move()

	return nil
}

// srcDir returns the absolute path of the srcdir containing pkg.
func srcDir(ctxt *build.Context, pkg string) (string, error) {
	for _, srcDir := range ctxt.SrcDirs() {
		path := buildutil.JoinPath(ctxt, srcDir, pkg)
		if buildutil.IsDir(ctxt, path) {
			return srcDir, nil
		}
	}
	return "", fmt.Errorf("src dir not found for package: %s", pkg)
}

// subpackages returns the set of packages in the given srcDir whose
// import paths start with dir.
func subpackages(ctxt *build.Context, srcDir string, dir string) map[string]bool {
	subs := map[string]bool{dir: true}

	// Find all packages under srcDir whose import paths start with dir.
	buildutil.ForEachPackage(ctxt, func(pkg string, err error) {
		if err != nil {
			log.Fatalf("unexpected error in ForEachPackage: %v", err)
		}

		if !strings.HasPrefix(pkg, path.Join(dir, "")) {
			return
		}

		p, err := ctxt.Import(pkg, "", build.FindOnly)
		if err != nil {
			log.Fatalf("unexpected: package %s can not be located by build context: %s", pkg, err)
		}
		if p.SrcRoot == "" {
			log.Fatalf("unexpected: could not determine srcDir for package %s: %s", pkg, err)
		}
		if p.SrcRoot != srcDir {
			return
		}

		subs[pkg] = true
	})

	return subs
}

type mover struct {
	// iprog contains all packages whose contents need to be updated
	// with new package names or import paths.
	iprog *loader.Program
	ctxt  *build.Context
	// fwd and rev are the forward and reverse import graphs
	fwd, rev importgraph.Graph
	// from and to are the source and destination import
	// paths. fromDir and toDir are the source and destination
	// absolute paths that package source files will be moved between.
	from, to, fromDir, toDir string
	// affectedPackages is the set of all packages whose contents need
	// to be updated to reflect new package names or import paths.
	affectedPackages map[string]bool
	// destinations maps each subpackage to be moved to its
	// destination path.
	destinations map[string]string
	// cmd, if not empty, will be executed to move fromDir to toDir.
	cmd string
}

func (m *mover) checkValid() error {
	const prefix = "invalid move destination"

	match, err := regexp.MatchString("^[_\\pL][_\\pL\\p{Nd}]*$", path.Base(m.to))
	if err != nil {
		panic("regexp.MatchString failed")
	}
	if !match {
		return fmt.Errorf("%s: %s; gomvpkg does not support move destinations "+
			"whose base names are not valid go identifiers", prefix, m.to)
	}

	if buildutil.FileExists(m.ctxt, m.toDir) {
		return fmt.Errorf("%s: %s conflicts with file %s", prefix, m.to, m.toDir)
	}
	if buildutil.IsDir(m.ctxt, m.toDir) {
		return fmt.Errorf("%s: %s conflicts with directory %s", prefix, m.to, m.toDir)
	}

	for _, toSubPkg := range m.destinations {
		if _, err := m.ctxt.Import(toSubPkg, "", build.FindOnly); err == nil {
			return fmt.Errorf("%s: %s; package or subpackage %s already exists",
				prefix, m.to, toSubPkg)
		}
	}

	return nil
}

// moveCmd produces the version control move command used to move fromDir to toDir by
// executing the given template.
func moveCmd(moveTmpl, fromDir, toDir string) (string, error) {
	tmpl, err := template.New("movecmd").Parse(moveTmpl)
	if err != nil {
		return "", err
	}

	var buf bytes.Buffer
	err = tmpl.Execute(&buf, struct {
		Src string
		Dst string
	}{fromDir, toDir})
	return buf.String(), err
}

func (m *mover) move() error {
	filesToUpdate := make(map[*ast.File]bool)

	// Change the moved package's "package" declaration to its new base name.
	pkg, ok := m.iprog.Imported[m.from]
	if !ok {
		log.Fatalf("unexpected: package %s is not in import map", m.from)
	}
	newName := filepath.Base(m.to)
	for _, f := range pkg.Files {
		f.Name.Name = newName // change package decl
		filesToUpdate[f] = true
	}
	// Update imports of that package to use the new import name.
	// None of the subpackages will change their name---only the from package
	// itself will.
	for p := range m.rev[m.from] {
		if err := importName(m.iprog, m.iprog.Imported[p], m.from, path.Base(m.from), newName); err != nil {
			return err
		}
	}

	// Update import paths for all imports by affected packages.
	for ap := range m.affectedPackages {
		info, ok := m.iprog.Imported[ap]
		if !ok {
			log.Fatalf("unexpected: package %s is not in import map", ap)
		}
		for _, f := range info.Files {
			for _, imp := range f.Imports {
				importPath, _ := strconv.Unquote(imp.Path.Value)
				if newPath, ok := m.destinations[importPath]; ok {
					imp.Path.Value = strconv.Quote(newPath)

					oldName := path.Base(importPath)
					if imp.Name != nil {
						oldName = imp.Name.Name
					}

					newName := path.Base(newPath)
					if imp.Name == nil && oldName != newName {
						imp.Name = ast.NewIdent(oldName)
					} else if imp.Name == nil || imp.Name.Name == newName {
						imp.Name = nil
					}
					filesToUpdate[f] = true
				}
			}
		}
	}

	for f := range filesToUpdate {
		tokenFile := m.iprog.Fset.File(f.Pos())
		rewriteFile(m.iprog.Fset, f, tokenFile.Name())
	}

	// Move the directories.
	// If either the fromDir or toDir are contained under version control it is
	// the user's responsibility to provide a custom move command that updates
	// version control to reflect the move.
	// TODO(matloob): If the parent directory of toDir does not exist, create it.
	//      For now, it's required that it does exist.

	if m.cmd != "" {
		// TODO(matloob): Verify that the windows and plan9 cases are correct.
		var cmd *exec.Cmd
		switch runtime.GOOS {
		case "windows":
			cmd = exec.Command("cmd", "/c", m.cmd)
		case "plan9":
			cmd = exec.Command("rc", "-c", m.cmd)
		default:
			cmd = exec.Command("sh", "-c", m.cmd)
		}
		cmd.Stderr = os.Stderr
		cmd.Stdout = os.Stdout
		if err := cmd.Run(); err != nil {
			return fmt.Errorf("version control system's move command failed: %v", err)
		}

		return nil
	}

	return moveDirectory(m.fromDir, m.toDir)
}

var moveDirectory = func(from, to string) error {
	return os.Rename(from, to)
}


text:
function Command(body){
	this.body = body;
	this.header = {
		tried: 0
		, endpoint: {port: 8126, host:'localhost'}
		, retries: 3
		, name: 'Message'
		, token: null
		, id: (new Date()).getTime()
	};
	this.type = 'command';
}
function AddMember(member){
	Command.apply(this, [member]);
	this.header.name = 'AddMember';
}
function UpdateMember(member){
	Command.apply(this, [member]);
	this.header.name = 'UpdateMember';
}

function DeleteMember(member){
	Command.apply(this, [member]);
	this.header.name = 'DeleteMember';
}
function ChangeAvatar(member){
	Command.apply(this, [member]);
	this.header.name = 'ChangeAvatar';
}

function ChangeBackground(member){
	Command.apply(this, [member]);
	this.header.name = 'ChangeBackground';
}
function NewMessage(message){
	Command.apply(this, [message]);
	this.header.name = 'NewMessage';
}
module.exports = {
	AddMember: AddMember
	, UpdateMember: UpdateMember
	, DeleteMember: DeleteMember
	, ChangeAvatar: ChangeAvatar
	, ChangeBackground: ChangeBackground
	, NewMessage: NewMessage
	, Command: Command
};


text:
%
% ObjVal = tspfun(Phen, Dist)
% Implementation of the TSP fitness function
%	Phen contains the phenocode of the matrix coded in adjacency
%	representation
%	Dist is the matrix with precalculated distances between each pair of cities
%	ObjVal is a vector with the fitness values for each candidate tour (=each row of Phen)
%

function ObjVal = tspfun(Phen, Dist)
	ObjVal=Dist(Phen(:,1),1);
	for t=2:size(Phen,2)
    	ObjVal=ObjVal+Dist(Phen(:,t),t);
    end
end


text:
require 'test_helper'
include Dateable

describe Dateable, 'days_till' do

  it 'calculate days till for this year' do
    date = Date.today + 10.days

    days_till(date).must_equal 10
  end

  it "calculates days till for next year" do
    date = Date.today + 1.year + 5.days

    days_till(date).must_equal 370
  end
end

describe Dateable, 'months_back' do
  it "finds the date n months back" do
    month_back(2).must_equal(Date.today.beginning_of_month - 2.months)
    month_back(13).must_equal(Date.today.beginning_of_month - 13.months)
  end
end


text:
package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.core.Fixtures;
import edu.northwestern.bioinformatics.studycalendar.core.StudyCalendarXmlTestCase;
import edu.northwestern.bioinformatics.studycalendar.domain.Activity;
import edu.northwestern.bioinformatics.studycalendar.domain.ActivityProperty;
import edu.northwestern.bioinformatics.studycalendar.xml.XsdElement;
import org.dom4j.Element;

import static edu.northwestern.bioinformatics.studycalendar.core.Fixtures.*;
import static edu.northwestern.bioinformatics.studycalendar.xml.XsdAttribute.*;

/**
 * @author Jalpa Patel
 */
public class ActivityPropertyXmlSerializerTest   extends StudyCalendarXmlTestCase {
    private ActivityPropertyXmlSerializer activityPropertyXmlSerializer;
    private ActivityProperty activityProperty;
    private Activity activity;
    private final String namespace = "URI";

    @Override
    protected void setUp() throws Exception {
           super.setUp();
           activity = setId(20, createActivity("Bone Scan"));
           activityProperty =  Fixtures.createActivityProperty(activity, namespace ,"id.template" ,"templateValue");
           activityPropertyXmlSerializer = new ActivityPropertyXmlSerializer();
       }

    public void testCreateElement() throws Exception {
           Element actual =   activityPropertyXmlSerializer.createElement(activityProperty);
           assertEquals("Wrong element name", XsdElement.ACTIVITY_PROPERTY.xmlName(), actual.getName());
           assertEquals("Should have no children", 0, actual.elements().size());
           assertEquals("Wrong property namespace", activityProperty.getNamespace(), ACTIVITY_PROPERTY_NAMESPACE.from(actual));
           assertEquals("Wrong property name", activityProperty.getName(), PROPERTY_NAME.from(actual));
           assertEquals("Wrong property value", activityProperty.getValue(), PROPERTY_VALUE.from(actual));

    }

    public void testReadElement() throws Exception {
           Element actual = XsdElement.ACTIVITY_PROPERTY.create();
           ACTIVITY_PROPERTY_NAMESPACE.addTo(actual,"URI");
           PROPERTY_NAME.addTo(actual,"id.template");
           PROPERTY_VALUE.addTo(actual,"templateValue");

           ActivityProperty read = activityPropertyXmlSerializer.readElement(actual);

           assertNotNull(read);
           assertNull(read.getId());
           assertEquals(null, read.getGridId());
           assertEquals("Wrong property namespace", "URI", read.getNamespace());
           assertEquals("Wrong property name", "id.template", read.getName());
           assertEquals("Wrong property value", "templateValue", read.getValue());
    }
}


text:
'use strict';

const colName = 'batch';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.addColumn('PaymentMethods', colName, {
      type: Sequelize.STRING,
      allowNull: true,
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.removeColumn('PaymentMethods', colName);
  },
};


text:
/**
 *
 */
package models;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * user : yonatan

 * update date : Jun 20, 2015

 * update by : Yonatan Alexis Quintero Rodriguez

 *
 * @created : Jun 20, 2015

 * @version : 0.1

 * @author Yonatan Alexis Quintero Rodriguez
 *
 */
public class Group {

	private int id;
	private String name;
	private int creationYear;
	private LocalDateTime starDate;
	private LocalDateTime expirationDate;
	private List<Collection> collections;
	private Collection collection;

	public Group(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public Group() {
		// TODO Auto-generated constructor stub
	}

	public Group(int id) {
		this.id = id;
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the creationYear
	 */
	public int getCreationYear() {
		return creationYear;
	}

	/**
	 * @param creationYear
	 *            the creationYear to set
	 */
	public void setCreationYear(int creationYear) {
		this.creationYear = creationYear;
	}

	/**
	 * @return the starDate
	 */
	public LocalDateTime getStarDate() {
		return starDate;
	}

	/**
	 * @param starDate
	 *            the starDate to set
	 */
	public void setStarDate(LocalDateTime starDate) {
		this.starDate = starDate;
	}

	/**
	 * @return the expirationDate
	 */
	public LocalDateTime getExpirationDate() {
		return expirationDate;
	}

	/**
	 * @param expirationDate
	 *            the expirationDate to set
	 */
	public void setExpirationDate(LocalDateTime expirationDate) {
		this.expirationDate = expirationDate;
	}

	/**
	 * @return the collections
	 */
	public List<Collection> getCollections() {
		return collections;
	}

	/**
	 * @param collections
	 *            the collections to set
	 */
	public void setCollections(List<Collection> collections) {
		this.collections = collections;
	}

	public Collection getCollection() {
		return collection;
	}

	public void setCollection(Collection collection) {
		this.collection = collection;
	}

	public void createCollection(int totalRows) {
		collections = new ArrayList<Collection>();
		for (int i = 0; i < totalRows + 1; i++) {
			collections.add(new Collection(0, i));
		}
	}

}


text:
<!DOCTYPE html>

  <title>Opera Extensions API Documentation</title>
  <link rel='stylesheet' href='../resources/markdown8.css'/>
  <meta charset='utf-8'>
  <meta charset='utf-8'>

« Documentation Home

Button.badge

This documentation relates to Opera's now deprecated .oex Extension API framework for Opera versions <= 12.15 and also provided by our OEX2NEX shim library.

For the latest Opera Extensions API documentation for Opera versions > 12.15 please consult the latest Opera Extensions API documentation online.

Description

This property represents the Badge for the button.

Example:

You can reference and update the badge properties directly from the button object (e.g. button.badge.textContent = 42) or through the badge object.

//
// The background process (e.g. index.html)
//

// Create a button
var button = opera.contexts.toolbar.createItem({
  title:'My Extension',
  icon:'icon.18x18.png',
  badge: {}
});

// Add it to the browser UI
opera.contexts.toolbar.addItem(button);

// Set the badge and the font colors
var badge = button.badge;
badge.backgroundColor = '#5566ff';
badge.color = "#ffffff";

// Update badge properties directly through the button object
button.badge.textContent = 42;

// Get the background color?
var badgeColor = button.badge.backgroundColor; // this was set to '#5566ff' above


text:
#import <Foundation/Foundation.h>
#import "TOCFutureAndSource.h"
#import "TOCTypeDefs.h"
#import "TOCTimeout.h"

@interface TOCFuture (MoreConstructors)

/*!
 * Returns a future that has already failed with a timeout failure.
 *
 * A timeout failure is just an instance of TOCTimeout.
 */
+(TOCFuture*) futureWithTimeoutFailure;

/*!
 * Returns a future that has already failed with a cancellation failure.
 *
 * A cancellation failure is just an instance of TOCCancelToken.
 */
+(TOCFuture*) futureWithCancelFailure;

/*!
 * Returns a future that completes with the value returned by a function run via grand central dispatch.
 *
 * @param operation The operation to eventually evaluate.
 *
 * @param queue The gcd queue to dispatch the operation on.
 *
 * @result A future that completes once the operation has been completed, and contains the operation's result.
 */
+(TOCFuture*) futureFromOperation:(id (^)(void))operation
                dispatchedOnQueue:(dispatch_queue_t)queue;

/*!
 * Returns a future that completes with the value returned by a function run on a specified thread.
 *
 * @param operation The operation to eventually evaluate.
 *
 * @param thread The thread to perform the operation on.
 *
 * @result A future that completes once the operation has been completed, and contains the operation's result.
 */
+(TOCFuture*) futureFromOperation:(id(^)(void))operation
                  invokedOnThread:(NSThread*)thread;

/*!
 * Returns a future that will contain the given result after the given delay, unless cancelled.
 *
 * @param resultValue The value the resulting future should complete with, after the delay has passed.
 *
 * @param delayInSeconds The amount of time to wait, in seconds, before the resulting future completes.
 * Must not be negative or NaN (raises exception).
 * A delay of 0 results in a future that's already completed.
 * A delay of INFINITY result in an immortal future that never completes.
 *
 * @param unlessCancelledToken If this token is cancelled before the delay expires, the future immediately fails with the cancel token as its failure.
 * Any resources being used for the delay, such as NSTimers, will also be immediately cleaned up upon cancellation.
 *
 * @result A delayed future result, unless the delay is cancelled.
 */
+(TOCFuture*) futureWithResult:(id)resultValue
                    afterDelay:(NSTimeInterval)delayInSeconds
                        unless:(TOCCancelToken*)unlessCancelledToken;

/*!
 * Returns a future that will contain the given result after the given delay.
 *
 * @param resultValue The value the resulting future should complete with, after the delay has passed.
 *
 * @param delayInSeconds The amount of time to wait, in seconds, before the resulting future completes.
 * Must not be negative or NaN (raises exception).
 * A delay of 0 results in a future that's already completed.
 * A delay of INFINITY result in an immortal future that never completes.
 *
 * @result A delayed future result.
 */
+(TOCFuture*) futureWithResult:(id)resultValue
                    afterDelay:(NSTimeInterval)delayInSeconds;

/*!
 * Returns a future that eventually contains the result, which lasts until the given token is cancelled, of an asynchronous operation as long as it completes before the given timeout.
 *
 * @param asyncOperationWithResultLastingUntilCancelled The asynchronous operation to evaluate.
 *
 * @param timeoutPeriodInSeconds The amount of time, in seconds, the asynchronous operation is given to finish before it is cancelled.
 * Must not be negative or NaN (raises exception).
 * A delay of 0 results in an immediate timeout failure without the operation even being run.
 * A delay of INFINITY results in the operation being run without a timeout.
 *
 * @param untilCancelledToken The operation, and its results, are cancelled when this token is cancelled.
 *
 * @result The eventual result of the asynchronous operation, unless the operation is cancelled or times out.
 *
 * @discussion If the operation has not yet completed when the untilCancelledToken is cancelled, the operation is immediately cancelled.
 *
 * If the operation has already completed when the untilCancelledToken is cancelled, its result is terminated / cleaned-up / dead.
 */
+(TOCFuture*) futureFromUntilOperation:(TOCUntilOperation)asyncOperationWithResultLastingUntilCancelled
                  withOperationTimeout:(NSTimeInterval)timeoutPeriodInSeconds
                                 until:(TOCCancelToken*)untilCancelledToken;

/*!
 * Returns a future for the eventual result of an asynchronous operation, unless the operation times out or is cancelled.
 *
 * @param asyncCancellableOperation The cancellable asynchronous operation to evaluate.
 *
 * @param timeoutPeriodInSeconds The amount of time, in seconds, the asynchronous operation is given to finish before it is cancelled due to a timeout.
 * Must not be negative or NaN (raises exception).
 * A delay of 0 results in an immediate timeout failure without the operation even being run.
 * A delay of INFINITY results in the operation being run without a timeout.
 *
 * @param unlessCancelledToken Cancelling this token will cancel the asynchronous operation, unless it has already finished.
 *
 * @result The eventual result of the asynchronous operation, or else a timeout or cancellation failure.
 *
 * @discussion If the operation times out, the resulting future fails with an instance of TOCTimeout as its failure.
 *
 * If the operation is cancelled, the resulting future fails with a cancel.
 *
 * If the operation finishes without being cancelled, the resulting future will match it.
 *
 * This method is unable to forward its result before the given asynchronous operation confirms it was cancelled (by cancelling the future it returned).
 * Otherwise it would be possible to leak a result that needed to be cleaned up, due to the operation's completion racing with timing out.
 */
+(TOCFuture*) futureFromUnlessOperation:(TOCUnlessOperation)asyncCancellableOperation
                            withTimeout:(NSTimeInterval)timeoutPeriodInSeconds
                                 unless:(TOCCancelToken*)unlessCancelledToken;

/*!
 * Returns a future for the eventual result of an asynchronous operation, unless the operation times out.
 *
 * @param asyncCancellableOperation The cancellable asynchronous operation to evaluate.
 *
 * @param timeoutPeriodInSeconds The amount of time, in seconds, the asynchronous operation is given to finish before it is cancelled due to a timeout.
 * Must not be negative or NaN (raises exception).
 * A delay of 0 results in an immediate timeout failure without the operation even being run.
 * A delay of INFINITY results in the operation being run without a timeout.
 *
 * @result The eventual result of the asynchronous operation, or else a timeout failure.
 *
 * @discussion If the operation times out, the resulting future fails with an instance of TOCTimeout as its failure.
 *
 * If the operation finishes without timing out or acknowledging the timeout, the resulting future will match it.
 *
 * This method is unable to forward its result before the given asynchronous operation confirms it was cancelled due to the timeout (by cancelling the future it returned).
 * Otherwise it would be possible to leak a result that needed to be cleaned up, due to the operation's completion racing with timing out.
 */
+(TOCFuture*) futureFromUnlessOperation:(TOCUnlessOperation)asyncCancellableOperation
                            withTimeout:(NSTimeInterval)timeoutPeriodInSeconds;

@end


text:
package ru.qatools.properties;

import ru.qatools.properties.converters.Converter;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Using this annotation you can override default converter
 * for property.
 *
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 05.05.15
 */
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.FIELD, ElementType.METHOD})
public @interface Use {

    Class<? extends Converter> value();
}


text:
require_relative 'test_helper'

class MachineWithDirtyAttributesAndCustomAttributeTest < BaseTestCase
  def setup
    @model = new_model do
      include ActiveModel::Dirty
      model_attribute :status
      define_attribute_methods [:status]
    end
    @machine = StateMachines::Machine.new(@model, :status, initial: :parked)
    @machine.event :ignite
    @machine.state :idling

    @record = @model.create

    @transition = StateMachines::Transition.new(@record, @machine, :ignite, :parked, :idling)
    @transition.perform
  end

  def test_should_include_state_in_changed_attributes
    assert_equal %w(status), @record.changed
  end

  def test_should_track_attribute_change
    assert_equal %w(parked idling), @record.changes['status']
  end

  def test_should_not_reset_changes_on_multiple_transitions
    transition = StateMachines::Transition.new(@record, @machine, :ignite, :idling, :idling)
    transition.perform

    assert_equal %w(parked idling), @record.changes['status']
  end
end


text:
import * as types from './types'
import axios from 'axios'
import { isMemory } from '@/assets/scripts/utils/memory'

export const state = {
  result: null
}

const jsonCache = {}
const urlCache = {}

export const mutations = {
  [types.VALIDATOR_SET] (state, payload) {
    state.result = payload
  }
}

let lastUrl = null
let lastJson = null

export const actions = {
  [types.VALIDATOR_RUN] ({commit}, {url, json}) {
    if (url && urlCache[url]) {
      commit(types.VALIDATOR_SET, urlCache[url])
      return
    } else if (json && jsonCache[json]) {
      commit(types.VALIDATOR_SET, jsonCache[json])
      return
    }

    commit(types.VALIDATOR_SET, null)

    if (url && !isMemory(url)) {
      lastUrl = url
      lastJson = null

      axios.get('https://online.swagger.io/validator/debug', {
        params: {url}
        // ,
        // onDownloadProgress: event => {
        //   console.log(event.lengthComputable, event.loaded, event.total)
        // },
        // onUploadProgress: event => {
        //   console.log('up', event.lengthComputable, event.loaded, event.total)
        // }
      }).then(res => {
        urlCache[url] = res.data

        if (lastUrl === url) {
          commit(types.VALIDATOR_SET, res.data)
        }
      })
    } else {
      lastUrl = null
      lastJson = json

      axios.post('https://online.swagger.io/validator/debug', json
      // , {
      //   onDownloadProgress: event => {
      //     console.log(event.lengthComputable, event.loaded, event.total)
      //   },
      //   onUploadProgress: event => {
      //     console.log('up', event.lengthComputable, event.loaded, event.total)
      //   }
      // }
      ).then(res => {
        jsonCache[json] = res.data

        if (lastJson === json) {
          commit(types.VALIDATOR_SET, res.data)
        }
      })
    }
  }
}

export const getters = {
  [types.VALIDATOR]: (state) => state.result
}

export default {
  state,
  mutations,
  getters,
  actions
}


text:
title: "Raspbian and Chef-Client"
excerpt: "Bootstrapping Raspbian disk image with Chef client"
tags: [pi, xig, chef]
article_header:
  type: cover
  image:
    src: /assets/images/sample-image-2.jpg
date: 2015-01-25T07:58:34-08:00
comments: true
---

Here are the high level steps I followed to install the chef client on the Pi, and also create a disk image that contained the base os with the chef client pre-installed.

These instructions are largely OSX specific.

#### Transfer the Raspbian disk image to the SD card
1. Run `diskutil` to determine where your SD Card device (I ran it before inserting the card, and after inserting, so I was confident I knew which device I was about to write over).
1. Run `diskutil unmountDisk /dev/disk1` to unmount your SD Card (if that is indeed your device)
1. Transfer the Raspbian image you've downloaded to the SD Card:
```
sudo dd bs=1m if=~/Downloads/2014-12-24-wheezy-raspbian.img of=/dev/disk1
```

This can take some time, so be patient, you should see activity on the SD Card reader... Blink Blink.

Once complete, boot the Pi, and don't do anything else, you want to keep the image factory fresh, and add the Chef client. You are now ready to install the Chef client.

#### Installing the Chef Client using 'Knife'
1. Install knife-solo gem:
```
gem install knife-solo
```
1. Ensure your Pi is booted with the base image you want to update
1. Install the Chef Client on your Pi:
```
knife solo prepare pi@your_pi_ip
```

This will take some time as it's got do download a fair bit from the internet. Once complete though, you will have a chef client installed on the Pi you can use to run your Cookbooks. More on that later.

* Power off the Pi.

#### Create a new disk image
1. Take the SD card from the PI and plug it into your desktop computer
1. Identify the device again using the diskutil steps from above
1. Unmount the device
1. Use `dd` to create your new image:

~~~
sudo dd bs=1m if=/dev/disk1 of=~/Downloads/2014-12-24-wheezy-chef-11-raspbian.img
~~~


text:
package uk.ac.cam.caret.sakai.rwiki.utils;

import java.text.MessageFormat;

import lombok.extern.slf4j.Slf4j;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

/**
 * Proxyis a content handler providing a debug output to stdout, not for
 * production use
 *
 * @author ieb
 */
@Slf4j
public class DebugContentHandler implements ContentHandler
{

	private ContentHandler ch = null;

	public DebugContentHandler(ContentHandler ch)
	{
		this.ch = ch;
	}

	public void setDocumentLocator(Locator arg0)
	{
		ch.setDocumentLocator(arg0);
	}

	public void startDocument() throws SAXException
	{
		ch.startDocument();
	}

	public void endDocument() throws SAXException
	{
		ch.endDocument();
	}

	public void startPrefixMapping(String arg0, String arg1)
			throws SAXException
	{
		ch.startPrefixMapping(arg0, arg1);
	}

	public void endPrefixMapping(String arg0) throws SAXException
	{
		ch.endPrefixMapping(arg0);
	}

	public void startElement(String arg0, String arg1, String arg2,
			Attributes arg3) throws SAXException
	{
		log.info(MessageFormat.format("<{0} {1} {2} >", new Object[] {
				arg0, arg1, arg2 }));
		ch.startElement(arg0, arg1, arg2, arg3);
	}

	public void endElement(String arg0, String arg1, String arg2)
			throws SAXException
	{
		log.info(MessageFormat.format("</{0} {1} {2} >",
				new Object[] { arg0, arg1, arg2 }));
		ch.endElement(arg0, arg1, arg2);
	}

	public void characters(char[] arg0, int arg1, int arg2) throws SAXException
	{
		log.info(String.valueOf(arg0, arg1, arg2));
		ch.characters(arg0, arg1, arg2);
	}

	public void ignorableWhitespace(char[] arg0, int arg1, int arg2)
			throws SAXException
	{
		log.info(String.valueOf(arg0, arg1, arg2));
		ch.ignorableWhitespace(arg0, arg1, arg2);
	}

	public void processingInstruction(String arg0, String arg1)
			throws SAXException
	{
		log.info(MessageFormat.format("<? {0} {1} ?>", new Object[] {
				arg0, arg1 }));
		ch.processingInstruction(arg0, arg1);
	}

	public void skippedEntity(String arg0) throws SAXException
	{
		ch.skippedEntity(arg0);
	}

}


text:
package swift_test

import (
	"context"
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/restic/restic/internal/errors"
	"github.com/restic/restic/internal/restic"
	. "github.com/restic/restic/internal/test"

	"github.com/restic/restic/internal/backend/swift"
	"github.com/restic/restic/internal/backend/test"
)

func newSwiftTestSuite(t testing.TB) *test.Suite {
	return &test.Suite{
		// do not use excessive data
		MinimalData: true,

		// wait for removals for at least 60s
		WaitForDelayedRemoval: 60 * time.Second,

		// NewConfig returns a config for a new temporary backend that will be used in tests.
		NewConfig: func() (interface{}, error) {
			swiftcfg, err := swift.ParseConfig(os.Getenv("RESTIC_TEST_SWIFT"))
			if err != nil {
				return nil, err
			}

			cfg := swiftcfg.(swift.Config)
			if err = swift.ApplyEnvironment("RESTIC_TEST_", &cfg); err != nil {
				return nil, err
			}
			cfg.Prefix += fmt.Sprintf("/test-%d", time.Now().UnixNano())
			t.Logf("using prefix %v", cfg.Prefix)
			return cfg, nil
		},

		// CreateFn is a function that creates a temporary repository for the tests.
		Create: func(config interface{}) (restic.Backend, error) {
			cfg := config.(swift.Config)

			be, err := swift.Open(cfg)
			if err != nil {
				return nil, err
			}

			exists, err := be.Test(context.TODO(), restic.Handle{Type: restic.ConfigFile})
			if err != nil {
				return nil, err
			}

			if exists {
				return nil, errors.New("config already exists")
			}

			return be, nil
		},

		// OpenFn is a function that opens a previously created temporary repository.
		Open: func(config interface{}) (restic.Backend, error) {
			cfg := config.(swift.Config)
			return swift.Open(cfg)
		},

		// CleanupFn removes data created during the tests.
		Cleanup: func(config interface{}) error {
			cfg := config.(swift.Config)

			be, err := swift.Open(cfg)
			if err != nil {
				return err
			}

			if err := be.(restic.Deleter).Delete(context.TODO()); err != nil {
				return err
			}

			return nil
		},
	}
}

func TestBackendSwift(t *testing.T) {
	defer func() {
		if t.Skipped() {
			SkipDisallowed(t, "restic/backend/swift.TestBackendSwift")
		}
	}()

	if os.Getenv("RESTIC_TEST_SWIFT") == "" {
		t.Skip("RESTIC_TEST_SWIFT unset, skipping test")
		return
	}

	t.Logf("run tests")
	newSwiftTestSuite(t).RunTests(t)
}

func BenchmarkBackendSwift(t *testing.B) {
	if os.Getenv("RESTIC_TEST_SWIFT") == "" {
		t.Skip("RESTIC_TEST_SWIFT unset, skipping test")
		return
	}

	t.Logf("run tests")
	newSwiftTestSuite(t).RunBenchmarks(t)
}


text:
package com.skyrocketgwt.core.client.widgets;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.text.client.IntegerParser;
import com.google.gwt.text.client.IntegerRenderer;
import com.skyrocketgwt.core.client.widgets.appearance.DefaultSkyTextBoxAppearance;
import com.skyrocketgwt.core.client.widgets.appearance.SkyValueBoxBaseAppearance;

/**
 * A SkyValueBox that uses {@link IntegerParser} and {@link IntegerRenderer}.
 */
public class SkyIntegerBox extends SkyValueBox<Integer> {

  public SkyIntegerBox() {
    this((SkyValueBoxBaseAppearance)GWT.create(DefaultSkyTextBoxAppearance.class));
  }

  public SkyIntegerBox(SkyValueBoxBaseAppearance appearance) {
	super(appearance, IntegerRenderer.instance(), IntegerParser.instance());

	/*if (enableLegacyStyling) {
	  addStyleName("gwt-TextBox");
	}*/
  }
}


text:
L'objectif de cet exercice est de créer et soumettre un formulaire.

Pour cela, je vous fourni un template déjà intégré sur lequel il faut se baser : [le template](./template.zip)

> un code soigné et parfaitement indenté sera grandement apprécié.

Le projet est à mettre sur github.
Envoyez moi ensuite le lien par email, avec nom/prénom et jusqu'où vous êtes arrivés.

### Première partie

Etape par étape, il faut :

- installer un nouveau projet Symfony (si vous ne pouvez sur votre machine, voici le lien d'un [Symfony avec vendor](../../symfony%20download/symfony5.zip)).

- récupérer le template et l'intégrer dans votre projet symfony (controller et view)

> Il n'y a qu'une seule page, la page d'accueil

> Pour les assets, pas besoin d'utiliser Webpack ou Gulp, vous pouvez mettre les fichiers css et js directement dans public.

> (BONUS) Il sera bien vu d'avoir découpé et structuré le template en base > layout > view

- créer une `entity` qui contiendra les champs de votre formulaire.

- créer le formulaire correspondant (class et view) pour ne plus avoir de formulaire en dur dans votre vue.

- faire en sorte que le formulaire puisse être soumis (manière classique pour le moment : button submit, POST, et rechargement de la page)

- les données doivent être enregistrées en BDD

- ajouter les contraintes de validation sur les champs du formulaire
    - civilité doit être 0, 1 ou -1
    - lastname est une chaine de caractères comprise entre 2 et 50 caractères.
    - firstname est une chaine de caractères comprise entre 2 et 50 caractères.
    - email doit être formater comme un email
    - téléphone est une chaine de caractères comprise entre 10 et 13 caractères, contenant des chiffres et optionnellement un + au début
    - newsletter est un boolean pouvant être null

- votre formulaire doit afficher les messages d'erreur

La première partie de l'exercice est terminée. Vous vous assurez une note au dessus de la moyenne en arrivant ici, les bases de Symfony vous sont acquises.

### Deuxième partie

Pour la 2e partie, nous allons ajouter une couche de JavaScript à tout ça, pour soumettre le formualaire en Ajax.

> jQuery est inclu dans le projet, vous pouvez donc l'utiliser et/ou ajouter des plugins.

A présent, il faut :

- bloquer la validation classique du formulaire, via JavaScript (petite piste : `onSubmit` et `event.preventDefault`)

- en JS, récupérer les données du formulaire (...`serialize`...) et les mettres dans une variable.

- en JS, soumettre les données du formulaire sur une action de controller spécifique.

> Pensez simple ici, ce que je vous demande n'est pas très compliqué. Si vous l'abordé de façon complexe, vous avez surement faux.

> Petite piste en js : `$.ajax`

> Petite piste côté controller SF :
> - Pensez à désactiver le CSRF Token (l'ajax ne permet pas d'utiliser cette protection)
> - Votre controller Ajax sera très similaire au controller classique, `$form->isSubmitted` en moins
> - `new JsonResponse`...

- en cas de validation, le controller doit renvoyer 'ok' (code http 200), le JS doit afficher un message à l'utilisateur en front et reset le formulaire.

- en cas d'erreur de validation, la JsonResponse doit renvoyer la liste des erreurs de soumissions.

> L'object `$form` dans votre controller contient cette liste d'erreurs, un `dump($form)` peut être salvateur ici.

- en JS, afficher les erreurs du form

> (BONUS) Si les erreurs sont affichées sous le champ associé (et pas toutes regroupées au même endroit), cela fera des points en plus.

La 2e partie est maintenant terminée. Bravo !

### Bonus

Point bonus, faire en sorte que les messages des contraintes de validation soient inscrits dans des fichiers de traductions.

### Rendu

Le projet est à mettre sur github.
Envoyez moi ensuite le lien par email, avec nom/prénom et jusqu'où vous êtes arrivés.

Bonne continuation à tous.


text:
//
//  ChatFriendSetViewController.h
//  Connect
//
//  Created by MoHuilin on 16/7/14.
//  Copyright © 2016年 Connect.  All rights reserved.
//

#import "BaseSetViewController.h"

@interface ChatFriendSetViewController : BaseSetViewController

/**
 *  init
 *
 *  @return
 */
- (instancetype)initWithMembersArrary:(NSArray *)members talkid:(NSString *)talkid;

@end


text:
package org.lwjgl.opengles;

public interface ARB_texture_rectangle {

	/**
	 * Accepted by the <cap> parameter of Enable, Disable and IsEnabled;
	 * by the <pname> parameter of GetBooleanv, GetIntegerv, GetFloatv
	 * and GetDoublev; and by the <target> parameter of BindTexture,
	 * GetTexParameterfv, GetTexParameteriv, TexParameterf, TexParameteri,
	 * TexParameterfv and TexParameteriv:
	 * Accepted by the <target> parameter of GetTexImage,
	 * GetTexLevelParameteriv, GetTexLevelParameterfv, TexImage2D,
	 * CopyTexImage2D, TexSubImage2D and CopySubTexImage2D:
	 */
	int GL_TEXTURE_RECTANGLE_ARB = 0x84F5;

	/**
	 * Accepted by the <pname> parameter of GetBooleanv, GetIntegerv,
	 * GetFloatv and GetDoublev:
	 */
	int GL_TEXTURE_BINDING_RECTANGLE_ARB = 0x84F6;

	/**
	 * Accepted by the <target> parameter of GetTexLevelParameteriv,
	 * GetTexLevelParameterfv, GetTexParameteriv and TexImage2D:
	 */
	int GL_PROXY_TEXTURE_RECTANGLE_ARB = 0x84F7;

	/**
	 * Accepted by the <pname> parameter of GetBooleanv, GetDoublev,
	 * GetIntegerv and GetFloatv:
	 */
	int GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB = 0x84F8;

	/**
	 * Returned by <type> parameter of GetActiveUniform when the location
	 * <index> for program object <program> is of type sampler2DRect:
	 */
	int GL_SAMPLER_2D_RECT_ARB = 0x8B63;

	/**
	 * Returned by <type> parameter of GetActiveUniform when the location
	 * <index> for program object <program> is of type sampler2DRectShadow:
	 */
	int GL_SAMPLER_2D_RECT_SHADOW_ARB = 0x8B64;

}


text:
def extractTurtleandHareTranslations(item):
	"""

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None
	if 'Time (对的时间对的人)' in item['title'] or 'Time (对的时间对的人)' in item['tags']:
		return buildReleaseMessageWithType(item, 'Time', vol, chp, frag=frag, postfix=postfix)
	return False


text:
import hashlib

from anchore_engine.db import AnalysisArtifact
from anchore_engine.services.policy_engine.engine.policy.gate import BaseTrigger, Gate
from anchore_engine.utils import ensure_bytes, ensure_str

MALWARE_CONTEXT_KEY = "malware_scans"

class ScanFindingsTrigger(BaseTrigger):
    __trigger_name__ = "scans"
    __description__ = (
        "Triggers if any malware scanner has found any matches in the image."
    )

    @staticmethod
    def _trigger_id(scanner, file, signature):
        """
        Trigger id is a string, but encoded as scanner name, signature, and m5hash of the file path (to keep size within reasonable bounds)
        :param scanner:
        :param file:
        :param signature:
        :return:
        """
        return "{}+{}+{}".format(
            scanner,
            signature,
            ensure_str(
                hashlib.new(
                    "md5", ensure_bytes(file), usedforsecurity=False
                ).hexdigest()
            ),
        )

    def evaluate(self, image_obj, context):
        try:
            scans = context.data[MALWARE_CONTEXT_KEY]
        except KeyError:
            scans = {}

        for scanner, scan in scans.items():
            scan_name = scan.get("scanner", scanner)
            for finding in scan.get("findings", []):
                signature = finding.get("signature")
                path = finding.get("path")
                if not path or not signature:
                    # Invalid finding, just for safety
                    continue

                trigger_inst_id = self._trigger_id(scan_name, path, signature)
                self._fire(
                    instance_id=trigger_inst_id,
                    msg="Malware scan finding: scanner={} file={} signature={}".format(
                        scan_name, path, signature
                    ),
                )

class ScanNotRunTrigger(BaseTrigger):
    __trigger_name__ = "scan_not_run"
    __description__ = "Triggers if no malware scan has been run on the image."

    def evaluate(self, image_obj, context):

        try:
            scans = context.data.get(MALWARE_CONTEXT_KEY)
        except AttributeError:
            scans = None

        if not scans:
            self._fire(msg="No malware scans found for image")

class MalwareGate(Gate):
    __gate_name__ = "malware"
    __description__ = "Checks for malware scan findings in the image"
    __triggers__ = [ScanFindingsTrigger, ScanNotRunTrigger]

    def prepare_context(self, image_obj, context):
        """
        prepare the context by extracting the file name list once and placing it in the eval context to avoid repeated
        loads from the db. this is an optimization and could removed.

        :rtype:
        :param image_obj:
        :param context:
        :return:
        """

        scans = image_obj.analysis_artifacts.filter(
            AnalysisArtifact.analyzer_id == "malware",
            AnalysisArtifact.analyzer_artifact == "malware",
            AnalysisArtifact.analyzer_type == "base",
        ).all()

        context.data[MALWARE_CONTEXT_KEY] = {
            scanner.artifact_key: scanner.json_value for scanner in scans
        }

        return context


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package be;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 *
 * @author argos
 */
@Entity
@Table(name = "cuentatipo")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Cuentatipo.findAll", query = "SELECT c FROM Cuentatipo c"),
    @NamedQuery(name = "Cuentatipo.findByPkId", query = "SELECT c FROM Cuentatipo c WHERE c.pkId = :pkId"),
    @NamedQuery(name = "Cuentatipo.findByDescripcion", query = "SELECT c FROM Cuentatipo c WHERE c.descripcion = :descripcion"),
    @NamedQuery(name = "Cuentatipo.findByDeslarga", query = "SELECT c FROM Cuentatipo c WHERE c.deslarga = :deslarga"),
    @NamedQuery(name = "Cuentatipo.findByFecReg", query = "SELECT c FROM Cuentatipo c WHERE c.fecReg = :fecReg"),
    @NamedQuery(name = "Cuentatipo.findByEstadoExistencia", query = "SELECT c FROM Cuentatipo c WHERE c.estadoExistencia = :estadoExistencia")})
public class Cuentatipo implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "pk_id")
    private Integer pkId;
    @Size(max = 50)
    @Column(name = "descripcion")
    private String descripcion;
    @Size(max = 2000)
    @Column(name = "deslarga")
    private String deslarga;
    @Column(name = "fec_reg")
    @Temporal(TemporalType.TIMESTAMP)
    private Date fecReg;
    @Column(name = "estado_existencia")
    private Boolean estadoExistencia;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "cuentatipo", fetch = FetchType.LAZY)
    private List<Cuenta> cuentaList;

    public Cuentatipo() {
    }

    public Cuentatipo(Integer pkId) {
        this.pkId = pkId;
    }

    public Integer getPkId() {
        return pkId;
    }

    public void setPkId(Integer pkId) {
        this.pkId = pkId;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public String getDeslarga() {
        return deslarga;
    }

    public void setDeslarga(String deslarga) {
        this.deslarga = deslarga;
    }

    public Date getFecReg() {
        return fecReg;
    }

    public void setFecReg(Date fecReg) {
        this.fecReg = fecReg;
    }

    public Boolean getEstadoExistencia() {
        return estadoExistencia;
    }

    public void setEstadoExistencia(Boolean estadoExistencia) {
        this.estadoExistencia = estadoExistencia;
    }

    @XmlTransient
    public List<Cuenta> getCuentaList() {
        return cuentaList;
    }

    public void setCuentaList(List<Cuenta> cuentaList) {
        this.cuentaList = cuentaList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (pkId != null ? pkId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Cuentatipo)) {
            return false;
        }
        Cuentatipo other = (Cuentatipo) object;
        if ((this.pkId == null && other.pkId != null) || (this.pkId != null && !this.pkId.equals(other.pkId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "be.Cuentatipo[ pkId=" + pkId + " ]";
    }

}


text:
//----------------------------------*-C++-*----------------------------------//

//---------------------------------------------------------------------------//

#ifndef CudaUtils_cuda_utils_CudaDBC_hh
#define CudaUtils_cuda_utils_CudaDBC_hh

#include "config.h"

//---------------------------------------------------------------------------//
// If compiling device code, disable DBC
//---------------------------------------------------------------------------//
#ifdef __CUDA_ARCH__
#ifdef REQUIRE
// Undefine DBC macros since we've included DBC.hh
#include "harness/DBC_undef.hh"
#else // Require
// Prevent DBC from being loaded
#define harness_DBC_hh
#endif // Require

// Null-ops for DBC macros
#include "harness/DBC_nulldef.hh"
#else // __CUDA_ARCH__
#include "harness/DBC.hh"
#endif

//---------------------------------------------------------------------------//
// Compile assertions on host code when CUDA is enabled
#if defined(USE_CUDA) && !defined(__CUDA_ARCH__) && !defined(PSEUDO_CUDA)

//---------------------------------------------------------------------------//
// FUNCTION DEFINITIONS
//---------------------------------------------------------------------------//
namespace cuda
{

// Raise profugus::assertion with a formatted error message
void toss_cuda_cookies(
        const char* err_string,
        const char* msg,
        const char* file,
        int         line);

} // end namespace cuda

//---------------------------------------------------------------------------//
// MACRO DEFINITIONS
//---------------------------------------------------------------------------//

/*!
 * \def CudaCall(statement)
 *
 * Execute the wrapped statement and throw a message if it fails.
 *
 * If it fails, we call \c cudaGetLastError to clear the error code.
 *
 * \code
 *     CudaCall(cudaMalloc(&ptr_gpu, 100 * sizeof(float)));
 * \endcode
 */
#define CudaCall(COND) \
    do \
    { \
        cudaError_t result_ = (COND); \
        if (result_ != cudaSuccess) \
        { \
            cudaGetLastError(); \
            ::cuda::toss_cuda_cookies(cudaGetErrorString(result_), #COND, \
                __FILE__, __LINE__); \
        } \
    } while (0);

/*!
 * \def CudaInsist(statement/condition, message)
 *
 * Call the given function and throw a message if it doesn't return cudaSuccess.
 *
 * If it fails, we call \c cudaGetLastError to clear the error code.
 */
#define CudaInsist(COND, MSG) \
    do \
    { \
        cudaError_t result_ = (COND); \
        if (result_ != cudaSuccess) \
        { \
            cudaGetLastError(); \
            ::cuda::toss_cuda_cookies(MSG, cudaGetErrorString(result_), \
                __FILE__, __LINE__); \
        } \
    } while (0);

//---------------------------------------------------------------------------//
#else // CUDA is disabled or we're compiling device code

// Compile out the CUDA calls
#define CudaInsist(COND, MSG)
#define CudaCall(COND)

#endif
//---------------------------------------------------------------------------//

#endif // CudaUtils_cuda_utils_CudaDBC_hh

//---------------------------------------------------------------------------//
//              end of cuda_utils/CudaDBC.hh
//---------------------------------------------------------------------------//


text:
package com.m11n.jdbc.hystrix.util;

import org.slf4j.Logger;

import java.io.IOException;
import java.io.OutputStream;

/**
 * == An OutputStream that flushes out to a Category.
 *
 * NOTE: no data is written out to the Category until the stream is flushed or closed.
 *
 * Example:
 * [source,java]
 * --
 * // make sure everything sent to System.err is logged
 * System.setErr(new PrintStream(new LoggingOutputStream(Logger.getRootCategory()), true));
 *
 * // make sure everything sent to System.out is also logged
 * System.setOut(new PrintStream(new LoggingOutputStream(Logger.getRootCategory()), true));
 * --
 *
 * @author https://github.com/vidakovic[Aleksandar Vidakovic]
 */
public class Slf4jOutputStream extends OutputStream {
    /**
     * Used to maintain the contract of #close()}.
     */
    private boolean hasBeenClosed = false;

    /**
     * The internal buffer where data is stored.
     */
    private byte[] buf;

    /**
     * The number of valid bytes in the buffer. This value is always
     * in the range <tt>0</tt> through <tt>buf.length</tt>; elements
     * <tt>buf[0]</tt> through <tt>buf[count-1]</tt> contain valid
     * byte data.
     */
    private int count;

    /**
     * Remembers the size of the buffer for speed.
     */
    private int bufLength;

    /**
     * The default number of bytes in the buffer. =2048
     */
    public static final int DEFAULT_BUFFER_LENGTH = 2048;

    /**
     * The category to write to.
     */
    private Logger logger;

    /**
     * Creates the LoggingOutputStream to flush to the given Category.
     *
     * @param log   the Logger to write to
     * @throws IllegalArgumentException if cat == null or priority == null
     */
    public Slf4jOutputStream(Logger log) throws IllegalArgumentException {
        if (log == null) {
            throw new IllegalArgumentException("cat == null");
        }

        this.logger = log;
        this.bufLength = DEFAULT_BUFFER_LENGTH;
        this.buf = new byte[DEFAULT_BUFFER_LENGTH];
        this.count = 0;
    }

    /**
     * Closes this output stream and releases any system resources
     * associated with this stream. The general contract of
     * `close`
     * is that it closes the output stream. A closed stream cannot
     * perform
     * output operations and cannot be reopened.
     */
    public void close() {
        flush();
        hasBeenClosed = true;
    }

    /**
     * Writes the specified byte to this output stream. The general
     * contract for `write` is that one byte is written
     * to the output stream. The byte to be written is the eight
     * low-order bits of the argument `b`. The 24
     * high-order bits of `b` are ignored.
     *
     * @param b the `byte` to write
     * @throws java.io.IOException if an I/O error occurs. In particular, an `IOException` may be
     *                 thrown if the output stream has been closed.
     */
    public void write(final int b) throws IOException {
        if (hasBeenClosed) {
            throw new IOException("The stream has been closed.");
        }

        // would this be writing past the buffer?

        if (count == bufLength) {
            // grow the buffer
            final int newBufLength = bufLength + DEFAULT_BUFFER_LENGTH;
            final byte[] newBuf = new byte[newBufLength];

            System.arraycopy(buf, 0, newBuf, 0, bufLength);
            buf = newBuf;

            bufLength = newBufLength;
        }

        buf[count] = (byte) b;

        count++;
    }

    /**
     * Flushes this output stream and forces any buffered output bytes
     * to be written out. The general contract of `flush` is
     * that calling it is an indication that, if any bytes previously
     * written have been buffered by the implementation of the output
     * stream, such bytes should immediately be written to their
     * intended destination.
     */
    public void flush() {

        if (count == 0) {
            return;
        }

        // don't print out blank lines; flushing from PrintStream puts

        // For linux system

        if (count == 1 && ((char) buf[0]) == '\n') {
            reset();
            return;
        }

        // For mac system

        if (count == 1 && ((char) buf[0]) == '\r') {
            reset();
            return;
        }

        // On windows system

        if (count == 2 && (char) buf[0] == '\r' && (char) buf[1] == '\n') {
            reset();
            return;
        }

        final byte[] theBytes = new byte[count];
        System.arraycopy(buf, 0, theBytes, 0, count);
        String message = new String(theBytes);

        if(logger.isTraceEnabled()) {
            logger.trace(message);
        } else if(logger.isDebugEnabled()) {
            logger.debug(message);
        } else if(logger.isInfoEnabled()) {
            logger.info(message);
        } else if(logger.isWarnEnabled()) {
            logger.warn(message);
        } else if(logger.isErrorEnabled()) {
            logger.error(message);
        } else {
            logger.info(message);
        }

        reset();

    }

    private void reset() {
        // not resetting the buffer -- assuming that if it grew then it will likely grow similarly again
        count = 0;
    }
}


text:
> [d2b](../README.md) › **Chart Sunburst**

# {#generator}
[#](#generator) d2b.**chartSunburst**()

Constructs a new sunburst chart generator with the default settings.

When using the d2b-sunburst generator you can draw a sunburst chart onto each element in the selection.

# {#apply}
[#](#apply) *sunburst*(*context*)

Render the sunburst chart(s) to the given *context*, which may be either a [d3-selection](https://github.com/d3/d3-selection) of html containers (e.g. div) or a corresponding [d3-transition](https://github.com/d3/d3-transition).

Before applying the d2b-sunburst-chart generator, you should join the data to the selected element(s) using [selection.data](https://github.com/d3/d3-selection#selection_data) or [selection.datum](https://github.com/d3/d3-selection#selection_datum). Here is the default data format.

# {#sunburst_default}
### [#](#sunburst_default) Default Sunburst Chart
Here is a live interactive demo of the default sunburst chart without any extra configurations. A sunburst chart is very similar to a tree data structure. It starts off with a `root` and branches out into its `children` until it reaches the leaf nodes. Each ring around the center represents a level of the sunburst (or tree), the most inner ring representing the root. Each ring is instatiated with the `children` array. Each segment of a ring represents a child, which is instatiated with the `label` and if the `child` is a node, then it also has the `size` properties. The `child`'s ancestors retrieve their `size` data by adding all the `size`s of their childrend.

# {#basic}
### [#](#basic) Basic
Here is a live interactive demo of the sunburst chart with basic property configurations. Some of these configurations include angles, ring sizes, and colors.

# {#breadcrumbs}
### [#](#breadcrumbs) Breadcrumbs
Here is a live interactive demo of the sunburst chart with breadcrumb property configurations. A breadcrumb is an expandable list of sunburst chart data. The root of the breadcrumb is visible (by default) and hovering over each ring expands this list to clearly display the details of that and its previous rings. Some of the breadcrumb configurations include visibility, orientation, and the html generated.

# {#Padding}
### [#](#Padding) Padding
Here is a live interactive demo of the sunburst chart with padding property configurations. These configurations pad the rings in the sunburst as well as the sunburst chart (without the legend) as a whole.

# {#Radius}
### [#](#Radius) Radius
Here is a live interactive demo of the sunburst chart with radius property configurations. These configurations affect the appearance of the rings' roundness and thickness.

# {#Root}
### [#](#root) Root
Here is a live interactive demo of the sunburst chart with root property configurations. As previosuly mentioned, the root is the top-most node of the tree with child branches. The properties set in the root object can change the `color`, `breadcrumb`, `label`, and all of its `children`. Within the children array of objects, in addition to the root properities, the `tooltip` and `selected` are properties a child can have. If the child is a leaf node, it can also have the `size` property.

# {#sort}
### [#](#sort) Sort
Here is a live interactive demo of the sunburst chart with sort property configurations. Changes to these configuration (an accessor function) reorient the order of how the data in the sunburst is displayed.

# {#tooltip}
### [#](#tooltip) Tooltip
Here is a live interactive demo of the sunburst chart with tooltip property configurations. The tooltip is the textbox that appears when hovering over a sunburst ring. Each ring can have its own `tooltip` property and there is also a global tooltip object that gets applied to all the tooltips in the chart.

# {#transition}
### [#](#transition) Transition
Here is a live interactive demo of the sunburst chart with a transition configuration. If the button "Change Data!" is clicked, the sunburst chart will toggle between different data to demonstrate the transition animations. `.transition()` is used on the chart and chained with the desired `.duration(2000)` of microseconds.

# {#typescript}
### [#](#typescript) Typescript
Here is a live interactive demo of the default sunburst chart without any extra configurations using typescript. Typescript ensures proper types and properties are used when creating objects, arrays, etc.

# {#properties}
# [#](#properties) Properties

This is a complete list of properties that may be supplied to the axis chart datum. **Bold** properties are required.

{% include "./sunburstProperties.md" %}


text:
package cn.elvea.platform.xapi.controller;

import cn.elvea.platform.xapi.http.XApiResponse;
import cn.elvea.platform.xapi.model.Person;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * XApiAgentController
 *
 * @author elvea
 */
@Controller
@RequestMapping("/xAPI/agents")
@Tag(name = "XApi Agents Resource")
public class XApiAgentController extends XApiAbstractController {

    @GetMapping
    @ResponseBody
    public XApiResponse<Person> getAgents(
            @RequestParam("agent") String agent) {
        return XApiResponse.success(new Person(agent));
    }

}


text:
title: Disk replace in Linux raid software
description: A simple guide on how to replace a broken disk that is part of a software RAID in Linux
author: Matteo Mattei
layout: post
permalink: /disk-replace-in-linux-raid-software/
categories:
  - bash
  - linux
  - raid
---
Sometimes it happens that, after a long time of usage, one disk is going to be damage and starts to give some troubles... What's happened when the disk is part of a software raid? If the failing disk is only one, all data are safe but you have to replace the disk as soon as possible in order to avoid very ugly surprises! I know that is always a very frustrating thing to change a disk from a raid software.

However, when a disk in RAID 5 or in RIAD 1 should be replaced, you have to follow these steps:

 1.  Take a look at */proc/mdstat*, if is all ok (i.e. you have to replace a disk that contains some corrupted sectors but the raid is yet integer) mark the bad partition as failed (sdb1 in my case), otherwise continue from step 2:

    ```mdadm --manage /dev/md0 --fail /dev/sdb1```

 2.  Remove that partition from the Raid array:
    ```mdadm --manage /dev/md0 --remove /dev/sdb1```

 3.  Shutdown the pc, change the disk and power on the pc again.
 4.  At this point if you type ```cat /proc/mdstat``` you should see **[U_U]**.
 5. Copy now the partition table from a working disk (sda) to the new inserted disk (sdb):
    ```sfdisk -d /dev/sda | sfdisk /dev/sdb```
 6. Add the new partition to the array:
    ```mdadm --manage /dev/md0 --add /dev/sdb1```
 7. Done!

When you have finished, type
```
cat /proc/mdstat
```
and wait for the array rebuild.

At the end of the process (that can takes also some hours, depending on the size of the partition) you should have all "U" (**[UUU]**).


text:
import {
  simpleHandlerBuilder
} from 'quiver/component'

export const greetHandler = simpleHandlerBuilder(
  config => {
    const { greet='Hello' } = config

    return args =>
      greet + ', ' + args.name
  }, 'void', 'text')


text:
package org.apache.logging.log4j;

/**
 * Extended interface to allow bridges between logging systems to convey the
 * correct location information.
 *
 */
public interface BridgeAware {

    /**
     * Fully qualified class name of the entry point to the logging system. This
     * class will not appear in the location information.
     *
     * @param fqcn
     * @return this
     */
    public void setEntryPoint(final String fqcn);
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class HomeController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request)
    {
        $user = $request->user()['email'];
        return view('home', ['user' => $user, 'date_today' => date('Y-m-d', time())]);
    }

}


text:
<!DOCTYPE html>

    <title>Mockup Designer</title>
    <link type="text/css" rel="stylesheet" href="media/css/jquery-ui-1.9.1.css" />
    <link type="text/css" rel="stylesheet" href="media/css/h5bp.css" />
    <link type="text/css" rel="stylesheet" href="media/css/screen.css" />

        Select a Document
        Properties
        Import / Export

Documents

Create a new document

            <form>
                <input type="text" name="title" id="id_title" />
            </form>

Document Properties

            <form>
                Title
                <input type="text" name="title" id="id_title" />

                    Width
                    <input type="text" name="width" id="id_width" />

                    Height
                    <input type="text" name="height" id="id_height" />

                <input type="submit" value="Save" id="save">

            </form>

Import / Export

            <form>
                Models
                <textarea name="textarea" rows="10" cols="60" id="id_models"></textarea>
                <input type="submit" value="Import" id="import">
                Export PNG
            </form>

Properties

        <form class="properties"></form>


text:
<?php

namespace Irs\MagentoInitializer\Initializer\Db;

class Mysql implements DbInterface
{
    private $hostName;
    private $port;
    private $userName;
    private $password;
    private $schemaName;

    public function __construct($hostName, $userName, $password, $schemaName, $port = 3306)
    {
        $this->hostName   = $hostName;
        $this->port       = $port;
        $this->userName   = $userName;
        $this->password   = $password;
        $this->schemaName = $schemaName;

    }

    public function createDump($fileName)
    {
        $dir = dirname($fileName);
        if (!is_writable($dir)) {
            throw new \InvalidArgumentException("Directory '$dir' is not writeable.");
        }

        if (!$this->isMysqldumpAvailable()) {
            throw new \RuntimeException("Unable execute mysqldump; please check that it's in the path.");
        }

        exec(
            vsprintf(
            	'mysqldump %s --host=%s --port=%s --user=%s --password=%s > %s',
                array_map(
                	'escapeshellarg',
                    array(
                        $this->schemaName,
                        $this->hostName,
                        $this->port,
                        $this->userName,
                        $this->password,
                        $fileName,
                    )
                )
            ),
            $output,
            $exitCode
        );

        if ($exitCode) {
            throw new \RuntimeException("Error occured on mysqldump call:\n" . substr(implode("\n", $output), 0, 150));
        }
    }

    public function restoreDump($fileName)
    {
        if (!file_exists($fileName)) {
            throw new \InvalidArgumentException("File '$fileName' does not exist.");
        }
        if (!is_readable($fileName)) {
            throw new \InvalidArgumentException("File '$fileName' is not readable.");
        }
        if (!$this->isMysqlClientAvailable()) {
            throw new \RuntimeException("Unable execute mysql; please check that it's in the path.");
        }

        exec(
            vsprintf(
            	'mysql --host=%s --port=%s --database=%s --user=%s --password=%s < %s',
                array_map(
                	'escapeshellarg',
                    array(
                        $this->hostName,
                        $this->port,
                        $this->schemaName,
                        $this->userName,
                        $this->password,
                        $fileName,
                    )
                )
            ),
            $output,
            $exitCode
        );

        if ($exitCode) {
            throw new \RuntimeException("Error occured on mysql call:\n" . substr(implode("\n", $output), 0, 150));
        }
    }

    private function isMysqldumpAvailable()
    {
        exec('mysqldump --version', $output, $exitCode);

        return 0 == $exitCode;
    }

    private function isMysqlClientAvailable()
    {
        exec('mysql --version', $output, $exitCode);

        return 0 == $exitCode;
    }
}


text:
<?php $this->load->helper('human_timingv2'); ?>

<?php echo $toggle_sidebar ?>

        <?php echo $sidebar ?>

            <?php
                $item_counter = 0;
                foreach($topics as $topic):
                $item_counter += 1;
                $currentPage = floor(($offset/$per_page) + 1);
                $rank = ($currentPage - 1) * 10 + $item_counter;
            ?>

<?php echo $rank;?>

                                <?php if ($topic['subscribed']) {?>
                                    <a href="javascript:void(0);" id="<?php echo $topic['topic'];?>" class="btn btn-small btn-danger" onclick="unsubscribe(this);" style="width:90px;">Abonelikten çık
                                <?php } else { ?>
                                    <a href="javascript:void(0);" id="<?php echo $topic['topic'];?>" class="btn btn-small btn-success" onclick="subscribe(this);" style="width:90px;">Abone ol
                                <?php }?>

<a class="link-title" href="<?php echo base_url("")."t/".$topic['topic']."/";?>"><?php echo "/t/".$topic['topic']; ?>

                                        <?php if ($topic['description']) echo $topic['description'].'
';?>
                                        <?php echo $topic['subscribers'];?> abone,  <?php echo human_timingv2($topic['created']);?> bir konu

                                                <a href="javascript:void(0)" onclick="report_topic('<?php echo $topic['topic'];?>')" class="login-required">şikayet

                                                paylaş

                <?php endforeach?>

                <?php echo $this->pagination->create_links(); ?>


text:
var ExpectationsListView = Backbone.View.extend({
    template: _.template( $('#expectations-list-template').html() ),
    className: 'collapsible-body',

    events: {
        'keypress #new-expectation'   :   'createOnEnter'
    },

    initialize: function() {
        this.listenTo(this.collection, 'add', this.addExpectation);
        this.listenTo(this.collection, 'remove', this.removeExpectation);
    },

    render: function() {
        console.log('Render ExpectationsListView');
        var self = this;
        this.$el.html( self.template( self.collection.models ) );

        // Display all expectations for this task (a new view for each)
        this.collection.models.forEach(function(expectation) {
            self.addExpectation(expectation);
        });

        this.$input = this.$el.children('#new-expectation');
        _.defer(function(){
            self.$input.focus();
            $('.collapsible').collapsible('open', 0);
        });

        return this;
    },

    addExpectation: function( expectation ) {
        var view = new ExpectationView({ model: expectation });
        this.$el.children('#new-expectation').after( view.render().el );
    },

    createOnEnter: function( event ) {
        if ( event.which !== ENTER_KEY || !this.$input.val().trim() ) {
            return;
        }

        var newExp = new Expectation({
            title: this.$input.val(),
            validate: true
        });
        this.collection.addExpectation(newExp);

        this.$input.val('');
        this.$input.focus();
    },

    removeExpectation: function() {
        this.render();
    }
});


text:
duti -s org.gnu.Emacs com.apple.property-list all
duti -s org.gnu.Emacs com.apple.xcode.strings-text all
duti -s org.gnu.Emacs com.netscape.javascript-source all
duti -s org.gnu.Emacs net.daringfireball.markdown all
duti -s org.gnu.Emacs public.c-header all
duti -s org.gnu.Emacs public.c-plus-plus-source all
duti -s org.gnu.Emacs public.c-source all
duti -s org.gnu.Emacs public.data all
duti -s org.gnu.Emacs public.json all
duti -s org.gnu.Emacs public.objective-c-source all
duti -s org.gnu.Emacs public.perl-script all
duti -s org.gnu.Emacs public.plain-text all
duti -s org.gnu.Emacs public.precompiled-c-header all
duti -s org.gnu.Emacs public.python-script all
duti -s org.gnu.Emacs public.ruby-script all
duti -s org.gnu.Emacs public.shell-script all
duti -s org.gnu.Emacs public.swift-source all
duti -s org.gnu.Emacs public.unix-executable all
duti -s org.gnu.Emacs public.xml all
duti -s org.gnu.Emacs public.yaml all

# code ends here