Masha's little brother draw two points on a sheet of paper. After that, he draws some circles and gave the sheet to his sister.

Masha has just returned from geometry lesson so she instantly noticed some interesting facts about brother's drawing.

At first, the line going through two points, that brother drew, doesn't intersect or touch any circle.

Also, no two circles intersect or touch, and there is no pair of circles such that one circle is located inside another.

Moreover, for each circle, Masha drew a square of the minimal area with sides parallel axis such that this circle is located inside the square and noticed that there is no two squares intersect or touch and there is no pair of squares such that one square is located inside other.

Now Masha wants to draw circle of minimal possible radius such that it goes through two points that brother drew and doesn't intersect any other circle, but other circles can touch Masha's circle and can be located inside it.

It's guaranteed, that answer won't exceed 1012. It should be held for hacks as well.


Hi to all the nice perople here!
I've been keeping an eye on this piece of software for quite a long time, I found it smart but a little young for sketchup users (like me). With the new material editor I find it to be very cool, and even more interesting to produce atmospheric images and videos with such an ease!
So I am creating this thread not to invade someone's other room, and try to make a little space for my sharing my noob tests. Hope to learn to play with this bad boy in a short time!
PS. My monitor calibration could be totally wrong due to reasons I won't bore you with: tell me if you see it just right! Thanks!


Raindrops the size of bullets thundered on the castle windows for days on end; the lake rose, the flowerbeds turned into muddy streams and Hagrid's pumpkins swelled to the size of garden sheds.
My question is how we should take "Raindrops the size of bullets" from the grammar standpoint. Is it a noun phrase "the size of bullets" modifying another noun word 'Raindrops'? Or it's kind of omission for Raindrops which had the size of bullets?
How should we understand it from the grammar standpoint?
-- From Harry Potter.


Signed Integer Overflow (72006238)
Hello graphviz team,
As part of our fuzzing efforts at Google, we have identified an issue affecting graphviz (tested with revision * master bd97cff6).
To reproduce, we are attaching a Dockerfile which compiles the project with LLVM, taking advantage of the sanitizers that it offers. More information about how to use the attached Dockerfile can be found here: https://docs.docker.com/engine/reference/builder/
TL;DR instructions: artifacts_72006238.zip
cp Dockerfile.graphviz /path/to/project/Dockerfile
docker build --no-cache /path/to/project
docker run -it image_id_from_docker_build
From another terminal, outside the container:
docker cp /path/to/attached/reproducer running_container_hostname:/fuzzing/reproducer
And, back inside the container:
Alternatively, and depending on the bug, you could use gcc, valgrind or other instrumentation tools to aid in the investigation. The sanitizer error that we encountered is here:
INFO: Seed: 2388882439 /fuzzing/graphviz/parser_fuzzer: Running 1 inputs 1 time(s) each. Running: poc-19b0928da2bc1de39ea63bc68e9766561f7535a677a0f107cd1ab8e21d00fd65 ../../lib/cgraph/scan.l:116:20: runtime error: signed integer overflow: -2147483648 - 1 cannot be represented in type 'int' SUMMARY: AddressSanitizer: undefined-behavior ../../lib/cgraph/scan.l:116:20 in INFO: Seed: 835891209 /fuzzing/graphviz/render_fuzzer: Running 1 inputs 1 time(s) each. Running: poc-19b0928da2bc1de39ea63bc68e9766561f7535a677a0f107cd1ab8e21d00fd65 ../../lib/cgraph/scan.l:116:20: runtime error: signed integer overflow: -2147483648 - 1 cannot be represented in type 'int' SUMMARY: AddressSanitizer: undefined-behavior ../../lib/cgraph/scan.l:116:20 in
We will gladly work with you so you can successfully confirm and reproduce this issue. Do let us know if you have any feedback surrounding the documentation.
Once you have reproduced the issue, we'd appreciate to learn your expected timeline for an update to be released. With any fix, please attribute the report to "Google Autofuzz project".
We are also pleased to inform you that your project is eligible for inclusion to the OSS-Fuzz project, which can provide additional continuous fuzzing, and encourage you to investigate integration options.
Don't hesitate to let us know if you have any questions!
Google AutoFuzz Team


/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/* A lightweight TPM command library.
 *
 * The general idea is that TPM commands are array of bytes whose
 * fields are mostly compile-time constant.  The goal is to build much
 * of the commands at compile time (or build time) and change some of
 * the fields at run time as needed.  The code in
 * utility/tlcl_generator.c builds structures containing the commands,
 * as well as the offsets of the fields that need to be set at run
 * time.
 */

#include "2sysincludes.h"
#include "2common.h"
#include "2hmac.h"
#include "2sha.h"

#include "sysincludes.h"
#include "tlcl.h"
#include "tlcl_internal.h"
#include "tlcl_structures.h"
#include "utility.h"
#include "vboot_api.h"

/* Sets the size field of a TPM command. */
static inline void SetTpmCommandSize(uint8_t* buffer, uint32_t size)
{
	ToTpmUint32(buffer + sizeof(uint16_t), size);
}

/* Gets the size field of a TPM command. */
__attribute__((unused))
static inline int TpmCommandSize(const uint8_t* buffer)
{
	uint32_t size;
	FromTpmUint32(buffer + sizeof(uint16_t), &size);
	return (int) size;
}

/* Gets the size field of a TPM request or response. */
int TlclPacketSize(const uint8_t* packet)
{
	return TpmCommandSize(packet);
}

/* Gets the code field of a TPM command. */
static inline int TpmCommandCode(const uint8_t* buffer)
{
	uint32_t code;
	FromTpmUint32(buffer + sizeof(uint16_t) + sizeof(uint32_t), &code);
	return code;
}

/* Gets the return code field of a TPM result. */
static inline int TpmReturnCode(const uint8_t* buffer)
{
	return TpmCommandCode(buffer);
}

/* Like TlclSendReceive below, but do not retry if NEEDS_SELFTEST or
 * DOING_SELFTEST errors are returned.
 */
static uint32_t TlclSendReceiveNoRetry(const uint8_t* request,
				       uint8_t* response, int max_length)
{

	uint32_t response_length = max_length;
	uint32_t result;

#ifdef EXTRA_LOGGING
	VB2_DEBUG("TPM: command: %x%x %x%x%x%x %x%x%x%x\n",
		  request[0], request[1],
		  request[2], request[3], request[4], request[5],
		  request[6], request[7], request[8], request[9]);
#endif

	result = VbExTpmSendReceive(request, TpmCommandSize(request),
				    response, &response_length);
	if (0 != result) {
		/* Communication with TPM failed, so response is garbage */
		VB2_DEBUG("TPM: command 0x%x send/receive failed: 0x%x\n",
			  TpmCommandCode(request), result);
		return result;
	}
	/* Otherwise, use the result code from the response */
	result = TpmReturnCode(response);

	/* TODO: add paranoia about returned response_length vs. max_length
	 * (and possibly expected length from the response header).  See
	 * crosbug.com/17017 */

#ifdef EXTRA_LOGGING
	VB2_DEBUG("TPM: response: %x%x %x%x%x%x %x%x%x%x\n",
		  response[0], response[1],
		  response[2], response[3], response[4], response[5],
		  response[6], response[7], response[8], response[9]);
#endif

	VB2_DEBUG("TPM: command 0x%x returned 0x%x\n",
		  TpmCommandCode(request), result);

	return result;
}

/* Sends a TPM command and gets a response.  Returns 0 if success or the TPM
 * error code if error. In the firmware, waits for the self test to complete
 * if needed. In the host, reports the first error without retries. */
uint32_t TlclSendReceive(const uint8_t* request, uint8_t* response,
			 int max_length)
{
	uint32_t result = TlclSendReceiveNoRetry(request, response, max_length);
	/* When compiling for the firmware, hide command failures due to the
	 * self test not having run or completed. */
#ifndef CHROMEOS_ENVIRONMENT
	/* If the command fails because the self test has not completed, try it
	 * again after attempting to ensure that the self test has completed. */
	if (result == TPM_E_NEEDS_SELFTEST || result == TPM_E_DOING_SELFTEST) {
		result = TlclContinueSelfTest();
		if (result != TPM_SUCCESS) {
			return result;
		}
#if defined(TPM_BLOCKING_CONTINUESELFTEST) || defined(VB_RECOVERY_MODE)
		/* Retry only once */
		result = TlclSendReceiveNoRetry(request, response, max_length);
#else
		/* This needs serious testing.  The TPM specification says:
		 * "iii. The caller MUST wait for the actions of
		 * TPM_ContinueSelfTest to complete before reissuing the
		 * command C1."  But, if ContinueSelfTest is non-blocking, how
		 * do we know that the actions have completed other than trying
		 * again? */
		do {
			result = TlclSendReceiveNoRetry(request, response,
							max_length);
		} while (result == TPM_E_DOING_SELFTEST);
#endif
	}
#endif  /* ! defined(CHROMEOS_ENVIRONMENT) */
	return result;
}

/* Sends a command and returns the error code. */
static uint32_t Send(const uint8_t* command)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	return TlclSendReceive(command, response, sizeof(response));
}

#ifdef CHROMEOS_ENVIRONMENT

struct auth_session
{
	uint32_t handle;
	TPM_NONCE nonce_even;
	TPM_NONCE nonce_odd;
	uint8_t shared_secret[TPM_AUTH_DATA_LEN];
	uint8_t valid;
};

