text:
#include "tensorflow/compiler/xla/rpc/grpc_stub.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h"

namespace xla {

GRPCStub::~GRPCStub() = default;

Status MakeRPC(
    const std::function<::grpc::Status(::grpc::ClientContext*)>& rpc_method) {
  ::grpc::ClientContext context;
  ::grpc::Status s = rpc_method(&context);
  return tensorflow::FromGrpcStatus(s);
}

Status GRPCStub::TransferToClient(const TransferToClientRequest* request,
                                  TransferToClientResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->TransferToClient(context, *request, response);
  });
}

Status GRPCStub::TransferToServer(const TransferToServerRequest* request,
                                  TransferToServerResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->TransferToServer(context, *request, response);
  });
}

Status GRPCStub::TransferToInfeed(const TransferToInfeedRequest* request,
                                  TransferToInfeedResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->TransferToInfeed(context, *request, response);
  });
}

Status GRPCStub::TransferFromOutfeed(const TransferFromOutfeedRequest* request,
                                     TransferFromOutfeedResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->TransferFromOutfeed(context, *request, response);
  });
}

Status GRPCStub::ResetDevice(const ResetDeviceRequest* request,
                             ResetDeviceResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->ResetDevice(context, *request, response);
  });
}

Status GRPCStub::LoadComputationSnapshot(
    const LoadComputationSnapshotRequest* request,
    LoadComputationSnapshotResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->LoadComputationSnapshot(context, *request, response);
  });
}

Status GRPCStub::Execute(const ExecuteRequest* request,
                         ExecuteResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->Execute(context, *request, response);
  });
}

Status GRPCStub::ExecuteGraph(const ExecuteGraphRequest* request,
                              ExecuteResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->ExecuteGraph(context, *request, response);
  });
}

Status GRPCStub::ExecuteParallel(const ExecuteParallelRequest* request,
                                 ExecuteParallelResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->ExecuteParallel(context, *request, response);
  });
}

Status GRPCStub::ExecuteGraphParallel(
    const ExecuteGraphParallelRequest* request,
    ExecuteParallelResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->ExecuteGraphParallel(context, *request, response);
  });
}

Status GRPCStub::ExecuteAsync(const ExecuteAsyncRequest* request,
                              ExecuteAsyncResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->ExecuteAsync(context, *request, response);
  });
}

Status GRPCStub::WaitForExecution(const WaitForExecutionRequest* request,
                                  WaitForExecutionResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->WaitForExecution(context, *request, response);
  });
}

Status GRPCStub::DeconstructTuple(const DeconstructTupleRequest* request,
                                  DeconstructTupleResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->DeconstructTuple(context, *request, response);
  });
}

Status GRPCStub::GetComputationStats(const ComputationStatsRequest* request,
                                     ComputationStatsResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->GetComputationStats(context, *request, response);
  });
}

Status GRPCStub::GetComputationGraphStats(
    const ComputationGraphStatsRequest* request,
    ComputationStatsResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->GetComputationGraphStats(context, *request, response);
  });
}

Status GRPCStub::GetComputationShape(const GetComputationShapeRequest* request,
                                     GetComputationShapeResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->GetComputationShape(context, *request, response);
  });
}

Status GRPCStub::GetShape(const GetShapeRequest* request,
                          GetShapeResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->GetShape(context, *request, response);
  });
}

Status GRPCStub::GetDeviceHandles(const GetDeviceHandlesRequest* request,
                                  GetDeviceHandlesResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->GetDeviceHandles(context, *request, response);
  });
}

Status GRPCStub::CreateChannelHandle(const CreateChannelHandleRequest* request,
                                     CreateChannelHandleResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->CreateChannelHandle(context, *request, response);
  });
}

// Methods used by ComputationBuilder.
Status GRPCStub::Computation(const ComputationRequest* request,
                             ComputationResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->Computation(context, *request, response);
  });
}

Status GRPCStub::Op(const OpRequest* request, OpResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->CreateOp(context, *request, response);
  });
}

Status GRPCStub::GetLocalShape(const GetLocalShapeRequest* request,
                               GetLocalShapeResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->GetLocalShape(context, *request, response);
  });
}

Status GRPCStub::SetReturnValue(const SetReturnValueRequest* request,
                                SetReturnValueResponse* responses) {
  return MakeRPC([this, request, responses](::grpc::ClientContext* context) {
    return grpc_stub_->SetReturnValue(context, *request, responses);
  });
}

Status GRPCStub::IsConstant(const IsConstantRequest* request,
                            IsConstantResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->IsConstant(context, *request, response);
  });
}

Status GRPCStub::ComputeConstant(const ComputeConstantRequest* request,
                                 ComputeConstantResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->ComputeConstant(context, *request, response);
  });
}

Status GRPCStub::ComputeConstantGraph(
    const ComputeConstantGraphRequest* request,
    ComputeConstantResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->ComputeConstantGraph(context, *request, response);
  });
}

// Methods used by Computation.
Status GRPCStub::SnapshotComputation(const SnapshotComputationRequest* request,
                                     SnapshotComputationResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->SnapshotComputation(context, *request, response);
  });
}

// Methods used by GlobalData.
Status GRPCStub::Unregister(const UnregisterRequest* request,
                            UnregisterResponse* response) {
  return MakeRPC([this, request, response](::grpc::ClientContext* context) {
    return grpc_stub_->Unregister(context, *request, response);
  });
}

}  // namespace xla


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

<title></title>

  <link href="../css/bootstrap.min.css" rel="stylesheet">
  <link rel = 'stylesheet' type = 'text/css' href = '../default2.css'>
  <link rel = 'stylesheet' type = 'text/css' href = '../default.css'>

Asking Good Questions

