code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* Copyright (C) Research In Motion Limited 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "SVGTextChunkBuilder.h"
#include "RenderSVGInlineText.h"
#include "SVGElement.h"
#include "SVGInlineTextBox.h"
namespace WebCore {
SVGTextChunkBuilder::SVGTextChunkBuilder()
{
}
void SVGTextChunkBuilder::transformationForTextBox(SVGInlineTextBox* textBox, AffineTransform& transform) const
{
DEFINE_STATIC_LOCAL(const AffineTransform, s_identityTransform, ());
if (!m_textBoxTransformations.contains(textBox)) {
transform = s_identityTransform;
return;
}
transform = m_textBoxTransformations.get(textBox);
}
void SVGTextChunkBuilder::buildTextChunks(Vector<SVGInlineTextBox*>& lineLayoutBoxes)
{
if (lineLayoutBoxes.isEmpty())
return;
bool foundStart = false;
unsigned lastChunkStartPosition = 0;
unsigned boxPosition = 0;
unsigned boxCount = lineLayoutBoxes.size();
for (; boxPosition < boxCount; ++boxPosition) {
SVGInlineTextBox* textBox = lineLayoutBoxes[boxPosition];
if (!textBox->startsNewTextChunk())
continue;
if (!foundStart) {
lastChunkStartPosition = boxPosition;
foundStart = true;
} else {
ASSERT(boxPosition > lastChunkStartPosition);
addTextChunk(lineLayoutBoxes, lastChunkStartPosition, boxPosition - lastChunkStartPosition);
lastChunkStartPosition = boxPosition;
}
}
if (!foundStart)
return;
if (boxPosition - lastChunkStartPosition > 0)
addTextChunk(lineLayoutBoxes, lastChunkStartPosition, boxPosition - lastChunkStartPosition);
}
void SVGTextChunkBuilder::layoutTextChunks(Vector<SVGInlineTextBox*>& lineLayoutBoxes)
{
buildTextChunks(lineLayoutBoxes);
if (m_textChunks.isEmpty())
return;
unsigned chunkCount = m_textChunks.size();
for (unsigned i = 0; i < chunkCount; ++i)
processTextChunk(m_textChunks[i]);
m_textChunks.clear();
}
void SVGTextChunkBuilder::addTextChunk(Vector<SVGInlineTextBox*>& lineLayoutBoxes, unsigned boxStart, unsigned boxCount)
{
SVGInlineTextBox* textBox = lineLayoutBoxes[boxStart];
ASSERT(textBox);
RenderSVGInlineText* textRenderer = toRenderSVGInlineText(textBox->textRenderer());
ASSERT(textRenderer);
const RenderStyle* style = textRenderer->style();
ASSERT(style);
const SVGRenderStyle* svgStyle = style->svgStyle();
ASSERT(svgStyle);
// Build chunk style flags.
unsigned chunkStyle = SVGTextChunk::DefaultStyle;
// Handle 'direction' property.
if (!style->isLeftToRightDirection())
chunkStyle |= SVGTextChunk::RightToLeftText;
// Handle 'writing-mode' property.
if (svgStyle->isVerticalWritingMode())
chunkStyle |= SVGTextChunk::VerticalText;
// Handle 'text-anchor' property.
switch (svgStyle->textAnchor()) {
case TA_START:
break;
case TA_MIDDLE:
chunkStyle |= SVGTextChunk::MiddleAnchor;
break;
case TA_END:
chunkStyle |= SVGTextChunk::EndAnchor;
break;
};
// Handle 'lengthAdjust' property.
float desiredTextLength = 0;
if (SVGTextContentElement* textContentElement = SVGTextContentElement::elementFromRenderer(textRenderer->parent())) {
desiredTextLength = textContentElement->specifiedTextLength().value(textContentElement);
switch (static_cast<SVGTextContentElement::SVGLengthAdjustType>(textContentElement->lengthAdjust())) {
case SVGTextContentElement::LENGTHADJUST_UNKNOWN:
break;
case SVGTextContentElement::LENGTHADJUST_SPACING:
chunkStyle |= SVGTextChunk::LengthAdjustSpacing;
break;
case SVGTextContentElement::LENGTHADJUST_SPACINGANDGLYPHS:
chunkStyle |= SVGTextChunk::LengthAdjustSpacingAndGlyphs;
break;
};
}
SVGTextChunk chunk(chunkStyle, desiredTextLength);
Vector<SVGInlineTextBox*>& boxes = chunk.boxes();
for (unsigned i = boxStart; i < boxStart + boxCount; ++i)
boxes.append(lineLayoutBoxes[i]);
m_textChunks.append(chunk);
}
void SVGTextChunkBuilder::processTextChunk(const SVGTextChunk& chunk)
{
bool processTextLength = chunk.hasDesiredTextLength();
bool processTextAnchor = chunk.hasTextAnchor();
if (!processTextAnchor && !processTextLength)
return;
const Vector<SVGInlineTextBox*>& boxes = chunk.boxes();
unsigned boxCount = boxes.size();
if (!boxCount)
return;
// Calculate absolute length of whole text chunk (starting from text box 'start', spanning 'length' text boxes).
float chunkLength = 0;
unsigned chunkCharacters = 0;
chunk.calculateLength(chunkLength, chunkCharacters);
bool isVerticalText = chunk.isVerticalText();
if (processTextLength) {
if (chunk.hasLengthAdjustSpacing()) {
float textLengthShift = (chunk.desiredTextLength() - chunkLength) / chunkCharacters;
unsigned atCharacter = 0;
for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
Vector<SVGTextFragment>& fragments = boxes[boxPosition]->textFragments();
if (fragments.isEmpty())
continue;
processTextLengthSpacingCorrection(isVerticalText, textLengthShift, fragments, atCharacter);
}
} else {
ASSERT(chunk.hasLengthAdjustSpacingAndGlyphs());
float textLengthScale = chunk.desiredTextLength() / chunkLength;
AffineTransform spacingAndGlyphsTransform;
bool foundFirstFragment = false;
for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
SVGInlineTextBox* textBox = boxes[boxPosition];
Vector<SVGTextFragment>& fragments = textBox->textFragments();
if (fragments.isEmpty())
continue;
if (!foundFirstFragment) {
foundFirstFragment = true;
buildSpacingAndGlyphsTransform(isVerticalText, textLengthScale, fragments.first(), spacingAndGlyphsTransform);
}
m_textBoxTransformations.set(textBox, spacingAndGlyphsTransform);
}
}
}
if (!processTextAnchor)
return;
// If we previously applied a lengthAdjust="spacing" correction, we have to recalculate the chunk length, to be able to apply the text-anchor shift.
if (processTextLength && chunk.hasLengthAdjustSpacing()) {
chunkLength = 0;
chunkCharacters = 0;
chunk.calculateLength(chunkLength, chunkCharacters);
}
float textAnchorShift = chunk.calculateTextAnchorShift(chunkLength);
for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
Vector<SVGTextFragment>& fragments = boxes[boxPosition]->textFragments();
if (fragments.isEmpty())
continue;
processTextAnchorCorrection(isVerticalText, textAnchorShift, fragments);
}
}
void SVGTextChunkBuilder::processTextLengthSpacingCorrection(bool isVerticalText, float textLengthShift, Vector<SVGTextFragment>& fragments, unsigned& atCharacter)
{
unsigned fragmentCount = fragments.size();
for (unsigned i = 0; i < fragmentCount; ++i) {
SVGTextFragment& fragment = fragments[i];
if (isVerticalText)
fragment.y += textLengthShift * atCharacter;
else
fragment.x += textLengthShift * atCharacter;
atCharacter += fragment.length;
}
}
void SVGTextChunkBuilder::processTextAnchorCorrection(bool isVerticalText, float textAnchorShift, Vector<SVGTextFragment>& fragments)
{
unsigned fragmentCount = fragments.size();
for (unsigned i = 0; i < fragmentCount; ++i) {
SVGTextFragment& fragment = fragments[i];
if (isVerticalText)
fragment.y += textAnchorShift;
else
fragment.x += textAnchorShift;
}
}
void SVGTextChunkBuilder::buildSpacingAndGlyphsTransform(bool isVerticalText, float scale, const SVGTextFragment& fragment, AffineTransform& spacingAndGlyphsTransform)
{
spacingAndGlyphsTransform.translate(fragment.x, fragment.y);
if (isVerticalText)
spacingAndGlyphsTransform.scaleNonUniform(1, scale);
else
spacingAndGlyphsTransform.scaleNonUniform(scale, 1);
spacingAndGlyphsTransform.translate(-fragment.x, -fragment.y);
}
}
#endif // ENABLE(SVG)
| mogoweb/webkit_for_android5.1 | webkit/Source/WebCore/rendering/svg/SVGTextChunkBuilder.cpp | C++ | apache-2.0 | 9,299 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
*
* @package PhpMyAdmin
*/
// Run common work
require_once './libraries/common.inc.php';
define('TABLE_MAY_BE_ABSENT', true);
require './libraries/tbl_common.php';
$url_query .= '&goto=tbl_tracking.php&back=tbl_tracking.php';
$url_params['goto'] = 'tbl_tracking.php';;
$url_params['back'] = 'tbl_tracking.php';
// Init vars for tracking report
if (isset($_REQUEST['report']) || isset($_REQUEST['report_export'])) {
$data = PMA_Tracker::getTrackedData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version']);
$selection_schema = false;
$selection_data = false;
$selection_both = false;
if (! isset($_REQUEST['logtype'])) {
$_REQUEST['logtype'] = 'schema_and_data';
}
if ($_REQUEST['logtype'] == 'schema') {
$selection_schema = true;
} elseif ($_REQUEST['logtype'] == 'data') {
$selection_data = true;
} else {
$selection_both = true;
}
if (! isset($_REQUEST['date_from'])) {
$_REQUEST['date_from'] = $data['date_from'];
}
if (! isset($_REQUEST['date_to'])) {
$_REQUEST['date_to'] = $data['date_to'];
}
if (! isset($_REQUEST['users'])) {
$_REQUEST['users'] = '*';
}
$filter_ts_from = strtotime($_REQUEST['date_from']);
$filter_ts_to = strtotime($_REQUEST['date_to']);
$filter_users = array_map('trim', explode(',', $_REQUEST['users']));
}
// Prepare export
if (isset($_REQUEST['report_export'])) {
/**
* Filters tracking entries
*
* @param array the entries to filter
* @param string "from" date
* @param string "to" date
* @param string users
*
* @return array filtered entries
*
*/
function PMA_filter_tracking($data, $filter_ts_from, $filter_ts_to, $filter_users) {
$tmp_entries = array();
$id = 0;
foreach ( $data as $entry ) {
$timestamp = strtotime($entry['date']);
if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to &&
( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) {
$tmp_entries[] = array( 'id' => $id,
'timestamp' => $timestamp,
'username' => $entry['username'],
'statement' => $entry['statement']
);
}
$id++;
}
return($tmp_entries);
}
$entries = array();
// Filtering data definition statements
if ($_REQUEST['logtype'] == 'schema' || $_REQUEST['logtype'] == 'schema_and_data') {
$entries = array_merge($entries, PMA_filter_tracking($data['ddlog'], $filter_ts_from, $filter_ts_to, $filter_users));
}
// Filtering data manipulation statements
if ($_REQUEST['logtype'] == 'data' || $_REQUEST['logtype'] == 'schema_and_data') {
$entries = array_merge($entries, PMA_filter_tracking($data['dmlog'], $filter_ts_from, $filter_ts_to, $filter_users));
}
// Sort it
foreach ($entries as $key => $row) {
$ids[$key] = $row['id'];
$timestamps[$key] = $row['timestamp'];
$usernames[$key] = $row['username'];
$statements[$key] = $row['statement'];
}
array_multisort($timestamps, SORT_ASC, $ids, SORT_ASC, $usernames, SORT_ASC, $statements, SORT_ASC, $entries);
}
// Export as file download
if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'sqldumpfile') {
@ini_set('url_rewriter.tags', '');
$dump = "# " . sprintf(__('Tracking report for table `%s`'), htmlspecialchars($_REQUEST['table'])) . "\n" .
"# " . date('Y-m-d H:i:s') . "\n";
foreach ($entries as $entry) {
$dump .= $entry['statement'];
}
$filename = 'log_' . htmlspecialchars($_REQUEST['table']) . '.sql';
PMA_download_header($filename, 'text/x-sql', strlen($dump));
echo $dump;
exit();
}
/**
* Gets tables informations
*/
/**
* Displays top menu links
*/
require_once './libraries/tbl_links.inc.php';
echo '<br />';
/**
* Actions
*/
// Create tracking version
if (isset($_REQUEST['submit_create_version'])) {
$tracking_set = '';
if ($_REQUEST['alter_table'] == true) {
$tracking_set .= 'ALTER TABLE,';
}
if ($_REQUEST['rename_table'] == true) {
$tracking_set .= 'RENAME TABLE,';
}
if ($_REQUEST['create_table'] == true) {
$tracking_set .= 'CREATE TABLE,';
}
if ($_REQUEST['drop_table'] == true) {
$tracking_set .= 'DROP TABLE,';
}
if ($_REQUEST['create_index'] == true) {
$tracking_set .= 'CREATE INDEX,';
}
if ($_REQUEST['drop_index'] == true) {
$tracking_set .= 'DROP INDEX,';
}
if ($_REQUEST['insert'] == true) {
$tracking_set .= 'INSERT,';
}
if ($_REQUEST['update'] == true) {
$tracking_set .= 'UPDATE,';
}
if ($_REQUEST['delete'] == true) {
$tracking_set .= 'DELETE,';
}
if ($_REQUEST['truncate'] == true) {
$tracking_set .= 'TRUNCATE,';
}
$tracking_set = rtrim($tracking_set, ',');
if (PMA_Tracker::createVersion($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'], $tracking_set )) {
$msg = PMA_Message::success(sprintf(__('Version %s is created, tracking for %s.%s is activated.'), htmlspecialchars($_REQUEST['version']), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])));
$msg->display();
}
}
// Deactivate tracking
if (isset($_REQUEST['submit_deactivate_now'])) {
if (PMA_Tracker::deactivateTracking($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'])) {
$msg = PMA_Message::success(sprintf(__('Tracking for %s.%s , version %s is deactivated.'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table']), htmlspecialchars($_REQUEST['version'])));
$msg->display();
}
}
// Activate tracking
if (isset($_REQUEST['submit_activate_now'])) {
if (PMA_Tracker::activateTracking($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'])) {
$msg = PMA_Message::success(sprintf(__('Tracking for %s.%s , version %s is activated.'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table']), htmlspecialchars($_REQUEST['version'])));
$msg->display();
}
}
// Export as SQL execution
if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'execution') {
foreach ($entries as $entry) {
$sql_result = PMA_DBI_query( "/*NOTRACK*/\n" . $entry['statement'] );
}
$msg = PMA_Message::success(__('SQL statements executed.'));
$msg->display();
}
// Export as SQL dump
if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'sqldump') {
$new_query = "# " . __('You can execute the dump by creating and using a temporary database. Please ensure that you have the privileges to do so.') . "\n" .
"# " . __('Comment out these two lines if you do not need them.') . "\n" .
"\n" .
"CREATE database IF NOT EXISTS pma_temp_db; \n" .
"USE pma_temp_db; \n" .
"\n";
foreach ($entries as $entry) {
$new_query .= $entry['statement'];
}
$msg = PMA_Message::success(__('SQL statements exported. Please copy the dump or execute it.'));
$msg->display();
$db_temp = $db;
$table_temp = $table;
$db = $table = '';
include_once './libraries/sql_query_form.lib.php';
PMA_sqlQueryForm($new_query, 'sql');
$db = $db_temp;
$table = $table_temp;
}
/*
* Schema snapshot
*/
if (isset($_REQUEST['snapshot'])) {
?>
<h3><?php echo __('Structure snapshot');?> [<a href="tbl_tracking.php?<?php echo $url_query;?>"><?php echo __('Close');?></a>]</h3>
<?php
$data = PMA_Tracker::getTrackedData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version']);
// Get first DROP TABLE and CREATE TABLE statements
$drop_create_statements = $data['ddlog'][0]['statement'];
if (strstr($data['ddlog'][0]['statement'], 'DROP TABLE')) {
$drop_create_statements .= $data['ddlog'][1]['statement'];
}
// Print SQL code
PMA_showMessage(sprintf(__('Version %s snapshot (SQL code)'), htmlspecialchars($_REQUEST['version'])), $drop_create_statements);
// Unserialize snapshot
$temp = unserialize($data['schema_snapshot']);
$columns = $temp['COLUMNS'];
$indexes = $temp['INDEXES'];
?>
<h3><?php echo __('Structure');?></h3>
<table id="tablestructure" class="data">
<thead>
<tr>
<th><?php echo __('Column'); ?></th>
<th><?php echo __('Type'); ?></th>
<th><?php echo __('Collation'); ?></th>
<th><?php echo __('Null'); ?></th>
<th><?php echo __('Default'); ?></th>
<th><?php echo __('Extra'); ?></th>
<th><?php echo __('Comment'); ?></th>
</tr>
</thead>
<tbody>
<?php
$style = 'odd';
foreach ($columns as $field_index => $field) {
?>
<tr class="noclick <?php echo $style; ?>">
<?php
if ($field['Key'] == 'PRI') {
echo '<td><b><u>' . htmlspecialchars($field['Field']) . '</u></b></td>' . "\n";
} else {
echo '<td><b>' . htmlspecialchars($field['Field']) . '</b></td>' . "\n";
}
?>
<td><?php echo htmlspecialchars($field['Type']);?></td>
<td><?php echo htmlspecialchars($field['Collation']);?></td>
<td><?php echo (($field['Null'] == 'YES') ? __('Yes') : __('No')); ?></td>
<td><?php
if (isset($field['Default'])) {
$extracted_fieldspec = PMA_extractFieldSpec($field['Type']);
if ($extracted_fieldspec['type'] == 'bit') {
// here, $field['Default'] contains something like b'010'
echo PMA_convert_bit_default_value($field['Default']);
} else {
echo htmlspecialchars($field['Default']);
}
} else {
if ($field['Null'] == 'YES') {
echo '<i>NULL</i>';
} else {
echo '<i>' . _pgettext('None for default', 'None') . '</i>';
}
} ?></td>
<td><?php echo htmlspecialchars($field['Extra']);?></td>
<td><?php echo htmlspecialchars($field['Comment']);?></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
}
?>
</tbody>
</table>
<?php
if (count($indexes) > 0) {
?>
<h3><?php echo __('Indexes');?></h3>
<table id="tablestructure_indexes" class="data">
<thead>
<tr>
<th><?php echo __('Keyname');?></th>
<th><?php echo __('Type');?></th>
<th><?php echo __('Unique');?></th>
<th><?php echo __('Packed');?></th>
<th><?php echo __('Column');?></th>
<th><?php echo __('Cardinality');?></th>
<th><?php echo __('Collation');?></th>
<th><?php echo __('Null');?></th>
<th><?php echo __('Comment');?></th>
</tr>
<tbody>
<?php
$style = 'odd';
foreach ($indexes as $indexes_index => $index) {
if ($index['Non_unique'] == 0) {
$str_unique = __('Yes');
} else {
$str_unique = __('No');
}
if ($index['Packed'] != '') {
$str_packed = __('Yes');
} else {
$str_packed = __('No');
}
?>
<tr class="noclick <?php echo $style; ?>">
<td><b><?php echo htmlspecialchars($index['Key_name']);?></b></td>
<td><?php echo htmlspecialchars($index['Index_type']);?></td>
<td><?php echo $str_unique;?></td>
<td><?php echo $str_packed;?></td>
<td><?php echo htmlspecialchars($index['Column_name']);?></td>
<td><?php echo htmlspecialchars($index['Cardinality']);?></td>
<td><?php echo htmlspecialchars($index['Collation']);?></td>
<td><?php echo htmlspecialchars($index['Null']);?></td>
<td><?php echo htmlspecialchars($index['Comment']);?></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
}
?>
</tbody>
</table>
<?php
} // endif
?>
<br /><hr /><br />
<?php
}
// end of snapshot report
/*
* Tracking report
*/
if (isset($_REQUEST['report']) && (isset($_REQUEST['delete_ddlog']) || isset($_REQUEST['delete_dmlog']))) {
if (isset($_REQUEST['delete_ddlog'])) {
// Delete ddlog row data
$delete_id = $_REQUEST['delete_ddlog'];
// Only in case of valable id
if ($delete_id == (int)$delete_id) {
unset($data['ddlog'][$delete_id]);
if (PMA_Tracker::changeTrackingData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version'], 'DDL', $data['ddlog']))
$msg = PMA_Message::success(__('Tracking data definition successfully deleted'));
else
$msg = PMA_Message::rawError(__('Query error'));
$msg->display();
}
}
if (isset($_REQUEST['delete_dmlog'])) {
// Delete dmlog row data
$delete_id = $_REQUEST['delete_dmlog'];
// Only in case of valable id
if ($delete_id == (int)$delete_id) {
unset($data['dmlog'][$delete_id]);
if (PMA_Tracker::changeTrackingData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version'], 'DML', $data['dmlog']))
$msg = PMA_Message::success(__('Tracking data manipulation successfully deleted'));
else
$msg = PMA_Message::rawError(__('Query error'));
$msg->display();
}
}
}
if (isset($_REQUEST['report']) || isset($_REQUEST['report_export'])) {
?>
<h3><?php echo __('Tracking report');?> [<a href="tbl_tracking.php?<?php echo $url_query;?>"><?php echo __('Close');?></a>]</h3>
<small><?php echo __('Tracking statements') . ' ' . htmlspecialchars($data['tracking']); ?></small><br/>
<br/>
<form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>">
<?php
$str1 = '<select name="logtype">' .
'<option value="schema"' . ($selection_schema ? ' selected="selected"' : '') . '>' . __('Structure only') . '</option>' .
'<option value="data"' . ($selection_data ? ' selected="selected"' : ''). '>' . __('Data only') . '</option>' .
'<option value="schema_and_data"' . ($selection_both ? ' selected="selected"' : '') . '>' . __('Structure and data') . '</option>' .
'</select>';
$str2 = '<input type="text" name="date_from" value="' . htmlspecialchars($_REQUEST['date_from']) . '" size="19" />';
$str3 = '<input type="text" name="date_to" value="' . htmlspecialchars($_REQUEST['date_to']) . '" size="19" />';
$str4 = '<input type="text" name="users" value="' . htmlspecialchars($_REQUEST['users']) . '" />';
$str5 = '<input type="submit" name="list_report" value="' . __('Go') . '" />';
printf(__('Show %s with dates from %s to %s by user %s %s'), $str1, $str2, $str3, $str4, $str5);
// Prepare delete link content here
$drop_image_or_text = '';
if (true == $GLOBALS['cfg']['PropertiesIconic']) {
$drop_image_or_text .= PMA_getImage('b_drop.png', __('Delete tracking data row from report'));
}
if ('both' === $GLOBALS['cfg']['PropertiesIconic'] || false === $GLOBALS['cfg']['PropertiesIconic']) {
$drop_image_or_text .= __('Delete');
}
/*
* First, list tracked data definition statements
*/
$i = 1;
if (count($data['ddlog']) == 0 && count($data['dmlog']) == 0) {
$msg = PMA_Message::notice(__('No data'));
$msg->display();
}
if ($selection_schema || $selection_both && count($data['ddlog']) > 0) {
?>
<table id="ddl_versions" class="data" width="100%">
<thead>
<tr>
<th width="18">#</th>
<th width="100"><?php echo __('Date');?></th>
<th width="60"><?php echo __('Username');?></th>
<th><?php echo __('Data definition statement');?></th>
<th><?php echo __('Delete');?></th>
</tr>
</thead>
<tbody>
<?php
$style = 'odd';
foreach ($data['ddlog'] as $entry) {
if (strlen($entry['statement']) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
$statement = substr($entry['statement'], 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
} else {
$statement = PMA_formatSql(PMA_SQP_parse($entry['statement']));
}
$timestamp = strtotime($entry['date']);
if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to &&
( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) {
?>
<tr class="noclick <?php echo $style; ?>">
<td><small><?php echo $i;?></small></td>
<td><small><?php echo htmlspecialchars($entry['date']);?></small></td>
<td><small><?php echo htmlspecialchars($entry['username']); ?></small></td>
<td><?php echo $statement; ?></td>
<td nowrap="nowrap"><a href="tbl_tracking.php?<?php echo $url_query;?>&report=true&version=<?php echo $version['version'];?>&delete_ddlog=<?php echo $i-1; ?>"><?php echo $drop_image_or_text; ?></a></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
$i++;
}
}
?>
</tbody>
</table>
<?php
} //endif
// Memorize data definition amount
$ddlog_count = $i;
/*
* Secondly, list tracked data manipulation statements
*/
if (($selection_data || $selection_both) && count($data['dmlog']) > 0) {
?>
<table id="dml_versions" class="data" width="100%">
<thead>
<tr>
<th width="18">#</th>
<th width="100"><?php echo __('Date');?></th>
<th width="60"><?php echo __('Username');?></th>
<th><?php echo __('Data manipulation statement');?></th>
<th><?php echo __('Delete');?></th>
</tr>
</thead>
<tbody>
<?php
$style = 'odd';
foreach ($data['dmlog'] as $entry) {
if (strlen($entry['statement']) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
$statement = substr($entry['statement'], 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
} else {
$statement = PMA_formatSql(PMA_SQP_parse($entry['statement']));
}
$timestamp = strtotime($entry['date']);
if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to &&
( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) {
?>
<tr class="noclick <?php echo $style; ?>">
<td><small><?php echo $i; ?></small></td>
<td><small><?php echo htmlspecialchars($entry['date']); ?></small></td>
<td><small><?php echo htmlspecialchars($entry['username']); ?></small></td>
<td><?php echo $statement; ?></td>
<td nowrap="nowrap"><a href="tbl_tracking.php?<?php echo $url_query;?>&report=true&version=<?php echo $version['version'];?>&delete_dmlog=<?php echo $i-$ddlog_count; ?>"><?php echo $drop_image_or_text; ?></a></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
$i++;
}
}
?>
</tbody>
</table>
<?php
}
?>
</form>
<form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>">
<?php
printf(__('Show %s with dates from %s to %s by user %s %s'), $str1, $str2, $str3, $str4, $str5);
$str_export1 = '<select name="export_type">' .
'<option value="sqldumpfile">' . __('SQL dump (file download)') . '</option>' .
'<option value="sqldump">' . __('SQL dump') . '</option>' .
'<option value="execution" onclick="alert(\'' . PMA_escapeJsString(__('This option will replace your table and contained data.')) .'\')">' . __('SQL execution') . '</option>' .
'</select>';
$str_export2 = '<input type="submit" name="report_export" value="' . __('Go') .'" />';
?>
</form>
<form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>">
<input type="hidden" name="logtype" value="<?php echo htmlspecialchars($_REQUEST['logtype']);?>" />
<input type="hidden" name="date_from" value="<?php echo htmlspecialchars($_REQUEST['date_from']);?>" />
<input type="hidden" name="date_to" value="<?php echo htmlspecialchars($_REQUEST['date_to']);?>" />
<input type="hidden" name="users" value="<?php echo htmlspecialchars($_REQUEST['users']);?>" />
<?php
echo "<br/>" . sprintf(__('Export as %s'), $str_export1) . $str_export2 . "<br/>";
?>
</form>
<?php
echo "<br/><br/><hr/><br/>\n";
} // end of report
/*
* List selectable tables
*/
$sql_query = " SELECT DISTINCT db_name, table_name FROM " .
PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "." .
PMA_backquote($GLOBALS['cfg']['Server']['tracking']) .
" WHERE db_name = '" . PMA_sqlAddSlashes($GLOBALS['db']) . "' " .
" ORDER BY db_name, table_name";
$sql_result = PMA_query_as_controluser($sql_query);
if (PMA_DBI_num_rows($sql_result) > 0) {
?>
<form method="post" action="tbl_tracking.php?<?php echo $url_query;?>">
<select name="table">
<?php
while ($entries = PMA_DBI_fetch_array($sql_result)) {
if (PMA_Tracker::isTracked($entries['db_name'], $entries['table_name'])) {
$status = ' (' . __('active') . ')';
} else {
$status = ' (' . __('not active') . ')';
}
if ($entries['table_name'] == $_REQUEST['table']) {
$s = ' selected="selected"';
} else {
$s = '';
}
echo '<option value="' . htmlspecialchars($entries['table_name']) . '"' . $s . '>' . htmlspecialchars($entries['db_name']) . ' . ' . htmlspecialchars($entries['table_name']) . $status . '</option>' . "\n";
}
?>
</select>
<input type="submit" name="show_versions_submit" value="<?php echo __('Show versions');?>" />
</form>
<?php
}
?>
<br />
<?php
/*
* List versions of current table
*/
$sql_query = " SELECT * FROM " .
PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "." .
PMA_backquote($GLOBALS['cfg']['Server']['tracking']) .
" WHERE db_name = '" . PMA_sqlAddSlashes($_REQUEST['db']) . "' ".
" AND table_name = '" . PMA_sqlAddSlashes($_REQUEST['table']) ."' ".
" ORDER BY version DESC ";
$sql_result = PMA_query_as_controluser($sql_query);
$last_version = 0;
$maxversion = PMA_DBI_fetch_array($sql_result);
$last_version = $maxversion['version'];
if ($last_version > 0) {
?>
<table id="versions" class="data">
<thead>
<tr>
<th><?php echo __('Database');?></th>
<th><?php echo __('Table');?></th>
<th><?php echo __('Version');?></th>
<th><?php echo __('Created');?></th>
<th><?php echo __('Updated');?></th>
<th><?php echo __('Status');?></th>
<th><?php echo __('Show');?></th>
</tr>
</thead>
<tbody>
<?php
$style = 'odd';
PMA_DBI_data_seek($sql_result, 0);
while ($version = PMA_DBI_fetch_array($sql_result)) {
if ($version['tracking_active'] == 1) {
$version_status = __('active');
} else {
$version_status = __('not active');
}
if ($version['version'] == $last_version) {
if ($version['tracking_active'] == 1) {
$tracking_active = true;
} else {
$tracking_active = false;
}
}
?>
<tr class="noclick <?php echo $style;?>">
<td><?php echo htmlspecialchars($version['db_name']);?></td>
<td><?php echo htmlspecialchars($version['table_name']);?></td>
<td><?php echo htmlspecialchars($version['version']);?></td>
<td><?php echo htmlspecialchars($version['date_created']);?></td>
<td><?php echo htmlspecialchars($version['date_updated']);?></td>
<td><?php echo $version_status;?></td>
<td> <a href="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $version['version'])
);?>"><?php echo __('Tracking report');?></a>
| <a href="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('snapshot' => 'true', 'version' => $version['version'])
);?>"><?php echo __('Structure snapshot');?></a>
</td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
}
?>
</tbody>
</table>
<?php if ($tracking_active == true) {?>
<div id="div_deactivate_tracking">
<form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>">
<fieldset>
<legend><?php printf(__('Deactivate tracking for %s.%s'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend>
<input type="hidden" name="version" value="<?php echo $last_version; ?>" />
<input type="submit" name="submit_deactivate_now" value="<?php echo __('Deactivate now'); ?>" />
</fieldset>
</form>
</div>
<?php
}
?>
<?php if ($tracking_active == false) {?>
<div id="div_activate_tracking">
<form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>">
<fieldset>
<legend><?php printf(__('Activate tracking for %s.%s'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend>
<input type="hidden" name="version" value="<?php echo $last_version; ?>" />
<input type="submit" name="submit_activate_now" value="<?php echo __('Activate now'); ?>" />
</fieldset>
</form>
</div>
<?php
}
}
?>
<div id="div_create_version">
<form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>">
<?php echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']); ?>
<fieldset>
<legend><?php printf(__('Create version %s of %s.%s'), ($last_version + 1), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend>
<input type="hidden" name="version" value="<?php echo ($last_version + 1); ?>" />
<p><?php echo __('Track these data definition statements:');?></p>
<input type="checkbox" name="alter_table" value="true" checked="checked" /> ALTER TABLE<br/>
<input type="checkbox" name="rename_table" value="true" checked="checked" /> RENAME TABLE<br/>
<input type="checkbox" name="create_table" value="true" checked="checked" /> CREATE TABLE<br/>
<input type="checkbox" name="drop_table" value="true" checked="checked" /> DROP TABLE<br/>
<br/>
<input type="checkbox" name="create_index" value="true" checked="checked" /> CREATE INDEX<br/>
<input type="checkbox" name="drop_index" value="true" checked="checked" /> DROP INDEX<br/>
<p><?php echo __('Track these data manipulation statements:');?></p>
<input type="checkbox" name="insert" value="true" checked="checked" /> INSERT<br/>
<input type="checkbox" name="update" value="true" checked="checked" /> UPDATE<br/>
<input type="checkbox" name="delete" value="true" checked="checked" /> DELETE<br/>
<input type="checkbox" name="truncate" value="true" checked="checked" /> TRUNCATE<br/>
</fieldset>
<fieldset class="tblFooters">
<input type="submit" name="submit_create_version" value="<?php echo __('Create version'); ?>" />
</fieldset>
</form>
</div>
<br class="clearfloat"/>
<?php
/**
* Displays the footer
*/
require './libraries/footer.inc.php';
?>
| teiath/lms | web/dbadmin/tbl_tracking.php | PHP | mit | 29,065 |
package terraform
//go:generate stringer -type=walkOperation graph_walk_operation.go
// walkOperation is an enum which tells the walkContext what to do.
type walkOperation byte
const (
walkInvalid walkOperation = iota
walkInput
walkApply
walkPlan
walkPlanDestroy
walkRefresh
walkValidate
walkDestroy
)
| kzittritsch/terraform-provider-bigip | vendor/github.com/hashicorp/terraform/terraform/graph_walk_operation.go | GO | mpl-2.0 | 313 |
(function (env) {
"use strict";
env.ddg_spice_bacon_ipsum = function(api_result){
if (!api_result || api_result.error) {
return Spice.failed('bacon_ipsum');
}
var pageContent = '';
for (var i in api_result) {
pageContent += "<p>" + api_result[i] + "</p>";
}
Spice.add({
id: 'bacon_ipsum',
name: 'Bacon Ipsum',
data: {
content: pageContent,
title: "Bacon Ipsum",
subtitle: "Randomly generated text"
},
meta: {
sourceName: 'Bacon Ipsum',
sourceUrl: 'http://baconipsum.com/'
},
templates: {
group: 'text',
options: {
content: Spice.bacon_ipsum.content
}
}
});
};
}(this));
| hshackathons/zeroclickinfo-spice | share/spice/bacon_ipsum/bacon_ipsum.js | JavaScript | apache-2.0 | 910 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class implements a set of methods for retrieving
// sort key information.
//
//
////////////////////////////////////////////////////////////////////////////
namespace System.Globalization {
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public class SortKey
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
[OptionalField(VersionAdded = 3)]
internal String localeName; // locale identifier
[OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it
internal int win32LCID;
// Whidbey serialization
internal CompareOptions options; // options
internal String m_String; // original string
internal byte[] m_KeyData; // sortkey data
//
// The following constructor is designed to be called from CompareInfo to get the
// the sort key of specific string for synthetic culture
//
internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData)
{
this.m_KeyData = keyData;
this.localeName = localeName;
this.options = options;
this.m_String = str;
}
#if FEATURE_USE_LCID
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
//set LCID to proper value for Whidbey serialization (no other use)
if (win32LCID == 0)
{
win32LCID = CultureInfo.GetCultureInfo(localeName).LCID;
}
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
//set locale name to proper value after Whidbey deserialization
if (String.IsNullOrEmpty(localeName) && win32LCID != 0)
{
localeName = CultureInfo.GetCultureInfo(win32LCID).Name;
}
}
#endif //FEATURE_USE_LCID
////////////////////////////////////////////////////////////////////////
//
// GetOriginalString
//
// Returns the original string used to create the current instance
// of SortKey.
//
////////////////////////////////////////////////////////////////////////
public virtual String OriginalString
{
get {
return (m_String);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetKeyData
//
// Returns a byte array representing the current instance of the
// sort key.
//
////////////////////////////////////////////////////////////////////////
public virtual byte[] KeyData
{
get {
return (byte[])(m_KeyData.Clone());
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two sort keys. Returns 0 if the two sort keys are
// equal, a number less than 0 if sortkey1 is less than sortkey2,
// and a number greater than 0 if sortkey1 is greater than sortkey2.
//
////////////////////////////////////////////////////////////////////////
public static int Compare(SortKey sortkey1, SortKey sortkey2) {
if (sortkey1==null || sortkey2==null) {
throw new ArgumentNullException((sortkey1==null ? "sortkey1": "sortkey2"));
}
Contract.EndContractBlock();
byte[] key1Data = sortkey1.m_KeyData;
byte[] key2Data = sortkey2.m_KeyData;
Contract.Assert(key1Data!=null, "key1Data!=null");
Contract.Assert(key2Data!=null, "key2Data!=null");
if (key1Data.Length == 0) {
if (key2Data.Length == 0) {
return (0);
}
return (-1);
}
if (key2Data.Length == 0) {
return (1);
}
int compLen = (key1Data.Length<key2Data.Length)?key1Data.Length:key2Data.Length;
for (int i=0; i<compLen; i++) {
if (key1Data[i]>key2Data[i]) {
return (1);
}
if (key1Data[i]<key2Data[i]) {
return (-1);
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same SortKey as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
SortKey that = value as SortKey;
if (that != null)
{
return Compare(this, that) == 0;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// SortKey. The hash code is guaranteed to be the same for
// SortKey A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (CompareInfo.GetCompareInfo(
this.localeName).GetHashCodeOfString(this.m_String, this.options));
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// SortKey.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("SortKey - " + localeName + ", " + options + ", " + m_String);
}
}
}
| Priya91/coreclr | src/mscorlib/src/System/Globalization/SortKey.cs | C# | mit | 6,975 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
//using System.Globalization;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
[Serializable]
[TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")]
public abstract class Comparer<T> : IComparer, IComparer<T>
{
static volatile Comparer<T> defaultComparer;
public static Comparer<T> Default {
get {
Contract.Ensures(Contract.Result<Comparer<T>>() != null);
Comparer<T> comparer = defaultComparer;
if (comparer == null) {
comparer = CreateComparer();
defaultComparer = comparer;
}
return comparer;
}
}
public static Comparer<T> Create(Comparison<T> comparison)
{
Contract.Ensures(Contract.Result<Comparer<T>>() != null);
if (comparison == null)
throw new ArgumentNullException("comparison");
return new ComparisonComparer<T>(comparison);
}
//
// Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
// saves the right instantiations
//
[System.Security.SecuritySafeCritical] // auto-generated
private static Comparer<T> CreateComparer() {
RuntimeType t = (RuntimeType)typeof(T);
// If T implements IComparable<T> return a GenericComparer<T>
#if FEATURE_LEGACYNETCF
// Pre-Apollo Windows Phone call the overload that sorts the keys, not values this achieves the same result
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
if (t.ImplementInterface(typeof(IComparable<T>))) {
return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t);
}
}
else
#endif
if (typeof(IComparable<T>).IsAssignableFrom(t)) {
return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t);
}
// If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U>
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) {
RuntimeType u = (RuntimeType)t.GetGenericArguments()[0];
if (typeof(IComparable<>).MakeGenericType(u).IsAssignableFrom(u)) {
return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableComparer<int>), u);
}
}
// Otherwise return an ObjectComparer<T>
return new ObjectComparer<T>();
}
public abstract int Compare(T x, T y);
int IComparer.Compare(object x, object y) {
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
if (x is T && y is T) return Compare((T)x, (T)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return 0;
}
}
[Serializable]
internal class GenericComparer<T> : Comparer<T> where T: IComparable<T>
{
public override int Compare(T x, T y) {
if (x != null) {
if (y != null) return x.CompareTo(y);
return 1;
}
if (y != null) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
GenericComparer<T> comparer = obj as GenericComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class NullableComparer<T> : Comparer<Nullable<T>> where T : struct, IComparable<T>
{
public override int Compare(Nullable<T> x, Nullable<T> y) {
if (x.HasValue) {
if (y.HasValue) return x.value.CompareTo(y.value);
return 1;
}
if (y.HasValue) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
NullableComparer<T> comparer = obj as NullableComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class ObjectComparer<T> : Comparer<T>
{
public override int Compare(T x, T y) {
return System.Collections.Comparer.Default.Compare(x, y);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
ObjectComparer<T> comparer = obj as ObjectComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class ComparisonComparer<T> : Comparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison) {
_comparison = comparison;
}
public override int Compare(T x, T y) {
return _comparison(x, y);
}
}
}
| Priya91/coreclr | src/mscorlib/src/System/Collections/Generic/Comparer.cs | C# | mit | 5,796 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public static class DiagnosticFixerTestsExtensions
{
internal static Document Apply(this Document document, CodeAction action)
{
var operations = action.GetOperationsAsync(CancellationToken.None).Result;
var solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution;
return solution.GetDocument(document.Id);
}
}
}
| mavasani/roslyn-analyzers | tools/AnalyzerCodeGenerator/template/src/Test/Utilities/CodeFixTests.Extensions.cs | C# | apache-2.0 | 826 |
package consul
import (
"fmt"
"strings"
"time"
"github.com/xordataexchange/crypt/backend"
"github.com/armon/consul-api"
)
type Client struct {
client *consulapi.KV
waitIndex uint64
}
func New(machines []string) (*Client, error) {
conf := consulapi.DefaultConfig()
if len(machines) > 0 {
conf.Address = machines[0]
}
client, err := consulapi.NewClient(conf)
if err != nil {
return nil, err
}
return &Client{client.KV(), 0}, nil
}
func (c *Client) Get(key string) ([]byte, error) {
kv, _, err := c.client.Get(key, nil)
if err != nil {
return nil, err
}
if kv == nil {
return nil, fmt.Errorf("Key ( %s ) was not found.", key)
}
return kv.Value, nil
}
func (c *Client) List(key string) (backend.KVPairs, error) {
pairs, _, err := c.client.List(key, nil)
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
ret := make(backend.KVPairs, len(pairs), len(pairs))
for i, kv := range pairs {
ret[i] = &backend.KVPair{Key: kv.Key, Value: kv.Value}
}
return ret, nil
}
func (c *Client) Set(key string, value []byte) error {
key = strings.TrimPrefix(key, "/")
kv := &consulapi.KVPair{
Key: key,
Value: value,
}
_, err := c.client.Put(kv, nil)
return err
}
func (c *Client) Watch(key string, stop chan bool) <-chan *backend.Response {
respChan := make(chan *backend.Response, 0)
go func() {
for {
opts := consulapi.QueryOptions{
WaitIndex: c.waitIndex,
}
keypair, meta, err := c.client.Get(key, &opts)
if keypair == nil && err == nil {
err = fmt.Errorf("Key ( %s ) was not found.", key)
}
if err != nil {
respChan <- &backend.Response{nil, err}
time.Sleep(time.Second * 5)
continue
}
c.waitIndex = meta.LastIndex
respChan <- &backend.Response{keypair.Value, nil}
}
}()
return respChan
}
| tcotav/etcdhooks | vendor/src/github.com/xordataexchange/crypt/backend/consul/consul.go | GO | mit | 1,810 |
require('../lib/node_loader');
var AWS = require('../lib/core');
var Service = require('../lib/service');
var apiLoader = require('../lib/api_loader');
apiLoader.services['cloudsearchdomain'] = {};
AWS.CloudSearchDomain = Service.defineService('cloudsearchdomain', ['2013-01-01']);
require('../lib/services/cloudsearchdomain');
Object.defineProperty(apiLoader.services['cloudsearchdomain'], '2013-01-01', {
get: function get() {
var model = require('../apis/cloudsearchdomain-2013-01-01.min.json');
return model;
},
enumerable: true,
configurable: true
});
module.exports = AWS.CloudSearchDomain;
| edeati/alexa-translink-skill-js | test/node_modules/aws-sdk/clients/cloudsearchdomain.js | JavaScript | apache-2.0 | 615 |
#!/usr/bin/env python
"""
exec_command
Implements exec_command function that is (almost) equivalent to
commands.getstatusoutput function but on NT, DOS systems the
returned status is actually correct (though, the returned status
values may be different by a factor). In addition, exec_command
takes keyword arguments for (re-)defining environment variables.
Provides functions:
exec_command --- execute command in a specified directory and
in the modified environment.
find_executable --- locate a command using info from environment
variable PATH. Equivalent to posix `which`
command.
Author: Pearu Peterson <pearu@cens.ioc.ee>
Created: 11 January 2003
Requires: Python 2.x
Succesfully tested on:
======== ============ =================================================
os.name sys.platform comments
======== ============ =================================================
posix linux2 Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3
PyCrust 0.9.3, Idle 1.0.2
posix linux2 Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2
posix sunos5 SunOS 5.9, Python 2.2, 2.3.2
posix darwin Darwin 7.2.0, Python 2.3
nt win32 Windows Me
Python 2.3(EE), Idle 1.0, PyCrust 0.7.2
Python 2.1.1 Idle 0.8
nt win32 Windows 98, Python 2.1.1. Idle 0.8
nt win32 Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests
fail i.e. redefining environment variables may
not work. FIXED: don't use cygwin echo!
Comment: also `cmd /c echo` will not work
but redefining environment variables do work.
posix cygwin Cygwin 98-4.10, Python 2.3.3(cygming special)
nt win32 Windows XP, Python 2.3.3
======== ============ =================================================
Known bugs:
* Tests, that send messages to stderr, fail when executed from MSYS prompt
because the messages are lost at some point.
"""
from __future__ import division, absolute_import, print_function
__all__ = ['exec_command', 'find_executable']
import os
import sys
import shlex
from numpy.distutils.misc_util import is_sequence, make_temp_file
from numpy.distutils import log
from numpy.distutils.compat import get_exception
from numpy.compat import open_latin1
def temp_file_name():
fo, name = make_temp_file()
fo.close()
return name
def get_pythonexe():
pythonexe = sys.executable
if os.name in ['nt', 'dos']:
fdir, fn = os.path.split(pythonexe)
fn = fn.upper().replace('PYTHONW', 'PYTHON')
pythonexe = os.path.join(fdir, fn)
assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,)
return pythonexe
def find_executable(exe, path=None, _cache={}):
"""Return full path of a executable or None.
Symbolic links are not followed.
"""
key = exe, path
try:
return _cache[key]
except KeyError:
pass
log.debug('find_executable(%r)' % exe)
orig_exe = exe
if path is None:
path = os.environ.get('PATH', os.defpath)
if os.name=='posix':
realpath = os.path.realpath
else:
realpath = lambda a:a
if exe.startswith('"'):
exe = exe[1:-1]
suffixes = ['']
if os.name in ['nt', 'dos', 'os2']:
fn, ext = os.path.splitext(exe)
extra_suffixes = ['.exe', '.com', '.bat']
if ext.lower() not in extra_suffixes:
suffixes = extra_suffixes
if os.path.isabs(exe):
paths = ['']
else:
paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]
for path in paths:
fn = os.path.join(path, exe)
for s in suffixes:
f_ext = fn+s
if not os.path.islink(f_ext):
f_ext = realpath(f_ext)
if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):
log.info('Found executable %s' % f_ext)
_cache[key] = f_ext
return f_ext
log.warn('Could not locate executable %s' % orig_exe)
return None
############################################################
def _preserve_environment( names ):
log.debug('_preserve_environment(%r)' % (names))
env = {}
for name in names:
env[name] = os.environ.get(name)
return env
def _update_environment( **env ):
log.debug('_update_environment(...)')
for name, value in env.items():
os.environ[name] = value or ''
def _supports_fileno(stream):
"""
Returns True if 'stream' supports the file descriptor and allows fileno().
"""
if hasattr(stream, 'fileno'):
try:
r = stream.fileno()
return True
except IOError:
return False
else:
return False
def exec_command(command, execute_in='', use_shell=None, use_tee=None,
_with_python = 1, **env ):
"""
Return (status,output) of executed command.
Parameters
----------
command : str
A concatenated string of executable and arguments.
execute_in : str
Before running command ``cd execute_in`` and after ``cd -``.
use_shell : {bool, None}, optional
If True, execute ``sh -c command``. Default None (True)
use_tee : {bool, None}, optional
If True use tee. Default None (True)
Returns
-------
res : str
Both stdout and stderr messages.
Notes
-----
On NT, DOS systems the returned status is correct for external commands.
Wild cards will not work for non-posix systems or when use_shell=0.
"""
log.debug('exec_command(%r,%s)' % (command,\
','.join(['%s=%r'%kv for kv in env.items()])))
if use_tee is None:
use_tee = os.name=='posix'
if use_shell is None:
use_shell = os.name=='posix'
execute_in = os.path.abspath(execute_in)
oldcwd = os.path.abspath(os.getcwd())
if __name__[-12:] == 'exec_command':
exec_dir = os.path.dirname(os.path.abspath(__file__))
elif os.path.isfile('exec_command.py'):
exec_dir = os.path.abspath('.')
else:
exec_dir = os.path.abspath(sys.argv[0])
if os.path.isfile(exec_dir):
exec_dir = os.path.dirname(exec_dir)
if oldcwd!=execute_in:
os.chdir(execute_in)
log.debug('New cwd: %s' % execute_in)
else:
log.debug('Retaining cwd: %s' % oldcwd)
oldenv = _preserve_environment( list(env.keys()) )
_update_environment( **env )
try:
# _exec_command is robust but slow, it relies on
# usable sys.std*.fileno() descriptors. If they
# are bad (like in win32 Idle, PyCrust environments)
# then _exec_command_python (even slower)
# will be used as a last resort.
#
# _exec_command_posix uses os.system and is faster
# but not on all platforms os.system will return
# a correct status.
if (_with_python and _supports_fileno(sys.stdout) and
sys.stdout.fileno() == -1):
st = _exec_command_python(command,
exec_command_dir = exec_dir,
**env)
elif os.name=='posix':
st = _exec_command_posix(command,
use_shell=use_shell,
use_tee=use_tee,
**env)
else:
st = _exec_command(command, use_shell=use_shell,
use_tee=use_tee,**env)
finally:
if oldcwd!=execute_in:
os.chdir(oldcwd)
log.debug('Restored cwd to %s' % oldcwd)
_update_environment(**oldenv)
return st
def _exec_command_posix( command,
use_shell = None,
use_tee = None,
**env ):
log.debug('_exec_command_posix(...)')
if is_sequence(command):
command_str = ' '.join(list(command))
else:
command_str = command
tmpfile = temp_file_name()
stsfile = None
if use_tee:
stsfile = temp_file_name()
filter = ''
if use_tee == 2:
filter = r'| tr -cd "\n" | tr "\n" "."; echo'
command_posix = '( %s ; echo $? > %s ) 2>&1 | tee %s %s'\
% (command_str, stsfile, tmpfile, filter)
else:
stsfile = temp_file_name()
command_posix = '( %s ; echo $? > %s ) > %s 2>&1'\
% (command_str, stsfile, tmpfile)
#command_posix = '( %s ) > %s 2>&1' % (command_str,tmpfile)
log.debug('Running os.system(%r)' % (command_posix))
status = os.system(command_posix)
if use_tee:
if status:
# if command_tee fails then fall back to robust exec_command
log.warn('_exec_command_posix failed (status=%s)' % status)
return _exec_command(command, use_shell=use_shell, **env)
if stsfile is not None:
f = open_latin1(stsfile, 'r')
status_text = f.read()
status = int(status_text)
f.close()
os.remove(stsfile)
f = open_latin1(tmpfile, 'r')
text = f.read()
f.close()
os.remove(tmpfile)
if text[-1:]=='\n':
text = text[:-1]
return status, text
def _exec_command_python(command,
exec_command_dir='', **env):
log.debug('_exec_command_python(...)')
python_exe = get_pythonexe()
cmdfile = temp_file_name()
stsfile = temp_file_name()
outfile = temp_file_name()
f = open(cmdfile, 'w')
f.write('import os\n')
f.write('import sys\n')
f.write('sys.path.insert(0,%r)\n' % (exec_command_dir))
f.write('from exec_command import exec_command\n')
f.write('del sys.path[0]\n')
f.write('cmd = %r\n' % command)
f.write('os.environ = %r\n' % (os.environ))
f.write('s,o = exec_command(cmd, _with_python=0, **%r)\n' % (env))
f.write('f=open(%r,"w")\nf.write(str(s))\nf.close()\n' % (stsfile))
f.write('f=open(%r,"w")\nf.write(o)\nf.close()\n' % (outfile))
f.close()
cmd = '%s %s' % (python_exe, cmdfile)
status = os.system(cmd)
if status:
raise RuntimeError("%r failed" % (cmd,))
os.remove(cmdfile)
f = open_latin1(stsfile, 'r')
status = int(f.read())
f.close()
os.remove(stsfile)
f = open_latin1(outfile, 'r')
text = f.read()
f.close()
os.remove(outfile)
return status, text
def quote_arg(arg):
if arg[0]!='"' and ' ' in arg:
return '"%s"' % arg
return arg
def _exec_command( command, use_shell=None, use_tee = None, **env ):
log.debug('_exec_command(...)')
if use_shell is None:
use_shell = os.name=='posix'
if use_tee is None:
use_tee = os.name=='posix'
using_command = 0
if use_shell:
# We use shell (unless use_shell==0) so that wildcards can be
# used.
sh = os.environ.get('SHELL', '/bin/sh')
if is_sequence(command):
argv = [sh, '-c', ' '.join(list(command))]
else:
argv = [sh, '-c', command]
else:
# On NT, DOS we avoid using command.com as it's exit status is
# not related to the exit status of a command.
if is_sequence(command):
argv = command[:]
else:
argv = shlex.split(command)
if hasattr(os, 'spawnvpe'):
spawn_command = os.spawnvpe
else:
spawn_command = os.spawnve
argv[0] = find_executable(argv[0]) or argv[0]
if not os.path.isfile(argv[0]):
log.warn('Executable %s does not exist' % (argv[0]))
if os.name in ['nt', 'dos']:
# argv[0] might be internal command
argv = [os.environ['COMSPEC'], '/C'] + argv
using_command = 1
_so_has_fileno = _supports_fileno(sys.stdout)
_se_has_fileno = _supports_fileno(sys.stderr)
so_flush = sys.stdout.flush
se_flush = sys.stderr.flush
if _so_has_fileno:
so_fileno = sys.stdout.fileno()
so_dup = os.dup(so_fileno)
if _se_has_fileno:
se_fileno = sys.stderr.fileno()
se_dup = os.dup(se_fileno)
outfile = temp_file_name()
fout = open(outfile, 'w')
if using_command:
errfile = temp_file_name()
ferr = open(errfile, 'w')
log.debug('Running %s(%s,%r,%r,os.environ)' \
% (spawn_command.__name__, os.P_WAIT, argv[0], argv))
if sys.version_info[0] >= 3 and os.name == 'nt':
# Pre-encode os.environ, discarding un-encodable entries,
# to avoid it failing during encoding as part of spawn. Failure
# is possible if the environment contains entries that are not
# encoded using the system codepage as windows expects.
#
# This is not necessary on unix, where os.environ is encoded
# using the surrogateescape error handler and decoded using
# it as part of spawn.
encoded_environ = {}
for k, v in os.environ.items():
try:
encoded_environ[k.encode(sys.getfilesystemencoding())] = v.encode(
sys.getfilesystemencoding())
except UnicodeEncodeError:
log.debug("ignoring un-encodable env entry %s", k)
else:
encoded_environ = os.environ
argv0 = argv[0]
if not using_command:
argv[0] = quote_arg(argv0)
so_flush()
se_flush()
if _so_has_fileno:
os.dup2(fout.fileno(), so_fileno)
if _se_has_fileno:
if using_command:
#XXX: disabled for now as it does not work from cmd under win32.
# Tests fail on msys
os.dup2(ferr.fileno(), se_fileno)
else:
os.dup2(fout.fileno(), se_fileno)
try:
status = spawn_command(os.P_WAIT, argv0, argv, encoded_environ)
except Exception:
errmess = str(get_exception())
status = 999
sys.stderr.write('%s: %s'%(errmess, argv[0]))
so_flush()
se_flush()
if _so_has_fileno:
os.dup2(so_dup, so_fileno)
os.close(so_dup)
if _se_has_fileno:
os.dup2(se_dup, se_fileno)
os.close(se_dup)
fout.close()
fout = open_latin1(outfile, 'r')
text = fout.read()
fout.close()
os.remove(outfile)
if using_command:
ferr.close()
ferr = open_latin1(errfile, 'r')
errmess = ferr.read()
ferr.close()
os.remove(errfile)
if errmess and not status:
# Not sure how to handle the case where errmess
# contains only warning messages and that should
# not be treated as errors.
#status = 998
if text:
text = text + '\n'
#text = '%sCOMMAND %r FAILED: %s' %(text,command,errmess)
text = text + errmess
print (errmess)
if text[-1:]=='\n':
text = text[:-1]
if status is None:
status = 0
if use_tee:
print (text)
return status, text
def test_nt(**kws):
pythonexe = get_pythonexe()
echo = find_executable('echo')
using_cygwin_echo = echo != 'echo'
if using_cygwin_echo:
log.warn('Using cygwin echo in win32 environment is not supported')
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'AAA\',\'\')"')
assert s==0 and o=='', (s, o)
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'AAA\')"',
AAA='Tere')
assert s==0 and o=='Tere', (s, o)
os.environ['BBB'] = 'Hi'
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'BBB\',\'\')"')
assert s==0 and o=='Hi', (s, o)
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'BBB\',\'\')"',
BBB='Hey')
assert s==0 and o=='Hey', (s, o)
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'BBB\',\'\')"')
assert s==0 and o=='Hi', (s, o)
elif 0:
s, o=exec_command('echo Hello')
assert s==0 and o=='Hello', (s, o)
s, o=exec_command('echo a%AAA%')
assert s==0 and o=='a', (s, o)
s, o=exec_command('echo a%AAA%', AAA='Tere')
assert s==0 and o=='aTere', (s, o)
os.environ['BBB'] = 'Hi'
s, o=exec_command('echo a%BBB%')
assert s==0 and o=='aHi', (s, o)
s, o=exec_command('echo a%BBB%', BBB='Hey')
assert s==0 and o=='aHey', (s, o)
s, o=exec_command('echo a%BBB%')
assert s==0 and o=='aHi', (s, o)
s, o=exec_command('this_is_not_a_command')
assert s and o!='', (s, o)
s, o=exec_command('type not_existing_file')
assert s and o!='', (s, o)
s, o=exec_command('echo path=%path%')
assert s==0 and o!='', (s, o)
s, o=exec_command('%s -c "import sys;sys.stderr.write(sys.platform)"' \
% pythonexe)
assert s==0 and o=='win32', (s, o)
s, o=exec_command('%s -c "raise \'Ignore me.\'"' % pythonexe)
assert s==1 and o, (s, o)
s, o=exec_command('%s -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"'\
% pythonexe)
assert s==0 and o=='012', (s, o)
s, o=exec_command('%s -c "import sys;sys.exit(15)"' % pythonexe)
assert s==15 and o=='', (s, o)
s, o=exec_command('%s -c "print \'Heipa\'"' % pythonexe)
assert s==0 and o=='Heipa', (s, o)
print ('ok')
def test_posix(**kws):
s, o=exec_command("echo Hello",**kws)
assert s==0 and o=='Hello', (s, o)
s, o=exec_command('echo $AAA',**kws)
assert s==0 and o=='', (s, o)
s, o=exec_command('echo "$AAA"',AAA='Tere',**kws)
assert s==0 and o=='Tere', (s, o)
s, o=exec_command('echo "$AAA"',**kws)
assert s==0 and o=='', (s, o)
os.environ['BBB'] = 'Hi'
s, o=exec_command('echo "$BBB"',**kws)
assert s==0 and o=='Hi', (s, o)
s, o=exec_command('echo "$BBB"',BBB='Hey',**kws)
assert s==0 and o=='Hey', (s, o)
s, o=exec_command('echo "$BBB"',**kws)
assert s==0 and o=='Hi', (s, o)
s, o=exec_command('this_is_not_a_command',**kws)
assert s!=0 and o!='', (s, o)
s, o=exec_command('echo path=$PATH',**kws)
assert s==0 and o!='', (s, o)
s, o=exec_command('python -c "import sys,os;sys.stderr.write(os.name)"',**kws)
assert s==0 and o=='posix', (s, o)
s, o=exec_command('python -c "raise \'Ignore me.\'"',**kws)
assert s==1 and o, (s, o)
s, o=exec_command('python -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"',**kws)
assert s==0 and o=='012', (s, o)
s, o=exec_command('python -c "import sys;sys.exit(15)"',**kws)
assert s==15 and o=='', (s, o)
s, o=exec_command('python -c "print \'Heipa\'"',**kws)
assert s==0 and o=='Heipa', (s, o)
print ('ok')
def test_execute_in(**kws):
pythonexe = get_pythonexe()
tmpfile = temp_file_name()
fn = os.path.basename(tmpfile)
tmpdir = os.path.dirname(tmpfile)
f = open(tmpfile, 'w')
f.write('Hello')
f.close()
s, o = exec_command('%s -c "print \'Ignore the following IOError:\','\
'open(%r,\'r\')"' % (pythonexe, fn),**kws)
assert s and o!='', (s, o)
s, o = exec_command('%s -c "print open(%r,\'r\').read()"' % (pythonexe, fn),
execute_in = tmpdir,**kws)
assert s==0 and o=='Hello', (s, o)
os.remove(tmpfile)
print ('ok')
def test_svn(**kws):
s, o = exec_command(['svn', 'status'],**kws)
assert s, (s, o)
print ('svn ok')
def test_cl(**kws):
if os.name=='nt':
s, o = exec_command(['cl', '/V'],**kws)
assert s, (s, o)
print ('cl ok')
if os.name=='posix':
test = test_posix
elif os.name in ['nt', 'dos']:
test = test_nt
else:
raise NotImplementedError('exec_command tests for ', os.name)
############################################################
if __name__ == "__main__":
test(use_tee=0)
test(use_tee=1)
test_execute_in(use_tee=0)
test_execute_in(use_tee=1)
test_svn(use_tee=1)
test_cl(use_tee=1)
| LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/distutils/exec_command.py | Python | bsd-2-clause | 20,462 |
<?php
namespace Drupal\file\Plugin\Field\FieldFormatter;
/**
* Defines getter methods for FileMediaFormatterBase.
*
* This interface is used on the FileMediaFormatterBase class to ensure that
* each file media formatter will be based on a media type.
*
* Abstract classes are not able to implement abstract static methods,
* this interface will work around that.
*
* @see \Drupal\file\Plugin\Field\FieldFormatter\FileMediaFormatterBase
*/
interface FileMediaFormatterInterface {
/**
* Gets the applicable media type for a formatter.
*
* @return string
* The media type of this formatter.
*/
public static function getMediaType();
}
| tobiasbuhrer/tobiasb | web/core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterInterface.php | PHP | gpl-2.0 | 667 |
#include <gtest/gtest.h>
#include "codec_def.h"
#include "codec_api.h"
#include "utils/BufferedData.h"
#include "utils/FileInputStream.h"
#include "BaseEncoderTest.h"
class EncInterfaceCallTest : public ::testing::Test, public BaseEncoderTest {
public:
virtual void SetUp() {
BaseEncoderTest::SetUp();
};
virtual void TearDown() {
BaseEncoderTest::TearDown();
};
virtual void onEncodeFrame (const SFrameBSInfo& frameInfo) {
//nothing
}
//testing case
};
TEST_F (EncInterfaceCallTest, BaseParameterVerify) {
int uiTraceLevel = WELS_LOG_QUIET;
encoder_->SetOption (ENCODER_OPTION_TRACE_LEVEL, &uiTraceLevel);
int ret = cmResultSuccess;
SEncParamBase baseparam;
memset (&baseparam, 0, sizeof (SEncParamBase));
baseparam.iPicWidth = 0;
baseparam.iPicHeight = 7896;
ret = encoder_->Initialize (&baseparam);
EXPECT_EQ (ret, static_cast<int> (cmInitParaError));
uiTraceLevel = WELS_LOG_ERROR;
encoder_->SetOption (ENCODER_OPTION_TRACE_LEVEL, &uiTraceLevel);
}
void outputData() {
}
TEST_F (EncInterfaceCallTest, SetOptionLTR) {
int iTotalFrameNum = 100;
int iFrameNum = 0;
int frameSize = 0;
int ret = cmResultSuccess;
int width = 320;
int height = 192;
SEncParamBase baseparam;
memset (&baseparam, 0, sizeof (SEncParamBase));
baseparam.iUsageType = CAMERA_VIDEO_REAL_TIME;
baseparam.fMaxFrameRate = 12;
baseparam.iPicWidth = width;
baseparam.iPicHeight = height;
baseparam.iTargetBitrate = 5000000;
encoder_->Initialize (&baseparam);
frameSize = width * height * 3 / 2;
BufferedData buf;
buf.SetLength (frameSize);
ASSERT_TRUE (buf.Length() == (size_t)frameSize);
SFrameBSInfo info;
memset (&info, 0, sizeof (SFrameBSInfo));
SSourcePicture pic;
memset (&pic, 0, sizeof (SSourcePicture));
pic.iPicWidth = width;
pic.iPicHeight = height;
pic.iColorFormat = videoFormatI420;
pic.iStride[0] = pic.iPicWidth;
pic.iStride[1] = pic.iStride[2] = pic.iPicWidth >> 1;
pic.pData[0] = buf.data();
pic.pData[1] = pic.pData[0] + width * height;
pic.pData[2] = pic.pData[1] + (width * height >> 2);
SLTRConfig config;
config.bEnableLongTermReference = true;
config.iLTRRefNum = rand() % 4;
encoder_->SetOption (ENCODER_OPTION_LTR, &config);
do {
FileInputStream fileStream;
ASSERT_TRUE (fileStream.Open ("res/CiscoVT2people_320x192_12fps.yuv"));
while (fileStream.read (buf.data(), frameSize) == frameSize) {
ret = encoder_->EncodeFrame (&pic, &info);
ASSERT_TRUE (ret == cmResultSuccess);
if (info.eFrameType != videoFrameTypeSkip) {
this->onEncodeFrame (info);
iFrameNum++;
}
}
} while (iFrameNum < iTotalFrameNum);
} | AnyRTC/AnyRTC-RTMP | third_party/openh264/src/test/encoder/EncUT_InterfaceTest.cpp | C++ | gpl-3.0 | 2,699 |
import { OpaqueToken } from './di';
/**
* A DI Token representing a unique string id assigned to the application by Angular and used
* primarily for prefixing application attributes and CSS styles when
* {@link ViewEncapsulation#Emulated} is being used.
*
* If you need to avoid randomly generated value to be used as an application id, you can provide
* a custom value via a DI provider <!-- TODO: provider --> configuring the root {@link Injector}
* using this token.
* @experimental
*/
export declare const APP_ID: any;
export declare function _appIdRandomProviderFactory(): string;
/**
* Providers that will generate a random APP_ID_TOKEN.
* @experimental
*/
export declare const APP_ID_RANDOM_PROVIDER: {
provide: any;
useFactory: () => string;
deps: any[];
};
/**
* A function that will be executed when a platform is initialized.
* @experimental
*/
export declare const PLATFORM_INITIALIZER: any;
/**
* All callbacks provided via this token will be called for every component that is bootstrapped.
* Signature of the callback:
*
* `(componentRef: ComponentRef) => void`.
*
* @experimental
*/
export declare const APP_BOOTSTRAP_LISTENER: OpaqueToken;
/**
* A token which indicates the root directory of the application
* @experimental
*/
export declare const PACKAGE_ROOT_URL: any;
| oleksandr-minakov/northshore | ui/node_modules/@angular/core/src/application_tokens.d.ts | TypeScript | apache-2.0 | 1,325 |
cask :v1 => 'navicat-for-sqlite' do
version '11.1.13' # navicat-premium.rb and navicat-for-* should be upgraded together
sha256 'd8dfce2de0af81f7c0883773a3c5ed1be64eb076fb67708344d0748244b7566a'
url "http://download.navicat.com/download/navicat#{version.sub(%r{^(\d+)\.(\d+).*},'\1\2')}_sqlite_en.dmg"
name 'Navicat for SQLite'
homepage 'http://www.navicat.com/products/navicat-for-sqlite'
license :commercial
tags :vendor => 'Navicat'
app 'Navicat for SQLite.app'
end
| bcaceiro/homebrew-cask | Casks/navicat-for-sqlite.rb | Ruby | bsd-2-clause | 489 |
/**
* Listens for the app launching then creates the window
*
* @see http://developer.chrome.com/apps/app.runtime.html
* @see http://developer.chrome.com/apps/app.window.html
*/
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', {
id: "camCaptureID",
innerBounds: {
width: 700,
height: 600
}
});
});
| Jabqooo/chrome-app-samples | samples/camera-capture/background.js | JavaScript | apache-2.0 | 375 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.psi;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
public abstract class JavaDirectoryService {
public static JavaDirectoryService getInstance() {
return ServiceManager.getService(JavaDirectoryService.class);
}
/**
* Returns the package corresponding to the directory.
*
* @return the package instance, or null if the directory does not correspond to any package.
*/
@Nullable
public abstract PsiPackage getPackage(@NotNull PsiDirectory dir);
/**
* Returns the list of Java classes contained in the directory.
*
* @return the array of classes.
*/
@NotNull
public abstract PsiClass[] getClasses(@NotNull PsiDirectory dir);
/**
* Creates a class with the specified name in the directory.
*
* @param name the name of the class to create (not including the file extension).
* @return the created class instance.
* @throws IncorrectOperationException if the operation failed for some reason.
*/
@NotNull
public abstract PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException;
/**
* Creates a class with the specified name in the directory.
*
* @param name the name of the class to create (not including the file extension).
* @param templateName custom file template to create class text based on.
* @return the created class instance.
* @throws IncorrectOperationException if the operation failed for some reason.
* @since 5.1
*/
@NotNull
public abstract PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName) throws IncorrectOperationException;
/**
* @param askForUndefinedVariables
* true show dialog asking for undefined variables
* false leave them blank
*/
public abstract PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName, boolean askForUndefinedVariables) throws IncorrectOperationException;
/**
* @param additionalProperties additional properties to be substituted in the template
*/
public abstract PsiClass createClass(@NotNull PsiDirectory dir,
@NotNull String name,
@NotNull String templateName,
boolean askForUndefinedVariables,
@NotNull final Map<String, String> additionalProperties) throws IncorrectOperationException;
/**
* Checks if it's possible to create a class with the specified name in the directory,
* and throws an exception if the creation is not possible. Does not actually modify
* anything.
*
* @param name the name of the class to check creation possibility (not including the file extension).
* @throws IncorrectOperationException if the creation is not possible.
*/
public abstract void checkCreateClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException;
/**
* Creates an interface class with the specified name in the directory.
*
* @param name the name of the interface to create (not including the file extension).
* @return the created interface instance.
* @throws IncorrectOperationException if the operation failed for some reason.
*/
@NotNull
public abstract PsiClass createInterface(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException;
/**
* Creates an enumeration class with the specified name in the directory.
*
* @param name the name of the enumeration class to create (not including the file extension).
* @return the created class instance.
* @throws IncorrectOperationException if the operation failed for some reason.
*/
@NotNull
public abstract PsiClass createEnum(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException;
/**
* Creates an annotation class with the specified name in the directory.
*
* @param name the name of the annotation class to create (not including the file extension).
* @return the created class instance.
* @throws IncorrectOperationException if the operation failed for some reason.
*/
@NotNull
public abstract PsiClass createAnnotationType(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException;
/**
* Checks if the directory is a source root for the project to which it belongs.
*
* @return true if the directory is a source root, false otherwise
*/
public abstract boolean isSourceRoot(@NotNull PsiDirectory dir);
public abstract LanguageLevel getLanguageLevel(@NotNull PsiDirectory dir);
} | caot/intellij-community | java/java-psi-api/src/com/intellij/psi/JavaDirectoryService.java | Java | apache-2.0 | 5,506 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), available at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* TIANI Medgraph AG.
* Portions created by the Initial Developer are Copyright (C) 2003-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <gunter.zeilinger@tiani.com>
* Franz Willer <franz.willer@gwi-ag.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chex.archive.common;
import java.util.Arrays;
/**
* @author gunter.zeilinger@tiani.com
* @version $Revision: 2772 $ $Date: 2006-09-20 16:58:51 +0800 (周三, 20 9月 2006) $
* @since 06.10.2004
*
*/
public class SPSStatus {
private static final String[] ENUM = { "SCHEDULED", "ARRIVED", "READY",
"STARTED", "COMPLETED", "DISCONTINUED" };
public static final int SCHEDULED = 0;
public static final int ARRIVED = 1;
public static final int READY = 2;
public static final int STARTED = 3;
public static final int COMPLETED = 4;
public static final int DISCONTINUED = 5;
public static final String toString(int value) {
return ENUM[value];
}
public static final int toInt(String s) {
final int index = Arrays.asList(ENUM).indexOf(s);
if (index == -1)
throw new IllegalArgumentException(s);
return index;
}
public static int[] toInts(String[] ss) {
if (ss == null) {
return null;
}
int[] ret = new int[ss.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = toInt(ss[i]);
}
return ret;
}
} | medicayun/medicayundicom | dcm4jboss-all/trunk/dcm4jboss-ejb/src/java/org/dcm4chex/archive/common/SPSStatus.java | Java | apache-2.0 | 3,087 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: FormTextarea.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* Abstract class for extension
*/
require_once 'Zend/View/Helper/FormElement.php';
/**
* Helper to generate a "textarea" element
*
* @category Zend
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_View_Helper_FormTextarea extends Zend_View_Helper_FormElement
{
/**
* The default number of rows for a textarea.
*
* @access public
*
* @var int
*/
public $rows = 24;
/**
* The default number of columns for a textarea.
*
* @access public
*
* @var int
*/
public $cols = 80;
/**
* Generates a 'textarea' element.
*
* @access public
*
* @param string|array $name If a string, the element name. If an
* array, all other parameters are ignored, and the array elements
* are extracted in place of added parameters.
*
* @param mixed $value The element value.
*
* @param array $attribs Attributes for the element tag.
*
* @return string The element XHTML.
*/
public function formTextarea($name, $value = null, $attribs = null)
{
$info = $this->_getInfo($name, $value, $attribs);
extract($info); // name, value, attribs, options, listsep, disable
// is it disabled?
$disabled = '';
if ($disable) {
// disabled.
$disabled = ' disabled="disabled"';
}
// Make sure that there are 'rows' and 'cols' values
// as required by the spec. noted by Orjan Persson.
if (empty($attribs['rows'])) {
$attribs['rows'] = (int) $this->rows;
}
if (empty($attribs['cols'])) {
$attribs['cols'] = (int) $this->cols;
}
// build the element
$xhtml = '<textarea name="' . $this->view->escape($name) . '"'
. ' id="' . $this->view->escape($id) . '"'
. $disabled
. $this->_htmlAttribs($attribs) . '>'
. $this->view->escape($value) . '</textarea>';
return $xhtml;
}
}
| chisimba/modules | zend/resources/Zend/View/Helper/FormTextarea.php | PHP | gpl-2.0 | 2,995 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.cvsSupport2.actions.update;
import com.intellij.cvsSupport2.cvsoperations.dateOrRevision.RevisionOrDate;
import com.intellij.cvsSupport2.cvsoperations.dateOrRevision.SimpleRevision;
import org.netbeans.lib.cvsclient.command.KeywordSubstitution;
/**
* author: lesya
*/
public class UpdateByBranchUpdateSettings implements UpdateSettings{
private final String myBranchName;
private final boolean myMakeNewFilesReadOnly;
public UpdateByBranchUpdateSettings(String branchName, boolean makeNewFilesReadOnly) {
myBranchName = branchName;
myMakeNewFilesReadOnly = makeNewFilesReadOnly;
}
public boolean getPruneEmptyDirectories() {
return true;
}
public String getBranch1ToMergeWith() {
return null;
}
public String getBranch2ToMergeWith() {
return null;
}
public boolean getResetAllSticky() {
return false;
}
public boolean getDontMakeAnyChanges() {
return false;
}
public boolean getCreateDirectories() {
return true;
}
public boolean getCleanCopy() {
return false;
}
public KeywordSubstitution getKeywordSubstitution() {
return null;
}
public RevisionOrDate getRevisionOrDate() {
return new SimpleRevision(myBranchName);
}
public boolean getMakeNewFilesReadOnly() {
return myMakeNewFilesReadOnly;
}
}
| akosyakov/intellij-community | plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/update/UpdateByBranchUpdateSettings.java | Java | apache-2.0 | 1,930 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.DataInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import com.google.common.base.Preconditions;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
/**
* An implementation of the abstract class {@link EditLogInputStream},
* which is used to updates HDFS meta-data state on a backup node.
*
* @see org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol#journal
* (org.apache.hadoop.hdfs.server.protocol.NamenodeRegistration,
* int, int, byte[])
*/
class EditLogBackupInputStream extends EditLogInputStream {
final String address; // sender address
private final ByteBufferInputStream inner;
private DataInputStream in;
private FSEditLogOp.Reader reader = null;
private FSEditLogLoader.PositionTrackingInputStream tracker = null;
private int version = 0;
/**
* A ByteArrayInputStream, which lets modify the underlying byte array.
*/
private static class ByteBufferInputStream extends ByteArrayInputStream {
ByteBufferInputStream() {
super(new byte[0]);
}
void setData(byte[] newBytes) {
super.buf = newBytes;
super.count = newBytes == null ? 0 : newBytes.length;
super.mark = 0;
reset();
}
/**
* Number of bytes read from the stream so far.
*/
int length() {
return count;
}
}
EditLogBackupInputStream(String name) throws IOException {
address = name;
inner = new ByteBufferInputStream();
in = null;
reader = null;
}
@Override
public String getName() {
return address;
}
@Override
protected FSEditLogOp nextOp() throws IOException {
Preconditions.checkState(reader != null,
"Must call setBytes() before readOp()");
return reader.readOp(false);
}
@Override
protected FSEditLogOp nextValidOp() {
try {
return reader.readOp(true);
} catch (IOException e) {
throw new RuntimeException("got unexpected IOException " + e, e);
}
}
@Override
public int getVersion(boolean verifyVersion) throws IOException {
return this.version;
}
@Override
public long getPosition() {
return tracker.getPos();
}
@Override
public void close() throws IOException {
in.close();
}
@Override
public long length() throws IOException {
// file size + size of both buffers
return inner.length();
}
void setBytes(byte[] newBytes, int version) throws IOException {
inner.setData(newBytes);
tracker = new FSEditLogLoader.PositionTrackingInputStream(inner);
in = new DataInputStream(tracker);
this.version = version;
reader = FSEditLogOp.Reader.create(in, tracker, version);
}
void clear() throws IOException {
setBytes(null, 0);
reader = null;
this.version = 0;
}
@Override
public long getFirstTxId() {
return HdfsServerConstants.INVALID_TXID;
}
@Override
public long getLastTxId() {
return HdfsServerConstants.INVALID_TXID;
}
@Override
public boolean isInProgress() {
return true;
}
@Override
public void setMaxOpSize(int maxOpSize) {
reader.setMaxOpSize(maxOpSize);
}
@Override
public boolean isLocalLog() {
return true;
}
}
| cnfire/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/EditLogBackupInputStream.java | Java | apache-2.0 | 4,051 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.refactoring.convertToJava.invocators;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiSubstitutor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod;
import org.jetbrains.plugins.groovy.refactoring.convertToJava.ExpressionGenerator;
/**
* @author Max Medvedev
*/
public abstract class CustomMethodInvocator {
private static final ExtensionPointName<CustomMethodInvocator> EP_NAME =
ExtensionPointName.create("org.intellij.groovy.convertToJava.customMethodInvocator");
protected abstract boolean invoke(@NotNull ExpressionGenerator generator,
@NotNull PsiMethod method,
@Nullable GrExpression caller,
@NotNull GrExpression[] exprs,
@NotNull GrNamedArgument[] namedArgs,
@NotNull GrClosableBlock[] closures,
@NotNull PsiSubstitutor substitutor,
@NotNull GroovyPsiElement context);
public static boolean invokeMethodOn(@NotNull ExpressionGenerator generator,
@NotNull GrGdkMethod method,
@Nullable GrExpression caller,
@NotNull GrExpression[] exprs,
@NotNull GrNamedArgument[] namedArgs,
@NotNull GrClosableBlock[] closures,
@NotNull PsiSubstitutor substitutor,
@NotNull GroovyPsiElement context) {
final PsiMethod staticMethod = method.getStaticMethod();
for (CustomMethodInvocator invocator : EP_NAME.getExtensions()) {
if (invocator.invoke(generator, staticMethod, caller, exprs, namedArgs, closures, substitutor, context)) {
return true;
}
}
return false;
}
}
| liveqmock/platform-tools-idea | plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/invocators/CustomMethodInvocator.java | Java | apache-2.0 | 3,095 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Translate
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @version $Id: Exception.php 20096 2010-01-06 02:05:09Z bkarwin $
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* Zend_Exception
*/
require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Translate
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Translate_Exception extends Zend_Exception
{
}
| chisimba/modules | zend/resources/Zend/Translate/Exception.php | PHP | gpl-2.0 | 1,099 |
/**
* Copyright (C) 2011 Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// markup required:
// <span class=" field-with-fancyplaceholder"><label for="email">Email Address</span></label><input type="text" id="login_apple_id"></span>
//
// css required:
// span.field-with-fancyplaceholder{display:block;display:inline-block;position:relative;vertical-align:top;}
// span.field-with-fancyplaceholder label.placeholder{color:#999;cursor:text;pointer-events:none;}
// span.field-with-fancyplaceholder label.placeholder span{position:absolute;z-index:2;-webkit-user-select:none;padding:3px 6px;}
// span.field-with-fancyplaceholder label.focus{color:#ccc;}
// span.field-with-fancyplaceholder label.hidden{color:#fff;}
// span.field-with-fancyplaceholder input.invalid{background:#ffffc5;color:#F30;}
// span.field-with-fancyplaceholder input.editing{color:#000;background:none repeat scroll 0 0 transparent;overflow:hidden;}
//
// then: $(".field-with-fancyplaceholder input").fancyPlaceholder();
define(['jquery'], function($) {
$.fn.fancyPlaceholder = function() {
var pollingInterval,
foundInputsAndLables = [];
function hideOrShowLabels(){
$.each(foundInputsAndLables, function(i, inputAndLable){
inputAndLable[1][inputAndLable[0].val() ? 'hide' : 'show']();
});
}
return this.each(function() {
var $input = $(this),
$label = $("label[for="+$input.attr('id')+"]");
$label.addClass('placeholder').wrapInner("<span/>").css({
'font-family' : $input.css('font-family'),
'font-size' : $input.css('font-size')
});
$input
.focus(function(){
$label.addClass('focus', 300);
})
.blur(function(){
$label.removeClass('focus', 300);
})
.bind('keyup', hideOrShowLabels);
// if this was already focused before we got here, make it light gray now. sorry, ie7 cant do :focus selector, it doesn't get this.
try {
if ($("input:focus").get(0) == this) {
$input.triggerHandler('focus');
}
} catch(e) {}
foundInputsAndLables.push([$input, $label]);
if (!pollingInterval) {
window.setInterval(hideOrShowLabels, 100);
}
});
};
});
| ajpi222/canvas-lms-hdi | public/javascripts/jquery.fancyplaceholder.js | JavaScript | agpl-3.0 | 2,861 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.navigation;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
/**
* Allows a plugin to add items to "Goto Class" and "Goto Symbol" lists.
*
* @see ChooseByNameRegistry
*/
public interface ChooseByNameContributor {
ExtensionPointName<ChooseByNameContributor> CLASS_EP_NAME = ExtensionPointName.create("com.intellij.gotoClassContributor");
ExtensionPointName<ChooseByNameContributor> SYMBOL_EP_NAME = ExtensionPointName.create("com.intellij.gotoSymbolContributor");
ExtensionPointName<ChooseByNameContributor> FILE_EP_NAME = ExtensionPointName.create("com.intellij.gotoFileContributor");
/**
* Returns the list of names for the specified project to which it is possible to navigate
* by name.
*
* @param project the project in which the navigation is performed.
* @param includeNonProjectItems if true, the names of non-project items (for example,
* library classes) should be included in the returned array.
* @return the array of names.
*/
@NotNull
String[] getNames(Project project, boolean includeNonProjectItems);
/**
* Returns the list of navigation items matching the specified name.
*
* @param name the name selected from the list.
* @param pattern the original pattern entered in the dialog
* @param project the project in which the navigation is performed.
* @param includeNonProjectItems if true, the navigation items for non-project items (for example,
* library classes) should be included in the returned array.
* @return the array of navigation items.
*/
@NotNull
NavigationItem[] getItemsByName(String name, final String pattern, Project project, boolean includeNonProjectItems);
} | caot/intellij-community | platform/lang-api/src/com/intellij/navigation/ChooseByNameContributor.java | Java | apache-2.0 | 2,515 |
if (require.register) {
var qs = require('querystring');
} else {
var qs = require('../')
, expect = require('expect.js');
}
var date = new Date(0);
var str_identities = {
'basics': [
{ str: 'foo=bar', obj: {'foo' : 'bar'}},
{ str: 'foo=%22bar%22', obj: {'foo' : '\"bar\"'}},
{ str: 'foo=', obj: {'foo': ''}},
{ str: 'foo=1&bar=2', obj: {'foo' : '1', 'bar' : '2'}},
{ str: 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', obj: {'my weird field': "q1!2\"'w$5&7/z8)?"}},
{ str: 'foo%3Dbaz=bar', obj: {'foo=baz': 'bar'}},
{ str: 'foo=bar&bar=baz', obj: {foo: 'bar', bar: 'baz'}}
],
'escaping': [
{ str: 'foo=foo%20bar', obj: {foo: 'foo bar'}},
{ str: 'cht=p3&chd=t%3A60%2C40&chs=250x100&chl=Hello%7CWorld', obj: {
cht: 'p3'
, chd: 't:60,40'
, chs: '250x100'
, chl: 'Hello|World'
}}
],
'nested': [
{ str: 'foo[0]=bar&foo[1]=quux', obj: {'foo' : ['bar', 'quux']}},
{ str: 'foo[0]=bar', obj: {foo: ['bar']}},
{ str: 'foo[0]=1&foo[1]=2', obj: {'foo' : ['1', '2']}},
{ str: 'foo=bar&baz[0]=1&baz[1]=2&baz[2]=3', obj: {'foo' : 'bar', 'baz' : ['1', '2', '3']}},
{ str: 'foo[0]=bar&baz[0]=1&baz[1]=2&baz[2]=3', obj: {'foo' : ['bar'], 'baz' : ['1', '2', '3']}},
{ str: 'x[y][z]=1', obj: {'x' : {'y' : {'z' : '1'}}}},
{ str: 'x[y][z][0]=1', obj: {'x' : {'y' : {'z' : ['1']}}}},
{ str: 'x[y][z]=2', obj: {'x' : {'y' : {'z' : '2'}}}},
{ str: 'x[y][z][0]=1&x[y][z][1]=2', obj: {'x' : {'y' : {'z' : ['1', '2']}}}},
{ str: 'x[y][0][z]=1', obj: {'x' : {'y' : [{'z' : '1'}]}}},
{ str: 'x[y][0][z][0]=1', obj: {'x' : {'y' : [{'z' : ['1']}]}}},
{ str: 'x[y][0][z]=1&x[y][0][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'w' : '2'}]}}},
{ str: 'x[y][0][v][w]=1', obj: {'x' : {'y' : [{'v' : {'w' : '1'}}]}}},
{ str: 'x[y][0][z]=1&x[y][0][v][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'v' : {'w' : '2'}}]}}},
{ str: 'x[y][0][z]=1&x[y][1][z]=2', obj: {'x' : {'y' : [{'z' : '1'}, {'z' : '2'}]}}},
{ str: 'x[y][0][z]=1&x[y][0][w]=a&x[y][1][z]=2&x[y][1][w]=3', obj: {'x' : {'y' : [{'z' : '1', 'w' : 'a'}, {'z' : '2', 'w' : '3'}]}}},
{ str: 'user[name][first]=tj&user[name][last]=holowaychuk', obj: { user: { name: { first: 'tj', last: 'holowaychuk' }}}}
],
'errors': [
{ obj: 'foo=bar', message: 'stringify expects an object' },
{ obj: ['foo', 'bar'], message: 'stringify expects an object' }
],
'numbers': [
{ str: 'limit[0]=1&limit[1]=2&limit[2]=3', obj: { limit: [1, 2, '3'] }},
{ str: 'limit=1', obj: { limit: 1 }}
],
'others': [
{ str: 'at=' + encodeURIComponent(date), obj: { at: date } }
]
};
function test(type) {
return function(){
var str, obj;
for (var i = 0; i < str_identities[type].length; i++) {
str = str_identities[type][i].str;
obj = str_identities[type][i].obj;
expect(qs.stringify(obj)).to.eql(str);
}
}
}
describe('qs.stringify()', function(){
it('should support the basics', test('basics'))
it('should support escapes', test('escaping'))
it('should support nesting', test('nested'))
it('should support numbers', test('numbers'))
it('should support others', test('others'))
})
| gglinux/node.js | webChat/node_modules/qs/test/stringify.js | JavaScript | apache-2.0 | 3,198 |
# databases/__init__.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Include imports from the sqlalchemy.dialects package for backwards
compatibility with pre 0.6 versions.
"""
from ..dialects.sqlite import base as sqlite
from ..dialects.postgresql import base as postgresql
postgres = postgresql
from ..dialects.mysql import base as mysql
from ..dialects.drizzle import base as drizzle
from ..dialects.oracle import base as oracle
from ..dialects.firebird import base as firebird
from ..dialects.mssql import base as mssql
from ..dialects.sybase import base as sybase
__all__ = (
'drizzle',
'firebird',
'mssql',
'mysql',
'postgresql',
'sqlite',
'oracle',
'sybase',
)
| jessekl/flixr | venv/lib/python2.7/site-packages/sqlalchemy/databases/__init__.py | Python | mit | 881 |
module ChefCompat
module CopiedFromChef
def self.extend_chef_module(chef_module, target)
target.instance_eval do
include chef_module
@chef_module = chef_module
def self.method_missing(name, *args, &block)
@chef_module.send(name, *args, &block)
end
def self.const_missing(name)
@chef_module.const_get(name)
end
end
end
# This patch to CopiedFromChef's ActionClass is necessary for the include to work
require 'chef/resource'
class Chef < ::Chef
class Resource < ::Chef::Resource
module ActionClass
def self.use_inline_resources
end
def self.include_resource_dsl(include_resource_dsl)
end
end
end
end
end
end
| Coveros/starcanada2016 | www-db/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef.rb | Ruby | apache-2.0 | 784 |
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btMultiBodyDynamicsWorld.h"
#include "btMultiBodyConstraintSolver.h"
#include "btMultiBody.h"
#include "btMultiBodyLinkCollider.h"
#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
#include "LinearMath/btQuickprof.h"
#include "btMultiBodyConstraint.h"
#include "LinearMath/btIDebugDraw.h"
void btMultiBodyDynamicsWorld::addMultiBody(btMultiBody* body, short group, short mask)
{
m_multiBodies.push_back(body);
}
void btMultiBodyDynamicsWorld::removeMultiBody(btMultiBody* body)
{
m_multiBodies.remove(body);
}
void btMultiBodyDynamicsWorld::calculateSimulationIslands()
{
BT_PROFILE("calculateSimulationIslands");
getSimulationIslandManager()->updateActivationState(getCollisionWorld(),getCollisionWorld()->getDispatcher());
{
//merge islands based on speculative contact manifolds too
for (int i=0;i<this->m_predictiveManifolds.size();i++)
{
btPersistentManifold* manifold = m_predictiveManifolds[i];
const btCollisionObject* colObj0 = manifold->getBody0();
const btCollisionObject* colObj1 = manifold->getBody1();
if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) &&
((colObj1) && (!(colObj1)->isStaticOrKinematicObject())))
{
getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag());
}
}
}
{
int i;
int numConstraints = int(m_constraints.size());
for (i=0;i< numConstraints ; i++ )
{
btTypedConstraint* constraint = m_constraints[i];
if (constraint->isEnabled())
{
const btRigidBody* colObj0 = &constraint->getRigidBodyA();
const btRigidBody* colObj1 = &constraint->getRigidBodyB();
if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) &&
((colObj1) && (!(colObj1)->isStaticOrKinematicObject())))
{
getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag());
}
}
}
}
//merge islands linked by Featherstone link colliders
for (int i=0;i<m_multiBodies.size();i++)
{
btMultiBody* body = m_multiBodies[i];
{
btMultiBodyLinkCollider* prev = body->getBaseCollider();
for (int b=0;b<body->getNumLinks();b++)
{
btMultiBodyLinkCollider* cur = body->getLink(b).m_collider;
if (((cur) && (!(cur)->isStaticOrKinematicObject())) &&
((prev) && (!(prev)->isStaticOrKinematicObject())))
{
int tagPrev = prev->getIslandTag();
int tagCur = cur->getIslandTag();
getSimulationIslandManager()->getUnionFind().unite(tagPrev, tagCur);
}
if (cur && !cur->isStaticOrKinematicObject())
prev = cur;
}
}
}
//merge islands linked by multibody constraints
{
for (int i=0;i<this->m_multiBodyConstraints.size();i++)
{
btMultiBodyConstraint* c = m_multiBodyConstraints[i];
int tagA = c->getIslandIdA();
int tagB = c->getIslandIdB();
if (tagA>=0 && tagB>=0)
getSimulationIslandManager()->getUnionFind().unite(tagA, tagB);
}
}
//Store the island id in each body
getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld());
}
void btMultiBodyDynamicsWorld::updateActivationState(btScalar timeStep)
{
BT_PROFILE("btMultiBodyDynamicsWorld::updateActivationState");
for ( int i=0;i<m_multiBodies.size();i++)
{
btMultiBody* body = m_multiBodies[i];
if (body)
{
body->checkMotionAndSleepIfRequired(timeStep);
if (!body->isAwake())
{
btMultiBodyLinkCollider* col = body->getBaseCollider();
if (col && col->getActivationState() == ACTIVE_TAG)
{
col->setActivationState( WANTS_DEACTIVATION);
col->setDeactivationTime(0.f);
}
for (int b=0;b<body->getNumLinks();b++)
{
btMultiBodyLinkCollider* col = body->getLink(b).m_collider;
if (col && col->getActivationState() == ACTIVE_TAG)
{
col->setActivationState( WANTS_DEACTIVATION);
col->setDeactivationTime(0.f);
}
}
} else
{
btMultiBodyLinkCollider* col = body->getBaseCollider();
if (col && col->getActivationState() != DISABLE_DEACTIVATION)
col->setActivationState( ACTIVE_TAG );
for (int b=0;b<body->getNumLinks();b++)
{
btMultiBodyLinkCollider* col = body->getLink(b).m_collider;
if (col && col->getActivationState() != DISABLE_DEACTIVATION)
col->setActivationState( ACTIVE_TAG );
}
}
}
}
btDiscreteDynamicsWorld::updateActivationState(timeStep);
}
SIMD_FORCE_INLINE int btGetConstraintIslandId2(const btTypedConstraint* lhs)
{
int islandId;
const btCollisionObject& rcolObj0 = lhs->getRigidBodyA();
const btCollisionObject& rcolObj1 = lhs->getRigidBodyB();
islandId= rcolObj0.getIslandTag()>=0?rcolObj0.getIslandTag():rcolObj1.getIslandTag();
return islandId;
}
class btSortConstraintOnIslandPredicate2
{
public:
bool operator() ( const btTypedConstraint* lhs, const btTypedConstraint* rhs ) const
{
int rIslandId0,lIslandId0;
rIslandId0 = btGetConstraintIslandId2(rhs);
lIslandId0 = btGetConstraintIslandId2(lhs);
return lIslandId0 < rIslandId0;
}
};
SIMD_FORCE_INLINE int btGetMultiBodyConstraintIslandId(const btMultiBodyConstraint* lhs)
{
int islandId;
int islandTagA = lhs->getIslandIdA();
int islandTagB = lhs->getIslandIdB();
islandId= islandTagA>=0?islandTagA:islandTagB;
return islandId;
}
class btSortMultiBodyConstraintOnIslandPredicate
{
public:
bool operator() ( const btMultiBodyConstraint* lhs, const btMultiBodyConstraint* rhs ) const
{
int rIslandId0,lIslandId0;
rIslandId0 = btGetMultiBodyConstraintIslandId(rhs);
lIslandId0 = btGetMultiBodyConstraintIslandId(lhs);
return lIslandId0 < rIslandId0;
}
};
struct MultiBodyInplaceSolverIslandCallback : public btSimulationIslandManager::IslandCallback
{
btContactSolverInfo* m_solverInfo;
btMultiBodyConstraintSolver* m_solver;
btMultiBodyConstraint** m_multiBodySortedConstraints;
int m_numMultiBodyConstraints;
btTypedConstraint** m_sortedConstraints;
int m_numConstraints;
btIDebugDraw* m_debugDrawer;
btDispatcher* m_dispatcher;
btAlignedObjectArray<btCollisionObject*> m_bodies;
btAlignedObjectArray<btPersistentManifold*> m_manifolds;
btAlignedObjectArray<btTypedConstraint*> m_constraints;
btAlignedObjectArray<btMultiBodyConstraint*> m_multiBodyConstraints;
MultiBodyInplaceSolverIslandCallback( btMultiBodyConstraintSolver* solver,
btDispatcher* dispatcher)
:m_solverInfo(NULL),
m_solver(solver),
m_multiBodySortedConstraints(NULL),
m_numConstraints(0),
m_debugDrawer(NULL),
m_dispatcher(dispatcher)
{
}
MultiBodyInplaceSolverIslandCallback& operator=(MultiBodyInplaceSolverIslandCallback& other)
{
btAssert(0);
(void)other;
return *this;
}
SIMD_FORCE_INLINE void setup ( btContactSolverInfo* solverInfo, btTypedConstraint** sortedConstraints, int numConstraints, btMultiBodyConstraint** sortedMultiBodyConstraints, int numMultiBodyConstraints, btIDebugDraw* debugDrawer)
{
btAssert(solverInfo);
m_solverInfo = solverInfo;
m_multiBodySortedConstraints = sortedMultiBodyConstraints;
m_numMultiBodyConstraints = numMultiBodyConstraints;
m_sortedConstraints = sortedConstraints;
m_numConstraints = numConstraints;
m_debugDrawer = debugDrawer;
m_bodies.resize (0);
m_manifolds.resize (0);
m_constraints.resize (0);
m_multiBodyConstraints.resize(0);
}
virtual void processIsland(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifolds,int numManifolds, int islandId)
{
if (islandId<0)
{
///we don't split islands, so all constraints/contact manifolds/bodies are passed into the solver regardless the island id
m_solver->solveMultiBodyGroup( bodies,numBodies,manifolds, numManifolds,m_sortedConstraints, m_numConstraints, &m_multiBodySortedConstraints[0],m_numConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher);
} else
{
//also add all non-contact constraints/joints for this island
btTypedConstraint** startConstraint = 0;
btMultiBodyConstraint** startMultiBodyConstraint = 0;
int numCurConstraints = 0;
int numCurMultiBodyConstraints = 0;
int i;
//find the first constraint for this island
for (i=0;i<m_numConstraints;i++)
{
if (btGetConstraintIslandId2(m_sortedConstraints[i]) == islandId)
{
startConstraint = &m_sortedConstraints[i];
break;
}
}
//count the number of constraints in this island
for (;i<m_numConstraints;i++)
{
if (btGetConstraintIslandId2(m_sortedConstraints[i]) == islandId)
{
numCurConstraints++;
}
}
for (i=0;i<m_numMultiBodyConstraints;i++)
{
if (btGetMultiBodyConstraintIslandId(m_multiBodySortedConstraints[i]) == islandId)
{
startMultiBodyConstraint = &m_multiBodySortedConstraints[i];
break;
}
}
//count the number of multi body constraints in this island
for (;i<m_numMultiBodyConstraints;i++)
{
if (btGetMultiBodyConstraintIslandId(m_multiBodySortedConstraints[i]) == islandId)
{
numCurMultiBodyConstraints++;
}
}
if (m_solverInfo->m_minimumSolverBatchSize<=1)
{
m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher);
} else
{
for (i=0;i<numBodies;i++)
m_bodies.push_back(bodies[i]);
for (i=0;i<numManifolds;i++)
m_manifolds.push_back(manifolds[i]);
for (i=0;i<numCurConstraints;i++)
m_constraints.push_back(startConstraint[i]);
for (i=0;i<numCurMultiBodyConstraints;i++)
m_multiBodyConstraints.push_back(startMultiBodyConstraint[i]);
if ((m_constraints.size()+m_manifolds.size())>m_solverInfo->m_minimumSolverBatchSize)
{
processConstraints();
} else
{
//printf("deferred\n");
}
}
}
}
void processConstraints()
{
btCollisionObject** bodies = m_bodies.size()? &m_bodies[0]:0;
btPersistentManifold** manifold = m_manifolds.size()?&m_manifolds[0]:0;
btTypedConstraint** constraints = m_constraints.size()?&m_constraints[0]:0;
btMultiBodyConstraint** multiBodyConstraints = m_multiBodyConstraints.size() ? &m_multiBodyConstraints[0] : 0;
//printf("mb contacts = %d, mb constraints = %d\n", mbContacts, m_multiBodyConstraints.size());
m_solver->solveMultiBodyGroup( bodies,m_bodies.size(),manifold, m_manifolds.size(),constraints, m_constraints.size() ,multiBodyConstraints, m_multiBodyConstraints.size(), *m_solverInfo,m_debugDrawer,m_dispatcher);
m_bodies.resize(0);
m_manifolds.resize(0);
m_constraints.resize(0);
m_multiBodyConstraints.resize(0);
}
};
btMultiBodyDynamicsWorld::btMultiBodyDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btMultiBodyConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration)
:btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration),
m_multiBodyConstraintSolver(constraintSolver)
{
//split impulse is not yet supported for Featherstone hierarchies
getSolverInfo().m_splitImpulse = false;
getSolverInfo().m_solverMode |=SOLVER_USE_2_FRICTION_DIRECTIONS;
m_solverMultiBodyIslandCallback = new MultiBodyInplaceSolverIslandCallback(constraintSolver,dispatcher);
}
btMultiBodyDynamicsWorld::~btMultiBodyDynamicsWorld ()
{
delete m_solverMultiBodyIslandCallback;
}
void btMultiBodyDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo)
{
btAlignedObjectArray<btScalar> scratch_r;
btAlignedObjectArray<btVector3> scratch_v;
btAlignedObjectArray<btMatrix3x3> scratch_m;
BT_PROFILE("solveConstraints");
m_sortedConstraints.resize( m_constraints.size());
int i;
for (i=0;i<getNumConstraints();i++)
{
m_sortedConstraints[i] = m_constraints[i];
}
m_sortedConstraints.quickSort(btSortConstraintOnIslandPredicate2());
btTypedConstraint** constraintsPtr = getNumConstraints() ? &m_sortedConstraints[0] : 0;
m_sortedMultiBodyConstraints.resize(m_multiBodyConstraints.size());
for (i=0;i<m_multiBodyConstraints.size();i++)
{
m_sortedMultiBodyConstraints[i] = m_multiBodyConstraints[i];
}
m_sortedMultiBodyConstraints.quickSort(btSortMultiBodyConstraintOnIslandPredicate());
btMultiBodyConstraint** sortedMultiBodyConstraints = m_sortedMultiBodyConstraints.size() ? &m_sortedMultiBodyConstraints[0] : 0;
m_solverMultiBodyIslandCallback->setup(&solverInfo,constraintsPtr,m_sortedConstraints.size(),sortedMultiBodyConstraints,m_sortedMultiBodyConstraints.size(), getDebugDrawer());
m_constraintSolver->prepareSolve(getCollisionWorld()->getNumCollisionObjects(), getCollisionWorld()->getDispatcher()->getNumManifolds());
/// solve all the constraints for this island
m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(),getCollisionWorld(),m_solverMultiBodyIslandCallback);
{
BT_PROFILE("btMultiBody addForce and stepVelocities");
for (int i=0;i<this->m_multiBodies.size();i++)
{
btMultiBody* bod = m_multiBodies[i];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b=0;b<bod->getNumLinks();b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState()==ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
//useless? they get resized in stepVelocities once again (AND DIFFERENTLY)
scratch_r.resize(bod->getNumLinks()+1); //multidof? ("Y"s use it and it is used to store qdd)
scratch_v.resize(bod->getNumLinks()+1);
scratch_m.resize(bod->getNumLinks()+1);
bod->addBaseForce(m_gravity * bod->getBaseMass());
for (int j = 0; j < bod->getNumLinks(); ++j)
{
bod->addLinkForce(j, m_gravity * bod->getLinkMass(j));
}
bool doNotUpdatePos = false;
if(bod->isMultiDof())
{
if(!bod->isUsingRK4Integration())
{
bod->stepVelocitiesMultiDof(solverInfo.m_timeStep, scratch_r, scratch_v, scratch_m);
}
else
{
//
int numDofs = bod->getNumDofs() + 6;
int numPosVars = bod->getNumPosVars() + 7;
btAlignedObjectArray<btScalar> scratch_r2; scratch_r2.resize(2*numPosVars + 8*numDofs);
//convenience
btScalar *pMem = &scratch_r2[0];
btScalar *scratch_q0 = pMem; pMem += numPosVars;
btScalar *scratch_qx = pMem; pMem += numPosVars;
btScalar *scratch_qd0 = pMem; pMem += numDofs;
btScalar *scratch_qd1 = pMem; pMem += numDofs;
btScalar *scratch_qd2 = pMem; pMem += numDofs;
btScalar *scratch_qd3 = pMem; pMem += numDofs;
btScalar *scratch_qdd0 = pMem; pMem += numDofs;
btScalar *scratch_qdd1 = pMem; pMem += numDofs;
btScalar *scratch_qdd2 = pMem; pMem += numDofs;
btScalar *scratch_qdd3 = pMem; pMem += numDofs;
btAssert((pMem - (2*numPosVars + 8*numDofs)) == &scratch_r2[0]);
/////
//copy q0 to scratch_q0 and qd0 to scratch_qd0
scratch_q0[0] = bod->getWorldToBaseRot().x();
scratch_q0[1] = bod->getWorldToBaseRot().y();
scratch_q0[2] = bod->getWorldToBaseRot().z();
scratch_q0[3] = bod->getWorldToBaseRot().w();
scratch_q0[4] = bod->getBasePos().x();
scratch_q0[5] = bod->getBasePos().y();
scratch_q0[6] = bod->getBasePos().z();
//
for(int link = 0; link < bod->getNumLinks(); ++link)
{
for(int dof = 0; dof < bod->getLink(link).m_posVarCount; ++dof)
scratch_q0[7 + bod->getLink(link).m_cfgOffset + dof] = bod->getLink(link).m_jointPos[dof];
}
//
for(int dof = 0; dof < numDofs; ++dof)
scratch_qd0[dof] = bod->getVelocityVector()[dof];
////
struct
{
btMultiBody *bod;
btScalar *scratch_qx, *scratch_q0;
void operator()()
{
for(int dof = 0; dof < bod->getNumPosVars() + 7; ++dof)
scratch_qx[dof] = scratch_q0[dof];
}
} pResetQx = {bod, scratch_qx, scratch_q0};
//
struct
{
void operator()(btScalar dt, const btScalar *pDer, const btScalar *pCurVal, btScalar *pVal, int size)
{
for(int i = 0; i < size; ++i)
pVal[i] = pCurVal[i] + dt * pDer[i];
}
} pEulerIntegrate;
//
struct
{
void operator()(btMultiBody *pBody, const btScalar *pData)
{
btScalar *pVel = const_cast<btScalar*>(pBody->getVelocityVector());
for(int i = 0; i < pBody->getNumDofs() + 6; ++i)
pVel[i] = pData[i];
}
} pCopyToVelocityVector;
//
struct
{
void operator()(const btScalar *pSrc, btScalar *pDst, int start, int size)
{
for(int i = 0; i < size; ++i)
pDst[i] = pSrc[start + i];
}
} pCopy;
//
btScalar h = solverInfo.m_timeStep;
#define output &scratch_r[bod->getNumDofs()]
//calc qdd0 from: q0 & qd0
bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m);
pCopy(output, scratch_qdd0, 0, numDofs);
//calc q1 = q0 + h/2 * qd0
pResetQx();
bod->stepPositionsMultiDof(btScalar(.5)*h, scratch_qx, scratch_qd0);
//calc qd1 = qd0 + h/2 * qdd0
pEulerIntegrate(btScalar(.5)*h, scratch_qdd0, scratch_qd0, scratch_qd1, numDofs);
//
//calc qdd1 from: q1 & qd1
pCopyToVelocityVector(bod, scratch_qd1);
bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m);
pCopy(output, scratch_qdd1, 0, numDofs);
//calc q2 = q0 + h/2 * qd1
pResetQx();
bod->stepPositionsMultiDof(btScalar(.5)*h, scratch_qx, scratch_qd1);
//calc qd2 = qd0 + h/2 * qdd1
pEulerIntegrate(btScalar(.5)*h, scratch_qdd1, scratch_qd0, scratch_qd2, numDofs);
//
//calc qdd2 from: q2 & qd2
pCopyToVelocityVector(bod, scratch_qd2);
bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m);
pCopy(output, scratch_qdd2, 0, numDofs);
//calc q3 = q0 + h * qd2
pResetQx();
bod->stepPositionsMultiDof(h, scratch_qx, scratch_qd2);
//calc qd3 = qd0 + h * qdd2
pEulerIntegrate(h, scratch_qdd2, scratch_qd0, scratch_qd3, numDofs);
//
//calc qdd3 from: q3 & qd3
pCopyToVelocityVector(bod, scratch_qd3);
bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m);
pCopy(output, scratch_qdd3, 0, numDofs);
//
//calc q = q0 + h/6(qd0 + 2*(qd1 + qd2) + qd3)
//calc qd = qd0 + h/6(qdd0 + 2*(qdd1 + qdd2) + qdd3)
btAlignedObjectArray<btScalar> delta_q; delta_q.resize(numDofs);
btAlignedObjectArray<btScalar> delta_qd; delta_qd.resize(numDofs);
for(int i = 0; i < numDofs; ++i)
{
delta_q[i] = h/btScalar(6.)*(scratch_qd0[i] + 2*scratch_qd1[i] + 2*scratch_qd2[i] + scratch_qd3[i]);
delta_qd[i] = h/btScalar(6.)*(scratch_qdd0[i] + 2*scratch_qdd1[i] + 2*scratch_qdd2[i] + scratch_qdd3[i]);
//delta_q[i] = h*scratch_qd0[i];
//delta_qd[i] = h*scratch_qdd0[i];
}
//
pCopyToVelocityVector(bod, scratch_qd0);
bod->applyDeltaVeeMultiDof(&delta_qd[0], 1);
//
if(!doNotUpdatePos)
{
btScalar *pRealBuf = const_cast<btScalar *>(bod->getVelocityVector());
pRealBuf += 6 + bod->getNumDofs() + bod->getNumDofs()*bod->getNumDofs();
for(int i = 0; i < numDofs; ++i)
pRealBuf[i] = delta_q[i];
//bod->stepPositionsMultiDof(1, 0, &delta_q[0]);
bod->setPosUpdated(true);
}
//ugly hack which resets the cached data to t0 (needed for constraint solver)
{
for(int link = 0; link < bod->getNumLinks(); ++link)
bod->getLink(link).updateCacheMultiDof();
bod->stepVelocitiesMultiDof(0, scratch_r, scratch_v, scratch_m);
}
}
}
else//if(bod->isMultiDof())
{
bod->stepVelocities(solverInfo.m_timeStep, scratch_r, scratch_v, scratch_m);
}
bod->clearForcesAndTorques();
}//if (!isSleeping)
}
}
m_solverMultiBodyIslandCallback->processConstraints();
m_constraintSolver->allSolved(solverInfo, m_debugDrawer);
}
void btMultiBodyDynamicsWorld::integrateTransforms(btScalar timeStep)
{
btDiscreteDynamicsWorld::integrateTransforms(timeStep);
{
BT_PROFILE("btMultiBody stepPositions");
//integrate and update the Featherstone hierarchies
btAlignedObjectArray<btQuaternion> world_to_local;
btAlignedObjectArray<btVector3> local_origin;
for (int b=0;b<m_multiBodies.size();b++)
{
btMultiBody* bod = m_multiBodies[b];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b=0;b<bod->getNumLinks();b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState()==ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
int nLinks = bod->getNumLinks();
///base + num m_links
world_to_local.resize(nLinks+1);
local_origin.resize(nLinks+1);
if(bod->isMultiDof())
{
if(!bod->isPosUpdated())
bod->stepPositionsMultiDof(timeStep);
else
{
btScalar *pRealBuf = const_cast<btScalar *>(bod->getVelocityVector());
pRealBuf += 6 + bod->getNumDofs() + bod->getNumDofs()*bod->getNumDofs();
bod->stepPositionsMultiDof(1, 0, pRealBuf);
bod->setPosUpdated(false);
}
}
else
bod->stepPositions(timeStep);
world_to_local[0] = bod->getWorldToBaseRot();
local_origin[0] = bod->getBasePos();
if (bod->getBaseCollider())
{
btVector3 posr = local_origin[0];
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
btScalar quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
btTransform tr;
tr.setIdentity();
tr.setOrigin(posr);
tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
bod->getBaseCollider()->setWorldTransform(tr);
}
for (int k=0;k<bod->getNumLinks();k++)
{
const int parent = bod->getParent(k);
world_to_local[k+1] = bod->getParentToLocalRot(k) * world_to_local[parent+1];
local_origin[k+1] = local_origin[parent+1] + (quatRotate(world_to_local[k+1].inverse() , bod->getRVector(k)));
}
for (int m=0;m<bod->getNumLinks();m++)
{
btMultiBodyLinkCollider* col = bod->getLink(m).m_collider;
if (col)
{
int link = col->m_link;
btAssert(link == m);
int index = link+1;
btVector3 posr = local_origin[index];
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
btScalar quat[4]={-world_to_local[index].x(),-world_to_local[index].y(),-world_to_local[index].z(),world_to_local[index].w()};
btTransform tr;
tr.setIdentity();
tr.setOrigin(posr);
tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
col->setWorldTransform(tr);
}
}
} else
{
bod->clearVelocities();
}
}
}
}
void btMultiBodyDynamicsWorld::addMultiBodyConstraint( btMultiBodyConstraint* constraint)
{
m_multiBodyConstraints.push_back(constraint);
}
void btMultiBodyDynamicsWorld::removeMultiBodyConstraint( btMultiBodyConstraint* constraint)
{
m_multiBodyConstraints.remove(constraint);
}
void btMultiBodyDynamicsWorld::debugDrawMultiBodyConstraint(btMultiBodyConstraint* constraint)
{
constraint->debugDraw(getDebugDrawer());
}
void btMultiBodyDynamicsWorld::debugDrawWorld()
{
BT_PROFILE("btMultiBodyDynamicsWorld debugDrawWorld");
bool drawConstraints = false;
if (getDebugDrawer())
{
int mode = getDebugDrawer()->getDebugMode();
if (mode & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits))
{
drawConstraints = true;
}
if (drawConstraints)
{
BT_PROFILE("btMultiBody debugDrawWorld");
btAlignedObjectArray<btQuaternion> world_to_local;
btAlignedObjectArray<btVector3> local_origin;
for (int c=0;c<m_multiBodyConstraints.size();c++)
{
btMultiBodyConstraint* constraint = m_multiBodyConstraints[c];
debugDrawMultiBodyConstraint(constraint);
}
for (int b = 0; b<m_multiBodies.size(); b++)
{
btMultiBody* bod = m_multiBodies[b];
int nLinks = bod->getNumLinks();
///base + num m_links
world_to_local.resize(nLinks + 1);
local_origin.resize(nLinks + 1);
world_to_local[0] = bod->getWorldToBaseRot();
local_origin[0] = bod->getBasePos();
{
btVector3 posr = local_origin[0];
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
btScalar quat[4] = { -world_to_local[0].x(), -world_to_local[0].y(), -world_to_local[0].z(), world_to_local[0].w() };
btTransform tr;
tr.setIdentity();
tr.setOrigin(posr);
tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3]));
getDebugDrawer()->drawTransform(tr, 0.1);
}
for (int k = 0; k<bod->getNumLinks(); k++)
{
const int parent = bod->getParent(k);
world_to_local[k + 1] = bod->getParentToLocalRot(k) * world_to_local[parent + 1];
local_origin[k + 1] = local_origin[parent + 1] + (quatRotate(world_to_local[k + 1].inverse(), bod->getRVector(k)));
}
for (int m = 0; m<bod->getNumLinks(); m++)
{
int link = m;
int index = link + 1;
btVector3 posr = local_origin[index];
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
btScalar quat[4] = { -world_to_local[index].x(), -world_to_local[index].y(), -world_to_local[index].z(), world_to_local[index].w() };
btTransform tr;
tr.setIdentity();
tr.setOrigin(posr);
tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3]));
getDebugDrawer()->drawTransform(tr, 0.1);
}
}
}
}
btDiscreteDynamicsWorld::debugDrawWorld();
}
| LauriM/PropellerEngine | thirdparty/Bullet/src/BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.cpp | C++ | bsd-2-clause | 27,139 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
return [
'code' => '672',
'patterns' => [
'national' => [
'general' => '/^[13]\\d{5}$/',
'fixed' => '/^(?:1(?:06|17|28|39)|3[012]\\d)\\d{3}$/',
'mobile' => '/^38\\d{4}$/',
'emergency' => '/^9(?:11|55|77)$/',
],
'possible' => [
'general' => '/^\\d{5,6}$/',
'emergency' => '/^\\d{3}$/',
],
],
];
| Urbannet/cleanclean | yii2/vendor/zendframework/zend-i18n/src/Validator/PhoneNumber/NF.php | PHP | bsd-3-clause | 720 |
<?php
require_once('../../config.php');
require_once('lib.php');
require_once('edit_form.php');
$cmid = required_param('cmid', PARAM_INT); // Course Module ID
$id = optional_param('id', 0, PARAM_INT); // EntryID
if (!$cm = get_coursemodule_from_id('glossary', $cmid)) {
print_error('invalidcoursemodule');
}
if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
print_error('coursemisconf');
}
require_login($course, false, $cm);
$context = context_module::instance($cm->id);
if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
print_error('invalidid', 'glossary');
}
$url = new moodle_url('/mod/glossary/edit.php', array('cmid'=>$cm->id));
if (!empty($id)) {
$url->param('id', $id);
}
$PAGE->set_url($url);
if ($id) { // if entry is specified
if (isguestuser()) {
print_error('guestnoedit', 'glossary', "$CFG->wwwroot/mod/glossary/view.php?id=$cmid");
}
if (!$entry = $DB->get_record('glossary_entries', array('id'=>$id, 'glossaryid'=>$glossary->id))) {
print_error('invalidentry');
}
$ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
if (!has_capability('mod/glossary:manageentries', $context) and !($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context)))) {
if ($USER->id != $entry->userid) {
print_error('errcannoteditothers', 'glossary', "view.php?id=$cm->id&mode=entry&hook=$id");
} elseif (!$ineditperiod) {
print_error('erredittimeexpired', 'glossary', "view.php?id=$cm->id&mode=entry&hook=$id");
}
}
//prepare extra data
if ($aliases = $DB->get_records_menu("glossary_alias", array("entryid"=>$id), '', 'id, alias')) {
$entry->aliases = implode("\n", $aliases) . "\n";
}
if ($categoriesarr = $DB->get_records_menu("glossary_entries_categories", array('entryid'=>$id), '', 'id, categoryid')) {
// TODO: this fetches cats from both main and secondary glossary :-(
$entry->categories = array_values($categoriesarr);
}
} else { // new entry
require_capability('mod/glossary:write', $context);
// note: guest user does not have any write capability
$entry = new stdClass();
$entry->id = null;
}
list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry);
$entry = file_prepare_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry', $entry->id);
$entry = file_prepare_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary', 'attachment', $entry->id);
$entry->cmid = $cm->id;
// create form and set initial data
$mform = new mod_glossary_entry_form(null, array('current'=>$entry, 'cm'=>$cm, 'glossary'=>$glossary,
'definitionoptions'=>$definitionoptions, 'attachmentoptions'=>$attachmentoptions));
if ($mform->is_cancelled()){
if ($id){
redirect("view.php?id=$cm->id&mode=entry&hook=$id");
} else {
redirect("view.php?id=$cm->id");
}
} else if ($data = $mform->get_data()) {
$entry = glossary_edit_entry($data, $course, $cm, $glossary, $context);
if (core_tag_tag::is_enabled('mod_glossary', 'glossary_entries') && isset($data->tags)) {
core_tag_tag::set_item_tags('mod_glossary', 'glossary_entries', $data->id, $context, $data->tags);
}
redirect("view.php?id=$cm->id&mode=entry&hook=$entry->id");
}
if (!empty($id)) {
$PAGE->navbar->add(get_string('edit'));
}
$PAGE->set_title($glossary->name);
$PAGE->set_heading($course->fullname);
echo $OUTPUT->header();
echo $OUTPUT->heading(format_string($glossary->name), 2);
if ($glossary->intro) {
echo $OUTPUT->box(format_module_intro('glossary', $glossary, $cm->id), 'generalbox', 'intro');
}
$data = new StdClass();
$data->tags = core_tag_tag::get_item_tags_array('mod_glossary', 'glossary_entries', $id);
$mform->set_data($data);
$mform->display();
echo $OUTPUT->footer();
| evltuma/moodle | mod/glossary/edit.php | PHP | gpl-3.0 | 4,125 |
// Copyright 2013 the V8 project authors. All rights reserved.
// Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
description(
"This test checks that the following expressions or statements are valid ECMASCRIPT code or should throw parse error"
);
function runTest(_a, errorType)
{
var success;
if (typeof _a != "string")
testFailed("runTest expects string argument: " + _a);
try {
eval(_a);
success = true;
} catch (e) {
success = !(e instanceof SyntaxError);
}
if ((!!errorType) == !success) {
if (errorType)
testPassed('Invalid: "' + _a + '"');
else
testPassed('Valid: "' + _a + '"');
} else {
if (errorType)
testFailed('Invalid: "' + _a + '" should throw ' + errorType.name);
else
testFailed('Valid: "' + _a + '" should NOT throw ');
}
}
function valid(_a)
{
// Test both the grammar and the syntax checker
runTest(_a, false);
runTest("function f() { " + _a + " }", false);
}
function invalid(_a, _type)
{
_type = _type || SyntaxError;
// Test both the grammar and the syntax checker
runTest(_a, true);
runTest("function f() { " + _a + " }", true);
}
// known issue:
// some statements requires statement as argument, and
// it seems the End-Of-File terminator is converted to semicolon
// "a:[EOF]" is not parse error, while "{ a: }" is parse error
// "if (a)[EOF]" is not parse error, while "{ if (a) }" is parse error
// known issues of bison parser:
// accepts: 'function f() { return 6 + }' (only inside a function declaration)
// some comma expressions: see reparsing-semicolon-insertion.js
debug ("Unary operators and member access");
valid ("");
invalid("(a");
invalid("a[5");
invalid("a[5 + 6");
invalid("a.");
invalid("()");
invalid("a.'l'");
valid ("a: +~!new a");
invalid("new -a");
valid ("new (-1)")
valid ("a: b: c: new f(x++)++")
valid ("(a)++");
valid ("(1--).x");
invalid("a-- ++");
invalid("(a:) --b");
valid ("++ -- ++ a");
valid ("++ new new a ++");
valid ("delete void 0");
invalid("delete the void");
invalid("(a++");
valid ("++a--");
valid ("++((a))--");
valid ("(a.x++)++");
invalid("1: null");
invalid("+-!~");
invalid("+-!~((");
invalid("a)");
invalid("a]");
invalid(".l");
invalid("1.l");
valid ("1 .l");
debug ("Binary and conditional operators");
valid ("a + + typeof this");
invalid("a + * b");
invalid("a ? b");
invalid("a ? b :");
invalid("%a");
invalid("a-");
valid ("a = b ? b = c : d = e");
valid ("s: a[1].l ? b.l['s'] ? c++ : d : true");
valid ("a ? b + 1 ? c + 3 * d.l : d[5][6] : e");
valid ("a in b instanceof delete -c");
invalid("a in instanceof b.l");
valid ("- - true % 5");
invalid("- false = 3");
valid ("a: b: c: (1 + null) = 3");
valid ("a[2] = b.l += c /= 4 * 7 ^ !6");
invalid("a + typeof b += c in d");
invalid("typeof a &= typeof b");
valid ("a: ((typeof (a))) >>>= a || b.l && c");
valid ("a: b: c[a /= f[a %= b]].l[c[x] = 7] -= a ? b <<= f : g");
valid ("-void+x['y'].l == x.l != 5 - f[7]");
debug ("Function calls (and new with arguments)");
valid ("a()()()");
valid ("s: l: a[2](4 == 6, 5 = 6)(f[4], 6)");
valid ("s: eval(a.apply(), b.call(c[5] - f[7]))");
invalid("a(");
invalid("a(5");
invalid("a(5,");
invalid("a(5,)");
invalid("a(5,6");
valid ("a(b[7], c <d> e.l, new a() > b)");
invalid("a(b[5)");
invalid("a(b.)");
valid ("~new new a(1)(i++)(c[l])");
invalid("a(*a)");
valid ("((((a))((b)()).l))()");
valid ("(a)[b + (c) / (d())].l--");
valid ("new (5)");
invalid("new a(5");
valid ("new (f + 5)(6, (g)() - 'l'() - true(false))");
invalid("a(.length)");
debug ("function declaration and expression");
valid ("function f() {}");
valid ("function f(a,b) {}");
invalid("function () {}");
invalid("function f(a b) {}");
invalid("function f(a,) {}");
invalid("function f(a,");
invalid("function f(a, 1) {}");
valid ("function g(arguments, eval) {}");
valid ("function f() {} + function g() {}");
invalid("(function a{})");
invalid("(function this(){})");
valid ("(delete new function f(){} + function(a,b){}(5)(6))");
valid ("6 - function (m) { function g() {} }");
invalid("function l() {");
invalid("function l++(){}");
debug ("Array and object literal, comma operator");
// Note these are tested elsewhere, no need to repeat those tests here
valid ("[] in [5,6] * [,5,] / [,,5,,] || [a,] && new [,b] % [,,]");
invalid("[5,");
invalid("[,");
invalid("(a,)");
valid ("1 + {get get(){}, set set(a){}, get1:4, set1:get-set, }");
invalid("1 + {a");
invalid("1 + {a:");
invalid("1 + {get l(");
invalid(",a");
valid ("(4,(5,a(3,4))),f[4,a-6]");
invalid("(,f)");
invalid("a,,b");
invalid("a ? b, c : d");
debug ("simple statements");
valid ("{ }");
invalid("{ { }");
valid ("{ ; ; ; }");
valid ("a: { ; }");
invalid("{ a: }");
valid ("{} f; { 6 + f() }");
valid ("{ a[5],6; {} ++b-new (-5)() } c().l++");
valid ("{ l1: l2: l3: { this } a = 32 ; { i++ ; { { { } } ++i } } }");
valid ("if (a) ;");
invalid("{ if (a) }");
invalid("if a {}");
invalid("if (a");
invalid("if (a { }");
valid ("x: s: if (a) ; else b");
invalid("else {}");
valid ("if (a) if (b) y; else {} else ;");
invalid("if (a) {} else x; else");
invalid("if (a) { else }");
valid ("if (a.l + new b()) 4 + 5 - f()");
valid ("if (a) with (x) ; else with (y) ;");
invalid("with a.b { }");
valid ("while (a() - new b) ;");
invalid("while a {}");
valid ("do ; while(0) i++"); // Is this REALLY valid? (Firefox also accepts this)
valid ("do if (a) x; else y; while(z)");
invalid("do g; while 4");
invalid("do g; while ((4)");
valid ("{ { do do do ; while(0) while(0) while(0) } }");
valid ("do while (0) if (a) {} else y; while(0)");
valid ("if (a) while (b) if (c) with(d) {} else e; else f");
invalid("break ; break your_limits ; continue ; continue living ; debugger");
invalid("debugger X");
invalid("break 0.2");
invalid("continue a++");
invalid("continue (my_friend)");
valid ("while (1) break");
valid ("do if (a) with (b) continue; else debugger; while (false)");
invalid("do if (a) while (false) else debugger");
invalid("while if (a) ;");
valid ("if (a) function f() {} else function g() {}");
valid ("if (a()) while(0) function f() {} else function g() {}");
invalid("if (a()) function f() { else function g() }");
invalid("if (a) if (b) ; else function f {}");
invalid("if (a) if (b) ; else function (){}");
valid ("throw a");
valid ("throw a + b in void c");
invalid("throw");
debug ("var and const statements");
valid ("var a, b = null");
valid ("const a = 5, b, c");
invalid("var");
invalid("var = 7");
invalid("var c (6)");
valid ("if (a) var a,b; else const b, c");
invalid("var 5 = 6");
valid ("while (0) var a, b, c=6, d, e, f=5*6, g=f*h, h");
invalid("var a = if (b) { c }");
invalid("var a = var b");
valid ("const a = b += c, a, a, a = (b - f())");
invalid("var a %= b | 5");
invalid("var (a) = 5");
invalid("var a = (4, b = 6");
invalid("const 'l' = 3");
invalid("var var = 3");
valid ("var varr = 3 in 1");
valid ("const a, a, a = void 7 - typeof 8, a = 8");
valid ("const x_x = 6 /= 7 ? e : f");
invalid("var a = ?");
invalid("const a = *7");
invalid("var a = :)");
valid ("var a = a in b in c instanceof d");
invalid("var a = b ? c, b");
invalid("const a = b : c");
debug ("for statement");
valid ("for ( ; ; ) { break }");
valid ("for ( a ; ; ) { break }");
valid ("for ( ; a ; ) { break }");
valid ("for ( ; ; a ) { break }");
valid ("for ( a ; a ; ) break");
valid ("for ( a ; ; a ) break");
valid ("for ( ; a ; a ) break");
invalid("for () { }");
invalid("for ( a ) { }");
invalid("for ( ; ) ;");
invalid("for a ; b ; c { }");
invalid("for (a ; { }");
invalid("for ( a ; ) ;");
invalid("for ( ; a ) break");
valid ("for (var a, b ; ; ) { break } ");
valid ("for (var a = b, b = a ; ; ) break");
valid ("for (var a = b, c, d, b = a ; x in b ; ) { break }");
valid ("for (var a = b, c, d ; ; 1 in a()) break");
invalid("for ( ; var a ; ) break");
invalid("for (const a; ; ) break");
invalid("for ( %a ; ; ) { }");
valid ("for (a in b) break");
valid ("for (a() in b) break");
valid ("for (a().l[4] in b) break");
valid ("for (new a in b in c in d) break");
valid ("for (new new new a in b) break");
invalid("for (delete new a() in b) break");
invalid("for (a * a in b) break");
valid ("for ((a * a) in b) break");
invalid("for (a++ in b) break");
valid ("for ((a++) in b) break");
invalid("for (++a in b) break");
valid ("for ((++a) in b) break");
invalid("for (a, b in c) break");
invalid("for (a,b in c ;;) break");
valid ("for (a,(b in c) ;;) break");
valid ("for ((a, b) in c) break");
invalid("for (a ? b : c in c) break");
valid ("for ((a ? b : c) in c) break");
valid ("for (var a in b in c) break");
valid ("for (var a = 5 += 6 in b) break");
invalid("for (var a += 5 in b) break");
invalid("for (var a = in b) break");
invalid("for (var a, b in b) break");
invalid("for (var a = -6, b in b) break");
invalid("for (var a, b = 8 in b) break");
valid ("for (var a = (b in c) in d) break");
invalid("for (var a = (b in c in d) break");
invalid("for (var (a) in b) { }");
valid ("for (var a = 7, b = c < d >= d ; f()[6]++ ; --i()[1]++ ) {}");
debug ("try statement");
invalid("try { break } catch(e) {}");
valid ("try {} finally { c++ }");
valid ("try { with (x) { } } catch(e) {} finally { if (a) ; }");
invalid("try {}");
invalid("catch(e) {}");
invalid("finally {}");
invalid("try a; catch(e) {}");
invalid("try {} catch(e) a()");
invalid("try {} finally a()");
invalid("try {} catch(e)");
invalid("try {} finally");
invalid("try {} finally {} catch(e) {}");
invalid("try {} catch (...) {}");
invalid("try {} catch {}");
valid ("if (a) try {} finally {} else b;");
valid ("if (--a()) do with(1) try {} catch(ke) { f() ; g() } while (a in b) else {}");
invalid("if (a) try {} else b; catch (e) { }");
invalid("try { finally {}");
debug ("switch statement");
valid ("switch (a) {}");
invalid("switch () {}");
invalid("case 5:");
invalid("default:");
invalid("switch (a) b;");
invalid("switch (a) case 3: b;");
valid ("switch (f()) { case 5 * f(): default: case '6' - 9: ++i }");
invalid("switch (true) { default: case 6: default: }");
invalid("switch (l) { f(); }");
invalid("switch (l) { case 1: ; a: case 5: }");
valid ("switch (g() - h[5].l) { case 1 + 6: a: b: c: ++f }");
invalid("switch (g) { case 1: a: }");
invalid("switch (g) { case 1: a: default: }");
invalid("switch g { case 1: l() }");
invalid("switch (g) { case 1:");
valid ("switch (l) { case a = b ? c : d : }");
valid ("switch (sw) { case a ? b - 7[1] ? [c,,] : d = 6 : { } : }");
invalid("switch (l) { case b ? c : }");
valid ("switch (l) { case 1: a: with(g) switch (g) { case 2: default: } default: }");
invalid("switch (4 - ) { }");
invalid("switch (l) { default case: 5; }");
invalid("L: L: ;");
invalid("L: L1: L: ;");
invalid("L: L1: L2: L3: L4: L: ;");
invalid("for(var a,b 'this shouldn\'t be allowed' false ; ) ;");
invalid("for(var a,b '");
valid("function __proto__(){}")
valid("(function __proto__(){})")
valid("'use strict'; function __proto__(){}")
valid("'use strict'; (function __proto__(){})")
valid("if (0) $foo; ")
valid("if (0) _foo; ")
valid("if (0) foo$; ")
valid("if (0) foo_; ")
valid("if (0) obj.$foo; ")
valid("if (0) obj._foo; ")
valid("if (0) obj.foo$; ")
valid("if (0) obj.foo_; ")
valid("if (0) obj.foo\\u03bb; ")
valid("if (0) new a(b+c).d = 5");
valid("if (0) new a(b+c) = 5");
valid("([1 || 1].a = 1)");
valid("({a: 1 || 1}.a = 1)");
invalid("var a.b = c");
invalid("var a.b;");
try { eval("a.b.c = {};"); } catch(e1) { e=e1; shouldBe("e.line", "1") }
foo = 'FAIL';
bar = 'PASS';
try {
eval("foo = 'PASS'; a.b.c = {}; bar = 'FAIL';");
} catch(e) {
shouldBe("foo", "'PASS'");
shouldBe("bar", "'PASS'");
}
| victorzhao/miniblink49 | v8_4_5/test/webkit/fast/js/parser-syntax-check.js | JavaScript | gpl-3.0 | 13,137 |
require File.expand_path('../../../spec_helper', __FILE__)
require 'date'
describe "Date.ajd_to_amjd" do
it "needs to be reviewed for spec completeness"
end
| takano32/rubinius | spec/ruby/library/date/ajd_to_amjd_spec.rb | Ruby | bsd-3-clause | 160 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Abstract class for the transformations plugins
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/* It also implements the transformations interface */
require_once 'TransformationsInterface.int.php';
/**
* Provides a common interface that will have to
* be implemented by all of the transformations plugins.
*
* @package PhpMyAdmin
*/
abstract class TransformationsPlugin implements TransformationsInterface
{
/**
* Does the actual work of each specific transformations plugin.
*
* @param array $options transformation options
*
* @return void
*/
public function applyTransformationNoWrap($options = array())
{
;
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param string $meta meta information
*
* @return string the transformed text
*/
abstract public function applyTransformation(
$buffer, $options = array(), $meta = ''
);
/**
* Returns passed options or default values if they were not set
*
* @param string[] $options List of passed options
* @param string[] $defaults List of default values
*
* @return string[] List of options possibly filled in by defaults.
*/
public function getOptions($options, $defaults)
{
$result = array();
foreach ($defaults as $key => $value) {
if (isset($options[$key]) && $options[$key] !== '') {
$result[$key] = $options[$key];
} else {
$result[$key] = $value;
}
}
return $result;
}
}
| Dokaponteam/ITF_Project | xampp/phpMyAdmin/libraries/plugins/TransformationsPlugin.class.php | PHP | mit | 1,804 |
<?php
/*************************************************************************************
* m68k.php
* --------
* Author: Benny Baumann (BenBE@omorphia.de)
* Copyright: (c) 2007 Benny Baumann (http://www.omorphia.de/), Nigel McNie (http://qbnz.com/highlighter)
* Release Version: 1.0.8.11
* Date Started: 2007/02/06
*
* Motorola 68000 Assembler language file for GeSHi.
*
* Syntax definition as commonly used by the motorola documentation for the
* MC68HC908GP32 Microcontroller (and maybe others).
*
* CHANGES
* -------
* 2008/05/23 (1.0.7.22)
* - Added description of extra language features (SF#1970248)
* 2007/06/02 (1.0.0)
* - First Release
*
* TODO (updated 2007/06/02)
* -------------------------
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GeSHi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/
$language_data = array (
'LANG_NAME' => 'Motorola 68000 Assembler',
'COMMENT_SINGLE' => array(1 => ';'),
'COMMENT_MULTI' => array(),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '',
'KEYWORDS' => array(
/*CPU*/
1 => array(
'adc','add','ais','aix','and','asl','asr','bcc','bclr','bcs','beq',
'bge','bgt','bhcc','bhcs','bhi','bhs','bih','bil','bit','ble','blo',
'bls','blt','bmc','bmi','bms','bne','bpl','bra','brclr','brn',
'brset','bset','bsr','cbeq','clc','cli','clr','cmp','com','cphx',
'cpx','daa','dbnz','dec','div','eor','inc','jmp','jsr','lda','ldhx',
'ldx','lsl','lsr','mov','mul','neg','nop','nsa','ora','psha','pshh',
'pshx','pula','pulh','pulx','rol','ror','rsp','rti','rts','sbc',
'sec','sei','sta','sthx','stop','stx','sub','swi','tap','tax','tpa',
'tst','tsx','txa','txs','wait'
),
/*registers*/
2 => array(
'a','h','x',
'hx','sp'
),
/*Directive*/
3 => array(
'#define','#endif','#else','#ifdef','#ifndef','#include','#undef',
'.db','.dd','.df','.dq','.dt','.dw','.end','.org','equ'
),
),
'SYMBOLS' => array(
','
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false,
1 => false,
2 => false,
3 => false,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #0000ff; font-weight:bold;',
2 => 'color: #0000ff;',
3 => 'color: #46aa03; font-weight:bold;'
),
'COMMENTS' => array(
1 => 'color: #adadad; font-style: italic;',
),
'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;'
),
'BRACKETS' => array(
0 => 'color: #0000ff;'
),
'STRINGS' => array(
0 => 'color: #7f007f;'
),
'NUMBERS' => array(
0 => 'color: #dd22dd;'
),
'METHODS' => array(
),
'SYMBOLS' => array(
0 => 'color: #008000;'
),
'REGEXPS' => array(
0 => 'color: #22bbff;',
1 => 'color: #22bbff;',
2 => 'color: #993333;'
),
'SCRIPT' => array(
)
),
'URLS' => array(
1 => '',
2 => '',
3 => ''
),
'OOLANG' => false,
'OBJECT_SPLITTERS' => array(
),
'REGEXPS' => array(
//Hex numbers
0 => '#?0[0-9a-fA-F]{1,32}[hH]',
//Binary numbers
1 => '\%[01]{1,64}[bB]',
//Labels
2 => '^[_a-zA-Z][_a-zA-Z0-9]*?\:'
),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(
),
'HIGHLIGHT_STRICT_BLOCK' => array(
),
'TAB_WIDTH' => 8
);
| MinecraftSnowServer/Server-Docker | web/wiki/vendor/easybook/geshi/geshi/m68k.php | PHP | mit | 4,666 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.portal.api;
import java.util.List;
import java.util.Map;
import org.sakaiproject.site.api.Site;
/**
* @author ieb
*
*/
public interface PageFilter
{
/**
* @param newPages
* @param site
* @return
*/
List filter(List newPages, Site site);
/**
* Filter the list of placements, potentially making them hierachical if required
* @param l
* @param site
* @return
*/
List<Map> filterPlacements(List<Map> l, Site site);
}
| bzhouduke123/sakai | portal/portal-api/api/src/java/org/sakaiproject/portal/api/PageFilter.java | Java | apache-2.0 | 1,396 |
#!/usr/bin/env node
var DocGenerator = require('../lib/utilities/doc-generator.js');
(new DocGenerator()).generate();
| waddedMeat/ember-proxy-example | test-app/node_modules/ember-cli/bin/generate-docs.js | JavaScript | mit | 119 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "quuid.h"
#include "qdatastream.h"
#include "qendian.h"
#include "qdebug.h"
#ifndef QT_BOOTSTRAPPED
#include "qcryptographichash.h"
#endif
QT_BEGIN_NAMESPACE
static const char digits[] = "0123456789abcdef";
template <class Char, class Integral>
void _q_toHex(Char *&dst, Integral value)
{
value = qToBigEndian(value);
const char* p = reinterpret_cast<const char*>(&value);
for (uint i = 0; i < sizeof(Integral); ++i, dst += 2) {
uint j = (p[i] >> 4) & 0xf;
dst[0] = Char(digits[j]);
j = p[i] & 0xf;
dst[1] = Char(digits[j]);
}
}
template <class Char, class Integral>
bool _q_fromHex(const Char *&src, Integral &value)
{
value = 0;
for (uint i = 0; i < sizeof(Integral) * 2; ++i) {
int ch = *src++;
int tmp;
if (ch >= '0' && ch <= '9')
tmp = ch - '0';
else if (ch >= 'a' && ch <= 'f')
tmp = ch - 'a' + 10;
else if (ch >= 'A' && ch <= 'F')
tmp = ch - 'A' + 10;
else
return false;
value = value * 16 + tmp;
}
return true;
}
template <class Char>
void _q_uuidToHex(Char *&dst, const uint &d1, const ushort &d2, const ushort &d3, const uchar (&d4)[8])
{
*dst++ = Char('{');
_q_toHex(dst, d1);
*dst++ = Char('-');
_q_toHex(dst, d2);
*dst++ = Char('-');
_q_toHex(dst, d3);
*dst++ = Char('-');
for (int i = 0; i < 2; i++)
_q_toHex(dst, d4[i]);
*dst++ = Char('-');
for (int i = 2; i < 8; i++)
_q_toHex(dst, d4[i]);
*dst = Char('}');
}
template <class Char>
bool _q_uuidFromHex(const Char *&src, uint &d1, ushort &d2, ushort &d3, uchar (&d4)[8])
{
if (*src == Char('{'))
src++;
if (!_q_fromHex(src, d1)
|| *src++ != Char('-')
|| !_q_fromHex(src, d2)
|| *src++ != Char('-')
|| !_q_fromHex(src, d3)
|| *src++ != Char('-')
|| !_q_fromHex(src, d4[0])
|| !_q_fromHex(src, d4[1])
|| *src++ != Char('-')
|| !_q_fromHex(src, d4[2])
|| !_q_fromHex(src, d4[3])
|| !_q_fromHex(src, d4[4])
|| !_q_fromHex(src, d4[5])
|| !_q_fromHex(src, d4[6])
|| !_q_fromHex(src, d4[7])) {
return false;
}
return true;
}
#ifndef QT_BOOTSTRAPPED
static QUuid createFromName(const QUuid &ns, const QByteArray &baseData, QCryptographicHash::Algorithm algorithm, int version)
{
QByteArray hashResult;
// create a scope so later resize won't reallocate
{
QCryptographicHash hash(algorithm);
hash.addData(ns.toRfc4122());
hash.addData(baseData);
hashResult = hash.result();
}
hashResult.resize(16); // Sha1 will be too long
QUuid result = QUuid::fromRfc4122(hashResult);
result.data3 &= 0x0FFF;
result.data3 |= (version << 12);
result.data4[0] &= 0x3F;
result.data4[0] |= 0x80;
return result;
}
#endif
/*!
\class QUuid
\inmodule QtCore
\brief The QUuid class stores a Universally Unique Identifier (UUID).
\reentrant
Using \e{U}niversally \e{U}nique \e{ID}entifiers (UUID) is a
standard way to uniquely identify entities in a distributed
computing environment. A UUID is a 16-byte (128-bit) number
generated by some algorithm that is meant to guarantee that the
UUID will be unique in the distributed computing environment where
it is used. The acronym GUID is often used instead, \e{G}lobally
\e{U}nique \e{ID}entifiers, but it refers to the same thing.
\target Variant field
Actually, the GUID is one \e{variant} of UUID. Multiple variants
are in use. Each UUID contains a bit field that specifies which
type (variant) of UUID it is. Call variant() to discover which
type of UUID an instance of QUuid contains. It extracts the three
most significant bits of byte 8 of the 16 bytes. In QUuid, byte 8
is \c{QUuid::data4[0]}. If you create instances of QUuid using the
constructor that accepts all the numeric values as parameters, use
the following table to set the three most significant bits of
parameter \c{b1}, which becomes \c{QUuid::data4[0]} and contains
the variant field in its three most significant bits. In the
table, 'x' means \e {don't care}.
\table
\header
\li msb0
\li msb1
\li msb2
\li Variant
\row
\li 0
\li x
\li x
\li NCS (Network Computing System)
\row
\li 1
\li 0
\li x
\li DCE (Distributed Computing Environment)
\row
\li 1
\li 1
\li 0
\li Microsoft (GUID)
\row
\li 1
\li 1
\li 1
\li Reserved for future expansion
\endtable
\target Version field
If variant() returns QUuid::DCE, the UUID also contains a
\e{version} field in the four most significant bits of
\c{QUuid::data3}, and you can call version() to discover which
version your QUuid contains. If you create instances of QUuid
using the constructor that accepts all the numeric values as
parameters, use the following table to set the four most
significant bits of parameter \c{w2}, which becomes
\c{QUuid::data3} and contains the version field in its four most
significant bits.
\table
\header
\li msb0
\li msb1
\li msb2
\li msb3
\li Version
\row
\li 0
\li 0
\li 0
\li 1
\li Time
\row
\li 0
\li 0
\li 1
\li 0
\li Embedded POSIX
\row
\li 0
\li 0
\li 1
\li 1
\li Md5(Name)
\row
\li 0
\li 1
\li 0
\li 0
\li Random
\row
\li 0
\li 1
\li 0
\li 1
\li Sha1
\endtable
The field layouts for the DCE versions listed in the table above
are specified in the \l{http://www.ietf.org/rfc/rfc4122.txt}
{Network Working Group UUID Specification}.
Most platforms provide a tool for generating new UUIDs, e.g. \c
uuidgen and \c guidgen. You can also use createUuid(). UUIDs
generated by createUuid() are of the random type. Their
QUuid::Version bits are set to QUuid::Random, and their
QUuid::Variant bits are set to QUuid::DCE. The rest of the UUID is
composed of random numbers. Theoretically, this means there is a
small chance that a UUID generated by createUuid() will not be
unique. But it is
\l{http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Random_UUID_probability_of_duplicates}
{a \e{very} small chance}.
UUIDs can be constructed from numeric values or from strings, or
using the static createUuid() function. They can be converted to a
string with toString(). UUIDs have a variant() and a version(),
and null UUIDs return true from isNull().
*/
/*!
\fn QUuid::QUuid(const GUID &guid)
Casts a Windows \a guid to a Qt QUuid.
\warning This function is only for Windows platforms.
*/
/*!
\fn QUuid &QUuid::operator=(const GUID &guid)
Assigns a Windows \a guid to a Qt QUuid.
\warning This function is only for Windows platforms.
*/
/*!
\fn QUuid::operator GUID() const
Returns a Windows GUID from a QUuid.
\warning This function is only for Windows platforms.
*/
/*!
\fn QUuid::QUuid()
Creates the null UUID. toString() will output the null UUID
as "{00000000-0000-0000-0000-000000000000}".
*/
/*!
\fn QUuid::QUuid(uint l, ushort w1, ushort w2, uchar b1, uchar b2, uchar b3, uchar b4, uchar b5, uchar b6, uchar b7, uchar b8)
Creates a UUID with the value specified by the parameters, \a l,
\a w1, \a w2, \a b1, \a b2, \a b3, \a b4, \a b5, \a b6, \a b7, \a
b8.
Example:
\snippet code/src_corelib_plugin_quuid.cpp 0
*/
/*!
Creates a QUuid object from the string \a text, which must be
formatted as five hex fields separated by '-', e.g.,
"{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex
digit. The curly braces shown here are optional, but it is normal to
include them. If the conversion fails, a null UUID is created. See
toString() for an explanation of how the five hex fields map to the
public data members in QUuid.
\sa toString(), QUuid()
*/
QUuid::QUuid(const QString &text)
{
if (text.length() < 36) {
*this = QUuid();
return;
}
const ushort *data = reinterpret_cast<const ushort *>(text.unicode());
if (*data == '{' && text.length() < 37) {
*this = QUuid();
return;
}
if (!_q_uuidFromHex(data, data1, data2, data3, data4)) {
*this = QUuid();
return;
}
}
/*!
\internal
*/
QUuid::QUuid(const char *text)
{
if (!text) {
*this = QUuid();
return;
}
if (!_q_uuidFromHex(text, data1, data2, data3, data4)) {
*this = QUuid();
return;
}
}
/*!
Creates a QUuid object from the QByteArray \a text, which must be
formatted as five hex fields separated by '-', e.g.,
"{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex
digit. The curly braces shown here are optional, but it is normal to
include them. If the conversion fails, a null UUID is created. See
toByteArray() for an explanation of how the five hex fields map to the
public data members in QUuid.
\since 4.8
\sa toByteArray(), QUuid()
*/
QUuid::QUuid(const QByteArray &text)
{
if (text.length() < 36) {
*this = QUuid();
return;
}
const char *data = text.constData();
if (*data == '{' && text.length() < 37) {
*this = QUuid();
return;
}
if (!_q_uuidFromHex(data, data1, data2, data3, data4)) {
*this = QUuid();
return;
}
}
/*!
\since 5.0
\fn QUuid QUuid::createUuidV3(const QUuid &ns, const QByteArray &baseData);
This function returns a new UUID with variant QUuid::DCE and version QUuid::Md5.
\a ns is the namespace and \a baseData is the basic data as described by RFC 4122.
\sa variant(), version(), createUuidV5()
*/
/*!
\since 5.0
\fn QUuid QUuid::createUuidV3(const QUuid &ns, const QString &baseData);
This function returns a new UUID with variant QUuid::DCE and version QUuid::Md5.
\a ns is the namespace and \a baseData is the basic data as described by RFC 4122.
\sa variant(), version(), createUuidV5()
*/
/*!
\since 5.0
\fn QUuid QUuid::createUuidV5(const QUuid &ns, const QByteArray &baseData);
This function returns a new UUID with variant QUuid::DCE and version QUuid::Sha1.
\a ns is the namespace and \a baseData is the basic data as described by RFC 4122.
\sa variant(), version(), createUuidV3()
*/
/*!
\since 5.0
\fn QUuid QUuid::createUuidV5(const QUuid &ns, const QString &baseData);
This function returns a new UUID with variant QUuid::DCE and version QUuid::Sha1.
\a ns is the namespace and \a baseData is the basic data as described by RFC 4122.
\sa variant(), version(), createUuidV3()
*/
#ifndef QT_BOOTSTRAPPED
QUuid QUuid::createUuidV3(const QUuid &ns, const QByteArray &baseData)
{
return createFromName(ns, baseData, QCryptographicHash::Md5, 3);
}
QUuid QUuid::createUuidV5(const QUuid &ns, const QByteArray &baseData)
{
return createFromName(ns, baseData, QCryptographicHash::Sha1, 5);
}
#endif
/*!
Creates a QUuid object from the binary representation of the UUID, as
specified by RFC 4122 section 4.1.2. See toRfc4122() for a further
explanation of the order of \a bytes required.
The byte array accepted is NOT a human readable format.
If the conversion fails, a null UUID is created.
\since 4.8
\sa toRfc4122(), QUuid()
*/
QUuid QUuid::fromRfc4122(const QByteArray &bytes)
{
if (bytes.isEmpty() || bytes.length() != 16)
return QUuid();
uint d1;
ushort d2, d3;
uchar d4[8];
const uchar *data = reinterpret_cast<const uchar *>(bytes.constData());
d1 = qFromBigEndian<quint32>(data);
data += sizeof(quint32);
d2 = qFromBigEndian<quint16>(data);
data += sizeof(quint16);
d3 = qFromBigEndian<quint16>(data);
data += sizeof(quint16);
for (int i = 0; i < 8; ++i) {
d4[i] = *(data);
data++;
}
return QUuid(d1, d2, d3, d4[0], d4[1], d4[2], d4[3], d4[4], d4[5], d4[6], d4[7]);
}
/*!
\fn bool QUuid::operator==(const QUuid &other) const
Returns \c true if this QUuid and the \a other QUuid are identical;
otherwise returns \c false.
*/
/*!
\fn bool QUuid::operator!=(const QUuid &other) const
Returns \c true if this QUuid and the \a other QUuid are different;
otherwise returns \c false.
*/
/*!
Returns the string representation of this QUuid. The string is
formatted as five hex fields separated by '-' and enclosed in
curly braces, i.e., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where
'x' is a hex digit. From left to right, the five hex fields are
obtained from the four public data members in QUuid as follows:
\table
\header
\li Field #
\li Source
\row
\li 1
\li data1
\row
\li 2
\li data2
\row
\li 3
\li data3
\row
\li 4
\li data4[0] .. data4[1]
\row
\li 5
\li data4[2] .. data4[7]
\endtable
*/
QString QUuid::toString() const
{
QString result(38, Qt::Uninitialized);
ushort *data = (ushort *)result.unicode();
_q_uuidToHex(data, data1, data2, data3, data4);
return result;
}
/*!
Returns the binary representation of this QUuid. The byte array is
formatted as five hex fields separated by '-' and enclosed in
curly braces, i.e., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where
'x' is a hex digit. From left to right, the five hex fields are
obtained from the four public data members in QUuid as follows:
\table
\header
\li Field #
\li Source
\row
\li 1
\li data1
\row
\li 2
\li data2
\row
\li 3
\li data3
\row
\li 4
\li data4[0] .. data4[1]
\row
\li 5
\li data4[2] .. data4[7]
\endtable
\since 4.8
*/
QByteArray QUuid::toByteArray() const
{
QByteArray result(38, Qt::Uninitialized);
char *data = result.data();
_q_uuidToHex(data, data1, data2, data3, data4);
return result;
}
/*!
Returns the binary representation of this QUuid. The byte array is in big
endian format, and formatted according to RFC 4122, section 4.1.2 -
"Layout and byte order".
The order is as follows:
\table
\header
\li Field #
\li Source
\row
\li 1
\li data1
\row
\li 2
\li data2
\row
\li 3
\li data3
\row
\li 4
\li data4[0] .. data4[7]
\endtable
\since 4.8
*/
QByteArray QUuid::toRfc4122() const
{
// we know how many bytes a UUID has, I hope :)
QByteArray bytes(16, Qt::Uninitialized);
uchar *data = reinterpret_cast<uchar*>(bytes.data());
qToBigEndian(data1, data);
data += sizeof(quint32);
qToBigEndian(data2, data);
data += sizeof(quint16);
qToBigEndian(data3, data);
data += sizeof(quint16);
for (int i = 0; i < 8; ++i) {
*(data) = data4[i];
data++;
}
return bytes;
}
#ifndef QT_NO_DATASTREAM
/*!
\relates QUuid
Writes the UUID \a id to the data stream \a s.
*/
QDataStream &operator<<(QDataStream &s, const QUuid &id)
{
QByteArray bytes;
if (s.byteOrder() == QDataStream::BigEndian) {
bytes = id.toRfc4122();
} else {
// we know how many bytes a UUID has, I hope :)
bytes = QByteArray(16, Qt::Uninitialized);
uchar *data = reinterpret_cast<uchar*>(bytes.data());
qToLittleEndian(id.data1, data);
data += sizeof(quint32);
qToLittleEndian(id.data2, data);
data += sizeof(quint16);
qToLittleEndian(id.data3, data);
data += sizeof(quint16);
for (int i = 0; i < 8; ++i) {
*(data) = id.data4[i];
data++;
}
}
if (s.writeRawData(bytes.data(), 16) != 16) {
s.setStatus(QDataStream::WriteFailed);
}
return s;
}
/*!
\relates QUuid
Reads a UUID from the stream \a s into \a id.
*/
QDataStream &operator>>(QDataStream &s, QUuid &id)
{
QByteArray bytes(16, Qt::Uninitialized);
if (s.readRawData(bytes.data(), 16) != 16) {
s.setStatus(QDataStream::ReadPastEnd);
return s;
}
if (s.byteOrder() == QDataStream::BigEndian) {
id = QUuid::fromRfc4122(bytes);
} else {
const uchar *data = reinterpret_cast<const uchar *>(bytes.constData());
id.data1 = qFromLittleEndian<quint32>(data);
data += sizeof(quint32);
id.data2 = qFromLittleEndian<quint16>(data);
data += sizeof(quint16);
id.data3 = qFromLittleEndian<quint16>(data);
data += sizeof(quint16);
for (int i = 0; i < 8; ++i) {
id.data4[i] = *(data);
data++;
}
}
return s;
}
#endif // QT_NO_DATASTREAM
/*!
Returns \c true if this is the null UUID
{00000000-0000-0000-0000-000000000000}; otherwise returns \c false.
*/
bool QUuid::isNull() const
{
return data4[0] == 0 && data4[1] == 0 && data4[2] == 0 && data4[3] == 0 &&
data4[4] == 0 && data4[5] == 0 && data4[6] == 0 && data4[7] == 0 &&
data1 == 0 && data2 == 0 && data3 == 0;
}
/*!
\enum QUuid::Variant
This enum defines the values used in the \l{Variant field}
{variant field} of the UUID. The value in the variant field
determines the layout of the 128-bit value.
\value VarUnknown Variant is unknown
\value NCS Reserved for NCS (Network Computing System) backward compatibility
\value DCE Distributed Computing Environment, the scheme used by QUuid
\value Microsoft Reserved for Microsoft backward compatibility (GUID)
\value Reserved Reserved for future definition
*/
/*!
\enum QUuid::Version
This enum defines the values used in the \l{Version field}
{version field} of the UUID. The version field is meaningful
only if the value in the \l{Variant field} {variant field}
is QUuid::DCE.
\value VerUnknown Version is unknown
\value Time Time-based, by using timestamp, clock sequence, and
MAC network card address (if available) for the node sections
\value EmbeddedPOSIX DCE Security version, with embedded POSIX UUIDs
\value Name Name-based, by using values from a name for all sections
\value Md5 Alias for Name
\value Random Random-based, by using random numbers for all sections
\value Sha1
*/
/*!
\fn QUuid::Variant QUuid::variant() const
Returns the value in the \l{Variant field} {variant field} of the
UUID. If the return value is QUuid::DCE, call version() to see
which layout it uses. The null UUID is considered to be of an
unknown variant.
\sa version()
*/
QUuid::Variant QUuid::variant() const
{
if (isNull())
return VarUnknown;
// Check the 3 MSB of data4[0]
if ((data4[0] & 0x80) == 0x00) return NCS;
else if ((data4[0] & 0xC0) == 0x80) return DCE;
else if ((data4[0] & 0xE0) == 0xC0) return Microsoft;
else if ((data4[0] & 0xE0) == 0xE0) return Reserved;
return VarUnknown;
}
/*!
\fn QUuid::Version QUuid::version() const
Returns the \l{Version field} {version field} of the UUID, if the
UUID's \l{Variant field} {variant field} is QUuid::DCE. Otherwise
it returns QUuid::VerUnknown.
\sa variant()
*/
QUuid::Version QUuid::version() const
{
// Check the 4 MSB of data3
Version ver = (Version)(data3>>12);
if (isNull()
|| (variant() != DCE)
|| ver < Time
|| ver > Sha1)
return VerUnknown;
return ver;
}
/*!
\fn bool QUuid::operator<(const QUuid &other) const
Returns \c true if this QUuid has the same \l{Variant field}
{variant field} as the \a other QUuid and is lexicographically
\e{before} the \a other QUuid. If the \a other QUuid has a
different variant field, the return value is determined by
comparing the two \l{QUuid::Variant} {variants}.
\sa variant()
*/
#define ISLESS(f1, f2) if (f1!=f2) return (f1<f2);
bool QUuid::operator<(const QUuid &other) const
{
if (variant() != other.variant())
return variant() < other.variant();
ISLESS(data1, other.data1);
ISLESS(data2, other.data2);
ISLESS(data3, other.data3);
for (int n = 0; n < 8; n++) {
ISLESS(data4[n], other.data4[n]);
}
return false;
}
/*!
\fn bool QUuid::operator>(const QUuid &other) const
Returns \c true if this QUuid has the same \l{Variant field}
{variant field} as the \a other QUuid and is lexicographically
\e{after} the \a other QUuid. If the \a other QUuid has a
different variant field, the return value is determined by
comparing the two \l{QUuid::Variant} {variants}.
\sa variant()
*/
#define ISMORE(f1, f2) if (f1!=f2) return (f1>f2);
bool QUuid::operator>(const QUuid &other) const
{
if (variant() != other.variant())
return variant() > other.variant();
ISMORE(data1, other.data1);
ISMORE(data2, other.data2);
ISMORE(data3, other.data3);
for (int n = 0; n < 8; n++) {
ISMORE(data4[n], other.data4[n]);
}
return false;
}
/*!
\fn QUuid QUuid::createUuid()
On any platform other than Windows, this function returns a new
UUID with variant QUuid::DCE and version QUuid::Random. If
the /dev/urandom device exists, then the numbers used to construct
the UUID will be of cryptographic quality, which will make the UUID
unique. Otherwise, the numbers of the UUID will be obtained from
the local pseudo-random number generator (qrand(), which is seeded
by qsrand()) which is usually not of cryptograhic quality, which
means that the UUID can't be guaranteed to be unique.
On a Windows platform, a GUID is generated, which almost certainly
\e{will} be unique, on this or any other system, networked or not.
\sa variant(), version()
*/
#if defined(Q_OS_WIN32)
QT_BEGIN_INCLUDE_NAMESPACE
#include <objbase.h> // For CoCreateGuid
QT_END_INCLUDE_NAMESPACE
QUuid QUuid::createUuid()
{
GUID guid;
CoCreateGuid(&guid);
QUuid result = guid;
return result;
}
#else // !Q_OS_WIN32
QT_BEGIN_INCLUDE_NAMESPACE
#include "qdatetime.h"
#include "qfile.h"
#include "qthreadstorage.h"
#include <stdlib.h> // for RAND_MAX
QT_END_INCLUDE_NAMESPACE
#if !defined(QT_BOOTSTRAPPED) && defined(Q_OS_UNIX)
Q_GLOBAL_STATIC(QThreadStorage<QFile *>, devUrandomStorage);
#endif
QUuid QUuid::createUuid()
{
QUuid result;
uint *data = &(result.data1);
#if defined(Q_OS_UNIX)
QFile *devUrandom;
# if !defined(QT_BOOTSTRAPPED)
devUrandom = devUrandomStorage()->localData();
if (!devUrandom) {
devUrandom = new QFile(QLatin1String("/dev/urandom"));
devUrandom->open(QIODevice::ReadOnly | QIODevice::Unbuffered);
devUrandomStorage()->setLocalData(devUrandom);
}
# else
QFile file(QLatin1String("/dev/urandom"));
devUrandom = &file;
devUrandom->open(QIODevice::ReadOnly | QIODevice::Unbuffered);
# endif
enum { AmountToRead = 4 * sizeof(uint) };
if (devUrandom->isOpen()
&& devUrandom->read((char *) data, AmountToRead) == AmountToRead) {
// we got what we wanted, nothing more to do
;
} else
#endif
{
static const int intbits = sizeof(int)*8;
static int randbits = 0;
if (!randbits) {
int r = 0;
int max = RAND_MAX;
do { ++r; } while ((max=max>>1));
randbits = r;
}
// Seed the PRNG once per thread with a combination of current time, a
// stack address and a serial counter (since thread stack addresses are
// re-used).
#ifndef QT_BOOTSTRAPPED
static QThreadStorage<int *> uuidseed;
if (!uuidseed.hasLocalData())
{
int *pseed = new int;
static QBasicAtomicInt serial = Q_BASIC_ATOMIC_INITIALIZER(2);
qsrand(*pseed = QDateTime::currentDateTime().toTime_t()
+ quintptr(&pseed)
+ serial.fetchAndAddRelaxed(1));
uuidseed.setLocalData(pseed);
}
#else
static bool seeded = false;
if (!seeded)
qsrand(QDateTime::currentDateTime().toTime_t()
+ quintptr(&seeded));
#endif
int chunks = 16 / sizeof(uint);
while (chunks--) {
uint randNumber = 0;
for (int filled = 0; filled < intbits; filled += randbits)
randNumber |= qrand()<<filled;
*(data+chunks) = randNumber;
}
}
result.data4[0] = (result.data4[0] & 0x3F) | 0x80; // UV_DCE
result.data3 = (result.data3 & 0x0FFF) | 0x4000; // UV_Random
return result;
}
#endif // !Q_OS_WIN32
/*!
\fn bool QUuid::operator==(const GUID &guid) const
Returns \c true if this UUID is equal to the Windows GUID \a guid;
otherwise returns \c false.
*/
/*!
\fn bool QUuid::operator!=(const GUID &guid) const
Returns \c true if this UUID is not equal to the Windows GUID \a
guid; otherwise returns \c false.
*/
#ifndef QT_NO_DEBUG_STREAM
/*!
\relates QUuid
Writes the UUID \a id to the output stream for debugging information \a dbg.
*/
QDebug operator<<(QDebug dbg, const QUuid &id)
{
dbg.nospace() << "QUuid(" << id.toString() << ')';
return dbg.space();
}
#endif
/*!
\since 5.0
\relates QUuid
Returns a hash of the UUID \a uuid, using \a seed to seed the calculation.
*/
uint qHash(const QUuid &uuid, uint seed) Q_DECL_NOTHROW
{
return uuid.data1 ^ uuid.data2 ^ (uuid.data3 << 16)
^ ((uuid.data4[0] << 24) | (uuid.data4[1] << 16) | (uuid.data4[2] << 8) | uuid.data4[3])
^ ((uuid.data4[4] << 24) | (uuid.data4[5] << 16) | (uuid.data4[6] << 8) | uuid.data4[7])
^ seed;
}
QT_END_NAMESPACE
| Observer-Wu/phantomjs | src/qt/qtbase/src/corelib/plugin/quuid.cpp | C++ | bsd-3-clause | 27,549 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.benchmark;
import com.google.common.collect.Maps;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import static java.util.Objects.requireNonNull;
public class AverageBenchmarkResults
implements BenchmarkResultHook
{
private final Map<String, Long> resultsSum = new LinkedHashMap<>();
private int resultsCount;
@Override
public BenchmarkResultHook addResults(Map<String, Long> results)
{
requireNonNull(results, "results is null");
for (Entry<String, Long> entry : results.entrySet()) {
Long currentSum = resultsSum.get(entry.getKey());
if (currentSum == null) {
currentSum = 0L;
}
resultsSum.put(entry.getKey(), currentSum + entry.getValue());
}
resultsCount++;
return this;
}
public Map<String, Double> getAverageResultsValues()
{
return Maps.transformValues(resultsSum, input -> 1.0 * input / resultsCount);
}
public Map<String, String> getAverageResultsStrings()
{
return Maps.transformValues(resultsSum, input -> String.format("%,3.2f", 1.0 * input / resultsCount));
}
@Override
public void finished()
{
}
}
| marsorp/blog | presto166/presto-benchmark/src/main/java/com/facebook/presto/benchmark/AverageBenchmarkResults.java | Java | apache-2.0 | 1,837 |
// Copyright 2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package gax
import (
"time"
"golang.org/x/net/context"
)
// A user defined call stub.
type APICall func(context.Context) error
// Invoke calls the given APICall,
// performing retries as specified by opts, if any.
func Invoke(ctx context.Context, call APICall, opts ...CallOption) error {
var settings CallSettings
for _, opt := range opts {
opt.Resolve(&settings)
}
return invoke(ctx, call, settings, Sleep)
}
// Sleep is similar to time.Sleep, but it can be interrupted by ctx.Done() closing.
// If interrupted, Sleep returns ctx.Err().
func Sleep(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
select {
case <-ctx.Done():
t.Stop()
return ctx.Err()
case <-t.C:
return nil
}
}
type sleeper func(ctx context.Context, d time.Duration) error
// invoke implements Invoke, taking an additional sleeper argument for testing.
func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error {
var retryer Retryer
for {
err := call(ctx)
if err == nil {
return nil
}
if settings.Retry == nil {
return err
}
if retryer == nil {
if r := settings.Retry(); r != nil {
retryer = r
} else {
return err
}
}
if d, ok := retryer.Retry(err); !ok {
return err
} else if err = sp(ctx, d); err != nil {
return err
}
}
}
| stardog-union/stardog-graviton | vendor/github.com/hashicorp/terraform/vendor/github.com/googleapis/gax-go/invoke.go | GO | apache-2.0 | 2,878 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Microsoft.Internal
{
internal static class AttributeServices
{
// MemberInfo Attribute helpers
public static IEnumerable<T> GetAttributes<T>(this MemberInfo memberInfo) where T : System.Attribute
{
return memberInfo.GetCustomAttributes<T>(false);
}
public static IEnumerable<T> GetAttributes<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute
{
return memberInfo.GetCustomAttributes<T>(inherit);
}
public static T GetFirstAttribute<T>(this MemberInfo memberInfo) where T : System.Attribute
{
return GetAttributes<T>(memberInfo).FirstOrDefault();
}
public static T GetFirstAttribute<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute
{
return GetAttributes<T>(memberInfo, inherit).FirstOrDefault();
}
public static bool IsAttributeDefined<T>(this MemberInfo memberInfo) where T : System.Attribute
{
return memberInfo.IsDefined(typeof(T), false);
}
public static bool IsAttributeDefined<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute
{
return memberInfo.IsDefined(typeof(T), inherit);
}
// ParameterInfo Attribute helpers
public static IEnumerable<T> GetAttributes<T>(this ParameterInfo parameterInfo) where T : System.Attribute
{
return parameterInfo.GetCustomAttributes<T>(false);
}
public static IEnumerable<T> GetAttributes<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute
{
return parameterInfo.GetCustomAttributes<T>(inherit);
}
public static T GetFirstAttribute<T>(this ParameterInfo parameterInfo) where T : System.Attribute
{
return GetAttributes<T>(parameterInfo).FirstOrDefault();
}
public static T GetFirstAttribute<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute
{
return GetAttributes<T>(parameterInfo, inherit).FirstOrDefault();
}
public static bool IsAttributeDefined<T>(this ParameterInfo parameterInfo) where T : System.Attribute
{
return parameterInfo.IsDefined(typeof(T), false);
}
public static bool IsAttributeDefined<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute
{
return parameterInfo.IsDefined(typeof(T), inherit);
}
}
}
| iamjasonp/corefx | src/System.Composition.Convention/src/Microsoft/Internal/AttributeServices.cs | C# | mit | 2,881 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.cluster.repositories.verify;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.master.TransportMasterNodeAction;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.repositories.RepositoriesService;
import org.elasticsearch.repositories.RepositoryVerificationException;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
/**
* Transport action for verifying repository operation
*/
public class TransportVerifyRepositoryAction extends TransportMasterNodeAction<VerifyRepositoryRequest, VerifyRepositoryResponse> {
private final RepositoriesService repositoriesService;
protected final ClusterName clusterName;
@Inject
public TransportVerifyRepositoryAction(Settings settings, ClusterName clusterName, TransportService transportService, ClusterService clusterService,
RepositoriesService repositoriesService, ThreadPool threadPool, ActionFilters actionFilters,
IndexNameExpressionResolver indexNameExpressionResolver) {
super(settings, VerifyRepositoryAction.NAME, transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver, VerifyRepositoryRequest.class);
this.repositoriesService = repositoriesService;
this.clusterName = clusterName;
}
@Override
protected String executor() {
return ThreadPool.Names.MANAGEMENT;
}
@Override
protected VerifyRepositoryResponse newResponse() {
return new VerifyRepositoryResponse();
}
@Override
protected ClusterBlockException checkBlock(VerifyRepositoryRequest request, ClusterState state) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ);
}
@Override
protected void masterOperation(final VerifyRepositoryRequest request, ClusterState state, final ActionListener<VerifyRepositoryResponse> listener) {
repositoriesService.verifyRepository(request.name(), new ActionListener<RepositoriesService.VerifyResponse>() {
@Override
public void onResponse(RepositoriesService.VerifyResponse verifyResponse) {
if (verifyResponse.failed()) {
listener.onFailure(new RepositoryVerificationException(request.name(), verifyResponse.failureDescription()));
} else {
listener.onResponse(new VerifyRepositoryResponse(clusterName, verifyResponse.nodes()));
}
}
@Override
public void onFailure(Throwable e) {
listener.onFailure(e);
}
});
}
}
| shashi95/kafkaES | core/src/main/java/org/elasticsearch/action/admin/cluster/repositories/verify/TransportVerifyRepositoryAction.java | Java | apache-2.0 | 3,999 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// DO NOT EDIT. GENERATED BY
// go run makeisprint.go -output isprint.go
package strconv
// (470+136+73)*2 + (342)*4 = 2726 bytes
var isPrint16 = []uint16{
0x0020, 0x007e,
0x00a1, 0x0377,
0x037a, 0x037f,
0x0384, 0x0556,
0x0559, 0x058a,
0x058d, 0x05c7,
0x05d0, 0x05ea,
0x05f0, 0x05f4,
0x0606, 0x061b,
0x061e, 0x070d,
0x0710, 0x074a,
0x074d, 0x07b1,
0x07c0, 0x07fa,
0x0800, 0x082d,
0x0830, 0x085b,
0x085e, 0x085e,
0x08a0, 0x08b4,
0x08e3, 0x098c,
0x098f, 0x0990,
0x0993, 0x09b2,
0x09b6, 0x09b9,
0x09bc, 0x09c4,
0x09c7, 0x09c8,
0x09cb, 0x09ce,
0x09d7, 0x09d7,
0x09dc, 0x09e3,
0x09e6, 0x09fb,
0x0a01, 0x0a0a,
0x0a0f, 0x0a10,
0x0a13, 0x0a39,
0x0a3c, 0x0a42,
0x0a47, 0x0a48,
0x0a4b, 0x0a4d,
0x0a51, 0x0a51,
0x0a59, 0x0a5e,
0x0a66, 0x0a75,
0x0a81, 0x0ab9,
0x0abc, 0x0acd,
0x0ad0, 0x0ad0,
0x0ae0, 0x0ae3,
0x0ae6, 0x0af1,
0x0af9, 0x0af9,
0x0b01, 0x0b0c,
0x0b0f, 0x0b10,
0x0b13, 0x0b39,
0x0b3c, 0x0b44,
0x0b47, 0x0b48,
0x0b4b, 0x0b4d,
0x0b56, 0x0b57,
0x0b5c, 0x0b63,
0x0b66, 0x0b77,
0x0b82, 0x0b8a,
0x0b8e, 0x0b95,
0x0b99, 0x0b9f,
0x0ba3, 0x0ba4,
0x0ba8, 0x0baa,
0x0bae, 0x0bb9,
0x0bbe, 0x0bc2,
0x0bc6, 0x0bcd,
0x0bd0, 0x0bd0,
0x0bd7, 0x0bd7,
0x0be6, 0x0bfa,
0x0c00, 0x0c39,
0x0c3d, 0x0c4d,
0x0c55, 0x0c5a,
0x0c60, 0x0c63,
0x0c66, 0x0c6f,
0x0c78, 0x0cb9,
0x0cbc, 0x0ccd,
0x0cd5, 0x0cd6,
0x0cde, 0x0ce3,
0x0ce6, 0x0cf2,
0x0d01, 0x0d3a,
0x0d3d, 0x0d4e,
0x0d57, 0x0d57,
0x0d5f, 0x0d63,
0x0d66, 0x0d75,
0x0d79, 0x0d7f,
0x0d82, 0x0d96,
0x0d9a, 0x0dbd,
0x0dc0, 0x0dc6,
0x0dca, 0x0dca,
0x0dcf, 0x0ddf,
0x0de6, 0x0def,
0x0df2, 0x0df4,
0x0e01, 0x0e3a,
0x0e3f, 0x0e5b,
0x0e81, 0x0e84,
0x0e87, 0x0e8a,
0x0e8d, 0x0e8d,
0x0e94, 0x0ea7,
0x0eaa, 0x0ebd,
0x0ec0, 0x0ecd,
0x0ed0, 0x0ed9,
0x0edc, 0x0edf,
0x0f00, 0x0f6c,
0x0f71, 0x0fda,
0x1000, 0x10c7,
0x10cd, 0x10cd,
0x10d0, 0x124d,
0x1250, 0x125d,
0x1260, 0x128d,
0x1290, 0x12b5,
0x12b8, 0x12c5,
0x12c8, 0x1315,
0x1318, 0x135a,
0x135d, 0x137c,
0x1380, 0x1399,
0x13a0, 0x13f5,
0x13f8, 0x13fd,
0x1400, 0x169c,
0x16a0, 0x16f8,
0x1700, 0x1714,
0x1720, 0x1736,
0x1740, 0x1753,
0x1760, 0x1773,
0x1780, 0x17dd,
0x17e0, 0x17e9,
0x17f0, 0x17f9,
0x1800, 0x180d,
0x1810, 0x1819,
0x1820, 0x1877,
0x1880, 0x18aa,
0x18b0, 0x18f5,
0x1900, 0x192b,
0x1930, 0x193b,
0x1940, 0x1940,
0x1944, 0x196d,
0x1970, 0x1974,
0x1980, 0x19ab,
0x19b0, 0x19c9,
0x19d0, 0x19da,
0x19de, 0x1a1b,
0x1a1e, 0x1a7c,
0x1a7f, 0x1a89,
0x1a90, 0x1a99,
0x1aa0, 0x1aad,
0x1ab0, 0x1abe,
0x1b00, 0x1b4b,
0x1b50, 0x1b7c,
0x1b80, 0x1bf3,
0x1bfc, 0x1c37,
0x1c3b, 0x1c49,
0x1c4d, 0x1c7f,
0x1cc0, 0x1cc7,
0x1cd0, 0x1cf9,
0x1d00, 0x1df5,
0x1dfc, 0x1f15,
0x1f18, 0x1f1d,
0x1f20, 0x1f45,
0x1f48, 0x1f4d,
0x1f50, 0x1f7d,
0x1f80, 0x1fd3,
0x1fd6, 0x1fef,
0x1ff2, 0x1ffe,
0x2010, 0x2027,
0x2030, 0x205e,
0x2070, 0x2071,
0x2074, 0x209c,
0x20a0, 0x20be,
0x20d0, 0x20f0,
0x2100, 0x218b,
0x2190, 0x23fa,
0x2400, 0x2426,
0x2440, 0x244a,
0x2460, 0x2b73,
0x2b76, 0x2b95,
0x2b98, 0x2bb9,
0x2bbd, 0x2bd1,
0x2bec, 0x2bef,
0x2c00, 0x2cf3,
0x2cf9, 0x2d27,
0x2d2d, 0x2d2d,
0x2d30, 0x2d67,
0x2d6f, 0x2d70,
0x2d7f, 0x2d96,
0x2da0, 0x2e42,
0x2e80, 0x2ef3,
0x2f00, 0x2fd5,
0x2ff0, 0x2ffb,
0x3001, 0x3096,
0x3099, 0x30ff,
0x3105, 0x312d,
0x3131, 0x31ba,
0x31c0, 0x31e3,
0x31f0, 0x4db5,
0x4dc0, 0x9fd5,
0xa000, 0xa48c,
0xa490, 0xa4c6,
0xa4d0, 0xa62b,
0xa640, 0xa6f7,
0xa700, 0xa7ad,
0xa7b0, 0xa7b7,
0xa7f7, 0xa82b,
0xa830, 0xa839,
0xa840, 0xa877,
0xa880, 0xa8c4,
0xa8ce, 0xa8d9,
0xa8e0, 0xa8fd,
0xa900, 0xa953,
0xa95f, 0xa97c,
0xa980, 0xa9d9,
0xa9de, 0xaa36,
0xaa40, 0xaa4d,
0xaa50, 0xaa59,
0xaa5c, 0xaac2,
0xaadb, 0xaaf6,
0xab01, 0xab06,
0xab09, 0xab0e,
0xab11, 0xab16,
0xab20, 0xab65,
0xab70, 0xabed,
0xabf0, 0xabf9,
0xac00, 0xd7a3,
0xd7b0, 0xd7c6,
0xd7cb, 0xd7fb,
0xf900, 0xfa6d,
0xfa70, 0xfad9,
0xfb00, 0xfb06,
0xfb13, 0xfb17,
0xfb1d, 0xfbc1,
0xfbd3, 0xfd3f,
0xfd50, 0xfd8f,
0xfd92, 0xfdc7,
0xfdf0, 0xfdfd,
0xfe00, 0xfe19,
0xfe20, 0xfe6b,
0xfe70, 0xfefc,
0xff01, 0xffbe,
0xffc2, 0xffc7,
0xffca, 0xffcf,
0xffd2, 0xffd7,
0xffda, 0xffdc,
0xffe0, 0xffee,
0xfffc, 0xfffd,
}
var isNotPrint16 = []uint16{
0x00ad,
0x038b,
0x038d,
0x03a2,
0x0530,
0x0560,
0x0588,
0x0590,
0x06dd,
0x083f,
0x0984,
0x09a9,
0x09b1,
0x09de,
0x0a04,
0x0a29,
0x0a31,
0x0a34,
0x0a37,
0x0a3d,
0x0a5d,
0x0a84,
0x0a8e,
0x0a92,
0x0aa9,
0x0ab1,
0x0ab4,
0x0ac6,
0x0aca,
0x0b04,
0x0b29,
0x0b31,
0x0b34,
0x0b5e,
0x0b84,
0x0b91,
0x0b9b,
0x0b9d,
0x0bc9,
0x0c04,
0x0c0d,
0x0c11,
0x0c29,
0x0c45,
0x0c49,
0x0c57,
0x0c80,
0x0c84,
0x0c8d,
0x0c91,
0x0ca9,
0x0cb4,
0x0cc5,
0x0cc9,
0x0cdf,
0x0cf0,
0x0d04,
0x0d0d,
0x0d11,
0x0d45,
0x0d49,
0x0d84,
0x0db2,
0x0dbc,
0x0dd5,
0x0dd7,
0x0e83,
0x0e89,
0x0e98,
0x0ea0,
0x0ea4,
0x0ea6,
0x0eac,
0x0eba,
0x0ec5,
0x0ec7,
0x0f48,
0x0f98,
0x0fbd,
0x0fcd,
0x10c6,
0x1249,
0x1257,
0x1259,
0x1289,
0x12b1,
0x12bf,
0x12c1,
0x12d7,
0x1311,
0x1680,
0x170d,
0x176d,
0x1771,
0x191f,
0x1a5f,
0x1cf7,
0x1f58,
0x1f5a,
0x1f5c,
0x1f5e,
0x1fb5,
0x1fc5,
0x1fdc,
0x1ff5,
0x208f,
0x2bc9,
0x2c2f,
0x2c5f,
0x2d26,
0x2da7,
0x2daf,
0x2db7,
0x2dbf,
0x2dc7,
0x2dcf,
0x2dd7,
0x2ddf,
0x2e9a,
0x3040,
0x318f,
0x321f,
0x32ff,
0xa9ce,
0xa9ff,
0xab27,
0xab2f,
0xfb37,
0xfb3d,
0xfb3f,
0xfb42,
0xfb45,
0xfe53,
0xfe67,
0xfe75,
0xffe7,
}
var isPrint32 = []uint32{
0x010000, 0x01004d,
0x010050, 0x01005d,
0x010080, 0x0100fa,
0x010100, 0x010102,
0x010107, 0x010133,
0x010137, 0x01018c,
0x010190, 0x01019b,
0x0101a0, 0x0101a0,
0x0101d0, 0x0101fd,
0x010280, 0x01029c,
0x0102a0, 0x0102d0,
0x0102e0, 0x0102fb,
0x010300, 0x010323,
0x010330, 0x01034a,
0x010350, 0x01037a,
0x010380, 0x0103c3,
0x0103c8, 0x0103d5,
0x010400, 0x01049d,
0x0104a0, 0x0104a9,
0x010500, 0x010527,
0x010530, 0x010563,
0x01056f, 0x01056f,
0x010600, 0x010736,
0x010740, 0x010755,
0x010760, 0x010767,
0x010800, 0x010805,
0x010808, 0x010838,
0x01083c, 0x01083c,
0x01083f, 0x01089e,
0x0108a7, 0x0108af,
0x0108e0, 0x0108f5,
0x0108fb, 0x01091b,
0x01091f, 0x010939,
0x01093f, 0x01093f,
0x010980, 0x0109b7,
0x0109bc, 0x0109cf,
0x0109d2, 0x010a06,
0x010a0c, 0x010a33,
0x010a38, 0x010a3a,
0x010a3f, 0x010a47,
0x010a50, 0x010a58,
0x010a60, 0x010a9f,
0x010ac0, 0x010ae6,
0x010aeb, 0x010af6,
0x010b00, 0x010b35,
0x010b39, 0x010b55,
0x010b58, 0x010b72,
0x010b78, 0x010b91,
0x010b99, 0x010b9c,
0x010ba9, 0x010baf,
0x010c00, 0x010c48,
0x010c80, 0x010cb2,
0x010cc0, 0x010cf2,
0x010cfa, 0x010cff,
0x010e60, 0x010e7e,
0x011000, 0x01104d,
0x011052, 0x01106f,
0x01107f, 0x0110c1,
0x0110d0, 0x0110e8,
0x0110f0, 0x0110f9,
0x011100, 0x011143,
0x011150, 0x011176,
0x011180, 0x0111cd,
0x0111d0, 0x0111f4,
0x011200, 0x01123d,
0x011280, 0x0112a9,
0x0112b0, 0x0112ea,
0x0112f0, 0x0112f9,
0x011300, 0x01130c,
0x01130f, 0x011310,
0x011313, 0x011339,
0x01133c, 0x011344,
0x011347, 0x011348,
0x01134b, 0x01134d,
0x011350, 0x011350,
0x011357, 0x011357,
0x01135d, 0x011363,
0x011366, 0x01136c,
0x011370, 0x011374,
0x011480, 0x0114c7,
0x0114d0, 0x0114d9,
0x011580, 0x0115b5,
0x0115b8, 0x0115dd,
0x011600, 0x011644,
0x011650, 0x011659,
0x011680, 0x0116b7,
0x0116c0, 0x0116c9,
0x011700, 0x011719,
0x01171d, 0x01172b,
0x011730, 0x01173f,
0x0118a0, 0x0118f2,
0x0118ff, 0x0118ff,
0x011ac0, 0x011af8,
0x012000, 0x012399,
0x012400, 0x012474,
0x012480, 0x012543,
0x013000, 0x01342e,
0x014400, 0x014646,
0x016800, 0x016a38,
0x016a40, 0x016a69,
0x016a6e, 0x016a6f,
0x016ad0, 0x016aed,
0x016af0, 0x016af5,
0x016b00, 0x016b45,
0x016b50, 0x016b77,
0x016b7d, 0x016b8f,
0x016f00, 0x016f44,
0x016f50, 0x016f7e,
0x016f8f, 0x016f9f,
0x01b000, 0x01b001,
0x01bc00, 0x01bc6a,
0x01bc70, 0x01bc7c,
0x01bc80, 0x01bc88,
0x01bc90, 0x01bc99,
0x01bc9c, 0x01bc9f,
0x01d000, 0x01d0f5,
0x01d100, 0x01d126,
0x01d129, 0x01d172,
0x01d17b, 0x01d1e8,
0x01d200, 0x01d245,
0x01d300, 0x01d356,
0x01d360, 0x01d371,
0x01d400, 0x01d49f,
0x01d4a2, 0x01d4a2,
0x01d4a5, 0x01d4a6,
0x01d4a9, 0x01d50a,
0x01d50d, 0x01d546,
0x01d54a, 0x01d6a5,
0x01d6a8, 0x01d7cb,
0x01d7ce, 0x01da8b,
0x01da9b, 0x01daaf,
0x01e800, 0x01e8c4,
0x01e8c7, 0x01e8d6,
0x01ee00, 0x01ee24,
0x01ee27, 0x01ee3b,
0x01ee42, 0x01ee42,
0x01ee47, 0x01ee54,
0x01ee57, 0x01ee64,
0x01ee67, 0x01ee9b,
0x01eea1, 0x01eebb,
0x01eef0, 0x01eef1,
0x01f000, 0x01f02b,
0x01f030, 0x01f093,
0x01f0a0, 0x01f0ae,
0x01f0b1, 0x01f0f5,
0x01f100, 0x01f10c,
0x01f110, 0x01f16b,
0x01f170, 0x01f19a,
0x01f1e6, 0x01f202,
0x01f210, 0x01f23a,
0x01f240, 0x01f248,
0x01f250, 0x01f251,
0x01f300, 0x01f6d0,
0x01f6e0, 0x01f6ec,
0x01f6f0, 0x01f6f3,
0x01f700, 0x01f773,
0x01f780, 0x01f7d4,
0x01f800, 0x01f80b,
0x01f810, 0x01f847,
0x01f850, 0x01f859,
0x01f860, 0x01f887,
0x01f890, 0x01f8ad,
0x01f910, 0x01f918,
0x01f980, 0x01f984,
0x01f9c0, 0x01f9c0,
0x020000, 0x02a6d6,
0x02a700, 0x02b734,
0x02b740, 0x02b81d,
0x02b820, 0x02cea1,
0x02f800, 0x02fa1d,
0x0e0100, 0x0e01ef,
}
var isNotPrint32 = []uint16{ // add 0x10000 to each entry
0x000c,
0x0027,
0x003b,
0x003e,
0x039e,
0x0809,
0x0836,
0x0856,
0x08f3,
0x0a04,
0x0a14,
0x0a18,
0x10bd,
0x1135,
0x11e0,
0x1212,
0x1287,
0x1289,
0x128e,
0x129e,
0x1304,
0x1329,
0x1331,
0x1334,
0x246f,
0x6a5f,
0x6b5a,
0x6b62,
0xd455,
0xd49d,
0xd4ad,
0xd4ba,
0xd4bc,
0xd4c4,
0xd506,
0xd515,
0xd51d,
0xd53a,
0xd53f,
0xd545,
0xd551,
0xdaa0,
0xee04,
0xee20,
0xee23,
0xee28,
0xee33,
0xee38,
0xee3a,
0xee48,
0xee4a,
0xee4c,
0xee50,
0xee53,
0xee58,
0xee5a,
0xee5c,
0xee5e,
0xee60,
0xee63,
0xee6b,
0xee73,
0xee78,
0xee7d,
0xee7f,
0xee8a,
0xeea4,
0xeeaa,
0xf0c0,
0xf0d0,
0xf12f,
0xf57a,
0xf5a4,
}
| shines77/go | src/strconv/isprint.go | GO | bsd-3-clause | 9,915 |
/*! UIkit 2.13.1 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
(function(addon) {
var component;
if (jQuery && UIkit) {
component = addon(jQuery, UIkit);
}
if (typeof define == "function" && define.amd) {
define("uikit-notify", ["uikit"], function(){
return component || addon(jQuery, UIkit);
});
}
})(function($, UI){
"use strict";
var containers = {},
messages = {},
notify = function(options){
if ($.type(options) == 'string') {
options = { message: options };
}
if (arguments[1]) {
options = $.extend(options, $.type(arguments[1]) == 'string' ? {status:arguments[1]} : arguments[1]);
}
return (new Message(options)).show();
},
closeAll = function(group, instantly){
var id;
if (group) {
for(id in messages) { if(group===messages[id].group) messages[id].close(instantly); }
} else {
for(id in messages) { messages[id].close(instantly); }
}
};
var Message = function(options){
var $this = this;
this.options = $.extend({}, Message.defaults, options);
this.uuid = UI.Utils.uid("notifymsg");
this.element = UI.$([
'<div class="@-notify-message">',
'<a class="@-close"></a>',
'<div></div>',
'</div>'
].join('')).data("notifyMessage", this);
this.content(this.options.message);
// status
if (this.options.status) {
this.element.addClass('@-notify-message-'+this.options.status);
this.currentstatus = this.options.status;
}
this.group = this.options.group;
messages[this.uuid] = this;
if(!containers[this.options.pos]) {
containers[this.options.pos] = UI.$('<div class="@-notify @-notify-'+this.options.pos+'"></div>').appendTo('body').on("click", UI.prefix(".@-notify-message"), function(){
UI.$(this).data("notifyMessage").close();
});
}
};
$.extend(Message.prototype, {
uuid: false,
element: false,
timout: false,
currentstatus: "",
group: false,
show: function() {
if (this.element.is(":visible")) return;
var $this = this;
containers[this.options.pos].show().prepend(this.element);
var marginbottom = parseInt(this.element.css("margin-bottom"), 10);
this.element.css({"opacity":0, "margin-top": -1*this.element.outerHeight(), "margin-bottom":0}).animate({"opacity":1, "margin-top": 0, "margin-bottom":marginbottom}, function(){
if ($this.options.timeout) {
var closefn = function(){ $this.close(); };
$this.timeout = setTimeout(closefn, $this.options.timeout);
$this.element.hover(
function() { clearTimeout($this.timeout); },
function() { $this.timeout = setTimeout(closefn, $this.options.timeout); }
);
}
});
return this;
},
close: function(instantly) {
var $this = this,
finalize = function(){
$this.element.remove();
if(!containers[$this.options.pos].children().length) {
containers[$this.options.pos].hide();
}
$this.options.onClose.apply($this, []);
delete messages[$this.uuid];
};
if (this.timeout) clearTimeout(this.timeout);
if (instantly) {
finalize();
} else {
this.element.animate({"opacity":0, "margin-top": -1* this.element.outerHeight(), "margin-bottom":0}, function(){
finalize();
});
}
},
content: function(html){
var container = this.element.find(">div");
if(!html) {
return container.html();
}
container.html(html);
return this;
},
status: function(status) {
if (!status) {
return this.currentstatus;
}
this.element.removeClass('@-notify-message-'+this.currentstatus).addClass('@-notify-message-'+status);
this.currentstatus = status;
return this;
}
});
Message.defaults = {
message: "",
status: "",
timeout: 5000,
group: null,
pos: 'top-center',
onClose: function() {}
};
UI.notify = notify;
UI.notify.message = Message;
UI.notify.closeAll = closeAll;
return notify;
});
| AppConcur/islacart | sites/all/themes/marketplace/vendor/uikit/js/components/notify.js | JavaScript | gpl-2.0 | 4,965 |
package graph
import (
"errors"
"fmt"
"net"
"net/url"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/docker/distribution/registry/client/transport"
"github.com/docker/docker/image"
"github.com/docker/docker/pkg/progressreader"
"github.com/docker/docker/pkg/streamformatter"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/docker/registry"
"github.com/docker/docker/utils"
)
type v1Puller struct {
*TagStore
endpoint registry.APIEndpoint
config *ImagePullConfig
sf *streamformatter.StreamFormatter
repoInfo *registry.RepositoryInfo
session *registry.Session
}
func (p *v1Puller) Pull(tag string) (fallback bool, err error) {
if utils.DigestReference(tag) {
// Allowing fallback, because HTTPS v1 is before HTTP v2
return true, registry.ErrNoSupport{errors.New("Cannot pull by digest with v1 registry")}
}
tlsConfig, err := p.registryService.TLSConfig(p.repoInfo.Index.Name)
if err != nil {
return false, err
}
// Adds Docker-specific headers as well as user-specified headers (metaHeaders)
tr := transport.NewTransport(
// TODO(tiborvass): was ReceiveTimeout
registry.NewTransport(tlsConfig),
registry.DockerHeaders(p.config.MetaHeaders)...,
)
client := registry.HTTPClient(tr)
v1Endpoint, err := p.endpoint.ToV1Endpoint(p.config.MetaHeaders)
if err != nil {
logrus.Debugf("Could not get v1 endpoint: %v", err)
return true, err
}
p.session, err = registry.NewSession(client, p.config.AuthConfig, v1Endpoint)
if err != nil {
// TODO(dmcgowan): Check if should fallback
logrus.Debugf("Fallback from error: %s", err)
return true, err
}
if err := p.pullRepository(tag); err != nil {
// TODO(dmcgowan): Check if should fallback
return false, err
}
return false, nil
}
func (p *v1Puller) pullRepository(askedTag string) error {
out := p.config.OutStream
out.Write(p.sf.FormatStatus("", "Pulling repository %s", p.repoInfo.CanonicalName))
repoData, err := p.session.GetRepositoryData(p.repoInfo.RemoteName)
if err != nil {
if strings.Contains(err.Error(), "HTTP code: 404") {
return fmt.Errorf("Error: image %s not found", utils.ImageReference(p.repoInfo.RemoteName, askedTag))
}
// Unexpected HTTP error
return err
}
logrus.Debugf("Retrieving the tag list")
tagsList := make(map[string]string)
if askedTag == "" {
tagsList, err = p.session.GetRemoteTags(repoData.Endpoints, p.repoInfo.RemoteName)
} else {
var tagID string
tagID, err = p.session.GetRemoteTag(repoData.Endpoints, p.repoInfo.RemoteName, askedTag)
tagsList[askedTag] = tagID
}
if err != nil {
if err == registry.ErrRepoNotFound && askedTag != "" {
return fmt.Errorf("Tag %s not found in repository %s", askedTag, p.repoInfo.CanonicalName)
}
logrus.Errorf("unable to get remote tags: %s", err)
return err
}
for tag, id := range tagsList {
repoData.ImgList[id] = ®istry.ImgData{
ID: id,
Tag: tag,
Checksum: "",
}
}
logrus.Debugf("Registering tags")
// If no tag has been specified, pull them all
if askedTag == "" {
for tag, id := range tagsList {
repoData.ImgList[id].Tag = tag
}
} else {
// Otherwise, check that the tag exists and use only that one
id, exists := tagsList[askedTag]
if !exists {
return fmt.Errorf("Tag %s not found in repository %s", askedTag, p.repoInfo.CanonicalName)
}
repoData.ImgList[id].Tag = askedTag
}
errors := make(chan error)
layersDownloaded := false
imgIDs := []string{}
sessionID := p.session.ID()
defer func() {
p.graph.Release(sessionID, imgIDs...)
}()
for _, image := range repoData.ImgList {
downloadImage := func(img *registry.ImgData) {
if askedTag != "" && img.Tag != askedTag {
errors <- nil
return
}
if img.Tag == "" {
logrus.Debugf("Image (id: %s) present in this repository but untagged, skipping", img.ID)
errors <- nil
return
}
// ensure no two downloads of the same image happen at the same time
if c, err := p.poolAdd("pull", "img:"+img.ID); err != nil {
if c != nil {
out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Layer already being pulled by another client. Waiting.", nil))
<-c
out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil))
} else {
logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err)
}
errors <- nil
return
}
defer p.poolRemove("pull", "img:"+img.ID)
// we need to retain it until tagging
p.graph.Retain(sessionID, img.ID)
imgIDs = append(imgIDs, img.ID)
out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s", img.Tag, p.repoInfo.CanonicalName), nil))
success := false
var lastErr, err error
var isDownloaded bool
for _, ep := range p.repoInfo.Index.Mirrors {
ep += "v1/"
out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, mirror: %s", img.Tag, p.repoInfo.CanonicalName, ep), nil))
if isDownloaded, err = p.pullImage(img.ID, ep, repoData.Tokens); err != nil {
// Don't report errors when pulling from mirrors.
logrus.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, p.repoInfo.CanonicalName, ep, err)
continue
}
layersDownloaded = layersDownloaded || isDownloaded
success = true
break
}
if !success {
for _, ep := range repoData.Endpoints {
out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, endpoint: %s", img.Tag, p.repoInfo.CanonicalName, ep), nil))
if isDownloaded, err = p.pullImage(img.ID, ep, repoData.Tokens); err != nil {
// It's not ideal that only the last error is returned, it would be better to concatenate the errors.
// As the error is also given to the output stream the user will see the error.
lastErr = err
out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Error pulling image (%s) from %s, endpoint: %s, %s", img.Tag, p.repoInfo.CanonicalName, ep, err), nil))
continue
}
layersDownloaded = layersDownloaded || isDownloaded
success = true
break
}
}
if !success {
err := fmt.Errorf("Error pulling image (%s) from %s, %v", img.Tag, p.repoInfo.CanonicalName, lastErr)
out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), err.Error(), nil))
errors <- err
return
}
out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil))
errors <- nil
}
go downloadImage(image)
}
var lastError error
for i := 0; i < len(repoData.ImgList); i++ {
if err := <-errors; err != nil {
lastError = err
}
}
if lastError != nil {
return lastError
}
for tag, id := range tagsList {
if askedTag != "" && tag != askedTag {
continue
}
if err := p.Tag(p.repoInfo.LocalName, tag, id, true); err != nil {
return err
}
}
requestedTag := p.repoInfo.LocalName
if len(askedTag) > 0 {
requestedTag = utils.ImageReference(p.repoInfo.LocalName, askedTag)
}
writeStatus(requestedTag, out, p.sf, layersDownloaded)
return nil
}
func (p *v1Puller) pullImage(imgID, endpoint string, token []string) (bool, error) {
history, err := p.session.GetRemoteHistory(imgID, endpoint)
if err != nil {
return false, err
}
out := p.config.OutStream
out.Write(p.sf.FormatProgress(stringid.TruncateID(imgID), "Pulling dependent layers", nil))
// FIXME: Try to stream the images?
// FIXME: Launch the getRemoteImage() in goroutines
sessionID := p.session.ID()
// As imgID has been retained in pullRepository, no need to retain again
p.graph.Retain(sessionID, history[1:]...)
defer p.graph.Release(sessionID, history[1:]...)
layersDownloaded := false
for i := len(history) - 1; i >= 0; i-- {
id := history[i]
// ensure no two downloads of the same layer happen at the same time
if c, err := p.poolAdd("pull", "layer:"+id); err != nil {
logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", id, err)
<-c
}
defer p.poolRemove("pull", "layer:"+id)
if !p.graph.Exists(id) {
out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Pulling metadata", nil))
var (
imgJSON []byte
imgSize int64
err error
img *image.Image
)
retries := 5
for j := 1; j <= retries; j++ {
imgJSON, imgSize, err = p.session.GetRemoteImageJSON(id, endpoint)
if err != nil && j == retries {
out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil))
return layersDownloaded, err
} else if err != nil {
time.Sleep(time.Duration(j) * 500 * time.Millisecond)
continue
}
img, err = image.NewImgJSON(imgJSON)
layersDownloaded = true
if err != nil && j == retries {
out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil))
return layersDownloaded, fmt.Errorf("Failed to parse json: %s", err)
} else if err != nil {
time.Sleep(time.Duration(j) * 500 * time.Millisecond)
continue
} else {
break
}
}
for j := 1; j <= retries; j++ {
// Get the layer
status := "Pulling fs layer"
if j > 1 {
status = fmt.Sprintf("Pulling fs layer [retries: %d]", j)
}
out.Write(p.sf.FormatProgress(stringid.TruncateID(id), status, nil))
layer, err := p.session.GetRemoteImageLayer(img.ID, endpoint, imgSize)
if uerr, ok := err.(*url.Error); ok {
err = uerr.Err
}
if terr, ok := err.(net.Error); ok && terr.Timeout() && j < retries {
time.Sleep(time.Duration(j) * 500 * time.Millisecond)
continue
} else if err != nil {
out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil))
return layersDownloaded, err
}
layersDownloaded = true
defer layer.Close()
err = p.graph.Register(img,
progressreader.New(progressreader.Config{
In: layer,
Out: out,
Formatter: p.sf,
Size: imgSize,
NewLines: false,
ID: stringid.TruncateID(id),
Action: "Downloading",
}))
if terr, ok := err.(net.Error); ok && terr.Timeout() && j < retries {
time.Sleep(time.Duration(j) * 500 * time.Millisecond)
continue
} else if err != nil {
out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error downloading dependent layers", nil))
return layersDownloaded, err
} else {
break
}
}
}
out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Download complete", nil))
}
return layersDownloaded, nil
}
| fmoliveira/docker | graph/pull_v1.go | GO | apache-2.0 | 10,610 |
package rancher
import (
"testing"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccRancherEnvironment_importBasic(t *testing.T) {
resourceName := "rancher_environment.foo"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckRancherEnvironmentDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccRancherEnvironmentConfig,
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
| stardog-union/stardog-graviton | vendor/github.com/hashicorp/terraform/builtin/providers/rancher/import_rancher_environment_test.go | GO | apache-2.0 | 605 |
class MyExc(Exception):
pass
e = MyExc(100, "Some error")
print(e)
print(repr(e))
print(e.args)
try:
raise MyExc("Some error")
except MyExc as e:
print("Caught exception:", repr(e))
try:
raise MyExc("Some error2")
except Exception as e:
print("Caught exception:", repr(e))
try:
raise MyExc("Some error2")
except:
print("Caught user exception")
| AriZuu/micropython | tests/basics/subclass_native3.py | Python | mit | 376 |
/*!
* Bootstrap-select v1.7.0 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2015 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Nu a fost selectat nimic',
noneResultsText: 'Nu exista niciun rezultat {0}',
countSelectedText: '{0} din {1} selectat(e)',
maxOptionsText: ['Limita a fost atinsa ({n} {var} max)', 'Limita de grup a fost atinsa ({n} {var} max)', ['iteme', 'item']],
multipleSeparator: ', '
};
})(jQuery);
| dominic/cdnjs | ajax/libs/bootstrap-select/1.7.0/js/i18n/defaults-ro_RO.js | JavaScript | mit | 597 |
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""MX-like base classes."""
import cStringIO
import struct
import dns.exception
import dns.rdata
import dns.name
class MXBase(dns.rdata.Rdata):
"""Base class for rdata that is like an MX record.
@ivar preference: the preference value
@type preference: int
@ivar exchange: the exchange name
@type exchange: dns.name.Name object"""
__slots__ = ['preference', 'exchange']
def __init__(self, rdclass, rdtype, preference, exchange):
super(MXBase, self).__init__(rdclass, rdtype)
self.preference = preference
self.exchange = exchange
def to_text(self, origin=None, relativize=True, **kw):
exchange = self.exchange.choose_relativity(origin, relativize)
return '%d %s' % (self.preference, exchange)
def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):
preference = tok.get_uint16()
exchange = tok.get_name()
exchange = exchange.choose_relativity(origin, relativize)
tok.get_eol()
return cls(rdclass, rdtype, preference, exchange)
from_text = classmethod(from_text)
def to_wire(self, file, compress = None, origin = None):
pref = struct.pack("!H", self.preference)
file.write(pref)
self.exchange.to_wire(file, compress, origin)
def to_digestable(self, origin = None):
return struct.pack("!H", self.preference) + \
self.exchange.to_digestable(origin)
def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None):
(preference, ) = struct.unpack('!H', wire[current : current + 2])
current += 2
rdlen -= 2
(exchange, cused) = dns.name.from_wire(wire[: current + rdlen],
current)
if cused != rdlen:
raise dns.exception.FormError
if not origin is None:
exchange = exchange.relativize(origin)
return cls(rdclass, rdtype, preference, exchange)
from_wire = classmethod(from_wire)
def choose_relativity(self, origin = None, relativize = True):
self.exchange = self.exchange.choose_relativity(origin, relativize)
def _cmp(self, other):
sp = struct.pack("!H", self.preference)
op = struct.pack("!H", other.preference)
v = cmp(sp, op)
if v == 0:
v = cmp(self.exchange, other.exchange)
return v
class UncompressedMX(MXBase):
"""Base class for rdata that is like an MX record, but whose name
is not compressed when converted to DNS wire format, and whose
digestable form is not downcased."""
def to_wire(self, file, compress = None, origin = None):
super(UncompressedMX, self).to_wire(file, None, origin)
def to_digestable(self, origin = None):
f = cStringIO.StringIO()
self.to_wire(f, None, origin)
return f.getvalue()
class UncompressedDowncasingMX(MXBase):
"""Base class for rdata that is like an MX record, but whose name
is not compressed when convert to DNS wire format."""
def to_wire(self, file, compress = None, origin = None):
super(UncompressedDowncasingMX, self).to_wire(file, None, origin)
| enigmamarketing/csf-allow-domains | usr/local/csf/bin/csf-allow-domains/dns/rdtypes/mxbase.py | Python | mit | 3,968 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.vending.expansion.downloader.impl;
import com.android.vending.expansion.downloader.R;
import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
import com.google.android.vending.expansion.downloader.Helpers;
import com.google.android.vending.expansion.downloader.IDownloaderClient;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Messenger;
/**
* This class handles displaying the notification associated with the download
* queue going on in the download manager. It handles multiple status types;
* Some require user interaction and some do not. Some of the user interactions
* may be transient. (for example: the user is queried to continue the download
* on 3G when it started on WiFi, but then the phone locks onto WiFi again so
* the prompt automatically goes away)
* <p/>
* The application interface for the downloader also needs to understand and
* handle these transient states.
*/
public class DownloadNotification implements IDownloaderClient {
private int mState;
private final Context mContext;
private final NotificationManager mNotificationManager;
private String mCurrentTitle;
private IDownloaderClient mClientProxy;
final ICustomNotification mCustomNotification;
private Notification mNotification;
private Notification mCurrentNotification;
private CharSequence mLabel;
private String mCurrentText;
private PendingIntent mContentIntent;
private DownloadProgressInfo mProgressInfo;
static final String LOGTAG = "DownloadNotification";
static final int NOTIFICATION_ID = LOGTAG.hashCode();
public PendingIntent getClientIntent() {
return mContentIntent;
}
public void setClientIntent(PendingIntent mClientIntent) {
this.mContentIntent = mClientIntent;
}
public void resendState() {
if (null != mClientProxy) {
mClientProxy.onDownloadStateChanged(mState);
}
}
@Override
public void onDownloadStateChanged(int newState) {
if (null != mClientProxy) {
mClientProxy.onDownloadStateChanged(newState);
}
if (newState != mState) {
mState = newState;
if (newState == IDownloaderClient.STATE_IDLE || null == mContentIntent) {
return;
}
int stringDownloadID;
int iconResource;
boolean ongoingEvent;
// get the new title string and paused text
switch (newState) {
case 0:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = R.string.state_unknown;
ongoingEvent = false;
break;
case IDownloaderClient.STATE_DOWNLOADING:
iconResource = android.R.drawable.stat_sys_download;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
case IDownloaderClient.STATE_FETCHING_URL:
case IDownloaderClient.STATE_CONNECTING:
iconResource = android.R.drawable.stat_sys_download_done;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
case IDownloaderClient.STATE_COMPLETED:
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
iconResource = android.R.drawable.stat_sys_download_done;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = false;
break;
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_SDCARD_FULL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = false;
break;
default:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
}
mCurrentText = mContext.getString(stringDownloadID);
mCurrentTitle = mLabel.toString();
mCurrentNotification.tickerText = mLabel + ": " + mCurrentText;
mCurrentNotification.icon = iconResource;
mCurrentNotification.setLatestEventInfo(mContext, mCurrentTitle, mCurrentText,
mContentIntent);
if (ongoingEvent) {
mCurrentNotification.flags |= Notification.FLAG_ONGOING_EVENT;
} else {
mCurrentNotification.flags &= ~Notification.FLAG_ONGOING_EVENT;
mCurrentNotification.flags |= Notification.FLAG_AUTO_CANCEL;
}
mNotificationManager.notify(NOTIFICATION_ID, mCurrentNotification);
}
}
@Override
public void onDownloadProgress(DownloadProgressInfo progress) {
mProgressInfo = progress;
if (null != mClientProxy) {
mClientProxy.onDownloadProgress(progress);
}
if (progress.mOverallTotal <= 0) {
// we just show the text
mNotification.tickerText = mCurrentTitle;
mNotification.icon = android.R.drawable.stat_sys_download;
mNotification.setLatestEventInfo(mContext, mLabel, mCurrentText, mContentIntent);
mCurrentNotification = mNotification;
} else {
mCustomNotification.setCurrentBytes(progress.mOverallProgress);
mCustomNotification.setTotalBytes(progress.mOverallTotal);
mCustomNotification.setIcon(android.R.drawable.stat_sys_download);
mCustomNotification.setPendingIntent(mContentIntent);
mCustomNotification.setTicker(mLabel + ": " + mCurrentText);
mCustomNotification.setTitle(mLabel);
mCustomNotification.setTimeRemaining(progress.mTimeRemaining);
mCurrentNotification = mCustomNotification.updateNotification(mContext);
}
mNotificationManager.notify(NOTIFICATION_ID, mCurrentNotification);
}
public interface ICustomNotification {
void setTitle(CharSequence title);
void setTicker(CharSequence ticker);
void setPendingIntent(PendingIntent mContentIntent);
void setTotalBytes(long totalBytes);
void setCurrentBytes(long currentBytes);
void setIcon(int iconResource);
void setTimeRemaining(long timeRemaining);
Notification updateNotification(Context c);
}
/**
* Called in response to onClientUpdated. Creates a new proxy and notifies
* it of the current state.
*
* @param msg the client Messenger to notify
*/
public void setMessenger(Messenger msg) {
mClientProxy = DownloaderClientMarshaller.CreateProxy(msg);
if (null != mProgressInfo) {
mClientProxy.onDownloadProgress(mProgressInfo);
}
if (mState != -1) {
mClientProxy.onDownloadStateChanged(mState);
}
}
/**
* Constructor
*
* @param ctx The context to use to obtain access to the Notification
* Service
*/
DownloadNotification(Context ctx, CharSequence applicationLabel) {
mState = -1;
mContext = ctx;
mLabel = applicationLabel;
mNotificationManager = (NotificationManager)
mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mCustomNotification = CustomNotificationFactory
.createCustomNotification();
mNotification = new Notification();
mCurrentNotification = mNotification;
}
@Override
public void onServiceConnected(Messenger m) {
}
}
| alebianco/ANE-Android-Expansion | source/android/play_apk_expansion/downloader_library/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java | Java | mit | 9,068 |
<?php
namespace Gliph\Visitor;
/**
* Interface for stateful algorithm visitors.
*/
interface StatefulVisitorInterface {
const NOT_STARTED = 0;
const IN_PROGRESS = 1;
const COMPLETE = 2;
/**
* Returns an integer indicating the current state of the visitor.
*
* @return int
* State should be one of the three StatefulVisitorInterface constants:
* - 0: indicates the algorithm has not yet started.
* - 1: indicates the algorithm is in progress.
* - 2: indicates the algorithm is complete.
*/
public function getState();
} | webflo/d8-core | vendor/sdboyer/gliph/src/Gliph/Visitor/StatefulVisitorInterface.php | PHP | gpl-2.0 | 594 |
// Utility functions
String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, ''); };
function supportsHtmlStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function get_text(el) {
ret = " ";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
if ( node.nodeType != 1 ) {
// Strip white space.
ret += node.nodeValue;
} else {
ret += get_text( node );
}
}
}
return ret.trim();
} | sandbox-team/techtalk-portal | vendor/zenpen/js/utils.js | JavaScript | mit | 641 |
'use strict';
var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-native');
var DESCRIPTORS = require('../internals/descriptors');
var global = require('../internals/global');
var isObject = require('../internals/is-object');
var has = require('../internals/has');
var classof = require('../internals/classof');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var redefine = require('../internals/redefine');
var defineProperty = require('../internals/object-define-property').f;
var getPrototypeOf = require('../internals/object-get-prototype-of');
var setPrototypeOf = require('../internals/object-set-prototype-of');
var wellKnownSymbol = require('../internals/well-known-symbol');
var uid = require('../internals/uid');
var Int8Array = global.Int8Array;
var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
var Uint8ClampedArray = global.Uint8ClampedArray;
var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
var TypedArray = Int8Array && getPrototypeOf(Int8Array);
var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
var ObjectPrototype = Object.prototype;
var isPrototypeOf = ObjectPrototype.isPrototypeOf;
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
// Fixing native typed arrays in Opera Presto crashes the browser, see #595
var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';
var TYPED_ARRAY_TAG_REQIRED = false;
var NAME;
var TypedArrayConstructorsList = {
Int8Array: 1,
Uint8Array: 1,
Uint8ClampedArray: 1,
Int16Array: 2,
Uint16Array: 2,
Int32Array: 4,
Uint32Array: 4,
Float32Array: 4,
Float64Array: 8
};
var isView = function isView(it) {
var klass = classof(it);
return klass === 'DataView' || has(TypedArrayConstructorsList, klass);
};
var isTypedArray = function (it) {
return isObject(it) && has(TypedArrayConstructorsList, classof(it));
};
var aTypedArray = function (it) {
if (isTypedArray(it)) return it;
throw TypeError('Target is not a typed array');
};
var aTypedArrayConstructor = function (C) {
if (setPrototypeOf) {
if (isPrototypeOf.call(TypedArray, C)) return C;
} else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) {
var TypedArrayConstructor = global[ARRAY];
if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) {
return C;
}
} throw TypeError('Target is not a typed array constructor');
};
var exportTypedArrayMethod = function (KEY, property, forced) {
if (!DESCRIPTORS) return;
if (forced) for (var ARRAY in TypedArrayConstructorsList) {
var TypedArrayConstructor = global[ARRAY];
if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) {
delete TypedArrayConstructor.prototype[KEY];
}
}
if (!TypedArrayPrototype[KEY] || forced) {
redefine(TypedArrayPrototype, KEY, forced ? property
: NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property);
}
};
var exportTypedArrayStaticMethod = function (KEY, property, forced) {
var ARRAY, TypedArrayConstructor;
if (!DESCRIPTORS) return;
if (setPrototypeOf) {
if (forced) for (ARRAY in TypedArrayConstructorsList) {
TypedArrayConstructor = global[ARRAY];
if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) {
delete TypedArrayConstructor[KEY];
}
}
if (!TypedArray[KEY] || forced) {
// V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
try {
return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property);
} catch (error) { /* empty */ }
} else return;
}
for (ARRAY in TypedArrayConstructorsList) {
TypedArrayConstructor = global[ARRAY];
if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
redefine(TypedArrayConstructor, KEY, property);
}
}
};
for (NAME in TypedArrayConstructorsList) {
if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false;
}
// WebKit bug - typed arrays constructors prototype is Object.prototype
if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) {
// eslint-disable-next-line no-shadow
TypedArray = function TypedArray() {
throw TypeError('Incorrect invocation');
};
if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);
}
}
if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
TypedArrayPrototype = TypedArray.prototype;
if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);
}
}
// WebKit bug - one more object in Uint8ClampedArray prototype chain
if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
}
if (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) {
TYPED_ARRAY_TAG_REQIRED = true;
defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {
return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
} });
for (NAME in TypedArrayConstructorsList) if (global[NAME]) {
createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);
}
}
module.exports = {
NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG,
aTypedArray: aTypedArray,
aTypedArrayConstructor: aTypedArrayConstructor,
exportTypedArrayMethod: exportTypedArrayMethod,
exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
isView: isView,
isTypedArray: isTypedArray,
TypedArray: TypedArray,
TypedArrayPrototype: TypedArrayPrototype
};
| BigBoss424/portfolio | v8/development/node_modules/jimp/node_modules/core-js/internals/array-buffer-view-core.js | JavaScript | apache-2.0 | 6,017 |
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $ */
/**
* The view that controls the showing and hiding of the sidebar.
*
* Although the sidebar view doesn't dispatch any events directly, it is a
* resizable element (../utils/Resizer.js), which means it can dispatch Resizer
* events. For example, if you want to listen for the sidebar showing
* or hiding itself, set up listeners for the corresponding Resizer events,
* panelCollapsed and panelExpanded:
*
* $("#sidebar").on("panelCollapsed", ...);
* $("#sidebar").on("panelExpanded", ...);
*/
define(function (require, exports, module) {
"use strict";
var AppInit = require("utils/AppInit"),
ProjectManager = require("project/ProjectManager"),
WorkingSetView = require("project/WorkingSetView"),
MainViewManager = require("view/MainViewManager"),
CommandManager = require("command/CommandManager"),
Commands = require("command/Commands"),
Strings = require("strings"),
Resizer = require("utils/Resizer"),
_ = require("thirdparty/lodash");
// These vars are initialized by the htmlReady handler
// below since they refer to DOM elements
var $sidebar,
$gearMenu,
$splitViewMenu,
$projectTitle,
$projectFilesContainer,
$workingSetViewsContainer;
var _cmdSplitNone,
_cmdSplitVertical,
_cmdSplitHorizontal;
/**
* @private
* Update project title when the project root changes
*/
function _updateProjectTitle() {
var displayName = ProjectManager.getProjectRoot().name;
var fullPath = ProjectManager.getProjectRoot().fullPath;
if (displayName === "" && fullPath === "/") {
displayName = "/";
}
$projectTitle.html(_.escape(displayName));
$projectTitle.attr("title", fullPath);
// Trigger a scroll on the project files container to
// reposition the scroller shadows and avoid issue #2255
$projectFilesContainer.trigger("scroll");
}
/**
* Toggle sidebar visibility.
*/
function toggle() {
Resizer.toggle($sidebar);
}
/**
* Show the sidebar.
*/
function show() {
Resizer.show($sidebar);
}
/**
* Hide the sidebar.
*/
function hide() {
Resizer.hide($sidebar);
}
/**
* Returns the visibility state of the sidebar.
* @return {boolean} true if element is visible, false if it is not visible
*/
function isVisible() {
return Resizer.isVisible($sidebar);
}
/**
* Update state of working set
* @private
*/
function _updateWorkingSetState() {
if (MainViewManager.getPaneCount() === 1 &&
MainViewManager.getWorkingSetSize(MainViewManager.ACTIVE_PANE) === 0) {
$workingSetViewsContainer.hide();
$gearMenu.hide();
} else {
$workingSetViewsContainer.show();
$gearMenu.show();
}
}
/**
* Update state of splitview and option elements
* @private
*/
function _updateUIStates() {
var spriteIndex,
ICON_CLASSES = ["splitview-icon-none", "splitview-icon-vertical", "splitview-icon-horizontal"],
layoutScheme = MainViewManager.getLayoutScheme();
if (layoutScheme.columns > 1) {
spriteIndex = 1;
} else if (layoutScheme.rows > 1) {
spriteIndex = 2;
} else {
spriteIndex = 0;
}
// SplitView Icon
$splitViewMenu.removeClass(ICON_CLASSES.join(" "))
.addClass(ICON_CLASSES[spriteIndex]);
// SplitView Menu
_cmdSplitNone.setChecked(spriteIndex === 0);
_cmdSplitVertical.setChecked(spriteIndex === 1);
_cmdSplitHorizontal.setChecked(spriteIndex === 2);
// Options icon
_updateWorkingSetState();
}
/**
* Handle No Split Command
* @private
*/
function _handleSplitViewNone() {
MainViewManager.setLayoutScheme(1, 1);
}
/**
* Handle Vertical Split Command
* @private
*/
function _handleSplitViewVertical() {
MainViewManager.setLayoutScheme(1, 2);
}
/**
* Handle Horizontal Split Command
* @private
*/
function _handleSplitViewHorizontal() {
MainViewManager.setLayoutScheme(2, 1);
}
// Initialize items dependent on HTML DOM
AppInit.htmlReady(function () {
$sidebar = $("#sidebar");
$gearMenu = $sidebar.find(".working-set-option-btn");
$splitViewMenu = $sidebar.find(".working-set-splitview-btn");
$projectTitle = $sidebar.find("#project-title");
$projectFilesContainer = $sidebar.find("#project-files-container");
$workingSetViewsContainer = $sidebar.find("#working-set-list-container");
function _resizeSidebarSelection() {
var $element;
$sidebar.find(".sidebar-selection").each(function (index, element) {
$element = $(element);
$element.width($element.parent()[0].scrollWidth);
});
}
// init
$sidebar.on("panelResizeStart", function (evt, width) {
$sidebar.find(".sidebar-selection-extension").css("display", "none");
$sidebar.find(".scroller-shadow").css("display", "none");
});
$sidebar.on("panelResizeUpdate", function (evt, width) {
$sidebar.find(".sidebar-selection").width(width);
ProjectManager._setFileTreeSelectionWidth(width);
});
$sidebar.on("panelResizeEnd", function (evt, width) {
_resizeSidebarSelection();
$sidebar.find(".sidebar-selection-extension").css("display", "block").css("left", width);
$sidebar.find(".scroller-shadow").css("display", "block");
$projectFilesContainer.triggerHandler("scroll");
WorkingSetView.syncSelectionIndicator();
});
$sidebar.on("panelCollapsed", function (evt, width) {
CommandManager.get(Commands.VIEW_HIDE_SIDEBAR).setName(Strings.CMD_SHOW_SIDEBAR);
});
$sidebar.on("panelExpanded", function (evt, width) {
WorkingSetView.refresh();
_resizeSidebarSelection();
$sidebar.find(".scroller-shadow").css("display", "block");
$sidebar.find(".sidebar-selection-extension").css("left", width);
$projectFilesContainer.triggerHandler("scroll");
WorkingSetView.syncSelectionIndicator();
CommandManager.get(Commands.VIEW_HIDE_SIDEBAR).setName(Strings.CMD_HIDE_SIDEBAR);
});
// AppInit.htmlReady in utils/Resizer executes before, so it's possible that the sidebar
// is collapsed before we add the event. Check here initially
if (!$sidebar.is(":visible")) {
$sidebar.trigger("panelCollapsed");
}
// wire up an event handler to monitor when panes are created
MainViewManager.on("paneCreate", function (evt, paneId) {
WorkingSetView.createWorkingSetViewForPane($workingSetViewsContainer, paneId);
});
MainViewManager.on("paneLayoutChange", function () {
_updateUIStates();
});
MainViewManager.on("workingSetAdd workingSetAddList workingSetRemove workingSetRemoveList workingSetUpdate", function () {
_updateWorkingSetState();
});
// create WorkingSetViews for each pane already created
_.forEach(MainViewManager.getPaneIdList(), function (paneId) {
WorkingSetView.createWorkingSetViewForPane($workingSetViewsContainer, paneId);
});
_updateUIStates();
// Tooltips
$gearMenu.attr("title", Strings.GEAR_MENU_TOOLTIP);
$splitViewMenu.attr("title", Strings.SPLITVIEW_MENU_TOOLTIP);
});
ProjectManager.on("projectOpen", _updateProjectTitle);
/**
* Register Command Handlers
*/
_cmdSplitNone = CommandManager.register(Strings.CMD_SPLITVIEW_NONE, Commands.CMD_SPLITVIEW_NONE, _handleSplitViewNone);
_cmdSplitVertical = CommandManager.register(Strings.CMD_SPLITVIEW_VERTICAL, Commands.CMD_SPLITVIEW_VERTICAL, _handleSplitViewVertical);
_cmdSplitHorizontal = CommandManager.register(Strings.CMD_SPLITVIEW_HORIZONTAL, Commands.CMD_SPLITVIEW_HORIZONTAL, _handleSplitViewHorizontal);
CommandManager.register(Strings.CMD_HIDE_SIDEBAR, Commands.VIEW_HIDE_SIDEBAR, toggle);
// Define public API
exports.toggle = toggle;
exports.show = show;
exports.hide = hide;
exports.isVisible = isVisible;
});
| resir014/brackets | src/project/SidebarView.js | JavaScript | mit | 10,278 |
package rdsutils
import (
"net/http"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/signer/v4"
)
// BuildAuthToken will return a authentication token for the database's connect
// based on the RDS database endpoint, AWS region, IAM user or role, and AWS credentials.
//
// Endpoint consists of the hostname and port, IE hostname:port, of the RDS database.
// Region is the AWS region the RDS database is in and where the authentication token
// will be generated for. DbUser is the IAM user or role the request will be authenticated
// for. The creds is the AWS credentials the authentication token is signed with.
//
// An error is returned if the authentication token is unable to be signed with
// the credentials, or the endpoint is not a valid URL.
//
// The following example shows how to use BuildAuthToken to create an authentication
// token for connecting to a MySQL database in RDS.
//
// authToken, err := BuildAuthToken(dbEndpoint, awsRegion, dbUser, awsCreds)
//
// // Create the MySQL DNS string for the DB connection
// // user:password@protocol(endpoint)/dbname?<params>
// dnsStr = fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true",
// dbUser, authToken, dbEndpoint, dbName,
// )
//
// // Use db to perform SQL operations on database
// db, err := sql.Open("mysql", dnsStr)
//
// See http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html
// for more information on using IAM database authentication with RDS.
func BuildAuthToken(endpoint, region, dbUser string, creds *credentials.Credentials) (string, error) {
// the scheme is arbitrary and is only needed because validation of the URL requires one.
if !(strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://")) {
endpoint = "https://" + endpoint
}
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return "", err
}
values := req.URL.Query()
values.Set("Action", "connect")
values.Set("DBUser", dbUser)
req.URL.RawQuery = values.Encode()
signer := v4.Signer{
Credentials: creds,
}
_, err = signer.Presign(req, nil, "rds-db", region, 15*time.Minute, time.Now())
if err != nil {
return "", err
}
url := req.URL.String()
if strings.HasPrefix(url, "http://") {
url = url[len("http://"):]
} else if strings.HasPrefix(url, "https://") {
url = url[len("https://"):]
}
return url, nil
}
| whosonfirst/go-whosonfirst-updated | vendor/github.com/whosonfirst/go-whosonfirst-s3/vendor/src/github.com/aws/aws-sdk-go/service/rds/rdsutils/connect.go | GO | bsd-3-clause | 2,417 |
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package store
type Watcher interface {
EventChan() chan *Event
StartIndex() uint64 // The EtcdIndex at which the Watcher was created
Remove()
}
type watcher struct {
eventChan chan *Event
stream bool
recursive bool
sinceIndex uint64
startIndex uint64
hub *watcherHub
removed bool
remove func()
}
func (w *watcher) EventChan() chan *Event {
return w.eventChan
}
func (w *watcher) StartIndex() uint64 {
return w.startIndex
}
// notify function notifies the watcher. If the watcher interests in the given path,
// the function will return true.
func (w *watcher) notify(e *Event, originalPath bool, deleted bool) bool {
// watcher is interested the path in three cases and under one condition
// the condition is that the event happens after the watcher's sinceIndex
// 1. the path at which the event happens is the path the watcher is watching at.
// For example if the watcher is watching at "/foo" and the event happens at "/foo",
// the watcher must be interested in that event.
// 2. the watcher is a recursive watcher, it interests in the event happens after
// its watching path. For example if watcher A watches at "/foo" and it is a recursive
// one, it will interest in the event happens at "/foo/bar".
// 3. when we delete a directory, we need to force notify all the watchers who watches
// at the file we need to delete.
// For example a watcher is watching at "/foo/bar". And we deletes "/foo". The watcher
// should get notified even if "/foo" is not the path it is watching.
if (w.recursive || originalPath || deleted) && e.Index() >= w.sinceIndex {
// We cannot block here if the eventChan capacity is full, otherwise
// etcd will hang. eventChan capacity is full when the rate of
// notifications are higher than our send rate.
// If this happens, we close the channel.
select {
case w.eventChan <- e:
default:
// We have missed a notification. Remove the watcher.
// Removing the watcher also closes the eventChan.
w.remove()
}
return true
}
return false
}
// Remove removes the watcher from watcherHub
// The actual remove function is guaranteed to only be executed once
func (w *watcher) Remove() {
w.hub.mutex.Lock()
defer w.hub.mutex.Unlock()
close(w.eventChan)
if w.remove != nil {
w.remove()
}
}
// nopWatcher is a watcher that receives nothing, always blocking.
type nopWatcher struct{}
func NewNopWatcher() Watcher { return &nopWatcher{} }
func (w *nopWatcher) EventChan() chan *Event { return nil }
func (w *nopWatcher) StartIndex() uint64 { return 0 }
func (w *nopWatcher) Remove() {}
| dmirubtsov/k8s-executor | vendor/k8s.io/kubernetes/vendor/github.com/coreos/etcd/store/watcher.go | GO | apache-2.0 | 3,230 |
using System;
namespace Notifications.Model
{
public interface IScenario
{
string Name { get; }
bool Contains(Type scenarioType);
Scenario FindScenario(Type scenarioType);
}
}
| TA-Team-Giant/PAaaS | pAaaS/Notifications/Model/IScenario.cs | C# | mit | 218 |
export default function Home() {
return <div className="red-text">This text should be red.</div>
}
| flybayer/next.js | test/integration/scss-fixtures/webpack-error/pages/index.js | JavaScript | mit | 101 |
/* */
module.exports = { "default": require("core-js/library/fn/math/sign"), __esModule: true }; | pauldijou/outdated | test/basic/jspm_packages/npm/babel-runtime@5.8.9/core-js/math/sign.js | JavaScript | apache-2.0 | 97 |
require 'formula'
class Avce00 < Formula
homepage 'http://avce00.maptools.org/avce00/index.html'
url 'http://avce00.maptools.org/dl/avce00-2.0.0.tar.gz'
sha1 '2948d9b1cfb6e80faf2e9b90c86fd224617efd75'
def install
system "make", "CC=#{ENV.cc}"
bin.install "avcimport", "avcexport", "avcdelete", "avctest"
end
end
| jtrag/homebrew | Library/Formula/avce00.rb | Ruby | bsd-2-clause | 333 |
module CodeRay
# = WordList
#
# <b>A Hash subclass designed for mapping word lists to token types.</b>
#
# A WordList is a Hash with some additional features.
# It is intended to be used for keyword recognition.
#
# WordList is optimized to be used in Scanners,
# typically to decide whether a given ident is a special token.
#
# For case insensitive words use WordList::CaseIgnoring.
#
# Example:
#
# # define word arrays
# RESERVED_WORDS = %w[
# asm break case continue default do else
# ]
#
# PREDEFINED_TYPES = %w[
# int long short char void
# ]
#
# # make a WordList
# IDENT_KIND = WordList.new(:ident).
# add(RESERVED_WORDS, :reserved).
# add(PREDEFINED_TYPES, :predefined_type)
#
# ...
#
# def scan_tokens tokens, options
# ...
#
# elsif scan(/[A-Za-z_][A-Za-z_0-9]*/)
# # use it
# kind = IDENT_KIND[match]
# ...
class WordList < Hash
# Create a new WordList with +default+ as default value.
def initialize default = false
super default
end
# Add words to the list and associate them with +value+.
#
# Returns +self+, so you can concat add calls.
def add words, value = true
words.each { |word| self[word] = value }
self
end
end
# A CaseIgnoring WordList is like a WordList, only that
# keys are compared case-insensitively (normalizing keys using +downcase+).
class WordList::CaseIgnoring < WordList
def [] key
super key.downcase
end
def []= key, value
super key.downcase, value
end
end
end
| emineKoc/WiseWit | wisewitapi/vendor/bundle/gems/coderay-1.1.1/lib/coderay/helpers/word_list.rb | Ruby | gpl-3.0 | 1,662 |
function loadedScript() {
return "externalScript1";
}
| nwjs/chromium.src | third_party/blink/web_tests/external/wpt/svg/linking/scripted/testScripts/externalScript1.js | JavaScript | bsd-3-clause | 56 |
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp.internal;
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
public final class RecordingOkAuthenticator implements Authenticator {
public final List<Response> responses = new ArrayList<>();
public final List<Proxy> proxies = new ArrayList<>();
public final String credential;
public RecordingOkAuthenticator(String credential) {
this.credential = credential;
}
public Response onlyResponse() {
if (responses.size() != 1) throw new IllegalStateException();
return responses.get(0);
}
public Proxy onlyProxy() {
if (proxies.size() != 1) throw new IllegalStateException();
return proxies.get(0);
}
@Override public Request authenticate(Proxy proxy, Response response) {
responses.add(response);
proxies.add(proxy);
return response.request().newBuilder()
.addHeader("Authorization", credential)
.build();
}
@Override public Request authenticateProxy(Proxy proxy, Response response) {
responses.add(response);
proxies.add(proxy);
return response.request().newBuilder()
.addHeader("Proxy-Authorization", credential)
.build();
}
}
| cdut007/PMS_TASK | third_party/okhttp-master/okhttp-tests/src/test/java/com/squareup/okhttp/internal/RecordingOkAuthenticator.java | Java | mit | 1,901 |
require 'formula'
class Gplcver < Formula
desc "Pragmatic C Software GPL Cver 2001"
homepage 'http://gplcver.sourceforge.net/'
url 'https://downloads.sourceforge.net/project/gplcver/gplcver/2.12a/gplcver-2.12a.src.tar.bz2'
sha1 '946bb35b6279646c6e10c309922ed17deb2aca8a'
def install
inreplace 'src/makefile.osx' do |s|
s.gsub! '-mcpu=powerpc', ''
s.change_make_var! 'CFLAGS', "$(INCS) $(OPTFLGS) #{ENV.cflags}"
s.change_make_var! 'LFLAGS', ''
end
system "make", "-C", "src", "-f", "makefile.osx"
bin.install 'bin/cver'
end
end
| stoshiya/homebrew | Library/Formula/gplcver.rb | Ruby | bsd-2-clause | 576 |
/**
* angular-strap
* @version v2.1.2 - 2014-10-19
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes (olivier@mg-crea.com)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('mgcrea.ngStrap.popover').run(['$templateCache', function($templateCache) {
$templateCache.put('popover/popover.tpl.html', '<div class="popover"><div class="arrow"></div><h3 class="popover-title" ng-bind="title" ng-show="title"></h3><div class="popover-content" ng-bind="content"></div></div>');
}]); | radhikabhanu/crowdsource-platform | staticfiles/bower_components/angular-strap/dist/modules/popover.tpl.js | JavaScript | mit | 553 |
module.exports = TapProducer
var Results = require("./tap-results")
, inherits = require("inherits")
, yamlish = require("yamlish")
TapProducer.encode = function (result, diag) {
var tp = new TapProducer(diag)
, out = ""
tp.on("data", function (c) { out += c })
if (Array.isArray(result)) {
result.forEach(tp.write, tp)
} else tp.write(result)
tp.end()
return out
}
var Stream = require("stream").Stream
inherits(TapProducer, Stream)
function TapProducer (diag) {
Stream.call(this)
this.diag = diag
this.count = 0
this.readable = this.writable = true
this.results = new Results
}
TapProducer.prototype.trailer = true
TapProducer.prototype.write = function (res) {
// console.error("TapProducer.write", res)
if (typeof res === "function") throw new Error("wtf?")
if (!this.writable) this.emit("error", new Error("not writable"))
if (!this._didHead) {
this.emit("data", "TAP version 13\n")
this._didHead = true
}
var diag = res.diag
if (diag === undefined) diag = this.diag
this.emit("data", encodeResult(res, this.count + 1, diag))
if (typeof res === "string") return true
if (res.bailout) {
var bo = "bail out!"
if (typeof res.bailout === "string") bo += " " + res.bailout
this.emit("data", bo)
return
}
this.results.add(res, false)
this.count ++
}
TapProducer.prototype.end = function (res) {
if (res) this.write(res)
// console.error("TapProducer end", res, this.results)
this.emit("data", "\n1.."+this.results.testsTotal+"\n")
if (this.trailer && typeof this.trailer !== "string") {
// summary trailer.
var trailer = "tests "+this.results.testsTotal + "\n"
if (this.results.pass) {
trailer += "pass " + this.results.pass + "\n"
}
if (this.results.fail) {
trailer += "fail " + this.results.fail + "\n"
}
if (this.results.skip) {
trailer += "skip "+this.results.skip + "\n"
}
if (this.results.todo) {
trailer += "todo "+this.results.todo + "\n"
}
if (this.results.bailedOut) {
trailer += "bailed out" + "\n"
}
if (this.results.testsTotal === this.results.pass) {
trailer += "\nok\n"
}
this.trailer = trailer
}
if (this.trailer) this.write(this.trailer)
this.writable = false
this.emit("end", null, this.count, this.ok)
}
function encodeResult (res, count, diag) {
// console.error(res, count, diag)
if (typeof res === "string") {
res = res.split(/\r?\n/).map(function (l) {
if (!l.trim()) return l.trim()
return "# " + l
}).join("\n")
if (res.substr(-1) !== "\n") res += "\n"
return res
}
if (res.bailout) return ""
if (!!process.env.TAP_NODIAG) diag = false
else if (!!process.env.TAP_DIAG) diag = true
else if (diag === undefined) diag = !res.ok
var output = ""
res.name = res.name && ("" + res.name).trim()
output += ( !res.ok ? "not " : "") + "ok " + count
+ ( !res.name ? ""
: " " + res.name.replace(/[\r\n]/g, " ") )
+ ( res.skip ? " # SKIP " + ( res.explanation || "" )
: res.todo ? " # TODO " + ( res.explanation || "" )
: "" )
+ "\n"
if (!diag) return output
var d = {}
, dc = 0
Object.keys(res).filter(function (k) {
return k !== "ok" && k !== "name" && k !== "id"
}).forEach(function (k) {
dc ++
d[k] = res[k]
})
//console.error(d, "about to encode")
if (dc > 0) output += " ---"+yamlish.encode(d)+"\n ...\n"
return output
}
| joshdrink/app_swig | wp-content/themes/brew/node_modules/grunt-contrib-nodeunit/node_modules/nodeunit/node_modules/tap/lib/tap-producer.js | JavaScript | gpl-2.0 | 3,516 |
// Code generated by protoc-gen-gogo.
// source: combos/unsafeboth/one.proto
// DO NOT EDIT!
/*
Package one is a generated protocol buffer package.
It is generated from these files:
combos/unsafeboth/one.proto
It has these top-level messages:
Subby
AllTypesOneOf
TwoOneofs
CustomOneof
*/
package one
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/gogo/protobuf/gogoproto"
import github_com_gogo_protobuf_test_custom "github.com/gogo/protobuf/test/custom"
import github_com_gogo_protobuf_test_casttype "github.com/gogo/protobuf/test/casttype"
import github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
import compress_gzip "compress/gzip"
import bytes "bytes"
import io_ioutil "io/ioutil"
import strings "strings"
import reflect "reflect"
import unsafe "unsafe"
import io "io"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
type Subby struct {
Sub *string `protobuf:"bytes,1,opt,name=sub" json:"sub,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *Subby) Reset() { *m = Subby{} }
func (*Subby) ProtoMessage() {}
func (*Subby) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{0} }
type AllTypesOneOf struct {
// Types that are valid to be assigned to TestOneof:
// *AllTypesOneOf_Field1
// *AllTypesOneOf_Field2
// *AllTypesOneOf_Field3
// *AllTypesOneOf_Field4
// *AllTypesOneOf_Field5
// *AllTypesOneOf_Field6
// *AllTypesOneOf_Field7
// *AllTypesOneOf_Field8
// *AllTypesOneOf_Field9
// *AllTypesOneOf_Field10
// *AllTypesOneOf_Field11
// *AllTypesOneOf_Field12
// *AllTypesOneOf_Field13
// *AllTypesOneOf_Field14
// *AllTypesOneOf_Field15
// *AllTypesOneOf_SubMessage
TestOneof isAllTypesOneOf_TestOneof `protobuf_oneof:"test_oneof"`
XXX_unrecognized []byte `json:"-"`
}
func (m *AllTypesOneOf) Reset() { *m = AllTypesOneOf{} }
func (*AllTypesOneOf) ProtoMessage() {}
func (*AllTypesOneOf) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{1} }
type isAllTypesOneOf_TestOneof interface {
isAllTypesOneOf_TestOneof()
Equal(interface{}) bool
VerboseEqual(interface{}) error
MarshalTo([]byte) (int, error)
Size() int
}
type AllTypesOneOf_Field1 struct {
Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,oneof"`
}
type AllTypesOneOf_Field2 struct {
Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,oneof"`
}
type AllTypesOneOf_Field3 struct {
Field3 int32 `protobuf:"varint,3,opt,name=Field3,oneof"`
}
type AllTypesOneOf_Field4 struct {
Field4 int64 `protobuf:"varint,4,opt,name=Field4,oneof"`
}
type AllTypesOneOf_Field5 struct {
Field5 uint32 `protobuf:"varint,5,opt,name=Field5,oneof"`
}
type AllTypesOneOf_Field6 struct {
Field6 uint64 `protobuf:"varint,6,opt,name=Field6,oneof"`
}
type AllTypesOneOf_Field7 struct {
Field7 int32 `protobuf:"zigzag32,7,opt,name=Field7,oneof"`
}
type AllTypesOneOf_Field8 struct {
Field8 int64 `protobuf:"zigzag64,8,opt,name=Field8,oneof"`
}
type AllTypesOneOf_Field9 struct {
Field9 uint32 `protobuf:"fixed32,9,opt,name=Field9,oneof"`
}
type AllTypesOneOf_Field10 struct {
Field10 int32 `protobuf:"fixed32,10,opt,name=Field10,oneof"`
}
type AllTypesOneOf_Field11 struct {
Field11 uint64 `protobuf:"fixed64,11,opt,name=Field11,oneof"`
}
type AllTypesOneOf_Field12 struct {
Field12 int64 `protobuf:"fixed64,12,opt,name=Field12,oneof"`
}
type AllTypesOneOf_Field13 struct {
Field13 bool `protobuf:"varint,13,opt,name=Field13,oneof"`
}
type AllTypesOneOf_Field14 struct {
Field14 string `protobuf:"bytes,14,opt,name=Field14,oneof"`
}
type AllTypesOneOf_Field15 struct {
Field15 []byte `protobuf:"bytes,15,opt,name=Field15,oneof"`
}
type AllTypesOneOf_SubMessage struct {
SubMessage *Subby `protobuf:"bytes,16,opt,name=sub_message,json=subMessage,oneof"`
}
func (*AllTypesOneOf_Field1) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field2) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field3) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field4) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field5) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field6) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field7) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field8) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field9) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field10) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field11) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field12) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field13) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field14) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field15) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_SubMessage) isAllTypesOneOf_TestOneof() {}
func (m *AllTypesOneOf) GetTestOneof() isAllTypesOneOf_TestOneof {
if m != nil {
return m.TestOneof
}
return nil
}
func (m *AllTypesOneOf) GetField1() float64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field1); ok {
return x.Field1
}
return 0
}
func (m *AllTypesOneOf) GetField2() float32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field2); ok {
return x.Field2
}
return 0
}
func (m *AllTypesOneOf) GetField3() int32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field3); ok {
return x.Field3
}
return 0
}
func (m *AllTypesOneOf) GetField4() int64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field4); ok {
return x.Field4
}
return 0
}
func (m *AllTypesOneOf) GetField5() uint32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field5); ok {
return x.Field5
}
return 0
}
func (m *AllTypesOneOf) GetField6() uint64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field6); ok {
return x.Field6
}
return 0
}
func (m *AllTypesOneOf) GetField7() int32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field7); ok {
return x.Field7
}
return 0
}
func (m *AllTypesOneOf) GetField8() int64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field8); ok {
return x.Field8
}
return 0
}
func (m *AllTypesOneOf) GetField9() uint32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field9); ok {
return x.Field9
}
return 0
}
func (m *AllTypesOneOf) GetField10() int32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field10); ok {
return x.Field10
}
return 0
}
func (m *AllTypesOneOf) GetField11() uint64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field11); ok {
return x.Field11
}
return 0
}
func (m *AllTypesOneOf) GetField12() int64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field12); ok {
return x.Field12
}
return 0
}
func (m *AllTypesOneOf) GetField13() bool {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field13); ok {
return x.Field13
}
return false
}
func (m *AllTypesOneOf) GetField14() string {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field14); ok {
return x.Field14
}
return ""
}
func (m *AllTypesOneOf) GetField15() []byte {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field15); ok {
return x.Field15
}
return nil
}
func (m *AllTypesOneOf) GetSubMessage() *Subby {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_SubMessage); ok {
return x.SubMessage
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*AllTypesOneOf) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _AllTypesOneOf_OneofMarshaler, _AllTypesOneOf_OneofUnmarshaler, _AllTypesOneOf_OneofSizer, []interface{}{
(*AllTypesOneOf_Field1)(nil),
(*AllTypesOneOf_Field2)(nil),
(*AllTypesOneOf_Field3)(nil),
(*AllTypesOneOf_Field4)(nil),
(*AllTypesOneOf_Field5)(nil),
(*AllTypesOneOf_Field6)(nil),
(*AllTypesOneOf_Field7)(nil),
(*AllTypesOneOf_Field8)(nil),
(*AllTypesOneOf_Field9)(nil),
(*AllTypesOneOf_Field10)(nil),
(*AllTypesOneOf_Field11)(nil),
(*AllTypesOneOf_Field12)(nil),
(*AllTypesOneOf_Field13)(nil),
(*AllTypesOneOf_Field14)(nil),
(*AllTypesOneOf_Field15)(nil),
(*AllTypesOneOf_SubMessage)(nil),
}
}
func _AllTypesOneOf_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*AllTypesOneOf)
// test_oneof
switch x := m.TestOneof.(type) {
case *AllTypesOneOf_Field1:
_ = b.EncodeVarint(1<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(math.Float64bits(x.Field1))
case *AllTypesOneOf_Field2:
_ = b.EncodeVarint(2<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2)))
case *AllTypesOneOf_Field3:
_ = b.EncodeVarint(3<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field3))
case *AllTypesOneOf_Field4:
_ = b.EncodeVarint(4<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field4))
case *AllTypesOneOf_Field5:
_ = b.EncodeVarint(5<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field5))
case *AllTypesOneOf_Field6:
_ = b.EncodeVarint(6<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field6))
case *AllTypesOneOf_Field7:
_ = b.EncodeVarint(7<<3 | proto.WireVarint)
_ = b.EncodeZigzag32(uint64(x.Field7))
case *AllTypesOneOf_Field8:
_ = b.EncodeVarint(8<<3 | proto.WireVarint)
_ = b.EncodeZigzag64(uint64(x.Field8))
case *AllTypesOneOf_Field9:
_ = b.EncodeVarint(9<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(x.Field9))
case *AllTypesOneOf_Field10:
_ = b.EncodeVarint(10<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(x.Field10))
case *AllTypesOneOf_Field11:
_ = b.EncodeVarint(11<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(uint64(x.Field11))
case *AllTypesOneOf_Field12:
_ = b.EncodeVarint(12<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(uint64(x.Field12))
case *AllTypesOneOf_Field13:
t := uint64(0)
if x.Field13 {
t = 1
}
_ = b.EncodeVarint(13<<3 | proto.WireVarint)
_ = b.EncodeVarint(t)
case *AllTypesOneOf_Field14:
_ = b.EncodeVarint(14<<3 | proto.WireBytes)
_ = b.EncodeStringBytes(x.Field14)
case *AllTypesOneOf_Field15:
_ = b.EncodeVarint(15<<3 | proto.WireBytes)
_ = b.EncodeRawBytes(x.Field15)
case *AllTypesOneOf_SubMessage:
_ = b.EncodeVarint(16<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.SubMessage); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("AllTypesOneOf.TestOneof has unexpected type %T", x)
}
return nil
}
func _AllTypesOneOf_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*AllTypesOneOf)
switch tag {
case 1: // test_oneof.Field1
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &AllTypesOneOf_Field1{math.Float64frombits(x)}
return true, err
case 2: // test_oneof.Field2
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &AllTypesOneOf_Field2{math.Float32frombits(uint32(x))}
return true, err
case 3: // test_oneof.Field3
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field3{int32(x)}
return true, err
case 4: // test_oneof.Field4
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field4{int64(x)}
return true, err
case 5: // test_oneof.Field5
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field5{uint32(x)}
return true, err
case 6: // test_oneof.Field6
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field6{x}
return true, err
case 7: // test_oneof.Field7
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeZigzag32()
m.TestOneof = &AllTypesOneOf_Field7{int32(x)}
return true, err
case 8: // test_oneof.Field8
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeZigzag64()
m.TestOneof = &AllTypesOneOf_Field8{int64(x)}
return true, err
case 9: // test_oneof.Field9
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &AllTypesOneOf_Field9{uint32(x)}
return true, err
case 10: // test_oneof.Field10
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &AllTypesOneOf_Field10{int32(x)}
return true, err
case 11: // test_oneof.Field11
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &AllTypesOneOf_Field11{x}
return true, err
case 12: // test_oneof.Field12
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &AllTypesOneOf_Field12{int64(x)}
return true, err
case 13: // test_oneof.Field13
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field13{x != 0}
return true, err
case 14: // test_oneof.Field14
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.TestOneof = &AllTypesOneOf_Field14{x}
return true, err
case 15: // test_oneof.Field15
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
m.TestOneof = &AllTypesOneOf_Field15{x}
return true, err
case 16: // test_oneof.sub_message
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(Subby)
err := b.DecodeMessage(msg)
m.TestOneof = &AllTypesOneOf_SubMessage{msg}
return true, err
default:
return false, nil
}
}
func _AllTypesOneOf_OneofSizer(msg proto.Message) (n int) {
m := msg.(*AllTypesOneOf)
// test_oneof
switch x := m.TestOneof.(type) {
case *AllTypesOneOf_Field1:
n += proto.SizeVarint(1<<3 | proto.WireFixed64)
n += 8
case *AllTypesOneOf_Field2:
n += proto.SizeVarint(2<<3 | proto.WireFixed32)
n += 4
case *AllTypesOneOf_Field3:
n += proto.SizeVarint(3<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field3))
case *AllTypesOneOf_Field4:
n += proto.SizeVarint(4<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field4))
case *AllTypesOneOf_Field5:
n += proto.SizeVarint(5<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field5))
case *AllTypesOneOf_Field6:
n += proto.SizeVarint(6<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field6))
case *AllTypesOneOf_Field7:
n += proto.SizeVarint(7<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64((uint32(x.Field7) << 1) ^ uint32((int32(x.Field7) >> 31))))
case *AllTypesOneOf_Field8:
n += proto.SizeVarint(8<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(uint64(x.Field8<<1) ^ uint64((int64(x.Field8) >> 63))))
case *AllTypesOneOf_Field9:
n += proto.SizeVarint(9<<3 | proto.WireFixed32)
n += 4
case *AllTypesOneOf_Field10:
n += proto.SizeVarint(10<<3 | proto.WireFixed32)
n += 4
case *AllTypesOneOf_Field11:
n += proto.SizeVarint(11<<3 | proto.WireFixed64)
n += 8
case *AllTypesOneOf_Field12:
n += proto.SizeVarint(12<<3 | proto.WireFixed64)
n += 8
case *AllTypesOneOf_Field13:
n += proto.SizeVarint(13<<3 | proto.WireVarint)
n += 1
case *AllTypesOneOf_Field14:
n += proto.SizeVarint(14<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field14)))
n += len(x.Field14)
case *AllTypesOneOf_Field15:
n += proto.SizeVarint(15<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field15)))
n += len(x.Field15)
case *AllTypesOneOf_SubMessage:
s := proto.Size(x.SubMessage)
n += proto.SizeVarint(16<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
type TwoOneofs struct {
// Types that are valid to be assigned to One:
// *TwoOneofs_Field1
// *TwoOneofs_Field2
// *TwoOneofs_Field3
One isTwoOneofs_One `protobuf_oneof:"one"`
// Types that are valid to be assigned to Two:
// *TwoOneofs_Field34
// *TwoOneofs_Field35
// *TwoOneofs_SubMessage2
Two isTwoOneofs_Two `protobuf_oneof:"two"`
XXX_unrecognized []byte `json:"-"`
}
func (m *TwoOneofs) Reset() { *m = TwoOneofs{} }
func (*TwoOneofs) ProtoMessage() {}
func (*TwoOneofs) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{2} }
type isTwoOneofs_One interface {
isTwoOneofs_One()
Equal(interface{}) bool
VerboseEqual(interface{}) error
MarshalTo([]byte) (int, error)
Size() int
}
type isTwoOneofs_Two interface {
isTwoOneofs_Two()
Equal(interface{}) bool
VerboseEqual(interface{}) error
MarshalTo([]byte) (int, error)
Size() int
}
type TwoOneofs_Field1 struct {
Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,oneof"`
}
type TwoOneofs_Field2 struct {
Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,oneof"`
}
type TwoOneofs_Field3 struct {
Field3 int32 `protobuf:"varint,3,opt,name=Field3,oneof"`
}
type TwoOneofs_Field34 struct {
Field34 string `protobuf:"bytes,34,opt,name=Field34,oneof"`
}
type TwoOneofs_Field35 struct {
Field35 []byte `protobuf:"bytes,35,opt,name=Field35,oneof"`
}
type TwoOneofs_SubMessage2 struct {
SubMessage2 *Subby `protobuf:"bytes,36,opt,name=sub_message2,json=subMessage2,oneof"`
}
func (*TwoOneofs_Field1) isTwoOneofs_One() {}
func (*TwoOneofs_Field2) isTwoOneofs_One() {}
func (*TwoOneofs_Field3) isTwoOneofs_One() {}
func (*TwoOneofs_Field34) isTwoOneofs_Two() {}
func (*TwoOneofs_Field35) isTwoOneofs_Two() {}
func (*TwoOneofs_SubMessage2) isTwoOneofs_Two() {}
func (m *TwoOneofs) GetOne() isTwoOneofs_One {
if m != nil {
return m.One
}
return nil
}
func (m *TwoOneofs) GetTwo() isTwoOneofs_Two {
if m != nil {
return m.Two
}
return nil
}
func (m *TwoOneofs) GetField1() float64 {
if x, ok := m.GetOne().(*TwoOneofs_Field1); ok {
return x.Field1
}
return 0
}
func (m *TwoOneofs) GetField2() float32 {
if x, ok := m.GetOne().(*TwoOneofs_Field2); ok {
return x.Field2
}
return 0
}
func (m *TwoOneofs) GetField3() int32 {
if x, ok := m.GetOne().(*TwoOneofs_Field3); ok {
return x.Field3
}
return 0
}
func (m *TwoOneofs) GetField34() string {
if x, ok := m.GetTwo().(*TwoOneofs_Field34); ok {
return x.Field34
}
return ""
}
func (m *TwoOneofs) GetField35() []byte {
if x, ok := m.GetTwo().(*TwoOneofs_Field35); ok {
return x.Field35
}
return nil
}
func (m *TwoOneofs) GetSubMessage2() *Subby {
if x, ok := m.GetTwo().(*TwoOneofs_SubMessage2); ok {
return x.SubMessage2
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{
(*TwoOneofs_Field1)(nil),
(*TwoOneofs_Field2)(nil),
(*TwoOneofs_Field3)(nil),
(*TwoOneofs_Field34)(nil),
(*TwoOneofs_Field35)(nil),
(*TwoOneofs_SubMessage2)(nil),
}
}
func _TwoOneofs_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*TwoOneofs)
// one
switch x := m.One.(type) {
case *TwoOneofs_Field1:
_ = b.EncodeVarint(1<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(math.Float64bits(x.Field1))
case *TwoOneofs_Field2:
_ = b.EncodeVarint(2<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2)))
case *TwoOneofs_Field3:
_ = b.EncodeVarint(3<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field3))
case nil:
default:
return fmt.Errorf("TwoOneofs.One has unexpected type %T", x)
}
// two
switch x := m.Two.(type) {
case *TwoOneofs_Field34:
_ = b.EncodeVarint(34<<3 | proto.WireBytes)
_ = b.EncodeStringBytes(x.Field34)
case *TwoOneofs_Field35:
_ = b.EncodeVarint(35<<3 | proto.WireBytes)
_ = b.EncodeRawBytes(x.Field35)
case *TwoOneofs_SubMessage2:
_ = b.EncodeVarint(36<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.SubMessage2); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("TwoOneofs.Two has unexpected type %T", x)
}
return nil
}
func _TwoOneofs_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*TwoOneofs)
switch tag {
case 1: // one.Field1
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.One = &TwoOneofs_Field1{math.Float64frombits(x)}
return true, err
case 2: // one.Field2
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.One = &TwoOneofs_Field2{math.Float32frombits(uint32(x))}
return true, err
case 3: // one.Field3
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.One = &TwoOneofs_Field3{int32(x)}
return true, err
case 34: // two.Field34
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Two = &TwoOneofs_Field34{x}
return true, err
case 35: // two.Field35
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
m.Two = &TwoOneofs_Field35{x}
return true, err
case 36: // two.sub_message2
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(Subby)
err := b.DecodeMessage(msg)
m.Two = &TwoOneofs_SubMessage2{msg}
return true, err
default:
return false, nil
}
}
func _TwoOneofs_OneofSizer(msg proto.Message) (n int) {
m := msg.(*TwoOneofs)
// one
switch x := m.One.(type) {
case *TwoOneofs_Field1:
n += proto.SizeVarint(1<<3 | proto.WireFixed64)
n += 8
case *TwoOneofs_Field2:
n += proto.SizeVarint(2<<3 | proto.WireFixed32)
n += 4
case *TwoOneofs_Field3:
n += proto.SizeVarint(3<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field3))
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
// two
switch x := m.Two.(type) {
case *TwoOneofs_Field34:
n += proto.SizeVarint(34<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field34)))
n += len(x.Field34)
case *TwoOneofs_Field35:
n += proto.SizeVarint(35<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field35)))
n += len(x.Field35)
case *TwoOneofs_SubMessage2:
s := proto.Size(x.SubMessage2)
n += proto.SizeVarint(36<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
type CustomOneof struct {
// Types that are valid to be assigned to Custom:
// *CustomOneof_Stringy
// *CustomOneof_CustomType
// *CustomOneof_CastType
// *CustomOneof_MyCustomName
Custom isCustomOneof_Custom `protobuf_oneof:"custom"`
XXX_unrecognized []byte `json:"-"`
}
func (m *CustomOneof) Reset() { *m = CustomOneof{} }
func (*CustomOneof) ProtoMessage() {}
func (*CustomOneof) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{3} }
type isCustomOneof_Custom interface {
isCustomOneof_Custom()
Equal(interface{}) bool
VerboseEqual(interface{}) error
MarshalTo([]byte) (int, error)
Size() int
}
type CustomOneof_Stringy struct {
Stringy string `protobuf:"bytes,34,opt,name=Stringy,oneof"`
}
type CustomOneof_CustomType struct {
CustomType github_com_gogo_protobuf_test_custom.Uint128 `protobuf:"bytes,35,opt,name=CustomType,oneof,customtype=github.com/gogo/protobuf/test/custom.Uint128"`
}
type CustomOneof_CastType struct {
CastType github_com_gogo_protobuf_test_casttype.MyUint64Type `protobuf:"varint,36,opt,name=CastType,oneof,casttype=github.com/gogo/protobuf/test/casttype.MyUint64Type"`
}
type CustomOneof_MyCustomName struct {
MyCustomName int64 `protobuf:"varint,37,opt,name=CustomName,oneof"`
}
func (*CustomOneof_Stringy) isCustomOneof_Custom() {}
func (*CustomOneof_CustomType) isCustomOneof_Custom() {}
func (*CustomOneof_CastType) isCustomOneof_Custom() {}
func (*CustomOneof_MyCustomName) isCustomOneof_Custom() {}
func (m *CustomOneof) GetCustom() isCustomOneof_Custom {
if m != nil {
return m.Custom
}
return nil
}
func (m *CustomOneof) GetStringy() string {
if x, ok := m.GetCustom().(*CustomOneof_Stringy); ok {
return x.Stringy
}
return ""
}
func (m *CustomOneof) GetCastType() github_com_gogo_protobuf_test_casttype.MyUint64Type {
if x, ok := m.GetCustom().(*CustomOneof_CastType); ok {
return x.CastType
}
return 0
}
func (m *CustomOneof) GetMyCustomName() int64 {
if x, ok := m.GetCustom().(*CustomOneof_MyCustomName); ok {
return x.MyCustomName
}
return 0
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*CustomOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _CustomOneof_OneofMarshaler, _CustomOneof_OneofUnmarshaler, _CustomOneof_OneofSizer, []interface{}{
(*CustomOneof_Stringy)(nil),
(*CustomOneof_CustomType)(nil),
(*CustomOneof_CastType)(nil),
(*CustomOneof_MyCustomName)(nil),
}
}
func _CustomOneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*CustomOneof)
// custom
switch x := m.Custom.(type) {
case *CustomOneof_Stringy:
_ = b.EncodeVarint(34<<3 | proto.WireBytes)
_ = b.EncodeStringBytes(x.Stringy)
case *CustomOneof_CustomType:
_ = b.EncodeVarint(35<<3 | proto.WireBytes)
dAtA, err := x.CustomType.Marshal()
if err != nil {
return err
}
_ = b.EncodeRawBytes(dAtA)
case *CustomOneof_CastType:
_ = b.EncodeVarint(36<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.CastType))
case *CustomOneof_MyCustomName:
_ = b.EncodeVarint(37<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.MyCustomName))
case nil:
default:
return fmt.Errorf("CustomOneof.Custom has unexpected type %T", x)
}
return nil
}
func _CustomOneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*CustomOneof)
switch tag {
case 34: // custom.Stringy
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Custom = &CustomOneof_Stringy{x}
return true, err
case 35: // custom.CustomType
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
if err != nil {
return true, err
}
var cc github_com_gogo_protobuf_test_custom.Uint128
c := &cc
err = c.Unmarshal(x)
m.Custom = &CustomOneof_CustomType{*c}
return true, err
case 36: // custom.CastType
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Custom = &CustomOneof_CastType{github_com_gogo_protobuf_test_casttype.MyUint64Type(x)}
return true, err
case 37: // custom.CustomName
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Custom = &CustomOneof_MyCustomName{int64(x)}
return true, err
default:
return false, nil
}
}
func _CustomOneof_OneofSizer(msg proto.Message) (n int) {
m := msg.(*CustomOneof)
// custom
switch x := m.Custom.(type) {
case *CustomOneof_Stringy:
n += proto.SizeVarint(34<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Stringy)))
n += len(x.Stringy)
case *CustomOneof_CustomType:
n += proto.SizeVarint(35<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(x.CustomType.Size()))
n += x.CustomType.Size()
case *CustomOneof_CastType:
n += proto.SizeVarint(36<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.CastType))
case *CustomOneof_MyCustomName:
n += proto.SizeVarint(37<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.MyCustomName))
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
func init() {
proto.RegisterType((*Subby)(nil), "one.Subby")
proto.RegisterType((*AllTypesOneOf)(nil), "one.AllTypesOneOf")
proto.RegisterType((*TwoOneofs)(nil), "one.TwoOneofs")
proto.RegisterType((*CustomOneof)(nil), "one.CustomOneof")
}
func (this *Subby) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func (this *AllTypesOneOf) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func (this *TwoOneofs) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func (this *CustomOneof) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func OneDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{}
var gzipped = []byte{
// 4043 bytes of a gzipped FileDescriptorSet
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x5a, 0x5b, 0x70, 0xe3, 0xe6,
0x75, 0x16, 0x78, 0x91, 0xc8, 0x43, 0x8a, 0x82, 0x20, 0x79, 0x8d, 0x95, 0x63, 0xee, 0x2e, 0x6d,
0xc7, 0xb2, 0x1d, 0x4b, 0xb6, 0x56, 0xda, 0x0b, 0xb7, 0x89, 0x87, 0xa4, 0xb8, 0x5a, 0x6d, 0x25,
0x51, 0x01, 0xa5, 0x78, 0x9d, 0x3e, 0x60, 0x40, 0xf0, 0x27, 0x85, 0x5d, 0x10, 0x60, 0x00, 0x70,
0xd7, 0xf2, 0xd3, 0x76, 0xdc, 0xcb, 0x64, 0x3a, 0xbd, 0xa5, 0x9d, 0x69, 0xe2, 0x3a, 0x6e, 0x9b,
0x99, 0xd6, 0x69, 0xd2, 0x4b, 0xd2, 0x4b, 0x9a, 0xe9, 0x53, 0x5f, 0xd2, 0xfa, 0xa9, 0xe3, 0xbc,
0x75, 0x3a, 0x1d, 0x8f, 0x57, 0xf1, 0x4c, 0xd3, 0xd6, 0x6d, 0xdd, 0xc6, 0x33, 0xcd, 0x74, 0x5f,
0x3a, 0xff, 0x0d, 0x00, 0x2f, 0x5a, 0x50, 0x99, 0x3a, 0x79, 0x92, 0x70, 0xce, 0xf9, 0x3e, 0x1c,
0x9c, 0xff, 0xfc, 0xe7, 0x1c, 0xfc, 0x04, 0x7c, 0x6f, 0x0d, 0xce, 0xb6, 0x6d, 0xbb, 0x6d, 0xa2,
0xe5, 0xae, 0x63, 0x7b, 0x76, 0xa3, 0xd7, 0x5a, 0x6e, 0x22, 0x57, 0x77, 0x8c, 0xae, 0x67, 0x3b,
0x4b, 0x44, 0x26, 0xcd, 0x50, 0x8b, 0x25, 0x6e, 0x51, 0xd8, 0x86, 0xd9, 0xab, 0x86, 0x89, 0xd6,
0x7d, 0xc3, 0x3a, 0xf2, 0xa4, 0x4b, 0x90, 0x68, 0x19, 0x26, 0x92, 0x85, 0xb3, 0xf1, 0xc5, 0xcc,
0xca, 0xe3, 0x4b, 0x03, 0xa0, 0xa5, 0x7e, 0xc4, 0x2e, 0x16, 0x2b, 0x04, 0x51, 0x78, 0x2f, 0x01,
0x73, 0x23, 0xb4, 0x92, 0x04, 0x09, 0x4b, 0xeb, 0x60, 0x46, 0x61, 0x31, 0xad, 0x90, 0xff, 0x25,
0x19, 0xa6, 0xba, 0x9a, 0x7e, 0x4b, 0x6b, 0x23, 0x39, 0x46, 0xc4, 0xfc, 0x52, 0xca, 0x03, 0x34,
0x51, 0x17, 0x59, 0x4d, 0x64, 0xe9, 0x87, 0x72, 0xfc, 0x6c, 0x7c, 0x31, 0xad, 0x84, 0x24, 0xd2,
0x33, 0x30, 0xdb, 0xed, 0x35, 0x4c, 0x43, 0x57, 0x43, 0x66, 0x70, 0x36, 0xbe, 0x98, 0x54, 0x44,
0xaa, 0x58, 0x0f, 0x8c, 0x9f, 0x84, 0x99, 0x3b, 0x48, 0xbb, 0x15, 0x36, 0xcd, 0x10, 0xd3, 0x1c,
0x16, 0x87, 0x0c, 0x2b, 0x90, 0xed, 0x20, 0xd7, 0xd5, 0xda, 0x48, 0xf5, 0x0e, 0xbb, 0x48, 0x4e,
0x90, 0xa7, 0x3f, 0x3b, 0xf4, 0xf4, 0x83, 0x4f, 0x9e, 0x61, 0xa8, 0xbd, 0xc3, 0x2e, 0x92, 0x4a,
0x90, 0x46, 0x56, 0xaf, 0x43, 0x19, 0x92, 0xc7, 0xc4, 0xaf, 0x6a, 0xf5, 0x3a, 0x83, 0x2c, 0x29,
0x0c, 0x63, 0x14, 0x53, 0x2e, 0x72, 0x6e, 0x1b, 0x3a, 0x92, 0x27, 0x09, 0xc1, 0x93, 0x43, 0x04,
0x75, 0xaa, 0x1f, 0xe4, 0xe0, 0x38, 0xa9, 0x02, 0x69, 0xf4, 0xb2, 0x87, 0x2c, 0xd7, 0xb0, 0x2d,
0x79, 0x8a, 0x90, 0x3c, 0x31, 0x62, 0x15, 0x91, 0xd9, 0x1c, 0xa4, 0x08, 0x70, 0xd2, 0x05, 0x98,
0xb2, 0xbb, 0x9e, 0x61, 0x5b, 0xae, 0x9c, 0x3a, 0x2b, 0x2c, 0x66, 0x56, 0x3e, 0x36, 0x32, 0x11,
0x6a, 0xd4, 0x46, 0xe1, 0xc6, 0xd2, 0x26, 0x88, 0xae, 0xdd, 0x73, 0x74, 0xa4, 0xea, 0x76, 0x13,
0xa9, 0x86, 0xd5, 0xb2, 0xe5, 0x34, 0x21, 0x38, 0x33, 0xfc, 0x20, 0xc4, 0xb0, 0x62, 0x37, 0xd1,
0xa6, 0xd5, 0xb2, 0x95, 0x9c, 0xdb, 0x77, 0x2d, 0x9d, 0x82, 0x49, 0xf7, 0xd0, 0xf2, 0xb4, 0x97,
0xe5, 0x2c, 0xc9, 0x10, 0x76, 0x55, 0xf8, 0x9f, 0x24, 0xcc, 0x8c, 0x93, 0x62, 0x57, 0x20, 0xd9,
0xc2, 0x4f, 0x29, 0xc7, 0x4e, 0x12, 0x03, 0x8a, 0xe9, 0x0f, 0xe2, 0xe4, 0x8f, 0x18, 0xc4, 0x12,
0x64, 0x2c, 0xe4, 0x7a, 0xa8, 0x49, 0x33, 0x22, 0x3e, 0x66, 0x4e, 0x01, 0x05, 0x0d, 0xa7, 0x54,
0xe2, 0x47, 0x4a, 0xa9, 0x1b, 0x30, 0xe3, 0xbb, 0xa4, 0x3a, 0x9a, 0xd5, 0xe6, 0xb9, 0xb9, 0x1c,
0xe5, 0xc9, 0x52, 0x95, 0xe3, 0x14, 0x0c, 0x53, 0x72, 0xa8, 0xef, 0x5a, 0x5a, 0x07, 0xb0, 0x2d,
0x64, 0xb7, 0xd4, 0x26, 0xd2, 0x4d, 0x39, 0x75, 0x4c, 0x94, 0x6a, 0xd8, 0x64, 0x28, 0x4a, 0x36,
0x95, 0xea, 0xa6, 0x74, 0x39, 0x48, 0xb5, 0xa9, 0x63, 0x32, 0x65, 0x9b, 0x6e, 0xb2, 0xa1, 0x6c,
0xdb, 0x87, 0x9c, 0x83, 0x70, 0xde, 0xa3, 0x26, 0x7b, 0xb2, 0x34, 0x71, 0x62, 0x29, 0xf2, 0xc9,
0x14, 0x06, 0xa3, 0x0f, 0x36, 0xed, 0x84, 0x2f, 0xa5, 0xc7, 0xc0, 0x17, 0xa8, 0x24, 0xad, 0x80,
0x54, 0xa1, 0x2c, 0x17, 0xee, 0x68, 0x1d, 0xb4, 0x70, 0x09, 0x72, 0xfd, 0xe1, 0x91, 0xe6, 0x21,
0xe9, 0x7a, 0x9a, 0xe3, 0x91, 0x2c, 0x4c, 0x2a, 0xf4, 0x42, 0x12, 0x21, 0x8e, 0xac, 0x26, 0xa9,
0x72, 0x49, 0x05, 0xff, 0xbb, 0x70, 0x11, 0xa6, 0xfb, 0x6e, 0x3f, 0x2e, 0xb0, 0xf0, 0xc5, 0x49,
0x98, 0x1f, 0x95, 0x73, 0x23, 0xd3, 0xff, 0x14, 0x4c, 0x5a, 0xbd, 0x4e, 0x03, 0x39, 0x72, 0x9c,
0x30, 0xb0, 0x2b, 0xa9, 0x04, 0x49, 0x53, 0x6b, 0x20, 0x53, 0x4e, 0x9c, 0x15, 0x16, 0x73, 0x2b,
0xcf, 0x8c, 0x95, 0xd5, 0x4b, 0x5b, 0x18, 0xa2, 0x50, 0xa4, 0xf4, 0x29, 0x48, 0xb0, 0x12, 0x87,
0x19, 0x9e, 0x1e, 0x8f, 0x01, 0xe7, 0xa2, 0x42, 0x70, 0xd2, 0x23, 0x90, 0xc6, 0x7f, 0x69, 0x6c,
0x27, 0x89, 0xcf, 0x29, 0x2c, 0xc0, 0x71, 0x95, 0x16, 0x20, 0x45, 0xd2, 0xac, 0x89, 0x78, 0x6b,
0xf0, 0xaf, 0xf1, 0xc2, 0x34, 0x51, 0x4b, 0xeb, 0x99, 0x9e, 0x7a, 0x5b, 0x33, 0x7b, 0x88, 0x24,
0x4c, 0x5a, 0xc9, 0x32, 0xe1, 0x67, 0xb0, 0x4c, 0x3a, 0x03, 0x19, 0x9a, 0x95, 0x86, 0xd5, 0x44,
0x2f, 0x93, 0xea, 0x93, 0x54, 0x68, 0xa2, 0x6e, 0x62, 0x09, 0xbe, 0xfd, 0x4d, 0xd7, 0xb6, 0xf8,
0xd2, 0x92, 0x5b, 0x60, 0x01, 0xb9, 0xfd, 0xc5, 0xc1, 0xc2, 0xf7, 0xe8, 0xe8, 0xc7, 0x1b, 0xcc,
0xc5, 0xc2, 0xb7, 0x62, 0x90, 0x20, 0xfb, 0x6d, 0x06, 0x32, 0x7b, 0x2f, 0xed, 0x56, 0xd5, 0xf5,
0xda, 0x7e, 0x79, 0xab, 0x2a, 0x0a, 0x52, 0x0e, 0x80, 0x08, 0xae, 0x6e, 0xd5, 0x4a, 0x7b, 0x62,
0xcc, 0xbf, 0xde, 0xdc, 0xd9, 0xbb, 0xb0, 0x2a, 0xc6, 0x7d, 0xc0, 0x3e, 0x15, 0x24, 0xc2, 0x06,
0xe7, 0x57, 0xc4, 0xa4, 0x24, 0x42, 0x96, 0x12, 0x6c, 0xde, 0xa8, 0xae, 0x5f, 0x58, 0x15, 0x27,
0xfb, 0x25, 0xe7, 0x57, 0xc4, 0x29, 0x69, 0x1a, 0xd2, 0x44, 0x52, 0xae, 0xd5, 0xb6, 0xc4, 0x94,
0xcf, 0x59, 0xdf, 0x53, 0x36, 0x77, 0x36, 0xc4, 0xb4, 0xcf, 0xb9, 0xa1, 0xd4, 0xf6, 0x77, 0x45,
0xf0, 0x19, 0xb6, 0xab, 0xf5, 0x7a, 0x69, 0xa3, 0x2a, 0x66, 0x7c, 0x8b, 0xf2, 0x4b, 0x7b, 0xd5,
0xba, 0x98, 0xed, 0x73, 0xeb, 0xfc, 0x8a, 0x38, 0xed, 0xdf, 0xa2, 0xba, 0xb3, 0xbf, 0x2d, 0xe6,
0xa4, 0x59, 0x98, 0xa6, 0xb7, 0xe0, 0x4e, 0xcc, 0x0c, 0x88, 0x2e, 0xac, 0x8a, 0x62, 0xe0, 0x08,
0x65, 0x99, 0xed, 0x13, 0x5c, 0x58, 0x15, 0xa5, 0x42, 0x05, 0x92, 0x24, 0xbb, 0x24, 0x09, 0x72,
0x5b, 0xa5, 0x72, 0x75, 0x4b, 0xad, 0xed, 0xee, 0x6d, 0xd6, 0x76, 0x4a, 0x5b, 0xa2, 0x10, 0xc8,
0x94, 0xea, 0xa7, 0xf7, 0x37, 0x95, 0xea, 0xba, 0x18, 0x0b, 0xcb, 0x76, 0xab, 0xa5, 0xbd, 0xea,
0xba, 0x18, 0x2f, 0xe8, 0x30, 0x3f, 0xaa, 0xce, 0x8c, 0xdc, 0x19, 0xa1, 0x25, 0x8e, 0x1d, 0xb3,
0xc4, 0x84, 0x6b, 0x68, 0x89, 0xbf, 0x22, 0xc0, 0xdc, 0x88, 0x5a, 0x3b, 0xf2, 0x26, 0x2f, 0x40,
0x92, 0xa6, 0x28, 0xed, 0x3e, 0x4f, 0x8d, 0x2c, 0xda, 0x24, 0x61, 0x87, 0x3a, 0x10, 0xc1, 0x85,
0x3b, 0x70, 0xfc, 0x98, 0x0e, 0x8c, 0x29, 0x86, 0x9c, 0x7c, 0x55, 0x00, 0xf9, 0x38, 0xee, 0x88,
0x42, 0x11, 0xeb, 0x2b, 0x14, 0x57, 0x06, 0x1d, 0x38, 0x77, 0xfc, 0x33, 0x0c, 0x79, 0xf1, 0xa6,
0x00, 0xa7, 0x46, 0x0f, 0x2a, 0x23, 0x7d, 0xf8, 0x14, 0x4c, 0x76, 0x90, 0x77, 0x60, 0xf3, 0x66,
0xfd, 0xf1, 0x11, 0x2d, 0x00, 0xab, 0x07, 0x63, 0xc5, 0x50, 0xe1, 0x1e, 0x12, 0x3f, 0x6e, 0xda,
0xa0, 0xde, 0x0c, 0x79, 0xfa, 0xf9, 0x18, 0x3c, 0x34, 0x92, 0x7c, 0xa4, 0xa3, 0x8f, 0x02, 0x18,
0x56, 0xb7, 0xe7, 0xd1, 0x86, 0x4c, 0xeb, 0x53, 0x9a, 0x48, 0xc8, 0xde, 0xc7, 0xb5, 0xa7, 0xe7,
0xf9, 0xfa, 0x38, 0xd1, 0x03, 0x15, 0x11, 0x83, 0x4b, 0x81, 0xa3, 0x09, 0xe2, 0x68, 0xfe, 0x98,
0x27, 0x1d, 0xea, 0x75, 0xcf, 0x81, 0xa8, 0x9b, 0x06, 0xb2, 0x3c, 0xd5, 0xf5, 0x1c, 0xa4, 0x75,
0x0c, 0xab, 0x4d, 0x0a, 0x70, 0xaa, 0x98, 0x6c, 0x69, 0xa6, 0x8b, 0x94, 0x19, 0xaa, 0xae, 0x73,
0x2d, 0x46, 0x90, 0x2e, 0xe3, 0x84, 0x10, 0x93, 0x7d, 0x08, 0xaa, 0xf6, 0x11, 0x85, 0xaf, 0x4f,
0x41, 0x26, 0x34, 0xd6, 0x49, 0xe7, 0x20, 0x7b, 0x53, 0xbb, 0xad, 0xa9, 0x7c, 0x54, 0xa7, 0x91,
0xc8, 0x60, 0xd9, 0x2e, 0x1b, 0xd7, 0x9f, 0x83, 0x79, 0x62, 0x62, 0xf7, 0x3c, 0xe4, 0xa8, 0xba,
0xa9, 0xb9, 0x2e, 0x09, 0x5a, 0x8a, 0x98, 0x4a, 0x58, 0x57, 0xc3, 0xaa, 0x0a, 0xd7, 0x48, 0x6b,
0x30, 0x47, 0x10, 0x9d, 0x9e, 0xe9, 0x19, 0x5d, 0x13, 0xa9, 0xf8, 0xe5, 0xc1, 0x25, 0x85, 0xd8,
0xf7, 0x6c, 0x16, 0x5b, 0x6c, 0x33, 0x03, 0xec, 0x91, 0x2b, 0xad, 0xc3, 0xa3, 0x04, 0xd6, 0x46,
0x16, 0x72, 0x34, 0x0f, 0xa9, 0xe8, 0x73, 0x3d, 0xcd, 0x74, 0x55, 0xcd, 0x6a, 0xaa, 0x07, 0x9a,
0x7b, 0x20, 0xcf, 0x63, 0x82, 0x72, 0x4c, 0x16, 0x94, 0xd3, 0xd8, 0x70, 0x83, 0xd9, 0x55, 0x89,
0x59, 0xc9, 0x6a, 0x5e, 0xd3, 0xdc, 0x03, 0xa9, 0x08, 0xa7, 0x08, 0x8b, 0xeb, 0x39, 0x86, 0xd5,
0x56, 0xf5, 0x03, 0xa4, 0xdf, 0x52, 0x7b, 0x5e, 0xeb, 0x92, 0xfc, 0x48, 0xf8, 0xfe, 0xc4, 0xc3,
0x3a, 0xb1, 0xa9, 0x60, 0x93, 0x7d, 0xaf, 0x75, 0x49, 0xaa, 0x43, 0x16, 0x2f, 0x46, 0xc7, 0x78,
0x05, 0xa9, 0x2d, 0xdb, 0x21, 0x9d, 0x25, 0x37, 0x62, 0x67, 0x87, 0x22, 0xb8, 0x54, 0x63, 0x80,
0x6d, 0xbb, 0x89, 0x8a, 0xc9, 0xfa, 0x6e, 0xb5, 0xba, 0xae, 0x64, 0x38, 0xcb, 0x55, 0xdb, 0xc1,
0x09, 0xd5, 0xb6, 0xfd, 0x00, 0x67, 0x68, 0x42, 0xb5, 0x6d, 0x1e, 0xde, 0x35, 0x98, 0xd3, 0x75,
0xfa, 0xcc, 0x86, 0xae, 0xb2, 0x11, 0xdf, 0x95, 0xc5, 0xbe, 0x60, 0xe9, 0xfa, 0x06, 0x35, 0x60,
0x39, 0xee, 0x4a, 0x97, 0xe1, 0xa1, 0x20, 0x58, 0x61, 0xe0, 0xec, 0xd0, 0x53, 0x0e, 0x42, 0xd7,
0x60, 0xae, 0x7b, 0x38, 0x0c, 0x94, 0xfa, 0xee, 0xd8, 0x3d, 0x1c, 0x84, 0x3d, 0x41, 0x5e, 0xdb,
0x1c, 0xa4, 0x6b, 0x1e, 0x6a, 0xca, 0x0f, 0x87, 0xad, 0x43, 0x0a, 0x69, 0x19, 0x44, 0x5d, 0x57,
0x91, 0xa5, 0x35, 0x4c, 0xa4, 0x6a, 0x0e, 0xb2, 0x34, 0x57, 0x3e, 0x13, 0x36, 0xce, 0xe9, 0x7a,
0x95, 0x68, 0x4b, 0x44, 0x29, 0x3d, 0x0d, 0xb3, 0x76, 0xe3, 0xa6, 0x4e, 0x33, 0x4b, 0xed, 0x3a,
0xa8, 0x65, 0xbc, 0x2c, 0x3f, 0x4e, 0xc2, 0x34, 0x83, 0x15, 0x24, 0xaf, 0x76, 0x89, 0x58, 0x7a,
0x0a, 0x44, 0xdd, 0x3d, 0xd0, 0x9c, 0x2e, 0x69, 0xed, 0x6e, 0x57, 0xd3, 0x91, 0xfc, 0x04, 0x35,
0xa5, 0xf2, 0x1d, 0x2e, 0xc6, 0x99, 0xed, 0xde, 0x31, 0x5a, 0x1e, 0x67, 0x7c, 0x92, 0x66, 0x36,
0x91, 0x31, 0xb6, 0x1b, 0x30, 0xdf, 0xb3, 0x0c, 0xcb, 0x43, 0x4e, 0xd7, 0x41, 0x78, 0x88, 0xa7,
0x3b, 0x51, 0xfe, 0xe7, 0xa9, 0x63, 0xc6, 0xf0, 0xfd, 0xb0, 0x35, 0x4d, 0x00, 0x65, 0xae, 0x37,
0x2c, 0x2c, 0x14, 0x21, 0x1b, 0xce, 0x0b, 0x29, 0x0d, 0x34, 0x33, 0x44, 0x01, 0xf7, 0xd8, 0x4a,
0x6d, 0x1d, 0x77, 0xc7, 0xcf, 0x56, 0xc5, 0x18, 0xee, 0xd2, 0x5b, 0x9b, 0x7b, 0x55, 0x55, 0xd9,
0xdf, 0xd9, 0xdb, 0xdc, 0xae, 0x8a, 0xf1, 0xa7, 0xd3, 0xa9, 0xef, 0x4f, 0x89, 0x77, 0xef, 0xde,
0xbd, 0x1b, 0x2b, 0x7c, 0x27, 0x06, 0xb9, 0xfe, 0xc9, 0x58, 0xfa, 0x29, 0x78, 0x98, 0xbf, 0xc6,
0xba, 0xc8, 0x53, 0xef, 0x18, 0x0e, 0x49, 0xd5, 0x8e, 0x46, 0x67, 0x4b, 0x3f, 0xca, 0xf3, 0xcc,
0xaa, 0x8e, 0xbc, 0x17, 0x0d, 0x07, 0x27, 0x62, 0x47, 0xf3, 0xa4, 0x2d, 0x38, 0x63, 0xd9, 0xaa,
0xeb, 0x69, 0x56, 0x53, 0x73, 0x9a, 0x6a, 0x70, 0x80, 0xa0, 0x6a, 0xba, 0x8e, 0x5c, 0xd7, 0xa6,
0x2d, 0xc2, 0x67, 0xf9, 0x98, 0x65, 0xd7, 0x99, 0x71, 0x50, 0x3b, 0x4b, 0xcc, 0x74, 0x20, 0x23,
0xe2, 0xc7, 0x65, 0xc4, 0x23, 0x90, 0xee, 0x68, 0x5d, 0x15, 0x59, 0x9e, 0x73, 0x48, 0xe6, 0xb9,
0x94, 0x92, 0xea, 0x68, 0xdd, 0x2a, 0xbe, 0xfe, 0xe8, 0xd6, 0x20, 0x1c, 0xc7, 0x7f, 0x8a, 0x43,
0x36, 0x3c, 0xd3, 0xe1, 0x11, 0x59, 0x27, 0xf5, 0x5b, 0x20, 0x3b, 0xfc, 0xb1, 0x07, 0x4e, 0x80,
0x4b, 0x15, 0x5c, 0xd8, 0x8b, 0x93, 0x74, 0xd2, 0x52, 0x28, 0x12, 0x37, 0x55, 0xbc, 0xa7, 0x11,
0x9d, 0xdf, 0x53, 0x0a, 0xbb, 0x92, 0x36, 0x60, 0xf2, 0xa6, 0x4b, 0xb8, 0x27, 0x09, 0xf7, 0xe3,
0x0f, 0xe6, 0xbe, 0x5e, 0x27, 0xe4, 0xe9, 0xeb, 0x75, 0x75, 0xa7, 0xa6, 0x6c, 0x97, 0xb6, 0x14,
0x06, 0x97, 0x4e, 0x43, 0xc2, 0xd4, 0x5e, 0x39, 0xec, 0x6f, 0x01, 0x44, 0x34, 0x6e, 0xe0, 0x4f,
0x43, 0xe2, 0x0e, 0xd2, 0x6e, 0xf5, 0x17, 0x5e, 0x22, 0xfa, 0x08, 0x53, 0x7f, 0x19, 0x92, 0x24,
0x5e, 0x12, 0x00, 0x8b, 0x98, 0x38, 0x21, 0xa5, 0x20, 0x51, 0xa9, 0x29, 0x38, 0xfd, 0x45, 0xc8,
0x52, 0xa9, 0xba, 0xbb, 0x59, 0xad, 0x54, 0xc5, 0x58, 0x61, 0x0d, 0x26, 0x69, 0x10, 0xf0, 0xd6,
0xf0, 0xc3, 0x20, 0x4e, 0xb0, 0x4b, 0xc6, 0x21, 0x70, 0xed, 0xfe, 0x76, 0xb9, 0xaa, 0x88, 0xb1,
0xf0, 0xf2, 0xba, 0x90, 0x0d, 0x8f, 0x73, 0x3f, 0x9e, 0x9c, 0xfa, 0x6b, 0x01, 0x32, 0xa1, 0xf1,
0x0c, 0x0f, 0x06, 0x9a, 0x69, 0xda, 0x77, 0x54, 0xcd, 0x34, 0x34, 0x97, 0x25, 0x05, 0x10, 0x51,
0x09, 0x4b, 0xc6, 0x5d, 0xb4, 0x1f, 0x8b, 0xf3, 0x6f, 0x08, 0x20, 0x0e, 0x8e, 0x76, 0x03, 0x0e,
0x0a, 0x3f, 0x51, 0x07, 0x5f, 0x17, 0x20, 0xd7, 0x3f, 0xcf, 0x0d, 0xb8, 0x77, 0xee, 0x27, 0xea,
0xde, 0xbb, 0x31, 0x98, 0xee, 0x9b, 0xe2, 0xc6, 0xf5, 0xee, 0x73, 0x30, 0x6b, 0x34, 0x51, 0xa7,
0x6b, 0x7b, 0xc8, 0xd2, 0x0f, 0x55, 0x13, 0xdd, 0x46, 0xa6, 0x5c, 0x20, 0x85, 0x62, 0xf9, 0xc1,
0x73, 0xe2, 0xd2, 0x66, 0x80, 0xdb, 0xc2, 0xb0, 0xe2, 0xdc, 0xe6, 0x7a, 0x75, 0x7b, 0xb7, 0xb6,
0x57, 0xdd, 0xa9, 0xbc, 0xa4, 0xee, 0xef, 0xfc, 0xf4, 0x4e, 0xed, 0xc5, 0x1d, 0x45, 0x34, 0x06,
0xcc, 0x3e, 0xc2, 0xad, 0xbe, 0x0b, 0xe2, 0xa0, 0x53, 0xd2, 0xc3, 0x30, 0xca, 0x2d, 0x71, 0x42,
0x9a, 0x83, 0x99, 0x9d, 0x9a, 0x5a, 0xdf, 0x5c, 0xaf, 0xaa, 0xd5, 0xab, 0x57, 0xab, 0x95, 0xbd,
0x3a, 0x7d, 0x71, 0xf6, 0xad, 0xf7, 0xfa, 0x37, 0xf5, 0x6b, 0x71, 0x98, 0x1b, 0xe1, 0x89, 0x54,
0x62, 0x33, 0x3b, 0x7d, 0x8d, 0x78, 0x76, 0x1c, 0xef, 0x97, 0xf0, 0x54, 0xb0, 0xab, 0x39, 0x1e,
0x1b, 0xf1, 0x9f, 0x02, 0x1c, 0x25, 0xcb, 0x33, 0x5a, 0x06, 0x72, 0xd8, 0x39, 0x03, 0x1d, 0xe4,
0x67, 0x02, 0x39, 0x3d, 0x6a, 0xf8, 0x04, 0x48, 0x5d, 0xdb, 0x35, 0x3c, 0xe3, 0x36, 0x52, 0x0d,
0x8b, 0x1f, 0x4a, 0xe0, 0xc1, 0x3e, 0xa1, 0x88, 0x5c, 0xb3, 0x69, 0x79, 0xbe, 0xb5, 0x85, 0xda,
0xda, 0x80, 0x35, 0x2e, 0xe0, 0x71, 0x45, 0xe4, 0x1a, 0xdf, 0xfa, 0x1c, 0x64, 0x9b, 0x76, 0x0f,
0x8f, 0x49, 0xd4, 0x0e, 0xf7, 0x0b, 0x41, 0xc9, 0x50, 0x99, 0x6f, 0xc2, 0xe6, 0xd8, 0xe0, 0x34,
0x24, 0xab, 0x64, 0xa8, 0x8c, 0x9a, 0x3c, 0x09, 0x33, 0x5a, 0xbb, 0xed, 0x60, 0x72, 0x4e, 0x44,
0x27, 0xf3, 0x9c, 0x2f, 0x26, 0x86, 0x0b, 0xd7, 0x21, 0xc5, 0xe3, 0x80, 0x5b, 0x32, 0x8e, 0x84,
0xda, 0xa5, 0x67, 0x52, 0xb1, 0xc5, 0xb4, 0x92, 0xb2, 0xb8, 0xf2, 0x1c, 0x64, 0x0d, 0x57, 0x0d,
0x0e, 0x47, 0x63, 0x67, 0x63, 0x8b, 0x29, 0x25, 0x63, 0xb8, 0xfe, 0x69, 0x58, 0xe1, 0xcd, 0x18,
0xe4, 0xfa, 0x0f, 0x77, 0xa5, 0x75, 0x48, 0x99, 0xb6, 0xae, 0x91, 0xd4, 0xa2, 0xbf, 0x2c, 0x2c,
0x46, 0x9c, 0x07, 0x2f, 0x6d, 0x31, 0x7b, 0xc5, 0x47, 0x2e, 0xfc, 0xbd, 0x00, 0x29, 0x2e, 0x96,
0x4e, 0x41, 0xa2, 0xab, 0x79, 0x07, 0x84, 0x2e, 0x59, 0x8e, 0x89, 0x82, 0x42, 0xae, 0xb1, 0xdc,
0xed, 0x6a, 0x16, 0x49, 0x01, 0x26, 0xc7, 0xd7, 0x78, 0x5d, 0x4d, 0xa4, 0x35, 0xc9, 0xd8, 0x6f,
0x77, 0x3a, 0xc8, 0xf2, 0x5c, 0xbe, 0xae, 0x4c, 0x5e, 0x61, 0x62, 0xe9, 0x19, 0x98, 0xf5, 0x1c,
0xcd, 0x30, 0xfb, 0x6c, 0x13, 0xc4, 0x56, 0xe4, 0x0a, 0xdf, 0xb8, 0x08, 0xa7, 0x39, 0x6f, 0x13,
0x79, 0x9a, 0x7e, 0x80, 0x9a, 0x01, 0x68, 0x92, 0x9c, 0x1c, 0x3e, 0xcc, 0x0c, 0xd6, 0x99, 0x9e,
0x63, 0x0b, 0xdf, 0x15, 0x60, 0x96, 0xbf, 0xa8, 0x34, 0xfd, 0x60, 0x6d, 0x03, 0x68, 0x96, 0x65,
0x7b, 0xe1, 0x70, 0x0d, 0xa7, 0xf2, 0x10, 0x6e, 0xa9, 0xe4, 0x83, 0x94, 0x10, 0xc1, 0x42, 0x07,
0x20, 0xd0, 0x1c, 0x1b, 0xb6, 0x33, 0x90, 0x61, 0x27, 0xf7, 0xe4, 0xe7, 0x1f, 0xfa, 0x6a, 0x0b,
0x54, 0x84, 0xdf, 0x68, 0xa4, 0x79, 0x48, 0x36, 0x50, 0xdb, 0xb0, 0xd8, 0x79, 0x22, 0xbd, 0xe0,
0xa7, 0x94, 0x09, 0xff, 0x94, 0xb2, 0x7c, 0x03, 0xe6, 0x74, 0xbb, 0x33, 0xe8, 0x6e, 0x59, 0x1c,
0x78, 0xbd, 0x76, 0xaf, 0x09, 0x9f, 0x85, 0x60, 0xc4, 0xfc, 0x4a, 0x2c, 0xbe, 0xb1, 0x5b, 0xfe,
0x5a, 0x6c, 0x61, 0x83, 0xe2, 0x76, 0xf9, 0x63, 0x2a, 0xa8, 0x65, 0x22, 0x1d, 0xbb, 0x0e, 0x3f,
0xf8, 0x38, 0x3c, 0xdb, 0x36, 0xbc, 0x83, 0x5e, 0x63, 0x49, 0xb7, 0x3b, 0xcb, 0x6d, 0xbb, 0x6d,
0x07, 0x3f, 0x77, 0xe1, 0x2b, 0x72, 0x41, 0xfe, 0x63, 0x3f, 0x79, 0xa5, 0x7d, 0xe9, 0x42, 0xe4,
0xef, 0x63, 0xc5, 0x1d, 0x98, 0x63, 0xc6, 0x2a, 0x39, 0x73, 0xa7, 0xaf, 0x06, 0xd2, 0x03, 0xcf,
0x5d, 0xe4, 0x6f, 0xbe, 0x47, 0x7a, 0xb5, 0x32, 0xcb, 0xa0, 0x58, 0x47, 0x5f, 0x20, 0x8a, 0x0a,
0x3c, 0xd4, 0xc7, 0x47, 0xf7, 0x25, 0x72, 0x22, 0x18, 0xbf, 0xc3, 0x18, 0xe7, 0x42, 0x8c, 0x75,
0x06, 0x2d, 0x56, 0x60, 0xfa, 0x24, 0x5c, 0x7f, 0xcb, 0xb8, 0xb2, 0x28, 0x4c, 0xb2, 0x01, 0x33,
0x84, 0x44, 0xef, 0xb9, 0x9e, 0xdd, 0x21, 0x45, 0xef, 0xc1, 0x34, 0x7f, 0xf7, 0x1e, 0xdd, 0x28,
0x39, 0x0c, 0xab, 0xf8, 0xa8, 0x62, 0x11, 0xc8, 0xcf, 0x0c, 0x4d, 0xa4, 0x9b, 0x11, 0x0c, 0x6f,
0x31, 0x47, 0x7c, 0xfb, 0xe2, 0x67, 0x60, 0x1e, 0xff, 0x4f, 0x6a, 0x52, 0xd8, 0x93, 0xe8, 0x53,
0x26, 0xf9, 0xbb, 0xaf, 0xd2, 0xbd, 0x38, 0xe7, 0x13, 0x84, 0x7c, 0x0a, 0xad, 0x62, 0x1b, 0x79,
0x1e, 0x72, 0x5c, 0x55, 0x33, 0x47, 0xb9, 0x17, 0x7a, 0x4d, 0x97, 0xbf, 0xf4, 0x7e, 0xff, 0x2a,
0x6e, 0x50, 0x64, 0xc9, 0x34, 0x8b, 0xfb, 0xf0, 0xf0, 0x88, 0xac, 0x18, 0x83, 0xf3, 0x35, 0xc6,
0x39, 0x3f, 0x94, 0x19, 0x98, 0x76, 0x17, 0xb8, 0xdc, 0x5f, 0xcb, 0x31, 0x38, 0x7f, 0x9b, 0x71,
0x4a, 0x0c, 0xcb, 0x97, 0x14, 0x33, 0x5e, 0x87, 0xd9, 0xdb, 0xc8, 0x69, 0xd8, 0x2e, 0x3b, 0x1a,
0x19, 0x83, 0xee, 0x75, 0x46, 0x37, 0xc3, 0x80, 0xe4, 0xac, 0x04, 0x73, 0x5d, 0x86, 0x54, 0x4b,
0xd3, 0xd1, 0x18, 0x14, 0x5f, 0x66, 0x14, 0x53, 0xd8, 0x1e, 0x43, 0x4b, 0x90, 0x6d, 0xdb, 0xac,
0x2d, 0x45, 0xc3, 0xdf, 0x60, 0xf0, 0x0c, 0xc7, 0x30, 0x8a, 0xae, 0xdd, 0xed, 0x99, 0xb8, 0x67,
0x45, 0x53, 0xfc, 0x0e, 0xa7, 0xe0, 0x18, 0x46, 0x71, 0x82, 0xb0, 0xfe, 0x2e, 0xa7, 0x70, 0x43,
0xf1, 0x7c, 0x01, 0x32, 0xb6, 0x65, 0x1e, 0xda, 0xd6, 0x38, 0x4e, 0xfc, 0x1e, 0x63, 0x00, 0x06,
0xc1, 0x04, 0x57, 0x20, 0x3d, 0xee, 0x42, 0xfc, 0xfe, 0xfb, 0x7c, 0x7b, 0xf0, 0x15, 0xd8, 0x80,
0x19, 0x5e, 0xa0, 0x0c, 0xdb, 0x1a, 0x83, 0xe2, 0x0f, 0x18, 0x45, 0x2e, 0x04, 0x63, 0x8f, 0xe1,
0x21, 0xd7, 0x6b, 0xa3, 0x71, 0x48, 0xde, 0xe4, 0x8f, 0xc1, 0x20, 0x2c, 0x94, 0x0d, 0x64, 0xe9,
0x07, 0xe3, 0x31, 0x7c, 0x95, 0x87, 0x92, 0x63, 0x30, 0x45, 0x05, 0xa6, 0x3b, 0x9a, 0xe3, 0x1e,
0x68, 0xe6, 0x58, 0xcb, 0xf1, 0x87, 0x8c, 0x23, 0xeb, 0x83, 0x58, 0x44, 0x7a, 0xd6, 0x49, 0x68,
0xbe, 0xc6, 0x23, 0x12, 0x82, 0xb1, 0xad, 0xe7, 0x7a, 0xe4, 0x00, 0xea, 0x24, 0x6c, 0x5f, 0xe7,
0x5b, 0x8f, 0x62, 0xb7, 0xc3, 0x8c, 0x57, 0x20, 0xed, 0x1a, 0xaf, 0x8c, 0x45, 0xf3, 0x47, 0x7c,
0xa5, 0x09, 0x00, 0x83, 0x5f, 0x82, 0xd3, 0x23, 0xdb, 0xc4, 0x18, 0x64, 0x7f, 0xcc, 0xc8, 0x4e,
0x8d, 0x68, 0x15, 0xac, 0x24, 0x9c, 0x94, 0xf2, 0x4f, 0x78, 0x49, 0x40, 0x03, 0x5c, 0xbb, 0xf8,
0x45, 0xc1, 0xd5, 0x5a, 0x27, 0x8b, 0xda, 0x9f, 0xf2, 0xa8, 0x51, 0x6c, 0x5f, 0xd4, 0xf6, 0xe0,
0x14, 0x63, 0x3c, 0xd9, 0xba, 0x7e, 0x83, 0x17, 0x56, 0x8a, 0xde, 0xef, 0x5f, 0xdd, 0x9f, 0x81,
0x05, 0x3f, 0x9c, 0x7c, 0x22, 0x75, 0xd5, 0x8e, 0xd6, 0x1d, 0x83, 0xf9, 0x9b, 0x8c, 0x99, 0x57,
0x7c, 0x7f, 0xa4, 0x75, 0xb7, 0xb5, 0x2e, 0x26, 0xbf, 0x01, 0x32, 0x27, 0xef, 0x59, 0x0e, 0xd2,
0xed, 0xb6, 0x65, 0xbc, 0x82, 0x9a, 0x63, 0x50, 0xff, 0xd9, 0xc0, 0x52, 0xed, 0x87, 0xe0, 0x98,
0x79, 0x13, 0x44, 0x7f, 0x56, 0x51, 0x8d, 0x4e, 0xd7, 0x76, 0xbc, 0x08, 0xc6, 0x3f, 0xe7, 0x2b,
0xe5, 0xe3, 0x36, 0x09, 0xac, 0x58, 0x85, 0x1c, 0xb9, 0x1c, 0x37, 0x25, 0xff, 0x82, 0x11, 0x4d,
0x07, 0x28, 0x56, 0x38, 0x74, 0xbb, 0xd3, 0xd5, 0x9c, 0x71, 0xea, 0xdf, 0x5f, 0xf2, 0xc2, 0xc1,
0x20, 0xac, 0x70, 0x78, 0x87, 0x5d, 0x84, 0xbb, 0xfd, 0x18, 0x0c, 0xdf, 0xe2, 0x85, 0x83, 0x63,
0x18, 0x05, 0x1f, 0x18, 0xc6, 0xa0, 0xf8, 0x2b, 0x4e, 0xc1, 0x31, 0x98, 0xe2, 0xd3, 0x41, 0xa3,
0x75, 0x50, 0xdb, 0x70, 0x3d, 0x87, 0xce, 0xc1, 0x0f, 0xa6, 0xfa, 0xf6, 0xfb, 0xfd, 0x43, 0x98,
0x12, 0x82, 0x16, 0xaf, 0xc3, 0xcc, 0xc0, 0x88, 0x21, 0x45, 0x7d, 0xb3, 0x20, 0xff, 0xec, 0x87,
0xac, 0x18, 0xf5, 0x4f, 0x18, 0xc5, 0x2d, 0xbc, 0xee, 0xfd, 0x73, 0x40, 0x34, 0xd9, 0xab, 0x1f,
0xfa, 0x4b, 0xdf, 0x37, 0x06, 0x14, 0xaf, 0xc2, 0x74, 0xdf, 0x0c, 0x10, 0x4d, 0xf5, 0x73, 0x8c,
0x2a, 0x1b, 0x1e, 0x01, 0x8a, 0x6b, 0x90, 0xc0, 0xfd, 0x3c, 0x1a, 0xfe, 0xf3, 0x0c, 0x4e, 0xcc,
0x8b, 0x9f, 0x84, 0x14, 0xef, 0xe3, 0xd1, 0xd0, 0x5f, 0x60, 0x50, 0x1f, 0x82, 0xe1, 0xbc, 0x87,
0x47, 0xc3, 0x7f, 0x91, 0xc3, 0x39, 0x04, 0xc3, 0xc7, 0x0f, 0xe1, 0xdf, 0xfc, 0x52, 0x82, 0xd5,
0x61, 0x1e, 0xbb, 0x2b, 0x30, 0xc5, 0x9a, 0x77, 0x34, 0xfa, 0xf3, 0xec, 0xe6, 0x1c, 0x51, 0xbc,
0x08, 0xc9, 0x31, 0x03, 0xfe, 0xcb, 0x0c, 0x4a, 0xed, 0x8b, 0x15, 0xc8, 0x84, 0x1a, 0x76, 0x34,
0xfc, 0x57, 0x18, 0x3c, 0x8c, 0xc2, 0xae, 0xb3, 0x86, 0x1d, 0x4d, 0xf0, 0xab, 0xdc, 0x75, 0x86,
0xc0, 0x61, 0xe3, 0xbd, 0x3a, 0x1a, 0xfd, 0x6b, 0x3c, 0xea, 0x1c, 0x52, 0x7c, 0x01, 0xd2, 0x7e,
0xfd, 0x8d, 0xc6, 0xff, 0x3a, 0xc3, 0x07, 0x18, 0x1c, 0x81, 0x50, 0xfd, 0x8f, 0xa6, 0xf8, 0x02,
0x8f, 0x40, 0x08, 0x85, 0xb7, 0xd1, 0x60, 0x4f, 0x8f, 0x66, 0xfa, 0x0d, 0xbe, 0x8d, 0x06, 0x5a,
0x3a, 0x5e, 0x4d, 0x52, 0x06, 0xa3, 0x29, 0x7e, 0x93, 0xaf, 0x26, 0xb1, 0xc7, 0x6e, 0x0c, 0x36,
0xc9, 0x68, 0x8e, 0xdf, 0xe2, 0x6e, 0x0c, 0xf4, 0xc8, 0xe2, 0x2e, 0x48, 0xc3, 0x0d, 0x32, 0x9a,
0xef, 0x8b, 0x8c, 0x6f, 0x76, 0xa8, 0x3f, 0x16, 0x5f, 0x84, 0x53, 0xa3, 0x9b, 0x63, 0x34, 0xeb,
0x97, 0x3e, 0x1c, 0x78, 0x9d, 0x09, 0xf7, 0xc6, 0xe2, 0x5e, 0x50, 0x65, 0xc3, 0x8d, 0x31, 0x9a,
0xf6, 0xb5, 0x0f, 0xfb, 0x0b, 0x6d, 0xb8, 0x2f, 0x16, 0x4b, 0x00, 0x41, 0x4f, 0x8a, 0xe6, 0x7a,
0x9d, 0x71, 0x85, 0x40, 0x78, 0x6b, 0xb0, 0x96, 0x14, 0x8d, 0xff, 0x32, 0xdf, 0x1a, 0x0c, 0x81,
0xb7, 0x06, 0xef, 0x46, 0xd1, 0xe8, 0x37, 0xf8, 0xd6, 0xe0, 0x90, 0xe2, 0x15, 0x48, 0x59, 0x3d,
0xd3, 0xc4, 0xb9, 0x25, 0x3d, 0xf8, 0x33, 0x22, 0xf9, 0x5f, 0xee, 0x33, 0x30, 0x07, 0x14, 0xd7,
0x20, 0x89, 0x3a, 0x0d, 0xd4, 0x8c, 0x42, 0xfe, 0xeb, 0x7d, 0x5e, 0x4f, 0xb0, 0x75, 0xf1, 0x05,
0x00, 0xfa, 0x32, 0x4d, 0x7e, 0x25, 0x8a, 0xc0, 0xfe, 0xdb, 0x7d, 0xf6, 0x85, 0x42, 0x00, 0x09,
0x08, 0xe8, 0xf7, 0x0e, 0x0f, 0x26, 0x78, 0xbf, 0x9f, 0x80, 0xbc, 0x80, 0x5f, 0x86, 0xa9, 0x9b,
0xae, 0x6d, 0x79, 0x5a, 0x3b, 0x0a, 0xfd, 0xef, 0x0c, 0xcd, 0xed, 0x71, 0xc0, 0x3a, 0xb6, 0x83,
0x3c, 0xad, 0xed, 0x46, 0x61, 0xff, 0x83, 0x61, 0x7d, 0x00, 0x06, 0xeb, 0x9a, 0xeb, 0x8d, 0xf3,
0xdc, 0xff, 0xc9, 0xc1, 0x1c, 0x80, 0x9d, 0xc6, 0xff, 0xdf, 0x42, 0x87, 0x51, 0xd8, 0x0f, 0xb8,
0xd3, 0xcc, 0xbe, 0xf8, 0x49, 0x48, 0xe3, 0x7f, 0xe9, 0x57, 0x3b, 0x11, 0xe0, 0xff, 0x62, 0xe0,
0x00, 0x81, 0xef, 0xec, 0x7a, 0x4d, 0xcf, 0x88, 0x0e, 0xf6, 0x7f, 0xb3, 0x95, 0xe6, 0xf6, 0xc5,
0x12, 0x64, 0x5c, 0xaf, 0xd9, 0xec, 0xb1, 0x89, 0x26, 0x02, 0xfe, 0x83, 0xfb, 0xfe, 0x4b, 0xae,
0x8f, 0x29, 0x9f, 0x1b, 0x7d, 0x58, 0x07, 0x1b, 0xf6, 0x86, 0x4d, 0x8f, 0xe9, 0xe0, 0x7e, 0x0a,
0x1e, 0xd1, 0xed, 0x4e, 0xc3, 0x76, 0x97, 0x69, 0x41, 0x69, 0xd8, 0xde, 0xc1, 0xb2, 0x6d, 0x31,
0x73, 0x29, 0x6e, 0x5b, 0x68, 0xe1, 0x64, 0xe7, 0x72, 0x85, 0xd3, 0x90, 0xac, 0xf7, 0x1a, 0x8d,
0x43, 0x49, 0x84, 0xb8, 0xdb, 0x6b, 0xb0, 0x0f, 0x4b, 0xf0, 0xbf, 0x85, 0x77, 0xe2, 0x30, 0x5d,
0x32, 0xcd, 0xbd, 0xc3, 0x2e, 0x72, 0x6b, 0x16, 0xaa, 0xb5, 0x24, 0x19, 0x26, 0xc9, 0x83, 0x3c,
0x4f, 0xcc, 0x84, 0x6b, 0x13, 0x0a, 0xbb, 0xf6, 0x35, 0x2b, 0xe4, 0xb8, 0x32, 0xe6, 0x6b, 0x56,
0x7c, 0xcd, 0x79, 0x7a, 0x5a, 0xe9, 0x6b, 0xce, 0xfb, 0x9a, 0x55, 0x72, 0x66, 0x19, 0xf7, 0x35,
0xab, 0xbe, 0x66, 0x8d, 0x9c, 0xc9, 0x4f, 0xfb, 0x9a, 0x35, 0x5f, 0x73, 0x81, 0x9c, 0xc2, 0x27,
0x7c, 0xcd, 0x05, 0x5f, 0x73, 0x91, 0x1c, 0xbe, 0xcf, 0xfa, 0x9a, 0x8b, 0xbe, 0xe6, 0x12, 0x39,
0x70, 0x97, 0x7c, 0xcd, 0x25, 0x5f, 0x73, 0x99, 0x7c, 0x41, 0x32, 0xe5, 0x6b, 0x2e, 0x4b, 0x0b,
0x30, 0x45, 0x9f, 0xec, 0x39, 0xf2, 0xab, 0xec, 0xcc, 0xb5, 0x09, 0x85, 0x0b, 0x02, 0xdd, 0xf3,
0xe4, 0x2b, 0x91, 0xc9, 0x40, 0xf7, 0x7c, 0xa0, 0x5b, 0x21, 0xdf, 0x4a, 0x8b, 0x81, 0x6e, 0x25,
0xd0, 0x9d, 0x97, 0xa7, 0xf1, 0xfa, 0x07, 0xba, 0xf3, 0x81, 0x6e, 0x55, 0xce, 0xe1, 0x15, 0x08,
0x74, 0xab, 0x81, 0x6e, 0x4d, 0x9e, 0x39, 0x2b, 0x2c, 0x66, 0x03, 0xdd, 0x9a, 0xf4, 0x2c, 0x64,
0xdc, 0x5e, 0x43, 0x65, 0x1f, 0x11, 0x90, 0xaf, 0x51, 0x32, 0x2b, 0xb0, 0x84, 0x73, 0x82, 0x2c,
0xeb, 0xb5, 0x09, 0x05, 0xdc, 0x5e, 0x83, 0x15, 0xc8, 0x72, 0x16, 0xc8, 0x79, 0x82, 0x4a, 0xbe,
0xc1, 0x2c, 0xbc, 0x2d, 0x40, 0x7a, 0xef, 0x8e, 0x4d, 0x7e, 0x93, 0x75, 0xff, 0x9f, 0x17, 0x97,
0x3b, 0x7d, 0x7e, 0x95, 0xfc, 0x6c, 0x96, 0xbe, 0x26, 0x28, 0x5c, 0x10, 0xe8, 0xd6, 0xe4, 0xc7,
0xc8, 0x03, 0xf9, 0xba, 0x35, 0x69, 0x19, 0xb2, 0xa1, 0x07, 0x5a, 0x21, 0x1f, 0x98, 0xf4, 0x3f,
0x91, 0xa0, 0x64, 0x82, 0x27, 0x5a, 0x29, 0x27, 0x01, 0xa7, 0x3d, 0xfe, 0xe3, 0xdd, 0xb1, 0x0b,
0x5f, 0x88, 0x41, 0x86, 0x1e, 0x41, 0x92, 0xa7, 0xc2, 0xb7, 0xa2, 0x23, 0xf9, 0x21, 0x73, 0x63,
0x42, 0xe1, 0x02, 0x49, 0x01, 0xa0, 0xa6, 0x38, 0xc3, 0xa9, 0x27, 0xe5, 0xe7, 0xfe, 0xf1, 0x9d,
0x33, 0x9f, 0x38, 0x76, 0x07, 0xe1, 0xd8, 0x2d, 0xd3, 0x02, 0xbb, 0xb4, 0x6f, 0x58, 0xde, 0xf3,
0x2b, 0x97, 0x70, 0x80, 0x03, 0x16, 0x69, 0x1f, 0x52, 0x15, 0xcd, 0x25, 0x5f, 0x98, 0x11, 0xd7,
0x13, 0xe5, 0x8b, 0xff, 0xfb, 0xce, 0x99, 0xf3, 0x11, 0x8c, 0xac, 0xf6, 0x2d, 0x6d, 0x1f, 0x62,
0xd6, 0x0b, 0xab, 0x18, 0x7e, 0x6d, 0x42, 0xf1, 0xa9, 0xa4, 0x15, 0xee, 0xea, 0x8e, 0xd6, 0xa1,
0x5f, 0xd2, 0xc4, 0xcb, 0xe2, 0xd1, 0x3b, 0x67, 0xb2, 0xdb, 0x87, 0x81, 0x3c, 0x70, 0x05, 0x5f,
0x95, 0x53, 0x30, 0x49, 0x5d, 0x2d, 0xaf, 0xbf, 0x75, 0x2f, 0x3f, 0xf1, 0xf6, 0xbd, 0xfc, 0xc4,
0x3f, 0xdc, 0xcb, 0x4f, 0xbc, 0x7b, 0x2f, 0x2f, 0x7c, 0x70, 0x2f, 0x2f, 0xfc, 0xf0, 0x5e, 0x5e,
0xb8, 0x7b, 0x94, 0x17, 0xbe, 0x7a, 0x94, 0x17, 0xbe, 0x71, 0x94, 0x17, 0xbe, 0x7d, 0x94, 0x17,
0xde, 0x3a, 0xca, 0x4f, 0xbc, 0x7d, 0x94, 0x9f, 0x78, 0xf7, 0x28, 0x2f, 0x7c, 0xff, 0x28, 0x3f,
0xf1, 0xc1, 0x51, 0x5e, 0xf8, 0xe1, 0x51, 0x5e, 0xb8, 0xfb, 0xbd, 0xbc, 0xf0, 0x7f, 0x01, 0x00,
0x00, 0xff, 0xff, 0x92, 0x09, 0x9d, 0x38, 0xda, 0x32, 0x00, 0x00,
}
r := bytes.NewReader(gzipped)
gzipr, err := compress_gzip.NewReader(r)
if err != nil {
panic(err)
}
ungzipped, err := io_ioutil.ReadAll(gzipr)
if err != nil {
panic(err)
}
if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil {
panic(err)
}
return d
}
func (this *Subby) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*Subby)
if !ok {
that2, ok := that.(Subby)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *Subby")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *Subby but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *Subby but is not nil && this == nil")
}
if this.Sub != nil && that1.Sub != nil {
if *this.Sub != *that1.Sub {
return fmt.Errorf("Sub this(%v) Not Equal that(%v)", *this.Sub, *that1.Sub)
}
} else if this.Sub != nil {
return fmt.Errorf("this.Sub == nil && that.Sub != nil")
} else if that1.Sub != nil {
return fmt.Errorf("Sub this(%v) Not Equal that(%v)", this.Sub, that1.Sub)
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *Subby) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*Subby)
if !ok {
that2, ok := that.(Subby)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Sub != nil && that1.Sub != nil {
if *this.Sub != *that1.Sub {
return false
}
} else if this.Sub != nil {
return false
} else if that1.Sub != nil {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *AllTypesOneOf) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf)
if !ok {
that2, ok := that.(AllTypesOneOf)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf but is not nil && this == nil")
}
if that1.TestOneof == nil {
if this.TestOneof != nil {
return fmt.Errorf("this.TestOneof != nil && that1.TestOneof == nil")
}
} else if this.TestOneof == nil {
return fmt.Errorf("this.TestOneof == nil && that1.TestOneof != nil")
} else if err := this.TestOneof.VerboseEqual(that1.TestOneof); err != nil {
return err
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *AllTypesOneOf_Field1) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field1)
if !ok {
that2, ok := that.(AllTypesOneOf_Field1)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field1")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field1 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field1 but is not nil && this == nil")
}
if this.Field1 != that1.Field1 {
return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1)
}
return nil
}
func (this *AllTypesOneOf_Field2) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field2)
if !ok {
that2, ok := that.(AllTypesOneOf_Field2)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field2")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field2 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field2 but is not nil && this == nil")
}
if this.Field2 != that1.Field2 {
return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2)
}
return nil
}
func (this *AllTypesOneOf_Field3) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field3)
if !ok {
that2, ok := that.(AllTypesOneOf_Field3)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field3")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field3 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field3 but is not nil && this == nil")
}
if this.Field3 != that1.Field3 {
return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3)
}
return nil
}
func (this *AllTypesOneOf_Field4) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field4)
if !ok {
that2, ok := that.(AllTypesOneOf_Field4)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field4")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field4 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field4 but is not nil && this == nil")
}
if this.Field4 != that1.Field4 {
return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", this.Field4, that1.Field4)
}
return nil
}
func (this *AllTypesOneOf_Field5) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field5)
if !ok {
that2, ok := that.(AllTypesOneOf_Field5)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field5")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field5 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field5 but is not nil && this == nil")
}
if this.Field5 != that1.Field5 {
return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", this.Field5, that1.Field5)
}
return nil
}
func (this *AllTypesOneOf_Field6) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field6)
if !ok {
that2, ok := that.(AllTypesOneOf_Field6)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field6")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field6 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field6 but is not nil && this == nil")
}
if this.Field6 != that1.Field6 {
return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", this.Field6, that1.Field6)
}
return nil
}
func (this *AllTypesOneOf_Field7) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field7)
if !ok {
that2, ok := that.(AllTypesOneOf_Field7)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field7")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field7 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field7 but is not nil && this == nil")
}
if this.Field7 != that1.Field7 {
return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", this.Field7, that1.Field7)
}
return nil
}
func (this *AllTypesOneOf_Field8) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field8)
if !ok {
that2, ok := that.(AllTypesOneOf_Field8)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field8")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field8 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field8 but is not nil && this == nil")
}
if this.Field8 != that1.Field8 {
return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", this.Field8, that1.Field8)
}
return nil
}
func (this *AllTypesOneOf_Field9) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field9)
if !ok {
that2, ok := that.(AllTypesOneOf_Field9)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field9")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field9 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field9 but is not nil && this == nil")
}
if this.Field9 != that1.Field9 {
return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", this.Field9, that1.Field9)
}
return nil
}
func (this *AllTypesOneOf_Field10) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field10)
if !ok {
that2, ok := that.(AllTypesOneOf_Field10)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field10")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field10 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field10 but is not nil && this == nil")
}
if this.Field10 != that1.Field10 {
return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", this.Field10, that1.Field10)
}
return nil
}
func (this *AllTypesOneOf_Field11) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field11)
if !ok {
that2, ok := that.(AllTypesOneOf_Field11)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field11")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field11 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field11 but is not nil && this == nil")
}
if this.Field11 != that1.Field11 {
return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", this.Field11, that1.Field11)
}
return nil
}
func (this *AllTypesOneOf_Field12) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field12)
if !ok {
that2, ok := that.(AllTypesOneOf_Field12)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field12")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field12 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field12 but is not nil && this == nil")
}
if this.Field12 != that1.Field12 {
return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", this.Field12, that1.Field12)
}
return nil
}
func (this *AllTypesOneOf_Field13) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field13)
if !ok {
that2, ok := that.(AllTypesOneOf_Field13)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field13")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field13 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field13 but is not nil && this == nil")
}
if this.Field13 != that1.Field13 {
return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", this.Field13, that1.Field13)
}
return nil
}
func (this *AllTypesOneOf_Field14) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field14)
if !ok {
that2, ok := that.(AllTypesOneOf_Field14)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field14")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field14 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field14 but is not nil && this == nil")
}
if this.Field14 != that1.Field14 {
return fmt.Errorf("Field14 this(%v) Not Equal that(%v)", this.Field14, that1.Field14)
}
return nil
}
func (this *AllTypesOneOf_Field15) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field15)
if !ok {
that2, ok := that.(AllTypesOneOf_Field15)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field15")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field15 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field15 but is not nil && this == nil")
}
if !bytes.Equal(this.Field15, that1.Field15) {
return fmt.Errorf("Field15 this(%v) Not Equal that(%v)", this.Field15, that1.Field15)
}
return nil
}
func (this *AllTypesOneOf_SubMessage) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_SubMessage)
if !ok {
that2, ok := that.(AllTypesOneOf_SubMessage)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_SubMessage")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_SubMessage but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_SubMessage but is not nil && this == nil")
}
if !this.SubMessage.Equal(that1.SubMessage) {
return fmt.Errorf("SubMessage this(%v) Not Equal that(%v)", this.SubMessage, that1.SubMessage)
}
return nil
}
func (this *AllTypesOneOf) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf)
if !ok {
that2, ok := that.(AllTypesOneOf)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if that1.TestOneof == nil {
if this.TestOneof != nil {
return false
}
} else if this.TestOneof == nil {
return false
} else if !this.TestOneof.Equal(that1.TestOneof) {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *AllTypesOneOf_Field1) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field1)
if !ok {
that2, ok := that.(AllTypesOneOf_Field1)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field1 != that1.Field1 {
return false
}
return true
}
func (this *AllTypesOneOf_Field2) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field2)
if !ok {
that2, ok := that.(AllTypesOneOf_Field2)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field2 != that1.Field2 {
return false
}
return true
}
func (this *AllTypesOneOf_Field3) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field3)
if !ok {
that2, ok := that.(AllTypesOneOf_Field3)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field3 != that1.Field3 {
return false
}
return true
}
func (this *AllTypesOneOf_Field4) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field4)
if !ok {
that2, ok := that.(AllTypesOneOf_Field4)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field4 != that1.Field4 {
return false
}
return true
}
func (this *AllTypesOneOf_Field5) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field5)
if !ok {
that2, ok := that.(AllTypesOneOf_Field5)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field5 != that1.Field5 {
return false
}
return true
}
func (this *AllTypesOneOf_Field6) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field6)
if !ok {
that2, ok := that.(AllTypesOneOf_Field6)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field6 != that1.Field6 {
return false
}
return true
}
func (this *AllTypesOneOf_Field7) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field7)
if !ok {
that2, ok := that.(AllTypesOneOf_Field7)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field7 != that1.Field7 {
return false
}
return true
}
func (this *AllTypesOneOf_Field8) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field8)
if !ok {
that2, ok := that.(AllTypesOneOf_Field8)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field8 != that1.Field8 {
return false
}
return true
}
func (this *AllTypesOneOf_Field9) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field9)
if !ok {
that2, ok := that.(AllTypesOneOf_Field9)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field9 != that1.Field9 {
return false
}
return true
}
func (this *AllTypesOneOf_Field10) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field10)
if !ok {
that2, ok := that.(AllTypesOneOf_Field10)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field10 != that1.Field10 {
return false
}
return true
}
func (this *AllTypesOneOf_Field11) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field11)
if !ok {
that2, ok := that.(AllTypesOneOf_Field11)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field11 != that1.Field11 {
return false
}
return true
}
func (this *AllTypesOneOf_Field12) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field12)
if !ok {
that2, ok := that.(AllTypesOneOf_Field12)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field12 != that1.Field12 {
return false
}
return true
}
func (this *AllTypesOneOf_Field13) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field13)
if !ok {
that2, ok := that.(AllTypesOneOf_Field13)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field13 != that1.Field13 {
return false
}
return true
}
func (this *AllTypesOneOf_Field14) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field14)
if !ok {
that2, ok := that.(AllTypesOneOf_Field14)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field14 != that1.Field14 {
return false
}
return true
}
func (this *AllTypesOneOf_Field15) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field15)
if !ok {
that2, ok := that.(AllTypesOneOf_Field15)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !bytes.Equal(this.Field15, that1.Field15) {
return false
}
return true
}
func (this *AllTypesOneOf_SubMessage) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_SubMessage)
if !ok {
that2, ok := that.(AllTypesOneOf_SubMessage)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !this.SubMessage.Equal(that1.SubMessage) {
return false
}
return true
}
func (this *TwoOneofs) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs)
if !ok {
that2, ok := that.(TwoOneofs)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs but is not nil && this == nil")
}
if that1.One == nil {
if this.One != nil {
return fmt.Errorf("this.One != nil && that1.One == nil")
}
} else if this.One == nil {
return fmt.Errorf("this.One == nil && that1.One != nil")
} else if err := this.One.VerboseEqual(that1.One); err != nil {
return err
}
if that1.Two == nil {
if this.Two != nil {
return fmt.Errorf("this.Two != nil && that1.Two == nil")
}
} else if this.Two == nil {
return fmt.Errorf("this.Two == nil && that1.Two != nil")
} else if err := this.Two.VerboseEqual(that1.Two); err != nil {
return err
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *TwoOneofs_Field1) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field1)
if !ok {
that2, ok := that.(TwoOneofs_Field1)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field1")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field1 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field1 but is not nil && this == nil")
}
if this.Field1 != that1.Field1 {
return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1)
}
return nil
}
func (this *TwoOneofs_Field2) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field2)
if !ok {
that2, ok := that.(TwoOneofs_Field2)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field2")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field2 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field2 but is not nil && this == nil")
}
if this.Field2 != that1.Field2 {
return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2)
}
return nil
}
func (this *TwoOneofs_Field3) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field3)
if !ok {
that2, ok := that.(TwoOneofs_Field3)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field3")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field3 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field3 but is not nil && this == nil")
}
if this.Field3 != that1.Field3 {
return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3)
}
return nil
}
func (this *TwoOneofs_Field34) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field34)
if !ok {
that2, ok := that.(TwoOneofs_Field34)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field34")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field34 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field34 but is not nil && this == nil")
}
if this.Field34 != that1.Field34 {
return fmt.Errorf("Field34 this(%v) Not Equal that(%v)", this.Field34, that1.Field34)
}
return nil
}
func (this *TwoOneofs_Field35) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field35)
if !ok {
that2, ok := that.(TwoOneofs_Field35)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field35")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field35 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field35 but is not nil && this == nil")
}
if !bytes.Equal(this.Field35, that1.Field35) {
return fmt.Errorf("Field35 this(%v) Not Equal that(%v)", this.Field35, that1.Field35)
}
return nil
}
func (this *TwoOneofs_SubMessage2) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_SubMessage2)
if !ok {
that2, ok := that.(TwoOneofs_SubMessage2)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_SubMessage2")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_SubMessage2 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_SubMessage2 but is not nil && this == nil")
}
if !this.SubMessage2.Equal(that1.SubMessage2) {
return fmt.Errorf("SubMessage2 this(%v) Not Equal that(%v)", this.SubMessage2, that1.SubMessage2)
}
return nil
}
func (this *TwoOneofs) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs)
if !ok {
that2, ok := that.(TwoOneofs)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if that1.One == nil {
if this.One != nil {
return false
}
} else if this.One == nil {
return false
} else if !this.One.Equal(that1.One) {
return false
}
if that1.Two == nil {
if this.Two != nil {
return false
}
} else if this.Two == nil {
return false
} else if !this.Two.Equal(that1.Two) {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *TwoOneofs_Field1) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field1)
if !ok {
that2, ok := that.(TwoOneofs_Field1)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field1 != that1.Field1 {
return false
}
return true
}
func (this *TwoOneofs_Field2) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field2)
if !ok {
that2, ok := that.(TwoOneofs_Field2)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field2 != that1.Field2 {
return false
}
return true
}
func (this *TwoOneofs_Field3) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field3)
if !ok {
that2, ok := that.(TwoOneofs_Field3)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field3 != that1.Field3 {
return false
}
return true
}
func (this *TwoOneofs_Field34) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field34)
if !ok {
that2, ok := that.(TwoOneofs_Field34)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field34 != that1.Field34 {
return false
}
return true
}
func (this *TwoOneofs_Field35) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field35)
if !ok {
that2, ok := that.(TwoOneofs_Field35)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !bytes.Equal(this.Field35, that1.Field35) {
return false
}
return true
}
func (this *TwoOneofs_SubMessage2) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_SubMessage2)
if !ok {
that2, ok := that.(TwoOneofs_SubMessage2)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !this.SubMessage2.Equal(that1.SubMessage2) {
return false
}
return true
}
func (this *CustomOneof) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof)
if !ok {
that2, ok := that.(CustomOneof)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof but is not nil && this == nil")
}
if that1.Custom == nil {
if this.Custom != nil {
return fmt.Errorf("this.Custom != nil && that1.Custom == nil")
}
} else if this.Custom == nil {
return fmt.Errorf("this.Custom == nil && that1.Custom != nil")
} else if err := this.Custom.VerboseEqual(that1.Custom); err != nil {
return err
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *CustomOneof_Stringy) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof_Stringy)
if !ok {
that2, ok := that.(CustomOneof_Stringy)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof_Stringy")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof_Stringy but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof_Stringy but is not nil && this == nil")
}
if this.Stringy != that1.Stringy {
return fmt.Errorf("Stringy this(%v) Not Equal that(%v)", this.Stringy, that1.Stringy)
}
return nil
}
func (this *CustomOneof_CustomType) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof_CustomType)
if !ok {
that2, ok := that.(CustomOneof_CustomType)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof_CustomType")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof_CustomType but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof_CustomType but is not nil && this == nil")
}
if !this.CustomType.Equal(that1.CustomType) {
return fmt.Errorf("CustomType this(%v) Not Equal that(%v)", this.CustomType, that1.CustomType)
}
return nil
}
func (this *CustomOneof_CastType) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof_CastType)
if !ok {
that2, ok := that.(CustomOneof_CastType)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof_CastType")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof_CastType but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof_CastType but is not nil && this == nil")
}
if this.CastType != that1.CastType {
return fmt.Errorf("CastType this(%v) Not Equal that(%v)", this.CastType, that1.CastType)
}
return nil
}
func (this *CustomOneof_MyCustomName) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof_MyCustomName)
if !ok {
that2, ok := that.(CustomOneof_MyCustomName)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof_MyCustomName")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof_MyCustomName but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof_MyCustomName but is not nil && this == nil")
}
if this.MyCustomName != that1.MyCustomName {
return fmt.Errorf("MyCustomName this(%v) Not Equal that(%v)", this.MyCustomName, that1.MyCustomName)
}
return nil
}
func (this *CustomOneof) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof)
if !ok {
that2, ok := that.(CustomOneof)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if that1.Custom == nil {
if this.Custom != nil {
return false
}
} else if this.Custom == nil {
return false
} else if !this.Custom.Equal(that1.Custom) {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *CustomOneof_Stringy) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof_Stringy)
if !ok {
that2, ok := that.(CustomOneof_Stringy)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Stringy != that1.Stringy {
return false
}
return true
}
func (this *CustomOneof_CustomType) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof_CustomType)
if !ok {
that2, ok := that.(CustomOneof_CustomType)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !this.CustomType.Equal(that1.CustomType) {
return false
}
return true
}
func (this *CustomOneof_CastType) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof_CastType)
if !ok {
that2, ok := that.(CustomOneof_CastType)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.CastType != that1.CastType {
return false
}
return true
}
func (this *CustomOneof_MyCustomName) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof_MyCustomName)
if !ok {
that2, ok := that.(CustomOneof_MyCustomName)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.MyCustomName != that1.MyCustomName {
return false
}
return true
}
func (this *Subby) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 5)
s = append(s, "&one.Subby{")
if this.Sub != nil {
s = append(s, "Sub: "+valueToGoStringOne(this.Sub, "string")+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *AllTypesOneOf) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 20)
s = append(s, "&one.AllTypesOneOf{")
if this.TestOneof != nil {
s = append(s, "TestOneof: "+fmt.Sprintf("%#v", this.TestOneof)+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *AllTypesOneOf_Field1) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field1{` +
`Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field2) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field2{` +
`Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field3) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field3{` +
`Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field4) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field4{` +
`Field4:` + fmt.Sprintf("%#v", this.Field4) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field5) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field5{` +
`Field5:` + fmt.Sprintf("%#v", this.Field5) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field6) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field6{` +
`Field6:` + fmt.Sprintf("%#v", this.Field6) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field7) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field7{` +
`Field7:` + fmt.Sprintf("%#v", this.Field7) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field8) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field8{` +
`Field8:` + fmt.Sprintf("%#v", this.Field8) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field9) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field9{` +
`Field9:` + fmt.Sprintf("%#v", this.Field9) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field10) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field10{` +
`Field10:` + fmt.Sprintf("%#v", this.Field10) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field11) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field11{` +
`Field11:` + fmt.Sprintf("%#v", this.Field11) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field12) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field12{` +
`Field12:` + fmt.Sprintf("%#v", this.Field12) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field13) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field13{` +
`Field13:` + fmt.Sprintf("%#v", this.Field13) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field14) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field14{` +
`Field14:` + fmt.Sprintf("%#v", this.Field14) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field15) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field15{` +
`Field15:` + fmt.Sprintf("%#v", this.Field15) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_SubMessage) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_SubMessage{` +
`SubMessage:` + fmt.Sprintf("%#v", this.SubMessage) + `}`}, ", ")
return s
}
func (this *TwoOneofs) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 10)
s = append(s, "&one.TwoOneofs{")
if this.One != nil {
s = append(s, "One: "+fmt.Sprintf("%#v", this.One)+",\n")
}
if this.Two != nil {
s = append(s, "Two: "+fmt.Sprintf("%#v", this.Two)+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *TwoOneofs_Field1) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field1{` +
`Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ")
return s
}
func (this *TwoOneofs_Field2) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field2{` +
`Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ")
return s
}
func (this *TwoOneofs_Field3) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field3{` +
`Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ")
return s
}
func (this *TwoOneofs_Field34) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field34{` +
`Field34:` + fmt.Sprintf("%#v", this.Field34) + `}`}, ", ")
return s
}
func (this *TwoOneofs_Field35) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field35{` +
`Field35:` + fmt.Sprintf("%#v", this.Field35) + `}`}, ", ")
return s
}
func (this *TwoOneofs_SubMessage2) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_SubMessage2{` +
`SubMessage2:` + fmt.Sprintf("%#v", this.SubMessage2) + `}`}, ", ")
return s
}
func (this *CustomOneof) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 8)
s = append(s, "&one.CustomOneof{")
if this.Custom != nil {
s = append(s, "Custom: "+fmt.Sprintf("%#v", this.Custom)+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *CustomOneof_Stringy) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.CustomOneof_Stringy{` +
`Stringy:` + fmt.Sprintf("%#v", this.Stringy) + `}`}, ", ")
return s
}
func (this *CustomOneof_CustomType) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.CustomOneof_CustomType{` +
`CustomType:` + fmt.Sprintf("%#v", this.CustomType) + `}`}, ", ")
return s
}
func (this *CustomOneof_CastType) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.CustomOneof_CastType{` +
`CastType:` + fmt.Sprintf("%#v", this.CastType) + `}`}, ", ")
return s
}
func (this *CustomOneof_MyCustomName) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.CustomOneof_MyCustomName{` +
`MyCustomName:` + fmt.Sprintf("%#v", this.MyCustomName) + `}`}, ", ")
return s
}
func valueToGoStringOne(v interface{}, typ string) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
}
func NewPopulatedSubby(r randyOne, easy bool) *Subby {
this := &Subby{}
if r.Intn(10) != 0 {
v1 := string(randStringOne(r))
this.Sub = &v1
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedOne(r, 2)
}
return this
}
func NewPopulatedAllTypesOneOf(r randyOne, easy bool) *AllTypesOneOf {
this := &AllTypesOneOf{}
oneofNumber_TestOneof := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}[r.Intn(16)]
switch oneofNumber_TestOneof {
case 1:
this.TestOneof = NewPopulatedAllTypesOneOf_Field1(r, easy)
case 2:
this.TestOneof = NewPopulatedAllTypesOneOf_Field2(r, easy)
case 3:
this.TestOneof = NewPopulatedAllTypesOneOf_Field3(r, easy)
case 4:
this.TestOneof = NewPopulatedAllTypesOneOf_Field4(r, easy)
case 5:
this.TestOneof = NewPopulatedAllTypesOneOf_Field5(r, easy)
case 6:
this.TestOneof = NewPopulatedAllTypesOneOf_Field6(r, easy)
case 7:
this.TestOneof = NewPopulatedAllTypesOneOf_Field7(r, easy)
case 8:
this.TestOneof = NewPopulatedAllTypesOneOf_Field8(r, easy)
case 9:
this.TestOneof = NewPopulatedAllTypesOneOf_Field9(r, easy)
case 10:
this.TestOneof = NewPopulatedAllTypesOneOf_Field10(r, easy)
case 11:
this.TestOneof = NewPopulatedAllTypesOneOf_Field11(r, easy)
case 12:
this.TestOneof = NewPopulatedAllTypesOneOf_Field12(r, easy)
case 13:
this.TestOneof = NewPopulatedAllTypesOneOf_Field13(r, easy)
case 14:
this.TestOneof = NewPopulatedAllTypesOneOf_Field14(r, easy)
case 15:
this.TestOneof = NewPopulatedAllTypesOneOf_Field15(r, easy)
case 16:
this.TestOneof = NewPopulatedAllTypesOneOf_SubMessage(r, easy)
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedOne(r, 17)
}
return this
}
func NewPopulatedAllTypesOneOf_Field1(r randyOne, easy bool) *AllTypesOneOf_Field1 {
this := &AllTypesOneOf_Field1{}
this.Field1 = float64(r.Float64())
if r.Intn(2) == 0 {
this.Field1 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field2(r randyOne, easy bool) *AllTypesOneOf_Field2 {
this := &AllTypesOneOf_Field2{}
this.Field2 = float32(r.Float32())
if r.Intn(2) == 0 {
this.Field2 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field3(r randyOne, easy bool) *AllTypesOneOf_Field3 {
this := &AllTypesOneOf_Field3{}
this.Field3 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field3 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field4(r randyOne, easy bool) *AllTypesOneOf_Field4 {
this := &AllTypesOneOf_Field4{}
this.Field4 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field4 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field5(r randyOne, easy bool) *AllTypesOneOf_Field5 {
this := &AllTypesOneOf_Field5{}
this.Field5 = uint32(r.Uint32())
return this
}
func NewPopulatedAllTypesOneOf_Field6(r randyOne, easy bool) *AllTypesOneOf_Field6 {
this := &AllTypesOneOf_Field6{}
this.Field6 = uint64(uint64(r.Uint32()))
return this
}
func NewPopulatedAllTypesOneOf_Field7(r randyOne, easy bool) *AllTypesOneOf_Field7 {
this := &AllTypesOneOf_Field7{}
this.Field7 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field7 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field8(r randyOne, easy bool) *AllTypesOneOf_Field8 {
this := &AllTypesOneOf_Field8{}
this.Field8 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field8 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field9(r randyOne, easy bool) *AllTypesOneOf_Field9 {
this := &AllTypesOneOf_Field9{}
this.Field9 = uint32(r.Uint32())
return this
}
func NewPopulatedAllTypesOneOf_Field10(r randyOne, easy bool) *AllTypesOneOf_Field10 {
this := &AllTypesOneOf_Field10{}
this.Field10 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field10 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field11(r randyOne, easy bool) *AllTypesOneOf_Field11 {
this := &AllTypesOneOf_Field11{}
this.Field11 = uint64(uint64(r.Uint32()))
return this
}
func NewPopulatedAllTypesOneOf_Field12(r randyOne, easy bool) *AllTypesOneOf_Field12 {
this := &AllTypesOneOf_Field12{}
this.Field12 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field12 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field13(r randyOne, easy bool) *AllTypesOneOf_Field13 {
this := &AllTypesOneOf_Field13{}
this.Field13 = bool(bool(r.Intn(2) == 0))
return this
}
func NewPopulatedAllTypesOneOf_Field14(r randyOne, easy bool) *AllTypesOneOf_Field14 {
this := &AllTypesOneOf_Field14{}
this.Field14 = string(randStringOne(r))
return this
}
func NewPopulatedAllTypesOneOf_Field15(r randyOne, easy bool) *AllTypesOneOf_Field15 {
this := &AllTypesOneOf_Field15{}
v2 := r.Intn(100)
this.Field15 = make([]byte, v2)
for i := 0; i < v2; i++ {
this.Field15[i] = byte(r.Intn(256))
}
return this
}
func NewPopulatedAllTypesOneOf_SubMessage(r randyOne, easy bool) *AllTypesOneOf_SubMessage {
this := &AllTypesOneOf_SubMessage{}
this.SubMessage = NewPopulatedSubby(r, easy)
return this
}
func NewPopulatedTwoOneofs(r randyOne, easy bool) *TwoOneofs {
this := &TwoOneofs{}
oneofNumber_One := []int32{1, 2, 3}[r.Intn(3)]
switch oneofNumber_One {
case 1:
this.One = NewPopulatedTwoOneofs_Field1(r, easy)
case 2:
this.One = NewPopulatedTwoOneofs_Field2(r, easy)
case 3:
this.One = NewPopulatedTwoOneofs_Field3(r, easy)
}
oneofNumber_Two := []int32{34, 35, 36}[r.Intn(3)]
switch oneofNumber_Two {
case 34:
this.Two = NewPopulatedTwoOneofs_Field34(r, easy)
case 35:
this.Two = NewPopulatedTwoOneofs_Field35(r, easy)
case 36:
this.Two = NewPopulatedTwoOneofs_SubMessage2(r, easy)
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedOne(r, 37)
}
return this
}
func NewPopulatedTwoOneofs_Field1(r randyOne, easy bool) *TwoOneofs_Field1 {
this := &TwoOneofs_Field1{}
this.Field1 = float64(r.Float64())
if r.Intn(2) == 0 {
this.Field1 *= -1
}
return this
}
func NewPopulatedTwoOneofs_Field2(r randyOne, easy bool) *TwoOneofs_Field2 {
this := &TwoOneofs_Field2{}
this.Field2 = float32(r.Float32())
if r.Intn(2) == 0 {
this.Field2 *= -1
}
return this
}
func NewPopulatedTwoOneofs_Field3(r randyOne, easy bool) *TwoOneofs_Field3 {
this := &TwoOneofs_Field3{}
this.Field3 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field3 *= -1
}
return this
}
func NewPopulatedTwoOneofs_Field34(r randyOne, easy bool) *TwoOneofs_Field34 {
this := &TwoOneofs_Field34{}
this.Field34 = string(randStringOne(r))
return this
}
func NewPopulatedTwoOneofs_Field35(r randyOne, easy bool) *TwoOneofs_Field35 {
this := &TwoOneofs_Field35{}
v3 := r.Intn(100)
this.Field35 = make([]byte, v3)
for i := 0; i < v3; i++ {
this.Field35[i] = byte(r.Intn(256))
}
return this
}
func NewPopulatedTwoOneofs_SubMessage2(r randyOne, easy bool) *TwoOneofs_SubMessage2 {
this := &TwoOneofs_SubMessage2{}
this.SubMessage2 = NewPopulatedSubby(r, easy)
return this
}
func NewPopulatedCustomOneof(r randyOne, easy bool) *CustomOneof {
this := &CustomOneof{}
oneofNumber_Custom := []int32{34, 35, 36, 37}[r.Intn(4)]
switch oneofNumber_Custom {
case 34:
this.Custom = NewPopulatedCustomOneof_Stringy(r, easy)
case 35:
this.Custom = NewPopulatedCustomOneof_CustomType(r, easy)
case 36:
this.Custom = NewPopulatedCustomOneof_CastType(r, easy)
case 37:
this.Custom = NewPopulatedCustomOneof_MyCustomName(r, easy)
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedOne(r, 38)
}
return this
}
func NewPopulatedCustomOneof_Stringy(r randyOne, easy bool) *CustomOneof_Stringy {
this := &CustomOneof_Stringy{}
this.Stringy = string(randStringOne(r))
return this
}
func NewPopulatedCustomOneof_CustomType(r randyOne, easy bool) *CustomOneof_CustomType {
this := &CustomOneof_CustomType{}
v4 := github_com_gogo_protobuf_test_custom.NewPopulatedUint128(r)
this.CustomType = *v4
return this
}
func NewPopulatedCustomOneof_CastType(r randyOne, easy bool) *CustomOneof_CastType {
this := &CustomOneof_CastType{}
this.CastType = github_com_gogo_protobuf_test_casttype.MyUint64Type(uint64(r.Uint32()))
return this
}
func NewPopulatedCustomOneof_MyCustomName(r randyOne, easy bool) *CustomOneof_MyCustomName {
this := &CustomOneof_MyCustomName{}
this.MyCustomName = int64(r.Int63())
if r.Intn(2) == 0 {
this.MyCustomName *= -1
}
return this
}
type randyOne interface {
Float32() float32
Float64() float64
Int63() int64
Int31() int32
Uint32() uint32
Intn(n int) int
}
func randUTF8RuneOne(r randyOne) rune {
ru := r.Intn(62)
if ru < 10 {
return rune(ru + 48)
} else if ru < 36 {
return rune(ru + 55)
}
return rune(ru + 61)
}
func randStringOne(r randyOne) string {
v5 := r.Intn(100)
tmps := make([]rune, v5)
for i := 0; i < v5; i++ {
tmps[i] = randUTF8RuneOne(r)
}
return string(tmps)
}
func randUnrecognizedOne(r randyOne, maxFieldNumber int) (dAtA []byte) {
l := r.Intn(5)
for i := 0; i < l; i++ {
wire := r.Intn(4)
if wire == 3 {
wire = 5
}
fieldNumber := maxFieldNumber + r.Intn(100)
dAtA = randFieldOne(dAtA, r, fieldNumber, wire)
}
return dAtA
}
func randFieldOne(dAtA []byte, r randyOne, fieldNumber int, wire int) []byte {
key := uint32(fieldNumber)<<3 | uint32(wire)
switch wire {
case 0:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
v6 := r.Int63()
if r.Intn(2) == 0 {
v6 *= -1
}
dAtA = encodeVarintPopulateOne(dAtA, uint64(v6))
case 1:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
case 2:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
ll := r.Intn(100)
dAtA = encodeVarintPopulateOne(dAtA, uint64(ll))
for j := 0; j < ll; j++ {
dAtA = append(dAtA, byte(r.Intn(256)))
}
default:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
}
return dAtA
}
func encodeVarintPopulateOne(dAtA []byte, v uint64) []byte {
for v >= 1<<7 {
dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
v >>= 7
}
dAtA = append(dAtA, uint8(v))
return dAtA
}
func (m *Subby) Size() (n int) {
var l int
_ = l
if m.Sub != nil {
l = len(*m.Sub)
n += 1 + l + sovOne(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *AllTypesOneOf) Size() (n int) {
var l int
_ = l
if m.TestOneof != nil {
n += m.TestOneof.Size()
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *AllTypesOneOf_Field1) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *AllTypesOneOf_Field2) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *AllTypesOneOf_Field3) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field3))
return n
}
func (m *AllTypesOneOf_Field4) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field4))
return n
}
func (m *AllTypesOneOf_Field5) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field5))
return n
}
func (m *AllTypesOneOf_Field6) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field6))
return n
}
func (m *AllTypesOneOf_Field7) Size() (n int) {
var l int
_ = l
n += 1 + sozOne(uint64(m.Field7))
return n
}
func (m *AllTypesOneOf_Field8) Size() (n int) {
var l int
_ = l
n += 1 + sozOne(uint64(m.Field8))
return n
}
func (m *AllTypesOneOf_Field9) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *AllTypesOneOf_Field10) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *AllTypesOneOf_Field11) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *AllTypesOneOf_Field12) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *AllTypesOneOf_Field13) Size() (n int) {
var l int
_ = l
n += 2
return n
}
func (m *AllTypesOneOf_Field14) Size() (n int) {
var l int
_ = l
l = len(m.Field14)
n += 1 + l + sovOne(uint64(l))
return n
}
func (m *AllTypesOneOf_Field15) Size() (n int) {
var l int
_ = l
if m.Field15 != nil {
l = len(m.Field15)
n += 1 + l + sovOne(uint64(l))
}
return n
}
func (m *AllTypesOneOf_SubMessage) Size() (n int) {
var l int
_ = l
if m.SubMessage != nil {
l = m.SubMessage.Size()
n += 2 + l + sovOne(uint64(l))
}
return n
}
func (m *TwoOneofs) Size() (n int) {
var l int
_ = l
if m.One != nil {
n += m.One.Size()
}
if m.Two != nil {
n += m.Two.Size()
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *TwoOneofs_Field1) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *TwoOneofs_Field2) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *TwoOneofs_Field3) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field3))
return n
}
func (m *TwoOneofs_Field34) Size() (n int) {
var l int
_ = l
l = len(m.Field34)
n += 2 + l + sovOne(uint64(l))
return n
}
func (m *TwoOneofs_Field35) Size() (n int) {
var l int
_ = l
if m.Field35 != nil {
l = len(m.Field35)
n += 2 + l + sovOne(uint64(l))
}
return n
}
func (m *TwoOneofs_SubMessage2) Size() (n int) {
var l int
_ = l
if m.SubMessage2 != nil {
l = m.SubMessage2.Size()
n += 2 + l + sovOne(uint64(l))
}
return n
}
func (m *CustomOneof) Size() (n int) {
var l int
_ = l
if m.Custom != nil {
n += m.Custom.Size()
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *CustomOneof_Stringy) Size() (n int) {
var l int
_ = l
l = len(m.Stringy)
n += 2 + l + sovOne(uint64(l))
return n
}
func (m *CustomOneof_CustomType) Size() (n int) {
var l int
_ = l
l = m.CustomType.Size()
n += 2 + l + sovOne(uint64(l))
return n
}
func (m *CustomOneof_CastType) Size() (n int) {
var l int
_ = l
n += 2 + sovOne(uint64(m.CastType))
return n
}
func (m *CustomOneof_MyCustomName) Size() (n int) {
var l int
_ = l
n += 2 + sovOne(uint64(m.MyCustomName))
return n
}
func sovOne(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozOne(x uint64) (n int) {
return sovOne(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *Subby) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&Subby{`,
`Sub:` + valueToStringOne(this.Sub) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf{`,
`TestOneof:` + fmt.Sprintf("%v", this.TestOneof) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field1) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field1{`,
`Field1:` + fmt.Sprintf("%v", this.Field1) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field2) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field2{`,
`Field2:` + fmt.Sprintf("%v", this.Field2) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field3) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field3{`,
`Field3:` + fmt.Sprintf("%v", this.Field3) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field4) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field4{`,
`Field4:` + fmt.Sprintf("%v", this.Field4) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field5) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field5{`,
`Field5:` + fmt.Sprintf("%v", this.Field5) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field6) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field6{`,
`Field6:` + fmt.Sprintf("%v", this.Field6) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field7) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field7{`,
`Field7:` + fmt.Sprintf("%v", this.Field7) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field8) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field8{`,
`Field8:` + fmt.Sprintf("%v", this.Field8) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field9) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field9{`,
`Field9:` + fmt.Sprintf("%v", this.Field9) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field10) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field10{`,
`Field10:` + fmt.Sprintf("%v", this.Field10) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field11) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field11{`,
`Field11:` + fmt.Sprintf("%v", this.Field11) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field12) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field12{`,
`Field12:` + fmt.Sprintf("%v", this.Field12) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field13) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field13{`,
`Field13:` + fmt.Sprintf("%v", this.Field13) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field14) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field14{`,
`Field14:` + fmt.Sprintf("%v", this.Field14) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field15) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field15{`,
`Field15:` + fmt.Sprintf("%v", this.Field15) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_SubMessage) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_SubMessage{`,
`SubMessage:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage), "Subby", "Subby", 1) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs{`,
`One:` + fmt.Sprintf("%v", this.One) + `,`,
`Two:` + fmt.Sprintf("%v", this.Two) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field1) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field1{`,
`Field1:` + fmt.Sprintf("%v", this.Field1) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field2) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field2{`,
`Field2:` + fmt.Sprintf("%v", this.Field2) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field3) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field3{`,
`Field3:` + fmt.Sprintf("%v", this.Field3) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field34) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field34{`,
`Field34:` + fmt.Sprintf("%v", this.Field34) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field35) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field35{`,
`Field35:` + fmt.Sprintf("%v", this.Field35) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_SubMessage2) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_SubMessage2{`,
`SubMessage2:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage2), "Subby", "Subby", 1) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof{`,
`Custom:` + fmt.Sprintf("%v", this.Custom) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof_Stringy) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof_Stringy{`,
`Stringy:` + fmt.Sprintf("%v", this.Stringy) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof_CustomType) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof_CustomType{`,
`CustomType:` + fmt.Sprintf("%v", this.CustomType) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof_CastType) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof_CastType{`,
`CastType:` + fmt.Sprintf("%v", this.CastType) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof_MyCustomName) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof_MyCustomName{`,
`MyCustomName:` + fmt.Sprintf("%v", this.MyCustomName) + `,`,
`}`,
}, "")
return s
}
func valueToStringOne(v interface{}) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func (m *Subby) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Subby) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Sub != nil {
dAtA[i] = 0xa
i++
i = encodeVarintOne(dAtA, i, uint64(len(*m.Sub)))
i += copy(dAtA[i:], *m.Sub)
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *AllTypesOneOf) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AllTypesOneOf) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.TestOneof != nil {
nn1, err := m.TestOneof.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += nn1
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *AllTypesOneOf_Field1) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x9
i++
*(*float64)(unsafe.Pointer(&dAtA[i])) = m.Field1
i += 8
return i, nil
}
func (m *AllTypesOneOf_Field2) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x15
i++
*(*float32)(unsafe.Pointer(&dAtA[i])) = m.Field2
i += 4
return i, nil
}
func (m *AllTypesOneOf_Field3) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x18
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field3))
return i, nil
}
func (m *AllTypesOneOf_Field4) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x20
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field4))
return i, nil
}
func (m *AllTypesOneOf_Field5) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x28
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field5))
return i, nil
}
func (m *AllTypesOneOf_Field6) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x30
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field6))
return i, nil
}
func (m *AllTypesOneOf_Field7) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x38
i++
i = encodeVarintOne(dAtA, i, uint64((uint32(m.Field7)<<1)^uint32((m.Field7>>31))))
return i, nil
}
func (m *AllTypesOneOf_Field8) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x40
i++
i = encodeVarintOne(dAtA, i, uint64((uint64(m.Field8)<<1)^uint64((m.Field8>>63))))
return i, nil
}
func (m *AllTypesOneOf_Field9) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x4d
i++
*(*uint32)(unsafe.Pointer(&dAtA[i])) = m.Field9
i += 4
return i, nil
}
func (m *AllTypesOneOf_Field10) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x55
i++
*(*int32)(unsafe.Pointer(&dAtA[i])) = m.Field10
i += 4
return i, nil
}
func (m *AllTypesOneOf_Field11) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x59
i++
*(*uint64)(unsafe.Pointer(&dAtA[i])) = m.Field11
i += 8
return i, nil
}
func (m *AllTypesOneOf_Field12) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x61
i++
*(*int64)(unsafe.Pointer(&dAtA[i])) = m.Field12
i += 8
return i, nil
}
func (m *AllTypesOneOf_Field13) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x68
i++
if m.Field13 {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i++
return i, nil
}
func (m *AllTypesOneOf_Field14) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x72
i++
i = encodeVarintOne(dAtA, i, uint64(len(m.Field14)))
i += copy(dAtA[i:], m.Field14)
return i, nil
}
func (m *AllTypesOneOf_Field15) MarshalTo(dAtA []byte) (int, error) {
i := 0
if m.Field15 != nil {
dAtA[i] = 0x7a
i++
i = encodeVarintOne(dAtA, i, uint64(len(m.Field15)))
i += copy(dAtA[i:], m.Field15)
}
return i, nil
}
func (m *AllTypesOneOf_SubMessage) MarshalTo(dAtA []byte) (int, error) {
i := 0
if m.SubMessage != nil {
dAtA[i] = 0x82
i++
dAtA[i] = 0x1
i++
i = encodeVarintOne(dAtA, i, uint64(m.SubMessage.Size()))
n2, err := m.SubMessage.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n2
}
return i, nil
}
func (m *TwoOneofs) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TwoOneofs) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.One != nil {
nn3, err := m.One.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += nn3
}
if m.Two != nil {
nn4, err := m.Two.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += nn4
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *TwoOneofs_Field1) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x9
i++
*(*float64)(unsafe.Pointer(&dAtA[i])) = m.Field1
i += 8
return i, nil
}
func (m *TwoOneofs_Field2) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x15
i++
*(*float32)(unsafe.Pointer(&dAtA[i])) = m.Field2
i += 4
return i, nil
}
func (m *TwoOneofs_Field3) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x18
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field3))
return i, nil
}
func (m *TwoOneofs_Field34) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x92
i++
dAtA[i] = 0x2
i++
i = encodeVarintOne(dAtA, i, uint64(len(m.Field34)))
i += copy(dAtA[i:], m.Field34)
return i, nil
}
func (m *TwoOneofs_Field35) MarshalTo(dAtA []byte) (int, error) {
i := 0
if m.Field35 != nil {
dAtA[i] = 0x9a
i++
dAtA[i] = 0x2
i++
i = encodeVarintOne(dAtA, i, uint64(len(m.Field35)))
i += copy(dAtA[i:], m.Field35)
}
return i, nil
}
func (m *TwoOneofs_SubMessage2) MarshalTo(dAtA []byte) (int, error) {
i := 0
if m.SubMessage2 != nil {
dAtA[i] = 0xa2
i++
dAtA[i] = 0x2
i++
i = encodeVarintOne(dAtA, i, uint64(m.SubMessage2.Size()))
n5, err := m.SubMessage2.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n5
}
return i, nil
}
func (m *CustomOneof) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *CustomOneof) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Custom != nil {
nn6, err := m.Custom.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += nn6
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *CustomOneof_Stringy) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x92
i++
dAtA[i] = 0x2
i++
i = encodeVarintOne(dAtA, i, uint64(len(m.Stringy)))
i += copy(dAtA[i:], m.Stringy)
return i, nil
}
func (m *CustomOneof_CustomType) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x9a
i++
dAtA[i] = 0x2
i++
i = encodeVarintOne(dAtA, i, uint64(m.CustomType.Size()))
n7, err := m.CustomType.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n7
return i, nil
}
func (m *CustomOneof_CastType) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0xa0
i++
dAtA[i] = 0x2
i++
i = encodeVarintOne(dAtA, i, uint64(m.CastType))
return i, nil
}
func (m *CustomOneof_MyCustomName) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0xa8
i++
dAtA[i] = 0x2
i++
i = encodeVarintOne(dAtA, i, uint64(m.MyCustomName))
return i, nil
}
func encodeFixed64One(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32One(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintOne(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return offset + 1
}
func (m *Subby) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Subby: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Subby: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Sub", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
s := string(dAtA[iNdEx:postIndex])
m.Sub = &s
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipOneUnsafe(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthOneUnsafe
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *AllTypesOneOf) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AllTypesOneOf: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AllTypesOneOf: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType)
}
var v float64
if iNdEx+8 > l {
return io.ErrUnexpectedEOF
}
v = *(*float64)(unsafe.Pointer(&dAtA[iNdEx]))
iNdEx += 8
m.TestOneof = &AllTypesOneOf_Field1{v}
case 2:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType)
}
var v float32
if iNdEx+4 > l {
return io.ErrUnexpectedEOF
}
v = *(*float32)(unsafe.Pointer(&dAtA[iNdEx]))
iNdEx += 4
m.TestOneof = &AllTypesOneOf_Field2{v}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field3", wireType)
}
var v int32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int32(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.TestOneof = &AllTypesOneOf_Field3{v}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field4", wireType)
}
var v int64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.TestOneof = &AllTypesOneOf_Field4{v}
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field5", wireType)
}
var v uint32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (uint32(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.TestOneof = &AllTypesOneOf_Field5{v}
case 6:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field6", wireType)
}
var v uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.TestOneof = &AllTypesOneOf_Field6{v}
case 7:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field7", wireType)
}
var v int32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int32(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
v = int32((uint32(v) >> 1) ^ uint32(((v&1)<<31)>>31))
m.TestOneof = &AllTypesOneOf_Field7{v}
case 8:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field8", wireType)
}
var v uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
v = (v >> 1) ^ uint64((int64(v&1)<<63)>>63)
m.TestOneof = &AllTypesOneOf_Field8{int64(v)}
case 9:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Field9", wireType)
}
var v uint32
if iNdEx+4 > l {
return io.ErrUnexpectedEOF
}
v = *(*uint32)(unsafe.Pointer(&dAtA[iNdEx]))
iNdEx += 4
m.TestOneof = &AllTypesOneOf_Field9{v}
case 10:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Field10", wireType)
}
var v int32
if iNdEx+4 > l {
return io.ErrUnexpectedEOF
}
v = *(*int32)(unsafe.Pointer(&dAtA[iNdEx]))
iNdEx += 4
m.TestOneof = &AllTypesOneOf_Field10{v}
case 11:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field Field11", wireType)
}
var v uint64
if iNdEx+8 > l {
return io.ErrUnexpectedEOF
}
v = *(*uint64)(unsafe.Pointer(&dAtA[iNdEx]))
iNdEx += 8
m.TestOneof = &AllTypesOneOf_Field11{v}
case 12:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field Field12", wireType)
}
var v int64
if iNdEx+8 > l {
return io.ErrUnexpectedEOF
}
v = *(*int64)(unsafe.Pointer(&dAtA[iNdEx]))
iNdEx += 8
m.TestOneof = &AllTypesOneOf_Field12{v}
case 13:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field13", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
b := bool(v != 0)
m.TestOneof = &AllTypesOneOf_Field13{b}
case 14:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field14", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TestOneof = &AllTypesOneOf_Field14{string(dAtA[iNdEx:postIndex])}
iNdEx = postIndex
case 15:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field15", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := make([]byte, postIndex-iNdEx)
copy(v, dAtA[iNdEx:postIndex])
m.TestOneof = &AllTypesOneOf_Field15{v}
iNdEx = postIndex
case 16:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field SubMessage", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &Subby{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.TestOneof = &AllTypesOneOf_SubMessage{v}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipOneUnsafe(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthOneUnsafe
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TwoOneofs) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TwoOneofs: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TwoOneofs: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType)
}
var v float64
if iNdEx+8 > l {
return io.ErrUnexpectedEOF
}
v = *(*float64)(unsafe.Pointer(&dAtA[iNdEx]))
iNdEx += 8
m.One = &TwoOneofs_Field1{v}
case 2:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType)
}
var v float32
if iNdEx+4 > l {
return io.ErrUnexpectedEOF
}
v = *(*float32)(unsafe.Pointer(&dAtA[iNdEx]))
iNdEx += 4
m.One = &TwoOneofs_Field2{v}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field3", wireType)
}
var v int32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int32(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.One = &TwoOneofs_Field3{v}
case 34:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field34", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Two = &TwoOneofs_Field34{string(dAtA[iNdEx:postIndex])}
iNdEx = postIndex
case 35:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field35", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := make([]byte, postIndex-iNdEx)
copy(v, dAtA[iNdEx:postIndex])
m.Two = &TwoOneofs_Field35{v}
iNdEx = postIndex
case 36:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field SubMessage2", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &Subby{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Two = &TwoOneofs_SubMessage2{v}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipOneUnsafe(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthOneUnsafe
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *CustomOneof) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: CustomOneof: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: CustomOneof: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 34:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Stringy", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Custom = &CustomOneof_Stringy{string(dAtA[iNdEx:postIndex])}
iNdEx = postIndex
case 35:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CustomType", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthOneUnsafe
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
var vv github_com_gogo_protobuf_test_custom.Uint128
v := &vv
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Custom = &CustomOneof_CustomType{*v}
iNdEx = postIndex
case 36:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CastType", wireType)
}
var v github_com_gogo_protobuf_test_casttype.MyUint64Type
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (github_com_gogo_protobuf_test_casttype.MyUint64Type(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.Custom = &CustomOneof_CastType{v}
case 37:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MyCustomName", wireType)
}
var v int64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.Custom = &CustomOneof_MyCustomName{v}
default:
iNdEx = preIndex
skippy, err := skipOneUnsafe(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthOneUnsafe
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipOneUnsafe(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
iNdEx += length
if length < 0 {
return 0, ErrInvalidLengthOneUnsafe
}
return iNdEx, nil
case 3:
for {
var innerWire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowOneUnsafe
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
innerWire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
innerWireType := int(innerWire & 0x7)
if innerWireType == 4 {
break
}
next, err := skipOneUnsafe(dAtA[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
var (
ErrInvalidLengthOneUnsafe = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowOneUnsafe = fmt.Errorf("proto: integer overflow")
)
func init() { proto.RegisterFile("combos/unsafeboth/one.proto", fileDescriptorOne) }
var fileDescriptorOne = []byte{
// 600 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0xd3, 0x3f, 0x4f, 0xdb, 0x40,
0x14, 0x00, 0x70, 0x3f, 0x42, 0x42, 0xb8, 0x84, 0x92, 0x7a, 0xba, 0x52, 0xe9, 0x38, 0xa5, 0xad,
0x74, 0x43, 0x49, 0x88, 0x93, 0xf0, 0x67, 0xac, 0xa9, 0xaa, 0x2c, 0x14, 0xc9, 0xc0, 0x8c, 0x62,
0x7a, 0x09, 0x91, 0x88, 0x0f, 0x71, 0x67, 0x21, 0x6f, 0x7c, 0x86, 0x7e, 0x8a, 0x8e, 0x1d, 0xfb,
0x11, 0x18, 0x19, 0xab, 0x0e, 0x11, 0x76, 0x97, 0x8e, 0x8c, 0xa8, 0x53, 0x75, 0x36, 0xb9, 0xab,
0x54, 0x55, 0x5d, 0x3a, 0xc5, 0xef, 0xfd, 0x7c, 0x2f, 0xef, 0xf9, 0xee, 0xd0, 0xf3, 0x53, 0x31,
0x0d, 0x85, 0x6c, 0xc7, 0x91, 0x1c, 0x8e, 0x78, 0x28, 0xd4, 0x59, 0x5b, 0x44, 0xbc, 0x75, 0x71,
0x29, 0x94, 0x70, 0x4b, 0x22, 0xe2, 0x6b, 0x1b, 0xe3, 0x89, 0x3a, 0x8b, 0xc3, 0xd6, 0xa9, 0x98,
0xb6, 0xc7, 0x62, 0x2c, 0xda, 0xb9, 0x85, 0xf1, 0x28, 0x8f, 0xf2, 0x20, 0x7f, 0x2a, 0xd6, 0x34,
0x9f, 0xa1, 0xf2, 0x61, 0x1c, 0x86, 0x89, 0xdb, 0x40, 0x25, 0x19, 0x87, 0x18, 0x28, 0xb0, 0xe5,
0x40, 0x3f, 0x36, 0x67, 0x25, 0xb4, 0xf2, 0xe6, 0xfc, 0xfc, 0x28, 0xb9, 0xe0, 0xf2, 0x20, 0xe2,
0x07, 0x23, 0x17, 0xa3, 0xca, 0xbb, 0x09, 0x3f, 0xff, 0xd0, 0xc9, 0x5f, 0x83, 0x81, 0x13, 0x3c,
0xc6, 0x46, 0x3c, 0xbc, 0x40, 0x81, 0x2d, 0x18, 0xf1, 0x8c, 0x74, 0x71, 0x89, 0x02, 0x2b, 0x1b,
0xe9, 0x1a, 0xe9, 0xe1, 0x45, 0x0a, 0xac, 0x64, 0xa4, 0x67, 0xa4, 0x8f, 0xcb, 0x14, 0xd8, 0x8a,
0x91, 0xbe, 0x91, 0x2d, 0x5c, 0xa1, 0xc0, 0x16, 0x8d, 0x6c, 0x19, 0xd9, 0xc6, 0x4b, 0x14, 0xd8,
0x53, 0x23, 0xdb, 0x46, 0x76, 0x70, 0x95, 0x02, 0x73, 0x8d, 0xec, 0x18, 0xd9, 0xc5, 0xcb, 0x14,
0xd8, 0x92, 0x91, 0x5d, 0x77, 0x0d, 0x2d, 0x15, 0x93, 0x6d, 0x62, 0x44, 0x81, 0xad, 0x0e, 0x9c,
0x60, 0x9e, 0xb0, 0xd6, 0xc1, 0x35, 0x0a, 0xac, 0x62, 0xad, 0x63, 0xcd, 0xc3, 0x75, 0x0a, 0xac,
0x61, 0xcd, 0xb3, 0xd6, 0xc5, 0x2b, 0x14, 0x58, 0xd5, 0x5a, 0xd7, 0x5a, 0x0f, 0x3f, 0xd1, 0x3b,
0x60, 0xad, 0x67, 0xad, 0x8f, 0x57, 0x29, 0xb0, 0xba, 0xb5, 0xbe, 0xbb, 0x81, 0x6a, 0x32, 0x0e,
0x4f, 0xa6, 0x5c, 0xca, 0xe1, 0x98, 0xe3, 0x06, 0x05, 0x56, 0xf3, 0x50, 0x4b, 0x9f, 0x89, 0x7c,
0x5b, 0x07, 0x4e, 0x80, 0x64, 0x1c, 0xee, 0x17, 0xee, 0xd7, 0x11, 0x52, 0x5c, 0xaa, 0x13, 0x11,
0x71, 0x31, 0x6a, 0xde, 0x02, 0x5a, 0x3e, 0xba, 0x12, 0x07, 0x3a, 0x90, 0xff, 0x79, 0x73, 0xe7,
0x4d, 0x77, 0x7b, 0xb8, 0x99, 0x0f, 0x04, 0xc1, 0x3c, 0x61, 0xad, 0x8f, 0x5f, 0xe4, 0x03, 0x19,
0xeb, 0xbb, 0x6d, 0x54, 0xff, 0x6d, 0x20, 0x0f, 0xbf, 0xfc, 0x63, 0x22, 0x08, 0x6a, 0x76, 0x22,
0xcf, 0x2f, 0x23, 0x7d, 0xec, 0xf5, 0x8f, 0xba, 0x12, 0xcd, 0x8f, 0x0b, 0xa8, 0xb6, 0x17, 0x4b,
0x25, 0xa6, 0xf9, 0x54, 0xfa, 0xaf, 0x0e, 0xd5, 0xe5, 0x24, 0x1a, 0x27, 0x8f, 0x6d, 0x38, 0xc1,
0x3c, 0xe1, 0x06, 0x08, 0x15, 0xaf, 0xea, 0x13, 0x5e, 0x74, 0xe2, 0x6f, 0x7e, 0x9b, 0xad, 0xbf,
0xfe, 0xeb, 0x0d, 0xd2, 0xdf, 0xae, 0x7d, 0x9a, 0xaf, 0x69, 0x1d, 0x4f, 0x22, 0xd5, 0xf1, 0x76,
0xf4, 0x07, 0xb6, 0x55, 0xdc, 0x63, 0x54, 0xdd, 0x1b, 0x4a, 0x95, 0x57, 0xd4, 0xad, 0x2f, 0xfa,
0xdb, 0x3f, 0x67, 0xeb, 0xdd, 0x7f, 0x54, 0x1c, 0x4a, 0xa5, 0x92, 0x0b, 0xde, 0xda, 0x4f, 0x74,
0xd5, 0xad, 0x9e, 0x5e, 0x3e, 0x70, 0x02, 0x53, 0xca, 0xf5, 0xe6, 0xad, 0xbe, 0x1f, 0x4e, 0x39,
0x7e, 0xa5, 0xaf, 0x8b, 0xdf, 0xc8, 0x66, 0xeb, 0xf5, 0xfd, 0xc4, 0xe6, 0x6d, 0x2b, 0x3a, 0xf2,
0xab, 0xa8, 0x52, 0xb4, 0xea, 0xbf, 0xbd, 0x49, 0x89, 0x73, 0x9b, 0x12, 0xe7, 0x6b, 0x4a, 0x9c,
0xbb, 0x94, 0xc0, 0x7d, 0x4a, 0xe0, 0x21, 0x25, 0x70, 0x9d, 0x11, 0xf8, 0x94, 0x11, 0xf8, 0x9c,
0x11, 0xf8, 0x92, 0x11, 0xb8, 0xc9, 0x88, 0x73, 0x9b, 0x11, 0xe7, 0x2e, 0x23, 0xf0, 0x23, 0x23,
0xce, 0x7d, 0x46, 0xe0, 0x21, 0x23, 0x70, 0xfd, 0x9d, 0xc0, 0xaf, 0x00, 0x00, 0x00, 0xff, 0xff,
0xa5, 0xf3, 0xa9, 0x7e, 0x7b, 0x04, 0x00, 0x00,
}
| kadel/kedge | vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/gogo/protobuf/test/oneof/combos/unsafeboth/one.pb.go | GO | apache-2.0 | 156,343 |
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERSTATES_HPP
#define SFML_RENDERSTATES_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/BlendMode.hpp>
#include <SFML/Graphics/Transform.hpp>
namespace sf
{
class Shader;
class Texture;
////////////////////////////////////////////////////////////
/// \brief Define the states used for drawing to a RenderTarget
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderStates
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructing a default set of render states is equivalent
/// to using sf::RenderStates::Default.
/// The default set defines:
/// \li the BlendAlpha blend mode
/// \li the identity transform
/// \li a null texture
/// \li a null shader
///
////////////////////////////////////////////////////////////
RenderStates();
////////////////////////////////////////////////////////////
/// \brief Construct a default set of render states with a custom blend mode
///
/// \param theBlendMode Blend mode to use
///
////////////////////////////////////////////////////////////
RenderStates(const BlendMode& theBlendMode);
////////////////////////////////////////////////////////////
/// \brief Construct a default set of render states with a custom transform
///
/// \param theTransform Transform to use
///
////////////////////////////////////////////////////////////
RenderStates(const Transform& theTransform);
////////////////////////////////////////////////////////////
/// \brief Construct a default set of render states with a custom texture
///
/// \param theTexture Texture to use
///
////////////////////////////////////////////////////////////
RenderStates(const Texture* theTexture);
////////////////////////////////////////////////////////////
/// \brief Construct a default set of render states with a custom shader
///
/// \param theShader Shader to use
///
////////////////////////////////////////////////////////////
RenderStates(const Shader* theShader);
////////////////////////////////////////////////////////////
/// \brief Construct a set of render states with all its attributes
///
/// \param theBlendMode Blend mode to use
/// \param theTransform Transform to use
/// \param theTexture Texture to use
/// \param theShader Shader to use
///
////////////////////////////////////////////////////////////
RenderStates(const BlendMode& theBlendMode, const Transform& theTransform,
const Texture* theTexture, const Shader* theShader);
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
static const RenderStates Default; ///< Special instance holding the default render states
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
BlendMode blendMode; ///< Blending mode
Transform transform; ///< Transform
const Texture* texture; ///< Texture
const Shader* shader; ///< Shader
};
} // namespace sf
#endif // SFML_RENDERSTATES_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderStates
/// \ingroup graphics
///
/// There are four global states that can be applied to
/// the drawn objects:
/// \li the blend mode: how pixels of the object are blended with the background
/// \li the transform: how the object is positioned/rotated/scaled
/// \li the texture: what image is mapped to the object
/// \li the shader: what custom effect is applied to the object
///
/// High-level objects such as sprites or text force some of
/// these states when they are drawn. For example, a sprite
/// will set its own texture, so that you don't have to care
/// about it when drawing the sprite.
///
/// The transform is a special case: sprites, texts and shapes
/// (and it's a good idea to do it with your own drawable classes
/// too) combine their transform with the one that is passed in the
/// RenderStates structure. So that you can use a "global" transform
/// on top of each object's transform.
///
/// Most objects, especially high-level drawables, can be drawn
/// directly without defining render states explicitly -- the
/// default set of states is ok in most cases.
/// \code
/// window.draw(sprite);
/// \endcode
///
/// If you want to use a single specific render state,
/// for example a shader, you can pass it directly to the Draw
/// function: sf::RenderStates has an implicit one-argument
/// constructor for each state.
/// \code
/// window.draw(sprite, shader);
/// \endcode
///
/// When you're inside the Draw function of a drawable
/// object (inherited from sf::Drawable), you can
/// either pass the render states unmodified, or change
/// some of them.
/// For example, a transformable object will combine the
/// current transform with its own transform. A sprite will
/// set its texture. Etc.
///
/// \see sf::RenderTarget, sf::Drawable
///
////////////////////////////////////////////////////////////
| UgoLouche/QPacman | src/includes/SFML/Graphics/RenderStates.hpp | C++ | gpl-3.0 | 6,538 |
<?php
/**
* @package Joomla.Site
* @subpackage mod_related_items
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once __DIR__ . '/helper.php';
$cacheparams = new stdClass;
$cacheparams->cachemode = 'safeuri';
$cacheparams->class = 'ModRelatedItemsHelper';
$cacheparams->method = 'getList';
$cacheparams->methodparams = $params;
$cacheparams->modeparams = array('id' => 'int', 'Itemid' => 'int');
$list = JModuleHelper::moduleCache($module, $params, $cacheparams);
if (!count($list))
{
return;
}
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));
$showDate = $params->get('showDate', 0);
require JModuleHelper::getLayoutPath('mod_related_items', $params->get('layout', 'default'));
| RCBiczok/ArticleRefs | src/test/lib/joomla/3_1_5/modules/mod_related_items/mod_related_items.php | PHP | gpl-3.0 | 921 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/system_message_window_win.h"
#include <dbt.h>
#include "base/logging.h"
#include "base/system_monitor/system_monitor.h"
#include "base/win/wrapped_window_proc.h"
#include "media/audio/win/core_audio_util_win.h"
namespace content {
namespace {
const wchar_t kWindowClassName[] = L"Chrome_SystemMessageWindow";
// A static map from a device category guid to base::SystemMonitor::DeviceType.
struct {
const GUID device_category;
const base::SystemMonitor::DeviceType device_type;
} const kDeviceCategoryMap[] = {
{ KSCATEGORY_AUDIO, base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE },
{ KSCATEGORY_VIDEO, base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE },
};
} // namespace
// Manages the device notification handles for SystemMessageWindowWin.
class SystemMessageWindowWin::DeviceNotifications {
public:
explicit DeviceNotifications(HWND hwnd) : notifications_() {
Register(hwnd);
}
~DeviceNotifications() {
Unregister();
}
void Register(HWND hwnd) {
// Request to receive device notifications. All applications receive basic
// notifications via WM_DEVICECHANGE but in order to receive detailed device
// arrival and removal messages, we need to register.
DEV_BROADCAST_DEVICEINTERFACE filter = {0};
filter.dbcc_size = sizeof(filter);
filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
bool core_audio_support = media::CoreAudioUtil::IsSupported();
for (int i = 0; i < arraysize(kDeviceCategoryMap); ++i) {
// If CoreAudio is supported, AudioDeviceListenerWin will
// take care of monitoring audio devices.
if (core_audio_support &&
KSCATEGORY_AUDIO == kDeviceCategoryMap[i].device_category) {
continue;
}
filter.dbcc_classguid = kDeviceCategoryMap[i].device_category;
DCHECK_EQ(notifications_[i], static_cast<HDEVNOTIFY>(NULL));
notifications_[i] = RegisterDeviceNotification(
hwnd, &filter, DEVICE_NOTIFY_WINDOW_HANDLE);
DPLOG_IF(ERROR, !notifications_[i])
<< "RegisterDeviceNotification failed";
}
}
void Unregister() {
for (int i = 0; i < arraysize(notifications_); ++i) {
if (notifications_[i]) {
UnregisterDeviceNotification(notifications_[i]);
notifications_[i] = NULL;
}
}
}
private:
HDEVNOTIFY notifications_[arraysize(kDeviceCategoryMap)];
DISALLOW_IMPLICIT_CONSTRUCTORS(DeviceNotifications);
};
SystemMessageWindowWin::SystemMessageWindowWin() {
WNDCLASSEX window_class;
base::win::InitializeWindowClass(
kWindowClassName,
&base::win::WrappedWindowProc<SystemMessageWindowWin::WndProcThunk>,
0, 0, 0, NULL, NULL, NULL, NULL, NULL,
&window_class);
instance_ = window_class.hInstance;
ATOM clazz = RegisterClassEx(&window_class);
DCHECK(clazz);
window_ = CreateWindow(kWindowClassName,
0, 0, 0, 0, 0, 0, 0, 0, instance_, 0);
SetWindowLongPtr(window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
device_notifications_.reset(new DeviceNotifications(window_));
}
SystemMessageWindowWin::~SystemMessageWindowWin() {
if (window_) {
DestroyWindow(window_);
UnregisterClass(kWindowClassName, instance_);
}
}
LRESULT SystemMessageWindowWin::OnDeviceChange(UINT event_type, LPARAM data) {
base::SystemMonitor* monitor = base::SystemMonitor::Get();
base::SystemMonitor::DeviceType device_type =
base::SystemMonitor::DEVTYPE_UNKNOWN;
switch (event_type) {
case DBT_DEVNODES_CHANGED:
// For this notification, we're happy with the default DEVTYPE_UNKNOWN.
break;
case DBT_DEVICEREMOVECOMPLETE:
case DBT_DEVICEARRIVAL: {
// This notification has more details about the specific device that
// was added or removed. See if this is a category we're interested
// in monitoring and if so report the specific device type. If we don't
// find the category in our map, ignore the notification and do not
// notify the system monitor.
DEV_BROADCAST_DEVICEINTERFACE* device_interface =
reinterpret_cast<DEV_BROADCAST_DEVICEINTERFACE*>(data);
if (device_interface->dbcc_devicetype != DBT_DEVTYP_DEVICEINTERFACE)
return TRUE;
for (int i = 0; i < arraysize(kDeviceCategoryMap); ++i) {
if (kDeviceCategoryMap[i].device_category ==
device_interface->dbcc_classguid) {
device_type = kDeviceCategoryMap[i].device_type;
break;
}
}
// Devices that we do not have a DEVTYPE_ for, get detected via
// DBT_DEVNODES_CHANGED, so we avoid sending additional notifications
// for those here.
if (device_type == base::SystemMonitor::DEVTYPE_UNKNOWN)
return TRUE;
break;
}
default:
return TRUE;
}
monitor->ProcessDevicesChanged(device_type);
return TRUE;
}
LRESULT CALLBACK SystemMessageWindowWin::WndProc(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam) {
switch (message) {
case WM_DEVICECHANGE:
return OnDeviceChange(static_cast<UINT>(wparam), lparam);
default:
break;
}
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
} // namespace content
| plxaye/chromium | src/content/browser/system_message_window_win.cc | C++ | apache-2.0 | 5,414 |
/*
* Copyright (C) 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WKMediaCacheManager.h"
#include "WKAPICast.h"
#include "WebMediaCacheManagerProxy.h"
using namespace WebKit;
WKTypeID WKMediaCacheManagerGetTypeID()
{
return toAPI(WebMediaCacheManagerProxy::APIType);
}
void WKMediaCacheManagerGetHostnamesWithMediaCache(WKMediaCacheManagerRef mediaCacheManagerRef, void* context, WKMediaCacheManagerGetHostnamesWithMediaCacheFunction callback)
{
toImpl(mediaCacheManagerRef)->getHostnamesWithMediaCache(ArrayCallback::create(context, callback));
}
void WKMediaCacheManagerClearCacheForHostname(WKMediaCacheManagerRef mediaCacheManagerRef, WKStringRef hostname)
{
toImpl(mediaCacheManagerRef)->clearCacheForHostname(toWTFString(hostname));
}
void WKMediaCacheManagerClearCacheForAllHostnames(WKMediaCacheManagerRef mediaCacheManagerRef)
{
toImpl(mediaCacheManagerRef)->clearCacheForAllHostnames();
}
| danialbehzadi/Nokia-RM-1013-2.0.0.11 | webkit/Source/WebKit2/UIProcess/API/C/WKMediaCacheManager.cpp | C++ | gpl-3.0 | 2,241 |
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runtime
import "github.com/go-openapi/strfmt"
// A ClientAuthInfoWriterFunc converts a function to a request writer interface
type ClientAuthInfoWriterFunc func(ClientRequest, strfmt.Registry) error
// AuthenticateRequest adds authentication data to the request
func (fn ClientAuthInfoWriterFunc) AuthenticateRequest(req ClientRequest, reg strfmt.Registry) error {
return fn(req, reg)
}
// A ClientAuthInfoWriter implementor knows how to write authentication info to a request
type ClientAuthInfoWriter interface {
AuthenticateRequest(ClientRequest, strfmt.Registry) error
}
| kgrygiel/autoscaler | vertical-pod-autoscaler/vendor/github.com/go-openapi/runtime/client_auth_info.go | GO | apache-2.0 | 1,188 |
/**
* Resource drag and drop.
*
* @class M.course.dragdrop.resource
* @constructor
* @extends M.core.dragdrop
*/
var DRAGRESOURCE = function() {
DRAGRESOURCE.superclass.constructor.apply(this, arguments);
};
Y.extend(DRAGRESOURCE, M.core.dragdrop, {
initializer: function() {
// Set group for parent class
this.groups = ['resource'];
this.samenodeclass = CSS.ACTIVITY;
this.parentnodeclass = CSS.SECTION;
this.resourcedraghandle = this.get_drag_handle(M.util.get_string('move', 'moodle'), CSS.EDITINGMOVE, CSS.ICONCLASS, true);
this.samenodelabel = {
identifier: 'dragtoafter',
component: 'quiz'
};
this.parentnodelabel = {
identifier: 'dragtostart',
component: 'quiz'
};
// Go through all sections
this.setup_for_section();
// Initialise drag & drop for all resources/activities
var nodeselector = 'li.' + CSS.ACTIVITY;
var del = new Y.DD.Delegate({
container: '.' + CSS.COURSECONTENT,
nodes: nodeselector,
target: true,
handles: ['.' + CSS.EDITINGMOVE],
dragConfig: {groups: this.groups}
});
del.dd.plug(Y.Plugin.DDProxy, {
// Don't move the node at the end of the drag
moveOnEnd: false,
cloneNode: true
});
del.dd.plug(Y.Plugin.DDConstrained, {
// Keep it inside the .mod-quiz-edit-content
constrain: '#' + CSS.SLOTS
});
del.dd.plug(Y.Plugin.DDWinScroll);
M.mod_quiz.quizbase.register_module(this);
M.mod_quiz.dragres = this;
},
/**
* Apply dragdrop features to the specified selector or node that refers to section(s)
*
* @method setup_for_section
* @param {String} baseselector The CSS selector or node to limit scope to
*/
setup_for_section: function() {
Y.Node.all('.mod-quiz-edit-content ul.slots ul.section').each(function(resources) {
resources.setAttribute('data-draggroups', this.groups.join(' '));
// Define empty ul as droptarget, so that item could be moved to empty list
new Y.DD.Drop({
node: resources,
groups: this.groups,
padding: '20 0 20 0'
});
// Initialise each resource/activity in this section
this.setup_for_resource('li.activity');
}, this);
},
/**
* Apply dragdrop features to the specified selector or node that refers to resource(s)
*
* @method setup_for_resource
* @param {String} baseselector The CSS selector or node to limit scope to
*/
setup_for_resource: function(baseselector) {
Y.Node.all(baseselector).each(function(resourcesnode) {
// Replace move icons
var move = resourcesnode.one('a.' + CSS.EDITINGMOVE);
if (move) {
move.replace(this.resourcedraghandle.cloneNode(true));
}
}, this);
},
drag_start: function(e) {
// Get our drag object
var drag = e.target;
drag.get('dragNode').setContent(drag.get('node').get('innerHTML'));
drag.get('dragNode').all('img.iconsmall').setStyle('vertical-align', 'baseline');
},
drag_dropmiss: function(e) {
// Missed the target, but we assume the user intended to drop it
// on the last ghost node location, e.drag and e.drop should be
// prepared by global_drag_dropmiss parent so simulate drop_hit(e).
this.drop_hit(e);
},
drop_hit: function(e) {
var drag = e.drag;
// Get a reference to our drag node
var dragnode = drag.get('node');
var dropnode = e.drop.get('node');
// Add spinner if it not there
var actionarea = dragnode.one(CSS.ACTIONAREA);
var spinner = M.util.add_spinner(Y, actionarea);
var params = {};
// Handle any variables which we must pass back through to
var pageparams = this.get('config').pageparams;
var varname;
for (varname in pageparams) {
params[varname] = pageparams[varname];
}
// Prepare request parameters
params.sesskey = M.cfg.sesskey;
params.courseid = this.get('courseid');
params.quizid = this.get('quizid');
params['class'] = 'resource';
params.field = 'move';
params.id = Number(Y.Moodle.mod_quiz.util.slot.getId(dragnode));
params.sectionId = Y.Moodle.core_course.util.section.getId(dropnode.ancestor('li.section', true));
var previousslot = dragnode.previous(SELECTOR.SLOT);
if (previousslot) {
params.previousid = Number(Y.Moodle.mod_quiz.util.slot.getId(previousslot));
}
var previouspage = dragnode.previous(SELECTOR.PAGE);
if (previouspage) {
params.page = Number(Y.Moodle.mod_quiz.util.page.getId(previouspage));
}
// Do AJAX request
var uri = M.cfg.wwwroot + this.get('ajaxurl');
Y.io(uri, {
method: 'POST',
data: params,
on: {
start: function() {
this.lock_drag_handle(drag, CSS.EDITINGMOVE);
spinner.show();
},
success: function(tid, response) {
var responsetext = Y.JSON.parse(response.responseText);
var params = {element: dragnode, visible: responsetext.visible};
M.mod_quiz.quizbase.invoke_function('set_visibility_resource_ui', params);
this.unlock_drag_handle(drag, CSS.EDITINGMOVE);
window.setTimeout(function() {
spinner.hide();
}, 250);
M.mod_quiz.resource_toolbox.reorganise_edit_page();
},
failure: function(tid, response) {
this.ajax_failure(response);
this.unlock_drag_handle(drag, CSS.SECTIONHANDLE);
spinner.hide();
window.location.reload(true);
}
},
context:this
});
},
global_drop_over: function(e) {
//Overriding parent method so we can stop the slots being dragged before the first page node.
// Check that drop object belong to correct group.
if (!e.drop || !e.drop.inGroup(this.groups)) {
return;
}
// Get a reference to our drag and drop nodes.
var drag = e.drag.get('node'),
drop = e.drop.get('node');
// Save last drop target for the case of missed target processing.
this.lastdroptarget = e.drop;
// Are we dropping within the same parent node?
if (drop.hasClass(this.samenodeclass)) {
var where;
if (this.goingup) {
where = "before";
} else {
where = "after";
}
drop.insert(drag, where);
} else if ((drop.hasClass(this.parentnodeclass) || drop.test('[data-droptarget="1"]')) && !drop.contains(drag)) {
// We are dropping on parent node and it is empty
if (this.goingup) {
drop.append(drag);
} else {
drop.prepend(drag);
}
}
this.drop_over(e);
}
}, {
NAME: 'mod_quiz-dragdrop-resource',
ATTRS: {
courseid: {
value: null
},
quizid: {
value: null
},
ajaxurl: {
value: 0
},
config: {
value: 0
}
}
});
M.mod_quiz = M.mod_quiz || {};
M.mod_quiz.init_resource_dragdrop = function(params) {
new DRAGRESOURCE(params);
};
| ernestovi/ups | moodle/mod/quiz/yui/src/dragdrop/js/resource.js | JavaScript | gpl-3.0 | 7,887 |
// Heartbeat options:
// heartbeatInterval: interval to send pings, in milliseconds.
// heartbeatTimeout: timeout to close the connection if a reply isn't
// received, in milliseconds.
// sendPing: function to call to send a ping on the connection.
// onTimeout: function to call to close the connection.
DDPCommon.Heartbeat = function (options) {
var self = this;
self.heartbeatInterval = options.heartbeatInterval;
self.heartbeatTimeout = options.heartbeatTimeout;
self._sendPing = options.sendPing;
self._onTimeout = options.onTimeout;
self._seenPacket = false;
self._heartbeatIntervalHandle = null;
self._heartbeatTimeoutHandle = null;
};
_.extend(DDPCommon.Heartbeat.prototype, {
stop: function () {
var self = this;
self._clearHeartbeatIntervalTimer();
self._clearHeartbeatTimeoutTimer();
},
start: function () {
var self = this;
self.stop();
self._startHeartbeatIntervalTimer();
},
_startHeartbeatIntervalTimer: function () {
var self = this;
self._heartbeatIntervalHandle = Meteor.setInterval(
_.bind(self._heartbeatIntervalFired, self),
self.heartbeatInterval
);
},
_startHeartbeatTimeoutTimer: function () {
var self = this;
self._heartbeatTimeoutHandle = Meteor.setTimeout(
_.bind(self._heartbeatTimeoutFired, self),
self.heartbeatTimeout
);
},
_clearHeartbeatIntervalTimer: function () {
var self = this;
if (self._heartbeatIntervalHandle) {
Meteor.clearInterval(self._heartbeatIntervalHandle);
self._heartbeatIntervalHandle = null;
}
},
_clearHeartbeatTimeoutTimer: function () {
var self = this;
if (self._heartbeatTimeoutHandle) {
Meteor.clearTimeout(self._heartbeatTimeoutHandle);
self._heartbeatTimeoutHandle = null;
}
},
// The heartbeat interval timer is fired when we should send a ping.
_heartbeatIntervalFired: function () {
var self = this;
// don't send ping if we've seen a packet since we last checked,
// *or* if we have already sent a ping and are awaiting a timeout.
// That shouldn't happen, but it's possible if
// `self.heartbeatInterval` is smaller than
// `self.heartbeatTimeout`.
if (! self._seenPacket && ! self._heartbeatTimeoutHandle) {
self._sendPing();
// Set up timeout, in case a pong doesn't arrive in time.
self._startHeartbeatTimeoutTimer();
}
self._seenPacket = false;
},
// The heartbeat timeout timer is fired when we sent a ping, but we
// timed out waiting for the pong.
_heartbeatTimeoutFired: function () {
var self = this;
self._heartbeatTimeoutHandle = null;
self._onTimeout();
},
messageReceived: function () {
var self = this;
// Tell periodic checkin that we have seen a packet, and thus it
// does not need to send a ping this cycle.
self._seenPacket = true;
// If we were waiting for a pong, we got it.
if (self._heartbeatTimeoutHandle) {
self._clearHeartbeatTimeoutTimer();
}
}
});
| lawrenceAIO/meteor | packages/ddp-common/heartbeat.js | JavaScript | mit | 3,044 |
require('./angular-locale_nl-cw');
module.exports = 'ngLocale';
| DamascenoRafael/cos482-qualidade-de-software | www/src/main/webapp/bower_components/angular-i18n/nl-cw.js | JavaScript | mit | 64 |
require('./angular-locale_en-im');
module.exports = 'ngLocale';
| DamascenoRafael/cos482-qualidade-de-software | www/src/main/webapp/bower_components/angular-i18n/en-im.js | JavaScript | mit | 64 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Tool
* @subpackage Framework
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* Basic Interface for factilities that load Zend_Tool providers or manifests.
*
* @category Zend
* @package Zend_Tool
* @subpackage Framework
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Tool_Framework_Loader_Interface
{
/**
* Load Providers and Manifests
*
* Returns an array of all loaded class names.
*
* @return array
*/
public function load();
}
| hansbonini/cloud9-magento | www/lib/Zend/Tool/Framework/Loader/Interface.php | PHP | mit | 1,265 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Assembly symbol referenced by a AssemblyRef for which we couldn't find a matching
/// compilation reference but we found one that differs in version.
/// Created only for assemblies that require runtime binding redirection policy,
/// i.e. not for Framework assemblies.
/// </summary>
internal struct UnifiedAssembly<TAssemblySymbol>
where TAssemblySymbol : class, IAssemblySymbol
{
/// <summary>
/// Original reference that was unified to the identity of the <see cref="TargetAssembly"/>.
/// </summary>
internal readonly AssemblyIdentity OriginalReference;
internal readonly TAssemblySymbol TargetAssembly;
public UnifiedAssembly(TAssemblySymbol targetAssembly, AssemblyIdentity originalReference)
{
Debug.Assert(originalReference != null);
Debug.Assert(targetAssembly != null);
this.OriginalReference = originalReference;
this.TargetAssembly = targetAssembly;
}
}
}
| balazssimon/meta-cs | src/Main/MetaDslx.CodeAnalysis.Common/ReferenceManager/UnifiedAssembly.cs | C# | apache-2.0 | 1,310 |
<?php
/**
* @file
* Contains \Drupal\Core\Field\Plugin\Field\FieldFormatter\NumericFormatterBase.
*/
namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\AllowedTagsXssTrait;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Parent plugin for decimal and integer formatters.
*/
abstract class NumericFormatterBase extends FormatterBase {
use AllowedTagsXssTrait;
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$options = array(
'' => t('- None -'),
'.' => t('Decimal point'),
',' => t('Comma'),
' ' => t('Space'),
chr(8201) => t('Thin space'),
"'" => t('Apostrophe'),
);
$elements['thousand_separator'] = array(
'#type' => 'select',
'#title' => t('Thousand marker'),
'#options' => $options,
'#default_value' => $this->getSetting('thousand_separator'),
'#weight' => 0,
);
$elements['prefix_suffix'] = array(
'#type' => 'checkbox',
'#title' => t('Display prefix and suffix'),
'#default_value' => $this->getSetting('prefix_suffix'),
'#weight' => 10,
);
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = $this->numberFormat(1234.1234567890);
if ($this->getSetting('prefix_suffix')) {
$summary[] = t('Display with prefix and suffix.');
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$settings = $this->getFieldSettings();
foreach ($items as $delta => $item) {
$output = $this->numberFormat($item->value);
// Account for prefix and suffix.
if ($this->getSetting('prefix_suffix')) {
$prefixes = isset($settings['prefix']) ? array_map(array('Drupal\Core\Field\FieldFilteredMarkup', 'create'), explode('|', $settings['prefix'])) : array('');
$suffixes = isset($settings['suffix']) ? array_map(array('Drupal\Core\Field\FieldFilteredMarkup', 'create'), explode('|', $settings['suffix'])) : array('');
$prefix = (count($prefixes) > 1) ? $this->formatPlural($item->value, $prefixes[0], $prefixes[1]) : $prefixes[0];
$suffix = (count($suffixes) > 1) ? $this->formatPlural($item->value, $suffixes[0], $suffixes[1]) : $suffixes[0];
$output = $prefix . $output . $suffix;
}
// Output the raw value in a content attribute if the text of the HTML
// element differs from the raw value (for example when a prefix is used).
if (isset($item->_attributes) && $item->value != $output) {
$item->_attributes += array('content' => $item->value);
}
$elements[$delta] = array('#markup' => $output);
}
return $elements;
}
/**
* Formats a number.
*
* @param mixed $number
* The numeric value.
*
* @return string
* The formatted number.
*/
abstract protected function numberFormat($number);
}
| nrackleff/capstone | web/core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/NumericFormatterBase.php | PHP | gpl-2.0 | 3,132 |
var assert = require('assert');
var Kareem = require('../');
describe('execPre', function() {
var hooks;
beforeEach(function() {
hooks = new Kareem();
});
it('handles errors with multiple pres', function(done) {
var execed = {};
hooks.pre('cook', function(done) {
execed.first = true;
done();
});
hooks.pre('cook', function(done) {
execed.second = true;
done('error!');
});
hooks.pre('cook', function(done) {
execed.third = true;
done();
});
hooks.execPre('cook', null, function(err) {
assert.equal('error!', err);
assert.equal(2, Object.keys(execed).length);
assert.ok(execed.first);
assert.ok(execed.second);
done();
});
});
it('handles async errors', function(done) {
var execed = {};
hooks.pre('cook', true, function(next, done) {
execed.first = true;
setTimeout(
function() {
done('error!');
},
5);
next();
});
hooks.pre('cook', true, function(next, done) {
execed.second = true;
setTimeout(
function() {
done('other error!');
},
10);
next();
});
hooks.execPre('cook', null, function(err) {
assert.equal('error!', err);
assert.equal(2, Object.keys(execed).length);
assert.ok(execed.first);
assert.ok(execed.second);
done();
});
});
it('handles async errors in next()', function(done) {
var execed = {};
hooks.pre('cook', true, function(next, done) {
execed.first = true;
setTimeout(
function() {
done('other error!');
},
15);
next();
});
hooks.pre('cook', true, function(next, done) {
execed.second = true;
setTimeout(
function() {
next('error!');
done('another error!');
},
5);
});
hooks.execPre('cook', null, function(err) {
assert.equal('error!', err);
assert.equal(2, Object.keys(execed).length);
assert.ok(execed.first);
assert.ok(execed.second);
done();
});
});
it('handles async errors in next() when already done', function(done) {
var execed = {};
hooks.pre('cook', true, function(next, done) {
execed.first = true;
setTimeout(
function() {
done('other error!');
},
5);
next();
});
hooks.pre('cook', true, function(next, done) {
execed.second = true;
setTimeout(
function() {
next('error!');
done('another error!');
},
25);
});
hooks.execPre('cook', null, function(err) {
assert.equal('other error!', err);
assert.equal(2, Object.keys(execed).length);
assert.ok(execed.first);
assert.ok(execed.second);
done();
});
});
it('async pres with clone()', function(done) {
var execed = false;
hooks.pre('cook', true, function(next, done) {
execed = true;
setTimeout(
function() {
done();
},
5);
next();
});
hooks.clone().execPre('cook', null, function(err) {
assert.ifError(err);
assert.ok(execed);
done();
});
});
it('returns correct error when async pre errors', function(done) {
var execed = {};
hooks.pre('cook', true, function(next, done) {
execed.first = true;
setTimeout(
function() {
done('other error!');
},
5);
next();
});
hooks.pre('cook', function(next) {
execed.second = true;
setTimeout(
function() {
next('error!');
},
15);
});
hooks.execPre('cook', null, function(err) {
assert.equal('other error!', err);
assert.equal(2, Object.keys(execed).length);
assert.ok(execed.first);
assert.ok(execed.second);
done();
});
});
it('lets async pres run when fully sync pres are done', function(done) {
var execed = {};
hooks.pre('cook', true, function(next, done) {
execed.first = true;
setTimeout(
function() {
done();
},
5);
next();
});
hooks.pre('cook', function() {
execed.second = true;
});
hooks.execPre('cook', null, function(err) {
assert.ifError(err);
assert.equal(2, Object.keys(execed).length);
assert.ok(execed.first);
assert.ok(execed.second);
done();
});
});
it('allows passing arguments to the next pre', function(done) {
var execed = {};
hooks.pre('cook', function(next) {
execed.first = true;
next(null, 'test');
});
hooks.pre('cook', function(next, p) {
execed.second = true;
assert.equal(p, 'test');
next();
});
hooks.pre('cook', function(next, p) {
execed.third = true;
assert.ok(!p);
next();
});
hooks.execPre('cook', null, function(err) {
assert.ifError(err);
assert.equal(3, Object.keys(execed).length);
assert.ok(execed.first);
assert.ok(execed.second);
assert.ok(execed.third);
done();
});
});
});
describe('execPreSync', function() {
var hooks;
beforeEach(function() {
hooks = new Kareem();
});
it('executes hooks synchronously', function() {
var execed = {};
hooks.pre('cook', function() {
execed.first = true;
});
hooks.pre('cook', function() {
execed.second = true;
});
hooks.execPreSync('cook', null);
assert.ok(execed.first);
assert.ok(execed.second);
});
it('works with no hooks specified', function() {
assert.doesNotThrow(function() {
hooks.execPreSync('cook', null);
});
});
});
| ChrisChenSZ/code | 表单注册验证/node_modules/kareem/test/pre.test.js | JavaScript | apache-2.0 | 5,771 |
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"os"
"github.com/spf13/pflag"
"k8s.io/apiserver/pkg/server/healthz"
"k8s.io/apiserver/pkg/util/flag"
"k8s.io/apiserver/pkg/util/logs"
"k8s.io/kubernetes/federation/cmd/federation-controller-manager/app"
"k8s.io/kubernetes/federation/cmd/federation-controller-manager/app/options"
_ "k8s.io/kubernetes/pkg/util/workqueue/prometheus" // for workqueue metric registration
"k8s.io/kubernetes/pkg/version/verflag"
)
func init() {
healthz.DefaultHealthz()
}
func main() {
s := options.NewCMServer()
s.AddFlags(pflag.CommandLine)
flag.InitFlags()
logs.InitLogs()
defer logs.FlushLogs()
verflag.PrintAndExitIfRequested()
if err := app.Run(s); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}
| sspeiche/origin | vendor/k8s.io/kubernetes/federation/cmd/federation-controller-manager/controller-manager.go | GO | apache-2.0 | 1,328 |
<?php
namespace Illuminate\Foundation\Console;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Foundation\Application;
use Illuminate\Database\Eloquent\Model;
use Symfony\Component\VarDumper\Caster\Caster;
class IlluminateCaster
{
/**
* Illuminate application methods to include in the presenter.
*
* @var array
*/
private static $appProperties = [
'configurationIsCached',
'environment',
'environmentFile',
'isLocal',
'routesAreCached',
'runningUnitTests',
'version',
'path',
'basePath',
'configPath',
'databasePath',
'langPath',
'publicPath',
'storagePath',
'bootstrapPath',
];
/**
* Get an array representing the properties of an application.
*
* @param \Illuminate\Foundation\Application $app
* @return array
*/
public static function castApplication(Application $app)
{
$results = [];
foreach (self::$appProperties as $property) {
try {
$val = $app->$property();
if (! is_null($val)) {
$results[Caster::PREFIX_VIRTUAL.$property] = $val;
}
} catch (Exception $e) {
//
}
}
return $results;
}
/**
* Get an array representing the properties of a collection.
*
* @param \Illuminate\Support\Collection $collection
* @return array
*/
public static function castCollection(Collection $collection)
{
return [
Caster::PREFIX_VIRTUAL.'all' => $collection->all(),
];
}
/**
* Get an array representing the properties of a model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return array
*/
public static function castModel(Model $model)
{
$attributes = array_merge(
$model->getAttributes(), $model->getRelations()
);
$visible = array_flip(
$model->getVisible() ?: array_diff(array_keys($attributes), $model->getHidden())
);
$results = [];
foreach (array_intersect_key($attributes, $visible) as $key => $value) {
$results[(isset($visible[$key]) ? Caster::PREFIX_VIRTUAL : Caster::PREFIX_PROTECTED).$key] = $value;
}
return $results;
}
}
| gayathma/footballs | vendor/laravel/framework/src/Illuminate/Foundation/Console/IlluminateCaster.php | PHP | gpl-3.0 | 2,431 |
var s = `a
b
c`;
assert.equal(s, 'a\n b\n c');
| oleksandr-minakov/northshore | ui/node_modules/es6-templates/test/examples/multi-line.js | JavaScript | apache-2.0 | 61 |
// { dg-do assemble }
// Copyright (C) 2000 Free Software Foundation
// Contributed by Kriang Lerdsuwanakij <lerdsuwa@users.sourceforge.net>
// Bug: We used reject template unification of two bound template template
// parameters.
template <class T, class U=int> class C
{
};
template <class T, class U> void f(C<T,U> c)
{
}
template <class T> void f(C<T> c)
{
}
template <template<class,class=int> class C, class T, class U>
void g(C<T,U> c)
{
}
template <template<class,class=int> class C, class T> void g(C<T> c)
{
}
int main()
{
C<int,char> c1;
f(c1);
g(c1);
C<int,int> c2;
f(c2);
g(c2);
}
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.pt/ttp65.C | C++ | gpl-2.0 | 615 |
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var reload = browserSync.reload;
var src = {
scss: 'app/scss/*.scss',
css: 'app/css',
html: 'app/*.html'
};
// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {
browserSync({
server: "./app"
});
gulp.watch(src.scss, ['sass']);
gulp.watch(src.html).on('change', reload);
});
// Compile sass into CSS
gulp.task('sass', function() {
return gulp.src(src.scss)
.pipe(sass())
.pipe(gulp.dest(src.css))
.pipe(reload({stream: true}));
});
gulp.task('default', ['serve']);
| yuyang545262477/Resume | 项目二电商首页/node_modules/bs-recipes/recipes/gulp.sass/gulpfile.js | JavaScript | mit | 691 |
// Validate.js 0.1.1
// (c) 2013 Wrapp
// Validate.js may be freely distributed under the MIT license.
// For all details and documentation:
// http://validatejs.org/
(function(exports, module) {
"use strict";
// The main function that calls the validators specified by the constraints.
// The options are the following:
//
var validate = function(attributes, constraints, options) {
var attr
, error
, validator
, validatorName
, validatorOptions
, value
, validators
, errors = {};
options = options || {};
// Loops through each constraints, finds the correct validator and run it.
for (attr in constraints) {
value = attributes[attr];
validators = v.result(constraints[attr], value, attributes, attr);
for (validatorName in validators) {
validator = v.validators[validatorName];
if (!validator) {
error = v.format("Unknown validator %{name}", {name: validatorName});
throw new Error(error);
}
validatorOptions = validators[validatorName];
// This allows the options to be a function. The function will be called
// with the value, attribute name and the complete dict of attribues.
// This is useful when you want to have different validations depending
// on the attribute value.
validatorOptions = v.result(validatorOptions, value, attributes, attr);
if (!validatorOptions) continue;
error = validator.call(validator,
value,
validatorOptions,
attr,
attributes);
// The validator is allowed to return a string or an array.
if (v.isString(error)) error = [error];
if (error && error.length > 0)
errors[attr] = (errors[attr] || []).concat(error);
}
}
// Return the errors if we have any
for (attr in errors) return v.fullMessages(errors, options);
};
var v = validate
, root = this
, XDate = root.XDate
// Finds %{key} style patterns in the given string
, FORMAT_REGEXP = /%\{([^\}]+)\}/g;
// Copies over attributes from one or more sources to a single destination.
// Very much similar to underscore's extend.
// The first argument is the target object and the remaining arguments will be
// used as targets.
v.extend = function(obj) {
var i
, attr
, source
, sources = [].slice.call(arguments, 1);
for (i = 0; i < sources.length; ++i) {
source = sources[i];
for (attr in source) obj[attr] = source[attr];
}
return obj;
};
v.extend(validate, {
// If the given argument is a call: function the and: function return the value
// otherwise just return the value. Additional arguments will be passed as
// arguments to the function.
// Example:
// ```
// result('foo') // 'foo'
// result(Math.max, 1, 2) // 2
// ```
result: function(value) {
var args = [].slice.call(arguments, 1);
if (typeof value === 'function') value = value.apply(null, args);
return value;
},
// Checks if the value is a number. This function does not consider NaN a
// number like many other `isNumber` functions do.
isNumber: function(value) {
return typeof value === 'number' && !isNaN(value);
},
// A simple check to verify that the value is an integer. Uses `isNumber`
// and a simple modulo check.
isInteger: function(value) {
return v.isNumber(value) && value % 1 === 0;
},
// Uses the `Object` function to check if the given argument is an object.
isObject: function(obj) {
return obj === Object(obj);
},
// Returns false if the object is `null` of `undefined`
isDefined: function(obj) {
return obj !== null && obj !== undefined;
},
// Formats the specified strings with the given values like so:
// ```
// format("Foo: %{foo}", {foo: "bar"}) // "Foo bar"
// ```
format: function(str, vals) {
return str.replace(FORMAT_REGEXP, function(m0, m1) {
return String(vals[m1]);
});
},
// "Prettifies" the given string.
// Prettifying means replacing - and _ with spaces as well as splitting
// camel case words.
prettify: function(str) {
return str
// Replaces - and _ with spaces
.replace(/[_\-]/g, ' ')
// Splits camel cased words
.replace(/([a-z])([A-Z])/g, function(m0, m1, m2) {
return "" + m1 + " " + m2.toLowerCase();
})
.toLowerCase();
},
isString: function(value) {
return typeof value === 'string';
},
isArray: function(value) {
return {}.toString.call(value) === '[object Array]';
},
contains: function(obj, value) {
var i;
if (!v.isDefined(obj)) return false;
if (v.isArray(obj)) {
if (obj.indexOf(value)) return obj.indexOf(value) !== -1;
for (i = obj.length - 1; i >= 0; --i) {
if (obj[i] === value) return true;
}
return false;
}
return value in obj;
},
capitalize: function(str) {
if (!str) return str;
return str[0].toUpperCase() + str.slice(1);
},
fullMessages: function(errors, options) {
options = options || {};
var ret = options.flatten ? [] : {}
, attr
, i
, error;
if (!errors) return ret;
// Converts the errors of object of the format
// {attr: [<error>, <error>, ...]} to contain the attribute name.
for (attr in errors) {
for (i = 0; i < errors[attr].length; ++i) {
error = errors[attr][i];
if (error[0] === '^') error = error.slice(1);
else if (options.fullMessages !== false) {
error = v.format("%{attr} %{message}", {
attr: v.capitalize(v.prettify(attr)),
message: error
});
}
error = error.replace(/\\\^/g, "^");
// If flatten is true a flat array is returned.
if (options.flatten) ret.push(error);
else (ret[attr] || (ret[attr] = [])).push(error);
}
}
return ret;
},
});
validate.validators = {
// Presence validates that the value isn't empty
presence: function(value, options) {
var message = options.message || "can't be blank"
, attr;
// Null and undefined aren't allowed
if (!v.isDefined(value)) return message;
if (typeof value === 'string') {
// Tests if the string contains only whitespace (tab, newline, space etc)
if ((/^\s*$/).test(value)) return message;
}
else if (v.isArray(value)) {
// For arrays we use the length property
if (value.length === 0) return message;
}
else if (v.isObject(value)) {
// If we find at least one property we consider it non empty
for (attr in value) return;
return message;
}
},
length: function(value, options) {
// Null and undefined are fine
if (!v.isDefined(value)) return;
var is = options.is
, maximum = options.maximum
, minimum = options.minimum
, tokenizer = options.tokenizer || function(val) { return val; }
, err
, errors = [];
value = tokenizer(value);
// Is checks
if (v.isNumber(is) && value.length !== is) {
err = options.wrongLength ||
"is the wrong length (should be %{count} characters)";
errors.push(v.format(err, {count: is}));
}
if (v.isNumber(minimum) && value.length < minimum) {
err = options.tooShort ||
"is too short (minimum is %{count} characters)";
errors.push(v.format(err, {count: minimum}));
}
if (v.isNumber(maximum) && value.length > maximum) {
err = options.tooLong ||
"is too long (maximum is %{count} characters)";
errors.push(v.format(err, {count: maximum}));
}
if (errors.length > 0) return options.message || errors;
},
numericality: function(value, options) {
if (!v.isDefined(value)) return;
var errors = []
, name
, count
, checks = {
greaterThan: function(v, c) { return v > c; },
greaterThanOrEqualTo: function(v, c) { return v >= c; },
equalTo: function(v, c) { return v === c; },
lessThan: function(v, c) { return v < c; },
lessThanOrEqualTo: function(v, c) { return v <= c; }
};
// Coerce the value to a number unless we're being strict.
if (options.noStrings !== true && v.isString(value)) value = +value;
// If it's not a number we shouldn't continue since it will compare it.
if (!v.isNumber(value)) return options.message || "is not a number";
// Same logic as above, sort of. Don't bother with comparisons if this
// doesn't pass.
if (options.onlyInteger && !v.isInteger(value))
return options.message || "must be an integer";
for (name in checks) {
count = options[name];
if (v.isNumber(count) && !checks[name](value, count)) {
errors.push(v.format("must be %{type} %{count}", {
count: count,
type: v.prettify(name)
}));
}
}
if (options.odd && value % 2 !== 1) errors.push("must be odd");
if (options.even && value % 2 !== 0) errors.push("must be even");
if (errors.length) return options.message || errors;
},
datetime: v.extend(function(value, options) {
if (!v.isDefined(value)) return;
var err
, errors = []
, message = options.message
, earliest = options.earliest ? this.parse(options.earliest, options) : NaN
, latest = options.latest ? this.parse(options.latest, options) : NaN;
value = this.parse(value, options);
if (isNaN(value) || options.dateOnly && value % 86400000 !== 0)
return message || "must be a valid date";
if (!isNaN(earliest) && value < earliest) {
err = "must be no earlier than %{date}";
err = v.format(err, {date: this.format(earliest, options)});
errors.push(err);
}
if (!isNaN(latest) && value > latest) {
err = "must be no later than %{date}";
err = v.format(err, {date: this.format(latest, options)});
errors.push(err);
}
if (errors.length) return options.message || errors;
}, {
// This is the function that will be used to convert input to the number
// of millis since the epoch.
// It should return NaN if it's not a valid date.
parse: function(value, options) {
return new XDate(value, true).getTime();
},
// Formats the given timestamp. Uses ISO8601 to format them.
// If options.dateOnly is true then only the year, month and day will be
// output.
format: function(date, options) {
var format = options.dateFormat || (options.dateOnly ? "yyyy-MM-dd" : "u");
return new XDate(date, true).toString(format);
}
}),
date: function(value, options) {
options = v.extend({}, options, {onlyDate: true});
return v.validators.datetime(value, options);
},
format: function(value, options) {
if (v.isString(options) || (options instanceof RegExp))
options = {pattern: options};
var message = options.message || "is invalid"
, pattern = options.pattern
, match;
if (!v.isDefined(value)) return;
if (!v.isString(value)) return message;
if (v.isString(pattern))
pattern = new RegExp(options.pattern, options.flags);
match = pattern.exec(value);
if (!match || match[0].length != value.length) return message;
},
inclusion: function(value, options) {
if (v.isArray(options)) options = {within: options};
if (!v.isDefined(value)) return;
if (v.contains(options.within, value)) return;
var message = options.message || "^%{value} is not included in the list";
return v.format(message, {value: value});
},
exclusion: function(value, options) {
if (v.isArray(options)) options = {within: options};
if (!v.isDefined(value)) return;
if (!v.contains(options.within, value)) return;
var message = options.message || "^%{value} is restricted";
return v.format(message, {value: value});
}
};
if (exports) {
if (module && module.exports) exports = module.exports = validate;
exports.validate = validate;
}
else root.validate = validate;
}).call(this,
typeof exports !== 'undefined' ? exports : null,
typeof module !== 'undefined' ? module : null);
| Piicksarn/cdnjs | ajax/libs/validate.js/0.1.1/validate.js | JavaScript | mit | 12,865 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["sourceMap"] = factory();
else
root["sourceMap"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;
exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer;
exports.SourceNode = __webpack_require__(10).SourceNode;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var base64VLQ = __webpack_require__(2);
var util = __webpack_require__(4);
var ArraySet = __webpack_require__(5).ArraySet;
var MappingList = __webpack_require__(6).MappingList;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. You may pass an object with the following
* properties:
*
* - file: The filename of the generated source.
* - sourceRoot: A root for all relative URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param aSourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
var sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error(
'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
'or the source map\'s "file" property. Both were omitted.'
);
}
sourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "sourceFile" relative if an absolute Url is passed.
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "sourceFile"
this._mappings.unsortedForEach(function (mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source)
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aSourceMapPath != null) {
sourceFile = util.join(aSourceMapPath, sourceFile);
}
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
// When aOriginal is truthy but has empty values for .line and .column,
// it is most likely a programmer error. In this case we throw a very
// specific error message to try to guide them the right way.
// For example: https://github.com/Polymer/polymer-bundler/pull/519
if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
throw new Error(
'original.line and original.column are not numbers -- you probably meant to omit ' +
'the original mapping entirely and only map the generated position. If so, pass ' +
'null for the original mapping instead of an object with empty or null values.'
);
}
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var next;
var mapping;
var nameIdx;
var sourceIdx;
var mappings = this._mappings.toArray();
for (var i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = ''
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ',';
}
}
next += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports.SourceMapGenerator = SourceMapGenerator;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var base64 = __webpack_require__(3);
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string via the out parameter.
*/
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};
/***/ }),
/* 3 */
/***/ (function(module, exports) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function (number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
};
/**
* Decode a single base 64 character code digit to an integer. Returns -1 on
* failure.
*/
exports.decode = function (charCode) {
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var littleA = 97; // 'a'
var littleZ = 122; // 'z'
var zero = 48; // '0'
var nine = 57; // '9'
var plus = 43; // '+'
var slash = 47; // '/'
var littleOffset = 26;
var numberOffset = 52;
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
if (bigA <= charCode && charCode <= bigZ) {
return (charCode - bigA);
}
// 26 - 51: abcdefghijklmnopqrstuvwxyz
if (littleA <= charCode && charCode <= littleZ) {
return (charCode - littleA + littleOffset);
}
// 52 - 61: 0123456789
if (zero <= charCode && charCode <= nine) {
return (charCode - zero + numberOffset);
}
// 62: +
if (charCode == plus) {
return 62;
}
// 63: /
if (charCode == slash) {
return 63;
}
// Invalid base64 digit.
return -1;
};
/***/ }),
/* 4 */
/***/ (function(module, exports) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = exports.isAbsolute(path);
var parts = path.split(/\/+/);
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/'
? aPath
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function (aPath) {
return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
var supportsNullProto = (function () {
var obj = Object.create(null);
return !('__proto__' in obj);
}());
function identity (s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return '$' + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
var length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
for (var i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = __webpack_require__(4);
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = hasNativeMap ? new Map() : Object.create(null);
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
ArraySet.prototype.size = function ArraySet_size() {
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
if (hasNativeMap) {
this._set.set(aStr, idx);
} else {
this._set[sStr] = idx;
}
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
if (hasNativeMap) {
return this._set.has(aStr);
} else {
var sStr = util.toSetString(aStr);
return has.call(this._set, sStr);
}
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (hasNativeMap) {
var idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
}
} else {
var sStr = util.toSetString(aStr);
if (has.call(this._set, sStr)) {
return this._set[sStr];
}
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = __webpack_require__(4);
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach =
function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = __webpack_require__(4);
var binarySearch = __webpack_require__(8);
var ArraySet = __webpack_require__(5).ArraySet;
var base64VLQ = __webpack_require__(2);
var quickSort = __webpack_require__(9).quickSort;
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
return sourceMap.sections != null
? new IndexedSourceMapConsumer(sourceMap)
: new BasicSourceMapConsumer(sourceMap);
}
SourceMapConsumer.fromSourceMap = function(aSourceMap) {
return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
}
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function () {
if (!this.__generatedMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function () {
if (!this.__originalMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
SourceMapConsumer.prototype._charIsMappingSeparator =
function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
var c = aStr.charAt(index);
return c === ";" || c === ",";
};
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
throw new Error("Subclasses must implement _parseMappings");
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer.LEAST_UPPER_BOUND = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping =
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source === null ? null : this._sources.at(mapping.source);
if (source != null && sourceRoot != null) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name === null ? null : this._names.at(mapping.name)
};
}, this).forEach(aCallback, context);
};
/**
* Returns all generated line and column information for the original source,
* line, and column provided. If no column is provided, returns all mappings
* corresponding to a either the line we are searching for or the next
* closest line that has any mappings. Otherwise, returns all mappings
* corresponding to the given line and either the column we are searching for
* or the next closest column that has any offsets.
*
* The only argument is an object with the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: Optional. the column number in the original source.
*
* and an array of objects is returned, each with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.allGeneratedPositionsFor =
function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
var line = util.getArg(aArgs, 'line');
// When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
// returns the index of the closest mapping less than the needle. By
// setting needle.originalColumn to 0, we thus find the last mapping for
// the given line, provided such a mapping exists.
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: line,
originalColumn: util.getArg(aArgs, 'column', 0)
};
if (this.sourceRoot != null) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
if (!this._sources.has(needle.source)) {
return [];
}
needle.source = this._sources.indexOf(needle.source);
var mappings = [];
var index = this._findMapping(needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions,
binarySearch.LEAST_UPPER_BOUND);
if (index >= 0) {
var mapping = this._originalMappings[index];
if (aArgs.column === undefined) {
var originalLine = mapping.originalLine;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we found. Since
// mappings are sorted, this is guaranteed to find all mappings for
// the line we found.
while (mapping && mapping.originalLine === originalLine) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
});
mapping = this._originalMappings[++index];
}
} else {
var originalColumn = mapping.originalColumn;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we were searching for.
// Since mappings are sorted, this is guaranteed to find all mappings for
// the line we are searching for.
while (mapping &&
mapping.originalLine === line &&
mapping.originalColumn == originalColumn) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
});
mapping = this._originalMappings[++index];
}
}
}
return mappings;
};
exports.SourceMapConsumer = SourceMapConsumer;
/**
* A BasicSourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: Optional. The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function BasicSourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
sources = sources
.map(String)
// Some source maps produce relative source paths like "./foo.js" instead of
// "foo.js". Normalize these first so that future comparisons will succeed.
// See bugzil.la/1090768.
.map(util.normalize)
// Always ensure that absolute sources are internally stored relative to
// the source root, if the source root is absolute. Not doing this would
// be particularly problematic when the source root is a prefix of the
// source (valid, but why??). See github issue #199 and bugzil.la/1188982.
.map(function (source) {
return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
? util.relative(sourceRoot, source)
: source;
});
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names.map(String), true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns BasicSourceMapConsumer
*/
BasicSourceMapConsumer.fromSourceMap =
function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(BasicSourceMapConsumer.prototype);
var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
smc.sourceRoot);
smc.file = aSourceMap._file;
// Because we are modifying the entries (by converting string sources and
// names to indices into the sources and names ArraySets), we have to make
// a copy of the entry or else bad things happen. Shared mutable state
// strikes again! See github issue #191.
var generatedMappings = aSourceMap._mappings.toArray().slice();
var destGeneratedMappings = smc.__generatedMappings = [];
var destOriginalMappings = smc.__originalMappings = [];
for (var i = 0, length = generatedMappings.length; i < length; i++) {
var srcMapping = generatedMappings[i];
var destMapping = new Mapping;
destMapping.generatedLine = srcMapping.generatedLine;
destMapping.generatedColumn = srcMapping.generatedColumn;
if (srcMapping.source) {
destMapping.source = sources.indexOf(srcMapping.source);
destMapping.originalLine = srcMapping.originalLine;
destMapping.originalColumn = srcMapping.originalColumn;
if (srcMapping.name) {
destMapping.name = names.indexOf(srcMapping.name);
}
destOriginalMappings.push(destMapping);
}
destGeneratedMappings.push(destMapping);
}
quickSort(smc.__originalMappings, util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
BasicSourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
get: function () {
return this._sources.toArray().map(function (s) {
return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
/**
* Provide the JIT with a nice shape / hidden class.
*/
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
BasicSourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var length = aStr.length;
var index = 0;
var cachedSegments = {};
var temp = {};
var originalMappings = [];
var generatedMappings = [];
var mapping, str, segment, end, value;
while (index < length) {
if (aStr.charAt(index) === ';') {
generatedLine++;
index++;
previousGeneratedColumn = 0;
}
else if (aStr.charAt(index) === ',') {
index++;
}
else {
mapping = new Mapping();
mapping.generatedLine = generatedLine;
// Because each offset is encoded relative to the previous one,
// many segments often have the same encoding. We can exploit this
// fact by caching the parsed variable length fields of each segment,
// allowing us to avoid a second parse if we encounter the same
// segment again.
for (end = index; end < length; end++) {
if (this._charIsMappingSeparator(aStr, end)) {
break;
}
}
str = aStr.slice(index, end);
segment = cachedSegments[str];
if (segment) {
index += str.length;
} else {
segment = [];
while (index < end) {
base64VLQ.decode(aStr, index, temp);
value = temp.value;
index = temp.rest;
segment.push(value);
}
if (segment.length === 2) {
throw new Error('Found a source, but no line and column');
}
if (segment.length === 3) {
throw new Error('Found a source and line, but no column');
}
cachedSegments[str] = segment;
}
// Generated column.
mapping.generatedColumn = previousGeneratedColumn + segment[0];
previousGeneratedColumn = mapping.generatedColumn;
if (segment.length > 1) {
// Original source.
mapping.source = previousSource + segment[1];
previousSource += segment[1];
// Original line.
mapping.originalLine = previousOriginalLine + segment[2];
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
// Original column.
mapping.originalColumn = previousOriginalColumn + segment[3];
previousOriginalColumn = mapping.originalColumn;
if (segment.length > 4) {
// Original name.
mapping.name = previousName + segment[4];
previousName += segment[4];
}
}
generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
originalMappings.push(mapping);
}
}
}
quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
this.__generatedMappings = generatedMappings;
quickSort(originalMappings, util.compareByOriginalPositions);
this.__originalMappings = originalMappings;
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
BasicSourceMapConsumer.prototype._findMapping =
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
aColumnName, aComparator, aBias) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got '
+ aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
};
/**
* Compute the last column for each generated mapping. The last column is
* inclusive.
*/
BasicSourceMapConsumer.prototype.computeColumnSpans =
function SourceMapConsumer_computeColumnSpans() {
for (var index = 0; index < this._generatedMappings.length; ++index) {
var mapping = this._generatedMappings[index];
// Mappings do not contain a field for the last generated columnt. We
// can come up with an optimistic estimate, however, by assuming that
// mappings are contiguous (i.e. given two consecutive mappings, the
// first mapping ends where the second one starts).
if (index + 1 < this._generatedMappings.length) {
var nextMapping = this._generatedMappings[index + 1];
if (mapping.generatedLine === nextMapping.generatedLine) {
mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
continue;
}
}
// The last mapping for each line spans the entire line.
mapping.lastGeneratedColumn = Infinity;
}
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
BasicSourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var index = this._findMapping(
needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
util.compareByGeneratedPositionsDeflated,
util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
);
if (index >= 0) {
var mapping = this._generatedMappings[index];
if (mapping.generatedLine === needle.generatedLine) {
var source = util.getArg(mapping, 'source', null);
if (source !== null) {
source = this._sources.at(source);
if (this.sourceRoot != null) {
source = util.join(this.sourceRoot, source);
}
}
var name = util.getArg(mapping, 'name', null);
if (name !== null) {
name = this._names.at(name);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: name
};
}
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
function BasicSourceMapConsumer_hasContentsOfAllSources() {
if (!this.sourcesContent) {
return false;
}
return this.sourcesContent.length >= this._sources.size() &&
!this.sourcesContent.some(function (sc) { return sc == null; });
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
BasicSourceMapConsumer.prototype.sourceContentFor =
function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot != null) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot != null
&& (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file"
&& this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
}
if ((!url.path || url.path == "/")
&& this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
// This function is used recursively from
// IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
// don't want to throw if we can't find the source - we just want to
// return null, so we provide a flag to exit gracefully.
if (nullOnMissing) {
return null;
}
else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
BasicSourceMapConsumer.prototype.generatedPositionFor =
function SourceMapConsumer_generatedPositionFor(aArgs) {
var source = util.getArg(aArgs, 'source');
if (this.sourceRoot != null) {
source = util.relative(this.sourceRoot, source);
}
if (!this._sources.has(source)) {
return {
line: null,
column: null,
lastColumn: null
};
}
source = this._sources.indexOf(source);
var needle = {
source: source,
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
var index = this._findMapping(
needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions,
util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
);
if (index >= 0) {
var mapping = this._originalMappings[index];
if (mapping.source === needle.source) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
};
}
}
return {
line: null,
column: null,
lastColumn: null
};
};
exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
/**
* An IndexedSourceMapConsumer instance represents a parsed source map which
* we can query for information. It differs from BasicSourceMapConsumer in
* that it takes "indexed" source maps (i.e. ones with a "sections" field) as
* input.
*
* The only parameter is a raw source map (either as a JSON string, or already
* parsed to an object). According to the spec for indexed source maps, they
* have the following attributes:
*
* - version: Which version of the source map spec this map is following.
* - file: Optional. The generated file this source map is associated with.
* - sections: A list of section definitions.
*
* Each value under the "sections" field has two fields:
* - offset: The offset into the original specified at which this section
* begins to apply, defined as an object with a "line" and "column"
* field.
* - map: A source map definition. This source map could also be indexed,
* but doesn't have to be.
*
* Instead of the "map" field, it's also possible to have a "url" field
* specifying a URL to retrieve a source map from, but that's currently
* unsupported.
*
* Here's an example source map, taken from the source map spec[0], but
* modified to omit a section which uses the "url" field.
*
* {
* version : 3,
* file: "app.js",
* sections: [{
* offset: {line:100, column:10},
* map: {
* version : 3,
* file: "section.js",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AAAA,E;;ABCDE;"
* }
* }],
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
*/
function IndexedSourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sections = util.getArg(sourceMap, 'sections');
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
this._sources = new ArraySet();
this._names = new ArraySet();
var lastOffset = {
line: -1,
column: 0
};
this._sections = sections.map(function (s) {
if (s.url) {
// The url field will require support for asynchronicity.
// See https://github.com/mozilla/source-map/issues/16
throw new Error('Support for url field in sections not implemented.');
}
var offset = util.getArg(s, 'offset');
var offsetLine = util.getArg(offset, 'line');
var offsetColumn = util.getArg(offset, 'column');
if (offsetLine < lastOffset.line ||
(offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
throw new Error('Section offsets must be ordered and non-overlapping.');
}
lastOffset = offset;
return {
generatedOffset: {
// The offset fields are 0-based, but we use 1-based indices when
// encoding/decoding from VLQ.
generatedLine: offsetLine + 1,
generatedColumn: offsetColumn + 1
},
consumer: new SourceMapConsumer(util.getArg(s, 'map'))
}
});
}
IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
/**
* The version of the source mapping spec that we are consuming.
*/
IndexedSourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
get: function () {
var sources = [];
for (var i = 0; i < this._sections.length; i++) {
for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
sources.push(this._sections[i].consumer.sources[j]);
}
}
return sources;
}
});
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
IndexedSourceMapConsumer.prototype.originalPositionFor =
function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
// Find the section containing the generated position we're trying to map
// to an original position.
var sectionIndex = binarySearch.search(needle, this._sections,
function(needle, section) {
var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
if (cmp) {
return cmp;
}
return (needle.generatedColumn -
section.generatedOffset.generatedColumn);
});
var section = this._sections[sectionIndex];
if (!section) {
return {
source: null,
line: null,
column: null,
name: null
};
}
return section.consumer.originalPositionFor({
line: needle.generatedLine -
(section.generatedOffset.generatedLine - 1),
column: needle.generatedColumn -
(section.generatedOffset.generatedLine === needle.generatedLine
? section.generatedOffset.generatedColumn - 1
: 0),
bias: aArgs.bias
});
};
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
function IndexedSourceMapConsumer_hasContentsOfAllSources() {
return this._sections.every(function (s) {
return s.consumer.hasContentsOfAllSources();
});
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
IndexedSourceMapConsumer.prototype.sourceContentFor =
function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
var content = section.consumer.sourceContentFor(aSource, true);
if (content) {
return content;
}
}
if (nullOnMissing) {
return null;
}
else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
IndexedSourceMapConsumer.prototype.generatedPositionFor =
function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
// Only consider this section if the requested source is in the list of
// sources of the consumer.
if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
continue;
}
var generatedPosition = section.consumer.generatedPositionFor(aArgs);
if (generatedPosition) {
var ret = {
line: generatedPosition.line +
(section.generatedOffset.generatedLine - 1),
column: generatedPosition.column +
(section.generatedOffset.generatedLine === generatedPosition.line
? section.generatedOffset.generatedColumn - 1
: 0)
};
return ret;
}
}
return {
line: null,
column: null
};
};
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
IndexedSourceMapConsumer.prototype._parseMappings =
function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
this.__generatedMappings = [];
this.__originalMappings = [];
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
var sectionMappings = section.consumer._generatedMappings;
for (var j = 0; j < sectionMappings.length; j++) {
var mapping = sectionMappings[j];
var source = section.consumer._sources.at(mapping.source);
if (section.consumer.sourceRoot !== null) {
source = util.join(section.consumer.sourceRoot, source);
}
this._sources.add(source);
source = this._sources.indexOf(source);
var name = section.consumer._names.at(mapping.name);
this._names.add(name);
name = this._names.indexOf(name);
// The mappings coming from the consumer for the section have
// generated positions relative to the start of the section, so we
// need to offset them to be relative to the start of the concatenated
// generated file.
var adjustedMapping = {
source: source,
generatedLine: mapping.generatedLine +
(section.generatedOffset.generatedLine - 1),
generatedColumn: mapping.generatedColumn +
(section.generatedOffset.generatedLine === mapping.generatedLine
? section.generatedOffset.generatedColumn - 1
: 0),
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: name
};
this.__generatedMappings.push(adjustedMapping);
if (typeof adjustedMapping.originalLine === 'number') {
this.__originalMappings.push(adjustedMapping);
}
}
}
quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
quickSort(this.__originalMappings, util.compareByOriginalPositions);
};
exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
/***/ }),
/* 8 */
/***/ (function(module, exports) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
}
else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};
/***/ }),
/* 9 */
/***/ (function(module, exports) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
// It turns out that some (most?) JavaScript engines don't self-host
// `Array.prototype.sort`. This makes sense because C++ will likely remain
// faster than JS when doing raw CPU-intensive sorting. However, when using a
// custom comparator function, calling back and forth between the VM's C++ and
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
// worse generated code for the comparator function than would be optimal. In
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.
/**
* Swap the elements indexed by `x` and `y` in the array `ary`.
*
* @param {Array} ary
* The array.
* @param {Number} x
* The index of the first item.
* @param {Number} y
* The index of the second item.
*/
function swap(ary, x, y) {
var temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
/**
* Returns a random integer within the range `low .. high` inclusive.
*
* @param {Number} low
* The lower bound on the range.
* @param {Number} high
* The upper bound on the range.
*/
function randomIntInRange(low, high) {
return Math.round(low + (Math.random() * (high - low)));
}
/**
* The Quick Sort algorithm.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
* @param {Number} p
* Start index of the array
* @param {Number} r
* End index of the array
*/
function doQuickSort(ary, comparator, p, r) {
// If our lower bound is less than our upper bound, we (1) partition the
// array into two pieces and (2) recurse on each half. If it is not, this is
// the empty array and our base case.
if (p < r) {
// (1) Partitioning.
//
// The partitioning chooses a pivot between `p` and `r` and moves all
// elements that are less than or equal to the pivot to the before it, and
// all the elements that are greater than it after it. The effect is that
// once partition is done, the pivot is in the exact place it will be when
// the array is put in sorted order, and it will not need to be moved
// again. This runs in O(n) time.
// Always choose a random pivot so that an input array which is reverse
// sorted does not cause O(n^2) running time.
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
// Immediately after `j` is incremented in this loop, the following hold
// true:
//
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
//
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
// (2) Recurse on each half.
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r);
}
}
/**
* Sort the given array in-place with the given comparator function.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
*/
exports.quickSort = function (ary, comparator) {
doQuickSort(ary, comparator, 0, ary.length - 1);
};
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;
var util = __webpack_require__(4);
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
var REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
var NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
* @param aRelativePath Optional. The path that relative sources in the
* SourceMapConsumer should be relative to.
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are accessed by calling `shiftNextLine`.
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var remainingLinesIndex = 0;
var shiftNextLine = function() {
var lineContents = getNextLine();
// The last line of a file might not have a newline.
var newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
};
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[remainingLinesIndex];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[remainingLinesIndex];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLinesIndex < remainingLines.length) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.splice(remainingLinesIndex).join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
var source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
/***/ })
/******/ ])
});
; | hellokidder/js-studying | 微信小程序/wxtest/node_modules/source-map/dist/source-map.js | JavaScript | mit | 101,940 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build amd64,!appengine,!gccgo
package intsets
func popcnt(x word) int
func havePOPCNT() bool
var hasPOPCNT = havePOPCNT()
// popcount returns the population count (number of set bits) of x.
func popcount(x word) int {
if hasPOPCNT {
return popcnt(x)
}
return popcountTable(x) // faster than Hacker's Delight
}
| muzining/net | x/tools/container/intsets/popcnt_amd64.go | GO | bsd-3-clause | 483 |