static uint32_t StartOIAPSession(struct auth_session* session,
				 const uint8_t secret[TPM_AUTH_DATA_LEN])
{
	session->valid = 0;

	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t result = TlclSendReceive(tpm_oiap_cmd.buffer, response,
					  sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

	uint32_t size;
	FromTpmUint32(response + sizeof(uint16_t), &size);
	if (size < kTpmResponseHeaderLength + sizeof(uint32_t)
			+ sizeof(TPM_NONCE)) {
		return TPM_E_INVALID_RESPONSE;
	}

	const uint8_t* cursor = response + kTpmResponseHeaderLength;
	session->handle = ReadTpmUint32(&cursor);
	memcpy(session->nonce_even.nonce, cursor, sizeof(TPM_NONCE));
	cursor += sizeof(TPM_NONCE);
	VbAssert(cursor - response <= TPM_LARGE_ENOUGH_COMMAND_SIZE);

	memcpy(session->shared_secret, secret, TPM_AUTH_DATA_LEN);
	session->valid = 1;

	return result;
}

static uint32_t StartOSAPSession(
		struct auth_session* session,
		uint16_t entity_type,
		uint32_t entity_value,
		const uint8_t entity_usage_auth[TPM_AUTH_DATA_LEN])
{
	session->valid = 0;

	/* Build OSAP command. */
	struct s_tpm_osap_cmd cmd;
	memcpy(&cmd, &tpm_osap_cmd, sizeof(cmd));
	ToTpmUint16(cmd.buffer + cmd.entityType, entity_type);
	ToTpmUint32(cmd.buffer + cmd.entityValue, entity_value);
	if (VbExTpmGetRandom(cmd.buffer + cmd.nonceOddOSAP,
			     sizeof(TPM_NONCE)) != VB2_SUCCESS) {
		return TPM_E_INTERNAL_ERROR;
	}

	/* Send OSAP command. */
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t result = TlclSendReceive(cmd.buffer, response,
					  sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

	/* Parse response. */
	uint32_t size;
	FromTpmUint32(response + sizeof(uint16_t), &size);
	if (size < kTpmResponseHeaderLength + sizeof(uint32_t)
			+ 2 * sizeof(TPM_NONCE)) {
		return TPM_E_INVALID_RESPONSE;
	}

	const uint8_t* cursor = response + kTpmResponseHeaderLength;
	session->handle = ReadTpmUint32(&cursor);
	memcpy(session->nonce_even.nonce, cursor, sizeof(TPM_NONCE));
	cursor += sizeof(TPM_NONCE);
	const uint8_t* nonce_even_osap = cursor;
	cursor += sizeof(TPM_NONCE);
	VbAssert(cursor - response <= TPM_LARGE_ENOUGH_COMMAND_SIZE);

	/* Compute shared secret */
	uint8_t hmac_input[2 * sizeof(TPM_NONCE)];
	memcpy(hmac_input, nonce_even_osap, sizeof(TPM_NONCE));
	memcpy(hmac_input + sizeof(TPM_NONCE), cmd.buffer + cmd.nonceOddOSAP,
	       sizeof(TPM_NONCE));
	if (hmac(VB2_HASH_SHA1, entity_usage_auth, TPM_AUTH_DATA_LEN,
		 hmac_input, sizeof(hmac_input), session->shared_secret,
		 sizeof(session->shared_secret))) {
		return TPM_E_INTERNAL_ERROR;
	}
	session->valid = 1;

	return result;
}

/* Fills in the authentication block at the end of the command. The command body
 * should already be initialized in |command_buffer|, and the included command
 * size should account for the auth block that gets filled in. */
uint32_t AddRequestAuthBlock(struct auth_session* auth_session,
			     uint8_t* command_buffer,
			     uint32_t command_buffer_size,
			     uint8_t continue_auth_session)
{
	if (!auth_session->valid) {
		return TPM_E_AUTHFAIL;
	}

	/* Sanity check to make sure the command buffer has sufficient space to
	 * add the auth block at the end of the command. */
	if (command_buffer_size < kTpmRequestHeaderLength) {
		return TPM_E_BUFFER_SIZE;
	}
	const uint32_t size = TpmCommandSize(command_buffer);
	if (size < kTpmResponseHeaderLength + kTpmRequestAuthBlockLength ||
	    size > command_buffer_size) {
		return TPM_E_INTERNAL_ERROR;
	}
	const uint32_t auth_offset = size - kTpmRequestAuthBlockLength;

	/*
	 * The digest of the command is computed over the command buffer, but
	 * excluding the leading tag and paramSize fields.
	 */
	struct vb2_sha1_context sha1_ctx;
	vb2_sha1_init(&sha1_ctx);
	vb2_sha1_update(&sha1_ctx,
			command_buffer + sizeof(uint16_t) + sizeof(uint32_t),
			auth_offset - sizeof(uint16_t) - sizeof(uint32_t));
	uint8_t buf[TPM_SHA1_160_HASH_LEN + 2 * sizeof(TPM_NONCE) + 1];
	vb2_sha1_finalize(&sha1_ctx, buf);

	/* Generate a fresh nonce. */
	if (VbExTpmGetRandom(auth_session->nonce_odd.nonce,
			     sizeof(TPM_NONCE)) != VB2_SUCCESS) {
		return TPM_E_INTERNAL_ERROR;
	}

	/* Append the authentication block to the command buffer. */
	uint8_t* cursor = command_buffer + auth_offset;
	ToTpmUint32(cursor, auth_session->handle);
	cursor += sizeof(uint32_t);
	memcpy(cursor, auth_session->nonce_odd.nonce, sizeof(TPM_NONCE));
	cursor += sizeof(TPM_NONCE);
	*cursor++ = continue_auth_session;

	/* Compute and append the MAC. */
	memcpy(buf + TPM_SHA1_160_HASH_LEN, auth_session->nonce_even.nonce,
	       sizeof(TPM_NONCE));
	memcpy(buf + TPM_SHA1_160_HASH_LEN + sizeof(TPM_NONCE),
	       auth_session->nonce_odd.nonce, sizeof(TPM_NONCE));
	buf[TPM_SHA1_160_HASH_LEN + 2 * sizeof(TPM_NONCE)] =
			continue_auth_session;
	if (hmac(VB2_HASH_SHA1, auth_session->shared_secret,
		 sizeof(auth_session->shared_secret), buf, sizeof(buf), cursor,
		 TPM_SHA1_160_HASH_LEN)) {
		return TPM_E_AUTHFAIL;
	}
	cursor += TPM_SHA1_160_HASH_LEN;

	return TPM_SUCCESS;
}

uint32_t CheckResponseAuthBlock(struct auth_session* auth_session,
				TPM_COMMAND_CODE ordinal,
				uint8_t* response_buffer,
				uint32_t response_buffer_size)
{
	if (!auth_session->valid) {
		return TPM_E_AUTHFAIL;
	}

	if (response_buffer_size < kTpmResponseHeaderLength) {
		return TPM_E_INVALID_RESPONSE;
	}

	/* Parse and validate the actual response size from the response. */
	uint32_t size;
	FromTpmUint32(response_buffer + sizeof(uint16_t), &size);
	if (size >= response_buffer_size ||
	    size < kTpmResponseHeaderLength + kTpmResponseAuthBlockLength) {
		return TPM_E_INVALID_RESPONSE;
	}
	uint32_t auth_offset = size - kTpmResponseAuthBlockLength;

	/*
	 * The digest of the response is computed over the return code, ordinal,
	 * response payload.
	 */
	struct vb2_sha1_context sha1_ctx;
	vb2_sha1_init(&sha1_ctx);
	vb2_sha1_update(&sha1_ctx,
			response_buffer + sizeof(uint16_t) + sizeof(uint32_t),
			sizeof(uint32_t));
	uint8_t ordinal_buf[sizeof(ordinal)];
	ToTpmUint32(ordinal_buf, ordinal);
	vb2_sha1_update(&sha1_ctx, ordinal_buf, sizeof(ordinal_buf));
	vb2_sha1_update(&sha1_ctx,
			response_buffer + kTpmResponseHeaderLength,
			auth_offset - kTpmResponseHeaderLength);
	uint8_t hmac_input[TPM_SHA1_160_HASH_LEN + 2 * sizeof(TPM_NONCE) + 1];
	vb2_sha1_finalize(&sha1_ctx, hmac_input);

	/* Compute the MAC. */
	uint8_t* cursor = response_buffer + auth_offset;
	memcpy(hmac_input + TPM_SHA1_160_HASH_LEN, cursor, sizeof(TPM_NONCE));
	cursor += sizeof(TPM_NONCE);
	memcpy(hmac_input + TPM_SHA1_160_HASH_LEN + sizeof(TPM_NONCE),
	       auth_session->nonce_odd.nonce, sizeof(TPM_NONCE));
	auth_session->valid = *cursor++;
	hmac_input[TPM_SHA1_160_HASH_LEN + 2 * sizeof(TPM_NONCE)] =
			auth_session->valid;
	uint8_t mac[TPM_SHA1_160_HASH_LEN];
	if (hmac(VB2_HASH_SHA1, auth_session->shared_secret,
		 sizeof(auth_session->shared_secret), hmac_input,
		 sizeof(hmac_input), mac, sizeof(mac))) {
		auth_session->valid = 0;
		return TPM_E_AUTHFAIL;
	}

	/* Check the MAC. */
	if (vb2_safe_memcmp(mac, cursor, sizeof(mac))) {
		auth_session->valid = 0;
		return TPM_E_AUTHFAIL;
	}

	/* Success, save the even nonce. */
	memcpy(auth_session->nonce_even.nonce, response_buffer + auth_offset,
	       sizeof(TPM_NONCE));

	return TPM_SUCCESS;
}

#endif  /* CHROMEOS_ENVIRONMENT */

/* Exported functions. */

uint32_t TlclLibInit(void)
{
	return VbExTpmInit();
}

uint32_t TlclLibClose(void)
{
	return VbExTpmClose();
}

uint32_t TlclStartup(void)
{
	VB2_DEBUG("TPM: Startup\n");
	return Send(tpm_startup_cmd.buffer);
}

uint32_t TlclSaveState(void)
{
	VB2_DEBUG("TPM: SaveState\n");
	return Send(tpm_savestate_cmd.buffer);
}

uint32_t TlclResume(void)
{
	VB2_DEBUG("TPM: Resume\n");
	return Send(tpm_resume_cmd.buffer);
}

uint32_t TlclSelfTestFull(void)
{
	VB2_DEBUG("TPM: Self test full\n");
	return Send(tpm_selftestfull_cmd.buffer);
}

uint32_t TlclContinueSelfTest(void)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	VB2_DEBUG("TPM: Continue self test\n");
	/* Call the No Retry version of SendReceive to avoid recursion. */
	return TlclSendReceiveNoRetry(tpm_continueselftest_cmd.buffer,
				      response, sizeof(response));
}

uint32_t TlclDefineSpace(uint32_t index, uint32_t perm, uint32_t size)
{
	VB2_DEBUG("TPM: TlclDefineSpace(0x%x, 0x%x, %d)\n", index, perm, size);
	return TlclDefineSpaceEx(NULL, 0, index, perm, size, NULL, 0);
}

#ifdef CHROMEOS_ENVIRONMENT

uint32_t TlclUndefineSpace(uint32_t index)
{
	VB2_DEBUG("TPM: TlclUndefineSpace(0x%x)\n", index);
	return TlclUndefineSpaceEx(NULL, 0, index);
}

uint32_t TlclUndefineSpaceEx(const uint8_t* owner_auth,
			     uint32_t owner_auth_size,
			     uint32_t index)
{
	return TlclDefineSpaceEx(owner_auth, owner_auth_size,
				 index, 0, 0,
				 NULL, 0);
}

#endif  /* CHROMEOS_ENVIRONMENT */

uint32_t TlclDefineSpaceEx(const uint8_t* owner_auth, uint32_t owner_auth_size,
			   uint32_t index, uint32_t perm, uint32_t size,
			   const void* auth_policy, uint32_t auth_policy_size)
{
	uint32_t result;

	/* Build the request data. */
	uint8_t cmd[sizeof(tpm_nv_definespace_cmd.buffer) +
			kTpmRequestAuthBlockLength];
	memcpy(cmd, &tpm_nv_definespace_cmd, sizeof(tpm_nv_definespace_cmd));
	ToTpmUint32(cmd + tpm_nv_definespace_cmd.index, index);
	ToTpmUint32(cmd + tpm_nv_definespace_cmd.perm, perm);
	ToTpmUint32(cmd + tpm_nv_definespace_cmd.size, size);
	if (auth_policy != NULL) {
		if (auth_policy_size != sizeof(TPM_NV_AUTH_POLICY)) {
			return TPM_E_BUFFER_SIZE;
		}

		const TPM_NV_AUTH_POLICY* policy = auth_policy;
		memcpy(cmd + tpm_nv_definespace_cmd.pcr_info_read,
		       &policy->pcr_info_read, sizeof(policy->pcr_info_read));
		memcpy(cmd + tpm_nv_definespace_cmd.pcr_info_write,
		       &policy->pcr_info_write, sizeof(policy->pcr_info_write));
	}

#ifdef CHROMEOS_ENVIRONMENT
	struct auth_session auth_session;
	if (owner_auth) {
		if (owner_auth_size != TPM_AUTH_DATA_LEN) {
			return TPM_E_AUTHFAIL;
		}

		result = StartOSAPSession(&auth_session, TPM_ET_OWNER, 0,
					  owner_auth);
		if (result != TPM_SUCCESS) {
			return result;
		}

		ToTpmUint32(cmd + sizeof(uint16_t), sizeof(cmd));
		ToTpmUint16(cmd, TPM_TAG_RQU_AUTH1_COMMAND);
		result = AddRequestAuthBlock(&auth_session, cmd, sizeof(cmd),
					     0);
		if (result != TPM_SUCCESS) {
			return result;
		}
	}
#endif

	/* Send the command. */
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	result = TlclSendReceive(cmd, response, sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

#ifdef CHROMEOS_ENVIRONMENT
	if (owner_auth) {
		result = CheckResponseAuthBlock(&auth_session,
						TPM_ORD_NV_DefineSpace,
						response, sizeof(response));
	}
#endif

	return result;
}

uint32_t TlclInitNvAuthPolicy(uint32_t pcr_selection_bitmap,
			      const uint8_t pcr_values[][TPM_PCR_DIGEST],
			      void* auth_policy, uint32_t* auth_policy_size)
{
	uint32_t buffer_size = *auth_policy_size;
	*auth_policy_size = sizeof(TPM_NV_AUTH_POLICY);
	if (!auth_policy || buffer_size < sizeof(TPM_NV_AUTH_POLICY)) {
		return TPM_E_BUFFER_SIZE;
	}
	TPM_NV_AUTH_POLICY* policy = auth_policy;

	/* Note that although the struct definition allocates space for 3 bytes
	 * worth of PCR selection, it is technically a variably-sized field in
	 * the TPM structure definition. Since this is part of the policy
	 * digest, we need to carefully match our selection sizes. For now, we
	 * use 3 bytes, which aligns with TrouSerS behavior. */
	TPM_PCR_SELECTION* select = &policy->pcr_info_read.pcrSelection;
	ToTpmUint16((uint8_t*)&select->sizeOfSelect, sizeof(select->pcrSelect));
	select->pcrSelect[0] = (pcr_selection_bitmap >> 0) & 0xff;
	select->pcrSelect[1] = (pcr_selection_bitmap >> 8) & 0xff;
	select->pcrSelect[2] = (pcr_selection_bitmap >> 16) & 0xff;
	VbAssert((pcr_selection_bitmap & 0xff000000) == 0);

	/* Allow all localities except locality 3. Rationale:
	 *
	 * We don't actually care about restricting NVRAM access to specific
	 * localities. In fact localities aren't used in Chrome OS and locality
	 * 0 is used for everything.
	 *
	 * However, the TPM specification makes an effort to not allow NVRAM
	 * spaces that do not have some write access control configured: When
	 * defining a space, either at least one of OWNERWRITE, AUTHWRITE,
	 * WRITEDEFINE, PPWRITE or a locality restriction must be specified (See
	 * TPM_NV_DefineSpace command description in the spec).
	 *
	 * This complicates matters when defining an NVRAM space that should be
	 * writable and lockable (for the remainder of the boot cycle) by the OS
	 * even when the TPM is not owned:
	 *  * OWNERWRITE doesn't work because there might be no owner.
	 *  * PPWRITE restricts writing to firmware only.
	 *  * Use of WRITEDEFINE prevents use of WRITE_STCLEAR (i.e. the space
	 *    can either not be locked, or it would remain locked until next TPM
	 *    clear).
	 *  * AUTHWRITE looks workable at first sight (by setting a well-known
	 *    auth secret). However writes must use TPM_NV_WriteValueAuth, which
	 *    only works when the TPM is owned. Interestingly, the spec admits
	 *    to that being a mistake in the TPM_NV_WriteValueAuth comment but
	 *    asserts that the behavior is normative.
	 *
	 * Having ruled out all attributes, we're left with locality restriction
	 * as the only option to pass the access control requirement check in
	 * TPM_NV_DefineSpace. We choose to disallow locality 3, since that is
	 * the most unlikely one to be used in practice, i.e. the spec says
	 * locality 3 is for "Auxiliary components. Use of this is optional and,
	 * if used, it is implementation dependent."
	 */
	policy->pcr_info_read.localityAtRelease =
		TPM_ALL_LOCALITIES & ~TPM_LOC_THREE;

	struct vb2_sha1_context sha1_ctx;
	vb2_sha1_init(&sha1_ctx);

	vb2_sha1_update(&sha1_ctx,
			(const uint8_t*)&policy->pcr_info_read.pcrSelection,
			sizeof(policy->pcr_info_read.pcrSelection));

	uint32_t num_pcrs = 0;
	int i;
	for (i = 0; i < sizeof(pcr_selection_bitmap) * 8; ++i) {
		if ((1 << i) & pcr_selection_bitmap) {
			num_pcrs++;
		}
	}

	uint8_t pcrs_size[sizeof(uint32_t)];
	ToTpmUint32(pcrs_size, num_pcrs * TPM_PCR_DIGEST);
	vb2_sha1_update(&sha1_ctx, pcrs_size, sizeof(pcrs_size));

	for (i = 0; i < num_pcrs; ++i) {
		vb2_sha1_update(&sha1_ctx, pcr_values[i], TPM_PCR_DIGEST);
	}

	vb2_sha1_finalize(&sha1_ctx,
			  policy->pcr_info_read.digestAtRelease.digest);

	/* Make the write policy an identical copy of the read auth policy. */
	memcpy(&policy->pcr_info_write, &policy->pcr_info_read,
	       sizeof(policy->pcr_info_read));

	return TPM_SUCCESS;
}

uint32_t TlclWrite(uint32_t index, const void* data, uint32_t length)
{
	struct s_tpm_nv_write_cmd cmd;
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	const int total_length =
			kTpmRequestHeaderLength + kWriteInfoLength + length;

	VB2_DEBUG("TPM: TlclWrite(0x%x, %d)\n", index, length);
	memcpy(&cmd, &tpm_nv_write_cmd, sizeof(cmd));
	VbAssert(total_length <= TPM_LARGE_ENOUGH_COMMAND_SIZE);
	SetTpmCommandSize(cmd.buffer, total_length);

	ToTpmUint32(cmd.buffer + tpm_nv_write_cmd.index, index);
	ToTpmUint32(cmd.buffer + tpm_nv_write_cmd.length, length);
	memcpy(cmd.buffer + tpm_nv_write_cmd.data, data, length);

	return TlclSendReceive(cmd.buffer, response, sizeof(response));
}

uint32_t TlclRead(uint32_t index, void* data, uint32_t length)
{
	struct s_tpm_nv_read_cmd cmd;
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t result;

	VB2_DEBUG("TPM: TlclRead(0x%x, %d)\n", index, length);
	memcpy(&cmd, &tpm_nv_read_cmd, sizeof(cmd));
	ToTpmUint32(cmd.buffer + tpm_nv_read_cmd.index, index);
	ToTpmUint32(cmd.buffer + tpm_nv_read_cmd.length, length);

	result = TlclSendReceive(cmd.buffer, response, sizeof(response));
	if (result == TPM_SUCCESS && length > 0) {
		const uint8_t* nv_read_cursor =
				response + kTpmResponseHeaderLength;
		uint32_t result_length = ReadTpmUint32(&nv_read_cursor);
		if (result_length > length)
			result_length = length;  /* Truncate to fit buffer */
		memcpy(data, nv_read_cursor, result_length);
	}

	return result;
}

uint32_t TlclPCRRead(uint32_t index, void* data, uint32_t length)
{
	struct s_tpm_pcr_read_cmd cmd;
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t result;

	VB2_DEBUG("TPM: TlclPCRRead(0x%x, %d)\n", index, length);
	if (length < kPcrDigestLength) {
		return TPM_E_IOERROR;
	}
	memcpy(&cmd, &tpm_pcr_read_cmd, sizeof(cmd));
	ToTpmUint32(cmd.buffer + tpm_pcr_read_cmd.pcrNum, index);

	result = TlclSendReceive(cmd.buffer, response, sizeof(response));
	if (result == TPM_SUCCESS) {
		const uint8_t* pcr_read_cursor =
				response + kTpmResponseHeaderLength;
		memcpy(data, pcr_read_cursor, kPcrDigestLength);
	}

	return result;
}

uint32_t TlclWriteLock(uint32_t index)
{
	VB2_DEBUG("TPM: Write lock 0x%x\n", index);
	return TlclWrite(index, NULL, 0);
}

uint32_t TlclReadLock(uint32_t index)
{
	VB2_DEBUG("TPM: Read lock 0x%x\n", index);
	return TlclRead(index, NULL, 0);
}

uint32_t TlclAssertPhysicalPresence(void)
{
	VB2_DEBUG("TPM: Asserting physical presence\n");
	return Send(tpm_ppassert_cmd.buffer);
}

uint32_t TlclPhysicalPresenceCMDEnable(void)
{
	VB2_DEBUG("TPM: Enable the physical presence command\n");
	return Send(tpm_ppenable_cmd.buffer);
}

uint32_t TlclFinalizePhysicalPresence(void)
{
	VB2_DEBUG("TPM: Enable PP cmd, disable HW pp, and set lifetime lock\n");
	return Send(tpm_finalizepp_cmd.buffer);
}

uint32_t TlclAssertPhysicalPresenceResult(void)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	return TlclSendReceive(tpm_ppassert_cmd.buffer, response,
			       sizeof(response));
}

uint32_t TlclLockPhysicalPresence(void)
{
	VB2_DEBUG("TPM: Lock physical presence\n");
	return Send(tpm_pplock_cmd.buffer);
}

uint32_t TlclSetNvLocked(void)
{
	VB2_DEBUG("TPM: Set NV locked\n");
	return TlclDefineSpace(TPM_NV_INDEX_LOCK, 0, 0);
}

int TlclIsOwned(void)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE + TPM_PUBEK_SIZE];
	uint32_t result;
	result = TlclSendReceive(tpm_readpubek_cmd.buffer,
				 response, sizeof(response));
	return (result != TPM_SUCCESS);
}