August 16th, 2015

    I believe that learning how to ask good questions will be an important skill going forward. In order to get help from your peers, it's vital that all the information and the format of the question be in a manner where it is easy for your peers to understand.

    When asking a question, it is important to remember that nobody will be able to help you if you do not explain and clarify yourself in the most practical way. I learned that the best way to start off when asking a question to your peers is to start it off with a title that summarizes the problem you have at hand. Nothing too long, but nothing too short and generic. You want to make the question very easy to follow! By taking a little bit more time to include all the relevant information ( whether it's your code or links to sandboxes) , you might be surprised at how people will be responding to you!

    Another important part of posting questions is to always proof-read. As stated above, it's important to make sure it's easy to follow! Making sure your links are working right and to have all the relavant code included in the question, will benefit both you and the people helping you.

    To sum it up, when asking questions, I believe by taking a little bit more time to format your question the right way will make a world of a difference! It's important to remember that you are trying to help the people that are helping you, and by giving a little bit more effort, everyone will be happy =]

      Home
      Contact
      Blog

redpajama_set_name: RedPajamaGithub


text:
import leftPad from 'left-pad';

function levelFn(data) {
  if (data.err || data.status >= 500 || data.duration > 10000) { // server internal error or error
    return 'error';
  } else if (data.status >= 400 || data.duration > 3000) { // client error
    return 'warn';
  }
  return 'info';
}

function logStart(data) {
  return `${leftPad(data.method, 4)} ${data.url} started reqId=${data.reqId}`;
}

function logFinish(data) {
  const time = (data.duration || 0).toFixed(3);
  const length = data.length || 0;
  return `${leftPad(data.method, 4)} ${data.url} ${leftPad(data.status, 3)} ${leftPad(time, 7)}ms ${leftPad(length, 5)}b reqId=${data.reqId}`;
}

export default (params) => ([
  (req, res, next) => {
    const data = {}
    if (!req.log) throw 'has no req.log!'
    const log = req.log.child({
      component: 'req',
    });

    data.reqId = req.reqId
    data.method = req.method
    if (req.ws) data.method = 'WS'
    data.host = req.headers.host
    data.url = (req.baseUrl || '') + (req.url || '-')
    data.referer = req.header('referer') || req.header('referrer')
    data.ip = req.ip || req.connection.remoteAddress ||
        (req.socket && req.socket.remoteAddress) ||
        (req.socket.socket && req.socket.socket.remoteAddress) ||
        '127.0.0.1'

    if (__DEV__) {
      log.debug(data, logStart(data));
      if (req.body) {
        log.trace(JSON.stringify(req.body));
      }
    }

    const hrtime = process.hrtime();
    function logging() {
      data.status = res.statusCode
      data.length = res.getHeader('Content-Length')

      const diff = process.hrtime(hrtime);
      data.duration = diff[0] * 1e3 + diff[1] * 1e-6

      log[levelFn(data)](data, logFinish(data));
    }
    res.on('finish', logging);
    res.on('close', logging);
    next();
  }
])


text:
from scrapy.conf import settings
from scrapy.contrib.exporter import CsvItemExporter

class CSVExporter(CsvItemExporter):

    def __init__(self, *args, **kwargs):
        kwargs['fields_to_export'] = settings.getlist('EXPORT_FIELDS') or None
        kwargs['encoding'] = settings.get('EXPORT_ENCODING', 'utf-8')

        super(CSVExporter, self).__init__(*args, **kwargs)


text:
#include "agent_based_epidemic_sim/core/small_world_graph.h"

#include <memory>

#include "absl/flags/declare.h"
#include "absl/flags/flag.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

ABSL_DECLARE_FLAG(bool, is_large_k);

namespace abesim {
namespace {

using ::testing::Pair;
using ::testing::UnorderedElementsAre;

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphInvalidInputsEvenK) {
  EXPECT_DEATH(SmallWorldGraph::GenerateWattsStrogatzGraph(4, 2, -0.1),
               "'p' must be >= 0");
  EXPECT_DEATH(SmallWorldGraph::GenerateWattsStrogatzGraph(4, 2, 1.1),
               "'p' must be <= 1");
  EXPECT_DEATH(SmallWorldGraph::GenerateWattsStrogatzGraph(4, 1, 0.5),
               "'k' must be >= 2");
  EXPECT_DEATH(SmallWorldGraph::GenerateWattsStrogatzGraph(2, 2, 0.5),
               "'n' must be >= 'k'");
}

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphInvalidInputsOddK) {
  EXPECT_DEATH(SmallWorldGraph::GenerateWattsStrogatzGraph(5, 3, -0.1),
               "'p' must be >= 0");
  EXPECT_DEATH(SmallWorldGraph::GenerateWattsStrogatzGraph(5, 3, 1.1),
               "'p' must be <= 1");
  EXPECT_DEATH(SmallWorldGraph::GenerateWattsStrogatzGraph(5, 1, 0.5),
               "'k' must be >= 2");
  EXPECT_DEATH(SmallWorldGraph::GenerateWattsStrogatzGraph(3, 3, 0.5),
               "'n' must be >= 'k'");
}

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphP0EvenK) {
  std::unique_ptr<SmallWorldGraph> ws =
      SmallWorldGraph::GenerateWattsStrogatzGraph(/*n=*/4, /*k=*/2, /*p=*/0.0);
  std::vector<std::pair<int, int>> edges = ws->GetEdges();
  EXPECT_EQ(ws->NumNodes(), 4);
  EXPECT_EQ(ws->Degree(), 2);
  EXPECT_FLOAT_EQ(ws->RewireProbability(), 0.0);
  EXPECT_EQ(edges.size(), 4);
  EXPECT_THAT(edges, UnorderedElementsAre(Pair(0, 1), Pair(0, 3), Pair(1, 2),
                                          Pair(2, 3)));
}

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphP1EvenK) {
  std::unique_ptr<SmallWorldGraph> ws =
      SmallWorldGraph::GenerateWattsStrogatzGraph(/*n=*/4, /*k=*/2, /*p=*/1.0);
  std::vector<std::pair<int, int>> edges = ws->GetEdges();
  EXPECT_EQ(ws->NumNodes(), 4);
  EXPECT_EQ(ws->Degree(), 2);
  EXPECT_FLOAT_EQ(ws->RewireProbability(), 1.0);
  EXPECT_EQ(edges.size(), 4);
  // TODO: Mock BitGen to test rewiring.
}

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphPhalfEvenK) {
  std::unique_ptr<SmallWorldGraph> ws =
      SmallWorldGraph::GenerateWattsStrogatzGraph(/*n=*/4, /*k=*/2, /*p=*/0.5);
  std::vector<std::pair<int, int>> edges = ws->GetEdges();
  EXPECT_EQ(ws->NumNodes(), 4);
  EXPECT_EQ(ws->Degree(), 2);
  EXPECT_FLOAT_EQ(ws->RewireProbability(), 0.5);
  EXPECT_EQ(edges.size(), 4);
}

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphP0OddK) {
  std::unique_ptr<SmallWorldGraph> ws =
      SmallWorldGraph::GenerateWattsStrogatzGraph(/*n=*/5, /*k=*/3, /*p=*/0.0);
  std::vector<std::pair<int, int>> edges = ws->GetEdges();
  EXPECT_EQ(ws->NumNodes(), 5);
  EXPECT_EQ(ws->Degree(), 3);
  EXPECT_FLOAT_EQ(ws->RewireProbability(), 0.0);
  EXPECT_EQ(edges.size(), 5);
  EXPECT_THAT(edges, UnorderedElementsAre(Pair(0, 1), Pair(0, 4), Pair(1, 2),
                                          Pair(2, 3), Pair(3, 4)));
}

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphP1OddK) {
  std::unique_ptr<SmallWorldGraph> ws =
      SmallWorldGraph::GenerateWattsStrogatzGraph(/*n=*/5, /*k=*/3,
                                                  /*p=*/1.0);
  std::vector<std::pair<int, int>> edges = ws->GetEdges();
  EXPECT_EQ(ws->NumNodes(), 5);
  EXPECT_EQ(ws->Degree(), 3);
  EXPECT_FLOAT_EQ(ws->RewireProbability(), 1.0);
  EXPECT_EQ(edges.size(), 5);
}

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphPhalfOddK) {
  std::unique_ptr<SmallWorldGraph> ws =
      SmallWorldGraph::GenerateWattsStrogatzGraph(/*n=*/5, /*k=*/3,
                                                  /*p=*/0.5);
  std::vector<std::pair<int, int>> edges = ws->GetEdges();
  EXPECT_EQ(ws->NumNodes(), 5);
  EXPECT_EQ(ws->Degree(), 3);
  EXPECT_FLOAT_EQ(ws->RewireProbability(), 0.5);
  EXPECT_EQ(edges.size(), 5);
}

TEST(SmallWorldGraph, GenerateWattsStrogatzGraphLargeK) {
  absl::SetFlag(&FLAGS_is_large_k, true);
  std::unique_ptr<SmallWorldGraph> ws =
      SmallWorldGraph::GenerateWattsStrogatzGraph(/*n=*/4, /*k=*/2, /*p=*/0.5);
  std::vector<std::pair<int, int>> edges = ws->GetEdges();
  EXPECT_EQ(ws->NumNodes(), 4);
  EXPECT_EQ(ws->Degree(), 2);
  EXPECT_FLOAT_EQ(ws->RewireProbability(), 0.5);
  EXPECT_EQ(edges.size(), 4);
}

}  // namespace
}  // namespace abesim


text:
from ... import graphql_to_sql  # noqa
from ...schema_generation.sqlalchemy import get_sqlalchemy_schema_info  # noqa

# pylint: enable=unused-import


text:
package org.pathirage.play.samlsso;

import org.pathirage.play.samlsso.session.SSOSessionStorageHelper;
import play.mvc.Http.Session;
import play.libs.F.Promise;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Result;
import play.mvc.SimpleResult;

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

import java.net.URI;

public class SAMLSSOAuthenticationAction extends Action<Result> {
    private static final Logger log = LoggerFactory.getLogger(SAMLSSOAuthenticationAction.class);

    @Override
    @SuppressWarnings("unchecked")
    public Promise<SimpleResult> call(Http.Context ctx) throws Throwable {
        Session session = ctx.session();
        String sessionId = null;
        String tagrgetUrl = ctx.request().uri();
        String absoluteTargetUrl = getAbsoluteUrl(tagrgetUrl, ctx);

        if(!SSOSessionStorageHelper.isSSOSessionExists(session)){
            sessionId = SSOSessionStorageHelper.createSession(session);
        } else {
            sessionId = SSOSessionStorageHelper.getSessionId(session);
        }

        // Check whether user profile information there and initiate SSO process
        UserProfile userProfile = SSOSessionStorageHelper.getUserProfile(sessionId);

        if(userProfile == null){
            return SAMLSSOManager.INSTANCE.buildAuthenticationRequest(ctx, absoluteTargetUrl);
        }

        return delegate.call(ctx);
    }

    private String getAbsoluteUrl(String url, Http.Context ctx){
        if(url != null && !url.startsWith("http://") && !url.startsWith("https://")){
            StringBuilder stringBuilder = new StringBuilder();
            // TODO: Add support for https and proxying.
            String[] parts = ctx.request().host().split(":");
            String serverName = parts[0];
            String port = parts.length > 1 ? parts[1] : "80";

            stringBuilder.append("http://").append(serverName).append(port);

            if(url.startsWith("/")){
                stringBuilder.append(url);
            } else {
                stringBuilder.append("/").append(url);
            }

            return stringBuilder.toString();
        }

        return url;
    }
}


text:
<?php
App::uses('Component', 'Controller');
App::uses('CartSessionComponent', 'Cart.Controller/Component');
App::uses('CakeEvent', 'Event');

