text
stringlengths 2
100k
| meta
dict |
---|---|
class MyDocument < NSDocument
attr_accessor :packerView
def init
super
@packModel = PackModel.new
@packModel.setUndoManager undoManager
self
end
def windowNibName
@nib_name ||= 'MyDocument'
end
def updateUI
@packerView.setPackModel @packModel
@packerView.window.nextResponder = CatalogController.sharedCatalogController
end
def windowControllerDidLoadNib(controller)
super
updateUI
end
def dataOfType(type, error:outError)
NSKeyedArchiver.archivedDataWithRootObject @packModel
end
def readFromData(data, ofType:type, error:outError)
@packModel = NSKeyedUnarchiver.unarchiveObjectWithData data
@packModel.setUndoManager undoManager
updateUI if @packerView
true
end
def printOperationWithSettings(printSettings, error:outError)
NSPrintOperation.printOperationWithView @packerView, printInfo:printInfo
end
end
|
{
"pile_set_name": "Github"
}
|
<discover-app class="app-container">
<!-- Local nav. -->
<kbn-top-nav name="discover" config="topNavMenu">
<!-- Transcluded elements. -->
<div data-transclude-slots>
<!-- Breadcrumbs. -->
<div data-transclude-slot="topLeftCorner" class="kuiLocalBreadcrumbs">
<h1 tabindex="0" id="kui_local_breadcrumb" class="kuiLocalBreadcrumb">
<span ng-show="opts.savedSearch.id" class="kuiLocalBreadcrumb__emphasis">
<span data-test-subj="discoverCurrentQuery" ng-bind="opts.savedSearch.lastSavedTitle"></span>
<span
id="reload_saved_search"
aria-label="{{::'kbn.discover.reloadSavedSearchAriaLabel' | i18n: {defaultMessage: 'Reload Saved Search'} }}"
tooltip="{{::'kbn.discover.reloadSavedSearchTooltip' | i18n: {defaultMessage: 'Reload Saved Search'} }}"
ng-click="resetQuery()"
kbn-accessible-click
class="kuiIcon fa-undo small"
></span>
</span>
<span data-test-subj="discoverQueryHits" class="kuiLocalBreadcrumb__emphasis">{{(hits || 0) | number:0}}</span>
<span
i18n-id="kbn.discover.hitsPluralTitle"
i18n-default-message="{hits, plural, one {hit} other {hits}}"
i18n-values="{ hits }"
></span>
</h1>
</div>
<!-- Search. -->
<div data-transclude-slot="bottomRow" class="fullWidth">
<query-bar
query="state.query"
on-submit="updateQueryAndFetch"
app-name="'discover'"
index-patterns="[indexPattern]"
></query-bar>
</div>
</div>
</kbn-top-nav>
<main class="container-fluid">
<div class="row">
<filter-bar
state="state"
index-patterns="[indexPattern]"
></filter-bar>
</div>
<div class="row">
<div class="col-md-2 sidebar-container collapsible-sidebar" id="discover-sidebar">
<disc-field-chooser
class="dscFieldChooser"
columns="state.columns"
hits="rows"
field-counts="fieldCounts"
index-pattern="searchSource.getField('index')"
index-pattern-list="opts.indexPatternList"
state="state"
on-add-field="addColumn"
on-add-filter="filterQuery"
on-remove-field="removeColumn"
>
</disc-field-chooser>
</div>
<div class="dscWrapper col-md-10">
<div class="dscWrapper__content">
<discover-unsupported-index-pattern
ng-if="isUnsupportedIndexPattern"
unsupported-type="unsupportedIndexPatternType"
></discover-unsupported-index-pattern>
<discover-no-results
ng-show="resultState === 'none'"
top-nav-toggle="kbnTopNav.toggle"
is-time-picker-open="kbnTopNav.isCurrent('filter')"
shard-failures="failures"
time-field-name="opts.timefield"
query-language="state.query.language"
get-doc-link="getDocLink"
></discover-no-results>
<!-- loading -->
<div ng-show="resultState === 'loading'">
<discover-fetch-error
ng-show="fetchError"
fetch-error="fetchError"
></discover-fetch-error>
<div
ng-hide="fetchError"
class="dscOverlay"
>
<div class="euiTitle" >
<h2
i18n-id="kbn.discover.searchingTitle"
i18n-default-message="Searching"
></h2>
</div>
<div class="euiSpacer euiSpacer--m"></div>
<div ng-show="fetchStatus">{{fetchStatus.complete}}/{{fetchStatus.total}}</div>
</div>
</div>
<!-- result -->
<div class="dscResults" ng-show="resultState === 'ready'">
<button
class="kuiButton kuiButton--basic kuiButton--iconText dscSkipButton"
ng-click="showAllRows(); scrollToBottom()"
>
<span class="kuiButton__inner">
<span aria-hidden="true" class="kuiButton__icon kuiIcon fa-chevron-down"></span>
<span
i18n-id="kbn.discover.skipToBottomButtonLabel"
i18n-default-message="Skip to bottom"
></span>
</span>
</button>
<section
aria-label="{{::'kbn.discover.histogramOfFoundDocumentsAriaLabel' | i18n: {defaultMessage: 'Histogram of found documents'} }}"
class="dscTimechart"
ng-if="opts.timefield"
>
<header class="dscTimechart__header">
<div class="small">
<span
tooltip="{{::'kbn.discover.howToChangeTheTimeTooltip' | i18n: {defaultMessage: 'To change the time, click the clock icon in the navigation bar'} }}"
>
{{timeRange.from | moment}} - {{timeRange.to | moment}}
</span>
—
<span class="form-inline">
<select
class="dscResults__interval form-control"
ng-model="state.interval"
ng-options="interval.val as interval.display for interval in intervalOptions | filter: intervalEnabled"
ng-blur="toggleInterval()"
data-test-subj="discoverIntervalSelect"
>
</select>
<span ng-if="bucketInterval.scaled">
<icon-tip
content="getBucketIntervalToolTipText()"
position="'top'"
></icon-tip>
<span
i18n-id="kbn.discover.scaledToDescription"
i18n-default-message="Scaled to {bucketIntervalDescription}"
i18n-values="{
bucketIntervalDescription: bucketInterval.description
}"
></span>
</span>
</span>
</div>
</header>
<div id="discoverHistogram"
ng-show="vis && rows.length !== 0"
style="display: flex; height: 200px"
>
</div>
</section>
<section
class="dscTable"
fixed-scroll
aria-label="{{::'kbn.discover.documentsAriaLabel' | i18n: {defaultMessage: 'Documents'} }}"
>
<doc-table
hits="rows"
index-pattern="indexPattern"
sorting="state.sort"
columns="state.columns"
infinite-scroll="true"
filter="filterQuery"
filters="state.filters"
data-shared-item
data-title="{{opts.savedSearch.lastSavedTitle}}"
data-description="{{opts.savedSearch.description}}"
minimum-visible-rows="minimumVisibleRows"
render-complete
on-add-column="addColumn"
on-change-sort-order="setSortOrder"
on-move-column="moveColumn"
on-remove-column="removeColumn"
></doc-table>
<a tabindex="0" id="discoverBottomMarker"></a>
<div
ng-if="rows.length == opts.sampleSize"
class="dscTable__footer"
>
<span
i18n-id="kbn.discover.howToSeeOtherMatchingDocumentsDescription"
i18n-default-message="These are the first {sampleSize} documents matching
your search, refine your search to see others. "
i18n-values="{
sampleSize: opts.sampleSize,
}"
></span>
<a
kbn-accessible-click
ng-click="scrollToTop()"
i18n-id="kbn.discover.backToTopLinkText"
i18n-default-message="Back to top."
></a>
</div>
</section>
</div>
</div>
</div>
</div>
</main>
</discover-app>
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#pragma mark Blocks
typedef void (^CDUnknownBlockType)(void); // return type and parameters are unknown
#pragma mark Named Structures
struct CGPoint {
double _field1;
double _field2;
};
struct CGRect {
struct CGPoint _field1;
struct CGSize _field2;
};
struct CGSize {
double _field1;
double _field2;
};
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* PHPExcel_Writer_Excel2007_Rels
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Writer_Excel2007
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_Writer_Excel2007_Rels extends PHPExcel_Writer_Excel2007_WriterPart
{
/**
* Write relationships to XML format
*
* @param PHPExcel $pPHPExcel
* @return string XML Output
* @throws PHPExcel_Writer_Exception
*/
public function writeRelationships(PHPExcel $pPHPExcel = null)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
$customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
if (!empty($customPropertyList)) {
// Relationship docProps/app.xml
$this->writeRelationship(
$objWriter,
4,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
'docProps/custom.xml'
);
}
// Relationship docProps/app.xml
$this->writeRelationship(
$objWriter,
3,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
'docProps/app.xml'
);
// Relationship docProps/core.xml
$this->writeRelationship(
$objWriter,
2,
'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
'docProps/core.xml'
);
// Relationship xl/workbook.xml
$this->writeRelationship(
$objWriter,
1,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
'xl/workbook.xml'
);
// a custom UI in workbook ?
if ($pPHPExcel->hasRibbon()) {
$this->writeRelationShip(
$objWriter,
5,
'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility',
$pPHPExcel->getRibbonXMLData('target')
);
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write workbook relationships to XML format
*
* @param PHPExcel $pPHPExcel
* @return string XML Output
* @throws PHPExcel_Writer_Exception
*/
public function writeWorkbookRelationships(PHPExcel $pPHPExcel = null)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Relationship styles.xml
$this->writeRelationship(
$objWriter,
1,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
'styles.xml'
);
// Relationship theme/theme1.xml
$this->writeRelationship(
$objWriter,
2,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
'theme/theme1.xml'
);
// Relationship sharedStrings.xml
$this->writeRelationship(
$objWriter,
3,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
'sharedStrings.xml'
);
// Relationships with sheets
$sheetCount = $pPHPExcel->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
$this->writeRelationship(
$objWriter,
($i + 1 + 3),
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
'worksheets/sheet' . ($i + 1) . '.xml'
);
}
// Relationships for vbaProject if needed
// id : just after the last sheet
if ($pPHPExcel->hasMacros()) {
$this->writeRelationShip(
$objWriter,
($i + 1 + 3),
'http://schemas.microsoft.com/office/2006/relationships/vbaProject',
'vbaProject.bin'
);
++$i;//increment i if needed for an another relation
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write worksheet relationships to XML format
*
* Numbering is as follows:
* rId1 - Drawings
* rId_hyperlink_x - Hyperlinks
*
* @param PHPExcel_Worksheet $pWorksheet
* @param int $pWorksheetId
* @param boolean $includeCharts Flag indicating if we should write charts
* @return string XML Output
* @throws PHPExcel_Writer_Exception
*/
public function writeWorksheetRelationships(PHPExcel_Worksheet $pWorksheet = null, $pWorksheetId = 1, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Write drawing relationships?
$d = 0;
if ($includeCharts) {
$charts = $pWorksheet->getChartCollection();
} else {
$charts = array();
}
if (($pWorksheet->getDrawingCollection()->count() > 0) ||
(count($charts) > 0)) {
$this->writeRelationship(
$objWriter,
++$d,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing',
'../drawings/drawing' . $pWorksheetId . '.xml'
);
}
// Write chart relationships?
// $chartCount = 0;
// $charts = $pWorksheet->getChartCollection();
// echo 'Chart Rels: ' , count($charts) , '<br />';
// if (count($charts) > 0) {
// foreach ($charts as $chart) {
// $this->writeRelationship(
// $objWriter,
// ++$d,
// 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
// '../charts/chart' . ++$chartCount . '.xml'
// );
// }
// }
//
// Write hyperlink relationships?
$i = 1;
foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) {
if (!$hyperlink->isInternal()) {
$this->writeRelationship(
$objWriter,
'_hyperlink_' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
$hyperlink->getUrl(),
'External'
);
++$i;
}
}
// Write comments relationship?
$i = 1;
if (count($pWorksheet->getComments()) > 0) {
$this->writeRelationship(
$objWriter,
'_comments_vml' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
'../drawings/vmlDrawing' . $pWorksheetId . '.vml'
);
$this->writeRelationship(
$objWriter,
'_comments' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
'../comments' . $pWorksheetId . '.xml'
);
}
// Write header/footer relationship?
$i = 1;
if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) {
$this->writeRelationship(
$objWriter,
'_headerfooter_vml' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
'../drawings/vmlDrawingHF' . $pWorksheetId . '.vml'
);
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write drawing relationships to XML format
*
* @param PHPExcel_Worksheet $pWorksheet
* @param int &$chartRef Chart ID
* @param boolean $includeCharts Flag indicating if we should write charts
* @return string XML Output
* @throws PHPExcel_Writer_Exception
*/
public function writeDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Loop through images and write relationships
$i = 1;
$iterator = $pWorksheet->getDrawingCollection()->getIterator();
while ($iterator->valid()) {
if ($iterator->current() instanceof PHPExcel_Worksheet_Drawing
|| $iterator->current() instanceof PHPExcel_Worksheet_MemoryDrawing) {
// Write relationship for image drawing
$this->writeRelationship(
$objWriter,
$i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
'../media/' . str_replace(' ', '', $iterator->current()->getIndexedFilename())
);
}
$iterator->next();
++$i;
}
if ($includeCharts) {
// Loop through charts and write relationships
$chartCount = $pWorksheet->getChartCount();
if ($chartCount > 0) {
for ($c = 0; $c < $chartCount; ++$c) {
$this->writeRelationship(
$objWriter,
$i++,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
'../charts/chart' . ++$chartRef . '.xml'
);
}
}
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write header/footer drawing relationships to XML format
*
* @param PHPExcel_Worksheet $pWorksheet
* @return string XML Output
* @throws PHPExcel_Writer_Exception
*/
public function writeHeaderFooterDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Loop through images and write relationships
foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) {
// Write relationship for image drawing
$this->writeRelationship(
$objWriter,
$key,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
'../media/' . $value->getIndexedFilename()
);
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write Override content type
*
* @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
* @param int $pId Relationship ID. rId will be prepended!
* @param string $pType Relationship type
* @param string $pTarget Relationship target
* @param string $pTargetMode Relationship target mode
* @throws PHPExcel_Writer_Exception
*/
private function writeRelationship(PHPExcel_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '')
{
if ($pType != '' && $pTarget != '') {
// Write relationship
$objWriter->startElement('Relationship');
$objWriter->writeAttribute('Id', 'rId' . $pId);
$objWriter->writeAttribute('Type', $pType);
$objWriter->writeAttribute('Target', $pTarget);
if ($pTargetMode != '') {
$objWriter->writeAttribute('TargetMode', $pTargetMode);
}
$objWriter->endElement();
} else {
throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* vim: set et ts=3 sw=3 sts=3 ft=c:
*
* Copyright (C) 2012, 2013, 2014 James McLaughlin et al. All rights reserved.
* https://github.com/udp/json-parser
*
* 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 THE AUTHOR 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 AUTHOR 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.
*/
#ifndef _JSON_H
#define _JSON_H
#ifndef json_char
#define json_char char
#endif
#ifndef json_int_t
#ifndef _MSC_VER
#include <inttypes.h>
#define json_int_t int64_t
#else
#define json_int_t __int64
#endif
#endif
#include <stdlib.h>
#ifdef __cplusplus
#include <string.h>
extern "C"
{
#endif
typedef struct
{
unsigned long max_memory;
int settings;
/* Custom allocator support (leave null to use malloc/free)
*/
void * (* mem_alloc) (size_t, int zero, void * user_data);
void (* mem_free) (void *, void * user_data);
void * user_data; /* will be passed to mem_alloc and mem_free */
size_t value_extra; /* how much extra space to allocate for values? */
} json_settings;
#define json_enable_comments 0x01
typedef enum
{
json_none,
json_object,
json_array,
json_integer,
json_double,
json_string,
json_boolean,
json_null
} json_type;
extern const struct _json_value json_value_none;
typedef struct _json_object_entry
{
json_char * name;
unsigned int name_length;
struct _json_value * value;
} json_object_entry;
typedef struct _json_value
{
struct _json_value * parent;
json_type type;
union
{
int boolean;
json_int_t integer;
double dbl;
struct
{
unsigned int length;
json_char * ptr; /* null terminated */
} string;
struct
{
unsigned int length;
json_object_entry * values;
#if defined(__cplusplus) && __cplusplus >= 201103L
decltype(values) begin () const
{ return values;
}
decltype(values) end () const
{ return values + length;
}
#endif
} object;
struct
{
unsigned int length;
struct _json_value ** values;
#if defined(__cplusplus) && __cplusplus >= 201103L
decltype(values) begin () const
{ return values;
}
decltype(values) end () const
{ return values + length;
}
#endif
} array;
} u;
union
{
struct _json_value * next_alloc;
void * object_mem;
} _reserved;
#ifdef JSON_TRACK_SOURCE
/* Location of the value in the source JSON
*/
unsigned int line, col;
#endif
/* Some C++ operator sugar */
#ifdef __cplusplus
public:
inline _json_value ()
{ memset (this, 0, sizeof (_json_value));
}
inline const struct _json_value &operator [] (int index) const
{
if (type != json_array || index < 0
|| ((unsigned int) index) >= u.array.length)
{
return json_value_none;
}
return *u.array.values [index];
}
inline const struct _json_value &operator [] (const char * index) const
{
if (type != json_object)
return json_value_none;
for (unsigned int i = 0; i < u.object.length; ++ i)
if (!strcmp (u.object.values [i].name, index))
return *u.object.values [i].value;
return json_value_none;
}
inline operator const char * () const
{
switch (type)
{
case json_string:
return u.string.ptr;
default:
return "";
};
}
inline operator json_int_t () const
{
switch (type)
{
case json_integer:
return u.integer;
case json_double:
return (json_int_t) u.dbl;
default:
return 0;
};
}
inline operator bool () const
{
if (type != json_boolean)
return false;
return u.boolean != 0;
}
inline operator double () const
{
switch (type)
{
case json_integer:
return (double) u.integer;
case json_double:
return u.dbl;
default:
return 0;
};
}
#endif
} json_value;
json_value * json_parse (const json_char * json,
size_t length);
#define json_error_max 128
json_value * json_parse_ex (json_settings * settings,
const json_char * json,
size_t length,
char * error);
void json_value_free (json_value *);
/* Not usually necessary, unless you used a custom mem_alloc and now want to
* use a custom mem_free.
*/
void json_value_free_ex (json_settings * settings,
json_value *);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2012-2013 Nokia Corporation. All rights reserved.
* Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
* Oracle and Java are trademarks or registered trademarks of Oracle and/or its
* affiliates. Other product and company names mentioned herein may be trademarks
* or trade names of their respective owners.
* See LICENSE.TXT for license information.
*/
package com.nokia.example.rlinks.view.item;
import com.nokia.example.rlinks.VisualStyles;
import com.nokia.example.rlinks.model.LinkThing;
import com.nokia.example.rlinks.network.ImageLoader;
import com.nokia.example.rlinks.util.TextWrapper;
import com.nokia.example.rlinks.util.TouchChecker;
import com.nokia.mid.ui.LCDUIUtil;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
/**
* A custom view item representing a LinkThing.
*/
public class LinkItem
extends AbstractCustomItem {
public static final int H_SPACE = VisualStyles.LINK_H_SPACE;
public static final int V_SPACE = VisualStyles.LINK_V_SPACE;
public static final int V_SPACE_HALF = V_SPACE / 2;
public static final int SEPARATOR_H_SPACE =
VisualStyles.LINK_SEPARATOR_H_SPACE;
public static final int SEPARATOR_V_SPACE =
VisualStyles.LINK_SEPARATOR_V_SPACE;
public static final int THUMBNAIL_HEIGHT = 70;
public static final int THUMBNAIL_H_SPACE = THUMBNAIL_HEIGHT + 2 * H_SPACE;
// Determine fonths and their measurements once
private static final Font FONT_TITLE = VisualStyles.LARGE_FONT;
private static final Font FONT_SCORE = VisualStyles.LARGE_BOLD_FONT;
private static final Font FONT_DETAILS = VisualStyles.SMALL_BOLD_FONT;
private static final int H_FONT_TITLE = FONT_TITLE.getHeight();
private static final int H_FONT_SCORE = FONT_SCORE.getHeight();
private static final int H_FONT_DETAILS = FONT_DETAILS.getHeight();
private int height;
private final int preferredWidth;
private Vector titleLines;
private final String detailsText;
private Vector detailsLines;
private final LinkThing link;
private final LinkSelectionListener listener;
private final Hashtable imageCache;
private final boolean showImage;
private final ImageLoader imageLoader = ImageLoader.getInstance();
private static Image separatorImage = Image.createImage(1, 1);
/**
* Interface used to signal link selections.
*/
public interface LinkSelectionListener {
public void linkSelected(LinkThing link);
}
/**
* Load the static resources once and for all.
*/
static {
try {
separatorImage = Image.createImage("/midlets/rlinks/images/separator-curved.png");
}
catch (IOException ex) {
System.err.println("Couldn't not load image: " + ex.getMessage());
}
}
/**
* Create a Linkitem.
*
* @param link Link represented by the Linkitem
* @param preferredWidth Preferred width
* @param showSubreddit Whether the subreddit should be displayed
* @param listener Listener to signal of link selections
* @param imageCache A cache to store images into
*/
public LinkItem(LinkThing link, int preferredWidth, boolean showSubreddit,
LinkSelectionListener listener, Hashtable imageCache, Form form) {
super(form, preferredWidth, null);
this.link = link;
this.preferredWidth = preferredWidth;
this.listener = listener;
this.imageCache = imageCache;
showImage = link.getThumbnail() != null;
updateTitleLines();
// E.g. "funny @ imgur.com", only "imgur.com" if a category is selected
detailsText = (showSubreddit ? link.getSubreddit() + " @ " : "") + link.
getDomain();
updateDetailsLines();
this.height = getPrefContentHeight(preferredWidth);
if (TouchChecker.DIRECT_TOUCH_SUPPORTED) {
LCDUIUtil.setObjectTrait(this, "nokia.ui.s40.item.direct_touch",
new Boolean(true));
}
if (showImage) {
loadImage();
}
}
public LinkThing getLink() {
return this.link;
}
protected int getMinContentWidth() {
return width;
}
protected int getMinContentHeight() {
return height;
}
protected int getPrefContentWidth(int height) {
return preferredWidth;
}
protected int getPrefContentHeight(int width) {
return (int) (V_SPACE_HALF + // Reserve space for a thumbnail or the title text, whichever
// one of the two takes more vertical space.
Math.max(
showImage ? THUMBNAIL_HEIGHT : 0,
titleLines.size() * H_FONT_TITLE + V_SPACE_HALF + detailsLines.size()
* H_FONT_DETAILS + V_SPACE_HALF) + V_SPACE + H_FONT_SCORE
+ V_SPACE_HALF);
}
/**
* Draw the friendly item.
*/
protected void paint(final Graphics g, final int w, final int h) {
int x = H_SPACE;
int y = V_SPACE_HALF;
g.setFont(FONT_TITLE);
g.setColor(VisualStyles.COLOR_FOREGROUND);
for (int i = 0; i < titleLines.size(); i++) {
g.drawString((String) titleLines.elementAt(i), x, y, Graphics.TOP
| Graphics.LEFT);
y += H_FONT_TITLE;
}
// Details text
y += V_SPACE_HALF;
g.setFont(FONT_DETAILS);
for (int i = 0; i < detailsLines.size(); i++) {
g.drawString((String) detailsLines.elementAt(i), x, y, Graphics.TOP
| Graphics.LEFT);
y += H_FONT_DETAILS;
}
// Draw left and right part of the separator, then the score in the middle
final String scoreStr = (link.getScore() > 0 ? "+" : "")
+ link.getScore();
final int scoreHeight = H_FONT_SCORE + SEPARATOR_V_SPACE;
y = height - scoreHeight - V_SPACE_HALF;
g.setColor(VisualStyles.COLOR_FOREGROUND_DIM);
if (separatorImage != null) {
g.drawImage(separatorImage, width / 2, y + scoreHeight / 2,
Graphics.TOP
| Graphics.HCENTER);
}
g.setFont(FONT_SCORE);
g.drawString(scoreStr, width / 2, y - V_SPACE_HALF, Graphics.TOP
| Graphics.HCENTER);
// Draw thumbnail image
if (showImage && link.getImage() != null) {
g.drawImage(link.getImage(), width - H_SPACE, V_SPACE_HALF,
Graphics.TOP | Graphics.RIGHT);
}
}
private void updateTitleLines() {
// Allocate some space for a possible thumbnail
final int titleWidth = width - 4 * H_SPACE
- (showImage ? THUMBNAIL_H_SPACE : 0) - deviceMargin;
titleLines = TextWrapper.wrapTextToWidth(link.getTitle(), titleWidth,
FONT_TITLE);
}
private void updateDetailsLines() {
final int detailsWidth = width - 4 * H_SPACE
- (showImage ? THUMBNAIL_H_SPACE : 0) - deviceMargin;
detailsLines = TextWrapper.wrapTextToWidth(detailsText, detailsWidth,
FONT_DETAILS);
}
/**
* Load the image represented by this Link.
*/
private void loadImage() {
String url = link.getThumbnail();
imageLoader.loadImage(url, Image.createImage(70, 70),
new ImageLoader.Listener() {
public void imageLoaded(final Image image) {
link.setImage(image);
repaint();
}
}, imageCache);
}
public void pointerReleased(int x, int y) {
if (!dragging) {
listener.linkSelected(this.link);
}
super.pointerReleased(x, y);
}
public void refresh() {
repaint();
}
protected boolean traverse(int dir, int viewportWidth, int viewportHeight,
int[] visRect_inout) {
return false;
}
}
|
{
"pile_set_name": "Github"
}
|
package org.lamw.appjcenteropenstreetmapdemo2;
//LAMW: Lazarus Android Module Wizard - version 0.8.4.4 - 30 May - 2019
//RAD Android: Project Wizard, Form Designer and Components Development Model!
//https://github.com/jmpessoa/lazandroidmodulewizard
//http://forum.lazarus.freepascal.org/index.php/topic,21919.270.html
//Android Java Interface for LAZARUS [december/2013 by jmpessoa]
//Developers:
// Simon,Choi / Choi,Won-sik
// [email protected]
// http://blog.naver.com/simonsayz
//
// LoadMan / Jang,Yang-Ho
// [email protected]
// http://blog.naver.com/wkddidgh
//
// Jose Marques Pessoa / [email protected]
//
//Version
//History
// 2013.02.24 ver0.01 Started
// 2013.02.28 ver0.02 added Delphi Style
// 2013.03.01 ver0.03 added sysInfo
// 2013.03.05 ver0.04 added Java Loading Png
// 2013.03.08 ver0.05 Restructuring (Interlation #.02)
// 2013.07.13 ver0.06 added TForm
// 2013.07.22 ver0.07 added Back Event for Close
// 2013.07.26 ver0.08 Class,Method Cache (Single Thread,Class)
// 2013.07.30 ver0.09 added TEditText Keyboard,Focus
// 2013.08.02 ver0.10 added TextView - Enabled
// 2013.08.05 ver0.11 added Form Object
// 2013.08.11 ver0.12 added Canvas
// added Direct Bitmap access
// 2013.08.14 ver0.13 Fixed Memory Leak
// 2013.08.18 ver0.14 added OpenGL ES1 2D (Stencil)
// 2013.08.21 ver0.15 Fixed jImageBtn Memory Leak
// Fixed Socket Buffer
// 2013.08.23 ver0.16 Fixed Memory Leak for Form,Control
// added Form Stack
// 2013.08.24 ver0.17 added Thread
// 2013.08.26 ver0.18 added OpenGL ES2 2D/3D
// added Button Font Color/Height
// 2013.08.31 ver0.19 added Unified OpenGL ES1,2 Canvas
// added OpenGL ES1,2 Simulator for Windows
// 2013.09.01 ver0.20 added GLThread on Canvas
// Fixed OpenGL Crash
// rename example Name
// 12.2013 LAMW Started by jmpessoa
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Vibrator;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.RemoteViews;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.io.*;
import java.lang.Class;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.lang.reflect.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.lang.Object;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
//-------------------------------------------------------------------------
//Constants
//-------------------------------------------------------------------------
class Const {
public static final int TouchDown = 0;
public static final int TouchMove = 1;
public static final int TouchUp = 2;
public static final int Click_Default = 0;
}
//-------------------------------------------------------------------------
//Form
//-------------------------------------------------------------------------
class jForm {
//Java-Pascal Interface
private long PasObj = 0; // Pascal Obj
private Controls controls = null; // Control Class for Event
private RelativeLayout layout = null;
private LayoutParams layparam = null;
private RelativeLayout parent = null; //activity appLayout
private OnClickListener onClickListener; // event
private OnClickListener onViewClickListener; // generic delegate event
private OnItemClickListener onListItemClickListener;
private Boolean enabled = true; //
private Intent intent;
private int mCountTab = 0;
private boolean mRemovedFromParent = false;
// Constructor
public jForm(Controls ctrls, long pasobj) {
PasObj = pasobj;
controls = ctrls;
parent = controls.appLayout;
layout = new RelativeLayout(controls.activity);
layparam = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(layparam);
// Init Event
onClickListener = new OnClickListener() {
public void onClick(View view) {
if (enabled) {
controls.pOnClick(PasObj,Const.Click_Default);
}
};
};
//geric list item click Event - experimental component model!
onListItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
controls.jAppOnListItemClick(parent, v, position, v.getId());
}
};
//Init Event
onViewClickListener = new OnClickListener() {
public void onClick(View view) {
if (enabled) {
controls.jAppOnViewClick(view, view.getId());
}
};
};
layout.setOnClickListener(onClickListener);
}
public RelativeLayout GetLayout() {
return layout;
}
public RelativeLayout GetView() {
return layout;
}
public void SetEnabled ( boolean enabled ) {
for (int i = 0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
child.setEnabled(enabled);
}
}
public void SetLayoutVisibility(boolean _value) {
if (!_value) {
layout.setVisibility(android.view.View.INVISIBLE);
}
else {
layout.setVisibility(android.view.View.VISIBLE);
}
}
public void SetVisible ( boolean visible ) {
if (visible) {
if (layout.getParent() == null) {
controls.appLayout.addView(layout);
layout.setVisibility(android.view.View.VISIBLE);
mRemovedFromParent = false;
}
}
else {
if (layout.getParent() != null) {
layout.setVisibility(android.view.View.INVISIBLE);
controls.appLayout.removeView(layout);
mRemovedFromParent = true;
}
}
}
public void RemoveFromViewParent() { //TODO Pascal
if (!mRemovedFromParent) {
if (layout != null) {
layout.setVisibility(android.view.View.INVISIBLE);
if (parent != null) parent.removeView(layout);
}
mRemovedFromParent = true;
}
}
public void SetViewParent( android.view.ViewGroup _viewgroup) {
if ( (parent != null) && (layout != null) ) { parent.removeView(layout); }
parent = (RelativeLayout) _viewgroup;
if ( (parent != null) && (layout != null) ) {
parent.addView(layout, layparam);
layout.setVisibility(android.view.View.VISIBLE);
}
mRemovedFromParent = false;
}
public void Show(int effect) {
controls.appLayout.addView(layout);
parent = controls.appLayout;
}
public ViewGroup GetParent() {
return controls.appLayout; //parent;
}
public void Close(int effect ) {
controls.pOnClose(PasObj);
}
public void Close2() {
controls.appLayout.removeView(layout);
controls.pOnClose(PasObj);
}
public boolean IsConnected(){ //by TR3E
ConnectivityManager cm = (ConnectivityManager)controls.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null)
return (activeNetwork.isAvailable() && activeNetwork.isConnected());
}
return false;
}
public boolean IsConnectedWifi(){ // by TR3E
ConnectivityManager cm = (ConnectivityManager)controls.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null)
{
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null)
return (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI);
}
return false;
}
public boolean IsConnectedTo(int _connectionType) { // by TR3E
ConnectivityManager cm = (ConnectivityManager)controls.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if( cm != null )
{
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
int result = -1;
if (activeNetwork != null)
if (activeNetwork.isAvailable() && activeNetwork.isConnected());
{
switch (activeNetwork.getType()){
case ConnectivityManager.TYPE_MOBILE: result = 0; break; //0
case ConnectivityManager.TYPE_WIFI: result = 1; break; //1
case ConnectivityManager.TYPE_BLUETOOTH: result = 2; break; //7
case ConnectivityManager.TYPE_ETHERNET: result = 3; break; //9
}
}
return (result == _connectionType);
}
return false;
}
public void ShowMessage(String msg){
Log.i("ShowMessage", msg);
Toast.makeText(controls.activity, msg, Toast.LENGTH_SHORT).show();
}
public void ShowMessage(String _msg, int _gravity, int _timeLength) {
Log.i("ShowMessage", _msg);
Toast toast = Toast.makeText(controls.activity, _msg, _timeLength);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public String GetDateTime() {
SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss", Locale.getDefault() );
return( formatter.format ( new Date () ) );
}
//Free object except Self, Pascal Code Free the class.
public void Free() {
if (parent != null) { controls.appLayout.removeView(layout); }
onClickListener = null;
layout.setOnClickListener(null);
layparam = null;
layout = null;
}
//http://startandroid.ru/en/lessons/complete-list/250-lesson-29-invoking-activity-and-getting-a-result-startactivityforresult-method.html
public String GetStringExtra(Intent data, String extraName) {
String valueStr;
valueStr= "";
if (data != null) {
valueStr = data.getStringExtra(extraName);
}
return valueStr;
}
public int GetIntExtra(Intent data, String extraName, int defaultValue) {
int value;
value = defaultValue;
if (data != null) {
value = data.getIntExtra(extraName, defaultValue);
}
return value;
}
public double GetDoubleExtra(Intent data, String extraName, double defaultValue) {
double value;
value = defaultValue;
if (data != null) {
value = data.getDoubleExtra(extraName, defaultValue);
}
return value;
}
public OnClickListener GetOnViewClickListener () {
return this.onViewClickListener;
}
public OnItemClickListener GetOnListItemClickListener () {
return this.onListItemClickListener;
}
public int getSystemVersion()
{
return controls.systemVersion;
}
public boolean SetWifiEnabled(boolean _status) {
//WifiManager wifiManager = (WifiManager)this.controls.activity.getSystemService(Context.WIFI_SERVICE);
WifiManager wifiManager = (WifiManager)this.controls.activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
return wifiManager.setWifiEnabled(_status);
}
public boolean IsWifiEnabled() {
//WifiManager wifiManager = (WifiManager)this.controls.activity.getSystemService(Context.WIFI_SERVICE);
WifiManager wifiManager = (WifiManager)this.controls.activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled();
}
public boolean IsMobileDataEnabled() {
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) controls.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
final Class<?> cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API
// TODO do whatever error handling you want here
}
return mobileDataEnabled;
}
public String GetEnvironmentDirectoryPath(int _directory) {
File filePath= null;
String absPath=""; //fail!
//Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);break; //only Api 19!
if (_directory != 8) {
switch(_directory) {
case 0: filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); break;
case 1: filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); break;
case 2: filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); break;
case 3: filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); break;
case 4: filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS); break;
case 5: filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); break;
case 6: filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS); break;
case 7: filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES); break;
case 9: absPath = this.controls.activity.getFilesDir().getAbsolutePath(); break; //Result : /data/data/com/MyApp/files
case 10: absPath = this.controls.activity.getFilesDir().getPath();
absPath = absPath.substring(0, absPath.lastIndexOf("/")) + "/databases"; break;
case 11: absPath = this.controls.activity.getFilesDir().getPath();
absPath = absPath.substring(0, absPath.lastIndexOf("/")) + "/shared_prefs"; break;
case 12: absPath = this.controls.activity.getFilesDir().getPath();
absPath = absPath.substring(0, absPath.lastIndexOf("/")) + "/cache"; break;
}
//Make sure the directory exists.
if (_directory < 8) {
filePath.mkdirs();
absPath= filePath.getPath();
}
}else { //== 8
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == true) {
filePath = Environment.getExternalStorageDirectory(); //sdcard!
// Make sure the directory exists.
filePath.mkdirs();
absPath= filePath.getPath();
}
}
return absPath;
}
public String GetInternalAppStoragePath() { //GetAbsoluteDirectoryPath
String PathDat = this.controls.activity.getFilesDir().getAbsolutePath(); //Result : /data/data/com/MyApp/files
return PathDat;
}
private void copyFileUsingFileStreams(File source, File dest)
throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} finally {
input.close();
output.close();
}
}
public boolean CopyFile(String _scrFullFileName, String _destFullFileName) {
File src= new File(_scrFullFileName);
File dest= new File(_destFullFileName);
try {
copyFileUsingFileStreams(src, dest);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
//ref. https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
//result: path to new storage [Internal App Storage]
public String LoadFromAssets(String _filename){
String pathRes="";
InputStream is = null;
FileOutputStream fos = null;
String PathDat = controls.activity.getFilesDir().getAbsolutePath();
try {
File outfile = new File(PathDat, _filename);
fos = new FileOutputStream(outfile); //save to data/data/your_package/files/your_file_name
is = controls.activity.getAssets().open(_filename);
int size = is.available();
byte[] buffer = new byte[size];
for (int c = is.read(buffer); c != -1; c = is.read(buffer)){
fos.write(buffer, 0, c);
}
is.close();
fos.close();
pathRes= PathDat +"/"+ _filename;
}catch (IOException e) {
e.printStackTrace();
}
return pathRes;
}
public boolean IsSdCardMounted() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public void DeleteFile(String _filename) {
this.controls.activity.deleteFile(_filename);
}
public void DeleteFile(String _fullPath, String _filename) {
File file;
if ( _fullPath.equalsIgnoreCase("") ) {
file = new File(Environment.getExternalStorageDirectory()+"/"+ _filename); // root
}
else {
file = new File(_fullPath+"/"+ _filename);
}
file.delete();
}
public void DeleteFile(int _environmentDir, String _filename) {
String baseDir = GetEnvironmentDirectoryPath(_environmentDir);
if (!baseDir.equalsIgnoreCase("")) {
File file = new File(baseDir, _filename);
file.delete();
}
}
public String CreateDir(String _dirName) {
this.controls.activity.getDir(_dirName, 0); //if not exist -->> CREATE!
String absPath = this.controls.activity.getFilesDir().getPath();
absPath = absPath.substring(0, absPath.lastIndexOf("/")) + "/"+_dirName;
return absPath;
}
public String CreateDir(int _environmentDir, String _dirName) {
String baseDir = GetEnvironmentDirectoryPath(_environmentDir);
if (!baseDir.equalsIgnoreCase("")) {
File file = new File(baseDir, _dirName);
file.mkdirs();
return file.getPath();
}else return "";
}
public String CreateDir(String _fullPath, String _dirName) {
File file = new File(_fullPath, _dirName);
file.mkdirs();
return file.getPath();
}
/*
Added in API level 11
Returns whether the primary "external" storage device is emulated. If true,
data stored on this device will be stored on a portion of the internal storage system.
*/
public boolean IsExternalStorageEmulated () {
return Environment.isExternalStorageEmulated();
}
/*
Added in API level 9
Returns whether the primary "external" storage device is removable.
*/
public boolean IsExternalStorageRemovable() {
return Environment.isExternalStorageRemovable();
}
//
public String GetjFormVersionFeatures() {
String listVersionInfo =
"6$5=SetWifiEnabled;" + //[0.6-05]
"6$5=IsWifiEnabled;" +
"6$5=GetEnvironmentDirectoryPath;" +
"6$5=GetInternalAppStoragePath;" +
"6$5=CopyFile;" +
"6$5=LoadFromAssets;" +
"6$5=IsSdCardMounted;" +
"6$5=DeleteFile;" +
"6$5=CreateDir;" +
"6$5=IsExternalStorageEmulated;" +
"6$5=IsExternalStorageRemovable";
return listVersionInfo;
}
/*
*Given that you can access R.java just fine normally in code.
*As long as you are retrieving data from your application's R.java - Use reflection!
*/
public int GetStringResourceId(String _resName) {
try {
Class<?> res = R.string.class;
Field field = res.getField(_resName);
int strId = field.getInt(null);
return strId;
}
catch (Exception e) {
Log.e("jForm", "Failure to Get String Resource", e);
return 0;
}
}
public String GetStringResourceById(int _resID) {
return (String)( this.controls.activity.getResources().getText(_resID));
}
public int GetDrawableResourceId(String _resName) {
try {
Class<?> res = R.drawable.class;
Field field = res.getField(_resName); //"drawableName"
int drawableId = field.getInt(null);
return drawableId;
}
catch (Exception e) {
Log.e("jForm", "Failure to get drawable id.", e);
return 0;
}
}
public Drawable GetDrawableResourceById(int _resID) {
if( _resID == 0 ) return null; // by tr3e
Drawable res = null;
if (Build.VERSION.SDK_INT < 21 ) { //for old device < 21
res = this.controls.activity.getResources().getDrawable(_resID);
}
//[ifdef_api21up]
if(Build.VERSION.SDK_INT >= 21) {
res = this.controls.activity.getResources().getDrawable(_resID, null);
}//[endif_api21up]
return res;
}
public void SetBackgroundImage(String _imageIdentifier) {
Drawable d = GetDrawableResourceById(GetDrawableResourceId(_imageIdentifier));
if( d == null ) return; // by tr3e
//Bitmap bmp = ((BitmapDrawable)d).getBitmap();
ImageView image = new ImageView(controls.activity);
LayoutParams param = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
image.setLayoutParams(param);
image.setImageResource(android.R.color.transparent);
image.setImageDrawable(d);
//image.invalidate();
layout.addView(image);
}
//by thierrydijoux
public String GetQuantityStringByName(String _resName, int _quantity) {
int id = this.controls.activity.getResources().getIdentifier(_resName, "plurals", this.controls.activity.getPackageName());
String value = id == 0 ? "" : (String) this.controls.activity.getResources().getQuantityString(id, _quantity, _quantity);
return value;
}
//by thierrydijoux
public String GetStringResourceByName(String _resName) {
int id = this.controls.activity.getResources().getIdentifier(_resName, "string", this.controls.activity.getPackageName());
String value = id == 0 ? "" : (String) this.controls.activity.getResources().getText(id);
return value;
}
public ActionBar GetActionBar() {
if (! jCommons.IsAppCompatProject() ) {
return (controls.activity).getActionBar();
} else return null;
}
/*
* To disableAction-bar Icon and Title, you must do two things:
setDisplayShowHomeEnabled(false); // hides action bar icon
setDisplayShowTitleEnabled(false); // hides action bar title
*/
public void HideActionBar() {
jCommons.ActionBarHide(controls);
}
public void ShowActionBar() {
jCommons.ActionBarShow(controls);
}
//Hide the title label
public void ShowTitleActionBar(boolean _value) {
jCommons.ActionBarShowTitle(controls, _value);
}
//Hide the logo = false
public void ShowLogoActionBar(boolean _value) {
jCommons.ActionBarShowLogo(controls, _value);
}
//set a title and subtitle to the Action bar as shown in the code snippet.
public void SetTitleActionBar(String _title) {
jCommons.SetActionBarTitle(controls, _title);
}
//set a title and subtitle to the Action bar as shown in the code snippet.
public void SetSubTitleActionBar(String _subtitle) {
jCommons.SetActionBarSubTitle(controls, _subtitle);
}
//forward [<] activity! // If your minSdkVersion is 11 or higher!
/*.*/public void SetDisplayHomeAsUpEnabledActionBar(boolean _value) {
jCommons.ActionBarDisplayHomeAsUpEnabled(controls, _value);
}
public void SetIconActionBar(String _iconIdentifier) {
//[ifdef_api14up]
Drawable d = GetDrawableResourceById(GetDrawableResourceId(_iconIdentifier));
if( d != null ) // by tr3e
jCommons.ActionBarSetIcon(controls, d);
//[endif_api14up]
}
public void SetTabNavigationModeActionBar(){
jCommons.ActionBarSetTabNavigationMode(controls);
}
//This method remove all tabs from the action bar and deselect the current tab
public void RemoveAllTabsActionBar() {
jCommons.ActionBarRemoveAllTabs(controls);
}
//Calculate ActionBar height
//ref http://stackoverflow.com/questions/12301510/how-to-get-the-actionbar-height
public int GetActionBarHeight() {
return jCommons.ActionGetBarBarHeight(controls);
}
public boolean ActionBarIsShowing() {
return jCommons.ActionBarIsShowing(controls);
}
public boolean HasActionBar() {
return jCommons.HasActionBar(controls);
}
public boolean IsAppCompatProject () {
return jCommons.IsAppCompatProject();
}
public boolean IsPackageInstalled(String _packagename) {
PackageManager pm = controls.activity.getPackageManager();
try {
pm.getPackageInfo(_packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
//android.view.View
public void ShowCustomMessage(View _layout, int _gravity) {
//controls.pOnShowCustomMessage(PasObj);
Toast toast = new Toast(controls.activity);
toast.setGravity(_gravity, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
RelativeLayout par = (RelativeLayout)_layout.getParent();
if (par != null) {
par.removeView(_layout);
}
_layout.setVisibility(View.VISIBLE);
toast.setView(_layout);
toast.show();
}
private class MyCountDownTimer extends CountDownTimer {
Toast toast;
public MyCountDownTimer(long startTime, long interval, Toast toas) {
super(startTime, interval);
toast = toas;
}
@Override
public void onFinish() {
//text.setText("Time's up!");
toast.cancel();
}
@Override
public void onTick(long millisUntilFinished) {
//text.setText("" + millisUntilFinished / 1000);
toast.show();
}
}
public void ShowCustomMessage(View _layout, int _gravity, int _lenghTimeSecond) {
Toast toast = new Toast(controls.activity);
toast.setGravity(_gravity, 0, 0);
//toast.setDuration(Toast.LENGTH_LONG);
RelativeLayout par = (RelativeLayout)_layout.getParent();
if (par != null) {
par.removeView(_layout);
}
_layout.setVisibility(View.VISIBLE);//0
toast.setView(_layout);
//it will show the toast for 20 seconds:
//(20000 milliseconds/1st argument) with interval of 1 second/2nd argument //--> (20 000, 1000)
MyCountDownTimer countDownTimer = new MyCountDownTimer(_lenghTimeSecond*1000, 1000, toast);
countDownTimer.start();
}
public void SetScreenOrientation(int _orientation) {
//Log.i("Screen","Orientation "+ _orientation);
switch(_orientation) {
case 1: controls.activity.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break;
case 2: controls.activity.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break;
default:controls.activity.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_SENSOR); break;
}
}
public int GetScreenOrientation() {
int orientation = controls.activity.getResources().getConfiguration().orientation;
int r = 0;
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
r= 1;//setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_LANDSCAPE:
r = 2; //setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
return r;
}
public String GetScreenDensity() {
String r= "";
DisplayMetrics metrics = new DisplayMetrics();
controls.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int density = metrics.densityDpi;
//[ifdef_api16up]
if (density==DisplayMetrics.DENSITY_XXHIGH) {
r= "XXHIGH:" + String.valueOf(density);
}
else
//[endif_api16up]
if (density==DisplayMetrics.DENSITY_XHIGH) {
r= "XHIGH:" + String.valueOf(density);
}
else if (density==DisplayMetrics.DENSITY_HIGH) {
r= "HIGH:" + String.valueOf(density);
}
else if (density==DisplayMetrics.DENSITY_MEDIUM) {
r= "MEDIUM:" + String.valueOf(density);
}
else if (density==DisplayMetrics.DENSITY_LOW) {
r= "LOW:" + String.valueOf(density);
}
return r;
}
public String GetScreenSize() {
String r= "";
if((controls.activity.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
r = "XLARGE";
}else if((controls.activity.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
r = "LARGE";
}else if ((controls.activity.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
r = "NORMAL";
}else if ((controls.activity.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
r = "SMALL";
}
return r;
}
public void LogDebug(String _tag, String _msg) {
Log.d(_tag, _msg); //debug
}
public void Vibrate(int _milliseconds) {
Vibrator vib = (Vibrator) controls.activity.getSystemService(Context.VIBRATOR_SERVICE);
if (vib.hasVibrator()) {
vib.vibrate(_milliseconds);
}
}
public void Vibrate(long[] _millisecondsPattern) {
Vibrator vib = (Vibrator) controls.activity.getSystemService(Context.VIBRATOR_SERVICE);
if (vib.hasVibrator()) {
vib.vibrate(_millisecondsPattern, -1);
}
}
//http://stackoverflow.com/questions/2661536/how-to-programatically-take-a-screenshot-on-android
public void TakeScreenshot(String _savePath, String _saveFileNameJPG) {
String myPath = _savePath + "/" + _saveFileNameJPG;
Bitmap bitmap;
View v1 = controls.activity.getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
File imageFile = new File(myPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String GetTitleActionBar() {
ActionBar actionBar = this.controls.activity.getActionBar();
return (String)actionBar.getTitle();
}
public String GetSubTitleActionBar() {
ActionBar actionBar = this.controls.activity.getActionBar();
return (String)actionBar.getSubtitle();
}
//https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
public String CopyFromAssetsToInternalAppStorage(String _filename) {
InputStream is = null;
FileOutputStream fos = null;
String PathDat = controls.activity.getFilesDir().getAbsolutePath();
try {
File outfile = new File(PathDat+"/"+_filename);
// if file doesnt exists, then create it
if (!outfile.exists()) {
outfile.createNewFile();
}
fos = new FileOutputStream(outfile); //save to data/data/your_package/files/your_file_name
is = controls.activity.getAssets().open(_filename);
int size = is.available();
byte[] buffer = new byte[size];
for (int c = is.read(buffer); c != -1; c = is.read(buffer)){
fos.write(buffer, 0, c);
}
is.close();
fos.close();
}catch (IOException e) {
// Log.i("ShareFromAssets","fail!!");
e.printStackTrace();
}
return PathDat+"/"+_filename;
}
public String GetPathFromAssetsFile(String _assetsFileName) {
return LoadFromAssets(_assetsFileName);
}
public Bitmap GetImageFromAssetsFile(String _assetsImageFileName) {
String path = LoadFromAssets(_assetsImageFileName);
BitmapFactory.Options bo = new BitmapFactory.Options();
bo.inScaled = false;
return BitmapFactory.decodeFile(path, bo);
}
public void CopyFromInternalAppStorageToEnvironmentDir(String _filename, String _environmentDir) {
String srcPath = controls.activity.getFilesDir().getAbsolutePath()+"/"+ _filename; //Result : /data/data/com/MyApp/files
String destPath = _environmentDir + "/" + _filename;
CopyFile(srcPath, destPath);
}
public void CopyFromAssetsToEnvironmentDir(String _filename, String _environmentDir) {
CopyFromAssetsToInternalAppStorage(_filename);
CopyFromInternalAppStorageToEnvironmentDir(_filename,_environmentDir);
}
public void ToggleSoftInput() {
InputMethodManager imm =(InputMethodManager) controls.activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
public void HideSoftInput() {
InputMethodManager imm =(InputMethodManager) controls.activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.RESULT_HIDDEN, 0);
}
public void HideSoftInput(View _view) {
InputMethodManager imm = (InputMethodManager)controls.activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(_view.getWindowToken(), 0);
}
public void ShowSoftInput() {
InputMethodManager imm =(InputMethodManager) controls.activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.RESULT_SHOWN, 0);
}
//thanks to Mladen
public String GetDeviceModel() {
return android.os.Build.MODEL;
}
public String GetDeviceManufacturer() {
return android.os.Build.MANUFACTURER;
}
public void SetKeepScreenOn(boolean _value) {
if (_value)
controls.activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
controls.activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
public void SetTurnScreenOn(boolean _value) {
if (_value)
controls.activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
else
controls.activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
public void SetAllowLockWhileScreenOn(boolean _value) {
if (_value)
controls.activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
else
controls.activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
}
public void SetShowWhenLocked(boolean _value) {
if (_value)
controls.activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
else
controls.activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}
public Uri ParseUri(String _uriAsString) {
return Uri.parse(_uriAsString);
}
public String UriToString(Uri _uri) {
return _uri.toString();
}
// ref. http://www.android-examples.com/get-display-ip-address-of-android-phone-device-programmatically/
public int GetNetworkStatus() {
boolean WIFI = false;
boolean MOBILE = false;
int r = 0; //NOT_CONNECTED
ConnectivityManager CM = (ConnectivityManager) controls.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfo = CM.getAllNetworkInfo();
for (NetworkInfo netInfo : networkInfo) {
if (netInfo.getTypeName().equalsIgnoreCase("WIFI"))
if (netInfo.isConnected()) WIFI = true;
if (netInfo.getTypeName().equalsIgnoreCase("MOBILE"))
if (netInfo.isConnected())
MOBILE = true;
}
if(WIFI == true) {
r = 1; //WIFI_CONNECTED
}
if(MOBILE == true) {
r = 2; //MOBILE_DATA_CONNECTED
}
return r;
}
public String GetDeviceDataMobileIPAddress(){
String r = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface networkinterface = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = networkinterface.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
boolean isIPv4 = inetAddress.getHostAddress().indexOf(':') < 0;
if (isIPv4) return r = inetAddress.getHostAddress();
if (!isIPv4) {
int delim = inetAddress.getHostAddress().indexOf('%'); // drop ip6 zone suffix
r = delim < 0 ? inetAddress.getHostAddress().toUpperCase() : inetAddress.getHostAddress().substring(0, delim).toUpperCase();
}
}
}
}
}catch (Exception ex) {
Log.e("Current IP", ex.toString());
}
return r;
}
//ref. http://www.devlper.com/2010/07/getting-ip-address-of-the-device-in-android/
public String GetDeviceWifiIPAddress() {
//WifiManager mWifi = (WifiManager) controls.activity.getSystemService(Context.WIFI_SERVICE);
WifiManager mWifi = (WifiManager)this.controls.activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//String ip = Formatter.formatIpAddress(
int ipAddress = mWifi.getConnectionInfo().getIpAddress();
String sIP =String.format("%d.%d.%d.%d",
(ipAddress & 0xff),
(ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff));
return sIP;
}
/**
* Calculate the broadcast IP we need to send the packet along.
* ref. http://www.ece.ncsu.edu/wireless/MadeInWALAN/AndroidTutorial/
*/
public String GetWifiBroadcastIPAddress() throws IOException {
String r = null;
//WifiManager mWifi = (WifiManager) controls.activity.getSystemService(Context.WIFI_SERVICE);
WifiManager mWifi = (WifiManager)this.controls.activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// DhcpInfo is a simple object for retrieving the results of a DHCP request
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
// Returns the InetAddress corresponding to the array of bytes.
// The high order byte is quads[0].
r = InetAddress.getByAddress(quads).getHostAddress();
if (r == null) r = "";
return r;
}
//https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
public String LoadFromAssetsTextContent(String _filename) {
String str;
// load text
try {
//Log.i("loadFromAssets", "name: "+_filename);
// get input stream for text
InputStream is = controls.activity.getAssets().open(_filename);
// check size
int size = is.available();
// create buffer for IO
byte[] buffer = new byte[size];
// get data to buffer
is.read(buffer);
// close stream
is.close();
// set result to TextView
str = new String(buffer);
//Log.i("loadFromAssets", ":: "+ str);
return str.toString();
}
catch (IOException ex) {
//Log.i("loadFromAssets", "error!");
return "";
}
}
//Fatih: Path = '' = Asset Root Folder
//Path Example: gunlukler/2015/02/28/001
public String[] GetAssetContentList(String _path) throws IOException {
ArrayList<String> Folders = new ArrayList<String>();
Resources r = this.controls.activity.getResources();
AssetManager am = r.getAssets();
String fileList[] = am.list(_path);
if (fileList != null)
{
for (int i = 0; i < fileList.length; i++)
{
Folders.add(fileList[i]);
}
}
String sFolders[] = Folders.toArray(new String[Folders.size()]);
return sFolders;
}
//Fatih: gets system storage driver list
public String[] GetDriverList() {
ArrayList<String> Drivers = new ArrayList<String>();
String sDriver;
sDriver = System.getenv("EXTERNAL_STORAGE");
if(sDriver != null)
{
File fDriver = new File(sDriver);
if (fDriver.exists() && fDriver.canWrite()) {
Drivers.add(fDriver.getAbsolutePath());
}
}
sDriver = System.getenv("SECONDARY_STORAGE");
if(sDriver != null)
{
File fDriver = new File(sDriver);
if (fDriver.exists() && fDriver.canWrite()) {
Drivers.add(fDriver.getAbsolutePath());
}
}
String sDrivers[] = Drivers.toArray(new String[Drivers.size()]);
return sDrivers;
}
//Fatih: get folders list
//Path Example: /storage/emulated/legacy/
public String[] GetFolderList(String _envPath) {
ArrayList<String> Folders = new ArrayList<String>();
File f = new File(_envPath);
File[] files = f.listFiles();
for (File fFile : files) {
if (fFile.isDirectory()) {
Folders.add(fFile.getName());
}
}
String sFolders[] = Folders.toArray(new String[Folders.size()]);
return sFolders;
}
//Fatih: get files list
//Path Example: /storage/emulated/legacy/
public String[] GetFileList(String _envPath) {
ArrayList<String> Folders = new ArrayList<String>();
File f = new File(_envPath);
File[] files = f.listFiles();
for (File fFile : files) {
if (fFile.isFile()) {
Folders.add(fFile.getName());
}
}
String sFolders[] = Folders.toArray(new String[Folders.size()]);
return sFolders;
}
public boolean FileExists(String _fullFileName) {
return new File(_fullFileName).isFile();
}
public boolean DirectoryExists(String _fullDirectoryName) {
return new File(_fullDirectoryName).isDirectory();
}
//http://blog.scriptico.com/category/dev/java/android/
public void Minimize() {
Intent main = new Intent(Intent.ACTION_MAIN);
main.addCategory(Intent.CATEGORY_HOME);
main.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
controls.activity.startActivity(main);
}
public void Restart(int _delay) {
PendingIntent intent = PendingIntent.getActivity(controls.activity.getBaseContext(), 0,
new Intent( controls.activity.getIntent() ),
controls.activity.getIntent().getFlags());
AlarmManager manager = (AlarmManager) controls.activity.getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC, System.currentTimeMillis() + _delay, intent);
System.exit(2);
}
public String UriEncode(String _message) {
return Uri.encode(_message);
}
//http://www.viralandroid.com/2015/12/how-to-use-font-awesome-icon-in-android-application.html
//http://fontawesome.io/cheatsheet/
public String ParseHtmlFontAwesome(String _htmlString) {
String iconHeart = _htmlString; //"";
String valHexStr = iconHeart.replace("&#x", "").replace(";", "");
long valLong = Long.parseLong(valHexStr,16);
//button.setText(getString((char)valLong+"");
return (char)valLong+"" ;
}
//https://developer.android.com/reference/android/provider/Settings.System
public int GetSettingsSystemInt(String _strKey) {
try {
return android.provider.Settings.System.getInt(controls.activity.getContentResolver(), _strKey);
} catch(android.provider.Settings.SettingNotFoundException e) {
return -1;
}
}
//https://developer.android.com/reference/android/provider/Settings.System
public String GetSettingsSystemString(String _strKey) {
String r = android.provider.Settings.System.getString(controls.activity.getContentResolver(), _strKey);
if (r == null) r = "";
return r;
}
public float GetSettingsSystemFloat(String _strKey) {
try {
return android.provider.Settings.System.getFloat(controls.activity.getContentResolver(), _strKey);
} catch(android.provider.Settings.SettingNotFoundException e) {
return -1;
}
}
public long GetSettingsSystemLong(String _strKey) {
try {
return android.provider.Settings.System.getLong(controls.activity.getContentResolver(), _strKey);
} catch(android.provider.Settings.SettingNotFoundException e) {
return -1;
}
}
public boolean PutSettingsSystemInt (String _strKey, int _value) {
return android.provider.Settings.System.putInt(controls.activity.getContentResolver(), _strKey, _value);
}
public boolean PutSettingsSystemLong (String _strKey, long _value) {
return android.provider.Settings.System.putLong(controls.activity.getContentResolver(), _strKey, _value);
}
public boolean PutSettingsSystemFloat(String _strKey, float _value) {
return android.provider.Settings.System.putFloat(controls.activity.getContentResolver(), _strKey, _value);
}
public boolean PutSettingsSystemString(String _strKey, String _strValue) {
return android.provider.Settings.System.putString(controls.activity.getContentResolver(), _strKey, _strValue);
}
public boolean IsRuntimePermissionNeed() {
return Build.VERSION.SDK_INT >= 23; //Build.VERSION_CODES.M
}
public boolean IsRuntimePermissionGranted(String _androidPermission) { //"android.permission.CAMERA"
return jCommons.IsRuntimePermissionGranted(controls, _androidPermission);
}
public void RequestRuntimePermission(String _androidPermission, int _requestCode) { //"android.permission.CAMERA"
jCommons.RequestRuntimePermission(controls, _androidPermission, _requestCode);
}
public void RequestRuntimePermission(String[] _androidPermissions, int _requestCode) { //"android.permission.CAMERA"
jCommons.RequestRuntimePermission(controls, _androidPermissions, _requestCode);
}
//by TR3E
public int getScreenWidth( ){
return this.controls.activity.getResources().getDisplayMetrics().widthPixels;
}
//by TR3E
public int getScreenHeight( ){
return this.controls.activity.getResources().getDisplayMetrics().heightPixels;
}
//by TR3E
public String getSystemVersionString(){
return android.os.Build.VERSION.RELEASE;
}
public ByteBuffer GetJByteBuffer(int _width, int _height) {
ByteBuffer graphicBuffer = ByteBuffer.allocateDirect(_width*_height*4);
return graphicBuffer;
}
public ByteBuffer GetByteBufferFromImage(Bitmap _bitmap) {
if (_bitmap == null) return null;
int w = _bitmap.getWidth();
int h =_bitmap.getHeight();
ByteBuffer graphicBuffer = ByteBuffer.allocateDirect(w*h*4);
_bitmap.copyPixelsToBuffer(graphicBuffer);
graphicBuffer.rewind(); //reset position
return graphicBuffer;
}
}
//**class entrypoint**//please, do not remove/change this line!
//Main Java/Pascal Interface Class
public class Controls {
//
public Activity activity; // Activity
public RelativeLayout appLayout; // Base Layout
public int screenStyle=0; // Screen Style [Dev:0 , Portrait: 1, Landscape : 2]
public int systemVersion;
//Jave -> Pascal Function ( Pascal Side = Event )
public native void pAppOnCreate(Context context, RelativeLayout layout, Intent intent);
public native int pAppOnScreenStyle();
public native void pAppOnNewIntent(Intent intent);
public native void pAppOnDestroy();
public native void pAppOnPause();
public native void pAppOnRestart();
public native void pAppOnResume();
public native void pAppOnStart();
public native void pAppOnStop();
public native void pAppOnBackPressed();
public native int pAppOnRotate(int rotate);
public native void pAppOnConfigurationChanged();
public native void pAppOnActivityResult(int requestCode, int resultCode, Intent data);
public native void pAppOnCreateOptionsMenu(Menu menu);
public native void pAppOnClickOptionMenuItem(MenuItem menuItem, int itemID, String itemCaption, boolean checked);
public native boolean pAppOnPrepareOptionsMenu(Menu menu, int menuSize);
public native boolean pAppOnPrepareOptionsMenuItem(Menu menu, MenuItem menuItem, int itemIndex);
public native void pAppOnCreateContextMenu(ContextMenu menu);
public native void pAppOnClickContextMenuItem(MenuItem menuItem, int itemID, String itemCaption, boolean checked);
public native void pOnDraw(long pasobj);
public native void pOnTouch(long pasobj, int act, int cnt, float x1, float y1, float x2, float y2);
public native void pOnClickGeneric(long pasobj, int value);
public native boolean pAppOnSpecialKeyDown(char keyChar, int keyCode, String keyCodeString);
public native void pOnDown(long pasobj, int value);
public native void pOnClick(long pasobj, int value);
public native void pOnLongClick(long pasobj, int value);
public native void pOnDoubleClick(long pasobj, int value);
public native void pOnChange(long pasobj, String txt, int count);
public native void pOnChanged(long pasobj, String txt, int count);
public native void pOnEnter(long pasobj);
public native void pOnBackPressed(long pasobj);
public native void pOnClose(long pasobj);
public native void pAppOnViewClick(View view, int id);
public native void pAppOnListItemClick(AdapterView adapter, View view, int position, int id);
public native void pOnFlingGestureDetected(long pasobj, int direction);
public native void pOnPinchZoomGestureDetected(long pasobj, float scaleFactor, int state);
public native void pOnLostFocus(long pasobj, String text);
public native void pOnBeforeDispatchDraw(long pasobj, Canvas canvas, int tag);
public native void pOnAfterDispatchDraw(long pasobj, Canvas canvas, int tag);
public native void pOnLayouting(long pasobj, boolean changed);
public native void pAppOnRequestPermissionResult(int requestCode, String permission, int grantResult);
// -------------------------------------------------------------------------------------------
//Load Pascal Library - Please, do not edit the static content commented in the template file
// -------------------------------------------------------------------------------------------
static {
try{System.loadLibrary("controls");} catch (UnsatisfiedLinkError e) {Log.e("JNI_Loading_libcontrols", "exception", e);}
}
// -------------------------------------------------------------------------
// Activity Event
// -------------------------------------------------------------------------
public int jAppOnScreenStyle() { return(pAppOnScreenStyle()); }
public void jAppOnCreate(Context context,RelativeLayout layout, Intent intent) //android.os.Bundle;
{ pAppOnCreate(context,layout,intent); }
public void jAppOnNewIntent(Intent intent) { pAppOnNewIntent(intent); }
public void jAppOnDestroy() { pAppOnDestroy(); }
public void jAppOnPause() { pAppOnPause(); }
public void jAppOnRestart() { pAppOnRestart(); }
public void jAppOnResume() { pAppOnResume(); }
public void jAppOnStart() { pAppOnStart(); }
public void jAppOnStop() { pAppOnStop(); }
public void jAppOnBackPressed() { pAppOnBackPressed(); }
public int jAppOnRotate(int rotate) { return(pAppOnRotate(rotate)); }
//rotate=1 --> device on vertical/default position ; 2 --> device on horizontal position
public void jAppOnConfigurationChanged() { pAppOnConfigurationChanged(); }
public void jAppOnActivityResult(int requestCode, int resultCode, Intent data)
{ pAppOnActivityResult(requestCode,resultCode,data); }
public void jAppOnCreateOptionsMenu(Menu m) {pAppOnCreateOptionsMenu(m);}
public void jAppOnClickOptionMenuItem(MenuItem item,int itemID, String itemCaption, boolean checked){pAppOnClickOptionMenuItem(item,itemID,itemCaption,checked);}
public boolean jAppOnPrepareOptionsMenu(Menu m, int size) {
boolean r = pAppOnPrepareOptionsMenu(m, size);
return r;
}
public boolean jAppOnPrepareOptionsItem(Menu m, MenuItem item, int index) {
boolean r = pAppOnPrepareOptionsMenuItem(m, item, index);
return r;
}
public void jAppOnCreateContextMenu(ContextMenu m) {pAppOnCreateContextMenu(m);}
public void jAppOnClickContextMenuItem(MenuItem item,int itemID, String itemCaption, boolean checked) {pAppOnClickContextMenuItem(item,itemID,itemCaption,checked);}
public void jAppOnViewClick(View view, int id){ pAppOnViewClick(view,id);}
public void jAppOnListItemClick(AdapterView<?> adapter, View view, int position, int id){ pAppOnListItemClick(adapter, view,position,id);}
//public void jAppOnHomePressed() { pAppOnHomePressed(); }
public boolean jAppOnKeyDown(char keyChar , int keyCode, String keyCodeString) {return pAppOnSpecialKeyDown(keyChar, keyCode, keyCodeString);};
public void jAppOnRequestPermissionResult(int requestCode, String permission, int grantResult) {
pAppOnRequestPermissionResult(requestCode, permission ,grantResult);
}
//// -------------------------------------------------------------------------
// System, Class
// -------------------------------------------------------------------------
public void systemGC() {
System.gc();
}
public void ShowAlert(String _title, String _message, String _btnText) {
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setMessage (_message)
.setCancelable (false)
.setNeutralButton(_btnText, null);
dialog = builder.create();
dialog.setTitle(_title);
dialog.show();
}
public void systemSetOrientation(int orientation) {
this.activity.setRequestedOrientation(orientation);
}
public int getAPILevel() {
return android.os.Build.VERSION.SDK_INT;
}
//by jmpessoa
public int systemGetOrientation() {
return (this.activity.getResources().getConfiguration().orientation);
}
public void classSetNull (Class<?> object) {
object = null;
}
public void classChkNull (Class<?> object) {
if (object == null) { Log.i("JAVA","checkNull-Null"); };
if (object != null) { Log.i("JAVA","checkNull-Not Null"); };
}
public Context GetContext() {
return this.activity;
}
//by TR3E Software
public int getContextTop(){
ViewGroup view = ((ViewGroup) this.activity.findViewById(android.R.id.content));
if( view != null)
return view.getTop();
else
return 0;
}
//by TR3E Software
public int getStatusBarHeight() {
int resourceId = this.activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
if ( resourceId > 0 )
return this.activity.getResources().getDimensionPixelSize(resourceId);
else
return 0;
}
//by thierrydijoux
public String getQuantityStringByName(String _resName, int _quantity) {
int id = this.activity.getResources().getIdentifier(_resName, "plurals", this.activity.getPackageName());
String value = id == 0 ? "" : (String) this.activity.getResources().getQuantityString(id, _quantity, _quantity);
return value;
}
//by thierrydijoux
public String getStringResourceByName(String _resName) {
int id = this.activity.getResources().getIdentifier(_resName, "string", this.activity.getPackageName());
String value = id == 0 ? "" : (String) this.activity.getResources().getText(id);
return value;
}
// -------------------------------------------------------------------------
// App Related
// -------------------------------------------------------------------------
//
public void appFinish() {
activity.finish();
System.exit(0); //<< ------- fix by jmpessoa
}
public void appRecreate() {
activity.recreate();
}
public void appKillProcess() {
this.activity.finish();
}
// -------------------------------------------------------------------------
// Asset Related
// -------------------------------------------------------------------------
// src : codedata.txt
// tgt : /data/data/com.kredix.control/data/codedata.txt
public boolean assetSaveToFile(String src, String tgt) {
InputStream is = null;
FileOutputStream fos = null;
String path = '/' + tgt.substring(1,tgt.lastIndexOf("/"));
File outDir = new File(path);
outDir.mkdirs();
try {
is = this.activity.getAssets().open(src);
int size = is.available();
byte[] buffer = new byte[size];
File outfile = new File(tgt);
fos = new FileOutputStream(outfile);
for (int c = is.read(buffer); c != -1; c = is.read(buffer)){
fos.write(buffer, 0, c);
}
is.close();
fos.close();
return(true); }
catch (IOException e) {
e.printStackTrace();
return(false); }
}
// -------------------------------------------------------------------------
// View Related - Generic! --> AndroidWidget.pas
// -------------------------------------------------------------------------
public void view_SetVisible(View view, int state) {
view.setVisibility(state);
}
public void view_SetBackGroundColor(View view, int color) {
view.setBackgroundColor(color);
}
public void view_Invalidate(View view) {
view.invalidate();
}
// -------------------------------------------------------------------------
// Form Related
// -------------------------------------------------------------------------
//
public java.lang.Object jForm_Create(long pasobj ) {
return (java.lang.Object)( new jForm(this,pasobj));
}
// -------------------------------------------------------------------------
// System Info
// -------------------------------------------------------------------------
// Result : Width(16bit) : Height (16bit)
public int getScreenWH(android.content.Context context) {
DisplayMetrics metrics = new DisplayMetrics();
int h = context.getResources().getDisplayMetrics().heightPixels;
int w = context.getResources().getDisplayMetrics().widthPixels;
// proposed by renabor
/*
float density = context.getResources().getDisplayMetrics().density;
int dpHeight = Math.round ( h / density );
int dpWidth = Math.round ( w / density );
return ( dpWidth << 16 | dpHeight ); // dp screen size
*/
return ( (w << 16)| h );
}
// LORDMAN - 2013-07-28
public int getStrLength(String Txt) { //fix by jmpessoa
int len = 0;
if(Txt != null) {
len = Txt.length();
}
return ( len );
}
/*LORDMAN - 2013-07-30
public String getStrDateTime() {
SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss", Locale.KOREA );
return( formatter.format ( new Date () ) );
}
*/
//----------------------------------------------
//Controls Version Info
//-------------------------------------------
//GetControlsVersionFeatures ... //Controls.java version-revision info! [0.6-04]
public String getStrDateTime() { //hacked by jmpessoa!! sorry, was for a good cause! please, use the jForm_GetDateTime!!
String listVersionInfo =
"7$0=GetControlsVersionInfo;" + //added ... etc..
"7$0=getLocale;"; //added ... etc..
return listVersionInfo;
}
//Fatih: Path = '' = Asset Root Folder
//Path Example: gunlukler/2015/02/28/001
public String[] getAssetContentList(String Path) throws IOException {
ArrayList<String> Folders = new ArrayList<String>();
Resources r = this.activity.getResources();
AssetManager am = r.getAssets();
String fileList[] = am.list(Path);
if (fileList != null)
{
for (int i = 0; i < fileList.length; i++)
{
Folders.add(fileList[i]);
}
}
String sFolders[] = Folders.toArray(new String[Folders.size()]);
return sFolders;
}
//Fatih: gets system storage driver list
public String[] getDriverList() {
ArrayList<String> Drivers = new ArrayList<String>();
String sDriver;
sDriver = System.getenv("EXTERNAL_STORAGE");
if(sDriver != null)
{
File fDriver = new File(sDriver);
if (fDriver.exists() && fDriver.canWrite()) {
Drivers.add(fDriver.getAbsolutePath());
}
}
sDriver = System.getenv("SECONDARY_STORAGE");
if(sDriver != null)
{
File fDriver = new File(sDriver);
if (fDriver.exists() && fDriver.canWrite()) {
Drivers.add(fDriver.getAbsolutePath());
}
}
String sDrivers[] = Drivers.toArray(new String[Drivers.size()]);
return sDrivers;
}
//Fatih: get folders list
//Path Example: /storage/emulated/legacy/
public String[] getFolderList(String Path) {
ArrayList<String> Folders = new ArrayList<String>();
File f = new File(Path);
File[] files = f.listFiles();
for (File fFile : files) {
if (fFile.isDirectory()) {
Folders.add(fFile.getName());
}
}
String sFolders[] = Folders.toArray(new String[Folders.size()]);
return sFolders;
}
//Fatih: get files list
//Path Example: /storage/emulated/legacy/
public String[] getFileList(String Path) {
ArrayList<String> Folders = new ArrayList<String>();
File f = new File(Path);
File[] files = f.listFiles();
for (File fFile : files) {
if (fFile.isFile()) {
Folders.add(fFile.getName());
}
}
String sFolders[] = Folders.toArray(new String[Folders.size()]);
return sFolders;
}
//by jmpessoa: Class controls version info
public String GetControlsVersionInfo() {
return "7$0"; //version$revision [0.6$5]
}
public long getTick() {
return ( System.currentTimeMillis() );
}
// -------------------------------------------------------------------------
// Android path
// -------------------------------------------------------------------------
// Result : /data/app/com.kredix-1.apk
public String getPathApp (android.content.Context context,String pkgName) {
String PathApp = "";
try {
PathApp = context.getPackageManager().getApplicationInfo( pkgName, 0 ).sourceDir;
}
catch ( NameNotFoundException e ) {}
return ( PathApp );
}
// Result : /data/data/com/kredix/files
public String getPathDat (android.content.Context context) {
//String version = Build.VERSION.RELEASE;
String PathDat = context.getFilesDir().getAbsolutePath();
return ( PathDat );
}
// Result : /storage/emulated/0
public String getPathExt() {
File FileExt = Environment.getExternalStorageDirectory();
return ( FileExt.getPath() );
}
// Result : /storage/emulated/0/DCIM
public String getPathDCIM() {
File FileDCIM = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return ( FileDCIM.getPath() );
}
//by jmpessoa
public String getPathDataBase(android.content.Context context) {
String destPath = context.getFilesDir().getAbsolutePath();
destPath = destPath.substring(0, destPath.lastIndexOf("/")) + "/databases";
return destPath;
}
// -------------------------------------------------------------------------
// Android Locale
// -------------------------------------------------------------------------
// thierrydijoux - get locale info
public String getLocale(int localeType) {
Context context = this.activity;
String value = "";
switch (localeType) {
case 0: value = context.getResources().getConfiguration().locale.getCountry();
break;
case 1: value = context.getResources().getConfiguration().locale.getDisplayCountry();
break;
case 2: value = context.getResources().getConfiguration().locale.getDisplayLanguage();
break;
case 3: value = context.getResources().getConfiguration().locale.getDisplayName();
break;
case 4: value = context.getResources().getConfiguration().locale.getDisplayVariant();
break;
case 5: value = context.getResources().getConfiguration().locale.getISO3Country();
break;
case 6: value = context.getResources().getConfiguration().locale.getISO3Language();
break;
case 7: value = context.getResources().getConfiguration().locale.getVariant();
break;
}
return value;
}
// -------------------------------------------------------------------------
// Android Device
// -------------------------------------------------------------------------
// Result: Phone Number - LORDMAN
public String getDevPhoneNumber() {
String f = "";
TelephonyManager telephony = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
if (telephony!=null) {
try {
f = telephony.getLine1Number();
} catch (SecurityException ex) {
Log.e("getDevPhoneNumber", ex.getMessage());
}
}
return f;
}
// Result: Device ID - LORDMAN
// Remarks : Nexus7 (no moblie device) -> Crash : fixed code - Simon
public String getDevDeviceID() {
String f = "";
TelephonyManager telephony = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
if (telephony!=null) {
try {
f = telephony.getDeviceId();
} catch (SecurityException ex) {
Log.e("getDevDeviceID", ex.getMessage());
}
}
return f;
}
// -------------------------------------------------------------------------
// Bitmap
// -------------------------------------------------------------------------
// Get Image Width,Height without Decoding
public int Image_getWH (String filename ) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
return ( (options.outWidth << 16) | (options.outHeight) );
}
//
public Bitmap Image_resample(String infile,int size) {
int iw,ih,im; // input image w,h, max
int scale; //
int ow,oh; // output image w,h
// get input image w,h
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(infile, options);
iw = options.outWidth;
ih = options.outHeight;
//
im = Math.max(iw,ih);
scale = 1;
if (size <= (im/32)) { scale = 32; }
if (((im/32) < size) && (size <= (im/16))) { scale = 16; }
if (((im/16) < size) && (size <= (im/ 8))) { scale = 8; }
if (((im/ 8) < size) && (size <= (im/ 4))) { scale = 4; }
if (((im/ 4) < size) && (size <= (im/ 2))) { scale = 2; }
//
options.inJustDecodeBounds = false;
options.inSampleSize = scale;
Bitmap src = BitmapFactory.decodeFile(infile, options);
//
if (im == iw) { ow = size;
oh = Math.round((float)ow*((float)ih/(float)iw)); }
else { oh = size;
ow = Math.round((float)oh*((float)iw/(float)ih)); }
//
return( Bitmap.createScaledBitmap(src, ow,oh, true) );
}
public void Image_save(Bitmap bmp, String filename) {
try { FileOutputStream out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); }
catch (Exception e)
{ e.printStackTrace(); }
}
// -------------------------------------------------------------------------
// Toast
// -------------------------------------------------------------------------
//
public void jToast( String str ) {
Toast.makeText(activity, str, Toast.LENGTH_SHORT).show();
}
//by jmpessoa
//you need a real android device (not emulator!)
//http://www.androidaspect.com/2013/09/how-to-send-email-from-android.html
public void jSend_Email(
String to,
String cc,
String bcc,
String subject,
String message)
{
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, to);
email.putExtra(Intent.EXTRA_CC, cc);
email.putExtra(Intent.EXTRA_BCC, bcc);
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
// Use email client only
email.setType("message/rfc822");
this.activity.startActivity(Intent.createChooser(email, "Choose an email client"));
//rst = 1; //ok
}catch (Exception e) {
//Log.i("Java","Send Email Error");
e.printStackTrace();
}
}
//http://codetheory.in/android-sms/
//http://www.developerfeed.com/java/tutorial/sending-sms-using-android
//http://www.techrepublic.com/blog/software-engineer/how-to-send-a-text-message-from-within-your-android-app/
public int jSend_SMS(String phoneNumber, String msg, boolean multipartMessage) {
SmsManager sms = SmsManager.getDefault();
try {
//SmsManager.getDefault().sendTextMessage(phoneNumber, null, msg, null, null);
if (multipartMessage) {
ArrayList<String> messages = sms.divideMessage(msg);
sms.sendMultipartTextMessage(phoneNumber, null, messages, null, null);
} else {
List<String> messages = sms.divideMessage(msg);
for (String message : messages) {
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
//Log.i("Send_SMS",phoneNumber+": "+ msg);
return 1; //ok
} catch (Exception e) {
//Log.i("Send_SMS Fail",e.toString());
return 0; //fail
}
}
//improved by CC
//http://forum.lazarus-ide.org/index.php/topic,44775.msg315109/topicseen.html
public int jSend_SMS(String phoneNumber, String msg, String packageDeliveredAction, boolean multipartMessage) {
String SMS_DELIVERED = packageDeliveredAction;
PendingIntent deliveredPendingIntent = PendingIntent.getBroadcast(this.GetContext(), 0, new Intent(SMS_DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
int partsCount = 1;
try {
if (multipartMessage)
{
ArrayList<String> messages = sms.divideMessage(msg);
partsCount = messages.size();
ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
for (int i = 0; i < messages.size(); i++)
{
deliveredPendingIntents.add(i, deliveredPendingIntent);
}
sms.sendMultipartTextMessage(phoneNumber, null, messages, deliveredPendingIntents, null );
}
else
{
List<String> messages = sms.divideMessage(msg);
partsCount = messages.size();
for (String message : messages)
{
sms.sendTextMessage(phoneNumber, null, message, deliveredPendingIntent, null );
}
}
return partsCount;
} catch (Exception e) {
return 0; //fail
}
}
public String jRead_SMS(Intent intent, String addressBodyDelimiter) {
//---get the SMS message passed in---
SmsMessage[] msgs = null;
String str = "";
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += msgs[i].getOriginatingAddress();
str += addressBodyDelimiter;
str += msgs[i].getMessageBody().toString();
str += " ";
}
}
}
return str;
}
//by jmpessoa
//http://eagle.phys.utk.edu/guidry/android/readContacts.html
@SuppressLint("DefaultLocale")
public String jContact_getMobileNumberByDisplayName(String contactName){
String matchNumber = "";
String username;
username = contactName;
username = username.toLowerCase();
Cursor phones = this.activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneType = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
name = name.toLowerCase();
if(name.equals(username)) {
if ( phoneType.equals("2")) { //mobile
matchNumber = phoneNumber;
break;
}
}
}
phones.close();
return matchNumber;
}
//by jmpessoa
//http://eagle.phys.utk.edu/guidry/android/readContacts.html
public String jContact_getDisplayNameList(char delimiter){
String nameList = "";
Cursor phones = this.activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneType = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
if ( phoneType.equals("2")) { //mobile
nameList = nameList + delimiter + name;
}
}
phones.close();
return nameList;
}
// -------------------------------------------------------------------------
// Bitmap
// -------------------------------------------------------------------------
public int[] getBmpArray(String file) {
Bitmap bmp = BitmapFactory.decodeFile(file);
int length = bmp.getWidth()*bmp.getHeight();
int[] pixels = new int[length+2];
bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
pixels[length+0] = bmp.getWidth ();
pixels[length+1] = bmp.getHeight();
return ( pixels );
}
// -------------------------------------------------------------------------
// Camera
// -------------------------------------------------------------------------
public void takePhoto(String filename) { //HINT: filename = App.Path.DCIM + '/test.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri mImageCaptureUri = Uri.fromFile(new File("", filename));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
activity.startActivityForResult(intent, 12345);
}
/*
* NOTE: The DCIM folder on the microSD card in your Android device is where Android stores the photos and videos
* you take with the device's built-in camera. When you open the Android Gallery app,
* you are browsing the files saved in the DCIM folder....
*/
public String jCamera_takePhoto(String path, String filename) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri mImageCaptureUri = Uri.fromFile(new File(path, '/'+filename)); // get Android.Uri from file
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
this.activity.startActivityForResult(intent, 12345); //12345 = requestCode
return (path+'/'+filename);
}
public String jCamera_takePhoto(String path, String filename, int requestCode) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri mImageCaptureUri = Uri.fromFile(new File(path, '/'+filename)); // get Android.Uri from file
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
this.activity.startActivityForResult(intent, requestCode); //12345 = requestCode
return (path+'/'+filename);
}
//-------------------------------------------------------------------------------------------------------
//SMART LAMW DESIGNER
//-------------------------------------------------------------------------------------------------------
public java.lang.Object jButton_Create(long pasobj ) {
return (java.lang.Object)( new jButton(this.activity,this,pasobj));
}
public java.lang.Object jCheckBox_Create(long pasobj ) {
return (java.lang.Object)( new jCheckBox(this.activity,this,pasobj));
}
public java.lang.Object jcOpenMapView_jCreate(long _Self, boolean _showScale, int _tileSource, int _zoom) {
return (java.lang.Object)(new jcOpenMapView(this,_Self, _showScale, _tileSource, _zoom));
}
public native int[] pOnOpenMapViewRoadDraw(long pasobj, int roadCode, int roadStatus, double roadDuration, double roadDistance);
public native void pOnOpenMapViewClick(long pasobj, double latitude, double longitude);
public native void pOnOpenMapViewLongClick(long pasobj, double latitude, double longitude);
public native void pOnOpenMapViewMarkerClick(long pasobj, String title, double latitude, double longitude);
public java.lang.Object jTextView_Create(long pasobj) {
return (java.lang.Object)( new jTextView(this.activity,this,pasobj));
}
}
|
{
"pile_set_name": "Github"
}
|
File 2 in directory 1
|
{
"pile_set_name": "Github"
}
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.alibaba.otter</groupId>
<artifactId>node</artifactId>
<version>4.2.19-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>com.alibaba.otter</groupId>
<artifactId>node.extend</artifactId>
<packaging>jar</packaging>
<name>otter extend module for otter</name>
<url>http://github.com/alibaba/otter</url>
<dependencies>
<dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>shared.etl</artifactId>
<version>${project.version}</version>
</dependency>
<!-- test dependency -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
|
{
"pile_set_name": "Github"
}
|
component extends="org.lucee.cfml.test.LuceeTestCase"{
function invokeTest(test) {
var obj = createObject("component","LDEV1679.test");
invoke(obj,"FuncWithArg",arguments);
return structIsempty(arguments);
}
function run(){
describe( title="Test suite for LDEV-1679", body=function(){
it(title="Checking invoke function with arguments scope ", body=function(){
try {
var dir="#GetDirectoryFromPath(GetCurrentTemplatePath())#LDEV1679\";
if(!directoryExists(dir)){
Directorycreate(dir);
}
var testfile = dir&"test.cfc";
fileWrite(testfile,"
component {
function FuncWithArg(test) {
}
}");
var testStr = {};
var result = invokeTest(testStr);
expect(result).toBe('false');
}
finally {
if(!isNull(testfile) && fileExists(testfile)) {
fileDelete(testfile);
}
}
});
});
}
}
|
{
"pile_set_name": "Github"
}
|
/* Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program 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, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#ifndef GCS_CONTROL_INTERFACE_INCLUDED
#define GCS_CONTROL_INTERFACE_INCLUDED
#include <vector>
#include "plugin/group_replication/libmysqlgcs/include/mysql/gcs/gcs_control_event_listener.h"
#include "plugin/group_replication/libmysqlgcs/include/mysql/gcs/gcs_member_identifier.h"
#include "plugin/group_replication/libmysqlgcs/include/mysql/gcs/gcs_view.h"
/**
@class Gcs_control_interface
This interface represents all the control functionalities that a binding
implementation must provide. Like all interfaces in this API, it is
group-oriented, meaning that a single instance shall exist per group,
as it was returned by the class Gcs_interface::get_control_session.
It contains methods for:
- View Membership;
- Control Events;
- Generic Data Exchange.
View Membership contain operations that will conduct one to:
- Belong to a group: join() and leave();
- Information about its status: belongs_to_group() and
get_current_view() that shall return the active Gcs_view.
Due to the asynchronous nature of this interface, the results of
join() and leave() operations, in local or remote members, shall come
via an event. Those events shall be delivered in form of callbacks
defined in Gcs_control_event_listener, that should be implemented by a
client of this interface interested in receiving those notifications.
Regarding Generic Data Exchange, it is a functionality that was created
to allow exchange of arbitrary data among members when one joins.
This generic data is retrieved via the callback get_exchangeable_data() each
time a View Change (VC) occurs. It states the data that one would like to
offer in exchange whenever a VC happens.
What must happen under the hood is that, when one receives a VC from
the underlying GCS, the binding implementation should start a round
of message exchange, in which members (one or all depending of the algorithm)
send the Exchangeable Data to the joining node.
That data is delivered when Gcs_control_event_listener::on_view_changed is
called, which hands-out all exchanged data in one point in time.
A typical usage for that interface would be:
@code{.cpp}
class my_Gcs_control_event_listener: Gcs_control_event_listener
{
void on_view_changed(const Gcs_view *new_view,
const Exchanged_data &exchanged_data)
{
// D something when view arrives...
// It will also deliver all data that nodes decided to offer at join()
// time
}
Gcs_message_data &get_exchangeable_data()
{
// Return whatever data we want to provide to a joining node
}
}
// Meanwhile in your client code...
Gcs_control_interface *gcs_control_interface_instance; // obtained
// previously
Gcs_control_event_listener *listener_instance=
new my_Gcs_control_event_listener();
int ref_handler=
gcs_control_interface_instance->add_event_listener(listener_instance);
// Normal program flow... join(), send_message(), leave()...
gcs_control_interface_instance->join();
gcs_control_interface_instance->leave();
// In the end...
gcs_control_interface_instance->remove_event_listener(ref_handler);
@endcode
*/
class Gcs_control_interface {
public:
/**
Method that causes one to join the group that this
interface pertains.
The method is non-blocking, meaning that it shall only send the
request to an underlying GCS. The final result shall come via a
View Change event delivered through Gcs_control_event_listener.
@retval GCS_OK in case of everything goes well. Any other value of
gcs_error in case of error.
*/
virtual enum_gcs_error join() = 0;
/**
Method that causes one to leave the group that this
interface pertains.
The method is non-blocking, meaning that it shall only send the
request to an underlying GCS. The final result shall come via a
View Change event delivered through Gcs_control_event_listener.
@retval GCS_OK in case of everything goes well. Any other value of
gcs_error in case of error
*/
virtual enum_gcs_error leave() = 0;
/**
Reports if one has joined and belongs to a group.
@retval true if belonging to a group
*/
virtual bool belongs_to_group() = 0;
/**
Returns the currently installed view.
@retval pointer to a Gcs_view object.
If one has left a group, this shall be the last
installed view. That view can be considered a best-effort
view since, in some GCSs, the one that leaves might not
have access to the exchanged information.
@retval NULL if one never joined a group.
*/
virtual Gcs_view *get_current_view() = 0;
/**
Retrieves the local identifier of this member on a group.
@retval reference to a valid Gcs_member_identifier instance
@retval NULL in case of error
*/
virtual const Gcs_member_identifier get_local_member_identifier() const = 0;
/**
Registers an implementation of a Gcs_control_event_listener that will
receive Control Events. See the class header for more details on
implementations and usage.
Note that a binding implementation shall not offer the possibility of
changing listeners while the system is up and running. In that sense,
listeners must be added to it only when booting up the system.
@param[in] event_listener a class that implements Gcs_control_event_listener
@return an handle representing the registration of this object to
be used in remove_event_listener
*/
virtual int add_event_listener(
const Gcs_control_event_listener &event_listener) = 0;
/**
Removes a previously registered event listener.
Note that a binding implementation shall not offer the possibility of
changing listeners while the system is up and running. In that sense
listeners must be removed from it only when shutting down the system.
@param[in] event_listener_handle the handle returned when the listener was
registered
*/
virtual void remove_event_listener(int event_listener_handle) = 0;
/**
Sets a new value for the maximum size of the XCom cache.
@param[in] size the new maximum size of the XCom cache
@retval - GCS_OK if request was successfully scheduled in XCom,
GCS_NOK otherwise.
*/
virtual enum_gcs_error set_xcom_cache_size(uint64_t size) = 0;
virtual ~Gcs_control_interface() {}
};
#endif // GCS_CONTROL_INTERFACE_INCLUDED
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
from HTMLParser import HTMLParser
import urllib2
class MyHtmlParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.picUrls = []
def handle_starttag(self, tag, attrs):
if tag == "img":
if len(attrs) > 0:
for key, value in attrs:
if key == "src":
self.picUrls.append(value)
def Pic(picurls):
count = 1
for picurl in picurls:
conn = urllib2.urlopen(picurl)
f = open(str(count)+".jpg", 'wb')
f.write(conn.read())
f.close()
count += 1
if __name__ == '__main__':
html = urllib2.urlopen("http://tieba.baidu.com/p/2166231880").read()
htmlParser = MyHtmlParser()
htmlParser.feed(html)
htmlParser.close()
Pic(htmlParser.picUrls)
|
{
"pile_set_name": "Github"
}
|
/*! \file optional.hpp
\brief Support for std::optional
\ingroup STLSupport */
/*
Copyright (c) 2017, Juan Pedro Bolivar Puente
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 cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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.
*/
#ifndef CEREAL_TYPES_STD_OPTIONAL_
#define CEREAL_TYPES_STD_OPTIONAL_
#include "cereal/cereal.hpp"
#include <optional>
namespace cereal {
//! Saving for std::optional
template <class Archive, typename T> inline
void CEREAL_SAVE_FUNCTION_NAME(Archive& ar, const std::optional<T>& optional)
{
if(!optional) {
ar(CEREAL_NVP_("nullopt", true));
} else {
ar(CEREAL_NVP_("nullopt", false),
CEREAL_NVP_("data", *optional));
}
}
//! Loading for std::optional
template <class Archive, typename T> inline
void CEREAL_LOAD_FUNCTION_NAME(Archive& ar, std::optional<T>& optional)
{
bool nullopt;
ar(CEREAL_NVP_("nullopt", nullopt));
if (nullopt) {
optional = std::nullopt;
} else {
T value;
ar(CEREAL_NVP_("data", value));
optional = std::move(value);
}
}
} // namespace cereal
#endif // CEREAL_TYPES_STD_OPTIONAL_
|
{
"pile_set_name": "Github"
}
|
{
"keyboard": "pinky/3",
"keymap": "default_ac7a9e3",
"commit": "ac7a9e3c66c59c8f35202269eebac692bb4c3716",
"layout": "LAYOUT",
"layers": [
[
"KC_ESC", "KC_Q", "KC_W", "KC_E", "KC_R", "KC_T", "KC_LPRN", "KC_RPRN", "KC_Y", "KC_U", "KC_I", "KC_O", "KC_P", "KC_BSPC",
"LCTL_T(KC_TAB)", "KC_A", "KC_S", "KC_D", "KC_F", "KC_G", "KC_LBRC", "KC_RBRC", "KC_H", "KC_J", "KC_K", "KC_L", "KC_SCLN", "KC_QUOT",
"KC_LSFT", "KC_Z", "KC_X", "KC_C", "KC_V", "KC_B", "MO(3)", "MO(3)", "KC_N", "KC_M", "KC_COMM", "KC_DOT", "KC_SLSH", "KC_ENT",
"KC_LALT", "MO(1)", "KC_LGUI", "KC_SPC", "KC_SPC", "KC_RGUI", "MO(2)", "KC_RALT"
],
[
"KC_GRV", "KC_1", "KC_2", "KC_3", "KC_4", "KC_5", "KC_TRNS", "KC_TRNS", "KC_6", "KC_7", "KC_8", "KC_9", "KC_0", "KC_BSLS",
"KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_MINS", "KC_EQL", "KC_TRNS",
"KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS",
"KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "MO(3)", "KC_TRNS"
],
[
"KC_GRV", "KC_1", "KC_2", "KC_3", "KC_4", "KC_5", "KC_TRNS", "KC_TRNS", "KC_6", "KC_7", "KC_8", "KC_9", "KC_0", "KC_BSLS",
"KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_MINS", "KC_EQL", "KC_TRNS",
"KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS",
"KC_TRNS", "MO(3)", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS"
],
[
"KC_TRNS", "KC_F1", "KC_F2", "KC_F3", "KC_F4", "KC_F5", "KC_LCBR", "KC_RCBR", "KC_F6", "KC_F7", "KC_F8", "KC_F9", "KC_F10", "KC_TRNS",
"KC_TRNS", "KC_F11", "KC_F12", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_LCBR", "KC_RCBR", "KC_HOME", "KC_PGDN", "KC_PGUP", "KC_END", "KC_TRNS", "KC_TRNS",
"KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS",
"KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS", "KC_TRNS"
]
]
}
|
{
"pile_set_name": "Github"
}
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
r"""Converts WAV audio files into input features for neural networks.
The models used in this example take in two-dimensional spectrograms as the
input to their neural network portions. For testing and porting purposes it's
useful to be able to generate these spectrograms outside of the full model, so
that on-device implementations using their own FFT and streaming code can be
tested against the version used in training for example. The output is as a
C source file, so it can be easily linked into an embedded test application.
To use this, run:
bazel run tensorflow/examples/speech_commands:wav_to_features -- \
--input_wav=my.wav --output_c_file=my_wav_data.c
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os.path
import sys
import tensorflow as tf
import input_data
import models
from tensorflow.python.platform import gfile
FLAGS = None
def wav_to_features(sample_rate, clip_duration_ms, window_size_ms,
window_stride_ms, feature_bin_count, quantize, preprocess,
input_wav, output_c_file):
"""Converts an audio file into its corresponding feature map.
Args:
sample_rate: Expected sample rate of the wavs.
clip_duration_ms: Expected duration in milliseconds of the wavs.
window_size_ms: How long each spectrogram timeslice is.
window_stride_ms: How far to move in time between spectogram timeslices.
feature_bin_count: How many bins to use for the feature fingerprint.
quantize: Whether to train the model for eight-bit deployment.
preprocess: Spectrogram processing mode; "mfcc", "average" or "micro".
input_wav: Path to the audio WAV file to read.
output_c_file: Where to save the generated C source file.
"""
# Start a new TensorFlow session.
sess = tf.compat.v1.InteractiveSession()
model_settings = models.prepare_model_settings(
0, sample_rate, clip_duration_ms, window_size_ms, window_stride_ms,
feature_bin_count, preprocess)
audio_processor = input_data.AudioProcessor(None, None, 0, 0, '', 0, 0,
model_settings, None)
results = audio_processor.get_features_for_wav(input_wav, model_settings,
sess)
features = results[0]
variable_base = os.path.splitext(os.path.basename(input_wav).lower())[0]
# Save a C source file containing the feature data as an array.
with gfile.GFile(output_c_file, 'w') as f:
f.write('/* File automatically created by\n')
f.write(' * tensorflow/examples/speech_commands/wav_to_features.py \\\n')
f.write(' * --sample_rate=%d \\\n' % sample_rate)
f.write(' * --clip_duration_ms=%d \\\n' % clip_duration_ms)
f.write(' * --window_size_ms=%d \\\n' % window_size_ms)
f.write(' * --window_stride_ms=%d \\\n' % window_stride_ms)
f.write(' * --feature_bin_count=%d \\\n' % feature_bin_count)
if quantize:
f.write(' * --quantize=1 \\\n')
f.write(' * --preprocess="%s" \\\n' % preprocess)
f.write(' * --input_wav="%s" \\\n' % input_wav)
f.write(' * --output_c_file="%s" \\\n' % output_c_file)
f.write(' */\n\n')
f.write('const int g_%s_width = %d;\n' %
(variable_base, model_settings['fingerprint_width']))
f.write('const int g_%s_height = %d;\n' %
(variable_base, model_settings['spectrogram_length']))
if quantize:
features_min, features_max = input_data.get_features_range(model_settings)
f.write('const unsigned char g_%s_data[] = {' % variable_base)
i = 0
for value in features.flatten():
quantized_value = int(
round(
(255 * (value - features_min)) / (features_max - features_min)))
if quantized_value < 0:
quantized_value = 0
if quantized_value > 255:
quantized_value = 255
if i == 0:
f.write('\n ')
f.write('%d, ' % (quantized_value))
i = (i + 1) % 10
else:
f.write('const float g_%s_data[] = {\n' % variable_base)
i = 0
for value in features.flatten():
if i == 0:
f.write('\n ')
f.write(' ,%f' % value)
i = (i + 1) % 10
f.write('\n};\n')
def main(_):
# We want to see all the logging messages.
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
wav_to_features(FLAGS.sample_rate, FLAGS.clip_duration_ms,
FLAGS.window_size_ms, FLAGS.window_stride_ms,
FLAGS.feature_bin_count, FLAGS.quantize, FLAGS.preprocess,
FLAGS.input_wav, FLAGS.output_c_file)
tf.compat.v1.logging.info('Wrote to "%s"' % (FLAGS.output_c_file))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--sample_rate',
type=int,
default=16000,
help='Expected sample rate of the wavs',)
parser.add_argument(
'--clip_duration_ms',
type=int,
default=1000,
help='Expected duration in milliseconds of the wavs',)
parser.add_argument(
'--window_size_ms',
type=float,
default=30.0,
help='How long each spectrogram timeslice is.',)
parser.add_argument(
'--window_stride_ms',
type=float,
default=10.0,
help='How far to move in time between spectogram timeslices.',)
parser.add_argument(
'--feature_bin_count',
type=int,
default=40,
help='How many bins to use for the MFCC fingerprint',
)
parser.add_argument(
'--quantize',
type=bool,
default=False,
help='Whether to train the model for eight-bit deployment')
parser.add_argument(
'--preprocess',
type=str,
default='mfcc',
help='Spectrogram processing mode. Can be "mfcc", "average", or "micro"')
parser.add_argument(
'--input_wav',
type=str,
default=None,
help='Path to the audio WAV file to read')
parser.add_argument(
'--output_c_file',
type=str,
default=None,
help='Where to save the generated C source file containing the features')
FLAGS, unparsed = parser.parse_known_args()
tf.compat.v1.app.run(main=main, argv=[sys.argv[0]] + unparsed)
|
{
"pile_set_name": "Github"
}
|
---
title: 'Session 08: Tuning'
draft: false
date: '2019-08-29'
slug: 08-tune
categories: []
tags: []
lastmod: '2019-09-09T11:21:55-07:00'
featured: no
projects: []
weight: 9
links:
- icon: images
icon_pack: fas
name: slides
url: /slides/08-tune.html
- icon: dumbbell
icon_pack: fas
name: Exercises
url: https://github.com/rstudio-conf-2020/intro-to-ml-tidy/blob/master/materials/exercises/08-Tune.Rmd
- icon: check-square
icon_pack: far
name: Solutions
url: https://github.com/rstudio-conf-2020/intro-to-ml-tidy/blob/master/materials/solutions/08-Tune.Rmd
---
<iframe src="/slides/08-tune.html" width="672" height="400px">
</iframe>
|
{
"pile_set_name": "Github"
}
|
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/less.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
template<
typename Tag1
, typename Tag2
>
struct less_impl
: if_c<
( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1)
> BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2)
)
, aux::cast2nd_impl< less_impl< Tag1,Tag1 >,Tag1, Tag2 >
, aux::cast1st_impl< less_impl< Tag2,Tag2 >,Tag1, Tag2 >
>::type
{
};
/// for Digital Mars C++/compilers with no CTPS/TTP support
template<> struct less_impl< na,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct less_impl< na,Tag >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct less_impl< Tag,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename T > struct less_tag
{
typedef typename T::tag type;
};
template<
typename BOOST_MPL_AUX_NA_PARAM(N1)
, typename BOOST_MPL_AUX_NA_PARAM(N2)
>
struct less
: less_impl<
typename less_tag<N1>::type
, typename less_tag<N2>::type
>::template apply< N1,N2 >::type
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(2, less, (N1, N2))
};
BOOST_MPL_AUX_NA_SPEC2(2, 2, less)
}}
namespace boost { namespace mpl {
template<>
struct less_impl< integral_c_tag,integral_c_tag >
{
template< typename N1, typename N2 > struct apply
: bool_< ( BOOST_MPL_AUX_VALUE_WKND(N2)::value > BOOST_MPL_AUX_VALUE_WKND(N1)::value ) >
{
};
};
}}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
* Copyright (c) 2010 David Chinner.
* Copyright (c) 2011 Christoph Hellwig.
* All Rights Reserved.
*
* This program 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.
*
* This program is distributed in the hope that it would 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 this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_log.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc.h"
#include "xfs_inode.h"
#include "xfs_extent_busy.h"
#include "xfs_trace.h"
void
xfs_extent_busy_insert(
struct xfs_trans *tp,
xfs_agnumber_t agno,
xfs_agblock_t bno,
xfs_extlen_t len,
unsigned int flags)
{
struct xfs_extent_busy *new;
struct xfs_extent_busy *busyp;
struct xfs_perag *pag;
struct rb_node **rbp;
struct rb_node *parent = NULL;
new = kmem_zalloc(sizeof(struct xfs_extent_busy), KM_MAYFAIL);
if (!new) {
/*
* No Memory! Since it is now not possible to track the free
* block, make this a synchronous transaction to insure that
* the block is not reused before this transaction commits.
*/
trace_xfs_extent_busy_enomem(tp->t_mountp, agno, bno, len);
xfs_trans_set_sync(tp);
return;
}
new->agno = agno;
new->bno = bno;
new->length = len;
INIT_LIST_HEAD(&new->list);
new->flags = flags;
/* trace before insert to be able to see failed inserts */
trace_xfs_extent_busy(tp->t_mountp, agno, bno, len);
pag = xfs_perag_get(tp->t_mountp, new->agno);
spin_lock(&pag->pagb_lock);
rbp = &pag->pagb_tree.rb_node;
while (*rbp) {
parent = *rbp;
busyp = rb_entry(parent, struct xfs_extent_busy, rb_node);
if (new->bno < busyp->bno) {
rbp = &(*rbp)->rb_left;
ASSERT(new->bno + new->length <= busyp->bno);
} else if (new->bno > busyp->bno) {
rbp = &(*rbp)->rb_right;
ASSERT(bno >= busyp->bno + busyp->length);
} else {
ASSERT(0);
}
}
rb_link_node(&new->rb_node, parent, rbp);
rb_insert_color(&new->rb_node, &pag->pagb_tree);
list_add(&new->list, &tp->t_busy);
spin_unlock(&pag->pagb_lock);
xfs_perag_put(pag);
}
/*
* Search for a busy extent within the range of the extent we are about to
* allocate. You need to be holding the busy extent tree lock when calling
* xfs_extent_busy_search(). This function returns 0 for no overlapping busy
* extent, -1 for an overlapping but not exact busy extent, and 1 for an exact
* match. This is done so that a non-zero return indicates an overlap that
* will require a synchronous transaction, but it can still be
* used to distinguish between a partial or exact match.
*/
int
xfs_extent_busy_search(
struct xfs_mount *mp,
xfs_agnumber_t agno,
xfs_agblock_t bno,
xfs_extlen_t len)
{
struct xfs_perag *pag;
struct rb_node *rbp;
struct xfs_extent_busy *busyp;
int match = 0;
pag = xfs_perag_get(mp, agno);
spin_lock(&pag->pagb_lock);
rbp = pag->pagb_tree.rb_node;
/* find closest start bno overlap */
while (rbp) {
busyp = rb_entry(rbp, struct xfs_extent_busy, rb_node);
if (bno < busyp->bno) {
/* may overlap, but exact start block is lower */
if (bno + len > busyp->bno)
match = -1;
rbp = rbp->rb_left;
} else if (bno > busyp->bno) {
/* may overlap, but exact start block is higher */
if (bno < busyp->bno + busyp->length)
match = -1;
rbp = rbp->rb_right;
} else {
/* bno matches busyp, length determines exact match */
match = (busyp->length == len) ? 1 : -1;
break;
}
}
spin_unlock(&pag->pagb_lock);
xfs_perag_put(pag);
return match;
}
/*
* The found free extent [fbno, fend] overlaps part or all of the given busy
* extent. If the overlap covers the beginning, the end, or all of the busy
* extent, the overlapping portion can be made unbusy and used for the
* allocation. We can't split a busy extent because we can't modify a
* transaction/CIL context busy list, but we can update an entries block
* number or length.
*
* Returns true if the extent can safely be reused, or false if the search
* needs to be restarted.
*/
STATIC bool
xfs_extent_busy_update_extent(
struct xfs_mount *mp,
struct xfs_perag *pag,
struct xfs_extent_busy *busyp,
xfs_agblock_t fbno,
xfs_extlen_t flen,
bool userdata)
{
xfs_agblock_t fend = fbno + flen;
xfs_agblock_t bbno = busyp->bno;
xfs_agblock_t bend = bbno + busyp->length;
/*
* This extent is currently being discarded. Give the thread
* performing the discard a chance to mark the extent unbusy
* and retry.
*/
if (busyp->flags & XFS_EXTENT_BUSY_DISCARDED) {
spin_unlock(&pag->pagb_lock);
delay(1);
spin_lock(&pag->pagb_lock);
return false;
}
/*
* If there is a busy extent overlapping a user allocation, we have
* no choice but to force the log and retry the search.
*
* Fortunately this does not happen during normal operation, but
* only if the filesystem is very low on space and has to dip into
* the AGFL for normal allocations.
*/
if (userdata)
goto out_force_log;
if (bbno < fbno && bend > fend) {
/*
* Case 1:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +---------+
* fbno fend
*/
/*
* We would have to split the busy extent to be able to track
* it correct, which we cannot do because we would have to
* modify the list of busy extents attached to the transaction
* or CIL context, which is immutable.
*
* Force out the log to clear the busy extent and retry the
* search.
*/
goto out_force_log;
} else if (bbno >= fbno && bend <= fend) {
/*
* Case 2:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +-----------------+
* fbno fend
*
* Case 3:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +--------------------------+
* fbno fend
*
* Case 4:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +--------------------------+
* fbno fend
*
* Case 5:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +-----------------------------------+
* fbno fend
*
*/
/*
* The busy extent is fully covered by the extent we are
* allocating, and can simply be removed from the rbtree.
* However we cannot remove it from the immutable list
* tracking busy extents in the transaction or CIL context,
* so set the length to zero to mark it invalid.
*
* We also need to restart the busy extent search from the
* tree root, because erasing the node can rearrange the
* tree topology.
*/
rb_erase(&busyp->rb_node, &pag->pagb_tree);
busyp->length = 0;
return false;
} else if (fend < bend) {
/*
* Case 6:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +---------+
* fbno fend
*
* Case 7:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +------------------+
* fbno fend
*
*/
busyp->bno = fend;
} else if (bbno < fbno) {
/*
* Case 8:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +-------------+
* fbno fend
*
* Case 9:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +----------------------+
* fbno fend
*/
busyp->length = fbno - busyp->bno;
} else {
ASSERT(0);
}
trace_xfs_extent_busy_reuse(mp, pag->pag_agno, fbno, flen);
return true;
out_force_log:
spin_unlock(&pag->pagb_lock);
xfs_log_force(mp, XFS_LOG_SYNC);
trace_xfs_extent_busy_force(mp, pag->pag_agno, fbno, flen);
spin_lock(&pag->pagb_lock);
return false;
}
/*
* For a given extent [fbno, flen], make sure we can reuse it safely.
*/
void
xfs_extent_busy_reuse(
struct xfs_mount *mp,
xfs_agnumber_t agno,
xfs_agblock_t fbno,
xfs_extlen_t flen,
bool userdata)
{
struct xfs_perag *pag;
struct rb_node *rbp;
ASSERT(flen > 0);
pag = xfs_perag_get(mp, agno);
spin_lock(&pag->pagb_lock);
restart:
rbp = pag->pagb_tree.rb_node;
while (rbp) {
struct xfs_extent_busy *busyp =
rb_entry(rbp, struct xfs_extent_busy, rb_node);
xfs_agblock_t bbno = busyp->bno;
xfs_agblock_t bend = bbno + busyp->length;
if (fbno + flen <= bbno) {
rbp = rbp->rb_left;
continue;
} else if (fbno >= bend) {
rbp = rbp->rb_right;
continue;
}
if (!xfs_extent_busy_update_extent(mp, pag, busyp, fbno, flen,
userdata))
goto restart;
}
spin_unlock(&pag->pagb_lock);
xfs_perag_put(pag);
}
/*
* For a given extent [fbno, flen], search the busy extent list to find a
* subset of the extent that is not busy. If *rlen is smaller than
* args->minlen no suitable extent could be found, and the higher level
* code needs to force out the log and retry the allocation.
*/
void
xfs_extent_busy_trim(
struct xfs_alloc_arg *args,
xfs_agblock_t bno,
xfs_extlen_t len,
xfs_agblock_t *rbno,
xfs_extlen_t *rlen)
{
xfs_agblock_t fbno;
xfs_extlen_t flen;
struct rb_node *rbp;
ASSERT(len > 0);
spin_lock(&args->pag->pagb_lock);
restart:
fbno = bno;
flen = len;
rbp = args->pag->pagb_tree.rb_node;
while (rbp && flen >= args->minlen) {
struct xfs_extent_busy *busyp =
rb_entry(rbp, struct xfs_extent_busy, rb_node);
xfs_agblock_t fend = fbno + flen;
xfs_agblock_t bbno = busyp->bno;
xfs_agblock_t bend = bbno + busyp->length;
if (fend <= bbno) {
rbp = rbp->rb_left;
continue;
} else if (fbno >= bend) {
rbp = rbp->rb_right;
continue;
}
/*
* If this is a metadata allocation, try to reuse the busy
* extent instead of trimming the allocation.
*/
if (!args->userdata &&
!(busyp->flags & XFS_EXTENT_BUSY_DISCARDED)) {
if (!xfs_extent_busy_update_extent(args->mp, args->pag,
busyp, fbno, flen,
false))
goto restart;
continue;
}
if (bbno <= fbno) {
/* start overlap */
/*
* Case 1:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +---------+
* fbno fend
*
* Case 2:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +-------------+
* fbno fend
*
* Case 3:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +-------------+
* fbno fend
*
* Case 4:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +-----------------+
* fbno fend
*
* No unbusy region in extent, return failure.
*/
if (fend <= bend)
goto fail;
/*
* Case 5:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +----------------------+
* fbno fend
*
* Case 6:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +--------------------------+
* fbno fend
*
* Needs to be trimmed to:
* +-------+
* fbno fend
*/
fbno = bend;
} else if (bend >= fend) {
/* end overlap */
/*
* Case 7:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +------------------+
* fbno fend
*
* Case 8:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +--------------------------+
* fbno fend
*
* Needs to be trimmed to:
* +-------+
* fbno fend
*/
fend = bbno;
} else {
/* middle overlap */
/*
* Case 9:
* bbno bend
* +BBBBBBBBBBBBBBBBB+
* +-----------------------------------+
* fbno fend
*
* Can be trimmed to:
* +-------+ OR +-------+
* fbno fend fbno fend
*
* Backward allocation leads to significant
* fragmentation of directories, which degrades
* directory performance, therefore we always want to
* choose the option that produces forward allocation
* patterns.
* Preferring the lower bno extent will make the next
* request use "fend" as the start of the next
* allocation; if the segment is no longer busy at
* that point, we'll get a contiguous allocation, but
* even if it is still busy, we will get a forward
* allocation.
* We try to avoid choosing the segment at "bend",
* because that can lead to the next allocation
* taking the segment at "fbno", which would be a
* backward allocation. We only use the segment at
* "fbno" if it is much larger than the current
* requested size, because in that case there's a
* good chance subsequent allocations will be
* contiguous.
*/
if (bbno - fbno >= args->maxlen) {
/* left candidate fits perfect */
fend = bbno;
} else if (fend - bend >= args->maxlen * 4) {
/* right candidate has enough free space */
fbno = bend;
} else if (bbno - fbno >= args->minlen) {
/* left candidate fits minimum requirement */
fend = bbno;
} else {
goto fail;
}
}
flen = fend - fbno;
}
spin_unlock(&args->pag->pagb_lock);
if (fbno != bno || flen != len) {
trace_xfs_extent_busy_trim(args->mp, args->agno, bno, len,
fbno, flen);
}
*rbno = fbno;
*rlen = flen;
return;
fail:
/*
* Return a zero extent length as failure indications. All callers
* re-check if the trimmed extent satisfies the minlen requirement.
*/
spin_unlock(&args->pag->pagb_lock);
trace_xfs_extent_busy_trim(args->mp, args->agno, bno, len, fbno, 0);
*rbno = fbno;
*rlen = 0;
}
STATIC void
xfs_extent_busy_clear_one(
struct xfs_mount *mp,
struct xfs_perag *pag,
struct xfs_extent_busy *busyp)
{
if (busyp->length) {
trace_xfs_extent_busy_clear(mp, busyp->agno, busyp->bno,
busyp->length);
rb_erase(&busyp->rb_node, &pag->pagb_tree);
}
list_del_init(&busyp->list);
kmem_free(busyp);
}
/*
* Remove all extents on the passed in list from the busy extents tree.
* If do_discard is set skip extents that need to be discarded, and mark
* these as undergoing a discard operation instead.
*/
void
xfs_extent_busy_clear(
struct xfs_mount *mp,
struct list_head *list,
bool do_discard)
{
struct xfs_extent_busy *busyp, *n;
struct xfs_perag *pag = NULL;
xfs_agnumber_t agno = NULLAGNUMBER;
list_for_each_entry_safe(busyp, n, list, list) {
if (busyp->agno != agno) {
if (pag) {
spin_unlock(&pag->pagb_lock);
xfs_perag_put(pag);
}
pag = xfs_perag_get(mp, busyp->agno);
spin_lock(&pag->pagb_lock);
agno = busyp->agno;
}
if (do_discard && busyp->length &&
!(busyp->flags & XFS_EXTENT_BUSY_SKIP_DISCARD))
busyp->flags = XFS_EXTENT_BUSY_DISCARDED;
else
xfs_extent_busy_clear_one(mp, pag, busyp);
}
if (pag) {
spin_unlock(&pag->pagb_lock);
xfs_perag_put(pag);
}
}
/*
* Callback for list_sort to sort busy extents by the AG they reside in.
*/
int
xfs_extent_busy_ag_cmp(
void *priv,
struct list_head *a,
struct list_head *b)
{
return container_of(a, struct xfs_extent_busy, list)->agno -
container_of(b, struct xfs_extent_busy, list)->agno;
}
|
{
"pile_set_name": "Github"
}
|
## knctl build list
List builds
### Synopsis
List all builds in a namespace
```
knctl build list [flags]
```
### Examples
```
# List all builds in namespace 'ns1'
knctl build list -n ns1
```
### Options
```
-h, --help help for list
-n, --namespace string Specified namespace ($KNCTL_NAMESPACE or default from kubeconfig)
```
### Options inherited from parent commands
```
--column strings Filter to show only given columns
--json Output as JSON
--kubeconfig string Path to the kubeconfig file ($KNCTL_KUBECONFIG or $KUBECONFIG)
--kubeconfig-context string Kubeconfig context override ($KNCTL_KUBECONFIG_CONTEXT)
--no-color Disable colorized output
--non-interactive Don't ask for user input
--tty Force TTY-like output
```
### SEE ALSO
* [knctl build](knctl_build.md) - Build management (create, delete, list, show)
|
{
"pile_set_name": "Github"
}
|
{
"accountLinkingWhitelistedDomains": null,
"asin": "B01H9FT3UG",
"averageRating": 0,
"canDisable": true,
"capabilities": null,
"category": null,
"description": "A demo built during the Alexa + Hackster.io bootcamp in Seattle that tells you drone facts.",
"enablement": null,
"exampleInteractions": [
"Alexa, ask Drone Geek for a fact",
"Alexa, open Drone Geek for a fact",
"Alexa, tell Drone Geek a fact"
],
"firstReleaseDate": 1466682336.486,
"homepageLinkText": null,
"homepageLinkUrl": null,
"id": "amzn1.echo-sdk-ams.app.42cc0cfe-8019-4c10-b4de-5f07fbd171cf",
"imageAltText": "Drone Geek icon",
"imageUrl": "https://github.com/dale3h/alexa-skills-list/raw/master/skills/B01H9FT3UG/skill_icon",
"inAppPurchasingSupported": false,
"launchPhrase": "drone geek",
"name": "Drone Geek",
"numberOfReviews": 0,
"pamsPartnerId": null,
"permissions": null,
"privacyPolicyUrl": null,
"shortDescription": "Drone Trivia Facts created during the Alexa Skills 101 in Seattle",
"skillTypes": null,
"stage": "live",
"termsOfUseUrl": null,
"vendorId": "M2WMQL6GRWE4YR",
"vendorName": "Anthony Ngu"
}
|
{
"pile_set_name": "Github"
}
|
// 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.
package singleflight
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestDo(t *testing.T) {
var g Group
v, err, _ := g.Do("key", func() (interface{}, error) {
return "bar", nil
})
if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want {
t.Errorf("Do = %v; want %v", got, want)
}
if err != nil {
t.Errorf("Do error = %v", err)
}
}
func TestDoErr(t *testing.T) {
var g Group
someErr := errors.New("Some error")
v, err, _ := g.Do("key", func() (interface{}, error) {
return nil, someErr
})
if err != someErr {
t.Errorf("Do error = %v; want someErr %v", err, someErr)
}
if v != nil {
t.Errorf("unexpected non-nil value %#v", v)
}
}
func TestDoDupSuppress(t *testing.T) {
var g Group
var wg1, wg2 sync.WaitGroup
c := make(chan string, 1)
var calls int32
fn := func() (interface{}, error) {
if atomic.AddInt32(&calls, 1) == 1 {
// First invocation.
wg1.Done()
}
v := <-c
c <- v // pump; make available for any future calls
time.Sleep(10 * time.Millisecond) // let more goroutines enter Do
return v, nil
}
const n = 10
wg1.Add(1)
for i := 0; i < n; i++ {
wg1.Add(1)
wg2.Add(1)
go func() {
defer wg2.Done()
wg1.Done()
v, err, _ := g.Do("key", fn)
if err != nil {
t.Errorf("Do error: %v", err)
return
}
if s, _ := v.(string); s != "bar" {
t.Errorf("Do = %T %v; want %q", v, v, "bar")
}
}()
}
wg1.Wait()
// At least one goroutine is in fn now and all of them have at
// least reached the line before the Do.
c <- "bar"
wg2.Wait()
if got := atomic.LoadInt32(&calls); got <= 0 || got >= n {
t.Errorf("number of calls = %d; want over 0 and less than %d", got, n)
}
}
|
{
"pile_set_name": "Github"
}
|
### Problem
You want to execute several Redis commands with a single atomic command.
### Solution
Use the MULTI/EXEC command to create a queue of commands and execute them atomically.
Use the `MULTI` command to start the queue. Redis reponds with an `OK`. Then queue up
each command. Finally, use `EXEC` to execute the commands. Redis returns a multi-bulk
reply with each command's return value. In this basic example, we add three values to a
list, increment (by 3) a key called 'country-count' and then ask for the range
of all the the values of the list.
If necessary, the DISCARD command can be used to clear the MULTI queue and exit the queue.
redis> MULTI
OK
redis> LPUSH country_list france
QUEUED
redis> LPUSH country_list italy
QUEUED
redis> LPUSH country_list germany
QUEUED
redis> INCRBY country_count 3
QUEUED
redis> LRANGE country_list 0 -1
QUEUED
redis> EXEC
1. (integer) 1
2. (integer) 2
3. (integer) 3
4. (integer) 3
5.
1. germany
2. italy
3. france
### Discussion
MULTI/EXEC, which will be added in Redis 2.0, is an extremely important component of
Redis and merits a good deal of discussion. It is important to know what it
does -- and what it does not do.
M/E is 'atomic' in the sense that, while a queue is being executed, no other clients
will be served by the Redis server -- the queue is treated as a single operation. This
is important for data integrity.
The M/E process is designed to prevent syntax errors during execution by immediately
reporting syntax errors whenever a command is added to the queue. For example:
redis> MULTI
OK
redis> LPUSH country_list italy
QUEUED
redis> LPUSH country_list italy germany
Wrong number of arguments for 'lpush'
Now, M/E does *not* provide complete 'transactions' -- at least not in the ordinary
sense -- since it does not include 'rollback' functionality. Consider the following
situation. You create a relatively large M/E queue (say, with 200 commands) and run
EXEC. Before all the queued commands are executed, the server crashes, or perhaps it
runs out of memory -- let's say that happens at command #148. The first 148 commands
are indeed executed, but the rest are not.
Indeed, M/E is only an 'all or nothing' operation *before* the EXEC command is run
(that is, during queueing) -- not during the execution.
Redis does provide an interesting way to deal with issue: the familiar Append-Only
File. In the upcoming version of Redis, the commands in the queue are only written
to the AOF upon successful completion of the EXEC command. So if your server crashes
mid-EXEC, you can rebuild state according to the previous, pre-EXEC state.
### See Also
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.map.impl;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.map.ExtendedMapEntry;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.query.impl.CachedQueryEntry;
import com.hazelcast.query.impl.Metadata;
import com.hazelcast.query.impl.getters.Extractors;
import static com.hazelcast.map.impl.record.Record.UNSET;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* A {@link java.util.Map.Entry Map.Entry} implementation
* which serializes/de-serializes key and value objects on
* demand. It is beneficial when you need to prevent unneeded
* serialization/de-serialization when creating a {@link
* java.util.Map.Entry Map.Entry}. Mainly targeted to supply a lazy entry
* to {@link com.hazelcast.map.EntryProcessor#process(Map.Entry)} method.
* <p>
* <STRONG>
* Note that this implementation is not
* synchronized and is not thread-safe.
* </STRONG>
* <p>
* LazyMapEntry itself is serializable as long as the object
* representations of both key and value are serializable.
* After serialization objects are resolved using injected
* SerializationService. De-serialized LazyMapEntry does
* contain object representation only Data representations
* and SerializationService is set to null. In other
* words: It's as usable just as a regular Map.Entry.
*
* @param <K> key
* @param <V> value
*/
public class LazyMapEntry<K, V> extends CachedQueryEntry<K, V>
implements Serializable, IdentifiedDataSerializable, ExtendedMapEntry<K, V> {
private static final long serialVersionUID = 0L;
private transient boolean modified;
private transient Metadata metadata;
private transient long newTtl = UNSET;
public LazyMapEntry() {
}
public LazyMapEntry(Data key, Object value, InternalSerializationService serializationService) {
this(key, value, serializationService, null);
}
public LazyMapEntry(Data key, Object value, InternalSerializationService serializationService, Extractors extractors) {
init(serializationService, key, value, extractors);
}
@Override
public LazyMapEntry init(InternalSerializationService serializationService, Data key, Object value, Extractors extractors) {
super.init(serializationService, key, value, extractors);
modified = false;
metadata = null;
return this;
}
public void setValueByInMemoryFormat(InMemoryFormat inMemoryFormat, Object value) {
if (inMemoryFormat == InMemoryFormat.OBJECT) {
valueObject = (V) value;
valueData = null;
} else {
valueData = (Data) value;
valueObject = null;
}
}
@Override
public V setValue(V value) {
modified = true;
V oldValue = getValue();
this.valueObject = value;
this.valueData = null;
return oldValue;
}
@Override
public V setValue(V value, long ttl, TimeUnit ttlUnit) {
newTtl = ttlUnit.toMillis(ttl);
return setValue(value);
}
/**
* Similar to calling {@link #setValue} with null but doesn't return old-value hence no extra deserialization.
*/
public void remove() {
modified = true;
valueObject = null;
valueData = null;
}
/**
* Checks if this entry has null value without any deserialization.
*
* @return true if value is null, otherwise returns false.
*/
public boolean hasNullValue() {
return valueObject == null && valueData == null;
}
public boolean isModified() {
return modified;
}
public long getNewTtl() {
return newTtl;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
return Objects.equals(getKey(), e.getKey())
&& Objects.equals(getValue(), e.getValue());
}
@Override
public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode())
^ (getValue() == null ? 0 : getValue().hashCode());
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
keyObject = (K) in.readObject();
valueObject = (V) in.readObject();
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(getKey());
out.writeObject(getValue());
}
@Override
public void readData(ObjectDataInput in) throws IOException {
keyObject = in.readObject();
valueObject = in.readObject();
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeObject(getKey());
out.writeObject(getValue());
}
@Override
public int getFactoryId() {
return MapDataSerializerHook.F_ID;
}
@Override
public int getClassId() {
return MapDataSerializerHook.LAZY_MAP_ENTRY;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
}
|
{
"pile_set_name": "Github"
}
|
package org.jboss.as.ejb3.subsystem;
import org.jboss.as.controller.ModelVersion;
/**
* Enumerates the supported model versions.
* @author Paul Ferraro
* @author Richard Achmatowicz
*/
public enum EJB3Model {
VERSION_1_2_0(1, 2, 0),
VERSION_1_2_1(1, 2, 1), // EAP 6.4.0
VERSION_1_3_0(1, 3, 0), // EAP 6.4.7
VERSION_3_0_0(3, 0, 0), //
VERSION_4_0_0(4, 0, 0), // EAP 7.0.0
VERSION_5_0_0(5, 0, 0), // EAP 7.2.0, EAP 7.1.0
VERSION_6_0_0(6, 0, 0),
VERSION_7_0_0(7, 0, 0),
VERSION_8_0_0(8, 0, 0)
;
static final EJB3Model CURRENT = VERSION_8_0_0;
private final ModelVersion version;
EJB3Model(int major, int minor, int micro) {
this.version = ModelVersion.create(major, minor, micro);
}
public ModelVersion getVersion() {
return this.version;
}
/**
* Indicates whether this model is more recent than the specified version and thus requires transformation
* @param version a model version
* @return true this this model is more recent than the specified version, false otherwise
*/
public boolean requiresTransformation(ModelVersion version) {
return ModelVersion.compare(this.version, version) < 0;
}
/**
* Indicates whether this model is equal to the specified version
* @param version a model version
* @return true this model is equal to the specified version, false otherwise
*/
public boolean matches(ModelVersion version) {
return this.version.equals(version);
}
}
|
{
"pile_set_name": "Github"
}
|
const compression = require('compression');
const express = require('express');
const twig = require('twig');
const auth = require('basic-auth');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const moment = require('moment');
module.exports = class Http {
constructor(
systemUtil,
ta,
signalHttp,
backtest,
exchangeManager,
pairsHttp,
logsHttp,
candleExportHttp,
candleImporter,
ordersHttp,
projectDir
) {
this.systemUtil = systemUtil;
this.ta = ta;
this.signalHttp = signalHttp;
this.backtest = backtest;
this.exchangeManager = exchangeManager;
this.pairsHttp = pairsHttp;
this.logsHttp = logsHttp;
this.candleExportHttp = candleExportHttp;
this.candleImporter = candleImporter;
this.ordersHttp = ordersHttp;
this.projectDir = projectDir;
}
start() {
twig.extendFilter('price_format', function(value) {
if (parseFloat(value) < 1) {
return Intl.NumberFormat('en-US', {
useGrouping: false,
minimumFractionDigits: 2,
maximumFractionDigits: 6
}).format(value);
}
return Intl.NumberFormat('en-US', {
useGrouping: false,
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(value);
});
const assetVersion = crypto
.createHash('md5')
.update(String(Math.floor(Date.now() / 1000)))
.digest('hex')
.substring(0, 8);
twig.extendFunction('asset_version', function() {
return assetVersion;
});
const desks = this.systemUtil.getConfig('desks', []).map(desk => desk.name);
twig.extendFunction('desks', function() {
return desks;
});
twig.extendFunction('node_version', function() {
return process.version;
});
twig.extendFunction('memory_usage', function() {
return Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100;
});
twig.extendFilter('format_json', function(value) {
return JSON.stringify(value, null, '\t');
});
const app = express();
app.set('views', `${this.projectDir}/templates`);
app.set('twig options', {
allow_async: true,
strict_variables: false
});
app.use(express.urlencoded({ limit: '12mb', extended: true, parameterLimit: 50000 }));
app.use(cookieParser());
app.use(compression());
app.use(express.static(`${this.projectDir}/web/static`, { maxAge: 3600000 * 24 }));
const username = this.systemUtil.getConfig('webserver.username');
const password = this.systemUtil.getConfig('webserver.password');
if (username && password) {
app.use((request, response, next) => {
const user = auth(request);
if (!user || !(user.name === username && user.pass === password)) {
response.set('WWW-Authenticate', 'Basic realm="Please Login"');
return response.status(401).send();
}
return next();
});
}
const { ta } = this;
app.get('/', async (req, res) => {
res.render(
'../templates/base.html.twig',
await ta.getTaForPeriods(this.systemUtil.getConfig('dashboard.periods', ['15m', '1h']))
);
});
app.get('/backtest', async (req, res) => {
res.render('../templates/backtest.html.twig', {
strategies: this.backtest.getBacktestStrategies(),
pairs: this.backtest.getBacktestPairs()
});
});
app.post('/backtest/submit', async (req, res) => {
const pair = req.body.pair.split('.');
res.render(
'../templates/backtest_submit.html.twig',
await this.backtest.getBacktestResult(
parseInt(req.body.ticker_interval),
req.body.hours,
req.body.strategy,
req.body.candle_period,
pair[0],
pair[1],
req.body.options ? JSON.parse(req.body.options) : {}
)
);
});
app.get('/tradingview/:symbol', (req, res) => {
res.render('../templates/tradingview.html.twig', {
symbol: this.buildTradingViewSymbol(req.params.symbol)
});
});
app.get('/signals', async (req, res) => {
res.render('../templates/signals.html.twig', {
signals: await this.signalHttp.getSignals(Math.floor(Date.now() / 1000) - 60 * 60 * 48)
});
});
app.get('/pairs', async (req, res) => {
res.render('../templates/pairs.html.twig', {
pairs: await this.pairsHttp.getTradePairs()
});
});
app.get('/logs', async (req, res) => {
res.render('../templates/logs.html.twig', await this.logsHttp.getLogsPageVariables(req, res));
});
app.get('/desks/:desk', async (req, res) => {
res.render('../templates/desks.html.twig', {
desk: this.systemUtil.getConfig('desks')[req.params.desk],
interval: req.query.interval || undefined,
id: req.params.desk
});
});
app.get('/tools/candles', async (req, res) => {
const options = {
pairs: await this.candleExportHttp.getPairs(),
start: moment()
.subtract(7, 'days')
.toDate(),
end: new Date()
};
if (req.query.pair && req.query.period && req.query.period && req.query.start && req.query.end) {
const [exchange, symbol] = req.query.pair.split('.');
const candles = await this.candleExportHttp.getCandles(
exchange,
symbol,
req.query.period,
new Date(req.query.start),
new Date(req.query.end)
);
if (req.query.metadata) {
candles.map(c => {
c.exchange = exchange;
c.symbol = symbol;
c.period = req.query.period;
return c;
});
}
options.start = new Date(req.query.start);
options.end = new Date(req.query.end);
options.exchange = exchange;
options.symbol = symbol;
options.period = req.query.period;
options.candles = candles;
options.candles_json = JSON.stringify(candles, null, 2);
}
res.render('../templates/candle_stick_export.html.twig', options);
});
app.post('/tools/candles', async (req, res) => {
const exchangeCandlesticks = JSON.parse(req.body.json);
await this.candleImporter.insertCandles(exchangeCandlesticks);
console.log(`Imported: ${exchangeCandlesticks.length} items`);
res.redirect('/tools/candles');
});
app.post('/pairs/:pair', async (req, res) => {
const pair = req.params.pair.split('-');
const { body } = req;
// exchange-ETC-FOO
// exchange-ETCFOO
const symbol = req.params.pair.substring(pair[0].length + 1);
await this.pairsHttp.triggerOrder(pair[0], symbol, body.action);
// simple sleep for async ui blocking for exchange communication
setTimeout(() => {
res.redirect('/pairs');
}, 800);
});
const { exchangeManager } = this;
app.get('/order/:exchange/:id', async (req, res) => {
const exchangeName = req.params.exchange;
const { id } = req.params;
const exchange = exchangeManager.get(exchangeName);
try {
await exchange.cancelOrder(id);
} catch (e) {
console.log(`Cancel order error: ${JSON.stringify([exchangeName, id, String(e)])}`);
}
res.redirect('/trades');
});
app.get('/orders', async (req, res) => {
res.render('../templates/orders/index.html.twig', {
pairs: this.ordersHttp.getPairs()
});
});
app.get('/orders/:pair', async (req, res) => {
const { pair } = req.params;
const tradingview = pair.split('.');
const ticker = this.ordersHttp.getTicker(pair);
res.render('../templates/orders/orders.html.twig', {
pair: pair,
pairs: this.ordersHttp.getPairs(),
orders: await this.ordersHttp.getOrders(pair),
position: await this.exchangeManager.getPosition(tradingview[0], tradingview[1]),
ticker: ticker,
tradingview: this.buildTradingViewSymbol(`${tradingview[0]}:${tradingview[1]}`),
form: {
price: ticker ? ticker.bid : undefined,
type: 'limit'
}
});
});
app.post('/orders/:pair', async (req, res) => {
const { pair } = req.params;
const tradingview = pair.split('.');
const ticker = this.ordersHttp.getTicker(pair);
const form = req.body;
let success = true;
let message;
let result;
try {
result = await this.ordersHttp.createOrder(pair, form);
message = JSON.stringify(result);
if (!result || result.shouldCancelOrderProcess()) {
success = false;
}
} catch (e) {
success = false;
message = String(e);
}
res.render('../templates/orders/orders.html.twig', {
pair: pair,
pairs: this.ordersHttp.getPairs(),
orders: await this.ordersHttp.getOrders(pair),
ticker: ticker,
position: await this.exchangeManager.getPosition(tradingview[0], tradingview[1]),
form: form,
tradingview: this.buildTradingViewSymbol(`${tradingview[0]}:${tradingview[1]}`),
alert: {
title: success ? 'Order Placed' : 'Place Error',
type: success ? 'success' : 'danger',
message: message
}
});
});
app.get('/orders/:pair/cancel/:id', async (req, res) => {
const foo = await this.ordersHttp.cancel(req.params.pair, req.params.id);
res.redirect(`/orders/${req.params.pair}`);
});
app.get('/orders/:pair/cancel-all', async (req, res) => {
await this.ordersHttp.cancelAll(req.params.pair);
res.redirect(`/orders/${req.params.pair}`);
});
app.get('/trades', async (req, res) => {
const positions = [];
const orders = [];
const exchanges = exchangeManager.all();
for (const key in exchanges) {
const exchange = exchanges[key];
const exchangeName = exchange.getName();
const myPositions = await exchange.getPositions();
myPositions.forEach(position => {
// simply converting of asset to currency value
let currencyValue;
if (
(exchangeName.includes('bitmex') && ['XBTUSD', 'ETHUSD'].includes(position.symbol)) ||
exchangeName.includes('bybit')
) {
// inverse exchanges
currencyValue = Math.abs(position.amount);
} else if (position.amount && position.entry) {
currencyValue = position.entry * Math.abs(position.amount);
}
positions.push({
exchange: exchangeName,
position: position,
currency: currencyValue
});
});
const myOrders = await exchange.getOrders();
myOrders.forEach(order => {
orders.push({
exchange: exchange.getName(),
order: order
});
});
}
res.render('../templates/trades.html.twig', {
orders: orders,
positions: positions.sort(
(a, b) =>
(!a.position.createdAt ? 0 : a.position.createdAt.getTime()) -
(!b.position.createdAt ? 0 : b.position.createdAt.getTime())
)
});
});
const ip = this.systemUtil.getConfig('webserver.ip', '0.0.0.0');
const port = this.systemUtil.getConfig('webserver.port', 8080);
app.listen(port, ip);
console.log(`Webserver listening on: ${ip}:${port}`);
}
/**
* Tricky way to normalize our tradingview views
*
* eg:
* - binance_futures:BTCUSDT => binance:BTCUSDTPERP
* - binance_margin:BTCUSDT => binance:BTCUSDT
* - coinbase_pro:BTC-USDT => coinbase:BTCUSDT
*
* @param symbol
* @returns {string}
*/
buildTradingViewSymbol(symbol) {
let mySymbol = symbol;
// binance:BTCUSDTPERP
if (mySymbol.includes('binance_futures')) {
mySymbol = mySymbol.replace('binance_futures', 'binance');
mySymbol += 'PERP';
}
return mySymbol
.replace('-', '')
.replace('coinbase_pro', 'coinbase')
.replace('binance_margin', 'binance')
.toUpperCase();
}
};
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2013 Marshall A. Greenblatt. 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 name Chromium Embedded
// Framework 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.
//
// ---------------------------------------------------------------------------
//
// The contents of this file must follow a specific format in order to
// support the CEF translator tool. See the translator.README.txt file in the
// tools directory for more information.
//
#ifndef CEF_INCLUDE_CEF_DRAG_HANDLER_H_
#define CEF_INCLUDE_CEF_DRAG_HANDLER_H_
#pragma once
#include "include/cef_base.h"
#include "include/cef_drag_data.h"
#include "include/cef_browser.h"
///
// Implement this interface to handle events related to dragging. The methods of
// this class will be called on the UI thread.
///
/*--cef(source=client)--*/
class CefDragHandler : public virtual CefBaseRefCounted {
public:
typedef cef_drag_operations_mask_t DragOperationsMask;
///
// Called when an external drag event enters the browser window. |dragData|
// contains the drag event data and |mask| represents the type of drag
// operation. Return false for default drag handling behavior or true to
// cancel the drag event.
///
/*--cef()--*/
virtual bool OnDragEnter(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefDragData> dragData,
DragOperationsMask mask) { return false; }
///
// Called whenever draggable regions for the browser window change. These can
// be specified using the '-webkit-app-region: drag/no-drag' CSS-property. If
// draggable regions are never defined in a document this method will also
// never be called. If the last draggable region is removed from a document
// this method will be called with an empty vector.
///
/*--cef()--*/
virtual void OnDraggableRegionsChanged(
CefRefPtr<CefBrowser> browser,
const std::vector<CefDraggableRegion>& regions) {}
};
#endif // CEF_INCLUDE_CEF_DRAG_HANDLER_H_
|
{
"pile_set_name": "Github"
}
|
#
#
# 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.
#
#
searching = Suchen...
|
{
"pile_set_name": "Github"
}
|
{
"scriptCategory": "tall",
"timeOfDayFormat": "H:mm",
"selectedRowCountTitleOne": "۱ مورد انتخاب شد",
"openAppDrawerTooltip": "باز کردن منوی پیمایش",
"backButtonTooltip": "برگشت",
"closeButtonTooltip": "بستن",
"deleteButtonTooltip": "حذف",
"nextMonthTooltip": "ماه بعد",
"previousMonthTooltip": "ماه قبل",
"nextPageTooltip": "صفحه بعد",
"previousPageTooltip": "صفحه قبل",
"showMenuTooltip": "نمایش منو",
"aboutListTileTitle": "درباره $applicationName",
"licensesPageTitle": "مجوزها",
"pageRowsInfoTitle": "$firstRow–$lastRow از $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow از حدود $rowCount",
"rowsPerPageTitle": "ردیف در هر صفحه:",
"tabLabel": "برگه $tabIndex از $tabCount",
"selectedRowCountTitleOther": "$selectedRowCount مورد انتخاب شدند",
"cancelButtonLabel": "لغو",
"closeButtonLabel": "بستن",
"continueButtonLabel": "ادامه",
"copyButtonLabel": "کپی",
"cutButtonLabel": "برش",
"okButtonLabel": "تأیید",
"pasteButtonLabel": "جایگذاری",
"selectAllButtonLabel": "انتخاب همه",
"viewLicensesButtonLabel": "مشاهده مجوزها",
"anteMeridiemAbbreviation": "ق.ظ.",
"postMeridiemAbbreviation": "ب.ظ.",
"timePickerHourModeAnnouncement": "انتخاب ساعت",
"timePickerMinuteModeAnnouncement": "انتخاب دقیقه",
"signedInLabel": "واردشده به سیستم",
"hideAccountsLabel": "پنهان کردن حسابها",
"showAccountsLabel": "نشان دادن حسابها",
"modalBarrierDismissLabel": "نپذیرفتن",
"drawerLabel": "منوی پیمایش",
"popupMenuLabel": "منوی بازشو",
"dialogLabel": "کادر گفتگو",
"alertDialogLabel": "هشدار",
"searchFieldLabel": "جستجو",
"reorderItemToStart": "انتقال به ابتدا",
"reorderItemToEnd": "انتقال به انتها",
"reorderItemUp": "انتقال به بالا",
"reorderItemDown": "انتقال به پایین",
"reorderItemLeft": "انتقال به راست",
"reorderItemRight": "انتقال به چپ",
"expandedIconTapHint": "کوچک کردن",
"collapsedIconTapHint": "بزرگ کردن",
"remainingTextFieldCharacterCountZero": "TBD",
"remainingTextFieldCharacterCountOne": "۱ نویسه باقی مانده است",
"remainingTextFieldCharacterCountOther": "$remainingCount نویسه باقی مانده است",
"refreshIndicatorSemanticLabel": "TBD",
"app_name": ""
}
|
{
"pile_set_name": "Github"
}
|
<!--
~ Copyright 2017 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.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="androidx.lifecycle.livedata">
</manifest>
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx
bundle install
# Do any other automated setup that you need to do here
|
{
"pile_set_name": "Github"
}
|
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the <dlfcn.h> header file. */
#undef HAVE_DLFCN_H
/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
#undef HAVE_FSEEKO
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#undef LT_OBJDIR
/* Name of package */
#undef PACKAGE
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the home page for this package. */
#undef PACKAGE_URL
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* The size of `void *', as computed by sizeof. */
#undef SIZEOF_VOID_P
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Version number of package */
#undef VERSION
/* Enable large inode numbers on Mac OS X 10.5. */
#ifndef _DARWIN_USE_64_BIT_INODE
# define _DARWIN_USE_64_BIT_INODE 1
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
#undef _FILE_OFFSET_BITS
/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
#undef _LARGEFILE_SOURCE
/* Define for large files, on AIX-style hosts. */
#undef _LARGE_FILES
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.http;
import org.yx.http.handler.WebContext;
public interface HttpEncryptor {
byte[] encrypt(byte[] data, WebContext ctx) throws Exception;
byte[] decrypt(byte[] data, WebContext ctx) throws Exception;
}
|
{
"pile_set_name": "Github"
}
|
Class {
#name : #RGTraitStrategyTest,
#superclass : #RGTest,
#category : #'Ring-Tests-Core'
}
{ #category : #tests }
RGTraitStrategyTest >> testClassVariablesString [
| anRGBehavior |
anRGBehavior := RGBehavior newTrait.
self assert: anRGBehavior classVariablesString equals: ''
]
{ #category : #tests }
RGTraitStrategyTest >> testCreationByMethod [
| anRGBehavior |
anRGBehavior := RGBehavior newTrait.
self assert: (anRGBehavior isBehavior).
self assert: (anRGBehavior behaviorStrategy isTraitStrategy).
]
{ #category : #tests }
RGTraitStrategyTest >> testIncompatibleBehavior [
| anRGBehavior |
anRGBehavior := RGBehavior newTrait.
self checkIncompatible: [
anRGBehavior instanceVariables: Array new ].
self checkIncompatible: [
anRGBehavior kindOfSubclass].
self checkIncompatible: [
anRGBehavior removeClassVariable: (RGClassVariable named: #ClassVar parent: anRGBehavior)].
self checkIncompatible: [
anRGBehavior removeSharedPool: (anRGBehavior environment ensureClassNamed: #SomeClass)].
self checkIncompatible: [
anRGBehavior sharedPoolsDo: [ :sharedPool | ] ].
self checkIncompatible: [
anRGBehavior defaultMetaClass ].
]
{ #category : #tests }
RGTraitStrategyTest >> testInstSize [
| anRGBehavior |
anRGBehavior := RGBehavior newTrait.
self assert: anRGBehavior instSize equals: 0
]
{ #category : #tests }
RGTraitStrategyTest >> testInstanceVariablesString [
| anRGBehavior |
anRGBehavior := RGBehavior newTrait.
self assert: anRGBehavior instanceVariablesString equals: ''
]
{ #category : #tests }
RGTraitStrategyTest >> testKind [
| strategy |
strategy := RGBehavior newTrait behaviorStrategy.
self deny: strategy isClassStrategy.
self deny: strategy isMetaclassStrategy.
self assert: strategy isTraitStrategy.
self deny: strategy isMetaclassTraitStrategy.
]
{ #category : #tests }
RGTraitStrategyTest >> testResolvingConsistency [
| anObject |
anObject := RGTrait unnamed behaviorStrategy.
self checkClassesConsistency: anObject and: anObject makeResolved
]
{ #category : #tests }
RGTraitStrategyTest >> testSharedPoolNames [
| anRGBehavior |
anRGBehavior := RGBehavior newTrait.
self assert: (anRGBehavior sharedPoolNames isEmpty).
]
{ #category : #tests }
RGTraitStrategyTest >> testSharedPools [
| anRGBehavior |
anRGBehavior := RGBehavior newTrait.
self assert: (anRGBehavior sharedPools isEmpty).
]
{ #category : #tests }
RGTraitStrategyTest >> testTrait [
| anRGBehavior |
anRGBehavior := RGBehavior newTrait.
self assert: anRGBehavior trait equals: anRGBehavior
]
|
{
"pile_set_name": "Github"
}
|
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Microsoft.DotNet.CodeFormatting
{
internal interface IFormattingFilter
{
bool ShouldBeProcessed(Document document);
}
}
|
{
"pile_set_name": "Github"
}
|
### 111. Minimum Depth of Binary Tree
题目:
<https://leetcode.com/problems/minimum-depth-of-binary-tree/>
难度:
Easy
思路,看完题目我想当然的认为就是直接递归取最小的值,代码如下:
```
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return 1 + min(map(self.minDepth, (root.left, root.right)))
```
但是没过,有一种特殊情况就是
注意```leaf node```反正就是没有```left```和```right```的
比如下图
```
1
\
2
```
```2```是一个孩子节点
这种情况应该输出```2```而不是```1```
唯一的特殊情况就是上面这种了,因为```root```下只有一个左节点或者是右节点,这样另外一边的空节点并不算是```leaf node```
```leaf node: itself is not null but it has both children null```
因此要避免这种情况,代码改成下面:
```python
# Definition for a binary tree node.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
depth_under_root = map(self.minDepth, (root.left, root.right))
return 1 + (min(depth_under_root) or max(depth_under_root))
```
所以还是要养成多写edge case的好习惯,也许就帮你避免了general写法的特例,代码如下
```python
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
elif root.left == None and root.right == None:
return 1
else :
if root.left == None:
return 1 + self.minDepth(root.right)
elif root.right == None:
return 1 + self.minDepth(root.left)
else:
return min(1+ self.minDepth(root.left), 1+ self.minDepth(root.right))
```
|
{
"pile_set_name": "Github"
}
|
# Copyright 2012 Mozilla Foundation
#
# 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.
# Main toolbar buttons (tooltips and alt text for images)
previous.title=পূর্ববর্তী পৃষ্ঠা
previous_label=পূর্ববর্তী
next.title=পরবর্তী পৃষ্ঠা
next_label=পরবর্তী
# LOCALIZATION NOTE (page.title): The tooltip for the pageNumber input.
page.title=পেজ
# LOCALIZATION NOTE (of_pages): "{{pagesCount}}" will be replaced by a number
# representing the total number of pages in the document.
of_pages={{pagesCount}}
# LOCALIZATION NOTE (page_of_pages): "{{pageNumber}}" and "{{pagesCount}}"
# will be replaced by a number representing the currently visible page,
# respectively a number representing the total number of pages in the document.
page_of_pages=({{pagesCount}} এর {{pageNumber}})
zoom_out.title=ছোট মাপে প্রদর্শন
zoom_out_label=ছোট মাপে প্রদর্শন
zoom_in.title=বড় মাপে প্রদর্শন
zoom_in_label=বড় মাপে প্রদর্শন
zoom.title=প্রদর্শনের মাপ
presentation_mode.title=উপস্থাপনা মোড স্যুইচ করুন
presentation_mode_label=উপস্থাপনা মোড
open_file.title=ফাইল খুলুন
open_file_label=খুলুন
print.title=প্রিন্ট করুন
print_label=প্রিন্ট করুন
download.title=ডাউনলোড করুন
download_label=ডাউনলোড করুন
bookmark.title=বর্তমান প্রদর্শন (কপি করুন অথবা নতুন উইন্ডোতে খুলুন)
bookmark_label=বর্তমান প্রদর্শন
# Secondary toolbar and context menu
tools.title=সরঞ্জাম
tools_label=সরঞ্জাম
first_page.title=প্রথম পৃষ্ঠায় চলুন
first_page.label=প্রথম পৃষ্ঠায় চলুন
first_page_label=প্রথম পৃষ্ঠায় চলুন
last_page.title=সর্বশেষ পৃষ্ঠায় চলুন
last_page.label=সর্বশেষ পৃষ্ঠায় চলুন
last_page_label=সর্বশেষ পৃষ্ঠায় চলুন
page_rotate_cw.title=ডানদিকে ঘোরানো হবে
page_rotate_cw.label=ডানদিকে ঘোরানো হবে
page_rotate_cw_label=ডানদিকে ঘোরানো হবে
page_rotate_ccw.title=বাঁদিকে ঘোরানো হবে
page_rotate_ccw.label=বাঁদিকে ঘোরানো হবে
page_rotate_ccw_label=বাঁদিকে ঘোরানো হবে
# Document properties dialog box
document_properties.title=নথির বৈশিষ্ট্য…
document_properties_label=নথির বৈশিষ্ট্য…
document_properties_file_name=ফাইলের নাম:
document_properties_file_size=ফাইলের মাপ:
# LOCALIZATION NOTE (document_properties_kb): "{{size_kb}}" and "{{size_b}}"
# will be replaced by the PDF file size in kilobytes, respectively in bytes.
document_properties_kb={{size_kb}} KB ({{size_b}} bytes)
# LOCALIZATION NOTE (document_properties_mb): "{{size_mb}}" and "{{size_b}}"
# will be replaced by the PDF file size in megabytes, respectively in bytes.
document_properties_mb={{size_mb}} মেগাবাইট ({{size_b}} bytes)
document_properties_title=শিরোনাম:
document_properties_author=লেখক:
document_properties_subject=বিষয়:
document_properties_keywords=নির্দেশক শব্দ:
document_properties_creation_date=নির্মাণের তারিখ:
document_properties_modification_date=পরিবর্তনের তারিখ:
# LOCALIZATION NOTE (document_properties_date_string): "{{date}}" and "{{time}}"
# will be replaced by the creation/modification date, and time, of the PDF file.
document_properties_date_string={{date}}, {{time}}
document_properties_creator=নির্মাতা:
document_properties_producer=PDF নির্মাতা:
document_properties_version=PDF সংস্করণ:
document_properties_page_count=মোট পৃষ্ঠা:
document_properties_close=বন্ধ করুন
print_progress_message=ডকুমেন্ট প্রিন্টিং-র জন্য তৈরি করা হচ্ছে...
# LOCALIZATION NOTE (print_progress_percent): "{{progress}}" will be replaced by
# a numerical per cent value.
print_progress_percent={{progress}}%
print_progress_close=বাতিল
# Tooltips and alt text for side panel toolbar buttons
# (the _label strings are alt text for the buttons, the .title strings are
# tooltips)
toggle_sidebar.title=সাইডবার টগল করুন
toggle_sidebar_label=সাইডবার টগল করুন
document_outline.title=ডকুমেন্ট আউটলাইন দেখান (দুবার ক্লিক করুন বাড়াতে//collapse সমস্ত আইটেম)
document_outline_label=ডকুমেন্ট আউটলাইন
attachments.title=সংযুক্তিসমূহ দেখান
attachments_label=সংযুক্ত বস্তু
thumbs.title=থাম্ব-নেইল প্রদর্শন
thumbs_label=থাম্ব-নেইল প্রদর্শন
findbar.title=নথিতে খুঁজুন
findbar_label=অনুসন্ধান করুন
# Thumbnails panel item (tooltip and alt text for images)
# LOCALIZATION NOTE (thumb_page_title): "{{page}}" will be replaced by the page
# number.
thumb_page_title=পৃষ্ঠা {{page}}
# LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page
# number.
thumb_page_canvas=পৃষ্ঠা {{page}}-র থাম্ব-নেইল
# Find panel button title and messages
find_previous.title=চিহ্নিত পংক্তির পূর্ববর্তী উপস্থিতি অনুসন্ধান করুন
find_previous_label=পূর্ববর্তী
find_next.title=চিহ্নিত পংক্তির পরবর্তী উপস্থিতি অনুসন্ধান করুন
find_next_label=পরবর্তী
find_highlight=সমগ্র উজ্জ্বল করুন
find_match_case_label=হরফের ছাঁদ মেলানো হবে
find_reached_top=পৃষ্ঠার প্রারম্ভে পৌছে গেছে, নীচের অংশ থেকে আরম্ভ করা হবে
find_reached_bottom=পৃষ্ঠার অন্তিম প্রান্তে পৌছে গেছে, প্রথম অংশ থেকে আরম্ভ করা হবে
find_not_found=পংক্তি পাওয়া যায়নি
# Error panel labels
error_more_info=অতিরিক্ত তথ্য
error_less_info=কম তথ্য
error_close=বন্ধ করুন
# LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be
# replaced by the PDF.JS version and build ID.
error_version_info=PDF.js v{{version}} (build: {{build}})
# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an
# english string describing the error.
error_message=Message: {{message}}
# LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack
# trace.
error_stack=Stack: {{stack}}
# LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename
error_file=File: {{file}}
# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number
error_line=Line: {{line}}
rendering_error=পৃষ্ঠা প্রদর্শনকালে একটি সমস্যা দেখা দিয়েছে।
# Predefined zoom values
page_scale_width=পৃষ্ঠার প্রস্থ অনুযায়ী
page_scale_fit=পৃষ্ঠার মাপ অনুযায়ী
page_scale_auto=স্বয়ংক্রিয় মাপ নির্ধারণ
page_scale_actual=প্রকৃত মাপ
# LOCALIZATION NOTE (page_scale_percent): "{{scale}}" will be replaced by a
# numerical scale value.
page_scale_percent={{scale}}%
# Loading indicator messages
loading_error_indicator=ত্রুটি
loading_error=PDF লোড করার সময় সমস্যা দেখা দিয়েছে।
invalid_file_error=অবৈধ বা ক্ষতিগ্রস্ত পিডিএফ ফাইল।
missing_file_error=অনুপস্থিত PDF ফাইল
unexpected_response_error=সার্ভার থেকে অপ্রত্যাশিত সাড়া পাওয়া গেছে।
# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.
# "{{type}}" will be replaced with an annotation type from a list defined in
# the PDF spec (32000-1:2008 Table 169 – Annotation types).
# Some common types are e.g.: "Check", "Text", "Comment", "Note"
text_annotation_type.alt=[{{type}} Annotation]
password_label=এই PDF ফাইল খোলার জন্য পাসওয়ার্ড দিন।
password_invalid=পাসওয়ার্ড সঠিক নয়। অনুগ্রহ করে পুনরায় প্রচেষ্টা করুন।
password_ok=OK
password_cancel=বাতিল করুন
printing_not_supported=সতর্কবার্তা: এই ব্রাউজার দ্বারা প্রিন্ট ব্যবস্থা সম্পূর্ণরূপে সমর্থিত নয়।
printing_not_ready=সতর্কবাণী: পিডিএফ সম্পূর্ণরূপে মুদ্রণের জন্য লোড করা হয় না.
web_fonts_disabled=ওয়েব ফন্ট নিষ্ক্রিয় করা হয়েছে: এমবেডেড পিডিএফ ফন্ট ব্যবহার করতে অক্ষম.
document_colors_not_allowed=পিডিএফ নথি তাদের নিজস্ব রং ব্যবহার করার জন্য অনুমতিপ্রাপ্ত নয়: ব্রাউজারে নিষ্ক্রিয় করা হয়েছে য়েন 'পেজ তাদের নিজস্ব রং নির্বাচন করার অনুমতি প্রদান করা য়ায়।'
|
{
"pile_set_name": "Github"
}
|
#!/bin/bash
#
# Test missed IP addresses on Botscout API.
#
# Get leanmail hits,
# exclude them from Fail2ban bans,
# extract IP addresses,
# check Botscout API
sed -n -e 's|.*leanmail: .* (\(.*\)) .*|\1|p' /var/log/syslog \
| grep -vFw -f - /var/log/fail2ban.log \
| grep -o '\b[0-9.]\{7,15\}\b' | sort -n -u \
| xargs -I % wget -q -O- "http://botscout.com/test/?ip=%"
|
{
"pile_set_name": "Github"
}
|
//
// JasonAgentAction.h
// Jasonette
//
// Copyright © 2017 Jasonette. All rights reserved.
//
#import "JasonAction.h"
@interface JasonAgentAction : JasonAction
@end
|
{
"pile_set_name": "Github"
}
|
#pragma once
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.
#ifdef __cplusplus
extern "C" {
#endif
typedef void (WINAPI *PFN_GETSYSTEMTIME)(
__out SYSTEMTIME *pst
);
HRESULT __stdcall TestHookOverrideUserDatabasePath(
__in_z LPCWSTR wzNewUserDatabasePath
);
HRESULT __stdcall TestHookOverrideAdminDatabasePath(
__in_z LPCWSTR wzNewAdminDatabasePath
);
HRESULT __stdcall TestHookOverrideArpPath(
__in_z LPCWSTR wzNewArpPath
);
HRESULT __stdcall TestHookOverrideApplicationsPath(
__in_z LPCWSTR wzNewApplicationsPath
);
HRESULT __stdcall TestHookOverrideGetSystemTime(
__in PFN_GETSYSTEMTIME systemTimeGetter
);
#ifdef __cplusplus
}
#endif
|
{
"pile_set_name": "Github"
}
|
// Copyright 2017 The Ray 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.
#pragma once
/// The definitions of metrics that you can use everywhere.
///
/// There are 4 types of metric:
/// Histogram: Histogram distribution of metric points.
/// Gauge: Keeps the last recorded value, drops everything before.
/// Count: The count of the number of metric points.
/// Sum: A sum up of the metric points.
///
/// You can follow these examples to define your metrics.
///
/// Common
///
static Histogram RedisLatency("redis_latency", "The latency of a Redis operation.", "us",
{100, 200, 300, 400, 500, 600, 700, 800, 900, 1000},
{CustomKey});
///
/// Raylet Metrics
///
static Gauge CurrentWorker("current_worker",
"This metric is used for reporting states of workers."
"Through this, we can see the worker's state on dashboard.",
"1 pcs", {LanguageKey, WorkerPidKey});
static Gauge CurrentDriver("current_driver",
"This metric is used for reporting states of drivers.",
"1 pcs", {LanguageKey, DriverPidKey});
static Count TaskCountReceived("task_count_received",
"Number of tasks received by raylet.", "pcs", {});
static Gauge LocalAvailableResource("local_available_resource",
"The available resources on this node.", "pcs",
{ResourceNameKey});
static Gauge LocalTotalResource("local_total_resource",
"The total resources on this node.", "pcs",
{ResourceNameKey});
static Gauge LiveActors("live_actors", "Number of live actors.", "actors");
static Gauge RestartingActors("restarting_actors", "Number of restarting actors.",
"actors");
static Gauge DeadActors("dead_actors", "Number of dead actors.", "actors");
static Gauge ObjectStoreAvailableMemory(
"object_store_available_memory",
"Amount of memory currently available in the object store.", "bytes");
static Gauge ObjectStoreUsedMemory(
"object_store_used_memory",
"Amount of memory currently occupied in the object store.", "bytes");
static Gauge ObjectStoreLocalObjects("object_store_num_local_objects",
"Number of objects currently in the object store.",
"objects");
static Gauge ObjectManagerWaitRequests("object_manager_num_wait_requests",
"Number of pending wait requests for objects.",
"requests");
static Gauge ObjectManagerPullRequests("object_manager_num_pull_requests",
"Number of active pull requests for objects.",
"requests");
static Gauge ObjectManagerUnfulfilledPushRequests(
"object_manager_unfulfilled_push_requests",
"Number of unfulfilled push requests for objects.", "requests");
static Gauge ObjectManagerProfileEvents("object_manager_num_buffered_profile_events",
"Number of locally-buffered profile events.",
"events");
static Gauge NumSubscribedTasks(
"num_subscribed_tasks",
"The number of tasks that are subscribed to object dependencies.", "tasks");
static Gauge NumRequiredTasks("num_required_tasks",
"The number of tasks whose output object(s) are "
"required by another subscribed task.",
"tasks");
static Gauge NumRequiredObjects(
"num_required_objects",
"The number of objects that are required by a subscribed task.", "objects");
static Gauge NumPendingTasks("num_pending_tasks",
"The number of tasks that are pending execution.", "tasks");
static Gauge NumPlaceableTasks(
"num_placeable_tasks",
"The number of tasks in the scheduler that are in the 'placeable' state.", "tasks");
static Gauge NumWaitingTasks(
"num_waiting_tasks",
"The number of tasks in the scheduler that are in the 'waiting' state.", "tasks");
static Gauge NumReadyTasks(
"num_ready_tasks",
"The number of tasks in the scheduler that are in the 'ready' state.", "tasks");
static Gauge NumRunningTasks(
"num_running_tasks",
"The number of tasks in the scheduler that are in the 'running' state.", "tasks");
static Gauge NumInfeasibleTasks(
"num_infeasible_tasks",
"The number of tasks in the scheduler that are in the 'infeasible' state.", "tasks");
|
{
"pile_set_name": "Github"
}
|
#
# clamav config files
#
install(
FILES
${CMAKE_CURRENT_SOURCE_DIR}/clamd.conf.sample
DESTINATION
${APP_CONFIG_DIRECTORY})
install(
FILES
${CMAKE_CURRENT_SOURCE_DIR}/freshclam.conf.sample
DESTINATION
${APP_CONFIG_DIRECTORY})
|
{
"pile_set_name": "Github"
}
|
# Taipei Metro (TRTC) station ID lists
`scrape_stationlist.py` is adapted from a shell script that appeared in the article [FuzzySecurity: EasyCard - Reverse Engineering an RFID payment system](http://www.fuzzysecurity.com/tutorials/rfid/4.html).
Data from the TRTC website:
* `stations_zh.csv`: https://web.metro.taipei/c/selectstation2010.asp
* `stations_en.csv`: https://web.metro.taipei/e/selectstation2010.asp
`scrape_stationlist.py` takes in these pages from stdin, and emits a CSV file of station IDs on stdout. A copy of the output is included in the repository for reference.
See also: [TRTC Open Data statement](https://english.metro.taipei/News_Content.aspx?n=784C655A49D3CD9D&sms=5E019B60E5224755&s=DCAD7B1493733FEC)
|
{
"pile_set_name": "Github"
}
|
from pyecharts import options as opts
from pyecharts.charts import Polar
from pyecharts.faker import Faker
c = (
Polar()
.add_schema(angleaxis_opts=opts.AngleAxisOpts(data=Faker.week, type_="category"))
.add("A", [1, 2, 3, 4, 3, 5, 1], type_="bar", stack="stack0")
.add("B", [2, 4, 6, 1, 2, 3, 1], type_="bar", stack="stack0")
.add("C", [1, 2, 3, 4, 1, 2, 5], type_="bar", stack="stack0")
.set_global_opts(title_opts=opts.TitleOpts(title="Polar-AngleAxis"))
.render("polar_angleaxis.html")
)
|
{
"pile_set_name": "Github"
}
|
/***************************************************************************
* Copyright (c) 2016 WandererFan <[email protected]> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#include <assert.h>
//#include <QGraphicsScene>
//#include <QGraphicsSceneHoverEvent>
//#include <QMouseEvent>
#include <QPainter>
#include <QPainterPathStroker>
#include <QStyleOptionGraphicsItem>
#endif
#include <App/Application.h>
#include <App/Material.h>
#include <Base/Console.h>
#include <Base/Parameter.h>
#include "Rez.h"
#include "PreferencesGui.h"
#include "ZVALUE.h"
#include "DrawGuiUtil.h"
#include "QGICMark.h"
#include "QGIDecoration.h"
using namespace TechDrawGui;
using namespace TechDraw;
QGIDecoration::QGIDecoration() :
m_colCurrent(Qt::black),
m_styleCurrent(Qt::SolidLine),
m_brushCurrent(Qt::SolidPattern)
{
setCacheMode(QGraphicsItem::NoCache);
setAcceptHoverEvents(false);
setFlag(QGraphicsItem::ItemIsSelectable, false);
setFlag(QGraphicsItem::ItemIsMovable, false);
setFlag(QGraphicsItem::ItemSendsGeometryChanges,true);
setWidth(1.0);
}
void QGIDecoration::draw()
{
}
void QGIDecoration::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) {
QStyleOptionGraphicsItem myOption(*option);
myOption.state &= ~QStyle::State_Selected;
QGraphicsItemGroup::paint (painter, &myOption, widget);
}
void QGIDecoration::setWidth(double w)
{
m_width = w;
m_pen.setWidthF(m_width);
}
void QGIDecoration::setStyle(Qt::PenStyle s)
{
m_styleCurrent = s;
m_pen.setStyle(m_styleCurrent);
}
void QGIDecoration::setColor(QColor c)
{
m_colNormal = c;
m_colCurrent = c;
m_pen.setColor(m_colCurrent);
m_brush.setColor(m_colCurrent);
}
QColor QGIDecoration::prefNormalColor()
{
return PreferencesGui::normalQColor();
}
QColor QGIDecoration::prefPreColor()
{
return PreferencesGui::preselectQColor();
}
QColor QGIDecoration::prefSelectColor()
{
return PreferencesGui::selectQColor();
}
QRectF QGIDecoration::boundingRect() const
{
return childrenBoundingRect();
}
void QGIDecoration::makeMark(double x, double y)
{
QGICMark* cmItem = new QGICMark(-1);
cmItem->setParentItem(this);
cmItem->setPos(x,y);
cmItem->setThick(2.0);
cmItem->setSize(40.0);
cmItem->setZValue(ZVALUE::VERTEX);
}
void QGIDecoration::makeMark(Base::Vector3d v)
{
makeMark(v.x,v.y);
}
|
{
"pile_set_name": "Github"
}
|
/* keyedit.h - Edit properties of a key
* Copyright (C) 1998-2010 Free Software Foundation, Inc.
* Copyright (C) 1998-2017 Werner Koch
* Copyright (C) 2015-2017 g10 Code GmbH
*
* This file is part of GnuPG.
*
* GnuPG 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 3 of the License, or
* (at your option) any later version.
*
* GnuPG 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 this program; if not, see <https://www.gnu.org/licenses/>.
*/
#ifndef GNUPG_G10_KEYEDIT_H
#define GNUPG_G10_KEYEDIT_H
#define NODFLG_BADSIG (1<<0) /* Bad signature. */
#define NODFLG_NOKEY (1<<1) /* No public key. */
#define NODFLG_SIGERR (1<<2) /* Other sig error. */
#define NODFLG_MARK_A (1<<4) /* Temporary mark. */
#define NODFLG_DELSIG (1<<5) /* To be deleted. */
#define NODFLG_SELUID (1<<8) /* Indicate the selected userid. */
#define NODFLG_SELKEY (1<<9) /* Indicate the selected key. */
#define NODFLG_SELSIG (1<<10) /* Indicate a selected signature. */
/*-- keyedit.c --*/
void keyedit_menu (ctrl_t ctrl, const char *username, strlist_t locusr,
strlist_t commands, int quiet, int seckey_check );
void keyedit_passwd (ctrl_t ctrl, const char *username);
void keyedit_quick_adduid (ctrl_t ctrl, const char *username,
const char *newuid);
void keyedit_quick_addkey (ctrl_t ctrl, const char *fpr, const char *algostr,
const char *usagestr, const char *expirestr);
void keyedit_quick_revuid (ctrl_t ctrl, const char *username,
const char *uidtorev);
void keyedit_quick_sign (ctrl_t ctrl, const char *fpr,
strlist_t uids, strlist_t locusr, int local);
void keyedit_quick_set_expire (ctrl_t ctrl,
const char *fpr, const char *expirestr,
char **subkeyfprs);
void keyedit_quick_set_primary (ctrl_t ctrl, const char *username,
const char *primaryuid);
void show_basic_key_info (ctrl_t ctrl, kbnode_t keyblock, int print_sec);
int keyedit_print_one_sig (ctrl_t ctrl, estream_t fp,
int rc, kbnode_t keyblock,
kbnode_t node, int *inv_sigs, int *no_key,
int *oth_err, int is_selfsig,
int print_without_key, int extended);
#endif /* GNUPG_G10_KEYEDIT_H */
|
{
"pile_set_name": "Github"
}
|
import buble from 'rollup-plugin-buble';
export default {
entry: 'src/index.js',
moduleName: 'acorn',
plugins: [ buble() ],
targets: [
{ dest: 'dist/acorn.js', format: 'umd' },
{ dest: 'dist/acorn.es.js', format: 'es' }
]
};
|
{
"pile_set_name": "Github"
}
|
// 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 swag contains a bunch of helper functions for go-openapi and go-swagger projects.
You may also use it standalone for your projects.
* convert between value and pointers for builtin types
* convert from string to builtin types (wraps strconv)
* fast json concatenation
* search in path
* load from file or http
* name mangling
This repo has only few dependencies outside of the standard library:
* YAML utilities depend on gopkg.in/yaml.v2
*/
package swag
|
{
"pile_set_name": "Github"
}
|
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": {
"0": "上午",
"1": "下午"
},
"DAY": {
"0": "星期日",
"1": "星期一",
"2": "星期二",
"3": "星期三",
"4": "星期四",
"5": "星期五",
"6": "星期六"
},
"MONTH": {
"0": "1月",
"1": "2月",
"2": "3月",
"3": "4月",
"4": "5月",
"5": "6月",
"6": "7月",
"7": "8月",
"8": "9月",
"9": "10月",
"10": "11月",
"11": "12月"
},
"SHORTDAY": {
"0": "週日",
"1": "週一",
"2": "週二",
"3": "週三",
"4": "週四",
"5": "週五",
"6": "週六"
},
"SHORTMONTH": {
"0": "1月",
"1": "2月",
"2": "3月",
"3": "4月",
"4": "5月",
"5": "6月",
"6": "7月",
"7": "8月",
"8": "9月",
"9": "10月",
"10": "11月",
"11": "12月"
},
"fullDate": "y年M月d日EEEE",
"longDate": "y年M月d日",
"medium": "yyyy/M/d ah:mm:ss",
"mediumDate": "yyyy/M/d",
"mediumTime": "ah:mm:ss",
"short": "y/M/d ah:mm",
"shortDate": "y/M/d",
"shortTime": "ah:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "NT$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": {
"0": {
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
"1": {
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00A4-",
"negSuf": "",
"posPre": "\u00A4",
"posSuf": ""
}
}
},
"id": "zh-tw",
"pluralCat": function (n) { return PLURAL_CATEGORY.OTHER;}
});
}]);
|
{
"pile_set_name": "Github"
}
|
const webpack = require("webpack");
const path = require("path");
const generateWebpackConfig = require("../webpack.config.js").default;
const utils = require("./utils");
const SUPPRESS = require('argparse').Const.SUPPRESS;
const addParser = (parser) => {
const description = `Build the client source code bundle.
For development, you may want to use "auspice develop" which recompiles code on the fly as changes are made.
You may provide customisations (e.g. code, options) to this step to modify the functionality and appearance of auspice.
To serve the bundle you will need a server such as "auspice view".
`;
const subparser = parser.addParser('build', {addHelp: true, description});
subparser.addArgument('--verbose', {action: "storeTrue", help: "Print more verbose progress messages."});
subparser.addArgument('--extend', {action: "store", metavar: "JSON", help: "Build-time customisations to be applied. See documentation for more details."});
const testing = subparser.addArgumentGroup({title: "Testing options"});
testing.addArgument('--analyzeBundle', {action: "storeTrue", help: "Load an interactive bundle analyzer tool to investigate the composition of produced bundles / chunks."});
testing.addArgument('--includeTiming', {action: "storeTrue", help: "Do not strip timing functions. With these included the browser console will print timing measurements for a number of functions."});
/* there are some options which we deliberately do not document via `--help` */
/* timing options can be left in -- these are hardcoded in the source code and (normally) removed at build-time. Keeping these is useful for profiling performance. */
/* serverless or "static site production" functionality is for a future release (auspice v3 ?!?) */
subparser.addArgument('--serverless', {action: "storeTrue", help: SUPPRESS});
};
const run = (args) => {
/* webpack set up */
const extensionPath = args.extend ? path.resolve(args.extend) : undefined;
const customOutputPath = utils.customOutputPath(args.extend);
const webpackConfig = generateWebpackConfig({extensionPath, devMode: false, customOutputPath, analyzeBundle: args.analyzeBundle});
const compiler = webpack(webpackConfig);
/* variables available to babel (which is called by webpack) */
process.env.BABEL_INCLUDE_TIMING_FUNCTIONS = args.includeTiming;
process.env.BABEL_ENV = "production";
process.env.BABEL_EXTENSION_PATH = extensionPath;
utils.log("Running webpack compiler");
compiler.run((err, stats) => {
if (err) {
console.error(err);
return;
}
if (stats.hasErrors()) {
console.log(stats.toString({colors: true}));
utils.error("Webpack built with errors. Exiting.");
} else {
if (stats.hasWarnings()) {
utils.warn("Webpack has warnings (run with '--verbose' to see them)");
}
if (global.AUSPICE_VERBOSE) {
console.log(stats.toString({colors: true}));
}
if (customOutputPath) {
utils.exportIndexDotHtml({relative: args.serverless});
}
}
});
};
module.exports = {
addParser,
run
};
|
{
"pile_set_name": "Github"
}
|
/*
* Author: Garrett Barboza <[email protected]>
*
* Copyright (c) 2014 Kaprica Security, Inc.
*
* 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.
*
*/
#include "libcgc.h"
int cgc_memcmp(const char *s1, const char *s2, cgc_size_t n)
{
cgc_size_t i;
for(i = 0; i < n; i++)
if (*s1 != *s2)
return *s1 - *s2;
else
s1++, s2++;
return 0;
}
|
{
"pile_set_name": "Github"
}
|
using UnityEngine;
using System.Collections;
namespace VoxelBusters.NativePlugins
{
public class MIMEType : MonoBehaviour
{
public const string kPDF = "application/pdf";
public const string kPNG = "image/png";
public const string kJPEG = "image/jpeg";
}
}
|
{
"pile_set_name": "Github"
}
|
- type: entity
id: Arcade
name: arcade
parent: ComputerBase
components:
- type: PowerReceiver
- type: Sprite
layers:
- state: arcade
map: ["enum.ComputerVisualizer+Layers.Body"]
- state: invaders
shader: unshaded
map: ["enum.ComputerVisualizer+Layers.Screen"]
- type: Appearance
visuals:
- type: ComputerVisualizer
screen: invaders
key: ""
body: arcade
bodyBroken: arcade
- type: Anchorable
- type: Pullable
- type: SpaceVillainArcade
- type: Wires
BoardName: "Arcade"
- type: UserInterface
interfaces:
- key: enum.SpaceVillainArcadeUiKey.Key
type: SpaceVillainArcadeBoundUserInterface
- key: enum.WiresUiKey.Key
type: WiresBoundUserInterface
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 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.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
v1beta1 "k8s.io/api/admissionregistration/v1beta1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
)
// FakeValidatingWebhookConfigurations implements ValidatingWebhookConfigurationInterface
type FakeValidatingWebhookConfigurations struct {
Fake *FakeAdmissionregistrationV1beta1
}
var validatingwebhookconfigurationsResource = schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "validatingwebhookconfigurations"}
var validatingwebhookconfigurationsKind = schema.GroupVersionKind{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "ValidatingWebhookConfiguration"}
// Get takes name of the validatingWebhookConfiguration, and returns the corresponding validatingWebhookConfiguration object, and an error if there is any.
func (c *FakeValidatingWebhookConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootGetAction(validatingwebhookconfigurationsResource, name), &v1beta1.ValidatingWebhookConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.ValidatingWebhookConfiguration), err
}
// List takes label and field selectors, and returns the list of ValidatingWebhookConfigurations that match those selectors.
func (c *FakeValidatingWebhookConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ValidatingWebhookConfigurationList, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootListAction(validatingwebhookconfigurationsResource, validatingwebhookconfigurationsKind, opts), &v1beta1.ValidatingWebhookConfigurationList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1beta1.ValidatingWebhookConfigurationList{ListMeta: obj.(*v1beta1.ValidatingWebhookConfigurationList).ListMeta}
for _, item := range obj.(*v1beta1.ValidatingWebhookConfigurationList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested validatingWebhookConfigurations.
func (c *FakeValidatingWebhookConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewRootWatchAction(validatingwebhookconfigurationsResource, opts))
}
// Create takes the representation of a validatingWebhookConfiguration and creates it. Returns the server's representation of the validatingWebhookConfiguration, and an error, if there is any.
func (c *FakeValidatingWebhookConfigurations) Create(ctx context.Context, validatingWebhookConfiguration *v1beta1.ValidatingWebhookConfiguration, opts v1.CreateOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootCreateAction(validatingwebhookconfigurationsResource, validatingWebhookConfiguration), &v1beta1.ValidatingWebhookConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.ValidatingWebhookConfiguration), err
}
// Update takes the representation of a validatingWebhookConfiguration and updates it. Returns the server's representation of the validatingWebhookConfiguration, and an error, if there is any.
func (c *FakeValidatingWebhookConfigurations) Update(ctx context.Context, validatingWebhookConfiguration *v1beta1.ValidatingWebhookConfiguration, opts v1.UpdateOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateAction(validatingwebhookconfigurationsResource, validatingWebhookConfiguration), &v1beta1.ValidatingWebhookConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.ValidatingWebhookConfiguration), err
}
// Delete takes name of the validatingWebhookConfiguration and deletes it. Returns an error if one occurs.
func (c *FakeValidatingWebhookConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewRootDeleteAction(validatingwebhookconfigurationsResource, name), &v1beta1.ValidatingWebhookConfiguration{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeValidatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
action := testing.NewRootDeleteCollectionAction(validatingwebhookconfigurationsResource, listOpts)
_, err := c.Fake.Invokes(action, &v1beta1.ValidatingWebhookConfigurationList{})
return err
}
// Patch applies the patch and returns the patched validatingWebhookConfiguration.
func (c *FakeValidatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ValidatingWebhookConfiguration, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(validatingwebhookconfigurationsResource, name, pt, data, subresources...), &v1beta1.ValidatingWebhookConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.ValidatingWebhookConfiguration), err
}
|
{
"pile_set_name": "Github"
}
|
[38;5;202;01mimport[39;00m[38;5;15m [39m [38;5;32m"github.com/mgutz/logxi/v1"[39m
[38;5;202;01mfunc[39;00m[38;5;15m [39m[38;5;15mloadConfig[39m[38;5;15m([39m[38;5;15m)[39m[38;5;15m [39m[38;5;15m{[39m
[38;5;15m [39m[38;5;15mlogger[39m[38;5;15m.[39m[38;5;15mError[39m[38;5;15m([39m[38;5;32m"Could not read config file"[39m[38;5;15m,[39m[38;5;15m [39m[38;5;32m"err"[39m[38;5;15m,[39m[38;5;15m [39m[38;5;15merrConfig[39m[38;5;15m)[39m
[38;5;15m}[39m
[38;5;202;01mfunc[39;00m[38;5;15m [39m[38;5;15mmain[39m[38;5;15m([39m[38;5;15m)[39m[38;5;15m [39m[38;5;15m{[39m
[38;5;15m [39m[38;5;28;48;5;233m// create loggers[39;49m
[38;5;15m [39m[38;5;15mlog[39m[38;5;15m.[39m[38;5;15mTrace[39m[38;5;15m([39m[38;5;32m"creating loggers"[39m[38;5;15m)[39m
[38;5;15m [39m[38;5;15mlogger[39m[38;5;15m [39m[38;5;15m=[39m[38;5;15m [39m[38;5;15mlog[39m[38;5;15m.[39m[38;5;15mNew[39m[38;5;15m([39m[38;5;32m"server"[39m[38;5;15m)[39m
[38;5;15m [39m[38;5;15mmodelsLogger[39m[38;5;15m [39m[38;5;15m:=[39m[38;5;15m [39m[38;5;15mlog[39m[38;5;15m.[39m[38;5;15mNew[39m[38;5;15m([39m[38;5;32m"models"[39m[38;5;15m)[39m
[38;5;15m [39m[38;5;15mlogger[39m[38;5;15m.[39m[38;5;15mDebug[39m[38;5;15m([39m[38;5;32m"Process"[39m[38;5;15m,[39m[38;5;15m [39m[38;5;32m"hostname"[39m[38;5;15m,[39m[38;5;15m [39m[38;5;15mhostname[39m[38;5;15m,[39m[38;5;15m [39m[38;5;32m"pid"[39m[38;5;15m,[39m[38;5;15m [39m[38;5;15mos[39m[38;5;15m.[39m[38;5;15mGetpid[39m[38;5;15m([39m[38;5;15m)[39m[38;5;15m)[39m
[38;5;15m [39m[38;5;15mmodelsLogger[39m[38;5;15m.[39m[38;5;15mInfo[39m[38;5;15m([39m[38;5;32m"Connecting to database..."[39m[38;5;15m)[39m
[38;5;15m [39m[38;5;15mmodelsLogger[39m[38;5;15m.[39m[38;5;15mWarn[39m[38;5;15m([39m[38;5;32m"Could not connect, retrying ..."[39m[38;5;15m,[39m[38;5;15m [39m[38;5;32m"dsn"[39m[38;5;15m,[39m[38;5;15m [39m[38;5;15mdsn[39m[38;5;15m)[39m
[38;5;15m [39m[38;5;15mloadConfig[39m[38;5;15m([39m[38;5;15m)[39m
[38;5;15m}[39m
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE root [
<!-- SGML-ism: exception spec -->
<!ELEMENT footnote (para*) -footnote>
]>
<root/>
|
{
"pile_set_name": "Github"
}
|
.forced-gc-warning {
background-color: $yellow-lightest;
padding: 1em;
bottom: 0;
left: 0;
width: 100%;
box-shadow: 0 -1px 3px #ccc;
border-right: 1px solid #ddd;
p {
line-height: 1.5 !important;
}
a.code-link {
&>code {
color: #1079c3;
background: #f7f7f7;
}
&:hover, &:focus, &:active {
text-decoration: none;
&>code {
background-color: #e5f1f6;
text-decoration: none;
}
}
}
code {
background-color: #f9f2f4;
color: #c7254e;
border-radius: 2px;
letter-spacing: 0.5px;
padding: 2px 4px;
}
>.gc-expando {
display: none;
&.expanded {
display: block;
padding-bottom: 1em;
.fa-times {
float: right;
font-size: 16px;
}
}
}
.gc-status {
color: #888;
border-bottom: 1px dotted;
}
>.gc-status-bar {
.status-text {
float: right;
}
>.total-time {
>i {
margin-right: .3em;
}
}
}
.clickable {
cursor: pointer;
opacity: .7;
&:hover {
opacity: 1;
}
}
}
|
{
"pile_set_name": "Github"
}
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant::Config.run do |config|
config.vm.box = "ec2-precise64"
config.vm.box_url = "https://s3.amazonaws.com/mediacore-public/boxes/ec2-precise64.box"
config.vm.provision :shell, :path => "Vagrantfile.sh"
end
|
{
"pile_set_name": "Github"
}
|
// Copyright 2013 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.
#ifndef CONTENT_RENDERER_INDEXED_DB_INDEXED_DB_DISPATCHER_H_
#define CONTENT_RENDERER_INDEXED_DB_INDEXED_DB_DISPATCHER_H_
#include <stddef.h>
#include <stdint.h>
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/strings/nullable_string16.h"
#include "content/common/content_export.h"
#include "content/common/indexed_db/indexed_db_constants.h"
#include "content/public/renderer/worker_thread.h"
#include "content/renderer/indexed_db/indexed_db_callbacks_impl.h"
#include "content/renderer/indexed_db/indexed_db_database_callbacks_impl.h"
#include "ipc/ipc_sync_message_filter.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
#include "url/origin.h"
namespace content {
class WebIDBCursorImpl;
// Handle the indexed db related communication for this context thread - the
// main thread and each worker thread have their own copies.
class CONTENT_EXPORT IndexedDBDispatcher : public WorkerThread::Observer {
public:
// Constructor made public to allow RenderThreadImpl to own a copy without
// failing a NOTREACHED in ThreadSpecificInstance in tests that instantiate
// two copies of RenderThreadImpl on the same thread. Everyone else probably
// wants to use ThreadSpecificInstance().
IndexedDBDispatcher();
~IndexedDBDispatcher() override;
static IndexedDBDispatcher* ThreadSpecificInstance();
// WorkerThread::Observer implementation.
void WillStopCurrentWorkerThread() override;
void RegisterCursor(WebIDBCursorImpl* cursor);
void UnregisterCursor(WebIDBCursorImpl* cursor);
// Reset cursor prefetch caches for all cursors except exception_cursor.
void ResetCursorPrefetchCaches(int64_t transaction_id,
WebIDBCursorImpl* exception_cursor);
void RegisterMojoOwnedCallbacks(
IndexedDBCallbacksImpl::InternalState* callback_state);
void UnregisterMojoOwnedCallbacks(
IndexedDBCallbacksImpl::InternalState* callback_state);
void RegisterMojoOwnedDatabaseCallbacks(
blink::WebIDBDatabaseCallbacks* callback_state);
void UnregisterMojoOwnedDatabaseCallbacks(
blink::WebIDBDatabaseCallbacks* callback_state);
private:
FRIEND_TEST_ALL_PREFIXES(IndexedDBDispatcherTest, CursorReset);
FRIEND_TEST_ALL_PREFIXES(IndexedDBDispatcherTest, CursorTransactionId);
// Looking up move-only entries in an std::unordered_set and removing them
// with out freeing them seems to be impossible so use a map instead so that
// the key type can remain a raw pointer.
using CallbackStateSet = std::unordered_map<
IndexedDBCallbacksImpl::InternalState*,
std::unique_ptr<IndexedDBCallbacksImpl::InternalState>>;
using DatabaseCallbackStateSet =
std::unordered_map<blink::WebIDBDatabaseCallbacks*,
std::unique_ptr<blink::WebIDBDatabaseCallbacks>>;
std::unordered_set<WebIDBCursorImpl*> cursors_;
// Holds pointers to the worker-thread owned state of IndexedDBCallbacksImpl
// and IndexedDBDatabaseCallbacksImpl objects to makes sure that it is
// destroyed on thread exit if the Mojo pipe is not yet closed. Otherwise the
// object will leak because the thread's task runner is no longer executing
// tasks.
CallbackStateSet mojo_owned_callback_state_;
DatabaseCallbackStateSet mojo_owned_database_callback_state_;
bool in_destructor_ = false;
DISALLOW_COPY_AND_ASSIGN(IndexedDBDispatcher);
};
} // namespace content
#endif // CONTENT_RENDERER_INDEXED_DB_INDEXED_DB_DISPATCHER_H_
|
{
"pile_set_name": "Github"
}
|
//
// UITableViewCell+LCCKCellIdentifier.h
// LCCKChatBarExample
//
// v0.7.10 Created by ElonChan (微信向我报BUG:chenyilong1010) ( https://github.com/leancloud/ChatKit-OC ) on 15/11/23.
// Copyright © 2015年 https://LeanCloud.cn . All rights reserved.
//
@import UIKit;
@import Foundation;
#import "LCCKChatMessageCell.h"
@interface LCCKCellIdentifierFactory : NSObject
/**
* 用来获取cellIdentifier
*/
+ (NSString *)cellIdentifierForMessageConfiguration:(id)message conversationType:(LCCKConversationType)conversationType;
@end
|
{
"pile_set_name": "Github"
}
|
好奇心原文链接:[又一家服装公司要上市,这回是欧时力的母公司_商业_好奇心日报-董芷菲 ](https://www.qdaily.com/articles/30078.html)
WebArchive归档链接:[又一家服装公司要上市,这回是欧时力的母公司_商业_好奇心日报-董芷菲 ](http://web.archive.org/web/20190623181437/https://www.qdaily.com/articles/30078.html)

|
{
"pile_set_name": "Github"
}
|
- Material Design
- [概述](material-design/material-design-intro/introduction.md)
- 什么是 Material
- [环境](material-design/whatis-material-design/environment.md)
- [Material 属性](material-design/whatis-material-design/material-properties.md)
- [高度和阴影](material-design/whatis-material-design/elevation-shadows.md)
- 动画
- [真实的动作](material-design/animation/authentic-motion.md)
- [响应式交互](material-design/animation/responsive-interaction.md)
- [有意义的转场动画](material-design/animation/meaningful-transitions.md)
- [打动用户的细节](material-design/animation/delightful-details.md)
- 样式
- [色彩](material-design/style/color.md)
- [字体排版](material-design/style/typography.md)
- [图标](material-design/style/icons.md)
- [图像](material-design/style/imagery.md)
- [书写](material-design/style/writing.md)
- 布局
- [准则](material-design/layout/layout-principles.md)
- [单位和度量](material-design/layout/units-measurements.md)
- [度量与边框](material-design/layout/metrics-and-keylines.md)
- [结构](material-design/layout/structure.md)
- [自适应 UI](material-design/layout/adaptive-ui.md)
- 组件
- [底部动作条](material-design/components/bottom-sheets.md)
- [按钮](material-design/components/buttons.md)
- [按钮:浮动操作按钮](material-design/components/buttons-floating-action-button.md)
- [卡片](material-design/components/cards.md)
- [纸片](material-design/components/chips.md)
- [数据表格](material-design/components/data-tables.md)
- [提示框](material-design/components/dialogs.md)
- [分隔线](material-design/components/dividers.md)
- [网格](material-design/components/grids.md)
- [列表](material-design/components/lists.md)
- [列表控制](material-design/components/list-controls.md)
- [菜单](material-design/components/menus.md)
- [选择器](material-design/components/pickers.md)
- [进度和动态](material-design/components/progress-activity.md)
- [选择控制](material-design/components/selection-controls.md)
- [滑块](material-design/components/sliders.md)
- [Snackbars 与 Toasts](material-design/components/snackbars-and-toasts.md)
- [副标题](material-design/components/subheaders.md)
- [开关](material-design/components/switches.md)
- [Tabs](material-design/components/tabs.md)
- [文本框](material-design/components/text-fields.md)
- [工具提示](material-design/components/tooltips.md)
- 模式
- [App 结构](material-design/patterns/app-structure.md)
- [数据格式](material-design/patterns/data-formats.md)
- [空状态](material-design/patterns/empty-states.md)
- [错误](material-design/patterns/errors.md)
- [内容选取](material-design/patterns/selection.md)
- [手势](material-design/patterns/gestures.md)
- [启动屏幕](material-design/patterns/launch-screens.md)
- [加载图像](material-design/patterns/loading-images.md)
- [抽屉式导航](material-design/patterns/navigation-drawer.md)
- [导航](material-design/patterns/navigation.md)
- [导航过渡](material-design/patterns/navigational-transitions.md)
- [滚动技巧](material-design/patterns/scrolling-techniques.md)
- [改进的操作](material-design/patterns/promoted-actions.md)
- [设置](material-design/patterns/settings.md)
- [影像处理](material-design/patterns/imagery-treatment.md)
- [搜索](material-design/patterns/search.md)
- [刷新](material-design/patterns/swipe-to-refresh.md)
- 可用性
- [可达性](material-design/usability/accessibility.md)
- [双向性](material-design/usability/bidirectionality.md)
- 资源
- [布局模板](material-design/resources/layout-templates.md)
- [设备](material-design/resources/devices.md)
- [贴片集](material-design/resources/sticker-sheets.md)
- [Roboto 字体](material-design/resources/roboto-font.md)
- [调色板](material-design/resources/color-palettes.md)
- What’s New
- [更新记录](material-design/whats-new/whats-new.md)
|
{
"pile_set_name": "Github"
}
|
//
// AppAgentManagerForMac.m
// AppAgent
//
// Created by Makara Khloth on 3/23/15.
//
//
#import "AppAgentManagerForMac.h"
#import "EventDelegate.h"
#import "FxSystemEvent.h"
#import "FxEventEnums.h"
#import "DateTimeFormat.h"
#import "DiskSpaceWarningAgent.h"
#import "ExceptionHandleAgent.h"
@interface AppAgentManagerForMac (PrivateAPI)
- (void) sendSystemEventForLowDiskSpace: (NSString *) aDiskspaceLevelTex;
- (void) sendSystemEventFor: (FxSystemEventType) aEventType message: (NSString *) aMessage;
- (void) diskSpaceWarningDidReceived: (NSNotification *) aNotification;
- (void) exceptionNotificationReceived: (NSNotification *) aNotification;
@end
@implementation AppAgentManagerForMac
@synthesize mEventDelegate;
- (id) init {
if ((self = [super init])) {
// Disk space
mDiskSpaceWarningAgent = [[DiskSpaceWarningAgent alloc] init];
mListeningDiskSpaceWarning = FALSE;
// Signal/Exception
// note that we need to register this notification before the init of mExceptionHandleAgent because
// the init method of mExceptionHandleAgent will post notification to check if there is a previous crash or not
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(exceptionNotificationReceived:)
name:CRASH_REPORT_NOTIFICATION
object:nil];
mExceptionHandleAgent = [[ExceptionHandleAgent alloc] init];
mListeningException = FALSE;
}
return self;
}
#pragma mark - Event delegate -
- (void) registerEventDelegate: (id <EventDelegate>) aEventDelegate {
self.mEventDelegate = aEventDelegate;
}
- (void) unregisterEventDelegate {
self.mEventDelegate = nil;
}
- (void) startCapture {
[self startHandleUncaughtException];
[self startListenDiskSpaceWarningLevel];
}
- (void) stopCapture {
[self stopHandleUncaughtException];
[self stopListenDiskSpaceWarningLevel];
}
#pragma mark -
#pragma mark Disk Space
- (void) startListenDiskSpaceWarningLevel {
//DLog(@"startListenDiskSpaceWarningLevel")
if (!mListeningDiskSpaceWarning) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(diskSpaceWarningDidReceived:)
name:NSDiskSpaceWarningLevelNotification
object:nil];
[mDiskSpaceWarningAgent startListenToDiskSpaceWarningLevelNotification];
mListeningDiskSpaceWarning = TRUE;
}
}
- (void) stopListenDiskSpaceWarningLevel {
if (mListeningDiskSpaceWarning) {
[mDiskSpaceWarningAgent stopListenToDiskSpaceWarningLevelNotification];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSDiskSpaceWarningLevelNotification
object:nil];
mListeningDiskSpaceWarning = FALSE;
}
}
- (void) diskSpaceWarningDidReceived: (NSNotification *) aNotification {
//DLog(@"AppAgentManager --> diskSpaceWarningDidReceived: main thread ? %d", [NSThread isMainThread]);
//DLog(@"AppAgentManager --> diskSpaceWarningDidReceived: !!!!! DISK SPACE WARNNING LEVEL: %@ !!!!! ", [aNotification object]);
NSDictionary *diskspaceInfo = (NSDictionary *)[aNotification object];
NSString *diskspaceLevelText = [diskspaceInfo objectForKey:DISK_SPACE_LEVEL_STRING_KEY];
[self sendSystemEventForLowDiskSpace:diskspaceLevelText];
}
- (void) sendSystemEventForLowDiskSpace: (NSString *) aDiskspaceLevelText {
[self sendSystemEventFor:kSystemEventTypeDiskInfo
message:[NSString stringWithFormat:@"%@%@", @"Disk space level: ", aDiskspaceLevelText]];
}
- (BOOL) setThresholdInMegabyteForDiskSpaceCriticalLevel: (uint64_t) aValue {
return [mDiskSpaceWarningAgent setDiskSpaceThresholdForLevel:DiskSpaceNotificationLevelCritical valueInMegaByte:aValue];
}
- (BOOL) setThresholdInMegabyteForDiskSpaceUrgentLevel: (uint64_t) aValue {
return [mDiskSpaceWarningAgent setDiskSpaceThresholdForLevel:DiskSpaceNotificationLevelUrgent valueInMegaByte:aValue];
}
- (BOOL) setThresholdInMegabyteForDiskSpaceWarningLevel: (uint64_t) aValue {
return [mDiskSpaceWarningAgent setDiskSpaceThresholdForLevel:DiskSpaceNotificationLevelWarning valueInMegaByte:aValue];
}
#pragma mark -
#pragma mark Exception handler
- (void) startHandleUncaughtException {
if (!mListeningException) {
[mExceptionHandleAgent installExceptionHandler];
}
}
- (void) stopHandleUncaughtException {
if (mListeningException) {
[mExceptionHandleAgent uninstallExceptionHandler];
}
}
- (void) exceptionNotificationReceived: (NSNotification *) aNotification {
//DLog(@"AppAgentManager --> exceptionNotificationReceived: >>>>>>>>>>>>>>>>>> %@ <<<<<<<<<<<<<<<<<<<<< ", [aNotification object]);
NSDictionary *crashInfo = (NSDictionary *)[aNotification object];
NSNumber *crashType = [crashInfo objectForKey:CRASH_TYPE_KEY];
NSString *log = [crashInfo objectForKey:CRASH_REPORT_KEY];
if ([crashType integerValue] == CRASH_TYPE_EXCEPTION) {
[self sendSystemEventFor:kSystemEventTypeAppCrash message:log];
} else if ([crashType integerValue] == CRASH_TYPE_SIGNAL) {
[self sendSystemEventFor:kSystemEventTypeAppCrash message:log];
}
}
#pragma mark -
#pragma mark System Event
- (void) sendSystemEventFor: (FxSystemEventType) aEventType message: (NSString *) aMessage {
DLog(@"sending system event")
FxSystemEvent *systemEvent = [[FxSystemEvent alloc] init];
[systemEvent setMessage:[NSString stringWithString:aMessage]];
[systemEvent setDirection:kEventDirectionOut];
[systemEvent setSystemEventType:aEventType];
[systemEvent setDateTime:[DateTimeFormat phoenixDateTime]];
if ([mEventDelegate respondsToSelector:@selector(eventFinished:)]) {
[mEventDelegate performSelector:@selector(eventFinished:) withObject:systemEvent withObject:self];
}
[systemEvent release];
}
- (void) dealloc {
DLog (@"Application agent manager is dealloced...");
[[NSNotificationCenter defaultCenter] removeObserver:self
name:CRASH_REPORT_NOTIFICATION
object:nil];
[self stopHandleUncaughtException];
[mExceptionHandleAgent release];
mExceptionHandleAgent = nil;
[self stopListenDiskSpaceWarningLevel]; // To invalidate otherwise it won't call dealloc
[mDiskSpaceWarningAgent release];
mDiskSpaceWarningAgent = nil;
[super dealloc];
}
@end
|
{
"pile_set_name": "Github"
}
|
import { useRouter } from "next/router";
import Link from "next/link";
const Show = ({ show }) => {
const router = useRouter();
// This is never shown on Netlify. We just need it for NextJS to be happy,
// because NextJS will render a fallback HTML page.
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<div>
<p>This page uses getStaticProps() to pre-fetch a TV show.</p>
<hr />
<h1>Show #{show.id}</h1>
<p>{show.name}</p>
<hr />
<Link href="/">
<a>Go back home</a>
</Link>
</div>
);
};
export async function getStaticPaths() {
// Set the paths we want to pre-render
const paths = [{ params: { id: "3" } }, { params: { id: "4" } }];
// We'll pre-render these paths at build time.
// { fallback: true } means other routes will be rendered at runtime.
return { paths, fallback: true };
}
export async function getStaticProps({ params }) {
// The ID to render
const { id } = params;
const res = await fetch(`https://api.tvmaze.com/shows/${id}`);
const data = await res.json();
return {
props: {
show: data,
},
};
}
export default Show;
|
{
"pile_set_name": "Github"
}
|
package xyz.gianlu.librespot.metadata;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author Gianlu
*/
public interface SpotifyId {
String STATIC_FROM_URI = "fromUri";
String STATIC_FROM_BASE62 = "fromBase62";
String STATIC_FROM_HEX = "fromHex";
@NotNull
static <I extends SpotifyId> I fromBase62(Class<I> clazz, String base62) throws SpotifyIdParsingException {
return callReflection(clazz, STATIC_FROM_BASE62, base62);
}
@NotNull
static <I extends SpotifyId> I fromHex(Class<I> clazz, String hex) throws SpotifyIdParsingException {
return callReflection(clazz, STATIC_FROM_HEX, hex);
}
@NotNull
static <I extends SpotifyId> I fromUri(Class<I> clazz, String uri) throws SpotifyIdParsingException {
return callReflection(clazz, STATIC_FROM_URI, uri);
}
@SuppressWarnings("unchecked")
@NotNull
static <I extends SpotifyId> I callReflection(@NotNull Class<I> clazz, @NotNull String name, @NotNull String arg) throws SpotifyIdParsingException {
try {
Method method = clazz.getDeclaredMethod(name, String.class);
return (I) method.invoke(null, arg);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
throw new SpotifyIdParsingException(ex);
}
}
@NotNull String toSpotifyUri();
class SpotifyIdParsingException extends Exception {
SpotifyIdParsingException(Throwable cause) {
super(cause);
}
}
}
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "CDStructures.h"
#import <IDEKit/IDEActivityReporter.h>
@class DVTObservingToken;
@interface IDECleanBuildFolderActivityReporter : IDEActivityReporter
{
DVTObservingToken *_isCleaningObserver;
}
+ (void)initialize;
- (void)primitiveInvalidate;
- (id)initWithWorkspace:(id)arg1;
- (void)updateActivityReports;
- (id)completionSummaryStringSegments;
@end
|
{
"pile_set_name": "Github"
}
|
From - Tue Jul 14 17:00:52 2009
X-Account-Key: account2
X-UIDL: UID6215-1201487268
X-Mozilla-Status: 0001
X-Mozilla-Status2: 00000000
X-Mozilla-Keys:
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from mail3.csmining.org (localhost [127.0.0.1])
by mail3.csmining.org (csminingorg Mail) with ESMTP id 4B4F82C21B
for <[email protected]>; Tue, 14 Jul 2009 16:51:38 +0900 (JST)
Received: from spamgw.csmining.org (spamgw.csmining.org [192.168.18.120])
by mail3.csmining.org (csminingorg Mail) with ESMTP id 47962512F
for <[email protected]>; Tue, 14 Jul 2009 16:51:38 +0900 (JST)
X-ASG-Debug-ID: 1247557897-3703002e0000-W4TwRL
X-Barracuda-URL: http://spamgw.csmining.org:8000/cgi-bin/mark.cgi
X-Barracuda-Connect: gw2.csmining.org[192.168.18.251]
X-Barracuda-Start-Time: 1247557897
Received: from gw2.csmining.org (gw2.csmining.org [192.168.18.251])
by spamgw.csmining.org Firewall) with SMTP id A90116B9DE5
for <[email protected]>; Tue, 14 Jul 2009 16:51:37 +0900 (JST)
Received: from gw2.csmining.org (localhost [127.0.0.1])
by gw2.csmining.org with ESMTP id n6E7pbio021973
for <[email protected]>; Tue, 14 Jul 2009 16:51:37 +0900 (JST)
Received: from ns2.csmining.org (ns2.csmining.org [192.168.3.2])
by gw2.csmining.org with ESMTP id n6E7pbCn021970
for <[email protected]>; Tue, 14 Jul 2009 16:51:37 +0900 (JST)
Received: from BTNL-TN-DSL-static-144.0.144.59.airtelbroadband.in (BTNL-TN-DSL-static-144.0.144.59.airtelbroadband.in [59.144.0.144] (may be forged))
by ns2.csmining.org with ESMTP id n6E7pXLO019006
for <[email protected]>; Tue, 14 Jul 2009 16:51:35 +0900 (JST)
Message-ID: <1312KCV.82192E0FD.81686506215OCAIDZSOEMHZONL5455@BTNL-TN-DSL-static-144.0.144.59.airtelbroadband.in>
MIME-Version: 1.0
Content-type: text/html; charset="utf-8"
From: "Gabriele Ewoc" <[email protected]>
To: [email protected]
X-ASG-Orig-Subj: Internal audit issue
Subject: [SPAM] Internal audit issue
Date: Tue, 14 Jul 2009 13:21:19 +05-30
Content-Transfer-Encoding: quoted-printable
X-MIME-Autoconverted: from 8bit to quoted-printable by gw2.csmining.org id n6E7pbio021973
X-Barracuda-Virus-Scanned: by csminingorg Anti-SPAM System at csmining.org
X-ASG-Tag: BRL ([<http://www.barracuda.com/reputation?ip=59.144.0.144>])
X-Barracuda-Spam-Score: 11.20
X-Barracuda-Spam-Status: No, SCORE=11.20 using per-user scores of TAG_LEVEL=1000.0 QUARANTINE_LEVEL=1000.0 KILL_LEVEL=1000.0
X-Barracuda-Spam-Report: Code version 3.1, rules version 3.1.90054
Rule breakdown below
pts rule name description
---- ---------------------- --------------------------------------------------
3.50 BARRACUDA_HEADER_FP20 RBL: Barracuda Reputation
[<http://www.barracuda.com/reputation?ip=59.144.0.144>]
0.01 INVALID_DATE Invalid Date: header (not RFC 2822)
1.66 HELO_DYNAMIC_DHCP Relay HELO'd using suspicious hostname (DHCP)
2.01 DATE_IN_FUTURE_03_06 Date: is 3 to 6 hours after Received: date
0.00 HTML_MESSAGE BODY: HTML included in message
0.26 HTML_FONT_BIG BODY: HTML tag for a big font size
0.00 MIME_HTML_ONLY BODY: Message only has text/html MIME parts
1.76 INVALID_DATE_2 Invalid Date: header (not RFC 2822)
0.50 BSF_SC0_SA_TO_FROM_ADDR_MATCH Sender Address Matches Recipient
Address
1.00 BSF_SC0_SA392f Custom Rule SA392f
4.00 BSF_SC0_SA392_HL Custom Rule SA392_HL
X-Barracuda-Spam-Flag: YES
X-BitDefenderWKS-SpamStamp: v1, build 2.8.21.72663, whitelisted,
total: 0(725)
X-BitDefenderWKS-Spam: No - 0
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><TITLE>Today's HOT News</TITLE>
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DUTF-8"=
>
<style type=3D"text/css">
<!--
img.NoBorder { border-width: 0px 0px 0px 0px; }
a.Menu1{ font-family:"Arial"; font-size:10.0pt; }
p.nw {line-height: 120%;margin:0pt; margin-bottom:0pt; margin-top:4pt; m=
argin-left: 0pt;
font-size:11.0pt;font-family:"Arial";
padding-left: 0.5cm;}
p.f10 {font-size:10.0pt;font-family:"Arial";}
-->
</style>
</head>
<BODY VLINK=3Dblack style=3D"margin-top: 3pt;">
<p align=3Dcenter >
<br>
<A class=3D"Menu1" href=3D"http://a61.aisqdoho.cn/cezonol.cgi?italjo=3Da=
61ccb2e0fd5d2ad980a">
<span style=3D"color: #808080">Home</span></A><span style=3D"color: #808=
080">
</span>
<a class=3D"Menu1" href=3D"http://191.aisqdoho.cn/jmjlef.cgi?avegolaru=3D=
a61ccb2e0fd5d2ad980a">
<span style=3D"color: #808080">Yesterday's News</span></a><span style=3D=
"color: #808080">
</span>
<A class=3D"Menu1" href=3D"http://191.aisqdoho.cn/yzuryeihqn.cgi?qboew=3D=
a61ccb2e0fd5d2ad980a">
<span style=3D"color: #808080">Site Search</span></A><span style=3D"colo=
r: #808080">
</span>
<A class=3D"Menu1" href=3D"http://191.aisqdoho.cn/uieky.cgi?rjjkopa=3Da6=
1ccb2e0fd5d2ad980a">
<span style=3D"color: #808080">Calendar</span></A><span style=3D"color: =
#808080">
</span><A class=3D"Menu1" href=3D"http://191.aisqdoho.cn/qgedal.cgi?tetu=
nqxuti=3Da61ccb2e0fd5d2ad980a">
<span style=3D"color: #808080">Contact Us</span></A><span style=3D"color=
: #808080">
</span>
<a class=3D"Menu1" href=3D"http://191.aisqdoho.cn/erqhino.cgi?ykytiv=3Da=
61ccb2e0fd5d2ad980a">
<span style=3D"color: #808080">Subscribe</span></a><span style=3D"color:=
#808080">
</span>
<a class=3D"Menu1" href=3D"http://191.aisqdoho.cn/damewqve.cgi?hqeomimqv=
=3Da61ccb2e0fd5d2ad980a" target=3D_blank>
<span style=3D"color: #808080">Advertise</span></a><span style=3D"color:=
#808080">
</span>
</p>
<HR>
<p align=3Dcenter>
<span style=3D"font-family: Arial; font-size:14.0pt">
Today=92s News - July 14, 2009 </span>
</p>
<p align=3Dcenter>
<span style=3D"font-family: Arial; font-size:9.0pt;">To view this newsle=
tter in your web browser,
<a href=3D"http://191.aisqdoho.cn/agjdutqbq.cgi?ugiimygu=3Da61ccb2e0fd5d=
2ad980a">click here.</a>
</span>
<p style=3D"text-align: center">
<a style=3D"font-size:24px; color:#CC3300" href=3D"http://191.aisqdoho.c=
n/yxjwaouq.cgi?mjdjoufi=3Da61ccb2e0fd5d2ad980a">
<img src=3D"http://images.aisqdoho.cn/spacer.gif" alt=3D"Click here to s=
how disabled image" style=3D"border-width: 0px"></a><hr>
<p class=3D"f10" align=3Dcenter>(c) 2009 Ofuqfemjsqfy Inc., 5 N Public =
Sq Cartersville, GA 30120 , USA.</p>
<P style=3D"text-align: center"><A href=3D"http://a61.aisqdoho.cn/zezajk=
ali.cgi?uxupituuva=3Da61ccb2e0fd5d2ad980a">
<span style=3D"color: #669900">Unsubscribe</span></A><span style=3D"colo=
r: #669900">
| </span><a href=3D"http://191.aisqdoho.cn/ehebqno.cgi?iqqwy=3Da61ccb2e0=
fd5d2ad980a"><span style=3D"color: #669900">Subscribe</span></a><span sty=
le=3D"color: #669900">
| </span><a href=3D"http://191.aisqdoho.cn/aolor.cgi?lukapj=3Da61ccb2e0f=
d5d2ad980a"><span style=3D"color: #669900">Privacy
Policy</span></a><span style=3D"color: #669900"> | </span>
<a href=3D"http://191.aisqdoho.cn/liuri.cgi?fjzqee=3Da61ccb2e0fd5d2ad980=
a"><span style=3D"color: #669900">About us</span></a></P>
</BODY></html>
|
{
"pile_set_name": "Github"
}
|
# SPDX-License-Identifier: GPL-2.0
#
# Makefile for memory devices
#
obj-$(CONFIG_DDR) += jedec_ddr_data.o
ifeq ($(CONFIG_DDR),y)
obj-$(CONFIG_OF) += of_memory.o
endif
obj-$(CONFIG_ARM_PL172_MPMC) += pl172.o
obj-$(CONFIG_ATMEL_SDRAMC) += atmel-sdramc.o
obj-$(CONFIG_ATMEL_EBI) += atmel-ebi.o
obj-$(CONFIG_ARCH_BRCMSTB) += brcmstb_dpfe.o
obj-$(CONFIG_TI_AEMIF) += ti-aemif.o
obj-$(CONFIG_TI_EMIF) += emif.o
obj-$(CONFIG_OMAP_GPMC) += omap-gpmc.o
obj-$(CONFIG_FSL_CORENET_CF) += fsl-corenet-cf.o
obj-$(CONFIG_FSL_IFC) += fsl_ifc.o
obj-$(CONFIG_MVEBU_DEVBUS) += mvebu-devbus.o
obj-$(CONFIG_JZ4780_NEMC) += jz4780-nemc.o
obj-$(CONFIG_MTK_SMI) += mtk-smi.o
obj-$(CONFIG_DA8XX_DDRCTL) += da8xx-ddrctl.o
obj-$(CONFIG_PL353_SMC) += pl353-smc.o
obj-$(CONFIG_SAMSUNG_MC) += samsung/
obj-$(CONFIG_TEGRA_MC) += tegra/
obj-$(CONFIG_TI_EMIF_SRAM) += ti-emif-sram.o
ti-emif-sram-objs := ti-emif-pm.o ti-emif-sram-pm.o
AFLAGS_ti-emif-sram-pm.o :=-Wa,-march=armv7-a
$(obj)/ti-emif-sram-pm.o: $(obj)/ti-emif-asm-offsets.h
$(obj)/ti-emif-asm-offsets.h: $(obj)/emif-asm-offsets.s FORCE
$(call filechk,offsets,__TI_EMIF_ASM_OFFSETS_H__)
targets += emif-asm-offsets.s
clean-files += ti-emif-asm-offsets.h
|
{
"pile_set_name": "Github"
}
|
////////////////////////////////////////////////////////////////////////////
// Module : alife_time_manager_inline.h
// Created : 05.01.2003
// Modified : 12.05.2004
// Author : Dmitriy Iassenev
// Description : ALife time manager class inline functions
////////////////////////////////////////////////////////////////////////////
#pragma once
IC void CALifeTimeManager::set_time_factor(float time_factor)
{
m_game_time = game_time();
m_start_time = Device.dwTimeGlobal;
m_time_factor = time_factor;
};
IC ALife::_TIME_ID CALifeTimeManager::start_game_time() const { return m_start_game_time; }
IC ALife::_TIME_ID CALifeTimeManager::game_time() const
{
return (m_game_time + ALife::_TIME_ID(m_time_factor * float(Device.dwTimeGlobal - m_start_time)));
};
IC float CALifeTimeManager::time_factor() const { return (m_time_factor); }
IC float CALifeTimeManager::normal_time_factor() const { return (m_normal_time_factor); }
IC void CALifeTimeManager::change_game_time(u32 value) { m_game_time += value; }
|
{
"pile_set_name": "Github"
}
|
# grpc
[gRPC](http://www.grpc.io/) is an excellent, modern IDL and transport for
microservices. If you're starting a greenfield project, go-kit strongly
recommends gRPC as your default transport.
One important note is that while gRPC supports streaming requests and replies,
go-kit does not. You can still use streams in your service, but their
implementation will not be able to take advantage of many go-kit features like middleware.
Using gRPC and go-kit together is very simple.
First, define your service using protobuf3. This is explained
[in gRPC documentation](http://www.grpc.io/docs/#defining-a-service).
See
[add.proto](https://github.com/go-kit/kit/blob/ec8b02591ee873433565a1ae9d317353412d1d27/examples/addsvc/pb/add.proto)
for an example. Make sure the proto definition matches your service's go-kit
(interface) definition.
Next, get the protoc compiler.
You can download pre-compiled binaries from the
[protobuf release page](https://github.com/google/protobuf/releases).
You will unzip a folder called `protoc3` with a subdirectory `bin` containing
an executable. Move that executable somewhere in your `$PATH` and you're good
to go!
It can also be built from source.
```sh
brew install autoconf automake libtool
git clone https://github.com/google/protobuf
cd protobuf
./autogen.sh ; ./configure ; make ; make install
```
Then, compile your service definition, from .proto to .go.
```sh
protoc add.proto --go_out=plugins=grpc:.
```
Finally, write a tiny binding from your service definition to the gRPC
definition. It's a simple conversion from one domain to another.
See
[grpc_binding.go](https://github.com/go-kit/kit/blob/ec8b02591ee873433565a1ae9d317353412d1d27/examples/addsvc/grpc_binding.go)
for an example.
That's it!
The gRPC binding can be bound to a listener and serve normal gRPC requests.
And within your service, you can use standard go-kit components and idioms.
See [addsvc](https://github.com/go-kit/kit/tree/master/examples/addsvc) for
a complete working example with gRPC support. And remember: go-kit services
can support multiple transports simultaneously.
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="Simulation Movement" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_count</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAI=</string> </persistent>
</value>
</item>
<item>
<key> <string>_mt_index</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAM=</string> </persistent>
</value>
</item>
<item>
<key> <string>_tree</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAQ=</string> </persistent>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
<tuple>
<string>trade_phase/default/invoicing</string>
<string>delivery_mode/air</string>
<string>causality/business_process_module/maxma_business_process/invoice_path</string>
<string>causality/business_process_module/maxma_business_process/invoice</string>
<string>source_section/organisation_module/myorganisation</string>
<string>incoterm/ddp</string>
<string>quantity_unit/unit/piece</string>
<string>destination/organisation_module/9</string>
<string>destination_decision/person_module/11</string>
<string>specialise/sale_trade_condition_module/1</string>
<string>source/organisation_module/myorganisation</string>
<string>source_decision/person_module/2</string>
<string>price_currency/currency_module/EUR</string>
<string>resource/product_module/7</string>
<string>destination_section/organisation_module/9</string>
<string>source_account/account_module/sales</string>
</tuple>
</value>
</item>
<item>
<key> <string>causality_state</string> </key>
<value> <string>expanded</string> </value>
</item>
<item>
<key> <string>description</string> </key>
<value> <string>Sale Order corresponding to coins delivery in May and July.</string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>1</string> </value>
</item>
<item>
<key> <string>last_id</string> </key>
<value> <string>2</string> </value>
</item>
<item>
<key> <string>portal_type</string> </key>
<value> <string>Simulation Movement</string> </value>
</item>
<item>
<key> <string>price</string> </key>
<value> <float>1.5</float> </value>
</item>
<item>
<key> <string>quantity</string> </key>
<value> <float>700.0</float> </value>
</item>
<item>
<key> <string>start_date</string> </key>
<value>
<object>
<klass>
<global id="1.1" name="DateTime" module="DateTime.DateTime"/>
</klass>
<tuple>
<none/>
</tuple>
<state>
<tuple>
<float>1281409200.0</float>
<string>GMT-3</string>
</tuple>
</state>
</object>
</value>
</item>
<item>
<key> <string>stop_date</string> </key>
<value>
<object>
<klass> <reference id="1.1"/> </klass>
<tuple>
<none/>
</tuple>
<state>
<tuple>
<float>1281409200.0</float>
<string>GMT-3</string>
</tuple>
</state>
</object>
</value>
</item>
</dictionary>
</pickle>
</record>
<record id="2" aka="AAAAAAAAAAI=">
<pickle>
<global name="Length" module="BTrees.Length"/>
</pickle>
<pickle> <int>0</int> </pickle>
</record>
<record id="3" aka="AAAAAAAAAAM=">
<pickle>
<global name="OOBTree" module="BTrees.OOBTree"/>
</pickle>
<pickle>
<none/>
</pickle>
</record>
<record id="4" aka="AAAAAAAAAAQ=">
<pickle>
<global name="OOBTree" module="BTrees.OOBTree"/>
</pickle>
<pickle>
<none/>
</pickle>
</record>
</ZopeData>
|
{
"pile_set_name": "Github"
}
|
/**
* @file utils.cpp
* @brief Mega SDK various utilities and helper classes
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega/utils.h"
#include "mega/logging.h"
#include "mega/megaclient.h"
#include "mega/base64.h"
#include "mega/serialize64.h"
#include "mega/filesystem.h"
#include <iomanip>
#if defined(_WIN32) && defined(_MSC_VER)
#include <sys/timeb.h>
#endif
#ifdef __APPLE__
#include <sys/sysctl.h>
#endif
namespace mega {
string toNodeHandle(handle nodeHandle)
{
char base64Handle[12];
Base64::btoa((byte*)&(nodeHandle), MegaClient::NODEHANDLE, base64Handle);
return string(base64Handle);
}
string toHandle(handle h)
{
char base64Handle[14];
Base64::btoa((byte*)&(h), sizeof h, base64Handle);
return string(base64Handle);
}
CacheableWriter::CacheableWriter(string& d)
: dest(d)
{
}
void CacheableWriter::serializebinary(byte* data, size_t len)
{
dest.append((char*)data, len);
}
void CacheableWriter::serializechunkmacs(const chunkmac_map& m)
{
m.serialize(dest);
}
void CacheableWriter::serializecstr(const char* field, bool storeNull)
{
unsigned short ll = (unsigned short)(field ? strlen(field) + (storeNull ? 1 : 0) : 0);
dest.append((char*)&ll, sizeof(ll));
dest.append(field, ll);
}
void CacheableWriter::serializepstr(const string* field)
{
unsigned short ll = (unsigned short)(field ? field->size() : 0);
dest.append((char*)&ll, sizeof(ll));
if (field) dest.append(field->data(), ll);
}
void CacheableWriter::serializestring(const string& field)
{
unsigned short ll = (unsigned short)field.size();
dest.append((char*)&ll, sizeof(ll));
dest.append(field.data(), ll);
}
void CacheableWriter::serializecompressed64(int64_t field)
{
byte buf[sizeof field+1];
dest.append((const char*)buf, Serialize64::serialize(buf, field));
}
void CacheableWriter::serializei64(int64_t field)
{
dest.append((char*)&field, sizeof(field));
}
void CacheableWriter::serializeu32(uint32_t field)
{
dest.append((char*)&field, sizeof(field));
}
void CacheableWriter::serializehandle(handle field)
{
dest.append((char*)&field, sizeof(field));
}
void CacheableWriter::serializenodehandle(handle field)
{
dest.append((const char*)&field, MegaClient::NODEHANDLE);
}
void CacheableWriter::serializefsfp(fsfp_t field)
{
dest.append((char*)&field, sizeof(field));
}
void CacheableWriter::serializebool(bool field)
{
dest.append((char*)&field, sizeof(field));
}
void CacheableWriter::serializebyte(byte field)
{
dest.append((char*)&field, sizeof(field));
}
void CacheableWriter::serializedouble(double field)
{
dest.append((char*)&field, sizeof(field));
}
void CacheableWriter::serializeexpansionflags(bool b0, bool b1, bool b2, bool b3, bool b4, bool b5, bool b6, bool b7)
{
unsigned char b[8];
b[0] = b0;
b[1] = b1;
b[2] = b2;
b[3] = b3;
b[4] = b4;
b[5] = b5;
b[6] = b6;
b[7] = b7;
dest.append((char*)b, 8);
}
CacheableReader::CacheableReader(const string& d)
: ptr(d.data())
, end(ptr + d.size())
, fieldnum(0)
{
}
void CacheableReader::eraseused(string& d)
{
assert(end == d.data() + d.size());
d.erase(0, ptr - d.data());
}
bool CacheableReader::unserializecstr(string& s, bool removeNull)
{
if (ptr + sizeof(unsigned short) > end)
{
return false;
}
unsigned short len = MemAccess::get<unsigned short>(ptr);
ptr += sizeof(len);
if (ptr + len > end)
{
return false;
}
if (len)
{
s.assign(ptr, len - (removeNull ? 1 : 0));
}
ptr += len;
fieldnum += 1;
return true;
}
bool CacheableReader::unserializestring(string& s)
{
if (ptr + sizeof(unsigned short) > end)
{
return false;
}
unsigned short len = MemAccess::get<unsigned short>(ptr);
ptr += sizeof(len);
if (ptr + len > end)
{
return false;
}
if (len)
{
s.assign(ptr, len);
}
ptr += len;
fieldnum += 1;
return true;
}
bool CacheableReader::unserializebinary(byte* data, size_t len)
{
if (ptr + len > end)
{
return false;
}
memcpy(data, ptr, len);
ptr += len;
fieldnum += 1;
return true;
}
void chunkmac_map::serialize(string& d) const
{
unsigned short ll = (unsigned short)size();
d.append((char*)&ll, sizeof(ll));
for (const_iterator it = begin(); it != end(); it++)
{
d.append((char*)&it->first, sizeof(it->first));
d.append((char*)&it->second, sizeof(it->second));
}
}
bool chunkmac_map::unserialize(const char*& ptr, const char* end)
{
unsigned short ll;
if ((ptr + sizeof(ll) > end) || ptr + (ll = MemAccess::get<unsigned short>(ptr)) * (sizeof(m_off_t) + sizeof(ChunkMAC)) + sizeof(ll) > end)
{
return false;
}
ptr += sizeof(ll);
for (int i = 0; i < ll; i++)
{
m_off_t pos = MemAccess::get<m_off_t>(ptr);
ptr += sizeof(m_off_t);
memcpy(&((*this)[pos]), ptr, sizeof(ChunkMAC));
ptr += sizeof(ChunkMAC);
}
return true;
}
void chunkmac_map::calcprogress(m_off_t size, m_off_t& chunkpos, m_off_t& progresscompleted, m_off_t* lastblockprogress)
{
chunkpos = 0;
progresscompleted = 0;
for (chunkmac_map::iterator it = begin(); it != end(); ++it)
{
m_off_t chunkceil = ChunkedHash::chunkceil(it->first, size);
if (chunkpos == it->first && it->second.finished)
{
chunkpos = chunkceil;
progresscompleted = chunkceil;
}
else if (it->second.finished)
{
m_off_t chunksize = chunkceil - ChunkedHash::chunkfloor(it->first);
progresscompleted += chunksize;
}
else
{
progresscompleted += it->second.offset;
if (lastblockprogress)
{
*lastblockprogress += it->second.offset;
}
}
}
}
m_off_t chunkmac_map::nextUnprocessedPosFrom(m_off_t pos)
{
for (const_iterator it = find(ChunkedHash::chunkfloor(pos));
it != end();
it = find(ChunkedHash::chunkfloor(pos)))
{
if (it->second.finished)
{
pos = ChunkedHash::chunkceil(pos);
}
else
{
pos += it->second.offset;
break;
}
}
return pos;
}
m_off_t chunkmac_map::expandUnprocessedPiece(m_off_t pos, m_off_t npos, m_off_t fileSize, m_off_t maxReqSize)
{
for (iterator it = find(npos);
npos < fileSize && (npos - pos) <= maxReqSize && (it == end() || (!it->second.finished && !it->second.offset));
it = find(npos))
{
npos = ChunkedHash::chunkceil(npos, fileSize);
}
return npos;
}
void chunkmac_map::finishedUploadChunks(chunkmac_map& macs)
{
for (auto& m : macs)
{
m.second.finished = true;
(*this)[m.first] = m.second;
LOG_verbose << "Upload chunk completed: " << m.first;
}
}
// coalesce block macs into file mac
int64_t chunkmac_map::macsmac(SymmCipher *cipher)
{
byte mac[SymmCipher::BLOCKSIZE] = { 0 };
for (chunkmac_map::iterator it = begin(); it != end(); it++)
{
assert(it->first == ChunkedHash::chunkfloor(it->first));
// LOG_debug << "macsmac input: " << it->first << ": " << Base64Str<sizeof it->second.mac>(it->second.mac);
SymmCipher::xorblock(it->second.mac, mac);
cipher->ecb_encrypt(mac);
}
uint32_t* m = (uint32_t*)mac;
m[0] ^= m[1];
m[1] = m[2] ^ m[3];
return MemAccess::get<int64_t>((const char*)mac);
}
bool CacheableReader::unserializechunkmacs(chunkmac_map& m)
{
if (m.unserialize(ptr, end)) // ptr is adjusted by reference
{
fieldnum += 1;
return true;
}
return false;
}
bool CacheableReader::unserializecompressed64(uint64_t& field)
{
int fieldSize;
if ((fieldSize = Serialize64::unserialize((byte*)ptr, static_cast<int>(end - ptr), &field)) < 0)
{
LOG_err << "Serialize64 unserialization failed - malformed field";
return false;
}
else
{
ptr += fieldSize;
}
return true;
}
bool CacheableReader::unserializei64(int64_t& field)
{
if (ptr + sizeof(int64_t) > end)
{
return false;
}
field = MemAccess::get<int64_t>(ptr);
ptr += sizeof(int64_t);
fieldnum += 1;
return true;
}
bool CacheableReader::unserializeu32(uint32_t& field)
{
if (ptr + sizeof(uint32_t) > end)
{
return false;
}
field = MemAccess::get<uint32_t>(ptr);
ptr += sizeof(uint32_t);
fieldnum += 1;
return true;
}
bool CacheableReader::unserializehandle(handle& field)
{
if (ptr + sizeof(handle) > end)
{
return false;
}
field = MemAccess::get<handle>(ptr);
ptr += sizeof(handle);
fieldnum += 1;
return true;
}
bool CacheableReader::unserializenodehandle(handle& field)
{
if (ptr + MegaClient::NODEHANDLE > end)
{
return false;
}
field = 0;
memcpy((char*)&field, ptr, MegaClient::NODEHANDLE);
ptr += MegaClient::NODEHANDLE;
fieldnum += 1;
return true;
}
bool CacheableReader::unserializefsfp(fsfp_t& field)
{
if (ptr + sizeof(fsfp_t) > end)
{
return false;
}
field = MemAccess::get<fsfp_t>(ptr);
ptr += sizeof(fsfp_t);
fieldnum += 1;
return true;
}
bool CacheableReader::unserializebool(bool& field)
{
if (ptr + sizeof(bool) > end)
{
return false;
}
field = MemAccess::get<bool>(ptr);
ptr += sizeof(bool);
fieldnum += 1;
return true;
}
bool CacheableReader::unserializebyte(byte& field)
{
if (ptr + sizeof(byte) > end)
{
return false;
}
field = MemAccess::get<byte>(ptr);
ptr += sizeof(byte);
fieldnum += 1;
return true;
}
bool CacheableReader::unserializedouble(double& field)
{
if (ptr + sizeof(double) > end)
{
return false;
}
field = MemAccess::get<double>(ptr);
ptr += sizeof(double);
fieldnum += 1;
return true;
}
bool CacheableReader::unserializeexpansionflags(unsigned char field[8], unsigned usedFlagCount)
{
if (ptr + 8 > end)
{
return false;
}
memcpy(field, ptr, 8);
for (int i = usedFlagCount; i < 8; i++ )
{
if (field[i])
{
LOG_err << "Unserialization failed in expansion flags, invalid version detected. Fieldnum: " << fieldnum;
return false;
}
}
ptr += 8;
fieldnum += 1;
return true;
}
#ifdef ENABLE_CHAT
TextChat::TextChat()
{
id = UNDEF;
priv = PRIV_UNKNOWN;
shard = -1;
userpriv = NULL;
group = false;
ou = UNDEF;
resetTag();
ts = 0;
flags = 0;
publicchat = false;
memset(&changed, 0, sizeof(changed));
}
TextChat::~TextChat()
{
delete userpriv;
}
bool TextChat::serialize(string *d)
{
unsigned short ll;
d->append((char*)&id, sizeof id);
d->append((char*)&priv, sizeof priv);
d->append((char*)&shard, sizeof shard);
ll = (unsigned short)(userpriv ? userpriv->size() : 0);
d->append((char*)&ll, sizeof ll);
if (userpriv)
{
userpriv_vector::iterator it = userpriv->begin();
while (it != userpriv->end())
{
handle uh = it->first;
d->append((char*)&uh, sizeof uh);
privilege_t priv = it->second;
d->append((char*)&priv, sizeof priv);
it++;
}
}
d->append((char*)&group, sizeof group);
// title is a binary array
ll = (unsigned short)title.size();
d->append((char*)&ll, sizeof ll);
d->append(title.data(), ll);
d->append((char*)&ou, sizeof ou);
d->append((char*)&ts, sizeof(ts));
char hasAttachments = attachedNodes.size() != 0;
d->append((char*)&hasAttachments, 1);
d->append((char*)&flags, 1);
char mode = publicchat ? 1 : 0;
d->append((char*)&mode, 1);
char hasUnifiedKey = unifiedKey.size() ? 1 : 0;
d->append((char *)&hasUnifiedKey, 1);
d->append("\0\0\0\0\0\0", 6); // additional bytes for backwards compatibility
if (hasAttachments)
{
ll = (unsigned short)attachedNodes.size(); // number of nodes with granted access
d->append((char*)&ll, sizeof ll);
for (attachments_map::iterator it = attachedNodes.begin(); it != attachedNodes.end(); it++)
{
d->append((char*)&it->first, sizeof it->first); // nodehandle
ll = (unsigned short)it->second.size(); // number of users with granted access to the node
d->append((char*)&ll, sizeof ll);
for (set<handle>::iterator ituh = it->second.begin(); ituh != it->second.end(); ituh++)
{
d->append((char*)&(*ituh), sizeof *ituh); // userhandle
}
}
}
if (hasUnifiedKey)
{
ll = (unsigned short) unifiedKey.size();
d->append((char *)&ll, sizeof ll);
d->append((char*) unifiedKey.data(), unifiedKey.size());
}
return true;
}
TextChat* TextChat::unserialize(class MegaClient *client, string *d)
{
handle id;
privilege_t priv;
int shard;
userpriv_vector *userpriv = NULL;
bool group;
string title; // byte array
handle ou;
m_time_t ts;
byte flags;
char hasAttachments;
attachments_map attachedNodes;
bool publicchat;
string unifiedKey;
unsigned short ll;
const char* ptr = d->data();
const char* end = ptr + d->size();
if (ptr + sizeof(handle) + sizeof(privilege_t) + sizeof(int) + sizeof(short) > end)
{
return NULL;
}
id = MemAccess::get<handle>(ptr);
ptr += sizeof id;
priv = MemAccess::get<privilege_t>(ptr);
ptr += sizeof priv;
shard = MemAccess::get<int>(ptr);
ptr += sizeof shard;
ll = MemAccess::get<unsigned short>(ptr);
ptr += sizeof ll;
if (ll)
{
if (ptr + ll * (sizeof(handle) + sizeof(privilege_t)) > end)
{
return NULL;
}
userpriv = new userpriv_vector();
for (unsigned short i = 0; i < ll; i++)
{
handle uh = MemAccess::get<handle>(ptr);
ptr += sizeof uh;
privilege_t priv = MemAccess::get<privilege_t>(ptr);
ptr += sizeof priv;
userpriv->push_back(userpriv_pair(uh, priv));
}
if (priv == PRIV_RM) // clear peerlist if removed
{
delete userpriv;
userpriv = NULL;
}
}
if (ptr + sizeof(bool) + sizeof(unsigned short) > end)
{
delete userpriv;
return NULL;
}
group = MemAccess::get<bool>(ptr);
ptr += sizeof group;
ll = MemAccess::get<unsigned short>(ptr);
ptr += sizeof ll;
if (ll)
{
if (ptr + ll > end)
{
delete userpriv;
return NULL;
}
title.assign(ptr, ll);
}
ptr += ll;
if (ptr + sizeof(handle) + sizeof(m_time_t) + sizeof(char) + 9 > end)
{
delete userpriv;
return NULL;
}
ou = MemAccess::get<handle>(ptr);
ptr += sizeof ou;
ts = MemAccess::get<m_time_t>(ptr);
ptr += sizeof(m_time_t);
hasAttachments = MemAccess::get<char>(ptr);
ptr += sizeof hasAttachments;
flags = MemAccess::get<char>(ptr);
ptr += sizeof(char);
char mode = MemAccess::get<char>(ptr);
publicchat = (mode == 1);
ptr += sizeof(char);
char hasUnifiedKey = MemAccess::get<char>(ptr);
ptr += sizeof(char);
for (int i = 6; i--;)
{
if (ptr + MemAccess::get<unsigned char>(ptr) < end)
{
ptr += MemAccess::get<unsigned char>(ptr) + 1;
}
}
if (hasAttachments)
{
unsigned short numNodes = 0;
if (ptr + sizeof numNodes > end)
{
delete userpriv;
return NULL;
}
numNodes = MemAccess::get<unsigned short>(ptr);
ptr += sizeof numNodes;
for (int i = 0; i < numNodes; i++)
{
handle h = UNDEF;
unsigned short numUsers = 0;
if (ptr + sizeof h + sizeof numUsers > end)
{
delete userpriv;
return NULL;
}
h = MemAccess::get<handle>(ptr);
ptr += sizeof h;
numUsers = MemAccess::get<unsigned short>(ptr);
ptr += sizeof numUsers;
handle uh = UNDEF;
if (ptr + (numUsers * sizeof(uh)) > end)
{
delete userpriv;
return NULL;
}
for (int j = 0; j < numUsers; j++)
{
uh = MemAccess::get<handle>(ptr);
ptr += sizeof uh;
attachedNodes[h].insert(uh);
}
}
}
if (hasUnifiedKey)
{
unsigned short keylen = 0;
if (ptr + sizeof keylen > end)
{
delete userpriv;
return NULL;
}
keylen = MemAccess::get<unsigned short>(ptr);
ptr += sizeof keylen;
if (ptr + keylen > end)
{
delete userpriv;
return NULL;
}
unifiedKey.assign(ptr, keylen);
ptr += keylen;
}
if (ptr < end)
{
delete userpriv;
return NULL;
}
if (client->chats.find(id) == client->chats.end())
{
client->chats[id] = new TextChat();
}
else
{
LOG_warn << "Unserialized a chat already in RAM";
}
TextChat* chat = client->chats[id];
chat->id = id;
chat->priv = priv;
chat->shard = shard;
chat->userpriv = userpriv;
chat->group = group;
chat->title = title;
chat->ou = ou;
chat->resetTag();
chat->ts = ts;
chat->flags = flags;
chat->attachedNodes = attachedNodes;
chat->publicchat = publicchat;
chat->unifiedKey = unifiedKey;
memset(&chat->changed, 0, sizeof(chat->changed));
return chat;
}
void TextChat::setTag(int tag)
{
if (this->tag != 0) // external changes prevail
{
this->tag = tag;
}
}
int TextChat::getTag()
{
return tag;
}
void TextChat::resetTag()
{
tag = -1;
}
bool TextChat::setNodeUserAccess(handle h, handle uh, bool revoke)
{
if (revoke)
{
attachments_map::iterator uhit = attachedNodes.find(h);
if (uhit != attachedNodes.end())
{
uhit->second.erase(uh);
if (uhit->second.empty())
{
attachedNodes.erase(h);
changed.attachments = true;
}
return true;
}
}
else
{
attachedNodes[h].insert(uh);
changed.attachments = true;
return true;
}
return false;
}
bool TextChat::setFlags(byte newFlags)
{
if (flags == newFlags)
{
return false;
}
flags = newFlags;
changed.flags = true;
return true;
}
bool TextChat::isFlagSet(uint8_t offset) const
{
return (flags >> offset) & 1U;
}
bool TextChat::setMode(bool publicchat)
{
if (this->publicchat == publicchat)
{
return false;
}
this->publicchat = publicchat;
changed.mode = true;
return true;
}
bool TextChat::setFlag(bool value, uint8_t offset)
{
if (bool((flags >> offset) & 1U) == value)
{
return false;
}
flags ^= (1U << offset);
changed.flags = true;
return true;
}
#endif
/**
* @brief Encrypts a string after padding it to block length.
*
* Note: With an IV, only use the first 8 bytes.
*
* @param data Data buffer to be encrypted. Encryption is done in-place,
* so cipher text will be in `data` afterwards as well.
* @param key AES key for encryption.
* @param iv Optional initialisation vector for encryption. Will use a
* zero IV if not given. If `iv` is a zero length string, a new IV
* for encryption will be generated and available through the reference.
* @return Void.
*/
void PaddedCBC::encrypt(PrnGen &rng, string* data, SymmCipher* key, string* iv)
{
if (iv)
{
// Make a new 8-byte IV, if the one passed is zero length.
if (iv->size() == 0)
{
byte* buf = new byte[8];
rng.genblock(buf, 8);
iv->append((char*)buf);
delete [] buf;
}
// Truncate a longer IV to its first 8 bytes.
if (iv->size() > 8)
{
iv->resize(8);
}
// Bring up the IV size to BLOCKSIZE.
iv->resize(key->BLOCKSIZE);
}
// Pad to block size and encrypt.
data->append("E");
data->resize((data->size() + key->BLOCKSIZE - 1) & - key->BLOCKSIZE, 'P');
if (iv)
{
key->cbc_encrypt((byte*)data->data(), data->size(),
(const byte*)iv->data());
}
else
{
key->cbc_encrypt((byte*)data->data(), data->size());
}
// Truncate IV back to the first 8 bytes only..
if (iv)
{
iv->resize(8);
}
}
/**
* @brief Decrypts a string and strips the padding.
*
* Note: With an IV, only use the first 8 bytes.
*
* @param data Data buffer to be decrypted. Decryption is done in-place,
* so plain text will be in `data` afterwards as well.
* @param key AES key for decryption.
* @param iv Optional initialisation vector for encryption. Will use a
* zero IV if not given.
* @return Void.
*/
bool PaddedCBC::decrypt(string* data, SymmCipher* key, string* iv)
{
if (iv)
{
// Truncate a longer IV to its first 8 bytes.
if (iv->size() > 8)
{
iv->resize(8);
}
// Bring up the IV size to BLOCKSIZE.
iv->resize(key->BLOCKSIZE);
}
if ((data->size() & (key->BLOCKSIZE - 1)))
{
return false;
}
// Decrypt and unpad.
if (iv)
{
key->cbc_decrypt((byte*)data->data(), data->size(),
(const byte*)iv->data());
}
else
{
key->cbc_decrypt((byte*)data->data(), data->size());
}
size_t p = data->find_last_of('E');
if (p == string::npos)
{
return false;
}
data->resize(p);
return true;
}
// start of chunk
m_off_t ChunkedHash::chunkfloor(m_off_t p)
{
m_off_t cp, np;
cp = 0;
for (unsigned i = 1; i <= 8; i++)
{
np = cp + i * SEGSIZE;
if ((p >= cp) && (p < np))
{
return cp;
}
cp = np;
}
return ((p - cp) & - (8 * SEGSIZE)) + cp;
}
// end of chunk (== start of next chunk)
m_off_t ChunkedHash::chunkceil(m_off_t p, m_off_t limit)
{
m_off_t cp, np;
cp = 0;
for (unsigned i = 1; i <= 8; i++)
{
np = cp + i * SEGSIZE;
if ((p >= cp) && (p < np))
{
return (limit < 0 || np < limit) ? np : limit;
}
cp = np;
}
np = ((p - cp) & - (8 * SEGSIZE)) + cp + 8 * SEGSIZE;
return (limit < 0 || np < limit) ? np : limit;
}
// cryptographic signature generation/verification
HashSignature::HashSignature(Hash* h)
{
hash = h;
}
HashSignature::~HashSignature()
{
delete hash;
}
void HashSignature::add(const byte* data, unsigned len)
{
hash->add(data, len);
}
unsigned HashSignature::get(AsymmCipher* privk, byte* sigbuf, unsigned sigbuflen)
{
string h;
hash->get(&h);
return privk->rawdecrypt((const byte*)h.data(), h.size(), sigbuf, sigbuflen);
}
bool HashSignature::checksignature(AsymmCipher* pubk, const byte* sig, unsigned len)
{
string h, s;
unsigned size;
hash->get(&h);
s.resize(h.size());
if (!(size = pubk->rawencrypt(sig, len, (byte*)s.data(), s.size())))
{
return 0;
}
if (size < h.size())
{
// left-pad with 0
s.insert(0, h.size() - size, 0);
s.resize(h.size());
}
return s == h;
}
PayCrypter::PayCrypter(PrnGen &rng)
: rng(rng)
{
rng.genblock(keys, ENC_KEY_BYTES + MAC_KEY_BYTES);
encKey = keys;
hmacKey = keys+ENC_KEY_BYTES;
rng.genblock(iv, IV_BYTES);
}
void PayCrypter::setKeys(const byte *newEncKey, const byte *newHmacKey, const byte *newIv)
{
memcpy(encKey, newEncKey, ENC_KEY_BYTES);
memcpy(hmacKey, newHmacKey, MAC_KEY_BYTES);
memcpy(iv, newIv, IV_BYTES);
}
bool PayCrypter::encryptPayload(const string *cleartext, string *result)
{
//Check parameters
if(!cleartext || !result)
{
return false;
}
//AES-CBC encryption
string encResult;
SymmCipher sym(encKey);
sym.cbc_encrypt_pkcs_padding(cleartext, iv, &encResult);
//Prepare the message to authenticate (IV + cipher text)
string toAuthenticate((char *)iv, IV_BYTES);
toAuthenticate.append(encResult);
//HMAC-SHA256
HMACSHA256 hmacProcessor(hmacKey, MAC_KEY_BYTES);
hmacProcessor.add((byte *)toAuthenticate.data(), toAuthenticate.size());
result->resize(32);
hmacProcessor.get((byte *)result->data());
//Complete the result (HMAC + IV - ciphertext)
result->append((char *)iv, IV_BYTES);
result->append(encResult);
return true;
}
bool PayCrypter::rsaEncryptKeys(const string *cleartext, const byte *pubkdata, int pubkdatalen, string *result, bool randompadding)
{
//Check parameters
if(!cleartext || !pubkdata || !result)
{
return false;
}
//Create an AsymmCipher with the public key
AsymmCipher asym;
asym.setkey(AsymmCipher::PUBKEY, pubkdata, pubkdatalen);
//Prepare the message to encrypt (2-byte header + clear text)
string keyString;
keyString.append(1, (byte)(cleartext->size() >> 8));
keyString.append(1, (byte)(cleartext->size()));
keyString.append(*cleartext);
//Save the length of the valid message
size_t keylen = keyString.size();
//Resize to add padding
keyString.resize(asym.key[AsymmCipher::PUB_PQ].ByteCount() - 2);
//Add padding
if(randompadding)
{
rng.genblock((byte *)keyString.data() + keylen, keyString.size() - keylen);
}
//RSA encryption
result->resize(pubkdatalen);
result->resize(asym.rawencrypt((byte *)keyString.data(), keyString.size(), (byte *)result->data(), result->size()));
//Complete the result (2-byte header + RSA result)
size_t reslen = result->size();
result->insert(0, 1, (byte)(reslen >> 8));
result->insert(1, 1, (byte)(reslen));
return true;
}
bool PayCrypter::hybridEncrypt(const string *cleartext, const byte *pubkdata, int pubkdatalen, string *result, bool randompadding)
{
if(!cleartext || !pubkdata || !result)
{
return false;
}
//Generate the payload
string payloadString;
encryptPayload(cleartext, &payloadString);
//RSA encryption
string rsaKeyCipher;
string keysString;
keysString.assign((char *)keys, ENC_KEY_BYTES + MAC_KEY_BYTES);
rsaEncryptKeys(&keysString, pubkdata, pubkdatalen, &rsaKeyCipher, randompadding);
//Complete the result
*result = rsaKeyCipher + payloadString;
return true;
}
#ifdef _WIN32
int mega_snprintf(char *s, size_t n, const char *format, ...)
{
va_list args;
int ret;
if (!s || n <= 0)
{
return -1;
}
va_start(args, format);
ret = vsnprintf(s, n, format, args);
va_end(args);
s[n - 1] = '\0';
return ret;
}
#endif
string * TLVstore::tlvRecordsToContainer(PrnGen &rng, SymmCipher *key, encryptionsetting_t encSetting)
{
// decide nonce/IV and auth. tag lengths based on the `mode`
unsigned ivlen = TLVstore::getIvlen(encSetting);
unsigned taglen = TLVstore::getTaglen(encSetting);
encryptionmode_t encMode = TLVstore::getMode(encSetting);
if (!ivlen || !taglen || encMode == AES_MODE_UNKNOWN)
{
return NULL;
}
// serialize the TLV records
string *container = tlvRecordsToContainer();
// generate IV array
byte *iv = new byte[ivlen];
rng.genblock(iv, ivlen);
string cipherText;
// encrypt the bytes using the specified mode
if (encMode == AES_MODE_CCM) // CCM or GCM_BROKEN (same than CCM)
{
key->ccm_encrypt(container, iv, ivlen, taglen, &cipherText);
}
else if (encMode == AES_MODE_GCM) // then use GCM
{
key->gcm_encrypt(container, iv, ivlen, taglen, &cipherText);
}
string *result = new string;
result->resize(1);
result->at(0) = static_cast<char>(encSetting);
result->append((char*) iv, ivlen);
result->append((char*) cipherText.data(), cipherText.length()); // includes auth. tag
delete [] iv;
delete container;
return result;
}
string* TLVstore::tlvRecordsToContainer()
{
string *result = new string;
size_t offset = 0;
size_t length;
for (TLV_map::iterator it = tlv.begin(); it != tlv.end(); it++)
{
// copy Type
result->append(it->first);
offset += it->first.length() + 1; // keep the NULL-char for Type string
// set Length of value
length = it->second.length();
result->resize(offset + 2);
result->at(offset) = static_cast<char>(length >> 8);
result->at(offset + 1) = static_cast<char>(length & 0xFF);
offset += 2;
// copy the Value
result->append((char*)it->second.data(), it->second.length());
offset += it->second.length();
}
return result;
}
std::string TLVstore::get(string type) const
{
return tlv.at(type);
}
const TLV_map * TLVstore::getMap() const
{
return &tlv;
}
vector<string> *TLVstore::getKeys() const
{
vector<string> *keys = new vector<string>;
for (string_map::const_iterator it = tlv.begin(); it != tlv.end(); it++)
{
keys->push_back(it->first);
}
return keys;
}
bool TLVstore::find(string type) const
{
return (tlv.find(type) != tlv.end());
}
void TLVstore::set(string type, string value)
{
tlv[type] = value;
}
void TLVstore::reset(std::string type)
{
tlv.erase(type);
}
size_t TLVstore::size()
{
return tlv.size();
}
unsigned TLVstore::getTaglen(int mode)
{
switch (mode)
{
case AES_CCM_10_16:
case AES_CCM_12_16:
case AES_GCM_12_16_BROKEN:
case AES_GCM_12_16:
return 16;
case AES_CCM_10_08:
case AES_GCM_10_08_BROKEN:
case AES_GCM_10_08:
return 8;
default: // unknown block encryption mode
return 0;
}
}
unsigned TLVstore::getIvlen(int mode)
{
switch (mode)
{
case AES_CCM_12_16:
case AES_GCM_12_16_BROKEN:
case AES_GCM_12_16:
return 12;
case AES_CCM_10_08:
case AES_GCM_10_08_BROKEN:
case AES_CCM_10_16:
case AES_GCM_10_08:
return 10;
default: // unknown block encryption mode
return 0;
}
}
encryptionmode_t TLVstore::getMode(int mode)
{
switch (mode)
{
case AES_CCM_12_16:
case AES_GCM_12_16_BROKEN:
case AES_CCM_10_16:
case AES_CCM_10_08:
case AES_GCM_10_08_BROKEN:
return AES_MODE_CCM;
case AES_GCM_12_16:
case AES_GCM_10_08:
return AES_MODE_GCM;
default: // unknown block encryption mode
return AES_MODE_UNKNOWN;
}
}
TLVstore * TLVstore::containerToTLVrecords(const string *data)
{
if (data->empty())
{
return NULL;
}
TLVstore *tlv = new TLVstore();
size_t offset = 0;
string type;
size_t typelen;
string value;
unsigned valuelen;
size_t pos;
size_t datalen = data->length();
while (offset < datalen)
{
// get the length of the Type string
pos = data->find('\0', offset);
typelen = pos - offset;
// if no valid TLV record in the container, but remaining bytes...
if (pos == string::npos || offset + typelen + 3 > datalen)
{
delete tlv;
return NULL;
}
// get the Type string
type.assign((char*)&(data->data()[offset]), typelen);
offset += typelen + 1; // +1: NULL character
// get the Length of the value
valuelen = (unsigned char)data->at(offset) << 8
| (unsigned char)data->at(offset + 1);
offset += 2;
// if there's not enough data for value...
if (offset + valuelen > datalen)
{
delete tlv;
return NULL;
}
// get the Value
value.assign((char*)&(data->data()[offset]), valuelen); // value may include NULL characters, read as a buffer
offset += valuelen;
// add it to the map
tlv->set(type, value);
}
return tlv;
}
TLVstore * TLVstore::containerToTLVrecords(const string *data, SymmCipher *key)
{
if (data->empty())
{
return NULL;
}
unsigned offset = 0;
encryptionsetting_t encSetting = (encryptionsetting_t) data->at(offset);
offset++;
unsigned ivlen = TLVstore::getIvlen(encSetting);
unsigned taglen = TLVstore::getTaglen(encSetting);
encryptionmode_t encMode = TLVstore::getMode(encSetting);
if (encMode == AES_MODE_UNKNOWN || !ivlen || !taglen || data->size() < offset+ivlen+taglen)
{
return NULL;
}
byte *iv = new byte[ivlen];
memcpy(iv, &(data->data()[offset]), ivlen);
offset += ivlen;
unsigned cipherTextLen = unsigned(data->length() - offset);
string cipherText = data->substr(offset, cipherTextLen);
unsigned clearTextLen = cipherTextLen - taglen;
string clearText;
bool decrypted = false;
if (encMode == AES_MODE_CCM) // CCM or GCM_BROKEN (same than CCM)
{
decrypted = key->ccm_decrypt(&cipherText, iv, ivlen, taglen, &clearText);
}
else if (encMode == AES_MODE_GCM) // GCM
{
decrypted = key->gcm_decrypt(&cipherText, iv, ivlen, taglen, &clearText);
}
delete [] iv;
if (!decrypted) // the decryption has failed (probably due to authentication)
{
return NULL;
}
else if (clearText.empty()) // If decryption succeeded but attribute is empty, generate an empty TLV
{
return new TLVstore();
}
TLVstore *tlv = TLVstore::containerToTLVrecords(&clearText);
if (!tlv) // 'data' might be affected by the legacy bug: strings encoded in UTF-8 instead of Unicode
{
// retry TLV decoding after conversion from 'UTF-8 chars' to 'Unicode chars'
LOG_warn << "Retrying TLV records decoding with UTF-8 patch";
string clearTextUnicode;
if (!Utils::utf8toUnicode((const byte*)clearText.data(), clearTextLen, &clearTextUnicode))
{
LOG_err << "Invalid UTF-8 encoding";
}
else
{
tlv = TLVstore::containerToTLVrecords(&clearTextUnicode);
}
}
return tlv;
}
TLVstore::~TLVstore()
{
}
size_t Utils::utf8SequenceSize(unsigned char c)
{
int aux = static_cast<int>(c);
if (aux >= 0 && aux <= 127) return 1;
else if ((aux & 0xE0) == 0xC0) return 2;
else if ((aux & 0xF0) == 0xE0) return 3;
else if ((aux & 0xF8) == 0xF0) return 4;
else
{
LOG_err << "Malformed UTF-8 sequence, interpret character " << c << " as literal";
return 1;
}
}
bool Utils::utf8toUnicode(const uint8_t *src, unsigned srclen, string *result)
{
uint8_t utf8cp1;
uint8_t utf8cp2;
int32_t unicodecp;
if (!srclen)
{
result->clear();
return true;
}
byte *res = new byte[srclen];
unsigned rescount = 0;
unsigned i = 0;
while (i < srclen)
{
utf8cp1 = src[i++];
if (utf8cp1 < 0x80)
{
res[rescount++] = utf8cp1;
}
else
{
if (i < srclen)
{
utf8cp2 = src[i++];
// check codepoints are valid
if ((utf8cp1 == 0xC2 || utf8cp1 == 0xC3) && utf8cp2 >= 0x80 && utf8cp2 <= 0xBF)
{
unicodecp = ((utf8cp1 & 0x1F) << 6) + (utf8cp2 & 0x3F);
res[rescount++] = unicodecp & 0xFF;
}
else
{
// error: one of the two-bytes UTF-8 char is not a valid UTF-8 char
delete [] res;
return false;
}
}
else
{
// error: last byte indicates a two-bytes UTF-8 char, but only one left
delete [] res;
return false;
}
}
}
result->assign((const char*)res, rescount);
delete [] res;
return true;
}
std::string Utils::stringToHex(const std::string &input)
{
static const char* const lut = "0123456789ABCDEF";
size_t len = input.length();
std::string output;
output.reserve(2 * len);
for (size_t i = 0; i < len; ++i)
{
const unsigned char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
}
return output;
}
std::string Utils::hexToString(const std::string &input)
{
static const char* const lut = "0123456789ABCDEF";
size_t len = input.length();
if (len & 1) throw std::invalid_argument("odd length");
std::string output;
output.reserve(len / 2);
for (size_t i = 0; i < len; i += 2)
{
char a = input[i];
const char* p = std::lower_bound(lut, lut + 16, a);
if (*p != a) throw std::invalid_argument("not a hex digit");
char b = input[i + 1];
const char* q = std::lower_bound(lut, lut + 16, b);
if (*q != b) throw std::invalid_argument("not a hex digit");
output.push_back(static_cast<char>(((p - lut) << 4) | (q - lut)));
}
return output;
}
long long abs(long long n)
{
// for pre-c++11 where this version is not defined yet
return n >= 0 ? n : -n;
}
struct tm* m_localtime(m_time_t ttime, struct tm *dt)
{
// works for 32 or 64 bit time_t
time_t t = time_t(ttime);
#if (__cplusplus >= 201103L) && defined (__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)
localtime_s(&t, dt);
#elif _MSC_VER >= 1400 || defined(__MINGW32__) // MSVCRT (2005+): std::localtime is threadsafe
struct tm *newtm = localtime(&t);
if (newtm)
{
memcpy(dt, newtm, sizeof(struct tm));
}
else
{
memset(dt, 0, sizeof(struct tm));
}
#elif _WIN32
#error "localtime is not thread safe in this compiler; please use a later one"
#else //POSIX
localtime_r(&t, dt);
#endif
return dt;
}
struct tm* m_gmtime(m_time_t ttime, struct tm *dt)
{
// works for 32 or 64 bit time_t
time_t t = time_t(ttime);
#if (__cplusplus >= 201103L) && defined (__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)
gmtime_s(&t, dt);
#elif _MSC_VER >= 1400 || defined(__MINGW32__) // MSVCRT (2005+): std::gmtime is threadsafe
struct tm *newtm = gmtime(&t);
if (newtm)
{
memcpy(dt, newtm, sizeof(struct tm));
}
else
{
memset(dt, 0, sizeof(struct tm));
}
#elif _WIN32
#error "gmtime is not thread safe in this compiler; please use a later one"
#else //POSIX
gmtime_r(&t, dt);
#endif
return dt;
}
m_time_t m_time(m_time_t* tt)
{
// works for 32 or 64 bit time_t
time_t t = time(NULL);
if (tt)
{
*tt = t;
}
return t;
}
m_time_t m_mktime(struct tm* stm)
{
// works for 32 or 64 bit time_t
return mktime(stm);
}
int m_clock_getmonotonictime(timespec *t)
{
#ifdef __APPLE__
struct timeval now;
int rv = gettimeofday(&now, NULL);
if (rv)
{
return rv;
}
t->tv_sec = now.tv_sec;
t->tv_nsec = now.tv_usec * 1000;
return 0;
#elif defined(_WIN32) && defined(_MSC_VER)
struct __timeb64 tb;
_ftime64(&tb);
t->tv_sec = tb.time;
t->tv_nsec = long(tb.millitm) * 1000000;
return 0;
#else
#ifdef CLOCK_BOOTTIME
return clock_gettime(CLOCK_BOOTTIME, t);
#else
return clock_gettime(CLOCK_MONOTONIC, t);
#endif
#endif
}
m_time_t m_mktime_UTC(const struct tm *src)
{
struct tm dst = *src;
m_time_t t = 0;
#if _MSC_VER >= 1400 || defined(__MINGW32__) // MSVCRT (2005+)
t = mktime(&dst);
TIME_ZONE_INFORMATION TimeZoneInfo;
GetTimeZoneInformation(&TimeZoneInfo);
t += TimeZoneInfo.Bias * 60 - dst.tm_isdst * 3600;
#elif _WIN32
#error "localtime is not thread safe in this compiler; please use a later one"
#else //POSIX
t = mktime(&dst);
t += dst.tm_gmtoff - dst.tm_isdst * 3600;
#endif
return t;
}
std::string rfc1123_datetime( time_t time )
{
struct tm * timeinfo;
char buffer [80];
timeinfo = gmtime(&time);
strftime (buffer, 80, "%a, %d %b %Y %H:%M:%S GMT",timeinfo);
return buffer;
}
string webdavurlescape(const string &value)
{
ostringstream escaped;
escaped.fill('0');
escaped << std::hex;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i)
{
string::value_type c = (*i);
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~' || c == '/' || c == ':')
{
escaped << c;
}
else
{
escaped << std::uppercase;
escaped << '%' << std::setw(2) << int((unsigned char) c);
escaped << std::nouppercase;
}
}
return escaped.str();
}
string escapewebdavchar(const char c)
{
static bool unintitialized = true;
static std::map<int,const char *> escapesec;
if (unintitialized)
{
escapesec[33] = "!"; // ! //For some reason &Exclamation; was not properly handled (crashed) by gvfsd-dav
escapesec[34] = """; // "
escapesec[37] = "%"; // %
escapesec[38] = "&"; // &
escapesec[39] = "'"; // '
escapesec[43] = "&add;"; // +
escapesec[60] = "<"; // <
escapesec[61] = "="; // = //For some reason &equal; was not properly handled (crashed) by gvfsd-dav
escapesec[62] = ">"; // >
escapesec[160] = " "; //NO-BREAK SPACE
escapesec[161] = "¡"; //INVERTED EXCLAMATION MARK
escapesec[162] = "¢"; //CENT SIGN
escapesec[163] = "£"; //POUND SIGN
escapesec[164] = "¤"; //CURRENCY SIGN
escapesec[165] = "¥"; //YEN SIGN
escapesec[166] = "¦"; //BROKEN BAR
escapesec[167] = "§"; //SECTION SIGN
escapesec[168] = "¨"; //DIAERESIS
escapesec[169] = "©"; //COPYRIGHT SIGN
escapesec[170] = "ª"; //FEMININE ORDINAL INDICATOR
escapesec[171] = "«"; //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
escapesec[172] = "¬"; //NOT SIGN
escapesec[173] = "­"; //SOFT HYPHEN
escapesec[174] = "®"; //REGISTERED SIGN
escapesec[175] = "¯"; //MACRON
escapesec[176] = "°"; //DEGREE SIGN
escapesec[177] = "±"; //PLUS-MINUS SIGN
escapesec[178] = "²"; //SUPERSCRIPT TWO
escapesec[179] = "³"; //SUPERSCRIPT THREE
escapesec[180] = "´"; //ACUTE ACCENT
escapesec[181] = "µ"; //MICRO SIGN
escapesec[182] = "¶"; //PILCROW SIGN
escapesec[183] = "·"; //MIDDLE DOT
escapesec[184] = "¸"; //CEDILLA
escapesec[185] = "¹"; //SUPERSCRIPT ONE
escapesec[186] = "º"; //MASCULINE ORDINAL INDICATOR
escapesec[187] = "»"; //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
escapesec[188] = "¼"; //VULGAR FRACTION ONE QUARTER
escapesec[189] = "½"; //VULGAR FRACTION ONE HALF
escapesec[190] = "¾"; //VULGAR FRACTION THREE QUARTERS
escapesec[191] = "¿"; //INVERTED QUESTION MARK
escapesec[192] = "À"; //LATIN CAPITAL LETTER A WITH GRAVE
escapesec[193] = "Á"; //LATIN CAPITAL LETTER A WITH ACUTE
escapesec[194] = "Â"; //LATIN CAPITAL LETTER A WITH CIRCUMFLEX
escapesec[195] = "Ã"; //LATIN CAPITAL LETTER A WITH TILDE
escapesec[196] = "Ä"; //LATIN CAPITAL LETTER A WITH DIAERESIS
escapesec[197] = "Å"; //LATIN CAPITAL LETTER A WITH RING ABOVE
escapesec[198] = "Æ"; //LATIN CAPITAL LETTER AE
escapesec[199] = "Ç"; //LATIN CAPITAL LETTER C WITH CEDILLA
escapesec[200] = "È"; //LATIN CAPITAL LETTER E WITH GRAVE
escapesec[201] = "É"; //LATIN CAPITAL LETTER E WITH ACUTE
escapesec[202] = "Ê"; //LATIN CAPITAL LETTER E WITH CIRCUMFLEX
escapesec[203] = "Ë"; //LATIN CAPITAL LETTER E WITH DIAERESIS
escapesec[204] = "Ì"; //LATIN CAPITAL LETTER I WITH GRAVE
escapesec[205] = "Í"; //LATIN CAPITAL LETTER I WITH ACUTE
escapesec[206] = "Î"; //LATIN CAPITAL LETTER I WITH CIRCUMFLEX
escapesec[207] = "Ï"; //LATIN CAPITAL LETTER I WITH DIAERESIS
escapesec[208] = "Ð"; //LATIN CAPITAL LETTER ETH
escapesec[209] = "Ñ"; //LATIN CAPITAL LETTER N WITH TILDE
escapesec[210] = "Ò"; //LATIN CAPITAL LETTER O WITH GRAVE
escapesec[211] = "Ó"; //LATIN CAPITAL LETTER O WITH ACUTE
escapesec[212] = "Ô"; //LATIN CAPITAL LETTER O WITH CIRCUMFLEX
escapesec[213] = "Õ"; //LATIN CAPITAL LETTER O WITH TILDE
escapesec[214] = "Ö"; //LATIN CAPITAL LETTER O WITH DIAERESIS
escapesec[215] = "×"; //MULTIPLICATION SIGN
escapesec[216] = "Ø"; //LATIN CAPITAL LETTER O WITH STROKE
escapesec[217] = "Ù"; //LATIN CAPITAL LETTER U WITH GRAVE
escapesec[218] = "Ú"; //LATIN CAPITAL LETTER U WITH ACUTE
escapesec[219] = "Û"; //LATIN CAPITAL LETTER U WITH CIRCUMFLEX
escapesec[220] = "Ü"; //LATIN CAPITAL LETTER U WITH DIAERESIS
escapesec[221] = "Ý"; //LATIN CAPITAL LETTER Y WITH ACUTE
escapesec[222] = "Þ"; //LATIN CAPITAL LETTER THORN
escapesec[223] = "ß"; //LATIN SMALL LETTER SHARP S
escapesec[224] = "à"; //LATIN SMALL LETTER A WITH GRAVE
escapesec[225] = "á"; //LATIN SMALL LETTER A WITH ACUTE
escapesec[226] = "â"; //LATIN SMALL LETTER A WITH CIRCUMFLEX
escapesec[227] = "ã"; //LATIN SMALL LETTER A WITH TILDE
escapesec[228] = "ä"; //LATIN SMALL LETTER A WITH DIAERESIS
escapesec[229] = "å"; //LATIN SMALL LETTER A WITH RING ABOVE
escapesec[230] = "æ"; //LATIN SMALL LETTER AE
escapesec[231] = "ç"; //LATIN SMALL LETTER C WITH CEDILLA
escapesec[232] = "è"; //LATIN SMALL LETTER E WITH GRAVE
escapesec[233] = "é"; //LATIN SMALL LETTER E WITH ACUTE
escapesec[234] = "ê"; //LATIN SMALL LETTER E WITH CIRCUMFLEX
escapesec[235] = "ë"; //LATIN SMALL LETTER E WITH DIAERESIS
escapesec[236] = "ì"; //LATIN SMALL LETTER I WITH GRAVE
escapesec[237] = "í"; //LATIN SMALL LETTER I WITH ACUTE
escapesec[238] = "î"; //LATIN SMALL LETTER I WITH CIRCUMFLEX
escapesec[239] = "ï"; //LATIN SMALL LETTER I WITH DIAERESIS
escapesec[240] = "ð"; //LATIN SMALL LETTER ETH
escapesec[241] = "ñ"; //LATIN SMALL LETTER N WITH TILDE
escapesec[242] = "ò"; //LATIN SMALL LETTER O WITH GRAVE
escapesec[243] = "ó"; //LATIN SMALL LETTER O WITH ACUTE
escapesec[244] = "ô"; //LATIN SMALL LETTER O WITH CIRCUMFLEX
escapesec[245] = "õ"; //LATIN SMALL LETTER O WITH TILDE
escapesec[246] = "ö"; //LATIN SMALL LETTER O WITH DIAERESIS
escapesec[247] = "÷"; //DIVISION SIGN
escapesec[248] = "ø"; //LATIN SMALL LETTER O WITH STROKE
escapesec[249] = "ù"; //LATIN SMALL LETTER U WITH GRAVE
escapesec[250] = "ú"; //LATIN SMALL LETTER U WITH ACUTE
escapesec[251] = "û"; //LATIN SMALL LETTER U WITH CIRCUMFLEX
escapesec[252] = "ü"; //LATIN SMALL LETTER U WITH DIAERESIS
escapesec[253] = "ý"; //LATIN SMALL LETTER Y WITH ACUTE
escapesec[254] = "þ"; //LATIN SMALL LETTER THORN
escapesec[255] = "ÿ"; //LATIN SMALL LETTER Y WITH DIAERESIS
escapesec[338] = "Œ"; //LATIN CAPITAL LIGATURE OE
escapesec[339] = "œ"; //LATIN SMALL LIGATURE OE
escapesec[352] = "Š"; //LATIN CAPITAL LETTER S WITH CARON
escapesec[353] = "š"; //LATIN SMALL LETTER S WITH CARON
escapesec[376] = "Ÿ"; //LATIN CAPITAL LETTER Y WITH DIAERESIS
escapesec[402] = "ƒ"; //LATIN SMALL LETTER F WITH HOOK
escapesec[710] = "ˆ"; //MODIFIER LETTER CIRCUMFLEX ACCENT
escapesec[732] = "˜"; //SMALL TILDE
escapesec[913] = "Α"; //GREEK CAPITAL LETTER ALPHA
escapesec[914] = "Β"; //GREEK CAPITAL LETTER BETA
escapesec[915] = "Γ"; //GREEK CAPITAL LETTER GAMMA
escapesec[916] = "Δ"; //GREEK CAPITAL LETTER DELTA
escapesec[917] = "Ε"; //GREEK CAPITAL LETTER EPSILON
escapesec[918] = "Ζ"; //GREEK CAPITAL LETTER ZETA
escapesec[919] = "Η"; //GREEK CAPITAL LETTER ETA
escapesec[920] = "Θ"; //GREEK CAPITAL LETTER THETA
escapesec[921] = "Ι"; //GREEK CAPITAL LETTER IOTA
escapesec[922] = "Κ"; //GREEK CAPITAL LETTER KAPPA
escapesec[923] = "Λ"; //GREEK CAPITAL LETTER LAMDA
escapesec[924] = "Μ"; //GREEK CAPITAL LETTER MU
escapesec[925] = "Ν"; //GREEK CAPITAL LETTER NU
escapesec[926] = "Ξ"; //GREEK CAPITAL LETTER XI
escapesec[927] = "Ο"; //GREEK CAPITAL LETTER OMICRON
escapesec[928] = "Π"; //GREEK CAPITAL LETTER PI
escapesec[929] = "Ρ"; //GREEK CAPITAL LETTER RHO
escapesec[931] = "Σ"; //GREEK CAPITAL LETTER SIGMA
escapesec[932] = "Τ"; //GREEK CAPITAL LETTER TAU
escapesec[933] = "Υ"; //GREEK CAPITAL LETTER UPSILON
escapesec[934] = "Φ"; //GREEK CAPITAL LETTER PHI
escapesec[935] = "Χ"; //GREEK CAPITAL LETTER CHI
escapesec[936] = "Ψ"; //GREEK CAPITAL LETTER PSI
escapesec[937] = "Ω"; //GREEK CAPITAL LETTER OMEGA
escapesec[945] = "α"; //GREEK SMALL LETTER ALPHA
escapesec[946] = "β"; //GREEK SMALL LETTER BETA
escapesec[947] = "γ"; //GREEK SMALL LETTER GAMMA
escapesec[948] = "δ"; //GREEK SMALL LETTER DELTA
escapesec[949] = "ε"; //GREEK SMALL LETTER EPSILON
escapesec[950] = "ζ"; //GREEK SMALL LETTER ZETA
escapesec[951] = "η"; //GREEK SMALL LETTER ETA
escapesec[952] = "θ"; //GREEK SMALL LETTER THETA
escapesec[953] = "ι"; //GREEK SMALL LETTER IOTA
escapesec[954] = "κ"; //GREEK SMALL LETTER KAPPA
escapesec[955] = "λ"; //GREEK SMALL LETTER LAMDA
escapesec[956] = "μ"; //GREEK SMALL LETTER MU
escapesec[957] = "ν"; //GREEK SMALL LETTER NU
escapesec[958] = "ξ"; //GREEK SMALL LETTER XI
escapesec[959] = "ο"; //GREEK SMALL LETTER OMICRON
escapesec[960] = "π"; //GREEK SMALL LETTER PI
escapesec[961] = "ρ"; //GREEK SMALL LETTER RHO
escapesec[962] = "ς"; //GREEK SMALL LETTER FINAL SIGMA
escapesec[963] = "σ"; //GREEK SMALL LETTER SIGMA
escapesec[964] = "τ"; //GREEK SMALL LETTER TAU
escapesec[965] = "υ"; //GREEK SMALL LETTER UPSILON
escapesec[966] = "φ"; //GREEK SMALL LETTER PHI
escapesec[967] = "χ"; //GREEK SMALL LETTER CHI
escapesec[968] = "ψ"; //GREEK SMALL LETTER PSI
escapesec[969] = "ω"; //GREEK SMALL LETTER OMEGA
escapesec[977] = "ϑ"; //GREEK THETA SYMBOL
escapesec[978] = "ϒ"; //GREEK UPSILON WITH HOOK SYMBOL
escapesec[982] = "ϖ"; //GREEK PI SYMBOL
escapesec[8194] = " "; //EN SPACE
escapesec[8195] = " "; //EM SPACE
escapesec[8201] = " "; //THIN SPACE
escapesec[8204] = "‌"; //ZERO WIDTH NON-JOINER
escapesec[8205] = "‍"; //ZERO WIDTH JOINER
escapesec[8206] = "‎"; //LEFT-TO-RIGHT MARK
escapesec[8207] = "‏"; //RIGHT-TO-LEFT MARK
escapesec[8211] = "–"; //EN DASH
escapesec[8212] = "—"; //EM DASH
escapesec[8213] = "―"; //HORIZONTAL BAR
escapesec[8216] = "‘"; //LEFT SINGLE QUOTATION MARK
escapesec[8217] = "’"; //RIGHT SINGLE QUOTATION MARK
escapesec[8218] = "‚"; //SINGLE LOW-9 QUOTATION MARK
escapesec[8220] = "“"; //LEFT DOUBLE QUOTATION MARK
escapesec[8221] = "”"; //RIGHT DOUBLE QUOTATION MARK
escapesec[8222] = "„"; //DOUBLE LOW-9 QUOTATION MARK
escapesec[8224] = "†"; //DAGGER
escapesec[8225] = "‡"; //DOUBLE DAGGER
escapesec[8226] = "•"; //BULLET
escapesec[8230] = "…"; //HORIZONTAL ELLIPSIS
escapesec[8240] = "‰"; //PER MILLE SIGN
escapesec[8242] = "′"; //PRIME
escapesec[8243] = "″"; //DOUBLE PRIME
escapesec[8249] = "‹"; //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
escapesec[8250] = "›"; //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
escapesec[8254] = "‾"; //OVERLINE
escapesec[8260] = "⁄"; //FRACTION SLASH
escapesec[8364] = "€"; //EURO SIGN
escapesec[8465] = "ℑ"; //BLACK-LETTER CAPITAL I
escapesec[8472] = "℘"; //SCRIPT CAPITAL P
escapesec[8476] = "ℜ"; //BLACK-LETTER CAPITAL R
escapesec[8482] = "™"; //TRADE MARK SIGN
escapesec[8501] = "ℵ"; //ALEF SYMBOL
escapesec[8592] = "←"; //LEFTWARDS ARROW
escapesec[8593] = "↑"; //UPWARDS ARROW
escapesec[8594] = "→"; //RIGHTWARDS ARROW
escapesec[8595] = "↓"; //DOWNWARDS ARROW
escapesec[8596] = "↔"; //LEFT RIGHT ARROW
escapesec[8629] = "↵"; //DOWNWARDS ARROW WITH CORNER LEFTWARDS
escapesec[8656] = "⇐"; //LEFTWARDS DOUBLE ARROW
escapesec[8657] = "⇑"; //UPWARDS DOUBLE ARROW
escapesec[8658] = "⇒"; //RIGHTWARDS DOUBLE ARROW
escapesec[8659] = "⇓"; //DOWNWARDS DOUBLE ARROW
escapesec[8660] = "⇔"; //LEFT RIGHT DOUBLE ARROW
escapesec[8704] = "∀"; //FOR ALL
escapesec[8706] = "∂"; //PARTIAL DIFFERENTIAL
escapesec[8707] = "∃"; //THERE EXISTS
escapesec[8709] = "∅"; //EMPTY SET
escapesec[8711] = "∇"; //NABLA
escapesec[8712] = "∈"; //ELEMENT OF
escapesec[8713] = "∉"; //NOT AN ELEMENT OF
escapesec[8715] = "∋"; //CONTAINS AS MEMBER
escapesec[8719] = "∏"; //N-ARY PRODUCT
escapesec[8721] = "∑"; //N-ARY SUMMATION
escapesec[8722] = "−"; //MINUS SIGN
escapesec[8727] = "∗"; //ASTERISK OPERATOR
escapesec[8730] = "√"; //SQUARE ROOT
escapesec[8733] = "∝"; //PROPORTIONAL TO
escapesec[8734] = "∞"; //INFINITY
escapesec[8736] = "∠"; //ANGLE
escapesec[8743] = "∧"; //LOGICAL AND
escapesec[8744] = "∨"; //LOGICAL OR
escapesec[8745] = "∩"; //INTERSECTION
escapesec[8746] = "∪"; //UNION
escapesec[8747] = "∫"; //INTEGRAL
escapesec[8756] = "∴"; //THEREFORE
escapesec[8764] = "∼"; //TILDE OPERATOR
escapesec[8773] = "≅"; //APPROXIMATELY EQUAL TO
escapesec[8776] = "≈"; //ALMOST EQUAL TO
escapesec[8800] = "≠"; //NOT EQUAL TO
escapesec[8801] = "≡"; //IDENTICAL TO
escapesec[8804] = "≤"; //LESS-THAN OR EQUAL TO
escapesec[8805] = "≥"; //GREATER-THAN OR EQUAL TO
escapesec[8834] = "⊂"; //SUBSET OF
escapesec[8835] = "⊃"; //SUPERSET OF
escapesec[8836] = "⊄"; //NOT A SUBSET OF
escapesec[8838] = "⊆"; //SUBSET OF OR EQUAL TO
escapesec[8839] = "⊇"; //SUPERSET OF OR EQUAL TO
escapesec[8853] = "⊕"; //CIRCLED PLUS
escapesec[8855] = "⊗"; //CIRCLED TIMES
escapesec[8869] = "⊥"; //UP TACK
escapesec[8901] = "⋅"; //DOT OPERATOR
escapesec[8968] = "⌈"; //LEFT CEILING
escapesec[8969] = "⌉"; //RIGHT CEILING
escapesec[8970] = "⌊"; //LEFT FLOOR
escapesec[8971] = "⌋"; //RIGHT FLOOR
escapesec[9001] = "⟨"; //LEFT-POINTING ANGLE BRACKET
escapesec[9002] = "⟩"; //RIGHT-POINTING ANGLE BRACKET
escapesec[9674] = "◊"; //LOZENGE
escapesec[9824] = "♠"; //BLACK SPADE SUIT
escapesec[9827] = "♣"; //BLACK CLUB SUIT
escapesec[9829] = "♥"; //BLACK HEART SUIT
escapesec[9830] = "♦"; //BLACK DIAMOND SUIT
unintitialized = false;
}
if (escapesec.find(c) != escapesec.end())
{
return escapesec[c];
}
return string(1,c);
}
string webdavnameescape(const string &value) {
ostringstream escaped;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i)
{
escaped << escapewebdavchar(*i);
}
return escaped.str();
}
void tolower_string(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), [](char c) {return static_cast<char>(::tolower(c)); });
}
#ifdef __APPLE__
int macOSmajorVersion()
{
char releaseStr[256];
size_t size = sizeof(releaseStr);
if (!sysctlbyname("kern.osrelease", releaseStr, &size, NULL, 0) && size > 0)
{
if (strchr(releaseStr,'.'))
{
char *token = strtok(releaseStr, ".");
if (token)
{
errno = 0;
char *endPtr = NULL;
long majorVersion = strtol(token, &endPtr, 10);
if (endPtr != token && errno != ERANGE && majorVersion >= INT_MIN && majorVersion <= INT_MAX)
{
return int(majorVersion);
}
}
}
}
return -1;
}
#endif
void NodeCounter::operator += (const NodeCounter& o)
{
storage += o.storage;
versionStorage += o.versionStorage;
files += o.files;
folders += o.folders;
versions += o.versions;
}
void NodeCounter::operator -= (const NodeCounter& o)
{
storage -= o.storage;
versionStorage -= o.versionStorage;
files -= o.files;
folders -= o.folders;
versions -= o.versions;
}
CacheableStatus::CacheableStatus(int64_t type, int64_t value)
: mType{type}, mValue{value}
{ }
// This should be a const-method but can't be due to the broken Cacheable interface.
// Do not mutate members in this function! Hence, we forward to a private const-method.
bool CacheableStatus::serialize(std::string* data)
{
return const_cast<const CacheableStatus*>(this)->serialize(*data);
}
std::shared_ptr<CacheableStatus> CacheableStatus::unserialize(class MegaClient *client, const std::string& data)
{
int64_t type;
int64_t value;
CacheableReader reader{data};
if (!reader.unserializei64(type))
{
return {};
}
if (!reader.unserializei64(value))
{
return {};
}
auto cacheableStatus = std::make_shared<CacheableStatus>(type, value);
client->loadCacheableStatus(cacheableStatus);
return cacheableStatus;
}
bool CacheableStatus::serialize(std::string& data) const
{
CacheableWriter writer{data};
writer.serializei64(mType);
writer.serializei64(mValue);
return true;
}
int64_t CacheableStatus::value() const
{
return mValue;
}
int64_t CacheableStatus::type() const
{
return mType;
}
void CacheableStatus::setValue(const int64_t value)
{
mValue = value;
}
SyncConfig::SyncConfig(int tag,
std::string localPath,
std::string name,
const handle remoteNode,
const std::string &remotePath,
const fsfp_t localFingerprint,
std::vector<std::string> regExps,
const bool enabled,
const Type syncType,
const bool syncDeletions,
const bool forceOverwrite,
const SyncError error)
: mTag{tag}
, mEnabled{enabled}
, mLocalPath{std::move(localPath)}
, mName{std::move(name)}
, mRemoteNode{remoteNode}
, mRemotePath{remotePath}
, mLocalFingerprint{localFingerprint}
, mRegExps{std::move(regExps)}
, mSyncType{syncType}
, mSyncDeletions{syncDeletions}
, mForceOverwrite{forceOverwrite}
, mError{error}
{}
int SyncConfig::getTag() const
{
return mTag;
}
void SyncConfig::setTag(int tag)
{
mTag = tag;
}
bool SyncConfig::getEnabled() const
{
return mEnabled;
}
void SyncConfig::setEnabled(bool enabled)
{
mEnabled = enabled;
}
bool SyncConfig::isEnabled(syncstate_t state, SyncError syncError)
{
return state != SYNC_CANCELED && (state != SYNC_DISABLED || syncError != NO_SYNC_ERROR);
}
bool SyncConfig::isResumable() const
{
return mEnabled && !isSyncErrorPermanent(mError);
}
bool SyncConfig::isResumableAtStartup() const
{
return mEnabled && (!isAnError(mError)
|| mError == LOGGED_OUT
|| mError == UNKNOWN_TEMPORARY_ERROR
|| mError == FOREIGN_TARGET_OVERSTORAGE); //temporary errors that don't have an asociated restore functionality
}
bool SyncConfig::hasError() const
{
return isAnError(mError);
}
const std::string& SyncConfig::getLocalPath() const
{
return mLocalPath;
}
const std::string& SyncConfig::getName() const
{
return mName;
}
handle SyncConfig::getRemoteNode() const
{
return mRemoteNode;
}
void SyncConfig::setRemoteNode(const handle &remoteNode)
{
mRemoteNode = remoteNode;
}
const std::string& SyncConfig::getRemotePath() const
{
return mRemotePath;
}
void SyncConfig::setRemotePath(const std::string &remotePath)
{
mRemotePath = remotePath;
}
handle SyncConfig::getLocalFingerprint() const
{
return mLocalFingerprint;
}
void SyncConfig::setLocalFingerprint(fsfp_t fingerprint)
{
mLocalFingerprint = fingerprint;
}
const std::vector<std::string>& SyncConfig::getRegExps() const
{
return mRegExps;
}
SyncConfig::Type SyncConfig::getType() const
{
return mSyncType;
}
bool SyncConfig::isUpSync() const
{
return mSyncType & TYPE_UP;
}
bool SyncConfig::isDownSync() const
{
return mSyncType & TYPE_DOWN;
}
bool SyncConfig::syncDeletions() const
{
switch (mSyncType)
{
case TYPE_UP: return mSyncDeletions;
case TYPE_DOWN: return mSyncDeletions;
case TYPE_TWOWAY: return true;
}
assert(false);
return true;
}
bool SyncConfig::forceOverwrite() const
{
switch (mSyncType)
{
case TYPE_UP: return mForceOverwrite;
case TYPE_DOWN: return mForceOverwrite;
case TYPE_TWOWAY: return false;
}
assert(false);
return false;
}
SyncError SyncConfig::getError() const
{
return mError;
}
void SyncConfig::setError(SyncError value)
{
mError = value;
}
// This should be a const-method but can't be due to the broken Cacheable interface.
// Do not mutate members in this function! Hence, we forward to a private const-method.
bool SyncConfig::serialize(std::string* data)
{
return const_cast<const SyncConfig*>(this)->serialize(*data);
}
std::unique_ptr<SyncConfig> SyncConfig::unserialize(const std::string& data)
{
int64_t tag;
bool enabled;
std::string localPath;
std::string name;
handle remoteNode;
std::string remotePath;
fsfp_t fingerprint;
uint32_t regExpCount;
std::vector<std::string> regExps;
uint32_t syncType;
bool syncDeletions;
bool forceOverwrite;
uint32_t error;
CacheableReader reader{data};
if (!reader.unserializei64(tag))
{
return {};
}
if (!reader.unserializebool(enabled))
{
return {};
}
if (!reader.unserializestring(localPath))
{
return {};
}
if (!reader.unserializestring(name))
{
return {};
}
if (!reader.unserializehandle(remoteNode))
{
return {};
}
if (!reader.unserializestring(remotePath))
{
return {};
}
if (!reader.unserializefsfp(fingerprint))
{
return {};
}
if (!reader.unserializeu32(regExpCount))
{
return {};
}
for (uint32_t i = 0; i < regExpCount; ++i)
{
std::string regExp;
if (!reader.unserializestring(regExp))
{
return {};
}
regExps.push_back(std::move(regExp));
}
if (!reader.unserializeu32(syncType))
{
return {};
}
if (!reader.unserializebool(syncDeletions))
{
return {};
}
if (!reader.unserializebool(forceOverwrite))
{
return {};
}
if (!reader.unserializeu32(error))
{
return {};
}
auto syncConfig = std::unique_ptr<SyncConfig>{new SyncConfig{static_cast<int>(tag), std::move(localPath), std::move(name),
remoteNode, std::move(remotePath), fingerprint, std::move(regExps), enabled,
static_cast<Type>(syncType), syncDeletions,
forceOverwrite, static_cast<SyncError>(error)}};
return syncConfig;
}
bool SyncConfig::serialize(std::string& data) const
{
CacheableWriter writer{data};
writer.serializei64(mTag);
writer.serializebool(mEnabled);
writer.serializestring(mLocalPath);
writer.serializestring(mName);
writer.serializehandle(mRemoteNode);
writer.serializestring(mRemotePath);
writer.serializefsfp(mLocalFingerprint);
writer.serializeu32(static_cast<uint32_t>(mRegExps.size()));
for (const auto& regExp : mRegExps)
{
writer.serializestring(regExp);
}
writer.serializeu32(static_cast<uint32_t>(mSyncType));
writer.serializebool(mSyncDeletions);
writer.serializebool(mForceOverwrite);
writer.serializeu32(static_cast<int>(mError));
writer.serializeexpansionflags();
return true;
}
std::pair<bool, int64_t> generateMetaMac(SymmCipher &cipher, FileAccess &ifAccess, const int64_t iv)
{
FileInputStream isAccess(&ifAccess);
return generateMetaMac(cipher, isAccess, iv);
}
std::pair<bool, int64_t> generateMetaMac(SymmCipher &cipher, InputStreamAccess &isAccess, const int64_t iv)
{
static const unsigned int SZ_1024K = 1l << 20;
static const unsigned int SZ_128K = 128l << 10;
std::unique_ptr<byte[]> buffer(new byte[SZ_1024K + SymmCipher::BLOCKSIZE]);
chunkmac_map chunkMacs;
unsigned int chunkLength = 0;
m_off_t current = 0;
m_off_t remaining = isAccess.size();
while (remaining > 0)
{
chunkLength =
std::min(chunkLength + SZ_128K,
static_cast<unsigned int>(std::min<m_off_t>(remaining, SZ_1024K)));
if (!isAccess.read(&buffer[0], chunkLength))
return std::make_pair(false, 0l);
memset(&buffer[chunkLength], 0, SymmCipher::BLOCKSIZE);
cipher.ctr_crypt(&buffer[0],
chunkLength,
current,
iv,
chunkMacs[current].mac,
1);
current += chunkLength;
remaining -= chunkLength;
}
return std::make_pair(true, chunkMacs.macsmac(&cipher));
}
void MegaClientAsyncQueue::push(std::function<void(SymmCipher&)> f, bool discardable)
{
if (mThreads.empty())
{
if (f)
{
f(mZeroThreadsCipher);
}
}
else
{
{
std::lock_guard<std::mutex> g(mMutex);
mQueue.emplace_back(discardable, std::move(f));
}
mConditionVariable.notify_one();
}
}
MegaClientAsyncQueue::MegaClientAsyncQueue(Waiter& w, unsigned threadCount)
: mWaiter(w)
{
for (int i = threadCount; i--; )
{
try
{
mThreads.emplace_back([this]()
{
asyncThreadLoop();
});
}
catch (std::system_error& e)
{
LOG_err << "Failed to start worker thread: " << e.what();
break;
}
}
LOG_debug << "MegaClient Worker threads running: " << mThreads.size();
}
MegaClientAsyncQueue::~MegaClientAsyncQueue()
{
clearDiscardable();
push(nullptr, false);
mConditionVariable.notify_all();
LOG_warn << "~MegaClientAsyncQueue() joining threads";
for (auto& t : mThreads)
{
t.join();
}
LOG_warn << "~MegaClientAsyncQueue() ends";
}
void MegaClientAsyncQueue::clearDiscardable()
{
std::lock_guard<std::mutex> g(mMutex);
auto newEnd = std::remove_if(mQueue.begin(), mQueue.end(), [](Entry& entry){ return entry.discardable; });
mQueue.erase(newEnd, mQueue.end());
}
void MegaClientAsyncQueue::asyncThreadLoop()
{
SymmCipher cipher;
for (;;)
{
std::function<void(SymmCipher&)> f;
{
std::unique_lock<std::mutex> g(mMutex);
mConditionVariable.wait(g, [this]() { return !mQueue.empty(); });
f = std::move(mQueue.front().f);
if (!f) return; // nullptr is not popped, and causes all the threads to exit
mQueue.pop_front();
}
f(cipher);
mWaiter.notify();
}
}
} // namespace
|
{
"pile_set_name": "Github"
}
|
FontAwesome, version 5.3.1
from https://github.com/FortAwesome/Font-Awesome/blob/master/LICENSE.txt
Font Awesome Free is free, open source, and GPL friendly. You can use it for
commercial projects, open source projects, or really almost whatever you want.
Full Font Awesome Free license: https://fontawesome.com/license/free.
# Icons: CC BY 4.0 License (https://creativecommons.org/licenses/by/4.0/)
In the Font Awesome Free download, the CC BY 4.0 license applies to all icons
packaged as SVG and JS file types.
# Fonts: SIL OFL 1.1 License (https://scripts.sil.org/OFL)
In the Font Awesome Free download, the SIL OLF license applies to all icons
packaged as web and desktop font files.
# Code: MIT License (https://opensource.org/licenses/MIT)
In the Font Awesome Free download, the MIT license applies to all non-font and
non-icon files.
# Attribution
Attribution is required by MIT, SIL OLF, and CC BY licenses. Downloaded Font
Awesome Free files already contain embedded comments with sufficient
attribution, so you shouldn't need to do anything additional when using these
files normally.
We've kept attribution comments terse, so we ask that you do not actively work
to remove them from files, especially code. They're a great way for folks to
learn about Font Awesome.
# Brand Icons
All brand icons are trademarks of their respective owners. The use of these
trademarks does not indicate endorsement of the trademark holder by Font
Awesome, nor vice versa. **Please do not use brand logos for any purpose except
to represent the company, product, or service to which they refer.**
|
{
"pile_set_name": "Github"
}
|
import express from 'express'
export function createApolloServerApp(apolloServer, { user } = {}) {
const app = express()
app.use((req, res, next) => {
req.user = user
next()
})
apolloServer.applyMiddleware({ app })
return app
}
|
{
"pile_set_name": "Github"
}
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
// Author: [email protected] (Kenton Varda)
//
// Deals with the fact that hash_map is not defined everywhere.
#ifndef GOOGLE_PROTOBUF_STUBS_HASH_H__
#define GOOGLE_PROTOBUF_STUBS_HASH_H__
#include <string.h>
#include <google/protobuf/stubs/common.h>
#define GOOGLE_PROTOBUF_HAVE_HASH_MAP 1
#define GOOGLE_PROTOBUF_HAVE_HASH_SET 1
// Android
#if defined(__ANDROID__)
# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP
# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP
// Use C++11 unordered_{map|set} if available.
#elif ((_LIBCPP_STD_VER >= 11) || \
(((__cplusplus >= 201103L) || defined(__GXX_EXPERIMENTAL_CXX0X)) && \
(__GLIBCXX__ > 20090421)))
# define GOOGLE_PROTOBUF_HAS_CXX11_HASH
// For XCode >= 4.6: the compiler is clang with libc++.
// For earlier XCode version: the compiler is gcc-4.2.1 with libstdc++.
// libc++ provides <unordered_map> and friends even in non C++11 mode,
// and it does not provide the tr1 library. Therefore the following macro
// checks against this special case.
// Note that we should not test the __APPLE_CC__ version number or the
// __clang__ macro, since the new compiler can still use -stdlib=libstdc++, in
// which case <unordered_map> is not compilable without -std=c++11
#elif defined(__APPLE_CC__)
# if __GNUC__ >= 4
# define GOOGLE_PROTOBUF_HAS_TR1
# else
// Not tested for gcc < 4... These setting can compile under 4.2.1 though.
# define GOOGLE_PROTOBUF_HASH_NAMESPACE __gnu_cxx
# include <ext/hash_map>
# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
# include <ext/hash_set>
# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
# endif
// Version checks for gcc.
#elif defined(__GNUC__)
// For GCC 4.x+, use tr1::unordered_map/set; otherwise, follow the
// instructions from:
// https://gcc.gnu.org/onlinedocs/libstdc++/manual/backwards.html
# if __GNUC__ >= 4
# define GOOGLE_PROTOBUF_HAS_TR1
# elif __GNUC__ >= 3
# include <backward/hash_map>
# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
# include <backward/hash_set>
# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
# if __GNUC__ == 3 && __GNUC_MINOR__ == 0
# define GOOGLE_PROTOBUF_HASH_NAMESPACE std // GCC 3.0
# else
# define GOOGLE_PROTOBUF_HASH_NAMESPACE __gnu_cxx // GCC 3.1 and later
# endif
# else
# define GOOGLE_PROTOBUF_HASH_NAMESPACE
# include <hash_map>
# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
# include <hash_set>
# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
# endif
// Version checks for MSC.
// Apparently Microsoft decided to move hash_map *back* to the std namespace in
// MSVC 2010:
// http://blogs.msdn.com/vcblog/archive/2009/05/25/stl-breaking-changes-in-visual-studio-2010-beta-1.aspx
// And.. they are moved back to stdext in MSVC 2013 (haven't checked 2012). That
// said, use unordered_map for MSVC 2010 and beyond is our safest bet.
#elif defined(_MSC_VER)
# if _MSC_VER >= 1600 // Since Visual Studio 2010
# define GOOGLE_PROTOBUF_HAS_CXX11_HASH
# define GOOGLE_PROTOBUF_HASH_COMPARE std::hash_compare
# elif _MSC_VER >= 1500 // Since Visual Studio 2008
# define GOOGLE_PROTOBUF_HASH_NAMESPACE stdext
# include <hash_map>
# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
# include <hash_set>
# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare
# define GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE
# elif _MSC_VER >= 1310
# define GOOGLE_PROTOBUF_HASH_NAMESPACE stdext
# include <hash_map>
# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
# include <hash_set>
# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare
# else
# define GOOGLE_PROTOBUF_HASH_NAMESPACE std
# include <hash_map>
# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
# include <hash_set>
# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare
# endif
// **ADD NEW COMPILERS SUPPORT HERE.**
// For other compilers, undefine the macro and fallback to use std::map, in
// google/protobuf/stubs/hash.h
#else
# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP
# undef GOOGLE_PROTOBUF_HAVE_HASH_SET
#endif
#if defined(GOOGLE_PROTOBUF_HAS_CXX11_HASH)
# define GOOGLE_PROTOBUF_HASH_NAMESPACE std
# include <unordered_map>
# define GOOGLE_PROTOBUF_HASH_MAP_CLASS unordered_map
# include <unordered_set>
# define GOOGLE_PROTOBUF_HASH_SET_CLASS unordered_set
#elif defined(GOOGLE_PROTOBUF_HAS_TR1)
# define GOOGLE_PROTOBUF_HASH_NAMESPACE std::tr1
# include <tr1/unordered_map>
# define GOOGLE_PROTOBUF_HASH_MAP_CLASS unordered_map
# include <tr1/unordered_set>
# define GOOGLE_PROTOBUF_HASH_SET_CLASS unordered_set
#endif
# define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START \
namespace google { \
namespace protobuf {
# define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END }}
#undef GOOGLE_PROTOBUF_HAS_CXX11_HASH
#undef GOOGLE_PROTOBUF_HAS_TR1
#if defined(GOOGLE_PROTOBUF_HAVE_HASH_MAP) && \
defined(GOOGLE_PROTOBUF_HAVE_HASH_SET)
#else
#define GOOGLE_PROTOBUF_MISSING_HASH
#include <map>
#include <set>
#endif
namespace google {
namespace protobuf {
#ifdef GOOGLE_PROTOBUF_MISSING_HASH
#undef GOOGLE_PROTOBUF_MISSING_HASH
// This system doesn't have hash_map or hash_set. Emulate them using map and
// set.
// Make hash<T> be the same as less<T>. Note that everywhere where custom
// hash functions are defined in the protobuf code, they are also defined such
// that they can be used as "less" functions, which is required by MSVC anyway.
template <typename Key>
struct hash {
// Dummy, just to make derivative hash functions compile.
int operator()(const Key& key) {
GOOGLE_LOG(FATAL) << "Should never be called.";
return 0;
}
inline bool operator()(const Key& a, const Key& b) const {
return a < b;
}
};
// Make sure char* is compared by value.
template <>
struct hash<const char*> {
// Dummy, just to make derivative hash functions compile.
int operator()(const char* key) {
GOOGLE_LOG(FATAL) << "Should never be called.";
return 0;
}
inline bool operator()(const char* a, const char* b) const {
return strcmp(a, b) < 0;
}
};
template <typename Key, typename Data,
typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key>,
typename Alloc = std::allocator< std::pair<const Key, Data> > >
class hash_map : public std::map<Key, Data, HashFcn, Alloc> {
typedef std::map<Key, Data, HashFcn, Alloc> BaseClass;
public:
hash_map(int a = 0, const HashFcn& b = HashFcn(),
const EqualKey& c = EqualKey(),
const Alloc& d = Alloc()) : BaseClass(b, d) {}
HashFcn hash_function() const { return HashFcn(); }
};
template <typename Key,
typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key> >
class hash_set : public std::set<Key, HashFcn> {
public:
hash_set(int = 0) {}
HashFcn hash_function() const { return HashFcn(); }
};
#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION)
template <typename Key>
struct hash : public GOOGLE_PROTOBUF_HASH_COMPARE<Key> {
};
// MSVC's hash_compare<const char*> hashes based on the string contents but
// compares based on the string pointer. WTF?
class CstringLess {
public:
inline bool operator()(const char* a, const char* b) const {
return strcmp(a, b) < 0;
}
};
template <>
struct hash<const char*>
: public GOOGLE_PROTOBUF_HASH_COMPARE<const char*, CstringLess> {};
#ifdef GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE
template <typename Key, typename HashFcn, typename EqualKey>
struct InternalHashCompare : public GOOGLE_PROTOBUF_HASH_COMPARE<Key> {
InternalHashCompare() {}
InternalHashCompare(HashFcn hashfcn, EqualKey equalkey)
: hashfcn_(hashfcn), equalkey_(equalkey) {}
size_t operator()(const Key& key) const { return hashfcn_(key); }
bool operator()(const Key& key1, const Key& key2) const {
return !equalkey_(key1, key2);
}
HashFcn hashfcn_;
EqualKey equalkey_;
};
template <typename Key, typename Data,
typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key>,
typename Alloc = std::allocator< std::pair<const Key, Data> > >
class hash_map
: public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
Key, Data, InternalHashCompare<Key, HashFcn, EqualKey>, Alloc> {
typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
Key, Data, InternalHashCompare<Key, HashFcn, EqualKey>, Alloc> BaseClass;
public:
hash_map(int a = 0, const HashFcn& b = HashFcn(),
const EqualKey& c = EqualKey(), const Alloc& d = Alloc())
: BaseClass(InternalHashCompare<Key, HashFcn, EqualKey>(b, c), d) {}
HashFcn hash_function() const { return HashFcn(); }
};
template <typename Key, typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key> >
class hash_set
: public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS<
Key, InternalHashCompare<Key, HashFcn, EqualKey> > {
public:
hash_set(int = 0) {}
HashFcn hash_function() const { return HashFcn(); }
};
#else // GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE
template <typename Key, typename Data,
typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key>,
typename Alloc = std::allocator< std::pair<const Key, Data> > >
class hash_map
: public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
Key, Data, HashFcn, EqualKey, Alloc> {
typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
Key, Data, HashFcn, EqualKey, Alloc> BaseClass;
public:
hash_map(int a = 0, const HashFcn& b = HashFcn(),
const EqualKey& c = EqualKey(),
const Alloc& d = Alloc()) : BaseClass(a, b, c, d) {}
HashFcn hash_function() const { return HashFcn(); }
};
template <typename Key, typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key> >
class hash_set
: public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS<
Key, HashFcn, EqualKey> {
public:
hash_set(int = 0) {}
HashFcn hash_function() const { return HashFcn(); }
};
#endif // GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE
#else // defined(_MSC_VER) && !defined(_STLPORT_VERSION)
template <typename Key>
struct hash : public GOOGLE_PROTOBUF_HASH_NAMESPACE::hash<Key> {
};
template <typename Key>
struct hash<const Key*> {
inline size_t operator()(const Key* key) const {
return reinterpret_cast<size_t>(key);
}
};
// Unlike the old SGI version, the TR1 "hash" does not special-case char*. So,
// we go ahead and provide our own implementation.
template <>
struct hash<const char*> {
inline size_t operator()(const char* str) const {
size_t result = 0;
for (; *str != '\0'; str++) {
result = 5 * result + *str;
}
return result;
}
};
template<>
struct hash<bool> {
size_t operator()(bool x) const {
return static_cast<size_t>(x);
}
};
template <typename Key, typename Data,
typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key>,
typename Alloc = std::allocator< std::pair<const Key, Data> > >
class hash_map
: public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
Key, Data, HashFcn, EqualKey, Alloc> {
typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
Key, Data, HashFcn, EqualKey, Alloc> BaseClass;
public:
hash_map(int a = 0, const HashFcn& b = HashFcn(),
const EqualKey& c = EqualKey(),
const Alloc& d = Alloc()) : BaseClass(a, b, c, d) {}
HashFcn hash_function() const { return HashFcn(); }
};
template <typename Key, typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key> >
class hash_set
: public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS<
Key, HashFcn, EqualKey> {
public:
hash_set(int = 0) {}
HashFcn hash_function() const { return HashFcn(); }
};
#endif // !GOOGLE_PROTOBUF_MISSING_HASH
template <>
struct hash<string> {
inline size_t operator()(const string& key) const {
return hash<const char*>()(key.c_str());
}
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
inline bool operator()(const string& a, const string& b) const {
return a < b;
}
};
template <typename First, typename Second>
struct hash<pair<First, Second> > {
inline size_t operator()(const pair<First, Second>& key) const {
size_t first_hash = hash<First>()(key.first);
size_t second_hash = hash<Second>()(key.second);
// FIXME(kenton): What is the best way to compute this hash? I have
// no idea! This seems a bit better than an XOR.
return first_hash * ((1 << 16) - 1) + second_hash;
}
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
inline bool operator()(const pair<First, Second>& a,
const pair<First, Second>& b) const {
return a < b;
}
};
// Used by GCC/SGI STL only. (Why isn't this provided by the standard
// library? :( )
struct streq {
inline bool operator()(const char* a, const char* b) const {
return strcmp(a, b) == 0;
}
};
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_STUBS_HASH_H__
|
{
"pile_set_name": "Github"
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <experimental/algorithm>
#include <experimental/algorithm>
#include "test_macros.h"
#ifndef _LIBCPP_VERSION
# error _LIBCPP_VERSION not defined
#endif
int main(int, char**)
{
return 0;
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright 2012 Impetus Infotech.
*
* 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.impetus.kundera.persistence.context;
import java.util.Deque;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.impetus.kundera.graph.Node;
/**
* Test case for {@link FlushStack}
*
* @author amresh.singh
*/
public class FlushStackTest
{
Deque<Node> fs;
FlushManager flushManager;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
flushManager = new FlushManager();
fs = flushManager.getFlushStack();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
}
@Test
public void testFlushStackPush()
{
PersistenceCache pc = new PersistenceCache();
fs.push(new Node("A", new Object().getClass(), null, pc, "A", null));
fs.push(new Node("B", new Object().getClass(), null, pc, "B", null));
fs.push(new Node("C", new Object().getClass(), null, pc, "C", null));
fs.push(new Node("D", new Object().getClass(), null, pc, "D", null));
Assert.assertEquals(4, fs.size());
}
}
|
{
"pile_set_name": "Github"
}
|
IDEAS & ISSUES FOR FUTURE DEVELOPMENT
=====================================
Problems to solve / Things to consider about OSM commands in GeoGig
---------------------------------------------------------------------
1. Updating
~~~~~~~~~~~~
The current update command just re-downloads with the last filter, but is not a smart download, and downloads everything. The `Overpass API <http://wiki.openstreetmap.org/wiki/Overpass_API>`_ allows to fetch only features newer than a given data, but that cannot be used if there are deletions, since it does not report deleted elements.
The OSM API allows to download history, including deletions, but does not support filters.
Ideally, a mix of both functionalities would be needed for geogig to work optimally
2. Unmapping of ways
~~~~~~~~~~~~~~~~~~~~~
When a way is unmapped, its geometry is used to re-create the list of nodes. The best way would be to take the coords of the nodes and check if a node exist in each coordinate, and if so, take the node id, otherwise, add a new node. This is, however, not possible now, since it would not be efficient. GeoGig has no spatial indexing, and searching a feature by its coordinates is not an available operation.
The current implementation just retrieves the nodes that belonged to the way in the last version, and check the current geometry against them. This is fine if all new nodes are actually new, but if the way uses a node that it did not use before but that exists already, that node will not be used (since there is no way of retrieving the id of the node in that coord), and a new one in that same position is added.
3. Updating new entities
~~~~~~~~~~~~~~~~~~~~~~~~~
When a new node is added (whether by the user, who created it in something like JOSM, or by an unmap operation), new entities get a negative ID, as it seems customary in OSM before committing them. Once submitted, they get a valid ID, and when later updating, the Id's will not match, so GeoGig will not replace them, leaving both versions.
This is, in fact, not a problem now, since the update operation just deletes and updates everything (see (1)), but once we get a more efficient update strategy, this problem will surface.
OSM paths
----------
.. note:: [This is just an idea, not implemented yet. Is it a good idea??]
The default paths for OSM data are ``way`` and ``node``. they should contain just OSM data imported using the corresponding GeoGig commands. To use those paths for different data and avoid problem with OSM commands, the default paths can be changed using the ``config`` command. Default paths are kept in the ``osm.nodepath`` and ``osm.waypath`` config parameters, which can be configured as shown in the example below.
::
$ geogig config osm.nodepath osmnode
$ geogig config osm.waypath osmway
|
{
"pile_set_name": "Github"
}
|
# Tenko parser test case
- Path: tests/testcases/operator_precedent/sanity_canaries/mul_and_urhs_xor_instanceof_plus_lor_land_eq_or_pow.one.rev.md
> :: operator precedent : sanity canaries
>
> ::> mul and urhs xor instanceof plus lor land eq or pow.one.rev
>
> Random ops to test for precedence
## Input
`````js
x0 * x1 & x2 >>> x3 ^ x4 instanceof x5 + x6 || x7 && x8 == x9 | x10 ** x
`````
## Output
_Note: the whole output block is auto-generated. Manual changes will be overwritten!_
Below follow outputs in five parsing modes: sloppy, sloppy+annexb, strict script, module, module+annexb.
Note that the output parts are auto-generated by the test runner to reflect actual result.
### Sloppy mode
Parsed with script goal and as if the code did not start with strict mode header.
`````
ast: {
type: 'Program',
loc:{start:{line:1,column:0},end:{line:1,column:72},source:''},
body: [
{
type: 'ExpressionStatement',
loc:{start:{line:1,column:0},end:{line:1,column:72},source:''},
expression: {
type: 'LogicalExpression',
loc:{start:{line:1,column:0},end:{line:1,column:72},source:''},
left: {
type: 'BinaryExpression',
loc:{start:{line:1,column:0},end:{line:1,column:43},source:''},
left: {
type: 'BinaryExpression',
loc:{start:{line:1,column:0},end:{line:1,column:19},source:''},
left: {
type: 'BinaryExpression',
loc:{start:{line:1,column:0},end:{line:1,column:7},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:0},end:{line:1,column:2},source:''},
name: 'x0'
},
operator: '*',
right: {
type: 'Identifier',
loc:{start:{line:1,column:5},end:{line:1,column:7},source:''},
name: 'x1'
}
},
operator: '&',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:10},end:{line:1,column:19},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:10},end:{line:1,column:12},source:''},
name: 'x2'
},
operator: '>>>',
right: {
type: 'Identifier',
loc:{start:{line:1,column:17},end:{line:1,column:19},source:''},
name: 'x3'
}
}
},
operator: '^',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:22},end:{line:1,column:43},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:22},end:{line:1,column:24},source:''},
name: 'x4'
},
operator: 'instanceof',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:36},end:{line:1,column:43},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:36},end:{line:1,column:38},source:''},
name: 'x5'
},
operator: '+',
right: {
type: 'Identifier',
loc:{start:{line:1,column:41},end:{line:1,column:43},source:''},
name: 'x6'
}
}
}
},
operator: '||',
right: {
type: 'LogicalExpression',
loc:{start:{line:1,column:47},end:{line:1,column:72},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:47},end:{line:1,column:49},source:''},
name: 'x7'
},
operator: '&&',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:53},end:{line:1,column:72},source:''},
left: {
type: 'BinaryExpression',
loc:{start:{line:1,column:53},end:{line:1,column:61},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:53},end:{line:1,column:55},source:''},
name: 'x8'
},
operator: '==',
right: {
type: 'Identifier',
loc:{start:{line:1,column:59},end:{line:1,column:61},source:''},
name: 'x9'
}
},
operator: '|',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:64},end:{line:1,column:72},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:64},end:{line:1,column:67},source:''},
name: 'x10'
},
operator: '**',
right: {
type: 'Identifier',
loc:{start:{line:1,column:71},end:{line:1,column:72},source:''},
name: 'x'
}
}
}
}
}
}
]
}
tokens (25x):
IDENT PUNC_STAR IDENT PUNC_AND IDENT PUNC_GT_GT_GT IDENT
PUNC_CARET IDENT ID_instanceof IDENT PUNC_PLUS IDENT PUNC_OR_OR
IDENT PUNC_AND_AND IDENT PUNC_EQ_EQ IDENT PUNC_OR IDENT
PUNC_STAR_STAR IDENT ASI
`````
### Strict mode
Parsed with script goal but as if it was starting with `"use strict"` at the top.
_Output same as sloppy mode._
### Module goal
Parsed with the module goal.
_Output same as sloppy mode._
### Sloppy mode with AnnexB
Parsed with script goal with AnnexB rules enabled and as if the code did not start with strict mode header.
_Output same as sloppy mode._
### Module goal with AnnexB
Parsed with the module goal with AnnexB rules enabled.
_Output same as sloppy mode._
## AST Printer
Printer output different from input [sloppy][annexb:no]:
````js
((((x0 * x1) & (x2 >>> x3)) ^ (x4 instanceof (x5 + x6))) || ((x7 && ((x8 == x9) | (x10 ** x)))));
````
Produces same AST
|
{
"pile_set_name": "Github"
}
|
/*
* zfcp device driver
*
* sysfs attributes.
*
* Copyright IBM Corp. 2008, 2010
*/
#define KMSG_COMPONENT "zfcp"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/slab.h>
#include "zfcp_ext.h"
#define ZFCP_DEV_ATTR(_feat, _name, _mode, _show, _store) \
struct device_attribute dev_attr_##_feat##_##_name = __ATTR(_name, _mode,\
_show, _store)
#define ZFCP_DEFINE_ATTR(_feat_def, _feat, _name, _format, _value) \
static ssize_t zfcp_sysfs_##_feat##_##_name##_show(struct device *dev, \
struct device_attribute *at,\
char *buf) \
{ \
struct _feat_def *_feat = container_of(dev, struct _feat_def, dev); \
\
return sprintf(buf, _format, _value); \
} \
static ZFCP_DEV_ATTR(_feat, _name, S_IRUGO, \
zfcp_sysfs_##_feat##_##_name##_show, NULL);
#define ZFCP_DEFINE_ATTR_CONST(_feat, _name, _format, _value) \
static ssize_t zfcp_sysfs_##_feat##_##_name##_show(struct device *dev, \
struct device_attribute *at,\
char *buf) \
{ \
return sprintf(buf, _format, _value); \
} \
static ZFCP_DEV_ATTR(_feat, _name, S_IRUGO, \
zfcp_sysfs_##_feat##_##_name##_show, NULL);
#define ZFCP_DEFINE_A_ATTR(_name, _format, _value) \
static ssize_t zfcp_sysfs_adapter_##_name##_show(struct device *dev, \
struct device_attribute *at,\
char *buf) \
{ \
struct ccw_device *cdev = to_ccwdev(dev); \
struct zfcp_adapter *adapter = zfcp_ccw_adapter_by_cdev(cdev); \
int i; \
\
if (!adapter) \
return -ENODEV; \
\
i = sprintf(buf, _format, _value); \
zfcp_ccw_adapter_put(adapter); \
return i; \
} \
static ZFCP_DEV_ATTR(adapter, _name, S_IRUGO, \
zfcp_sysfs_adapter_##_name##_show, NULL);
ZFCP_DEFINE_A_ATTR(status, "0x%08x\n", atomic_read(&adapter->status));
ZFCP_DEFINE_A_ATTR(peer_wwnn, "0x%016llx\n",
(unsigned long long) adapter->peer_wwnn);
ZFCP_DEFINE_A_ATTR(peer_wwpn, "0x%016llx\n",
(unsigned long long) adapter->peer_wwpn);
ZFCP_DEFINE_A_ATTR(peer_d_id, "0x%06x\n", adapter->peer_d_id);
ZFCP_DEFINE_A_ATTR(card_version, "0x%04x\n", adapter->hydra_version);
ZFCP_DEFINE_A_ATTR(lic_version, "0x%08x\n", adapter->fsf_lic_version);
ZFCP_DEFINE_A_ATTR(hardware_version, "0x%08x\n", adapter->hardware_version);
ZFCP_DEFINE_A_ATTR(in_recovery, "%d\n", (atomic_read(&adapter->status) &
ZFCP_STATUS_COMMON_ERP_INUSE) != 0);
ZFCP_DEFINE_ATTR(zfcp_port, port, status, "0x%08x\n",
atomic_read(&port->status));
ZFCP_DEFINE_ATTR(zfcp_port, port, in_recovery, "%d\n",
(atomic_read(&port->status) &
ZFCP_STATUS_COMMON_ERP_INUSE) != 0);
ZFCP_DEFINE_ATTR_CONST(port, access_denied, "%d\n", 0);
ZFCP_DEFINE_ATTR(zfcp_unit, unit, status, "0x%08x\n",
zfcp_unit_sdev_status(unit));
ZFCP_DEFINE_ATTR(zfcp_unit, unit, in_recovery, "%d\n",
(zfcp_unit_sdev_status(unit) &
ZFCP_STATUS_COMMON_ERP_INUSE) != 0);
ZFCP_DEFINE_ATTR(zfcp_unit, unit, access_denied, "%d\n",
(zfcp_unit_sdev_status(unit) &
ZFCP_STATUS_COMMON_ACCESS_DENIED) != 0);
ZFCP_DEFINE_ATTR_CONST(unit, access_shared, "%d\n", 0);
ZFCP_DEFINE_ATTR_CONST(unit, access_readonly, "%d\n", 0);
static ssize_t zfcp_sysfs_port_failed_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct zfcp_port *port = container_of(dev, struct zfcp_port, dev);
if (atomic_read(&port->status) & ZFCP_STATUS_COMMON_ERP_FAILED)
return sprintf(buf, "1\n");
return sprintf(buf, "0\n");
}
static ssize_t zfcp_sysfs_port_failed_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct zfcp_port *port = container_of(dev, struct zfcp_port, dev);
unsigned long val;
if (kstrtoul(buf, 0, &val) || val != 0)
return -EINVAL;
zfcp_erp_set_port_status(port, ZFCP_STATUS_COMMON_RUNNING);
zfcp_erp_port_reopen(port, ZFCP_STATUS_COMMON_ERP_FAILED, "sypfai2");
zfcp_erp_wait(port->adapter);
return count;
}
static ZFCP_DEV_ATTR(port, failed, S_IWUSR | S_IRUGO,
zfcp_sysfs_port_failed_show,
zfcp_sysfs_port_failed_store);
static ssize_t zfcp_sysfs_unit_failed_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct zfcp_unit *unit = container_of(dev, struct zfcp_unit, dev);
struct scsi_device *sdev;
unsigned int status, failed = 1;
sdev = zfcp_unit_sdev(unit);
if (sdev) {
status = atomic_read(&sdev_to_zfcp(sdev)->status);
failed = status & ZFCP_STATUS_COMMON_ERP_FAILED ? 1 : 0;
scsi_device_put(sdev);
}
return sprintf(buf, "%d\n", failed);
}
static ssize_t zfcp_sysfs_unit_failed_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct zfcp_unit *unit = container_of(dev, struct zfcp_unit, dev);
unsigned long val;
struct scsi_device *sdev;
if (kstrtoul(buf, 0, &val) || val != 0)
return -EINVAL;
sdev = zfcp_unit_sdev(unit);
if (sdev) {
zfcp_erp_set_lun_status(sdev, ZFCP_STATUS_COMMON_RUNNING);
zfcp_erp_lun_reopen(sdev, ZFCP_STATUS_COMMON_ERP_FAILED,
"syufai2");
zfcp_erp_wait(unit->port->adapter);
} else
zfcp_unit_scsi_scan(unit);
return count;
}
static ZFCP_DEV_ATTR(unit, failed, S_IWUSR | S_IRUGO,
zfcp_sysfs_unit_failed_show,
zfcp_sysfs_unit_failed_store);
static ssize_t zfcp_sysfs_adapter_failed_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct ccw_device *cdev = to_ccwdev(dev);
struct zfcp_adapter *adapter = zfcp_ccw_adapter_by_cdev(cdev);
int i;
if (!adapter)
return -ENODEV;
if (atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_ERP_FAILED)
i = sprintf(buf, "1\n");
else
i = sprintf(buf, "0\n");
zfcp_ccw_adapter_put(adapter);
return i;
}
static ssize_t zfcp_sysfs_adapter_failed_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ccw_device *cdev = to_ccwdev(dev);
struct zfcp_adapter *adapter = zfcp_ccw_adapter_by_cdev(cdev);
unsigned long val;
int retval = 0;
if (!adapter)
return -ENODEV;
if (kstrtoul(buf, 0, &val) || val != 0) {
retval = -EINVAL;
goto out;
}
zfcp_erp_set_adapter_status(adapter, ZFCP_STATUS_COMMON_RUNNING);
zfcp_erp_adapter_reopen(adapter, ZFCP_STATUS_COMMON_ERP_FAILED,
"syafai2");
zfcp_erp_wait(adapter);
out:
zfcp_ccw_adapter_put(adapter);
return retval ? retval : (ssize_t) count;
}
static ZFCP_DEV_ATTR(adapter, failed, S_IWUSR | S_IRUGO,
zfcp_sysfs_adapter_failed_show,
zfcp_sysfs_adapter_failed_store);
static ssize_t zfcp_sysfs_port_rescan_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ccw_device *cdev = to_ccwdev(dev);
struct zfcp_adapter *adapter = zfcp_ccw_adapter_by_cdev(cdev);
if (!adapter)
return -ENODEV;
/*
* Users wish is our command: immediately schedule and flush a
* worker to conduct a synchronous port scan, that is, neither
* a random delay nor a rate limit is applied here.
*/
queue_delayed_work(adapter->work_queue, &adapter->scan_work, 0);
flush_delayed_work(&adapter->scan_work);
zfcp_ccw_adapter_put(adapter);
return (ssize_t) count;
}
static ZFCP_DEV_ATTR(adapter, port_rescan, S_IWUSR, NULL,
zfcp_sysfs_port_rescan_store);
DEFINE_MUTEX(zfcp_sysfs_port_units_mutex);
static ssize_t zfcp_sysfs_port_remove_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ccw_device *cdev = to_ccwdev(dev);
struct zfcp_adapter *adapter = zfcp_ccw_adapter_by_cdev(cdev);
struct zfcp_port *port;
u64 wwpn;
int retval = -EINVAL;
if (!adapter)
return -ENODEV;
if (kstrtoull(buf, 0, (unsigned long long *) &wwpn))
goto out;
port = zfcp_get_port_by_wwpn(adapter, wwpn);
if (!port)
goto out;
else
retval = 0;
mutex_lock(&zfcp_sysfs_port_units_mutex);
if (atomic_read(&port->units) > 0) {
retval = -EBUSY;
mutex_unlock(&zfcp_sysfs_port_units_mutex);
goto out;
}
/* port is about to be removed, so no more unit_add */
atomic_set(&port->units, -1);
mutex_unlock(&zfcp_sysfs_port_units_mutex);
write_lock_irq(&adapter->port_list_lock);
list_del(&port->list);
write_unlock_irq(&adapter->port_list_lock);
put_device(&port->dev);
zfcp_erp_port_shutdown(port, 0, "syprs_1");
device_unregister(&port->dev);
out:
zfcp_ccw_adapter_put(adapter);
return retval ? retval : (ssize_t) count;
}
static ZFCP_DEV_ATTR(adapter, port_remove, S_IWUSR, NULL,
zfcp_sysfs_port_remove_store);
static struct attribute *zfcp_adapter_attrs[] = {
&dev_attr_adapter_failed.attr,
&dev_attr_adapter_in_recovery.attr,
&dev_attr_adapter_port_remove.attr,
&dev_attr_adapter_port_rescan.attr,
&dev_attr_adapter_peer_wwnn.attr,
&dev_attr_adapter_peer_wwpn.attr,
&dev_attr_adapter_peer_d_id.attr,
&dev_attr_adapter_card_version.attr,
&dev_attr_adapter_lic_version.attr,
&dev_attr_adapter_status.attr,
&dev_attr_adapter_hardware_version.attr,
NULL
};
struct attribute_group zfcp_sysfs_adapter_attrs = {
.attrs = zfcp_adapter_attrs,
};
static ssize_t zfcp_sysfs_unit_add_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct zfcp_port *port = container_of(dev, struct zfcp_port, dev);
u64 fcp_lun;
int retval;
if (kstrtoull(buf, 0, (unsigned long long *) &fcp_lun))
return -EINVAL;
retval = zfcp_unit_add(port, fcp_lun);
if (retval)
return retval;
return count;
}
static DEVICE_ATTR(unit_add, S_IWUSR, NULL, zfcp_sysfs_unit_add_store);
static ssize_t zfcp_sysfs_unit_remove_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct zfcp_port *port = container_of(dev, struct zfcp_port, dev);
u64 fcp_lun;
if (kstrtoull(buf, 0, (unsigned long long *) &fcp_lun))
return -EINVAL;
if (zfcp_unit_remove(port, fcp_lun))
return -EINVAL;
return count;
}
static DEVICE_ATTR(unit_remove, S_IWUSR, NULL, zfcp_sysfs_unit_remove_store);
static struct attribute *zfcp_port_attrs[] = {
&dev_attr_unit_add.attr,
&dev_attr_unit_remove.attr,
&dev_attr_port_failed.attr,
&dev_attr_port_in_recovery.attr,
&dev_attr_port_status.attr,
&dev_attr_port_access_denied.attr,
NULL
};
static struct attribute_group zfcp_port_attr_group = {
.attrs = zfcp_port_attrs,
};
const struct attribute_group *zfcp_port_attr_groups[] = {
&zfcp_port_attr_group,
NULL,
};
static struct attribute *zfcp_unit_attrs[] = {
&dev_attr_unit_failed.attr,
&dev_attr_unit_in_recovery.attr,
&dev_attr_unit_status.attr,
&dev_attr_unit_access_denied.attr,
&dev_attr_unit_access_shared.attr,
&dev_attr_unit_access_readonly.attr,
NULL
};
static struct attribute_group zfcp_unit_attr_group = {
.attrs = zfcp_unit_attrs,
};
const struct attribute_group *zfcp_unit_attr_groups[] = {
&zfcp_unit_attr_group,
NULL,
};
#define ZFCP_DEFINE_LATENCY_ATTR(_name) \
static ssize_t \
zfcp_sysfs_unit_##_name##_latency_show(struct device *dev, \
struct device_attribute *attr, \
char *buf) { \
struct scsi_device *sdev = to_scsi_device(dev); \
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev); \
struct zfcp_latencies *lat = &zfcp_sdev->latencies; \
struct zfcp_adapter *adapter = zfcp_sdev->port->adapter; \
unsigned long long fsum, fmin, fmax, csum, cmin, cmax, cc; \
\
spin_lock_bh(&lat->lock); \
fsum = lat->_name.fabric.sum * adapter->timer_ticks; \
fmin = lat->_name.fabric.min * adapter->timer_ticks; \
fmax = lat->_name.fabric.max * adapter->timer_ticks; \
csum = lat->_name.channel.sum * adapter->timer_ticks; \
cmin = lat->_name.channel.min * adapter->timer_ticks; \
cmax = lat->_name.channel.max * adapter->timer_ticks; \
cc = lat->_name.counter; \
spin_unlock_bh(&lat->lock); \
\
do_div(fsum, 1000); \
do_div(fmin, 1000); \
do_div(fmax, 1000); \
do_div(csum, 1000); \
do_div(cmin, 1000); \
do_div(cmax, 1000); \
\
return sprintf(buf, "%llu %llu %llu %llu %llu %llu %llu\n", \
fmin, fmax, fsum, cmin, cmax, csum, cc); \
} \
static ssize_t \
zfcp_sysfs_unit_##_name##_latency_store(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct scsi_device *sdev = to_scsi_device(dev); \
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev); \
struct zfcp_latencies *lat = &zfcp_sdev->latencies; \
unsigned long flags; \
\
spin_lock_irqsave(&lat->lock, flags); \
lat->_name.fabric.sum = 0; \
lat->_name.fabric.min = 0xFFFFFFFF; \
lat->_name.fabric.max = 0; \
lat->_name.channel.sum = 0; \
lat->_name.channel.min = 0xFFFFFFFF; \
lat->_name.channel.max = 0; \
lat->_name.counter = 0; \
spin_unlock_irqrestore(&lat->lock, flags); \
\
return (ssize_t) count; \
} \
static DEVICE_ATTR(_name##_latency, S_IWUSR | S_IRUGO, \
zfcp_sysfs_unit_##_name##_latency_show, \
zfcp_sysfs_unit_##_name##_latency_store);
ZFCP_DEFINE_LATENCY_ATTR(read);
ZFCP_DEFINE_LATENCY_ATTR(write);
ZFCP_DEFINE_LATENCY_ATTR(cmd);
#define ZFCP_DEFINE_SCSI_ATTR(_name, _format, _value) \
static ssize_t zfcp_sysfs_scsi_##_name##_show(struct device *dev, \
struct device_attribute *attr,\
char *buf) \
{ \
struct scsi_device *sdev = to_scsi_device(dev); \
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev); \
\
return sprintf(buf, _format, _value); \
} \
static DEVICE_ATTR(_name, S_IRUGO, zfcp_sysfs_scsi_##_name##_show, NULL);
ZFCP_DEFINE_SCSI_ATTR(hba_id, "%s\n",
dev_name(&zfcp_sdev->port->adapter->ccw_device->dev));
ZFCP_DEFINE_SCSI_ATTR(wwpn, "0x%016llx\n",
(unsigned long long) zfcp_sdev->port->wwpn);
static ssize_t zfcp_sysfs_scsi_fcp_lun_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct scsi_device *sdev = to_scsi_device(dev);
return sprintf(buf, "0x%016llx\n", zfcp_scsi_dev_lun(sdev));
}
static DEVICE_ATTR(fcp_lun, S_IRUGO, zfcp_sysfs_scsi_fcp_lun_show, NULL);
ZFCP_DEFINE_SCSI_ATTR(zfcp_access_denied, "%d\n",
(atomic_read(&zfcp_sdev->status) &
ZFCP_STATUS_COMMON_ACCESS_DENIED) != 0);
static ssize_t zfcp_sysfs_scsi_zfcp_failed_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct scsi_device *sdev = to_scsi_device(dev);
unsigned int status = atomic_read(&sdev_to_zfcp(sdev)->status);
unsigned int failed = status & ZFCP_STATUS_COMMON_ERP_FAILED ? 1 : 0;
return sprintf(buf, "%d\n", failed);
}
static ssize_t zfcp_sysfs_scsi_zfcp_failed_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct scsi_device *sdev = to_scsi_device(dev);
unsigned long val;
if (kstrtoul(buf, 0, &val) || val != 0)
return -EINVAL;
zfcp_erp_set_lun_status(sdev, ZFCP_STATUS_COMMON_RUNNING);
zfcp_erp_lun_reopen(sdev, ZFCP_STATUS_COMMON_ERP_FAILED,
"syufai3");
zfcp_erp_wait(sdev_to_zfcp(sdev)->port->adapter);
return count;
}
static DEVICE_ATTR(zfcp_failed, S_IWUSR | S_IRUGO,
zfcp_sysfs_scsi_zfcp_failed_show,
zfcp_sysfs_scsi_zfcp_failed_store);
ZFCP_DEFINE_SCSI_ATTR(zfcp_in_recovery, "%d\n",
(atomic_read(&zfcp_sdev->status) &
ZFCP_STATUS_COMMON_ERP_INUSE) != 0);
ZFCP_DEFINE_SCSI_ATTR(zfcp_status, "0x%08x\n",
atomic_read(&zfcp_sdev->status));
struct device_attribute *zfcp_sysfs_sdev_attrs[] = {
&dev_attr_fcp_lun,
&dev_attr_wwpn,
&dev_attr_hba_id,
&dev_attr_read_latency,
&dev_attr_write_latency,
&dev_attr_cmd_latency,
&dev_attr_zfcp_access_denied,
&dev_attr_zfcp_failed,
&dev_attr_zfcp_in_recovery,
&dev_attr_zfcp_status,
NULL
};
static ssize_t zfcp_sysfs_adapter_util_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *scsi_host = dev_to_shost(dev);
struct fsf_qtcb_bottom_port *qtcb_port;
struct zfcp_adapter *adapter;
int retval;
adapter = (struct zfcp_adapter *) scsi_host->hostdata[0];
if (!(adapter->adapter_features & FSF_FEATURE_MEASUREMENT_DATA))
return -EOPNOTSUPP;
qtcb_port = kzalloc(sizeof(struct fsf_qtcb_bottom_port), GFP_KERNEL);
if (!qtcb_port)
return -ENOMEM;
retval = zfcp_fsf_exchange_port_data_sync(adapter->qdio, qtcb_port);
if (!retval)
retval = sprintf(buf, "%u %u %u\n", qtcb_port->cp_util,
qtcb_port->cb_util, qtcb_port->a_util);
kfree(qtcb_port);
return retval;
}
static DEVICE_ATTR(utilization, S_IRUGO, zfcp_sysfs_adapter_util_show, NULL);
static int zfcp_sysfs_adapter_ex_config(struct device *dev,
struct fsf_statistics_info *stat_inf)
{
struct Scsi_Host *scsi_host = dev_to_shost(dev);
struct fsf_qtcb_bottom_config *qtcb_config;
struct zfcp_adapter *adapter;
int retval;
adapter = (struct zfcp_adapter *) scsi_host->hostdata[0];
if (!(adapter->adapter_features & FSF_FEATURE_MEASUREMENT_DATA))
return -EOPNOTSUPP;
qtcb_config = kzalloc(sizeof(struct fsf_qtcb_bottom_config),
GFP_KERNEL);
if (!qtcb_config)
return -ENOMEM;
retval = zfcp_fsf_exchange_config_data_sync(adapter->qdio, qtcb_config);
if (!retval)
*stat_inf = qtcb_config->stat_info;
kfree(qtcb_config);
return retval;
}
#define ZFCP_SHOST_ATTR(_name, _format, _arg...) \
static ssize_t zfcp_sysfs_adapter_##_name##_show(struct device *dev, \
struct device_attribute *attr,\
char *buf) \
{ \
struct fsf_statistics_info stat_info; \
int retval; \
\
retval = zfcp_sysfs_adapter_ex_config(dev, &stat_info); \
if (retval) \
return retval; \
\
return sprintf(buf, _format, ## _arg); \
} \
static DEVICE_ATTR(_name, S_IRUGO, zfcp_sysfs_adapter_##_name##_show, NULL);
ZFCP_SHOST_ATTR(requests, "%llu %llu %llu\n",
(unsigned long long) stat_info.input_req,
(unsigned long long) stat_info.output_req,
(unsigned long long) stat_info.control_req);
ZFCP_SHOST_ATTR(megabytes, "%llu %llu\n",
(unsigned long long) stat_info.input_mb,
(unsigned long long) stat_info.output_mb);
ZFCP_SHOST_ATTR(seconds_active, "%llu\n",
(unsigned long long) stat_info.seconds_act);
static ssize_t zfcp_sysfs_adapter_q_full_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *scsi_host = class_to_shost(dev);
struct zfcp_qdio *qdio =
((struct zfcp_adapter *) scsi_host->hostdata[0])->qdio;
u64 util;
spin_lock_bh(&qdio->stat_lock);
util = qdio->req_q_util;
spin_unlock_bh(&qdio->stat_lock);
return sprintf(buf, "%d %llu\n", atomic_read(&qdio->req_q_full),
(unsigned long long)util);
}
static DEVICE_ATTR(queue_full, S_IRUGO, zfcp_sysfs_adapter_q_full_show, NULL);
struct device_attribute *zfcp_sysfs_shost_attrs[] = {
&dev_attr_utilization,
&dev_attr_requests,
&dev_attr_megabytes,
&dev_attr_seconds_active,
&dev_attr_queue_full,
NULL
};
|
{
"pile_set_name": "Github"
}
|
<?php
/*
* Copyright 2014 Google 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.
*/
class Google_Service_Slides_PageProperties extends Google_Model
{
protected $colorSchemeType = 'Google_Service_Slides_ColorScheme';
protected $colorSchemeDataType = '';
protected $pageBackgroundFillType = 'Google_Service_Slides_PageBackgroundFill';
protected $pageBackgroundFillDataType = '';
/**
* @param Google_Service_Slides_ColorScheme
*/
public function setColorScheme(Google_Service_Slides_ColorScheme $colorScheme)
{
$this->colorScheme = $colorScheme;
}
/**
* @return Google_Service_Slides_ColorScheme
*/
public function getColorScheme()
{
return $this->colorScheme;
}
/**
* @param Google_Service_Slides_PageBackgroundFill
*/
public function setPageBackgroundFill(Google_Service_Slides_PageBackgroundFill $pageBackgroundFill)
{
$this->pageBackgroundFill = $pageBackgroundFill;
}
/**
* @return Google_Service_Slides_PageBackgroundFill
*/
public function getPageBackgroundFill()
{
return $this->pageBackgroundFill;
}
}
|
{
"pile_set_name": "Github"
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysisFramework;
using Internal.IL;
using Internal.IL.Stubs;
using Internal.TypeSystem;
using Internal.ReadyToRunConstants;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler
{
/// <summary>
/// IL scan analyzer of programs - this class analyzes what methods, types and other runtime artifact
/// will need to be generated during a compilation. The result of analysis is a conservative superset of
/// what methods will be compiled by the actual codegen backend.
/// </summary>
internal sealed class ILScanner : Compilation, IILScanner
{
private CountdownEvent _compilationCountdown;
private readonly bool _singleThreaded;
internal ILScanner(
DependencyAnalyzerBase<NodeFactory> dependencyGraph,
ILScanNodeFactory nodeFactory,
IEnumerable<ICompilationRootProvider> roots,
ILProvider ilProvider,
DebugInformationProvider debugInformationProvider,
Logger logger,
bool singleThreaded)
: base(dependencyGraph, nodeFactory, roots, ilProvider, debugInformationProvider, null, logger)
{
_helperCache = new HelperCache(this);
_singleThreaded = singleThreaded;
}
protected override void CompileInternal(string outputFile, ObjectDumper dumper)
{
// TODO: We should have a base class for compilation that doesn't implement ICompilation so that
// we don't need this.
throw new NotSupportedException();
}
protected override void ComputeDependencyNodeDependencies(List<DependencyNodeCore<NodeFactory>> obj)
{
// Determine the list of method we actually need to scan
var methodsToCompile = new List<ScannedMethodNode>();
var canonicalMethodsToCompile = new HashSet<MethodDesc>();
foreach (DependencyNodeCore<NodeFactory> dependency in obj)
{
var methodCodeNodeNeedingCode = dependency as ScannedMethodNode;
if (methodCodeNodeNeedingCode == null)
{
// To compute dependencies of the shadow method that tracks dictionary
// dependencies we need to ensure there is code for the canonical method body.
var dependencyMethod = (ShadowConcreteMethodNode)dependency;
methodCodeNodeNeedingCode = (ScannedMethodNode)dependencyMethod.CanonicalMethodNode;
}
// We might have already queued this method for compilation
MethodDesc method = methodCodeNodeNeedingCode.Method;
if (method.IsCanonicalMethod(CanonicalFormKind.Any)
&& !canonicalMethodsToCompile.Add(method))
{
continue;
}
methodsToCompile.Add(methodCodeNodeNeedingCode);
}
if (_singleThreaded)
{
CompileSingleThreaded(methodsToCompile);
}
else
{
CompileMultiThreaded(methodsToCompile);
}
}
private void CompileMultiThreaded(List<ScannedMethodNode> methodsToCompile)
{
if (Logger.IsVerbose)
{
Logger.Writer.WriteLine($"Scanning {methodsToCompile.Count} methods...");
}
WaitCallback compileSingleMethodDelegate = m => CompileSingleMethod((ScannedMethodNode)m);
using (_compilationCountdown = new CountdownEvent(methodsToCompile.Count))
{
foreach (ScannedMethodNode methodCodeNodeNeedingCode in methodsToCompile)
{
ThreadPool.QueueUserWorkItem(compileSingleMethodDelegate, methodCodeNodeNeedingCode);
}
_compilationCountdown.Wait();
_compilationCountdown = null;
}
}
private void CompileSingleThreaded(List<ScannedMethodNode> methodsToCompile)
{
foreach (ScannedMethodNode methodCodeNodeNeedingCode in methodsToCompile)
{
if (Logger.IsVerbose)
{
Logger.Writer.WriteLine($"Compiling {methodCodeNodeNeedingCode.Method}...");
}
CompileSingleMethod(methodCodeNodeNeedingCode);
}
}
private void CompileSingleMethod(ScannedMethodNode methodCodeNodeNeedingCode)
{
MethodDesc method = methodCodeNodeNeedingCode.Method;
try
{
var importer = new ILImporter(this, method);
methodCodeNodeNeedingCode.InitializeDependencies(_nodeFactory, importer.Import());
}
catch (TypeSystemException ex)
{
// Try to compile the method again, but with a throwing method body this time.
MethodIL throwingIL = TypeSystemThrowingILEmitter.EmitIL(method, ex);
var importer = new ILImporter(this, method, throwingIL);
methodCodeNodeNeedingCode.InitializeDependencies(_nodeFactory, importer.Import());
}
catch (Exception ex)
{
throw new CodeGenerationFailedException(method, ex);
}
finally
{
if (_compilationCountdown != null)
_compilationCountdown.Signal();
}
}
ILScanResults IILScanner.Scan()
{
_dependencyGraph.ComputeMarkedNodes();
return new ILScanResults(_dependencyGraph, _nodeFactory);
}
public ISymbolNode GetHelperEntrypoint(ReadyToRunHelper helper)
{
return _helperCache.GetOrCreateValue(helper).Symbol;
}
class Helper
{
public ReadyToRunHelper HelperID { get; }
public ISymbolNode Symbol { get; }
public Helper(ReadyToRunHelper id, ISymbolNode symbol)
{
HelperID = id;
Symbol = symbol;
}
}
private HelperCache _helperCache;
class HelperCache : LockFreeReaderHashtable<ReadyToRunHelper, Helper>
{
private Compilation _compilation;
public HelperCache(Compilation compilation)
{
_compilation = compilation;
}
protected override bool CompareKeyToValue(ReadyToRunHelper key, Helper value) => key == value.HelperID;
protected override bool CompareValueToValue(Helper value1, Helper value2) => value1.HelperID == value2.HelperID;
protected override int GetKeyHashCode(ReadyToRunHelper key) => (int)key;
protected override int GetValueHashCode(Helper value) => (int)value.HelperID;
protected override Helper CreateValueFromKey(ReadyToRunHelper key)
{
string mangledName;
MethodDesc methodDesc;
JitHelper.GetEntryPoint(_compilation.TypeSystemContext, key, out mangledName, out methodDesc);
Debug.Assert(mangledName != null || methodDesc != null);
ISymbolNode entryPoint;
if (mangledName != null)
entryPoint = _compilation.NodeFactory.ExternSymbol(mangledName);
else
entryPoint = _compilation.NodeFactory.MethodEntrypoint(methodDesc);
return new Helper(key, entryPoint);
}
}
}
public interface IILScanner
{
ILScanResults Scan();
}
internal class ScannerFailedException : InternalCompilerErrorException
{
public ScannerFailedException(string message)
: base(message + " " + "You can work around by running the compilation with scanner disabled.")
{
}
}
public class ILScanResults : CompilationResults
{
internal ILScanResults(DependencyAnalyzerBase<NodeFactory> graph, NodeFactory factory)
: base(graph, factory)
{
}
public AnalysisBasedInteropStubManager GetInteropStubManager(InteropStateManager stateManager, PInvokeILEmitterConfiguration pinvokePolicy)
{
return new AnalysisBasedInteropStubManager(stateManager, pinvokePolicy,
_factory.MetadataManager.GetTypesWithStructMarshalling(),
_factory.MetadataManager.GetTypesWithDelegateMarshalling());
}
public VTableSliceProvider GetVTableLayoutInfo()
{
return new ScannedVTableProvider(MarkedNodes);
}
public DictionaryLayoutProvider GetDictionaryLayoutInfo()
{
return new ScannedDictionaryLayoutProvider(MarkedNodes);
}
public DevirtualizationManager GetDevirtualizationManager()
{
return new ScannedDevirtualizationManager(MarkedNodes);
}
private class ScannedVTableProvider : VTableSliceProvider
{
private Dictionary<TypeDesc, IReadOnlyList<MethodDesc>> _vtableSlices = new Dictionary<TypeDesc, IReadOnlyList<MethodDesc>>();
public ScannedVTableProvider(ImmutableArray<DependencyNodeCore<NodeFactory>> markedNodes)
{
foreach (var node in markedNodes)
{
var vtableSliceNode = node as VTableSliceNode;
if (vtableSliceNode != null)
{
_vtableSlices.Add(vtableSliceNode.Type, vtableSliceNode.Slots);
}
}
}
internal override VTableSliceNode GetSlice(TypeDesc type)
{
// TODO: move ownership of compiler-generated entities to CompilerTypeSystemContext.
// https://github.com/dotnet/corert/issues/3873
if (type.GetTypeDefinition() is Internal.TypeSystem.Ecma.EcmaType)
{
if (!_vtableSlices.TryGetValue(type, out IReadOnlyList<MethodDesc> slots))
{
// If we couln't find the vtable slice information for this type, it's because the scanner
// didn't correctly predict what will be needed.
// To troubleshoot, compare the dependency graph of the scanner and the compiler.
// Follow the path from the node that requested this node to the root.
// On the path, you'll find a node that exists in both graphs, but it's predecessor
// only exists in the compiler's graph. That's the place to focus the investigation on.
// Use the ILCompiler-DependencyGraph-Viewer tool to investigate.
Debug.Assert(false);
string typeName = ExceptionTypeNameFormatter.Instance.FormatName(type);
throw new ScannerFailedException($"VTable of type '{typeName}' not computed by the IL scanner.");
}
return new PrecomputedVTableSliceNode(type, slots);
}
else
return new LazilyBuiltVTableSliceNode(type);
}
}
private class ScannedDictionaryLayoutProvider : DictionaryLayoutProvider
{
private Dictionary<TypeSystemEntity, IEnumerable<GenericLookupResult>> _layouts = new Dictionary<TypeSystemEntity, IEnumerable<GenericLookupResult>>();
public ScannedDictionaryLayoutProvider(ImmutableArray<DependencyNodeCore<NodeFactory>> markedNodes)
{
foreach (var node in markedNodes)
{
var layoutNode = node as DictionaryLayoutNode;
if (layoutNode != null)
{
TypeSystemEntity owningMethodOrType = layoutNode.OwningMethodOrType;
_layouts.Add(owningMethodOrType, layoutNode.Entries);
}
}
}
private DictionaryLayoutNode GetPrecomputedLayout(TypeSystemEntity methodOrType)
{
if (!_layouts.TryGetValue(methodOrType, out IEnumerable<GenericLookupResult> layout))
{
// If we couln't find the dictionary layout information for this, it's because the scanner
// didn't correctly predict what will be needed.
// To troubleshoot, compare the dependency graph of the scanner and the compiler.
// Follow the path from the node that requested this node to the root.
// On the path, you'll find a node that exists in both graphs, but it's predecessor
// only exists in the compiler's graph. That's the place to focus the investigation on.
// Use the ILCompiler-DependencyGraph-Viewer tool to investigate.
Debug.Assert(false);
throw new ScannerFailedException($"A dictionary layout was not computed by the IL scanner.");
}
return new PrecomputedDictionaryLayoutNode(methodOrType, layout);
}
public override DictionaryLayoutNode GetLayout(TypeSystemEntity methodOrType)
{
if (methodOrType is TypeDesc type)
{
// TODO: move ownership of compiler-generated entities to CompilerTypeSystemContext.
// https://github.com/dotnet/corert/issues/3873
if (type.GetTypeDefinition() is Internal.TypeSystem.Ecma.EcmaType)
return GetPrecomputedLayout(type);
else
return new LazilyBuiltDictionaryLayoutNode(type);
}
else
{
Debug.Assert(methodOrType is MethodDesc);
MethodDesc method = (MethodDesc)methodOrType;
// TODO: move ownership of compiler-generated entities to CompilerTypeSystemContext.
// https://github.com/dotnet/corert/issues/3873
if (method.GetTypicalMethodDefinition() is Internal.TypeSystem.Ecma.EcmaMethod)
return GetPrecomputedLayout(method);
else
return new LazilyBuiltDictionaryLayoutNode(method);
}
}
}
private class ScannedDevirtualizationManager : DevirtualizationManager
{
private HashSet<TypeDesc> _constructedTypes = new HashSet<TypeDesc>();
private HashSet<TypeDesc> _unsealedTypes = new HashSet<TypeDesc>();
public ScannedDevirtualizationManager(ImmutableArray<DependencyNodeCore<NodeFactory>> markedNodes)
{
foreach (var node in markedNodes)
{
if (node is ConstructedEETypeNode eetypeNode)
{
TypeDesc type = eetypeNode.Type;
if (!type.IsInterface)
{
//
// We collect this information:
//
// 1. What types got allocated
// This is needed for optimizing codegens that might attempt to devirtualize
// calls to sealed types. The devirtualization is not allowed to succeed
// for types that never got allocated because the scanner likely didn't scan
// the target of the virtual call.
// 2. What types are the base types of other types
// This is needed for optimizations. We use this information to effectively
// seal types that are not base types for any other type.
//
TypeDesc canonType = type.ConvertToCanonForm(CanonicalFormKind.Specific);
_constructedTypes.Add(canonType);
// Since this is used for the purposes of devirtualization, it's really convenient
// to also have Array<T> for each T[].
if (canonType.IsArray)
_constructedTypes.Add(canonType.GetClosestDefType());
TypeDesc baseType = canonType.BaseType;
bool added = true;
while (baseType != null && added)
{
baseType = baseType.ConvertToCanonForm(CanonicalFormKind.Specific);
added = _unsealedTypes.Add(baseType);
baseType = baseType.BaseType;
}
}
}
}
}
public override bool IsEffectivelySealed(TypeDesc type)
{
// If we know we scanned a type that derives from this one, this for sure can't be reported as sealed.
TypeDesc canonType = type.ConvertToCanonForm(CanonicalFormKind.Specific);
if (_unsealedTypes.Contains(canonType))
return false;
// We don't want to report types that never got allocated as sealed because that would allow
// the codegen to do direct calls to the type's methods. That can potentially lead to codegen
// generating calls to methods we never scanned (consider a sealed type that never got allocated
// with a virtual method that can be devirtualized because the type is sealed).
// Codegen looking at code we didn't scan is never okay.
if (!_constructedTypes.Contains(canonType))
return false;
if (type is MetadataType metadataType)
{
// Due to how the compiler is structured, we might see "constructed" EETypes for things
// that never got allocated (doing a typeof() on a class that is otherwise never used is
// a good example of when that happens). This can put us into a position where we could
// report `sealed` on an `abstract` class, but that doesn't lead to anything good.
return !metadataType.IsAbstract;
}
// Everything else can be considered sealed.
return true;
}
public override bool IsEffectivelySealed(MethodDesc method)
{
// For the same reason as above, don't report methods on unallocated types as sealed.
if (!_constructedTypes.Contains(method.OwningType.ConvertToCanonForm(CanonicalFormKind.Specific)))
return false;
return base.IsEffectivelySealed(method);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
//===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the LLVM Pass infrastructure. It is primarily
// responsible with ensuring that passes are executed and batched together
// optimally.
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/OptBisect.h"
#include "llvm/PassInfo.h"
#include "llvm/PassRegistry.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
using namespace llvm;
#define DEBUG_TYPE "ir"
//===----------------------------------------------------------------------===//
// Pass Implementation
//
// Force out-of-line virtual method.
Pass::~Pass() {
delete Resolver;
}
// Force out-of-line virtual method.
ModulePass::~ModulePass() = default;
Pass *ModulePass::createPrinterPass(raw_ostream &OS,
const std::string &Banner) const {
return createPrintModulePass(OS, Banner);
}
PassManagerType ModulePass::getPotentialPassManagerType() const {
return PMT_ModulePassManager;
}
static std::string getDescription(const Module &M) {
return "module (" + M.getName().str() + ")";
}
bool ModulePass::skipModule(Module &M) const {
OptPassGate &Gate = M.getContext().getOptPassGate();
return Gate.isEnabled() && !Gate.shouldRunPass(this, getDescription(M));
}
bool Pass::mustPreserveAnalysisID(char &AID) const {
return Resolver->getAnalysisIfAvailable(&AID, true) != nullptr;
}
// dumpPassStructure - Implement the -debug-pass=Structure option
void Pass::dumpPassStructure(unsigned Offset) {
dbgs().indent(Offset*2) << getPassName() << "\n";
}
/// getPassName - Return a nice clean name for a pass. This usually
/// implemented in terms of the name that is registered by one of the
/// Registration templates, but can be overloaded directly.
StringRef Pass::getPassName() const {
AnalysisID AID = getPassID();
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
if (PI)
return PI->getPassName();
return "Unnamed pass: implement Pass::getPassName()";
}
void Pass::preparePassManager(PMStack &) {
// By default, don't do anything.
}
PassManagerType Pass::getPotentialPassManagerType() const {
// Default implementation.
return PMT_Unknown;
}
void Pass::getAnalysisUsage(AnalysisUsage &) const {
// By default, no analysis results are used, all are invalidated.
}
void Pass::releaseMemory() {
// By default, don't do anything.
}
void Pass::verifyAnalysis() const {
// By default, don't do anything.
}
void *Pass::getAdjustedAnalysisPointer(AnalysisID AID) {
return this;
}
ImmutablePass *Pass::getAsImmutablePass() {
return nullptr;
}
PMDataManager *Pass::getAsPMDataManager() {
return nullptr;
}
void Pass::setResolver(AnalysisResolver *AR) {
assert(!Resolver && "Resolver is already set");
Resolver = AR;
}
// print - Print out the internal state of the pass. This is called by Analyze
// to print out the contents of an analysis. Otherwise it is not necessary to
// implement this method.
void Pass::print(raw_ostream &OS, const Module *) const {
OS << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
// dump - call print(cerr);
LLVM_DUMP_METHOD void Pass::dump() const {
print(dbgs(), nullptr);
}
#endif
//===----------------------------------------------------------------------===//
// ImmutablePass Implementation
//
// Force out-of-line virtual method.
ImmutablePass::~ImmutablePass() = default;
void ImmutablePass::initializePass() {
// By default, don't do anything.
}
//===----------------------------------------------------------------------===//
// FunctionPass Implementation
//
Pass *FunctionPass::createPrinterPass(raw_ostream &OS,
const std::string &Banner) const {
return createPrintFunctionPass(OS, Banner);
}
PassManagerType FunctionPass::getPotentialPassManagerType() const {
return PMT_FunctionPassManager;
}
static std::string getDescription(const Function &F) {
return "function (" + F.getName().str() + ")";
}
bool FunctionPass::skipFunction(const Function &F) const {
OptPassGate &Gate = F.getContext().getOptPassGate();
if (Gate.isEnabled() && !Gate.shouldRunPass(this, getDescription(F)))
return true;
if (F.hasOptNone()) {
LLVM_DEBUG(dbgs() << "Skipping pass '" << getPassName() << "' on function "
<< F.getName() << "\n");
return true;
}
return false;
}
const PassInfo *Pass::lookupPassInfo(const void *TI) {
return PassRegistry::getPassRegistry()->getPassInfo(TI);
}
const PassInfo *Pass::lookupPassInfo(StringRef Arg) {
return PassRegistry::getPassRegistry()->getPassInfo(Arg);
}
Pass *Pass::createPass(AnalysisID ID) {
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
if (!PI)
return nullptr;
return PI->createPass();
}
//===----------------------------------------------------------------------===//
// Analysis Group Implementation Code
//===----------------------------------------------------------------------===//
// RegisterAGBase implementation
RegisterAGBase::RegisterAGBase(StringRef Name, const void *InterfaceID,
const void *PassID, bool isDefault)
: PassInfo(Name, InterfaceID) {
PassRegistry::getPassRegistry()->registerAnalysisGroup(InterfaceID, PassID,
*this, isDefault);
}
//===----------------------------------------------------------------------===//
// PassRegistrationListener implementation
//
// enumeratePasses - Iterate over the registered passes, calling the
// passEnumerate callback on each PassInfo object.
void PassRegistrationListener::enumeratePasses() {
PassRegistry::getPassRegistry()->enumerateWith(this);
}
PassNameParser::PassNameParser(cl::Option &O)
: cl::parser<const PassInfo *>(O) {
PassRegistry::getPassRegistry()->addRegistrationListener(this);
}
// This only gets called during static destruction, in which case the
// PassRegistry will have already been destroyed by llvm_shutdown(). So
// attempting to remove the registration listener is an error.
PassNameParser::~PassNameParser() = default;
//===----------------------------------------------------------------------===//
// AnalysisUsage Class Implementation
//
namespace {
struct GetCFGOnlyPasses : public PassRegistrationListener {
using VectorType = AnalysisUsage::VectorType;
VectorType &CFGOnlyList;
GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
void passEnumerate(const PassInfo *P) override {
if (P->isCFGOnlyPass())
CFGOnlyList.push_back(P->getTypeInfo());
}
};
} // end anonymous namespace
// setPreservesCFG - This function should be called to by the pass, iff they do
// not:
//
// 1. Add or remove basic blocks from the function
// 2. Modify terminator instructions in any way.
//
// This function annotates the AnalysisUsage info object to say that analyses
// that only depend on the CFG are preserved by this pass.
void AnalysisUsage::setPreservesCFG() {
// Since this transformation doesn't modify the CFG, it preserves all analyses
// that only depend on the CFG (like dominators, loop info, etc...)
GetCFGOnlyPasses(Preserved).enumeratePasses();
}
AnalysisUsage &AnalysisUsage::addPreserved(StringRef Arg) {
const PassInfo *PI = Pass::lookupPassInfo(Arg);
// If the pass exists, preserve it. Otherwise silently do nothing.
if (PI) Preserved.push_back(PI->getTypeInfo());
return *this;
}
AnalysisUsage &AnalysisUsage::addRequiredID(const void *ID) {
Required.push_back(ID);
return *this;
}
AnalysisUsage &AnalysisUsage::addRequiredID(char &ID) {
Required.push_back(&ID);
return *this;
}
AnalysisUsage &AnalysisUsage::addRequiredTransitiveID(char &ID) {
Required.push_back(&ID);
RequiredTransitive.push_back(&ID);
return *this;
}
|
{
"pile_set_name": "Github"
}
|
{
"name": "@microsoft/api-documenter",
"version": "7.8.56",
"description": "Read JSON files from api-extractor, generate documentation pages",
"repository": {
"type": "git",
"url": "https://github.com/microsoft/rushstack/tree/master/apps/api-documenter"
},
"homepage": "https://api-extractor.com/",
"license": "MIT",
"scripts": {
"build": "heft test --clean"
},
"bin": {
"api-documenter": "./bin/api-documenter"
},
"main": "lib/index.js",
"typings": "dist/rollup.d.ts",
"dependencies": {
"@microsoft/api-extractor-model": "workspace:*",
"@microsoft/tsdoc": "0.12.19",
"@rushstack/node-core-library": "workspace:*",
"@rushstack/ts-command-line": "workspace:*",
"colors": "~1.2.1",
"js-yaml": "~3.13.1",
"resolve": "~1.17.0"
},
"devDependencies": {
"@rushstack/eslint-config": "workspace:*",
"@rushstack/heft": "workspace:*",
"@rushstack/heft-node-rig": "workspace:*",
"@types/heft-jest": "1.0.1",
"@types/js-yaml": "3.12.1",
"@types/node": "10.17.13",
"@types/resolve": "1.17.1",
"jest": "~25.4.0"
}
}
|
{
"pile_set_name": "Github"
}
|
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"vorm.",
"nachm."
],
"DAY": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"MONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"SHORTDAY": [
"So.",
"Mo.",
"Di.",
"Mi.",
"Do.",
"Fr.",
"Sa."
],
"SHORTMONTH": [
"Jan",
"Feb",
"M\u00e4r",
"Apr",
"Mai",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez"
],
"fullDate": "EEEE, d. MMMM y",
"longDate": "d. MMMM y",
"medium": "dd.MM.yyyy HH:mm:ss",
"mediumDate": "dd.MM.yyyy",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "de-de",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
{
"pile_set_name": "Github"
}
|
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"clientset_generated.go",
"doc.go",
"register.go",
],
importpath = "k8s.io/client-go/kubernetes/fake",
deps = [
"//vendor/k8s.io/api/admissionregistration/v1alpha1:go_default_library",
"//vendor/k8s.io/api/admissionregistration/v1beta1:go_default_library",
"//vendor/k8s.io/api/apps/v1:go_default_library",
"//vendor/k8s.io/api/apps/v1beta1:go_default_library",
"//vendor/k8s.io/api/apps/v1beta2:go_default_library",
"//vendor/k8s.io/api/authentication/v1:go_default_library",
"//vendor/k8s.io/api/authentication/v1beta1:go_default_library",
"//vendor/k8s.io/api/authorization/v1:go_default_library",
"//vendor/k8s.io/api/authorization/v1beta1:go_default_library",
"//vendor/k8s.io/api/autoscaling/v1:go_default_library",
"//vendor/k8s.io/api/autoscaling/v2beta1:go_default_library",
"//vendor/k8s.io/api/batch/v1:go_default_library",
"//vendor/k8s.io/api/batch/v1beta1:go_default_library",
"//vendor/k8s.io/api/batch/v2alpha1:go_default_library",
"//vendor/k8s.io/api/certificates/v1beta1:go_default_library",
"//vendor/k8s.io/api/core/v1:go_default_library",
"//vendor/k8s.io/api/events/v1beta1:go_default_library",
"//vendor/k8s.io/api/extensions/v1beta1:go_default_library",
"//vendor/k8s.io/api/networking/v1:go_default_library",
"//vendor/k8s.io/api/policy/v1beta1:go_default_library",
"//vendor/k8s.io/api/rbac/v1:go_default_library",
"//vendor/k8s.io/api/rbac/v1alpha1:go_default_library",
"//vendor/k8s.io/api/rbac/v1beta1:go_default_library",
"//vendor/k8s.io/api/scheduling/v1alpha1:go_default_library",
"//vendor/k8s.io/api/settings/v1alpha1:go_default_library",
"//vendor/k8s.io/api/storage/v1:go_default_library",
"//vendor/k8s.io/api/storage/v1alpha1:go_default_library",
"//vendor/k8s.io/api/storage/v1beta1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/watch:go_default_library",
"//vendor/k8s.io/client-go/discovery:go_default_library",
"//vendor/k8s.io/client-go/discovery/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/apps/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/apps/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/apps/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/apps/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/apps/v1beta2:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/apps/v1beta2/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/authentication/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/authentication/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/authentication/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/authorization/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/authorization/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/authorization/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/autoscaling/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/autoscaling/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/batch/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/batch/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/batch/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/batch/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/batch/v2alpha1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/batch/v2alpha1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/certificates/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/core/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/core/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/events/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/events/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/extensions/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/networking/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/networking/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/policy/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/policy/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/rbac/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/rbac/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/rbac/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/settings/v1alpha1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/settings/v1alpha1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/storage/v1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/storage/v1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/storage/v1alpha1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/fake:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/storage/v1beta1:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/typed/storage/v1beta1/fake:go_default_library",
"//vendor/k8s.io/client-go/testing:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
|
{
"pile_set_name": "Github"
}
|
@import 'node_modules/nib/index'
.nsg-editor
padding 10px
cursor text
.nsg-tag
display inline-block
border 1px solid #666
padding 3px
margin 4px
.nsg-invalid
border-color #c00
.nsg-tag-remove:after
margin-left 4px
padding 0 4px
content 'x'
background-color #ccc
cursor pointer
.nsg-input
display inline-block
padding 3px 3px 3px 8px
margin 5px 0
&[placeholder]
min-width 100%
|
{
"pile_set_name": "Github"
}
|
var baseIteratee = require('./_baseIteratee'),
isArrayLike = require('./isArrayLike'),
keys = require('./keys');
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
module.exports = createFind;
|
{
"pile_set_name": "Github"
}
|
\version "2.5.21"
mIIIViolinTwo = \relative csharp' {
\clef "treble"
r4 fsharp-.\f fsharp-. r
r2 r8 csharp16\p[( d]) e8-.[ fsharp-.]
g4 r4 r2
r4 b,-.\f fsharp'8-.[ d16\p( e]) fsharp8-.[ asharp,-.]
b4 r4 r8 fsharp'16[( asharp]) b8-.[ fsharp-.]
d4 r4 r8^\markup { \musicglyph #"scripts.caesura" }
r8 r4
r4 gsharp!\p( csharp, fsharp)
< b, fsharp' > < fsharp' a >8 r r2
r2 r8 dsharp8(_\cr e) e~
e fsharp4.~_\markup { \dynamic rf } fsharp8 gsharp(\> fsharp < fsharp a >
gsharp\p)\! b,[(_\cr gsharp d'!8] b) r < e e' >\f r
}
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2019 Kyle Terry
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rev1.h"
bool process_record_kb(uint16_t keycode, keyrecord_t *record) {
return process_record_user(keycode, record);
}
void matrix_init_kb(void) {
// put your keyboard start-up code here
// runs once when the firmware starts up
matrix_init_user();
}
void matrix_scan_kb(void) {
// put your looping keyboard code here
// runs every cycle (a lot)
matrix_scan_user();
}
void led_set_kb(uint8_t usb_led) {
// put your keyboard LED indicator (ex: Caps Lock LED) toggling code here
led_set_user(usb_led);
}
|
{
"pile_set_name": "Github"
}
|
namespace Microsoft.Azure.Cosmos.Tests
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
public static class TextFileConcatenation
{
public static string ReadMultipartFile(string path)
{
if (!path.EndsWith(".json"))
{
path += ".json";
}
try
{
// Try as a file
FileAttributes attr = File.GetAttributes(path);
if (!attr.HasFlag(FileAttributes.Directory))
{
return File.ReadAllText(path);
}
}
catch (FileNotFoundException)
{
// try as a directory
path = path.Replace(".json", string.Empty);
}
DirectoryInfo dir = new DirectoryInfo(path);
IEnumerable<FileInfo> files = dir.GetFiles().OrderBy(x => x.Name);
string text;
using (MemoryStream dest = new MemoryStream())
{
foreach (FileInfo file in files)
{
FileStream fileStream = File.OpenRead(file.FullName);
fileStream.CopyTo(dest);
}
text = Encoding.UTF8.GetString(dest.ToArray());
}
return text;
}
}
}
|
{
"pile_set_name": "Github"
}
|
var toString = require('./toString'),
upperFirst = require('./upperFirst');
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}
module.exports = capitalize;
|
{
"pile_set_name": "Github"
}
|
/*
*
* Copyright 2016 gRPC 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.
*
*/
#include <grpc++/test/server_context_test_spouse.h>
#include <cstring>
#include <vector>
#include <grpc++/impl/grpc_library.h>
#include <gtest/gtest.h>
namespace grpc {
namespace testing {
static internal::GrpcLibraryInitializer g_initializer;
const char key1[] = "metadata-key1";
const char key2[] = "metadata-key2";
const char val1[] = "metadata-val1";
const char val2[] = "metadata-val2";
bool ClientMetadataContains(const ServerContext& context,
const grpc::string_ref& key,
const grpc::string_ref& value) {
const auto& client_metadata = context.client_metadata();
for (auto iter = client_metadata.begin(); iter != client_metadata.end();
++iter) {
if (iter->first == key && iter->second == value) {
return true;
}
}
return false;
}
TEST(ServerContextTestSpouseTest, ClientMetadata) {
ServerContext context;
ServerContextTestSpouse spouse(&context);
spouse.AddClientMetadata(key1, val1);
ASSERT_TRUE(ClientMetadataContains(context, key1, val1));
spouse.AddClientMetadata(key2, val2);
ASSERT_TRUE(ClientMetadataContains(context, key1, val1));
ASSERT_TRUE(ClientMetadataContains(context, key2, val2));
}
TEST(ServerContextTestSpouseTest, InitialMetadata) {
ServerContext context;
ServerContextTestSpouse spouse(&context);
std::multimap<grpc::string, grpc::string> metadata;
context.AddInitialMetadata(key1, val1);
metadata.insert(std::pair<grpc::string, grpc::string>(key1, val1));
ASSERT_EQ(metadata, spouse.GetInitialMetadata());
context.AddInitialMetadata(key2, val2);
metadata.insert(std::pair<grpc::string, grpc::string>(key2, val2));
ASSERT_EQ(metadata, spouse.GetInitialMetadata());
}
TEST(ServerContextTestSpouseTest, TrailingMetadata) {
ServerContext context;
ServerContextTestSpouse spouse(&context);
std::multimap<grpc::string, grpc::string> metadata;
context.AddTrailingMetadata(key1, val1);
metadata.insert(std::pair<grpc::string, grpc::string>(key1, val1));
ASSERT_EQ(metadata, spouse.GetTrailingMetadata());
context.AddTrailingMetadata(key2, val2);
metadata.insert(std::pair<grpc::string, grpc::string>(key2, val2));
ASSERT_EQ(metadata, spouse.GetTrailingMetadata());
}
} // namespace
} // namespace grpc
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
{
"pile_set_name": "Github"
}
|
# Contributor: Bart Ribbers <[email protected]>
# Maintainer: Bart Ribbers <[email protected]>
pkgname=kbreakout
pkgver=20.08.1
pkgrel=0
arch="all !armhf" # armhf blocked by extra-cmake-modules
url="https://kde.org/applications/games/kbreakout/"
pkgdesc="A Breakout-like game"
license="GPL-2.0-or-later AND GFDL-1.2-only"
makedepends="extra-cmake-modules qt5-qtbase-dev qt5-qtdeclarative-dev kcoreaddons-dev kconfig-dev kcrash-dev kwidgetsaddons-dev kdbusaddons-dev ki18n-dev kconfigwidgets-dev kxmlgui-dev kdoctools-dev libkdegames-dev"
source="https://download.kde.org/stable/release-service/$pkgver/src/kbreakout-$pkgver.tar.xz"
subpackages="$pkgname-doc $pkgname-lang"
build() {
cmake -B build \
-DCMAKE_BUILD_TYPE=None \
-DCMAKE_INSTALL_PREFIX=/usr \
-DCMAKE_INSTALL_LIBDIR=lib
cmake --build build
}
check() {
cd build
CTEST_OUTPUT_ON_FAILURE=TRUE ctest
}
package() {
DESTDIR="$pkgdir" cmake --build build --target install
}
sha512sums="238070a42d0e91b8e788b7eb9da613c2d1a3897fd2ca055ac0182808dadba97f024e6619d2bd7052753226ba94ce69a394e6837cc120292b7b0252aa17fbf9c3 kbreakout-20.08.1.tar.xz"
|
{
"pile_set_name": "Github"
}
|
# The MIT License (MIT)
#
# Copyright (c) 2014 Richard Moore
#
# 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.
# This is a pure-Python implementation of the AES algorithm and AES common
# modes of operation.
# See: https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
# See: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
# Supported key sizes:
# 128-bit
# 192-bit
# 256-bit
# Supported modes of operation:
# ECB - Electronic Codebook
# CBC - Cipher-Block Chaining
# CFB - Cipher Feedback
# OFB - Output Feedback
# CTR - Counter
# See the README.md for API details and general information.
# Also useful, PyCrypto, a crypto library implemented in C with Python bindings:
# https://www.dlitz.net/software/pycrypto/
VERSION = [1, 3, 0]
from .aes import AES, AESModeOfOperationCTR, AESModeOfOperationCBC, AESModeOfOperationCFB, AESModeOfOperationECB, AESModeOfOperationOFB, AESModesOfOperation, Counter
from .blockfeeder import decrypt_stream, Decrypter, encrypt_stream, Encrypter
from .blockfeeder import PADDING_NONE, PADDING_DEFAULT
|
{
"pile_set_name": "Github"
}
|
// Copyright 2012 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.
package main
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"github.com/Sirupsen/logrus"
)
const utf8RuneSelf = 0x80
// walkAndCopySymlinks modifes the walkSymlinks implementation to use a chroot
// when calculating absolute paths and to copy the symlinks into the output dir
func walkAndCopySymlinks(chrootDir, outputDir, path string) (string, error) {
const maxIter = 255
originalPath := path
// consume path by taking each frontmost path element,
// expanding it if it's a symlink, and appending it to b
var b bytes.Buffer
for n := 0; path != ""; n++ {
if n > maxIter {
return "", errors.New("EvalSymlinks: too many links in " + originalPath)
}
// find next path component, p
var i = -1
for j, c := range path {
if c < utf8RuneSelf && os.IsPathSeparator(uint8(c)) {
i = j
break
}
}
var p string
if i == -1 {
p, path = path, ""
} else {
p, path = path[:i], path[i+1:]
}
if p == "" {
if b.Len() == 0 {
// must be absolute path
b.WriteRune(filepath.Separator)
}
continue
}
current := b.String() + p
fi, err := os.Lstat(current)
if err != nil {
return "", err
}
if fi.Mode()&os.ModeSymlink == 0 {
b.WriteString(p)
if path != "" || (b.Len() == 2 && len(p) == 2 && p[1] == ':') {
b.WriteRune(filepath.Separator)
}
continue
}
// it's a symlink, put it at the front of path
dest, err := os.Readlink(current)
if err != nil {
return "", err
}
// esnure the symlink in output directory
logrus.Debugf("Symlink %s points to %s", current, dest)
outpath := filepath.Join(outputDir, strings.TrimPrefix(current, chrootDir))
logrus.Debugf("Creating %s symlink inside %s", outpath, chrootDir)
if err := ensureSymlink(dest, outpath); err != nil {
return "", err
}
if filepath.IsAbs(dest) || os.IsPathSeparator(dest[0]) {
b.Reset()
b.WriteString(chrootDir)
b.WriteRune(filepath.Separator)
}
path = dest + string(filepath.Separator) + path
}
return filepath.Clean(b.String()), nil
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
var assert = require("assert");
var types = require("recast").types;
var n = types.namedTypes;
var b = types.builders;
var hasOwn = Object.prototype.hasOwnProperty;
// The hoist function takes a FunctionExpression or FunctionDeclaration
// and replaces any Declaration nodes in its body with assignments, then
// returns a VariableDeclaration containing just the names of the removed
// declarations.
exports.hoist = function(funPath) {
assert.ok(funPath instanceof types.NodePath);
n.Function.assert(funPath.value);
var vars = {};
function varDeclToExpr(vdec, includeIdentifiers) {
n.VariableDeclaration.assert(vdec);
var exprs = [];
vdec.declarations.forEach(function(dec) {
vars[dec.id.name] = dec.id;
if (dec.init) {
exprs.push(b.assignmentExpression(
"=", dec.id, dec.init
));
} else if (includeIdentifiers) {
exprs.push(dec.id);
}
});
if (exprs.length === 0)
return null;
if (exprs.length === 1)
return exprs[0];
return b.sequenceExpression(exprs);
}
types.visit(funPath.get("body"), {
visitVariableDeclaration: function(path) {
var expr = varDeclToExpr(path.value, false);
if (expr === null) {
path.replace();
} else {
// We don't need to traverse this expression any further because
// there can't be any new declarations inside an expression.
return b.expressionStatement(expr);
}
// Since the original node has been either removed or replaced,
// avoid traversing it any further.
return false;
},
visitForStatement: function(path) {
var init = path.value.init;
if (n.VariableDeclaration.check(init)) {
path.get("init").replace(varDeclToExpr(init, false));
}
this.traverse(path);
},
visitForInStatement: function(path) {
var left = path.value.left;
if (n.VariableDeclaration.check(left)) {
path.get("left").replace(varDeclToExpr(left, true));
}
this.traverse(path);
},
visitFunctionDeclaration: function(path) {
var node = path.value;
vars[node.id.name] = node.id;
var parentNode = path.parent.node;
var assignment = b.expressionStatement(
b.assignmentExpression(
"=",
node.id,
b.functionExpression(
node.id,
node.params,
node.body,
node.generator,
node.expression
)
)
);
if (n.BlockStatement.check(path.parent.node)) {
// Insert the assignment form before the first statement in the
// enclosing block.
path.parent.get("body").unshift(assignment);
// Remove the function declaration now that we've inserted the
// equivalent assignment form at the beginning of the block.
path.replace();
} else {
// If the parent node is not a block statement, then we can just
// replace the declaration with the equivalent assignment form
// without worrying about hoisting it.
path.replace(assignment);
}
// Don't hoist variables out of inner functions.
return false;
},
visitFunctionExpression: function(path) {
// Don't descend into nested function expressions.
return false;
}
});
var paramNames = {};
funPath.get("params").each(function(paramPath) {
var param = paramPath.value;
if (n.Identifier.check(param)) {
paramNames[param.name] = param;
} else {
// Variables declared by destructuring parameter patterns will be
// harmlessly re-declared.
}
});
var declarations = [];
Object.keys(vars).forEach(function(name) {
if (!hasOwn.call(paramNames, name)) {
declarations.push(b.variableDeclarator(vars[name], null));
}
});
if (declarations.length === 0) {
return null; // Be sure to handle this case!
}
return b.variableDeclaration("var", declarations);
};
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\CheckoutAgreements\Model\Agreement;
use Magento\CheckoutAgreements\Model\ResourceModel\Agreement as AgreementResource;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/**
* @var $agreement Agreement
* @var $agreementResource AgreementResource
*/
$agreement = $objectManager->create(Agreement::class);
$agreementResource = $objectManager->create(AgreementResource::class);
$agreement->setData([
'name' => 'Checkout Agreement (inactive)',
'content' => 'Checkout agreement content: TEXT',
'content_height' => '200px',
'checkbox_text' => 'Checkout agreement checkbox text.',
'is_active' => false,
'is_html' => false,
'stores' => [0, 1],
]);
$agreementResource->save($agreement);
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import <objc/NSObject.h>
@class NSMutableSet, PFDispatchQueue;
@interface DisableTerminationActivityManager : NSObject
{
BOOL _pendingWorkActivityIsRegistered;
PFDispatchQueue *_isolationQueue;
NSMutableSet *_openActivityRecords;
}
@property BOOL pendingWorkActivityIsRegistered; // @synthesize pendingWorkActivityIsRegistered=_pendingWorkActivityIsRegistered;
@property(retain) NSMutableSet *openActivityRecords; // @synthesize openActivityRecords=_openActivityRecords;
@property(retain) PFDispatchQueue *isolationQueue; // @synthesize isolationQueue=_isolationQueue;
- (void).cxx_destruct;
- (void)activityDidEnd:(id)arg1;
- (id)_onQueueActivityWithReason:(id)arg1;
- (id)activityWithReason:(id)arg1 arguments:(struct __va_list_tag [1])arg2;
- (id)activityWithReason:(id)arg1;
- (void)disablePendingWorkXpcActivity;
- (void)didReceivePendingWorkEvent;
- (void)enablePendingWorkXpcActivity;
- (void)checkInWithPendingWorkXpcActivity;
- (void)checkInWithPendingWorkStaticXpcActivity;
- (id)init;
@end
|
{
"pile_set_name": "Github"
}
|
//Package notifyf comment
// This file war generated by tars2go 1.1
// Generated from NotifyF.tars
package notifyf
type ReportType int32
const (
ReportType_REPORT = 0
ReportType_NOTIFY = 1
)
|
{
"pile_set_name": "Github"
}
|
/*****************************************************************************
*
* Copyright (C) 2008 Cedric Bregardis <[email protected]> and
* Jean-Christian Hassler <[email protected]>
*
* This file is part of the Audiowerk2 ALSA driver
*
* The Audiowerk2 ALSA driver 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; version 2.
*
* The Audiowerk2 ALSA driver 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 the Audiowerk2 ALSA driver; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*****************************************************************************/
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <asm/io.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/control.h>
#include "saa7146.h"
#include "aw2-saa7146.h"
MODULE_AUTHOR("Cedric Bregardis <[email protected]>, "
"Jean-Christian Hassler <[email protected]>");
MODULE_DESCRIPTION("Emagic Audiowerk 2 sound driver");
MODULE_LICENSE("GPL");
/*********************************
* DEFINES
********************************/
#define PCI_VENDOR_ID_SAA7146 0x1131
#define PCI_DEVICE_ID_SAA7146 0x7146
#define CTL_ROUTE_ANALOG 0
#define CTL_ROUTE_DIGITAL 1
/*********************************
* TYPEDEFS
********************************/
/* hardware definition */
static struct snd_pcm_hardware snd_aw2_playback_hw = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_44100,
.rate_min = 44100,
.rate_max = 44100,
.channels_min = 2,
.channels_max = 4,
.buffer_bytes_max = 32768,
.period_bytes_min = 4096,
.period_bytes_max = 32768,
.periods_min = 1,
.periods_max = 1024,
};
static struct snd_pcm_hardware snd_aw2_capture_hw = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_44100,
.rate_min = 44100,
.rate_max = 44100,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = 32768,
.period_bytes_min = 4096,
.period_bytes_max = 32768,
.periods_min = 1,
.periods_max = 1024,
};
struct aw2_pcm_device {
struct snd_pcm *pcm;
unsigned int stream_number;
struct aw2 *chip;
};
struct aw2 {
struct snd_aw2_saa7146 saa7146;
struct pci_dev *pci;
int irq;
spinlock_t reg_lock;
struct mutex mtx;
unsigned long iobase_phys;
void __iomem *iobase_virt;
struct snd_card *card;
struct aw2_pcm_device device_playback[NB_STREAM_PLAYBACK];
struct aw2_pcm_device device_capture[NB_STREAM_CAPTURE];
};
/*********************************
* FUNCTION DECLARATIONS
********************************/
static int __init alsa_card_aw2_init(void);
static void __exit alsa_card_aw2_exit(void);
static int snd_aw2_dev_free(struct snd_device *device);
static int __devinit snd_aw2_create(struct snd_card *card,
struct pci_dev *pci, struct aw2 **rchip);
static int __devinit snd_aw2_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id);
static void __devexit snd_aw2_remove(struct pci_dev *pci);
static int snd_aw2_pcm_playback_open(struct snd_pcm_substream *substream);
static int snd_aw2_pcm_playback_close(struct snd_pcm_substream *substream);
static int snd_aw2_pcm_capture_open(struct snd_pcm_substream *substream);
static int snd_aw2_pcm_capture_close(struct snd_pcm_substream *substream);
static int snd_aw2_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params);
static int snd_aw2_pcm_hw_free(struct snd_pcm_substream *substream);
static int snd_aw2_pcm_prepare_playback(struct snd_pcm_substream *substream);
static int snd_aw2_pcm_prepare_capture(struct snd_pcm_substream *substream);
static int snd_aw2_pcm_trigger_playback(struct snd_pcm_substream *substream,
int cmd);
static int snd_aw2_pcm_trigger_capture(struct snd_pcm_substream *substream,
int cmd);
static snd_pcm_uframes_t snd_aw2_pcm_pointer_playback(struct snd_pcm_substream
*substream);
static snd_pcm_uframes_t snd_aw2_pcm_pointer_capture(struct snd_pcm_substream
*substream);
static int __devinit snd_aw2_new_pcm(struct aw2 *chip);
static int snd_aw2_control_switch_capture_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo);
static int snd_aw2_control_switch_capture_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value
*ucontrol);
static int snd_aw2_control_switch_capture_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value
*ucontrol);
/*********************************
* VARIABLES
********************************/
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for Audiowerk2 soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for the Audiowerk2 soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable Audiowerk2 soundcard.");
static struct pci_device_id snd_aw2_ids[] = {
{PCI_VENDOR_ID_SAA7146, PCI_DEVICE_ID_SAA7146, 0, 0,
0, 0, 0},
{0}
};
MODULE_DEVICE_TABLE(pci, snd_aw2_ids);
/* pci_driver definition */
static struct pci_driver driver = {
.name = "Emagic Audiowerk 2",
.id_table = snd_aw2_ids,
.probe = snd_aw2_probe,
.remove = __devexit_p(snd_aw2_remove),
};
/* operators for playback PCM alsa interface */
static struct snd_pcm_ops snd_aw2_playback_ops = {
.open = snd_aw2_pcm_playback_open,
.close = snd_aw2_pcm_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_aw2_pcm_hw_params,
.hw_free = snd_aw2_pcm_hw_free,
.prepare = snd_aw2_pcm_prepare_playback,
.trigger = snd_aw2_pcm_trigger_playback,
.pointer = snd_aw2_pcm_pointer_playback,
};
/* operators for capture PCM alsa interface */
static struct snd_pcm_ops snd_aw2_capture_ops = {
.open = snd_aw2_pcm_capture_open,
.close = snd_aw2_pcm_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_aw2_pcm_hw_params,
.hw_free = snd_aw2_pcm_hw_free,
.prepare = snd_aw2_pcm_prepare_capture,
.trigger = snd_aw2_pcm_trigger_capture,
.pointer = snd_aw2_pcm_pointer_capture,
};
static struct snd_kcontrol_new aw2_control __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Capture Route",
.index = 0,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.private_value = 0xffff,
.info = snd_aw2_control_switch_capture_info,
.get = snd_aw2_control_switch_capture_get,
.put = snd_aw2_control_switch_capture_put
};
/*********************************
* FUNCTION IMPLEMENTATIONS
********************************/
/* initialization of the module */
static int __init alsa_card_aw2_init(void)
{
snd_printdd(KERN_DEBUG "aw2: Load aw2 module\n");
return pci_register_driver(&driver);
}
/* clean up the module */
static void __exit alsa_card_aw2_exit(void)
{
snd_printdd(KERN_DEBUG "aw2: Unload aw2 module\n");
pci_unregister_driver(&driver);
}
module_init(alsa_card_aw2_init);
module_exit(alsa_card_aw2_exit);
/* component-destructor */
static int snd_aw2_dev_free(struct snd_device *device)
{
struct aw2 *chip = device->device_data;
/* Free hardware */
snd_aw2_saa7146_free(&chip->saa7146);
/* release the irq */
if (chip->irq >= 0)
free_irq(chip->irq, (void *)chip);
/* release the i/o ports & memory */
if (chip->iobase_virt)
iounmap(chip->iobase_virt);
pci_release_regions(chip->pci);
/* disable the PCI entry */
pci_disable_device(chip->pci);
/* release the data */
kfree(chip);
return 0;
}
/* chip-specific constructor */
static int __devinit snd_aw2_create(struct snd_card *card,
struct pci_dev *pci, struct aw2 **rchip)
{
struct aw2 *chip;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_aw2_dev_free,
};
*rchip = NULL;
/* initialize the PCI entry */
err = pci_enable_device(pci);
if (err < 0)
return err;
pci_set_master(pci);
/* check PCI availability (32bit DMA) */
if ((pci_set_dma_mask(pci, DMA_BIT_MASK(32)) < 0) ||
(pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(32)) < 0)) {
printk(KERN_ERR "aw2: Impossible to set 32bit mask DMA\n");
pci_disable_device(pci);
return -ENXIO;
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
/* initialize the stuff */
chip->card = card;
chip->pci = pci;
chip->irq = -1;
/* (1) PCI resource allocation */
err = pci_request_regions(pci, "Audiowerk2");
if (err < 0) {
pci_disable_device(pci);
kfree(chip);
return err;
}
chip->iobase_phys = pci_resource_start(pci, 0);
chip->iobase_virt =
ioremap_nocache(chip->iobase_phys,
pci_resource_len(pci, 0));
if (chip->iobase_virt == NULL) {
printk(KERN_ERR "aw2: unable to remap memory region");
pci_release_regions(pci);
pci_disable_device(pci);
kfree(chip);
return -ENOMEM;
}
/* (2) initialization of the chip hardware */
snd_aw2_saa7146_setup(&chip->saa7146, chip->iobase_virt);
if (request_irq(pci->irq, snd_aw2_saa7146_interrupt,
IRQF_SHARED, "Audiowerk2", chip)) {
printk(KERN_ERR "aw2: Cannot grab irq %d\n", pci->irq);
iounmap(chip->iobase_virt);
pci_release_regions(chip->pci);
pci_disable_device(chip->pci);
kfree(chip);
return -EBUSY;
}
chip->irq = pci->irq;
err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
if (err < 0) {
free_irq(chip->irq, (void *)chip);
iounmap(chip->iobase_virt);
pci_release_regions(chip->pci);
pci_disable_device(chip->pci);
kfree(chip);
return err;
}
snd_card_set_dev(card, &pci->dev);
*rchip = chip;
printk(KERN_INFO
"Audiowerk 2 sound card (saa7146 chipset) detected and "
"managed\n");
return 0;
}
/* constructor */
static int __devinit snd_aw2_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct aw2 *chip;
int err;
/* (1) Continue if device is not enabled, else inc dev */
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
/* (2) Create card instance */
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
/* (3) Create main component */
err = snd_aw2_create(card, pci, &chip);
if (err < 0) {
snd_card_free(card);
return err;
}
/* initialize mutex */
mutex_init(&chip->mtx);
/* init spinlock */
spin_lock_init(&chip->reg_lock);
/* (4) Define driver ID and name string */
strcpy(card->driver, "aw2");
strcpy(card->shortname, "Audiowerk2");
sprintf(card->longname, "%s with SAA7146 irq %i",
card->shortname, chip->irq);
/* (5) Create other components */
snd_aw2_new_pcm(chip);
/* (6) Register card instance */
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
return err;
}
/* (7) Set PCI driver data */
pci_set_drvdata(pci, card);
dev++;
return 0;
}
/* destructor */
static void __devexit snd_aw2_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
/* open callback */
static int snd_aw2_pcm_playback_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
snd_printdd(KERN_DEBUG "aw2: Playback_open \n");
runtime->hw = snd_aw2_playback_hw;
return 0;
}
/* close callback */
static int snd_aw2_pcm_playback_close(struct snd_pcm_substream *substream)
{
return 0;
}
static int snd_aw2_pcm_capture_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
snd_printdd(KERN_DEBUG "aw2: Capture_open \n");
runtime->hw = snd_aw2_capture_hw;
return 0;
}
/* close callback */
static int snd_aw2_pcm_capture_close(struct snd_pcm_substream *substream)
{
/* TODO: something to do ? */
return 0;
}
/* hw_params callback */
static int snd_aw2_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(hw_params));
}
/* hw_free callback */
static int snd_aw2_pcm_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
/* prepare callback for playback */
static int snd_aw2_pcm_prepare_playback(struct snd_pcm_substream *substream)
{
struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream);
struct aw2 *chip = pcm_device->chip;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned long period_size, buffer_size;
mutex_lock(&chip->mtx);
period_size = snd_pcm_lib_period_bytes(substream);
buffer_size = snd_pcm_lib_buffer_bytes(substream);
snd_aw2_saa7146_pcm_init_playback(&chip->saa7146,
pcm_device->stream_number,
runtime->dma_addr, period_size,
buffer_size);
/* Define Interrupt callback */
snd_aw2_saa7146_define_it_playback_callback(pcm_device->stream_number,
(snd_aw2_saa7146_it_cb)
snd_pcm_period_elapsed,
(void *)substream);
mutex_unlock(&chip->mtx);
return 0;
}
/* prepare callback for capture */
static int snd_aw2_pcm_prepare_capture(struct snd_pcm_substream *substream)
{
struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream);
struct aw2 *chip = pcm_device->chip;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned long period_size, buffer_size;
mutex_lock(&chip->mtx);
period_size = snd_pcm_lib_period_bytes(substream);
buffer_size = snd_pcm_lib_buffer_bytes(substream);
snd_aw2_saa7146_pcm_init_capture(&chip->saa7146,
pcm_device->stream_number,
runtime->dma_addr, period_size,
buffer_size);
/* Define Interrupt callback */
snd_aw2_saa7146_define_it_capture_callback(pcm_device->stream_number,
(snd_aw2_saa7146_it_cb)
snd_pcm_period_elapsed,
(void *)substream);
mutex_unlock(&chip->mtx);
return 0;
}
/* playback trigger callback */
static int snd_aw2_pcm_trigger_playback(struct snd_pcm_substream *substream,
int cmd)
{
int status = 0;
struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream);
struct aw2 *chip = pcm_device->chip;
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
snd_aw2_saa7146_pcm_trigger_start_playback(&chip->saa7146,
pcm_device->
stream_number);
break;
case SNDRV_PCM_TRIGGER_STOP:
snd_aw2_saa7146_pcm_trigger_stop_playback(&chip->saa7146,
pcm_device->
stream_number);
break;
default:
status = -EINVAL;
}
spin_unlock(&chip->reg_lock);
return status;
}
/* capture trigger callback */
static int snd_aw2_pcm_trigger_capture(struct snd_pcm_substream *substream,
int cmd)
{
int status = 0;
struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream);
struct aw2 *chip = pcm_device->chip;
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
snd_aw2_saa7146_pcm_trigger_start_capture(&chip->saa7146,
pcm_device->
stream_number);
break;
case SNDRV_PCM_TRIGGER_STOP:
snd_aw2_saa7146_pcm_trigger_stop_capture(&chip->saa7146,
pcm_device->
stream_number);
break;
default:
status = -EINVAL;
}
spin_unlock(&chip->reg_lock);
return status;
}
/* playback pointer callback */
static snd_pcm_uframes_t snd_aw2_pcm_pointer_playback(struct snd_pcm_substream
*substream)
{
struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream);
struct aw2 *chip = pcm_device->chip;
unsigned int current_ptr;
/* get the current hardware pointer */
struct snd_pcm_runtime *runtime = substream->runtime;
current_ptr =
snd_aw2_saa7146_get_hw_ptr_playback(&chip->saa7146,
pcm_device->stream_number,
runtime->dma_area,
runtime->buffer_size);
return bytes_to_frames(substream->runtime, current_ptr);
}
/* capture pointer callback */
static snd_pcm_uframes_t snd_aw2_pcm_pointer_capture(struct snd_pcm_substream
*substream)
{
struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream);
struct aw2 *chip = pcm_device->chip;
unsigned int current_ptr;
/* get the current hardware pointer */
struct snd_pcm_runtime *runtime = substream->runtime;
current_ptr =
snd_aw2_saa7146_get_hw_ptr_capture(&chip->saa7146,
pcm_device->stream_number,
runtime->dma_area,
runtime->buffer_size);
return bytes_to_frames(substream->runtime, current_ptr);
}
/* create a pcm device */
static int __devinit snd_aw2_new_pcm(struct aw2 *chip)
{
struct snd_pcm *pcm_playback_ana;
struct snd_pcm *pcm_playback_num;
struct snd_pcm *pcm_capture;
struct aw2_pcm_device *pcm_device;
int err = 0;
/* Create new Alsa PCM device */
err = snd_pcm_new(chip->card, "Audiowerk2 analog playback", 0, 1, 0,
&pcm_playback_ana);
if (err < 0) {
printk(KERN_ERR "aw2: snd_pcm_new error (0x%X)\n", err);
return err;
}
/* Creation ok */
pcm_device = &chip->device_playback[NUM_STREAM_PLAYBACK_ANA];
/* Set PCM device name */
strcpy(pcm_playback_ana->name, "Analog playback");
/* Associate private data to PCM device */
pcm_playback_ana->private_data = pcm_device;
/* set operators of PCM device */
snd_pcm_set_ops(pcm_playback_ana, SNDRV_PCM_STREAM_PLAYBACK,
&snd_aw2_playback_ops);
/* store PCM device */
pcm_device->pcm = pcm_playback_ana;
/* give base chip pointer to our internal pcm device
structure */
pcm_device->chip = chip;
/* Give stream number to PCM device */
pcm_device->stream_number = NUM_STREAM_PLAYBACK_ANA;
/* pre-allocation of buffers */
/* Preallocate continuous pages. */
err = snd_pcm_lib_preallocate_pages_for_all(pcm_playback_ana,
SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data
(chip->pci),
64 * 1024, 64 * 1024);
if (err)
printk(KERN_ERR "aw2: snd_pcm_lib_preallocate_pages_for_all "
"error (0x%X)\n", err);
err = snd_pcm_new(chip->card, "Audiowerk2 digital playback", 1, 1, 0,
&pcm_playback_num);
if (err < 0) {
printk(KERN_ERR "aw2: snd_pcm_new error (0x%X)\n", err);
return err;
}
/* Creation ok */
pcm_device = &chip->device_playback[NUM_STREAM_PLAYBACK_DIG];
/* Set PCM device name */
strcpy(pcm_playback_num->name, "Digital playback");
/* Associate private data to PCM device */
pcm_playback_num->private_data = pcm_device;
/* set operators of PCM device */
snd_pcm_set_ops(pcm_playback_num, SNDRV_PCM_STREAM_PLAYBACK,
&snd_aw2_playback_ops);
/* store PCM device */
pcm_device->pcm = pcm_playback_num;
/* give base chip pointer to our internal pcm device
structure */
pcm_device->chip = chip;
/* Give stream number to PCM device */
pcm_device->stream_number = NUM_STREAM_PLAYBACK_DIG;
/* pre-allocation of buffers */
/* Preallocate continuous pages. */
err = snd_pcm_lib_preallocate_pages_for_all(pcm_playback_num,
SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data
(chip->pci),
64 * 1024, 64 * 1024);
if (err)
printk(KERN_ERR
"aw2: snd_pcm_lib_preallocate_pages_for_all error "
"(0x%X)\n", err);
err = snd_pcm_new(chip->card, "Audiowerk2 capture", 2, 0, 1,
&pcm_capture);
if (err < 0) {
printk(KERN_ERR "aw2: snd_pcm_new error (0x%X)\n", err);
return err;
}
/* Creation ok */
pcm_device = &chip->device_capture[NUM_STREAM_CAPTURE_ANA];
/* Set PCM device name */
strcpy(pcm_capture->name, "Capture");
/* Associate private data to PCM device */
pcm_capture->private_data = pcm_device;
/* set operators of PCM device */
snd_pcm_set_ops(pcm_capture, SNDRV_PCM_STREAM_CAPTURE,
&snd_aw2_capture_ops);
/* store PCM device */
pcm_device->pcm = pcm_capture;
/* give base chip pointer to our internal pcm device
structure */
pcm_device->chip = chip;
/* Give stream number to PCM device */
pcm_device->stream_number = NUM_STREAM_CAPTURE_ANA;
/* pre-allocation of buffers */
/* Preallocate continuous pages. */
err = snd_pcm_lib_preallocate_pages_for_all(pcm_capture,
SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data
(chip->pci),
64 * 1024, 64 * 1024);
if (err)
printk(KERN_ERR
"aw2: snd_pcm_lib_preallocate_pages_for_all error "
"(0x%X)\n", err);
/* Create control */
err = snd_ctl_add(chip->card, snd_ctl_new1(&aw2_control, chip));
if (err < 0) {
printk(KERN_ERR "aw2: snd_ctl_add error (0x%X)\n", err);
return err;
}
return 0;
}
static int snd_aw2_control_switch_capture_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static char *texts[2] = {
"Analog", "Digital"
};
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items) {
uinfo->value.enumerated.item =
uinfo->value.enumerated.items - 1;
}
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_aw2_control_switch_capture_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value
*ucontrol)
{
struct aw2 *chip = snd_kcontrol_chip(kcontrol);
if (snd_aw2_saa7146_is_using_digital_input(&chip->saa7146))
ucontrol->value.enumerated.item[0] = CTL_ROUTE_DIGITAL;
else
ucontrol->value.enumerated.item[0] = CTL_ROUTE_ANALOG;
return 0;
}
static int snd_aw2_control_switch_capture_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value
*ucontrol)
{
struct aw2 *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int is_disgital =
snd_aw2_saa7146_is_using_digital_input(&chip->saa7146);
if (((ucontrol->value.integer.value[0] == CTL_ROUTE_DIGITAL)
&& !is_disgital)
|| ((ucontrol->value.integer.value[0] == CTL_ROUTE_ANALOG)
&& is_disgital)) {
snd_aw2_saa7146_use_digital_input(&chip->saa7146, !is_disgital);
changed = 1;
}
return changed;
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.