uint32_t TlclForceClear(void)
{
	VB2_DEBUG("TPM: Force clear\n");
	return Send(tpm_forceclear_cmd.buffer);
}

uint32_t TlclSetEnable(void)
{
	VB2_DEBUG("TPM: Enabling TPM\n");
	return Send(tpm_physicalenable_cmd.buffer);
}

uint32_t TlclClearEnable(void)
{
	VB2_DEBUG("TPM: Disabling TPM\n");
	return Send(tpm_physicaldisable_cmd.buffer);
}

uint32_t TlclSetDeactivated(uint8_t flag)
{
	struct s_tpm_physicalsetdeactivated_cmd cmd;
	VB2_DEBUG("TPM: SetDeactivated(%d)\n", flag);
	memcpy(&cmd, &tpm_physicalsetdeactivated_cmd, sizeof(cmd));
	*(cmd.buffer + cmd.deactivated) = flag;
	return Send(cmd.buffer);
}

uint32_t TlclGetPermanentFlags(TPM_PERMANENT_FLAGS* pflags)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t size;
	uint32_t result = TlclSendReceive(tpm_getflags_cmd.buffer, response,
					  sizeof(response));
	if (result != TPM_SUCCESS)
		return result;
	FromTpmUint32(response + kTpmResponseHeaderLength, &size);
	/* TODO(crbug.com/379255): This fails. Find out why.
	 * VbAssert(size == sizeof(TPM_PERMANENT_FLAGS));
	 */
	memcpy(pflags,
	       response + kTpmResponseHeaderLength + sizeof(size),
	       sizeof(TPM_PERMANENT_FLAGS));
	return result;
}

uint32_t TlclGetSTClearFlags(TPM_STCLEAR_FLAGS* vflags)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t size;
	uint32_t result = TlclSendReceive(tpm_getstclearflags_cmd.buffer,
					  response, sizeof(response));
	if (result != TPM_SUCCESS)
		return result;
	FromTpmUint32(response + kTpmResponseHeaderLength, &size);
	/* Ugly assertion, but the struct is padded up by one byte. */
	/* TODO(crbug.com/379255): This fails. Find out why.
	 * VbAssert(size == 7 && sizeof(TPM_STCLEAR_FLAGS) - 1 == 7);
	 */
	memcpy(vflags,
	       response + kTpmResponseHeaderLength + sizeof(size),
	       sizeof(TPM_STCLEAR_FLAGS));
	return result;
}

uint32_t TlclGetFlags(uint8_t* disable,
		      uint8_t* deactivated,
		      uint8_t *nvlocked)
{
	TPM_PERMANENT_FLAGS pflags;
	uint32_t result = TlclGetPermanentFlags(&pflags);
	if (result == TPM_SUCCESS) {
		if (disable)
			*disable = pflags.disable;
		if (deactivated)
			*deactivated = pflags.deactivated;
		if (nvlocked)
			*nvlocked = pflags.nvLocked;
		VB2_DEBUG("TPM: Got flags disable=%d, deactivated=%d, "
			  "nvlocked=%d\n",
			  pflags.disable, pflags.deactivated, pflags.nvLocked);
	}
	return result;
}