class CartManagerComponent extends Component {

/**
 * Components
 *
 * @var array
 */
	public $components = array(
		'Auth',
		'Session',
		'Cookie',
		'Cart.CartSession'
	);

/**
 * Id of the active database cart
 *
 * @var string Cart UUID
 */
	protected $_cartId = null;

/**
 * User status if logged in or not
 *
 * @var boolean
 */
	protected $_isLoggedIn = false;

/**
 * CakeEventManager
 */
	protected $_EventManager = null;

/**
 * Default settings
 *
 * - model overrides the Controller defaults modelClass that is used by the cart manager
 * - buyAction the controller action to use or check for
 * - cartModel
 * - sessionKey the session key of the cart session data
 * - useCookie use a cookie to store the cart persistent for non logged in users
 * - cookieName
 * - afterAddItemRedirect
 *   - false to disable it
 *   - null to use the referer
 *   - string or array to set a redirect url
 * - getBuy boolean enable/disable capture of buy data via get
 * - postBuy boolean enable/disable capture of buy data via post
 * - update mixed true/false/'get'/'post'
 *   Allow to update the item in cart: true/false for both get and post, or only allow for method
 * - incremental mixed true/false/'get'/'post'
 *   Allow to increment/decrement the item in cart: true/false for both get and post, or only allow for method
 * - remove mixed true/false/'get'/'post'
 *   Allow to remove the item from the cart: true/false for both get and post, or only allow for method
 *
 * @var array
 */
	protected $_defaultSettings = array(
		'model' => null,
		'buyAction' => 'buy',
		'cartModel' => 'Cart.Cart',
		'cartSession' => array('CartSession', 'Cart.Controller/Component'),
		'sessionKey' => 'Cart',
		'useCookie' => false,
		'cookieName' => 'Cart',
		'afterAddItemRedirect' => true,
		'afterAddItemFailedRedirect' => true,
		'getBuy' => true,
		'postBuy' => true,
		'update' => true,
		'incremental' => true,
		'remove' => true,
		'emptyCartStructure' => array(
			'Cart' => array(
				'item_count' => 0.00,
				'total' => 0.00
			),
			'CartsItem' => array()
		)
	);

/**
 * Default settings
 *
 * @var array
 */
	public function initialize(Controller $Controller) {
		$this->settings = array_merge($this->_defaultSettings, $this->settings);
		$this->Controller = $Controller;
		$this->_EventManager = CakeEventManager::instance();

		if (empty($this->settings['model'])) {
			$this->settings['model'] = $this->Controller->modelClass;
		}

		$this->sessionKey = $this->settings['sessionKey'];
	}

/**
 * Extend the CartManagerComponent and Override this method if needed
 *
 * @return void
 */
	protected function _setLoggedInStatus() {
		if (is_a($this->Controller->Auth, 'AuthComponent') && $this->Controller->Auth->user()) {
			$this->_isLoggedIn = true;
		}
	}

/**
 * Cart initialization
 *
 * - Checks if the cart data is in the session and if not initializes an empty cart structure in the session
 * - If the user is logged in and a cart session is present it merges the persistent data from the db with the session
 * - Sets the CartManager::$_cartId
 *
 * @return void
 */
	public function initializeCart() {
		extract($this->settings);
		$userId = $this->Auth->user('id');
		$this->CartModel = ClassRegistry::init($cartModel);

		if (!$this->Session->check($sessionKey)) {
			$this->Session->write($sessionKey, $emptyCartStructure);
		} else {
			if ($userId && !$this->Session->check($sessionKey . '.Cart.id')) {
				$merged = $this->CartModel->CartsItem->mergeItems(
					$this->CartModel->getActive($userId),
					$this->Session->read($sessionKey)
				);

				$this->_cartId = $merged['Cart']['id'];
				$this->Session->write($sessionKey, $merged);

				foreach ($merged['CartsItem'] as $item) {
					$this->CartModel->CartsItem->addItem($this->_cartId, $item);
				}

				$this->calculateCart();
			}
		}

		$this->_cartId = $this->CartSession->read('Cart.id');
	}

/**
 * Component startup callback
 *
 * @param Controller $Controller
 * @return void
 */
	public function startup(Controller $Controller) {
		$this->_setLoggedInStatus();
		$this->initializeCart();
		extract($this->settings);
		if ($this->Controller->action == $buyAction && !method_exists($this->Controller, $buyAction)) {
			$this->captureBuy();
		}
	}

/**
 * Captures a buy from a post or get request
 *
 * @throws InternalErrorException
 * @param boolean $returnItem
 * @param array $options
 * @return mixed False if the catpure failed array with item data on success
 */
	public function captureBuy($returnItem = false, $options = array()) {
		extract($this->settings);

		if ($this->Controller->request->is('get')) {
			$data = $this->getBuy();
		}

		if ($this->Controller->request->is('post')) {
			$data = $this->postBuy();
		}

		if ($data === false) {
			return false;
		}

		$type = $this->getItemAction($data);
		if (!$this->itemActionAllowed($type)) {
			throw new InternalErrorException(__d('cart', 'Type %s is not allowed', $type));
		}

		if (!$data) {
			if ($afterAddItemFailedRedirect === true) {
				$this->Session->setFlash(__d('cart', 'Failed to buy the item'));
				$this->Controller->redirect($this->Controller->referer());
			}
			return false;
		}

		$item = $this->updateItem($data);
		if ($returnItem === true) {
			return $item;
		}

		if ($item !== false) {
			if ($this->Controller->request->is('ajax') || $this->Controller->request->is('json') || $this->Controller->request->is('xml')) {
				$this->Controller->set('item', $item);
				$this->Controller->set('_serialize', array('item'));
			} else {
				$this->afterAddItemRedirect($item);
			}
		}

		if ($afterAddItemFailedRedirect === true) {
			$this->Session->setFlash(__d('cart', 'Failed to buy the item'));
			$this->Controller->redirect($this->Controller->referer());
		}

		return false;
	}

/**
 * Checks if the increment/decrement/update type is allowed.
 *
 * @param string|array $type array or type string
 * @return boolean The type is allowed or not
 */
	public function itemActionAllowed($type) {
		if (is_array($type)) {
			$type = $this->getItemAction($type);
		}
		if (in_array($type, array('update', 'remove'))) {
			$key = $type;
		} elseif (in_array($type, array('increment', 'decrement'))) {
			$key = 'incremental';
		}

		if (!isset($key)) {
			return false;
		}

		return (
			$this->settings[$key] === true ||
			strtoupper($this->settings[$key]) === $this->Controller->request->method()
		);
	}

/**
 * Returns 'type' from data, if not present defaults to 'update'
 *
 * @param array $data
 * @return string type for the buy action
 */
	public function getItemAction($data) {
		if (!empty($data['CartsItem']['increment'])) {
			return 'increment';
		} elseif (!empty($data['CartsItem']['decrement'])) {
			return 'decrement';
		} elseif (!empty($data['CartsItem']['remove'])) {
			return 'remove';
		}
		return 'update';
	}

/**
 * Update an item
 *
 * @param array $data
 * @param boolean $recalculate
 * @return void
 */
	public function updateItem($data, $recalculate = true) {
		$type = $this->getItemAction($data);
		$data = $this->_additionalData($data, $type);
		if ($type == 'update') {
			return $this->addItem($data, $recalculate);
		}

		$contains = $this->contains($data['CartsItem']['foreign_key'], $data['CartsItem']['model']);
		if (!$contains && $type === 'increment') {
			return $this->addItem($data, $recalculate);
		} elseif (!$contains) {
			return false;
		}

		$item = $this->getItem($data['CartsItem']['foreign_key'], $data['CartsItem']['model']);
		if ($type == 'increment') {
			$data['CartsItem']['quantity'] += $item['quantity'];
			return $this->addItem($data, $recalculate);
		} elseif ($type == 'decrement') {
			$data['CartsItem']['quantity'] = $item['quantity'] - $data['CartsItem']['quantity'];
			if ($data['CartsItem']['quantity'] > 0) {
				return $this->addItem($data, $recalculate);
			}
			return $this->removeItem($data);
		} elseif ($type == 'remove') {
			return $this->removeItem($data);
		}
		return false;
	}

/**
 * Adds additional data here that depends more or less on the controller and we
 * want to be present in the addItem() method
 *
 * @param array $data
 * @param string $type
 * @return array
 */
	protected function _additionalData($data, $type = 'update') {
		$data['CartsItem']['user_id'] = $this->Auth->user('id');
		$data['CartsItem']['cart_id'] = $this->_cartId;

		if (!isset($data['CartsItem']['model'])) {
			$data['CartsItem']['model'] = $this->settings['model'];
		}
		if (!empty($data['CartsItem'][$type]) && empty($data['CartsItem']['quantity'])) {
			$data['CartsItem']['quantity'] = (int)$data['CartsItem'][$type];
		}
		unset($data['CartsItem'][$type]);

		if (!isset($data['CartsItem']['quantity'])) {
			$data['CartsItem']['quantity'] = 1;
		}

		return $data;
	}

/**
 * afterAddItemRedirect
 *
 * @param array $item
 * @return vodi
 */
	public function afterAddItemRedirect($item) {
		extract($this->settings);
		if ($item === true) {
			$this->Session->setFlash(__d('cart', 'Item was successfully removed from your cart'));
		} else {
			$this->Session->setFlash(__d('cart', 'You now have %s %s in your cart', $item['quantity'], $item['name']));
		}
		if (is_string($afterAddItemRedirect) || is_array($afterAddItemRedirect)) {
			$this->Controller->redirect($afterAddItemRedirect);
		} elseif ($afterAddItemRedirect === true) {
			$this->Controller->redirect($this->Controller->referer());
		}
	}

/**
 * Gets item data via a http get request and url parameters
 *
 * @return mixed false or array
 */
	public function getBuy() {
		if ($this->Controller->request->is('get') && $this->settings['getBuy'] === true && isset($this->Controller->request->params['named']['item'])) {
			$data = array(
				'CartsItem' => array(
					'foreign_key' => $this->Controller->request->params['named']['item']));

			if (isset($this->Controller->request->params['named']['model'])) {
				$data['CartsItem']['model'] = $this->Controller->request->params['named']['model'];
			}

			if (isset($this->Controller->request->params['named']['quantity'])) {
				$data['CartsItem']['quantity'] = $this->Controller->request->params['named']['quantity'];
			}
			foreach (array('update', 'increment', 'decrement', 'remove') as $type) {
				if (isset($this->Controller->request->params['named'][$type])) {
					$data['CartsItem'][$type] = $this->Controller->request->params['named'][$type];
					break;
				}
			}

			return $data;
		}
		return false;
	}

/**
 * Gets the item data via http post request
 *
 * @return mixed false or array
 */
	public function postBuy() {
		if ($this->Controller->request->is('post') && $this->settings['postBuy'] === true) {
			return $this->Controller->request->data;
		}
		return false;
	}

/**
 * Adds an item to the cart, the session and database if a user is logged in
 *
 * @param  array $data
 * @param  boolean $recalculate
 * @throws InternalErrorException
 * @throws RuntimeException
 * @return boolean
 */
	public function addItem($data, $recalculate = true) {
		$data = $this->_additionalData($data);
		if ($data['CartsItem']['quantity'] == 0) {
			return $this->removeItem($data);
		}

		$Event = new CakeEvent('CartManager.beforeAddItem', $this, array($data));
		$this->_EventManager->dispatch($Event);
		if ($Event->result === false || $Event->isStopped()) {
			return false;
		}

		$ItemModel = ClassRegistry::init($data['CartsItem']['model']);

		if (!$ItemModel->hasMethod('isBuyable') || !$ItemModel->hasMethod('beforeAddToCart')) {
			throw new InternalErrorException(__d('cart', 'The model %s is not implementing isBuyable() or beforeAddToCart() or is not using the BuyableBehavior!', get_class($ItemModel)));
		}

		if (!$ItemModel->isBuyable($data)) {
			// throw exception?
			return false;
		}

		$data = $ItemModel->beforeAddToCart($data);

		if ($data === false || !is_array($data) || !$this->CartModel->CartsItem->validateItem($data, $this->_isLoggedIn)) {
			$this->validationErrors = $this->CartModel->CartsItem->invalidFields;
			if (Configure::read('debug') > 0 && !empty($this->CartModel->CartsItem->invalidFields)) {
				throw new RuntimeException(__d('cart', 'Cart item did not validate!'));
			}
			return false;
		}

		if ($this->_isLoggedIn) {
			$data = $this->CartModel->addItem($this->_cartId, $data, array(
				'validates' => false // Has been already validated before!
			));
			if ($data === false) {
				return false;
			}
			$data = $data['CartsItem'];
		}

		$result = $this->CartSession->addItem($data);
		if ($recalculate) {
			$this->calculateCart();
		}

		$Event = new CakeEvent('CartManager.afterAddItem', $this, array($result));
		$this->_EventManager->dispatch($Event);
		return $result;
	}

/**
 * Removes an item from the cart session and if a user is logged in from the database
 *
 * @param array $data
 * @return boolean
 */
	public function removeItem($data = null) {
		extract($this->settings);

		$Event = new CakeEvent('CartManager.beforeRemoveItem', $this, array($data));
		$this->_EventManager->dispatch($Event);
		if ($Event->isStopped()) {
			return false;
		}

		if ($this->_isLoggedIn) {
			if (!$this->CartModel->removeItem($this->_cartId, $data['CartsItem'])) {
				return false;
			}
		}

		$result = $this->CartSession->removeItem($data['CartsItem']);
		$this->calculateCart();

		$Event = new CakeEvent('CartManager.afterRemoveItem', $this, array($result));
		$this->_EventManager->dispatch($Event);

		return $result;
	}

/**
 * Drops all items and re-initializes the cart
 *
 * @return boolean
 */
	public function emptyCart() {
		if ($this->_isLoggedIn) {
			$this->CartModel->emptyCart($this->_cartId);
		}

		if ($this->settings['useCookie'] === true) {
			$this->Cookie->delete($this->settings['cookieName']);
		}

		$result = $this->CartSession->emptyCart();

		$this->initializeCart();
		return $result;
	}

/**
 * Cart content
 *
 * @param array $options
 * @return array
 */
	public function content($options = array()) {
		$defaults = array(
			'unserialize' => true,
		);
		$options = Hash::merge($defaults, $options);
		$cart = $this->CartSession->read();
		if ($options['unserialize'] === true) {
			foreach ($cart['CartsItem'] as $key => &$cartItem) {
				if (isset($cartItem['additional_data'])) {
					$cartItem['additional_data'] = unserialize($cartItem['additional_data']);
				}
			}
		}
		return $cart;
	}

/**
 * Find if an item that already exists in the cart
 *
 * @param mixed $id integer or string uuid
 * @param string $model Model name
 * @return boolean
 */
	public function contains($id, $model) {
		return $this->getItemKey($id, $model) !== false;
	}

/**
 * Find the item key
 *
 * @param mixed $id integer or string uuid
 * @param string $model Model name
 * @return mixed False or key of the array entry in the cart session
 */
	public function getItemKey($id, $model) {
		return $this->CartSession->getItemKey($id, $model);
	}

/**
 * @param $id
 * @param $model
 * @param string $field
 * @return bool
 * @internal param $
 */
	public function getItem($id, $model, $field = '') {
		$key = $this->getItemKey($id, $model);
		if ($key === false) {
			return false;
		}

		if (!empty($field)) {
			$field = '.' . $field;
		}

		return $this->CartSession->read('CartsItem.' . $key . $field);
	}

/**
 * Checks if the cart requires shipping
 *
 * @return boolean
 */
	public function requiresShipping() {
		return (bool)$this->Session->read($this->settings['sessionKey'] . '.Cart.requires_shipping');
	}

/**
 * (Re-)calculates a cart, this will run over all items, coupons and taxes
 *
 * @param array $options
 * @return array the cart data
 */
	public function calculateCart($options = array()) {
		$cartData = $this->Session->read($this->settings['sessionKey']);

		if (isset($options['cartData'])) {
			$cartData = Hash::merge($cartData, $options['cartData']);
		}

		$cartData = $this->CartModel->calculateCart($cartData, $options);

		if ($this->_isLoggedIn) {
			$this->CartModel->saveAll($cartData);
		}

		$this->Session->write($this->settings['sessionKey'], $cartData);
		return $cartData;
	}

/**
 * Stores the whole cart in a cookie
 *
 * Use this in the case the user is not logged in to make it semi-persistant
 *
 * @return boolean
 */
	public function writeCookie() {
		return $this->Cookie->write($this->settings['cookieName'], $this->content());
	}

/**
 * Used to restore a cart from a cookie
 *
 * Use this in the case the user was not logged in and left the page for a longer time
 *
 * @return boolean true on success
 */
	public function restoreFromCookie() {
		$result = $this->Cookie->read($this->settings['cookieName']);
		$this->Session->write($this->settings['sessionKey'], $result);
		return (!empty($result));
	}

/**
 * Adds multiple items to the cart, the session and database if a user is logged in
 *
 * @param $items
 * @param string $type Buy type, 'update' will replace quantity if present in cart, 'increment' will add to existing quantity
 * @throws Exception
 * @return boolean
 */
	public function updateItems($items, $type = 'update') {
		try {
			$results = array();
			foreach ($items as $item) {
				$item[$type] = true;
				$results[] = $this->updateItem(array('CartsItem' => $item), false);
			}
			$this->calculateCart();
			return (!in_array(false, $results, true));
		} catch (Exception $e) {
			throw $e;
		}
	}

/**
 * shutdown callback
 *
 * @param Controller $controller
 * @return void
 */
	public function shutdown(Controller $controller) {
		if ($this->settings['useCookie']) {
			$this->writeCookie();
		}
	}

}


