text stringlengths 2 99k | meta dict |
|---|---|
select
extract(year from '2000-01-01 12:34:56'::timestamptz),
extract(month from '2000-01-01 12:34:56'::timestamptz),
extract(day from '2000-01-01 12:34:56'::timestamptz),
extract(hour from '2000-01-01 12:34:56'::timestamptz),
extract(minute from '2000-01-01 12:34:56'::timestamptz),
extract(second from '2000-01-01 12:34:56'::timestamptz),
extract('second' from '2000-01-01 12:34:56'::timestamptz),
extract("second" from '2000-01-01 12:34:56'::timestamptz)
| {
"pile_set_name": "Github"
} |
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.writableObjectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (util.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (!util.isFunction(cb))
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function() {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function() {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing &&
!state.corked &&
!state.finished &&
!state.bufferProcessing &&
state.buffer.length)
clearBuffer(this, state);
}
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
util.isString(chunk)) {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing || state.corked)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, false, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev)
stream._writev(chunk, state.onwrite);
else
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
state.pendingcb--;
cb(er);
});
else {
state.pendingcb--;
cb(er);
}
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished &&
!state.corked &&
!state.bufferProcessing &&
state.buffer.length) {
clearBuffer(stream, state);
}
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
if (stream._writev && state.buffer.length > 1) {
// Fast case, write everything using _writev()
var cbs = [];
for (var c = 0; c < state.buffer.length; c++)
cbs.push(state.buffer[c].callback);
// count the one we are adding, as well.
// TODO(isaacs) clean this up
state.pendingcb++;
doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
for (var i = 0; i < cbs.length; i++) {
state.pendingcb--;
cbs[i](err);
}
});
// Clear buffer
state.buffer = [];
} else {
// Slow case, write chunks one-by-one
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
state.bufferProcessing = false;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (util.isFunction(chunk)) {
cb = chunk;
chunk = null;
encoding = null;
} else if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (!util.isNullOrUndefined(chunk))
this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else
prefinish(stream, state);
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished)
process.nextTick(cb);
else
stream.once('finish', cb);
}
state.ended = true;
}
| {
"pile_set_name": "Github"
} |
.. zeek:type:: ZeekygenTest::TypeAlias
:Type: :zeek:type:`bool`
This is just an alias for a builtin type ``bool``.
.. zeek:type:: ZeekygenTest::NotTypeAlias
:Type: :zeek:type:`bool`
This type should get its own comments, not associated w/ TypeAlias.
.. zeek:type:: ZeekygenTest::OtherTypeAlias
:Type: :zeek:type:`bool`
This cross references ``bool`` in the description of its type
instead of ``TypeAlias`` just because it seems more useful --
one doesn't have to click through the full type alias chain to
find out what the actual type is...
.. zeek:id:: ZeekygenTest::a
:Type: :zeek:type:`ZeekygenTest::TypeAlias`
But this should reference a type of ``TypeAlias``.
.. zeek:id:: ZeekygenTest::b
:Type: :zeek:type:`ZeekygenTest::OtherTypeAlias`
And this should reference a type of ``OtherTypeAlias``.
.. zeek:type:: ZeekygenTest::MyRecord
:Type: :zeek:type:`record`
f1: :zeek:type:`ZeekygenTest::TypeAlias`
f2: :zeek:type:`ZeekygenTest::OtherTypeAlias`
f3: :zeek:type:`bool`
| {
"pile_set_name": "Github"
} |
;(function($){
/**
* jqGrid Portuguese Translation
* Tradu��o da jqGrid em Portugues por Frederico Carvalho, http://www.eyeviewdesign.pt
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
**/
$.jgrid = $.jgrid || {};
$.extend($.jgrid,{
defaults : {
recordtext: "View {0} - {1} of {2}",
emptyrecords: "No records to view",
loadtext: "A carregar...",
pgtext : "Página {0} de {1}"
},
search : {
caption: "Busca...",
Find: "Procurar",
Reset: "Limpar",
odata: [{ oper:'eq', text:'equal'},{ oper:'ne', text:'not equal'},{ oper:'lt', text:'less'},{ oper:'le', text:'less or equal'},{ oper:'gt', text:'greater'},{ oper:'ge', text:'greater or equal'},{ oper:'bw', text:'begins with'},{ oper:'bn', text:'does not begin with'},{ oper:'in', text:'is in'},{ oper:'ni', text:'is not in'},{ oper:'ew', text:'ends with'},{ oper:'en', text:'does not end with'},{ oper:'cn', text:'contains'},{ oper:'nc', text:'does not contain'},{ oper:'nu', text:'is null'},{ oper:'nn', text:'is not null'}],
groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ],
operandTitle : "Click to select search operation.",
resetTitle : "Reset Search Value"
},
edit : {
addCaption: "Adicionar Registo",
editCaption: "Modificar Registo",
bSubmit: "Submeter",
bCancel: "Cancelar",
bClose: "Fechar",
saveData: "Data has been changed! Save changes?",
bYes : "Yes",
bNo : "No",
bExit : "Cancel",
msg: {
required:"Campo obrigat�rio",
number:"Por favor, introduza um numero",
minValue:"O valor deve ser maior ou igual que",
maxValue:"O valor deve ser menor ou igual a",
email: "N�o � um endere�o de email v�lido",
integer: "Por favor, introduza um numero inteiro",
url: "is not a valid URL. Prefix required ('http://' or 'https://')",
nodefined : " is not defined!",
novalue : " return value is required!",
customarray : "Custom function should return array!",
customfcheck : "Custom function should be present in case of custom checking!"
}
},
view : {
caption: "View Record",
bClose: "Close"
},
del : {
caption: "Eliminar",
msg: "Deseja eliminar o(s) registo(s) seleccionado(s)?",
bSubmit: "Eliminar",
bCancel: "Cancelar"
},
nav : {
edittext: " ",
edittitle: "Modificar registo seleccionado",
addtext:" ",
addtitle: "Adicionar novo registo",
deltext: " ",
deltitle: "Eliminar registo seleccionado",
searchtext: " ",
searchtitle: "Procurar",
refreshtext: "",
refreshtitle: "Actualizar",
alertcap: "Aviso",
alerttext: "Por favor, seleccione um registo",
viewtext: "",
viewtitle: "View selected row"
},
col : {
caption: "Mostrar/Ocultar Colunas",
bSubmit: "Enviar",
bCancel: "Cancelar"
},
errors : {
errcap : "Erro",
nourl : "N�o especificou um url",
norecords: "N�o existem dados para processar",
model : "Tamanho do colNames <> colModel!"
},
formatter : {
integer : {thousandsSeparator: " ", defaultValue: '0'},
number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'},
currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'},
date : {
dayNames: [
"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab",
"Domingo", "Segunda-Feira", "Ter�a-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "S�bado"
],
monthNames: [
"Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez",
"Janeiro", "Fevereiro", "Mar�o", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
],
AmPm : ["am","pm","AM","PM"],
S: function (j) {return j < 11 || j > 13 ? ['�', '�', '�', '�'][Math.min((j - 1) % 10, 3)] : '�'},
srcformat: 'Y-m-d',
newformat: 'd/m/Y',
parseRe : /[#%\\\/:_;.,\t\s-]/,
masks : {
ISO8601Long:"Y-m-d H:i:s",
ISO8601Short:"Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l, F d, Y g:i:s A",
MonthDay: "F d",
ShortTime: "g:i A",
LongTime: "g:i:s A",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
},
reformatAfterEdit : false
},
baseLinkUrl: '',
showAction: '',
target: '',
checkbox : {disabled:true},
idName : 'id'
}
});
})(jQuery);
| {
"pile_set_name": "Github"
} |
package kr.dogfoot.hwplib.object.bodytext.control.sectiondefine;
/**
* 용지 설정에 대한 레코드
*
* @author neolord
*/
public class PageDef {
/**
* 용지 가로 크기
*/
private long paperWidth;
/**
* 용지 세로 크기
*/
private long paperHeight;
/**
* 용지 왼쪽 여백
*/
private long leftMargin;
/**
* 용지 오른쪽 여백
*/
private long rightMargin;
/**
* 용지 위쪽 여백
*/
private long topMargin;
/**
* 용지 아래쪽 여백
*/
private long bottomMargin;
/**
* 머리말 여백
*/
private long headerMargin;
/**
* 꼬리말 여백
*/
private long footerMargin;
/**
* 제본 여백
*/
private long gutterMargin;
/**
* 속성
*/
private PageDefProperty property;
/**
* 생상자
*/
public PageDef() {
property = new PageDefProperty();
}
/**
* 용지 가로 크기를 반환한다.
*
* @return 용지 가로 크기
*/
public long getPaperWidth() {
return paperWidth;
}
/**
* 용지 가로 크기를 설정한다.
*
* @param paperWidth 용지 가로 크기
*/
public void setPaperWidth(long paperWidth) {
this.paperWidth = paperWidth;
}
/**
* 용지 세로 크기를 반환한다.
*
* @return 용지 세로 크기
*/
public long getPaperHeight() {
return paperHeight;
}
/**
* 용지 세로 크기를 설정한다.
*
* @param paperHeight 용지 세로 크기
*/
public void setPaperHeight(long paperHeight) {
this.paperHeight = paperHeight;
}
/**
* 용지 왼쪽 여백의 크기를 반환한다.
*
* @return 용지 왼쪽 여백의 크기
*/
public long getLeftMargin() {
return leftMargin;
}
/**
* 용지 왼쪽 여백의 크기를 설정한다.
*
* @param leftMargin 용지 왼쪽 여백의 크기
*/
public void setLeftMargin(long leftMargin) {
this.leftMargin = leftMargin;
}
/**
* 용지 오른쪽 여백의 크기를 반환한다.
*
* @return 용지 오른쪽 여백의 크기
*/
public long getRightMargin() {
return rightMargin;
}
/**
* 용지 오른쪽 여백의 크기를 설정한다.
*
* @param rightMargin 용지 오른쪽 여백의 크기
*/
public void setRightMargin(long rightMargin) {
this.rightMargin = rightMargin;
}
/**
* 용지 위쪽 여백의 크기를 반환한다.
*
* @return 용지 위쪽 여백의 크기
*/
public long getTopMargin() {
return topMargin;
}
/**
* 용지 위쪽 여백의 크기를 설정한다.
*
* @param topMargin 용지 위쪽 여백의 크기
*/
public void setTopMargin(long topMargin) {
this.topMargin = topMargin;
}
/**
* 용지 아래쪽 여백의 크기를 반환한다.
*
* @return 용지 아래쪽 여백의 크기
*/
public long getBottomMargin() {
return bottomMargin;
}
/**
* 용지 아래쪽 여백의 크기를 설정한다.
*
* @param bottomMargin 용지 아래쪽 여백의 크기
*/
public void setBottomMargin(long bottomMargin) {
this.bottomMargin = bottomMargin;
}
/**
* 머리말 여백의 크기를 반환한다.
*
* @return 머리말 여백의 크기
*/
public long getHeaderMargin() {
return headerMargin;
}
/**
* 머리말 여백의 크기를 설정한다.
*
* @param headerMargin 머리말 여백의 크기
*/
public void setHeaderMargin(long headerMargin) {
this.headerMargin = headerMargin;
}
/**
* 꼬리말 여백의 크기를 반환한다.
*
* @return 꼬리말 여백의 크기
*/
public long getFooterMargin() {
return footerMargin;
}
/**
* 꼬리말 여백의 크기를 설정한다.
*
* @param footerMargin 꼬리말 여백의 크기
*/
public void setFooterMargin(long footerMargin) {
this.footerMargin = footerMargin;
}
/**
* 제본 여백의 크기를 반환한다.
*
* @return 제본 여백의 크기
*/
public long getGutterMargin() {
return gutterMargin;
}
/**
* 제본 여백의 크기를 설정한다.
*
* @param gutterMargin 제본 여백의 크기
*/
public void setGutterMargin(long gutterMargin) {
this.gutterMargin = gutterMargin;
}
/**
* 속성 객체를 반환한다.
*
* @return 속성 객체
*/
public PageDefProperty getProperty() {
return property;
}
}
| {
"pile_set_name": "Github"
} |
//
// BIM IFC library: this library works with Autodesk(R) Revit(R) to export IFC files containing model geometry.
// Copyright (C) 2012 Autodesk, Inc.
//
// 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
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.Revit.DB.IFC;
using Revit.IFC.Export.Exporter;
using Revit.IFC.Export.Toolkit;
namespace Revit.IFC.Export.Utility
{
/// <summary>
/// Used to keep a cache of the elements contained in another element.
/// For example, by default, IFCPROJECT would have one item, IFCSITE.
/// </summary>
public class ContainmentCache : Dictionary<IFCAnyHandle, ICollection<IFCAnyHandle>>
{
Dictionary<IFCAnyHandle, string> m_ContainerGUIDs = new Dictionary<IFCAnyHandle, string>();
/// <summary>
/// Define the GUID for the IFCRELAGGREGATES.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="guid">The guid.</param>
public void SetGUIDForRelation(IFCAnyHandle container, string guid)
{
string existingGUID;
if (m_ContainerGUIDs.TryGetValue(container, out existingGUID))
throw new InvalidOperationException("GUID is already set.");
m_ContainerGUIDs[container] = guid;
}
/// <summary>
/// Get the GUID for the IFCRELAGGREGATES.
/// </summary>
/// <param name="container">The container.</param>
/// <returns>The GUID, if it exists.</returns>
public string GetGUIDForRelation(IFCAnyHandle container)
{
string existingGUID = null;
m_ContainerGUIDs.TryGetValue(container, out existingGUID);
return existingGUID;
}
/// <summary>
/// And an object to a container.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="objectHnd">The object to add.</param>
public void AddRelation(IFCAnyHandle container, IFCAnyHandle objectHnd)
{
ICollection<IFCAnyHandle> containedItems;
if (!TryGetValue(container, out containedItems))
{
containedItems = new HashSet<IFCAnyHandle>();
this[container] = containedItems;
}
containedItems.Add(objectHnd);
}
/// <summary>
/// And a collection of objects to a container.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="objectHnds">The objects to add.</param>
public void AddRelations(IFCAnyHandle container, ICollection<IFCAnyHandle> objectHnds)
{
foreach (IFCAnyHandle objectHnd in objectHnds)
AddRelation(container, objectHnd);
}
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
#ifndef ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_INCLUDE_AVSCOMMON_SDKINTERFACES_RANGECONTROLLER_RANGECONTROLLEROBSERVERINTERFACE_H_
#define ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_INCLUDE_AVSCOMMON_SDKINTERFACES_RANGECONTROLLER_RANGECONTROLLEROBSERVERINTERFACE_H_
#include <AVSCommon/SDKInterfaces/AlexaStateChangeCauseType.h>
#include <AVSCommon/Utils/Timing/TimePoint.h>
namespace alexaClientSDK {
namespace avsCommon {
namespace sdkInterfaces {
namespace rangeController {
/**
* This interface is used to observe changes to the range property of an endpoint
* that are caused by the @c RangeControllerInteface.
*/
class RangeControllerObserverInterface {
public:
/**
* Destructor.
*/
virtual ~RangeControllerObserverInterface() = default;
/**
* Struct represents the range state of the endpoint.
*/
struct RangeState {
/// A double to represent the range value of instance.
double value;
/// The time at which the range value was recorded.
avsCommon::utils::timing::TimePoint timeOfSample;
/// The number of milliseconds that have elapsed since the range value was last confrimed.
std::chrono::milliseconds valueUncertainty;
};
/**
* Notifies the change in the range value of the endpoint.
*
* @param rangeState The toggle state specified using @c RangeState.
* @param cause The cause for this change specified using @c AlexaStateChangeCauseType.
*/
virtual void onRangeChanged(const RangeState& rangeState, AlexaStateChangeCauseType cause) = 0;
};
} // namespace rangeController
} // namespace sdkInterfaces
} // namespace avsCommon
} // namespace alexaClientSDK
#endif // ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_INCLUDE_AVSCOMMON_SDKINTERFACES_RANGECONTROLLER_RANGECONTROLLEROBSERVERINTERFACE_H_
| {
"pile_set_name": "Github"
} |
// SV - Symbolic Vector Hardware Analysis Framework
// Copyright (C) 2014-2015 Centaur Technology
//
// Contact:
// Centaur Technology Formal Verification Group
// 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
// http://www.centtech.com/
//
// License: (An MIT/X11-style license)
//
// 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.
//
// Original author: Jared Davis <jared@centtech.com>
module spec (input logic [127:0] in,
output wire [127:0] out);
// Similar to gates_wideand
wire a1, b1, c1;
wire [1:0] a2, b2, c2;
wire [2:0] a3, b3, c3;
wire [3:0] a4, b4, c4;
wire signed sa1, sb1, sc1;
wire signed [1:0] sa2, sb2, sc2;
wire signed [2:0] sa3, sb3, sc3;
wire signed [3:0] sa4, sb4, sc4;
assign {a1, b1, c1} = in;
assign {a2, b2, c2} = in;
assign {a3, b3, c3} = in;
assign {a4, b4, c4} = in;
assign {sa1, sb1, sc1} = in;
assign {sa2, sb2, sc2} = in;
assign {sa3, sb3, sc3} = in;
assign {sa4, sb4, sc4} = in;
wire m1, m2, m3, m4;
buf(m1, a1);
buf(m2, a2);
buf(m3, a3);
buf(m4, a4);
wire sm1, sm2, sm3, sm4;
buf (sm1, sa1);
buf (sm2, sa2);
buf (sm3, sb3);
buf (sm4, sa4);
wire sr1, sr2, sr3, sr4, sr5, sr6, sr7, sr8;
buf (sr1, sr2, sa1);
buf (sr3, sr4, sa2);
buf (sr5, sr6, sa3);
buf (sr7, sr8, sa4);
assign out = { m1, m2, m3, m4,
sm1, sm2, sm3, sm4,
sr1, sr2, sr3, sr4
};
endmodule
| {
"pile_set_name": "Github"
} |
//
// read_at.hpp
// ~~~~~~~~~~~
//
// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef BOOST_ASIO_READ_AT_HPP
#define BOOST_ASIO_READ_AT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <cstddef>
#include <boost/asio/async_result.hpp>
#include <boost/asio/detail/cstdint.hpp>
#include <boost/asio/error.hpp>
#if !defined(BOOST_ASIO_NO_EXTENSIONS)
# include <boost/asio/basic_streambuf_fwd.hpp>
#endif // !defined(BOOST_ASIO_NO_EXTENSIONS)
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
/**
* @defgroup read_at boost::asio::read_at
*
* @brief The @c read_at function is a composed operation that reads a certain
* amount of data at the specified offset before returning.
*/
/*@{*/
/// Attempt to read a certain amount of data at the specified offset before
/// returning.
/**
* This function is used to read a certain number of bytes of data from a
* random access device at the specified offset. The call will block until one
* of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the device's
* read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the SyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* device.
*
* @returns The number of bytes transferred.
*
* @throws boost::system::system_error Thrown on failure.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code boost::asio::read_at(d, 42, boost::asio::buffer(data, size)); @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @note This overload is equivalent to calling:
* @code boost::asio::read_at(
* d, 42, buffers,
* boost::asio::transfer_all()); @endcode
*/
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers);
/// Attempt to read a certain amount of data at the specified offset before
/// returning.
/**
* This function is used to read a certain number of bytes of data from a
* random access device at the specified offset. The call will block until one
* of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the device's
* read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the SyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* device.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes transferred.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code boost::asio::read_at(d, 42,
* boost::asio::buffer(data, size), ec); @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @note This overload is equivalent to calling:
* @code boost::asio::read_at(
* d, 42, buffers,
* boost::asio::transfer_all(), ec); @endcode
*/
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
boost::system::error_code& ec);
/// Attempt to read a certain amount of data at the specified offset before
/// returning.
/**
* This function is used to read a certain number of bytes of data from a
* random access device at the specified offset. The call will block until one
* of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the device's
* read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the SyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* device.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest read_some_at operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the device's read_some_at function.
*
* @returns The number of bytes transferred.
*
* @throws boost::system::system_error Thrown on failure.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code boost::asio::read_at(d, 42, boost::asio::buffer(data, size),
* boost::asio::transfer_at_least(32)); @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence,
typename CompletionCondition>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
CompletionCondition completion_condition);
/// Attempt to read a certain amount of data at the specified offset before
/// returning.
/**
* This function is used to read a certain number of bytes of data from a
* random access device at the specified offset. The call will block until one
* of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the device's
* read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the SyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* device.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest read_some_at operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the device's read_some_at function.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes read. If an error occurs, returns the total
* number of bytes successfully transferred prior to the error.
*/
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence,
typename CompletionCondition>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
CompletionCondition completion_condition, boost::system::error_code& ec);
#if !defined(BOOST_ASIO_NO_EXTENSIONS)
#if !defined(BOOST_ASIO_NO_IOSTREAM)
/// Attempt to read a certain amount of data at the specified offset before
/// returning.
/**
* This function is used to read a certain number of bytes of data from a
* random access device at the specified offset. The call will block until one
* of the following conditions is true:
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the device's
* read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the SyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param b The basic_streambuf object into which the data will be read.
*
* @returns The number of bytes transferred.
*
* @throws boost::system::system_error Thrown on failure.
*
* @note This overload is equivalent to calling:
* @code boost::asio::read_at(
* d, 42, b,
* boost::asio::transfer_all()); @endcode
*/
template <typename SyncRandomAccessReadDevice, typename Allocator>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, basic_streambuf<Allocator>& b);
/// Attempt to read a certain amount of data at the specified offset before
/// returning.
/**
* This function is used to read a certain number of bytes of data from a
* random access device at the specified offset. The call will block until one
* of the following conditions is true:
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the device's
* read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the SyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param b The basic_streambuf object into which the data will be read.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes transferred.
*
* @note This overload is equivalent to calling:
* @code boost::asio::read_at(
* d, 42, b,
* boost::asio::transfer_all(), ec); @endcode
*/
template <typename SyncRandomAccessReadDevice, typename Allocator>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, basic_streambuf<Allocator>& b,
boost::system::error_code& ec);
/// Attempt to read a certain amount of data at the specified offset before
/// returning.
/**
* This function is used to read a certain number of bytes of data from a
* random access device at the specified offset. The call will block until one
* of the following conditions is true:
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the device's
* read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the SyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param b The basic_streambuf object into which the data will be read.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest read_some_at operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the device's read_some_at function.
*
* @returns The number of bytes transferred.
*
* @throws boost::system::system_error Thrown on failure.
*/
template <typename SyncRandomAccessReadDevice, typename Allocator,
typename CompletionCondition>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, basic_streambuf<Allocator>& b,
CompletionCondition completion_condition);
/// Attempt to read a certain amount of data at the specified offset before
/// returning.
/**
* This function is used to read a certain number of bytes of data from a
* random access device at the specified offset. The call will block until one
* of the following conditions is true:
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the device's
* read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the SyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param b The basic_streambuf object into which the data will be read.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest read_some_at operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the device's read_some_at function.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes read. If an error occurs, returns the total
* number of bytes successfully transferred prior to the error.
*/
template <typename SyncRandomAccessReadDevice, typename Allocator,
typename CompletionCondition>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, basic_streambuf<Allocator>& b,
CompletionCondition completion_condition, boost::system::error_code& ec);
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)
#endif // !defined(BOOST_ASIO_NO_EXTENSIONS)
/*@}*/
/**
* @defgroup async_read_at boost::asio::async_read_at
*
* @brief The @c async_read_at function is a composed asynchronous operation
* that reads a certain amount of data at the specified offset.
*/
/*@{*/
/// Start an asynchronous operation to read a certain amount of data at the
/// specified offset.
/**
* This function is used to asynchronously read a certain number of bytes of
* data from a random access device at the specified offset. The function call
* always returns immediately. The asynchronous operation will continue until
* one of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the device's
* async_read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the AsyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* device. Although the buffers object may be copied as necessary, ownership of
* the underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the handler is called.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* // Result of operation.
* const boost::system::error_code& error,
*
* // Number of bytes copied into the buffers. If an error
* // occurred, this will be the number of bytes successfully
* // transferred prior to the error.
* std::size_t bytes_transferred
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. On
* immediate completion, invocation of the handler will be performed in a
* manner equivalent to using boost::asio::post().
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code
* boost::asio::async_read_at(d, 42, boost::asio::buffer(data, size), handler);
* @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @note This overload is equivalent to calling:
* @code boost::asio::async_read_at(
* d, 42, buffers,
* boost::asio::transfer_all(),
* handler); @endcode
*/
template <typename AsyncRandomAccessReadDevice, typename MutableBufferSequence,
typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset,
const MutableBufferSequence& buffers,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler);
/// Start an asynchronous operation to read a certain amount of data at the
/// specified offset.
/**
* This function is used to asynchronously read a certain number of bytes of
* data from a random access device at the specified offset. The function call
* always returns immediately. The asynchronous operation will continue until
* one of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li The completion_condition function object returns 0.
*
* @param d The device from which the data is to be read. The type must support
* the AsyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* device. Although the buffers object may be copied as necessary, ownership of
* the underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the handler is called.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest async_read_some_at operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the device's async_read_some_at function.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* // Result of operation.
* const boost::system::error_code& error,
*
* // Number of bytes copied into the buffers. If an error
* // occurred, this will be the number of bytes successfully
* // transferred prior to the error.
* std::size_t bytes_transferred
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. On
* immediate completion, invocation of the handler will be performed in a
* manner equivalent to using boost::asio::post().
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code boost::asio::async_read_at(d, 42,
* boost::asio::buffer(data, size),
* boost::asio::transfer_at_least(32),
* handler); @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename AsyncRandomAccessReadDevice, typename MutableBufferSequence,
typename CompletionCondition, typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read_at(AsyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
CompletionCondition completion_condition,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler);
#if !defined(BOOST_ASIO_NO_EXTENSIONS)
#if !defined(BOOST_ASIO_NO_IOSTREAM)
/// Start an asynchronous operation to read a certain amount of data at the
/// specified offset.
/**
* This function is used to asynchronously read a certain number of bytes of
* data from a random access device at the specified offset. The function call
* always returns immediately. The asynchronous operation will continue until
* one of the following conditions is true:
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the device's
* async_read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the AsyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param b A basic_streambuf object into which the data will be read. Ownership
* of the streambuf is retained by the caller, which must guarantee that it
* remains valid until the handler is called.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* // Result of operation.
* const boost::system::error_code& error,
*
* // Number of bytes copied into the buffers. If an error
* // occurred, this will be the number of bytes successfully
* // transferred prior to the error.
* std::size_t bytes_transferred
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. On
* immediate completion, invocation of the handler will be performed in a
* manner equivalent to using boost::asio::post().
*
* @note This overload is equivalent to calling:
* @code boost::asio::async_read_at(
* d, 42, b,
* boost::asio::transfer_all(),
* handler); @endcode
*/
template <typename AsyncRandomAccessReadDevice, typename Allocator,
typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset,
basic_streambuf<Allocator>& b, BOOST_ASIO_MOVE_ARG(ReadHandler) handler);
/// Start an asynchronous operation to read a certain amount of data at the
/// specified offset.
/**
* This function is used to asynchronously read a certain number of bytes of
* data from a random access device at the specified offset. The function call
* always returns immediately. The asynchronous operation will continue until
* one of the following conditions is true:
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the device's
* async_read_some_at function.
*
* @param d The device from which the data is to be read. The type must support
* the AsyncRandomAccessReadDevice concept.
*
* @param offset The offset at which the data will be read.
*
* @param b A basic_streambuf object into which the data will be read. Ownership
* of the streambuf is retained by the caller, which must guarantee that it
* remains valid until the handler is called.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest async_read_some_at operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the device's async_read_some_at function.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* // Result of operation.
* const boost::system::error_code& error,
*
* // Number of bytes copied into the buffers. If an error
* // occurred, this will be the number of bytes successfully
* // transferred prior to the error.
* std::size_t bytes_transferred
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. On
* immediate completion, invocation of the handler will be performed in a
* manner equivalent to using boost::asio::post().
*/
template <typename AsyncRandomAccessReadDevice, typename Allocator,
typename CompletionCondition, typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read_at(AsyncRandomAccessReadDevice& d,
uint64_t offset, basic_streambuf<Allocator>& b,
CompletionCondition completion_condition,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler);
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)
#endif // !defined(BOOST_ASIO_NO_EXTENSIONS)
/*@}*/
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#include <boost/asio/impl/read_at.hpp>
#endif // BOOST_ASIO_READ_AT_HPP
| {
"pile_set_name": "Github"
} |
## @file
# This package provides EDKII capsule related support.
#
# Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
[Defines]
DEC_SPECIFICATION = 0x00010005
PACKAGE_NAME = SignedCapsulePkg
PACKAGE_GUID = 75AA5D82-7BC4-44A9-82FB-0820EBC79BED
PACKAGE_VERSION = 0.1
[Includes]
Include
[LibraryClasses]
## @libraryclass Provides services for EDKII system FMP capsule.
#
EdkiiSystemCapsuleLib|Include/Library/EdkiiSystemCapsuleLib.h
## @libraryclass Provides services to parse the INI configuration file.
#
IniParsingLib|Include/Library/IniParsingLib.h
## @libraryclass Provides services to access flash device.
#
PlatformFlashAccessLib|Include/Library/PlatformFlashAccessLib.h
[Guids]
gEfiSignedCapsulePkgTokenSpaceGuid = { 0xe1eb612f, 0x1c6c, 0x485d, { 0x9d, 0x6, 0x65, 0x8, 0x44, 0x88, 0x15, 0x69 }}
## Include/Guid/EdkiiSystemFmpCapsule.h
gEdkiiSystemFirmwareImageDescriptorFileGuid = {0x90b2b846, 0xca6d, 0x4d6e, {0xa8, 0xd3, 0xc1, 0x40, 0xa8, 0xe1, 0x10, 0xac}}
gEdkiiSystemFmpCapsuleConfigFileGuid = {0x812136d3, 0x4d3a, 0x433a, {0x94, 0x18, 0x29, 0xbb, 0x9b, 0xf7, 0x8f, 0x6e}}
gEdkiiSystemFmpCapsuleDriverFvFileGuid = {0xce57b167, 0xb0e4, 0x41e8, {0xa8, 0x97, 0x5f, 0x4f, 0xeb, 0x78, 0x1d, 0x40}}
[PcdsFixedAtBuild, PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx]
## This is the GUID of the FFS which contains the Rsa2048Sha256TestPublicKeyFile as a RAW section.
# @Prompt GUID of the FFS which contains the Rsa2048Sha256TestPublicKeyFile.
gEfiSignedCapsulePkgTokenSpaceGuid.PcdEdkiiRsa2048Sha256TestPublicKeyFileGuid|{0x04, 0xe1, 0xfe, 0xc4, 0x57, 0x66, 0x36, 0x49, 0xa6, 0x11, 0x13, 0x8d, 0xbc, 0x2a, 0x76, 0xad}|VOID*|0xA0010001
## This is the GUID of the FFS which contains the Pkcs7TestPublicKeyFile as a RAW section.
# @Prompt GUID of the FFS which contains the Pkcs7TestPublicKeyFile.
gEfiSignedCapsulePkgTokenSpaceGuid.PcdEdkiiPkcs7TestPublicKeyFileGuid|{0xba, 0xf5, 0x93, 0xf0, 0x37, 0x6f, 0x16, 0x48, 0x9e, 0x52, 0x91, 0xbe, 0xa0, 0xf7, 0xe0, 0xb8}|VOID*|0xA0010002
## This is the lowest supported version number that can be upgraded to, as exposed via the System Firmware descriptor.
# @Prompt Lowest support version number that can be upgraded to via capsule update
gEfiSignedCapsulePkgTokenSpaceGuid.PcdLowestSupportedFirmwareVersion|0x1|UINT32|0xA0010003
[PcdsDynamicEx]
## This dynamic PCD holds the EDKII system firmware image descriptor.
# This information can be used for version check in EDKII system FMP capsule.
# Only if the new EdkiiSystemFirmwareImageDescriptor.Version is not less than
# the current PcdEdkiiSystemFirmwareImageDescriptor.LowestSupportedVersion,
# the EDKII system FmpCapsule will be processed.
# The data structure of this PCD is EDKII_SYSTEM_FIRMWARE_IMAGE_DESCRIPTOR,
# SignedCapsulePkg/Include/Guid/EdkiiSystemFmpCapsule.h.
# It must be in [PcdsDynamicEx], because the EDKII system firmware update module may
# consume the PCD produced in current system firmware.
# @Prompt EDKII system firmware image descriptor.
gEfiSignedCapsulePkgTokenSpaceGuid.PcdEdkiiSystemFirmwareImageDescriptor|{0x0}|VOID*|0x00000037
## This dynamic PCD hold the GUID of a firmware FFS which includes EDKII
# system firmware image.
# An EDKII system firmware update module need consume this PCD to extract
# the EDKII system firmware from the capsule image.
# It must be in [PcdsDynamicEx], because the EDKII system firmware update module may
# consume the PCD produced in current system firmware image.
# @Prompt EDKII system firmware image FFS GUID.
gEfiSignedCapsulePkgTokenSpaceGuid.PcdEdkiiSystemFirmwareFileGuid|{0x0}|VOID*|0x00001010
| {
"pile_set_name": "Github"
} |
/*!
* Bootstrap Responsive v2.3.2
*
* Copyright 2013 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @mdo and @fat.
*/
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
display: table;
line-height: 0;
content: "";
}
.clearfix:after {
clear: both;
}
.hide-text {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.input-block-level {
display: block;
width: 100%;
min-height: 30px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
@-ms-viewport {
width: device-width;
}
.hidden {
display: none;
visibility: hidden;
}
.visible-phone {
display: none !important;
}
.visible-tablet {
display: none !important;
}
.hidden-desktop {
display: none !important;
}
.visible-desktop {
display: inherit !important;
}
@media (min-width: 768px) and (max-width: 979px) {
.hidden-desktop {
display: inherit !important;
}
.visible-desktop {
display: none !important ;
}
.visible-tablet {
display: inherit !important;
}
.hidden-tablet {
display: none !important;
}
}
@media (max-width: 767px) {
.hidden-desktop {
display: inherit !important;
}
.visible-desktop {
display: none !important;
}
.visible-phone {
display: inherit !important;
}
.hidden-phone {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: inherit !important;
}
.hidden-print {
display: none !important;
}
}
@media (min-width: 1200px) {
.row {
margin-left: -30px;
*zoom: 1;
}
.row:before,
.row:after {
display: table;
line-height: 0;
content: "";
}
.row:after {
clear: both;
}
[class*="span"] {
float: left;
min-height: 1px;
margin-left: 30px;
}
.container,
.navbar-static-top .container,
.navbar-fixed-top .container,
.navbar-fixed-bottom .container {
width: 1170px;
}
.span12 {
width: 1170px;
}
.span11 {
width: 1070px;
}
.span10 {
width: 970px;
}
.span9 {
width: 870px;
}
.span8 {
width: 770px;
}
.span7 {
width: 670px;
}
.span6 {
width: 570px;
}
.span5 {
width: 470px;
}
.span4 {
width: 370px;
}
.span3 {
width: 270px;
}
.span2 {
width: 170px;
}
.span1 {
width: 70px;
}
.offset12 {
margin-left: 1230px;
}
.offset11 {
margin-left: 1130px;
}
.offset10 {
margin-left: 1030px;
}
.offset9 {
margin-left: 930px;
}
.offset8 {
margin-left: 830px;
}
.offset7 {
margin-left: 730px;
}
.offset6 {
margin-left: 630px;
}
.offset5 {
margin-left: 530px;
}
.offset4 {
margin-left: 430px;
}
.offset3 {
margin-left: 330px;
}
.offset2 {
margin-left: 230px;
}
.offset1 {
margin-left: 130px;
}
.row-fluid {
width: 100%;
*zoom: 1;
}
.row-fluid:before,
.row-fluid:after {
display: table;
line-height: 0;
content: "";
}
.row-fluid:after {
clear: both;
}
.row-fluid [class*="span"] {
display: block;
float: left;
width: 100%;
min-height: 30px;
margin-left: 2.564102564102564%;
*margin-left: 2.5109110747408616%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.row-fluid [class*="span"]:first-child {
margin-left: 0;
}
.row-fluid .controls-row [class*="span"] + [class*="span"] {
margin-left: 2.564102564102564%;
}
.row-fluid .span12 {
width: 100%;
*width: 99.94680851063829%;
}
.row-fluid .span11 {
width: 91.45299145299145%;
*width: 91.39979996362975%;
}
.row-fluid .span10 {
width: 82.90598290598291%;
*width: 82.8527914166212%;
}
.row-fluid .span9 {
width: 74.35897435897436%;
*width: 74.30578286961266%;
}
.row-fluid .span8 {
width: 65.81196581196582%;
*width: 65.75877432260411%;
}
.row-fluid .span7 {
width: 57.26495726495726%;
*width: 57.21176577559556%;
}
.row-fluid .span6 {
width: 48.717948717948715%;
*width: 48.664757228587014%;
}
.row-fluid .span5 {
width: 40.17094017094017%;
*width: 40.11774868157847%;
}
.row-fluid .span4 {
width: 31.623931623931625%;
*width: 31.570740134569924%;
}
.row-fluid .span3 {
width: 23.076923076923077%;
*width: 23.023731587561375%;
}
.row-fluid .span2 {
width: 14.52991452991453%;
*width: 14.476723040552828%;
}
.row-fluid .span1 {
width: 5.982905982905983%;
*width: 5.929714493544281%;
}
.row-fluid .offset12 {
margin-left: 105.12820512820512%;
*margin-left: 105.02182214948171%;
}
.row-fluid .offset12:first-child {
margin-left: 102.56410256410257%;
*margin-left: 102.45771958537915%;
}
.row-fluid .offset11 {
margin-left: 96.58119658119658%;
*margin-left: 96.47481360247316%;
}
.row-fluid .offset11:first-child {
margin-left: 94.01709401709402%;
*margin-left: 93.91071103837061%;
}
.row-fluid .offset10 {
margin-left: 88.03418803418803%;
*margin-left: 87.92780505546462%;
}
.row-fluid .offset10:first-child {
margin-left: 85.47008547008548%;
*margin-left: 85.36370249136206%;
}
.row-fluid .offset9 {
margin-left: 79.48717948717949%;
*margin-left: 79.38079650845607%;
}
.row-fluid .offset9:first-child {
margin-left: 76.92307692307693%;
*margin-left: 76.81669394435352%;
}
.row-fluid .offset8 {
margin-left: 70.94017094017094%;
*margin-left: 70.83378796144753%;
}
.row-fluid .offset8:first-child {
margin-left: 68.37606837606839%;
*margin-left: 68.26968539734497%;
}
.row-fluid .offset7 {
margin-left: 62.393162393162385%;
*margin-left: 62.28677941443899%;
}
.row-fluid .offset7:first-child {
margin-left: 59.82905982905982%;
*margin-left: 59.72267685033642%;
}
.row-fluid .offset6 {
margin-left: 53.84615384615384%;
*margin-left: 53.739770867430444%;
}
.row-fluid .offset6:first-child {
margin-left: 51.28205128205128%;
*margin-left: 51.175668303327875%;
}
.row-fluid .offset5 {
margin-left: 45.299145299145295%;
*margin-left: 45.1927623204219%;
}
.row-fluid .offset5:first-child {
margin-left: 42.73504273504273%;
*margin-left: 42.62865975631933%;
}
.row-fluid .offset4 {
margin-left: 36.75213675213675%;
*margin-left: 36.645753773413354%;
}
.row-fluid .offset4:first-child {
margin-left: 34.18803418803419%;
*margin-left: 34.081651209310785%;
}
.row-fluid .offset3 {
margin-left: 28.205128205128204%;
*margin-left: 28.0987452264048%;
}
.row-fluid .offset3:first-child {
margin-left: 25.641025641025642%;
*margin-left: 25.53464266230224%;
}
.row-fluid .offset2 {
margin-left: 19.65811965811966%;
*margin-left: 19.551736679396257%;
}
.row-fluid .offset2:first-child {
margin-left: 17.094017094017094%;
*margin-left: 16.98763411529369%;
}
.row-fluid .offset1 {
margin-left: 11.11111111111111%;
*margin-left: 11.004728132387708%;
}
.row-fluid .offset1:first-child {
margin-left: 8.547008547008547%;
*margin-left: 8.440625568285142%;
}
input,
textarea,
.uneditable-input {
margin-left: 0;
}
.controls-row [class*="span"] + [class*="span"] {
margin-left: 30px;
}
input.span12,
textarea.span12,
.uneditable-input.span12 {
width: 1156px;
}
input.span11,
textarea.span11,
.uneditable-input.span11 {
width: 1056px;
}
input.span10,
textarea.span10,
.uneditable-input.span10 {
width: 956px;
}
input.span9,
textarea.span9,
.uneditable-input.span9 {
width: 856px;
}
input.span8,
textarea.span8,
.uneditable-input.span8 {
width: 756px;
}
input.span7,
textarea.span7,
.uneditable-input.span7 {
width: 656px;
}
input.span6,
textarea.span6,
.uneditable-input.span6 {
width: 556px;
}
input.span5,
textarea.span5,
.uneditable-input.span5 {
width: 456px;
}
input.span4,
textarea.span4,
.uneditable-input.span4 {
width: 356px;
}
input.span3,
textarea.span3,
.uneditable-input.span3 {
width: 256px;
}
input.span2,
textarea.span2,
.uneditable-input.span2 {
width: 156px;
}
input.span1,
textarea.span1,
.uneditable-input.span1 {
width: 56px;
}
.thumbnails {
margin-left: -30px;
}
.thumbnails > li {
margin-left: 30px;
}
.row-fluid .thumbnails {
margin-left: 0;
}
}
@media (min-width: 768px) and (max-width: 979px) {
.row {
margin-left: -20px;
*zoom: 1;
}
.row:before,
.row:after {
display: table;
line-height: 0;
content: "";
}
.row:after {
clear: both;
}
[class*="span"] {
float: left;
min-height: 1px;
margin-left: 20px;
}
.container,
.navbar-static-top .container,
.navbar-fixed-top .container,
.navbar-fixed-bottom .container {
width: 724px;
}
.span12 {
width: 724px;
}
.span11 {
width: 662px;
}
.span10 {
width: 600px;
}
.span9 {
width: 538px;
}
.span8 {
width: 476px;
}
.span7 {
width: 414px;
}
.span6 {
width: 352px;
}
.span5 {
width: 290px;
}
.span4 {
width: 228px;
}
.span3 {
width: 166px;
}
.span2 {
width: 104px;
}
.span1 {
width: 42px;
}
.offset12 {
margin-left: 764px;
}
.offset11 {
margin-left: 702px;
}
.offset10 {
margin-left: 640px;
}
.offset9 {
margin-left: 578px;
}
.offset8 {
margin-left: 516px;
}
.offset7 {
margin-left: 454px;
}
.offset6 {
margin-left: 392px;
}
.offset5 {
margin-left: 330px;
}
.offset4 {
margin-left: 268px;
}
.offset3 {
margin-left: 206px;
}
.offset2 {
margin-left: 144px;
}
.offset1 {
margin-left: 82px;
}
.row-fluid {
width: 100%;
*zoom: 1;
}
.row-fluid:before,
.row-fluid:after {
display: table;
line-height: 0;
content: "";
}
.row-fluid:after {
clear: both;
}
.row-fluid [class*="span"] {
display: block;
float: left;
width: 100%;
min-height: 30px;
margin-left: 2.7624309392265194%;
*margin-left: 2.709239449864817%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.row-fluid [class*="span"]:first-child {
margin-left: 0;
}
.row-fluid .controls-row [class*="span"] + [class*="span"] {
margin-left: 2.7624309392265194%;
}
.row-fluid .span12 {
width: 100%;
*width: 99.94680851063829%;
}
.row-fluid .span11 {
width: 91.43646408839778%;
*width: 91.38327259903608%;
}
.row-fluid .span10 {
width: 82.87292817679558%;
*width: 82.81973668743387%;
}
.row-fluid .span9 {
width: 74.30939226519337%;
*width: 74.25620077583166%;
}
.row-fluid .span8 {
width: 65.74585635359117%;
*width: 65.69266486422946%;
}
.row-fluid .span7 {
width: 57.18232044198895%;
*width: 57.12912895262725%;
}
.row-fluid .span6 {
width: 48.61878453038674%;
*width: 48.56559304102504%;
}
.row-fluid .span5 {
width: 40.05524861878453%;
*width: 40.00205712942283%;
}
.row-fluid .span4 {
width: 31.491712707182323%;
*width: 31.43852121782062%;
}
.row-fluid .span3 {
width: 22.92817679558011%;
*width: 22.87498530621841%;
}
.row-fluid .span2 {
width: 14.3646408839779%;
*width: 14.311449394616199%;
}
.row-fluid .span1 {
width: 5.801104972375691%;
*width: 5.747913483013988%;
}
.row-fluid .offset12 {
margin-left: 105.52486187845304%;
*margin-left: 105.41847889972962%;
}
.row-fluid .offset12:first-child {
margin-left: 102.76243093922652%;
*margin-left: 102.6560479605031%;
}
.row-fluid .offset11 {
margin-left: 96.96132596685082%;
*margin-left: 96.8549429881274%;
}
.row-fluid .offset11:first-child {
margin-left: 94.1988950276243%;
*margin-left: 94.09251204890089%;
}
.row-fluid .offset10 {
margin-left: 88.39779005524862%;
*margin-left: 88.2914070765252%;
}
.row-fluid .offset10:first-child {
margin-left: 85.6353591160221%;
*margin-left: 85.52897613729868%;
}
.row-fluid .offset9 {
margin-left: 79.8342541436464%;
*margin-left: 79.72787116492299%;
}
.row-fluid .offset9:first-child {
margin-left: 77.07182320441989%;
*margin-left: 76.96544022569647%;
}
.row-fluid .offset8 {
margin-left: 71.2707182320442%;
*margin-left: 71.16433525332079%;
}
.row-fluid .offset8:first-child {
margin-left: 68.50828729281768%;
*margin-left: 68.40190431409427%;
}
.row-fluid .offset7 {
margin-left: 62.70718232044199%;
*margin-left: 62.600799341718584%;
}
.row-fluid .offset7:first-child {
margin-left: 59.94475138121547%;
*margin-left: 59.838368402492065%;
}
.row-fluid .offset6 {
margin-left: 54.14364640883978%;
*margin-left: 54.037263430116376%;
}
.row-fluid .offset6:first-child {
margin-left: 51.38121546961326%;
*margin-left: 51.27483249088986%;
}
.row-fluid .offset5 {
margin-left: 45.58011049723757%;
*margin-left: 45.47372751851417%;
}
.row-fluid .offset5:first-child {
margin-left: 42.81767955801105%;
*margin-left: 42.71129657928765%;
}
.row-fluid .offset4 {
margin-left: 37.01657458563536%;
*margin-left: 36.91019160691196%;
}
.row-fluid .offset4:first-child {
margin-left: 34.25414364640884%;
*margin-left: 34.14776066768544%;
}
.row-fluid .offset3 {
margin-left: 28.45303867403315%;
*margin-left: 28.346655695309746%;
}
.row-fluid .offset3:first-child {
margin-left: 25.69060773480663%;
*margin-left: 25.584224756083227%;
}
.row-fluid .offset2 {
margin-left: 19.88950276243094%;
*margin-left: 19.783119783707537%;
}
.row-fluid .offset2:first-child {
margin-left: 17.12707182320442%;
*margin-left: 17.02068884448102%;
}
.row-fluid .offset1 {
margin-left: 11.32596685082873%;
*margin-left: 11.219583872105325%;
}
.row-fluid .offset1:first-child {
margin-left: 8.56353591160221%;
*margin-left: 8.457152932878806%;
}
input,
textarea,
.uneditable-input {
margin-left: 0;
}
.controls-row [class*="span"] + [class*="span"] {
margin-left: 20px;
}
input.span12,
textarea.span12,
.uneditable-input.span12 {
width: 710px;
}
input.span11,
textarea.span11,
.uneditable-input.span11 {
width: 648px;
}
input.span10,
textarea.span10,
.uneditable-input.span10 {
width: 586px;
}
input.span9,
textarea.span9,
.uneditable-input.span9 {
width: 524px;
}
input.span8,
textarea.span8,
.uneditable-input.span8 {
width: 462px;
}
input.span7,
textarea.span7,
.uneditable-input.span7 {
width: 400px;
}
input.span6,
textarea.span6,
.uneditable-input.span6 {
width: 338px;
}
input.span5,
textarea.span5,
.uneditable-input.span5 {
width: 276px;
}
input.span4,
textarea.span4,
.uneditable-input.span4 {
width: 214px;
}
input.span3,
textarea.span3,
.uneditable-input.span3 {
width: 152px;
}
input.span2,
textarea.span2,
.uneditable-input.span2 {
width: 90px;
}
input.span1,
textarea.span1,
.uneditable-input.span1 {
width: 28px;
}
}
@media (max-width: 767px) {
body {
padding-right: 20px;
padding-left: 20px;
}
.navbar-fixed-top,
.navbar-fixed-bottom,
.navbar-static-top {
margin-right: -20px;
margin-left: -20px;
}
.container-fluid {
padding: 0;
}
.dl-horizontal dt {
float: none;
width: auto;
clear: none;
text-align: left;
}
.dl-horizontal dd {
margin-left: 0;
}
.container {
width: auto;
}
.row-fluid {
width: 100%;
}
.row,
.thumbnails {
margin-left: 0;
}
.thumbnails > li {
float: none;
margin-left: 0;
}
[class*="span"],
.uneditable-input[class*="span"],
.row-fluid [class*="span"] {
display: block;
float: none;
width: 100%;
margin-left: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.span12,
.row-fluid .span12 {
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.row-fluid [class*="offset"]:first-child {
margin-left: 0;
}
.input-large,
.input-xlarge,
.input-xxlarge,
input[class*="span"],
select[class*="span"],
textarea[class*="span"],
.uneditable-input {
display: block;
width: 100%;
min-height: 30px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.input-prepend input,
.input-append input,
.input-prepend input[class*="span"],
.input-append input[class*="span"] {
display: inline-block;
width: auto;
}
.controls-row [class*="span"] + [class*="span"] {
margin-left: 0;
}
.modal {
position: fixed;
top: 20px;
right: 20px;
left: 20px;
width: auto;
margin: 0;
}
.modal.fade {
top: -100px;
}
.modal.fade.in {
top: 20px;
}
}
@media (max-width: 480px) {
.nav-collapse {
-webkit-transform: translate3d(0, 0, 0);
}
.page-header h1 small {
display: block;
line-height: 20px;
}
input[type="checkbox"],
input[type="radio"] {
border: 1px solid #ccc;
}
.form-horizontal .control-label {
float: none;
width: auto;
padding-top: 0;
text-align: left;
}
.form-horizontal .controls {
margin-left: 0;
}
.form-horizontal .control-list {
padding-top: 0;
}
.form-horizontal .form-actions {
padding-right: 10px;
padding-left: 10px;
}
.media .pull-left,
.media .pull-right {
display: block;
float: none;
margin-bottom: 10px;
}
.media-object {
margin-right: 0;
margin-left: 0;
}
.modal {
top: 10px;
right: 10px;
left: 10px;
}
.modal-header .close {
padding: 10px;
margin: -10px;
}
.carousel-caption {
position: static;
}
}
@media (max-width: 979px) {
body {
padding-top: 0;
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: static;
}
.navbar-fixed-top {
margin-bottom: 20px;
}
.navbar-fixed-bottom {
margin-top: 20px;
}
.navbar-fixed-top .navbar-inner,
.navbar-fixed-bottom .navbar-inner {
padding: 5px;
}
.navbar .container {
width: auto;
padding: 0;
}
.navbar .brand {
padding-right: 10px;
padding-left: 10px;
margin: 0 0 0 -5px;
}
.nav-collapse {
clear: both;
}
.nav-collapse .nav {
float: none;
margin: 0 0 10px;
}
.nav-collapse .nav > li {
float: none;
}
.nav-collapse .nav > li > a {
margin-bottom: 2px;
}
.nav-collapse .nav > .divider-vertical {
display: none;
}
.nav-collapse .nav .nav-header {
color: #777777;
text-shadow: none;
}
.nav-collapse .nav > li > a,
.nav-collapse .dropdown-menu a {
padding: 9px 15px;
font-weight: bold;
color: #777777;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.nav-collapse .btn {
padding: 4px 10px 4px;
font-weight: normal;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.nav-collapse .dropdown-menu li + li a {
margin-bottom: 2px;
}
.nav-collapse .nav > li > a:hover,
.nav-collapse .nav > li > a:focus,
.nav-collapse .dropdown-menu a:hover,
.nav-collapse .dropdown-menu a:focus {
background-color: #f2f2f2;
}
.navbar-inverse .nav-collapse .nav > li > a,
.navbar-inverse .nav-collapse .dropdown-menu a {
color: #999999;
}
.navbar-inverse .nav-collapse .nav > li > a:hover,
.navbar-inverse .nav-collapse .nav > li > a:focus,
.navbar-inverse .nav-collapse .dropdown-menu a:hover,
.navbar-inverse .nav-collapse .dropdown-menu a:focus {
background-color: #111111;
}
.nav-collapse.in .btn-group {
padding: 0;
margin-top: 5px;
}
.nav-collapse .dropdown-menu {
position: static;
top: auto;
left: auto;
display: none;
float: none;
max-width: none;
padding: 0;
margin: 0 15px;
background-color: transparent;
border: none;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
.nav-collapse .open > .dropdown-menu {
display: block;
}
.nav-collapse .dropdown-menu:before,
.nav-collapse .dropdown-menu:after {
display: none;
}
.nav-collapse .dropdown-menu .divider {
display: none;
}
.nav-collapse .nav > li > .dropdown-menu:before,
.nav-collapse .nav > li > .dropdown-menu:after {
display: none;
}
.nav-collapse .navbar-form,
.nav-collapse .navbar-search {
float: none;
padding: 10px 15px;
margin: 10px 0;
border-top: 1px solid #f2f2f2;
border-bottom: 1px solid #f2f2f2;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
}
.navbar-inverse .nav-collapse .navbar-form,
.navbar-inverse .nav-collapse .navbar-search {
border-top-color: #111111;
border-bottom-color: #111111;
}
.navbar .nav-collapse .nav.pull-right {
float: none;
margin-left: 0;
}
.nav-collapse,
.nav-collapse.collapse {
height: 0;
overflow: hidden;
}
.navbar .btn-navbar {
display: block;
}
.navbar-static .navbar-inner {
padding-right: 10px;
padding-left: 10px;
}
}
@media (min-width: 980px) {
.nav-collapse.collapse {
height: auto !important;
overflow: visible !important;
}
}
| {
"pile_set_name": "Github"
} |
# 前言
>文本已收录至我的GitHub仓库,欢迎Star:https://github.com/bin392328206/six-finger
> **种一棵树最好的时间是十年前,其次是现在**
>我知道很多人不玩**qq**了,但是怀旧一下,欢迎加入六脉神剑Java菜鸟学习群,群聊号码:**549684836** 鼓励大家在技术的路上写博客
## 絮叨
前面的章节
- [JVM从入门到入土之详解G1垃圾回收器](https://juejin.im/post/5e366c895188254dfd43df80)
## 回顾
上面一篇文章大家其实可以搞懂G1的动态内存管理策略,它会根据情况动态的把Regiuon分配给 新生代,Eden,Survivor,老年代和大对象,但是新生代和老年代有一个各自最大的占比,然后在新生代Eden满的时候,触发新生代垃圾回收。
新生代的垃圾回收还是采用了复制算法,只不过会考虑预设的GC停顿时间,保证垃圾回收的停顿时间不难超过设置的时间,因此会挑选一些Region来进行垃圾回收。
然后跟之前说的一样,如果一些对象在新生代熬过拉框一定次数的GC,或者触发了动态年龄判定规则,则会进入老年代
而大对象则是进入单独的Regin,不再进入老年代
所以实际上在G1中,还是会存在新生代的对象会因为各种情况进入老年代
### 什么时候G1触发新生代+老年代混合垃圾回收?
G1 有个参数 是-XX:InitiatingHeapOccupancyPercent 它的默认值是45%
意思是说 如果老年代占了 堆内存的45%的Region的时候,此时就会触发混合回收阶段 如下图

### G1垃圾回收的过程
首先会触发一个 初始标记的操作,这个过程需要 Stop the world 的,但是这个过程很快
如下图,先停止系统程序的运行,然后对各个线程栈内存中的局部变量代表GC Roots,以及方法区代表静态变量的Roots,进行扫描,标记出他们直接引用对象。

接下来就会进入到 并发标记的阶段,这个阶段会允许系统程序继续运行,同时进行GC Root追踪,如下图所示

这个并发标记阶段还是很耗时的,因为要追踪全部的存活对象
但是这个阶段是可以跟系统程序并发进行的,所以对系统程序的影响不太大
而且JVM会对并发标记阶段对象做出一些记录,比如哪个对象新建了,哪个对象失去引用了,等等
接着下一个阶段就是 最终标记阶段,这个阶段也会进入Stop the world ,系统程序是禁止运行的,但是会根据并发标记记录那些 对象修改,最终标记哪些对象存活,如下图所示

最后一个阶段 是混合回收阶段,这个阶段会计算老年代每个Region中的存活对象数量,存活对象占比,还有执行垃圾回收的预期性能和效率。
接着会停止系统程序,然后全力以赴尽快进行回收,此时会选择部分Region进行回收,因为必须让垃圾回收的停顿时间控制在我们指定的范围内。
比如说 老年代此时有1000Region都满了,但是因为设置的时间,只能停顿200ms,不那么我只能回收800个,那么就会只回收800个Region,把GC的时间控制在我们指定的范围之内,如下图

## 案例背景引入
这是一个百万级注册用户的在线教育平台,主要目标用户群体是几岁到十几岁的孩子,注册用户大概是几百万的规模,日活跃规模大概在几十万。
系统的业务流程其实也不复杂,而且我们可以排除掉一些选课,排课,浏览课程详情这些低频行为。
为啥呢?因为它不是一个电商平台,不是说每个人进去都会去浏览课程详情,
所以 一般的业务流程就是,有人进来浏览一下,考虑一段时间,然后买拉课程,所以它的高频行为是什么呢?我想了一下,应该是上课
也就是说,孩子们白天要在学校上课,一般也是晚上 8 9点的样子,是这个平台最活跃的时候,还有就是周末也是最活跃的时候,
所以晚上二三个小时的时间段,将会是平台的高峰期,而且白天几乎没有什么流量,可能90%的流量读在晚上,如下图所示

### 系统核心业务流程
接着我们来明确一下,这样的一个系统,孩子们在上课的时候主要高频的使用哪些功能呢
其实非常的简单,现在如果大家家里有孩子,平时对一些在线教育App有一定的了解的话,应该知道现在在线App都会主打互动环节
给大家举个例子,比如说给五六岁的孩子上的幼儿园英语课,大家觉得还会像以前一样吗,机械的跟读嘛
那肯定不是了,现在尤为强调的是在欢快的愉快的游戏中进行教学,让孩子们快乐的学习英语,数学之类学科的知识
所以说 在那几十万用户 晚上最高峰的时间使用系统上课的时候,尤为核心的业务流程就是大量的游戏互动环节

也就是说,这个游戏互动功能,一定会承担用户高频点击,大量的互动点击
比如在完成什么任务的时候必须点击很多的按钮,频繁的进行互动,然后系统后台需要大量的接收大量的互动请求,并记录用户互动的结果,
系统得记录下来用户完成了多少个任务,作对了几个,做错了几个。
### 系统的运行压力
现在我们开始来分析一下这个系统运行时候对内存使用的一个压力
其实核心点就是搞明白晚上二三个小时高峰期内,每秒钟会有多少请求,每个请求会连带产生多少对象,占用多少内存,每个请求处理多长时间。
首先我们来分析一下晚上高峰期内几十万用户同时在线使用平台,每秒钟会产生多少请求?
我们可以大致来估算一下,比如说晚上3小时高峰期内总共60万活跃用户,平均每个用户大概会使用1小时左右来上课,一个小时内会进行60次互动操作
那么20W活跃用户因为需要大量的互动操作,所以大致可以认为是每分钟进行1次互动操作,一小时内会进行60次互动操作
那么20万用户在1小时内会进行1200万次互动操作,平均每秒大概是3000次左右的互动操作,这个是一个很合理的数字
那么每秒要承载3000并发请求,根据经验来看 一般核心系统需要部署5台 4核8G的机器来抗住是差不多的,每台机器能抗住600请求,这个压力可以接受,一般不会导致宕机问题。
### 那么每个请求会产生多少个对象呢?
一次互动请求不会有太复杂的对象,他主要是记录一些用户互动过程的,可能会跟一些积分类的东西有关联
所以大致估算一下,一次互动请求大致会连带创建几个对象,占多大的内存,比如我们就认为是5kb吧那么一秒600请求会占用3MB左右的内存
### G1垃圾回收的默认内存布局
接着我们来看看G1垃圾回收器的默认内存布局,我们采用4核8G的机器来部署系统,然后每台机器每秒会有600个请求会占用3Mb左右的内存空间。
那么假设我们对机器上的JVM,分配4G给堆内存,其中新生代默认初始占比5%,最大占比60%,每个Java线程的栈内存为1MB,元数据区域的内存为256M,此时的JVM参数如下

-XX:G1NewSizePercent 参数是用来设置新生代初始占比的,不用设置,维持默认值5%就可以了
-XX:G1MaxNewSizePercent 参数是用来设置新生代最大占比的,也不用设置 维持默认的60%就可以了
此时堆内存共4G,那么此时会除以2048,计算每个Region的大小,此时每个Region的大小就是2MB,刚开始新生代就占5%的Region,可以认为新生代就只有100个Region,有200MB的内存空间,如下图所示。

### 设置GC停顿时间
在G1垃圾回收器中有一个至关重要的参数会影响到GC的表现,就是 -XX:MaxGCPauseMills,它的默认值是200毫秒
也就是我们每次触发GC的时候导致的系统停顿时间 Stop the world 不要超过200ms,避免系统因为GC长时间卡死。
这个参数我们可以先保持一个默认值,继续往下分析看看,不着急忙下结论
### 到底多长时间会触发新生代GC?
有一个问题,就是系统运行起来之后,会不停的在新生代的Eden区域分配对象,按照之前的推算是每秒分配3MB的对象,如下图

那什么时候Eden的区域会不够呢?
前面我们说过 -XX:G1MAXNEWSIZE参数规定了新生代最大的堆内存空间
那么难道必须得随着系统运行一直给新生代分配更多得Region,直到新生代占据了60%之后,再进行GC?
G1肯定不是这样玩的
我们假设G1回收300Region需要 200ms
那么很有可能系统运行时,G1呈现出现如下的运行效果
首先,随着系统运行,每秒创建3MB的对象,大概1分钟左右就会塞满100个Region,如下图所示

此时很可能G1会觉得 ,要是我现在就触发GC,那么回收区区200MB 只需要大概几十ms,最多就让系统停止几十ms而已,跟我的主人设定的参数200Ms还相差很远。
如果现在gc, 那么每分钟都要GC会不会太频繁了,好像没有这个必要
所以还不如给新生代先增加一些Region,然后让系统继续运行再新生代Region中分配对象好了,这样就不用过于频繁触发新生代gc了,此时如图所示

然后系统继续进行,一直到可能300个Region都占满了,此时通过计算发现回收300个Region大概需要200ms,那么可能这个时候就会触发一次新生代gc了
G1是非常灵活的,它会根据你设置的时间 给新生代不停的分配更多Region
然后到一定程度,感觉差不多了,就会触发新生代gc,保证新生代Gc的时候导致的系统停顿时间再你预设的范围内
### 新生代如何优化
其实就是优化-XX:MaxGCPauseMills参数
如果这个参数设置小了 ,那么说明每次gc的停顿时间很短,但是很频繁
如果这个参数设置大了 停顿的时间就会非常长,
所以这个参数到底如何设置,需要结合工具来测试,来达到一个合理的值
### 老年代如何优化
其实也是核ParNew +CMS 控制不必要的对象进入老年代就好了,也是-XX:MaxGCPauseMills这个参数,
大家可以想象一下 如果这个参数很大,那么经过新生代的gc后,就会导致Survivor区域放不下那么多的对象,那么这些对象就会进入老年代了
或者是因为动态年龄判断进入老年代了,所以说还是设置这个参数
## 结尾
其实也就是把G1简单的说了一下,后面还有具体的干货
> 因为博主也是一个开发萌新 我也是一边学一边写 我有个目标就是一周 二到三篇 希望能坚持个一年吧 希望各位大佬多提意见,让我多学习,一起进步。
## 日常求赞
> 好了各位,以上就是这篇文章的全部内容了,能看到这里的人呀,都是**真粉**。
> 创作不易,各位的支持和认可,就是我创作的最大动力,我们下篇文章见
>六脉神剑 | 文 【原创】如果本篇博客有任何错误,请批评指教,不胜感激 !
| {
"pile_set_name": "Github"
} |
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your need!
*/
class Version20140210225215 extends AbstractMigration
{
public function up(Schema $schema)
{
// this up() migration is autogenerated, please modify it to your needs
$this->addSql("ALTER TABLE `testpaper` CHANGE `choiceMissScore` `missScore` INT UNSIGNED NOT NULL DEFAULT '0'");
}
public function down(Schema $schema)
{
// this down() migration is autogenerated, please modify it to your needs
}
}
| {
"pile_set_name": "Github"
} |
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/routes_file.xsd">
<vType id="DEFAULT_VEHTYPE" sigma="0"/>
<container id="c1" depart="0">
<stop lane="beg_0" duration="5" startPos="40"/>
<tranship edges="beg end" speed="2" departPos="50" arrivalPos="50"/>
<stop lane="end_0" duration="5" startPos="40"/>
</container>
</routes>
| {
"pile_set_name": "Github"
} |
//
// ______ ______ ______
// /\ __ \ /\ ___\ /\ ___\
// \ \ __< \ \ __\_ \ \ __\_
// \ \_____\ \ \_____\ \ \_____\
// \/_____/ \/_____/ \/_____/
//
//
// Copyright (c) 2014-2015, Geek Zoo Studio
// http://www.bee-framework.com
//
//
// 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.
//
#if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
#import "Bee_UISearchBar.h"
#import "UIView+BeeUISignal.h"
#pragma mark -
@implementation BeeUISearchBar
@end
#endif // #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
| {
"pile_set_name": "Github"
} |
use serde::{Serialize, Deserialize};
#[derive(PartialEq, Copy, Clone, Serialize, Deserialize)]
pub struct Rect {
pub x1 : i32,
pub x2 : i32,
pub y1 : i32,
pub y2 : i32
}
impl Rect {
pub fn new(x:i32, y: i32, w:i32, h:i32) -> Rect {
Rect{x1:x, y1:y, x2:x+w, y2:y+h}
}
// Returns true if this overlaps with other
pub fn intersect(&self, other:&Rect) -> bool {
self.x1 <= other.x2 && self.x2 >= other.x1 && self.y1 <= other.y2 && self.y2 >= other.y1
}
pub fn center(&self) -> (i32, i32) {
((self.x1 + self.x2)/2, (self.y1 + self.y2)/2)
}
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (C) 2009-2012 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.fusesource.restygwt.examples.client;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.RestService;
/**
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
@Path("/rest/mapservice")
public interface MapService extends RestService {
@GET
void get(MethodCallback<MapResult> callback);
}
| {
"pile_set_name": "Github"
} |
(*
Copyright 2008-2018 Microsoft Research
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.
*)
module FStar.DM4F.Id
let id (a:Type) = unit -> M a
let return_id (a:Type) (x:a) : id a = fun () -> x
// TODO : elaborate f (x ()) to let __x = x () in f __x ?
// TODO : Not exactly sure why let x = x () in f x fails...
let bind_id (a:Type) (b:Type) (x:id a) (f:(a -> id b)) : id b =
fun () ->
let x = x () in
f x ()
total reifiable reflectable new_effect {
ID : a:Type -> Effect
with repr = id
; bind = bind_id
; return = return_id
}
// Paranoid check that dm4f didn't mess up something
[@@expect_failure]
let _ = assert False
// Checking that we can access the generated combinators
let _ = ID?.lift1
let _ = ID?.lift2
let _ = ID?.pure
let _ = ID?.app
let _ = ID?.push
let _ = ID?.wp_if_then_else
let _ = ID?.wp_close
let _ = ID?.stronger
let _ = ID?.ite_wp
let _ = ID?.wp_trivial
let _ = ID?.ctx
let _ = ID?.gctx
let _ = ID?.lift_from_pure
let _ = ID?.return_wp
let _ = ID?.return_elab
let _ = ID?.bind_wp
let _ = ID?.bind_elab
let _ = ID?.repr
let _ = ID?.post
let _ = ID?.pre
let _ = ID?.wp
| {
"pile_set_name": "Github"
} |
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
package cloudfront
import (
"github.com/aws/aws-sdk-go/private/waiter"
)
func (c *CloudFront) WaitUntilDistributionDeployed(input *GetDistributionInput) error {
waiterCfg := waiter.Config{
Operation: "GetDistribution",
Delay: 60,
MaxAttempts: 25,
Acceptors: []waiter.WaitAcceptor{
{
State: "success",
Matcher: "path",
Argument: "Status",
Expected: "Deployed",
},
},
}
w := waiter.Waiter{
Client: c,
Input: input,
Config: waiterCfg,
}
return w.Wait()
}
func (c *CloudFront) WaitUntilInvalidationCompleted(input *GetInvalidationInput) error {
waiterCfg := waiter.Config{
Operation: "GetInvalidation",
Delay: 20,
MaxAttempts: 30,
Acceptors: []waiter.WaitAcceptor{
{
State: "success",
Matcher: "path",
Argument: "Status",
Expected: "Completed",
},
},
}
w := waiter.Waiter{
Client: c,
Input: input,
Config: waiterCfg,
}
return w.Wait()
}
func (c *CloudFront) WaitUntilStreamingDistributionDeployed(input *GetStreamingDistributionInput) error {
waiterCfg := waiter.Config{
Operation: "GetStreamingDistribution",
Delay: 60,
MaxAttempts: 25,
Acceptors: []waiter.WaitAcceptor{
{
State: "success",
Matcher: "path",
Argument: "Status",
Expected: "Deployed",
},
},
}
w := waiter.Waiter{
Client: c,
Input: input,
Config: waiterCfg,
}
return w.Wait()
}
| {
"pile_set_name": "Github"
} |
[
false
/*
true
*/
] | {
"pile_set_name": "Github"
} |
.. _network-boot-server:
Setting Up a Network Boot Server
================================
.. sidebar:: Abstract
This page provides general information how to setup
a network boot server that provides all services
needed for the PXE boot protocol
To be able to deploy a system through the PXE boot protocol, you need
to set up a network boot server providing the services DHCP and tftp.
With `dnsmasq` an utility exists which allows to setup all needed
services at once:
Installing and Configuring DHCP and TFTP with dnsmasq
-----------------------------------------------------
The following instructions can only serve as an example. Depending on your
network structure, the IP addresses, ranges and domain settings needs to
be adapted to allow the DHCP server to work within your network. If you
already have a DHCP server running in your network, make sure that the
`filename` and `next-server` directives are correctly set on this server.
The following steps describe how to set up dnsmasq to work as
DHCP and TFTP server.
1. Install the `dnsmasq` package.
2. Create the file :file:`/etc/dnsmasq.conf` and insert the following content
.. code:: bash
# Don't function as a DNS server.
port=0
# Log information about DHCP transactions.
log-dhcp
# Set the root directory for files available via FTP,
# usually "/srv/tftpboot":
tftp-root=TFTP_ROOT_DIR
enable-tftp
dhcp-range=BOOT_SERVER_IP,proxy
In the next step it's required to decide for the boot method. There
is the PXE loader provided via pxelinux.0 from the syslinux package
and there is the GRUB loader provided via the grub package.
.. note:: Placeholders
Replace all placeholders (written in uppercase) with data fitting
your network setup.
2.1. insert the following content to use pxelinux.0:
.. code:: bash
# The boot filename, Server name, Server Ip Address
dhcp-boot=pxelinux.0,,BOOT_SERVER_IP
# Disable re-use of the DHCP servername and filename fields as extra
# option space. That's to avoid confusing some old or broken
# DHCP clients.
dhcp-no-override
# PXE menu. The first part is the text displayed to the user.
# The second is the timeout, in seconds.
pxe-prompt="Booting FOG Client", 1
# The known types are x86PC, PC98, IA64_EFI, Alpha, Arc_x86,
# Intel_Lean_Client, IA32_EFI, BC_EFI, Xscale_EFI and X86-64_EFI
# This option is first and will be the default if there is no input
# from the user.
pxe-service=X86PC, "Boot to FOG", pxelinux.0
pxe-service=X86-64_EFI, "Boot to FOG UEFI", ipxe
pxe-service=BC_EFI, "Boot to FOG UEFI PXE-BC", ipxe
.. note::
On boot of a network client with that configuration the default
pxelinux.0 config file is expected at
:file:`TFTP_ROOT_DIR/pxelinux.cfg/default`
2.2. insert the following content to use grub:
.. code:: bash
# The boot filename, Server name, Server Ip Address
dhcp-boot=boot/grub2/i386-pc/core.0,,BOOT_SERVER_IP
When using grub the referenced dhcp-boot grub module must be genereated.
To do this change the directory to :file:`TFTP_ROOT_DIR` and create
the :file:`setvars.conf` with the following content:
.. code:: bash
set root=(tftp)
set net_default_server=BOOT_SERVER_IP
set prefix=boot/grub2
Now call the following commands to create the grub module
.. code:: bash
$ grub2-mknetdir --net-directory=TFTP_ROOT_DIR --subdir=boot/grub2
$ grub2-mkimage -O i386-pc-pxe \
--output boot/grub2/i386-pc/core.0 \
--prefix=/boot/grub2 \
-c setvars.conf \
pxe tftp
.. note::
On boot of a network client with that configuration the grub
config file is expected at :file:`TFTP_ROOT_DIR/boot/grub2/grub.cfg`
3. Run the dnsmasq server by calling:
.. code:: bash
systemctl start dnsmasq
| {
"pile_set_name": "Github"
} |
function NetLocalGroupEnum {
<#
.SYNOPSIS
Enumerates the local groups on the local (or remote) machine.
.DESCRIPTION
This function will execute the NetLocalGroupEnum Win32API call to query
a given host for local groups.
.PARAMETER ComputerName
Specifies the hostname to query for local groups (also accepts IP addresses).
Defaults to 'localhost'.
.PARAMETER Level
Specifies the level of information to query from NetLocalGroupEnum.
Default of 1. Affects the result structure returned.
.NOTES
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: PSReflect, NetApiBufferFree (Function)
Optional Dependencies: None
(func netapi32 NetLocalGroupEnum ([Int32]) @(
[String], # _In_ LPCWSTR servername
[Int32], # _In_ DWORD level
[IntPtr].MakeByRefType(), # _Out_ LPBYTE *bufptr
[Int32], # _In_ DWORD prefmaxlen
[Int32].MakeByRefType(), # _Out_ LPDWORD entriesread
[Int32].MakeByRefType(), # _Out_ LPDWORD totalentries
[Int32].MakeByRefType() # _Inout_ PDWORD_PTR resumehandle
) -EntryPoint NetLocalGroupEnum)
.LINK
https://msdn.microsoft.com/en-us/library/windows/desktop/bb525382(v=vs.85).aspx
.EXAMPLE
#>
[CmdletBinding()]
Param(
[Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[Alias('HostName', 'dnshostname', 'name')]
[ValidateNotNullOrEmpty()]
[String[]]
$ComputerName = 'localhost',
[ValidateSet(0, 1)]
[String]
$Level = 1
)
PROCESS {
ForEach ($Computer in $ComputerName) {
$PtrInfo = [IntPtr]::Zero
$EntriesRead = 0
$TotalRead = 0
$ResumeHandle = 0
$Result = $Netapi32::NetLocalGroupEnum($Computer, $Level, [ref]$PtrInfo, -1, [ref]$EntriesRead, [ref]$TotalRead, [ref]$ResumeHandle)
# locate the offset of the initial intPtr
$Offset = $PtrInfo.ToInt64()
# work out how much to increment the pointer by finding out the size of the structure
$Increment = Switch ($Level) {
0 { $LOCALGROUP_INFO_0::GetSize() }
1 { $LOCALGROUP_INFO_1::GetSize() }
}
# 0 = success
if (($Result -eq 0) -and ($Offset -gt 0)) {
# parse all the result structures
for ($i = 0; ($i -lt $EntriesRead); $i++) {
# create a new int ptr at the given offset and cast the pointer as our result structure
$NewIntPtr = New-Object System.Intptr -ArgumentList $Offset
# grab the appropriate result structure
$Info = Switch ($Level) {
0 { $NewIntPtr -as $LOCALGROUP_INFO_0 }
1 { $NewIntPtr -as $LOCALGROUP_INFO_1 }
}
# return all the sections of the structure - have to do it this way for V2
$Object = $Info | Select-Object *
$Offset = $NewIntPtr.ToInt64()
$Offset += $Increment
$Object
}
# free up the result buffer
NetApiBufferFree -Buffer $PtrInfo
}
else {
Write-Verbose "[NetLocalGroupEnum] Error: $(([ComponentModel.Win32Exception] $Result).Message)"
}
}
}
} | {
"pile_set_name": "Github"
} |
/*
* MPC52xx PSC in SPI mode driver.
*
* Maintainer: Dragos Carp
*
* Copyright (C) 2006 TOPTICA Photonics AG.
*
* 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.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/workqueue.h>
#include <linux/completion.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <linux/fsl_devices.h>
#include <linux/slab.h>
#include <asm/mpc52xx.h>
#include <asm/mpc52xx_psc.h>
#define MCLK 20000000 /* PSC port MClk in hz */
struct mpc52xx_psc_spi {
/* fsl_spi_platform data */
void (*cs_control)(struct spi_device *spi, bool on);
u32 sysclk;
/* driver internal data */
struct mpc52xx_psc __iomem *psc;
struct mpc52xx_psc_fifo __iomem *fifo;
unsigned int irq;
u8 bits_per_word;
u8 busy;
struct workqueue_struct *workqueue;
struct work_struct work;
struct list_head queue;
spinlock_t lock;
struct completion done;
};
/* controller state */
struct mpc52xx_psc_spi_cs {
int bits_per_word;
int speed_hz;
};
/* set clock freq, clock ramp, bits per work
* if t is NULL then reset the values to the default values
*/
static int mpc52xx_psc_spi_transfer_setup(struct spi_device *spi,
struct spi_transfer *t)
{
struct mpc52xx_psc_spi_cs *cs = spi->controller_state;
cs->speed_hz = (t && t->speed_hz)
? t->speed_hz : spi->max_speed_hz;
cs->bits_per_word = (t && t->bits_per_word)
? t->bits_per_word : spi->bits_per_word;
cs->bits_per_word = ((cs->bits_per_word + 7) / 8) * 8;
return 0;
}
static void mpc52xx_psc_spi_activate_cs(struct spi_device *spi)
{
struct mpc52xx_psc_spi_cs *cs = spi->controller_state;
struct mpc52xx_psc_spi *mps = spi_master_get_devdata(spi->master);
struct mpc52xx_psc __iomem *psc = mps->psc;
u32 sicr;
u16 ccr;
sicr = in_be32(&psc->sicr);
/* Set clock phase and polarity */
if (spi->mode & SPI_CPHA)
sicr |= 0x00001000;
else
sicr &= ~0x00001000;
if (spi->mode & SPI_CPOL)
sicr |= 0x00002000;
else
sicr &= ~0x00002000;
if (spi->mode & SPI_LSB_FIRST)
sicr |= 0x10000000;
else
sicr &= ~0x10000000;
out_be32(&psc->sicr, sicr);
/* Set clock frequency and bits per word
* Because psc->ccr is defined as 16bit register instead of 32bit
* just set the lower byte of BitClkDiv
*/
ccr = in_be16((u16 __iomem *)&psc->ccr);
ccr &= 0xFF00;
if (cs->speed_hz)
ccr |= (MCLK / cs->speed_hz - 1) & 0xFF;
else /* by default SPI Clk 1MHz */
ccr |= (MCLK / 1000000 - 1) & 0xFF;
out_be16((u16 __iomem *)&psc->ccr, ccr);
mps->bits_per_word = cs->bits_per_word;
if (mps->cs_control)
mps->cs_control(spi, (spi->mode & SPI_CS_HIGH) ? 1 : 0);
}
static void mpc52xx_psc_spi_deactivate_cs(struct spi_device *spi)
{
struct mpc52xx_psc_spi *mps = spi_master_get_devdata(spi->master);
if (mps->cs_control)
mps->cs_control(spi, (spi->mode & SPI_CS_HIGH) ? 0 : 1);
}
#define MPC52xx_PSC_BUFSIZE (MPC52xx_PSC_RFNUM_MASK + 1)
/* wake up when 80% fifo full */
#define MPC52xx_PSC_RFALARM (MPC52xx_PSC_BUFSIZE * 20 / 100)
static int mpc52xx_psc_spi_transfer_rxtx(struct spi_device *spi,
struct spi_transfer *t)
{
struct mpc52xx_psc_spi *mps = spi_master_get_devdata(spi->master);
struct mpc52xx_psc __iomem *psc = mps->psc;
struct mpc52xx_psc_fifo __iomem *fifo = mps->fifo;
unsigned rb = 0; /* number of bytes receieved */
unsigned sb = 0; /* number of bytes sent */
unsigned char *rx_buf = (unsigned char *)t->rx_buf;
unsigned char *tx_buf = (unsigned char *)t->tx_buf;
unsigned rfalarm;
unsigned send_at_once = MPC52xx_PSC_BUFSIZE;
unsigned recv_at_once;
int last_block = 0;
if (!t->tx_buf && !t->rx_buf && t->len)
return -EINVAL;
/* enable transmiter/receiver */
out_8(&psc->command, MPC52xx_PSC_TX_ENABLE | MPC52xx_PSC_RX_ENABLE);
while (rb < t->len) {
if (t->len - rb > MPC52xx_PSC_BUFSIZE) {
rfalarm = MPC52xx_PSC_RFALARM;
last_block = 0;
} else {
send_at_once = t->len - sb;
rfalarm = MPC52xx_PSC_BUFSIZE - (t->len - rb);
last_block = 1;
}
dev_dbg(&spi->dev, "send %d bytes...\n", send_at_once);
for (; send_at_once; sb++, send_at_once--) {
/* set EOF flag before the last word is sent */
if (send_at_once == 1 && last_block)
out_8(&psc->ircr2, 0x01);
if (tx_buf)
out_8(&psc->mpc52xx_psc_buffer_8, tx_buf[sb]);
else
out_8(&psc->mpc52xx_psc_buffer_8, 0);
}
/* enable interrupts and wait for wake up
* if just one byte is expected the Rx FIFO genererates no
* FFULL interrupt, so activate the RxRDY interrupt
*/
out_8(&psc->command, MPC52xx_PSC_SEL_MODE_REG_1);
if (t->len - rb == 1) {
out_8(&psc->mode, 0);
} else {
out_8(&psc->mode, MPC52xx_PSC_MODE_FFULL);
out_be16(&fifo->rfalarm, rfalarm);
}
out_be16(&psc->mpc52xx_psc_imr, MPC52xx_PSC_IMR_RXRDY);
wait_for_completion(&mps->done);
recv_at_once = in_be16(&fifo->rfnum);
dev_dbg(&spi->dev, "%d bytes received\n", recv_at_once);
send_at_once = recv_at_once;
if (rx_buf) {
for (; recv_at_once; rb++, recv_at_once--)
rx_buf[rb] = in_8(&psc->mpc52xx_psc_buffer_8);
} else {
for (; recv_at_once; rb++, recv_at_once--)
in_8(&psc->mpc52xx_psc_buffer_8);
}
}
/* disable transmiter/receiver */
out_8(&psc->command, MPC52xx_PSC_TX_DISABLE | MPC52xx_PSC_RX_DISABLE);
return 0;
}
static void mpc52xx_psc_spi_work(struct work_struct *work)
{
struct mpc52xx_psc_spi *mps =
container_of(work, struct mpc52xx_psc_spi, work);
spin_lock_irq(&mps->lock);
mps->busy = 1;
while (!list_empty(&mps->queue)) {
struct spi_message *m;
struct spi_device *spi;
struct spi_transfer *t = NULL;
unsigned cs_change;
int status;
m = container_of(mps->queue.next, struct spi_message, queue);
list_del_init(&m->queue);
spin_unlock_irq(&mps->lock);
spi = m->spi;
cs_change = 1;
status = 0;
list_for_each_entry (t, &m->transfers, transfer_list) {
if (t->bits_per_word || t->speed_hz) {
status = mpc52xx_psc_spi_transfer_setup(spi, t);
if (status < 0)
break;
}
if (cs_change)
mpc52xx_psc_spi_activate_cs(spi);
cs_change = t->cs_change;
status = mpc52xx_psc_spi_transfer_rxtx(spi, t);
if (status)
break;
m->actual_length += t->len;
if (t->delay_usecs)
udelay(t->delay_usecs);
if (cs_change)
mpc52xx_psc_spi_deactivate_cs(spi);
}
m->status = status;
if (m->complete)
m->complete(m->context);
if (status || !cs_change)
mpc52xx_psc_spi_deactivate_cs(spi);
mpc52xx_psc_spi_transfer_setup(spi, NULL);
spin_lock_irq(&mps->lock);
}
mps->busy = 0;
spin_unlock_irq(&mps->lock);
}
static int mpc52xx_psc_spi_setup(struct spi_device *spi)
{
struct mpc52xx_psc_spi *mps = spi_master_get_devdata(spi->master);
struct mpc52xx_psc_spi_cs *cs = spi->controller_state;
unsigned long flags;
if (spi->bits_per_word%8)
return -EINVAL;
if (!cs) {
cs = kzalloc(sizeof *cs, GFP_KERNEL);
if (!cs)
return -ENOMEM;
spi->controller_state = cs;
}
cs->bits_per_word = spi->bits_per_word;
cs->speed_hz = spi->max_speed_hz;
spin_lock_irqsave(&mps->lock, flags);
if (!mps->busy)
mpc52xx_psc_spi_deactivate_cs(spi);
spin_unlock_irqrestore(&mps->lock, flags);
return 0;
}
static int mpc52xx_psc_spi_transfer(struct spi_device *spi,
struct spi_message *m)
{
struct mpc52xx_psc_spi *mps = spi_master_get_devdata(spi->master);
unsigned long flags;
m->actual_length = 0;
m->status = -EINPROGRESS;
spin_lock_irqsave(&mps->lock, flags);
list_add_tail(&m->queue, &mps->queue);
queue_work(mps->workqueue, &mps->work);
spin_unlock_irqrestore(&mps->lock, flags);
return 0;
}
static void mpc52xx_psc_spi_cleanup(struct spi_device *spi)
{
kfree(spi->controller_state);
}
static int mpc52xx_psc_spi_port_config(int psc_id, struct mpc52xx_psc_spi *mps)
{
struct mpc52xx_psc __iomem *psc = mps->psc;
struct mpc52xx_psc_fifo __iomem *fifo = mps->fifo;
u32 mclken_div;
int ret;
/* default sysclk is 512MHz */
mclken_div = (mps->sysclk ? mps->sysclk : 512000000) / MCLK;
ret = mpc52xx_set_psc_clkdiv(psc_id, mclken_div);
if (ret)
return ret;
/* Reset the PSC into a known state */
out_8(&psc->command, MPC52xx_PSC_RST_RX);
out_8(&psc->command, MPC52xx_PSC_RST_TX);
out_8(&psc->command, MPC52xx_PSC_TX_DISABLE | MPC52xx_PSC_RX_DISABLE);
/* Disable interrupts, interrupts are based on alarm level */
out_be16(&psc->mpc52xx_psc_imr, 0);
out_8(&psc->command, MPC52xx_PSC_SEL_MODE_REG_1);
out_8(&fifo->rfcntl, 0);
out_8(&psc->mode, MPC52xx_PSC_MODE_FFULL);
/* Configure 8bit codec mode as a SPI master and use EOF flags */
/* SICR_SIM_CODEC8|SICR_GENCLK|SICR_SPI|SICR_MSTR|SICR_USEEOF */
out_be32(&psc->sicr, 0x0180C800);
out_be16((u16 __iomem *)&psc->ccr, 0x070F); /* default SPI Clk 1MHz */
/* Set 2ms DTL delay */
out_8(&psc->ctur, 0x00);
out_8(&psc->ctlr, 0x84);
mps->bits_per_word = 8;
return 0;
}
static irqreturn_t mpc52xx_psc_spi_isr(int irq, void *dev_id)
{
struct mpc52xx_psc_spi *mps = (struct mpc52xx_psc_spi *)dev_id;
struct mpc52xx_psc __iomem *psc = mps->psc;
/* disable interrupt and wake up the work queue */
if (in_be16(&psc->mpc52xx_psc_isr) & MPC52xx_PSC_IMR_RXRDY) {
out_be16(&psc->mpc52xx_psc_imr, 0);
complete(&mps->done);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
/* bus_num is used only for the case dev->platform_data == NULL */
static int mpc52xx_psc_spi_do_probe(struct device *dev, u32 regaddr,
u32 size, unsigned int irq, s16 bus_num)
{
struct fsl_spi_platform_data *pdata = dev_get_platdata(dev);
struct mpc52xx_psc_spi *mps;
struct spi_master *master;
int ret;
master = spi_alloc_master(dev, sizeof *mps);
if (master == NULL)
return -ENOMEM;
dev_set_drvdata(dev, master);
mps = spi_master_get_devdata(master);
/* the spi->mode bits understood by this driver: */
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LSB_FIRST;
mps->irq = irq;
if (pdata == NULL) {
dev_warn(dev,
"probe called without platform data, no cs_control function will be called\n");
mps->cs_control = NULL;
mps->sysclk = 0;
master->bus_num = bus_num;
master->num_chipselect = 255;
} else {
mps->cs_control = pdata->cs_control;
mps->sysclk = pdata->sysclk;
master->bus_num = pdata->bus_num;
master->num_chipselect = pdata->max_chipselect;
}
master->setup = mpc52xx_psc_spi_setup;
master->transfer = mpc52xx_psc_spi_transfer;
master->cleanup = mpc52xx_psc_spi_cleanup;
master->dev.of_node = dev->of_node;
mps->psc = ioremap(regaddr, size);
if (!mps->psc) {
dev_err(dev, "could not ioremap I/O port range\n");
ret = -EFAULT;
goto free_master;
}
/* On the 5200, fifo regs are immediately ajacent to the psc regs */
mps->fifo = ((void __iomem *)mps->psc) + sizeof(struct mpc52xx_psc);
ret = request_irq(mps->irq, mpc52xx_psc_spi_isr, 0, "mpc52xx-psc-spi",
mps);
if (ret)
goto free_master;
ret = mpc52xx_psc_spi_port_config(master->bus_num, mps);
if (ret < 0) {
dev_err(dev, "can't configure PSC! Is it capable of SPI?\n");
goto free_irq;
}
spin_lock_init(&mps->lock);
init_completion(&mps->done);
INIT_WORK(&mps->work, mpc52xx_psc_spi_work);
INIT_LIST_HEAD(&mps->queue);
mps->workqueue = create_singlethread_workqueue(
dev_name(master->dev.parent));
if (mps->workqueue == NULL) {
ret = -EBUSY;
goto free_irq;
}
ret = spi_register_master(master);
if (ret < 0)
goto unreg_master;
return ret;
unreg_master:
destroy_workqueue(mps->workqueue);
free_irq:
free_irq(mps->irq, mps);
free_master:
if (mps->psc)
iounmap(mps->psc);
spi_master_put(master);
return ret;
}
static int mpc52xx_psc_spi_of_probe(struct platform_device *op)
{
const u32 *regaddr_p;
u64 regaddr64, size64;
s16 id = -1;
regaddr_p = of_get_address(op->dev.of_node, 0, &size64, NULL);
if (!regaddr_p) {
dev_err(&op->dev, "Invalid PSC address\n");
return -EINVAL;
}
regaddr64 = of_translate_address(op->dev.of_node, regaddr_p);
/* get PSC id (1..6, used by port_config) */
if (op->dev.platform_data == NULL) {
const u32 *psc_nump;
psc_nump = of_get_property(op->dev.of_node, "cell-index", NULL);
if (!psc_nump || *psc_nump > 5) {
dev_err(&op->dev, "Invalid cell-index property\n");
return -EINVAL;
}
id = *psc_nump + 1;
}
return mpc52xx_psc_spi_do_probe(&op->dev, (u32)regaddr64, (u32)size64,
irq_of_parse_and_map(op->dev.of_node, 0), id);
}
static int mpc52xx_psc_spi_of_remove(struct platform_device *op)
{
struct spi_master *master = spi_master_get(platform_get_drvdata(op));
struct mpc52xx_psc_spi *mps = spi_master_get_devdata(master);
flush_workqueue(mps->workqueue);
destroy_workqueue(mps->workqueue);
spi_unregister_master(master);
free_irq(mps->irq, mps);
if (mps->psc)
iounmap(mps->psc);
spi_master_put(master);
return 0;
}
static const struct of_device_id mpc52xx_psc_spi_of_match[] = {
{ .compatible = "fsl,mpc5200-psc-spi", },
{ .compatible = "mpc5200-psc-spi", }, /* old */
{}
};
MODULE_DEVICE_TABLE(of, mpc52xx_psc_spi_of_match);
static struct platform_driver mpc52xx_psc_spi_of_driver = {
.probe = mpc52xx_psc_spi_of_probe,
.remove = mpc52xx_psc_spi_of_remove,
.driver = {
.name = "mpc52xx-psc-spi",
.of_match_table = mpc52xx_psc_spi_of_match,
},
};
module_platform_driver(mpc52xx_psc_spi_of_driver);
MODULE_AUTHOR("Dragos Carp");
MODULE_DESCRIPTION("MPC52xx PSC SPI Driver");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
# MISRA Compliance
The POSIX platform implementations of transport interfaces, clock utility and retry utils conform to the [MISRA C:2012](https://www.misra.org.uk/MISRAHome/MISRAC2012/tabid/196/Default.aspx)
guidelines, with some noted exceptions. Compliance is checked with Coverity static analysis.
Deviations from the MISRA standard are listed below:
### Ignored by [Coverity Configuration](tools/coverity/misra.config)
| Deviation | Category | Justification |
| :-: | :-: | :-: |
| Directive 4.5 | Advisory | Allow names that MISRA considers ambiguous (such as LogInfo and LogError) |
| Directive 4.8 | Advisory | Allow inclusion of unused types. Header files for a specific port, which are needed by all files, may define types that are not used by a specific file. |
| Directive 4.9 | Advisory | Allow inclusion of function like macros. The `assert` macro is used throughout the library for parameter validation, and logging is done using function like macros. |
| Rule 2.3 | Advisory | Allow unused types. Library headers may define types intended for the application's use, but not used within the library files. |
| Rule 2.4 | Advisory | Allow unused tags. Some compilers warn if types are not tagged. |
| Rule 2.5 | Advisory | Allow unused macros. Library headers may define macros intended for the application's use, but are not used by a specific file. |
| Rule 3.1 | Required | Allow nested comments. C++ style `//` comments are used in example code within Doxygen documentation blocks. |
| Rule 11.5 | Advisory | Allow casts from `void *`. Fields may be passed as `void *`, requiring a cast to the correct data type before use. |
| Rule 21.1 | Required | Allow use of all macro names. For compatibility, libraries may define macros introduced in C99 for use with C90 compilers. |
| Rule 21.2 | Required | Allow use of all macro and identifier names. For compatibility, libraries may define macros introduced in C99 for use with C90 compilers. |
### Flagged by Coverity
| Deviation | Category | Justification |
| :-: | :-: | :-: |
| Rule 5.6 | Required | The header file `transport_interface.h` is present in each library repository that depends on the transport interface. This is to be able to independently compile the library repository build targets. When all the targets are analyzed together, Coverity flags the type duplication caused by multiple copies of header files in this repository as violations. However, this violation will not be flagged if each library repository build target is analyzed individually. |
| Rule 5.7 | Required | The network context struct is defined by each transport implementation; however, only one transport implementation is needed by an application at a time. If the transport implementations are analyzed one at a time by Coverity, this violation will not be flagged. |
| Rule 8.7 | Advisory | API functions are not used by the library outside of the files they are defined; however, they must be externally visible in order to be used by an application. |
### Suppressed with Coverity Comments
| Deviation | Category | Justification |
| :-: | :-: | :-: |
| Directive 4.6 | Advisory | Basic numerical types are used in platform implementations, since the POSIX platform functions and openssl functions used in the platform implementations take arguments of these types. |
| Rule 10.1 | Required | A POSIX-specific macro utility `FD_SET` is flagged for this violation. This macro utility, whose implementation is supplied by the system, is used in the transport implementation. |
| Rule 10.8 | Required | A POSIX-specific macro utility `FD_SET` is flagged for this violation. This macro utility, whose implementation is supplied by the system, is used in the transport implementation. |
| Rule 11.3 | Required | The transport implementation casts an object pointer to a pointer of a different object type. This cast is supported in POSIX, and is used to obtain IP addresses from address records. |
| Rule 11.8 | Required | An openssl API `SSL_set_tlsext_host_name`, which is used in the TLS transport implementation, internally casts a string literal to a `void *` pointer. |
| Rule 13.4 | Required | A POSIX-specific macro utility `FD_SET` is flagged for this violation. This macro utility, whose implementation is supplied by the system, is used in the transport implementation. |
| Rule 14.4 | Required | A POSIX-specific macro utility `FD_ZERO` is flagged for this violation. This macro utility, whose implementation is supplied by the system, is used in the transport implementation. |
| Rule 21.6 | Required | The Standard Library input/output functions for opening and closing files are used by the openssl transport implementation, since the openssl API `PEM_read_X509` to read PEM files takes `FILE *` as an argument. |
| {
"pile_set_name": "Github"
} |
.TH libssh2_publickey_list_fetch 3 "1 Jun 2007" "libssh2 0.15" "libssh2 manual"
.SH NAME
libssh2_publickey_list_fetch - TODO
.SH SYNOPSIS
.SH DESCRIPTION
.SH RETURN VALUE
.SH ERRORS
.SH SEE ALSO
| {
"pile_set_name": "Github"
} |
module Trustification
def self.included(recipient)
recipient.extend(ModelClassMethods)
recipient.class_eval do
include ModelInstanceMethods
end
end
module ModelClassMethods
end # class methods
module ModelInstanceMethods
end # instance methods
end
| {
"pile_set_name": "Github"
} |
/*
* QEMU Audio subsystem
*
* Copyright (c) 2003-2005 Vassili Karpov (malc)
*
* 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 "qemu/osdep.h"
#include "hw/hw.h"
#include "audio.h"
#include "monitor/monitor.h"
#include "qemu/timer.h"
#include "qapi/error.h"
#include "qapi/qobject-input-visitor.h"
#include "qapi/qapi-visit-audio.h"
#include "sysemu/sysemu.h"
#include "qemu/cutils.h"
#include "sysemu/replay.h"
#include "trace.h"
#define AUDIO_CAP "audio"
#include "audio_int.h"
/* #define DEBUG_LIVE */
/* #define DEBUG_OUT */
/* #define DEBUG_CAPTURE */
/* #define DEBUG_POLL */
#define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
/* Order of CONFIG_AUDIO_DRIVERS is import.
The 1st one is the one used by default, that is the reason
that we generate the list.
*/
const char *audio_prio_list[] = {
"spice",
CONFIG_AUDIO_DRIVERS
"none",
"wav",
NULL
};
static QLIST_HEAD(, audio_driver) audio_drivers;
static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
void audio_driver_register(audio_driver *drv)
{
QLIST_INSERT_HEAD(&audio_drivers, drv, next);
}
audio_driver *audio_driver_lookup(const char *name)
{
struct audio_driver *d;
QLIST_FOREACH(d, &audio_drivers, next) {
if (strcmp(name, d->name) == 0) {
return d;
}
}
audio_module_load_one(name);
QLIST_FOREACH(d, &audio_drivers, next) {
if (strcmp(name, d->name) == 0) {
return d;
}
}
return NULL;
}
static AudioState glob_audio_state;
const struct mixeng_volume nominal_volume = {
.mute = 0,
#ifdef FLOAT_MIXENG
.r = 1.0,
.l = 1.0,
#else
.r = 1ULL << 32,
.l = 1ULL << 32,
#endif
};
#ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
#error No its not
#else
int audio_bug (const char *funcname, int cond)
{
if (cond) {
static int shown;
AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
if (!shown) {
shown = 1;
AUD_log (NULL, "Save all your work and restart without audio\n");
AUD_log (NULL, "I am sorry\n");
}
AUD_log (NULL, "Context:\n");
#if defined AUDIO_BREAKPOINT_ON_BUG
# if defined HOST_I386
# if defined __GNUC__
__asm__ ("int3");
# elif defined _MSC_VER
_asm _emit 0xcc;
# else
abort ();
# endif
# else
abort ();
# endif
#endif
}
return cond;
}
#endif
static inline int audio_bits_to_index (int bits)
{
switch (bits) {
case 8:
return 0;
case 16:
return 1;
case 32:
return 2;
default:
audio_bug ("bits_to_index", 1);
AUD_log (NULL, "invalid bits %d\n", bits);
return 0;
}
}
void *audio_calloc (const char *funcname, int nmemb, size_t size)
{
int cond;
size_t len;
len = nmemb * size;
cond = !nmemb || !size;
cond |= nmemb < 0;
cond |= len < size;
if (audio_bug ("audio_calloc", cond)) {
AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
funcname);
AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
return NULL;
}
return g_malloc0 (len);
}
void AUD_vlog (const char *cap, const char *fmt, va_list ap)
{
if (cap) {
fprintf(stderr, "%s: ", cap);
}
vfprintf(stderr, fmt, ap);
}
void AUD_log (const char *cap, const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
AUD_vlog (cap, fmt, ap);
va_end (ap);
}
static void audio_print_settings (struct audsettings *as)
{
dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
switch (as->fmt) {
case AUDIO_FORMAT_S8:
AUD_log (NULL, "S8");
break;
case AUDIO_FORMAT_U8:
AUD_log (NULL, "U8");
break;
case AUDIO_FORMAT_S16:
AUD_log (NULL, "S16");
break;
case AUDIO_FORMAT_U16:
AUD_log (NULL, "U16");
break;
case AUDIO_FORMAT_S32:
AUD_log (NULL, "S32");
break;
case AUDIO_FORMAT_U32:
AUD_log (NULL, "U32");
break;
default:
AUD_log (NULL, "invalid(%d)", as->fmt);
break;
}
AUD_log (NULL, " endianness=");
switch (as->endianness) {
case 0:
AUD_log (NULL, "little");
break;
case 1:
AUD_log (NULL, "big");
break;
default:
AUD_log (NULL, "invalid");
break;
}
AUD_log (NULL, "\n");
}
static int audio_validate_settings (struct audsettings *as)
{
int invalid;
invalid = as->nchannels != 1 && as->nchannels != 2;
invalid |= as->endianness != 0 && as->endianness != 1;
switch (as->fmt) {
case AUDIO_FORMAT_S8:
case AUDIO_FORMAT_U8:
case AUDIO_FORMAT_S16:
case AUDIO_FORMAT_U16:
case AUDIO_FORMAT_S32:
case AUDIO_FORMAT_U32:
break;
default:
invalid = 1;
break;
}
invalid |= as->freq <= 0;
return invalid ? -1 : 0;
}
static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
{
int bits = 8, sign = 0;
switch (as->fmt) {
case AUDIO_FORMAT_S8:
sign = 1;
/* fall through */
case AUDIO_FORMAT_U8:
break;
case AUDIO_FORMAT_S16:
sign = 1;
/* fall through */
case AUDIO_FORMAT_U16:
bits = 16;
break;
case AUDIO_FORMAT_S32:
sign = 1;
/* fall through */
case AUDIO_FORMAT_U32:
bits = 32;
break;
default:
abort();
}
return info->freq == as->freq
&& info->nchannels == as->nchannels
&& info->sign == sign
&& info->bits == bits
&& info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
}
void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
{
int bits = 8, sign = 0, shift = 0;
switch (as->fmt) {
case AUDIO_FORMAT_S8:
sign = 1;
case AUDIO_FORMAT_U8:
break;
case AUDIO_FORMAT_S16:
sign = 1;
case AUDIO_FORMAT_U16:
bits = 16;
shift = 1;
break;
case AUDIO_FORMAT_S32:
sign = 1;
case AUDIO_FORMAT_U32:
bits = 32;
shift = 2;
break;
default:
abort();
}
info->freq = as->freq;
info->bits = bits;
info->sign = sign;
info->nchannels = as->nchannels;
info->shift = (as->nchannels == 2) + shift;
info->align = (1 << info->shift) - 1;
info->bytes_per_second = info->freq << info->shift;
info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
}
void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
{
if (!len) {
return;
}
if (info->sign) {
memset (buf, 0x00, len << info->shift);
}
else {
switch (info->bits) {
case 8:
memset (buf, 0x80, len << info->shift);
break;
case 16:
{
int i;
uint16_t *p = buf;
int shift = info->nchannels - 1;
short s = INT16_MAX;
if (info->swap_endianness) {
s = bswap16 (s);
}
for (i = 0; i < len << shift; i++) {
p[i] = s;
}
}
break;
case 32:
{
int i;
uint32_t *p = buf;
int shift = info->nchannels - 1;
int32_t s = INT32_MAX;
if (info->swap_endianness) {
s = bswap32 (s);
}
for (i = 0; i < len << shift; i++) {
p[i] = s;
}
}
break;
default:
AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
info->bits);
break;
}
}
}
/*
* Capture
*/
static void noop_conv (struct st_sample *dst, const void *src, int samples)
{
(void) src;
(void) dst;
(void) samples;
}
static CaptureVoiceOut *audio_pcm_capture_find_specific (
struct audsettings *as
)
{
CaptureVoiceOut *cap;
AudioState *s = &glob_audio_state;
for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
if (audio_pcm_info_eq (&cap->hw.info, as)) {
return cap;
}
}
return NULL;
}
static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
{
struct capture_callback *cb;
#ifdef DEBUG_CAPTURE
dolog ("notification %d sent\n", cmd);
#endif
for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
cb->ops.notify (cb->opaque, cmd);
}
}
static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
{
if (cap->hw.enabled != enabled) {
audcnotification_e cmd;
cap->hw.enabled = enabled;
cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
audio_notify_capture (cap, cmd);
}
}
static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
{
HWVoiceOut *hw = &cap->hw;
SWVoiceOut *sw;
int enabled = 0;
for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
if (sw->active) {
enabled = 1;
break;
}
}
audio_capture_maybe_changed (cap, enabled);
}
static void audio_detach_capture (HWVoiceOut *hw)
{
SWVoiceCap *sc = hw->cap_head.lh_first;
while (sc) {
SWVoiceCap *sc1 = sc->entries.le_next;
SWVoiceOut *sw = &sc->sw;
CaptureVoiceOut *cap = sc->cap;
int was_active = sw->active;
if (sw->rate) {
st_rate_stop (sw->rate);
sw->rate = NULL;
}
QLIST_REMOVE (sw, entries);
QLIST_REMOVE (sc, entries);
g_free (sc);
if (was_active) {
/* We have removed soft voice from the capture:
this might have changed the overall status of the capture
since this might have been the only active voice */
audio_recalc_and_notify_capture (cap);
}
sc = sc1;
}
}
static int audio_attach_capture (HWVoiceOut *hw)
{
AudioState *s = &glob_audio_state;
CaptureVoiceOut *cap;
audio_detach_capture (hw);
for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
SWVoiceCap *sc;
SWVoiceOut *sw;
HWVoiceOut *hw_cap = &cap->hw;
sc = g_malloc0(sizeof(*sc));
sc->cap = cap;
sw = &sc->sw;
sw->hw = hw_cap;
sw->info = hw->info;
sw->empty = 1;
sw->active = hw->enabled;
sw->conv = noop_conv;
sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
sw->vol = nominal_volume;
sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
if (!sw->rate) {
dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
g_free (sw);
return -1;
}
QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
#ifdef DEBUG_CAPTURE
sw->name = g_strdup_printf ("for %p %d,%d,%d",
hw, sw->info.freq, sw->info.bits,
sw->info.nchannels);
dolog ("Added %s active = %d\n", sw->name, sw->active);
#endif
if (sw->active) {
audio_capture_maybe_changed (cap, 1);
}
}
return 0;
}
/*
* Hard voice (capture)
*/
static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
{
SWVoiceIn *sw;
int m = hw->total_samples_captured;
for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
if (sw->active) {
m = audio_MIN (m, sw->total_hw_samples_acquired);
}
}
return m;
}
int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
{
int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
if (audio_bug(__func__, live < 0 || live > hw->samples)) {
dolog ("live=%d hw->samples=%d\n", live, hw->samples);
return 0;
}
return live;
}
int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf,
int live, int pending)
{
int left = hw->samples - pending;
int len = audio_MIN (left, live);
int clipped = 0;
while (len) {
struct st_sample *src = hw->mix_buf + hw->rpos;
uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift);
int samples_till_end_of_buf = hw->samples - hw->rpos;
int samples_to_clip = audio_MIN (len, samples_till_end_of_buf);
hw->clip (dst, src, samples_to_clip);
hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
len -= samples_to_clip;
clipped += samples_to_clip;
}
return clipped;
}
/*
* Soft voice (capture)
*/
static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
{
HWVoiceIn *hw = sw->hw;
int live = hw->total_samples_captured - sw->total_hw_samples_acquired;
int rpos;
if (audio_bug(__func__, live < 0 || live > hw->samples)) {
dolog ("live=%d hw->samples=%d\n", live, hw->samples);
return 0;
}
rpos = hw->wpos - live;
if (rpos >= 0) {
return rpos;
}
else {
return hw->samples + rpos;
}
}
int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
{
HWVoiceIn *hw = sw->hw;
int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
struct st_sample *src, *dst = sw->buf;
rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
live = hw->total_samples_captured - sw->total_hw_samples_acquired;
if (audio_bug(__func__, live < 0 || live > hw->samples)) {
dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);
return 0;
}
samples = size >> sw->info.shift;
if (!live) {
return 0;
}
swlim = (live * sw->ratio) >> 32;
swlim = audio_MIN (swlim, samples);
while (swlim) {
src = hw->conv_buf + rpos;
isamp = hw->wpos - rpos;
/* XXX: <= ? */
if (isamp <= 0) {
isamp = hw->samples - rpos;
}
if (!isamp) {
break;
}
osamp = swlim;
if (audio_bug(__func__, osamp < 0)) {
dolog ("osamp=%d\n", osamp);
return 0;
}
st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
swlim -= osamp;
rpos = (rpos + isamp) % hw->samples;
dst += osamp;
ret += osamp;
total += isamp;
}
if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) {
mixeng_volume (sw->buf, ret, &sw->vol);
}
sw->clip (buf, sw->buf, ret);
sw->total_hw_samples_acquired += total;
return ret << sw->info.shift;
}
/*
* Hard voice (playback)
*/
static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
{
SWVoiceOut *sw;
int m = INT_MAX;
int nb_live = 0;
for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
if (sw->active || !sw->empty) {
m = audio_MIN (m, sw->total_hw_samples_mixed);
nb_live += 1;
}
}
*nb_livep = nb_live;
return m;
}
static int audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
{
int smin;
int nb_live1;
smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
if (nb_live) {
*nb_live = nb_live1;
}
if (nb_live1) {
int live = smin;
if (audio_bug(__func__, live < 0 || live > hw->samples)) {
dolog ("live=%d hw->samples=%d\n", live, hw->samples);
return 0;
}
return live;
}
return 0;
}
/*
* Soft voice (playback)
*/
int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
{
int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
int ret = 0, pos = 0, total = 0;
if (!sw) {
return size;
}
hwsamples = sw->hw->samples;
live = sw->total_hw_samples_mixed;
if (audio_bug(__func__, live < 0 || live > hwsamples)) {
dolog ("live=%d hw->samples=%d\n", live, hwsamples);
return 0;
}
if (live == hwsamples) {
#ifdef DEBUG_OUT
dolog ("%s is full %d\n", sw->name, live);
#endif
return 0;
}
wpos = (sw->hw->rpos + live) % hwsamples;
samples = size >> sw->info.shift;
dead = hwsamples - live;
swlim = ((int64_t) dead << 32) / sw->ratio;
swlim = audio_MIN (swlim, samples);
if (swlim) {
sw->conv (sw->buf, buf, swlim);
if (!(sw->hw->ctl_caps & VOICE_VOLUME_CAP)) {
mixeng_volume (sw->buf, swlim, &sw->vol);
}
}
while (swlim) {
dead = hwsamples - live;
left = hwsamples - wpos;
blck = audio_MIN (dead, left);
if (!blck) {
break;
}
isamp = swlim;
osamp = blck;
st_rate_flow_mix (
sw->rate,
sw->buf + pos,
sw->hw->mix_buf + wpos,
&isamp,
&osamp
);
ret += isamp;
swlim -= isamp;
pos += isamp;
live += osamp;
wpos = (wpos + osamp) % hwsamples;
total += osamp;
}
sw->total_hw_samples_mixed += total;
sw->empty = sw->total_hw_samples_mixed == 0;
#ifdef DEBUG_OUT
dolog (
"%s: write size %d ret %d total sw %d\n",
SW_NAME (sw),
size >> sw->info.shift,
ret,
sw->total_hw_samples_mixed
);
#endif
return ret << sw->info.shift;
}
#ifdef DEBUG_AUDIO
static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
{
dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
cap, info->bits, info->sign, info->freq, info->nchannels);
}
#endif
#define DAC
#include "audio_template.h"
#undef DAC
#include "audio_template.h"
/*
* Timer
*/
static bool audio_timer_running;
static uint64_t audio_timer_last;
static int audio_is_timer_needed (void)
{
HWVoiceIn *hwi = NULL;
HWVoiceOut *hwo = NULL;
while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
if (!hwo->poll_mode) return 1;
}
while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
if (!hwi->poll_mode) return 1;
}
return 0;
}
static void audio_reset_timer (AudioState *s)
{
if (audio_is_timer_needed ()) {
timer_mod_anticipate_ns(s->ts,
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
if (!audio_timer_running) {
audio_timer_running = true;
audio_timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
trace_audio_timer_start(s->period_ticks / SCALE_MS);
}
} else {
timer_del(s->ts);
if (audio_timer_running) {
audio_timer_running = false;
trace_audio_timer_stop();
}
}
}
static void audio_timer (void *opaque)
{
int64_t now, diff;
AudioState *s = opaque;
now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
diff = now - audio_timer_last;
if (diff > s->period_ticks * 3 / 2) {
trace_audio_timer_delayed(diff / SCALE_MS);
}
audio_timer_last = now;
audio_run("timer");
audio_reset_timer(s);
}
/*
* Public API
*/
int AUD_write (SWVoiceOut *sw, void *buf, int size)
{
if (!sw) {
/* XXX: Consider options */
return size;
}
if (!sw->hw->enabled) {
dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
return 0;
}
return sw->hw->pcm_ops->write(sw, buf, size);
}
int AUD_read (SWVoiceIn *sw, void *buf, int size)
{
if (!sw) {
/* XXX: Consider options */
return size;
}
if (!sw->hw->enabled) {
dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
return 0;
}
return sw->hw->pcm_ops->read(sw, buf, size);
}
int AUD_get_buffer_size_out (SWVoiceOut *sw)
{
return sw->hw->samples << sw->hw->info.shift;
}
void AUD_set_active_out (SWVoiceOut *sw, int on)
{
HWVoiceOut *hw;
if (!sw) {
return;
}
hw = sw->hw;
if (sw->active != on) {
AudioState *s = &glob_audio_state;
SWVoiceOut *temp_sw;
SWVoiceCap *sc;
if (on) {
hw->pending_disable = 0;
if (!hw->enabled) {
hw->enabled = 1;
if (s->vm_running) {
hw->pcm_ops->ctl_out(hw, VOICE_ENABLE);
audio_reset_timer (s);
}
}
}
else {
if (hw->enabled) {
int nb_active = 0;
for (temp_sw = hw->sw_head.lh_first; temp_sw;
temp_sw = temp_sw->entries.le_next) {
nb_active += temp_sw->active != 0;
}
hw->pending_disable = nb_active == 1;
}
}
for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
sc->sw.active = hw->enabled;
if (hw->enabled) {
audio_capture_maybe_changed (sc->cap, 1);
}
}
sw->active = on;
}
}
void AUD_set_active_in (SWVoiceIn *sw, int on)
{
HWVoiceIn *hw;
if (!sw) {
return;
}
hw = sw->hw;
if (sw->active != on) {
AudioState *s = &glob_audio_state;
SWVoiceIn *temp_sw;
if (on) {
if (!hw->enabled) {
hw->enabled = 1;
if (s->vm_running) {
hw->pcm_ops->ctl_in(hw, VOICE_ENABLE);
audio_reset_timer (s);
}
}
sw->total_hw_samples_acquired = hw->total_samples_captured;
}
else {
if (hw->enabled) {
int nb_active = 0;
for (temp_sw = hw->sw_head.lh_first; temp_sw;
temp_sw = temp_sw->entries.le_next) {
nb_active += temp_sw->active != 0;
}
if (nb_active == 1) {
hw->enabled = 0;
hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
}
}
}
sw->active = on;
}
}
static int audio_get_avail (SWVoiceIn *sw)
{
int live;
if (!sw) {
return 0;
}
live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
return 0;
}
ldebug (
"%s: get_avail live %d ret %" PRId64 "\n",
SW_NAME (sw),
live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
);
return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
}
static int audio_get_free (SWVoiceOut *sw)
{
int live, dead;
if (!sw) {
return 0;
}
live = sw->total_hw_samples_mixed;
if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
return 0;
}
dead = sw->hw->samples - live;
#ifdef DEBUG_OUT
dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
SW_NAME (sw),
live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
#endif
return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
}
static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples)
{
int n;
if (hw->enabled) {
SWVoiceCap *sc;
for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
SWVoiceOut *sw = &sc->sw;
int rpos2 = rpos;
n = samples;
while (n) {
int till_end_of_hw = hw->samples - rpos2;
int to_write = audio_MIN (till_end_of_hw, n);
int bytes = to_write << hw->info.shift;
int written;
sw->buf = hw->mix_buf + rpos2;
written = audio_pcm_sw_write (sw, NULL, bytes);
if (written - bytes) {
dolog ("Could not mix %d bytes into a capture "
"buffer, mixed %d\n",
bytes, written);
break;
}
n -= to_write;
rpos2 = (rpos2 + to_write) % hw->samples;
}
}
}
n = audio_MIN (samples, hw->samples - rpos);
mixeng_clear (hw->mix_buf + rpos, n);
mixeng_clear (hw->mix_buf, samples - n);
}
static void audio_run_out (AudioState *s)
{
HWVoiceOut *hw = NULL;
SWVoiceOut *sw;
while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) {
int played;
int live, free, nb_live, cleanup_required, prev_rpos;
live = audio_pcm_hw_get_live_out (hw, &nb_live);
if (!nb_live) {
live = 0;
}
if (audio_bug(__func__, live < 0 || live > hw->samples)) {
dolog ("live=%d hw->samples=%d\n", live, hw->samples);
continue;
}
if (hw->pending_disable && !nb_live) {
SWVoiceCap *sc;
#ifdef DEBUG_OUT
dolog ("Disabling voice\n");
#endif
hw->enabled = 0;
hw->pending_disable = 0;
hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
sc->sw.active = 0;
audio_recalc_and_notify_capture (sc->cap);
}
continue;
}
if (!live) {
for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
if (sw->active) {
free = audio_get_free (sw);
if (free > 0) {
sw->callback.fn (sw->callback.opaque, free);
}
}
}
continue;
}
prev_rpos = hw->rpos;
played = hw->pcm_ops->run_out (hw, live);
replay_audio_out(&played);
if (audio_bug(__func__, hw->rpos >= hw->samples)) {
dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
hw->rpos, hw->samples, played);
hw->rpos = 0;
}
#ifdef DEBUG_OUT
dolog ("played=%d\n", played);
#endif
if (played) {
hw->ts_helper += played;
audio_capture_mix_and_clear (hw, prev_rpos, played);
}
cleanup_required = 0;
for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
if (!sw->active && sw->empty) {
continue;
}
if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
dolog ("played=%d sw->total_hw_samples_mixed=%d\n",
played, sw->total_hw_samples_mixed);
played = sw->total_hw_samples_mixed;
}
sw->total_hw_samples_mixed -= played;
if (!sw->total_hw_samples_mixed) {
sw->empty = 1;
cleanup_required |= !sw->active && !sw->callback.fn;
}
if (sw->active) {
free = audio_get_free (sw);
if (free > 0) {
sw->callback.fn (sw->callback.opaque, free);
}
}
}
if (cleanup_required) {
SWVoiceOut *sw1;
sw = hw->sw_head.lh_first;
while (sw) {
sw1 = sw->entries.le_next;
if (!sw->active && !sw->callback.fn) {
audio_close_out (sw);
}
sw = sw1;
}
}
}
}
static void audio_run_in (AudioState *s)
{
HWVoiceIn *hw = NULL;
while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {
SWVoiceIn *sw;
int captured = 0, min;
if (replay_mode != REPLAY_MODE_PLAY) {
captured = hw->pcm_ops->run_in(hw);
}
replay_audio_in(&captured, hw->conv_buf, &hw->wpos, hw->samples);
min = audio_pcm_hw_find_min_in (hw);
hw->total_samples_captured += captured - min;
hw->ts_helper += captured;
for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
sw->total_hw_samples_acquired -= min;
if (sw->active) {
int avail;
avail = audio_get_avail (sw);
if (avail > 0) {
sw->callback.fn (sw->callback.opaque, avail);
}
}
}
}
}
static void audio_run_capture (AudioState *s)
{
CaptureVoiceOut *cap;
for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
int live, rpos, captured;
HWVoiceOut *hw = &cap->hw;
SWVoiceOut *sw;
captured = live = audio_pcm_hw_get_live_out (hw, NULL);
rpos = hw->rpos;
while (live) {
int left = hw->samples - rpos;
int to_capture = audio_MIN (live, left);
struct st_sample *src;
struct capture_callback *cb;
src = hw->mix_buf + rpos;
hw->clip (cap->buf, src, to_capture);
mixeng_clear (src, to_capture);
for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
cb->ops.capture (cb->opaque, cap->buf,
to_capture << hw->info.shift);
}
rpos = (rpos + to_capture) % hw->samples;
live -= to_capture;
}
hw->rpos = rpos;
for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
if (!sw->active && sw->empty) {
continue;
}
if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
dolog ("captured=%d sw->total_hw_samples_mixed=%d\n",
captured, sw->total_hw_samples_mixed);
captured = sw->total_hw_samples_mixed;
}
sw->total_hw_samples_mixed -= captured;
sw->empty = sw->total_hw_samples_mixed == 0;
}
}
}
void audio_run (const char *msg)
{
AudioState *s = &glob_audio_state;
audio_run_out (s);
audio_run_in (s);
audio_run_capture (s);
#ifdef DEBUG_POLL
{
static double prevtime;
double currtime;
struct timeval tv;
if (gettimeofday (&tv, NULL)) {
perror ("audio_run: gettimeofday");
return;
}
currtime = tv.tv_sec + tv.tv_usec * 1e-6;
dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
prevtime = currtime;
}
#endif
}
static int audio_driver_init(AudioState *s, struct audio_driver *drv,
bool msg, Audiodev *dev)
{
s->drv_opaque = drv->init(dev);
if (s->drv_opaque) {
audio_init_nb_voices_out (drv);
audio_init_nb_voices_in (drv);
s->drv = drv;
return 0;
}
else {
if (msg) {
dolog("Could not init `%s' audio driver\n", drv->name);
}
return -1;
}
}
static void audio_vm_change_state_handler (void *opaque, int running,
RunState state)
{
AudioState *s = opaque;
HWVoiceOut *hwo = NULL;
HWVoiceIn *hwi = NULL;
int op = running ? VOICE_ENABLE : VOICE_DISABLE;
s->vm_running = running;
while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
hwo->pcm_ops->ctl_out(hwo, op);
}
while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
hwi->pcm_ops->ctl_in(hwi, op);
}
audio_reset_timer (s);
}
static bool is_cleaning_up;
bool audio_is_cleaning_up(void)
{
return is_cleaning_up;
}
void audio_cleanup(void)
{
AudioState *s = &glob_audio_state;
HWVoiceOut *hwo, *hwon;
HWVoiceIn *hwi, *hwin;
is_cleaning_up = true;
QLIST_FOREACH_SAFE(hwo, &glob_audio_state.hw_head_out, entries, hwon) {
SWVoiceCap *sc;
if (hwo->enabled) {
hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
}
hwo->pcm_ops->fini_out (hwo);
for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
CaptureVoiceOut *cap = sc->cap;
struct capture_callback *cb;
for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
cb->ops.destroy (cb->opaque);
}
}
QLIST_REMOVE(hwo, entries);
}
QLIST_FOREACH_SAFE(hwi, &glob_audio_state.hw_head_in, entries, hwin) {
if (hwi->enabled) {
hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
}
hwi->pcm_ops->fini_in (hwi);
QLIST_REMOVE(hwi, entries);
}
if (s->drv) {
s->drv->fini (s->drv_opaque);
s->drv = NULL;
}
if (s->dev) {
qapi_free_Audiodev(s->dev);
s->dev = NULL;
}
}
static const VMStateDescription vmstate_audio = {
.name = "audio",
.version_id = 1,
.minimum_version_id = 1,
.fields = (VMStateField[]) {
VMSTATE_END_OF_LIST()
}
};
static void audio_validate_opts(Audiodev *dev, Error **errp);
static AudiodevListEntry *audiodev_find(
AudiodevListHead *head, const char *drvname)
{
AudiodevListEntry *e;
QSIMPLEQ_FOREACH(e, head, next) {
if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
return e;
}
}
return NULL;
}
static int audio_init(Audiodev *dev)
{
size_t i;
int done = 0;
const char *drvname = NULL;
VMChangeStateEntry *e;
AudioState *s = &glob_audio_state;
struct audio_driver *driver;
/* silence gcc warning about uninitialized variable */
AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
if (s->drv) {
if (dev) {
dolog("Cannot create more than one audio backend, sorry\n");
qapi_free_Audiodev(dev);
}
return -1;
}
if (dev) {
/* -audiodev option */
drvname = AudiodevDriver_str(dev->driver);
} else {
/* legacy implicit initialization */
head = audio_handle_legacy_opts();
/*
* In case of legacy initialization, all Audiodevs in the list will have
* the same configuration (except the driver), so it does't matter which
* one we chose. We need an Audiodev to set up AudioState before we can
* init a driver. Also note that dev at this point is still in the
* list.
*/
dev = QSIMPLEQ_FIRST(&head)->dev;
audio_validate_opts(dev, &error_abort);
}
s->dev = dev;
QLIST_INIT (&s->hw_head_out);
QLIST_INIT (&s->hw_head_in);
QLIST_INIT (&s->cap_head);
atexit(audio_cleanup);
s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
if (s->nb_hw_voices_out <= 0) {
dolog ("Bogus number of playback voices %d, setting to 1\n",
s->nb_hw_voices_out);
s->nb_hw_voices_out = 1;
}
if (s->nb_hw_voices_in <= 0) {
dolog ("Bogus number of capture voices %d, setting to 0\n",
s->nb_hw_voices_in);
s->nb_hw_voices_in = 0;
}
if (drvname) {
driver = audio_driver_lookup(drvname);
if (driver) {
done = !audio_driver_init(s, driver, true, dev);
} else {
dolog ("Unknown audio driver `%s'\n", drvname);
}
} else {
for (i = 0; audio_prio_list[i]; i++) {
AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
driver = audio_driver_lookup(audio_prio_list[i]);
if (e && driver) {
s->dev = dev = e->dev;
audio_validate_opts(dev, &error_abort);
done = !audio_driver_init(s, driver, false, dev);
if (done) {
e->dev = NULL;
break;
}
}
}
}
audio_free_audiodev_list(&head);
if (!done) {
driver = audio_driver_lookup("none");
done = !audio_driver_init(s, driver, false, dev);
assert(done);
dolog("warning: Using timer based audio emulation\n");
}
if (dev->timer_period <= 0) {
s->period_ticks = 1;
} else {
s->period_ticks = dev->timer_period * SCALE_US;
}
e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
if (!e) {
dolog ("warning: Could not register change state handler\n"
"(Audio can continue looping even after stopping the VM)\n");
}
QLIST_INIT (&s->card_head);
vmstate_register (NULL, 0, &vmstate_audio, s);
return 0;
}
void audio_free_audiodev_list(AudiodevListHead *head)
{
AudiodevListEntry *e;
while ((e = QSIMPLEQ_FIRST(head))) {
QSIMPLEQ_REMOVE_HEAD(head, next);
qapi_free_Audiodev(e->dev);
g_free(e);
}
}
void AUD_register_card (const char *name, QEMUSoundCard *card)
{
audio_init(NULL);
card->name = g_strdup (name);
memset (&card->entries, 0, sizeof (card->entries));
QLIST_INSERT_HEAD (&glob_audio_state.card_head, card, entries);
}
void AUD_remove_card (QEMUSoundCard *card)
{
QLIST_REMOVE (card, entries);
g_free (card->name);
}
CaptureVoiceOut *AUD_add_capture (
struct audsettings *as,
struct audio_capture_ops *ops,
void *cb_opaque
)
{
AudioState *s = &glob_audio_state;
CaptureVoiceOut *cap;
struct capture_callback *cb;
if (audio_validate_settings (as)) {
dolog ("Invalid settings were passed when trying to add capture\n");
audio_print_settings (as);
return NULL;
}
cb = g_malloc0(sizeof(*cb));
cb->ops = *ops;
cb->opaque = cb_opaque;
cap = audio_pcm_capture_find_specific (as);
if (cap) {
QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
return cap;
}
else {
HWVoiceOut *hw;
CaptureVoiceOut *cap;
cap = g_malloc0(sizeof(*cap));
hw = &cap->hw;
QLIST_INIT (&hw->sw_head);
QLIST_INIT (&cap->cb_head);
/* XXX find a more elegant way */
hw->samples = 4096 * 4;
hw->mix_buf = g_new0(struct st_sample, hw->samples);
audio_pcm_init_info (&hw->info, as);
cap->buf = g_malloc0_n(hw->samples, 1 << hw->info.shift);
hw->clip = mixeng_clip
[hw->info.nchannels == 2]
[hw->info.sign]
[hw->info.swap_endianness]
[audio_bits_to_index (hw->info.bits)];
QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
QLIST_FOREACH(hw, &glob_audio_state.hw_head_out, entries) {
audio_attach_capture (hw);
}
return cap;
}
}
void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
{
struct capture_callback *cb;
for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
if (cb->opaque == cb_opaque) {
cb->ops.destroy (cb_opaque);
QLIST_REMOVE (cb, entries);
g_free (cb);
if (!cap->cb_head.lh_first) {
SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
while (sw) {
SWVoiceCap *sc = (SWVoiceCap *) sw;
#ifdef DEBUG_CAPTURE
dolog ("freeing %s\n", sw->name);
#endif
sw1 = sw->entries.le_next;
if (sw->rate) {
st_rate_stop (sw->rate);
sw->rate = NULL;
}
QLIST_REMOVE (sw, entries);
QLIST_REMOVE (sc, entries);
g_free (sc);
sw = sw1;
}
QLIST_REMOVE (cap, entries);
g_free (cap->hw.mix_buf);
g_free (cap->buf);
g_free (cap);
}
return;
}
}
}
void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
{
if (sw) {
HWVoiceOut *hw = sw->hw;
sw->vol.mute = mute;
sw->vol.l = nominal_volume.l * lvol / 255;
sw->vol.r = nominal_volume.r * rvol / 255;
if (hw->pcm_ops->ctl_out) {
hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw);
}
}
}
void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
{
if (sw) {
HWVoiceIn *hw = sw->hw;
sw->vol.mute = mute;
sw->vol.l = nominal_volume.l * lvol / 255;
sw->vol.r = nominal_volume.r * rvol / 255;
if (hw->pcm_ops->ctl_in) {
hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw);
}
}
}
void audio_create_pdos(Audiodev *dev)
{
switch (dev->driver) {
#define CASE(DRIVER, driver, pdo_name) \
case AUDIODEV_DRIVER_##DRIVER: \
if (!dev->u.driver.has_in) { \
dev->u.driver.in = g_malloc0( \
sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
dev->u.driver.has_in = true; \
} \
if (!dev->u.driver.has_out) { \
dev->u.driver.out = g_malloc0( \
sizeof(AudiodevAlsaPerDirectionOptions)); \
dev->u.driver.has_out = true; \
} \
break
CASE(NONE, none, );
CASE(ALSA, alsa, Alsa);
CASE(COREAUDIO, coreaudio, Coreaudio);
CASE(DSOUND, dsound, );
CASE(OSS, oss, Oss);
CASE(PA, pa, Pa);
CASE(SDL, sdl, );
CASE(SPICE, spice, );
CASE(WAV, wav, );
case AUDIODEV_DRIVER__MAX:
abort();
};
}
static void audio_validate_per_direction_opts(
AudiodevPerDirectionOptions *pdo, Error **errp)
{
if (!pdo->has_fixed_settings) {
pdo->has_fixed_settings = true;
pdo->fixed_settings = true;
}
if (!pdo->fixed_settings &&
(pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
error_setg(errp,
"You can't use frequency, channels or format with fixed-settings=off");
return;
}
if (!pdo->has_frequency) {
pdo->has_frequency = true;
pdo->frequency = 44100;
}
if (!pdo->has_channels) {
pdo->has_channels = true;
pdo->channels = 2;
}
if (!pdo->has_voices) {
pdo->has_voices = true;
pdo->voices = 1;
}
if (!pdo->has_format) {
pdo->has_format = true;
pdo->format = AUDIO_FORMAT_S16;
}
}
static void audio_validate_opts(Audiodev *dev, Error **errp)
{
Error *err = NULL;
audio_create_pdos(dev);
audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
if (err) {
error_propagate(errp, err);
return;
}
audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
if (err) {
error_propagate(errp, err);
return;
}
if (!dev->has_timer_period) {
dev->has_timer_period = true;
dev->timer_period = 10000; /* 100Hz -> 10ms */
}
}
void audio_parse_option(const char *opt)
{
AudiodevListEntry *e;
Audiodev *dev = NULL;
Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
visit_type_Audiodev(v, NULL, &dev, &error_fatal);
visit_free(v);
audio_validate_opts(dev, &error_fatal);
e = g_malloc0(sizeof(AudiodevListEntry));
e->dev = dev;
QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
}
void audio_init_audiodevs(void)
{
AudiodevListEntry *e;
QSIMPLEQ_FOREACH(e, &audiodevs, next) {
audio_init(e->dev);
}
}
audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
{
return (audsettings) {
.freq = pdo->frequency,
.nchannels = pdo->channels,
.fmt = pdo->format,
.endianness = AUDIO_HOST_ENDIANNESS,
};
}
int audioformat_bytes_per_sample(AudioFormat fmt)
{
switch (fmt) {
case AUDIO_FORMAT_U8:
case AUDIO_FORMAT_S8:
return 1;
case AUDIO_FORMAT_U16:
case AUDIO_FORMAT_S16:
return 2;
case AUDIO_FORMAT_U32:
case AUDIO_FORMAT_S32:
return 4;
case AUDIO_FORMAT__MAX:
;
}
abort();
}
/* frames = freq * usec / 1e6 */
int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
audsettings *as, int def_usecs)
{
uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
return (as->freq * usecs + 500000) / 1000000;
}
/* samples = channels * frames = channels * freq * usec / 1e6 */
int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
audsettings *as, int def_usecs)
{
return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
}
/*
* bytes = bytes_per_sample * samples =
* bytes_per_sample * channels * freq * usec / 1e6
*/
int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
audsettings *as, int def_usecs)
{
return audio_buffer_samples(pdo, as, def_usecs) *
audioformat_bytes_per_sample(as->fmt);
}
| {
"pile_set_name": "Github"
} |
#include "common.h"
#include "constants.h"
#include "filters.h"
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <tuple>
using std::chrono::duration;
using std::chrono::system_clock;
using std::tie;
int main(int argc, char* argv[]) {
// Parse command line
arguments opt = parse_args(argc, argv);
int input_size = opt.width * opt.height * sizeof(RGBPixel);
FILE *streamIn, *streamOut;
tie(streamIn, streamOut) = get_streams(opt);
float* coefficients = gaussian;
int coefficient_size = 3;
printf("Processing %d frames of %s ...\n", opt.nframes, opt.input_file);
auto start = system_clock::now();
convolve(streamIn, streamOut, coefficients, coefficient_size, opt);
float elapsed = duration<float>(system_clock::now() - start).count();
fflush(streamIn);
fflush(streamOut);
double mbps = opt.nframes * input_size / 1024. / 1024. / elapsed;
printf("\n\nProcessed %2.2f MB in %3.3fs (%3.2f MBps)\n\n",
input_size / 1024. /1024., elapsed, mbps);
return EXIT_SUCCESS;
}
| {
"pile_set_name": "Github"
} |
# Lt. brown face 1 - eyes
# 4 groups
# 1 neutral
# 2 happy
# 3 angry
# 4 wry
-s 14
14
Pe000aab.bmp [-15, -10]
Pe045aab.bmp [-17, -10]
Pe090aab.bmp [-11, -11]
Pe270aab.bmp [-4, -9]
Pe315aab.bmp [-5, -14]
Pe000abb.bmp [-15, -10]
Pe045abb.bmp [-17, -10]
Pe315abb.bmp [-5, -14]
Pe000acb.bmp [-15, -10]
Pe045acb.bmp [-17, -10]
Pe315acb.bmp [-5, -14]
Pe000adb.bmp [-15, -10]
Pe045adb.bmp [-17, -10]
Pe315adb.bmp [-5, -14]
4
8 1 5 4 0 0 0 3 2
8 6 8 4 0 0 0 3 7
8 9 11 4 0 0 0 3 10
8 12 14 4 0 0 0 3 13
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) Fuzhou Rockchip Electronics Co.Ltd
* Author:Mark Yao <mark.yao@rock-chips.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*/
#include <drm/drm.h>
#include <drm/drmP.h>
#include <drm/drm_atomic.h>
#include <drm/drm_crtc.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_flip_work.h>
#include <drm/drm_plane_helper.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/iopoll.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/pm_runtime.h>
#include <linux/component.h>
#include <linux/reset.h>
#include <linux/delay.h>
#include "rockchip_drm_drv.h"
#include "rockchip_drm_gem.h"
#include "rockchip_drm_fb.h"
#include "rockchip_drm_psr.h"
#include "rockchip_drm_vop.h"
#define __REG_SET_RELAXED(x, off, mask, shift, v, write_mask) \
vop_mask_write(x, off, mask, shift, v, write_mask, true)
#define __REG_SET_NORMAL(x, off, mask, shift, v, write_mask) \
vop_mask_write(x, off, mask, shift, v, write_mask, false)
#define REG_SET(x, base, reg, v, mode) \
__REG_SET_##mode(x, base + reg.offset, \
reg.mask, reg.shift, v, reg.write_mask)
#define REG_SET_MASK(x, base, reg, mask, v, mode) \
__REG_SET_##mode(x, base + reg.offset, \
mask, reg.shift, v, reg.write_mask)
#define VOP_WIN_SET(x, win, name, v) \
REG_SET(x, win->base, win->phy->name, v, RELAXED)
#define VOP_SCL_SET(x, win, name, v) \
REG_SET(x, win->base, win->phy->scl->name, v, RELAXED)
#define VOP_SCL_SET_EXT(x, win, name, v) \
REG_SET(x, win->base, win->phy->scl->ext->name, v, RELAXED)
#define VOP_CTRL_SET(x, name, v) \
REG_SET(x, 0, (x)->data->ctrl->name, v, NORMAL)
#define VOP_INTR_GET(vop, name) \
vop_read_reg(vop, 0, &vop->data->ctrl->name)
#define VOP_INTR_SET(vop, name, mask, v) \
REG_SET_MASK(vop, 0, vop->data->intr->name, mask, v, NORMAL)
#define VOP_INTR_SET_TYPE(vop, name, type, v) \
do { \
int i, reg = 0, mask = 0; \
for (i = 0; i < vop->data->intr->nintrs; i++) { \
if (vop->data->intr->intrs[i] & type) { \
reg |= (v) << i; \
mask |= 1 << i; \
} \
} \
VOP_INTR_SET(vop, name, mask, reg); \
} while (0)
#define VOP_INTR_GET_TYPE(vop, name, type) \
vop_get_intr_type(vop, &vop->data->intr->name, type)
#define VOP_WIN_GET(x, win, name) \
vop_read_reg(x, win->base, &win->phy->name)
#define VOP_WIN_GET_YRGBADDR(vop, win) \
vop_readl(vop, win->base + win->phy->yrgb_mst.offset)
#define to_vop(x) container_of(x, struct vop, crtc)
#define to_vop_win(x) container_of(x, struct vop_win, base)
enum vop_pending {
VOP_PENDING_FB_UNREF,
};
struct vop_win {
struct drm_plane base;
const struct vop_win_data *data;
struct vop *vop;
};
struct vop {
struct drm_crtc crtc;
struct device *dev;
struct drm_device *drm_dev;
bool is_enabled;
/* mutex vsync_ work */
struct mutex vsync_mutex;
bool vsync_work_pending;
struct completion dsp_hold_completion;
/* protected by dev->event_lock */
struct drm_pending_vblank_event *event;
struct drm_flip_work fb_unref_work;
unsigned long pending;
struct completion line_flag_completion;
const struct vop_data *data;
uint32_t *regsbak;
void __iomem *regs;
/* physical map length of vop register */
uint32_t len;
/* one time only one process allowed to config the register */
spinlock_t reg_lock;
/* lock vop irq reg */
spinlock_t irq_lock;
unsigned int irq;
/* vop AHP clk */
struct clk *hclk;
/* vop dclk */
struct clk *dclk;
/* vop share memory frequency */
struct clk *aclk;
/* vop dclk reset */
struct reset_control *dclk_rst;
struct vop_win win[];
};
static inline void vop_writel(struct vop *vop, uint32_t offset, uint32_t v)
{
writel(v, vop->regs + offset);
vop->regsbak[offset >> 2] = v;
}
static inline uint32_t vop_readl(struct vop *vop, uint32_t offset)
{
return readl(vop->regs + offset);
}
static inline uint32_t vop_read_reg(struct vop *vop, uint32_t base,
const struct vop_reg *reg)
{
return (vop_readl(vop, base + reg->offset) >> reg->shift) & reg->mask;
}
static inline void vop_mask_write(struct vop *vop, uint32_t offset,
uint32_t mask, uint32_t shift, uint32_t v,
bool write_mask, bool relaxed)
{
if (!mask)
return;
if (write_mask) {
v = ((v << shift) & 0xffff) | (mask << (shift + 16));
} else {
uint32_t cached_val = vop->regsbak[offset >> 2];
v = (cached_val & ~(mask << shift)) | ((v & mask) << shift);
vop->regsbak[offset >> 2] = v;
}
if (relaxed)
writel_relaxed(v, vop->regs + offset);
else
writel(v, vop->regs + offset);
}
static inline uint32_t vop_get_intr_type(struct vop *vop,
const struct vop_reg *reg, int type)
{
uint32_t i, ret = 0;
uint32_t regs = vop_read_reg(vop, 0, reg);
for (i = 0; i < vop->data->intr->nintrs; i++) {
if ((type & vop->data->intr->intrs[i]) && (regs & 1 << i))
ret |= vop->data->intr->intrs[i];
}
return ret;
}
static inline void vop_cfg_done(struct vop *vop)
{
VOP_CTRL_SET(vop, cfg_done, 1);
}
static bool has_rb_swapped(uint32_t format)
{
switch (format) {
case DRM_FORMAT_XBGR8888:
case DRM_FORMAT_ABGR8888:
case DRM_FORMAT_BGR888:
case DRM_FORMAT_BGR565:
return true;
default:
return false;
}
}
static enum vop_data_format vop_convert_format(uint32_t format)
{
switch (format) {
case DRM_FORMAT_XRGB8888:
case DRM_FORMAT_ARGB8888:
case DRM_FORMAT_XBGR8888:
case DRM_FORMAT_ABGR8888:
return VOP_FMT_ARGB8888;
case DRM_FORMAT_RGB888:
case DRM_FORMAT_BGR888:
return VOP_FMT_RGB888;
case DRM_FORMAT_RGB565:
case DRM_FORMAT_BGR565:
return VOP_FMT_RGB565;
case DRM_FORMAT_NV12:
return VOP_FMT_YUV420SP;
case DRM_FORMAT_NV16:
return VOP_FMT_YUV422SP;
case DRM_FORMAT_NV24:
return VOP_FMT_YUV444SP;
default:
DRM_ERROR("unsupported format[%08x]\n", format);
return -EINVAL;
}
}
static bool is_yuv_support(uint32_t format)
{
switch (format) {
case DRM_FORMAT_NV12:
case DRM_FORMAT_NV16:
case DRM_FORMAT_NV24:
return true;
default:
return false;
}
}
static bool is_alpha_support(uint32_t format)
{
switch (format) {
case DRM_FORMAT_ARGB8888:
case DRM_FORMAT_ABGR8888:
return true;
default:
return false;
}
}
static uint16_t scl_vop_cal_scale(enum scale_mode mode, uint32_t src,
uint32_t dst, bool is_horizontal,
int vsu_mode, int *vskiplines)
{
uint16_t val = 1 << SCL_FT_DEFAULT_FIXPOINT_SHIFT;
if (is_horizontal) {
if (mode == SCALE_UP)
val = GET_SCL_FT_BIC(src, dst);
else if (mode == SCALE_DOWN)
val = GET_SCL_FT_BILI_DN(src, dst);
} else {
if (mode == SCALE_UP) {
if (vsu_mode == SCALE_UP_BIL)
val = GET_SCL_FT_BILI_UP(src, dst);
else
val = GET_SCL_FT_BIC(src, dst);
} else if (mode == SCALE_DOWN) {
if (vskiplines) {
*vskiplines = scl_get_vskiplines(src, dst);
val = scl_get_bili_dn_vskip(src, dst,
*vskiplines);
} else {
val = GET_SCL_FT_BILI_DN(src, dst);
}
}
}
return val;
}
static void scl_vop_cal_scl_fac(struct vop *vop, const struct vop_win_data *win,
uint32_t src_w, uint32_t src_h, uint32_t dst_w,
uint32_t dst_h, uint32_t pixel_format)
{
uint16_t yrgb_hor_scl_mode, yrgb_ver_scl_mode;
uint16_t cbcr_hor_scl_mode = SCALE_NONE;
uint16_t cbcr_ver_scl_mode = SCALE_NONE;
int hsub = drm_format_horz_chroma_subsampling(pixel_format);
int vsub = drm_format_vert_chroma_subsampling(pixel_format);
bool is_yuv = is_yuv_support(pixel_format);
uint16_t cbcr_src_w = src_w / hsub;
uint16_t cbcr_src_h = src_h / vsub;
uint16_t vsu_mode;
uint16_t lb_mode;
uint32_t val;
int vskiplines = 0;
if (dst_w > 3840) {
DRM_DEV_ERROR(vop->dev, "Maximum dst width (3840) exceeded\n");
return;
}
if (!win->phy->scl->ext) {
VOP_SCL_SET(vop, win, scale_yrgb_x,
scl_cal_scale2(src_w, dst_w));
VOP_SCL_SET(vop, win, scale_yrgb_y,
scl_cal_scale2(src_h, dst_h));
if (is_yuv) {
VOP_SCL_SET(vop, win, scale_cbcr_x,
scl_cal_scale2(cbcr_src_w, dst_w));
VOP_SCL_SET(vop, win, scale_cbcr_y,
scl_cal_scale2(cbcr_src_h, dst_h));
}
return;
}
yrgb_hor_scl_mode = scl_get_scl_mode(src_w, dst_w);
yrgb_ver_scl_mode = scl_get_scl_mode(src_h, dst_h);
if (is_yuv) {
cbcr_hor_scl_mode = scl_get_scl_mode(cbcr_src_w, dst_w);
cbcr_ver_scl_mode = scl_get_scl_mode(cbcr_src_h, dst_h);
if (cbcr_hor_scl_mode == SCALE_DOWN)
lb_mode = scl_vop_cal_lb_mode(dst_w, true);
else
lb_mode = scl_vop_cal_lb_mode(cbcr_src_w, true);
} else {
if (yrgb_hor_scl_mode == SCALE_DOWN)
lb_mode = scl_vop_cal_lb_mode(dst_w, false);
else
lb_mode = scl_vop_cal_lb_mode(src_w, false);
}
VOP_SCL_SET_EXT(vop, win, lb_mode, lb_mode);
if (lb_mode == LB_RGB_3840X2) {
if (yrgb_ver_scl_mode != SCALE_NONE) {
DRM_DEV_ERROR(vop->dev, "not allow yrgb ver scale\n");
return;
}
if (cbcr_ver_scl_mode != SCALE_NONE) {
DRM_DEV_ERROR(vop->dev, "not allow cbcr ver scale\n");
return;
}
vsu_mode = SCALE_UP_BIL;
} else if (lb_mode == LB_RGB_2560X4) {
vsu_mode = SCALE_UP_BIL;
} else {
vsu_mode = SCALE_UP_BIC;
}
val = scl_vop_cal_scale(yrgb_hor_scl_mode, src_w, dst_w,
true, 0, NULL);
VOP_SCL_SET(vop, win, scale_yrgb_x, val);
val = scl_vop_cal_scale(yrgb_ver_scl_mode, src_h, dst_h,
false, vsu_mode, &vskiplines);
VOP_SCL_SET(vop, win, scale_yrgb_y, val);
VOP_SCL_SET_EXT(vop, win, vsd_yrgb_gt4, vskiplines == 4);
VOP_SCL_SET_EXT(vop, win, vsd_yrgb_gt2, vskiplines == 2);
VOP_SCL_SET_EXT(vop, win, yrgb_hor_scl_mode, yrgb_hor_scl_mode);
VOP_SCL_SET_EXT(vop, win, yrgb_ver_scl_mode, yrgb_ver_scl_mode);
VOP_SCL_SET_EXT(vop, win, yrgb_hsd_mode, SCALE_DOWN_BIL);
VOP_SCL_SET_EXT(vop, win, yrgb_vsd_mode, SCALE_DOWN_BIL);
VOP_SCL_SET_EXT(vop, win, yrgb_vsu_mode, vsu_mode);
if (is_yuv) {
val = scl_vop_cal_scale(cbcr_hor_scl_mode, cbcr_src_w,
dst_w, true, 0, NULL);
VOP_SCL_SET(vop, win, scale_cbcr_x, val);
val = scl_vop_cal_scale(cbcr_ver_scl_mode, cbcr_src_h,
dst_h, false, vsu_mode, &vskiplines);
VOP_SCL_SET(vop, win, scale_cbcr_y, val);
VOP_SCL_SET_EXT(vop, win, vsd_cbcr_gt4, vskiplines == 4);
VOP_SCL_SET_EXT(vop, win, vsd_cbcr_gt2, vskiplines == 2);
VOP_SCL_SET_EXT(vop, win, cbcr_hor_scl_mode, cbcr_hor_scl_mode);
VOP_SCL_SET_EXT(vop, win, cbcr_ver_scl_mode, cbcr_ver_scl_mode);
VOP_SCL_SET_EXT(vop, win, cbcr_hsd_mode, SCALE_DOWN_BIL);
VOP_SCL_SET_EXT(vop, win, cbcr_vsd_mode, SCALE_DOWN_BIL);
VOP_SCL_SET_EXT(vop, win, cbcr_vsu_mode, vsu_mode);
}
}
static void vop_dsp_hold_valid_irq_enable(struct vop *vop)
{
unsigned long flags;
if (WARN_ON(!vop->is_enabled))
return;
spin_lock_irqsave(&vop->irq_lock, flags);
VOP_INTR_SET_TYPE(vop, clear, DSP_HOLD_VALID_INTR, 1);
VOP_INTR_SET_TYPE(vop, enable, DSP_HOLD_VALID_INTR, 1);
spin_unlock_irqrestore(&vop->irq_lock, flags);
}
static void vop_dsp_hold_valid_irq_disable(struct vop *vop)
{
unsigned long flags;
if (WARN_ON(!vop->is_enabled))
return;
spin_lock_irqsave(&vop->irq_lock, flags);
VOP_INTR_SET_TYPE(vop, enable, DSP_HOLD_VALID_INTR, 0);
spin_unlock_irqrestore(&vop->irq_lock, flags);
}
/*
* (1) each frame starts at the start of the Vsync pulse which is signaled by
* the "FRAME_SYNC" interrupt.
* (2) the active data region of each frame ends at dsp_vact_end
* (3) we should program this same number (dsp_vact_end) into dsp_line_frag_num,
* to get "LINE_FLAG" interrupt at the end of the active on screen data.
*
* VOP_INTR_CTRL0.dsp_line_frag_num = VOP_DSP_VACT_ST_END.dsp_vact_end
* Interrupts
* LINE_FLAG -------------------------------+
* FRAME_SYNC ----+ |
* | |
* v v
* | Vsync | Vbp | Vactive | Vfp |
* ^ ^ ^ ^
* | | | |
* | | | |
* dsp_vs_end ------------+ | | | VOP_DSP_VTOTAL_VS_END
* dsp_vact_start --------------+ | | VOP_DSP_VACT_ST_END
* dsp_vact_end ----------------------------+ | VOP_DSP_VACT_ST_END
* dsp_total -------------------------------------+ VOP_DSP_VTOTAL_VS_END
*/
static bool vop_line_flag_irq_is_enabled(struct vop *vop)
{
uint32_t line_flag_irq;
unsigned long flags;
spin_lock_irqsave(&vop->irq_lock, flags);
line_flag_irq = VOP_INTR_GET_TYPE(vop, enable, LINE_FLAG_INTR);
spin_unlock_irqrestore(&vop->irq_lock, flags);
return !!line_flag_irq;
}
static void vop_line_flag_irq_enable(struct vop *vop, int line_num)
{
unsigned long flags;
if (WARN_ON(!vop->is_enabled))
return;
spin_lock_irqsave(&vop->irq_lock, flags);
VOP_CTRL_SET(vop, line_flag_num[0], line_num);
VOP_INTR_SET_TYPE(vop, clear, LINE_FLAG_INTR, 1);
VOP_INTR_SET_TYPE(vop, enable, LINE_FLAG_INTR, 1);
spin_unlock_irqrestore(&vop->irq_lock, flags);
}
static void vop_line_flag_irq_disable(struct vop *vop)
{
unsigned long flags;
if (WARN_ON(!vop->is_enabled))
return;
spin_lock_irqsave(&vop->irq_lock, flags);
VOP_INTR_SET_TYPE(vop, enable, LINE_FLAG_INTR, 0);
spin_unlock_irqrestore(&vop->irq_lock, flags);
}
static int vop_enable(struct drm_crtc *crtc)
{
struct vop *vop = to_vop(crtc);
int ret;
ret = pm_runtime_get_sync(vop->dev);
if (ret < 0) {
dev_err(vop->dev, "failed to get pm runtime: %d\n", ret);
goto err_put_pm_runtime;
}
ret = clk_enable(vop->hclk);
if (WARN_ON(ret < 0))
goto err_put_pm_runtime;
ret = clk_enable(vop->dclk);
if (WARN_ON(ret < 0))
goto err_disable_hclk;
ret = clk_enable(vop->aclk);
if (WARN_ON(ret < 0))
goto err_disable_dclk;
/*
* Slave iommu shares power, irq and clock with vop. It was associated
* automatically with this master device via common driver code.
* Now that we have enabled the clock we attach it to the shared drm
* mapping.
*/
ret = rockchip_drm_dma_attach_device(vop->drm_dev, vop->dev);
if (ret) {
dev_err(vop->dev, "failed to attach dma mapping, %d\n", ret);
goto err_disable_aclk;
}
memcpy(vop->regs, vop->regsbak, vop->len);
vop_cfg_done(vop);
/*
* At here, vop clock & iommu is enable, R/W vop regs would be safe.
*/
vop->is_enabled = true;
spin_lock(&vop->reg_lock);
VOP_CTRL_SET(vop, standby, 0);
spin_unlock(&vop->reg_lock);
enable_irq(vop->irq);
drm_crtc_vblank_on(crtc);
return 0;
err_disable_aclk:
clk_disable(vop->aclk);
err_disable_dclk:
clk_disable(vop->dclk);
err_disable_hclk:
clk_disable(vop->hclk);
err_put_pm_runtime:
pm_runtime_put_sync(vop->dev);
return ret;
}
static void vop_crtc_disable(struct drm_crtc *crtc)
{
struct vop *vop = to_vop(crtc);
int i;
WARN_ON(vop->event);
rockchip_drm_psr_deactivate(&vop->crtc);
/*
* We need to make sure that all windows are disabled before we
* disable that crtc. Otherwise we might try to scan from a destroyed
* buffer later.
*/
for (i = 0; i < vop->data->win_size; i++) {
struct vop_win *vop_win = &vop->win[i];
const struct vop_win_data *win = vop_win->data;
spin_lock(&vop->reg_lock);
VOP_WIN_SET(vop, win, enable, 0);
spin_unlock(&vop->reg_lock);
}
vop_cfg_done(vop);
drm_crtc_vblank_off(crtc);
/*
* Vop standby will take effect at end of current frame,
* if dsp hold valid irq happen, it means standby complete.
*
* we must wait standby complete when we want to disable aclk,
* if not, memory bus maybe dead.
*/
reinit_completion(&vop->dsp_hold_completion);
vop_dsp_hold_valid_irq_enable(vop);
spin_lock(&vop->reg_lock);
VOP_CTRL_SET(vop, standby, 1);
spin_unlock(&vop->reg_lock);
wait_for_completion(&vop->dsp_hold_completion);
vop_dsp_hold_valid_irq_disable(vop);
disable_irq(vop->irq);
vop->is_enabled = false;
/*
* vop standby complete, so iommu detach is safe.
*/
rockchip_drm_dma_detach_device(vop->drm_dev, vop->dev);
clk_disable(vop->dclk);
clk_disable(vop->aclk);
clk_disable(vop->hclk);
pm_runtime_put(vop->dev);
if (crtc->state->event && !crtc->state->active) {
spin_lock_irq(&crtc->dev->event_lock);
drm_crtc_send_vblank_event(crtc, crtc->state->event);
spin_unlock_irq(&crtc->dev->event_lock);
crtc->state->event = NULL;
}
}
static void vop_plane_destroy(struct drm_plane *plane)
{
drm_plane_cleanup(plane);
}
static int vop_plane_atomic_check(struct drm_plane *plane,
struct drm_plane_state *state)
{
struct drm_crtc *crtc = state->crtc;
struct drm_crtc_state *crtc_state;
struct drm_framebuffer *fb = state->fb;
struct vop_win *vop_win = to_vop_win(plane);
const struct vop_win_data *win = vop_win->data;
int ret;
struct drm_rect clip;
int min_scale = win->phy->scl ? FRAC_16_16(1, 8) :
DRM_PLANE_HELPER_NO_SCALING;
int max_scale = win->phy->scl ? FRAC_16_16(8, 1) :
DRM_PLANE_HELPER_NO_SCALING;
if (!crtc || !fb)
return 0;
crtc_state = drm_atomic_get_existing_crtc_state(state->state, crtc);
if (WARN_ON(!crtc_state))
return -EINVAL;
clip.x1 = 0;
clip.y1 = 0;
clip.x2 = crtc_state->adjusted_mode.hdisplay;
clip.y2 = crtc_state->adjusted_mode.vdisplay;
ret = drm_plane_helper_check_state(state, &clip,
min_scale, max_scale,
true, true);
if (ret)
return ret;
if (!state->visible)
return 0;
ret = vop_convert_format(fb->format->format);
if (ret < 0)
return ret;
/*
* Src.x1 can be odd when do clip, but yuv plane start point
* need align with 2 pixel.
*/
if (is_yuv_support(fb->format->format) && ((state->src.x1 >> 16) % 2))
return -EINVAL;
return 0;
}
static void vop_plane_atomic_disable(struct drm_plane *plane,
struct drm_plane_state *old_state)
{
struct vop_win *vop_win = to_vop_win(plane);
const struct vop_win_data *win = vop_win->data;
struct vop *vop = to_vop(old_state->crtc);
if (!old_state->crtc)
return;
spin_lock(&vop->reg_lock);
VOP_WIN_SET(vop, win, enable, 0);
spin_unlock(&vop->reg_lock);
}
static void vop_plane_atomic_update(struct drm_plane *plane,
struct drm_plane_state *old_state)
{
struct drm_plane_state *state = plane->state;
struct drm_crtc *crtc = state->crtc;
struct vop_win *vop_win = to_vop_win(plane);
const struct vop_win_data *win = vop_win->data;
struct vop *vop = to_vop(state->crtc);
struct drm_framebuffer *fb = state->fb;
unsigned int actual_w, actual_h;
unsigned int dsp_stx, dsp_sty;
uint32_t act_info, dsp_info, dsp_st;
struct drm_rect *src = &state->src;
struct drm_rect *dest = &state->dst;
struct drm_gem_object *obj, *uv_obj;
struct rockchip_gem_object *rk_obj, *rk_uv_obj;
unsigned long offset;
dma_addr_t dma_addr;
uint32_t val;
bool rb_swap;
int format;
/*
* can't update plane when vop is disabled.
*/
if (WARN_ON(!crtc))
return;
if (WARN_ON(!vop->is_enabled))
return;
if (!state->visible) {
vop_plane_atomic_disable(plane, old_state);
return;
}
obj = rockchip_fb_get_gem_obj(fb, 0);
rk_obj = to_rockchip_obj(obj);
actual_w = drm_rect_width(src) >> 16;
actual_h = drm_rect_height(src) >> 16;
act_info = (actual_h - 1) << 16 | ((actual_w - 1) & 0xffff);
dsp_info = (drm_rect_height(dest) - 1) << 16;
dsp_info |= (drm_rect_width(dest) - 1) & 0xffff;
dsp_stx = dest->x1 + crtc->mode.htotal - crtc->mode.hsync_start;
dsp_sty = dest->y1 + crtc->mode.vtotal - crtc->mode.vsync_start;
dsp_st = dsp_sty << 16 | (dsp_stx & 0xffff);
offset = (src->x1 >> 16) * fb->format->cpp[0];
offset += (src->y1 >> 16) * fb->pitches[0];
dma_addr = rk_obj->dma_addr + offset + fb->offsets[0];
format = vop_convert_format(fb->format->format);
spin_lock(&vop->reg_lock);
VOP_WIN_SET(vop, win, format, format);
VOP_WIN_SET(vop, win, yrgb_vir, fb->pitches[0] >> 2);
VOP_WIN_SET(vop, win, yrgb_mst, dma_addr);
if (is_yuv_support(fb->format->format)) {
int hsub = drm_format_horz_chroma_subsampling(fb->format->format);
int vsub = drm_format_vert_chroma_subsampling(fb->format->format);
int bpp = fb->format->cpp[1];
uv_obj = rockchip_fb_get_gem_obj(fb, 1);
rk_uv_obj = to_rockchip_obj(uv_obj);
offset = (src->x1 >> 16) * bpp / hsub;
offset += (src->y1 >> 16) * fb->pitches[1] / vsub;
dma_addr = rk_uv_obj->dma_addr + offset + fb->offsets[1];
VOP_WIN_SET(vop, win, uv_vir, fb->pitches[1] >> 2);
VOP_WIN_SET(vop, win, uv_mst, dma_addr);
}
if (win->phy->scl)
scl_vop_cal_scl_fac(vop, win, actual_w, actual_h,
drm_rect_width(dest), drm_rect_height(dest),
fb->format->format);
VOP_WIN_SET(vop, win, act_info, act_info);
VOP_WIN_SET(vop, win, dsp_info, dsp_info);
VOP_WIN_SET(vop, win, dsp_st, dsp_st);
rb_swap = has_rb_swapped(fb->format->format);
VOP_WIN_SET(vop, win, rb_swap, rb_swap);
if (is_alpha_support(fb->format->format)) {
VOP_WIN_SET(vop, win, dst_alpha_ctl,
DST_FACTOR_M0(ALPHA_SRC_INVERSE));
val = SRC_ALPHA_EN(1) | SRC_COLOR_M0(ALPHA_SRC_PRE_MUL) |
SRC_ALPHA_M0(ALPHA_STRAIGHT) |
SRC_BLEND_M0(ALPHA_PER_PIX) |
SRC_ALPHA_CAL_M0(ALPHA_NO_SATURATION) |
SRC_FACTOR_M0(ALPHA_ONE);
VOP_WIN_SET(vop, win, src_alpha_ctl, val);
} else {
VOP_WIN_SET(vop, win, src_alpha_ctl, SRC_ALPHA_EN(0));
}
VOP_WIN_SET(vop, win, enable, 1);
spin_unlock(&vop->reg_lock);
}
static const struct drm_plane_helper_funcs plane_helper_funcs = {
.atomic_check = vop_plane_atomic_check,
.atomic_update = vop_plane_atomic_update,
.atomic_disable = vop_plane_atomic_disable,
};
static const struct drm_plane_funcs vop_plane_funcs = {
.update_plane = drm_atomic_helper_update_plane,
.disable_plane = drm_atomic_helper_disable_plane,
.destroy = vop_plane_destroy,
.reset = drm_atomic_helper_plane_reset,
.atomic_duplicate_state = drm_atomic_helper_plane_duplicate_state,
.atomic_destroy_state = drm_atomic_helper_plane_destroy_state,
};
static int vop_crtc_enable_vblank(struct drm_crtc *crtc)
{
struct vop *vop = to_vop(crtc);
unsigned long flags;
if (WARN_ON(!vop->is_enabled))
return -EPERM;
spin_lock_irqsave(&vop->irq_lock, flags);
VOP_INTR_SET_TYPE(vop, clear, FS_INTR, 1);
VOP_INTR_SET_TYPE(vop, enable, FS_INTR, 1);
spin_unlock_irqrestore(&vop->irq_lock, flags);
return 0;
}
static void vop_crtc_disable_vblank(struct drm_crtc *crtc)
{
struct vop *vop = to_vop(crtc);
unsigned long flags;
if (WARN_ON(!vop->is_enabled))
return;
spin_lock_irqsave(&vop->irq_lock, flags);
VOP_INTR_SET_TYPE(vop, enable, FS_INTR, 0);
spin_unlock_irqrestore(&vop->irq_lock, flags);
}
static const struct rockchip_crtc_funcs private_crtc_funcs = {
.enable_vblank = vop_crtc_enable_vblank,
.disable_vblank = vop_crtc_disable_vblank,
};
static bool vop_crtc_mode_fixup(struct drm_crtc *crtc,
const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct vop *vop = to_vop(crtc);
adjusted_mode->clock =
clk_round_rate(vop->dclk, mode->clock * 1000) / 1000;
return true;
}
static void vop_crtc_enable(struct drm_crtc *crtc)
{
struct vop *vop = to_vop(crtc);
struct rockchip_crtc_state *s = to_rockchip_crtc_state(crtc->state);
struct drm_display_mode *adjusted_mode = &crtc->state->adjusted_mode;
u16 hsync_len = adjusted_mode->hsync_end - adjusted_mode->hsync_start;
u16 hdisplay = adjusted_mode->hdisplay;
u16 htotal = adjusted_mode->htotal;
u16 hact_st = adjusted_mode->htotal - adjusted_mode->hsync_start;
u16 hact_end = hact_st + hdisplay;
u16 vdisplay = adjusted_mode->vdisplay;
u16 vtotal = adjusted_mode->vtotal;
u16 vsync_len = adjusted_mode->vsync_end - adjusted_mode->vsync_start;
u16 vact_st = adjusted_mode->vtotal - adjusted_mode->vsync_start;
u16 vact_end = vact_st + vdisplay;
uint32_t pin_pol, val;
int ret;
WARN_ON(vop->event);
ret = vop_enable(crtc);
if (ret) {
DRM_DEV_ERROR(vop->dev, "Failed to enable vop (%d)\n", ret);
return;
}
/*
* If dclk rate is zero, mean that scanout is stop,
* we don't need wait any more.
*/
if (clk_get_rate(vop->dclk)) {
/*
* Rk3288 vop timing register is immediately, when configure
* display timing on display time, may cause tearing.
*
* Vop standby will take effect at end of current frame,
* if dsp hold valid irq happen, it means standby complete.
*
* mode set:
* standby and wait complete --> |----
* | display time
* |----
* |---> dsp hold irq
* configure display timing --> |
* standby exit |
* | new frame start.
*/
reinit_completion(&vop->dsp_hold_completion);
vop_dsp_hold_valid_irq_enable(vop);
spin_lock(&vop->reg_lock);
VOP_CTRL_SET(vop, standby, 1);
spin_unlock(&vop->reg_lock);
wait_for_completion(&vop->dsp_hold_completion);
vop_dsp_hold_valid_irq_disable(vop);
}
pin_pol = BIT(DCLK_INVERT);
pin_pol |= (adjusted_mode->flags & DRM_MODE_FLAG_NHSYNC) ?
0 : BIT(HSYNC_POSITIVE);
pin_pol |= (adjusted_mode->flags & DRM_MODE_FLAG_NVSYNC) ?
0 : BIT(VSYNC_POSITIVE);
VOP_CTRL_SET(vop, pin_pol, pin_pol);
switch (s->output_type) {
case DRM_MODE_CONNECTOR_LVDS:
VOP_CTRL_SET(vop, rgb_en, 1);
VOP_CTRL_SET(vop, rgb_pin_pol, pin_pol);
break;
case DRM_MODE_CONNECTOR_eDP:
VOP_CTRL_SET(vop, edp_pin_pol, pin_pol);
VOP_CTRL_SET(vop, edp_en, 1);
break;
case DRM_MODE_CONNECTOR_HDMIA:
VOP_CTRL_SET(vop, hdmi_pin_pol, pin_pol);
VOP_CTRL_SET(vop, hdmi_en, 1);
break;
case DRM_MODE_CONNECTOR_DSI:
VOP_CTRL_SET(vop, mipi_pin_pol, pin_pol);
VOP_CTRL_SET(vop, mipi_en, 1);
break;
case DRM_MODE_CONNECTOR_DisplayPort:
pin_pol &= ~BIT(DCLK_INVERT);
VOP_CTRL_SET(vop, dp_pin_pol, pin_pol);
VOP_CTRL_SET(vop, dp_en, 1);
break;
default:
DRM_DEV_ERROR(vop->dev, "unsupported connector_type [%d]\n",
s->output_type);
}
VOP_CTRL_SET(vop, out_mode, s->output_mode);
VOP_CTRL_SET(vop, htotal_pw, (htotal << 16) | hsync_len);
val = hact_st << 16;
val |= hact_end;
VOP_CTRL_SET(vop, hact_st_end, val);
VOP_CTRL_SET(vop, hpost_st_end, val);
VOP_CTRL_SET(vop, vtotal_pw, (vtotal << 16) | vsync_len);
val = vact_st << 16;
val |= vact_end;
VOP_CTRL_SET(vop, vact_st_end, val);
VOP_CTRL_SET(vop, vpost_st_end, val);
clk_set_rate(vop->dclk, adjusted_mode->clock * 1000);
VOP_CTRL_SET(vop, standby, 0);
rockchip_drm_psr_activate(&vop->crtc);
}
static bool vop_fs_irq_is_pending(struct vop *vop)
{
return VOP_INTR_GET_TYPE(vop, status, FS_INTR);
}
static void vop_wait_for_irq_handler(struct vop *vop)
{
bool pending;
int ret;
/*
* Spin until frame start interrupt status bit goes low, which means
* that interrupt handler was invoked and cleared it. The timeout of
* 10 msecs is really too long, but it is just a safety measure if
* something goes really wrong. The wait will only happen in the very
* unlikely case of a vblank happening exactly at the same time and
* shouldn't exceed microseconds range.
*/
ret = readx_poll_timeout_atomic(vop_fs_irq_is_pending, vop, pending,
!pending, 0, 10 * 1000);
if (ret)
DRM_DEV_ERROR(vop->dev, "VOP vblank IRQ stuck for 10 ms\n");
synchronize_irq(vop->irq);
}
static void vop_crtc_atomic_flush(struct drm_crtc *crtc,
struct drm_crtc_state *old_crtc_state)
{
struct drm_atomic_state *old_state = old_crtc_state->state;
struct drm_plane_state *old_plane_state;
struct vop *vop = to_vop(crtc);
struct drm_plane *plane;
int i;
if (WARN_ON(!vop->is_enabled))
return;
spin_lock(&vop->reg_lock);
vop_cfg_done(vop);
spin_unlock(&vop->reg_lock);
/*
* There is a (rather unlikely) possiblity that a vblank interrupt
* fired before we set the cfg_done bit. To avoid spuriously
* signalling flip completion we need to wait for it to finish.
*/
vop_wait_for_irq_handler(vop);
spin_lock_irq(&crtc->dev->event_lock);
if (crtc->state->event) {
WARN_ON(drm_crtc_vblank_get(crtc) != 0);
WARN_ON(vop->event);
vop->event = crtc->state->event;
crtc->state->event = NULL;
}
spin_unlock_irq(&crtc->dev->event_lock);
for_each_plane_in_state(old_state, plane, old_plane_state, i) {
if (!old_plane_state->fb)
continue;
if (old_plane_state->fb == plane->state->fb)
continue;
drm_framebuffer_reference(old_plane_state->fb);
drm_flip_work_queue(&vop->fb_unref_work, old_plane_state->fb);
set_bit(VOP_PENDING_FB_UNREF, &vop->pending);
WARN_ON(drm_crtc_vblank_get(crtc) != 0);
}
}
static void vop_crtc_atomic_begin(struct drm_crtc *crtc,
struct drm_crtc_state *old_crtc_state)
{
rockchip_drm_psr_flush(crtc);
}
static const struct drm_crtc_helper_funcs vop_crtc_helper_funcs = {
.enable = vop_crtc_enable,
.disable = vop_crtc_disable,
.mode_fixup = vop_crtc_mode_fixup,
.atomic_flush = vop_crtc_atomic_flush,
.atomic_begin = vop_crtc_atomic_begin,
};
static void vop_crtc_destroy(struct drm_crtc *crtc)
{
drm_crtc_cleanup(crtc);
}
static void vop_crtc_reset(struct drm_crtc *crtc)
{
if (crtc->state)
__drm_atomic_helper_crtc_destroy_state(crtc->state);
kfree(crtc->state);
crtc->state = kzalloc(sizeof(struct rockchip_crtc_state), GFP_KERNEL);
if (crtc->state)
crtc->state->crtc = crtc;
}
static struct drm_crtc_state *vop_crtc_duplicate_state(struct drm_crtc *crtc)
{
struct rockchip_crtc_state *rockchip_state;
rockchip_state = kzalloc(sizeof(*rockchip_state), GFP_KERNEL);
if (!rockchip_state)
return NULL;
__drm_atomic_helper_crtc_duplicate_state(crtc, &rockchip_state->base);
return &rockchip_state->base;
}
static void vop_crtc_destroy_state(struct drm_crtc *crtc,
struct drm_crtc_state *state)
{
struct rockchip_crtc_state *s = to_rockchip_crtc_state(state);
__drm_atomic_helper_crtc_destroy_state(&s->base);
kfree(s);
}
static const struct drm_crtc_funcs vop_crtc_funcs = {
.set_config = drm_atomic_helper_set_config,
.page_flip = drm_atomic_helper_page_flip,
.destroy = vop_crtc_destroy,
.reset = vop_crtc_reset,
.atomic_duplicate_state = vop_crtc_duplicate_state,
.atomic_destroy_state = vop_crtc_destroy_state,
};
static void vop_fb_unref_worker(struct drm_flip_work *work, void *val)
{
struct vop *vop = container_of(work, struct vop, fb_unref_work);
struct drm_framebuffer *fb = val;
drm_crtc_vblank_put(&vop->crtc);
drm_framebuffer_unreference(fb);
}
static void vop_handle_vblank(struct vop *vop)
{
struct drm_device *drm = vop->drm_dev;
struct drm_crtc *crtc = &vop->crtc;
unsigned long flags;
spin_lock_irqsave(&drm->event_lock, flags);
if (vop->event) {
drm_crtc_send_vblank_event(crtc, vop->event);
drm_crtc_vblank_put(crtc);
vop->event = NULL;
}
spin_unlock_irqrestore(&drm->event_lock, flags);
if (test_and_clear_bit(VOP_PENDING_FB_UNREF, &vop->pending))
drm_flip_work_commit(&vop->fb_unref_work, system_unbound_wq);
}
static irqreturn_t vop_isr(int irq, void *data)
{
struct vop *vop = data;
struct drm_crtc *crtc = &vop->crtc;
uint32_t active_irqs;
unsigned long flags;
int ret = IRQ_NONE;
/*
* interrupt register has interrupt status, enable and clear bits, we
* must hold irq_lock to avoid a race with enable/disable_vblank().
*/
spin_lock_irqsave(&vop->irq_lock, flags);
active_irqs = VOP_INTR_GET_TYPE(vop, status, INTR_MASK);
/* Clear all active interrupt sources */
if (active_irqs)
VOP_INTR_SET_TYPE(vop, clear, active_irqs, 1);
spin_unlock_irqrestore(&vop->irq_lock, flags);
/* This is expected for vop iommu irqs, since the irq is shared */
if (!active_irqs)
return IRQ_NONE;
if (active_irqs & DSP_HOLD_VALID_INTR) {
complete(&vop->dsp_hold_completion);
active_irqs &= ~DSP_HOLD_VALID_INTR;
ret = IRQ_HANDLED;
}
if (active_irqs & LINE_FLAG_INTR) {
complete(&vop->line_flag_completion);
active_irqs &= ~LINE_FLAG_INTR;
ret = IRQ_HANDLED;
}
if (active_irqs & FS_INTR) {
drm_crtc_handle_vblank(crtc);
vop_handle_vblank(vop);
active_irqs &= ~FS_INTR;
ret = IRQ_HANDLED;
}
/* Unhandled irqs are spurious. */
if (active_irqs)
DRM_DEV_ERROR(vop->dev, "Unknown VOP IRQs: %#02x\n",
active_irqs);
return ret;
}
static int vop_create_crtc(struct vop *vop)
{
const struct vop_data *vop_data = vop->data;
struct device *dev = vop->dev;
struct drm_device *drm_dev = vop->drm_dev;
struct drm_plane *primary = NULL, *cursor = NULL, *plane, *tmp;
struct drm_crtc *crtc = &vop->crtc;
struct device_node *port;
int ret;
int i;
/*
* Create drm_plane for primary and cursor planes first, since we need
* to pass them to drm_crtc_init_with_planes, which sets the
* "possible_crtcs" to the newly initialized crtc.
*/
for (i = 0; i < vop_data->win_size; i++) {
struct vop_win *vop_win = &vop->win[i];
const struct vop_win_data *win_data = vop_win->data;
if (win_data->type != DRM_PLANE_TYPE_PRIMARY &&
win_data->type != DRM_PLANE_TYPE_CURSOR)
continue;
ret = drm_universal_plane_init(vop->drm_dev, &vop_win->base,
0, &vop_plane_funcs,
win_data->phy->data_formats,
win_data->phy->nformats,
win_data->type, NULL);
if (ret) {
DRM_DEV_ERROR(vop->dev, "failed to init plane %d\n",
ret);
goto err_cleanup_planes;
}
plane = &vop_win->base;
drm_plane_helper_add(plane, &plane_helper_funcs);
if (plane->type == DRM_PLANE_TYPE_PRIMARY)
primary = plane;
else if (plane->type == DRM_PLANE_TYPE_CURSOR)
cursor = plane;
}
ret = drm_crtc_init_with_planes(drm_dev, crtc, primary, cursor,
&vop_crtc_funcs, NULL);
if (ret)
goto err_cleanup_planes;
drm_crtc_helper_add(crtc, &vop_crtc_helper_funcs);
/*
* Create drm_planes for overlay windows with possible_crtcs restricted
* to the newly created crtc.
*/
for (i = 0; i < vop_data->win_size; i++) {
struct vop_win *vop_win = &vop->win[i];
const struct vop_win_data *win_data = vop_win->data;
unsigned long possible_crtcs = 1 << drm_crtc_index(crtc);
if (win_data->type != DRM_PLANE_TYPE_OVERLAY)
continue;
ret = drm_universal_plane_init(vop->drm_dev, &vop_win->base,
possible_crtcs,
&vop_plane_funcs,
win_data->phy->data_formats,
win_data->phy->nformats,
win_data->type, NULL);
if (ret) {
DRM_DEV_ERROR(vop->dev, "failed to init overlay %d\n",
ret);
goto err_cleanup_crtc;
}
drm_plane_helper_add(&vop_win->base, &plane_helper_funcs);
}
port = of_get_child_by_name(dev->of_node, "port");
if (!port) {
DRM_DEV_ERROR(vop->dev, "no port node found in %s\n",
dev->of_node->full_name);
ret = -ENOENT;
goto err_cleanup_crtc;
}
drm_flip_work_init(&vop->fb_unref_work, "fb_unref",
vop_fb_unref_worker);
init_completion(&vop->dsp_hold_completion);
init_completion(&vop->line_flag_completion);
crtc->port = port;
rockchip_register_crtc_funcs(crtc, &private_crtc_funcs);
return 0;
err_cleanup_crtc:
drm_crtc_cleanup(crtc);
err_cleanup_planes:
list_for_each_entry_safe(plane, tmp, &drm_dev->mode_config.plane_list,
head)
drm_plane_cleanup(plane);
return ret;
}
static void vop_destroy_crtc(struct vop *vop)
{
struct drm_crtc *crtc = &vop->crtc;
struct drm_device *drm_dev = vop->drm_dev;
struct drm_plane *plane, *tmp;
rockchip_unregister_crtc_funcs(crtc);
of_node_put(crtc->port);
/*
* We need to cleanup the planes now. Why?
*
* The planes are "&vop->win[i].base". That means the memory is
* all part of the big "struct vop" chunk of memory. That memory
* was devm allocated and associated with this component. We need to
* free it ourselves before vop_unbind() finishes.
*/
list_for_each_entry_safe(plane, tmp, &drm_dev->mode_config.plane_list,
head)
vop_plane_destroy(plane);
/*
* Destroy CRTC after vop_plane_destroy() since vop_disable_plane()
* references the CRTC.
*/
drm_crtc_cleanup(crtc);
drm_flip_work_cleanup(&vop->fb_unref_work);
}
static int vop_initial(struct vop *vop)
{
const struct vop_data *vop_data = vop->data;
const struct vop_reg_data *init_table = vop_data->init_table;
struct reset_control *ahb_rst;
int i, ret;
vop->hclk = devm_clk_get(vop->dev, "hclk_vop");
if (IS_ERR(vop->hclk)) {
dev_err(vop->dev, "failed to get hclk source\n");
return PTR_ERR(vop->hclk);
}
vop->aclk = devm_clk_get(vop->dev, "aclk_vop");
if (IS_ERR(vop->aclk)) {
dev_err(vop->dev, "failed to get aclk source\n");
return PTR_ERR(vop->aclk);
}
vop->dclk = devm_clk_get(vop->dev, "dclk_vop");
if (IS_ERR(vop->dclk)) {
dev_err(vop->dev, "failed to get dclk source\n");
return PTR_ERR(vop->dclk);
}
ret = clk_prepare(vop->dclk);
if (ret < 0) {
dev_err(vop->dev, "failed to prepare dclk\n");
return ret;
}
/* Enable both the hclk and aclk to setup the vop */
ret = clk_prepare_enable(vop->hclk);
if (ret < 0) {
dev_err(vop->dev, "failed to prepare/enable hclk\n");
goto err_unprepare_dclk;
}
ret = clk_prepare_enable(vop->aclk);
if (ret < 0) {
dev_err(vop->dev, "failed to prepare/enable aclk\n");
goto err_disable_hclk;
}
/*
* do hclk_reset, reset all vop registers.
*/
ahb_rst = devm_reset_control_get(vop->dev, "ahb");
if (IS_ERR(ahb_rst)) {
dev_err(vop->dev, "failed to get ahb reset\n");
ret = PTR_ERR(ahb_rst);
goto err_disable_aclk;
}
reset_control_assert(ahb_rst);
usleep_range(10, 20);
reset_control_deassert(ahb_rst);
memcpy(vop->regsbak, vop->regs, vop->len);
for (i = 0; i < vop_data->table_size; i++)
vop_writel(vop, init_table[i].offset, init_table[i].value);
for (i = 0; i < vop_data->win_size; i++) {
const struct vop_win_data *win = &vop_data->win[i];
VOP_WIN_SET(vop, win, enable, 0);
}
vop_cfg_done(vop);
/*
* do dclk_reset, let all config take affect.
*/
vop->dclk_rst = devm_reset_control_get(vop->dev, "dclk");
if (IS_ERR(vop->dclk_rst)) {
dev_err(vop->dev, "failed to get dclk reset\n");
ret = PTR_ERR(vop->dclk_rst);
goto err_disable_aclk;
}
reset_control_assert(vop->dclk_rst);
usleep_range(10, 20);
reset_control_deassert(vop->dclk_rst);
clk_disable(vop->hclk);
clk_disable(vop->aclk);
vop->is_enabled = false;
return 0;
err_disable_aclk:
clk_disable_unprepare(vop->aclk);
err_disable_hclk:
clk_disable_unprepare(vop->hclk);
err_unprepare_dclk:
clk_unprepare(vop->dclk);
return ret;
}
/*
* Initialize the vop->win array elements.
*/
static void vop_win_init(struct vop *vop)
{
const struct vop_data *vop_data = vop->data;
unsigned int i;
for (i = 0; i < vop_data->win_size; i++) {
struct vop_win *vop_win = &vop->win[i];
const struct vop_win_data *win_data = &vop_data->win[i];
vop_win->data = win_data;
vop_win->vop = vop;
}
}
/**
* rockchip_drm_wait_line_flag - acqiure the give line flag event
* @crtc: CRTC to enable line flag
* @line_num: interested line number
* @mstimeout: millisecond for timeout
*
* Driver would hold here until the interested line flag interrupt have
* happened or timeout to wait.
*
* Returns:
* Zero on success, negative errno on failure.
*/
int rockchip_drm_wait_line_flag(struct drm_crtc *crtc, unsigned int line_num,
unsigned int mstimeout)
{
struct vop *vop = to_vop(crtc);
unsigned long jiffies_left;
if (!crtc || !vop->is_enabled)
return -ENODEV;
if (line_num > crtc->mode.vtotal || mstimeout <= 0)
return -EINVAL;
if (vop_line_flag_irq_is_enabled(vop))
return -EBUSY;
reinit_completion(&vop->line_flag_completion);
vop_line_flag_irq_enable(vop, line_num);
jiffies_left = wait_for_completion_timeout(&vop->line_flag_completion,
msecs_to_jiffies(mstimeout));
vop_line_flag_irq_disable(vop);
if (jiffies_left == 0) {
dev_err(vop->dev, "Timeout waiting for IRQ\n");
return -ETIMEDOUT;
}
return 0;
}
EXPORT_SYMBOL(rockchip_drm_wait_line_flag);
static int vop_bind(struct device *dev, struct device *master, void *data)
{
struct platform_device *pdev = to_platform_device(dev);
const struct vop_data *vop_data;
struct drm_device *drm_dev = data;
struct vop *vop;
struct resource *res;
size_t alloc_size;
int ret, irq;
vop_data = of_device_get_match_data(dev);
if (!vop_data)
return -ENODEV;
/* Allocate vop struct and its vop_win array */
alloc_size = sizeof(*vop) + sizeof(*vop->win) * vop_data->win_size;
vop = devm_kzalloc(dev, alloc_size, GFP_KERNEL);
if (!vop)
return -ENOMEM;
vop->dev = dev;
vop->data = vop_data;
vop->drm_dev = drm_dev;
dev_set_drvdata(dev, vop);
vop_win_init(vop);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
vop->len = resource_size(res);
vop->regs = devm_ioremap_resource(dev, res);
if (IS_ERR(vop->regs))
return PTR_ERR(vop->regs);
vop->regsbak = devm_kzalloc(dev, vop->len, GFP_KERNEL);
if (!vop->regsbak)
return -ENOMEM;
ret = vop_initial(vop);
if (ret < 0) {
dev_err(&pdev->dev, "cannot initial vop dev - err %d\n", ret);
return ret;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(dev, "cannot find irq for vop\n");
return irq;
}
vop->irq = (unsigned int)irq;
spin_lock_init(&vop->reg_lock);
spin_lock_init(&vop->irq_lock);
mutex_init(&vop->vsync_mutex);
ret = devm_request_irq(dev, vop->irq, vop_isr,
IRQF_SHARED, dev_name(dev), vop);
if (ret)
return ret;
/* IRQ is initially disabled; it gets enabled in power_on */
disable_irq(vop->irq);
ret = vop_create_crtc(vop);
if (ret)
goto err_enable_irq;
pm_runtime_enable(&pdev->dev);
return 0;
err_enable_irq:
enable_irq(vop->irq); /* To balance out the disable_irq above */
return ret;
}
static void vop_unbind(struct device *dev, struct device *master, void *data)
{
struct vop *vop = dev_get_drvdata(dev);
pm_runtime_disable(dev);
vop_destroy_crtc(vop);
}
const struct component_ops vop_component_ops = {
.bind = vop_bind,
.unbind = vop_unbind,
};
EXPORT_SYMBOL_GPL(vop_component_ops);
| {
"pile_set_name": "Github"
} |
// go run mksyscall.go -openbsd -tags openbsd,amd64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build openbsd,amd64
package unix
import (
"syscall"
"unsafe"
)
var _ syscall.Errno
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setgroups(ngid int, gid *_Gid_t) (err error) {
_, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) {
r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
wpid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socket(domain int, typ int, proto int) (fd int, err error) {
r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
_, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Shutdown(s int, how int) (err error) {
_, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
var _p0 unsafe.Pointer
if len(mib) > 0 {
_p0 = unsafe.Pointer(&mib[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimes(path string, timeval *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func futimes(fd int, timeval *[2]Timeval) (err error) {
_, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func poll(fds *PollFd, nfds int, timeout int) (n int, err error) {
r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Madvise(b []byte, behav int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlockall(flags int) (err error) {
_, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mprotect(b []byte, prot int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Msync(b []byte, flags int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlockall() (err error) {
_, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe(p *[2]_C_int) (err error) {
_, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getdents(fd int, buf []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getcwd(buf []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ioctl(fd int, req uint, arg uintptr) (err error) {
_, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Access(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chflags(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chmod(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
_, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(fd int) (nfd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup2(from int, to int) (err error) {
_, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exit(code int) {
Syscall(SYS_EXIT, uintptr(code), 0, 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchdir(fd int) (err error) {
_, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchflags(fd int, flags int) (err error) {
_, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmod(fd int, mode uint32) (err error) {
_, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchown(fd int, uid int, gid int) (err error) {
_, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Flock(fd int, how int) (err error) {
_, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fpathconf(fd int, name int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatfs(fd int, stat *Statfs_t) (err error) {
_, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fsync(fd int) (err error) {
_, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Ftruncate(fd int, length int64) (err error) {
_, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getegid() (egid int) {
r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
egid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Geteuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getgid() (gid int) {
r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgid(pid int) (pgid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgrp() (pgrp int) {
r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
pgrp = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpid() (pid int) {
r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getppid() (ppid int) {
r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0)
ppid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpriority(which int, who int) (prio int, err error) {
r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrtable() (rtable int, err error) {
r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0)
rtable = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getsid(pid int) (sid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Gettimeofday(tv *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Issetugid() (tainted bool) {
r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
tainted = bool(r0 != 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kill(pid int, signum syscall.Signal) (err error) {
_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kqueue() (fd int, err error) {
r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lchown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Link(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Listen(s int, backlog int) (err error) {
_, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lstat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifoat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Nanosleep(time *Timespec, leftover *Timespec) (err error) {
_, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pathconf(path string, name int) (val int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func read(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rename(from string, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Renameat(fromfd int, from string, tofd int, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Revoke(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rmdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0)
newoffset = int64(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
_, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setegid(egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seteuid(euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setgid(gid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setlogin(name string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpgid(pid int, pgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpriority(which int, who int, prio int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setregid(rgid int, egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setreuid(ruid int, euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setresgid(rgid int, egid int, sgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setresuid(ruid int, euid int, suid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrtable(rtable int) (err error) {
_, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setsid() (pid int, err error) {
r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0)
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Settimeofday(tp *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setuid(uid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Stat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Statfs(path string, stat *Statfs_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlink(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(oldpath)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(newpath)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Sync() (err error) {
_, _, e1 := Syscall(SYS_SYNC, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Truncate(path string, length int64) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Umask(newmask int) (oldmask int) {
r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
oldmask = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlink(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlinkat(dirfd int, path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unmount(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func write(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0)
ret = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func munmap(addr uintptr, length uintptr) (err error) {
_, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
| {
"pile_set_name": "Github"
} |
package com.onboard.frontend.websocket;
import java.util.Collection;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.onboard.frontend.model.User;
import com.onboard.frontend.service.web.SessionService;
/**
* Echo messages by implementing a Spring {@link WebSocketHandler} abstraction.
*/
@Service
public class WebsocketHandler extends TextWebSocketHandler {
private static Logger logger = LoggerFactory.getLogger(WebsocketHandler.class);
private final Multimap<String, WebSocketSession> userPagesMap;
@Autowired
private SessionService sessionService;
public WebsocketHandler() {
userPagesMap = ArrayListMultimap.create();
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
logger.info("Opened new session in instance " + this);
User user = sessionService.getCurrentUser();
if (user != null) {
userPagesMap.put(user.getEmail(), session);
}
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.info(message.toString());
// session.sendMessage(new TextMessage(echoMessage));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
session.close(CloseStatus.SERVER_ERROR);
}
public void sendMessage(String userEmail, String message) {
Multimap<String, WebSocketSession> syncMap = Multimaps.synchronizedMultimap(userPagesMap);
Collection<WebSocketSession> mis = syncMap.get(userEmail);
synchronized (syncMap) {
if (mis != null) {
Iterator<WebSocketSession> it = mis.iterator();
while (it.hasNext()) {
WebSocketSession session = it.next();
try {
session.sendMessage(new TextMessage(message));
} catch (Exception e) {
logger.info("The WebSocket connection has been closed: " + session.toString());
}
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
mouse.shortcut.label=\u70b9\u51fb\u8fd9\u91cc\u8f93\u5165\u9f20\u6807\u5feb\u6377\u952e
prefix.key.pressed.message=\u6309\u4e0b\u524d\u7f00\u952e\u3002
action.column.name=\u64cd\u4f5c
shortcuts.column.name=\u5feb\u6377\u952e
main.menu.action.title=\u4e3b\u83dc\u5355
main.toolbar.title=\u4e3b\u5de5\u5177\u680f
editor.popup.menu.title=\u7f16\u8f91\u7a97\u53e3\u5f39\u51fa\u83dc\u5355
editor.tab.popup.menu.title=\u7f16\u8f91\u5668\u9009\u9879\u5361\u5f39\u51fa\u83dc\u5355
favorites.popup.title=\u6536\u85cf\u89c6\u56fe\u5f39\u51fa\u83dc\u5355
project.view.popup.menu.title=\u9879\u76ee\u89c6\u56fe\u5f39\u51fa\u83dc\u5355
commender.view.popup.menu.title=\u547d\u4ee4\u89c6\u56fe\u5f39\u51fa\u83dc\u5355
j2ee.view.popup.menu.title=Java EE \u89c6\u56fe\u5f39\u51fa\u83dc\u5355
all.actions.group.title=\u6240\u6709\u64cd\u4f5c
plugins.group.title=\u63d2\u4ef6
version.control.group.title=\u7248\u672c\u63a7\u5236\u7cfb\u7edf
debugger.actions.group.title=\u8c03\u8bd5\u5668\u64cd\u4f5c
editor.actions.group.title=\u7f16\u8f91\u5668\u64cd\u4f5c
ant.targets.group.title=Ant \u76ee\u6807
macros.group.title=\u5b8f
quick.lists.group.title=\u5feb\u901f\u5217\u8868
other.group.title=\u5176\u4ed6
no.quick.lists=\u6ca1\u6709\u5feb\u901f\u5217\u8868
edit.quick.list.dialog.title=\u7f16\u8f91\u5feb\u901f\u5217\u8868
keyboard.shortcut.dialog.title=\u952e\u76d8\u5feb\u6377\u952e
enable.second.keystroke.check.box=\u542f\u7528:
first.stroke.panel.title=\u7b2c\u4e00\u6b21\u6309\u4e0b\u952e\u76d8
second.stroke.panel.title=\u7b2c\u4e8c\u6b21\u6309\u4e0b\u952e\u76d8
shortcut.preview.ide.border.factory.title=\u5feb\u6377\u952e\u9884\u89c8
conflicts.ide.border.factory.title=\u51b2\u7a81
action.description.ide.border.factory.title=\u64cd\u4f5c\u8bf4\u660e
quick.lists.ide.border.factory.title=\u5feb\u901f\u5217\u8868
no.conflict.info.message=\u6ca1\u6709\u51b2\u7a81
assigned.to.info.message=\u5206\u914d\u5230 {0}
keymap.display.name=\u5feb\u6377\u952e
keymap.parent.display.name=\u4e0d\u53ef\u89c1\u7684\u5feb\u6377\u952e\u7ec4\u7236\u9879
based.on.keymap.label=\u57fa\u4e8e {0} \u5feb\u6377\u952e
shortcuts.keymap.label=\u5feb\u6377\u952e(&U)
shortcuts.keymap.no.shortcuts=\u6ca1\u6709\u5feb\u6377\u952e
add.keymap.label=\u6dfb\u52a0(&D)
remove.keymap.label=\u79fb\u9664(&V)
unnamed.list.display.name=unnamed
prefer.key.position=\u5728 national \u5e03\u5c40\u4e0a\u952e\u4f4d\u4f18\u5148\u4e8e\u952e\u5b57\u7b26
disable.mnemonic.in.menu.check.box=\u5728\u83dc\u5355\u4e2d\u7981\u7528\u52a9\u8bb0\u7b26(&M)
add.keyboard.shortcut.button=\u6dfb\u52a0\u952e\u76d8\u5feb\u6377\u952e...(&K)
add.mouse.shortcut.button=\u6dfb\u52a0\u9f20\u6807\u5feb\u6377\u952e...(&M)
remove.shortcut.button=\u79fb\u9664(&R)
conflict.shortcut.dialog.message=\u5feb\u6377\u952e\u5df2\u7ecf\u5206\u914d\u7ed9\u5176\u4ed6\u64cd\u4f5c\u3002\u8981\u79fb\u9664\u5176\u4ed6\u7684\u5206\u914d\u5417\uff1f
conflict.shortcut.dialog.title=\u8b66\u544a
conflict.shortcut.dialog.remove.button=\u79fb\u9664
conflict.shortcut.dialog.leave.button=\u79bb\u5f00
conflict.shortcut.dialog.cancel.button=\u53d6\u6d88
editor.shortcut=\u7f16\u8f91 {0}
mouse.shortcut.dialog.title=\u9f20\u6807\u5feb\u6377\u952e
mouse.shortcut.dialog.single.click.radio=\u5355\u51fb
mouse.shortcut.dialog.double.click.radio=\u53cc\u51fb
mouse.shortcut.dialog.click.count.border=\u70b9\u51fb\u8ba1\u6570
mouse.shortcut.dialog.click.pad.border=\u70b9\u51fb Pad
mouse.shortcut.dialog.shortcut.preview.border=\u5feb\u6377\u952e\u9884\u89c8
mouse.shortcut.dialog.conflicts.border=\u51b2\u7a81
mouse.shortcut.dialog.no.conflicts.area=\u6ca1\u6709\u51b2\u7a81
mouse.shortcut.dialog.assigned.to.area=\u5206\u914d\u5230 {0}
mouse.shortcut.dialog.side.buttons.with.double.click=\u6309\u94ae {0} \u4e0d\u652f\u6301\u53cc\u51fb
actions.tree.external.tools.group=\u5916\u90e8\u5de5\u5177
new.keymap.name={0} \u590d\u5236
new.indexed.keymap.name={0} \u590d\u5236 {1}
quick.list.panel.move.down.button=\u4e0b\u79fb(&D)
quick.list.panel.move.up.button=\u4e0a\u79fb(&U)
quick.list.panel.add.separator.button=\u6dfb\u52a0\u5206\u9694\u7b26
quick.list.panel.description.label=\u63cf\u8ff0:
quick.list.panel.display.name.label=\u663e\u793a\u540d\u79f0:
no.actions=\u65e0\u52a8\u4f5c
#0 - modifiers (with + for windows or empty str), 1 - button num (1 - left, 2 - center, 3 - right etc.)
mouse.click.shortcut.text={0} \u6309\u94ae {1} \u5355\u51fb
mouse.double.click.shortcut.text={0} \u6309\u94ae {1} \u53cc\u51fb
mouse.wheel.rotate.up.shortcut.text={0} \u6eda\u8f6e\u5411\u4e0a
mouse.wheel.rotate.down.shortcut.text={0} \u6eda\u8f6e\u5411\u4e0b
configuration.all.keymaps.should.have.non.empty.names.error.message=\u6240\u6709\u5feb\u6377\u952e\u6620\u5c04\u5e94\u8be5\u8f93\u5165\u975e\u7a7a\u7684\u540d\u79f0
configuration.all.keymaps.should.have.unique.names.error.message=\u6240\u6709\u5feb\u6377\u952e\u6620\u5c04\u5e94\u8be5\u4f7f\u7528\u552f\u4e00\u7684\u540d\u79f0
dialog.enable.second.stroke.checkbox=\u7b2c\u4e8c\u6b21\u6309\u4e0b\u952e\u76d8:
dialog.mouse.pad.default.text=<html><center>\u5728\u8fd9\u91cc\u8f93\u5165\u4e00\u4e2a\u5feb\u6377\u65b9\u5f0f: <br>\u5355\u51fb\u6216\u53cc\u51fb\uff0c\u6eda\u52a8\u6eda\u8f6e,<br> \u7528 Ctrl\uff0cAlt \u548c Shift \u8fdb\u884c\u4fee\u6539
dialog.mouse.pad.shortcut.text=<html><center> <br>{0}<br><br>
dialog.conflicts.text=\u5df2\u7ecf\u5206\u914d\u7ed9:
filter.clear.action.text=\u6e05\u9664\u8fc7\u6ee4
filter.settings.popup.title=\u67e5\u627e\u5feb\u6377\u952e
filter.enable.second.stroke.checkbox=\u7b2c\u4e8c\u6b21\u6309\u4e0b\u952e\u76d8
filter.mouse.pad.label=\u9f20\u6807\u5feb\u6377\u952e
filter.first.stroke.input=\u7b2c\u4e00\u6b21\u6309\u4e0b\u952e\u76d8:
filter.second.stroke.input=\u7b2c\u4e8c\u6b21\u6309\u4e0b\u952e\u76d8:
filter.shortcut.action.text=\u7528\u5feb\u6377\u952e\u627e\u5230\u64cd\u4f5c
disable.mnemonic.in.controls.check.box=\u7981\u7528\u63a7\u5236\u4e2d\u7684\u52a9\u8bb0\u7b26
keymap.with.patched.redo.name={0} \u6b63\u786e\u91cd\u505a
keymap.patch.dialog.title=\u5c06\u64cd\u4f5c\u6620\u5c04\u5230 Ctrl+Y
# suppress inspection "TrailingSpacesInProperty"
keymap.patch.dialog.message=\u4f7f\u7528 Ctrl+Y \u91cd\u505a\u8fd8\u662f\u5220\u9664\u884c\uff1f\n\n\u7a0d\u540e\u53ef\u4ee5\u5728\u201c\u8bbe\u7f6e\u201d\u4e2d\u66f4\u6539\u6b64\u884c\u4e3a\u952e\u76d8\u6620\u5c04\u3002\n
keymap.patch.dialog.redo.option=\u91cd\u505a
keymap.patch.dialog.delete.line.option=\u5220\u9664\u884c
keymap.patch.dialog.cancel.option=\u53d6\u6d88
| {
"pile_set_name": "Github"
} |
/* HTTPS GET Example using plain mbedTLS sockets
*
* Contacts the howsmyssl.com API via TLS v1.2 and reads a JSON
* response.
*
* Adapted from the ssl_client1 example in mbedtls.
*
* Original Copyright (C) 2006-2016, ARM Limited, All Rights Reserved, Apache 2.0 License.
* Additions Copyright (C) Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD, Apache 2.0 License.
*
*
* 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 <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_event.h"
#include "protocol_examples_common.h"
#include "nvs.h"
#include "nvs_flash.h"
#include <netdb.h>
#include <sys/socket.h>
#include "mbedtls/platform.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/esp_debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/certs.h"
/* Constants that aren't configurable in menuconfig */
#define WEB_SERVER "www.howsmyssl.com"
#define WEB_PORT "443"
#define WEB_URL "https://www.howsmyssl.com/a/check"
static const char *TAG = "example";
static const char *REQUEST = "GET " WEB_URL " HTTP/1.0\r\n"
"Host: "WEB_SERVER"\r\n"
"User-Agent: esp-idf/1.0 esp32\r\n"
"\r\n";
/* Root cert for howsmyssl.com, taken from server_root_cert.pem
The PEM file was extracted from the output of this command:
openssl s_client -showcerts -connect www.howsmyssl.com:443 </dev/null
The CA root cert is the last cert given in the chain of certs.
To embed it in the app binary, the PEM file is named
in the component.mk COMPONENT_EMBED_TXTFILES variable.
*/
extern const uint8_t server_root_cert_pem_start[] asm("_binary_server_root_cert_pem_start");
extern const uint8_t server_root_cert_pem_end[] asm("_binary_server_root_cert_pem_end");
static void https_get_task(void *pvParameters)
{
char buf[512];
int ret, flags, len;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_context ssl;
mbedtls_x509_crt cacert;
mbedtls_ssl_config conf;
mbedtls_net_context server_fd;
mbedtls_ssl_init(&ssl);
mbedtls_x509_crt_init(&cacert);
mbedtls_ctr_drbg_init(&ctr_drbg);
ESP_LOGI(TAG, "Seeding the random number generator");
mbedtls_ssl_config_init(&conf);
mbedtls_entropy_init(&entropy);
if((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
NULL, 0)) != 0)
{
ESP_LOGE(TAG, "mbedtls_ctr_drbg_seed returned %d", ret);
abort();
}
ESP_LOGI(TAG, "Loading the CA root certificate...");
ret = mbedtls_x509_crt_parse(&cacert, server_root_cert_pem_start,
server_root_cert_pem_end-server_root_cert_pem_start);
if(ret < 0)
{
ESP_LOGE(TAG, "mbedtls_x509_crt_parse returned -0x%x\n\n", -ret);
abort();
}
ESP_LOGI(TAG, "Setting hostname for TLS session...");
/* Hostname set here should match CN in server certificate */
if((ret = mbedtls_ssl_set_hostname(&ssl, WEB_SERVER)) != 0)
{
ESP_LOGE(TAG, "mbedtls_ssl_set_hostname returned -0x%x", -ret);
abort();
}
ESP_LOGI(TAG, "Setting up the SSL/TLS structure...");
if((ret = mbedtls_ssl_config_defaults(&conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0)
{
ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned %d", ret);
goto exit;
}
/* MBEDTLS_SSL_VERIFY_OPTIONAL is bad for security, in this example it will print
a warning if CA verification fails but it will continue to connect.
You should consider using MBEDTLS_SSL_VERIFY_REQUIRED in your own code.
*/
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
#ifdef CONFIG_MBEDTLS_DEBUG
mbedtls_esp_enable_debug_log(&conf, 4);
#endif
if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0)
{
ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x\n\n", -ret);
goto exit;
}
while(1) {
mbedtls_net_init(&server_fd);
ESP_LOGI(TAG, "Connecting to %s:%s...", WEB_SERVER, WEB_PORT);
if ((ret = mbedtls_net_connect(&server_fd, WEB_SERVER,
WEB_PORT, MBEDTLS_NET_PROTO_TCP)) != 0)
{
ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret);
goto exit;
}
ESP_LOGI(TAG, "Connected.");
mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
ESP_LOGI(TAG, "Performing the SSL/TLS handshake...");
while ((ret = mbedtls_ssl_handshake(&ssl)) != 0)
{
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
{
ESP_LOGE(TAG, "mbedtls_ssl_handshake returned -0x%x", -ret);
goto exit;
}
}
ESP_LOGI(TAG, "Verifying peer X.509 certificate...");
if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0)
{
/* In real life, we probably want to close connection if ret != 0 */
ESP_LOGW(TAG, "Failed to verify peer certificate!");
bzero(buf, sizeof(buf));
mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags);
ESP_LOGW(TAG, "verification info: %s", buf);
}
else {
ESP_LOGI(TAG, "Certificate verified.");
}
ESP_LOGI(TAG, "Cipher suite is %s", mbedtls_ssl_get_ciphersuite(&ssl));
ESP_LOGI(TAG, "Writing HTTP request...");
size_t written_bytes = 0;
do {
ret = mbedtls_ssl_write(&ssl,
(const unsigned char *)REQUEST + written_bytes,
strlen(REQUEST) - written_bytes);
if (ret >= 0) {
ESP_LOGI(TAG, "%d bytes written", ret);
written_bytes += ret;
} else if (ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret != MBEDTLS_ERR_SSL_WANT_READ) {
ESP_LOGE(TAG, "mbedtls_ssl_write returned -0x%x", -ret);
goto exit;
}
} while(written_bytes < strlen(REQUEST));
ESP_LOGI(TAG, "Reading HTTP response...");
do
{
len = sizeof(buf) - 1;
bzero(buf, sizeof(buf));
ret = mbedtls_ssl_read(&ssl, (unsigned char *)buf, len);
if(ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE)
continue;
if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
ret = 0;
break;
}
if(ret < 0)
{
ESP_LOGE(TAG, "mbedtls_ssl_read returned -0x%x", -ret);
break;
}
if(ret == 0)
{
ESP_LOGI(TAG, "connection closed");
break;
}
len = ret;
ESP_LOGD(TAG, "%d bytes read", len);
/* Print response directly to stdout as it is read */
for(int i = 0; i < len; i++) {
putchar(buf[i]);
}
} while(1);
mbedtls_ssl_close_notify(&ssl);
exit:
mbedtls_ssl_session_reset(&ssl);
mbedtls_net_free(&server_fd);
if(ret != 0)
{
mbedtls_strerror(ret, buf, 100);
ESP_LOGE(TAG, "Last error was: -0x%x - %s", -ret, buf);
}
putchar('\n'); // JSON output doesn't have a newline at end
static int request_count;
ESP_LOGI(TAG, "Completed %d requests", ++request_count);
for(int countdown = 10; countdown >= 0; countdown--) {
ESP_LOGI(TAG, "%d...", countdown);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
ESP_LOGI(TAG, "Starting again!");
}
}
void app_main(void)
{
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(example_connect());
xTaskCreate(&https_get_task, "https_get_task", 8192, NULL, 5, NULL);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015 John Ahlroos
*
* 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.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui.csslayout;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ui.dd.VAcceptCallback;
import com.vaadin.client.ui.dd.VDragEvent;
import com.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui.VDDAbstractDropHandler;
public class VDDCssLayoutDropHandler
extends VDDAbstractDropHandler<VDDCssLayout> {
public VDDCssLayoutDropHandler(ComponentConnector connector) {
super(connector);
}
@Override
public boolean drop(VDragEvent drag) {
getLayout().updateDragDetails(drag);
getLayout().detachDragImageFromLayout(drag);
return getLayout().postDropHook(drag) && super.drop(drag);
}
@Override
public void dragEnter(VDragEvent drag) {
super.dragEnter(drag);
getLayout().attachDragImageToLayout(drag);
getLayout().updateDragDetails(drag);
getLayout().postEnterHook(drag);
}
@Override
public void dragLeave(VDragEvent drag) {
super.dragLeave(drag);
getLayout().detachDragImageFromLayout(drag);
getLayout().postLeaveHook(drag);
}
@Override
public void dragOver(VDragEvent drag) {
getLayout().updateDragDetails(drag);
getLayout().postOverHook(drag);
// Validate the drop
validate(new VAcceptCallback() {
public void accepted(VDragEvent event) {
getLayout().updateDrag(event);
}
}, drag);
}
}
| {
"pile_set_name": "Github"
} |
# Copyright 2018 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.
# ==============================================================================
"""Helper code to run complete models from within python.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import shutil
import sys
import tempfile
from absl import flags
from official.utils.flags import core as flags_core
def run_synthetic(main, tmp_root, extra_flags=None, synth=True, max_train=1):
"""Performs a minimal run of a model.
This function is intended to test for syntax errors throughout a model. A
very limited run is performed using synthetic data.
Args:
main: The primary function used to exercise a code path. Generally this
function is "<MODULE>.main(argv)".
tmp_root: Root path for the temp directory created by the test class.
extra_flags: Additional flags passed by the caller of this function.
synth: Use synthetic data.
max_train: Maximum number of allowed training steps.
"""
extra_flags = [] if extra_flags is None else extra_flags
model_dir = tempfile.mkdtemp(dir=tmp_root)
args = [sys.argv[0], "--model_dir", model_dir, "--train_epochs", "1",
"--epochs_between_evals", "1"] + extra_flags
if synth:
args.append("--use_synthetic_data")
if max_train is not None:
args.extend(["--max_train_steps", str(max_train)])
try:
flags_core.parse_flags(argv=args)
main(flags.FLAGS)
finally:
if os.path.exists(model_dir):
shutil.rmtree(model_dir)
| {
"pile_set_name": "Github"
} |
function f = cumsum2(f, dims)
%CUMSUM2 Double indefinite integral of a CHEBFUN3.
% F = CUMSUM2(F) returns the double indefinite integral of a CHEBFUN3 F.
% By default, that means cumsum in the first 2 variables, i.e., x and y:
% y x
% / /
% CUMSUM2(F) = | | F(x,y,z) dx dy
% / /
% c a
%
% where [a,b] x [c,d] x [e,g] is the domain of F.
%
% DIMS is a vector containing two of the three indices 1,2,3 to show
% which two of the dimensions are to be used.
%
% See also CHEBFUN3/CUMSUM, CHEBFUN3/CUMSUM3, CHEBFUN3/SUM, CHEBFUN3/SUM2
% and CHEBFUN3/SUM3.
% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.
% Check for empty:
if ( isempty(f) )
f = [];
return
end
% Default to cumsum in the first two variables x and y:
if ( nargin == 1 )
dims = [1, 2];
end
if ( numel(dims) ~= 2 )
error('CHEBFUN:CHEBFUN3:cumsum2:dims', 'Dims should have 2 entries.');
end
if ismember(1, dims)
% cumsum along the 1st variable
f.cols = cumsum(f.cols);
end
if ismember(2, dims)
% cumsum along the 2nd variable
f.rows = cumsum(f.rows);
end
if ismember(3, dims)
% cumsum along the 3rd variable
f.tubes = cumsum(f.tubes);
end
end | {
"pile_set_name": "Github"
} |
import { Component, ViewChild, ViewContainerRef, ViewEncapsulation } from '@angular/core';
import { MatMenu } from '@angular/material/menu';
import { PblNgridComponent, PblColumn, PblNgridDataHeaderExtensionContext } from '@pebula/ngrid';
import { PblNgridOverlayPanelRef } from '@pebula/ngrid/overlay-panel';
@Component({
selector: 'mat-excel-style-header-menu',
templateUrl: `./excel-style-header-menu.html`,
styleUrls: [ `./excel-style-header-menu.scss` ],
encapsulation: ViewEncapsulation.None,
})
export class MatExcelStyleHeaderMenu {
column: PblColumn;
grid: PblNgridComponent
@ViewChild('columnMenu', { read: MatMenu, static: true }) matMenu: MatMenu;
@ViewChild('menuViewLocation', { read: ViewContainerRef, static: true }) menuViewLocation: ViewContainerRef;
currentSort: 'asc' | 'desc' | undefined;
currentPin: 'start' | 'end' | undefined;
currentFilter: any = '';
constructor(private ref: PblNgridOverlayPanelRef<PblNgridDataHeaderExtensionContext>) {
this.column = ref.data.col;
this.grid = ref.data.grid;
if (this.grid.ds.sort.column === this.column) {
this.currentSort = this.grid.ds.sort.sort.order;
}
this.currentPin = this.column.columnDef.sticky ? 'start' : this.column.columnDef.stickyEnd ? 'end' : undefined;
const dsFilter = this.grid.ds.filter;
if (dsFilter && dsFilter.type === 'value' && dsFilter.columns && dsFilter.columns.indexOf(this.column) >= 0) {
this.currentFilter = dsFilter.filter;
}
}
ngAfterViewInit() {
this.matMenu.closed.subscribe( reason => {
this.ref.close();
});
const view = this.menuViewLocation.createEmbeddedView(this.matMenu.templateRef);
this.matMenu.setElevation(0);
this.matMenu.focusFirstItem('program');
this.matMenu._resetAnimation();
view.markForCheck();
view.detectChanges();
this.matMenu._startAnimation();
}
hide(): void {
const hidden: string[] = [this.column.id];
for (const col of this.grid.columnApi.columns) {
if (col.hidden) {
hidden.push(col.id);
}
}
this.grid.hideColumns = hidden;
}
onSortToggle(sort: 'asc' | 'desc'): void {
if (this.currentSort === sort) {
this.grid.ds.setSort();
} else {
this.grid.ds.setSort(this.column, { order: sort });
}
}
onPinToggle(pin: 'start' | 'end'): void {
if (this.currentPin === pin) {
this.column.columnDef.updatePin()
} else {
this.column.columnDef.updatePin(pin)
}
}
filterColumn(filterValue: string) {
this.currentFilter = filterValue;
if (!filterValue) {
this.grid.setFilter();
} else {
this.grid.setFilter(filterValue.trim(), [ this.column ]);
}
}
clickTrap(event: MouseEvent): void {
event.preventDefault();
event.stopPropagation();
}
}
| {
"pile_set_name": "Github"
} |
# pyshyacc.py - PLY grammar definition for pysh
#
# Copyright 2007 Patrick Mezard
#
# This software may be used and distributed according to the terms
# of the GNU General Public License, incorporated herein by reference.
"""PLY grammar file.
"""
import os.path
import sys
import bb.pysh.pyshlex as pyshlex
tokens = pyshlex.tokens
from ply import yacc
import bb.pysh.sherrors as sherrors
class IORedirect:
def __init__(self, op, filename, io_number=None):
self.op = op
self.filename = filename
self.io_number = io_number
class HereDocument:
def __init__(self, op, name, content, io_number=None):
self.op = op
self.name = name
self.content = content
self.io_number = io_number
def make_io_redirect(p):
"""Make an IORedirect instance from the input 'io_redirect' production."""
name, io_number, io_target = p
assert name=='io_redirect'
if io_target[0]=='io_file':
io_type, io_op, io_file = io_target
return IORedirect(io_op, io_file, io_number)
elif io_target[0]=='io_here':
io_type, io_op, io_name, io_content = io_target
return HereDocument(io_op, io_name, io_content, io_number)
else:
assert False, "Invalid IO redirection token %s" % repr(io_type)
class SimpleCommand:
"""
assigns contains (name, value) pairs.
"""
def __init__(self, words, redirs, assigns):
self.words = list(words)
self.redirs = list(redirs)
self.assigns = list(assigns)
class Pipeline:
def __init__(self, commands, reverse_status=False):
self.commands = list(commands)
assert self.commands #Grammar forbids this
self.reverse_status = reverse_status
class AndOr:
def __init__(self, op, left, right):
self.op = str(op)
self.left = left
self.right = right
class ForLoop:
def __init__(self, name, items, cmds):
self.name = str(name)
self.items = list(items)
self.cmds = list(cmds)
class WhileLoop:
def __init__(self, condition, cmds):
self.condition = list(condition)
self.cmds = list(cmds)
class UntilLoop:
def __init__(self, condition, cmds):
self.condition = list(condition)
self.cmds = list(cmds)
class FunDef:
def __init__(self, name, body):
self.name = str(name)
self.body = body
class BraceGroup:
def __init__(self, cmds):
self.cmds = list(cmds)
class IfCond:
def __init__(self, cond, if_cmds, else_cmds):
self.cond = list(cond)
self.if_cmds = if_cmds
self.else_cmds = else_cmds
class Case:
def __init__(self, name, items):
self.name = name
self.items = items
class SubShell:
def __init__(self, cmds):
self.cmds = cmds
class RedirectList:
def __init__(self, cmd, redirs):
self.cmd = cmd
self.redirs = list(redirs)
def get_production(productions, ptype):
"""productions must be a list of production tuples like (name, obj) where
name is the production string identifier.
Return the first production named 'ptype'. Raise KeyError if None can be
found.
"""
for production in productions:
if production is not None and production[0]==ptype:
return production
raise KeyError(ptype)
#-------------------------------------------------------------------------------
# PLY grammar definition
#-------------------------------------------------------------------------------
def p_multiple_commands(p):
"""multiple_commands : newline_sequence
| complete_command
| multiple_commands complete_command"""
if len(p)==2:
if p[1] is not None:
p[0] = [p[1]]
else:
p[0] = []
else:
p[0] = p[1] + [p[2]]
def p_complete_command(p):
"""complete_command : list separator
| list"""
if len(p)==3 and p[2] and p[2][1] == '&':
p[0] = ('async', p[1])
else:
p[0] = p[1]
def p_list(p):
"""list : list separator_op and_or
| and_or"""
if len(p)==2:
p[0] = [p[1]]
else:
#if p[2]!=';':
# raise NotImplementedError('AND-OR list asynchronous execution is not implemented')
p[0] = p[1] + [p[3]]
def p_and_or(p):
"""and_or : pipeline
| and_or AND_IF linebreak pipeline
| and_or OR_IF linebreak pipeline"""
if len(p)==2:
p[0] = p[1]
else:
p[0] = ('and_or', AndOr(p[2], p[1], p[4]))
def p_maybe_bang_word(p):
"""maybe_bang_word : Bang"""
p[0] = ('maybe_bang_word', p[1])
def p_pipeline(p):
"""pipeline : pipe_sequence
| bang_word pipe_sequence"""
if len(p)==3:
p[0] = ('pipeline', Pipeline(p[2][1:], True))
else:
p[0] = ('pipeline', Pipeline(p[1][1:]))
def p_pipe_sequence(p):
"""pipe_sequence : command
| pipe_sequence PIPE linebreak command"""
if len(p)==2:
p[0] = ['pipe_sequence', p[1]]
else:
p[0] = p[1] + [p[4]]
def p_command(p):
"""command : simple_command
| compound_command
| compound_command redirect_list
| function_definition"""
if p[1][0] in ( 'simple_command',
'for_clause',
'while_clause',
'until_clause',
'case_clause',
'if_clause',
'function_definition',
'subshell',
'brace_group',):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ('redirect_list', RedirectList(p[1], p[2][1:]))
else:
raise NotImplementedError('%s command is not implemented' % repr(p[1][0]))
def p_compound_command(p):
"""compound_command : brace_group
| subshell
| for_clause
| case_clause
| if_clause
| while_clause
| until_clause"""
p[0] = p[1]
def p_subshell(p):
"""subshell : LPARENS compound_list RPARENS"""
p[0] = ('subshell', SubShell(p[2][1:]))
def p_compound_list(p):
"""compound_list : term
| newline_list term
| term separator
| newline_list term separator"""
productions = p[1:]
try:
sep = get_production(productions, 'separator')
if sep[1]!=';':
raise NotImplementedError()
except KeyError:
pass
term = get_production(productions, 'term')
p[0] = ['compound_list'] + term[1:]
def p_term(p):
"""term : term separator and_or
| and_or"""
if len(p)==2:
p[0] = ['term', p[1]]
else:
if p[2] is not None and p[2][1] == '&':
p[0] = ['term', ('async', p[1][1:])] + [p[3]]
else:
p[0] = p[1] + [p[3]]
def p_maybe_for_word(p):
# Rearrange 'For' priority wrt TOKEN. See p_for_word
"""maybe_for_word : For"""
p[0] = ('maybe_for_word', p[1])
def p_for_clause(p):
"""for_clause : for_word name linebreak do_group
| for_word name linebreak in sequential_sep do_group
| for_word name linebreak in wordlist sequential_sep do_group"""
productions = p[1:]
do_group = get_production(productions, 'do_group')
try:
items = get_production(productions, 'in')[1:]
except KeyError:
raise NotImplementedError('"in" omission is not implemented')
try:
items = get_production(productions, 'wordlist')[1:]
except KeyError:
items = []
name = p[2]
p[0] = ('for_clause', ForLoop(name, items, do_group[1:]))
def p_name(p):
"""name : token""" #Was NAME instead of token
p[0] = p[1]
def p_in(p):
"""in : In"""
p[0] = ('in', p[1])
def p_wordlist(p):
"""wordlist : wordlist token
| token"""
if len(p)==2:
p[0] = ['wordlist', ('TOKEN', p[1])]
else:
p[0] = p[1] + [('TOKEN', p[2])]
def p_case_clause(p):
"""case_clause : Case token linebreak in linebreak case_list Esac
| Case token linebreak in linebreak case_list_ns Esac
| Case token linebreak in linebreak Esac"""
if len(p) < 8:
items = []
else:
items = p[6][1:]
name = p[2]
p[0] = ('case_clause', Case(name, [c[1] for c in items]))
def p_case_list_ns(p):
"""case_list_ns : case_list case_item_ns
| case_item_ns"""
p_case_list(p)
def p_case_list(p):
"""case_list : case_list case_item
| case_item"""
if len(p)==2:
p[0] = ['case_list', p[1]]
else:
p[0] = p[1] + [p[2]]
def p_case_item_ns(p):
"""case_item_ns : pattern RPARENS linebreak
| pattern RPARENS compound_list linebreak
| LPARENS pattern RPARENS linebreak
| LPARENS pattern RPARENS compound_list linebreak"""
p_case_item(p)
def p_case_item(p):
"""case_item : pattern RPARENS linebreak DSEMI linebreak
| pattern RPARENS compound_list DSEMI linebreak
| LPARENS pattern RPARENS linebreak DSEMI linebreak
| LPARENS pattern RPARENS compound_list DSEMI linebreak"""
if len(p) < 7:
name = p[1][1:]
else:
name = p[2][1:]
try:
cmds = get_production(p[1:], "compound_list")[1:]
except KeyError:
cmds = []
p[0] = ('case_item', (name, cmds))
def p_pattern(p):
"""pattern : token
| pattern PIPE token"""
if len(p)==2:
p[0] = ['pattern', ('TOKEN', p[1])]
else:
p[0] = p[1] + [('TOKEN', p[2])]
def p_maybe_if_word(p):
# Rearrange 'If' priority wrt TOKEN. See p_if_word
"""maybe_if_word : If"""
p[0] = ('maybe_if_word', p[1])
def p_maybe_then_word(p):
# Rearrange 'Then' priority wrt TOKEN. See p_then_word
"""maybe_then_word : Then"""
p[0] = ('maybe_then_word', p[1])
def p_if_clause(p):
"""if_clause : if_word compound_list then_word compound_list else_part Fi
| if_word compound_list then_word compound_list Fi"""
else_part = []
if len(p)==7:
else_part = p[5]
p[0] = ('if_clause', IfCond(p[2][1:], p[4][1:], else_part))
def p_else_part(p):
"""else_part : Elif compound_list then_word compound_list else_part
| Elif compound_list then_word compound_list
| Else compound_list"""
if len(p)==3:
p[0] = p[2][1:]
else:
else_part = []
if len(p)==6:
else_part = p[5]
p[0] = ('elif', IfCond(p[2][1:], p[4][1:], else_part))
def p_while_clause(p):
"""while_clause : While compound_list do_group"""
p[0] = ('while_clause', WhileLoop(p[2][1:], p[3][1:]))
def p_maybe_until_word(p):
# Rearrange 'Until' priority wrt TOKEN. See p_until_word
"""maybe_until_word : Until"""
p[0] = ('maybe_until_word', p[1])
def p_until_clause(p):
"""until_clause : until_word compound_list do_group"""
p[0] = ('until_clause', UntilLoop(p[2][1:], p[3][1:]))
def p_function_definition(p):
"""function_definition : fname LPARENS RPARENS linebreak function_body"""
p[0] = ('function_definition', FunDef(p[1], p[5]))
def p_function_body(p):
"""function_body : compound_command
| compound_command redirect_list"""
if len(p)!=2:
raise NotImplementedError('functions redirections lists are not implemented')
p[0] = p[1]
def p_fname(p):
"""fname : TOKEN""" #Was NAME instead of token
p[0] = p[1]
def p_brace_group(p):
"""brace_group : Lbrace compound_list Rbrace"""
p[0] = ('brace_group', BraceGroup(p[2][1:]))
def p_maybe_done_word(p):
#See p_assignment_word for details.
"""maybe_done_word : Done"""
p[0] = ('maybe_done_word', p[1])
def p_maybe_do_word(p):
"""maybe_do_word : Do"""
p[0] = ('maybe_do_word', p[1])
def p_do_group(p):
"""do_group : do_word compound_list done_word"""
#Do group contains a list of AndOr
p[0] = ['do_group'] + p[2][1:]
def p_simple_command(p):
"""simple_command : cmd_prefix cmd_word cmd_suffix
| cmd_prefix cmd_word
| cmd_prefix
| cmd_name cmd_suffix
| cmd_name"""
words, redirs, assigns = [], [], []
for e in p[1:]:
name = e[0]
if name in ('cmd_prefix', 'cmd_suffix'):
for sube in e[1:]:
subname = sube[0]
if subname=='io_redirect':
redirs.append(make_io_redirect(sube))
elif subname=='ASSIGNMENT_WORD':
assigns.append(sube)
else:
words.append(sube)
elif name in ('cmd_word', 'cmd_name'):
words.append(e)
cmd = SimpleCommand(words, redirs, assigns)
p[0] = ('simple_command', cmd)
def p_cmd_name(p):
"""cmd_name : TOKEN"""
p[0] = ('cmd_name', p[1])
def p_cmd_word(p):
"""cmd_word : token"""
p[0] = ('cmd_word', p[1])
def p_maybe_assignment_word(p):
#See p_assignment_word for details.
"""maybe_assignment_word : ASSIGNMENT_WORD"""
p[0] = ('maybe_assignment_word', p[1])
def p_cmd_prefix(p):
"""cmd_prefix : io_redirect
| cmd_prefix io_redirect
| assignment_word
| cmd_prefix assignment_word"""
try:
prefix = get_production(p[1:], 'cmd_prefix')
except KeyError:
prefix = ['cmd_prefix']
try:
value = get_production(p[1:], 'assignment_word')[1]
value = ('ASSIGNMENT_WORD', value.split('=', 1))
except KeyError:
value = get_production(p[1:], 'io_redirect')
p[0] = prefix + [value]
def p_cmd_suffix(p):
"""cmd_suffix : io_redirect
| cmd_suffix io_redirect
| token
| cmd_suffix token
| maybe_for_word
| cmd_suffix maybe_for_word
| maybe_done_word
| cmd_suffix maybe_done_word
| maybe_do_word
| cmd_suffix maybe_do_word
| maybe_until_word
| cmd_suffix maybe_until_word
| maybe_assignment_word
| cmd_suffix maybe_assignment_word
| maybe_if_word
| cmd_suffix maybe_if_word
| maybe_then_word
| cmd_suffix maybe_then_word
| maybe_bang_word
| cmd_suffix maybe_bang_word"""
try:
suffix = get_production(p[1:], 'cmd_suffix')
token = p[2]
except KeyError:
suffix = ['cmd_suffix']
token = p[1]
if isinstance(token, tuple):
if token[0]=='io_redirect':
p[0] = suffix + [token]
else:
#Convert maybe_* to TOKEN if necessary
p[0] = suffix + [('TOKEN', token[1])]
else:
p[0] = suffix + [('TOKEN', token)]
def p_redirect_list(p):
"""redirect_list : io_redirect
| redirect_list io_redirect"""
if len(p) == 2:
p[0] = ['redirect_list', make_io_redirect(p[1])]
else:
p[0] = p[1] + [make_io_redirect(p[2])]
def p_io_redirect(p):
"""io_redirect : io_file
| IO_NUMBER io_file
| io_here
| IO_NUMBER io_here"""
if len(p)==3:
p[0] = ('io_redirect', p[1], p[2])
else:
p[0] = ('io_redirect', None, p[1])
def p_io_file(p):
#Return the tuple (operator, filename)
"""io_file : LESS filename
| LESSAND filename
| GREATER filename
| GREATAND filename
| DGREAT filename
| LESSGREAT filename
| CLOBBER filename"""
#Extract the filename from the file
p[0] = ('io_file', p[1], p[2][1])
def p_filename(p):
#Return the filename
"""filename : TOKEN"""
p[0] = ('filename', p[1])
def p_io_here(p):
"""io_here : DLESS here_end
| DLESSDASH here_end"""
p[0] = ('io_here', p[1], p[2][1], p[2][2])
def p_here_end(p):
"""here_end : HERENAME TOKEN"""
p[0] = ('here_document', p[1], p[2])
def p_newline_sequence(p):
# Nothing in the grammar can handle leading NEWLINE productions, so add
# this one with the lowest possible priority relatively to newline_list.
"""newline_sequence : newline_list"""
p[0] = None
def p_newline_list(p):
"""newline_list : NEWLINE
| newline_list NEWLINE"""
p[0] = None
def p_linebreak(p):
"""linebreak : newline_list
| empty"""
p[0] = None
def p_separator_op(p):
"""separator_op : COMMA
| COMMA COMMA
| AMP"""
p[0] = p[1]
def p_separator(p):
"""separator : separator_op linebreak
| newline_list"""
if len(p)==2:
#Ignore newlines
p[0] = None
else:
#Keep the separator operator
p[0] = ('separator', p[1])
def p_sequential_sep(p):
"""sequential_sep : COMMA linebreak
| newline_list"""
p[0] = None
# Low priority TOKEN => for_word conversion.
# Let maybe_for_word be used as a token when necessary in higher priority
# rules.
def p_for_word(p):
"""for_word : maybe_for_word"""
p[0] = p[1]
def p_if_word(p):
"""if_word : maybe_if_word"""
p[0] = p[1]
def p_then_word(p):
"""then_word : maybe_then_word"""
p[0] = p[1]
def p_done_word(p):
"""done_word : maybe_done_word"""
p[0] = p[1]
def p_do_word(p):
"""do_word : maybe_do_word"""
p[0] = p[1]
def p_until_word(p):
"""until_word : maybe_until_word"""
p[0] = p[1]
def p_assignment_word(p):
"""assignment_word : maybe_assignment_word"""
p[0] = ('assignment_word', p[1][1])
def p_bang_word(p):
"""bang_word : maybe_bang_word"""
p[0] = ('bang_word', p[1][1])
def p_token(p):
"""token : TOKEN
| Fi"""
p[0] = p[1]
def p_empty(p):
'empty :'
p[0] = None
# Error rule for syntax errors
def p_error(p):
msg = []
w = msg.append
if p:
w('%r\n' % p)
w('followed by:\n')
for i in range(5):
n = yacc.token()
if not n:
break
w(' %r\n' % n)
else:
w('Unexpected EOF')
raise sherrors.ShellSyntaxError(''.join(msg))
# Build the parser
try:
import pyshtables
except ImportError:
outputdir = os.path.dirname(__file__)
if not os.access(outputdir, os.W_OK):
outputdir = ''
yacc.yacc(tabmodule = 'pyshtables', outputdir = outputdir, debug = 0)
else:
yacc.yacc(tabmodule = 'pysh.pyshtables', write_tables = 0, debug = 0)
def parse(input, eof=False, debug=False):
"""Parse a whole script at once and return the generated AST and unconsumed
data in a tuple.
NOTE: eof is probably meaningless for now, the parser being unable to work
in pull mode. It should be set to True.
"""
lexer = pyshlex.PLYLexer()
remaining = lexer.add(input, eof)
if lexer.is_empty():
return [], remaining
if debug:
debug = 2
return yacc.parse(lexer=lexer, debug=debug), remaining
#-------------------------------------------------------------------------------
# AST rendering helpers
#-------------------------------------------------------------------------------
def format_commands(v):
"""Return a tree made of strings and lists. Make command trees easier to
display.
"""
if isinstance(v, list):
return [format_commands(c) for c in v]
if isinstance(v, tuple):
if len(v)==2 and isinstance(v[0], str) and not isinstance(v[1], str):
if v[0] == 'async':
return ['AsyncList', map(format_commands, v[1])]
else:
#Avoid decomposing tuples like ('pipeline', Pipeline(...))
return format_commands(v[1])
return format_commands(list(v))
elif isinstance(v, IfCond):
name = ['IfCond']
name += ['if', map(format_commands, v.cond)]
name += ['then', map(format_commands, v.if_cmds)]
name += ['else', map(format_commands, v.else_cmds)]
return name
elif isinstance(v, ForLoop):
name = ['ForLoop']
name += [repr(v.name)+' in ', map(str, v.items)]
name += ['commands', map(format_commands, v.cmds)]
return name
elif isinstance(v, AndOr):
return [v.op, format_commands(v.left), format_commands(v.right)]
elif isinstance(v, Pipeline):
name = 'Pipeline'
if v.reverse_status:
name = '!' + name
return [name, format_commands(v.commands)]
elif isinstance(v, Case):
name = ['Case']
name += [v.name, format_commands(v.items)]
elif isinstance(v, SimpleCommand):
name = ['SimpleCommand']
if v.words:
name += ['words', map(str, v.words)]
if v.assigns:
assigns = [tuple(a[1]) for a in v.assigns]
name += ['assigns', map(str, assigns)]
if v.redirs:
name += ['redirs', map(format_commands, v.redirs)]
return name
elif isinstance(v, RedirectList):
name = ['RedirectList']
if v.redirs:
name += ['redirs', map(format_commands, v.redirs)]
name += ['command', format_commands(v.cmd)]
return name
elif isinstance(v, IORedirect):
return ' '.join(map(str, (v.io_number, v.op, v.filename)))
elif isinstance(v, HereDocument):
return ' '.join(map(str, (v.io_number, v.op, repr(v.name), repr(v.content))))
elif isinstance(v, SubShell):
return ['SubShell', map(format_commands, v.cmds)]
else:
return repr(v)
def print_commands(cmds, output=sys.stdout):
"""Pretty print a command tree."""
def print_tree(cmd, spaces, output):
if isinstance(cmd, list):
for c in cmd:
print_tree(c, spaces + 3, output)
else:
print >>output, ' '*spaces + str(cmd)
formatted = format_commands(cmds)
print_tree(formatted, 0, output)
def stringify_commands(cmds):
"""Serialize a command tree as a string.
Returned string is not pretty and is currently used for unit tests only.
"""
def stringify(value):
output = []
if isinstance(value, list):
formatted = []
for v in value:
formatted.append(stringify(v))
formatted = ' '.join(formatted)
output.append(''.join(['<', formatted, '>']))
else:
output.append(value)
return ' '.join(output)
return stringify(format_commands(cmds))
def visit_commands(cmds, callable):
"""Visit the command tree and execute callable on every Pipeline and
SimpleCommand instances.
"""
if isinstance(cmds, (tuple, list)):
map(lambda c: visit_commands(c,callable), cmds)
elif isinstance(cmds, (Pipeline, SimpleCommand)):
callable(cmds)
| {
"pile_set_name": "Github"
} |
<?php
/**
* Detects unnecessary final modifiers inside of final classes.
*
* This rule is based on the PMD rule catalog. The Unnecessary Final Modifier
* sniff detects the use of the final modifier inside of a final class which
* is unnecessary.
*
* <code>
* final class Foo
* {
* public final function bar()
* {
* }
* }
* </code>
*
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2014 Manuel Pichler. All rights reserved.
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
class UnnecessaryFinalModifierSniff implements Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return int[]
*/
public function register()
{
return [T_CLASS];
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip for-statements without body.
if (isset($token['scope_opener']) === false) {
return;
}
// Fetch previous token.
$prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
// Skip for non final class.
if ($prev === false || $tokens[$prev]['code'] !== T_FINAL) {
return;
}
$next = ++$token['scope_opener'];
$end = --$token['scope_closer'];
for (; $next <= $end; ++$next) {
if ($tokens[$next]['code'] === T_FINAL) {
$error = 'Unnecessary FINAL modifier in FINAL class';
$phpcsFile->addWarning($error, $next, 'Found');
}
}
}//end process()
}//end class
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@null"
android:minHeight="60dp"
android:minWidth="180dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/loading_icon"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"/>
<TextView
android:id="@+id/tipTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="0dp"
android:layout_centerInParent="true"
android:singleLine="true"
android:ellipsize="middle"
android:textSize="16sp" />
</RelativeLayout>
| {
"pile_set_name": "Github"
} |
# zipline的命令行入口
## 先上个图

## 几种使用方式
首先`zipline`主要有三种启动的方式:
1. 使用`zipline`命令行工具
2. 使用`jupyter notebook` 的`zipline`集成`magic`
3. 直接自己组装和调用`TradingAlgorithm`
我们主要以`zipline`命令行工具为研究对象,来看一下它的结构,其它情况类似
## zipline 命令行
首先从`setup.py`中可以看到代码的entry_point
```python
entry_points={
'console_scripts': [
'zipline = zipline.__main__:main',
],
....
}
```
研究 `__main__.py` 文件,发现其石宏了 `click` (http://click.pocoo.org/)包来做命令行接口的路由,其中可以分为4个子命令
* run : 负责执行策略
* ingest : 负责拉取策略所需的数据包(bundle)
* bundles : 查看所有数据包
* clean: 清除数据包
后两个命令都比较简单,前两个里面的逻辑相对复杂一些。
其中 在`main`的入口中,除了者几个子命令,它还是用了`load_extensions`来载入所有的扩展,`-extension` 可以指定扩展的列表。
`run`命令在一些初始化和装载过程之后,会调用TradingAlgorithm的run方法。
`ingest`命令会调用`data.bundles.core`的`ingest`函数来进行拉取。
| {
"pile_set_name": "Github"
} |
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:dc/services/show', 'Unit | Controller | dc/services/show', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
| {
"pile_set_name": "Github"
} |
<!--
Using This Code Example
=========================
The code examples provided are provided by Daniel Greenfeld and Audrey Roy of
Two Scoops Press to help you reference Two Scoops of Django: Best Practices
for Django 1.11. Code samples follow PEP-0008, with exceptions made for the
purposes of improving book formatting. Example code is provided "as is", and
is not intended to be, and should not be considered or labeled as "tutorial
code".
Permissions
============
In general, you may use the code we've provided with this book in your
programs and documentation. You do not need to contact us for permission
unless you're reproducing a significant portion of the code or using it in
commercial distributions. Examples:
* Writing a program that uses several chunks of code from this course does
not require permission.
* Selling or distributing a digital package from material taken from this
book does require permission.
* Answering a question by citing this book and quoting example code does not
require permission.
* Incorporating a significant amount of example code from this book into your
product's documentation does require permission.
Attributions usually include the title, author, publisher and an ISBN. For
example, "Two Scoops of Django: Best Practices for Django 1.11, by Daniel
Roy Greenfeld and Audrey Roy Greenfeld. Copyright 2017 Two Scoops Press
(978-0-692-91572-1)."
If you feel your use of code examples falls outside fair use of the permission
given here, please contact us at info@twoscoopspress.org.
-->
<a href="/flavors/">
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
#
# Created by: Pearu Peterson, April 2002
#
from __future__ import division, print_function, absolute_import
__usage__ = """
Build linalg:
python setup.py build
Run tests if scipy is installed:
python -c 'import scipy;scipy.linalg.test()'
"""
import math
import numpy as np
from numpy.testing import (TestCase, run_module_suite, assert_equal,
assert_almost_equal, assert_array_almost_equal, assert_raises, assert_,
assert_allclose)
from scipy.linalg import _fblas as fblas, get_blas_funcs
try:
from scipy.linalg import _cblas as cblas
except ImportError:
cblas = None
def test_get_blas_funcs():
# check that it returns Fortran code for arrays that are
# fortran-ordered
f1, f2, f3 = get_blas_funcs(
('axpy', 'axpy', 'axpy'),
(np.empty((2,2), dtype=np.complex64, order='F'),
np.empty((2,2), dtype=np.complex128, order='C'))
)
# get_blas_funcs will choose libraries depending on most generic
# array
assert_equal(f1.typecode, 'z')
assert_equal(f2.typecode, 'z')
if cblas is not None:
assert_equal(f1.module_name, 'cblas')
assert_equal(f2.module_name, 'cblas')
# check defaults.
f1 = get_blas_funcs('rotg')
assert_equal(f1.typecode, 'd')
# check also dtype interface
f1 = get_blas_funcs('gemm', dtype=np.complex64)
assert_equal(f1.typecode, 'c')
f1 = get_blas_funcs('gemm', dtype='F')
assert_equal(f1.typecode, 'c')
# extended precision complex
f1 = get_blas_funcs('gemm', dtype=np.longcomplex)
assert_equal(f1.typecode, 'z')
# check safe complex upcasting
f1 = get_blas_funcs('axpy',
(np.empty((2,2), dtype=np.float64),
np.empty((2,2), dtype=np.complex64))
)
assert_equal(f1.typecode, 'z')
def test_get_blas_funcs_alias():
# check alias for get_blas_funcs
f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64)
assert f.typecode == 'c'
assert g.typecode == 'c'
f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64)
assert f is g
assert f is h
class TestCBLAS1Simple(TestCase):
def test_axpy(self):
for p in 'sd':
f = getattr(cblas,p+'axpy',None)
if f is None:
continue
assert_array_almost_equal(f([1,2,3],[2,-1,3],a=5),[7,9,18])
for p in 'cz':
f = getattr(cblas,p+'axpy',None)
if f is None:
continue
assert_array_almost_equal(f([1,2j,3],[2,-1,3],a=5),[7,10j-1,18])
class TestFBLAS1Simple(TestCase):
def test_axpy(self):
for p in 'sd':
f = getattr(fblas,p+'axpy',None)
if f is None:
continue
assert_array_almost_equal(f([1,2,3],[2,-1,3],a=5),[7,9,18])
for p in 'cz':
f = getattr(fblas,p+'axpy',None)
if f is None:
continue
assert_array_almost_equal(f([1,2j,3],[2,-1,3],a=5),[7,10j-1,18])
def test_copy(self):
for p in 'sd':
f = getattr(fblas,p+'copy',None)
if f is None:
continue
assert_array_almost_equal(f([3,4,5],[8]*3),[3,4,5])
for p in 'cz':
f = getattr(fblas,p+'copy',None)
if f is None:
continue
assert_array_almost_equal(f([3,4j,5+3j],[8]*3),[3,4j,5+3j])
def test_asum(self):
for p in 'sd':
f = getattr(fblas,p+'asum',None)
if f is None:
continue
assert_almost_equal(f([3,-4,5]),12)
for p in ['sc','dz']:
f = getattr(fblas,p+'asum',None)
if f is None:
continue
assert_almost_equal(f([3j,-4,3-4j]),14)
def test_dot(self):
for p in 'sd':
f = getattr(fblas,p+'dot',None)
if f is None:
continue
assert_almost_equal(f([3,-4,5],[2,5,1]),-9)
def test_complex_dotu(self):
for p in 'cz':
f = getattr(fblas,p+'dotu',None)
if f is None:
continue
assert_almost_equal(f([3j,-4,3-4j],[2,3,1]),-9+2j)
def test_complex_dotc(self):
for p in 'cz':
f = getattr(fblas,p+'dotc',None)
if f is None:
continue
assert_almost_equal(f([3j,-4,3-4j],[2,3j,1]),3-14j)
def test_nrm2(self):
for p in 'sd':
f = getattr(fblas,p+'nrm2',None)
if f is None:
continue
assert_almost_equal(f([3,-4,5]),math.sqrt(50))
for p in ['c', 'z', 'sc','dz']:
f = getattr(fblas,p+'nrm2',None)
if f is None:
continue
assert_almost_equal(f([3j,-4,3-4j]),math.sqrt(50))
def test_scal(self):
for p in 'sd':
f = getattr(fblas,p+'scal',None)
if f is None:
continue
assert_array_almost_equal(f(2,[3,-4,5]),[6,-8,10])
for p in 'cz':
f = getattr(fblas,p+'scal',None)
if f is None:
continue
assert_array_almost_equal(f(3j,[3j,-4,3-4j]),[-9,-12j,12+9j])
for p in ['cs','zd']:
f = getattr(fblas,p+'scal',None)
if f is None:
continue
assert_array_almost_equal(f(3,[3j,-4,3-4j]),[9j,-12,9-12j])
def test_swap(self):
for p in 'sd':
f = getattr(fblas,p+'swap',None)
if f is None:
continue
x,y = [2,3,1],[-2,3,7]
x1,y1 = f(x,y)
assert_array_almost_equal(x1,y)
assert_array_almost_equal(y1,x)
for p in 'cz':
f = getattr(fblas,p+'swap',None)
if f is None:
continue
x,y = [2,3j,1],[-2,3,7-3j]
x1,y1 = f(x,y)
assert_array_almost_equal(x1,y)
assert_array_almost_equal(y1,x)
def test_amax(self):
for p in 'sd':
f = getattr(fblas,'i'+p+'amax')
assert_equal(f([-2,4,3]),1)
for p in 'cz':
f = getattr(fblas,'i'+p+'amax')
assert_equal(f([-5,4+3j,6]),1)
#XXX: need tests for rot,rotm,rotg,rotmg
class TestFBLAS2Simple(TestCase):
def test_gemv(self):
for p in 'sd':
f = getattr(fblas,p+'gemv',None)
if f is None:
continue
assert_array_almost_equal(f(3,[[3]],[-4]),[-36])
assert_array_almost_equal(f(3,[[3]],[-4],3,[5]),[-21])
for p in 'cz':
f = getattr(fblas,p+'gemv',None)
if f is None:
continue
assert_array_almost_equal(f(3j,[[3-4j]],[-4]),[-48-36j])
assert_array_almost_equal(f(3j,[[3-4j]],[-4],3,[5j]),[-48-21j])
def test_ger(self):
for p in 'sd':
f = getattr(fblas,p+'ger',None)
if f is None:
continue
assert_array_almost_equal(f(1,[1,
2],[3,4]),[[3,4],[6,8]])
assert_array_almost_equal(f(2,[1,
2,
3],[3,4]),[[6,8],[12,16],[18,24]])
assert_array_almost_equal(f(1,[1,
2],[3,4],
a=[[1,2],[3,4]]
),[[4,6],[9,12]])
for p in 'cz':
f = getattr(fblas,p+'geru',None)
if f is None:
continue
assert_array_almost_equal(f(1,[1j,
2],[3,4]),[[3j,4j],[6,8]])
assert_array_almost_equal(f(-2,[1j,
2j,
3j],[3j,4j]),[[6,8],[12,16],[18,24]])
for p in 'cz':
for name in ('ger', 'gerc'):
f = getattr(fblas,p+name,None)
if f is None:
continue
assert_array_almost_equal(f(1,[1j,
2],[3,4]),[[3j,4j],[6,8]])
assert_array_almost_equal(f(2,[1j,
2j,
3j],[3j,4j]),[[6,8],[12,16],[18,24]])
def test_syr_her(self):
x = np.arange(1, 5, dtype='d')
resx = np.triu(x[:, np.newaxis] * x)
resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1])
y = np.linspace(0,8.5,17,endpoint=False)
z = np.arange(1, 9, dtype='d').view('D')
resz = np.triu(z[:, np.newaxis] * z)
resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1])
rehz = np.triu(z[:, np.newaxis] * z.conj())
rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj())
w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
for p, rtol in zip('sd',[1e-7,1e-14]):
f = getattr(fblas, p+'syr', None)
if f is None:
continue
assert_allclose(f(1.0, x), resx, rtol=rtol)
assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol)
assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol)
# negative increments imply reversed vectors in blas
assert_allclose(f(1.0, y, incx=-2, offx=2, n=4),
resx_reverse, rtol=rtol)
a = np.zeros((4,4), 'f' if p == 's' else 'd', 'F')
b = f(1.0, x, a=a, overwrite_a=True)
assert_allclose(a, resx, rtol=rtol)
b = f(2.0, x, a=a)
assert_(a is not b)
assert_allclose(b, 3*resx, rtol=rtol)
assert_raises(Exception, f, 1.0, x, incx=0)
assert_raises(Exception, f, 1.0, x, offx=5)
assert_raises(Exception, f, 1.0, x, offx=-2)
assert_raises(Exception, f, 1.0, x, n=-2)
assert_raises(Exception, f, 1.0, x, n=5)
assert_raises(Exception, f, 1.0, x, lower=2)
assert_raises(Exception, f, 1.0, x, a=np.zeros((2,2), 'd', 'F'))
for p, rtol in zip('cz',[1e-7,1e-14]):
f = getattr(fblas, p+'syr', None)
if f is None:
continue
assert_allclose(f(1.0, z), resz, rtol=rtol)
assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol)
assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol)
# negative increments imply reversed vectors in blas
assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
resz_reverse, rtol=rtol)
a = np.zeros((4,4), 'F' if p == 'c' else 'D', 'F')
b = f(1.0, z, a=a, overwrite_a=True)
assert_allclose(a, resz, rtol=rtol)
b = f(2.0, z, a=a)
assert_(a is not b)
assert_allclose(b, 3*resz, rtol=rtol)
assert_raises(Exception, f, 1.0, x, incx=0)
assert_raises(Exception, f, 1.0, x, offx=5)
assert_raises(Exception, f, 1.0, x, offx=-2)
assert_raises(Exception, f, 1.0, x, n=-2)
assert_raises(Exception, f, 1.0, x, n=5)
assert_raises(Exception, f, 1.0, x, lower=2)
assert_raises(Exception, f, 1.0, x, a=np.zeros((2,2), 'd', 'F'))
for p, rtol in zip('cz',[1e-7,1e-14]):
f = getattr(fblas, p+'her', None)
if f is None:
continue
assert_allclose(f(1.0, z), rehz, rtol=rtol)
assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol)
assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol)
# negative increments imply reversed vectors in blas
assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
rehz_reverse, rtol=rtol)
a = np.zeros((4,4), 'F' if p == 'c' else 'D', 'F')
b = f(1.0, z, a=a, overwrite_a=True)
assert_allclose(a, rehz, rtol=rtol)
b = f(2.0, z, a=a)
assert_(a is not b)
assert_allclose(b, 3*rehz, rtol=rtol)
assert_raises(Exception, f, 1.0, x, incx=0)
assert_raises(Exception, f, 1.0, x, offx=5)
assert_raises(Exception, f, 1.0, x, offx=-2)
assert_raises(Exception, f, 1.0, x, n=-2)
assert_raises(Exception, f, 1.0, x, n=5)
assert_raises(Exception, f, 1.0, x, lower=2)
assert_raises(Exception, f, 1.0, x, a=np.zeros((2,2), 'd', 'F'))
def test_syr2(self):
x = np.arange(1, 5, dtype='d')
y = np.arange(5, 9, dtype='d')
resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x)
resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1]
+ y[::-1, np.newaxis] * x[::-1])
q = np.linspace(0,8.5,17,endpoint=False)
for p, rtol in zip('sd',[1e-7,1e-14]):
f = getattr(fblas, p+'syr2', None)
if f is None:
continue
assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
assert_allclose(f(1.0, x, y, n=3), resxy[:3,:3], rtol=rtol)
assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol)
assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10),
resxy, rtol=rtol)
assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3),
resxy[:3,:3], rtol=rtol)
# negative increments imply reversed vectors in blas
assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10),
resxy_reverse, rtol=rtol)
a = np.zeros((4,4), 'f' if p == 's' else 'd', 'F')
b = f(1.0, x, y, a=a, overwrite_a=True)
assert_allclose(a, resxy, rtol=rtol)
b = f(2.0, x, y, a=a)
assert_(a is not b)
assert_allclose(b, 3*resxy, rtol=rtol)
assert_raises(Exception, f, 1.0, x, y, incx=0)
assert_raises(Exception, f, 1.0, x, y, offx=5)
assert_raises(Exception, f, 1.0, x, y, offx=-2)
assert_raises(Exception, f, 1.0, x, y, incy=0)
assert_raises(Exception, f, 1.0, x, y, offy=5)
assert_raises(Exception, f, 1.0, x, y, offy=-2)
assert_raises(Exception, f, 1.0, x, y, n=-2)
assert_raises(Exception, f, 1.0, x, y, n=5)
assert_raises(Exception, f, 1.0, x, y, lower=2)
assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2,2), 'd', 'F'))
def test_her2(self):
x = np.arange(1, 9, dtype='d').view('D')
y = np.arange(9, 17, dtype='d').view('D')
resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj()
resxy = np.triu(resxy)
resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj()
resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj()
resxy_reverse = np.triu(resxy_reverse)
u = np.c_[np.zeros(4), x, np.zeros(4)].ravel()
v = np.c_[np.zeros(4), y, np.zeros(4)].ravel()
for p, rtol in zip('cz',[1e-7,1e-14]):
f = getattr(fblas, p+'her2', None)
if f is None:
continue
assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
assert_allclose(f(1.0, x, y, n=3), resxy[:3,:3], rtol=rtol)
assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(), rtol=rtol)
assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1),
resxy, rtol=rtol)
assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3),
resxy[:3,:3], rtol=rtol)
# negative increments imply reversed vectors in blas
assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1),
resxy_reverse, rtol=rtol)
a = np.zeros((4,4), 'F' if p == 'c' else 'D', 'F')
b = f(1.0, x, y, a=a, overwrite_a=True)
assert_allclose(a, resxy, rtol=rtol)
b = f(2.0, x, y, a=a)
assert_(a is not b)
assert_allclose(b, 3*resxy, rtol=rtol)
assert_raises(Exception, f, 1.0, x, y, incx=0)
assert_raises(Exception, f, 1.0, x, y, offx=5)
assert_raises(Exception, f, 1.0, x, y, offx=-2)
assert_raises(Exception, f, 1.0, x, y, incy=0)
assert_raises(Exception, f, 1.0, x, y, offy=5)
assert_raises(Exception, f, 1.0, x, y, offy=-2)
assert_raises(Exception, f, 1.0, x, y, n=-2)
assert_raises(Exception, f, 1.0, x, y, n=5)
assert_raises(Exception, f, 1.0, x, y, lower=2)
assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2,2), 'd', 'F'))
class TestFBLAS3Simple(TestCase):
def test_gemm(self):
for p in 'sd':
f = getattr(fblas,p+'gemm',None)
if f is None:
continue
assert_array_almost_equal(f(3,[3],[-4]),[[-36]])
assert_array_almost_equal(f(3,[3],[-4],3,[5]),[-21])
for p in 'cz':
f = getattr(fblas,p+'gemm',None)
if f is None:
continue
assert_array_almost_equal(f(3j,[3-4j],[-4]),[[-48-36j]])
assert_array_almost_equal(f(3j,[3-4j],[-4],3,[5j]),[-48-21j])
def _get_func(func, ps='sdzc'):
"""Just a helper: return a specified BLAS function w/typecode."""
for p in ps:
f = getattr(fblas, p+func, None)
if f is None:
continue
yield f
class TestBLAS3Symm(TestCase):
def setUp(self):
self.a = np.array([[1., 2.],
[0., 1.]])
self.b = np.array([[1., 0., 3.],
[0., -1., 2.]])
self.c = np.ones((2,3))
self.t = np.array([[2., -1., 8.],
[3., 0., 9.]])
def test_symm(self):
for f in _get_func('symm'):
res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
assert_array_almost_equal(res, self.t)
res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
assert_array_almost_equal(res, self.t)
res = f(a=self.a, b=self.b.T, side=1, c=self.c.T, alpha=1., beta=1.)
assert_array_almost_equal(res, self.t.T)
def test_summ_wrong_side(self):
f = getattr(fblas, 'dsymm', None)
if f is not None:
assert_raises(Exception, f, **{'a': self.a, 'b': self.b, 'alpha': 1,
'side': 1})
# `side=1` means C <- B*A, hence shapes of A and B are to be
# compatible. Otherwise, f2py exception is raised
def test_symm_wrong_uplo(self):
"""SYMM only considers the upper/lower part of A. Hence setting
wrong value for `lower` (default is lower=0, meaning upper triangle)
gives a wrong result.
"""
f = getattr(fblas,'dsymm',None)
if f is not None:
res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
assert np.allclose(res, self.t)
res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
assert not np.allclose(res, self.t)
class TestBLAS3Syrk(TestCase):
def setUp(self):
self.a = np.array([[1., 0.],
[0., -2.],
[2., 3.]])
self.t = np.array([[1., 0., 2.],
[0., 4., -6.],
[2., -6., 13.]])
self.tt = np.array([[5., 6.],
[6., 13.]])
def test_syrk(self):
for f in _get_func('syrk'):
c = f(a=self.a, alpha=1.)
assert_array_almost_equal(np.triu(c), np.triu(self.t))
c = f(a=self.a, alpha=1., lower=1)
assert_array_almost_equal(np.tril(c), np.tril(self.t))
c0 = np.ones(self.t.shape)
c = f(a=self.a, alpha=1., beta=1., c=c0)
assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
c = f(a=self.a, alpha=1., trans=1)
assert_array_almost_equal(np.triu(c), np.triu(self.tt))
#prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
# FIXME: how to catch the _fblas.error?
def test_syrk_wrong_c(self):
f = getattr(fblas, 'dsyrk', None)
if f is not None:
assert_raises(Exception, f, **{'a': self.a, 'alpha': 1.,
'c': np.ones((5, 8))})
# if C is supplied, it must have compatible dimensions
class TestBLAS3Syr2k(TestCase):
def setUp(self):
self.a = np.array([[1., 0.],
[0., -2.],
[2., 3.]])
self.b = np.array([[0., 1.],
[1., 0.],
[0, 1.]])
self.t = np.array([[0., -1., 3.],
[-1., 0., 0.],
[3., 0., 6.]])
self.tt = np.array([[0., 1.],
[1., 6]])
def test_syr2k(self):
for f in _get_func('syr2k'):
c = f(a=self.a, b=self.b, alpha=1.)
assert_array_almost_equal(np.triu(c), np.triu(self.t))
c = f(a=self.a, b=self.b, alpha=1., lower=1)
assert_array_almost_equal(np.tril(c), np.tril(self.t))
c0 = np.ones(self.t.shape)
c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0)
assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
c = f(a=self.a, b=self.b, alpha=1., trans=1)
assert_array_almost_equal(np.triu(c), np.triu(self.tt))
#prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
def test_syr2k_wrong_c(self):
f = getattr(fblas, 'dsyr2k', None)
if f is not None:
assert_raises(Exception, f, **{'a': self.a, 'b': self.b, 'alpha': 1.,
'c': np.zeros((15, 8))})
# if C is supplied, it must have compatible dimensions
class TestSyHe(TestCase):
"""Quick and simple tests for (zc)-symm, syrk, syr2k."""
def setUp(self):
self.sigma_y = np.array([[0., -1.j],
[1.j, 0.]])
def test_symm_zc(self):
for f in _get_func('symm', 'zc'):
# NB: a is symmetric w/upper diag of ONLY
res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
assert_array_almost_equal(np.triu(res), np.diag([1, -1]))
def test_hemm_zc(self):
for f in _get_func('hemm', 'zc'):
# NB: a is hermitian w/upper diag of ONLY
res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
def test_syrk_zr(self):
for f in _get_func('syrk', 'zc'):
res = f(a=self.sigma_y, alpha=1.)
assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
def test_herk_zr(self):
for f in _get_func('herk', 'zc'):
res = f(a=self.sigma_y, alpha=1.)
assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
def test_syr2k_zr(self):
for f in _get_func('syr2k', 'zc'):
res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
def test_her2k_zr(self):
for f in _get_func('her2k', 'zc'):
res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1]))
class TestTRMM(TestCase):
"""Quick and simple tests for dtrmm."""
def setUp(self):
self.a = np.array([[1., 2., ],
[-2., 1.]])
self.b = np.array([[3., 4., -1.],
[5., 6., -2.]])
def test_ab(self):
f = getattr(fblas, 'dtrmm', None)
if f is not None:
result = f(1., self.a, self.b)
expected = np.array([[13., 16., -5.],
[5., 6., -2.]]) # default a is upper triangular
assert_array_almost_equal(result, expected)
def test_ab_lower(self):
f = getattr(fblas, 'dtrmm', None)
if f is not None:
result = f(1., self.a, self.b, lower=True)
expected = np.array([[3., 4., -1.],
[-1., -2., 0.]]) # now a is lower triangular
assert_array_almost_equal(result, expected)
def test_b_overwrites(self):
# BLAS dtrmm modifies B argument in-place.
# Here the default is to copy, but this can be overridden
f = getattr(fblas, 'dtrmm', None)
if f is not None:
for overwr in [True, False]:
bcopy = self.b.copy()
result = f(1., self.a, bcopy, overwrite_b=overwr)
# C-contiguous arrays are copied
assert_(bcopy.flags.f_contiguous is False and
np.may_share_memory(bcopy, result) is False)
assert_equal(bcopy, self.b)
bcopy = np.asfortranarray(self.b.copy()) # or just transpose it
result = f(1., self.a, bcopy, overwrite_b=True)
assert_(bcopy.flags.f_contiguous is True and
np.may_share_memory(bcopy, result) is True)
assert_array_almost_equal(bcopy, result)
if __name__ == "__main__":
run_module_suite()
| {
"pile_set_name": "Github"
} |
{-
Alertmanager API
API of the Prometheus Alertmanager (https://github.com/prometheus/alertmanager)
OpenAPI spec version: 0.0.1
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Data.InlineResponse200 exposing (InlineResponse200, decoder, encoder)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
type alias InlineResponse200 =
{ silenceID : Maybe String
}
decoder : Decoder InlineResponse200
decoder =
Decode.succeed InlineResponse200
|> optional "silenceID" (Decode.nullable Decode.string) Nothing
encoder : InlineResponse200 -> Encode.Value
encoder model =
Encode.object
[ ( "silenceID", Maybe.withDefault Encode.null (Maybe.map Encode.string model.silenceID) )
]
| {
"pile_set_name": "Github"
} |
TITLE passive membrane channel
UNITS {
(mV) = (millivolt)
(mA) = (milliamp)
}
NEURON {
SUFFIX Passive
NONSPECIFIC_CURRENT i
RANGE g, erev
}
PARAMETER {
g = .001 (mho/cm2)
erev = -70 (mV)
}
ASSIGNED { i (mA/cm2)}
BREAKPOINT {
i = g*(v - erev)
}
COMMENT
The passive channel is very simple but illustrates several features of
the interface to NEURON. As a SCoP or hoc model the NEURON block is
ignored. About the only thing you can do with this as an isolated channel
in SCoP is plot the current vs the potential. Notice that stand alone
models require
that all variables be declared, The calculation is done in the BREAKPOINT
block. The intended
semantics of the breakpoint block are that after the block is executed, ALL
variables are consistent with the value of the independent variable (t).
In this case, of course a trivial assignment statement suffices.
PARAMETER declares variables which generally do not change during
solution of the BREAKPOINT block and ASSIGNED declares variables which
get values via assignment statements (as opposed to STATE variables whose
values can only be determined by solving differential or simultaneous
algebraic equations.) The values of PARAMETERs are the default values
and can be changed in SCoP.
The NEURON block serves as the interface to NEURON. One has to imagine
many models linked to NEURON at the same time. Therefore in order to
avoid conflicts with names of variables in other mechanisms a SUFFIX
is applied to all the declared names that are accessible from NEURON.
Accessible PARAMETERs are of two types. Those appearing in the
PARAMETER list become range variables that can be used in any section
in which the mechanism is "insert"ed. PARAMETERs that do not appear in
the PARAMETER list become global scalars which are the same for every
section. ASSIGNED variables and STATE variables also become range variables
that depend on position in a section.
NONSPECIFIC_CURRENT specifies a list of currents not associated with
any particular ion but computed by this model
that affect the calculation of the membrane potential. I.e. a nonspecific
current adds its contribution to the total membrane current.
The following neuron program is suitable for investigating the behavior
of the channel and determining its effect on the membrane.
create a
access a
nseg = 1
insert Passive
g_Passive=.001
erev_Passive=0
proc cur() {
axis(0,1,1,0,.001,1) axis()
plot(1)
for (v=0; v < 1; v=v+.01) {
fcurrent()
plot(v, i_Passive)
}
plt(-1)
}
proc run() {
axis(0,3,3,0,1,1) axis()
t = 0
v=1
plot(1)
while (t < 3) {
plot(t,v)
fadvance()
}
}
/* the cur() procedure uses the fcurrent() function of neuron to calculate
all the currents and conductances with all states (including v) held
constant. In the run() procedure fadvance() integrates all equations
by one time step. In this case the Passive channel in combination with
the default capacitance of 1uF/cm2 give a membrane with a time constant of
1 ms. Thus the voltage decreases exponentially toward 0 from its initial
value of 1.
ENDCOMMENT
| {
"pile_set_name": "Github"
} |
// Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.
#ifndef _OE_MALLOC_H
#define _OE_MALLOC_H
#include <openenclave/bits/defs.h>
#include <openenclave/bits/result.h>
#include <openenclave/bits/types.h>
OE_EXTERNC_BEGIN
typedef void (*oe_allocation_failure_callback_t)(
const char* file,
size_t line,
const char* func,
size_t size);
void oe_set_allocation_failure_callback(
oe_allocation_failure_callback_t function);
/* Dump the list of all in-use allocations */
void oe_debug_malloc_dump(void);
/* Print trace of memory still in use. Return number of blocks allocated. */
size_t oe_debug_malloc_check(void);
//
// If true, oe_debug_malloc_check() is not called on enclave termination.
// To use this mechanism in an enclave:
//
// #include <openenclave/internal/malloc.h>
// .
// .
// .
// oe_disable_debug_malloc_check = true;
//
// The variable must be set prior to enclave termination so it is best to
// set it as soon as the enclave is entered.
//
extern bool oe_disable_debug_malloc_check;
OE_EXTERNC_END
#endif /* _OE_MALLOC_H */
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\QuoteGraphQl\Model\Cart;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Quote\Model\QuoteIdMask;
use Magento\Quote\Model\QuoteIdMaskFactory;
use Magento\Quote\Model\QuoteIdToMaskedQuoteIdInterface;
use Magento\Quote\Model\ResourceModel\Quote\QuoteIdMask as QuoteIdMaskResourceModel;
/**
* Create empty cart for customer
*/
class CreateEmptyCartForCustomer
{
/**
* @var CartManagementInterface
*/
private $cartManagement;
/**
* @var QuoteIdMaskFactory
*/
private $quoteIdMaskFactory;
/**
* @var QuoteIdMaskResourceModel
*/
private $quoteIdMaskResourceModel;
/**
* @var QuoteIdToMaskedQuoteIdInterface
*/
private $quoteIdToMaskedQuoteId;
/**
* @param CartManagementInterface $cartManagement
* @param QuoteIdMaskFactory $quoteIdMaskFactory
* @param QuoteIdMaskResourceModel $quoteIdMaskResourceModel
* @param QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId
*/
public function __construct(
CartManagementInterface $cartManagement,
QuoteIdMaskFactory $quoteIdMaskFactory,
QuoteIdMaskResourceModel $quoteIdMaskResourceModel,
QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId
) {
$this->cartManagement = $cartManagement;
$this->quoteIdMaskFactory = $quoteIdMaskFactory;
$this->quoteIdMaskResourceModel = $quoteIdMaskResourceModel;
$this->quoteIdToMaskedQuoteId = $quoteIdToMaskedQuoteId;
}
/**
* Create empty cart for customer
*
* @param int $customerId
* @param string|null $predefinedMaskedQuoteId
* @return string
*/
public function execute(int $customerId, string $predefinedMaskedQuoteId = null): string
{
$quoteId = (int) $this->cartManagement->createEmptyCartForCustomer($customerId);
if ($predefinedMaskedQuoteId !== null) {
$maskedId = $this->createPredefinedMaskId($quoteId, $predefinedMaskedQuoteId);
} else {
$maskedId = $this->getQuoteMaskId($quoteId);
}
return $maskedId;
}
/**
* Create quote masked id from predefined value
*
* @param int $quoteId
* @param string $maskId
* @return string
* @throws \Magento\Framework\Exception\AlreadyExistsException
*/
private function createPredefinedMaskId(int $quoteId, string $maskId): string
{
/** @var QuoteIdMask $quoteIdMask */
$quoteIdMask = $this->quoteIdMaskFactory->create();
$quoteIdMask->setQuoteId($quoteId);
$quoteIdMask->setMaskedId($maskId);
$this->quoteIdMaskResourceModel->save($quoteIdMask);
return $quoteIdMask->getMaskedId();
}
/**
* Fetch or create masked id for customer's active quote
*
* @param int $quoteId
* @return string
* @throws \Magento\Framework\Exception\AlreadyExistsException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getQuoteMaskId(int $quoteId): string
{
$maskedId = $this->quoteIdToMaskedQuoteId->execute($quoteId);
if ($maskedId === '') {
$quoteIdMask = $this->quoteIdMaskFactory->create();
$quoteIdMask->setQuoteId($quoteId);
$this->quoteIdMaskResourceModel->save($quoteIdMask);
$maskedId = $quoteIdMask->getMaskedId();
}
return $maskedId;
}
}
| {
"pile_set_name": "Github"
} |
// +build !ignore_autogenerated
/*
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 conversion-gen. DO NOT EDIT.
package v1
import (
url "net/url"
unsafe "unsafe"
resource "k8s.io/apimachinery/pkg/api/resource"
conversion "k8s.io/apimachinery/pkg/conversion"
fields "k8s.io/apimachinery/pkg/fields"
labels "k8s.io/apimachinery/pkg/labels"
runtime "k8s.io/apimachinery/pkg/runtime"
intstr "k8s.io/apimachinery/pkg/util/intstr"
watch "k8s.io/apimachinery/pkg/watch"
)
func init() {
localSchemeBuilder.Register(RegisterConversions)
}
// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
if err := s.AddGeneratedConversionFunc((*url.Values)(nil), (*CreateOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_CreateOptions(a.(*url.Values), b.(*CreateOptions), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*url.Values)(nil), (*DeleteOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_DeleteOptions(a.(*url.Values), b.(*DeleteOptions), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*url.Values)(nil), (*ExportOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_ExportOptions(a.(*url.Values), b.(*ExportOptions), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*url.Values)(nil), (*GetOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_GetOptions(a.(*url.Values), b.(*GetOptions), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*url.Values)(nil), (*ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_ListOptions(a.(*url.Values), b.(*ListOptions), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*url.Values)(nil), (*PatchOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_PatchOptions(a.(*url.Values), b.(*PatchOptions), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*url.Values)(nil), (*TableOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_TableOptions(a.(*url.Values), b.(*TableOptions), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*url.Values)(nil), (*UpdateOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_UpdateOptions(a.(*url.Values), b.(*UpdateOptions), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*map[string]string)(nil), (*LabelSelector)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Map_string_To_string_To_v1_LabelSelector(a.(*map[string]string), b.(*LabelSelector), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((**bool)(nil), (*bool)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Pointer_bool_To_bool(a.(**bool), b.(*bool), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((**float64)(nil), (*float64)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Pointer_float64_To_float64(a.(**float64), b.(*float64), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((**int32)(nil), (*int32)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Pointer_int32_To_int32(a.(**int32), b.(*int32), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((**int64)(nil), (*int)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Pointer_int64_To_int(a.(**int64), b.(*int), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((**int64)(nil), (*int64)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Pointer_int64_To_int64(a.(**int64), b.(*int64), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((**intstr.IntOrString)(nil), (*intstr.IntOrString)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Pointer_intstr_IntOrString_To_intstr_IntOrString(a.(**intstr.IntOrString), b.(*intstr.IntOrString), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((**string)(nil), (*string)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Pointer_string_To_string(a.(**string), b.(*string), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((**Duration)(nil), (*Duration)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Pointer_v1_Duration_To_v1_Duration(a.(**Duration), b.(*Duration), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*[]string)(nil), (**DeletionPropagation)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Slice_string_To_Pointer_v1_DeletionPropagation(a.(*[]string), b.(**DeletionPropagation), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*[]string)(nil), (**Time)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Slice_string_To_Pointer_v1_Time(a.(*[]string), b.(**Time), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*[]string)(nil), (*[]int32)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Slice_string_To_Slice_int32(a.(*[]string), b.(*[]int32), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*[]string)(nil), (*IncludeObjectPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Slice_string_To_v1_IncludeObjectPolicy(a.(*[]string), b.(*IncludeObjectPolicy), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*[]string)(nil), (*Time)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_Slice_string_To_v1_Time(a.(*[]string), b.(*Time), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*bool)(nil), (**bool)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_bool_To_Pointer_bool(a.(*bool), b.(**bool), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*fields.Selector)(nil), (*string)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_fields_Selector_To_string(a.(*fields.Selector), b.(*string), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*float64)(nil), (**float64)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_float64_To_Pointer_float64(a.(*float64), b.(**float64), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*int32)(nil), (**int32)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_int32_To_Pointer_int32(a.(*int32), b.(**int32), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*int64)(nil), (**int64)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_int64_To_Pointer_int64(a.(*int64), b.(**int64), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*int)(nil), (**int64)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_int_To_Pointer_int64(a.(*int), b.(**int64), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*intstr.IntOrString)(nil), (**intstr.IntOrString)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_intstr_IntOrString_To_Pointer_intstr_IntOrString(a.(*intstr.IntOrString), b.(**intstr.IntOrString), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*intstr.IntOrString)(nil), (*intstr.IntOrString)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_intstr_IntOrString_To_intstr_IntOrString(a.(*intstr.IntOrString), b.(*intstr.IntOrString), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*labels.Selector)(nil), (*string)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_labels_Selector_To_string(a.(*labels.Selector), b.(*string), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*resource.Quantity)(nil), (*resource.Quantity)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_resource_Quantity_To_resource_Quantity(a.(*resource.Quantity), b.(*resource.Quantity), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*string)(nil), (**string)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_string_To_Pointer_string(a.(*string), b.(**string), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*string)(nil), (*fields.Selector)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_string_To_fields_Selector(a.(*string), b.(*fields.Selector), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*string)(nil), (*labels.Selector)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_string_To_labels_Selector(a.(*string), b.(*labels.Selector), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*url.Values)(nil), (*DeleteOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_url_Values_To_v1_DeleteOptions(a.(*url.Values), b.(*DeleteOptions), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*DeleteOptions)(nil), (*DeleteOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_DeleteOptions_To_v1_DeleteOptions(a.(*DeleteOptions), b.(*DeleteOptions), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*Duration)(nil), (**Duration)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_Duration_To_Pointer_v1_Duration(a.(*Duration), b.(**Duration), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*InternalEvent)(nil), (*WatchEvent)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_InternalEvent_To_v1_WatchEvent(a.(*InternalEvent), b.(*WatchEvent), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*LabelSelector)(nil), (*map[string]string)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_LabelSelector_To_Map_string_To_string(a.(*LabelSelector), b.(*map[string]string), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*ListMeta)(nil), (*ListMeta)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ListMeta_To_v1_ListMeta(a.(*ListMeta), b.(*ListMeta), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*MicroTime)(nil), (*MicroTime)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_MicroTime_To_v1_MicroTime(a.(*MicroTime), b.(*MicroTime), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*Time)(nil), (*Time)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_Time_To_v1_Time(a.(*Time), b.(*Time), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*TypeMeta)(nil), (*TypeMeta)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_TypeMeta_To_v1_TypeMeta(a.(*TypeMeta), b.(*TypeMeta), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*WatchEvent)(nil), (*InternalEvent)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_WatchEvent_To_v1_InternalEvent(a.(*WatchEvent), b.(*InternalEvent), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*WatchEvent)(nil), (*watch.Event)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_WatchEvent_To_watch_Event(a.(*WatchEvent), b.(*watch.Event), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*watch.Event)(nil), (*WatchEvent)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_watch_Event_To_v1_WatchEvent(a.(*watch.Event), b.(*WatchEvent), scope)
}); err != nil {
return err
}
return nil
}
func autoConvert_url_Values_To_v1_CreateOptions(in *url.Values, out *CreateOptions, s conversion.Scope) error {
// WARNING: Field TypeMeta does not have json tag, skipping.
if values, ok := map[string][]string(*in)["dryRun"]; ok && len(values) > 0 {
out.DryRun = *(*[]string)(unsafe.Pointer(&values))
} else {
out.DryRun = nil
}
if values, ok := map[string][]string(*in)["fieldManager"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.FieldManager, s); err != nil {
return err
}
} else {
out.FieldManager = ""
}
return nil
}
// Convert_url_Values_To_v1_CreateOptions is an autogenerated conversion function.
func Convert_url_Values_To_v1_CreateOptions(in *url.Values, out *CreateOptions, s conversion.Scope) error {
return autoConvert_url_Values_To_v1_CreateOptions(in, out, s)
}
func autoConvert_url_Values_To_v1_DeleteOptions(in *url.Values, out *DeleteOptions, s conversion.Scope) error {
// WARNING: Field TypeMeta does not have json tag, skipping.
if values, ok := map[string][]string(*in)["gracePeriodSeconds"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_Pointer_int64(&values, &out.GracePeriodSeconds, s); err != nil {
return err
}
} else {
out.GracePeriodSeconds = nil
}
// INFO: in.Preconditions opted out of conversion generation
if values, ok := map[string][]string(*in)["orphanDependents"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_Pointer_bool(&values, &out.OrphanDependents, s); err != nil {
return err
}
} else {
out.OrphanDependents = nil
}
if values, ok := map[string][]string(*in)["propagationPolicy"]; ok && len(values) > 0 {
if err := Convert_Slice_string_To_Pointer_v1_DeletionPropagation(&values, &out.PropagationPolicy, s); err != nil {
return err
}
} else {
out.PropagationPolicy = nil
}
if values, ok := map[string][]string(*in)["dryRun"]; ok && len(values) > 0 {
out.DryRun = *(*[]string)(unsafe.Pointer(&values))
} else {
out.DryRun = nil
}
return nil
}
func autoConvert_url_Values_To_v1_ExportOptions(in *url.Values, out *ExportOptions, s conversion.Scope) error {
// WARNING: Field TypeMeta does not have json tag, skipping.
if values, ok := map[string][]string(*in)["export"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_bool(&values, &out.Export, s); err != nil {
return err
}
} else {
out.Export = false
}
if values, ok := map[string][]string(*in)["exact"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_bool(&values, &out.Exact, s); err != nil {
return err
}
} else {
out.Exact = false
}
return nil
}
// Convert_url_Values_To_v1_ExportOptions is an autogenerated conversion function.
func Convert_url_Values_To_v1_ExportOptions(in *url.Values, out *ExportOptions, s conversion.Scope) error {
return autoConvert_url_Values_To_v1_ExportOptions(in, out, s)
}
func autoConvert_url_Values_To_v1_GetOptions(in *url.Values, out *GetOptions, s conversion.Scope) error {
// WARNING: Field TypeMeta does not have json tag, skipping.
if values, ok := map[string][]string(*in)["resourceVersion"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.ResourceVersion, s); err != nil {
return err
}
} else {
out.ResourceVersion = ""
}
return nil
}
// Convert_url_Values_To_v1_GetOptions is an autogenerated conversion function.
func Convert_url_Values_To_v1_GetOptions(in *url.Values, out *GetOptions, s conversion.Scope) error {
return autoConvert_url_Values_To_v1_GetOptions(in, out, s)
}
func autoConvert_url_Values_To_v1_ListOptions(in *url.Values, out *ListOptions, s conversion.Scope) error {
// WARNING: Field TypeMeta does not have json tag, skipping.
if values, ok := map[string][]string(*in)["labelSelector"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.LabelSelector, s); err != nil {
return err
}
} else {
out.LabelSelector = ""
}
if values, ok := map[string][]string(*in)["fieldSelector"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.FieldSelector, s); err != nil {
return err
}
} else {
out.FieldSelector = ""
}
if values, ok := map[string][]string(*in)["watch"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_bool(&values, &out.Watch, s); err != nil {
return err
}
} else {
out.Watch = false
}
if values, ok := map[string][]string(*in)["allowWatchBookmarks"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_bool(&values, &out.AllowWatchBookmarks, s); err != nil {
return err
}
} else {
out.AllowWatchBookmarks = false
}
if values, ok := map[string][]string(*in)["resourceVersion"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.ResourceVersion, s); err != nil {
return err
}
} else {
out.ResourceVersion = ""
}
if values, ok := map[string][]string(*in)["timeoutSeconds"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_Pointer_int64(&values, &out.TimeoutSeconds, s); err != nil {
return err
}
} else {
out.TimeoutSeconds = nil
}
if values, ok := map[string][]string(*in)["limit"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_int64(&values, &out.Limit, s); err != nil {
return err
}
} else {
out.Limit = 0
}
if values, ok := map[string][]string(*in)["continue"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.Continue, s); err != nil {
return err
}
} else {
out.Continue = ""
}
return nil
}
// Convert_url_Values_To_v1_ListOptions is an autogenerated conversion function.
func Convert_url_Values_To_v1_ListOptions(in *url.Values, out *ListOptions, s conversion.Scope) error {
return autoConvert_url_Values_To_v1_ListOptions(in, out, s)
}
func autoConvert_url_Values_To_v1_PatchOptions(in *url.Values, out *PatchOptions, s conversion.Scope) error {
// WARNING: Field TypeMeta does not have json tag, skipping.
if values, ok := map[string][]string(*in)["dryRun"]; ok && len(values) > 0 {
out.DryRun = *(*[]string)(unsafe.Pointer(&values))
} else {
out.DryRun = nil
}
if values, ok := map[string][]string(*in)["force"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_Pointer_bool(&values, &out.Force, s); err != nil {
return err
}
} else {
out.Force = nil
}
if values, ok := map[string][]string(*in)["fieldManager"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.FieldManager, s); err != nil {
return err
}
} else {
out.FieldManager = ""
}
return nil
}
// Convert_url_Values_To_v1_PatchOptions is an autogenerated conversion function.
func Convert_url_Values_To_v1_PatchOptions(in *url.Values, out *PatchOptions, s conversion.Scope) error {
return autoConvert_url_Values_To_v1_PatchOptions(in, out, s)
}
func autoConvert_url_Values_To_v1_TableOptions(in *url.Values, out *TableOptions, s conversion.Scope) error {
// WARNING: Field TypeMeta does not have json tag, skipping.
if values, ok := map[string][]string(*in)["-"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_bool(&values, &out.NoHeaders, s); err != nil {
return err
}
} else {
out.NoHeaders = false
}
if values, ok := map[string][]string(*in)["includeObject"]; ok && len(values) > 0 {
if err := Convert_Slice_string_To_v1_IncludeObjectPolicy(&values, &out.IncludeObject, s); err != nil {
return err
}
} else {
out.IncludeObject = ""
}
return nil
}
// Convert_url_Values_To_v1_TableOptions is an autogenerated conversion function.
func Convert_url_Values_To_v1_TableOptions(in *url.Values, out *TableOptions, s conversion.Scope) error {
return autoConvert_url_Values_To_v1_TableOptions(in, out, s)
}
func autoConvert_url_Values_To_v1_UpdateOptions(in *url.Values, out *UpdateOptions, s conversion.Scope) error {
// WARNING: Field TypeMeta does not have json tag, skipping.
if values, ok := map[string][]string(*in)["dryRun"]; ok && len(values) > 0 {
out.DryRun = *(*[]string)(unsafe.Pointer(&values))
} else {
out.DryRun = nil
}
if values, ok := map[string][]string(*in)["fieldManager"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.FieldManager, s); err != nil {
return err
}
} else {
out.FieldManager = ""
}
return nil
}
// Convert_url_Values_To_v1_UpdateOptions is an autogenerated conversion function.
func Convert_url_Values_To_v1_UpdateOptions(in *url.Values, out *UpdateOptions, s conversion.Scope) error {
return autoConvert_url_Values_To_v1_UpdateOptions(in, out, s)
}
| {
"pile_set_name": "Github"
} |
[package]
name = "libeir_intern"
version = "0.1.0"
authors = ["Hans Elias B. Josephsen <me@hansihe.com>"]
edition = "2018"
license = "MIT OR Apache-2.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
libeir_diagnostics = { path = "../libeir_diagnostics" }
rustc-hash = "1.0"
lazy_static = "1.2"
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2012 Hartmut Kaiser. 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)
The tests included in this file were initially taken from the mcpp V2.5
preprocessor validation suite and were modified to fit into the Boost.Wave
unit test requirements.
The original files of the mcpp preprocessor are distributed under the
license reproduced at the end of this file.
=============================================================================*/
// Tests translation limits.
#undef NEST
#define NEST 4
#include "t_5_035_05.hpp"
/*-
* Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <kmatsui@t3.rim.or.jp>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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.
*/
| {
"pile_set_name": "Github"
} |
<Type Name="SelectCursorParentHandler" FullName="Gtk.SelectCursorParentHandler">
<TypeSignature Language="C#" Maintainer="auto" Value="public delegate void SelectCursorParentHandler(object o, SelectCursorParentArgs args);" />
<TypeSignature Language="ILAsm" Value=".class public auto ansi sealed SelectCursorParentHandler extends System.MulticastDelegate" />
<AssemblyInfo>
<AssemblyName>gtk-sharp</AssemblyName>
<AssemblyPublicKey />
</AssemblyInfo>
<ThreadSafetyStatement>Gtk# is thread aware, but not thread safe; See the <link location="node:gtk-sharp/programming/threads">Gtk# Thread Programming</link> for details.</ThreadSafetyStatement>
<Base>
<BaseTypeName>System.Delegate</BaseTypeName>
</Base>
<Parameters>
<Parameter Name="o" Type="System.Object" />
<Parameter Name="args" Type="Gtk.SelectCursorParentArgs" />
</Parameters>
<ReturnValue>
<ReturnType>System.Void</ReturnType>
</ReturnValue>
<Docs>
<param name="o">Event sender.</param>
<param name="args">Event arguments.</param>
<summary>Event handler.</summary>
<remarks>
<para>The <see cref="M:Gtk.TreeView.SelectCursorParent" /> event utilizes this delegate:</para>
<para>Event data is passed via the <see cref="T:Gtk.SelectCursorParentArgs" /> parameter.</para>
<para>To attach a <see cref="T:Gtk.SelectCursorParentHandler" /> to an event, add the SelectCursorParentHandler instance to the event. The methods referenced by the SelectCursorParentHandler instance are invoked whenever the event is raised, until the SelectCursorParentHandler is removed from the event.</para>
</remarks>
</Docs>
<Members />
</Type>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.3">
<title>Contracts on the Producer side 2.2.4.BUILD-SNAPSHOT</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<style>
/* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */
/* Remove comment around @import statement below when using as a custom stylesheet */
/*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}
audio,canvas,video{display:inline-block}
audio:not([controls]){display:none;height:0}
[hidden],template{display:none}
script{display:none!important}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
body{margin:0}
a{background:transparent}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:bold}
dfn{font-style:italic}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}
input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}
input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
body{-webkit-font-smoothing:antialiased}
img,object,svg{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
.center{margin-left:auto;margin-right:auto}
.spread{width:100%}
p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{font-size:1.21875em;line-height:1.6}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:none}
p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol,ul.no-bullet,ol.no-bullet{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ul.no-bullet{list-style:none}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help}
abbr{text-transform:none}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)}
blockquote cite:before{content:"\2014 \0020"}
blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media only screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}
table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede}
table thead,table tfoot{background:#f7f8f7;font-weight:bold}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}
body{tab-size:4}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table}
.clearfix:after,.float-group:after{clear:both}
*:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed}
pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed}
.keyseq{color:rgba(51,51,51,.8)}
kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menu{color:rgba(0,0,0,.8)}
b.button:before,b.button:after{position:relative;top:-1px;font-weight:400}
b.button:before{content:"[";padding:0 3px 0 2px}
b.button:after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table}
#header:after,#content:after,#footnotes:after,#footer:after{clear:both}
#content{margin-top:1.25em}
#content:before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #ddddd8}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px}
#header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span:before{content:"\00a0\2013\00a0"}
#header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark:before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber:after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #efefed;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc li{line-height:1.3334;margin-top:.3334em}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media only screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #efefed;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #efefed;left:auto;right:0}}
@media only screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}
#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:rgba(255,255,255,.8);line-height:1.44}
.sect1{padding-bottom:.625em}
@media only screen and (min-width:768px){.sect1{padding-bottom:1.25em}}
.sect1+.sect1{border-top:1px solid #efefed}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0}
.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{color:rgba(0,0,0,.85)}
table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #ddddd8;color:rgba(0,0,0,.6)}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8}
.sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1}
.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;padding:1em;font-size:.8125em}
.literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto;white-space:pre;word-wrap:normal}
@media only screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}}
@media only screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}}
.literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.listingblock>.content{position:relative}
.listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999}
.listingblock:hover code[data-lang]:before{display:block}
.listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:.5em;color:#999}
.listingblock.terminal pre .command:not([data-prompt]):before{content:"$"}
table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45}
table.pyhltable td.code{padding-left:.75em;padding-right:0}
pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8}
pre.pygments .lineno{display:inline-block;margin-right:.25em}
table.pyhltable .linenodiv{background:none!important;padding-right:0!important}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote:before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.5em;margin-right:.5ex;text-align:right}
.quoteblock .quoteblock{margin-left:0;margin-right:0;padding:.5em 0;border-left:3px solid rgba(0,0,0,.6)}
.quoteblock .quoteblock blockquote{padding:0 0 0 .75em}
.quoteblock .quoteblock blockquote:before{display:none}
.verseblock{margin:0 1em 1.25em 1em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)}
.quoteblock.abstract{margin:0 0 1.25em 0;display:block}
.quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0}
.quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none}
table.tableblock{max-width:100%;border-collapse:separate}
table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0}
table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0}
table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0}
table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0}
table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0}
table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0}
table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0}
table.frame-all{border-width:1px}
table.frame-sides{border-width:0 1px}
table.frame-topbot{border-width:1px 0}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
td>div.verse{white-space:pre}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none}
ul.unstyled,ol.unnumbered,ul.checklist{margin-left:.625em}
ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:.85em}
ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px}
ul.inline{margin:0 auto .625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden}
ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block}
ul.inline>li>*{display:block}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em}
td.hdlist1{font-weight:bold;padding-bottom:1.25em}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist>table tr>td:first-of-type{padding:0 .75em;line-height:1}
.colist>table tr>td:last-of-type{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd}
.imageblock.left,.imageblock[style*="float: left"]{margin:.25em .625em 1.25em 0}
.imageblock.right,.imageblock[style*="float: right"]{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none;display:inline-block}
a.image object{pointer-events:none}
sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super}
sup.footnote a,sup.footnoteref a{text-decoration:none}
sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em 0;border-width:1px 0 0 0}
#footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;text-indent:-1.05em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background-color:#00fafa}
.black{color:#000}
.black-background{background-color:#000}
.blue{color:#0000bf}
.blue-background{background-color:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background-color:#fa00fa}
.gray{color:#606060}
.gray-background{background-color:#7d7d7d}
.green{color:#006000}
.green-background{background-color:#007d00}
.lime{color:#00bf00}
.lime-background{background-color:#00fa00}
.maroon{color:#600000}
.maroon-background{background-color:#7d0000}
.navy{color:#000060}
.navy-background{background-color:#00007d}
.olive{color:#606000}
.olive-background{background-color:#7d7d00}
.purple{color:#600060}
.purple-background{background-color:#7d007d}
.red{color:#bf0000}
.red-background{background-color:#fa0000}
.silver{color:#909090}
.silver-background{background-color:#bcbcbc}
.teal{color:#006060}
.teal-background{background-color:#007d7d}
.white{color:#bfbfbf}
.white-background{background-color:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background-color:#fafa00}
span.icon>.fa{cursor:default}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]:after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility}
h1,h2,p,td.content,span.alt{letter-spacing:-.01em}
p strong,td.content strong,div.footnote strong{letter-spacing:-.005em}
p,blockquote,dt,td.content,span.alt{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@media print{@page{margin:1.25cm .75cm}
*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare):after,a[href^="https:"]:not(.bare):after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]:after{content:" (" attr(title) ")"}
pre,blockquote,tr,img,object,svg{page-break-inside:avoid}
thead{display:table-header-group}
svg{max-width:100%}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #ddddd8!important;padding-bottom:0!important}
.sect1{padding-bottom:0!important}
.sect1+.sect1{border:0!important}
#header>h1:first-child{margin-top:1.25rem}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em 0}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span:before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]:before{display:block}
#footer{background:none!important;padding:0 .9375em}
#footer-text{color:rgba(0,0,0,.6)!important;font-size:.9em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
</style>
<style>
.hidden {
display: none;
}
.switch {
border-width: 1px 1px 0 1px;
border-style: solid;
border-color: #7a2518;
display: inline-block;
}
.switch--item {
padding: 10px;
background-color: #ffffff;
color: #7a2518;
display: inline-block;
cursor: pointer;
}
.switch--item.selected {
background-color: #7a2519;
color: #ffffff;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
<script type="text/javascript">
function addBlockSwitches() {
$('.primary').each(function() {
primary = $(this);
createSwitchItem(primary, createBlockSwitch(primary)).item.addClass("selected");
primary.children('.title').remove();
});
$('.secondary').each(function(idx, node) {
secondary = $(node);
primary = findPrimary(secondary);
switchItem = createSwitchItem(secondary, primary.children('.switch'));
switchItem.content.addClass('hidden');
findPrimary(secondary).append(switchItem.content);
secondary.remove();
});
}
function createBlockSwitch(primary) {
blockSwitch = $('<div class="switch"></div>');
primary.prepend(blockSwitch);
return blockSwitch;
}
function findPrimary(secondary) {
candidate = secondary.prev();
while (!candidate.is('.primary')) {
candidate = candidate.prev();
}
return candidate;
}
function createSwitchItem(block, blockSwitch) {
blockName = block.children('.title').text();
content = block.children('.content').first().append(block.next('.colist'));
item = $('<div class="switch--item">' + blockName + '</div>');
item.on('click', '', content, function(e) {
$(this).addClass('selected');
$(this).siblings().removeClass('selected');
e.data.siblings('.content').addClass('hidden');
e.data.removeClass('hidden');
});
blockSwitch.append(item);
return {'item': item, 'content': content};
}
$(addBlockSwitches);
</script>
</head>
<body class="article toc2 toc-left">
<div id="header">
<h1>Contracts on the Producer side 2.2.4.BUILD-SNAPSHOT</h1>
<div id="toc" class="toc2">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_scenarios">Scenarios</a></li>
<li><a href="#_flow">Flow</a></li>
<li><a href="#_tutorial">Tutorial</a>
<ul class="sectlevel2">
<li><a href="#_consumer_flow_1">Consumer flow 1</a>
<ul class="sectlevel3">
<li><a href="#_writing_the_missing_consumer_http_implementation">Writing the Missing Consumer HTTP Implementation</a></li>
<li><a href="#_turning_on_stub_runner_in_http_consumer_tests">Turning on Stub Runner in HTTP Consumer Tests</a></li>
<li><a href="#_playing_with_the_http_contracts">Playing with the HTTP Contracts</a></li>
</ul>
</li>
<li><a href="#_producer_flow_1">Producer Flow 1</a>
<ul class="sectlevel3">
<li><a href="#_ide_setup">IDE setup</a></li>
<li><a href="#_setting_up_the_spring_cloud_contract_plugin">Setting up the Spring Cloud Contract plugin</a></li>
<li><a href="#_updating_contracts_from_the_pr">Updating Contracts from the PR</a></li>
<li><a href="#_generating_tests_from_contracts">Generating tests from contracts</a></li>
<li><a href="#_fixing_broken_http_tests">Fixing broken HTTP tests</a></li>
</ul>
</li>
<li><a href="#_consumer_flow_2">Consumer flow 2</a></li>
</ul>
</li>
<li><a href="#_solutions">Solutions</a>
<ul class="sectlevel2">
<li><a href="#_written_consumer_tests">Written consumer tests</a></li>
<li><a href="#_adding_spring_cloud_contract_dependency">Adding Spring Cloud Contract Dependency</a></li>
<li><a href="#_proposal_of_simple_contracts_by_consumer">Proposal of simple contracts by consumer</a></li>
<li><a href="#_missing_consumer_controller_code">Missing consumer controller code</a></li>
<li><a href="#_stub_logs">Stub Logs</a></li>
<li><a href="#_beer_request">Beer Request</a></li>
<li><a href="#_missing_listener_code">Missing listener code</a></li>
<li><a href="#_missing_triggers">Missing triggers</a></li>
<li><a href="#_messaging_dsls">Messaging DSLs</a></li>
<li><a href="#_producercontroller_implementation">ProducerController implementation</a></li>
<li><a href="#_beerrestbase">BeerRestBase</a></li>
<li><a href="#_beermessagingbase">BeerMessagingBase</a></li>
<li><a href="#_messaging_implementation">Messaging implementation</a></li>
<li><a href="#_missing_consumer_controller_code_with_discovery">Missing Consumer Controller Code with Discovery</a></li>
</ul>
</li>
<li><a href="#_back_to_the_main_page">Back to the Main Page</a></li>
</ul>
</div>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>In this tutorial, we keep the contracts together with the producer code. On the consumer
side, we be using Service Discovery.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_scenarios">Scenarios</h2>
<div class="sectionbody">
<div class="imageblock">
<div class="content">
<img src="../images/beer_1.png" alt="beer 1">
</div>
<div class="title">Figure 1. Positive beer selling via HTTP</div>
</div>
<div class="paragraph">
<p> 
 </p>
</div>
<div class="imageblock">
<div class="content">
<img src="../images/beer_2.png" alt="beer 2">
</div>
<div class="title">Figure 2. Negative beer selling via HTTP</div>
</div>
<div class="paragraph">
<p> 
 </p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_flow">Flow</h2>
<div class="sectionbody">
<div class="imageblock">
<div class="content">
<img src="../images/flow.png" alt="flow">
</div>
<div class="title">Figure 3. Consumer Driven Contract flow</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_tutorial">Tutorial</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Using Consumer Driven Contracts is like using TDD at the architecture level. We start by
writing a test on the consumer side.</p>
</div>
<div class="sect2">
<h3 id="_consumer_flow_1">Consumer flow 1</h3>
<div class="imageblock">
<div class="content">
<img src="../images/consumer_flow_1.png" alt="consumer flow 1">
</div>
<div class="title">Figure 4. Interact with cloned producer code</div>
</div>
<div class="paragraph">
<p>Let’s go back to our consumer code. We need to look at <code>BeerControllerTest</code> and
<code>BeerController</code>. We know how we would like the API to look, so now we can write the
missing implementation in the <code>BeerController</code>.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
Remember that, in order to use the load balancing features, we need to add the
<code>org.springframework.cloud:spring-cloud-starter-netflix-eureka-client</code> dependency.
</td>
</tr>
</table>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml"><dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency></code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">implementation("org.springframework.cloud:spring-cloud-starter-netflix-eureka-client")</code></pre>
</div>
</div>
<div class="paragraph">
<p>Also, you need to register the <code>RestTemplate</code> bean as <code>@LoadBalanced</code>. Go to
the <code>ClientApplication</code> class and register the bean as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now let’s assume that we call the producer application by using the
<code><a href="http://somenameforproducer/check" class="bare">http://somenameforproducer/check</a></code> URL. You need to provide some properties to tell Stub
Runner that the given service name (in our case, <code>somenameforproducer</code>) should be mapped
to the running HTTP server stub of a given producer. Let’s set those properties.
Stub Runner requires you to set the <code>stubrunner.idsToServiceIds</code> mapping in which the key
is the artifact ID and the value is the service name in the code. You also need to define
the <code>idsToServiceIds</code> property, as shown in the following code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-yml" data-lang="yml">stubrunner:
idsToServiceIds:
beer-api-producer: somenameforproducer</code></pre>
</div>
</div>
<div class="paragraph">
<p>When you call the URL <code><a href="http://somenameforproducer/check" class="bare">http://somenameforproducer/check</a></code>, it will get redirected to a
fake HTTP instance that was started with the <code>beer-api-producer</code> stubs JAR. We know how
the API needs to look, so we can now go ahead and try to write the missing implementation
of the <code>BeerController</code>.</p>
</div>
<div class="sect3">
<h4 id="_writing_the_missing_consumer_http_implementation">Writing the Missing Consumer HTTP Implementation</h4>
<div class="ulist">
<ul>
<li>
<p>Let’s go back to our, consumer’s code - let’s go back to the <code>BeerControllerTest</code> and <code>BeerController</code>.
We know how we would like the API to look like so now we can write the missing implementation in the
<code>BeerController</code>. Let’s assume that the producer application will be running at
<code><a href="http://localhost:8090/" class="bare">http://localhost:8090/</a></code>. Now go ahead and try to write the missing implementation
of the <code>BeerController</code></p>
</li>
<li>
<p>In case of any issues you can check out the <a href="#_missing_consumer_controller_code_with_discovery">solution</a></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_turning_on_stub_runner_in_http_consumer_tests">Turning on Stub Runner in HTTP Consumer Tests</h4>
<div class="ulist">
<ul>
<li>
<p>Now it’s time to turn on the magic! Let’s add the Spring Cloud Starter Contract Stub Runner test dependency.</p>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml"><dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
<scope>test</scope>
</dependency></code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">testImplementation("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")</code></pre>
</div>
</div>
</li>
<li>
<p>We can annotate our test class with
<code>@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.LOCAL, ids = "com.example:beer-api-producer:+:stubs:8090")</code>. What that
will do is:</p>
<div class="ulist">
<ul>
<li>
<p>it will download the stub JARs from Maven local (<code>stubsMode = StubRunnerProperties.StubsMode.LOCAL</code>)</p>
</li>
<li>
<p>it will search for a JAR with coordinates <code>com.example:beer-api-producer</code> with latest version (<code>+</code>)
and <code>stubs</code> classifier. Once it’s found the fake HTTP server stub will be started at port <code>8090</code></p>
</li>
</ul>
</div>
</li>
<li>
<p>Rerun the test - it should automagically pass!</p>
<div class="ulist">
<ul>
<li>
<p>In the logs you will see information about downloading, unpacking and starting stubs (<a href="#_stub_logs">see the logs</a>)</p>
</li>
<li>
<p>What happened is that we could interact with real API without writing a single line of production code</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_playing_with_the_http_contracts">Playing with the HTTP Contracts</h4>
<div class="ulist">
<ul>
<li>
<p>TDD is about red, green and refactor. We went through the first two. Time to refactor the code.
We come to the conclusion that the <code>name</code> field is unnecessary. In the <code>BeerController.java</code> file let’s
create a new class called <code>BeerRequest</code> that will contain only age field and let’s try to send that
to our stubbed producer. (<a href="#_beer_request">Show solution</a>)</p>
</li>
<li>
<p>Let’s run the tests again - what will happen is that the tests will fail. That’s because in the contract
you have explicitly described that you want the <code>name</code> to be there. As you can see all the typos will be
caught during the build time of your project.</p>
<div class="ulist">
<ul>
<li>
<p>The same will happen if you leave the <code>name</code> but change the <code>age</code> to some other value (e.g. 28).
Our stubs at the moment are very strict. We’ll try to fix that in a second</p>
</li>
</ul>
</div>
</li>
<li>
<p>To fix this you need to go back with your IDE to the producer and modify your HTTP contracts.</p>
<div class="ulist">
<ul>
<li>
<p>Just remove the <code>name</code> field from the request body.</p>
</li>
<li>
<p>Spring Cloud Contract allows you to provide dynamic values for parts of body, urls, headers etc.
This is especially useful when working with dates, database ids, UUIDs etc.</p>
</li>
<li>
<p>Let’s open the <code>shouldGrantABeerIfOldEnough.groovy</code> and go to the request body <code>age</code> element</p>
</li>
<li>
<p>Instead of <code>22</code> write <code>$(regex('[2-9][0-9]'))</code>. Now let’s analyze what this is.</p>
<div class="ulist">
<ul>
<li>
<p>In order to tell Spring Cloud Contract that there will be a dynamic value set you have to use either
the <code>$()</code> or <code>value()</code> method. They are equivalent.</p>
</li>
<li>
<p>Next we use <code>regex()</code> method that converts your <code>String</code> into <code>Pattern</code>. In this case we assume
a 2 digit number greater or equal to <code>20</code></p>
</li>
</ul>
</div>
</li>
<li>
<p>Repeat the same process for the <code>shouldRejectABeerIfTooYoung.groovy</code> contract but change the
regular expression to <code>[0-1][0-9]</code></p>
</li>
<li>
<p>Run the building with test skipping and check the output of stubs. You’ll see that the generated
mappings have changed from equality check in JSON Path to regular expression check</p>
</li>
<li>
<p>Go back to the consumer code and run the <code>BeerControlerTest</code> again. This time it should pass. You can
also change the values of age to e.g. <code>45</code> for the positive case and <code>11</code> for the negative on.</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>Congratulations! As a consumer, you have successfully used the API of the producer for
both HTTP and messaging. Now you can file a pull request (PR) to the producer code with
the proposal of the contract,</p>
</div>
<div class="paragraph">
<p>Let’s switch to the producer side.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_producer_flow_1">Producer Flow 1</h3>
<div class="imageblock">
<div class="content">
<img src="../images/producer_flow_1.png" alt="producer flow 1">
</div>
<div class="title">Figure 5. Producer takes over the PR, writes missing impl and merges the PR</div>
</div>
<div class="sect3">
<h4 id="_ide_setup">IDE setup</h4>
<div class="ulist">
<ul>
<li>
<p>Open in your IDE the <code>producer</code> project (either via Maven or Gradle)</p>
</li>
<li>
<p>We’re assuming that we’ve taken over the PR. Example of how to achieve that in "real life" for a PR
that got submitted to via a branch called <code>the_pr</code> looks like this:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">git fetch origin
git checkout -b the_pr origin/the_pr
git merge master</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>The idea of Spring Cloud Contract is about stub and contract validity. Right now we have a set of
contracts defined but we haven’t tested it against the producer side. Time to change that!</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_setting_up_the_spring_cloud_contract_plugin">Setting up the Spring Cloud Contract plugin</h4>
<div class="ulist">
<ul>
<li>
<p>Spring Cloud Contract can generate tests from your contracts to ensure that your implementation’s API
is compatible with the defined contract. Let’s set up the project to start generating tests.</p>
<div class="ulist">
<ul>
<li>
<p>Spring Cloud Contract needs a base class that all of the generated tests will extend. Currently
we support 3 different ways of defining a base class (you can read more about this in the
Spring Cloud Contract documentation for <a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_configure_plugin">Gradle</a>
and <a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_configure_plugin_2">Maven</a>)</p>
<div class="ulist">
<ul>
<li>
<p>a single class for all tests</p>
</li>
<li>
<p>convention based naming (takes 2 last package names and appends <code>Base</code>. Having a contract
<code>src/test/resources/contracts/foo/bar/shouldDoSth.groovy</code> would create a test class called
<code>BarTest</code> that would extend <code>FooBarBase</code> class.</p>
</li>
<li>
<p>manual mapping (you can state that contracts matching certain regular expression will have to
have a base class with fully qualified name equal to X)</p>
</li>
</ul>
</div>
</li>
<li>
<p>In the following example we’ll play with convention based naming</p>
<div class="ulist">
<ul>
<li>
<p>For Maven under the plugin setup you have to set up the plugin configuration
<code><configuration><packageWithBaseClasses>com.example</packageWithBaseClasses></configuration></code></p>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml"><plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${spring-cloud-contract.version}</version>
<extensions>true</extensions>
<configuration>
<packageWithBaseClasses>com.example</packageWithBaseClasses>
</configuration>
</plugin></code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">contracts {
packageWithBaseClasses = 'com.example'
}</code></pre>
</div>
</div>
</li>
<li>
<p>In both cases passing of that value tells the plugin that a given base class is available under
the <code>com.example</code> package</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_updating_contracts_from_the_pr">Updating Contracts from the PR</h4>
</div>
<div class="sect3">
<h4 id="_generating_tests_from_contracts">Generating tests from contracts</h4>
<div class="ulist">
<ul>
<li>
<p>Let’s generate the tests! Just call:</p>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">$ ./mvnw clean install</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">$ ./gradlew clean build publishToMavenLocal</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Suddenly some tests should start failing. Those tests are the autogenerated tests created
by Spring Cloud Contract</p>
</li>
<li>
<p>The tests lay under <code>/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/beer</code>
in <code>target</code> for Maven or <code>build</code> for Gradle</p>
</li>
<li>
<p>There will be a test for each folder in which you store your contracts. The name of the test class
will be the name of that folder</p>
</li>
<li>
<p>Each of the contracts will be a single test inside that test class</p>
</li>
<li>
<p>If you check out the generated tests you’ll notice that the dynamic parts of the <code>request</code> part
of the contract got converted to a concrete value. Any dynamic bits on the <code>response</code> side would be
converted into matchers.</p>
</li>
</ul>
</div>
</li>
<li>
<p>Time to fix the broken tests. We need to do that by providing the missing implementation.</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_fixing_broken_http_tests">Fixing broken HTTP tests</h4>
<div class="ulist">
<ul>
<li>
<p>Let’s start with HTTP</p>
<div class="ulist">
<ul>
<li>
<p>First let’s write the missing implementation in <code>ProducerController</code>. The logic to be written
is extremely simple - if the <code>personCheckingService.shouldGetBeer(…​)</code> returns <code>true</code> then we
should return <code>new Response(BeerCheckStatus.OK)</code>. Otherwise <code>new Response(BeerCheckStatus.NOT_OK)</code>.
(<a href="#_producerController_implementation">Show solution</a>)</p>
</li>
</ul>
</div>
</li>
<li>
<p>Let’s fix the <code>BeerRestBase</code> class now</p>
<div class="ulist">
<ul>
<li>
<p>The idea of CDC is <strong>NOT TO TEST</strong> every single feature. Contract tests are there to see if the API
is matched, <strong>NOT</strong> that the feature is working. That’s why we shouldn’t be accessing databases etc.
That means that we will work with mock of the <code>PersonCheckingService</code>. (<a href="#_beerrestbase">Show solution</a>)</p>
</li>
<li>
<p>Let’s annotate the test class with <code>@RunWith(MockitoJUnitRunner.class)</code> to enable Mockito runner.</p>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@RunWith(MockitoJUnitRunner.class)
public abstract class BeerRestBase {
...
}</code></pre>
</div>
</div>
</li>
<li>
<p>We’ll want to test the <code>ProducerController</code> so we can create a field <code>@InjectMocks ProducerController
producerController</code>. Mockito will inject any mocks for us via the constructor.</p>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java"> @Mock PersonCheckingService personCheckingService;
@InjectMocks ProducerController producerController;
@Before
public void setup() {
given(personCheckingService.shouldGetBeer(argThat(oldEnough()))).willReturn(true);
}</code></pre>
</div>
</div>
</li>
<li>
<p>It won’t compile cause we don’t have the <code>oldEnough()</code> method but don’t worry. So this line stubs
the <code>shouldGetBeer</code> method in such a way that if the user is old enough then the method will return
true. Let’s now add the <code>oldEnoughMethod()</code></p>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java"> private TypeSafeMatcher<PersonToCheck> oldEnough() {
return new TypeSafeMatcher<PersonToCheck>() {
@Override protected boolean matchesSafely(PersonToCheck personToCheck) {
return personToCheck.age >= 20;
}
@Override public void describeTo(Description description) {
}
};
}</code></pre>
</div>
</div>
</li>
<li>
<p>We’re using the <code>TypeSafeMatcher</code> from Hamcrest to create a matcher for <code>PersonToCheck</code>. In this case
if the person to check is older or is 20 then the method <code>shouldGetBeer</code> method will return <code>true</code>.</p>
</li>
<li>
<p>Now we need to configure <a href="http://rest-assured.io/">RestAssured</a> that is used by Spring Cloud Contract
to send requests. In our case we want to profit from MockMvc. In order to set the <code>ProducerController</code>
with RestAssured it’s enough to call <code>RestAssuredMockMvc.standaloneSetup(producerController);</code></p>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@RunWith(MockitoJUnitRunner.class)
public abstract class BeerRestBase {
@Mock PersonCheckingService personCheckingService;
@InjectMocks ProducerController producerController;
@Before
public void setup() {
given(personCheckingService.shouldGetBeer(argThat(oldEnough()))).willReturn(true);
RestAssuredMockMvc.standaloneSetup(producerController);
}
private TypeSafeMatcher<PersonToCheck> oldEnough() {
return new TypeSafeMatcher<PersonToCheck>() {
@Override protected boolean matchesSafely(PersonToCheck personToCheck) {
return personToCheck.age >= 20;
}
@Override public void describeTo(Description description) {
}
};
}
}</code></pre>
</div>
</div>
</li>
<li>
<p>With mocks and RestAssured setup - we’re ready to run our HTTP based autogenerated tests</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>Now you could merge the PR to master, and your CI system would build a fat jar and the
stubs.</p>
</div>
<div class="paragraph">
<p>Congratulations! You’ve completed the producer side of this tutorial.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_consumer_flow_2">Consumer flow 2</h3>
<div class="imageblock">
<div class="content">
<img src="../images/consumer_flow_2.png" alt="consumer flow 2">
</div>
<div class="title">Figure 6. Switch to work online</div>
</div>
<div class="ulist">
<ul>
<li>
<p>After merging the PR the producer’s stubs reside in some Artifactory / Nexus instance</p>
</li>
<li>
<p>As consumers we no longer want to retrieve the stubs from our local Maven repository -
we’d like to download them from the remote location</p>
</li>
<li>
<p>To do that (we won’t do that for the tutorial but you would do it in your "production"
code) it’s enough to pass the <code>repositoryRoot</code> parameter and set the
<code>stubsMode</code> to <code>StubRunnerProperties.StubsMode.REMOTE</code></p>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
@AutoConfigureJsonTesters
@AutoConfigureStubRunner(
repositoryRoot="http://www.foo.com/bar,
ids = "com.example:beer-api-producer:+:stubs:8090",
stubsMode = StubRunnerProperties.StubsMode.REMOTE
)
@DirtiesContext
public class YourTestOnTheConsumerSide extends AbstractTest {
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Another option is to pass the property <code>stubrunner.repositoryRoot</code> either as a
system / environment property, or via an <code>application.yml</code> and <code>stubrunner.stubs-mode</code>
equal to <code>remote</code></p>
</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_solutions">Solutions</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_written_consumer_tests">Written consumer tests</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java"> @Test
public void should_give_me_a_beer_when_im_old_enough() throws Exception {
//remove::start[]
this.mockMvc.perform(MockMvcRequestBuilders.post("/beer")
.contentType(MediaType.APPLICATION_JSON)
.content(this.json.write(new Person("marcin", 22)).getJson()))
.andExpect(status().isOk())
.andExpect(content().string("THERE YOU GO"));
//remove::end[]
}
@Test
public void should_reject_a_beer_when_im_too_young() throws Exception {
//remove::start[]
this.mockMvc.perform(MockMvcRequestBuilders.post("/beer")
.contentType(MediaType.APPLICATION_JSON)
.content(this.json.write(new Person("marcin", 17)).getJson()))
.andExpect(status().isOk())
.andExpect(content().string("GET LOST"));
//remove::end[]
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_adding_spring_cloud_contract_dependency">Adding Spring Cloud Contract Dependency</h3>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml"><dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
<scope>test</scope>
</dependency></code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">testImplementation("org.springframework.cloud:spring-cloud-starter-contract-verifier")</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_proposal_of_simple_contracts_by_consumer">Proposal of simple contracts by consumer</h3>
<div class="paragraph">
<p><strong>HTTP communication</strong></p>
</div>
<div class="listingblock primary">
<div class="title">Old Enough</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">// rest/shouldGrantABeerIfOldEnough.groovy
org.springframework.cloud.contract.spec.Contract.make {
description("""
Represents a successful scenario of getting a beer
```
given:
client is old enough
when:
he applies for a beer
then:
we'll grant him the beer
```
""")
request {
method 'POST'
url '/check'
body(
age: 22,
name: "marcin"
)
headers {
contentType(applicationJson())
}
}
response {
status 200
body("""
{
"status": "OK"
}
""")
headers {
contentType(applicationJson())
}
}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Too Young</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">// rest/shouldRejectABeerIfTooYoung.groovy
org.springframework.cloud.contract.spec.Contract.make {
description("""
Represents a successful scenario of getting a beer
```
given:
client is old enough
when:
he applies for a beer
then:
we'll grant him the beer
```
""")
request {
method 'POST'
url '/check'
body(
age: 17,
name: "marcin"
)
headers {
contentType(applicationJson())
}
}
response {
status 200
body("""
{
"status": "NOT_OK"
}
""")
headers {
contentType(applicationJson())
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Messaging communication</strong></p>
</div>
<div class="listingblock primary">
<div class="title">Positive Verification</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">// messaging/shouldSendAcceptedVerification.groovy
org.springframework.cloud.contract.spec.Contract.make {
description("""
Sends a positive verification message when person is eligible to get the beer
```
given:
client is old enough
when:
he applies for a beer
then:
we'll send a message with a positive verification
```
""")
// Label by means of which the output message can be triggered
label 'accepted_verification'
// output message of the contract
outputMessage {
// destination to which the output message will be sent
sentTo 'verifications'
// the body of the output message
body(
eligible: true
)
headers {
header("contentType", applicationJsonUtf8())
}
}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Negative Verification</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">// messaging/shouldSendRejectedVerification.groovy
org.springframework.cloud.contract.spec.Contract.make {
description("""
Sends a negative verification message when person is not eligible to get the beer
```
given:
client is too young
when:
he applies for a beer
then:
we'll send a message with a negative verification
```
""")
// Label by means of which the output message can be triggered
label 'rejected_verification'
// output message of the contract
outputMessage {
// destination to which the output message will be sent
sentTo 'verifications'
// the body of the output message
body(
eligible: false
)
headers {
header("contentType", applicationJsonUtf8())
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_missing_consumer_controller_code">Missing consumer controller code</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java"> ResponseEntity<Response> response = this.restTemplate.exchange(
RequestEntity
.post(URI.create("http://localhost:" + this.port + "/check"))
.contentType(MediaType.APPLICATION_JSON)
.body(person),
Response.class);
switch (response.getBody().status) {
case OK:
return "THERE YOU GO";
default:
return "GET LOST";
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_logs">Stub Logs</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">2017-05-11 12:16:51.146 INFO 4693 --- [ main] o.s.c.c.s.StubDownloaderBuilderProvider : Will download stubs using Aether
2017-05-11 12:16:51.148 INFO 4693 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Remote repos not passed but the switch to work offline was set. Stubs will be used from your local Maven repository.
2017-05-11 12:16:51.291 INFO 4693 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is [+] - will try to resolve the latest version
2017-05-11 12:16:51.308 INFO 4693 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is [0.0.1-SNAPSHOT]
2017-05-11 12:16:51.309 INFO 4693 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact [com.example:{producer_artifact}:jar:stubs:0.0.1-SNAPSHOT] using remote repositories []
2017-05-11 12:16:51.317 INFO 4693 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact [com.example:{producer_artifact}:jar:stubs:0.0.1-SNAPSHOT] to /home/marcin/.m2/repository/com/example/{producer_artifact}/0.0.1-SNAPSHOT/{producer_artifact}-0.0.1-SNAPSHOT-stubs.jar
2017-05-11 12:16:51.322 INFO 4693 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/home/marcin/.m2/repository/com/example/{producer_artifact}/0.0.1-SNAPSHOT/{producer_artifact}-0.0.1-SNAPSHOT-stubs.jar]
2017-05-11 12:16:51.327 INFO 4693 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/tmp/contracts9053257535983128167]
2017-05-11 12:16:52.608 INFO 4693 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@699e0bf0: startup date [Thu May 11 12:16:52 CEST 2017]; root of context hierarchy
2017-05-11 12:16:52.684 INFO 4693 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-05-11 12:16:52.837 INFO 4693 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8090 (http)
2017-05-11 12:16:52.851 INFO 4693 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-05-11 12:16:52.853 INFO 4693 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.14
2017-05-11 12:16:52.975 INFO 4693 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-05-11 12:16:52.975 INFO 4693 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 367 ms
2017-05-11 12:16:52.996 INFO 4693 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'stub' to [/]
2017-05-11 12:16:53.000 INFO 4693 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'admin' to [/__admin/*]
2017-05-11 12:16:53.135 INFO 4693 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8090 (http)
2017-05-11 12:16:53.139 INFO 4693 --- [ main] o.s.c.contract.stubrunner.StubServer : Started stub server for project [com.example:{producer_artifact}:0.0.1-SNAPSHOT:stubs] on port 8090</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_beer_request">Beer Request</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">class BeerRequest {
public int age;
public BeerRequest(int age) {
this.age = age;
}
public BeerRequest() {
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_missing_listener_code">Missing listener code</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java"> if (verification.eligible) {
this.eligibleCounter.incrementAndGet();
} else {
this.notEligibleCounter.incrementAndGet();
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_missing_triggers">Missing triggers</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java"> @Test public void should_increase_the_eligible_counter_when_verification_was_accepted() throws Exception {
int initialCounter = this.listener.eligibleCounter.get();
//remove::start[]
this.stubTrigger.trigger("accepted_verification");
//remove::end[]
then(this.listener.eligibleCounter.get()).isGreaterThan(initialCounter);
}
@Test public void should_increase_the_noteligible_counter_when_verification_was_rejected() throws Exception {
int initialCounter = this.listener.notEligibleCounter.get();
//remove::start[]
this.stubTrigger.trigger("rejected_verification");
//remove::end[]
then(this.listener.notEligibleCounter.get()).isGreaterThan(initialCounter);
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_messaging_dsls">Messaging DSLs</h3>
<div class="listingblock primary">
<div class="title">Positive Verification</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">// messaging/shouldSendAcceptedVerification.groovy
org.springframework.cloud.contract.spec.Contract.make {
description("""
Sends a positive verification message when person is eligible to get the beer
```
given:
client is old enough
when:
he applies for a beer
then:
we'll send a message with a positive verification
```
""")
// Label by means of which the output message can be triggered
label 'accepted_verification'
// input to the contract
input {
// the contract will be triggered by a method
triggeredBy('clientIsOldEnough()')
}
// output message of the contract
outputMessage {
// destination to which the output message will be sent
sentTo 'verifications'
// the body of the output message
body(
eligible: true
)
headers {
header("contentType", applicationJsonUtf8())
}
}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Negative Verification</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">// messaging/shouldSendRejectedVerification.groovy
org.springframework.cloud.contract.spec.Contract.make {
description("""
Sends a negative verification message when person is not eligible to get the beer
```
given:
client is too young
when:
he applies for a beer
then:
we'll send a message with a negative verification
```
""")
// Label by means of which the output message can be triggered
label 'rejected_verification'
// input to the contract
input {
// the contract will be triggered by a method
triggeredBy('clientIsTooYoung()')
}
// output message of the contract
outputMessage {
// destination to which the output message will be sent
sentTo 'verifications'
// the body of the output message
body(
eligible: false
)
headers {
header("contentType", applicationJsonUtf8())
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_producercontroller_implementation">ProducerController implementation</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">if (personCheckingService.shouldGetBeer(personToCheck)) {
return new Response(BeerCheckStatus.OK);
}
return new Response(BeerCheckStatus.NOT_OK);</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_beerrestbase">BeerRestBase</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@RunWith(MockitoJUnitRunner.class)
public abstract class BeerRestBase {
@Mock PersonCheckingService personCheckingService;
@InjectMocks ProducerController producerController;
@Before
public void setup() {
given(personCheckingService.shouldGetBeer(argThat(oldEnough()))).willReturn(true);
RestAssuredMockMvc.standaloneSetup(producerController);
}
private TypeSafeMatcher<PersonToCheck> oldEnough() {
return new TypeSafeMatcher<PersonToCheck>() {
@Override protected boolean matchesSafely(PersonToCheck personToCheck) {
return personToCheck.age >= 20;
}
@Override public void describeTo(Description description) {
}
};
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_beermessagingbase">BeerMessagingBase</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProducerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.NONE)
@AutoConfigureMessageVerifier
public abstract class BeerMessagingBase {
@Inject MessageVerifier messaging;
@Autowired PersonCheckingService personCheckingService;
@Before
public void setup() {
// let's clear any remaining messages
// output == destination or channel name
this.messaging.receive("output", 100, TimeUnit.MILLISECONDS);
}
public void clientIsOldEnough() {
personCheckingService.shouldGetBeer(new PersonToCheck(25));
}
public void clientIsTooYoung() {
personCheckingService.shouldGetBeer(new PersonToCheck(5));
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_messaging_implementation">Messaging implementation</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java"> boolean shouldGetBeer = personToCheck.age >= 20;
this.source.output().send(MessageBuilder.withPayload(new Verification(shouldGetBeer)).build());
return shouldGetBeer;</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_missing_consumer_controller_code_with_discovery">Missing Consumer Controller Code with Discovery</h3>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java"> ResponseEntity<Response> response = this.restTemplate.exchange(
RequestEntity
.post(URI.create("http://somenameforproducer/check"))
.contentType(MediaType.APPLICATION_JSON)
.body(person),
Response.class);
switch (response.getBody().status) {
case OK:
return "THERE YOU GO";
default:
return "GET LOST";
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_back_to_the_main_page">Back to the Main Page</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="../workshops.html">Click here to go back to the main page</a></p>
</div>
</div>
</div>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.js"></script>
<script>prettyPrint()</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2008, Harald Kuhr
* 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 the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.image;
import magick.ImageType;
import magick.MagickException;
import magick.MagickImage;
import magick.PixelPacket;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.*;
/**
* Utility for converting JMagick {@code MagickImage}s to standard Java
* {@code BufferedImage}s and back.
* <p>
* <em>NOTE: This class is considered an implementation detail and not part of
* the public API. This class is subject to change without further notice.
* You have been warned. :-)</em>
* </p>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/MagickUtil.java#4 $
*/
public final class MagickUtil {
// IMPORTANT NOTE: Disaster happens if any of these constants are used outside this class
// because you then have a dependency on MagickException (this is due to Java class loading
// and initialization magic).
// Do not use outside this class. If the constants need to be shared, move to Magick or ImageUtil.
/** Color Model usesd for bilevel (B/W) */
private static final IndexColorModel CM_MONOCHROME = MonochromeColorModel.getInstance();
/** Color Model usesd for raw ABGR */
private static final ColorModel CM_COLOR_ALPHA =
new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8, 8, 8, 8},
true, true, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
/** Color Model usesd for raw BGR */
private static final ColorModel CM_COLOR_OPAQUE =
new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8, 8, 8},
false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
/** Color Model usesd for raw RGB */
//private static final ColorModel CM_COLOR_RGB = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x0);
/** Color Model usesd for raw GRAY + ALPHA */
private static final ColorModel CM_GRAY_ALPHA =
new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY),
true, true, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
/** Color Model usesd for raw GRAY */
private static final ColorModel CM_GRAY_OPAQUE =
new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY),
false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
/** Band offsets for raw ABGR */
private static final int[] BAND_OFF_TRANS = new int[] {3, 2, 1, 0};
/** Band offsets for raw BGR */
private static final int[] BAND_OFF_OPAQUE = new int[] {2, 1, 0};
/** The point at {@code 0, 0} */
private static final Point LOCATION_UPPER_LEFT = new Point(0, 0);
private static final boolean DEBUG = Magick.DEBUG;
// Only static members and methods
private MagickUtil() {}
/**
* Converts a {@code MagickImage} to a {@code BufferedImage}.
* <p>
* The conversion depends on {@code pImage}'s {@code ImageType}:
* </p>
* <dl>
* <dt>{@code ImageType.BilevelType}</dt>
* <dd>{@code BufferedImage} of type {@code TYPE_BYTE_BINARY}</dd>
*
* <dt>{@code ImageType.GrayscaleType}</dt>
* <dd>{@code BufferedImage} of type {@code TYPE_BYTE_GRAY}</dd>
* <dt>{@code ImageType.GrayscaleMatteType}</dt>
* <dd>{@code BufferedImage} of type {@code TYPE_USHORT_GRAY}</dd>
*
* <dt>{@code ImageType.PaletteType}</dt>
* <dd>{@code BufferedImage} of type {@code TYPE_BYTE_BINARY} (for images
* with a palette of <= 16 colors) or {@code TYPE_BYTE_INDEXED}</dd>
* <dt>{@code ImageType.PaletteMatteType}</dt>
* <dd>{@code BufferedImage} of type {@code TYPE_BYTE_BINARY} (for images
* with a palette of <= 16 colors) or {@code TYPE_BYTE_INDEXED}</dd>
*
* <dt>{@code ImageType.TrueColorType}</dt>
* <dd>{@code BufferedImage} of type {@code TYPE_3BYTE_BGR}</dd>
* <dt>{@code ImageType.TrueColorPaletteType}</dt>
* <dd>{@code BufferedImage} of type {@code TYPE_4BYTE_ABGR}</dd>
* </dl>
*
* @param pImage the original {@code MagickImage}
* @return a new {@code BufferedImage}
*
* @throws IllegalArgumentException if {@code pImage} is {@code null}
* or if the {@code ImageType} is not one mentioned above.
* @throws MagickException if an exception occurs during conversion
*
* @see BufferedImage
*/
public static BufferedImage toBuffered(MagickImage pImage) throws MagickException {
if (pImage == null) {
throw new IllegalArgumentException("image == null");
}
long start = 0L;
if (DEBUG) {
start = System.currentTimeMillis();
}
BufferedImage image = null;
try {
switch (pImage.getImageType()) {
case ImageType.BilevelType:
image = bilevelToBuffered(pImage);
break;
case ImageType.GrayscaleType:
image = grayToBuffered(pImage, false);
break;
case ImageType.GrayscaleMatteType:
image = grayToBuffered(pImage, true);
break;
case ImageType.PaletteType:
image = paletteToBuffered(pImage, false);
break;
case ImageType.PaletteMatteType:
image = paletteToBuffered(pImage, true);
break;
case ImageType.TrueColorType:
image = rgbToBuffered(pImage, false);
break;
case ImageType.TrueColorMatteType:
image = rgbToBuffered(pImage, true);
break;
case ImageType.ColorSeparationType:
image = cmykToBuffered(pImage, false);
break;
case ImageType.ColorSeparationMatteType:
image = cmykToBuffered(pImage, true);
break;
case ImageType.OptimizeType:
default:
throw new IllegalArgumentException("Unknown JMagick image type: " + pImage.getImageType());
}
}
finally {
if (DEBUG) {
long time = System.currentTimeMillis() - start;
System.out.println("Converted JMagick image type: " + pImage.getImageType() + " to BufferedImage: " + image);
System.out.println("Conversion to BufferedImage: " + time + " ms");
}
}
return image;
}
/**
* Converts a {@code BufferedImage} to a {@code MagickImage}.
* <p>
* The conversion depends on {@code pImage}'s {@code ColorModel}:
* </p>
* <dl>
* <dt>{@code IndexColorModel} with 1 bit b/w</dt>
* <dd>{@code MagickImage} of type {@code ImageType.BilevelType}</dd>
* <dt>{@code IndexColorModel} > 1 bit,</dt>
* <dd>{@code MagickImage} of type {@code ImageType.PaletteType}
* or {@code MagickImage} of type {@code ImageType.PaletteMatteType}
* depending on <tt>ColorModel.getAlpha()</tt></dd>
*
* <dt>{@code ColorModel.getColorSpace().getType() == ColorSpace.TYPE_GRAY}</dt>
* <dd>{@code MagickImage} of type {@code ImageType.GrayscaleType}
* or {@code MagickImage} of type {@code ImageType.GrayscaleMatteType}
* depending on <tt>ColorModel.getAlpha()</tt></dd>
*
* <dt>{@code ColorModel.getColorSpace().getType() == ColorSpace.TYPE_RGB}</dt>
* <dd>{@code MagickImage} of type {@code ImageType.TrueColorType}
* or {@code MagickImage} of type {@code ImageType.TrueColorPaletteType}</dd>
* </dl>
*
* @param pImage the original {@code BufferedImage}
* @return a new {@code MagickImage}
*
* @throws IllegalArgumentException if {@code pImage} is {@code null}
* or if the {@code ColorModel} is not one mentioned above.
* @throws MagickException if an exception occurs during conversion
*
* @see BufferedImage
*/
public static MagickImage toMagick(BufferedImage pImage) throws MagickException {
if (pImage == null) {
throw new IllegalArgumentException("image == null");
}
long start = 0L;
if (DEBUG) {
start = System.currentTimeMillis();
}
try {
ColorModel cm = pImage.getColorModel();
if (cm instanceof IndexColorModel) {
// Handles both BilevelType, PaletteType and PaletteMatteType
return indexedToMagick(pImage, (IndexColorModel) cm, cm.hasAlpha());
}
switch (cm.getColorSpace().getType()) {
case ColorSpace.TYPE_GRAY:
// Handles GrayType and GrayMatteType
return grayToMagick(pImage, cm.hasAlpha());
case ColorSpace.TYPE_RGB:
// Handles TrueColorType and TrueColorMatteType
return rgbToMagic(pImage, cm.hasAlpha());
case ColorSpace.TYPE_CMY:
case ColorSpace.TYPE_CMYK:
case ColorSpace.TYPE_HLS:
case ColorSpace.TYPE_HSV:
// Other types not supported yet
default:
throw new IllegalArgumentException("Unknown buffered image type: " + pImage);
}
}
finally {
if (DEBUG) {
long time = System.currentTimeMillis() - start;
System.out.println("Conversion to MagickImage: " + time + " ms");
}
}
}
private static MagickImage rgbToMagic(BufferedImage pImage, boolean pAlpha) throws MagickException {
MagickImage image = new MagickImage();
BufferedImage buffered = ImageUtil.toBuffered(pImage, pAlpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR);
// Need to get data of sub raster, not the full data array, this is
// just a convenient way
Raster raster;
if (buffered.getRaster().getParent() != null) {
raster = buffered.getData(new Rectangle(buffered.getWidth(), buffered.getHeight()));
}
else {
raster = buffered.getRaster();
}
image.constituteImage(buffered.getWidth(), buffered.getHeight(), pAlpha ? "ABGR" : "BGR",
((DataBufferByte) raster.getDataBuffer()).getData());
return image;
}
private static MagickImage grayToMagick(BufferedImage pImage, boolean pAlpha) throws MagickException {
MagickImage image = new MagickImage();
// TODO: Make a fix for TYPE_USHORT_GRAY
// The code below does not seem to work (JMagick issues?)...
/*
if (pImage.getType() == BufferedImage.TYPE_USHORT_GRAY) {
short[] data = ((DataBufferUShort) pImage.getRaster().getDataBuffer()).getData();
int[] intData = new int[data.length];
for (int i = 0; i < data.length; i++) {
intData[i] = (data[i] & 0xffff) * 0xffff;
}
image.constituteImage(pImage.getWidth(), pImage.getHeight(), "I", intData);
System.out.println("storageClass: " + image.getStorageClass());
System.out.println("depth: " + image.getDepth());
System.out.println("imageType: " + image.getImageType());
}
else {
*/
BufferedImage buffered = ImageUtil.toBuffered(pImage, pAlpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_BYTE_GRAY);
// Need to get data of sub raster, not the full data array, this is
// just a convenient way
Raster raster;
if (buffered.getRaster().getParent() != null) {
raster = buffered.getData(new Rectangle(buffered.getWidth(), buffered.getHeight()));
}
else {
raster = buffered.getRaster();
}
image.constituteImage(buffered.getWidth(), buffered.getHeight(), pAlpha ? "ABGR" : "I", ((DataBufferByte) raster.getDataBuffer()).getData());
//}
return image;
}
private static MagickImage indexedToMagick(BufferedImage pImage, IndexColorModel pColorModel, boolean pAlpha) throws MagickException {
MagickImage image = rgbToMagic(pImage, pAlpha);
int mapSize = pColorModel.getMapSize();
image.setNumberColors(mapSize);
return image;
}
/*
public static MagickImage toMagick(BufferedImage pImage) throws MagickException {
if (pImage == null) {
throw new IllegalArgumentException("image == null");
}
final int width = pImage.getWidth();
final int height = pImage.getHeight();
// int ARGB -> byte RGBA conversion
// NOTE: This is ImageMagick Q16 compatible raw RGBA format with 16 bits/sample...
// For a Q8 build, we could probably go with half the space...
// NOTE: This is close to insanity, as it wastes extreme ammounts of memory
final int[] argb = new int[width];
final byte[] raw16 = new byte[width * height * 8];
for (int y = 0; y < height; y++) {
// Fetch one line of ARGB data
pImage.getRGB(0, y, width, 1, argb, 0, width);
for (int x = 0; x < width; x++) {
int pixel = (x + (y * width)) * 8;
raw16[pixel ] = (byte) ((argb[x] >> 16) & 0xff); // R
raw16[pixel + 2] = (byte) ((argb[x] >> 8) & 0xff); // G
raw16[pixel + 4] = (byte) ((argb[x] ) & 0xff); // B
raw16[pixel + 6] = (byte) ((argb[x] >> 24) & 0xff); // A
}
}
// Create magick image
ImageInfo info = new ImageInfo();
info.setMagick("RGBA"); // Raw RGBA samples
info.setSize(width + "x" + height); // String?!?
MagickImage image = new MagickImage(info);
image.setImageAttribute("depth", "8");
// Set pixel data in 16 bit raw RGBA format
image.blobToImage(info, raw16);
return image;
}
*/
/**
* Converts a bi-level {@code MagickImage} to a {@code BufferedImage}, of
* type {@code TYPE_BYTE_BINARY}.
*
* @param pImage the original {@code MagickImage}
* @return a new {@code BufferedImage}
*
* @throws MagickException if an exception occurs during conversion
*
* @see BufferedImage
*/
private static BufferedImage bilevelToBuffered(MagickImage pImage) throws MagickException {
// As there is no way to get the binary representation of the image,
// convert to gray, and the create a binary image from it
BufferedImage temp = grayToBuffered(pImage, false);
BufferedImage image = new BufferedImage(temp.getWidth(), temp.getHeight(), BufferedImage.TYPE_BYTE_BINARY, CM_MONOCHROME);
ImageUtil.drawOnto(image, temp);
return image;
}
/**
* Converts a gray {@code MagickImage} to a {@code BufferedImage}, of
* type {@code TYPE_USHORT_GRAY} or {@code TYPE_BYTE_GRAY}.
*
* @param pImage the original {@code MagickImage}
* @param pAlpha keep alpha channel
* @return a new {@code BufferedImage}
*
* @throws MagickException if an exception occurs during conversion
*
* @see BufferedImage
*/
private static BufferedImage grayToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException {
Dimension size = pImage.getDimension();
int length = size.width * size.height;
int bands = pAlpha ? 2 : 1;
byte[] pixels = new byte[length * bands];
// TODO: Make a fix for 16 bit TYPE_USHORT_GRAY?!
// Note: The ordering AI or I corresponds to BufferedImage
// TYPE_CUSTOM and TYPE_BYTE_GRAY respectively
pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "AI" : "I", pixels);
// Init databuffer with array, to avoid allocation of empty array
DataBuffer buffer = new DataBufferByte(pixels, pixels.length);
int[] bandOffsets = pAlpha ? new int[] {1, 0} : new int[] {0};
WritableRaster raster =
Raster.createInterleavedRaster(buffer, size.width, size.height,
size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT);
return new BufferedImage(pAlpha ? CM_GRAY_ALPHA : CM_GRAY_OPAQUE, raster, pAlpha, null);
}
/**
* Converts a palette-based {@code MagickImage} to a
* {@code BufferedImage}, of type {@code TYPE_BYTE_BINARY} (for images
* with a palette of <= 16 colors) or {@code TYPE_BYTE_INDEXED}.
*
* @param pImage the original {@code MagickImage}
* @param pAlpha keep alpha channel
* @return a new {@code BufferedImage}
*
* @throws MagickException if an exception occurs during conversion
*
* @see BufferedImage
*/
private static BufferedImage paletteToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException {
// Create indexcolormodel for the image
IndexColorModel cm;
try {
cm = createIndexColorModel(pImage.getColormap(), pAlpha);
}
catch (MagickException e) {
// NOTE: Some MagickImages incorrecly (?) reports to be paletteType,
// but does not have a colormap, this is a workaround.
return rgbToBuffered(pImage, pAlpha);
}
// As there is no way to get the indexes of an indexed image, convert to
// RGB, and the create an indexed image from it
BufferedImage temp = rgbToBuffered(pImage, pAlpha);
BufferedImage image;
if (cm.getMapSize() <= 16) {
image = new BufferedImage(temp.getWidth(), temp.getHeight(), BufferedImage.TYPE_BYTE_BINARY, cm);
}
else {
image = new BufferedImage(temp.getWidth(), temp.getHeight(), BufferedImage.TYPE_BYTE_INDEXED, cm);
}
// Create transparent background for images containing alpha
if (pAlpha) {
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, temp.getWidth(), temp.getHeight());
}
finally {
g.dispose();
}
}
// NOTE: This is (surprisingly) much faster than using g2d.drawImage()..
// (Tests shows 20-30ms, vs. 600-700ms on the same image)
BufferedImageOp op = new CopyDither(cm);
op.filter(temp, image);
return image;
}
/**
* Creates an {@code IndexColorModel} from an array of
* {@code PixelPacket}s.
*
* @param pColormap the original colormap as a {@code PixelPacket} array
* @param pAlpha keep alpha channel
*
* @return a new {@code IndexColorModel}
*/
public static IndexColorModel createIndexColorModel(PixelPacket[] pColormap, boolean pAlpha) {
int[] colors = new int[pColormap.length];
// TODO: Verify if this is correct for alpha...?
int trans = pAlpha ? colors.length - 1 : -1;
//for (int i = 0; i < pColormap.length; i++) {
for (int i = pColormap.length - 1; i != 0; i--) {
PixelPacket color = pColormap[i];
if (pAlpha) {
colors[i] = (0xff - (color.getOpacity() & 0xff)) << 24 |
(color.getRed() & 0xff) << 16 |
(color.getGreen() & 0xff) << 8 |
(color.getBlue() & 0xff);
}
else {
colors[i] = (color.getRed() & 0xff) << 16 |
(color.getGreen() & 0xff) << 8 |
(color.getBlue() & 0xff);
}
}
return new InverseColorMapIndexColorModel(8, colors.length, colors, 0, pAlpha, trans, DataBuffer.TYPE_BYTE);
}
/**
* Converts an (A)RGB {@code MagickImage} to a {@code BufferedImage}, of
* type {@code TYPE_4BYTE_ABGR} or {@code TYPE_3BYTE_BGR}.
*
* @param pImage the original {@code MagickImage}
* @param pAlpha keep alpha channel
* @return a new {@code BufferedImage}
*
* @throws MagickException if an exception occurs during conversion
*
* @see BufferedImage
*/
private static BufferedImage rgbToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException {
Dimension size = pImage.getDimension();
int length = size.width * size.height;
int bands = pAlpha ? 4 : 3;
byte[] pixels = new byte[length * bands];
// TODO: If we do multiple dispatches (one per line, typically), we could provide listener
// feedback. But it's currently a lot slower than fetching all the pixels in one go.
// Note: The ordering ABGR or BGR corresponds to BufferedImage
// TYPE_4BYTE_ABGR and TYPE_3BYTE_BGR respectively
pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "ABGR" : "BGR", pixels);
// Init databuffer with array, to avoid allocation of empty array
DataBuffer buffer = new DataBufferByte(pixels, pixels.length);
int[] bandOffsets = pAlpha ? BAND_OFF_TRANS : BAND_OFF_OPAQUE;
WritableRaster raster =
Raster.createInterleavedRaster(buffer, size.width, size.height,
size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT);
return new BufferedImage(pAlpha ? CM_COLOR_ALPHA : CM_COLOR_OPAQUE, raster, pAlpha, null);
}
/**
* Converts an {@code MagickImage} to a {@code BufferedImage} which holds an CMYK ICC profile
*
* @param pImage the original {@code MagickImage}
* @param pAlpha keep alpha channel
* @return a new {@code BufferedImage}
*
* @throws MagickException if an exception occurs during conversion
*
* @see BufferedImage
*/
private static BufferedImage cmykToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException {
Dimension size = pImage.getDimension();
int length = size.width * size.height;
// Retreive the ICC profile
ICC_Profile profile = ICC_Profile.getInstance(pImage.getColorProfile().getInfo());
ColorSpace cs = new ICC_ColorSpace(profile);
int bands = cs.getNumComponents() + (pAlpha ? 1 : 0);
int[] bits = new int[bands];
for (int i = 0; i < bands; i++) {
bits[i] = 8;
}
ColorModel cm = pAlpha ?
new ComponentColorModel(cs, bits, true, true, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE) :
new ComponentColorModel(cs, bits, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
byte[] pixels = new byte[length * bands];
// TODO: If we do multiple dispatches (one per line, typically), we could provide listener
// feedback. But it's currently a lot slower than fetching all the pixels in one go.
// TODO: handle more generic cases if profile is not CMYK
// TODO: Test "ACMYK"
pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "ACMYK" : "CMYK", pixels);
// Init databuffer with array, to avoid allocation of empty array
DataBuffer buffer = new DataBufferByte(pixels, pixels.length);
// TODO: build array from bands variable, here it just works for CMYK
// The values has not been tested with an alpha picture actually...
int[] bandOffsets = pAlpha ? new int[] {0, 1, 2, 3, 4} : new int[] {0, 1, 2, 3};
WritableRaster raster =
Raster.createInterleavedRaster(buffer, size.width, size.height,
size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT);
return new BufferedImage(cm, raster, pAlpha, null);
}
}
| {
"pile_set_name": "Github"
} |
/**
* <html>
* <body>
* <P> Copyright 1994 JsonInternational</p>
* <p> All rights reserved.</p>
* <p> Created on 19941115</p>
* <p> Created by Jason</p>
* </body>
* </html>
*/
package cn.ucaner.pattern.create.builder;
/**
* @Package:cn.ucaner.pattern.create.builder
* @ClassName:XManBuilder
* @Description: <p> XManBuilder</p>
* @Author: -
* @CreatTime:2018年1月16日 下午2:06:06
* @Modify By:
* @ModifyTime: 2018年1月16日
* @Modify marker:
* @version V1.0
*/
public interface XManBuilder {
XManBuilder buildXFactor();
XManBuilder buildLover();
XManBuilder buildName();
XManBuilder buildAge();
XMan buildXman();
}
| {
"pile_set_name": "Github"
} |
# Introduction
flare-dbg is a project meant to aid malware reverse engineers in rapidly developing debugger scripts.
# Installation/setup
1. Install the ```pykd``` windbg extension from: https://pykd.codeplex.com/releases
1. Download the Bootstrapper dll.
2. Add the Bootstrapper pykd.dll file into your winext directory. Something like ```%ProgramFiles%\Debugging Tools for Windows\winext```.
3. Install the latest 0.3.x version of pykd using ```pip install pykd```.
4. Ensure you can import ```pykd``` from within windbg: ```.load pykd```.
2. Install ```winappdbg```
1. ```pip install winappdbg```
3. Setup ```vivisect```
1. Install vivisect using one of the following options:
1. Install source using pip: ```pip install https://github.com/williballenthin/vivisect/zipball/master```
2. Download and extract upstream [vivisect](https://github.com/vivisect/vivisect) and set ```PYTHONPATH``` to the extracted directory.
2. Ensure you can import vivisect from a python shell: ```import vivisect```.
4. Setup ```flaredbg```
1. Install flaredbg using ```setup.py```
# Running scripts
There are two options for running scripts:
1. Create a script directory and set ```PYTHONPATH``` to the newly created script directory and add your scripts here.
2. Copy scripts to the root of your windbg directory. Something like: ```%ProgramFiles%\Debugging Tools for Windows\```.
Once your script path is setup, scripts are run from the windbg console as follows:
```
> .load pykd
> !py <script_name>
```
# Installing and running plugins
The recommended way to install scripts is to add the plugins directory of this project to your ```PYTHONPATH```.
Another option is to follow the second option described above in the ```Running scripts``` section. Simply copy the plugin scripts to the root of your windbg directory.
| {
"pile_set_name": "Github"
} |
<?php
$dt=$_REQUEST['dt'] ;
if($dt=="1"):
//include "auto.php";
else:
include "data.php";
endif;
?> | {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Access to Memory (AtoM) software.
*
* Access to Memory (AtoM) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Access to Memory (AtoM) 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 Access to Memory (AtoM). If not, see <http://www.gnu.org/licenses/>.
*/
class AclGroupIndexInformationObjectAclAction extends sfAction
{
public function execute($request)
{
$this->group = QubitAclGroup::getById($this->request->id);
$this->forward404Unless($this->group);
$this->groups = array();
foreach ($this->group->getAncestorsAndSelfForAcl() as $group)
{
if (QubitAclGroup::ROOT_ID < $group->id)
{
$this->groups[] = $group->id;
}
}
// Table width
$this->tableCols = count($this->groups) + 3;
// Get access control permissions
$criteria = new Criteria;
$criteria->addJoin(QubitAclPermission::OBJECT_ID, QubitObject::ID, Criteria::LEFT_JOIN);
// Add group criteria
if (1 == count($this->groups))
{
$criteria->add(QubitAclPermission::GROUP_ID, $this->groups[0]);
}
else
{
$criteria->add(QubitAclPermission::GROUP_ID, $this->groups, Criteria::IN);
}
// Add info object criteria
$c1 = $criteria->getNewCriterion(QubitObject::CLASS_NAME, 'QubitInformationObject');
$c2 = $criteria->getNewCriterion(QubitAclPermission::OBJECT_ID, null, Criteria::ISNULL);
$c1->addOr($c2);
$criteria->add($c1);
// Sort
$criteria->addAscendingOrderByColumn(QubitAclPermission::CONSTANTS);
$criteria->addAscendingOrderByColumn(QubitAclPermission::OBJECT_ID);
$criteria->addAscendingOrderByColumn(QubitAclPermission::USER_ID);
$criteria->addAscendingOrderByColumn(QubitAclPermission::GROUP_ID);
// Build ACL
$this->acl = array();
if (0 < count($permissions = QubitAclPermission::get($criteria)))
{
foreach ($permissions as $permission)
{
// In this context permissions for all objects (null) and root actor
// object are equivalent
$objectId = (QubitInformationObject::ROOT_ID != $permission->objectId) ? $permission->objectId : null;
$this->acl[$permission->getConstants(array('name' => 'repository'))][$objectId][$permission->action][$permission->groupId] = $permission;
}
}
}
}
| {
"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.
*/
module.exports = angular.module('trafficPortal.form.deliveryServiceRegex', [])
.controller('FormDeliveryServiceRegexController', require('./FormDeliveryServiceRegexController'));
| {
"pile_set_name": "Github"
} |
import {
assign,
defaults,
flatten,
isFunction,
uniq,
some,
groupBy,
uniqBy,
values,
isPlainObject
} from "lodash";
import React from "react";
import Axis from "./axis";
import Style from "./style";
import Transitions from "./transitions";
import Data from "./data";
import Domain from "./domain";
import Events from "./events";
import Collection from "./collection";
import Helpers from "./helpers";
import Scale from "./scale";
import Log from "./log";
export default {
getData(props, childComponents) {
if (props.data) {
return Data.getData(props);
}
childComponents = childComponents || React.Children.toArray(props.children);
return this.getDataFromChildren(childComponents);
},
getDefaultDomainPadding(props, axis, childComponents) {
if (props.polar || axis !== "x") {
return undefined;
}
const groupComponent = childComponents.filter((child) => {
return child.type && child.type.role && child.type.role === "group";
});
if (groupComponent.length < 1) {
return undefined;
}
const { offset, children } = groupComponent[0].props;
return { x: (offset * children.length) / 2 };
},
getDomain(props, axis, childComponents) {
childComponents = childComponents || React.Children.toArray(props.children);
const propsDomain = Domain.getDomainFromProps(props, axis);
const domainPadding = this.getDefaultDomainPadding(props, axis, childComponents);
let domain;
if (propsDomain) {
domain = propsDomain;
} else {
const minDomain = Domain.getMinFromProps(props, axis);
const maxDomain = Domain.getMaxFromProps(props, axis);
const dataset = (props.data || props.y) && Data.getData(props);
const dataDomain = dataset ? Domain.getDomainFromData(props, axis, dataset) : [];
const childDomain = this.getDomainFromChildren(props, axis, childComponents);
const min = minDomain || Collection.getMinValue([...dataDomain, ...childDomain]);
const max = maxDomain || Collection.getMaxValue([...dataDomain, ...childDomain]);
domain = Domain.getDomainFromMinMax(min, max);
}
return Domain.formatDomain(domain, assign({ domainPadding }, props), axis);
},
getScale(props, axis, childComponents) {
if (props.data) {
return Scale.getBaseScale(props, axis);
}
const children = childComponents
? childComponents.slice(0)
: React.Children.toArray(props.children);
const iteratee = (child) => {
const sharedProps = assign({}, child.props, { horizontal: props.horizontal });
return Scale.getScaleType(sharedProps, axis);
};
const childScale = uniq(Helpers.reduceChildren(children, iteratee, props));
// default to linear scale if more than one uniq scale type is given by children
return childScale.length > 1
? Scale.getScaleFromName("linear")
: Scale.getScaleFromName(childScale[0]);
},
setAnimationState(props, nextProps) {
if (!props.animate) {
return;
}
if (props.animate.parentState) {
const nodesWillExit = props.animate.parentState.nodesWillExit;
const oldProps = nodesWillExit ? props : null;
this.setState(defaults({ oldProps, nextProps }, props.animate.parentState));
} else {
const oldChildren = React.Children.toArray(props.children);
const nextChildren = React.Children.toArray(nextProps.children);
const isContinuous = (child) => {
const check = (c) => c.type && c.type.continuous;
return Array.isArray(child) ? some(child, check) : check(child);
};
const continuous =
!props.polar &&
some(oldChildren, (child) => {
return (
isContinuous(child) || (child.props.children && isContinuous(child.props.children))
);
});
const {
nodesWillExit,
nodesWillEnter,
childrenTransitions,
nodesShouldEnter
} = Transitions.getInitialTransitionState(oldChildren, nextChildren);
this.setState({
nodesWillExit,
nodesWillEnter,
nodesShouldEnter,
childrenTransitions: Collection.isArrayOfArrays(childrenTransitions)
? childrenTransitions[0]
: childrenTransitions,
oldProps: nodesWillExit ? props : null,
nextProps,
continuous
});
}
},
getAllEvents(props) {
const components = ["groupComponent", "containerComponent", "labelComponent"];
this.componentEvents = Events.getComponentEvents(props, components);
let events = props.events;
if (Array.isArray(this.componentEvents)) {
events = Array.isArray(props.events)
? this.componentEvents.concat(...props.events)
: this.componentEvents;
}
return events || [];
},
getAnimationProps(props, child, index) {
if (!props.animate) {
return child.props.animate;
}
const getFilteredState = () => {
let childrenTransitions = this.state && this.state.childrenTransitions;
childrenTransitions = Collection.isArrayOfArrays(childrenTransitions)
? childrenTransitions[index]
: childrenTransitions;
return defaults({ childrenTransitions }, this.state);
};
let getTransitions = props.animate && props.animate.getTransitions;
const state = getFilteredState();
const parentState = (props.animate && props.animate.parentState) || state;
if (!getTransitions) {
const getTransitionProps = Transitions.getTransitionPropsFactory(props, state, (newState) =>
this.setState(newState)
);
getTransitions = (childComponent) => getTransitionProps(childComponent, index);
}
return defaults({ getTransitions, parentState }, props.animate, child.props.animate);
},
getDomainFromChildren(props, axis, childComponents) {
// eslint-disable-line max-statements, complexity, max-len
const children = childComponents
? childComponents.slice(0)
: React.Children.toArray(props.children);
const parentData = props.data ? Data.getData(props, axis) : undefined;
const { polar, startAngle, endAngle, categories, minDomain, maxDomain, horizontal } = props;
const baseParentProps = {
horizontal,
polar,
startAngle,
endAngle,
minDomain,
maxDomain,
categories
};
const parentProps = parentData
? assign(baseParentProps, { data: parentData })
: baseParentProps;
const iteratee = (child) => {
const sharedProps = assign({}, child.props, parentProps);
if (!Domain.isDomainComponent(child)) {
return null;
} else if (child.type && isFunction(child.type.getDomain)) {
return child.props && child.type.getDomain(sharedProps, axis);
} else {
return Domain.getDomain(sharedProps, axis);
}
};
const childDomains = Helpers.reduceChildren(children, iteratee, props);
const min = childDomains.length === 0 ? 0 : Collection.getMinValue(childDomains);
const max = childDomains.length === 0 ? 1 : Collection.getMaxValue(childDomains);
return [min, max];
},
addBinsToParentPropsIfHistogram({ children, props, childComponents, parentProps }) {
const someChildrenAreHistograms = children.some((child) => {
return child.type && child.type.role === "histogram";
});
const allChildrenAreHistograms =
someChildrenAreHistograms &&
children.length &&
children.every((child) => {
return child.type && child.type.role === "histogram";
});
if (someChildrenAreHistograms && !allChildrenAreHistograms) {
Log.warn(
"VictoryHistogram only supports being stacked with other VictoryHistogram components. Check to make sure that you are only passing VictoryHistogram components to VictoryStack"
);
}
// if we are stacking histograms, we need to generate explicit bins
// or else each histogram may end up having different bins
if (!allChildrenAreHistograms) {
return parentProps;
}
let childBins = props.bins || childComponents[0].props.bins;
// if we have explicit bins then we don't need to calculate them
if (!Array.isArray(childBins)) {
const combinedData = children.reduce((memo, child) => {
const xAccessor = Helpers.createAccessor(child.props.x || "x");
return memo.concat(child.props.data.map((datum) => ({ x: xAccessor(datum) })));
}, []);
// use the same function to generate bins as VictoryHistogram but with
// the combined data from above, then get explicit bins from that
const getFormattedHistogramData = children[0].type.getFormattedData;
childBins = getFormattedHistogramData({ data: combinedData, bins: childBins }).reduce(
(memo, { x0, x1 }, index) => (index === 0 ? memo.concat([x0, x1]) : memo.concat(x1)),
[]
);
}
return { ...parentProps, bins: childBins };
},
getDataFromChildren(props, childComponents) {
const { polar, startAngle, endAngle, categories, minDomain, maxDomain } = props;
let parentProps = { polar, startAngle, endAngle, categories, minDomain, maxDomain };
let stack = 0;
const children = childComponents
? childComponents.slice(0)
: React.Children.toArray(props.children);
parentProps = this.addBinsToParentPropsIfHistogram({
children,
props,
childComponents,
parentProps
});
const iteratee = (child, childName, parent) => {
const childProps = assign({}, child.props, parentProps);
let childData;
if (!Data.isDataComponent(child)) {
return null;
} else if (child.type && isFunction(child.type.getData)) {
child = parent ? React.cloneElement(child, parent.props) : child;
childData = child.type.getData(childProps);
} else {
childData = Data.getData(childProps);
}
stack += 1;
return childData.map((datum, index) => assign({ _stack: stack, _group: index }, datum));
};
const stacked = children.filter((c) => c.type && c.type.role === "stack").length;
const combine = (memo, val) => memo.concat(uniqBy(val, "_group"));
const datasets = Helpers.reduceChildren(children, iteratee, props, [], combine);
const group = stacked ? "_group" : "_stack";
return values(groupBy(datasets, group));
},
getColor(calculatedProps, child, index) {
// check for styles first
const { style } = calculatedProps;
let { colorScale, color } = calculatedProps;
if (style && style.data && style.data.fill) {
return style.data.fill;
}
colorScale = child.props && child.props.colorScale ? child.props.colorScale : colorScale;
color = child.props && child.props.color ? child.props.color : color;
if (!colorScale && !color) {
return undefined;
}
const colors = Array.isArray(colorScale) ? colorScale : Style.getColorScale(colorScale);
return color || colors[index % colors.length];
},
getWidth(props) {
const { datasets, scale, horizontal } = props;
const range = horizontal ? scale.y.range() : scale.x.range();
const extent = Math.abs(range[1] - range[0]);
const seriesLength = Array.isArray(datasets[0]) ? datasets[0].length : 1;
const bars = datasets.length * seriesLength + 2;
const barRatio = 0.5;
return { width: Math.round((barRatio * extent) / bars) };
},
getStyle(theme, style, role) {
const defaultStyle = theme && theme[role] && theme[role].style ? theme[role].style : {};
return Helpers.getStyles(style, defaultStyle);
},
getChildStyle(child, index, calculatedProps) {
const { style, role } = calculatedProps;
const childStyle = child.props.style || {};
if (Array.isArray(childStyle)) {
return childStyle;
}
const childRole = child.type && child.type.role;
const defaultFill =
childRole === "stack" ? undefined : this.getColor(calculatedProps, child, index);
const defaultColor =
childRole === "line" ? { fill: "none", stroke: defaultFill } : { fill: defaultFill };
const dataWidth = role === "stack" ? {} : this.getWidth(calculatedProps);
const dataStyle = defaults(
{},
childStyle.data,
assign({}, dataWidth, style.data, defaultColor)
);
const labelsStyle = defaults({}, childStyle.labels, style.labels);
return {
parent: style.parent,
data: dataStyle,
labels: labelsStyle
};
},
getStringsFromCategories(childComponents, axis) {
const iteratee = (child) => {
const childProps = child.props || {};
if (!Domain.isDomainComponent(child) || !childProps.categories) {
return null;
} else {
const categories =
childProps.categories && !Array.isArray(childProps.categories)
? childProps.categories[axis]
: childProps.props.categories;
const categoryStrings = categories && categories.filter((val) => typeof val === "string");
return categoryStrings ? Collection.removeUndefined(categoryStrings) : [];
}
};
return Helpers.reduceChildren(childComponents.slice(0), iteratee);
},
getStringsFromData(childComponents) {
const iteratee = (child) => {
const childProps = child.props || {};
let data;
if (!Data.isDataComponent(child)) {
return null;
} else if (child.type && isFunction(child.type.getData)) {
data = child.type.getData(childProps);
} else {
data = Data.getData(childProps);
}
return data.map((d) => ({ x: d.xName, y: d.yName }));
};
const initialMemo = { x: [], y: [] };
const combine = (memo, datum) => {
const x = Array.isArray(datum) ? datum.map((d) => d.x).filter(Boolean) : datum.x;
const y = Array.isArray(datum) ? datum.map((d) => d.y).filter(Boolean) : datum.y;
return {
x: x !== undefined ? memo.x.concat(x) : memo.x,
y: y !== undefined ? memo.y.concat(y) : memo.y
};
};
return Helpers.reduceChildren(childComponents.slice(0), iteratee, {}, initialMemo, combine);
},
getCategoryAndAxisStringsFromChildren(props, axis, childComponents) {
const categories = isPlainObject(props.categories) ? props.categories[axis] : props.categories;
const axisComponent = Axis.getAxisComponent(childComponents, axis);
const axisStrings = axisComponent ? Data.getStringsFromAxes(axisComponent.props, axis) : [];
const categoryStrings = categories || this.getStringsFromCategories(childComponents, axis);
return uniq(flatten([...categoryStrings, ...axisStrings]));
},
getStringsFromChildren(props, childComponents) {
childComponents = childComponents || React.Children.toArray(props.children);
const xStrings = this.getCategoryAndAxisStringsFromChildren(props, "x", childComponents);
const yStrings = this.getCategoryAndAxisStringsFromChildren(props, "y", childComponents);
const dataStrings = this.getStringsFromData(childComponents);
return {
x: uniq(flatten([...xStrings, ...dataStrings.x])),
y: uniq(flatten([...yStrings, ...dataStrings.y]))
};
},
getCategories(props, childComponents, allStrings) {
const xPropCategories =
props.categories && !Array.isArray(props.categories) ? props.categories.x : props.categories;
const yPropCategories =
props.categories && !Array.isArray(props.categories) ? props.categories.y : props.categories;
const fallbackRequired = !xPropCategories || !yPropCategories;
const fallbackProps = fallbackRequired
? allStrings || this.getStringsFromChildren(props, childComponents)
: {};
const xCategories = xPropCategories || fallbackProps.x;
const yCategories = yPropCategories || fallbackProps.y;
return {
x: xCategories.length > 0 ? xCategories : undefined,
y: yCategories.length > 0 ? yCategories : undefined
};
}
};
| {
"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 ipv4_test
import (
"net"
"runtime"
"testing"
"golang.org/x/net/internal/iana"
"golang.org/x/net/internal/nettest"
"golang.org/x/net/ipv4"
)
func TestConnUnicastSocketOptions(t *testing.T) {
switch runtime.GOOS {
case "nacl", "plan9":
t.Skipf("not supported on %s", runtime.GOOS)
}
ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback)
if ifi == nil {
t.Skipf("not available on %s", runtime.GOOS)
}
ln, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
done := make(chan bool)
go acceptor(t, ln, done)
c, err := net.Dial("tcp4", ln.Addr().String())
if err != nil {
t.Fatal(err)
}
defer c.Close()
testUnicastSocketOptions(t, ipv4.NewConn(c))
<-done
}
var packetConnUnicastSocketOptionTests = []struct {
net, proto, addr string
}{
{"udp4", "", "127.0.0.1:0"},
{"ip4", ":icmp", "127.0.0.1"},
}
func TestPacketConnUnicastSocketOptions(t *testing.T) {
switch runtime.GOOS {
case "nacl", "plan9":
t.Skipf("not supported on %s", runtime.GOOS)
}
ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback)
if ifi == nil {
t.Skipf("not available on %s", runtime.GOOS)
}
m, ok := nettest.SupportsRawIPSocket()
for _, tt := range packetConnUnicastSocketOptionTests {
if tt.net == "ip4" && !ok {
t.Log(m)
continue
}
c, err := net.ListenPacket(tt.net+tt.proto, tt.addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
testUnicastSocketOptions(t, ipv4.NewPacketConn(c))
}
}
func TestRawConnUnicastSocketOptions(t *testing.T) {
switch runtime.GOOS {
case "nacl", "plan9":
t.Skipf("not supported on %s", runtime.GOOS)
}
if m, ok := nettest.SupportsRawIPSocket(); !ok {
t.Skip(m)
}
ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback)
if ifi == nil {
t.Skipf("not available on %s", runtime.GOOS)
}
c, err := net.ListenPacket("ip4:icmp", "127.0.0.1")
if err != nil {
t.Fatal(err)
}
defer c.Close()
r, err := ipv4.NewRawConn(c)
if err != nil {
t.Fatal(err)
}
testUnicastSocketOptions(t, r)
}
type testIPv4UnicastConn interface {
TOS() (int, error)
SetTOS(int) error
TTL() (int, error)
SetTTL(int) error
}
func testUnicastSocketOptions(t *testing.T, c testIPv4UnicastConn) {
tos := iana.DiffServCS0 | iana.NotECNTransport
switch runtime.GOOS {
case "windows":
// IP_TOS option is supported on Windows 8 and beyond.
t.Skipf("not supported on %s", runtime.GOOS)
}
if err := c.SetTOS(tos); err != nil {
t.Fatal(err)
}
if v, err := c.TOS(); err != nil {
t.Fatal(err)
} else if v != tos {
t.Fatalf("got %v; want %v", v, tos)
}
const ttl = 255
if err := c.SetTTL(ttl); err != nil {
t.Fatal(err)
}
if v, err := c.TTL(); err != nil {
t.Fatal(err)
} else if v != ttl {
t.Fatalf("got %v; want %v", v, ttl)
}
}
| {
"pile_set_name": "Github"
} |
#
# Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code 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 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# This file stores localized messages for the Xerces JAXP Datatype API implementation.
#
# The messages are arranged in key and value tuples in a ListResourceBundle.
BadMessageKey = Die zum Meldungsschl\u00FCssel geh\u00F6rige Fehlermeldung kann nicht gefunden werden.
FormatFailed = Beim Formatieren der folgenden Meldung ist ein interner Fehler aufgetreten:\n
FieldCannotBeNull={0} kann nicht mit "Null"-Parameter aufgerufen werden.
UnknownField={0} mit unbekanntem Feld aufgerufen:{1}
#There are two similar keys 'InvalidXMLGreogorianCalendarValue' . Suffix (year, month) has been added and are used as per the context.
InvalidXGCValue-milli=Jahr = {0}, Monat = {1}, Tag = {2}, Stunde= {3}, Minute = {4}, Sekunde = {5}, fractionalSecond = {6}, Zeitzone = {7} ist keine g\u00FCltige Darstellung eines XML-Wertes f\u00FCr einen gregorianischen Kalender.
#There are two similar keys 'InvalidXMLGreogorianCalendarValue' . Suffix (year, month) has been added and are used as per the context.
InvalidXGCValue-fractional=Jahr = {0}, Monat = {1}, Tag = {2}, Stunde= {3}, Minute = {4}, Sekunde = {5}, fractionalSecond = {6}, Zeitzone = {7} ist keine g\u00FCltige Darstellung eines XML-Wertes f\u00FCr einen gregorianischen Kalender.
InvalidXGCFields=Ung\u00FCltige Gruppe von Feldern f\u00FCr XMLGregorianCalendar festgelegt
InvalidFractional=Ung\u00FCltiger Wert {0} f\u00FCr Sekundenbruchteil.
#XGC stands for XML Gregorian Calendar
InvalidXGCRepresentation="{0}" ist keine g\u00FCltige Darstellung eines XML-Wertes f\u00FCr einen gregorianischen Kalender.
InvalidFieldValue=Ung\u00FCltiger Wert {0} f\u00FCr Feld {1}.
NegativeField= Feld {0} ist negativ
AllFieldsNull=Alle Felder (javax.xml.datatype.DatatypeConstants.Field) sind null.
TooLarge={0}-Wert "{1}" zu gro\u00DF, um von dieser Implementierung unterst\u00FCtzt zu werden
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright Medical Information Integration,LLC info@mi-squared.com
* 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.
*
* @file C_AbstractClickmap.php
*
* @brief This file contains the C_AbstractClickmap class, used to control smarty.
*/
/* for encounter','fileroot','pid','srcdir','style','webroot']
* remember that include paths are calculated relative to the including script, not this file.
* to lock the path to this script (so if called from different scripts) use the dirname(FILE) variable
*/
require_once(dirname(__FILE__) . '/../globals.php');
/* For the addform() function */
require_once($GLOBALS['srcdir'] . '/forms.inc');
/**
* @class C_AbstractClickmap
*
* @brief This class extends the Controller class, which is used to control the smarty templating engine.
*
*/
abstract class C_AbstractClickmap extends Controller
{
/**
* the directory to find our template file in.
*
* @var template_dir
*/
var $template_dir;
/**
* @brief Initialize a newly created object belonging to this class
*
* @param template_mod
* template module name, passed to Controller's initializer.
*/
function __construct($template_mod = "general")
{
parent::__construct();
$returnurl = 'encounter_top.php';
$this->template_mod = $template_mod;
$this->template_dir = $GLOBALS['fileroot'] . "/interface/clickmap/template/";
$this->assign("DONT_SAVE_LINK", $GLOBALS['webroot'] . "/interface/patient_file/encounter/$returnurl");
$this->assign("FORM_ACTION", $GLOBALS['webroot']);
$this->assign("STYLE", $GLOBALS['style']);
}
/**
* @brief Override this abstract function with your implementation of createModel.
*
* @param $form_id
* An optional id of a form, to populate data from.
*
* @return Model
* An AbstractClickmapModel derived Object.
*/
abstract public function createModel($form_id = "");
/**
* @brief Override this abstract function with your implememtation of getImage
*
* @return The path to the image backing this form relative to the webroot.
*/
abstract function getImage();
/**
* @brief Override this abstract function to return the label of the optionlists on this form.
*
* @return The label used for all dropdown boxes on this form.
*/
abstract function getOptionsLabel();
/**
* @brief Override this abstract functon to return a hash of the optionlist (key=>value pairs).
*
* @return A hash of key=>value pairs, representing all the possible options in the dropdown boxes on this form.
*/
abstract function getOptionList();
/**
* @brief set up the passed in Model object to model the form.
*/
private function set_context($model)
{
$root = $GLOBALS['webroot'] . "/interface/clickmap";
$model->saveAction = $GLOBALS['webroot'] . "/interface/forms/" . $model->getCode() . "/save.php";
$model->template_dir = $root . "/template";
$model->image = $this->getImage();
$optionList = $this->getOptionList();
$model->optionList = $optionList != null ? json_encode($optionList) : "null";
$optionsLabel = $this->getOptionsLabel();
$model->optionsLabel = isset($optionsLabel) ? "'" . $optionsLabel . "'" : "null";
$data = $model->get_data();
$model->data = $data != "" ? "'" . $data . "'" : "null";
$model->hideNav = "false";
}
/**
* @brief generate an html document from the 'new form' template
*
* @return the result of smarty's fetch() operation.
*/
function default_action()
{
$model = $this->createModel();
$this->assign("form", $model);
$this->set_context($model);
return $this->fetch($this->template_dir . $this->template_mod . "_new.html");
}
/**
* @brief generate an html document from the 'new form' template, populated with form data from the passed in form_id.
*
* @param form_id
* The id of the form to populate data from.
*
* @return the result of smarty's fetch() operation.
*/
function view_action($form_id)
{
$model = $this->createModel($form_id);
$this->assign("form", $model);
$this->set_context($model);
return $this->fetch($this->template_dir . $this->template_mod . "_new.html");
}
/**
* @brief generate a fragment of an HTML document from the 'new form' template, populated with form data from the passed in form_id.
*
* @param form_id
* The id of the form to populate data from.
*
* @return the result of smarty's fetch() operation.
*/
function report_action($form_id)
{
$model = $this->createModel($form_id);
$this->assign("form", $model);
$this->set_context($model);
$model->hideNav = "true";
$this->assign("reportMode", true);
return $this->fetch($this->template_dir . $this->template_mod . "_new.html");
}
/**
* @brief called to store the submitted form's contents to the database, adding the form to the encounter if necissary.
*/
function default_action_process()
{
if ($_POST['process'] != "true") {
return;
}
$this->model = $this->createModel($_POST['id']);
parent::populate_object($this->model);
$this->model->persist();
if ($GLOBALS['encounter'] == "") {
$GLOBALS['encounter'] = date("Ymd");
}
if (empty($_POST['id'])) {
addForm(
$GLOBALS['encounter'],
$this->model->getTitle(),
$this->model->id,
$this->model->getCode(),
$GLOBALS['pid'],
$_SESSION['userauthorized']
);
$_POST['process'] = "";
}
}
}
| {
"pile_set_name": "Github"
} |
FROM ubuntu:18.04
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc-multilib \
libc6-dev \
file \
make \
ca-certificates
| {
"pile_set_name": "Github"
} |
from smtplib import SMTPResponseException
from socket import error as socket_error
from django.core.mail.backends.smtp import EmailBackend as DjangoEmailBackend
from conf.utils import get_site_setting
class EmailBackend(DjangoEmailBackend):
"""
Handles emails using Site-based settings from Conf.
"""
def __init__(self, fail_silently=False, **kwargs):
super().__init__(
host=get_site_setting("smtp_host"),
port=get_site_setting("smtp_port"),
username=get_site_setting("smtp_user"),
password=get_site_setting("smtp_password"),
use_tls=get_site_setting("use_tls"),
fail_silently=fail_silently,
**kwargs
)
def send_messages(self, email_messages):
"""
Override the from_email property all email messages.
"""
if not email_messages:
return
with self._lock:
for message in email_messages:
message.from_email = get_site_setting("smtp_from_address")
try:
super().send_messages(email_messages)
except (SMTPResponseException, socket_error) as e:
# TODO: Determine how to handle failures gracefully.
raise e
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!-- Copyright © 1991-2013 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml>
<identity>
<version number="$Revision: 9061 $"/>
<generation date="$Date: 2013-07-20 12:27:45 -0500 (Sat, 20 Jul 2013) $"/>
<language type="hy"/>
<territory type="AM"/>
</identity>
</ldml>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_60) on Thu Jun 18 16:18:51 EDT 2015 -->
<title>Uses of Class com.sleepycat.bind.tuple.SortedFloatBinding (Oracle - Berkeley DB Java API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../../style.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.sleepycat.bind.tuple.SortedFloatBinding (Oracle - Berkeley DB Java API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/sleepycat/bind/tuple/SortedFloatBinding.html" title="class in com.sleepycat.bind.tuple">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Berkeley DB</b><br><font size="-1"> version 6.1.26</font></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/sleepycat/bind/tuple/class-use/SortedFloatBinding.html" target="_top">Frames</a></li>
<li><a href="SortedFloatBinding.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.sleepycat.bind.tuple.SortedFloatBinding" class="title">Uses of Class<br>com.sleepycat.bind.tuple.SortedFloatBinding</h2>
</div>
<div class="classUseContainer">No usage of com.sleepycat.bind.tuple.SortedFloatBinding</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/sleepycat/bind/tuple/SortedFloatBinding.html" title="class in com.sleepycat.bind.tuple">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Berkeley DB</b><br><font size="-1"> version 6.1.26</font></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/sleepycat/bind/tuple/class-use/SortedFloatBinding.html" target="_top">Frames</a></li>
<li><a href="SortedFloatBinding.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size=1>Copyright (c) 1996, 2015 Oracle and/or its affiliates. All rights reserved.</font></small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
# NULL合体演算子(Nullish coalescing operator) '??'
[recent browser="new"]
NULL合体演算子 `??` はリストの中から最初の "定義済み" 変数を選択するための短縮構文です。
`a ?? b` の結果は:
- `a` が `null` あるいは `undefined` でなければ `a`,
- それ以外の場合は `b`.
したがって、`x = a ?? b` は以下と同等です:
```js
x = (a !== null && a !== undefined) ? a : b;
```
次はより長い例です。
想像してください、ユーザがいて、性、名、ニックネーム用の変数 `firstName`, `lastName`, `nickName` があるとします。ユーザが何も入力しなければ、それらはすべて undefined になるかもしれません。
ユーザ名を表示します: 3つの変数のいずれか、あるいは設定されていない場合は "Anonymous" とします。
`??` 演算子を使って最初に定義されたものを選択しましょう。:
```js run
let firstName = null;
let lastName = null;
let nickName = "Supercoder";
// 最初の null/undefined でない値を表示します
*!*
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
*/!*
```
## || との比較
OR `||` 演算子は `??` と同じ方法で利用することができます。[前のチャプター](info:logical-operators#or-finds-the-first-truthy-value) で説明したように、実際、上のコードでは `??` を `||` に置き換えることができ、同じ結果を得ることができます。
重要な違いは次の通りです:
- `||` は最初の *真* の値を返します。
- `??` は最初の *定義済み* の値を返します。
これは、`null/undefined` を `0` とは別に扱いたい場合、非常に重要です。
例えば、次を考えてみましょう:
```js
height = height ?? 100;
```
`height` が未定義であれば、`100` が設定されます。
`||` と比較してみましょう:
```js run
let height = 0;
alert(height || 100); // 100
alert(height ?? 100); // 0
```
ここでは、`height || 100` は 高さゼロを `null` や `undefined` あるいは他の偽の値と同様に未定義として扱っています。そのため、結果は `100` です。
`height ?? 100` は `height` がまさに `null` あるいは `undefined` の場合にのみ `100` を返します。したがって、`alert` は高さの値 `0` を "そのまま" 表示します。
どちらの振る舞いがよいかはユースケースによります。高さゼロは有効な値の場合、`??` の方が好ましいです。
## 優先順位
`??` の順位は低めです: [MDN テーブル](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table) の `5` です。
したがって、`??` は他の多くの演算子の後で、`=` と `?` の前に評価されます。
複雑な式で `??` を用いて値を選択する必要がある場合は括弧を用いることを検討してください:
```js run
let height = null;
let width = null;
// 重要: 括弧を使用します
let area = (height ?? 100) * (width ?? 50);
alert(area); // 5000
```
そうでない場合、括弧を省略すると `*` は `??` よりも優先度が高いため、最初に実行されます。
これば次のように動くことを意味します:
```js
// 恐らくこれは正しくない計算でしょう
let area = height ?? (100 * width) ?? 50;
```
また、ここには関連する言語レベルの制限もあります。
**安全上の理由により、`&&` や `||` 演算子と一緒に `??` を用いることは禁止されています。**
次のコードは構文エラーになります:
```js run
let x = 1 && 2 ?? 3; // Syntax error
```
この制限には当然議論の余地がありますが、人々が `||` から `??` に切り替え始めるときに、プログラミングのミスを避ける目的で言語仕様に追加されました。
回避するには明示的に括弧を使用します:
```js run
*!*
let x = (1 && 2) ?? 3; // 動作します
*/!*
alert(x); // 2
```
## サマリ
- Null合体演算子 `??` は一覧から "定義済み" の値を選択するための簡単な方法を提供します。
変数にデフォルト値を代入するために使用されます:
```js
// height が null あるいは undefined であれば height=100 を設定します
height = height ?? 100;
```
- 演算子 `??` は優先度が低く、`?` や `=` よりも少し高い程度です。
- 明示的な括弧なしに `||` や `&&` と一緒に利用することは禁止されています。
| {
"pile_set_name": "Github"
} |
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2015 Intel Corporation. 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
the Intel Corporation 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 INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
/*
* Sample buffering tool
*
* This tool collects an address trace, including PC, read/write EA,
* and read/write size, by filling a buffer. When the buffer overflows,
* the callback writes all of the collected records to a file.
*
*/
#include "pin.H"
#include <iostream>
#include <stdio.h>
#include <stddef.h>
/* Struct for holding memory references. Rather than having two separate
* buffers for loads and stores, we just use one struct that includes a
* flag for type.
*/
struct MEMREF
{
ADDRINT pc;
ADDRINT address;
UINT32 size;
UINT32 load;
};
FILE *outfile;
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "allocate.out", "output file");
BUFFER_ID bufId;
PIN_LOCK fileLock;
#define NUM_BUF_PAGES 64
/*!
* Print out help message.
*/
INT32 Usage()
{
cerr << "This tool demonstrates the basic use of the buffering API." << endl << endl;
return -1;
}
VOID Trace(TRACE trace, VOID *v){
UINT32 refSize;
for(BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl=BBL_Next(bbl)){
for(INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins=INS_Next(ins)){
if(INS_IsMemoryRead(ins)){
refSize = INS_MemoryReadSize(ins);
INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId,
IARG_INST_PTR, offsetof(struct MEMREF, pc),
IARG_MEMORYREAD_EA, offsetof(struct MEMREF, address),
IARG_UINT32, refSize, offsetof(struct MEMREF, size),
IARG_UINT32, 1, offsetof(struct MEMREF, load),
IARG_END);
}
if(INS_HasMemoryRead2(ins)){
refSize = INS_MemoryReadSize(ins);
INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId,
IARG_INST_PTR, offsetof(struct MEMREF, pc),
IARG_MEMORYREAD2_EA, offsetof(struct MEMREF, address),
IARG_UINT32, refSize, offsetof(struct MEMREF, size),
IARG_UINT32, 1, offsetof(struct MEMREF, load),
IARG_END);
}
if(INS_IsMemoryWrite(ins)){
refSize = INS_MemoryWriteSize(ins);
INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId,
IARG_INST_PTR, offsetof(struct MEMREF, pc),
IARG_MEMORYWRITE_EA, offsetof(struct MEMREF, address),
IARG_UINT32, refSize, offsetof(struct MEMREF, size),
IARG_UINT32, 0, offsetof(struct MEMREF, load),
IARG_END);
}
}
}
}
/*!
* Called when a buffer fills up, or the thread exits, so we can process it or pass it off
* as we see fit.
* @param[in] id buffer handle
* @param[in] tid id of owning thread
* @param[in] ctxt application context when the buffer filled
* @param[in] buf actual pointer to buffer
* @param[in] numElements number of records
* @param[in] v callback value
* @return A pointer to the buffer to resume filling.
*/
VOID * BufferFull(BUFFER_ID id, THREADID tid, const CONTEXT *ctxt, VOID *buf,
UINT64 numElements, VOID *v)
{
PIN_GetLock(&fileLock, 1);
struct MEMREF* reference=(struct MEMREF*)buf;
UINT64 i;
for(i=0; i<numElements; i++, reference++){
fprintf(outfile, "%lx %lx %u %u\n", (unsigned long)reference->pc, (unsigned long)reference->address,
reference->size, reference->load);
}
fflush(outfile);
PIN_ReleaseLock(&fileLock);
// Test deallocate and allocate
VOID * newbuf = PIN_AllocateBuffer(id);
PIN_DeallocateBuffer( id, buf );
return newbuf;
}
/*!
* Print out analysis results.
* This function is called when the application exits.
* @param[in] code exit code of the application
* @param[in] v value specified by the tool in the
* PIN_AddFiniFunction function call
*/
VOID Fini(INT32 code, VOID *v)
{
PIN_GetLock(&fileLock, 1);
fclose(outfile);
printf("outfile closed\n");
PIN_ReleaseLock(&fileLock);
}
/*!
* The main procedure of the tool.
* This function is called when the application image is loaded but not yet started.
* @param[in] argc total number of elements in the argv array
* @param[in] argv array of command line arguments,
* including pin -t <toolname> -- ...
*/
int main(int argc, char *argv[])
{
// Initialize PIN library. Print help message if -h(elp) is specified
// in the command line or the command line is invalid
if( PIN_Init(argc,argv) )
{
return Usage();
}
// Initialize the memory reference buffer
bufId = PIN_DefineTraceBuffer(sizeof(struct MEMREF), NUM_BUF_PAGES,
BufferFull, 0);
if(bufId == BUFFER_ID_INVALID){
cerr << "Error allocating initial buffer" << endl;
return 1;
}
outfile = fopen(KnobOutputFile.Value().c_str(), "w");
if(!outfile){
cerr << "Couldn't open " << KnobOutputFile.Value() << endl;
return 1;
}
PIN_InitLock(&fileLock);
// add an instrumentation function
TRACE_AddInstrumentFunction(Trace, 0);
// Register function to be called when the application exits
PIN_AddFiniFunction(Fini, 0);
// Start the program, never returns
PIN_StartProgram();
return 0;
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'list', 'en-gb', {
bulletedlist: 'Insert/Remove Bulleted List',
numberedlist: 'Insert/Remove Numbered List'
} );
| {
"pile_set_name": "Github"
} |
@import "ui-variables";
html,
body {
margin: 0;
height: 100%;
width: 100%;
overflow: hidden;
-webkit-font-smoothing: antialiased;
}
.theme-option {
position: absolute;
top: 0;
margin-top: 4px;
margin-left: 5px;
width: 100px;
height: 60px;
background-color: @background-secondary;
color: @text-color;
border-radius: 5px;
text-align: center;
overflow: hidden;
&.active-true {
border: 1px solid #3187e1;
box-shadow: 0 0 4px #9ecaed;
}
&.active-false {
border: 1px solid darken(#f6f6f6, 10%);
}
.theme-name {
font-family: @font-family;
font-size: 12px;
font-weight: 600;
margin-top: 7px;
height: 18px;
overflow: hidden;
}
.swatches {
padding-left: 27px;
padding-right: 27px;
display: flex;
flex-direction: row;
.swatch {
flex: 1;
height: 10px;
width: 10px;
margin: 4px 2px 4px 2px;
border-radius: 2px;
border: 1px solid rgba(0, 0, 0, 0.15);
background-clip: border-box;
background-origin: border-box;
&.font-color {
background-color: @text-color;
}
&.active-color {
background-color: @component-active-color;
}
&.toolbar-color {
background-color: @toolbar-background-color;
}
}
}
.divider-black {
position: absolute;
bottom: 12px;
height: 1px;
width: 100%;
background-color: black;
opacity: 0.15;
}
.divider-white {
position: absolute;
z-index: 10;
bottom: 11px;
height: 1px;
width: 100%;
background-color: white;
opacity: 0.15;
}
.strip {
position: absolute;
bottom: 0;
height: 12px;
width: 100%;
background-color: @panel-background-color;
}
}
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
<%namespace module='pyfr.backends.base.makoutil' name='pyfr'/>
<% gmo = c['gamma'] - 1.0 %>
<% gamma = c['gamma'] %>
<%pyfr:macro name='bc_rsolve_state' params='ul, nl, ur' externs='ploc, t'>
fpdtype_t cs = sqrt(${gamma}*${c['p']}/${c['rho']});
fpdtype_t s = ${c['p']}*pow(${c['rho']}, -${gamma});
fpdtype_t ratio = cs*${2.0/gmo};
fpdtype_t inv = 1.0/ul[0];
fpdtype_t V_e = ${' + '.join('{0}*nl[{1}]'.format(c['uvw'[i]], i)
for i in range(ndims))};
fpdtype_t V_i = inv*(${' + '.join('ul[{1}]*nl[{0}]'.format(i, i + 1)
for i in range(ndims))});
fpdtype_t p_i = ${gmo}*ul[${nvars - 1}]
- ${0.5*gmo}*inv*${pyfr.dot('ul[{i}]', i=(1, ndims + 1))};
fpdtype_t c_i = sqrt(${gamma}*p_i*inv);
fpdtype_t R_e = (fabs(V_e) >= cs && V_i >= 0)
? V_i - c_i*${2.0/gmo}
: V_e - ratio;
fpdtype_t R_i = (fabs(V_e) >= cs && V_i < 0)
? V_e + ratio
: V_i + c_i*${2.0/gmo};
fpdtype_t V_b = 0.5*(R_e + R_i);
fpdtype_t c_b = ${0.25*gmo}*(R_i - R_e);
fpdtype_t rho_b = (V_i < 0)
? pow((1.0/(${gamma}*s))*c_b*c_b, ${1.0/gmo})
: ul[0]*pow(ul[0]*c_b*c_b/(${gamma}*p_i), ${1.0/gmo});
fpdtype_t p_b = ${1.0/gamma}*rho_b*c_b*c_b;
ur[0] = rho_b;
% for i in range(ndims):
ur[${i + 1}] = (V_i >= 0)
? rho_b*(ul[${i + 1}]*inv + (V_b - V_i)*nl[${i}])
: rho_b*(${c['uvw'[i]]} + (V_b - V_e)*nl[${i}]);
% endfor
ur[${nvars - 1}] = p_b*${1.0/gmo}
+ 0.5*(1.0/ur[0])*${pyfr.dot('ur[{i}]', i=(1, ndims + 1))};
</%pyfr:macro>
| {
"pile_set_name": "Github"
} |
// Copyright 2015 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.
MOVE_TO, 40, 36,
R_CUBIC_TO, 2.2f, 0, 4, -1.8f, 4, -4,
V_LINE_TO, 12,
R_CUBIC_TO, 0, -2.2f, -1.8f, -4, -4, -4,
H_LINE_TO, 8,
R_CUBIC_TO, -2.2f, 0, -4, 1.8f, -4, 4,
R_V_LINE_TO, 20,
R_CUBIC_TO, 0, 2.2f, 1.8f, 4, 4, 4,
H_LINE_TO, 0,
R_V_LINE_TO, 4,
R_H_LINE_TO, 48,
R_V_LINE_TO, -4,
R_H_LINE_TO, -8,
CLOSE,
MOVE_TO, 8, 12,
R_H_LINE_TO, 32,
R_V_LINE_TO, 20,
H_LINE_TO, 8,
V_LINE_TO, 12,
CLOSE,
END
| {
"pile_set_name": "Github"
} |
//
// UnaryOp.cpp
// MNNConverter
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "OpConverter.hpp"
class UnaryOp : public OpConverter {
public:
virtual void run(MNN::OpT* dstOp, const caffe::LayerParameter& parameters, const caffe::LayerParameter& weight);
UnaryOp() {
}
virtual ~UnaryOp() {
}
virtual MNN::OpType opType() {
return MNN::OpType_UnaryOp;
}
virtual MNN::OpParameter type() {
return MNN::OpParameter_UnaryOp;
}
};
void UnaryOp::run(MNN::OpT* dstOp, const caffe::LayerParameter& parameters, const caffe::LayerParameter& weight) {
auto parameter = new MNN::UnaryOpT;
parameter->T = MNN::DataType_DT_FLOAT;
parameter->opType = MNN::UnaryOpOperation_ABS;
dstOp->main.value = parameter;
}
static OpConverterRegister<UnaryOp> ____a("AbsVal");
| {
"pile_set_name": "Github"
} |
import {Component, Input} from "@angular/core";
@Component({
selector: 'color-previewer',
template: `
<div class="color-previewer" [ngStyle]="{color:color}">
Preview Text Color
</div>
`
})
export class ColorPreviewer {
@Input()
color:string;
} | {
"pile_set_name": "Github"
} |
/*
* Copyright 1998 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.io;
/**
* A table to convert Cp858 to Unicode. This converter differs from
* Cp850 is one code point, 0xD5, which changes from \u0131 to \u20AC.
* @author Alan Liu
*/
public class ByteToCharCp858 extends ByteToCharCp850 {
public ByteToCharCp858() {}
public String getCharacterEncoding() {
return "Cp858";
}
protected char getUnicode(int byteIndex) {
// Change single code point with respect to parent.
// Cast to byte to get sign extension to match byteIndex.
return (byteIndex == (byte)0xD5) ? '\u20AC' : super.getUnicode(byteIndex);
}
}
//eof
| {
"pile_set_name": "Github"
} |
package android.service;
public final class NetworkStatsHistoryBucketProto {
public static final long BUCKET_START_MS = 1112396529665L;
public static final long OPERATIONS = 1112396529670L;
public static final long RX_BYTES = 1112396529666L;
public static final long RX_PACKETS = 1112396529667L;
public static final long TX_BYTES = 1112396529668L;
public static final long TX_PACKETS = 1112396529669L;
}
| {
"pile_set_name": "Github"
} |
{
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
#' Programme for International Student Assessment (PISA) 2012 Data for Australia
#'
#' About PISA
#'
#' The Programme for International Student Assessment (PISA) is a triennial international survey which aims to evaluate education systems worldwide by testing the skills and knowledge of 15-year-old students. To date, students representing more than 70 economies have participated in the assessment.
#'
#' While 65 economies took part in the 2012 study, this data set only contains information from the country of Australia.
#'
#' @details \itemize{
#' \item gender : Factor w/ 2 levels "female","male": 1 1 2 2 2 1 1 1 2 1 ...
#' \item age : Factor w/ 4 levels "4","5","6","7": 2 2 2 4 3 1 2 2 2 2 ...
#' \item homework : num 5 5 9 3 2 3 4 3 5 1 ...
#' \item desk : num 1 0 1 1 1 1 1 1 1 1 ...
#' \item room : num 1 1 1 1 1 1 1 1 1 1 ...
#' \item study : num 1 1 1 1 1 1 1 1 1 1 ...
#' \item computer : num 1 1 1 1 1 1 1 1 1 1 ...
#' \item software : num 1 1 1 1 1 1 1 1 1 1 ...
#' \item internet : num 1 1 1 1 1 1 1 1 1 1 ...
#' \item literature : num 0 0 1 0 1 1 1 1 1 0 ...
#' \item poetry : num 0 0 1 0 1 1 0 1 1 1 ...
#' \item art : num 1 0 1 0 1 1 0 1 1 1 ...
#' \item textbook : num 1 1 1 1 1 0 1 1 1 1 ...
#' \item dictionary : num 1 1 1 1 1 1 1 1 1 1 ...
#' \item dishwasher : num 1 1 1 1 0 1 1 1 1 1 ...
#' \item PV1MATH : num 562 565 602 520 613 ...
#' \item PV2MATH : num 569 557 594 507 567 ...
#' \item PV3MATH : num 555 553 552 501 585 ...
#' \item PV4MATH : num 579 538 526 521 596 ...
#' \item PV5MATH : num 548 573 619 547 603 ...
#' \item PV1READ : num 582 617 650 554 605 ...
#' \item PV2READ : num 571 572 608 560 557 ...
#' \item PV3READ : num 602 560 594 517 627 ...
#' \item PV4READ : num 572 564 575 564 597 ...
#' \item PV5READ : num 585 565 620 572 598 ...
#' \item PV1SCIE : num 583 627 668 574 639 ...
#' \item PV2SCIE : num 579 600 665 612 635 ...
#' \item PV3SCIE : num 593 574 620 571 666 ...
#' \item PV4SCIE : num 567 582 592 598 700 ...
#' \item PV5SCIE : num 587 625 656 662 670 ...
#' \item SENWGT_STU : num 0.133 0.133 0.141 0.141 0.141 ...
#' \item possessions: num 10 8 12 9 11 11 10 12 12 11 ...
#' }
#'
#' @docType data
#' @keywords datasets
#' @name australia_PISA2012
#' @usage data(australia_PISA2012)
#' @format A data frame with 8247 rows and 32 variables
#' @source \url{http://www.oecd.org/pisa/pisaproducts/database-cbapisa2012.htm}
NULL
| {
"pile_set_name": "Github"
} |
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/*
* WARNING!
*
* Do not edit this file directly, it is built from the sources at
* https://github.com/mozilla/source-map/
*/
///////////////////////////////////////////////////////////////////////////////
this.EXPORTED_SYMBOLS = [ "SourceMapConsumer", "SourceMapGenerator", "SourceNode" ];
Components.utils.import('resource://gre/modules/devtools/Require.jsm');
| {
"pile_set_name": "Github"
} |
Actor ZombieManSpawner replaces ZombieMan
{
+LOOKALLAROUND
States
{
Spawn:
TNT1 A 0
TNT1 A 0 A_SpawnItemEx("ZombieManPackSpawner",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
TNT1 A 1 ACS_NamedExecuteAlways("StarterPackDynamicProgressionFix",0)
TNT1 A 1 ACS_NamedExecuteAlways("SpawnerScript",0)
Deciding:
TNT1 A 1
loop
DiceRandom:
TNT1 A 0 A_RadiusGive("IsPlayingChaoticRandom", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
DiceMain: // Default spawn preset with a slight difficulty curve. Tier 1-4 Monster presets are contained here to provide more variety.
EarlyLevelMob:
TNT1 A 0 A_Jump(1,"RifleCommandoPack")
TNT1 A 0 A_Jump(6,"ScientistZombiePack2")
TNT1 A 0 A_Jump(8,"ScientistZombiePack")
TNT1 A 0 A_Jump(1,"PlasmaZombiePack")
TNT1 A 0 A_Jump(1,"MinigunZombiePack")
TNT1 A 0 A_Jump(1,"CarbineZombiePack")
TNT1 A 0 A_Jump(14,"MixedZombieManPack")
TNT1 A 0 A_Jump(16,"HelmetPistolZombieManPack")
TNT1 A 0 A_Jump(28,"PistolZombieManPack")
TNT1 A 0 A_Jump(16,"HelmetZombieManPack")
GoTo NormalZombieManPack
LowLevelMob:
TNT1 A 0 A_Jump(2,"RifleCommandoPack")
TNT1 A 0 A_Jump(6,"ScientistZombiePack2")
TNT1 A 0 A_Jump(8,"ScientistZombiePack")
TNT1 A 0 A_Jump(4,"PlasmaZombiePack")
TNT1 A 0 A_Jump(6,"MinigunZombiePack")
TNT1 A 0 A_Jump(7,"CarbineZombiePack")
TNT1 A 0 A_Jump(16,"MixedZombieManPack")
TNT1 A 0 A_Jump(20,"HelmetPistolZombieManPack")
TNT1 A 0 A_Jump(34,"PistolZombieManPack")
TNT1 A 0 A_Jump(20,"HelmetZombieManPack")
Goto NormalZombieManPack
MidLevelMob:
TNT1 A 0 A_Jump(6,"RifleCommandoPack")
TNT1 A 0 A_Jump(6,"ScientistZombiePack2")
TNT1 A 0 A_Jump(8,"ScientistZombiePack")
TNT1 A 0 A_Jump(18,"PlasmaZombiePack")
TNT1 A 0 A_Jump(45,"MinigunZombiePack")
TNT1 A 0 A_Jump(51,"CarbineZombiePack")
TNT1 A 0 A_Jump(18,"MixedZombieManPack")
TNT1 A 0 A_Jump(24,"HelmetPistolZombieManPack")
TNT1 A 0 A_Jump(28,"PistolZombieManPack")
TNT1 A 0 A_Jump(24,"HelmetZombieManPack")
Goto NormalZombieManPack
HighLevelMob:
TNT1 A 0 A_Jump(7,"RifleCommandoPack")
TNT1 A 0 A_Jump(8,"ScientistZombiePack2")
TNT1 A 0 A_Jump(22,"PlasmaZombiePack")
TNT1 A 0 A_Jump(56,"MinigunZombiePack")
TNT1 A 0 A_Jump(56,"CarbineZombiePack")
TNT1 A 0 A_Jump(20,"MixedZombieManPack")
TNT1 A 0 A_Jump(26,"HelmetPistolZombieManPack")
TNT1 A 0 A_Jump(26,"PistolZombieManPack")
TNT1 A 0 A_Jump(26,"HelmetZombieManPack")
Goto NormalZombieManPack
DiceProg: // Progressive spawn preset enforces strict spawning rules by excluding monsters until they are presented in later levels.
DiceTier1:
TNT1 A 0 A_Jump(14,"ScientistZombiePack")
TNT1 A 0 A_Jump(100,"MixedZombieManPack")
TNT1 A 0 A_Jump(16,"HelmetPistolZombieManPack")
TNT1 A 0 A_Jump(28,"PistolZombieManPack")
TNT1 A 0 A_Jump(16,"HelmetZombieManPack")
Goto NormalZombieManPack
DiceTier2:
TNT1 A 0 A_Jump(13,"ScientistZombiePack2")
TNT1 A 0 A_Jump(32,"MixedZombieManPack")
TNT1 A 0 A_Jump(20,"HelmetPistolZombieManPack")
TNT1 A 0 A_Jump(34,"PistolZombieManPack")
TNT1 A 0 A_Jump(20,"HelmetZombieManPack")
Goto NormalZombieManPack
DiceTier3:
TNT1 A 0 A_Jump(6,"RifleCommandoPack")
TNT1 A 0 A_Jump(13,"ScientistZombiePack2")
TNT1 A 0 A_Jump(35,"PlasmaZombiePack")
TNT1 A 0 A_Jump(45,"MinigunZombiePack")
TNT1 A 0 A_Jump(51,"CarbineZombiePack")
TNT1 A 0 A_Jump(32,"MixedZombieManPack")
TNT1 A 0 A_Jump(24,"HelmetPistolZombieManPack")
TNT1 A 0 A_Jump(28,"PistolZombieManPack")
TNT1 A 0 A_Jump(24,"HelmetZombieManPack")
Goto NormalZombieManPack
DiceTier4:
TNT1 A 0 A_Jump(7,"RifleCommandoPack")
TNT1 A 0 A_Jump(13,"ScientistZombiePack2")
TNT1 A 0 A_Jump(44,"PlasmaZombiePack")
TNT1 A 0 A_Jump(56,"MinigunZombiePack")
TNT1 A 0 A_Jump(56,"CarbineZombiePack")
TNT1 A 0 A_Jump(32,"MixedZombieManPack")
TNT1 A 0 A_Jump(26,"HelmetPistolZombieManPack")
TNT1 A 0 A_Jump(26,"PistolZombieManPack")
TNT1 A 0 A_Jump(26,"HelmetZombieManPack")
Goto NormalZombieManPack
DiceDeathWish:
TNT1 A 0 A_Jump(7,"RifleCommandoPack")
TNT1 A 0 A_Jump(13,"ScientistZombiePack2")
TNT1 A 0 A_Jump(58,"PlasmaZombiePack")
TNT1 A 0 A_Jump(60,"MinigunZombiePack")
TNT1 A 0 A_Jump(62,"CarbineZombiePack")
Goto MixedZombieManPack
MixedZombieManPack: // This is where the pack tokens are distributed
TNT1 A 0 A_RadiusGive("IsMixedZombieManPack", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
RifleCommandoPack:
TNT1 A 0 A_RadiusGive("IsRifleCommando", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
PlasmaZombiePack:
TNT1 A 0 A_RadiusGive("IsPlasmaZombie", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
MinigunZombiePack:
TNT1 A 0 A_RadiusGive("IsMinigunZombie", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
CarbineZombiePack:
TNT1 A 0 A_RadiusGive("IsCarbineZombie", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
ScientistZombiePack:
TNT1 A 0 A_RadiusGive("IsScientistZombie", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
ScientistZombiePack2:
TNT1 A 0 A_RadiusGive("IsScientistZombie2", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
HelmetPistolZombieManPack:
TNT1 A 0 A_RadiusGive("IsHelmetPistolZombieMan", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
PistolZombieManPack:
TNT1 A 0 A_RadiusGive("IsPistolZombieMan", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
HelmetZombieManPack:
TNT1 A 0 A_RadiusGive("IsHelmetZombieMan", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
NormalZombieManPack:
ReplaceBrutalOnly:
ReplaceVanilla:
ReplaceTraditional:
TNT1 A 0 A_RadiusGive("IsNormalZombieMan", 290, RGF_GIVESELF | RGF_MONSTERS | RGF_ITEMS | RGF_NOSIGHT, 1)
Stop
}
}
Actor ZombieManPackSpawner : Demonpickup
{
+LOOKALLAROUND
States
{
Spawn:
TNT1 A 3
TNT1 A 0 A_JumpIfInventory("IsPlayingChaoticRandom", 1, "RandomSpawn")
TNT1 A 0 A_JumpIfInventory("IsRifleCommando", 1, "SpawnRifleCommando")
TNT1 A 0 A_JumpIfInventory("IsPlasmaZombie", 1, "SpawnPlasmaZombie")
TNT1 A 0 A_JumpIfInventory("IsMinigunZombie", 1, "SpawnMinigunZombie")
TNT1 A 0 A_JumpIfInventory("IsCarbineZombie", 1, "SpawnCarbineZombie")
TNT1 A 0 A_JumpIfInventory("IsScientistZombie2", 1, "SpawnScientistZombie2")
TNT1 A 0 A_JumpIfInventory("IsScientistZombie", 1, "SpawnScientistZombie")
TNT1 A 0 A_JumpIfInventory("IsMixedZombieManPack", 1, "SpawnMixedZombieman")
TNT1 A 0 A_JumpIfInventory("IsHelmetPistolZombieMan", 1, "SpawnHelmetPistolZombieMan")
TNT1 A 0 A_JumpIfInventory("IsPistolZombieMan", 1, "SpawnPistolZombieMan")
TNT1 A 0 A_JumpIfInventory("IsHelmetZombieMan", 1, "SpawnHelmetZombieMan")
TNT1 A 0 A_JumpIfInventory("IsNormalZombieMan", 1, "SpawnNormalZombieMan")
Loop
RandomSpawn:
TNT1 A 0 A_Jump(256, "SpawnScientistZombie2", "SpawnRifleCommando", "SpawnPlasmaZombie", "SpawnMinigunZombie", "SpawnCarbineZombie", "SpawnScientistZombie", "SpawnHelmetPistolZombieMan", "SpawnPistolZombieMan", "SpawnHelmetZombieMan", "SpawnNormalZombieMan")
SpawnMixedZombieman:
TNT1 A 0 A_Jump(256, "SpawnScientistZombie", "SpawnScientistZombie2", "SpawnHelmetPistolZombieMan", "SpawnPistolZombieMan", "SpawnHelmetZombieMan", "SpawnNormalZombieMan")
Stop
SpawnRifleCommando:
TNT1 A 1 ACS_NamedExecuteAlways("ToggleRifleCommando",0)
TNT1 A 0 A_SpawnItemEx("RifleCommando",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnPlasmaZombie:
TNT1 A 1 ACS_NamedExecuteAlways("TogglePlasmaZombie",0)
TNT1 A 0 A_SpawnItemEx("PlasmaZombie",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnMinigunZombie:
TNT1 A 1 ACS_NamedExecuteAlways("ToggleMinigunZombie",0)
TNT1 A 0 A_SpawnItemEx("MinigunGuy",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnCarbineZombie:
TNT1 A 1 ACS_NamedExecuteAlways("ToggleCarbineZombie",0)
TNT1 A 0 A_SpawnItemEx("PB_CarbineZombieman",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnScientistZombie:
TNT1 A 1 ACS_NamedExecuteAlways("ToggleScientistZombie",0)
TNT1 A 0 A_SpawnItemEx("PB_ZombieScientist",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnScientistZombie2:
TNT1 A 1 ACS_NamedExecuteAlways("ToggleScientistZombie",0)
TNT1 A 0 A_Jump(100, 2)
TNT1 A 0 A_SpawnItemEx("PB_ZombieScientist",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
TNT1 A 0 A_SpawnItemEx("PB_ZombieScientistChainsaw",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnHelmetPistolZombieMan:
TNT1 A 1 ACS_NamedExecuteAlways("ToggleHelmetZombie",0)
TNT1 A 0 A_SpawnItemEx("PB_PistolZombieman2",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnPistolZombieMan:
TNT1 A 1 ACS_NamedExecuteAlways("TogglePistolZombie",0)
TNT1 A 0 A_SpawnItemEx("PB_PistolZombieman1",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnHelmetZombieMan:
TNT1 A 1 ACS_NamedExecuteAlways("ToggleHelmetZombie",0)
TNT1 A 0 A_SpawnItemEx("PB_HelmetZombieman",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
SpawnNormalZombieMan:
ReplaceToggle:
TNT1 A 0 A_SpawnItemEx("PB_ZombieMan",0,0,0,0,0,0,0,SXF_TRANSFERSPECIAL | SXF_TRANSFERAMBUSHFLAG | SXF_TRANSFERPOINTERS | 288,0,tid)
Stop
}
} | {
"pile_set_name": "Github"
} |
$: << '../lib' << 'lib'
require 'eventmachine'
require 'em-http'
EventMachine.run {
multi = EventMachine::MultiRequest.new
reqs = [
'http://google.com/',
'http://google.ca:81/'
]
reqs.each_with_index do |url, idx|
http = EventMachine::HttpRequest.new(url, :connect_timeout => 1)
req = http.get
multi.add idx, req
end
multi.callback do
p multi.responses[:callback].size
p multi.responses[:errback].size
EventMachine.stop
end
}
| {
"pile_set_name": "Github"
} |
{
"word": "Irreversible",
"definitions": [
"Not able to be undone or altered."
],
"parts-of-speech": "Adjective"
} | {
"pile_set_name": "Github"
} |
package Paws::AlexaForBusiness::UpdateBusinessReportSchedule;
use Moose;
has Format => (is => 'ro', isa => 'Str');
has Recurrence => (is => 'ro', isa => 'Paws::AlexaForBusiness::BusinessReportRecurrence');
has S3BucketName => (is => 'ro', isa => 'Str');
has S3KeyPrefix => (is => 'ro', isa => 'Str');
has ScheduleArn => (is => 'ro', isa => 'Str', required => 1);
has ScheduleName => (is => 'ro', isa => 'Str');
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'UpdateBusinessReportSchedule');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::AlexaForBusiness::UpdateBusinessReportScheduleResponse');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::AlexaForBusiness::UpdateBusinessReportSchedule - Arguments for method UpdateBusinessReportSchedule on L<Paws::AlexaForBusiness>
=head1 DESCRIPTION
This class represents the parameters used for calling the method UpdateBusinessReportSchedule on the
L<Alexa For Business|Paws::AlexaForBusiness> service. Use the attributes of this class
as arguments to method UpdateBusinessReportSchedule.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to UpdateBusinessReportSchedule.
=head1 SYNOPSIS
my $a4b = Paws->service('AlexaForBusiness');
my $UpdateBusinessReportScheduleResponse =
$a4b->UpdateBusinessReportSchedule(
ScheduleArn => 'MyArn',
Format => 'CSV', # OPTIONAL
Recurrence => {
StartDate => 'MyDate', # OPTIONAL
}, # OPTIONAL
S3BucketName => 'MyCustomerS3BucketName', # OPTIONAL
S3KeyPrefix => 'MyS3KeyPrefix', # OPTIONAL
ScheduleName => 'MyBusinessReportScheduleName', # OPTIONAL
);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
For the AWS API documentation, see L<https://docs.aws.amazon.com/goto/WebAPI/a4b/UpdateBusinessReportSchedule>
=head1 ATTRIBUTES
=head2 Format => Str
The format of the generated report (individual CSV files or zipped
files of individual files).
Valid values are: C<"CSV">, C<"CSV_ZIP">
=head2 Recurrence => L<Paws::AlexaForBusiness::BusinessReportRecurrence>
The recurrence of the reports.
=head2 S3BucketName => Str
The S3 location of the output reports.
=head2 S3KeyPrefix => Str
The S3 key where the report is delivered.
=head2 B<REQUIRED> ScheduleArn => Str
The ARN of the business report schedule.
=head2 ScheduleName => Str
The name identifier of the schedule.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method UpdateBusinessReportSchedule in L<Paws::AlexaForBusiness>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: L<https://github.com/pplu/aws-sdk-perl>
Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues>
=cut
| {
"pile_set_name": "Github"
} |
E
M 我刚看过了
M 我们有伯爵茶,英式早餐茶,肉桂茶
M 菊花茶,薄荷茶,黑莓茶
M 还有…柠檬派
E
M 你不是那个要喝茶的人对吧?
M 六人行 第1季 第19集 猴子被送走
E
M 瑞秋,你有信
M 谢谢
M 酷,免费试喝的咖啡
M 太好了,因为在哪儿还有免费的咖啡?
M 哦,是啊
E
M 太好了
M 那是什么?
M 乡村俱乐部的每日公报
M 我妈寄来通知有人要订婚了
M 噢,我的天!是巴瑞和明蒂
M 巴瑞,你几乎…
M 明蒂,你的伴娘
M 我看看,那是明蒂?
M 真漂亮!
E
M 她真幸运…
M 有你这样的朋友
M 现在是静默时间
E
M 马修,拿饭给我,快…
M 好小子.把饭给我
M 真乖,谢谢
M 他终于能分辨“拿来”和“尿在”的差别了
E
M 瑞秋怎么啦?
M 抱歉
M 我真是太笨了
M 是我不要巴瑞的,对吧?
M 我应该为他们高兴
M 我…真为他们高兴
M 真的?
M 如果我和别人在一起就不同了
M 谁,什么…
E
M 你不是说要忘了那段感情,不再和男人在一起
M 厌恶男人吗?
E
M 我不知道
M 我想这不是没有男人的问题, 而是合适男人的问题
M 和巴瑞在一起安全自在 但是没有激情
M 和保罗在一起就充满激情
M 如野兽般原始的性爱
M 好了,我懂
M 我看过你们两个在一起的样子
M 你认为我能两者同时拥有吗?
M 找到一个能当知己 又能让我感受到激情的人?
M 是呀
M 我也这么认为.我真的这么认为
M 其实说来好笑
M 时常你认为
M 无法让你感受到激情的人
M 却是…
E
M 被打断了
M 电影如何?
M 很不错
M 很不错
M 逊毙了
M 根本是小妞们看的嘛
E
M 真遗撼这不是枪林弹雨
M 公车速度奇快的那种电影
E
M 暴力并不能吸引我
M 只要有裸体镜头我就满足了
M 那电影也有裸体镜头
M 我是指女生的裸体镜头
M 我不爱看卢葛兰的春宫
M 休葛兰特!
E
M 我得走了
M 走吧,马修,快
M 我们去洗澡,对不对?对
M 他们只是朋友吗?
E
M 明天见
M 对,你明天要到瑞秋阿姨家
M 等等,摩尼卡阿姨能说句话吗?
M 摩尼卡阿姨请说?
M 别紧张了,你不会在这儿的
E
M 我无法相信我们竟在讨论此事
M 我同意,我也无法相信
M 如果你和瑞秋会爱情产生的话? 还会一直拖到现在吗?
M 她说她在寻找像我这样的人
M 她真的这样说?
M “像我这样”是我自己加的
M 她说她在寻找某人,而此人今晚就会出现
M 今天晚上?
M 这样最好不过了,因为只有我们两个
M 她整天都在照顾我的猴子
E
M 我早已忘记哪个女人照顾过我的猴子
M 总之下班后我要去买瓶酒…
M 去向她“示爱”
E
M Know what you should do? 知道你该怎么做吗?
M 带她回到用“示爱”的十九世纪去
E
M 如果你继续这样,我发誓这星期内 你就可以和这个浑蛋结束
M 围羽毛围巾的是法博土
M 她曾是个男人
M 蕾文出现了
M 我们讨厌她,真高兴她就快死了
M 什么?马修!
M 想玩摩妮卡的鞋吗?你不能玩…
E
M 马修,你在鞋里大便?
M 天啊,坏猴子
M 哦,天哪!
E
M 抱歉,巴瑞
M 一份小小的订婚礼物
M 我相信你没登记
E
M 谁死了?谁死了?
M 翻过去!好不好,翻过去!
M 好吧,我们知道不是崔斯勒, 因为…马修?…
M 马修?
E
M 你怎会把它弄丢了呢?
M 天晓得
M 我正在看电视, 它在摩妮卡的鞋内大便
M 它在我的鞋里大便?哪一双?
M 我不知道,左脚
M 是哪一双?
M 搭配什么都好看的阿米许鞋
E
M 为何一片愁云惨雾?
M 瑞秋把马修弄丢了
M 不会吧,怎么丢的?
M 它在我鞋里大便
M 哪只?
M 我常穿的那只可爱黑鞋
M 是哪一只?
M 左脚还右脚?
M 因为左脚是幸运鞋
M 大家快想办法!我该怎么办?
M 有了,如果你是只猴子,迷失在大城市时
M 你会去哪儿?
M 这是它第一次出门, 所以大概和一般游客一样
E
M 我去百老汇找.你去俄罗斯茶坊
M 别再闹了!
M 他马上就会回家,他不会饶过我的
M 我们从这栋公寓开始找起 你们找一楼和二楼,菲比和我找三楼和四楼
M 我该怎么办?
M 你留在家里等电话
M 在我鞋内啧芳香剂,顺便等罗斯回来杀你
M 有人要交换吗?
E
M 干嘛?
M 哈克先生,我们朋友遗失了一只猴子 你有看见吗?
M 我放了威化饼在这儿,是不是你拿了?
M 你怎会放威化饼在走廊?
M 我还不想吃
M 你有看见猴子吗?
E
M 我看过“理吉斯菲邦”
M 谢谢你,哈克先生
M 你们欠我威化饼
E
M 他是一只白脸的黑卷尾猴
M 加俄国酱外加腌黄瓜
M 好,谢谢
E
M 今天过得如何?
M 很好啊!很好啊.真的很不错
M 那是酒吗?
M 是的,想喝吗?
M 我非常乐意来点
M 可是我们别在这儿喝
M 我感觉有点疯狂,我们去纽华克好吗?
E
M 前往这东北犯罪首府之前…
M …我有些话想说
M 我们曾谈过…
M …感情的问题
M 罗斯,我受不了了!
M 你回绝得倒是很快嘛
E
M 哦,上帝啊!
M 好吧,好吧
M 罗斯,别恨我
M 到底是什么?
E
M 马修它…
M 我把它…弄丢了
E
M 我真不敢相信
M 我只是麻烦你别让它跑出去
M 我知道,对不起
M 不,我该负一半的责任
M 我不该叫你照顾猴子
M 应该叫你照顾铅笔才对
M 罗斯,我已尽最大的努力 我已叫大家分头去找
E
M 是谁?
M 动物控制中心
M 瞧,我甚至打给动物控制中心
M 你打给动物控制中心?
M 怎么了?你不喜欢他们?
E
M 马修是非法的外来动物
M 我是非法饲养.万一被他们找到他们就会带走它
M 好吧,可是,你从来就没有告诉大家
M 没错,因为我没想到你会请他们来
E
M 谢谢你来
M 有人遗失猴子?
M 对,这完全是个误会
M 我以为我们有养猴子, 但是我们没有
M 结果是帽子
M 猫!
E
M 我们查过了,没人看到马修
M 我叔叔马修
M 那猴子是以你叔叔命名?
M 你知道持有非法外来动物
M 可判刑两年并没收动物?
M 天啊
M 你要把这可怜的小东西关进监牢?
E
M 菲比,你记得如何先对自己小声说吗?
M 记得,但总不是时候
E
M 我相信我们能以友善的处理方式,请坐
M 首先,我们还没自己介绍,我叫摩妮卡
M 天啊,你是莫尼卡
M 还有,你是瑞秋对吗?
E
M 露莎,林肯高中
M 我坐在你们后面
M 露莎!哦,天哪!
M 摩妮卡,是露莎
E
M 我也去了那里!
M 是在后面那个?
E
M 你们根本不知道我是谁对不?
M 一点也不
M 或许你们那四年,都在当我不存在
M 难道说“早安,露莎”
M 或“好漂亮的连身裤”有那么困难吗?
E
M 对不起
M 我不怪你,你当时很胖, 你有自己的烦恼
M 可是你实在是个贱货
E
M 什么?
M 别计较了
M 你真认为你能帮我们找猴子? 看在过去的份上?
M 帮我们找
M 我可以,我不
M 如果我找到猴子,它就是我的了
E
M 抱歉
M 马修?
M 马修?
E
M 需要帮忙吗?
M 我们有急事,我们在找东西
M 猴子
M 对,你有看见吗?
M 我没看见猴子
M 你知道如何修理散热器吗?
M 当然!你试过将转钮转回去吗?
M 当然!
M 那之后我就不知道了
E
M 试试这个是不是加太多兰姆酒了?
M 等等
M 希望你们能找到猴子
M 不,等等
M 我们对散热器或许不太懂
M 我们可是冷暖环境的专家
E
M 我们不是正在忙吗?
M 对,她们很热而且需要帮助
M 而且很火辣
E
M 我们不行
M 抱歉你们不知道
M 我们有多抱歉,我们答应人家要找猴子
M 它约这么高,名叫马修
M 如果能拥有你们的照片,就算是帮了大忙
E
M 从现在起不准你和其他人讲话
E
M 噢,我的天!
M 什么?
M 有东西碰到我的右脚
M 没什么,是我的左脚
E
M 看,菲比
M 马修,过来…
M 站过去,两位小姐
E
M 你要干什么?
M 打镇定剂
E
M 快跑,马修,快跑!
M 坏了!
M 你还好吧?
M 还行.哦
E
M 哦,糟了!
E
M 我们把周围的邻居都找遍了, 它不见了,就这么消失了
M 罗斯,还不一定
M 拜托,天气好冷天又黑
M 它根本不认识路!
M 现在我的脚又受伤了, 猴子没了还换来受伤的脚
M 真的感谢你!
M 罗斯,我已向你道歉过无数次
M 你到底要我怎么样?
M 你也要我的脚受伤?要我也把脚弄伤
M 瞧,高兴了吧
M 对,你踢完路标后
M 我突然不再想念马修了
E
M 我真的不是故意的
M 当然,这是典型的瑞秋
M 这种事常发生在你身上
M 你活在自己的世界中 做着自己的事情…
M 完全无视别人的猴子, 或是别人的感觉…
M 罗斯,我不想听!忘了他,好不好?
M 什么?
E
M 嗨,香蕉男!
E
M 这下可好
M 一边的屁股在睡觉, 另一边却毫无所知
E
M 菲比怎么啦?
M 麻醉枪
M 你有订香蕉吗?
M 那是干吗的?
M 还我的猴子
M 我没猴子
M 干嘛买一箱香蕉?
M 补充钾
E
M 马修?它在哪儿?
M 你在浪费时间
M 什么?
E
M 你对他干了什么?
M 这是我的猴子,它叫佩蒂
M 你疯了不成?过来,马修…
M 过来,佩蒂
M 过来,马修…
M 过来,佩蒂
M 猴子过来…
M 过来,猴子!
M 总算逮到你了
M 把我的猴子还给我
M 那是我的猴子
M 你们到法官面前去争吧
M 那不是我的猴子 只有衣服是我的,随时可以送回来
M 好吧,我要我的猴子!
M 露莎,拜托
M 抱歉了,舞会皇后
M 你高中时干嘛那么贱,为何不当个胖妹?
E
M 在学校我是舞会皇后
M 返校皇后,但是你
M 你也在的啊
M 但是这不是高中,我们现在都是成年人!
M 我能要这个吗?
M 随意
M 如果你把猴子带走 我将失去我生命中重要的人
M 你可以恨我,请别折磨他
M 此时你有机会成为大人物
M 把握机会吧
E
M 不
M 那么,我只好告诉你的长官
M 你在我朋友的屁股上开了一枪
E
M 终于能脱去这件衣服,不是吗?
M 或是这样也不错
M 配上鞋就是完整的一套
E
M 抱歉,我对你这么凶
M 不,这都是我的错,我差点…
M 不,它也是你找回来的,你做得很好
E
M 那瓶酒还在
M 有心情喝杯葡萄酒吗?
M 好呀
M 很好
E
M 隔壁一定在用吸尘器
E
M 只要我们在这儿…
M …不谈那个话题…
M 我在想…
E
M …我们刚刚实在是恶言相向
M 大概是因为我们…
M 瑞秋?
M 瑞秋?
M 我办不到.我无法和明蒂结婚
M 我想我爱的人依然是你
E
M 我们得开始锁门了!
E
M 给我们看看!来吗!
M 很久很久以前
M 好吧
M 这是我在“音乐之声”里面, 看见范崔普的孩子吗?
M 因为我挡在他们前面
M 大修女!
M 我以为那是阿尔卑斯山
M 我的高中时代并不如意
M 我爱高中
M 四年的舞会,约会和做爱
M 我和400个男孩上的住宿学校
M 每次做爱都是一次生活方式的重大抉择
E
M 天啊,那不是回到史前时代?
M 我的屁股醒了
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.tools.doclets.Taglet;
import com.sun.javadoc.*;
import java.util.Map;
/**
* A sample Taglet representing @todo. This tag can be used in any kind of
* {@link com.sun.javadoc.Doc}. It is not an inline tag. The text is displayed
* in yellow to remind the developer to perform a task. For
* example, "@todo Fix this!" would be shown as:
* <DL>
* <DT>
* <B>To Do:</B>
* <DD><table cellpadding=2 cellspacing=0><tr><td bgcolor="yellow">Fix this!
* </td></tr></table></DD>
* </DL>
*
* @author Jamie Ho
* @since 1.4
*/
public class ToDoTaglet implements Taglet {
private static final String NAME = "todo";
private static final String HEADER = "To Do:";
/**
* Return the name of this custom tag.
*/
public String getName() {
return NAME;
}
/**
* Will return true since <code>@todo</code>
* can be used in field documentation.
* @return true since <code>@todo</code>
* can be used in field documentation and false
* otherwise.
*/
public boolean inField() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in constructor documentation.
* @return true since <code>@todo</code>
* can be used in constructor documentation and false
* otherwise.
*/
public boolean inConstructor() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in method documentation.
* @return true since <code>@todo</code>
* can be used in method documentation and false
* otherwise.
*/
public boolean inMethod() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in method documentation.
* @return true since <code>@todo</code>
* can be used in overview documentation and false
* otherwise.
*/
public boolean inOverview() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in package documentation.
* @return true since <code>@todo</code>
* can be used in package documentation and false
* otherwise.
*/
public boolean inPackage() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in type documentation (classes or interfaces).
* @return true since <code>@todo</code>
* can be used in type documentation and false
* otherwise.
*/
public boolean inType() {
return true;
}
/**
* Will return false since <code>@todo</code>
* is not an inline tag.
* @return false since <code>@todo</code>
* is not an inline tag.
*/
public boolean isInlineTag() {
return false;
}
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
public static void register(Map tagletMap) {
ToDoTaglet tag = new ToDoTaglet();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
* @param tag the <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
return "<DT><B>" + HEADER + "</B><DD>"
+ "<table cellpadding=2 cellspacing=0><tr><td bgcolor=\"yellow\">"
+ tag.text()
+ "</td></tr></table></DD>\n";
}
/**
* Given an array of <code>Tag</code>s representing this custom
* tag, return its string representation.
* @param tags the array of <code>Tag</code>s representing of this custom tag.
*/
public String toString(Tag[] tags) {
if (tags.length == 0) {
return null;
}
String result = "\n<DT><B>" + HEADER + "</B><DD>";
result += "<table cellpadding=2 cellspacing=0><tr><td bgcolor=\"yellow\">";
for (int i = 0; i < tags.length; i++) {
if (i > 0) {
result += ", ";
}
result += tags[i].text();
}
return result + "</td></tr></table></DD>\n";
}
}
| {
"pile_set_name": "Github"
} |
define("ace/snippets/groovy",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText =undefined;
exports.scope = "groovy";
});
| {
"pile_set_name": "Github"
} |
import collections
import torch
import itertools
from typing import List
import math
SSDBoxSizes = collections.namedtuple('SSDBoxSizes', ['min', 'max'])
SSDSpec = collections.namedtuple('SSDSpec', ['feature_map_size', 'shrinkage', 'box_sizes', 'aspect_ratios'])
def generate_ssd_priors(specs: List[SSDSpec], image_size, clamp=True) -> torch.Tensor:
"""Generate SSD Prior Boxes.
It returns the center, height and width of the priors. The values are relative to the image size
Args:
specs: SSDSpecs about the shapes of sizes of prior boxes. i.e.
specs = [
SSDSpec(38, 8, SSDBoxSizes(30, 60), [2]),
SSDSpec(19, 16, SSDBoxSizes(60, 111), [2, 3]),
SSDSpec(10, 32, SSDBoxSizes(111, 162), [2, 3]),
SSDSpec(5, 64, SSDBoxSizes(162, 213), [2, 3]),
SSDSpec(3, 100, SSDBoxSizes(213, 264), [2]),
SSDSpec(1, 300, SSDBoxSizes(264, 315), [2])
]
image_size: image size.
clamp: if true, clamp the values to make fall between [0.0, 1.0]
Returns:
priors (num_priors, 4): The prior boxes represented as [[center_x, center_y, w, h]]. All the values
are relative to the image size.
"""
priors = []
for spec in specs:
scale = image_size / spec.shrinkage
for j, i in itertools.product(range(spec.feature_map_size), repeat=2):
x_center = (i + 0.5) / scale
y_center = (j + 0.5) / scale
# small sized square box
size = spec.box_sizes.min
h = w = size / image_size
priors.append([
x_center,
y_center,
w,
h
])
# big sized square box
size = math.sqrt(spec.box_sizes.max * spec.box_sizes.min)
h = w = size / image_size
priors.append([
x_center,
y_center,
w,
h
])
# change h/w ratio of the small sized box
size = spec.box_sizes.min
h = w = size / image_size
for ratio in spec.aspect_ratios:
ratio = math.sqrt(ratio)
priors.append([
x_center,
y_center,
w * ratio,
h / ratio
])
priors.append([
x_center,
y_center,
w / ratio,
h * ratio
])
priors = torch.tensor(priors)
if clamp:
torch.clamp(priors, 0.0, 1.0, out=priors)
return priors
def convert_locations_to_boxes(locations, priors, center_variance,
size_variance):
"""Convert regressional location results of SSD into boxes in the form of (center_x, center_y, h, w).
The conversion:
$$predicted\_center * center_variance = \frac {real\_center - prior\_center} {prior\_hw}$$
$$exp(predicted\_hw * size_variance) = \frac {real\_hw} {prior\_hw}$$
We do it in the inverse direction here.
Args:
locations (batch_size, num_priors, 4): the regression output of SSD. It will contain the outputs as well.
priors (num_priors, 4) or (batch_size/1, num_priors, 4): prior boxes.
center_variance: a float used to change the scale of center.
size_variance: a float used to change of scale of size.
Returns:
boxes: priors: [[center_x, center_y, h, w]]. All the values
are relative to the image size.
"""
# priors can have one dimension less.
if priors.dim() + 1 == locations.dim():
priors = priors.unsqueeze(0)
return torch.cat([
locations[..., :2] * center_variance * priors[..., 2:] + priors[..., :2],
torch.exp(locations[..., 2:] * size_variance) * priors[..., 2:]
], dim=locations.dim() - 1)
def convert_boxes_to_locations(center_form_boxes, center_form_priors, center_variance, size_variance):
# priors can have one dimension less
if center_form_priors.dim() + 1 == center_form_boxes.dim():
center_form_priors = center_form_priors.unsqueeze(0)
return torch.cat([
(center_form_boxes[..., :2] - center_form_priors[..., :2]) / center_form_priors[..., 2:] / center_variance,
torch.log(center_form_boxes[..., 2:] / center_form_priors[..., 2:]) / size_variance
], dim=center_form_boxes.dim() - 1)
def area_of(left_top, right_bottom) -> torch.Tensor:
"""Compute the areas of rectangles given two corners.
Args:
left_top (N, 2): left top corner.
right_bottom (N, 2): right bottom corner.
Returns:
area (N): return the area.
"""
hw = torch.clamp(right_bottom - left_top, min=0.0)
return hw[..., 0] * hw[..., 1]
def iou_of(boxes0, boxes1, eps=1e-5):
"""Return intersection-over-union (Jaccard index) of boxes.
Args:
boxes0 (N, 4): ground truth boxes.
boxes1 (N or 1, 4): predicted boxes.
eps: a small number to avoid 0 as denominator.
Returns:
iou (N): IoU values.
"""
overlap_left_top = torch.max(boxes0[..., :2], boxes1[..., :2])
overlap_right_bottom = torch.min(boxes0[..., 2:], boxes1[..., 2:])
overlap_area = area_of(overlap_left_top, overlap_right_bottom)
area0 = area_of(boxes0[..., :2], boxes0[..., 2:])
area1 = area_of(boxes1[..., :2], boxes1[..., 2:])
return overlap_area / (area0 + area1 - overlap_area + eps)
def assign_priors(gt_boxes, gt_labels, corner_form_priors,
iou_threshold):
"""Assign ground truth boxes and targets to priors.
Args:
gt_boxes (num_targets, 4): ground truth boxes.
gt_labels (num_targets): labels of targets.
priors (num_priors, 4): corner form priors
Returns:
boxes (num_priors, 4): real values for priors.
labels (num_priros): labels for priors.
"""
# size: num_priors x num_targets
ious = iou_of(gt_boxes.unsqueeze(0), corner_form_priors.unsqueeze(1))
# size: num_priors
best_target_per_prior, best_target_per_prior_index = ious.max(1)
# size: num_targets
best_prior_per_target, best_prior_per_target_index = ious.max(0)
for target_index, prior_index in enumerate(best_prior_per_target_index):
best_target_per_prior_index[prior_index] = target_index
# 2.0 is used to make sure every target has a prior assigned
best_target_per_prior.index_fill_(0, best_prior_per_target_index, 2)
# size: num_priors
labels = gt_labels[best_target_per_prior_index]
labels[best_target_per_prior < iou_threshold] = 0 # the backgournd id
boxes = gt_boxes[best_target_per_prior_index]
return boxes, labels
def hard_negative_mining(loss, labels, neg_pos_ratio):
"""
It used to suppress the presence of a large number of negative prediction.
It works on image level not batch level.
For any example/image, it keeps all the positive predictions and
cut the number of negative predictions to make sure the ratio
between the negative examples and positive examples is no more
the given ratio for an image.
Args:
loss (N, num_priors): the loss for each example.
labels (N, num_priors): the labels.
neg_pos_ratio: the ratio between the negative examples and positive examples.
"""
pos_mask = labels > 0
num_pos = pos_mask.long().sum(dim=1, keepdim=True)
num_neg = num_pos * neg_pos_ratio
loss[pos_mask] = -math.inf
_, indexes = loss.sort(dim=1, descending=True)
_, orders = indexes.sort(dim=1)
neg_mask = orders < num_neg
return pos_mask | neg_mask
def center_form_to_corner_form(locations):
return torch.cat([locations[..., :2] - locations[..., 2:]/2,
locations[..., :2] + locations[..., 2:]/2], locations.dim() - 1)
def corner_form_to_center_form(boxes):
return torch.cat([
(boxes[..., :2] + boxes[..., 2:]) / 2,
boxes[..., 2:] - boxes[..., :2]
], boxes.dim() - 1)
def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200):
"""
Args:
box_scores (N, 5): boxes in corner-form and probabilities.
iou_threshold: intersection over union threshold.
top_k: keep top_k results. If k <= 0, keep all the results.
candidate_size: only consider the candidates with the highest scores.
Returns:
picked: a list of indexes of the kept boxes
"""
scores = box_scores[:, -1]
boxes = box_scores[:, :-1]
picked = []
_, indexes = scores.sort(descending=True)
indexes = indexes[:candidate_size]
while len(indexes) > 0:
current = indexes[0]
picked.append(current.item())
if 0 < top_k == len(picked) or len(indexes) == 1:
break
current_box = boxes[current, :]
indexes = indexes[1:]
rest_boxes = boxes[indexes, :]
iou = iou_of(
rest_boxes,
current_box.unsqueeze(0),
)
indexes = indexes[iou <= iou_threshold]
return box_scores[picked, :]
def nms(box_scores, nms_method=None, score_threshold=None, iou_threshold=None,
sigma=0.5, top_k=-1, candidate_size=200):
if nms_method == "soft":
return soft_nms(box_scores, score_threshold, sigma, top_k)
else:
return hard_nms(box_scores, iou_threshold, top_k, candidate_size=candidate_size)
def soft_nms(box_scores, score_threshold, sigma=0.5, top_k=-1):
"""Soft NMS implementation.
References:
https://arxiv.org/abs/1704.04503
https://github.com/facebookresearch/Detectron/blob/master/detectron/utils/cython_nms.pyx
Args:
box_scores (N, 5): boxes in corner-form and probabilities.
score_threshold: boxes with scores less than value are not considered.
sigma: the parameter in score re-computation.
scores[i] = scores[i] * exp(-(iou_i)^2 / simga)
top_k: keep top_k results. If k <= 0, keep all the results.
Returns:
picked_box_scores (K, 5): results of NMS.
"""
picked_box_scores = []
while box_scores.size(0) > 0:
max_score_index = torch.argmax(box_scores[:, 4])
cur_box_prob = torch.tensor(box_scores[max_score_index, :])
picked_box_scores.append(cur_box_prob)
if len(picked_box_scores) == top_k > 0 or box_scores.size(0) == 1:
break
cur_box = cur_box_prob[:-1]
box_scores[max_score_index, :] = box_scores[-1, :]
box_scores = box_scores[:-1, :]
ious = iou_of(cur_box.unsqueeze(0), box_scores[:, :-1])
box_scores[:, -1] = box_scores[:, -1] * torch.exp(-(ious * ious) / sigma)
box_scores = box_scores[box_scores[:, -1] > score_threshold, :]
if len(picked_box_scores) > 0:
return torch.stack(picked_box_scores)
else:
return torch.tensor([])
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_34) on Tue May 26 09:04:15 BST 2015 -->
<TITLE>
Uses of Class org.apache.fop.render.AbstractRendererConfigurator (Apache FOP 2.0 API)
</TITLE>
<META NAME="date" CONTENT="2015-05-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.fop.render.AbstractRendererConfigurator (Apache FOP 2.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.0</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/fop/render//class-useAbstractRendererConfigurator.html" target="_top"><B>FRAMES</B></A>
<A HREF="AbstractRendererConfigurator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.fop.render.AbstractRendererConfigurator</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render"><B>org.apache.fop.render</B></A></TD>
<TD>Generic renderer interface. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.afp"><B>org.apache.fop.render.afp</B></A></TD>
<TD>An AFP Renderer implementation and supporting classes. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.bitmap"><B>org.apache.fop.render.bitmap</B></A></TD>
<TD>Bitmap Renderer which creates TIFF and PNG images from rendered pages. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.java2d"><B>org.apache.fop.render.java2d</B></A></TD>
<TD>Java2D Renderer which paints rendered pages on Graphics2D instances. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.pcl"><B>org.apache.fop.render.pcl</B></A></TD>
<TD>PCL Renderer (Supports PCL5 and HP GL/2) </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.pdf"><B>org.apache.fop.render.pdf</B></A></TD>
<TD>PDF Renderer </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.ps"><B>org.apache.fop.render.ps</B></A></TD>
<TD>PostScript Renderer </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.txt"><B>org.apache.fop.render.txt</B></A></TD>
<TD>Plain Text Renderer </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/package-summary.html">org.apache.fop.render</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/package-summary.html">org.apache.fop.render</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/DefaultRendererConfigurator.html" title="class in org.apache.fop.render">DefaultRendererConfigurator</A></B></CODE>
<BR>
This object represents the default renderer configurator and contains the methods for most the
RendererConfigurators.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/PrintRendererConfigurator.html" title="class in org.apache.fop.render">PrintRendererConfigurator</A></B></CODE>
<BR>
Base Print renderer configurator (mostly handles font configuration)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/XMLHandlerConfigurator.html" title="class in org.apache.fop.render">XMLHandlerConfigurator</A></B></CODE>
<BR>
Configurator for XMLHandler objects.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.afp"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/afp/package-summary.html">org.apache.fop.render.afp</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/afp/package-summary.html">org.apache.fop.render.afp</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/afp/AFPRendererConfigurator.html" title="class in org.apache.fop.render.afp">AFPRendererConfigurator</A></B></CODE>
<BR>
AFP Renderer configurator</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.bitmap"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/bitmap/package-summary.html">org.apache.fop.render.bitmap</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/bitmap/package-summary.html">org.apache.fop.render.bitmap</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/bitmap/BitmapRendererConfigurator.html" title="class in org.apache.fop.render.bitmap">BitmapRendererConfigurator</A></B></CODE>
<BR>
Configurator for bitmap output.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/bitmap/TIFFRendererConfigurator.html" title="class in org.apache.fop.render.bitmap">TIFFRendererConfigurator</A></B></CODE>
<BR>
TIFF Renderer configurator</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.java2d"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/java2d/package-summary.html">org.apache.fop.render.java2d</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/java2d/package-summary.html">org.apache.fop.render.java2d</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/java2d/Java2DRendererConfigurator.html" title="class in org.apache.fop.render.java2d">Java2DRendererConfigurator</A></B></CODE>
<BR>
Configurerer for Java 2D renderer</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.pcl"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/pcl/package-summary.html">org.apache.fop.render.pcl</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/pcl/package-summary.html">org.apache.fop.render.pcl</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/pcl/PCLRendererConfigurator.html" title="class in org.apache.fop.render.pcl">PCLRendererConfigurator</A></B></CODE>
<BR>
PCL Renderer configurator</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.pdf"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/pdf/package-summary.html">org.apache.fop.render.pdf</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/pdf/package-summary.html">org.apache.fop.render.pdf</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFRendererConfigurator.html" title="class in org.apache.fop.render.pdf">PDFRendererConfigurator</A></B></CODE>
<BR>
PDF renderer configurator.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.ps"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/ps/package-summary.html">org.apache.fop.render.ps</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/ps/package-summary.html">org.apache.fop.render.ps</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/ps/PSRendererConfigurator.html" title="class in org.apache.fop.render.ps">PSRendererConfigurator</A></B></CODE>
<BR>
Postscript renderer config</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.txt"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/txt/package-summary.html">org.apache.fop.render.txt</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render">AbstractRendererConfigurator</A> in <A HREF="../../../../../org/apache/fop/render/txt/package-summary.html">org.apache.fop.render.txt</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/fop/render/txt/TXTRendererConfigurator.html" title="class in org.apache.fop.render.txt">TXTRendererConfigurator</A></B></CODE>
<BR>
TXT Renderer configurator</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.0</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/fop/render//class-useAbstractRendererConfigurator.html" target="_top"><B>FRAMES</B></A>
<A HREF="AbstractRendererConfigurator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2015 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace mojoPortal.Web.Framework
{
/// <summary>
/// Author:
/// Created: 2/6/2006
/// Last Modified: 2/6/2006
/// </summary>
public class mojoEncryptionConfigurationHandler : IConfigurationSectionHandler
{
#region IConfigurationSectionHandler Members
public object Create(object parent, object configContext, XmlNode node)
{
mojoEncryptionConfiguration config = new mojoEncryptionConfiguration();
config.LoadValuesFromConfigurationXml(node);
return config;
}
#endregion
}
}
| {
"pile_set_name": "Github"
} |
// +build OMIT
package string_test
import (
"fmt"
"strings"
"testing"
)
func TestIndex(t *testing.T) {
var tests = []struct {
s string
sep string
out int
}{
{"", "", 0},
{"", "a", -1},
{"fo", "foo", -1},
{"foo", "foo", 0},
{"oofofoofooo", "f", 2},
// etc
}
for _, test := range tests {
actual := strings.Index(test.s, test.sep)
if actual != test.out {
t.Errorf("Index(%q,%q) = %v; want %v", test.s, test.sep, actual, test.out)
}
}
}
func BenchmarkIndex(b *testing.B) {
const s = "some_text=some☺value"
for i := 0; i < b.N; i++ {
strings.Index(s, "v")
}
}
func ExampleIndex() {
fmt.Println(strings.Index("chicken", "ken"))
fmt.Println(strings.Index("chicken", "dmr"))
// Output:
// 4
// -1
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* ALIPAY API: alipay.marketing.voucher.template.delete request
*
* @author auto create
* @since 1.0, 2018-01-30 22:43:25
*/
class AlipayMarketingVoucherTemplateDeleteRequest
{
/**
* 删除资金券模板
**/
private $bizContent;
private $apiParas = array();
private $terminalType;
private $terminalInfo;
private $prodCode;
private $apiVersion="1.0";
private $notifyUrl;
private $returnUrl;
private $needEncrypt=false;
public function setBizContent($bizContent)
{
$this->bizContent = $bizContent;
$this->apiParas["biz_content"] = $bizContent;
}
public function getBizContent()
{
return $this->bizContent;
}
public function getApiMethodName()
{
return "alipay.marketing.voucher.template.delete";
}
public function setNotifyUrl($notifyUrl)
{
$this->notifyUrl=$notifyUrl;
}
public function getNotifyUrl()
{
return $this->notifyUrl;
}
public function setReturnUrl($returnUrl)
{
$this->returnUrl=$returnUrl;
}
public function getReturnUrl()
{
return $this->returnUrl;
}
public function getApiParas()
{
return $this->apiParas;
}
public function getTerminalType()
{
return $this->terminalType;
}
public function setTerminalType($terminalType)
{
$this->terminalType = $terminalType;
}
public function getTerminalInfo()
{
return $this->terminalInfo;
}
public function setTerminalInfo($terminalInfo)
{
$this->terminalInfo = $terminalInfo;
}
public function getProdCode()
{
return $this->prodCode;
}
public function setProdCode($prodCode)
{
$this->prodCode = $prodCode;
}
public function setApiVersion($apiVersion)
{
$this->apiVersion=$apiVersion;
}
public function getApiVersion()
{
return $this->apiVersion;
}
public function setNeedEncrypt($needEncrypt)
{
$this->needEncrypt=$needEncrypt;
}
public function getNeedEncrypt()
{
return $this->needEncrypt;
}
}
| {
"pile_set_name": "Github"
} |
<?php
generate_mock_once('HTMLPurifier_DefinitionCache');
class HTMLPurifier_DefinitionCache_DecoratorHarness extends HTMLPurifier_DefinitionCacheHarness
{
public function setup()
{
$this->mock = new HTMLPurifier_DefinitionCacheMock();
$this->mock->type = 'Test';
$this->cache = $this->cache->decorate($this->mock);
$this->def = $this->generateDefinition();
$this->config = $this->generateConfigMock();
}
public function teardown()
{
unset($this->mock);
unset($this->cache);
}
}
// vim: et sw=4 sts=4
| {
"pile_set_name": "Github"
} |
// German language
(function($) {
elRTE.prototype.i18Messages.de = {
'Editor' : 'Editor',
'Source' : 'Quellcode',
// Panel Name
'Copy/Pase' : 'Kopieren/Einfügen',
'Undo/Redo' : 'Rückgängig/Wiederherstellen',
'Text styles' : 'Textstile',
'Colors' : 'Farbe',
'Alignment' : 'Alignment',
'Indent/Outdent' : 'Einrücken / Ausrücken',
'Text format' : 'Format',
'Lists' : 'Listen',
'Misc elements' : 'Sonstige elemente',
'Links' : 'Link',
'Images' : 'Bild',
'Media' : 'Media datei',
'Tables' : 'Tabelle',
'File manager (elFinder)' : 'Datei-Manager (elFinder)',
// button names
'Save' : 'Speichern',
'Copy' : 'Ausschneiden',
'Cut' : 'Kopieren',
'Paste' : 'Einfügen',
'Paste only text' : 'Fügen sie nur text',
'Paste formatted text' : 'Fügen sie formatierten text',
'Clean format' : 'Formatierungen entfernen',
'Undo last action' : 'Rückgängig',
'Redo previous action' : 'Wiederherstellen',
'Bold' : 'Fett',
'Italic' : 'Kursiv',
'Underline' : 'Unterstrichen',
'Strikethrough' : 'Durchgestrichen',
'Superscript' : 'Hochgestellt',
'Subscript' : 'Tiefgestellt',
'Align left' : 'Linksbündig',
'Ailgn right' : 'Rechtsbündig',
'Align center' : 'Zentriert',
'Align full' : 'Blocksatz',
'Font color' : 'Textfarbe',
'Background color' : 'Hintergrundfarbe',
'Indent' : 'Einzug erhöhen',
'Outdent' : 'Einzug verringern',
'Format' : 'Format',
'Font size' : 'Größe',
'Font' : 'Schriftart',
'Ordered list' : 'Nummerierte Liste',
'Unordered list' : 'Liste',
'Horizontal rule' : 'Horizontale Linie',
'Blockquote' : 'Zitatblock',
'Block element (DIV)' : 'Block-Element (DIV)',
'Link' : 'Link',
'Delete link' : 'Link entfernen',
'Bookmark' : 'Anker einfügen/editieren',
'Image' : 'Bild',
'Table' : 'Tabelle',
'Delete table' : 'Tabelle löschen',
'Insert row before' : 'Zeile oberhalb einfügen',
'Insert row after' : 'Zeile unterhalb einfügen',
'Delete row' : 'Zeile entfernen',
'Insert column before' : 'Spalte links davor einfügen',
'Insert column after' : 'Spalte rechts danach einfügen',
'Delete column' : 'Spalte löschen',
'Merge table cells' : 'Zellen verbinden',
'Split table cell' : 'Zelle teilen',
'Toggle display document structure' : 'Blöcke anzeigen',
'Table cell properties' : 'Zellen-Eigenschaften',
'Table properties' : 'Tabellen-Eigenschaften',
'Toggle full screen mode' : 'Editor maximieren',
'Open file manager' : 'Server',
'Non breakable space' : 'Non-breaking space',
'Stop element floating' : 'Deaktivieren Sie flow-Element Text',
// dialogs
'Warning' : 'ACHTUNG',
'Properies' : 'Properies',
'Popup' : 'Pop-up',
'Advanced' : 'mehr',
'Events' : 'Veranstaltungen',
'Width' : 'Breite',
'Height' : 'Höhe',
'Left' : 'Links',
'Center' : 'Zentrum',
'Right' : 'Rechts',
'Border' : 'Rahmen',
'Background' : 'Hintergrundfarbe',
'Css class' : 'Css class',
'Css style' : 'Css style',
'No' : 'Nein',
'Title' : 'Titel',
'Script direction' : 'Richtung Schreiben',
'Language' : 'Sprache',
'Charset' : 'Charset',
'Not set' : 'nicht',
'Left to right' : 'Links nach Rechts',
'Right to left' : 'Rechts nach Links',
'In this window' : 'Gleiches Fenster (_self)',
'In new window (_blank)' : 'Neues Fenster (_blank)',
'In new parent window (_parent)' : 'Oberes Fenster (_parent)',
'In top frame (_top)' : 'Oberstes Fenster (_top)',
'URL' : '',
'Open in' : '',
// copy
'This operation is disabled in your browser on security reason. Use shortcut instead.' : 'Dieser Vorgang ist in Ihrem Browser aus Sicherheitsgründen deaktiviert. Tastenkombination statt.',
// format
'Heading 1' : 'Überschrift 1',
'Heading 2' : 'Überschrift 2',
'Heading 3' : 'Überschrift 3',
'Heading 4' : 'Überschrift 4',
'Heading 5' : 'Überschrift 5',
'Heading 6' : 'Überschrift 6',
'Paragraph' : 'Formatiert',
'Address' : 'Addresse',
'Preformatted' : '',
// font size
'Small (8pt)' : '',
'Small (10px)' : '',
'Small (12pt)' : '',
'Normal (14pt)' : '',
'Large (18pt)' : '',
'Large (24pt)' : '',
'Large (36pt)' : '',
// bookmark
'Bookmark name' : 'Anker Name',
// link
'Link URL' : '(URL)',
'Target' : 'Zielseite',
'Open link in popup window' : 'Link in einem Popup-Fenster',
'URL' : '',
'Window name' : 'Pop-up Fenster-Name',
'Window size' : 'Größe',
'Window position' : 'Position',
'Location bar' : 'Adress-Leiste',
'Menu bar' : 'Menü-Leiste',
'Toolbar' : 'Werkzeugleiste',
'Scrollbars' : 'Rollbalken',
'Status bar' : 'Statusleiste',
'Resizable' : 'Vergrößerbar',
'Depedent' : 'Abhängig (Netscape)',
'Add return false' : 'add (return false)',
'Target MIME type' : 'MIME type',
'Relationship page to target (rel)' : '',
'Relationship target to page (rev)' : '',
'Tab index' : '',
'Access key' : 'Zugriffstaste',
// image
'Size' : 'Größe',
'Preview' : 'Vorschau',
'Margins' : '',
'Alt text' : 'Alt',
'Image URL' : 'URL',
// table
'Spacing' : 'Abstand (spacing)',
'Padding' : 'Abstand (padding)',
'Rows' : 'Zeile',
'Columns' : 'Spalte',
'Groups' : 'Gruppen',
'Cells' : 'Zellen',
'Caption' : 'Tabellen-Eigenschaften',
'Inner borders' : 'Innere Grenzen'
}
})(jQuery); | {
"pile_set_name": "Github"
} |
import clsx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
import Avatar from '@material-ui/core/Avatar';
import { withStyles } from '@material-ui/core/styles';
import { capitalize } from '@material-ui/core/utils';
import SpeedDial from '@material-ui/lab/SpeedDial';
import SpeedDialIcon from '@material-ui/lab/SpeedDialIcon';
import SpeedDialAction from '@material-ui/lab/SpeedDialAction';
const styles = {
root: {
position: 'relative',
height: 360,
width: 400,
},
speedDial: {
position: 'absolute',
'&$directionUp': {
bottom: 0,
right: 0,
},
'&$directionRight': {
bottom: 0,
left: 0,
},
'&$directionDown': {
top: 0,
left: 0,
},
'&$directionLeft': {
top: 0,
right: 0,
},
},
directionUp: {},
directionRight: {},
directionDown: {},
directionLeft: {},
};
function SimpleSpeedDial(props) {
const tooltipPlacement = {
up: 'left',
right: 'top',
down: 'right',
left: 'bottom',
};
return (
<SpeedDial icon={<SpeedDialIcon />} open {...props}>
{['A', 'B', 'C'].map((name) => (
<SpeedDialAction
key={name}
icon={<Avatar>{name}</Avatar>}
tooltipOpen
tooltipPlacement={tooltipPlacement[props.direction]}
tooltipTitle={'Tooltip'}
/>
))}
</SpeedDial>
);
}
SimpleSpeedDial.propTypes = {
direction: PropTypes.string.isRequired,
};
function Directions({ classes }) {
const speedDialClassName = (direction) =>
clsx(classes.speedDial, classes[`direction${capitalize(direction)}`]);
return (
<div className={classes.root}>
{['up', 'down'].map((direction) => (
<SimpleSpeedDial
key={direction}
ariaLabel={direction}
className={speedDialClassName(direction)}
direction={direction}
/>
))}
</div>
);
}
Directions.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Directions);
| {
"pile_set_name": "Github"
} |
module NSIndexPathWrap
def +(aNumber)
self.class.indexPathForRow(row+aNumber, inSection:section)
end
def -(aNumber)
self.class.indexPathForRow(row-aNumber, inSection:section)
end
end
| {
"pile_set_name": "Github"
} |
<!ENTITY polyglot.label "Polyglot">
| {
"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.
*/
package org.apache.spark.deploy.mesos.ui
import javax.servlet.http.HttpServletRequest
import scala.xml.Node
import org.apache.mesos.Protos.TaskStatus
import org.apache.spark.deploy.mesos.MesosDriverDescription
import org.apache.spark.deploy.mesos.config._
import org.apache.spark.scheduler.cluster.mesos.MesosClusterSubmissionState
import org.apache.spark.ui.{UIUtils, WebUIPage}
private[mesos] class MesosClusterPage(parent: MesosClusterUI) extends WebUIPage("") {
private val historyServerURL = parent.conf.get(HISTORY_SERVER_URL)
def render(request: HttpServletRequest): Seq[Node] = {
val state = parent.scheduler.getSchedulerState()
val driverHeader = Seq("Driver ID")
val historyHeader = historyServerURL.map(url => Seq("History")).getOrElse(Nil)
val submissionHeader = Seq("Submit Date", "Main Class", "Driver Resources")
val sandboxHeader = Seq("Sandbox")
val queuedHeaders = driverHeader ++ submissionHeader
val driverHeaders = driverHeader ++ historyHeader ++ submissionHeader ++
Seq("Start Date", "Mesos Slave ID", "State") ++ sandboxHeader
val retryHeaders = Seq("Driver ID", "Submit Date", "Description") ++
Seq("Last Failed Status", "Next Retry Time", "Attempt Count")
val queuedTable = UIUtils.listingTable(queuedHeaders, queuedRow, state.queuedDrivers)
val launchedTable = UIUtils.listingTable(driverHeaders, driverRow, state.launchedDrivers)
val finishedTable = UIUtils.listingTable(driverHeaders, driverRow, state.finishedDrivers)
val retryTable = UIUtils.listingTable(retryHeaders, retryRow, state.pendingRetryDrivers)
val content =
<p>Mesos Framework ID: {state.frameworkId}</p>
<div class="row-fluid">
<div class="span12">
<h4>Queued Drivers:</h4>
{queuedTable}
<h4>Launched Drivers:</h4>
{launchedTable}
<h4>Finished Drivers:</h4>
{finishedTable}
<h4>Supervise drivers waiting for retry:</h4>
{retryTable}
</div>
</div>;
UIUtils.basicSparkPage(content, "Spark Drivers for Mesos cluster")
}
private def queuedRow(submission: MesosDriverDescription): Seq[Node] = {
val id = submission.submissionId
<tr>
<td><a href={s"driver?id=$id"}>{id}</a></td>
<td>{UIUtils.formatDate(submission.submissionDate)}</td>
<td>{submission.command.mainClass}</td>
<td>cpus: {submission.cores}, mem: {submission.mem}</td>
</tr>
}
private def driverRow(state: MesosClusterSubmissionState): Seq[Node] = {
val id = state.driverDescription.submissionId
val proxy = parent.conf.getOption("spark.mesos.proxy.baseURL")
val sandboxCol = if (proxy.isDefined) {
val clusterSchedulerId = parent.scheduler.getSchedulerState().frameworkId
val sandBoxUri = s"${proxy.get}/#/agents/${state.slaveId.getValue}/frameworks/" +
s"${clusterSchedulerId}/executors/${id}/browse"
<a href={sandBoxUri}>Sandbox</a>
} else {
" "
}
val historyCol = if (historyServerURL.isDefined) {
<td>
<a href={s"${historyServerURL.get}/history/${state.frameworkId}"}>
{state.frameworkId}
</a>
</td>
} else Nil
<tr>
<td><a href={s"driver?id=$id"}>{id}</a></td>
{historyCol}
<td>{UIUtils.formatDate(state.driverDescription.submissionDate)}</td>
<td>{state.driverDescription.command.mainClass}</td>
<td>cpus: {state.driverDescription.cores}, mem: {state.driverDescription.mem}</td>
<td>{UIUtils.formatDate(state.startDate)}</td>
<td>{state.slaveId.getValue}</td>
<td>{stateString(state.mesosTaskStatus)}</td>
<td>{sandboxCol}</td>
</tr>
}
private def retryRow(submission: MesosDriverDescription): Seq[Node] = {
val id = submission.submissionId
<tr>
<td><a href={s"driver?id=$id"}>{id}</a></td>
<td>{UIUtils.formatDate(submission.submissionDate)}</td>
<td>{submission.command.mainClass}</td>
<td>{submission.retryState.get.lastFailureStatus}</td>
<td>{submission.retryState.get.nextRetry}</td>
<td>{submission.retryState.get.retries}</td>
</tr>
}
private def stateString(status: Option[TaskStatus]): String = {
if (status.isEmpty) {
return ""
}
val sb = new StringBuilder
val s = status.get
sb.append(s"State: ${s.getState}")
if (status.get.hasMessage) {
sb.append(s", Message: ${s.getMessage}")
}
if (status.get.hasHealthy) {
sb.append(s", Healthy: ${s.getHealthy}")
}
if (status.get.hasSource) {
sb.append(s", Source: ${s.getSource}")
}
if (status.get.hasReason) {
sb.append(s", Reason: ${s.getReason}")
}
if (status.get.hasTimestamp) {
sb.append(s", Time: ${s.getTimestamp}")
}
sb.toString()
}
}
| {
"pile_set_name": "Github"
} |
# Pull base image
FROM python:3.8
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /code
# Install dependencies
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
# Copy project
COPY . /code/
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.