uint32_t TlclSetGlobalLock(void)
{
	uint32_t x;
	VB2_DEBUG("TPM: Set global lock\n");
	return TlclWrite(TPM_NV_INDEX0, (uint8_t*) &x, 0);
}

uint32_t TlclExtend(int pcr_num, const uint8_t* in_digest,
		    uint8_t* out_digest)
{
	struct s_tpm_extend_cmd cmd;
	uint8_t response[kTpmResponseHeaderLength + kPcrDigestLength];
	uint32_t result;

	memcpy(&cmd, &tpm_extend_cmd, sizeof(cmd));
	ToTpmUint32(cmd.buffer + tpm_extend_cmd.pcrNum, pcr_num);
	memcpy(cmd.buffer + cmd.inDigest, in_digest, kPcrDigestLength);

	result = TlclSendReceive(cmd.buffer, response, sizeof(response));
	if (result != TPM_SUCCESS)
		return result;

	memcpy(out_digest, response + kTpmResponseHeaderLength,
	       kPcrDigestLength);
	return result;
}

uint32_t TlclGetPermissions(uint32_t index, uint32_t* permissions)
{
	uint32_t dummy_attributes;
	TPM_NV_AUTH_POLICY dummy_policy;
	uint32_t dummy_policy_size = sizeof(dummy_policy);

	return TlclGetSpaceInfo(index, permissions, &dummy_attributes,
				&dummy_policy, &dummy_policy_size);
}

static int DecodePCRInfo(const uint8_t** cursor,
			 const uint8_t* end,
			 TPM_PCR_INFO_SHORT* pcr_info)
{
	const size_t available_size = end - *cursor;
	if (available_size < sizeof(uint16_t)) {
		return 0;
	}

	uint16_t size_of_select = 0;
	FromTpmUint16(*cursor, &size_of_select);

	/* Compute the actual size of the encoded PCR selection (which is a
	 * variable-length field). */
	const size_t encoded_pcr_info_size = sizeof(TPM_PCR_INFO_SHORT) -
		sizeof(pcr_info->pcrSelection.pcrSelect) + size_of_select;
	if (available_size < encoded_pcr_info_size ||
	    size_of_select > sizeof(pcr_info->pcrSelection.pcrSelect)) {
		return 0;
	}

	memset(&pcr_info->pcrSelection, 0, sizeof(pcr_info->pcrSelection));
	const size_t pcr_selection_size =
		sizeof(size_of_select) + size_of_select;
	memcpy(&pcr_info->pcrSelection, *cursor, pcr_selection_size);
	*cursor += pcr_selection_size;

	pcr_info->localityAtRelease = **cursor;
	(*cursor)++;

	memcpy(&pcr_info->digestAtRelease, *cursor, sizeof(TPM_COMPOSITE_HASH));
	*cursor += sizeof(TPM_COMPOSITE_HASH);

	return 1;
}

uint32_t TlclGetSpaceInfo(uint32_t index, uint32_t *attributes, uint32_t *size,
			  void* auth_policy, uint32_t* auth_policy_size)
{
	TPM_NV_AUTH_POLICY* policy;
	uint32_t buffer_size = *auth_policy_size;
	*auth_policy_size = sizeof(TPM_NV_AUTH_POLICY);
	if (buffer_size < sizeof(TPM_NV_AUTH_POLICY)) {
		return TPM_E_BUFFER_SIZE;
	}
	policy = auth_policy;

	struct s_tpm_getspaceinfo_cmd cmd;
	memcpy(&cmd, &tpm_getspaceinfo_cmd, sizeof(cmd));
	ToTpmUint32(cmd.buffer + tpm_getspaceinfo_cmd.index, index);
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t result = TlclSendReceive(cmd.buffer, response,
					  sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

	uint32_t response_size = TpmCommandSize(response);
	if (response_size > sizeof(response)) {
		return TPM_E_RESPONSE_TOO_LARGE;
	}

	const uint8_t* cursor = response + kTpmResponseHeaderLength;
	uint32_t cap_size = ReadTpmUint32(&cursor);
	if (cap_size >
	    response_size - sizeof(cap_size) - kTpmResponseHeaderLength) {
		return TPM_E_INVALID_RESPONSE;
	}
	const uint8_t* end = cursor + cap_size;

	cursor += sizeof(uint16_t);  /* skip tag */
	uint32_t response_index = ReadTpmUint32(&cursor);
	if (index != response_index) {
		return TPM_E_INVALID_RESPONSE;
	}

	if (!DecodePCRInfo(&cursor, end, &policy->pcr_info_read) ||
	    !DecodePCRInfo(&cursor, end, &policy->pcr_info_write)) {
		return TPM_E_INVALID_RESPONSE;
	}

	/* Make sure that the remaining data in the buffer matches the size of
	 * the remaining fields to decode. */
	if (end - cursor !=
	    2 * sizeof(uint32_t) + 3 * sizeof(uint8_t) + sizeof(uint16_t)) {
		return TPM_E_INVALID_RESPONSE;
	}

	cursor += sizeof(uint16_t);  /* skip TPM_NV_ATTRIBUTES tag */
	*attributes = ReadTpmUint32(&cursor);
	cursor += sizeof(uint8_t);  /* skip bReadSTClear */
	cursor += sizeof(uint8_t);  /* skip bWriteSTClear */
	cursor += sizeof(uint8_t);  /* skip bWriteDefine */
	*size = ReadTpmUint32(&cursor);

	return TPM_SUCCESS;
}

uint32_t TlclGetOwnership(uint8_t* owned)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t size;
	uint32_t result = TlclSendReceive(tpm_getownership_cmd.buffer,
					  response, sizeof(response));
	if (result != TPM_SUCCESS)
		return result;
	FromTpmUint32(response + kTpmResponseHeaderLength, &size);
	/* TODO(crbug.com/379255): This fails. Find out why.
	 * VbAssert(size == sizeof(*owned));
	 */
	memcpy(owned,
	       response + kTpmResponseHeaderLength + sizeof(size),
	       sizeof(*owned));
	return result;
}

uint32_t TlclGetRandom(uint8_t* data, uint32_t length, uint32_t *size)
{
	struct s_tpm_get_random_cmd cmd;
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t result;

	VB2_DEBUG("TPM: TlclGetRandom(%d)\n", length);
	memcpy(&cmd, &tpm_get_random_cmd, sizeof(cmd));
	ToTpmUint32(cmd.buffer + tpm_get_random_cmd.bytesRequested, length);
	/* There must be room in the response buffer for the bytes. */
	if (length > TPM_LARGE_ENOUGH_COMMAND_SIZE - kTpmResponseHeaderLength
	    - sizeof(uint32_t)) {
		return TPM_E_IOERROR;
	}

	result = TlclSendReceive(cmd.buffer, response, sizeof(response));
	if (result == TPM_SUCCESS) {
		const uint8_t* get_random_cursor =
				response + kTpmResponseHeaderLength;
		*size = ReadTpmUint32(&get_random_cursor);

		/* There must be room in the target buffer for the bytes. */
		if (*size > length) {
			return TPM_E_RESPONSE_TOO_LARGE;
		}
		memcpy(data, get_random_cursor, *size);
	}

	return result;
}

uint32_t TlclGetVersion(uint32_t* vendor, uint64_t* firmware_version,
			uint8_t* vendor_specific_buf,
			size_t* vendor_specific_buf_size)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t result = TlclSendReceive(tpm_getversionval_cmd.buffer,
					  response, sizeof(response));
	if (result != TPM_SUCCESS)
		return result;

	const uint8_t* cursor = response + kTpmResponseHeaderLength;
	uint32_t size = ReadTpmUint32(&cursor);

	/* Verify size >= sizeof(TPM_CAP_VERSION_INFO). */
	const uint32_t kSizeofCapVersionInfo = 15;
	if (size < kSizeofCapVersionInfo ||
	    kTpmResponseHeaderLength + sizeof(size) + size >
			TPM_LARGE_ENOUGH_COMMAND_SIZE) {
		return TPM_E_IOERROR;
	}

	cursor += sizeof(uint16_t);  /* tag */
	cursor += sizeof(uint16_t);  /* spec version */

	*firmware_version = ReadTpmUint16(&cursor);

	cursor += sizeof(uint16_t);  /* specLevel */
	cursor += sizeof(uint8_t);  /* errataRev */

	*vendor = ReadTpmUint32(&cursor);

	if (vendor_specific_buf_size) {
		uint16_t vendor_specific_size = ReadTpmUint16(&cursor);

		if (size < kSizeofCapVersionInfo + vendor_specific_size) {
			return TPM_E_IOERROR;
		}
		if (vendor_specific_buf) {
			if (vendor_specific_size > *vendor_specific_buf_size) {
				vendor_specific_size =
					*vendor_specific_buf_size;
			}
			memcpy(vendor_specific_buf, cursor,
			       vendor_specific_size);
			cursor += vendor_specific_size;
		}
		*vendor_specific_buf_size = vendor_specific_size;
	}

	return TPM_SUCCESS;
}

static void ParseIFXFirmwarePackage(const uint8_t** cursor,
				    TPM_IFX_FIRMWAREPACKAGE* firmware_package)
{
	firmware_package->FwPackageIdentifier = ReadTpmUint32(cursor);
	firmware_package->Version = ReadTpmUint32(cursor);
	firmware_package->StaleVersion = ReadTpmUint32(cursor);
}