text:
package pubsub

import com.spotify.scio.pubsub._
import com.spotify.scio.values.SCollection
import com.spotify.scio.{Args, ContextAndArgs, ScioContext}
import org.slf4j.LoggerFactory

object WriteWithAttributes {

  private val log = LoggerFactory.getLogger(this.getClass)

  def main(cmdlineArgs: Array[String]): Unit = {
    val (scontext: ScioContext, opts: Args) = ContextAndArgs(cmdlineArgs)
    implicit val sc: ScioContext = scontext

    // pipeline option parameter
    val pubsubOutputTopic: String = opts("outputTopic")

    val elements = Seq(
      ("Carlos", 27, "Spain"),
      ("Maria", 27, "UK"),
      ("Ruben", 15, "Japan"),
      ("Juana", 38, "Ghana"),
      ("Kim", 77, "Brazil")
    )

    val create: SCollection[(String, Int, String)] = sc.parallelize(elements)

    val pubsubMessages = create
      .map { element: (String, Int, String) =>
        // Map has to be [String, String]
        val attributesMap = Map(
          "age" -> element._2.toString,
          "country" -> element._3
        )
        (element._1, attributesMap)
      }
      .write(PubsubIO.withAttributes[String](pubsubOutputTopic))(PubsubIO.WriteParam())

    sc.run()
  }

}


text:
module.exports = {
  server: "http://pharmacy.emre.sh",
  endpoints: {
    districts: "/api/v1/istanbul/",
    pharmacies: "/api/v1/istanbul/%s"
  },
  request_headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }
}


text:
using System;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;

namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
    /// <summary>
    /// Base class of a all test-containing classes. Automatically creates a FileCodeModel for testing with the given
    /// file.
    /// </summary>
    public abstract class AbstractFileCodeElementTests : IDisposable
    {
        protected TestWorkspace Workspace { get; }
        protected FileCodeModel CodeModel { get; }

        protected Microsoft.CodeAnalysis.Solution CurrentSolution { get; }
        protected Microsoft.CodeAnalysis.Project CurrentProject { get; }
        protected Microsoft.CodeAnalysis.Document CurrentDocument { get; }

        public AbstractFileCodeElementTests(string file)
        {
            var pair = FileCodeModelTestHelpers.CreateWorkspaceAndFileCodeModel(file);
            Workspace = pair.Item1;
            CodeModel = pair.Item2;

            CurrentSolution = Workspace.CurrentSolution;
            CurrentProject = CurrentSolution.Projects.Single();
            CurrentDocument = CurrentProject.Documents.Single();
        }

        protected CodeElement GetCodeElement(params object[] path)
        {
            if (path.Length == 0)
            {
                throw new ArgumentException("path must be non-empty.", "path");
            }

            CodeElement codeElement = CodeModel.CodeElements.Item(path[0]);

            foreach (var pathElement in path.Skip(1))
            {
                codeElement = codeElement.Children.Item(pathElement);
            }

            return codeElement;
        }

        public void Dispose()
        {
            Workspace.Dispose();
        }

        /// <summary>
        /// Returns the current text of the test buffer.
        /// </summary>
        protected string GetFileText()
        {
            return Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText();
        }
    }
}


text:
/*
 * Created on Jun 27, 2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package com.cosylab.acs.jms;

import javax.jms.JMSException;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;

import alma.acs.container.ContainerServicesBase;
import alma.acs.exceptions.AcsJException;
import alma.acs.nc.AcsEventSubscriber;
import alma.acscommon.ACS_NC_DOMAIN_ALARMSYSTEM;
import alma.acsnc.EventDescription;

/**
 * @author kzagar
 */