uint32_t TlclIFXFieldUpgradeInfo(TPM_IFX_FIELDUPGRADEINFO* info)
{
	uint32_t vendor;
	uint64_t firmware_version;
	uint32_t result =
			TlclGetVersion(&vendor, &firmware_version, NULL, NULL);
	if (result != TPM_SUCCESS) {
		return result;
	}
	if (vendor != 0x49465800) {
		return TPM_E_BAD_ORDINAL;
	}

	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	result = TlclSendReceive(tpm_ifx_fieldupgradeinforequest2_cmd.buffer,
				 response, sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

	const uint8_t* cursor = response + kTpmResponseHeaderLength;
	uint16_t size = ReadTpmUint16(&cursor);

	/* Comments below indicate skipped fields of unknown purpose that are
	 * marked "internal" in the firmware updater source. */
	cursor += sizeof(uint16_t);  /* internal1 */
	info->wMaxDataSize = ReadTpmUint16(&cursor);
	cursor += sizeof(uint16_t);  /* sSecurityModuleLogic.internal1 */
	cursor += sizeof(uint32_t);  /* sSecurityModuleLogic.internal2 */
	cursor += sizeof(uint8_t[34]);  /* sSecurityModuleLogic.internal3 */
	ParseIFXFirmwarePackage(&cursor, &info->sBootloaderFirmwarePackage);
	uint16_t fw_entry_count = ReadTpmUint16(&cursor);
	if (fw_entry_count > ARRAY_SIZE(info->sFirmwarePackages)) {
		return TPM_E_INVALID_RESPONSE;
	}
	uint16_t i;
	for (i = 0; i < fw_entry_count; ++i) {
		ParseIFXFirmwarePackage(&cursor, &info->sFirmwarePackages[i]);
	}
	info->wSecurityModuleStatus = ReadTpmUint16(&cursor);
	ParseIFXFirmwarePackage(&cursor, &info->sProcessFirmwarePackage);
	cursor += sizeof(uint16_t);  /* internal6 */
	cursor += sizeof(uint8_t[6]);  /* internal7 */
	info->wFieldUpgradeCounter = ReadTpmUint16(&cursor);

	uint32_t parsed_bytes = cursor - response;
	VbAssert(parsed_bytes <= TPM_LARGE_ENOUGH_COMMAND_SIZE);
	if (parsed_bytes > kTpmResponseHeaderLength + sizeof(size) + size) {
		return TPM_E_INVALID_RESPONSE;
	}

	return result;
}

#ifdef CHROMEOS_ENVIRONMENT

static uint32_t ParseRsaKeyParms(const uint8_t* buffer,
				 const uint8_t* end,
				 uint32_t* key_len,
				 uint32_t* num_primes,
				 uint32_t* exponent)
{
	if (end - buffer < 3 * sizeof(uint32_t)) {
		return TPM_E_INVALID_RESPONSE;
	}
	*key_len = ReadTpmUint32(&buffer);
	*num_primes = ReadTpmUint32(&buffer);
	uint32_t exponent_size = ReadTpmUint32(&buffer);
	if (end - buffer < exponent_size) {
		return TPM_E_INVALID_RESPONSE;
	}

	if (exponent_size == 0) {
		*exponent = 0x10001;
	} else if (exponent_size <= sizeof(*exponent)) {
		*exponent = 0;
		int i;
		for (i = 0; i < exponent_size; ++i) {
			*exponent |= (*buffer++) << (8 * i);
		}
	} else {
		return TPM_E_INTERNAL_ERROR;
	}

	return TPM_SUCCESS;
}

static uint32_t ParseTpmPubKey(const uint8_t** buffer,
			       const uint8_t* end,
			       uint32_t* algorithm,
			       uint16_t* enc_scheme,
			       uint16_t* sig_scheme,
			       uint32_t* key_len,
			       uint32_t* num_primes,
			       uint32_t* exponent,
			       uint8_t* modulus,
			       uint32_t* modulus_size)
{
	uint32_t result = TPM_SUCCESS;

	if (end - *buffer < 2 * sizeof(uint32_t) + 2 * sizeof(uint16_t)) {
		return TPM_E_INVALID_RESPONSE;
	}

	*algorithm = ReadTpmUint32(buffer);
	*enc_scheme = ReadTpmUint16(buffer);
	*sig_scheme = ReadTpmUint16(buffer);

	uint32_t parm_size = ReadTpmUint32(buffer);
	if (end - *buffer < parm_size) {
		return TPM_E_INVALID_RESPONSE;
	}

	if (*algorithm == TPM_ALG_RSA) {
		result = ParseRsaKeyParms(*buffer, *buffer + parm_size,
					  key_len, num_primes, exponent);
		if (result != TPM_SUCCESS) {
			return result;
		}
	} else {
		return TPM_E_INTERNAL_ERROR;
	}

	*buffer += parm_size;

	if (end - *buffer < sizeof(uint32_t)) {
		return TPM_E_INVALID_RESPONSE;
	}

	uint32_t actual_modulus_size = ReadTpmUint32(buffer);
	if (end - *buffer < actual_modulus_size) {
		return TPM_E_INVALID_RESPONSE;
	}

	if (modulus && *modulus_size >= actual_modulus_size) {
		memcpy(modulus, *buffer, actual_modulus_size);
	} else {
		result = TPM_E_BUFFER_SIZE;
	}
	*modulus_size = actual_modulus_size;
	*buffer += actual_modulus_size;

	return result;
}

uint32_t TlclReadPubek(uint32_t* public_exponent,
		       uint8_t* modulus,
		       uint32_t* modulus_size)
{
	struct s_tpm_readpubek_cmd cmd;
	memcpy(&cmd, &tpm_readpubek_cmd, sizeof(cmd));
	if (VbExTpmGetRandom(cmd.buffer + tpm_readpubek_cmd.antiReplay,
			     sizeof(TPM_NONCE)) != VB2_SUCCESS) {
		return TPM_E_INTERNAL_ERROR;
	}

	/* The response contains the public endorsement key, so use a large
	 * response buffer. */
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE + TPM_RSA_2048_LEN];
	uint32_t result = TlclSendReceive(cmd.buffer, response,
					  sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

	const uint8_t* cursor = response + kTpmResponseHeaderLength;
	const uint8_t* end = response + sizeof(response);

	/* Parse the key */
	uint32_t algorithm;
	uint16_t enc_scheme;
	uint16_t sig_scheme;
	uint32_t key_len;
	uint32_t num_primes;
	result = ParseTpmPubKey(&cursor, end, &algorithm, &enc_scheme,
				&sig_scheme, &key_len, &num_primes,
				public_exponent, modulus, modulus_size);
	if (result != TPM_SUCCESS) {
		return result;
	}

	/* Parse the checksum */
	if (end - cursor < TPM_SHA1_160_HASH_LEN) {
		return TPM_E_INVALID_RESPONSE;
	}
	const uint8_t* checksum = cursor;
	cursor += TPM_SHA1_160_HASH_LEN;

	/* Check the digest */
	struct vb2_sha1_context sha1_ctx;
	vb2_sha1_init(&sha1_ctx);
	vb2_sha1_update(&sha1_ctx, response + kTpmResponseHeaderLength,
			checksum - (response + kTpmResponseHeaderLength));
	vb2_sha1_update(&sha1_ctx, cmd.buffer + tpm_readpubek_cmd.antiReplay,
			sizeof(TPM_NONCE));
	uint8_t digest[TPM_SHA1_160_HASH_LEN];
	vb2_sha1_finalize(&sha1_ctx, digest);
	if (vb2_safe_memcmp(digest, checksum, sizeof(digest))) {
		return TPM_E_AUTHFAIL;
	}

	/* Validate expectations for the EK. */
	if (algorithm != TPM_ALG_RSA ||
	    enc_scheme != TPM_ES_RSAESOAEP_SHA1_MGF1 ||
	    sig_scheme != TPM_SS_NONE ||
	    key_len != 2048 ||
	    num_primes != 2) {
		return TPM_E_INVALID_RESPONSE;
	}

	return result;
}

uint32_t TlclTakeOwnership(uint8_t enc_owner_auth[TPM_RSA_2048_LEN],
			   uint8_t enc_srk_auth[TPM_RSA_2048_LEN],
			   uint8_t owner_auth[TPM_AUTH_DATA_LEN])
{
	/* Start an OAIP session. */
	struct auth_session auth_session;
	uint32_t result = StartOIAPSession(&auth_session, owner_auth);
	if (result != TPM_SUCCESS) {
		return result;
	}

	/* Build the TakeOwnership command. */
	struct s_tpm_takeownership_cmd cmd;
	memcpy(&cmd, &tpm_takeownership_cmd, sizeof(cmd));
	memcpy(cmd.buffer + tpm_takeownership_cmd.encOwnerAuth, enc_owner_auth,
	       TPM_RSA_2048_LEN);
	memcpy(cmd.buffer + tpm_takeownership_cmd.encSrkAuth, enc_srk_auth,
	       TPM_RSA_2048_LEN);
	result = AddRequestAuthBlock(&auth_session, cmd.buffer,
				     sizeof(cmd.buffer), 0);
	if (result != TPM_SUCCESS) {
		return result;
	}

	/* The response buffer needs to be large to hold the public half of the
	 * generated SRK. */
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE + TPM_RSA_2048_LEN];
	result = TlclSendReceive(cmd.buffer, response, sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

	/* Check the auth tag on the response. */
	result = CheckResponseAuthBlock(&auth_session, TPM_ORD_TakeOwnership,
					response, sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

	return TPM_SUCCESS;
}

uint32_t TlclCreateDelegationFamily(uint8_t family_label)
{
	struct s_tpm_create_delegation_family_cmd cmd;
	memcpy(&cmd, &tpm_create_delegation_family_cmd, sizeof(cmd));
	cmd.buffer[tpm_create_delegation_family_cmd.familyLabel] = family_label;
	return Send(cmd.buffer);
}

uint32_t TlclReadDelegationFamilyTable(TPM_FAMILY_TABLE_ENTRY *table,
				       uint32_t* table_size)
{
	uint8_t response[TPM_LARGE_ENOUGH_COMMAND_SIZE];
	uint32_t result = TlclSendReceive(tpm_delegate_read_table_cmd.buffer,
					  response, sizeof(response));
	if (result != TPM_SUCCESS) {
		return result;
	}

	uint32_t size;
	FromTpmUint32(response + sizeof(uint16_t), &size);
	if (size < kTpmRequestHeaderLength + sizeof(uint32_t) ||
	    size > sizeof(response)) {
		return TPM_E_INVALID_RESPONSE;
	}

	const uint8_t* cursor = response + kTpmRequestHeaderLength;
	uint32_t table_bytes = ReadTpmUint32(&cursor);

	if (table_bytes > size - (cursor - response)) {
		return TPM_E_INVALID_RESPONSE;
	}

	uint32_t table_entries = table_bytes / sizeof(TPM_FAMILY_TABLE_ENTRY);
	int i;
	for (i = 0; i < table_entries; ++i) {
		if (i >= *table_size || !table) {
			result = TPM_E_BUFFER_SIZE;
			break;
		}

		table[i].tag = ReadTpmUint16(&cursor);
		table[i].familyLabel = *cursor++;
		table[i].familyID = ReadTpmUint32(&cursor);
		table[i].verificationCount = ReadTpmUint32(&cursor);
		table[i].flags = ReadTpmUint32(&cursor);
	}

	*table_size = table_entries;

	return result;
}

#endif  /* CHROMEOS_ENVIRONMENT */


/*
 * Author: Leandro Augusto Lacerda Campos <llacerdacampos@gmail.com>
 *
 * Data Structures and Algorithms Specialization,
 * by University of California, San Diego,
 * and National Research University Higher School of Economics
 *
 * Course 1: Algorithmic Toolbox
 *
 * Solution for Greatest Common Divisor Problem
 */

#include <stdio.h>

unsigned int gcd(unsigned int, unsigned int);

int main()
{
    unsigned int a, b;

    scanf("%u %u", &a, &b);
    printf("%u\n", gcd(a, b));
    return 0;
}

// gcd: calculate the greatest common divisor of two non-negative integers a and b,
// where 0 <= a, b <= 2 * 10^9. This function implements the Euclidean algorithm.
unsigned int gcd(unsigned int a, unsigned int b)
{
    if (a > b)
    {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }
    else
    {
        if (a == 0)
            return b;
        else
            return gcd(a, b % a);
    }
}


Implement a quantum oracle on N qubits which implements a function f(x) = xk, i.e. the value of the function is the value of the k-th qubit.

For an explanation on how the quantum oracles work, see the tutorial blog post.


Oscar was a visitor in the SRG group in 2014. His research interests include software reliability, particularly in the domain of networked and distributed systems. He focuses on influence of time on the behaviour of systems and how this can be analysed by symbolic execution.
Oscar received his BSc and MSc in Computer Science from the chair for *Communication and Distributed Systems* of *RWTH Aachen University*, where he is also pursuing his PhD studies since late 2013. He visited the Software Reliability Group during the summer semester of 2014 working on the KLEE memory model and solver algorithms.
Oscar is one of the two main contributors to and maintainer of the KleeNet project, a fork of KLEE for distributed systems.


Users will occasionally come to a page that doesn't exist on your site, either by following a broken link or typing in the wrong URL. Having a custom 404 page30 that kindly guides users back to a working page on your site can greatly improve a user's experience. Your 404 page should probably have a link back to your root page and could also provide links to popular or related content on your site. You can use Google Search Console to find the sources of URLs causing "not found" errors31.
Great content. Although I disagree with ‘the best times to post’ section. It is important to understand your audience. For example, if your brand/business is in high school, there will be low engagement until 2-5 when they are out of school. I highly suggest using instagram analytics (a subsidiary of facebook analytics) which gives you all of the details on when your followers are active. https://www.facebook.com/help/788388387972460
Excellent post Brian. I think the point about writing content that appeals to influencers in spot on. Could you recommend some good, manual strategies through which I can spot influencers in boring niches *B2B* where influencers are not really talking much online? Is it a good idea to rely on newspaper articles to a feel for what a particular industry is talking about? Would love to hear your thoughts on that.


Job Not Found
Sorry we couldn't find the job you were looking for.
Find the most recent jobs here:
I need you to develop some software for me. I would like this software to be developed.
i will help you get wins in Garina Free Fire on mobile.
I need drawings of a dining table and dining chair in 3-4 hours with proper sizes so that it can be given for production.I will send the pictures in inbox
We been attached by ransomware .com
I need some help with selling something.
Need a simple app built in flutter
We are a start up company, who are in need of an accurate logo. Our main themes are the following: name : Lumexus (from the latin words lumen=light and connect colour: maybe a gradient from redish-yellow-turkoise or just some light grey (feel free to try other stuff too, we are open about that) Font: not to plain, maybe a little abstract or in that direction (we want to seem modern) If yo...
each function needs to be properly commented including a clear description of the purpose of the function, its parameter list and its return values. For example, in Matlab, this means that a user should be able to use the help command to obtain information on how to use each function.
we daily update games in our website. we are looking for 1st page ranking on [login to view URL] / [login to view URL] for keywords. We need to work on long term for wordpress sites. Looking for Advanced Seo techniques , already we are builded links. Improve more keywords & website traffic . We need ranking reports on every week/month.
The task: We want to make a drone work with Unity C#. This drone has to move in commands in C#. We talk about the drone in the link below [login to view URL] We already did a lot and are just stuck on the following tasks: 1. Update [login to view URL] to match new drone 2. Figure out why heartbeats are blocked (probably requires handshake type TCP or UDP messaging first, .pcap file of drone-phone ...


- Get To Know Us
- Discuss Your Project
- Get An Estimate
We believe that dynamic languages such as Ruby allow us to create more value for our clients.
Behavior Driven Development
We believe that test-first processes create the cleanest code.
We adhere to the principles in the Agile Manifesto.


Everything started with watching a video of an LED cube and thinking it couldn't be that hard to solder some LEDs together and build one on my own.
But as it turned out not everything was that easy.
Concept behind an LED cube
On each layer the cathodes of the LEDs are connected, furthermore, all the anodes are connected vertically. This means, in the case of a 4x4x4 cube, there are 16 positive and 4 negative links. Now if one column is connected to positive voltage and one layer to ground then the LED in this column and this layer will light up. But at this point one can't turn on two individual LEDs on two different layers, the LEDs in all the positive columns where the layers are connected to ground will light up. The solution to this problem is multiplexing, so the first layer is turned on for a short time, then the next one, and so on.
Click on the LEDs to see how it works.
Control the speed here:
Multiplexing in real applications is so fast that the human eye can't distinguish between the separate layers. The downside is that the LEDs appear to be darker because they're not turned on the whole time.
With some experience in electronics but none in developing own circuits, I used (of course) an Arduino as microcontroller at the beginning.
I read about shift registers and played with the 74HC595 for a while.
One important thing I learned right at the start was that every input pin of this chip should be connected!
For example not connecting the 'enable' pin, thinking I didn't have to disable the shift register anyway, wasn't a good idea. The result was an undefined state for this pin and the chip dis- and enabled itself happily.
Two of the 74HC595 shift registers were used to drive the LEDs. Their outputs were directly connected to the anode of the LEDs. This didn't destroy the LEDs only because the shift register uses a MOSFET in its output circuit (2nd page "input and output equivalent circuit").
MOSFET characteristic curve
This MOSFET example characteristic curve basically tells us that the more current [IDS] is flowing the higher the drain to source voltage [VDS] gets. So with enough current its much like a series resistor for the LED.
Based on the work by "CyrilB", available under the Creative Commons Attribution-Share Alike 3.0 Unported license.
But I won't do this again because I have no idea how much current is flowing through one LED so they could have been destroyed. With that I also don't know exactly how much current the base of the ground-transistor needs to turn on all LEDs. A solution would be to use a transistor for each LED with a resistor in series so the LED won't be harmed.
For testing, to select which layer should be lit, I used transistors which were connected to the ground of each layer.
Here I ran into the next misconception.
First I used the analogue pins of the Arduino because I knew I didn't have to apply the 5V to the base to saturate the transistor.
This is nonsense because:
The analogue pins of the Arduino are using PWM which means toggling between 0V and 5V.
To get a different 'equivalent analogue value' the duty cycle via TON is changed. This means the transistor also turns on and off and doesn't get any 'analogue' voltage value at all.
In the end I just used another 74HC595 shift register with transistors at the outputs to connect each layer with ground.
For the circuit I used a perfboard. As long as it's simple stuff a perfboard is great but the circuit for the cube was already a bit too complex, so insulated wires were used for the connection to the LEDs. The cube was soldered with the help of a mounting-mask, which was made of a plastic sheet with drilled holes in it.
Because I want to understand how stuff works I coded a library myself (I can only recommend this) and didn't use an existing one. My goal was to give my code a coordinate and the right LED would turn on.
At the beginning coding a function for multiplexing the layers makes sense.
The function takes 8 x 8bit, that represents the LEDs in the cube and handles how long one frame is turned on.
After that I had to figure out which output of the shift registers goes to which LED. To give my code coordinates, another function is needed with a 3-dimensional array, that translates the coordinates into positions in a 64 digit long number (for the 8 x 8bit for the multiplexing function).
Now that I could address each coordinate, I wrote some animation functions. After that I wanted something more exciting, something with music. I found a Processing library called minim which is able to detect beats. Now there is only the communication between Processing and Arduino left and the beat visualization is good to go.
- Connect all input pins of this shift register.
- Use transistors with resistors or something similar to ensure a defined current for all the LEDs.
- The analogue pins of an Arduino don't really deliver analogue values instead they use PWM.


This is generally enforced by having Defaults requiretty in the /etc/sudoers. No panic, there is an easy fix!
-> sudo vim /etc/sudoers # # Disable "ssh hostname sudo
", because it will show the password in clear. # You have to run "ssh -t hostname sudo ". # #Defaults requiretty -> wq!
Defaults requiretty Defaults:sam !requiretty


Priest Spell Memorization
Priests do not need to memorize specific spells like wizards, due to their divine nature. Every day they receive the ability to cast a number of spells, which represents their ability to channel divine energy through their body. They do not have the ability to cast further spells until the start of the next day (at dawn). Spells slots of a higher level can be used to cast spells of a lower level (a 3rd level slot can be used to cast a 1st, 2nd, or 3rd level spell)
Priests have access to certain spheres (determined by class) and have access to spells from listed in the Player’s Option: Spells & Magic index. Any spells from other sources (Priest Spell Compendiums, other modules, or other books) or ones that the player wants to make, must be researched first. Some spells may be made available to start if they are related to a particular deity or class.


Прошло много лет, и на вечеринке снова встретились n друзей. С момента последней встречи техника шагнула далеко вперёд, появились фотоаппараты с автоспуском, и теперь не требуется, чтобы один из друзей стоял с фотоаппаратом, и, тем самым, оказывался не запечатлённым на снимке.

Упрощенно процесс фотографирования можно описать следующим образом. На фотографии каждый из друзей занимает прямоугольник из пикселей: в стоячем положении i-й из них занимает прямоугольник ширины wi пикселей и высоты hi пикселей. Но также, при фотографировании каждый человек может лечь, и тогда он будет занимать прямоугольник ширины hi пикселей и высоты wi пикселей.

Общая фотография будет иметь размеры W × H, где W — суммарная ширина всех прямоугольников-людей, а H — максимальная из высот. Друзья хотят определить, какую минимальную площадь может иметь общая фотография. Помогите им в этом.


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct node {
	int data;
	struct node * next;
} node;
const int BUFF = 256;

node * llbuild();
node *  addnode(node *, int);
node * traverse(node *, int);
int length(node *);
void display(node *);

int main()	{
	node * head = NULL;
	head = llbuild();
//	display(head);

	//delete to the left if small in one pass
	for(node * cur = head, *prev = NULL; cur->next; cur = cur->next)	{
		if(cur->next->data > cur->data)	{
			if(!prev)
				head = cur->next;
			else
				prev->next = cur->next;
		}
		else prev = cur;
	}

	//display
	display(head);

	return 0;
}

void display(node * list)	{
	node * new = list;
	while(new != NULL)	{
		printf("%d -> ", new->data);
		new = new->next;
	}
	printf("NULL\n");
}

node * traverse(node * list, int index)	{
	node * cur = list;
	for(int i = 2; i <= index; i++)
		cur = cur->next;
	return cur;
}

int length(node * list)	{
	int count = 1;
	node * cur = list;
	if(cur == NULL)
		return 0;
	while(cur->next != NULL)	{
		cur = cur->next;
		count++;
	}
	return count;
}

node * addnode(node * list, int value)	{
	node * end = traverse(list, length(list));
	node * new = malloc(sizeof(node));
	*new = (node){value, NULL};
	if(end == NULL)
		list = new;
	else
		end->next = new;
	return list;
}

node * llbuild()	{
	char * list = malloc(BUFF);
	scanf("%[^\n]", list);
	node * head = NULL;
	char * token = strtok(list, " ");
	while(token != NULL)	{
		char * endptr = NULL;
		int val = strtol(token, &endptr, 10);
		if(!*endptr)
			head = addnode(head, val);
		token = strtok(NULL, " ");
	}
	return head;
}


You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.

One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.

For example, if the string s is abacaba and the query is l1 = 3, r1 = 6, k1 = 1 then the answer is abbacaa. If after that we would process the query l2 = 1, r2 = 4, k2 = 2 then we would get the string baabcaa.


One of the core modules that I couldn't live without. Excellent feature set for relational database access. All viable relational databases on earth are supported. I've been using DBI with Oracle, Postgres and SQLite with no major issues. The user community is so huge that so far I haven't come to a question that a Google search couldn't answer.
The standard indispensable core of all things database.
The only minor issue I have is with the DBI distribution packaging, which does seem to be bloating out a little in recent times with some features and packages that might be better in a seperate distributions.
I use this module whenever I need to talk to a database. It has excellent documentation, clear examples, and provides a logical interface which makes using it in everyday coding rather easy. I can say that time invested in learning this module is rewarded with an excellent tool and better code.
Thanks for this de-facto standard in perl database penetration.
Strong points of DBI:
* it's the de facto standard in Perl, focusing database development.
* a unified interface for connectivity, basic activities (and somewhat for capabilities), making it almost-not-a-nightmare to switch between database backends (but then there's always the specific syntax, semantics and concepts of different databases for anything non-trivial... *sigh*)
* it's stable and mature with countless hours in production.
* nice API.
* huge amounts of additions and utilities in the DBIx namespace, built on top of DBI. Not to mention Class::DBI.
Although it is one of the best developed perl-modules around (IMHO) I think it could use a bit nicer API - the length of the function names makes it error-prone. One solution would be returning (browsable) recordsets instead of a handler. (just daydreaming here)
I haved used this version reliably with DBD::mysql 1.2216 and with the MySQL 3.23.52 database under Red Hat Linux 7.2 for over a year.
Overall DBI is a great tool. it has brought a consistency to dealing with a whole variety of different databases and the APIs that go with them.
Tried using Proxy 1.30 but gave it away in the end. It was on Digital Unix 4.0f and kept stopping responding after a couple of days. Restarting would work but this was frustrating. Not sure whether the fault was DBD::Ingres or the server but don't really care now as we have moved on.
Used with DBD::Oracle without problem.
Excellent; provides all DB interface functionality I need when using Perl.
I have one ongonig problem in that the DBI:Proxy on HPUX crashes which is probably due to Net::Daemon not handling client side disconnects gracefully enough. I have to run a cron job every 5 minutes to restart DBI::Proxy if it dies. Installation was difficult (since I am not the DBA) for Oracle, but once it was figured out, the coding was straight forward.
My DBA and SysAdmin both think I have implemented a "BLACK BOX" which they fear, don't trust, and can't seem to get their arms around. But after 1 1/2 successful years of a small production program that works, and with implementations added on for Microsoft SQL on W2K, Linux MySQL and Oracle on HPUX, it is being more widely accepted.
Thanks to the DBI team. I have been very happy with this one and only version I have installed and used thus far.
Very complete and mature database framework for Perl.
A wonderful module.
Using Perl DBI is so much more fun than using Java and JDBC.
It also seems to knock the socks off PHP's database APIs, although I'm going on the PHP documentation rather than actual experience.
It's the DB category-killer. Indispensible for any DB work.
one of the strongest modules for Perl.
A fantastic module with very thorough documentation and a nice API. As a matter of fact we wouldn't be using Perl for a lot of our projects at work if it wasn't for DBI. Best module on the CPAN? Hmm, top 5 for sure.
This gets fives because it is the classic way to connect to any database. You might want to look at Class::DBI for something easier.
The DBI is the single package that has made my life easier than any other non-Core module. I learned it once and now use it every day on multiple RDBMS. It is Just Right.
Excellent module. Smart and responsive author. There's just no other choice when it comes to using Perl to interface with a database.
Excellent module with thorough documentation. The newer versions also have lots of shortcut methods which save a lot of time (and are part of why I'm giving it 5/5 for "Ease of Use").
I dread to think how my code would be if I'd had to write this for myself
Fantastic! I couldn't imagine having to do my job without it!
(& thanks for the new ratings system!)
DBI.pm is an amazingly useful module; but you probably already use it and know that.
(how's this for a test review?)
5 hidden unhelpful reviews


//
//  R5Connection.h
//  Red5Pro
//
//  Created by Andy Zupko on 9/16/14.
//  Copyright (c) 2014 Infrared5. All rights reserved.
//

#import <Foundation/Foundation.h>
#include "global.h"
#import "R5Configuration.h"

@protocol R5ConnectionDelegate;

/**
 *  @brief The main connection class for R5Pro.  This establishes the connection to the server.  Used by R5Stream as the communication layer.
 */
@interface R5Connection : NSObject

/**
 *  The configuration for this connection
 */
@property (readonly) R5Configuration *config;

/**
 *  The delegate to receive events for this connection. Specifically for Data Only streams.
 */
@property NSObject<R5ConnectionDelegate> *delegate;

/**
 *  The client to receive rpc calls for this connection. Specifically for Data Only streams.
 */
@property NSObject *client;

/**
 *  Initialize the connection with the configuration
 *
 *  @param config The configuration of the connection
 *
 *  @return a new connection
 */
-(id)initWithConfig:(R5Configuration*) configuration;

/**
 * De-initialize the connection.
 */
-(void)invalidate;

/**
 *  Make a connection call RPC to the server
 *
 *  @param method Method name to call
 *  @param returnMethod Return method name.  "void" if no return
 *  @param param  Parameter to send for this method
 */
-(void)call:(NSString*)method withReturn:(NSString*)returnMethod withParam:(NSString*)param;

/*
 *  Start a connection with a remote shared object
 */
-(void)connectToSharedObject:(NSString*)name;

/*
 *  Send a message through the Shared Object interface
 */
-(void)sharedObjectSend:(NSString*)message;

/**
 *  Request to switch the stream received on the current connection.
 * @param app The webapp context the target stream is being streamed in. e.g., "live".
 * @param streamName The new target stream name to request playback.
 */
-(void)switchStream:(NSString*)app name:(NSString*)streamName;

/**
 * Request a connection for data transfers - can't be used if this object is already being used for an A/V stream
 */
-(void)startDataOnlyStream;
-(void)stopDataOnlyStream;

/**
 *  Get the connection context associated with this context
 *
 *  @return A client connection context.
 */
-(client_ctx*)context;

@end

/**
 *  @protocol R5ConnectionDelegate
 *  @brief Delegate for handling R5Stream events
 */
@protocol R5ConnectionDelegate <NSObject>

/**
 *  Status handler for the R5Stream events
 *
 *  @param stream     Stream that has dispatched the event.
 *  @param statusCode Unique status code of the event.
 *  @param msg        A string description of the event.
 *
 *
 *
 *  Status Code     |  Msg
 *  -----------     | ------------
 *  CONNECTED       |   null
 *  DISCONNECTED    |   null
 *  ERROR           |   string message describing error
 *  TIMEOUT         |   null
 *  CLOSE           |   null
 *  START_STREAMING |   null
 *  STOP_STREAMING  |   null
 *  NET_STATUS      |   "NetStream.Play.PublishNotify" - publisher started
"NetStream.Play.UnpublishNotify" - publisher stopped
"NetStream.Play.StreamDry" - Keep Alive while no publisher publishing
"NetStream.Play.InSufficientBW.Audio" - subscriber does not have enough bandwidth to accept audio in stream
"NetStream.Play.InSufficientBW.Video" - subsceiber does not have enough bandwidth to accept video in stream
"NetStream.Play.SufficientBW.Audio" - subscriber has regained enough bandwidth to consume audio
"NetStream.Play.SufficientBW.Video" - subscriber has regained enough bandwidth to consume video
 *  AUDIO_MUTE      |   null
 *  AUDIO_UNMUTE    |   null
 *  VIDEO_MUTE      |   null
 *  VIDEO_UNMUTE    |   null
 *  LICENSE_ERROR   |   null
 *  LICENSE_VALID   |   null
 *  BUFFER_FLUSH_START  |   null
 *  BUFFER_FLUSH_EMPTY  |   null
 *  VIDEO_RENDER_START  |   null
 *
 */
-(void)onR5ConnectionStatus:(R5Connection *)connection withStatus:(int) statusCode withMessage:(NSString*)msg;

@end


Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.

The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square $$\frac{i}{2}$$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads.

Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe.

He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.


As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as $$\frac{k(k+1)}{2}$$, where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.

A well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number n, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)!


Sarlo's Guru Rating Service is an invaluable reference work; a vast compendium of links to and short irreverent summaries of just about every guru and spiritual master out there, plus a growing list of historicals, less well known figures, etc. Each entry is classified according to category, given a short description, and cheekily rated in terms of what seem to be little seated meditating figures or maybe they're buddhas (instead of the usual stars).
Sarlo was raised an agnostic, made a number of trips to India, dabbled with Paramahansa Yogananda and a few others before deciding on Osho as his Master. Although his ratings (how many "buddhas" awared to each) at times differ radically from the recommendations given in these pages, his massive website is a real inspiration and wonderful resource for anyone wishing to critique gurus, spiritual teachers and masters.
Sarlo's ratings are:
(note: I did briefly consider including some sort of similar rating here, but felt that the whole guru and master phenomenon is too diverse to be simplistically rated along a single scale. Hence I decided to employ a number of different categories - Insight, Morality, and Following)
Rated categories include Devotion, Advaita, Middle Path (a combination of the preceeding two) and Fringe (New Age, esoteric, etc, universally rated very poorly). Unrated categories are (Zen) (Tibetan) (Sufis) (Buddhists) (Misc) (Yoga) (Indian) (Nondual) (Perennials) (Earth Medicine) (Humour) (Quasi-Christian) (Gnostic/Science) (Literature), and (Channels/New Age)
Also of use are Essays, further Links, and Dirt: (Special "Anti-"sites devoted to particular masters or groups).
In short an excellent, humourous reference, not to be taken serious (in fact Sarlo is even more irreverant than I am), and index for gurus and masters of all sorts (although with an emphasis on the Eastern ones)


Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way.

In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are:

1. If i ≠ n, move from pile i to pile i + 1;
2. If pile located at the position of student is not empty, remove one box from it.

GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed.


GitKraken vs SourceTree: What are the differences?
Developers describe GitKraken as "Git GUI Client for Windows Mac and Linux built on Electron". The downright luxurious Git client for Windows, Mac and Linux. Cross-platform, 100% standalone, and free. On the other hand, SourceTree is detailed as "A free Git GUI client for Windows and macOS". Use the full capability of Git and Mercurial in the SourceTree desktop app. Manage all your repositories, hosted or local, through SourceTree's simple interface.
GitKraken and SourceTree can be categorized as "Source Code Management Desktop Apps" tools.
"Dark theme" is the primary reason why developers consider GitKraken over the competitors, whereas "Visual history and branch view" was stated as the key factor in picking SourceTree.
According to the StackShare community, SourceTree has a broader approval, being mentioned in 615 company stacks & 400 developers stacks; compared to GitKraken, which is listed in 42 company stacks and 38 developer stacks.


QUOTE(xamindar @ Mar 28 2008, 12:07 AM)
Please provide a little more info.....Zaurus doesn't support bluetooth out of the box so list what software you are using for pairing and dialing. Also, how are you sure the phone is paired?
I currently use bluetooth on my zaurus to get internet access through my LG phone without any problems so I may be of help. You just need to provide as much info as you can to get help.
Sorry I only just saw your reply!
I just about got this connection to work with my LG phone by tring to connect from an imac. However the phone then shut off and will not turn back on so is away for repair. In the meantime I have a Motorola V8 phone and I am trying to connect to this. Unfortunateley the same thing is happening - the phone requests a pin for pairing instead of connecting via gprs. - I had this working great with my V3 and thought this would be easy!
I am using the network application in the cacko Rom.
I have the user name and password for the o2 connection and I have tried different phone dial up codes.
i.e. star99hash ( cannot locate these on this keyboard)
I tried the connection from the imac with exactly the same result. - The phone asks for a pin for pairing and then shuts off any network connection.
I have all devices paired and selected for dial up networking and have selected to allow connections.
Not sure what else to try.
keef c860 and V8


… but man, I wish I’d had a camera with me.
On one of the woodchip paths today, I saw four Garter Snakes, one large brown one which I think was female (thicker body which thins abruptly at the tail) and three smaller males (no change of size between body/tail). One of the males lay on top of the female, matching all her curves and his tail wrapped around her. An occasional muscular contraction passed down his body. The other two males kept tasting the air around her and trying to nudge their way between the pair.
It certainly looked like mating behaviour, but every reference I can find says garter snakes mate in the spring, fresh out of hibernation. I posted a question to the Western NY Herp Society, hoping they can enlighten me.
I watched them for 20 minutes or so. Not a lot was going on, just slow slithering. I decided to leave them alone after a while and hoped no one would come along and freak out at the sight of snakes.


I'd like to debug Lazarus library code. In Delphi IDE I would simply check the Project Options -> Compiler -> Use Debug DCUs option on. Is there something similar in Lazarus?
Yes and no. It roughly works the same as in Delphi, you need two sets of the compiled units. (.o/.ppu), and some way to switch.
But because FPC/Lazarus are open source, only one set (the one without) is distributed. But you can craft the other byrecompile FPC and Lazarus with -gl. For tips on recompiling FPC/Lazarus see http://www.stack.nl/~marcov/buildfaq.pdf
(it is even possible to do combinations. I debug many of my applications with everything debug except systems and sysutils, so that I don't trace into each and every string and exception helper, a major annoyance on Delphi)
Currently the releases afaik don't distribute the duplicate sets, but this is more a release engineering problem. (specially since by using strip, the non-debug set can be probably crafted from the debug set)
BTW, it might be worth the trouble to ask on the Lazarus maillist if such way exists. Even if the release doesn't set it up, there might still be a possibility that the functionality exists.


There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that

- starts in the upper left cell of the matrix;
- each following cell is to the right or down from the current cell;
- the way ends in the bottom right cell.

Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.


Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium.

The digital board is n pixels in height and m pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The j-th pixel of the i-th line is pixel (i, j). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light.

Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (i, j) belongs to a side of sub-rectangle with (x1, y1) and (x2, y2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition:

((i = x1 or i = x2) and (y1 ≤ j ≤ y2)) or ((j = y1 or j = y2) and (x1 ≤ i ≤ x2)).

Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them?


Song, Victor, Hasan Cavusoglu, Mary L. Z. Ma, Gene Moo Lee (2022) “IT Risk and Stock Price Crashes,” Major Revision, Information Systems Research. [HICSS version]
- Presented at UBC Cybersecurity 2018 (Vancouver, BC) and HICSS 2020 (Maui, HI)
- Based on Victor Song’s Master’s Thesis
As firms increasingly depend on Information Technology (IT), risks associated with IT have become one of the top concerns for managers and investors. This study examines the relation between the IT-related risk factor in Item 1A of the 10-K annual reports and a firm’s stock price crash risk, a firm-specific propensity to stock price crashes. Using topic modeling to identify IT-related risk factors, we find that IT risk emerges as one of the firms’ key risk categories and that IT risk factors are positively associated with a firm’s future stock price crash risk. We further separate IT risk factors into cybersecurity risk that potentially leads to a loss or leak of data, and non-cybersecurity IT risk that relates to a firm’s reliance on IT for its competitive advantage and value creation activities. We find that cybersecurity risk continues to affect crash risk, but non-cybersecurity IT risk does not, consistent with their different risk natures. We also find that the readability, novelty, and the order of appearance of the IT risk factor in Item 1A enhance the information content of IT risk factors and strengthen their relation with stock price crash risk.


So here’s a crazy idea. CC @mjdsmith965
- we try to pull together a community-driven, open-source spacecraft/satellite bus system
- we open access to the bus by developing it into a cloud solution so people around the world can remotely connect novel payloads to it and run applications on it - as if it was a cloud service
There are a number of open-sourced CubeSats around, but I feel that they aren’t quite good enough to be a more powerful platform. I’m thinking a spacecraft bus for craft in the 100-200kg range. Could be useful for telecoms sats, EO sats, or even spacetugs.
Moonshot would be happy to host the hardware. I think we could start to see some incredible innovations if that was made available, and its exactly this kind of open activity that I build Moonshot to encourage.
It would be good to check out FOS licences that are more appropriate for hardware, which are only just coming to up, like this one.
What do we reckon? 🤔


Fishingprince loves trees. A tree is a connected undirected graph without cycles.

Fishingprince has a tree of $$$n$$$ vertices. The vertices are numbered $$$1$$$ through $$$n$$$. Let $$$d(x,y)$$$ denote the shortest distance on the tree from vertex $$$x$$$ to vertex $$$y$$$, assuming that the length of each edge is $$$1$$$.

However, the tree was lost in an accident. Fortunately, Fishingprince still remembers some information about the tree. More specifically, for every triple of integers $$$x,y,z$$$ ($$$1\le x<y\le n$$$, $$$1\le z\le n$$$) he remembers whether $$$d(x,z)=d(y,z)$$$ or not.

Help him recover the structure of the tree, or report that no tree satisfying the constraints exists.


A new programming language has been developed to try to reduce the complexity of building applications for ad hoc peer-to-peer mobile device networks. The new D3N (Data-Driven Declarative Networking) language devloped by a team from Cambridge University offers a way to communicate without some of the geographical constraints.
Research team leader, Jon Crowcroft released a paper paper describing the new technology. "We envision an emergence of a new type of communications based on physical proximity, where people encounter each other and devices directly communicate within their range," the paper said. "We introduce declarative networking for pocket-switched networks called D3N, which allows applications to construct a protocol description consisting of a reactive behaviour of a distributed node."
Such peer-to-peer mobile device networks, called "pocket-switched networks," could allow communications between wireless devices without the need for conventional cellular networks, thereby eliminating the need for cell towers and base stations, researchers said in a recent issue of MIT's Technology Review.
For example, an ad hoc network would mean that after a hurricane knocks down cell towers, as happened when Hurricane Katrina hit near New Orleans in 2005, people using wireless devices could theoretically connect with one another over pocket-switched networks for access to help. Or, instead of going to the Internet for information on good places to stay or eat in an unfamiliar town, an ad hoc mobile network might help a visitor get the information from local residents or businesses.
Peer-to-peer networking is a fairly commonplace idea in wired networks, but linking wireless smartphones and other handheld computers through pocket-switched networks would require using Bluetooth or another short-range wireless network.
Crowcroft told Technology Review that if D3N gains popularity, it would usher in a "whole slew of applications." Part of the challenge of building an ad hoc wireless network would be dealing with delays in connections, partly because individual mobile devices might be only occasionally connected. Still, they would need to be able to forward messages when reconnected. Users would subscribe to be part of an ad hoc network.
D3N is based on the F# programming language, a Microsoft initiative. The paper says that future research will include validating the D3N language on a compiler deployed on actual wireless devices.


/******************************************************************************
 * @file     main.c
 * @version  V3.00
 * @brief
 *           Use SD card as storage to implement a USB mass storage device.
 * @note
 * @copyright SPDX-License-Identifier: Apache-2.0
 * @copyright Copyright (C) 2021 Nuvoton Technology Corp. All rights reserved.
 ******************************************************************************/
#include <stdio.h>
#include "NuMicro.h"
#include "massstorage.h"
#include "SDCARD.h"

/* If crystal-less is enabled, system won't use any crystal as clock source
   If using crystal-less, system will be 48MHz, otherwise, system is 72MHz
*/
#define CRYSTAL_LESS        1
#define HIRC_AUTO_TRIM      0x611   /* Use USB signal to fine tune HIRC 48MHz */
#define TRIM_INIT           (SYS_BASE+0x110)

void SYS_Init(void)
{
    /*---------------------------------------------------------------------------------------------------------*/
    /* Init System Clock                                                                                */
    /*---------------------------------------------------------------------------------------------------------*/
    /* Enable HIRC clock */
    CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk);

    /* Wait for HIRC clock ready */
    CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk);

#if (!CRYSTAL_LESS)
    /* Enable GPIO Port F module clock */
    CLK_EnableModuleClock(GPIOF_MODULE);

    /* Set XT1_OUT(PF.2) and XT1_IN(PF.3) as input mode to use HXT */
    GPIO_SetMode(PF, BIT2|BIT3, GPIO_MODE_INPUT);

    /* Enable HXT clock */
    CLK_EnableXtalRC(CLK_PWRCTL_HXTEN_Msk);

    /* Wait for HXT clock ready */
    CLK_WaitClockReady(CLK_STATUS_HXTSTB_Msk);

    /* Set core clock to 72MHz */
    CLK_SetCoreClock(72000000);

    /* Select USB clock source as PLL and USB clock divider as 3 */
    CLK_SetModuleClock(USBD_MODULE, CLK_CLKSEL3_USBDSEL_PLL, CLK_CLKDIV0_USB(3));
#else
    /* Select HCLK clock source to HIRC and HCLK clock divider as 1 */
    CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1));

    /* Select USB clock source as HIRC and USB clock divider as 1 */
    CLK_SetModuleClock(USBD_MODULE, CLK_CLKSEL3_USBDSEL_HIRC, CLK_CLKDIV0_USB(1));
#endif

    /* Enable UART0 module clock */
    CLK_EnableModuleClock(UART0_MODULE);

    /* Select UART0 module clock source as HIRC/2 and UART0 module clock divider as 1 */
    CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UART0SEL_HIRC_DIV2, CLK_CLKDIV0_UART0(1));

    /* Enable USBD module clock */
    CLK_EnableModuleClock(USBD_MODULE);

    /* Enable SPI1 module clock */
    CLK_EnableModuleClock(SPI1_MODULE);

    /* Select SPI1 module clock source as PCLK0 */
    CLK_SetModuleClock(SPI1_MODULE, CLK_CLKSEL2_SPI1SEL_PCLK0, MODULE_NoMsk);

    /*---------------------------------------------------------------------------------------------------------*/
    /* Init I/O Multi-function                                                                                */
    /*---------------------------------------------------------------------------------------------------------*/
    /* Set PB multi-function pins for UART0 RXD and TXD */
    SYS->GPB_MFPH = (SYS->GPB_MFPH & (~(UART0_RXD_PB12_Msk | UART0_TXD_PB13_Msk))) | UART0_RXD_PB12 | UART0_TXD_PB13;

    /* Set SPI1 multi-function pins */
    SYS->GPC_MFPL &= ~(SYS_GPC_MFPL_PC1MFP_Msk | SYS_GPC_MFPL_PC2MFP_Msk | SYS_GPC_MFPL_PC3MFP_Msk);
    SYS->GPC_MFPL |= SYS_GPC_MFPL_PC1MFP_SPI1_CLK | SYS_GPC_MFPL_PC2MFP_SPI1_MOSI | SYS_GPC_MFPL_PC3MFP_SPI1_MISO;
    GPIO_SetMode(PC, BIT5, GPIO_MODE_OUTPUT);
    GPIO_SetMode(PC, BIT4, GPIO_MODE_OUTPUT);
}

/*---------------------------------------------------------------------------------------------------------*/
/*  Main Function                                                                                */
/*---------------------------------------------------------------------------------------------------------*/
int32_t main(void)
{
#if CRYSTAL_LESS
    uint32_t u32TrimInit;
#endif

    /* Unlock protected registers */
    SYS_UnlockReg();

    /* Init system and multi-function I/O */
    SYS_Init();

    /* Configure UART0: 115200, 8-bit word, no parity bit, 1 stop bit. */
    UART_Open(UART0, 115200);

    printf("+-------------------------------------------------------+\n");
    printf("|          NuMicro USB MassStorage Sample Code          |\n");
    printf("+-------------------------------------------------------+\n");

    SDCARD_Open();

    /* Open USB controller */
    USBD_Open(&gsInfo, MSC_ClassRequest, NULL);

    USBD_SetConfigCallback(MSC_SetConfig);

    /* Endpoint configuration */
    MSC_Init();

    /* Start USB device */
    USBD_Start();

    /* Enable USB device interrupt */
    NVIC_EnableIRQ(USBD_IRQn);

#if CRYSTAL_LESS
    /* Backup default trim */
    u32TrimInit = M32(TRIM_INIT);
#endif

    /* Clear SOF */
    USBD->INTSTS = USBD_INTSTS_SOFIF_Msk;

    while(1)
    {
#if CRYSTAL_LESS
        /* Start USB trim if it is not enabled. */
        if((SYS->IRCTCTL & SYS_IRCTCTL_FREQSEL_Msk) != 1)
        {
            /* Start USB trim only when SOF */
            if(USBD->INTSTS & USBD_INTSTS_SOFIF_Msk)
            {
                /* Clear SOF */
                USBD->INTSTS = USBD_INTSTS_SOFIF_Msk;

                /* Re-enable crystal-less */
                SYS->IRCTCTL = HIRC_AUTO_TRIM | (8 << SYS_IRCTCTL_BOUNDARY_Pos);
            }
        }

        /* Disable USB Trim when error */
        if(SYS->IRCTISTS & (SYS_IRCTISTS_CLKERRIF_Msk | SYS_IRCTISTS_TFAILIF_Msk))
        {
            /* Init TRIM */
            M32(TRIM_INIT) = u32TrimInit;

            /* Disable crystal-less */
            SYS->IRCTCTL = 0;

            /* Clear error flags */
            SYS->IRCTISTS = SYS_IRCTISTS_CLKERRIF_Msk | SYS_IRCTISTS_TFAILIF_Msk;

            /* Clear SOF */
            USBD->INTSTS = USBD_INTSTS_SOFIF_Msk;
        }
#endif

        MSC_ProcessCmd();
    }
}


I am not sure if people are still having problems basically it was stated to create a new forum. But I bought my laptop brand new. I got it from Best Buy... they said nothing about open box or anything. (If it was I want my discount) but anyways. I tried to register my laptop and it says it can not be registered because it is already registered. So I am not sure what to do at this point? Can I get help?