public class ACSJMSTopicSubscriber
	extends ACSJMSConsumer implements TopicSubscriber, AcsEventSubscriber.Callback<ACSJMSMessageEntity> {

	private AcsEventSubscriber<ACSJMSMessageEntity> consumer;

	/**
	 * @param destination
	 * @param containerServices
	 * @param selector
	 * @throws AcsJException
	 * @throws JMSException
	 */
	public ACSJMSTopicSubscriber(Topic topic, ContainerServicesBase containerServices, String selector) throws JMSException {
		super(topic, containerServices,selector);
		try {
			consumer = containerServices.createNotificationChannelSubscriber(
					topic.getTopicName(), ACS_NC_DOMAIN_ALARMSYSTEM.value, ACSJMSMessageEntity.class);
			consumer.addSubscription(this);
			consumer.startReceivingEvents();
		} catch (AcsJException e) {
			System.err.println("Error creating the subscriber: "+e.getMessage());
			e.printStackTrace(System.err);
			throw new JMSException("Error creating topic subscriber: " + e.getMessage());
		}
	}

	/* (non-Javadoc)
	 * @see javax.jms.TopicSubscriber#getTopic()
	 */
	public Topic getTopic() throws JMSException {
		return (Topic)this.destination;
	}

	/* (non-Javadoc)
	 * @see javax.jms.TopicSubscriber#getNoLocal()
	 */
	public boolean getNoLocal() throws JMSException {
		throw new UnsupportedOperationException();
	}

	/**
	 * The NC subscriber callback method.
	 */
	@Override
	public void receive(ACSJMSMessageEntity eventData, EventDescription eventDescrip) {
		// let base class handle it
		receive(eventData);
	}

	@Override
	public Class<ACSJMSMessageEntity> getEventType() {
		return ACSJMSMessageEntity.class;
	}

	/* (non-Javadoc)
	 * @see javax.jms.MessageConsumer#close()
	 */
	public void close() throws JMSException {
		if(consumer != null) {
			try {
				this.consumer.disconnect();
			} catch (Exception ex) {
				JMSException ex2 = new JMSException("Failed to disconnect NC subscriber for topic " + getTopic().getTopicName());
				ex2.setLinkedException(ex);
				throw ex2;
			}
		}
	}
}


text:
'use strict';

define(['controllers/_controllers', 'services/RecipeSvc', 'directives/paginationDrtv'], function(controllers) {

    controllers.controller('RecipeListCtrl', ['$scope', 'Recipe', 'recipe',
        function($scope, Recipe, recipe) {
            $scope.recipes = recipe.list;

            $scope.totalItems = $scope.orderNo = recipe.count;
            $scope.currentPage = 1;
            $scope.itemsPerPage = recipe.limit;

            $scope.setPage = function(pageNo) {
                $scope.currentPage = pageNo;
            };

            $scope.pageChanged = function() {
                Recipe.list({
                    page: $scope.currentPage
                }).then(function(data) {
                    $scope.recipes = data.list;
                });

                $scope.orderNo = recipe.count - ($scope.currentPage - 1) * recipe.limit;
                console.log('Page changed to: ' + $scope.currentPage);
            };

            $scope.maxSize = 5;
            $scope.bigTotalItems = 175;
            $scope.bigCurrentPage = 1;
        }
    ]);

    controllers.controller('RecipeViewCtrl', ['$scope', '$location', 'recipe',
        function($scope, $location, recipe) {
            $scope.recipe = recipe;

            $scope.edit = function() {
                $location.path('/recipe/edit/' + recipe._id);
            };
        }
    ]);

    controllers.controller('RecipeEditCtrl', ['$scope', '$location', 'recipe',
        function($scope, $location, recipe) {
            $scope.recipe = recipe;
            $scope.recipe.recipeId = recipe._id;

            $scope.save = function() {
                $scope.recipe.$update(function(data) {
                    alert(data._id);

                    $location.path('/recipe/view/' + data._id);
                });
            }

            $scope.remove = function() {
                $scope.recipe.$delete(function(data) {
                    alert(data._id);

                    delete $scope.recipe;
                    $location.path('/recipe');
                });
            }
        }
    ]);

    controllers.controller('RecipeNewCtrl', ['$scope', '$location', 'Recipe',
        function($scope, $location, Recipe) {
            $scope.recipe = new Recipe.conn({
                ingredients: [ {} ]
            });

            $scope.save = function() {
                $scope.recipe.$save(function(data) {
                    alert(data._id);

                    // $location.path('/recipe/view/' + recipe.id);
                    $location.path('/recipe');
                });
            }
        }
    ]);

    controllers.controller('RecipeIngredientsCtrl', ['$scope',
        function($scope) {
            $scope.addIngredient = function() {
                var ingredients = $scope.recipe.ingredients;
                ingredients[ingredients.length] = {};
            };

            $scope.removeIngredient = function(index) {
                $scope.recipe.ingredients.splice(index, 1);
            };
        }
    ]);

});


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

<TITLE>
DisplayMode (Java 2 Platform SE 5.0)
</TITLE>
<meta name="collection" content="api">

<META NAME="keywords" CONTENT="java.awt.DisplayMode class">
<META NAME="keywords" CONTENT="BIT_DEPTH_MULTI">
<META NAME="keywords" CONTENT="REFRESH_RATE_UNKNOWN">
<META NAME="keywords" CONTENT="getHeight()">
<META NAME="keywords" CONTENT="getWidth()">
<META NAME="keywords" CONTENT="getBitDepth()">
<META NAME="keywords" CONTENT="getRefreshRate()">
<META NAME="keywords" CONTENT="equals()">
<META NAME="keywords" CONTENT="hashCode()">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

java.awt

Class DisplayMode

java.lang.Object
  java.awt.DisplayMode

public final class DisplayMode
extends Object

The DisplayMode class encapsulates the bit depth, height,
 width, and refresh rate of a GraphicsDevice.  Display modes
 are hardware-dependent and may not always be available.

Since:

1.4

See Also:
GraphicsDevice

Field Summary

static int
BIT_DEPTH_MULTI

          Value of the bit depth if multiple bit depths are supported in this
 dislay mode.

static int
REFRESH_RATE_UNKNOWN

          Value of the refresh rate if not known

Constructor Summary

DisplayMode(int width,
            int height,
            int bitDepth,
            int refreshRate)

          Create a new display mode object with the supplied parameters.

Method Summary

 boolean
equals(DisplayMode dm)

 boolean
equals(Object dm)

          Indicates whether some other object is "equal to" this one.

 int
getBitDepth()

 int
getHeight()

 int
getRefreshRate()

 int
getWidth()

 int
hashCode()

          Returns a hash code value for the object.

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Field Detail

BIT_DEPTH_MULTI

public static final int BIT_DEPTH_MULTI

Value of the bit depth if multiple bit depths are supported in this
 dislay mode.

See Also:
getBitDepth(),
Constant Field Values

REFRESH_RATE_UNKNOWN

public static final int REFRESH_RATE_UNKNOWN

Value of the refresh rate if not known

See Also:
getRefreshRate(),
Constant Field Values

Constructor Detail

DisplayMode

public DisplayMode(int width,
                   int height,
                   int bitDepth,
                   int refreshRate)

Create a new display mode object with the supplied parameters.

Parameters:
width - the width of the display, in pixels
height - the height of the display, in pixels
bitDepth - the bit depth of the display, in bits per
        pixel.  This can be BIT_DEPTH_MULTI if multiple
        bit depths are available.
refreshRate - the refresh rate of the display, in hertz.
        This can be REFRESH_RATE_UNKNOWN if the
        information is not available.
See Also:
BIT_DEPTH_MULTI,
REFRESH_RATE_UNKNOWN

Method Detail

getHeight

public int getHeight()

Returns:
the height of the display, in pixels

getWidth

public int getWidth()

Returns:
the width of the display, in pixels

getBitDepth

public int getBitDepth()

Returns:
the bit depth of the display, in bits per pixel.  This may be
 BIT_DEPTH_MULTI if multiple bit depths are supported in
 this display mode.
See Also:
BIT_DEPTH_MULTI

getRefreshRate

public int getRefreshRate()

Returns:
the refresh rate of the display, in hertz.  This may be
 REFRESH_RATE_UNKNOWN if the information is not available.
See Also:
REFRESH_RATE_UNKNOWN

equals

public boolean equals(DisplayMode dm)

Returns:
whether the two display modes are equal

equals

public boolean equals(Object dm)

Description copied from class: Object

Indicates whether some other object is "equal to" this one.

 The equals method implements an equivalence relation
 on non-null object references:

It is reflexive: for any non-null reference value
     x, x.equals(x) should return
     true.

It is symmetric: for any non-null reference values
     x and y, x.equals(y)
     should return true if and only if
     y.equals(x) returns true.

It is transitive: for any non-null reference values
     x, y, and z, if
     x.equals(y) returns true and
     y.equals(z) returns true, then
     x.equals(z) should return true.

It is consistent: for any non-null reference values
     x and y, multiple invocations of
     <tt>x.equals(y)</tt> consistently return true
     or consistently return false, provided no
     information used in equals comparisons on the
     objects is modified.

For any non-null reference value x,
     x.equals(null) should return false.

 The <tt>equals</tt> method for class Object implements
 the most discriminating possible equivalence relation on objects;
 that is, for any non-null reference values x and
 y, this method returns true if and only
 if x and y refer to the same object
 (x == y has the value true).

 Note that it is generally necessary to override the <tt>hashCode</tt>
 method whenever this method is overridden, so as to maintain the
 general contract for the <tt>hashCode</tt> method, which states
 that equal objects must have equal hash codes.

Overrides:
equals in class Object

Parameters:
dm - the reference object with which to compare.

Returns:
whether the two display modes are equal
See Also:
Object.hashCode(),
Hashtable

hashCode

public int hashCode()

Description copied from class: Object

Returns a hash code value for the object. This method is
 supported for the benefit of hashtables such as those provided by
 java.util.Hashtable.

 The general contract of hashCode is:

Whenever it is invoked on the same object more than once during
     an execution of a Java application, the <tt>hashCode</tt> method
     must consistently return the same integer, provided no information
     used in <tt>equals</tt> comparisons on the object is modified.
     This integer need not remain consistent from one execution of an
     application to another execution of the same application.

If two objects are equal according to the <tt>equals(Object)</tt>
     method, then calling the hashCode method on each of
     the two objects must produce the same integer result.

It is not required that if two objects are unequal
     according to the Object.equals(java.lang.Object)
     method, then calling the <tt>hashCode</tt> method on each of the
     two objects must produce distinct integer results.  However, the
     programmer should be aware that producing distinct integer results
     for unequal objects may improve the performance of hashtables.

 As much as is reasonably practical, the hashCode method defined by
 class <tt>Object</tt> does return distinct integers for distinct
 objects. (This is typically implemented by converting the internal
 address of the object into an integer, but this implementation
 technique is not required by the
 JavaTM programming language.)

Overrides:
hashCode in class Object

Returns:
a hash code value for this object
See Also:
Object.equals(java.lang.Object),
Hashtable

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


text:
#ifndef TUDAT_JSONESTIMATIONINTERFACE_H
#define TUDAT_JSONESTIMATIONINTERFACE_H

#include "tudat/interface/json/unitTestSupport.h"
#include "tudat/interface/json/propagation/acceleration.h"
#include "tudat/interface/json/estimation/observation.h"
#include "tudat/interface/json/estimation/parameter.h"
#include "tudat/interface/json/estimation/orbitDetermination.h"
#include "tudat/interface/json/support/valueConversions.h"
#include "tudat/interface/json/jsonInterfaceVariational.h"

#include "tudat/simulation/estimation.h"

namespace tudat
{

namespace json_interface
{

//! Class for managing JSON-based simulations.
template< typename TimeType = double, typename StateScalarType = double >
class JsonEstimationManager: public JsonVariationalEquationsSimulationManager< TimeType, StateScalarType >
{

public:

    using JsonSimulationManager< TimeType, StateScalarType >::jsonObject_;
    using JsonSimulationManager< TimeType, StateScalarType >::applicationOptions_;
    using JsonSimulationManager< TimeType, StateScalarType >::profiling;
    using JsonSimulationManager< TimeType, StateScalarType >::initialClockTime_;
    using JsonSimulationManager< TimeType, StateScalarType >::inputFilePath_;
    using JsonSimulationManager< TimeType, StateScalarType >::dynamicsSimulator_;
    using JsonSimulationManager< TimeType, StateScalarType >::bodies_;
    using JsonSimulationManager< TimeType, StateScalarType >::integratorSettings_;
    using JsonSimulationManager< TimeType, StateScalarType >::propagatorSettings_;
    using JsonSimulationManager< TimeType, StateScalarType >::exportAsJson;

    using JsonVariationalEquationsSimulationManager< TimeType, StateScalarType >::variationalEquationsSolver_;
    using JsonVariationalEquationsSimulationManager< TimeType, StateScalarType >::parametersToEstimate_;

    //! Constructor from JSON file.
    /*!
     * Constructor.
     * \param inputFilePath Path to the root JSON input file. Can be absolute or relative (to the working directory).
     * \param initialClockTime Initial clock time from which the cummulative CPU time during the propagation will be
     * computed. Default is the moment at which the constructor was called.
     */
    JsonEstimationManager(
            const std::string& inputFilePath,
            const std::chrono::steady_clock::time_point initialClockTime = std::chrono::steady_clock::now( ) ):
        JsonVariationalEquationsSimulationManager< TimeType, StateScalarType >( inputFilePath, initialClockTime )
    { }

    //! Constructor from JSON object.
    /*!
     * Constructor.
     * \param jsonObject The root JSON object.
     * \param initialClockTime Initial clock time from which the cummulative CPU time during the propagation will be
     * computed. Default is the moment at which the constructor was called.
     */
    JsonEstimationManager(
            const nlohmann::json& jsonObject,
            const std::chrono::steady_clock::time_point initialClockTime = std::chrono::steady_clock::now( ) ):
        JsonVariationalEquationsSimulationManager< TimeType, StateScalarType >( jsonObject, initialClockTime ){ }

    virtual ~JsonEstimationManager( ){ }

    virtual void updateSettings( )
    {
        std::cout<<"T1"<<std::endl;
        JsonVariationalEquationsSimulationManager< TimeType, StateScalarType >::updateSettings( );
        std::cout<<"T2"<<std::endl;

        resetObservationSettings( );
        std::cout<<"T3"<<std::endl;

        resetEstimationSettings( );
        std::cout<<"T4"<<std::endl;
        createSimulationObjects( );
        std::cout<<"T5"<<std::endl;

    }

    virtual void runJsonSimulation( )
    {
        estimationOutput_ = orbitDeterminationManager_->estimateParameters( estimationInput_, convergenceChecker_ );
    }

    //! Export the results of the dynamics simulation according to the export settings.
    /*!
     * @copybrief exportResults
     */
    void exportEstimationResults( )
    {

    }

protected:

    void resetObservationSettings( )
    {
        observationSettingsMap_ = getValue< observation_models::ObservationSettingsListPerLinkEnd >(
            jsonObject_, Keys::observations );
        std::cout<<"Size of obs. settings "<<observationSettingsMap_.size( )<<std::endl;

        if ( profiling )
        {

            std::cout << "resetObservationSettings: " << std::chrono::duration_cast< std::chrono::milliseconds >(
                             std::chrono::steady_clock::now( ) - initialClockTime_ ).count( ) * 1.0e-3 << " s" << std::endl;
            initialClockTime_ = std::chrono::steady_clock::now( );
        }
    }

    void resetEstimationSettings( )
    {
        updatePodSettingsFromJSON(
                    jsonObject_[ Keys::estimationSettings ], estimationInput_, convergenceChecker_, parametersToEstimate_->getParameterSetSize( )  );

        if ( profiling )
        {
            std::cout << "resetEstimationSettings: " << std::chrono::duration_cast< std::chrono::milliseconds >(
                             std::chrono::steady_clock::now( ) - initialClockTime_ ).count( ) * 1.0e-3 << " s" << std::endl;
            initialClockTime_ = std::chrono::steady_clock::now( );
        }
    }

    //! Reset dynamicsSimulator_ for the current bodies_, integratorSettings_ and propagatorSettings_.
    /*!
     * @copybrief resetDynamicsSimulator
     */
    virtual void resetDynamicsSimulator( )
    {
        this->createSimulationObjects( );
    }

    virtual void resetVariationalEquationsSolver( )
    {
        this->createSimulationObjects( );
    }

    virtual void createSimulationObjects( )
    {
        orbitDeterminationManager_ =
                std::make_shared< simulation_setup::OrbitDeterminationManager< StateScalarType, TimeType > >(
                    bodies_, parametersToEstimate_, observation_models::convertUnsortedToSortedObservationSettingsMap(
                        observationSettingsMap_ ), integratorSettings_, propagatorSettings_,
                    false );
        variationalEquationsSolver_ =
                std::dynamic_pointer_cast< propagators::SingleArcVariationalEquationsSolver< StateScalarType, TimeType > >(
                    orbitDeterminationManager_->getVariationalEquationsSolver( ) );
        dynamicsSimulator_ = variationalEquationsSolver_->getDynamicsSimulator( );
        std::cout<<"check NULL "<<( variationalEquationsSolver_ == NULL )<<" "<<
                   ( orbitDeterminationManager_->getVariationalEquationsSolver( ) == NULL )<<std::endl;
    }

private:

    observation_models::ObservationSettingsListPerLinkEnd observationSettingsMap_;

    std::shared_ptr< simulation_setup::OrbitDeterminationManager< StateScalarType, TimeType > > orbitDeterminationManager_;

    std::shared_ptr< simulation_setup::EstimationConvergenceChecker > convergenceChecker_;

    std::shared_ptr< simulation_setup::PodInput< StateScalarType, TimeType > > estimationInput_;

    std::shared_ptr< simulation_setup::PodOutput< StateScalarType, TimeType > > estimationOutput_;

};

extern template class JsonEstimationManager< double, double >;

//#if( BUILD_EXTENDED_PRECISION_PROPAGATION_TOOLS )
//extern template class JsonEstimationManager< Time, long double >;
//extern template class JsonEstimationManager< double, double >;
//extern template class JsonEstimationManager< Time, long double >;
//#endif

} // namespace json_interface

} // namespace tudat

#endif // TUDAT_JSONESTIMATIONINTERFACE_H


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Res. 97(5): 614 (1993)

#### Original name
Hydnangium sublamellatum Bougher, Tommerup & Malajczuk

### Remarks
null


text:
import os
import PyPDF2
from PyPDF2.pdf import ContentStream
from PyPDF2.pdf import TextStringObject
from mako.template import Template

class Piu(object):

    def __init__(self, file_path):
        self.file_path = file_path

    def _get_pages(self):
        pdf = PyPDF2.PdfFileReader(open(self.file_path, "rb"))
        return pdf.pages

    def _read_page_content(self, page):
        content = page["/Contents"].getObject()
        if not isinstance(content, ContentStream):
            content = ContentStream(content, page.pdf)
        return content

    def text(self):
        """
        Return an array of texts.The text of nth page' index is n - 1.
        """
        texts = []
        for page in self._get_pages():
            text = self._extract_text(page)
            texts.append(text)

        return texts

    def _handle_content_stream_operator(self, content):
        # PDF operators
        # https://github.com/galkahana/HummusJS/wiki/Use-the-pdf-drawing-operators#operators-list
        # Tj|TJ: apply the Tj operator, which shows text, on the text string
        text = u""
        for operands, operator in content.operations:
            if operator == "Tj":
                _text = operands[0]
                if isinstance(_text, TextStringObject):
                    text += _text

            # T*: text state operators | text position operators
            elif operator == "T*":
                text += "\n"

            # Quote|DoubleQuote: text showing operations
            elif operator == "'":
                text += "\n"
                _text = operands[0]
                if isinstance(_text, TextStringObject):
                    text += operands[0]
            elif operator == '"':
                _text = operands[2]
                if isinstance(_text, TextStringObject):
                    text += "\n"
                    text += _text
            elif operator == "TJ":
                for i in operands[0]:
                    if isinstance(i, TextStringObject):
                        text += i
            text = self._make_string_space(text)
        return text

    def _extract_text(self, page):
        content = self._read_page_content(page)
        return self._handle_content_stream_operator(content)

    def _make_string_space(self, text):
        text = text or ""
        if not text.endswith(" "):
            text += " "
        return text

    def _invoke_gs(self, cmd_options):
        ghostscript = os.environ.get("GHOSTSCRIPT", "gs")
        print cmd_options
        cmd = "%s %s" % (ghostscript, cmd_options)
        return os.system(cmd)

    def _build_cmd_options(self, src, filename, options):
        # default
        cmd_options = ""
        default_options = {
            "-dNOPAUSE": True,
            "-dPDFFitPage": True,
            "-dTextAlphaBits": 4,
            "-sDEVICE": "jpeg",
            "-dJPEG": 80,
            "-dDEVICEWIDTH": 620,
            "-dDEVICEHEIGHT": 480,
        }
        merged_options = default_options.copy()
        merged_options.update(options)
        for option, value in merged_options.items():
            if value is True:
                cmd_options += "%s " % option
            else:
                cmd_options += "%s=%s " % (option, str(value))
        cmd_options += "-sOutputFile=%s " % filename
        cmd_options += "%s -c quit" % src
        return cmd_options

    def create_images(self, output, index=True, prefix="slide", options={}):

        if not os.path.exists(output):
            os.makedirs(output)

        src = self.file_path
        output = output.rstrip("/")
        filename = "%(output)s/%(prefix)s%%d.jpg" % locals()

        cmd_options = self._build_cmd_options(src, filename, options)
        self._invoke_gs(cmd_options)

        if index:
            relative_path = "%s/" % output
            self._create_index(prefix=relative_path)

    def _create_index(self, filename="index.html", prefix="", template=""):
        html = ""
        if not template:
            template = os.path.join(os.path.abspath(os.path.dirname(__file__)), "templates/slides.html")
        texts = self.text()
        with open(template, "rb") as f:
            template = f.read()
            html += Template(template).render(texts=texts, prefix=prefix)

        with open(filename, "wt") as f:
            f.write(html)


text:
<?php

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/database.php';

use Illuminate\Database\Capsule\Manager as Capsule;

?><!doctype html>

    <meta charset="utf-8">
    <title>Asistente de instalación Virtuágora</title>
    <link rel="stylesheet" href="assets/css/app.css" />

<?php if(isset($_POST['submit'])) {
$titulo = '¡Virtuágora se ha instalado exitosamente!';
$descrp = 'Ya puede comenzar a utilizar la plataforma, pero primero elimine este archivo para evitar inconvenientes de seguridad.';
$exito = true;
try {
    if (Capsule::schema()->hasTable('ajustes')) {
        $titulo = '¡Ha ocurrido un error!';
        $descrp = 'La plataforma parece ya estar instalada.';
        $exito = true;
    } else {
        Capsule::schema()->create('ajustes', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('key')->unique();
            $table->string('value_type');
            $table->integer('int_value')->nullable();
            $table->string('str_value')->nullable();
            $table->text('txt_value')->nullable();
            $table->string('description');
            $table->timestamps();
        });
        Capsule::schema()->create('usuarios', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('nombre');
            $table->string('apellido');
            $table->integer('img_tipo')->unsigned();
            $table->string('img_hash');
            $table->string('huella')->nullable();
            $table->integer('puntos')->default(0);
            $table->string('advertencia')->nullable();
            $table->boolean('suspendido')->default(0);
            $table->boolean('es_funcionario')->default(0);
            $table->boolean('es_jefe')->default(0);
            $table->string('dni')->nullable();
            $table->string('token')->nullable()->default(null);
            $table->timestamp('verified_at')->nullable();
            $table->timestamp('fin_advertencia')->nullable();
            $table->timestamp('fin_suspension')->nullable();
            $table->integer('partido_id')->unsigned()->nullable();
            $table->integer('patrulla_id')->unsigned()->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('preusuarios', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('nombre');
            $table->string('apellido');
            $table->string('emailed_token');
            $table->timestamps();
        });
        Capsule::schema()->create('partidos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('nombre')->unique();
            $table->string('acronimo');
            $table->text('descripcion');
            $table->string('huella')->nullable();
            $table->string('fundador')->nullable();
            $table->date('fecha_fundacion')->nullable();
            $table->integer('creador_id')->unsigned();
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('organismos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('nombre');
            $table->text('descripcion');
            $table->integer('cupo')->unsigned();
            $table->string('huella')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('funcionarios', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('usuario_id')->unsigned();
            $table->integer('organismo_id')->unsigned();
            $table->foreign('usuario_id')->references('id')->on('usuarios')->onDelete('cascade');
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('contactos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->morphs('contactable');
            $table->string('email')->nullable();
            $table->string('telefono')->nullable();
            $table->string('web')->nullable();
            $table->timestamps();
        });
        Capsule::schema()->create('acciones', function($table) {
            $table->engine = 'InnoDB';
            $table->string('id', 10)->primary();
            $table->string('nombre');
        });
        Capsule::schema()->create('userlogs', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->morphs('objeto');
            $table->string('accion_id', 10);
            $table->integer('actor_id')->unsigned();
            $table->foreign('actor_id')->references('id')->on('usuarios')->onDelete('cascade');
            $table->timestamps();
        });
        Capsule::schema()->create('notificaciones', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->morphs('notificable');
            $table->integer('usuario_id')->unsigned();
            $table->foreign('usuario_id')->references('id')->on('usuarios')->onDelete('cascade');
            $table->softDeletes();
        });
        Capsule::schema()->create('patrullas', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('nombre');
            $table->text('descripcion');
            $table->timestamps();
        });
        Capsule::schema()->create('poderes', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('nombre');
            $table->string('descripcion');
        });
        Capsule::schema()->create('patrulla_poder', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('patrulla_id')->unsigned();
            $table->integer('poder_id')->unsigned();
            $table->foreign('patrulla_id')->references('id')->on('patrullas')->onDelete('cascade');
            $table->foreign('poder_id')->references('id')->on('poderes')->onDelete('cascade');
        });
        Capsule::schema()->create('adminlogs', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('descripcion');
            $table->string('subclase');
            $table->morphs('objeto');
            $table->integer('poder_id')->unsigned();
            $table->integer('actor_id')->unsigned();
            $table->foreign('actor_id')->references('id')->on('usuarios')->onDelete('cascade');
            $table->timestamps();
        });
        Capsule::schema()->create('categorias', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('nombre');
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('contenidos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->morphs('contenible');
            $table->string('titulo');
            $table->string('huella')->nullable();
            $table->integer('puntos')->unsigned()->default(0);
            $table->integer('impulsor_id')->unsigned()->nullable();
            $table->integer('referido_id')->unsigned()->nullable();
            $table->integer('categoria_id')->unsigned();
            $table->integer('autor_id')->unsigned();
            $table->foreign('autor_id')->references('id')->on('usuarios')->onDelete('cascade');
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('tags', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('nombre');
            $table->string('huella')->nullable();
            $table->integer('menciones')->unsigned()->default(0);
            $table->timestamps();
        });
        Capsule::schema()->create('taggables', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->morphs('taggable');
            $table->integer('tag_id')->unsigned();
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
        });
        Capsule::schema()->create('propuestas', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->text('cuerpo');
            $table->integer('votos_favor')->unsigned()->default(0);
            $table->integer('votos_contra')->unsigned()->default(0);
            $table->integer('votos_neutro')->unsigned()->default(0);
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('propuesta_votos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('postura');
            $table->boolean('publico');
            $table->integer('usuario_id')->unsigned();
            $table->integer('propuesta_id')->unsigned();
            $table->foreign('propuesta_id')->references('id')->on('propuestas')->onDelete('cascade');
            $table->timestamps();
        });
        Capsule::schema()->create('problematicas', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->text('cuerpo');
            $table->integer('afectados_directos')->unsigned()->default(0);
            $table->integer('afectados_indirectos')->unsigned()->default(0);
            $table->integer('afectados_indiferentes')->unsigned()->default(0);
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('problematica_votos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('postura')->unsigned();
            $table->integer('usuario_id')->unsigned();
            $table->integer('problematica_id')->unsigned();
            $table->foreign('problematica_id')->references('id')->on('problematicas')->onDelete('cascade');
            $table->timestamps();
        });
        Capsule::schema()->create('documentos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('descripcion');
            $table->integer('ultima_version')->unsigned();
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('documento_versiones', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('version')->unsigned();
            $table->integer('documento_id')->unsigned();
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('documento_parrafos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->text('cuerpo');
            $table->integer('ubicacion')->unsigned();
            $table->integer('version_id')->unsigned();
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('novedades', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->text('cuerpo');
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('eventos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->text('cuerpo');
            $table->string('lugar');
            $table->timestamp('fecha');
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('evento_usuario', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->boolean('presente');
            $table->boolean('publico');
            $table->integer('usuario_id')->unsigned();
            $table->integer('evento_id')->unsigned();
            $table->foreign('evento_id')->references('id')->on('eventos')->onDelete('cascade');
            $table->timestamps();
        });
        Capsule::schema()->create('comentarios', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->morphs('comentable');
            $table->text('cuerpo');
            $table->integer('votos')->default(0);
            $table->integer('autor_id')->unsigned();
            $table->foreign('autor_id')->references('id')->on('usuarios')->onDelete('cascade');
            $table->timestamps();
            $table->softDeletes();
        });
        Capsule::schema()->create('comentario_votos', function($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('valor');
            $table->integer('usuario_id')->unsigned();
            $table->integer('comentario_id')->unsigned();
            $table->foreign('comentario_id')->references('id')->on('comentarios')->onDelete('cascade');
            $table->timestamps();
        });
        $ajuste = new Ajuste;
        $ajuste->key = 'tos';
        $ajuste->value_type = 'txt';
        $ajuste->value = 'Términos y condiciones de uso.';
        $ajuste->description = 'Términos y condiciones para el uso de la plataforma.';
        $ajuste->save();
        $categoria = new Categoria;
        $categoria->nombre = 'General';
        $categoria->save();
        $usuario = new Usuario;
        $usuario->email = $_POST['usr_email'];
        $usuario->password = password_hash($_POST['usr_password'], PASSWORD_DEFAULT);
        $usuario->nombre = $_POST['usr_nombre'];
        $usuario->apellido = $_POST['usr_apellido'];
        $usuario->img_tipo = 1;
        $usuario->img_hash = md5(strtolower(trim($usuario->email)));
        $patrulla = new Patrulla;
        $patrulla->nombre = 'Aministrador';
        $patrulla->descripcion = 'Admnistrador que instaló la plataforma.';
        $patrulla->save();
        $poderes = [
            ['nombre' => 'Moderar', 'descripcion' => 'Moderar en la plataforma.'],
            ['nombre' => 'Configurar plataforma', 'descripcion' => 'Configurar parámetros de Virtugora.'],
            ['nombre' => 'Administrar organismos', 'descripcion' => 'Definir los organimos existentes.'],
            ['nombre' => 'Administrar funcionarios', 'descripcion' => 'Asignar los funcionarios a sus respectivos organismos.'],
            ['nombre' => 'Administrar patrullas', 'descripcion' => 'Definir los distintos grupos de moderación.'],
            ['nombre' => 'Administrar moderadores', 'descripcion' => 'Asignar los usuarios que serán moderadores.'],
            ['nombre' => 'Verificar ciudadanos', 'descripcion' => 'Registrar como verificados a usuarios que lo demuestren.'],
        ];
        Poder::insert($poderes);
        $patrulla->poderes()->attach([1,2,3,4,5,6,7]);
        $usuario->patrulla()->associate($patrulla);
        $usuario->save();
    }
} catch (Exception $e) {
    $titulo = '¡Ha ocurrido un error!';
    $descrp = 'No puede establecerse conexión con la base de datos. Revise el archivo de configuracion.';
    $exito = false;
}?>

<?php echo $titulo ?>

<?php echo $descrp ?>

    <?php if ($exito) { ?>

        Ir a Virtuágora

    <?php } ?>
<?php } else { ?>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

¡Bienvenido!

Muchas gracias por elegir Virtuágora. Por favor complete los siguientes datos para crear
            la cuenta de administrador principal de la plataforma.

Crear cuenta de administrador:

        Email: <input name="usr_email" type="text">
        Nombre: <input name="usr_nombre" type="text">
        Apellido: <input name="usr_apellido" type="text">
        Contraseña: <input name="usr_password" type="password">

        <input class="button expand" type="submit" name="submit" value="Instalar">

    </form>
<?php } ?>


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.ui;

/**
 * Contains all of the command line switches that are specific to the ui/ portion of Chromium on
 * Android.
 */
public abstract class UiSwitches {
    // Enables the screenshot mode, which disables certain UI elements (e.g. dialogs) to facilitate
    // more easily scripting screenshots of web content.
    public static final String ENABLE_SCREENSHOT_UI_MODE = "enable-screenshot-ui-mode";

    // Prevent instantiation.
    private UiSwitches() {}
}


text:
(function () {
  /**
   * Utility to hold and/or create an assortment of data to use during testing.
   */

  process.env.NODE_ENV = 'testing'; // Ensures we're using the test db.

  var app = require('../../app');
  var request = require('supertest')(app);
  var User = require('../../server/models').User;
  var Role = require('../../server/models').Role;
  var Document = require('../../server/models').Document;

  module.exports = {
    // ///////////////////////////
    // User Testing Utilities. //
    // ///////////////////////////

    /**
     * Wherever you need raw user data, use this one.
     */
    testUserData: require('./testUserData.json'),

    /**
     * Wherever you require users in bulk, user these ones.
     */
    testUsers: require('./testUsers.json'),

    /**
     * Create a user using a HTTP POST request.
     */
    createUserByPost: function (data, _log) {
      // If only _log was passed, make data null in order to use the default.
      if (!_log && typeof data !== 'object') {
        _log = data;
        data = null;
      }
      data = data || this.testUserData;
      return new Promise(function (resolve, reject) {
        log(['Attempting to create user with data', data], _log);
        return request
          .post('/api/users')
          .send(data)
          .accept('application/json')
          .end(function (err, res) {
            if (err) {
              reject(err);
              return;
            }
            log('User created successfully.', _log);
            resolve(res);
          });
      });
    },

    /**
     * Login a user.
     */
    login: function (userData, _log) {
      userData = userData || this.testUserData;
      return new Promise(function (resolve, reject) {
        log([
          'Attempting to login user', userData.username,
          'with password', userData.password, '...'], _log);
        return request
          .post('/api/users/login')
          .send(userData)
          .accept('application/json')
          .end(function (err, res) {
            if (err) {
              reject(err);
            } else {
              log('Logged in.', _log);
              resolve(res);
            }
          });
      });
    },

    /**
     * Get an authentication token from the API by logging in a user.
     *
     * Should have used a module like superagent to make the API call here,
     * but supertest should work just fine - less one dependency! ¯\_(ツ)_/¯
     */
    getToken: function (username, password, _log) {
      // Treacherous waters here...
      // Username, password and _log are all optional. Assume that if any
      // of them is a boolean, that was meant to be the _log.
      if (typeof username === 'boolean') {
        _log = username;
        username = null;
        password = null;
      } else if (typeof password === 'boolean') {
        _log = password;
        password = null;
      }

      username = username || 'test';
      password = password || 'test-password';
      return this.login({username: username, password: password})
        .then(function (res) {
          return res.body.token;
        });
    },

    /**
     * Promote a user to 'admin' status.
     */
    makeAdmin: function (username, _log) {
      var _this = this;
      username = username || this.testUserData.username;
      return new Promise(function (resolve, reject) {
        log(['Attempting to promote user', username, 'to admin status...'], _log);
        _this.getAdminRole()
          .then(function (role) {
            User.findOneAndUpdate({ username: username }, {
              $set: {
                role: role._id
              }
            }, function (err, user) {
              if (err) {
                reject(err);
                return;
              }

              log(['Promoted ', username, ' to admin status.'], _log);
              resolve(user);
            });
          });
      });
    },

    /**
     * Seed the system with users.
     */
    seedTestUsers: function (_log) {
      var _this = this;
      return new Promise(function (resolve, reject) {
        log('Seeding test users...', _log);
        User.create(_this.testUsers, function (err, users) {
          if (err) {
            reject(err);
          } else {
            log(['Created', _this.testUsers.length, ' users.'], _log);
            resolve(users);
          }
        });
      });
    },

    /**
     * Remove all seeded users from the db.
     * Don't remove users we didn't create.
     */
    destroyTestUsers: function (_log) {
      return new Promise(function (resolve, reject) {
        log('Removing test users...', _log);
        User.find({}, function (err, users) {
          if (err) {
            reject(err);
            return;
          }
          users.forEach(function (user) {
            User.findOneAndRemove({username: user.username}, function (err) {
              if (err) {
                reject(err);
                return;
              }
              log(['Removed:', user.username], _log);
            });
          });
          resolve(true);
        });
      });
    },

    /**
     * Get the admin role.
     */
    getAdminRole: function () {
      return new Promise(function (resolve, reject) {
        Role.findOne({title: 'admin'}, function (err, role) {
          if (err) {
            reject(err);
            return;
          }
          resolve(role);
        });
      });
    },

    // ////////////////////////////////
    // Documents Testing Utilities. //
    // ////////////////////////////////
    testDocument: require('./testDocumentData'),
    testDocuments: require('./testDocuments'),
    createDocumentByPost: function (token, data, _log) {
      // If only _log was passed, make data null in order to use the default.
      if (!_log && typeof data !== 'object') {
        _log = data;
        data = null;
      }
      data = data || this.testDocumentData;
      return new Promise(function (resolve, reject) {
        if (!token) {
          var err = new Error('No access token provided');
          reject(err);
        } else {
          log(['Attempting to create document with data', data], _log);
          return request
            .post('/api/documents')
            .send(data)
            .set('x-access-token', token)
            .accept('application/json')
            .end(function (err, res) {
              if (err) {
                reject(err);
              } else {
                log('Document created successfully.', _log);
                resolve(res);
              }
            });
        }
      });
    },

    seedTestDocuments: function (owner_id, _log) {
      log('Seeding test documents...', _log);

      var _this = this;
      // eslint-disable-next-line
      return new Promise(function (resolve, reject) {
        return User.findOne({_id: owner_id}).exec(function (err, user) {
          if (err) {
            reject(err);
          }
          _this.testDocuments.forEach(function (doc) {
            var data = Object.assign({}, doc);
            data.owner = user._id;
            Role.findOne({title: data.role}, function (err, role) {
              if (err) reject(err);
              data.role = role._id;
              Document.create(data, function (err) {
                if (err) reject(err);
              });
            });
          });
          log(['Created', _this.testDocuments.length, 'documents'], _log);
          resolve(true);
        });
      });
    },

    /**
     * Backdate every document found in the datebase. Every document is
     * backdated by a day more than the document immediately ahead of it.
     */
    backDateDocumentCreatedAt: function (_log) {
      return new Promise(function (resolve, reject) {
        var timeout = 300;
        log(['Backdating documents in ', timeout, 'milliseconds...'], _log);
        setInterval(function () {
          return Document.find({}, function (err, docs) {
            if (err) {
              reject(err);
            }
            docs.forEach(function (doc, index) {
              var created = new Date(doc.createdAt);
              created = created.setDate(created.getDate() - index);
              doc.createdAt = created;
              doc.save(function (err, doc) {
                if (err) {
                  reject(err);
                }
              });
            });
            log(['Backdated ', docs.length, 'documents successfully'], _log);
            resolve(docs);
          });
        }, timeout);
      });
    },

    destroyTestDocuments: function (_log) {
      log('Destroying test documents...', _log);
      return Document.remove({}, function (err) { // eslint-disable-line
        log('Destroyed test documents.', _log);
      });
    }
  };

  /**
   * Simple logger.
   *
   * @param {_log} Boolean Whether or not to log to the console.
   * @param {items} Array|String A string or an array of items to log to the console.
   */
  function log (items, _log) {
    /* eslint-disable no-console */
    if (_log) {
      if (Array.isArray(items)) {
        console.log(items.join(' '));
      } else {
        console.log(items);
      }
    }
  /* eslint-enable no-console */
  }
}());