text
stringlengths 2
99.9k
| meta
dict |
|---|---|
---
title: AppointmentItem.IsConflict Property (Outlook)
keywords: vbaol11.chm918
f1_keywords:
- vbaol11.chm918
ms.prod: outlook
api_name:
- Outlook.AppointmentItem.IsConflict
ms.assetid: d0c14fa2-6bfe-29e8-e68b-3eff01a8bd70
ms.date: 06/08/2017
---
# AppointmentItem.IsConflict Property (Outlook)
Returns a **Boolean** that determines if the item on the local computer is different from the copy on the server. Read-only.
## Syntax
_expression_ . **IsConflict**
_expression_ A variable that represents an **AppointmentItem** object.
## Remarks
Whether or not an item is in conflict is determined by the state of the application. For example, when a user is offline and tries to access an online folder the action will fail. In this scenario, the **IsConflict** property will return **True** .
This property does not indicate whether the appointment item has a time conflict with another appointment in the calendar.
## See also
#### Concepts
[AppointmentItem Object](appointmentitem-object-outlook.md)
|
{
"pile_set_name": "Github"
}
|
'use strict';
// jquery.resize 2020-05-27
(function() {
// skip if library is already handling resize events
if ($.event.special.resize) return;
// skip if old library has been loaded
if ($.fn.off.elementResizeOriginalOff) return;
// handler id generation
var expando = {
index: 0,
check: function(element) {
// check that the element has a valid jquery expando property, or make one
var hasExpando = (element[$.expando]);
if (hasExpando) return;
element[$.expando] = ++expando.index;
},
make: function(element, data) {
// make a unique event id from the element's expando property and the event handler guid
expando.check(element);
return data.guid + "-" + element[$.expando];
}
};
// handler functions
var handlers = {
registered: [],
shouldReProcess: true,
register: function(element, data) {
var $element = $(element);
handlers.registered.push({
id: expando.make(element, data),
$element: $element,
_measurement: measurements.get($element).uniqueMeasurementId,
_hasTriggered: false
});
handlers.shouldReProcess = true;
},
unregister: function(element, data) {
var registered = handlers.registered;
var findId = expando.make(element, data);
for (var i = registered.length-1, l = -1; i > l; i--) {
var item = registered[i]
if (item.id != findId) continue;
registered.splice(i,1);
handlers.shouldReProcess = true;
}
},
process: function() {
var registered = handlers.registered;
var registeredCount;
handlers.shouldReProcess = true;
while (handlers.shouldReProcess) {
handlers.shouldReProcess = false;
registeredCount = registered.length;
if (registeredCount == 0) return;
for (var i = 0; i < registeredCount; i++) {
var item = registered[i];
var measure = measurements.get(item.$element);
// check if measure has the same values as last
var wasPreviouslyMeasured = (item._measurement !== undefined);
if (wasPreviouslyMeasured && item._hasTriggered) {
var hasMeasureChanged = (item._measurement != measure.uniqueMeasurementId);
if (!hasMeasureChanged) {
continue;
}
}
item._measurement = measure.uniqueMeasurementId;
item._hasTriggered = true;
handlers.trigger(item);
if (handlers.shouldReProcess) {
break;
}
}
}
},
trigger: function triggerResize(item) {
item.$element.trigger('resize');
}
};
// checking loop management
var loop = {
lastStartEvent: 0,
timeoutHandle: null,
intervalDuration: 100,
hasRaf: false,
start: function() {
loop.lastStartEvent = (new Date()).getTime();
loop.repeat();
},
force: function() {
loop.lastStartEvent = (new Date()).getTime();
loop.main(true);
loop.repeat();
},
repeat: function() {
loop.stop();
if (loop.hasRaf) {
loop.timeoutHandle = requestAnimationFrame(loop.main);
} else {
loop.timeoutHandle = setTimeout(loop.main, loop.intervalDuration);
}
},
hasExpired: function() {
var timeSinceLast = (new Date()).getTime() - loop.lastStartEvent;
if (timeSinceLast < 1500) return;
loop.stop()
return true;
},
lastMain: (new Date()).getTime(),
isThrottled: function() {
var passedTime = (new Date()).getTime() - loop.lastMain;
if (passedTime > loop.intervalDuration) return false;
return true;
},
main: function(force) {
if (force !== true && loop.isThrottled()) {
loop.repeat();
return;
}
loop.lastMain = (new Date()).getTime();
if (force !== true && loop.hasExpired()) {
loop.stop();
return;
}
if (handlers.registered.length == 0) {
// nothing to check
loop.stop();
// slow down to save cycles
loop.intervalDuration = 200;
loop.repeat();
} else {
// something to check
loop.stop();
// speed up to make more responsive
loop.intervalDuration = 100;
loop.repeat();
}
handlers.process();
},
stop: function() {
var intervalAttached = (loop.timeoutHandle !== null);
if (!intervalAttached) return;
if (loop.hasRaf) {
cancelAnimationFrame(loop.timeoutHandle);
loop.timeoutHandle = null;
} else {
clearTimeout(loop.timeoutHandle);
loop.timeoutHandle = null;
}
}
};
// jQuery element + event handler attachment / removal
$.extend($.event.special, {
resize: {
noBubble: true,
add: function(data) {
// allow window resize to be handled by browser
if (this === window) return;
handlers.register(this, data);
},
remove: function(data) {
// allow window resize to be handled by browser
if (this === window) return;
handlers.unregister(this, data);
}
}
});
var measurements = {
featureDetect: function() {
loop.hasRaf = (window.requestAnimationFrame && window.cancelAnimationFrame);
},
get: function($element) {
var element = $element[0];
var height = element.clientHeight;
var width = element.clientWidth;
return {
uniqueMeasurementId: height+","+width
};
}
};
//attach event handlers
$(window).on({
"touchmove scroll mousedown keydown": loop.start, // asynchronous
"resize": loop.force // synchronous
});
$(measurements.featureDetect);
})();
|
{
"pile_set_name": "Github"
}
|
// Copyright 2011 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.
// This benchmark tests gzip and gunzip performance.
package go1
import (
"bytes"
gz "compress/gzip"
"io"
"io/ioutil"
"testing"
)
var (
jsongunz = bytes.Repeat(jsonbytes, 10)
jsongz []byte
)
func init() {
var buf bytes.Buffer
c := gz.NewWriter(&buf)
c.Write(jsongunz)
c.Close()
jsongz = buf.Bytes()
}
func gzip() {
c := gz.NewWriter(ioutil.Discard)
if _, err := c.Write(jsongunz); err != nil {
panic(err)
}
if err := c.Close(); err != nil {
panic(err)
}
}
func gunzip() {
r, err := gz.NewReader(bytes.NewBuffer(jsongz))
if err != nil {
panic(err)
}
if _, err := io.Copy(ioutil.Discard, r); err != nil {
panic(err)
}
r.Close()
}
func BenchmarkGzip(b *testing.B) {
b.SetBytes(int64(len(jsongunz)))
for i := 0; i < b.N; i++ {
gzip()
}
}
func BenchmarkGunzip(b *testing.B) {
b.SetBytes(int64(len(jsongunz)))
for i := 0; i < b.N; i++ {
gunzip()
}
}
|
{
"pile_set_name": "Github"
}
|
../parsel/csstranslator.py
../parsel/xpathfuncs.py
../parsel/selector.py
../parsel/__init__.py
../parsel/utils.py
../parsel/csstranslator.pyc
../parsel/xpathfuncs.pyc
../parsel/selector.pyc
../parsel/__init__.pyc
../parsel/utils.pyc
PKG-INFO
not-zip-safe
SOURCES.txt
requires.txt
top_level.txt
dependency_links.txt
|
{
"pile_set_name": "Github"
}
|
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
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)
This is an auto-generated file. Do not edit!
==============================================================================*/
namespace boost { namespace fusion { namespace detail
{
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29>
struct vector_n_chooser
{
typedef vector30<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29> type;
};
template <>
struct vector_n_chooser<void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector0<> type;
};
template <typename T0>
struct vector_n_chooser<
T0
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector1<T0> type;
};
template <typename T0 , typename T1>
struct vector_n_chooser<
T0 , T1
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector2<T0 , T1> type;
};
template <typename T0 , typename T1 , typename T2>
struct vector_n_chooser<
T0 , T1 , T2
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector3<T0 , T1 , T2> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3>
struct vector_n_chooser<
T0 , T1 , T2 , T3
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector4<T0 , T1 , T2 , T3> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector5<T0 , T1 , T2 , T3 , T4> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector6<T0 , T1 , T2 , T3 , T4 , T5> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector7<T0 , T1 , T2 , T3 , T4 , T5 , T6> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector8<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector9<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector10<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector11<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector12<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector13<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector14<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector15<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector16<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector17<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector18<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector19<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector20<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector21<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21
, void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector22<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22
, void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector23<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23
, void_ , void_ , void_ , void_ , void_ , void_>
{
typedef vector24<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24
, void_ , void_ , void_ , void_ , void_>
{
typedef vector25<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25
, void_ , void_ , void_ , void_>
{
typedef vector26<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26
, void_ , void_ , void_>
{
typedef vector27<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27
, void_ , void_>
{
typedef vector28<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27> type;
};
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28>
struct vector_n_chooser<
T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28
, void_>
{
typedef vector29<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28> type;
};
}}}
|
{
"pile_set_name": "Github"
}
|
[[
"start",
["xml-pe.doctype.xml","<!"],
["xml-pe.doctype.xml","DOCTYPE"],
["text.whitespace.xml"," "],
["xml-pe.xml","html"],
["xml-pe.doctype.xml",">"]
],[
"start",
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.tag-name.xml","html"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.tag-name.xml","head"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.tag-name.xml","title"],
["meta.tag.punctuation.tag-close.xml",">"],
["text.xml","Cloud9 Rocks!"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.tag-name.xml","title"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.tag-name.xml","head"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.tag-name.xml","body"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start"
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","table"],
["text.tag-whitespace.xml"," "],
["entity.other.attribute-name.xml","class"],
["keyword.operator.attribute-equals.xml","="],
["string.attribute-value.xml","\"table\""],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","tr"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","th"],
["meta.tag.punctuation.tag-close.xml",">"],
["text.xml","Name"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","th"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","th"],
["meta.tag.punctuation.tag-close.xml",">"],
["text.xml","Size"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","th"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","tr"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["markup.list.meta.tag","<%"],
["text"," "],
["keyword","if"],
["text"," "],
["paren.lparen","("],
["keyword.operator","!"],
["identifier","isRoot"],
["paren.rparen",")"],
["text"," "],
["paren.lparen","{"],
["text"," "],
["markup.list.meta.tag","%>"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","tr"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.anchor.tag-name.xml","a"],
["text.tag-whitespace.xml"," "],
["entity.other.attribute-name.xml","href"],
["keyword.operator.attribute-equals.xml","="],
["string.attribute-value.xml","\"..\""],
["meta.tag.punctuation.tag-close.xml",">"],
["text.xml",".."],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.anchor.tag-name.xml","a"],
["meta.tag.punctuation.tag-close.xml",">"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","tr"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["markup.list.meta.tag","<%"],
["text"," "],
["paren.rparen","}"],
["text"," "],
["markup.list.meta.tag","%>"]
],[
"start",
["text.xml"," "],
["markup.list.meta.tag","<%"],
["text"," "],
["identifier","entries"],
["punctuation.operator","."],
["identifier","forEach"],
["paren.lparen","("],
["storage.type","function"],
["paren.lparen","("],
["identifier","entry"],
["paren.rparen",")"],
["text"," "],
["paren.lparen","{"],
["text"," "],
["markup.list.meta.tag","%>"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","tr"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.tag-name.xml","span"],
["text.tag-whitespace.xml"," "],
["entity.other.attribute-name.xml","class"],
["keyword.operator.attribute-equals.xml","="],
["string.attribute-value.xml","\"glyphicon "],
["markup.list.meta.tag","<%="],
["text"," "],
["identifier","entry"],
["punctuation.operator","."],
["identifier","mime"],
["text"," "],
["keyword.operator","=="],
["text"," "],
["string","'directory'"],
["text"," "],
["punctuation.operator","?"],
["text"," "],
["string","'folder'"],
["punctuation.operator",":"],
["text"," "],
["string","'file'"],
["markup.list.meta.tag","%>"],
["string.attribute-value.xml","\""],
["meta.tag.punctuation.tag-close.xml",">"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.tag-name.xml","span"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.anchor.tag-name.xml","a"],
["text.tag-whitespace.xml"," "],
["entity.other.attribute-name.xml","href"],
["keyword.operator.attribute-equals.xml","="],
["string.attribute-value.xml","\""],
["markup.list.meta.tag","<%="],
["text"," "],
["identifier","entry"],
["punctuation.operator","."],
["identifier","name"],
["text"," "],
["markup.list.meta.tag","%>"],
["string.attribute-value.xml","\""],
["meta.tag.punctuation.tag-close.xml",">"],
["markup.list.meta.tag","<%="],
["text"," "],
["identifier","entry"],
["punctuation.operator","."],
["identifier","name"],
["text"," "],
["markup.list.meta.tag","%>"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.anchor.tag-name.xml","a"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.tag-open.xml","<"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"],
["markup.list.meta.tag","<%="],
["text"," "],
["identifier","entry"],
["punctuation.operator","."],
["identifier","size"],
["text"," "],
["markup.list.meta.tag","%>"],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","td"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","tr"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "],
["markup.list.meta.tag","<%"],
["text"," "],
["paren.rparen","})"],
["text"," "],
["markup.list.meta.tag","%>"]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.table.tag-name.xml","table"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["text.xml"," "]
],[
"start",
["text.xml"," "],
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.tag-name.xml","body"],
["meta.tag.punctuation.tag-close.xml",">"]
],[
"start",
["meta.tag.punctuation.end-tag-open.xml","</"],
["meta.tag.tag-name.xml","html"],
["meta.tag.punctuation.tag-close.xml",">"]
]]
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* @file
* Contains the node view row style plugin.
*/
/**
* Plugin which performs a node_view on the resulting object.
*
* Most of the code on this object is in the theme function.
*/
class views_plugin_row_node_view extends views_plugin_row {
// Basic properties that let the row style follow relationships.
var $base_table = 'node';
var $base_field = 'nid';
function init(&$view, &$display, $options = NULL) {
parent::init($view, $display, $options);
// Handle existing views with the deprecated 'teaser' option.
if (isset($this->options['teaser'])) {
$this->options['build_mode'] = $this->options['teaser'] ? 'teaser' : 'full';
}
}
function option_definition() {
$options = parent::option_definition();
$options['build_mode'] = array('default' => 'teaser');
$options['links'] = array('default' => TRUE);
$options['comments'] = array('default' => FALSE);
return $options;
}
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
// CCK holds the registry of available build modes, but can hardly
// push them as options for the node row style, so we break the normal
// rule of not directly relying on non-core modules.
if ($modes = module_invoke('content', 'build_modes')) {
$options = array();
foreach ($modes as $key => $value) {
if (isset($value['views style']) && $value['views style']) {
$options[$key] = $value['title'];
}
}
}
else {
$options = array(
'teaser' => t('Teaser'),
'full' => t('Full node')
);
}
$form['build_mode'] = array(
'#type' => 'select',
'#options' => $options,
'#title' => t('Build mode'),
'#default_value' => $this->options['build_mode'],
);
$form['links'] = array(
'#type' => 'checkbox',
'#title' => t('Display links'),
'#default_value' => $this->options['links'],
);
$form['comments'] = array(
'#type' => 'checkbox',
'#title' => t('Display node comments'),
'#default_value' => $this->options['comments'],
);
}
}
|
{
"pile_set_name": "Github"
}
|
package org.cloudfoundry.credhub.helpers
class CredHubRestDocs {
companion object {
@JvmField
val DOCUMENT_IDENTIFIER = "{methodName}"
}
}
|
{
"pile_set_name": "Github"
}
|
//
// YYDiskCacheHelper.h
// headlineNews
//
// Created by dengweihao on 2017/12/6.
// Copyright © 2017年 vcyber. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <YYCache/YYCache.h>
@interface HNDiskCacheHelper : NSObject
@property (nonatomic , strong)YYDiskCache *diskCache;
+ (instancetype)defaultHelper;
- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key;
- ( id<NSCoding>)objectForKey:(NSString *)key;
- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(void))block;
- (void)removeObjectForKey:(NSString *)key;
- (void)setMaxArrayCount:(NSInteger)maxCount forKey:(NSString *)key;
- (void)removeMaxCountForKey:(NSString *)key;
@end
|
{
"pile_set_name": "Github"
}
|
import string
import Printer
from xml.dom import XHTML_NAMESPACE
# Wrapper classes to convert nodes from HTML to XHTML
class XHtmlDocType:
def __init__(self, doctype):
self.name = 'html'
self.publicId = "-//W3C//DTD XHTML 1.0 Strict//EN"
self.systemId = "DTD/xhtml1-strict.dtd"
self.entities = doctype and doctype.entities or []
self.notations = doctype and doctype.notation or []
return
class XHtmlAttr:
def __init__(self, node):
self.namespaceURI = XHTML_NAMESPACE
self.name = string.lower(node.name)
self.node = node
return
def __getattr__(self, key):
return getattr(self.node, key)
class XHtmlElement:
def __init__(self, node):
self.tagName = string.lower(node.tagName)
self.node = node
return
def __getattr__(self, key):
return getattr(self.node, key)
class XHtmlPrintVisitor(Printer.PrintVisitor):
def __init__(self, stream, encoding, indent):
xhtml = {None: 'http://www.w3.org/1999/xhtml'}
Printer.PrintVisitor.__init__(self, stream, encoding, indent, nsHints=xhtml)
self._html = 0
return
def visitDocument(self,node):
self.visitProlog()
self._tryIndent()
self.visitDocumentType(XHtmlDocType(node.doctype))
self.visitNodeList(node.childNodes, exclude=node.doctype)
return
def visitAttr(self, node):
Printer.PrintVisitor.visitAttr(self, XHtmlAttr(node))
return
def visitElement(self, node):
Printer.PrintVisitor.visitElement(self, XHtmlElement(node))
return
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0"?>
<!DOCTYPE EXAMPLE SYSTEM "example.dtd" [
<!ENTITY xml "Extensible Markup Language">
]>
<EXAMPLE>
Extensible Markup Language
</EXAMPLE>
|
{
"pile_set_name": "Github"
}
|
# These are supported funding model platforms
github:
- romaninsh
- DarkSide666
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright 2019 Intel Corporation
*
* 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.
*******************************************************************************/
#ifndef MKLDNN_VERSION_H
#define MKLDNN_VERSION_H
/* Major version of MKL-DNN */
#define MKLDNN_VERSION_MAJOR 0
/* Minor version of MKL-DNN */
#define MKLDNN_VERSION_MINOR 90
/* Patch version of MKL-DNN */
#define MKLDNN_VERSION_PATCH 0
/* Git Commit Hash of MKL-DNN */
#define MKLDNN_VERSION_HASH "096bda1ca23324879f2df5a129e610e4405f775c"
#endif
|
{
"pile_set_name": "Github"
}
|
package com.common.util;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.common.web.support.pagination.PaginationUtils;
public class JsonUtil {
public static String build(String flag, String text) {
return "{'" + flag + "' : true , '" + ResponseUtils.RESPONSE_TEXT_KEY
+ "' : '" + text + "'}";
}
public static String buildFailure(String text) {
return build(ResponseUtils.RESPONSE_FAILURE_KEY, text);
}
public static String buildSuccess(String text) {
return build(ResponseUtils.RESPONSE_SUCCESS_KEY, text);
}
public static String buildPagination(List<?> list) {
JSONObject json = new JSONObject();
json.element(ResponseUtils.RESPONSE_SUCCESS_KEY, true);
json.element(ResponseUtils.PAGINATION_TOTAL_PROPERTY_KEY,
PaginationUtils.getPagination().getTotal());
json.element(ResponseUtils.PAGINATION_ROOT_PROPERTY_KEY,
JSONArray.fromObject(list));
return json.toString();
}
public static String buildArrayList(List<?> list) {
return JSONArray.fromObject(list).toString();
}
}
|
{
"pile_set_name": "Github"
}
|
# Colors (Tomorrow Night Blue)
colors:
bright:
black: '#000000'
blue: '#bbdaff'
cyan: '#99ffff'
green: '#d1f1a9'
magenta: '#ebbbff'
red: '#ff9da4'
white: '#ffffff'
yellow: '#ffeead'
cursor:
cursor: '#ffffff'
text: '#003f8e'
normal:
black: '#000000'
blue: '#bbdaff'
cyan: '#99ffff'
green: '#d1f1a9'
magenta: '#ebbbff'
red: '#ff9da4'
white: '#ffffff'
yellow: '#ffeead'
primary:
background: '#002451'
foreground: '#ffffff'
selection:
background: '#003f8e'
text: '#ffffff'
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <CoreMotion/CMLogItem.h>
@class NSDate, NSNumber, NSUUID;
@interface CMNatalieData : CMLogItem
{
long long fRecordId;
double fStartDate;
long long fActivityType;
double fMets;
double fNatalies;
double fBasalNatalies;
NSUUID *fSourceId;
}
+ (id)maxNatalieEntries;
+ (BOOL)supportsSecureCoding;
- (id)description;
@property(readonly, nonatomic) NSUUID *sourceId;
@property(readonly, nonatomic) long long recordId;
@property(readonly, nonatomic) long long activityType;
@property(readonly, nonatomic) long long session;
@property(readonly, nonatomic) NSNumber *basalNatalies;
@property(readonly, nonatomic) NSNumber *natalies;
@property(readonly, nonatomic) NSNumber *mets;
@property(readonly, nonatomic) NSDate *startDate;
- (void)encodeWithCoder:(id)arg1;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)initWithCoder:(id)arg1;
- (void)dealloc;
- (id)initWithStartDate:(double)arg1 recordId:(long long)arg2 activityType:(long long)arg3 mets:(double)arg4 natalies:(double)arg5 basalNatalies:(double)arg6 sourceId:(id)arg7;
@end
|
{
"pile_set_name": "Github"
}
|
#ifndef HEADER_CURL_NON_ASCII_H
#define HEADER_CURL_NON_ASCII_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef CURL_DOES_CONVERSIONS
#include "urldata.h"
/*
* Curl_convert_clone() returns a malloced copy of the source string (if
* returning CURLE_OK), with the data converted to network format.
*
* If no conversion was needed *outbuf may be NULL.
*/
CURLcode Curl_convert_clone(struct SessionHandle *data,
const char *indata,
size_t insize,
char **outbuf);
void Curl_convert_init(struct SessionHandle *data);
void Curl_convert_setup(struct SessionHandle *data);
void Curl_convert_close(struct SessionHandle *data);
CURLcode Curl_convert_to_network(struct SessionHandle *data,
char *buffer, size_t length);
CURLcode Curl_convert_from_network(struct SessionHandle *data,
char *buffer, size_t length);
CURLcode Curl_convert_from_utf8(struct SessionHandle *data,
char *buffer, size_t length);
CURLcode Curl_convert_form(struct SessionHandle *data, struct FormData *form);
#else
#define Curl_convert_clone(a,b,c,d) ((void)a, CURLE_OK)
#define Curl_convert_init(x) Curl_nop_stmt
#define Curl_convert_setup(x) Curl_nop_stmt
#define Curl_convert_close(x) Curl_nop_stmt
#define Curl_convert_to_network(a,b,c) ((void)a, CURLE_OK)
#define Curl_convert_from_network(a,b,c) ((void)a, CURLE_OK)
#define Curl_convert_from_utf8(a,b,c) ((void)a, CURLE_OK)
#define Curl_convert_form(a,b) CURLE_OK
#endif
#endif /* HEADER_CURL_NON_ASCII_H */
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2016 Álinson Santos Xavier <isoron@gmail.com>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.widgets;
import androidx.test.filters.*;
import android.widget.*;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.isoron.uhabits.*;
import org.isoron.uhabits.core.models.*;
import org.junit.*;
import org.junit.runner.*;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
import static org.isoron.uhabits.core.models.Checkmark.*;
@RunWith(AndroidJUnit4.class)
@MediumTest
public class CheckmarkWidgetTest extends BaseViewTest
{
private static final String PATH = "widgets/CheckmarkWidget/";
private Habit habit;
private CheckmarkList checkmarks;
private FrameLayout view;
@Override
public void setUp()
{
super.setUp();
setTheme(R.style.WidgetTheme);
prefs.setWidgetOpacity(255);
habit = fixtures.createVeryLongHabit();
checkmarks = habit.getCheckmarks();
CheckmarkWidget widget = new CheckmarkWidget(targetContext, 0, habit);
view = convertToView(widget, 150, 200);
assertThat(checkmarks.getTodayValue(), equalTo(YES_MANUAL));
}
@Test
public void testClick() throws Exception
{
Button button = (Button) view.findViewById(R.id.button);
assertThat(button, is(not(nullValue())));
// A better test would be to capture the intent, but it doesn't seem
// possible to capture intents sent to BroadcastReceivers.
button.performClick();
sleep(1000);
assertThat(checkmarks.getTodayValue(), equalTo(SKIP));
button.performClick();
sleep(1000);
assertThat(checkmarks.getTodayValue(), equalTo(NO));
}
@Test
public void testIsInstalled()
{
assertWidgetProviderIsInstalled(CheckmarkWidgetProvider.class);
}
@Test
public void testRender() throws Exception
{
assertRenders(view, PATH + "render.png");
}
}
|
{
"pile_set_name": "Github"
}
|
/**
******************************************************************************
* @file system_stm32f4xx.c
* @author MCD Application Team
* @version V2.6.1
* @date 14-February-2017
* @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File.
*
* This file provides two functions and one global variable to be called from
* user application:
* - SystemInit(): This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32f4xx.s" file.
*
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
* by the user application to setup the SysTick
* timer or configure other parameters.
*
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
* be called whenever the core clock is changed
* during program execution.
*
*
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2017 STMicroelectronics</center></h2>
*
* 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.
* 3. Neither the name of STMicroelectronics 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.
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32f4xx_system
* @{
*/
/** @addtogroup STM32F4xx_System_Private_Includes
* @{
*/
#include "stm32f4xx.h"
#if !defined (HSE_VALUE)
#define HSE_VALUE ((uint32_t)25000000) /*!< Default value of the External oscillator in Hz */
#endif /* HSE_VALUE */
#if !defined (HSI_VALUE)
#define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/
#endif /* HSI_VALUE */
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_Defines
* @{
*/
/************************* Miscellaneous Configuration ************************/
/*!< Uncomment the following line if you need to use external SRAM or SDRAM as data memory */
#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\
|| defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx)
/* #define DATA_IN_ExtSRAM */
#endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx || STM32F469xx || STM32F479xx ||\
STM32F412Zx || STM32F412Vx */
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx)
/* #define DATA_IN_ExtSDRAM */
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\
STM32F479xx */
/*!< Uncomment the following line if you need to relocate your vector Table in
Internal SRAM. */
/* #define VECT_TAB_SRAM */
#define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
/******************************************************************************/
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_Variables
* @{
*/
/* This variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetHCLKFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
uint32_t SystemCoreClock = 16000000;
const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4};
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_FunctionPrototypes
* @{
*/
#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM)
static void SystemInit_ExtMemCtl(void);
#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system
* Initialize the FPU setting, vector table location and External memory
* configuration.
* @param None
* @retval None
*/
void SystemInit(void)
{
/* FPU settings ------------------------------------------------------------*/
#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */
#endif
/* Reset the RCC clock configuration to the default reset state ------------*/
/* Set HSION bit */
RCC->CR |= (uint32_t)0x00000001;
/* Reset CFGR register */
RCC->CFGR = 0x00000000;
/* Reset HSEON, CSSON and PLLON bits */
RCC->CR &= (uint32_t)0xFEF6FFFF;
/* Reset PLLCFGR register */
RCC->PLLCFGR = 0x24003010;
/* Reset HSEBYP bit */
RCC->CR &= (uint32_t)0xFFFBFFFF;
/* Disable all interrupts */
RCC->CIR = 0x00000000;
#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM)
SystemInit_ExtMemCtl();
#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */
/* Configure the Vector Table location add offset address ------------------*/
#ifdef VECT_TAB_SRAM
SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */
#else
SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */
#endif
}
/**
* @brief Update SystemCoreClock variable according to Clock Register Values.
* The SystemCoreClock variable contains the core clock (HCLK), it can
* be used by the user application to setup the SysTick timer or configure
* other parameters.
*
* @note Each time the core clock (HCLK) changes, this function must be called
* to update SystemCoreClock variable value. Otherwise, any configuration
* based on this variable will be incorrect.
*
* @note - The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
*
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
*
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
*
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**)
* or HSI_VALUE(*) multiplied/divided by the PLL factors.
*
* (*) HSI_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value
* 16 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (**) HSE_VALUE is a constant defined in stm32f4xx_hal_conf.h file (its value
* depends on the application requirements), user has to ensure that HSE_VALUE
* is same as the real frequency of the crystal used. Otherwise, this function
* may have wrong result.
*
* - The result of this function could be not correct when using fractional
* value for HSE crystal.
*
* @param None
* @retval None
*/
void SystemCoreClockUpdate(void)
{
uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2;
/* Get SYSCLK source -------------------------------------------------------*/
tmp = RCC->CFGR & RCC_CFGR_SWS;
switch (tmp)
{
case 0x00: /* HSI used as system clock source */
SystemCoreClock = HSI_VALUE;
break;
case 0x04: /* HSE used as system clock source */
SystemCoreClock = HSE_VALUE;
break;
case 0x08: /* PLL used as system clock source */
/* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N
SYSCLK = PLL_VCO / PLL_P
*/
pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22;
pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM;
if (pllsource != 0)
{
/* HSE used as PLL clock source */
pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6);
}
else
{
/* HSI used as PLL clock source */
pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6);
}
pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2;
SystemCoreClock = pllvco/pllp;
break;
default:
SystemCoreClock = HSI_VALUE;
break;
}
/* Compute HCLK frequency --------------------------------------------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)];
/* HCLK frequency */
SystemCoreClock >>= tmp;
}
#if defined (DATA_IN_ExtSRAM) && defined (DATA_IN_ExtSDRAM)
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F469xx) || defined(STM32F479xx)
/**
* @brief Setup the external memory controller.
* Called in startup_stm32f4xx.s before jump to main.
* This function configures the external memories (SRAM/SDRAM)
* This SRAM/SDRAM will be used as program data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
__IO uint32_t tmp = 0x00;
register uint32_t tmpreg = 0, timeout = 0xFFFF;
register __IO uint32_t index;
/* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */
RCC->AHB1ENR |= 0x000001F8;
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);
/* Connect PDx pins to FMC Alternate function */
GPIOD->AFR[0] = 0x00CCC0CC;
GPIOD->AFR[1] = 0xCCCCCCCC;
/* Configure PDx pins in Alternate function mode */
GPIOD->MODER = 0xAAAA0A8A;
/* Configure PDx pins speed to 100 MHz */
GPIOD->OSPEEDR = 0xFFFF0FCF;
/* Configure PDx pins Output type to push-pull */
GPIOD->OTYPER = 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOD->PUPDR = 0x00000000;
/* Connect PEx pins to FMC Alternate function */
GPIOE->AFR[0] = 0xC00CC0CC;
GPIOE->AFR[1] = 0xCCCCCCCC;
/* Configure PEx pins in Alternate function mode */
GPIOE->MODER = 0xAAAA828A;
/* Configure PEx pins speed to 100 MHz */
GPIOE->OSPEEDR = 0xFFFFC3CF;
/* Configure PEx pins Output type to push-pull */
GPIOE->OTYPER = 0x00000000;
/* No pull-up, pull-down for PEx pins */
GPIOE->PUPDR = 0x00000000;
/* Connect PFx pins to FMC Alternate function */
GPIOF->AFR[0] = 0xCCCCCCCC;
GPIOF->AFR[1] = 0xCCCCCCCC;
/* Configure PFx pins in Alternate function mode */
GPIOF->MODER = 0xAA800AAA;
/* Configure PFx pins speed to 50 MHz */
GPIOF->OSPEEDR = 0xAA800AAA;
/* Configure PFx pins Output type to push-pull */
GPIOF->OTYPER = 0x00000000;
/* No pull-up, pull-down for PFx pins */
GPIOF->PUPDR = 0x00000000;
/* Connect PGx pins to FMC Alternate function */
GPIOG->AFR[0] = 0xCCCCCCCC;
GPIOG->AFR[1] = 0xCCCCCCCC;
/* Configure PGx pins in Alternate function mode */
GPIOG->MODER = 0xAAAAAAAA;
/* Configure PGx pins speed to 50 MHz */
GPIOG->OSPEEDR = 0xAAAAAAAA;
/* Configure PGx pins Output type to push-pull */
GPIOG->OTYPER = 0x00000000;
/* No pull-up, pull-down for PGx pins */
GPIOG->PUPDR = 0x00000000;
/* Connect PHx pins to FMC Alternate function */
GPIOH->AFR[0] = 0x00C0CC00;
GPIOH->AFR[1] = 0xCCCCCCCC;
/* Configure PHx pins in Alternate function mode */
GPIOH->MODER = 0xAAAA08A0;
/* Configure PHx pins speed to 50 MHz */
GPIOH->OSPEEDR = 0xAAAA08A0;
/* Configure PHx pins Output type to push-pull */
GPIOH->OTYPER = 0x00000000;
/* No pull-up, pull-down for PHx pins */
GPIOH->PUPDR = 0x00000000;
/* Connect PIx pins to FMC Alternate function */
GPIOI->AFR[0] = 0xCCCCCCCC;
GPIOI->AFR[1] = 0x00000CC0;
/* Configure PIx pins in Alternate function mode */
GPIOI->MODER = 0x0028AAAA;
/* Configure PIx pins speed to 50 MHz */
GPIOI->OSPEEDR = 0x0028AAAA;
/* Configure PIx pins Output type to push-pull */
GPIOI->OTYPER = 0x00000000;
/* No pull-up, pull-down for PIx pins */
GPIOI->PUPDR = 0x00000000;
/*-- FMC Configuration -------------------------------------------------------*/
/* Enable the FMC interface clock */
RCC->AHB3ENR |= 0x00000001;
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);
FMC_Bank5_6->SDCR[0] = 0x000019E4;
FMC_Bank5_6->SDTR[0] = 0x01115351;
/* SDRAM initialization sequence */
/* Clock enable command */
FMC_Bank5_6->SDCMR = 0x00000011;
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Delay */
for (index = 0; index<1000; index++);
/* PALL command */
FMC_Bank5_6->SDCMR = 0x00000012;
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Auto refresh command */
FMC_Bank5_6->SDCMR = 0x00000073;
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* MRD register program */
FMC_Bank5_6->SDCMR = 0x00046014;
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Set refresh count */
tmpreg = FMC_Bank5_6->SDRTR;
FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1));
/* Disable write protection */
tmpreg = FMC_Bank5_6->SDCR[0];
FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF);
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
/* Configure and enable Bank1_SRAM2 */
FMC_Bank1->BTCR[2] = 0x00001011;
FMC_Bank1->BTCR[3] = 0x00000201;
FMC_Bank1E->BWTR[2] = 0x0fffffff;
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
#if defined(STM32F469xx) || defined(STM32F479xx)
/* Configure and enable Bank1_SRAM2 */
FMC_Bank1->BTCR[2] = 0x00001091;
FMC_Bank1->BTCR[3] = 0x00110212;
FMC_Bank1E->BWTR[2] = 0x0fffffff;
#endif /* STM32F469xx || STM32F479xx */
(void)(tmp);
}
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */
#elif defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM)
/**
* @brief Setup the external memory controller.
* Called in startup_stm32f4xx.s before jump to main.
* This function configures the external memories (SRAM/SDRAM)
* This SRAM/SDRAM will be used as program data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
__IO uint32_t tmp = 0x00;
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx)
#if defined (DATA_IN_ExtSDRAM)
register uint32_t tmpreg = 0, timeout = 0xFFFF;
register __IO uint32_t index;
#if defined(STM32F446xx)
/* Enable GPIOA, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG interface
clock */
RCC->AHB1ENR |= 0x0000007D;
#else
/* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface
clock */
RCC->AHB1ENR |= 0x000001F8;
#endif /* STM32F446xx */
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);
#if defined(STM32F446xx)
/* Connect PAx pins to FMC Alternate function */
GPIOA->AFR[0] |= 0xC0000000;
GPIOA->AFR[1] |= 0x00000000;
/* Configure PDx pins in Alternate function mode */
GPIOA->MODER |= 0x00008000;
/* Configure PDx pins speed to 50 MHz */
GPIOA->OSPEEDR |= 0x00008000;
/* Configure PDx pins Output type to push-pull */
GPIOA->OTYPER |= 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOA->PUPDR |= 0x00000000;
/* Connect PCx pins to FMC Alternate function */
GPIOC->AFR[0] |= 0x00CC0000;
GPIOC->AFR[1] |= 0x00000000;
/* Configure PDx pins in Alternate function mode */
GPIOC->MODER |= 0x00000A00;
/* Configure PDx pins speed to 50 MHz */
GPIOC->OSPEEDR |= 0x00000A00;
/* Configure PDx pins Output type to push-pull */
GPIOC->OTYPER |= 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOC->PUPDR |= 0x00000000;
#endif /* STM32F446xx */
/* Connect PDx pins to FMC Alternate function */
GPIOD->AFR[0] = 0x000000CC;
GPIOD->AFR[1] = 0xCC000CCC;
/* Configure PDx pins in Alternate function mode */
GPIOD->MODER = 0xA02A000A;
/* Configure PDx pins speed to 50 MHz */
GPIOD->OSPEEDR = 0xA02A000A;
/* Configure PDx pins Output type to push-pull */
GPIOD->OTYPER = 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOD->PUPDR = 0x00000000;
/* Connect PEx pins to FMC Alternate function */
GPIOE->AFR[0] = 0xC00000CC;
GPIOE->AFR[1] = 0xCCCCCCCC;
/* Configure PEx pins in Alternate function mode */
GPIOE->MODER = 0xAAAA800A;
/* Configure PEx pins speed to 50 MHz */
GPIOE->OSPEEDR = 0xAAAA800A;
/* Configure PEx pins Output type to push-pull */
GPIOE->OTYPER = 0x00000000;
/* No pull-up, pull-down for PEx pins */
GPIOE->PUPDR = 0x00000000;
/* Connect PFx pins to FMC Alternate function */
GPIOF->AFR[0] = 0xCCCCCCCC;
GPIOF->AFR[1] = 0xCCCCCCCC;
/* Configure PFx pins in Alternate function mode */
GPIOF->MODER = 0xAA800AAA;
/* Configure PFx pins speed to 50 MHz */
GPIOF->OSPEEDR = 0xAA800AAA;
/* Configure PFx pins Output type to push-pull */
GPIOF->OTYPER = 0x00000000;
/* No pull-up, pull-down for PFx pins */
GPIOF->PUPDR = 0x00000000;
/* Connect PGx pins to FMC Alternate function */
GPIOG->AFR[0] = 0xCCCCCCCC;
GPIOG->AFR[1] = 0xCCCCCCCC;
/* Configure PGx pins in Alternate function mode */
GPIOG->MODER = 0xAAAAAAAA;
/* Configure PGx pins speed to 50 MHz */
GPIOG->OSPEEDR = 0xAAAAAAAA;
/* Configure PGx pins Output type to push-pull */
GPIOG->OTYPER = 0x00000000;
/* No pull-up, pull-down for PGx pins */
GPIOG->PUPDR = 0x00000000;
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F469xx) || defined(STM32F479xx)
/* Connect PHx pins to FMC Alternate function */
GPIOH->AFR[0] = 0x00C0CC00;
GPIOH->AFR[1] = 0xCCCCCCCC;
/* Configure PHx pins in Alternate function mode */
GPIOH->MODER = 0xAAAA08A0;
/* Configure PHx pins speed to 50 MHz */
GPIOH->OSPEEDR = 0xAAAA08A0;
/* Configure PHx pins Output type to push-pull */
GPIOH->OTYPER = 0x00000000;
/* No pull-up, pull-down for PHx pins */
GPIOH->PUPDR = 0x00000000;
/* Connect PIx pins to FMC Alternate function */
GPIOI->AFR[0] = 0xCCCCCCCC;
GPIOI->AFR[1] = 0x00000CC0;
/* Configure PIx pins in Alternate function mode */
GPIOI->MODER = 0x0028AAAA;
/* Configure PIx pins speed to 50 MHz */
GPIOI->OSPEEDR = 0x0028AAAA;
/* Configure PIx pins Output type to push-pull */
GPIOI->OTYPER = 0x00000000;
/* No pull-up, pull-down for PIx pins */
GPIOI->PUPDR = 0x00000000;
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */
/*-- FMC Configuration -------------------------------------------------------*/
/* Enable the FMC interface clock */
RCC->AHB3ENR |= 0x00000001;
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);
/* Configure and enable SDRAM bank1 */
#if defined(STM32F446xx)
FMC_Bank5_6->SDCR[0] = 0x00001954;
#else
FMC_Bank5_6->SDCR[0] = 0x000019E4;
#endif /* STM32F446xx */
FMC_Bank5_6->SDTR[0] = 0x01115351;
/* SDRAM initialization sequence */
/* Clock enable command */
FMC_Bank5_6->SDCMR = 0x00000011;
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Delay */
for (index = 0; index<1000; index++);
/* PALL command */
FMC_Bank5_6->SDCMR = 0x00000012;
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Auto refresh command */
#if defined(STM32F446xx)
FMC_Bank5_6->SDCMR = 0x000000F3;
#else
FMC_Bank5_6->SDCMR = 0x00000073;
#endif /* STM32F446xx */
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* MRD register program */
#if defined(STM32F446xx)
FMC_Bank5_6->SDCMR = 0x00044014;
#else
FMC_Bank5_6->SDCMR = 0x00046014;
#endif /* STM32F446xx */
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Set refresh count */
tmpreg = FMC_Bank5_6->SDRTR;
#if defined(STM32F446xx)
FMC_Bank5_6->SDRTR = (tmpreg | (0x0000050C<<1));
#else
FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1));
#endif /* STM32F446xx */
/* Disable write protection */
tmpreg = FMC_Bank5_6->SDCR[0];
FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF);
#endif /* DATA_IN_ExtSDRAM */
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */
#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\
|| defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx)
#if defined(DATA_IN_ExtSRAM)
/*-- GPIOs Configuration -----------------------------------------------------*/
/* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */
RCC->AHB1ENR |= 0x00000078;
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);
/* Connect PDx pins to FMC Alternate function */
GPIOD->AFR[0] = 0x00CCC0CC;
GPIOD->AFR[1] = 0xCCCCCCCC;
/* Configure PDx pins in Alternate function mode */
GPIOD->MODER = 0xAAAA0A8A;
/* Configure PDx pins speed to 100 MHz */
GPIOD->OSPEEDR = 0xFFFF0FCF;
/* Configure PDx pins Output type to push-pull */
GPIOD->OTYPER = 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOD->PUPDR = 0x00000000;
/* Connect PEx pins to FMC Alternate function */
GPIOE->AFR[0] = 0xC00CC0CC;
GPIOE->AFR[1] = 0xCCCCCCCC;
/* Configure PEx pins in Alternate function mode */
GPIOE->MODER = 0xAAAA828A;
/* Configure PEx pins speed to 100 MHz */
GPIOE->OSPEEDR = 0xFFFFC3CF;
/* Configure PEx pins Output type to push-pull */
GPIOE->OTYPER = 0x00000000;
/* No pull-up, pull-down for PEx pins */
GPIOE->PUPDR = 0x00000000;
/* Connect PFx pins to FMC Alternate function */
GPIOF->AFR[0] = 0x00CCCCCC;
GPIOF->AFR[1] = 0xCCCC0000;
/* Configure PFx pins in Alternate function mode */
GPIOF->MODER = 0xAA000AAA;
/* Configure PFx pins speed to 100 MHz */
GPIOF->OSPEEDR = 0xFF000FFF;
/* Configure PFx pins Output type to push-pull */
GPIOF->OTYPER = 0x00000000;
/* No pull-up, pull-down for PFx pins */
GPIOF->PUPDR = 0x00000000;
/* Connect PGx pins to FMC Alternate function */
GPIOG->AFR[0] = 0x00CCCCCC;
GPIOG->AFR[1] = 0x000000C0;
/* Configure PGx pins in Alternate function mode */
GPIOG->MODER = 0x00085AAA;
/* Configure PGx pins speed to 100 MHz */
GPIOG->OSPEEDR = 0x000CAFFF;
/* Configure PGx pins Output type to push-pull */
GPIOG->OTYPER = 0x00000000;
/* No pull-up, pull-down for PGx pins */
GPIOG->PUPDR = 0x00000000;
/*-- FMC/FSMC Configuration --------------------------------------------------*/
/* Enable the FMC/FSMC interface clock */
RCC->AHB3ENR |= 0x00000001;
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);
/* Configure and enable Bank1_SRAM2 */
FMC_Bank1->BTCR[2] = 0x00001011;
FMC_Bank1->BTCR[3] = 0x00000201;
FMC_Bank1E->BWTR[2] = 0x0fffffff;
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
#if defined(STM32F469xx) || defined(STM32F479xx)
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);
/* Configure and enable Bank1_SRAM2 */
FMC_Bank1->BTCR[2] = 0x00001091;
FMC_Bank1->BTCR[3] = 0x00110212;
FMC_Bank1E->BWTR[2] = 0x0fffffff;
#endif /* STM32F469xx || STM32F479xx */
#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx)\
|| defined(STM32F412Zx) || defined(STM32F412Vx)
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);
/* Configure and enable Bank1_SRAM2 */
FSMC_Bank1->BTCR[2] = 0x00001011;
FSMC_Bank1->BTCR[3] = 0x00000201;
FSMC_Bank1E->BWTR[2] = 0x0FFFFFFF;
#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F412Zx || STM32F412Vx */
#endif /* DATA_IN_ExtSRAM */
#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\
STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx */
(void)(tmp);
}
#endif /* DATA_IN_ExtSRAM && DATA_IN_ExtSDRAM */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
{
"pile_set_name": "Github"
}
|
/* Start RU-RU locale-specific CSS */
/* End locale-specific CSS */
|
{
"pile_set_name": "Github"
}
|
//------------------------------------------------------------------------
// Project : VST SDK
//
// Category : Interfaces
// Filename : pluginterfaces/vst/vsttypes.h
// Created by : Steinberg, 12/2005
// Description : Common Defines
//
//-----------------------------------------------------------------------------
// This file is part of a Steinberg SDK. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this distribution
// and at www.steinberg.net/sdklicenses.
// No part of the SDK, including this file, may be copied, modified, propagated,
// or distributed except according to the terms contained in the LICENSE file.
//-----------------------------------------------------------------------------
#pragma once
#include "pluginterfaces/base/fstrdefs.h"
//------------------------------------------------------------------------
namespace Steinberg {
namespace Vst {
//------------------------------------------------------------------------
#ifndef kVstVersionString
#define kVstVersionString "VST 3.6.13" ///< SDK version for PClassInfo2
#endif
#define kVstVersionMajor 3
#define kVstVersionMinor 6
#define kVstVersionSub 13
// this allows to write things like: #if VST_VERSION >= 0x030500 // note that 3.10.0 is 0x030a00
#define VST_VERSION ((kVstVersionMajor << 16) | (kVstVersionMinor << 8) | kVstVersionSub)
//------------------------------------------------------------------------
/** \defgroup vst3typedef VST 3 Data Types
*/
/*@{*/
//------------------------------------------------------------------------
// String Types
//------------------------------------------------------------------------
typedef char16 TChar; ///< UTF-16 character
typedef TChar String128[128]; ///< 128 character UTF-16 string
typedef const char8* CString; ///< C-String
//------------------------------------------------------------------------
// General
//------------------------------------------------------------------------
typedef int32 MediaType; ///< media type (audio/event)
typedef int32 BusDirection; ///< bus direction (in/out)
typedef int32 BusType; ///< bus type (main/aux)
typedef int32 IoMode; ///< I/O mode (see \ref vst3IoMode)
typedef int32 UnitID; ///< unit identifier
typedef double ParamValue; ///< parameter value type
typedef uint32 ParamID; ///< parameter identifier
typedef int32 ProgramListID; ///< program list identifier
typedef int16 CtrlNumber; ///< MIDI controller number (see \ref ControllerNumbers for allowed values)
typedef double TQuarterNotes; ///< time expressed in quarter notes
typedef int64 TSamples; ///< time expressed in audio samples
typedef uint32 ColorSpec; ///< color defining by 4 component ARGB value (Alpha/Red/Green/Blue)
//------------------------------------------------------------------------
static const ParamID kNoParamId = 0xffffffff; ///< default for uninitialized parameter ID
// static const ParamID kNoParamId = std::numeric_limits<ParamID>::max ();
//------------------------------------------------------------------------
// Audio Types
//------------------------------------------------------------------------
typedef float Sample32; ///< 32-bit precision audio sample
typedef double Sample64; ///< 64-bit precision audio sample
typedef double SampleRate; ///< sample rate
//------------------------------------------------------------------------
// Speaker Arrangements Types
//------------------------------------------------------------------------
typedef uint64 SpeakerArrangement; ///< Bitset of speakers
typedef uint64 Speaker; ///< Bit for one speaker
/*@}*/
//------------------------------------------------------------------------
} // namespace Vst
} // namespace Steinberg
|
{
"pile_set_name": "Github"
}
|
/*
FUNCTION
<<isblank>>, <<isblank_l>>---blank character predicate
INDEX
isblank
INDEX
isblank_l
ANSI_SYNOPSIS
#include <ctype.h>
int isblank(int <[c]>);
#include <ctype.h>
int isblank_l(int <[c]>, locale_t <[locale]>);
TRAD_SYNOPSIS
#include <ctype.h>
int isblank(<[c]>);
DESCRIPTION
<<isblank>> is a function which classifies singlebyte charset values by table
lookup. It is a predicate returning non-zero for blank characters, and 0
for other characters. It is defined only if <[c]> is representable as an
unsigned char or if <[c]> is EOF.
<<isblank_l>> is like <<isblank>> but performs the check based on the
locale specified by the locale object locale. If <[locale]> is
LC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
RETURNS
<<isblank>>, <<isblank_l>> return non-zero if <[c]> is a blank character.
PORTABILITY
<<isblank>> is C99.
<<isblank_l>> is POSIX-1.2008.
No supporting OS subroutines are required.
*/
/* Includes */
#include <ctype.h>
/* Undefine symbol in case it's been
* inlined as a macro */
#undef isblank
/* <<isblank>> is a function which classifies singlebyte charset values by table
* lookup. It is a predicate returning non-zero for blank characters, and 0
* for other characters. It is defined only if <[c]> is representable as an
* unsigned char or if <[c]> is EOF. */
int isblank(int c)
{
return ((__CTYPE_PTR[c+1] & _CTYPE_B) || (c == '\t'));
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2014 Imagination Technologies
* Authors: Will Thomas, James Hartley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Interface structure taken from omap-sham driver
*/
#include <linux/clk.h>
#include <linux/dmaengine.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/scatterlist.h>
#include <crypto/internal/hash.h>
#include <crypto/md5.h>
#include <crypto/sha.h>
#define CR_RESET 0
#define CR_RESET_SET 1
#define CR_RESET_UNSET 0
#define CR_MESSAGE_LENGTH_H 0x4
#define CR_MESSAGE_LENGTH_L 0x8
#define CR_CONTROL 0xc
#define CR_CONTROL_BYTE_ORDER_3210 0
#define CR_CONTROL_BYTE_ORDER_0123 1
#define CR_CONTROL_BYTE_ORDER_2310 2
#define CR_CONTROL_BYTE_ORDER_1032 3
#define CR_CONTROL_BYTE_ORDER_SHIFT 8
#define CR_CONTROL_ALGO_MD5 0
#define CR_CONTROL_ALGO_SHA1 1
#define CR_CONTROL_ALGO_SHA224 2
#define CR_CONTROL_ALGO_SHA256 3
#define CR_INTSTAT 0x10
#define CR_INTENAB 0x14
#define CR_INTCLEAR 0x18
#define CR_INT_RESULTS_AVAILABLE BIT(0)
#define CR_INT_NEW_RESULTS_SET BIT(1)
#define CR_INT_RESULT_READ_ERR BIT(2)
#define CR_INT_MESSAGE_WRITE_ERROR BIT(3)
#define CR_INT_STATUS BIT(8)
#define CR_RESULT_QUEUE 0x1c
#define CR_RSD0 0x40
#define CR_CORE_REV 0x50
#define CR_CORE_DES1 0x60
#define CR_CORE_DES2 0x70
#define DRIVER_FLAGS_BUSY BIT(0)
#define DRIVER_FLAGS_FINAL BIT(1)
#define DRIVER_FLAGS_DMA_ACTIVE BIT(2)
#define DRIVER_FLAGS_OUTPUT_READY BIT(3)
#define DRIVER_FLAGS_INIT BIT(4)
#define DRIVER_FLAGS_CPU BIT(5)
#define DRIVER_FLAGS_DMA_READY BIT(6)
#define DRIVER_FLAGS_ERROR BIT(7)
#define DRIVER_FLAGS_SG BIT(8)
#define DRIVER_FLAGS_SHA1 BIT(18)
#define DRIVER_FLAGS_SHA224 BIT(19)
#define DRIVER_FLAGS_SHA256 BIT(20)
#define DRIVER_FLAGS_MD5 BIT(21)
#define IMG_HASH_QUEUE_LENGTH 20
#define IMG_HASH_DMA_BURST 4
#define IMG_HASH_DMA_THRESHOLD 64
#ifdef __LITTLE_ENDIAN
#define IMG_HASH_BYTE_ORDER CR_CONTROL_BYTE_ORDER_3210
#else
#define IMG_HASH_BYTE_ORDER CR_CONTROL_BYTE_ORDER_0123
#endif
struct img_hash_dev;
struct img_hash_request_ctx {
struct img_hash_dev *hdev;
u8 digest[SHA256_DIGEST_SIZE] __aligned(sizeof(u32));
unsigned long flags;
size_t digsize;
dma_addr_t dma_addr;
size_t dma_ct;
/* sg root */
struct scatterlist *sgfirst;
/* walk state */
struct scatterlist *sg;
size_t nents;
size_t offset;
unsigned int total;
size_t sent;
unsigned long op;
size_t bufcnt;
struct ahash_request fallback_req;
/* Zero length buffer must remain last member of struct */
u8 buffer[0] __aligned(sizeof(u32));
};
struct img_hash_ctx {
struct img_hash_dev *hdev;
unsigned long flags;
struct crypto_ahash *fallback;
};
struct img_hash_dev {
struct list_head list;
struct device *dev;
struct clk *hash_clk;
struct clk *sys_clk;
void __iomem *io_base;
phys_addr_t bus_addr;
void __iomem *cpu_addr;
spinlock_t lock;
int err;
struct tasklet_struct done_task;
struct tasklet_struct dma_task;
unsigned long flags;
struct crypto_queue queue;
struct ahash_request *req;
struct dma_chan *dma_lch;
};
struct img_hash_drv {
struct list_head dev_list;
spinlock_t lock;
};
static struct img_hash_drv img_hash = {
.dev_list = LIST_HEAD_INIT(img_hash.dev_list),
.lock = __SPIN_LOCK_UNLOCKED(img_hash.lock),
};
static inline u32 img_hash_read(struct img_hash_dev *hdev, u32 offset)
{
return readl_relaxed(hdev->io_base + offset);
}
static inline void img_hash_write(struct img_hash_dev *hdev,
u32 offset, u32 value)
{
writel_relaxed(value, hdev->io_base + offset);
}
static inline u32 img_hash_read_result_queue(struct img_hash_dev *hdev)
{
return be32_to_cpu(img_hash_read(hdev, CR_RESULT_QUEUE));
}
static void img_hash_start(struct img_hash_dev *hdev, bool dma)
{
struct img_hash_request_ctx *ctx = ahash_request_ctx(hdev->req);
u32 cr = IMG_HASH_BYTE_ORDER << CR_CONTROL_BYTE_ORDER_SHIFT;
if (ctx->flags & DRIVER_FLAGS_MD5)
cr |= CR_CONTROL_ALGO_MD5;
else if (ctx->flags & DRIVER_FLAGS_SHA1)
cr |= CR_CONTROL_ALGO_SHA1;
else if (ctx->flags & DRIVER_FLAGS_SHA224)
cr |= CR_CONTROL_ALGO_SHA224;
else if (ctx->flags & DRIVER_FLAGS_SHA256)
cr |= CR_CONTROL_ALGO_SHA256;
dev_dbg(hdev->dev, "Starting hash process\n");
img_hash_write(hdev, CR_CONTROL, cr);
/*
* The hardware block requires two cycles between writing the control
* register and writing the first word of data in non DMA mode, to
* ensure the first data write is not grouped in burst with the control
* register write a read is issued to 'flush' the bus.
*/
if (!dma)
img_hash_read(hdev, CR_CONTROL);
}
static int img_hash_xmit_cpu(struct img_hash_dev *hdev, const u8 *buf,
size_t length, int final)
{
u32 count, len32;
const u32 *buffer = (const u32 *)buf;
dev_dbg(hdev->dev, "xmit_cpu: length: %zu bytes\n", length);
if (final)
hdev->flags |= DRIVER_FLAGS_FINAL;
len32 = DIV_ROUND_UP(length, sizeof(u32));
for (count = 0; count < len32; count++)
writel_relaxed(buffer[count], hdev->cpu_addr);
return -EINPROGRESS;
}
static void img_hash_dma_callback(void *data)
{
struct img_hash_dev *hdev = (struct img_hash_dev *)data;
struct img_hash_request_ctx *ctx = ahash_request_ctx(hdev->req);
if (ctx->bufcnt) {
img_hash_xmit_cpu(hdev, ctx->buffer, ctx->bufcnt, 0);
ctx->bufcnt = 0;
}
if (ctx->sg)
tasklet_schedule(&hdev->dma_task);
}
static int img_hash_xmit_dma(struct img_hash_dev *hdev, struct scatterlist *sg)
{
struct dma_async_tx_descriptor *desc;
struct img_hash_request_ctx *ctx = ahash_request_ctx(hdev->req);
ctx->dma_ct = dma_map_sg(hdev->dev, sg, 1, DMA_TO_DEVICE);
if (ctx->dma_ct == 0) {
dev_err(hdev->dev, "Invalid DMA sg\n");
hdev->err = -EINVAL;
return -EINVAL;
}
desc = dmaengine_prep_slave_sg(hdev->dma_lch,
sg,
ctx->dma_ct,
DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc) {
dev_err(hdev->dev, "Null DMA descriptor\n");
hdev->err = -EINVAL;
dma_unmap_sg(hdev->dev, sg, 1, DMA_TO_DEVICE);
return -EINVAL;
}
desc->callback = img_hash_dma_callback;
desc->callback_param = hdev;
dmaengine_submit(desc);
dma_async_issue_pending(hdev->dma_lch);
return 0;
}
static int img_hash_write_via_cpu(struct img_hash_dev *hdev)
{
struct img_hash_request_ctx *ctx = ahash_request_ctx(hdev->req);
ctx->bufcnt = sg_copy_to_buffer(hdev->req->src, sg_nents(ctx->sg),
ctx->buffer, hdev->req->nbytes);
ctx->total = hdev->req->nbytes;
ctx->bufcnt = 0;
hdev->flags |= (DRIVER_FLAGS_CPU | DRIVER_FLAGS_FINAL);
img_hash_start(hdev, false);
return img_hash_xmit_cpu(hdev, ctx->buffer, ctx->total, 1);
}
static int img_hash_finish(struct ahash_request *req)
{
struct img_hash_request_ctx *ctx = ahash_request_ctx(req);
if (!req->result)
return -EINVAL;
memcpy(req->result, ctx->digest, ctx->digsize);
return 0;
}
static void img_hash_copy_hash(struct ahash_request *req)
{
struct img_hash_request_ctx *ctx = ahash_request_ctx(req);
u32 *hash = (u32 *)ctx->digest;
int i;
for (i = (ctx->digsize / sizeof(u32)) - 1; i >= 0; i--)
hash[i] = img_hash_read_result_queue(ctx->hdev);
}
static void img_hash_finish_req(struct ahash_request *req, int err)
{
struct img_hash_request_ctx *ctx = ahash_request_ctx(req);
struct img_hash_dev *hdev = ctx->hdev;
if (!err) {
img_hash_copy_hash(req);
if (DRIVER_FLAGS_FINAL & hdev->flags)
err = img_hash_finish(req);
} else {
dev_warn(hdev->dev, "Hash failed with error %d\n", err);
ctx->flags |= DRIVER_FLAGS_ERROR;
}
hdev->flags &= ~(DRIVER_FLAGS_DMA_READY | DRIVER_FLAGS_OUTPUT_READY |
DRIVER_FLAGS_CPU | DRIVER_FLAGS_BUSY | DRIVER_FLAGS_FINAL);
if (req->base.complete)
req->base.complete(&req->base, err);
}
static int img_hash_write_via_dma(struct img_hash_dev *hdev)
{
struct img_hash_request_ctx *ctx = ahash_request_ctx(hdev->req);
img_hash_start(hdev, true);
dev_dbg(hdev->dev, "xmit dma size: %d\n", ctx->total);
if (!ctx->total)
hdev->flags |= DRIVER_FLAGS_FINAL;
hdev->flags |= DRIVER_FLAGS_DMA_ACTIVE | DRIVER_FLAGS_FINAL;
tasklet_schedule(&hdev->dma_task);
return -EINPROGRESS;
}
static int img_hash_dma_init(struct img_hash_dev *hdev)
{
struct dma_slave_config dma_conf;
int err = -EINVAL;
hdev->dma_lch = dma_request_slave_channel(hdev->dev, "tx");
if (!hdev->dma_lch) {
dev_err(hdev->dev, "Couldn't acquire a slave DMA channel.\n");
return -EBUSY;
}
dma_conf.direction = DMA_MEM_TO_DEV;
dma_conf.dst_addr = hdev->bus_addr;
dma_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
dma_conf.dst_maxburst = IMG_HASH_DMA_BURST;
dma_conf.device_fc = false;
err = dmaengine_slave_config(hdev->dma_lch, &dma_conf);
if (err) {
dev_err(hdev->dev, "Couldn't configure DMA slave.\n");
dma_release_channel(hdev->dma_lch);
return err;
}
return 0;
}
static void img_hash_dma_task(unsigned long d)
{
struct img_hash_dev *hdev = (struct img_hash_dev *)d;
struct img_hash_request_ctx *ctx = ahash_request_ctx(hdev->req);
u8 *addr;
size_t nbytes, bleft, wsend, len, tbc;
struct scatterlist tsg;
if (!hdev->req || !ctx->sg)
return;
addr = sg_virt(ctx->sg);
nbytes = ctx->sg->length - ctx->offset;
/*
* The hash accelerator does not support a data valid mask. This means
* that if each dma (i.e. per page) is not a multiple of 4 bytes, the
* padding bytes in the last word written by that dma would erroneously
* be included in the hash. To avoid this we round down the transfer,
* and add the excess to the start of the next dma. It does not matter
* that the final dma may not be a multiple of 4 bytes as the hashing
* block is programmed to accept the correct number of bytes.
*/
bleft = nbytes % 4;
wsend = (nbytes / 4);
if (wsend) {
sg_init_one(&tsg, addr + ctx->offset, wsend * 4);
if (img_hash_xmit_dma(hdev, &tsg)) {
dev_err(hdev->dev, "DMA failed, falling back to CPU");
ctx->flags |= DRIVER_FLAGS_CPU;
hdev->err = 0;
img_hash_xmit_cpu(hdev, addr + ctx->offset,
wsend * 4, 0);
ctx->sent += wsend * 4;
wsend = 0;
} else {
ctx->sent += wsend * 4;
}
}
if (bleft) {
ctx->bufcnt = sg_pcopy_to_buffer(ctx->sgfirst, ctx->nents,
ctx->buffer, bleft, ctx->sent);
tbc = 0;
ctx->sg = sg_next(ctx->sg);
while (ctx->sg && (ctx->bufcnt < 4)) {
len = ctx->sg->length;
if (likely(len > (4 - ctx->bufcnt)))
len = 4 - ctx->bufcnt;
tbc = sg_pcopy_to_buffer(ctx->sgfirst, ctx->nents,
ctx->buffer + ctx->bufcnt, len,
ctx->sent + ctx->bufcnt);
ctx->bufcnt += tbc;
if (tbc >= ctx->sg->length) {
ctx->sg = sg_next(ctx->sg);
tbc = 0;
}
}
ctx->sent += ctx->bufcnt;
ctx->offset = tbc;
if (!wsend)
img_hash_dma_callback(hdev);
} else {
ctx->offset = 0;
ctx->sg = sg_next(ctx->sg);
}
}
static int img_hash_write_via_dma_stop(struct img_hash_dev *hdev)
{
struct img_hash_request_ctx *ctx = ahash_request_ctx(hdev->req);
if (ctx->flags & DRIVER_FLAGS_SG)
dma_unmap_sg(hdev->dev, ctx->sg, ctx->dma_ct, DMA_TO_DEVICE);
return 0;
}
static int img_hash_process_data(struct img_hash_dev *hdev)
{
struct ahash_request *req = hdev->req;
struct img_hash_request_ctx *ctx = ahash_request_ctx(req);
int err = 0;
ctx->bufcnt = 0;
if (req->nbytes >= IMG_HASH_DMA_THRESHOLD) {
dev_dbg(hdev->dev, "process data request(%d bytes) using DMA\n",
req->nbytes);
err = img_hash_write_via_dma(hdev);
} else {
dev_dbg(hdev->dev, "process data request(%d bytes) using CPU\n",
req->nbytes);
err = img_hash_write_via_cpu(hdev);
}
return err;
}
static int img_hash_hw_init(struct img_hash_dev *hdev)
{
unsigned long long nbits;
u32 u, l;
img_hash_write(hdev, CR_RESET, CR_RESET_SET);
img_hash_write(hdev, CR_RESET, CR_RESET_UNSET);
img_hash_write(hdev, CR_INTENAB, CR_INT_NEW_RESULTS_SET);
nbits = (u64)hdev->req->nbytes << 3;
u = nbits >> 32;
l = nbits;
img_hash_write(hdev, CR_MESSAGE_LENGTH_H, u);
img_hash_write(hdev, CR_MESSAGE_LENGTH_L, l);
if (!(DRIVER_FLAGS_INIT & hdev->flags)) {
hdev->flags |= DRIVER_FLAGS_INIT;
hdev->err = 0;
}
dev_dbg(hdev->dev, "hw initialized, nbits: %llx\n", nbits);
return 0;
}
static int img_hash_init(struct ahash_request *req)
{
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct img_hash_request_ctx *rctx = ahash_request_ctx(req);
struct img_hash_ctx *ctx = crypto_ahash_ctx(tfm);
ahash_request_set_tfm(&rctx->fallback_req, ctx->fallback);
rctx->fallback_req.base.flags = req->base.flags
& CRYPTO_TFM_REQ_MAY_SLEEP;
return crypto_ahash_init(&rctx->fallback_req);
}
static int img_hash_handle_queue(struct img_hash_dev *hdev,
struct ahash_request *req)
{
struct crypto_async_request *async_req, *backlog;
struct img_hash_request_ctx *ctx;
unsigned long flags;
int err = 0, res = 0;
spin_lock_irqsave(&hdev->lock, flags);
if (req)
res = ahash_enqueue_request(&hdev->queue, req);
if (DRIVER_FLAGS_BUSY & hdev->flags) {
spin_unlock_irqrestore(&hdev->lock, flags);
return res;
}
backlog = crypto_get_backlog(&hdev->queue);
async_req = crypto_dequeue_request(&hdev->queue);
if (async_req)
hdev->flags |= DRIVER_FLAGS_BUSY;
spin_unlock_irqrestore(&hdev->lock, flags);
if (!async_req)
return res;
if (backlog)
backlog->complete(backlog, -EINPROGRESS);
req = ahash_request_cast(async_req);
hdev->req = req;
ctx = ahash_request_ctx(req);
dev_info(hdev->dev, "processing req, op: %lu, bytes: %d\n",
ctx->op, req->nbytes);
err = img_hash_hw_init(hdev);
if (!err)
err = img_hash_process_data(hdev);
if (err != -EINPROGRESS) {
/* done_task will not finish so do it here */
img_hash_finish_req(req, err);
}
return res;
}
static int img_hash_update(struct ahash_request *req)
{
struct img_hash_request_ctx *rctx = ahash_request_ctx(req);
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct img_hash_ctx *ctx = crypto_ahash_ctx(tfm);
ahash_request_set_tfm(&rctx->fallback_req, ctx->fallback);
rctx->fallback_req.base.flags = req->base.flags
& CRYPTO_TFM_REQ_MAY_SLEEP;
rctx->fallback_req.nbytes = req->nbytes;
rctx->fallback_req.src = req->src;
return crypto_ahash_update(&rctx->fallback_req);
}
static int img_hash_final(struct ahash_request *req)
{
struct img_hash_request_ctx *rctx = ahash_request_ctx(req);
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct img_hash_ctx *ctx = crypto_ahash_ctx(tfm);
ahash_request_set_tfm(&rctx->fallback_req, ctx->fallback);
rctx->fallback_req.base.flags = req->base.flags
& CRYPTO_TFM_REQ_MAY_SLEEP;
rctx->fallback_req.result = req->result;
return crypto_ahash_final(&rctx->fallback_req);
}
static int img_hash_finup(struct ahash_request *req)
{
struct img_hash_request_ctx *rctx = ahash_request_ctx(req);
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct img_hash_ctx *ctx = crypto_ahash_ctx(tfm);
ahash_request_set_tfm(&rctx->fallback_req, ctx->fallback);
rctx->fallback_req.base.flags = req->base.flags
& CRYPTO_TFM_REQ_MAY_SLEEP;
rctx->fallback_req.nbytes = req->nbytes;
rctx->fallback_req.src = req->src;
rctx->fallback_req.result = req->result;
return crypto_ahash_finup(&rctx->fallback_req);
}
static int img_hash_import(struct ahash_request *req, const void *in)
{
struct img_hash_request_ctx *rctx = ahash_request_ctx(req);
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct img_hash_ctx *ctx = crypto_ahash_ctx(tfm);
ahash_request_set_tfm(&rctx->fallback_req, ctx->fallback);
rctx->fallback_req.base.flags = req->base.flags
& CRYPTO_TFM_REQ_MAY_SLEEP;
return crypto_ahash_import(&rctx->fallback_req, in);
}
static int img_hash_export(struct ahash_request *req, void *out)
{
struct img_hash_request_ctx *rctx = ahash_request_ctx(req);
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct img_hash_ctx *ctx = crypto_ahash_ctx(tfm);
ahash_request_set_tfm(&rctx->fallback_req, ctx->fallback);
rctx->fallback_req.base.flags = req->base.flags
& CRYPTO_TFM_REQ_MAY_SLEEP;
return crypto_ahash_export(&rctx->fallback_req, out);
}
static int img_hash_digest(struct ahash_request *req)
{
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct img_hash_ctx *tctx = crypto_ahash_ctx(tfm);
struct img_hash_request_ctx *ctx = ahash_request_ctx(req);
struct img_hash_dev *hdev = NULL;
struct img_hash_dev *tmp;
int err;
spin_lock(&img_hash.lock);
if (!tctx->hdev) {
list_for_each_entry(tmp, &img_hash.dev_list, list) {
hdev = tmp;
break;
}
tctx->hdev = hdev;
} else {
hdev = tctx->hdev;
}
spin_unlock(&img_hash.lock);
ctx->hdev = hdev;
ctx->flags = 0;
ctx->digsize = crypto_ahash_digestsize(tfm);
switch (ctx->digsize) {
case SHA1_DIGEST_SIZE:
ctx->flags |= DRIVER_FLAGS_SHA1;
break;
case SHA256_DIGEST_SIZE:
ctx->flags |= DRIVER_FLAGS_SHA256;
break;
case SHA224_DIGEST_SIZE:
ctx->flags |= DRIVER_FLAGS_SHA224;
break;
case MD5_DIGEST_SIZE:
ctx->flags |= DRIVER_FLAGS_MD5;
break;
default:
return -EINVAL;
}
ctx->bufcnt = 0;
ctx->offset = 0;
ctx->sent = 0;
ctx->total = req->nbytes;
ctx->sg = req->src;
ctx->sgfirst = req->src;
ctx->nents = sg_nents(ctx->sg);
err = img_hash_handle_queue(tctx->hdev, req);
return err;
}
static int img_hash_cra_init(struct crypto_tfm *tfm, const char *alg_name)
{
struct img_hash_ctx *ctx = crypto_tfm_ctx(tfm);
int err = -ENOMEM;
ctx->fallback = crypto_alloc_ahash(alg_name, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(ctx->fallback)) {
pr_err("img_hash: Could not load fallback driver.\n");
err = PTR_ERR(ctx->fallback);
goto err;
}
crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
sizeof(struct img_hash_request_ctx) +
crypto_ahash_reqsize(ctx->fallback) +
IMG_HASH_DMA_THRESHOLD);
return 0;
err:
return err;
}
static int img_hash_cra_md5_init(struct crypto_tfm *tfm)
{
return img_hash_cra_init(tfm, "md5-generic");
}
static int img_hash_cra_sha1_init(struct crypto_tfm *tfm)
{
return img_hash_cra_init(tfm, "sha1-generic");
}
static int img_hash_cra_sha224_init(struct crypto_tfm *tfm)
{
return img_hash_cra_init(tfm, "sha224-generic");
}
static int img_hash_cra_sha256_init(struct crypto_tfm *tfm)
{
return img_hash_cra_init(tfm, "sha256-generic");
}
static void img_hash_cra_exit(struct crypto_tfm *tfm)
{
struct img_hash_ctx *tctx = crypto_tfm_ctx(tfm);
crypto_free_ahash(tctx->fallback);
}
static irqreturn_t img_irq_handler(int irq, void *dev_id)
{
struct img_hash_dev *hdev = dev_id;
u32 reg;
reg = img_hash_read(hdev, CR_INTSTAT);
img_hash_write(hdev, CR_INTCLEAR, reg);
if (reg & CR_INT_NEW_RESULTS_SET) {
dev_dbg(hdev->dev, "IRQ CR_INT_NEW_RESULTS_SET\n");
if (DRIVER_FLAGS_BUSY & hdev->flags) {
hdev->flags |= DRIVER_FLAGS_OUTPUT_READY;
if (!(DRIVER_FLAGS_CPU & hdev->flags))
hdev->flags |= DRIVER_FLAGS_DMA_READY;
tasklet_schedule(&hdev->done_task);
} else {
dev_warn(hdev->dev,
"HASH interrupt when no active requests.\n");
}
} else if (reg & CR_INT_RESULTS_AVAILABLE) {
dev_warn(hdev->dev,
"IRQ triggered before the hash had completed\n");
} else if (reg & CR_INT_RESULT_READ_ERR) {
dev_warn(hdev->dev,
"Attempt to read from an empty result queue\n");
} else if (reg & CR_INT_MESSAGE_WRITE_ERROR) {
dev_warn(hdev->dev,
"Data written before the hardware was configured\n");
}
return IRQ_HANDLED;
}
static struct ahash_alg img_algs[] = {
{
.init = img_hash_init,
.update = img_hash_update,
.final = img_hash_final,
.finup = img_hash_finup,
.export = img_hash_export,
.import = img_hash_import,
.digest = img_hash_digest,
.halg = {
.digestsize = MD5_DIGEST_SIZE,
.statesize = sizeof(struct md5_state),
.base = {
.cra_name = "md5",
.cra_driver_name = "img-md5",
.cra_priority = 300,
.cra_flags =
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = MD5_HMAC_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct img_hash_ctx),
.cra_init = img_hash_cra_md5_init,
.cra_exit = img_hash_cra_exit,
.cra_module = THIS_MODULE,
}
}
},
{
.init = img_hash_init,
.update = img_hash_update,
.final = img_hash_final,
.finup = img_hash_finup,
.export = img_hash_export,
.import = img_hash_import,
.digest = img_hash_digest,
.halg = {
.digestsize = SHA1_DIGEST_SIZE,
.statesize = sizeof(struct sha1_state),
.base = {
.cra_name = "sha1",
.cra_driver_name = "img-sha1",
.cra_priority = 300,
.cra_flags =
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct img_hash_ctx),
.cra_init = img_hash_cra_sha1_init,
.cra_exit = img_hash_cra_exit,
.cra_module = THIS_MODULE,
}
}
},
{
.init = img_hash_init,
.update = img_hash_update,
.final = img_hash_final,
.finup = img_hash_finup,
.export = img_hash_export,
.import = img_hash_import,
.digest = img_hash_digest,
.halg = {
.digestsize = SHA224_DIGEST_SIZE,
.statesize = sizeof(struct sha256_state),
.base = {
.cra_name = "sha224",
.cra_driver_name = "img-sha224",
.cra_priority = 300,
.cra_flags =
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA224_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct img_hash_ctx),
.cra_init = img_hash_cra_sha224_init,
.cra_exit = img_hash_cra_exit,
.cra_module = THIS_MODULE,
}
}
},
{
.init = img_hash_init,
.update = img_hash_update,
.final = img_hash_final,
.finup = img_hash_finup,
.export = img_hash_export,
.import = img_hash_import,
.digest = img_hash_digest,
.halg = {
.digestsize = SHA256_DIGEST_SIZE,
.statesize = sizeof(struct sha256_state),
.base = {
.cra_name = "sha256",
.cra_driver_name = "img-sha256",
.cra_priority = 300,
.cra_flags =
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA256_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct img_hash_ctx),
.cra_init = img_hash_cra_sha256_init,
.cra_exit = img_hash_cra_exit,
.cra_module = THIS_MODULE,
}
}
}
};
static int img_register_algs(struct img_hash_dev *hdev)
{
int i, err;
for (i = 0; i < ARRAY_SIZE(img_algs); i++) {
err = crypto_register_ahash(&img_algs[i]);
if (err)
goto err_reg;
}
return 0;
err_reg:
for (; i--; )
crypto_unregister_ahash(&img_algs[i]);
return err;
}
static int img_unregister_algs(struct img_hash_dev *hdev)
{
int i;
for (i = 0; i < ARRAY_SIZE(img_algs); i++)
crypto_unregister_ahash(&img_algs[i]);
return 0;
}
static void img_hash_done_task(unsigned long data)
{
struct img_hash_dev *hdev = (struct img_hash_dev *)data;
int err = 0;
if (hdev->err == -EINVAL) {
err = hdev->err;
goto finish;
}
if (!(DRIVER_FLAGS_BUSY & hdev->flags)) {
img_hash_handle_queue(hdev, NULL);
return;
}
if (DRIVER_FLAGS_CPU & hdev->flags) {
if (DRIVER_FLAGS_OUTPUT_READY & hdev->flags) {
hdev->flags &= ~DRIVER_FLAGS_OUTPUT_READY;
goto finish;
}
} else if (DRIVER_FLAGS_DMA_READY & hdev->flags) {
if (DRIVER_FLAGS_DMA_ACTIVE & hdev->flags) {
hdev->flags &= ~DRIVER_FLAGS_DMA_ACTIVE;
img_hash_write_via_dma_stop(hdev);
if (hdev->err) {
err = hdev->err;
goto finish;
}
}
if (DRIVER_FLAGS_OUTPUT_READY & hdev->flags) {
hdev->flags &= ~(DRIVER_FLAGS_DMA_READY |
DRIVER_FLAGS_OUTPUT_READY);
goto finish;
}
}
return;
finish:
img_hash_finish_req(hdev->req, err);
}
static const struct of_device_id img_hash_match[] = {
{ .compatible = "img,hash-accelerator" },
{}
};
MODULE_DEVICE_TABLE(of, img_hash_match);
static int img_hash_probe(struct platform_device *pdev)
{
struct img_hash_dev *hdev;
struct device *dev = &pdev->dev;
struct resource *hash_res;
int irq;
int err;
hdev = devm_kzalloc(dev, sizeof(*hdev), GFP_KERNEL);
if (hdev == NULL)
return -ENOMEM;
spin_lock_init(&hdev->lock);
hdev->dev = dev;
platform_set_drvdata(pdev, hdev);
INIT_LIST_HEAD(&hdev->list);
tasklet_init(&hdev->done_task, img_hash_done_task, (unsigned long)hdev);
tasklet_init(&hdev->dma_task, img_hash_dma_task, (unsigned long)hdev);
crypto_init_queue(&hdev->queue, IMG_HASH_QUEUE_LENGTH);
/* Register bank */
hash_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
hdev->io_base = devm_ioremap_resource(dev, hash_res);
if (IS_ERR(hdev->io_base)) {
err = PTR_ERR(hdev->io_base);
dev_err(dev, "can't ioremap, returned %d\n", err);
goto res_err;
}
/* Write port (DMA or CPU) */
hash_res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
hdev->cpu_addr = devm_ioremap_resource(dev, hash_res);
if (IS_ERR(hdev->cpu_addr)) {
dev_err(dev, "can't ioremap write port\n");
err = PTR_ERR(hdev->cpu_addr);
goto res_err;
}
hdev->bus_addr = hash_res->start;
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(dev, "no IRQ resource info\n");
err = irq;
goto res_err;
}
err = devm_request_irq(dev, irq, img_irq_handler, 0,
dev_name(dev), hdev);
if (err) {
dev_err(dev, "unable to request irq\n");
goto res_err;
}
dev_dbg(dev, "using IRQ channel %d\n", irq);
hdev->hash_clk = devm_clk_get(&pdev->dev, "hash");
if (IS_ERR(hdev->hash_clk)) {
dev_err(dev, "clock initialization failed.\n");
err = PTR_ERR(hdev->hash_clk);
goto res_err;
}
hdev->sys_clk = devm_clk_get(&pdev->dev, "sys");
if (IS_ERR(hdev->sys_clk)) {
dev_err(dev, "clock initialization failed.\n");
err = PTR_ERR(hdev->sys_clk);
goto res_err;
}
err = clk_prepare_enable(hdev->hash_clk);
if (err)
goto res_err;
err = clk_prepare_enable(hdev->sys_clk);
if (err)
goto clk_err;
err = img_hash_dma_init(hdev);
if (err)
goto dma_err;
dev_dbg(dev, "using %s for DMA transfers\n",
dma_chan_name(hdev->dma_lch));
spin_lock(&img_hash.lock);
list_add_tail(&hdev->list, &img_hash.dev_list);
spin_unlock(&img_hash.lock);
err = img_register_algs(hdev);
if (err)
goto err_algs;
dev_info(dev, "Img MD5/SHA1/SHA224/SHA256 Hardware accelerator initialized\n");
return 0;
err_algs:
spin_lock(&img_hash.lock);
list_del(&hdev->list);
spin_unlock(&img_hash.lock);
dma_release_channel(hdev->dma_lch);
dma_err:
clk_disable_unprepare(hdev->sys_clk);
clk_err:
clk_disable_unprepare(hdev->hash_clk);
res_err:
tasklet_kill(&hdev->done_task);
tasklet_kill(&hdev->dma_task);
return err;
}
static int img_hash_remove(struct platform_device *pdev)
{
struct img_hash_dev *hdev;
hdev = platform_get_drvdata(pdev);
spin_lock(&img_hash.lock);
list_del(&hdev->list);
spin_unlock(&img_hash.lock);
img_unregister_algs(hdev);
tasklet_kill(&hdev->done_task);
tasklet_kill(&hdev->dma_task);
dma_release_channel(hdev->dma_lch);
clk_disable_unprepare(hdev->hash_clk);
clk_disable_unprepare(hdev->sys_clk);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int img_hash_suspend(struct device *dev)
{
struct img_hash_dev *hdev = dev_get_drvdata(dev);
clk_disable_unprepare(hdev->hash_clk);
clk_disable_unprepare(hdev->sys_clk);
return 0;
}
static int img_hash_resume(struct device *dev)
{
struct img_hash_dev *hdev = dev_get_drvdata(dev);
int ret;
ret = clk_prepare_enable(hdev->hash_clk);
if (ret)
return ret;
ret = clk_prepare_enable(hdev->sys_clk);
if (ret) {
clk_disable_unprepare(hdev->hash_clk);
return ret;
}
return 0;
}
#endif /* CONFIG_PM_SLEEP */
static const struct dev_pm_ops img_hash_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(img_hash_suspend, img_hash_resume)
};
static struct platform_driver img_hash_driver = {
.probe = img_hash_probe,
.remove = img_hash_remove,
.driver = {
.name = "img-hash-accelerator",
.pm = &img_hash_pm_ops,
.of_match_table = of_match_ptr(img_hash_match),
}
};
module_platform_driver(img_hash_driver);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Imgtec SHA1/224/256 & MD5 hw accelerator driver");
MODULE_AUTHOR("Will Thomas.");
MODULE_AUTHOR("James Hartley <james.hartley@imgtec.com>");
|
{
"pile_set_name": "Github"
}
|
/**
* Checkbox
* --------------------------------------------------
*/
.checkbox {
// set the color defaults
@include checkbox-style($checkbox-off-border-default, $checkbox-on-bg-default);
position: relative;
display: inline-block;
padding: ($checkbox-height / 4) ($checkbox-width / 4);
cursor: pointer;
}
.checkbox-light {
@include checkbox-style($checkbox-off-border-light, $checkbox-on-bg-light);
}
.checkbox-stable {
@include checkbox-style($checkbox-off-border-stable, $checkbox-on-bg-stable);
}
.checkbox-positive {
@include checkbox-style($checkbox-off-border-positive, $checkbox-on-bg-positive);
}
.checkbox-calm {
@include checkbox-style($checkbox-off-border-calm, $checkbox-on-bg-calm);
}
.checkbox-assertive {
@include checkbox-style($checkbox-off-border-assertive, $checkbox-on-bg-assertive);
}
.checkbox-balanced {
@include checkbox-style($checkbox-off-border-balanced, $checkbox-on-bg-balanced);
}
.checkbox-energized{
@include checkbox-style($checkbox-off-border-energized, $checkbox-on-bg-energized);
}
.checkbox-royal {
@include checkbox-style($checkbox-off-border-royal, $checkbox-on-bg-royal);
}
.checkbox-dark {
@include checkbox-style($checkbox-off-border-dark, $checkbox-on-bg-dark);
}
.checkbox input:disabled:before,
.checkbox input:disabled + .checkbox-icon:before {
border-color: $checkbox-off-border-light;
}
.checkbox input:disabled:checked:before,
.checkbox input:disabled:checked + .checkbox-icon:before {
background: $checkbox-on-bg-light;
}
.checkbox.checkbox-input-hidden input {
display: none !important;
}
.checkbox input,
.checkbox-icon {
position: relative;
width: $checkbox-width;
height: $checkbox-height;
display: block;
border: 0;
background: transparent;
cursor: pointer;
-webkit-appearance: none;
&:before {
// what the checkbox looks like when its not checked
display: table;
width: 100%;
height: 100%;
border-width: $checkbox-border-width;
border-style: solid;
border-radius: $checkbox-border-radius;
background: $checkbox-off-bg-color;
content: ' ';
transition: background-color 20ms ease-in-out;
}
}
.checkbox input:checked:before,
input:checked + .checkbox-icon:before {
border-width: $checkbox-border-width + 1;
}
// the checkmark within the box
.checkbox input:after,
.checkbox-icon:after {
@include transition(opacity .05s ease-in-out);
@include rotate(-45deg);
position: absolute;
top: 30%;
left: 26%;
display: table;
width: ($checkbox-width / 2) + 1;
height: ($checkbox-width / 3) + 1;
border: $checkbox-check-width solid $checkbox-check-color;
border-top: 0;
border-right: 0;
content: ' ';
opacity: 0;
}
.grade-c .checkbox input:after,
.grade-c .checkbox-icon:after {
@include rotate(0);
top: 3px;
left: 4px;
border: none;
color: $checkbox-check-color;
content: '\2713';
font-weight: bold;
font-size: 20px;
}
// what the checkmark looks like when its checked
.checkbox input:checked:after,
input:checked + .checkbox-icon:after {
opacity: 1;
}
// make sure item content have enough padding on left to fit the checkbox
.item-checkbox {
padding-left: ($item-padding * 2) + $checkbox-width;
&.active {
box-shadow: none;
}
}
// position the checkbox to the left within an item
.item-checkbox .checkbox {
position: absolute;
top: 50%;
right: $item-padding / 2;
left: $item-padding / 2;
z-index: $z-index-item-checkbox;
margin-top: (($checkbox-height + ($checkbox-height / 2)) / 2) * -1;
}
.item-checkbox.item-checkbox-right {
padding-right: ($item-padding * 2) + $checkbox-width;
padding-left: $item-padding;
}
.item-checkbox-right .checkbox input,
.item-checkbox-right .checkbox-icon {
float: right;
}
|
{
"pile_set_name": "Github"
}
|
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
*
* Bluetooth support for Intel devices
*
* Copyright (C) 2015 Intel Corporation
*/
struct intel_version {
u8 status;
u8 hw_platform;
u8 hw_variant;
u8 hw_revision;
u8 fw_variant;
u8 fw_revision;
u8 fw_build_num;
u8 fw_build_ww;
u8 fw_build_yy;
u8 fw_patch_num;
} __packed;
struct intel_boot_params {
__u8 status;
__u8 otp_format;
__u8 otp_content;
__u8 otp_patch;
__le16 dev_revid;
__u8 secure_boot;
__u8 key_from_hdr;
__u8 key_type;
__u8 otp_lock;
__u8 api_lock;
__u8 debug_lock;
bdaddr_t otp_bdaddr;
__u8 min_fw_build_nn;
__u8 min_fw_build_cw;
__u8 min_fw_build_yy;
__u8 limited_cce;
__u8 unlocked_state;
} __packed;
struct intel_bootup {
__u8 zero;
__u8 num_cmds;
__u8 source;
__u8 reset_type;
__u8 reset_reason;
__u8 ddc_status;
} __packed;
struct intel_secure_send_result {
__u8 result;
__le16 opcode;
__u8 status;
} __packed;
struct intel_reset {
__u8 reset_type;
__u8 patch_enable;
__u8 ddc_reload;
__u8 boot_option;
__le32 boot_param;
} __packed;
struct intel_debug_features {
__u8 page1[16];
} __packed;
#if IS_ENABLED(CONFIG_BT_INTEL)
int btintel_check_bdaddr(struct hci_dev *hdev);
int btintel_enter_mfg(struct hci_dev *hdev);
int btintel_exit_mfg(struct hci_dev *hdev, bool reset, bool patched);
int btintel_set_bdaddr(struct hci_dev *hdev, const bdaddr_t *bdaddr);
int btintel_set_diag(struct hci_dev *hdev, bool enable);
int btintel_set_diag_mfg(struct hci_dev *hdev, bool enable);
void btintel_hw_error(struct hci_dev *hdev, u8 code);
void btintel_version_info(struct hci_dev *hdev, struct intel_version *ver);
int btintel_secure_send(struct hci_dev *hdev, u8 fragment_type, u32 plen,
const void *param);
int btintel_load_ddc_config(struct hci_dev *hdev, const char *ddc_name);
int btintel_set_event_mask(struct hci_dev *hdev, bool debug);
int btintel_set_event_mask_mfg(struct hci_dev *hdev, bool debug);
int btintel_read_version(struct hci_dev *hdev, struct intel_version *ver);
struct regmap *btintel_regmap_init(struct hci_dev *hdev, u16 opcode_read,
u16 opcode_write);
int btintel_send_intel_reset(struct hci_dev *hdev, u32 boot_param);
int btintel_read_boot_params(struct hci_dev *hdev,
struct intel_boot_params *params);
int btintel_download_firmware(struct hci_dev *dev, const struct firmware *fw,
u32 *boot_param);
void btintel_reset_to_bootloader(struct hci_dev *hdev);
int btintel_read_debug_features(struct hci_dev *hdev,
struct intel_debug_features *features);
int btintel_set_debug_features(struct hci_dev *hdev,
const struct intel_debug_features *features);
#else
static inline int btintel_check_bdaddr(struct hci_dev *hdev)
{
return -EOPNOTSUPP;
}
static inline int btintel_enter_mfg(struct hci_dev *hdev)
{
return -EOPNOTSUPP;
}
static inline int btintel_exit_mfg(struct hci_dev *hdev, bool reset, bool patched)
{
return -EOPNOTSUPP;
}
static inline int btintel_set_bdaddr(struct hci_dev *hdev, const bdaddr_t *bdaddr)
{
return -EOPNOTSUPP;
}
static inline int btintel_set_diag(struct hci_dev *hdev, bool enable)
{
return -EOPNOTSUPP;
}
static inline int btintel_set_diag_mfg(struct hci_dev *hdev, bool enable)
{
return -EOPNOTSUPP;
}
static inline void btintel_hw_error(struct hci_dev *hdev, u8 code)
{
}
static inline void btintel_version_info(struct hci_dev *hdev,
struct intel_version *ver)
{
}
static inline int btintel_secure_send(struct hci_dev *hdev, u8 fragment_type,
u32 plen, const void *param)
{
return -EOPNOTSUPP;
}
static inline int btintel_load_ddc_config(struct hci_dev *hdev,
const char *ddc_name)
{
return -EOPNOTSUPP;
}
static inline int btintel_set_event_mask(struct hci_dev *hdev, bool debug)
{
return -EOPNOTSUPP;
}
static inline int btintel_set_event_mask_mfg(struct hci_dev *hdev, bool debug)
{
return -EOPNOTSUPP;
}
static inline int btintel_read_version(struct hci_dev *hdev,
struct intel_version *ver)
{
return -EOPNOTSUPP;
}
static inline struct regmap *btintel_regmap_init(struct hci_dev *hdev,
u16 opcode_read,
u16 opcode_write)
{
return ERR_PTR(-EINVAL);
}
static inline int btintel_send_intel_reset(struct hci_dev *hdev,
u32 reset_param)
{
return -EOPNOTSUPP;
}
static inline int btintel_read_boot_params(struct hci_dev *hdev,
struct intel_boot_params *params)
{
return -EOPNOTSUPP;
}
static inline int btintel_download_firmware(struct hci_dev *dev,
const struct firmware *fw,
u32 *boot_param)
{
return -EOPNOTSUPP;
}
static inline void btintel_reset_to_bootloader(struct hci_dev *hdev)
{
}
static inline int btintel_read_debug_features(struct hci_dev *hdev,
struct intel_debug_features *features)
{
return -EOPNOTSUPP;
}
static inline int btintel_set_debug_features(struct hci_dev *hdev,
const struct intel_debug_features *features)
{
return -EOPNOTSUPP;
}
#endif
|
{
"pile_set_name": "Github"
}
|
# frozen_string_literal: true
RSpec.describe Hyrax::SearchState do
let(:controller) { CatalogController.new }
let(:config) { Blacklight::Configuration.new }
let(:state) { described_class.new({}, config, controller) }
describe "url_for_document" do
subject { state.url_for_document(document) }
context "with a collection" do
let(:document) { SolrDocument.new(id: '9999', has_model_ssim: ['Collection']) }
it "returns an array with the route set and doc" do
expect(subject.first).to be_kind_of ActionDispatch::Routing::RoutesProxy
expect(subject.last).to eq document
end
end
context "with a work" do
let(:document) { SolrDocument.new(id: '9999', has_model_ssim: ['GenericWork']) }
it "returns an array with the route set and doc" do
expect(subject.first).to be_kind_of ActionDispatch::Routing::RoutesProxy
expect(subject.last).to eq document
end
end
end
end
|
{
"pile_set_name": "Github"
}
|
#
# Test for persistent corrupt bit for corrupted index and table
#
-- source include/have_innodb.inc
-- source include/have_innodb_16k.inc
# Issues with innodb_change_buffering_debug on Windows, so the test scenario
# cannot be created on windows
--source include/not_windows.inc
# This test needs debug server
--source include/have_debug.inc
-- disable_query_log
call mtr.add_suppression("Flagged corruption of idx.*in CHECK TABLE");
# This test setup is extracted from bug56680.test:
# The flag innodb_change_buffering_debug is only available in debug builds.
# It instructs InnoDB to try to evict pages from the buffer pool when
# change buffering is possible, so that the change buffer will be used
# whenever possible.
SET @innodb_change_buffering_debug_orig = @@innodb_change_buffering_debug;
SET GLOBAL innodb_change_buffering_debug = 1;
# Turn off Unique Check to create corrupted index with dup key
SET UNIQUE_CHECKS=0;
CREATE DATABASE pad;
let $i=338;
while ($i)
{
--eval CREATE TABLE pad.t$i(a INT PRIMARY KEY)ENGINE=InnoDB STATS_PERSISTENT=0;
dec $i;
}
-- enable_query_log
set names utf8;
CREATE TABLE corrupt_bit_test_ā(
a INT AUTO_INCREMENT PRIMARY KEY,
b CHAR(100),
c INT,
z INT,
INDEX(b))
ENGINE=InnoDB STATS_PERSISTENT=0;
INSERT INTO corrupt_bit_test_ā VALUES(0,'x',1, 1);
# This is the first unique index we intend to corrupt
CREATE UNIQUE INDEX idxā ON corrupt_bit_test_ā(c, b);
# This is the second unique index we intend to corrupt
CREATE UNIQUE INDEX idxē ON corrupt_bit_test_ā(z, b);
SELECT * FROM corrupt_bit_test_ā;
select @@unique_checks;
select @@innodb_change_buffering_debug;
# Create enough rows for the table, so that the insert buffer will be
# used for modifying the secondary index page. There must be multiple
# index pages, because changes to the root page are never buffered.
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+1,z+1 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+10,z+10 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+20,z+20 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+50,z+50 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+100,z+100 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+200,z+200 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+400,z+400 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+800,z+800 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+1600,z+1600 FROM corrupt_bit_test_ā;
INSERT INTO corrupt_bit_test_ā SELECT 0,b,c+4000,z+4000 FROM corrupt_bit_test_ā;
select count(*) from corrupt_bit_test_ā;
CREATE INDEX idx3 ON corrupt_bit_test_ā(b, c);
# Create a dup key error on index "idxē" and "idxā" by inserting a dup value
INSERT INTO corrupt_bit_test_ā VALUES(13000,'x',1,1);
# creating an index should succeed even if other secondary indexes are corrupted
CREATE INDEX idx4 ON corrupt_bit_test_ā(b, z);
# Check table will find the unique indexes corrupted
# with dup key
check table corrupt_bit_test_ā;
# This selection intend to use the corrupted index. Expect to fail
-- error ER_INDEX_CORRUPT
select c from corrupt_bit_test_ā;
-- error ER_INDEX_CORRUPT
select z from corrupt_bit_test_ā;
show warnings;
# Since corrupted index is a secondary index, we only disable such
# index and allow other DML to proceed
insert into corrupt_bit_test_ā values (10001, "a", 20001, 20001);
# This does not use the corrupted index, expect to succeed
select * from corrupt_bit_test_ā use index(primary) where a = 10001;
# Some more DMLs
begin;
insert into corrupt_bit_test_ā values (10002, "a", 20002, 20002);
delete from corrupt_bit_test_ā where a = 10001;
insert into corrupt_bit_test_ā values (10001, "a", 20001, 20001);
rollback;
# Drop one corrupted index before reboot
drop index idxā on corrupt_bit_test_ā;
check table corrupt_bit_test_ā;
set names utf8;
-- error ER_INDEX_CORRUPT
select z from corrupt_bit_test_ā;
# Drop the corrupted index
drop index idxē on corrupt_bit_test_ā;
# Now select back to normal
select z from corrupt_bit_test_ā limit 10;
# Drop table
drop table corrupt_bit_test_ā;
DROP DATABASE pad;
SET GLOBAL innodb_change_buffering_debug = 0;
|
{
"pile_set_name": "Github"
}
|
package org.mitre.synthea.helpers;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.client.api.IRestfulClient;
import org.hl7.fhir.r4.model.IntegerType;
import org.hl7.fhir.r4.model.UriType;
import org.hl7.fhir.r4.model.ValueSet;
/**
* HAPI annotation client for invoking operations on a FHIR terminology service.
*/
public interface TerminologyClient extends IRestfulClient {
@Operation(type = ValueSet.class, name = "$expand")
ValueSet expand(@OperationParam(name = "url") UriType url,
@OperationParam(name = "count") IntegerType count,
@OperationParam(name = "offset") IntegerType offset);
}
|
{
"pile_set_name": "Github"
}
|
//
// GJCFCoreTextContentView.h
// GJCommonFoundation
//
// Created by ZYVincent QQ:1003081775 on 14-9-21.
// Copyright (c) 2014年 ZYProSoft. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "GJCFCoreTextKeywordAttributedStringStyle.h"
#import "GJCFCoreTextImageAttributedStringStyle.h"
#import "GJCFCoreTextCommonDefine.h"
#import "GJCFCoreTextImageScriptParser.h"
#import "GJCFCoreTextParagraphStyle.h"
#import "NSMutableAttributedString+GJCFCoreText.h"
#import "UIView+GJCFViewFrameUitil.h"
#define kGJCFCoreTextContentViewAdjustHeightNSCachePreFix @"kGJCFCoreTextContentViewAdjustHeightNSCachePreFix"
@class GJCFCoreTextContentView;
/* 记住block内的对象会被retain */
typedef void (^GJCFCoreTextContentViewTouchHanlder) (NSString *keyword,NSRange keywordRange);
/* 长按事件捕捉 */
typedef void (^GJCFCoreTextContentViewLongPressHanlder) (GJCFCoreTextContentView *textView, NSString *contentString);
/* 整体点击事件捕捉 */
typedef void (^GJCFCoreTextContentViewTapHanlder) (GJCFCoreTextContentView *textView);
@interface GJCFCoreTextContentView : UIView
//============= 支持类UILabel的属性 ============//
/**
* 设置字体
*/
@property (nonatomic,strong)UIFont *font;
/**
* 文本内容
*/
@property (nonatomic,copy)NSString *text;
/**
* 是否高亮
*/
@property (nonatomic,assign)BOOL highlighted;
/**
* 高亮文本颜色
*/
@property (nonatomic,strong)UIColor *highlightedTextColor;
/**
* 行高 1.0为基础进行scale
*/
@property (nonatomic,assign)CGFloat lineHeight;
/**
* 文本颜色
*/
@property (nonatomic,strong)UIColor *textColor;
/**
* 文本对齐形式
*/
@property (nonatomic,assign)NSTextAlignment alignment;
/**
* 是否多行模式
*/
@property (nonatomic,assign)NSInteger numberOfLines;
/**
* 换行模式
*/
@property (nonatomic,assign)NSLineBreakMode lineBreakMode;
/* 支持转成图片的标记 */
@property (nonatomic,readonly)NSArray *supportImageTagArray;
/* 多态字符串内容 */
@property (nonatomic,copy)NSAttributedString *contentAttributedString;
/* 长按的时候是否让全部文字显示选中效果 */
@property (nonatomic,assign)BOOL isLongPressShowSelectedState;
/* 当前是否全部选中状态 */
@property (nonatomic,assign)BOOL selected;
/* 选中点击时候的背景颜色效果 */
@property (nonatomic,strong)UIColor *selectedStateColor;
/* 用户设置一些自己的信息 */
@property (nonatomic,strong)NSDictionary *userInfo;
/* 省略号模式 */
@property (nonatomic,assign)BOOL isTailMode;
/**
* 该标签的基础宽度,设置之后,每次自适应的时候都以这个宽度为基础宽度自适应
* 如果不设置,默认使用 self.frame.width 作为基准
*/
@property (nonatomic,assign)CGFloat contentBaseWidth;
/**
* 该标签内容的基础高度,设置之后,每次自适应的时候都以这个高度为基础宽度自适应
* 如果不设置,默认使用 self.frame.height 作为基准
*/
@property (nonatomic,assign)CGFloat contentBaseHeight;
/**
* 内容的基础限定大小
*/
@property (nonatomic,assign)CGSize contentBaseSize;
//阴影颜色
@property (nonatomic,strong)UIColor *shadowColor;
//阴影大小
@property (nonatomic,assign)CGSize shadowOffset;
//阴影半径
@property (nonatomic,assign)CGFloat shadowBlurRadius;
/*
* 省略号单行模式,如果这个设置为YES,那么最终只会保留一行然后省略号
* 如果为NO,那么会计算当前view的frame下能显示多少文字,显示不了的
* 用省略号表示,默认是NO
*/
@property (nonatomic,assign)BOOL isOneLineTailMode;
/*
* 当前视图能够显示的可见字符范围
*/
@property (nonatomic,readonly)NSRange visiableStringRange;
/////////////////////////////////////////////// 公开接口 ////////////////////////////////////////////
/* 记录一个图片标记被插入的图片的真实字符串内容 */
- (void)appendImageInfo:(NSDictionary *)imageInfo;
/* 替换所有的图片信息成新的 */
- (void)replaceAllImageInfosWithArray:(NSArray *)newImageInfos;
/* 添加一个图片标记 */
- (void)appendImageTag:(NSString *)imageTagName;
/* 为某个特定的字符串设定响应事件 */
- (void)appenTouchObserverForKeyword:(NSString *)keyword withHanlder:(GJCFCoreTextContentViewTouchHanlder)handler;
///* 为某个特定的关键字设定圆角背景 */
//- (void)appendRoundCorner:(CGFloat)cornerRadius backgroundColor:(UIColor *)backColor forKeyword:(NSString *)keyword;
/* 计算内容高度 */
+ (CGFloat)contentHeightForAttributedString:(NSAttributedString *)attributedString forContentSize:(CGSize)contentSize;
/* 计算内容一行情况下的真实宽度 */
+ (CGFloat)contentWidthForAttributedString:(NSAttributedString *)attributedString forContentSize:(CGSize)contentSize;
/* 获取一个基于基础的Size的自适应大小 */
+ (CGSize)contentSuggestSizeWithAttributedString:(NSAttributedString *)attributedString forBaseContentSize:(CGSize)contentSize;
/* 获取一个最大行数下自适应的大小 */
+ (CGSize)contentSuggestSizeWithAttributedString:(NSAttributedString *)attributedString forBaseContentSize:(CGSize)contentSize maxNumberOfLine:(NSInteger)lineCount;
/* 设置一个外部可以监测coreText 长按事件的block */
- (void)setLongPressEventHandler:(GJCFCoreTextContentViewLongPressHanlder)longPressBlock;
/* 设置一个整体点击事件观察 */
- (void)setTapActionHandler:(GJCFCoreTextContentViewTapHanlder)tapBlock;
/* 自动根据内容调整大小 */
- (void)sizeToFit;
/* 清除关键字观察事件 */
- (void)clearKeywordTouchEventHanlder;
/* 替换图片的原始文字信息 */
- (NSString *)imageInfoOriginSourceString;
/**
* 最后一个字符的位置右下角的位置,或者右上角在整个view中的位置
*
* @param isCharTop YES 右上角 NO 右下角
*
* @return 位置
*/
- (CGPoint)lastCharPostion:(BOOL)isCharTop;
@end
|
{
"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.kafka.common.requests;
import org.apache.kafka.common.message.ApiVersionsResponseData;
import org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersionsResponseKeyCollection;
import org.apache.kafka.common.network.ClientInformation;
import org.apache.kafka.common.network.ListenerName;
import org.apache.kafka.common.network.Send;
import org.apache.kafka.common.protocol.ApiKeys;
import org.apache.kafka.common.protocol.Errors;
import org.apache.kafka.common.protocol.types.Struct;
import org.apache.kafka.common.security.auth.KafkaPrincipal;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.junit.Test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class RequestContextTest {
@Test
public void testSerdeUnsupportedApiVersionRequest() throws Exception {
int correlationId = 23423;
RequestHeader header = new RequestHeader(ApiKeys.API_VERSIONS, Short.MAX_VALUE, "", correlationId);
RequestContext context = new RequestContext(header, "0", InetAddress.getLocalHost(), KafkaPrincipal.ANONYMOUS,
new ListenerName("ssl"), SecurityProtocol.SASL_SSL, ClientInformation.EMPTY, false);
assertEquals(0, context.apiVersion());
// Write some garbage to the request buffer. This should be ignored since we will treat
// the unknown version type as v0 which has an empty request body.
ByteBuffer requestBuffer = ByteBuffer.allocate(8);
requestBuffer.putInt(3709234);
requestBuffer.putInt(29034);
requestBuffer.flip();
RequestAndSize requestAndSize = context.parseRequest(requestBuffer);
assertTrue(requestAndSize.request instanceof ApiVersionsRequest);
ApiVersionsRequest request = (ApiVersionsRequest) requestAndSize.request;
assertTrue(request.hasUnsupportedRequestVersion());
Send send = context.buildResponse(new ApiVersionsResponse(new ApiVersionsResponseData()
.setThrottleTimeMs(0)
.setErrorCode(Errors.UNSUPPORTED_VERSION.code())
.setApiKeys(new ApiVersionsResponseKeyCollection())));
ByteBufferChannel channel = new ByteBufferChannel(256);
send.writeTo(channel);
ByteBuffer responseBuffer = channel.buffer();
responseBuffer.flip();
responseBuffer.getInt(); // strip off the size
ResponseHeader responseHeader = ResponseHeader.parse(responseBuffer,
ApiKeys.API_VERSIONS.responseHeaderVersion(header.apiVersion()));
assertEquals(correlationId, responseHeader.correlationId());
Struct struct = ApiKeys.API_VERSIONS.parseResponse((short) 0, responseBuffer);
ApiVersionsResponse response = (ApiVersionsResponse)
AbstractResponse.parseResponse(ApiKeys.API_VERSIONS, struct, (short) 0);
assertEquals(Errors.UNSUPPORTED_VERSION.code(), response.data.errorCode());
assertTrue(response.data.apiKeys().isEmpty());
}
@Test
public void testInitialPrincipalName() throws UnknownHostException {
final String initialPrincipalName = "initial-principal";
RequestHeader header = new RequestHeader(ApiKeys.API_VERSIONS, Short.MAX_VALUE, "", 1, initialPrincipalName, null);
RequestContext context = new RequestContext(header, "0", InetAddress.getLocalHost(), KafkaPrincipal.ANONYMOUS,
new ListenerName("ssl"), SecurityProtocol.SASL_SSL, ClientInformation.EMPTY, false);
assertEquals(initialPrincipalName, context.initialPrincipalName());
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2014-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.serializers;
import java.util.ArrayList;
import java.util.List;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Kryo Serializer for {@link java.util.Arrays#asList(Object...)}.
*/
public final class ArraysAsListSerializer extends Serializer<List<?>> {
@Override
public void write(Kryo kryo, Output output, List<?> object) {
output.writeInt(object.size(), true);
for (Object elm : object) {
kryo.writeClassAndObject(output, elm);
}
}
@Override
public List<?> read(Kryo kryo, Input input, Class<List<?>> type) {
final int size = input.readInt(true);
List<Object> list = new ArrayList<>(size);
for (int i = 0; i < size; ++i) {
list.add(kryo.readClassAndObject(input));
}
return list;
}
}
|
{
"pile_set_name": "Github"
}
|
package org.assetloader.base
{
import org.assetloader.core.IParam;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertTrue;
import flash.system.LoaderContext;
public class ParamTest
{
protected var _param : Param;
protected var _id : String = "test-id";
protected var _value : LoaderContext = new LoaderContext();
[BeforeClass]
public static function runBeforeEntireSuite() : void
{
}
[AfterClass]
public static function runAfterEntireSuite() : void
{
}
[Before]
public function runBeforeEachTest() : void
{
_param = new Param(_id, _value);
}
[After]
public function runAfterEachTest() : void
{
_param = null;
}
[Test]
public function implementsIParam() : void
{
assertTrue("Param should implement IParam", _param is IParam);
}
[Test]
public function retainsId() : void
{
assertEquals("Param should retain id passed", _param.id, _id);
}
[Test]
public function retainsValue() : void
{
assertEquals("Param should retain value passed", _param.value, _value);
}
}
}
|
{
"pile_set_name": "Github"
}
|
import React from 'react';
import Switch from 'terra-switch';
const DisabledSwitch = () => (
<Switch
labelText="Label"
isDisabled
/>
);
export default DisabledSwitch;
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2018 Crown Copyright
*
* 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.
*/
import * as React from "react";
import { storiesOf } from "@storybook/react";
import useManageUsers from "./useManageUsers";
import Button from "components/Button";
import { loremIpsum } from "lorem-ipsum";
const TestHarness: React.FunctionComponent = () => {
const { users, createUser, deleteUser } = useManageUsers();
const onClickCreateUser = React.useCallback(() => {
createUser(loremIpsum({ count: 1, units: "words" }), false);
}, [createUser]);
return (
<div>
<Button onClick={onClickCreateUser}>Create User</Button>
<h2>Users</h2>
<ul>
{users.map((user) => (
<div key={user.uuid}>
<Button onClick={() => deleteUser(user.uuid)}>Delete</Button>
{JSON.stringify(user)}
</div>
))}
</ul>
</div>
);
};
storiesOf(
"Sections/Authorisation Manager/useManageUsers",
module,
).add("Sample 1", () => <TestHarness />);
|
{
"pile_set_name": "Github"
}
|
package com.soywiz.korge.render
import com.soywiz.kmem.*
import com.soywiz.korag.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.format.*
import com.soywiz.korio.*
import com.soywiz.korio.file.*
import com.soywiz.korio.lang.*
import com.soywiz.korma.geom.*
/**
* A [Texture] is a region (delimited by [left], [top], [right] and [bottom]) of a [Texture.Base].
* A [Texture.Base] wraps a [AG.Texture] but adds [width] and [height] information.
*/
class Texture(
val base: Base,
/** Left position of the region of the texture in pixels */
val left: Int = 0,
/** Top position of the region of the texture in pixels */
val top: Int = 0,
/** Right position of the region of the texture in pixels */
val right: Int = base.width,
/** Bottom position of the region of the texture in pixels */
val bottom: Int = base.height
) : Closeable {
/** Wether the texture is multiplied or not */
val premultiplied get() = base.premultiplied
/** Left position of the region of the texture in pixels */
val x = left
/** Top position of the region of the texture in pixels */
val y = top
/** Width of this texture region in pixels */
val width = right - left
/** Height of this texture region in pixels */
val height = bottom - top
/** Left coord of the texture region as a ratio (a value between 0 and 1) */
val x0: Float = (left).toFloat() / base.width.toFloat()
/** Right coord of the texture region as a ratio (a value between 0 and 1) */
val x1: Float = (right).toFloat() / base.width.toFloat()
/** Top coord of the texture region as a ratio (a value between 0 and 1) */
val y0: Float = (top).toFloat() / base.height.toFloat()
/** Bottom coord of the texture region as a ratio (a value between 0 and 1) */
val y1: Float = (bottom).toFloat() / base.height.toFloat()
/**
* Creates a slice of this texture, by [x], [y], [width] and [height].
*/
fun slice(x: Int, y: Int, width: Int, height: Int) = sliceBounds(x, y, x + width, y + height)
/**
* Createa a slice of this texture by [rect].
*/
fun slice(rect: Rectangle) = slice(rect.x.toInt(), rect.y.toInt(), rect.width.toInt(), rect.height.toInt())
/**
* Creates a slice of this texture by its bounds [left], [top], [right], [bottom].
*/
fun sliceBounds(left: Int, top: Int, right: Int, bottom: Int): Texture {
val tleft = (this.x + left).clamp(this.left, this.right)
val tright = (this.x + right).clamp(this.left, this.right)
val ttop = (this.y + top).clamp(this.top, this.bottom)
val tbottom = (this.y + bottom).clamp(this.top, this.bottom)
return Texture(base, tleft, ttop, tright, tbottom)
}
companion object {
/**
* Creates a [Texture] from a texture [agBase] and its wanted size [width], [height].
*/
operator fun invoke(agBase: AG.Texture, width: Int, height: Int): Texture =
Texture(Base(agBase, width, height), 0, 0, width, height)
}
/**
* Represents a full texture region wraping a [base] [AG.Texture] and specifying its [width] and [height]
*/
class Base(var base: AG.Texture?, var width: Int, var height: Int) : Closeable {
var version = -1
val premultiplied get() = base?.premultiplied == true
override fun close(): Unit {
base?.close()
base = null
}
fun update(bmp: Bitmap, mipmaps: Boolean = bmp.mipmaps) {
base?.upload(bmp, mipmaps)
}
}
/**
* Updates this texture from a [bmp] and optionally generates [mipmaps].
*/
fun update(bmp: Bitmap32, mipmaps: Boolean = false) {
base.update(bmp, mipmaps)
}
/**
* Closes the texture
*/
override fun close() = base.close()
override fun toString(): String = "Texture($base, (x=$x, y=$y, width=$width, height=$height))"
}
//suspend fun VfsFile.readTexture(ag: AG, imageFormats: ImageFormats, mipmaps: Boolean = true): Texture {
// //println("VfsFile.readTexture[1]")
// val tex = ag.createTexture()
// //println("VfsFile.readTexture[2]")
// val bmp = this.readBitmapOptimized(imageFormats)
// //val bmp = this.readBitmapNoNative()
// //println("VfsFile.readTexture[3]")
// val canHasMipmaps = bmp.width.isPowerOfTwo && bmp.height.isPowerOfTwo
// //println("VfsFile.readTexture[4]")
// tex.upload(bmp, mipmaps = canHasMipmaps && mipmaps)
// //println("VfsFile.readTexture[5]")
// return Texture(tex, bmp.width, bmp.height)
//}
|
{
"pile_set_name": "Github"
}
|
# create library from source files
DCMTK_ADD_LIBRARY(
dcmdsig dcsighlp dcsignat siautopr sibrsapr sicert sicertvf sicreapr
sidsa siecdsa simaccon simd5 sinullpr siprivat sipurpos siripemd sirsa
sisha1 sisprof sisrpr sisrvpr sitstamp sitypes sisha256 sisha384
sisha512 sitsfs)
DCMTK_TARGET_LINK_MODULES(dcmdsig ofstd dcmdata)
DCMTK_TARGET_LINK_LIBRARIES(dcmdsig ${OPENSSL_LIBS})
|
{
"pile_set_name": "Github"
}
|
-----BEGIN CERTIFICATE-----
MIIC4jCCAcygAwIBAgIUZbmAIMGfIwuZfn0vysY+RdkOAaQwCwYJKoZIhvcNAQEL
MCMxITAfBgNVBAMMGGNhLW5vLWtleVVzYWdlLWV4dGVuc2lvbjAiGA8yMDE0MTEy
NzAwMDAwMFoYDzIwMTcwMjA0MDAwMDAwWjAiMSAwHgYDVQQDDBdlZS1rZXlFbmNp
cGhlcm1lbnQtb25seTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALqI
UahEjhbWQf1utogGNhA9PBPZ6uQ1SrTs9WhXbCR7wcclqODYH72xnAabbhqG8mvi
r1p1a2pkcQh6pVqnRYf3HNUknAJ+zUP8HmnQOCApk6sgw0nk27lMwmtsDu0Vgg/x
fq1pGrHTAjqLKkHup3DgDw2N/WYLK7AkkqR9uYhheZCxV5A90jvF4LhIH6g304hD
7ycW2FW3ZlqqfgKQLzp7EIAGJMwcbJetlmFbt+KWEsB1MaMMkd20yvf8rR0l0wnv
uRcOp2jhs3svIm9p47SKlWEd7ibWJZ2rkQhONsscJAQsvxaLL+Xxj5kXMbiz/kkj
+nJRxDHVA6zaGAo17Y0CAwEAAaMPMA0wCwYDVR0PBAQDAgUgMAsGCSqGSIb3DQEB
CwOCAQEAuhFkBmuBtaMgUFnfX63pC8GC5WbO7hCx+n0xu8TjGPc0yc1KVXCHJhMJ
4FGzhmMUPU6RP1lNN2cLmMd5mkLArNaobcSa7A1Xfd2hZrHadKHxA3NV7fyi55Ws
oRnOAOt07EiKjfD5KYguCdakYR6XnhAIyBMoSZ9pDBBeefnPutO9WvSpvA0P4G6C
Cg6zNeeH3FIy8EzEjFDNfsrdYAgjHpFh2VH9z9WuxUplRHMSxaY+6JkHvWcTQy6T
7zTO2RjPLCgJFYY9J7Pu0CvM4Lv4W5YXJlIumsX9jHlOXryKpB8PmUQ5aQloLJ2w
TKUtIQm6m49ljnHvl3Yuha59uWxZPQ==
-----END CERTIFICATE-----
|
{
"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_67) on Mon Jul 20 11:24:05 PDT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Package com.fasterxml.jackson.dataformat.xml.ser (Jackson-dataformat-XML 2.6.0 API)</title>
<meta name="date" content="2015-07-20">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package com.fasterxml.jackson.dataformat.xml.ser (Jackson-dataformat-XML 2.6.0 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>Class</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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/dataformat/xml/ser/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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">
<h1 title="Uses of Package com.fasterxml.jackson.dataformat.xml.ser" class="title">Uses of Package<br>com.fasterxml.jackson.dataformat.xml.ser</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/package-summary.html">com.fasterxml.jackson.dataformat.xml.ser</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.dataformat.xml">com.fasterxml.jackson.dataformat.xml</a></td>
<td class="colLast">
<div class="block">Package that contains XML-based backends which can serialize POJOs
to and deserialize from XML, using Stax XML parsers and generators
for XML processing and mostly standard Jackson data binding otherwise.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.dataformat.xml.ser">com.fasterxml.jackson.dataformat.xml.ser</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.dataformat.xml">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/package-summary.html">com.fasterxml.jackson.dataformat.xml.ser</a> used by <a href="../../../../../../com/fasterxml/jackson/dataformat/xml/package-summary.html">com.fasterxml.jackson.dataformat.xml</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/class-use/ToXmlGenerator.html#com.fasterxml.jackson.dataformat.xml">ToXmlGenerator</a>
<div class="block"><code>JsonGenerator</code> that outputs JAXB-style XML output instead of JSON content.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/class-use/ToXmlGenerator.Feature.html#com.fasterxml.jackson.dataformat.xml">ToXmlGenerator.Feature</a>
<div class="block">Enumeration that defines all togglable extra XML-specific features</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.dataformat.xml.ser">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/package-summary.html">com.fasterxml.jackson.dataformat.xml.ser</a> used by <a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/package-summary.html">com.fasterxml.jackson.dataformat.xml.ser</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/class-use/ToXmlGenerator.html#com.fasterxml.jackson.dataformat.xml.ser">ToXmlGenerator</a>
<div class="block"><code>JsonGenerator</code> that outputs JAXB-style XML output instead of JSON content.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/class-use/ToXmlGenerator.Feature.html#com.fasterxml.jackson.dataformat.xml.ser">ToXmlGenerator.Feature</a>
<div class="block">Enumeration that defines all togglable extra XML-specific features</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/class-use/UnwrappingXmlBeanSerializer.html#com.fasterxml.jackson.dataformat.xml.ser">UnwrappingXmlBeanSerializer</a>
<div class="block">Copy of <code>UnwrappingBeanSerializer</code> required to extend
<a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/XmlBeanSerializerBase.html" title="class in com.fasterxml.jackson.dataformat.xml.ser"><code>XmlBeanSerializerBase</code></a> for XML-specific handling.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/class-use/XmlBeanSerializerBase.html#com.fasterxml.jackson.dataformat.xml.ser">XmlBeanSerializerBase</a>
<div class="block">Specific sub-class of <code>BeanSerializerBase</code> needed to take care
of some xml-specific aspects, such as distinction between attributes
and elements.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/ser/class-use/XmlSerializerProvider.html#com.fasterxml.jackson.dataformat.xml.ser">XmlSerializerProvider</a>
<div class="block">We need to override some parts of
<code>SerializerProvider</code>
implementation to handle oddities of XML output, like "extra" root element.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</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>Class</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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/dataformat/xml/ser/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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>Copyright © 2014–2015 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
2
23
2
5
2
4
OK
4
OK
10
1
()
10
|
{
"pile_set_name": "Github"
}
|
IsBoldStyle false
IsItalicStyle true
PreferOS/2TypoMetrics true
IsOS/2WidthWeigthSlopeOnly false
IsOS/2OBLIQUE true
|
{
"pile_set_name": "Github"
}
|
# 配置慢sql,以及日志输出
druid_filters=stat,wall,log4j
driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/druid_spring_config?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=1234
#初始化连接大小
jdbc_init=50
#连接池最小空闲
jdbc_minIdle=20
#获取连接最大等待时间 单位为毫秒
jdbc_maxActive=60000
|
{
"pile_set_name": "Github"
}
|
#include "cudaWrapper.h"
CCudaWrapper::CCudaWrapper()
{
}
CCudaWrapper::~CCudaWrapper()
{
}
bool CCudaWrapper::warmUpGPU()
{
cudaError_t err = ::cudaSuccess;
err = cudaSetDevice(0);
if(err != ::cudaSuccess)return false;
err = cudaWarmUpGPU();
if(err != ::cudaSuccess)return false;
this->threads = getNumberOfAvailableThreads();
return true;
}
int CCudaWrapper::getNumberOfAvailableThreads()
{
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop,0);
int threads = 0;
if(prop.major == 2)
{
threads=prop.maxThreadsPerBlock/2;
}else if(prop.major > 2)
{
threads=prop.maxThreadsPerBlock;
}else
{
return 0;
}
return threads;
}
void CCudaWrapper::coutMemoryStatus()
{
size_t free_byte ;
size_t total_byte ;
cudaError_t err = cudaMemGetInfo( &free_byte, &total_byte ) ;
if(err != ::cudaSuccess)
{
std::cout << "Error: cudaMemGetInfo fails: " << cudaGetErrorString(err) << std::endl;
return;
}
double free_db = (double)free_byte ;
double total_db = (double)total_byte ;
double used_db = total_db - free_db ;
std::cout << "GPU memory usage: used = " <<
used_db/1024.0/1024.0 <<
"(MB), free = " <<
free_db/1024.0/1024.0 <<
"(MB), total = " <<
total_db/1024.0/1024.0 <<
"(MB)" << std::endl;
}
bool CCudaWrapper::compute_projections( pcl::PointCloud<lidar_pointcloud::PointXYZIRNL> &first_point_cloud,
pcl::PointCloud<lidar_pointcloud::PointXYZIRNL> &second_point_cloud,
float projections_search_radius,
float bounding_box_extension,
int max_number_considered_in_INNER_bucket,
int max_number_considered_in_OUTER_bucket,
pcl::PointCloud<lidar_pointcloud::PointProjection> &projections )
{
cudaError_t err = ::cudaSuccess;
std::cout << "Memory before cudaMalloc" << std::endl;
coutMemoryStatus();
gridParameters rgd_params;
lidar_pointcloud::PointXYZIRNL *d_first_point_cloud = NULL;
lidar_pointcloud::PointXYZIRNL *d_second_point_cloud = NULL;
lidar_pointcloud::PointProjection *d_projections = NULL;
hashElement* d_hashTable = NULL;
bucket* d_buckets = NULL;
err = cudaMalloc((void**)&d_first_point_cloud, first_point_cloud.points.size()*sizeof(lidar_pointcloud::PointXYZIRNL) );
if(err != ::cudaSuccess)return false;
err = cudaMemcpy(d_first_point_cloud, first_point_cloud.points.data(), first_point_cloud.points.size()*sizeof(lidar_pointcloud::PointXYZIRNL), cudaMemcpyHostToDevice);
if(err != ::cudaSuccess)return false;
err = cudaMalloc((void**)&d_second_point_cloud, second_point_cloud.points.size()*sizeof(lidar_pointcloud::PointXYZIRNL) );
if(err != ::cudaSuccess)return false;
err = cudaMemcpy(d_second_point_cloud, second_point_cloud.points.data(), second_point_cloud.points.size()*sizeof(lidar_pointcloud::PointXYZIRNL), cudaMemcpyHostToDevice);
if(err != ::cudaSuccess)return false;
err = cudaMalloc((void**)&d_hashTable, first_point_cloud.points.size()*sizeof(hashElement));
if(err != ::cudaSuccess)return false;
err = cudaCalculateGridParams(
d_first_point_cloud,
first_point_cloud.points.size(),
projections_search_radius,
projections_search_radius,
projections_search_radius,
bounding_box_extension,
rgd_params);
if(err != ::cudaSuccess)return false;
std::cout << "regular grid parameters for projections:" << std::endl;
std::cout << "bounding_box_min_X: " << rgd_params.bounding_box_min_X << std::endl;
std::cout << "bounding_box_min_Y: " << rgd_params.bounding_box_min_Y << std::endl;
std::cout << "bounding_box_min_Z: " << rgd_params.bounding_box_min_Z << std::endl;
std::cout << "bounding_box_max_X: " << rgd_params.bounding_box_max_X << std::endl;
std::cout << "bounding_box_max_Y: " << rgd_params.bounding_box_max_Y << std::endl;
std::cout << "bounding_box_max_Z: " << rgd_params.bounding_box_max_Z << std::endl;
std::cout << "number_of_buckets_X: " << rgd_params.number_of_buckets_X << std::endl;
std::cout << "number_of_buckets_Y: " << rgd_params.number_of_buckets_Y << std::endl;
std::cout << "number_of_buckets_Z: " << rgd_params.number_of_buckets_Z << std::endl;
std::cout << "resolution_X: " << rgd_params.resolution_X << std::endl;
std::cout << "resolution_Y: " << rgd_params.resolution_Y << std::endl;
std::cout << "resolution_Z: " << rgd_params.resolution_Z << std::endl;
std::cout << "number_of_buckets: " << rgd_params.number_of_buckets << std::endl;
err = cudaMalloc((void**)&d_buckets, rgd_params.number_of_buckets*sizeof(bucket));
if(err != ::cudaSuccess)return false;
err = cudaCalculateGrid(threads, d_first_point_cloud, d_buckets, d_hashTable, first_point_cloud.points.size(), rgd_params);
if(err != ::cudaSuccess)return false;
err = cudaMalloc((void**)&d_projections, second_point_cloud.points.size()*sizeof(lidar_pointcloud::PointProjection) );
if(err != ::cudaSuccess)return false;
std::cout << "Memory status after cudaMalloc projections" << std::endl;
coutMemoryStatus();
err = cudaCalculateProjections(
this->threads,
d_first_point_cloud,
first_point_cloud.points.size(),
d_second_point_cloud,
second_point_cloud.points.size(),
d_hashTable,
d_buckets,
rgd_params,
max_number_considered_in_INNER_bucket,
max_number_considered_in_OUTER_bucket,
projections_search_radius,
d_projections);
if(err != ::cudaSuccess)return false;
err = cudaMemcpy(projections.points.data(), d_projections, second_point_cloud.points.size()*sizeof(lidar_pointcloud::PointProjection),cudaMemcpyDeviceToHost);
if(err != ::cudaSuccess){return false;}
err = cudaFree(d_first_point_cloud); d_first_point_cloud = NULL;
if(err != ::cudaSuccess)return false;
err = cudaFree(d_second_point_cloud); d_second_point_cloud = NULL;
if(err != ::cudaSuccess)return false;
err = cudaFree(d_hashTable); d_hashTable = NULL;
if(err != ::cudaSuccess)return false;
err = cudaFree(d_buckets); d_buckets = NULL;
if(err != ::cudaSuccess)return false;
err = cudaFree(d_projections); d_projections = NULL;
if(err != ::cudaSuccess)return false;
std::cout << "After cudaFree" << std::endl;
coutMemoryStatus();
return true;
}
void CCudaWrapper::Matrix4ToEuler(const double *alignxf, double *rPosTheta, double *rPos)
{
double _trX, _trY;
if(alignxf[0] > 0.0)
{
rPosTheta[1] = asin(alignxf[8]);
}
else
{
rPosTheta[1] = M_PI - asin(alignxf[8]);
}
double C = cos( rPosTheta[1] );
if ( fabs( C ) > 0.005 )
{ // Gimball lock?
_trX = alignxf[10] / C; // No, so get X-axis angle
_trY = -alignxf[9] / C;
rPosTheta[0] = atan2( _trY, _trX );
_trX = alignxf[0] / C; // Get Z-axis angle
_trY = -alignxf[4] / C;
rPosTheta[2] = atan2( _trY, _trX );
}
else
{ // Gimball lock has occurred
rPosTheta[0] = 0.0; // Set X-axis angle to zero
_trX = alignxf[5]; //1 // And calculate Z-axis angle
_trY = alignxf[1]; //2
rPosTheta[2] = atan2( _trY, _trX );
}
rPosTheta[0] = rPosTheta[0];
rPosTheta[1] = rPosTheta[1];
rPosTheta[2] = rPosTheta[2];
if (rPos != 0)
{
rPos[0] = alignxf[12];
rPos[1] = alignxf[13];
rPos[2] = alignxf[14];
}
}
void CCudaWrapper::Matrix4ToEuler(Eigen::Affine3f m, Eigen::Vector3f &omfika, Eigen::Vector3f &xyz)
{
double _trX, _trY;
if(m(0,0) > 0.0)
{
omfika.y() = asin(m(0,2));
}
else
{
omfika.y() = M_PI - asin(m(0,2));
}
double C = cos( omfika.y() );
if ( fabs( C ) > 0.005 )
{ // Gimball lock?
_trX = m(2,2) / C; // No, so get X-axis angle
_trY = -m(1,2) / C;
omfika.x() = atan2( _trY, _trX );
_trX = m(0,0) / C; // Get Z-axis angle
_trY = -m(0,1) / C;
omfika.z()= atan2( _trY, _trX );
}
else
{ // Gimball lock has occurred
omfika.x() = 0.0; // Set X-axis angle to zero
_trX = m(1,1); //1 // And calculate Z-axis angle
_trY = m(1,0); //2
omfika.z() = atan2( _trY, _trX );
}
xyz.x() = m(0,3);
xyz.y() = m(1,3);
xyz.z() = m(2,3);
}
void CCudaWrapper::EulerToMatrix(Eigen::Vector3f omfika, Eigen::Vector3f xyz, Eigen::Affine3f &m)
{
Eigen::Affine3f mR;
mR = Eigen::AngleAxisf(omfika.x(), Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(omfika.y(), Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(omfika.z(), Eigen::Vector3f::UnitZ());
Eigen::Affine3f mT(Eigen::Translation3f(xyz.x(), xyz.y(), xyz.z()));
m = mT * mR;
}
bool CCudaWrapper::registerLS3D(observations_LS3D_t &obs)
{
cudaError_t errCUDA = ::cudaSuccess;
CCUDA_AX_B_SolverWrapper::Solver_Method solver_method = CCUDA_AX_B_SolverWrapper::chol;
double PforGround = 1.0;
double PforObstacles = 1.0;
double x[7];
pcl::PointCloud<lidar_pointcloud::PointProjection> projections_confirmed;
for(size_t i = 0 ; i < obs.projections.size(); i++)
{
if(obs.projections[i].isProjection == 1)projections_confirmed.push_back(obs.projections[i]);
}
double *d_A = NULL;
errCUDA = cudaMalloc((void**)&d_A, projections_confirmed.size()* 7 *sizeof(double));
if(errCUDA != ::cudaSuccess){return false;}
double *d_P = NULL;
errCUDA = cudaMalloc((void**)&d_P, projections_confirmed.size() *sizeof(double));
if(errCUDA != ::cudaSuccess){return false;}
double *d_l=NULL;
errCUDA = cudaMalloc((void**)&d_l, projections_confirmed.size() *sizeof(double));
if(errCUDA != ::cudaSuccess){return false;}
lidar_pointcloud::PointProjection *d_projections; d_projections = NULL;
errCUDA = cudaMalloc((void**)&d_projections, projections_confirmed.size()*sizeof(lidar_pointcloud::PointProjection) );
if(errCUDA != ::cudaSuccess)return false;
errCUDA = cudaMemcpy(d_projections, projections_confirmed.points.data(), projections_confirmed.size()*sizeof(lidar_pointcloud::PointProjection), cudaMemcpyHostToDevice);
if(errCUDA != ::cudaSuccess)return false;
errCUDA = fill_A_l_cuda(threads/2, d_A, obs.tx, obs.ty, obs.tz, 1.0, obs.om, obs.fi, obs.ka, d_projections, projections_confirmed.size(),
d_P, PforGround, PforObstacles, d_l);
if(errCUDA != ::cudaSuccess){return false;}
CCUDA_AX_B_SolverWrapper * wr = new CCUDA_AX_B_SolverWrapper(false, 0);
CCUDA_AX_B_SolverWrapper::CCUDA_AX_B_SolverWrapper_error errAXB =
wr->Solve_ATPA_ATPl_x_data_on_GPU(this->threads, d_A, d_P, d_l, x, 7, projections_confirmed.size(), solver_method);
if(errAXB!=CCUDA_AX_B_SolverWrapper::success)
{
std::cout << "problem with solving Ax=B" << std::endl;
return false;
}
delete wr;
errCUDA = cudaFree(d_projections); d_projections = 0;
if(errCUDA != ::cudaSuccess){return false;}
std::cout << "Ax=B solution:" << std::endl;
for(int i = 0 ; i < 7; i++)
{
std::cout << "x[" << i <<"]: " << x[i] << std::endl;
}
errCUDA = cudaFree(d_A); d_A = 0;
if(errCUDA != ::cudaSuccess){return false;}
errCUDA = cudaFree(d_P); d_P = 0;
if(errCUDA != ::cudaSuccess){return false;}
errCUDA = cudaFree(d_l); d_l = 0;
if(errCUDA != ::cudaSuccess){return false;}
obs.tx -= x[0];
obs.ty -= x[1];
obs.tz -= x[2];
obs.om -= x[4];
obs.fi -= x[5];
obs.ka -= x[6];
return true;
}
|
{
"pile_set_name": "Github"
}
|
var fs = require('fs')
var polyfills = require('./polyfills.js')
var legacy = require('./legacy-streams.js')
var clone = require('./clone.js')
var queue = []
var util = require('util')
function noop () {}
var debug = noop
if (util.debuglog)
debug = util.debuglog('gfs4')
else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
debug = function() {
var m = util.format.apply(util, arguments)
m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
console.error(m)
}
if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
process.on('exit', function() {
debug(queue)
require('assert').equal(queue.length, 0)
})
}
module.exports = patch(clone(fs))
if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
module.exports = patch(fs)
fs.__patched = true;
}
// Always patch fs.close/closeSync, because we want to
// retry() whenever a close happens *anywhere* in the program.
// This is essential when multiple graceful-fs instances are
// in play at the same time.
module.exports.close = (function (fs$close) { return function (fd, cb) {
return fs$close.call(fs, fd, function (err) {
if (!err)
retry()
if (typeof cb === 'function')
cb.apply(this, arguments)
})
}})(fs.close)
module.exports.closeSync = (function (fs$closeSync) { return function (fd) {
// Note that graceful-fs also retries when fs.closeSync() fails.
// Looks like a bug to me, although it's probably a harmless one.
var rval = fs$closeSync.apply(fs, arguments)
retry()
return rval
}})(fs.closeSync)
// Only patch fs once, otherwise we'll run into a memory leak if
// graceful-fs is loaded multiple times, such as in test environments that
// reset the loaded modules between tests.
// We look for the string `graceful-fs` from the comment above. This
// way we are not adding any extra properties and it will detect if older
// versions of graceful-fs are installed.
if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) {
fs.closeSync = module.exports.closeSync;
fs.close = module.exports.close;
}
function patch (fs) {
// Everything that references the open() function needs to be in here
polyfills(fs)
fs.gracefulify = patch
fs.FileReadStream = ReadStream; // Legacy name.
fs.FileWriteStream = WriteStream; // Legacy name.
fs.createReadStream = createReadStream
fs.createWriteStream = createWriteStream
var fs$readFile = fs.readFile
fs.readFile = readFile
function readFile (path, options, cb) {
if (typeof options === 'function')
cb = options, options = null
return go$readFile(path, options, cb)
function go$readFile (path, options, cb) {
return fs$readFile(path, options, function (err) {
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
enqueue([go$readFile, [path, options, cb]])
else {
if (typeof cb === 'function')
cb.apply(this, arguments)
retry()
}
})
}
}
var fs$writeFile = fs.writeFile
fs.writeFile = writeFile
function writeFile (path, data, options, cb) {
if (typeof options === 'function')
cb = options, options = null
return go$writeFile(path, data, options, cb)
function go$writeFile (path, data, options, cb) {
return fs$writeFile(path, data, options, function (err) {
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
enqueue([go$writeFile, [path, data, options, cb]])
else {
if (typeof cb === 'function')
cb.apply(this, arguments)
retry()
}
})
}
}
var fs$appendFile = fs.appendFile
if (fs$appendFile)
fs.appendFile = appendFile
function appendFile (path, data, options, cb) {
if (typeof options === 'function')
cb = options, options = null
return go$appendFile(path, data, options, cb)
function go$appendFile (path, data, options, cb) {
return fs$appendFile(path, data, options, function (err) {
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
enqueue([go$appendFile, [path, data, options, cb]])
else {
if (typeof cb === 'function')
cb.apply(this, arguments)
retry()
}
})
}
}
var fs$readdir = fs.readdir
fs.readdir = readdir
function readdir (path, options, cb) {
var args = [path]
if (typeof options !== 'function') {
args.push(options)
} else {
cb = options
}
args.push(go$readdir$cb)
return go$readdir(args)
function go$readdir$cb (err, files) {
if (files && files.sort)
files.sort()
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
enqueue([go$readdir, [args]])
else {
if (typeof cb === 'function')
cb.apply(this, arguments)
retry()
}
}
}
function go$readdir (args) {
return fs$readdir.apply(fs, args)
}
if (process.version.substr(0, 4) === 'v0.8') {
var legStreams = legacy(fs)
ReadStream = legStreams.ReadStream
WriteStream = legStreams.WriteStream
}
var fs$ReadStream = fs.ReadStream
if (fs$ReadStream) {
ReadStream.prototype = Object.create(fs$ReadStream.prototype)
ReadStream.prototype.open = ReadStream$open
}
var fs$WriteStream = fs.WriteStream
if (fs$WriteStream) {
WriteStream.prototype = Object.create(fs$WriteStream.prototype)
WriteStream.prototype.open = WriteStream$open
}
fs.ReadStream = ReadStream
fs.WriteStream = WriteStream
function ReadStream (path, options) {
if (this instanceof ReadStream)
return fs$ReadStream.apply(this, arguments), this
else
return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
}
function ReadStream$open () {
var that = this
open(that.path, that.flags, that.mode, function (err, fd) {
if (err) {
if (that.autoClose)
that.destroy()
that.emit('error', err)
} else {
that.fd = fd
that.emit('open', fd)
that.read()
}
})
}
function WriteStream (path, options) {
if (this instanceof WriteStream)
return fs$WriteStream.apply(this, arguments), this
else
return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
}
function WriteStream$open () {
var that = this
open(that.path, that.flags, that.mode, function (err, fd) {
if (err) {
that.destroy()
that.emit('error', err)
} else {
that.fd = fd
that.emit('open', fd)
}
})
}
function createReadStream (path, options) {
return new ReadStream(path, options)
}
function createWriteStream (path, options) {
return new WriteStream(path, options)
}
var fs$open = fs.open
fs.open = open
function open (path, flags, mode, cb) {
if (typeof mode === 'function')
cb = mode, mode = null
return go$open(path, flags, mode, cb)
function go$open (path, flags, mode, cb) {
return fs$open(path, flags, mode, function (err, fd) {
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
enqueue([go$open, [path, flags, mode, cb]])
else {
if (typeof cb === 'function')
cb.apply(this, arguments)
retry()
}
})
}
}
return fs
}
function enqueue (elem) {
debug('ENQUEUE', elem[0].name, elem[1])
queue.push(elem)
}
function retry () {
var elem = queue.shift()
if (elem) {
debug('RETRY', elem[0].name, elem[1])
elem[0].apply(null, elem[1])
}
}
|
{
"pile_set_name": "Github"
}
|
"""HTTP cookie handling for web clients.
This module originally developed from my port of Gisle Aas' Perl module
HTTP::Cookies, from the libwww-perl library.
Docstrings, comments and debug strings in this code refer to the
attributes of the HTTP cookie system as cookie-attributes, to distinguish
them clearly from Python attributes.
CookieJar____
/ \ \
FileCookieJar \ \
/ | \ \ \
MozillaCookieJar | LWPCookieJar \ \
| | \
| ---MSIEBase | \
| / | | \
| / MSIEDBCookieJar BSDDBCookieJar
|/
MSIECookieJar
Comments to John J Lee <jjl@pobox.com>.
Copyright 2002-2006 John J Lee <jjl@pobox.com>
Copyright 1997-1999 Gisle Aas (original libwww-perl code)
Copyright 2002-2003 Johnny Lee (original MSIE Perl code)
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses (see the file
COPYING.txt included with the distribution).
"""
import sys, re, copy, time, struct, urllib, types, logging
try:
import threading
_threading = threading; del threading
except ImportError:
import dummy_threading
_threading = dummy_threading; del dummy_threading
import httplib # only for the default HTTP port
MISSING_FILENAME_TEXT = ("a filename was not supplied (nor was the CookieJar "
"instance initialised with one)")
DEFAULT_HTTP_PORT = str(httplib.HTTP_PORT)
from _headersutil import split_header_words, parse_ns_headers
from _util import isstringlike
import _rfc3986
debug = logging.getLogger("mechanize.cookies").debug
def reraise_unmasked_exceptions(unmasked=()):
# There are a few catch-all except: statements in this module, for
# catching input that's bad in unexpected ways.
# This function re-raises some exceptions we don't want to trap.
import mechanize, warnings
if not mechanize.USE_BARE_EXCEPT:
raise
unmasked = unmasked + (KeyboardInterrupt, SystemExit, MemoryError)
etype = sys.exc_info()[0]
if issubclass(etype, unmasked):
raise
# swallowed an exception
import traceback, StringIO
f = StringIO.StringIO()
traceback.print_exc(None, f)
msg = f.getvalue()
warnings.warn("mechanize bug!\n%s" % msg, stacklevel=2)
IPV4_RE = re.compile(r"\.\d+$")
def is_HDN(text):
"""Return True if text is a host domain name."""
# XXX
# This may well be wrong. Which RFC is HDN defined in, if any (for
# the purposes of RFC 2965)?
# For the current implementation, what about IPv6? Remember to look
# at other uses of IPV4_RE also, if change this.
return not (IPV4_RE.search(text) or
text == "" or
text[0] == "." or text[-1] == ".")
def domain_match(A, B):
"""Return True if domain A domain-matches domain B, according to RFC 2965.
A and B may be host domain names or IP addresses.
RFC 2965, section 1:
Host names can be specified either as an IP address or a HDN string.
Sometimes we compare one host name with another. (Such comparisons SHALL
be case-insensitive.) Host A's name domain-matches host B's if
* their host name strings string-compare equal; or
* A is a HDN string and has the form NB, where N is a non-empty
name string, B has the form .B', and B' is a HDN string. (So,
x.y.com domain-matches .Y.com but not Y.com.)
Note that domain-match is not a commutative operation: a.b.c.com
domain-matches .c.com, but not the reverse.
"""
# Note that, if A or B are IP addresses, the only relevant part of the
# definition of the domain-match algorithm is the direct string-compare.
A = A.lower()
B = B.lower()
if A == B:
return True
if not is_HDN(A):
return False
i = A.rfind(B)
has_form_nb = not (i == -1 or i == 0)
return (
has_form_nb and
B.startswith(".") and
is_HDN(B[1:])
)
def liberal_is_HDN(text):
"""Return True if text is a sort-of-like a host domain name.
For accepting/blocking domains.
"""
return not IPV4_RE.search(text)
def user_domain_match(A, B):
"""For blocking/accepting domains.
A and B may be host domain names or IP addresses.
"""
A = A.lower()
B = B.lower()
if not (liberal_is_HDN(A) and liberal_is_HDN(B)):
if A == B:
# equal IP addresses
return True
return False
initial_dot = B.startswith(".")
if initial_dot and A.endswith(B):
return True
if not initial_dot and A == B:
return True
return False
cut_port_re = re.compile(r":\d+$")
def request_host(request):
"""Return request-host, as defined by RFC 2965.
Variation from RFC: returned value is lowercased, for convenient
comparison.
"""
url = request.get_full_url()
host = _rfc3986.urlsplit(url)[1]
if host is None:
host = request.get_header("Host", "")
# remove port, if present
host = cut_port_re.sub("", host, 1)
return host.lower()
def eff_request_host(request):
"""Return a tuple (request-host, effective request-host name).
As defined by RFC 2965, except both are lowercased.
"""
erhn = req_host = request_host(request)
if req_host.find(".") == -1 and not IPV4_RE.search(req_host):
erhn = req_host + ".local"
return req_host, erhn
def request_path(request):
"""request-URI, as defined by RFC 2965."""
url = request.get_full_url()
path, query, frag = _rfc3986.urlsplit(url)[2:]
path = escape_path(path)
req_path = _rfc3986.urlunsplit((None, None, path, query, frag))
if not req_path.startswith("/"):
req_path = "/"+req_path
return req_path
def request_port(request):
host = request.get_host()
i = host.find(':')
if i >= 0:
port = host[i+1:]
try:
int(port)
except ValueError:
debug("nonnumeric port: '%s'", port)
return None
else:
port = DEFAULT_HTTP_PORT
return port
# Characters in addition to A-Z, a-z, 0-9, '_', '.', and '-' that don't
# need to be escaped to form a valid HTTP URL (RFCs 2396 and 1738).
HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()"
ESCAPED_CHAR_RE = re.compile(r"%([0-9a-fA-F][0-9a-fA-F])")
def uppercase_escaped_char(match):
return "%%%s" % match.group(1).upper()
def escape_path(path):
"""Escape any invalid characters in HTTP URL, and uppercase all escapes."""
# There's no knowing what character encoding was used to create URLs
# containing %-escapes, but since we have to pick one to escape invalid
# path characters, we pick UTF-8, as recommended in the HTML 4.0
# specification:
# http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1
# And here, kind of: draft-fielding-uri-rfc2396bis-03
# (And in draft IRI specification: draft-duerst-iri-05)
# (And here, for new URI schemes: RFC 2718)
if isinstance(path, types.UnicodeType):
path = path.encode("utf-8")
path = urllib.quote(path, HTTP_PATH_SAFE)
path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)
return path
def reach(h):
"""Return reach of host h, as defined by RFC 2965, section 1.
The reach R of a host name H is defined as follows:
* If
- H is the host domain name of a host; and,
- H has the form A.B; and
- A has no embedded (that is, interior) dots; and
- B has at least one embedded dot, or B is the string "local".
then the reach of H is .B.
* Otherwise, the reach of H is H.
>>> reach("www.acme.com")
'.acme.com'
>>> reach("acme.com")
'acme.com'
>>> reach("acme.local")
'.local'
"""
i = h.find(".")
if i >= 0:
#a = h[:i] # this line is only here to show what a is
b = h[i+1:]
i = b.find(".")
if is_HDN(h) and (i >= 0 or b == "local"):
return "."+b
return h
def is_third_party(request):
"""
RFC 2965, section 3.3.6:
An unverifiable transaction is to a third-party host if its request-
host U does not domain-match the reach R of the request-host O in the
origin transaction.
"""
req_host = request_host(request)
# the origin request's request-host was stuffed into request by
# _urllib2_support.AbstractHTTPHandler
return not domain_match(req_host, reach(request.origin_req_host))
class Cookie:
"""HTTP Cookie.
This class represents both Netscape and RFC 2965 cookies.
This is deliberately a very simple class. It just holds attributes. It's
possible to construct Cookie instances that don't comply with the cookie
standards. CookieJar.make_cookies is the factory function for Cookie
objects -- it deals with cookie parsing, supplying defaults, and
normalising to the representation used in this class. CookiePolicy is
responsible for checking them to see whether they should be accepted from
and returned to the server.
version: integer;
name: string;
value: string (may be None);
port: string; None indicates no attribute was supplied (eg. "Port", rather
than eg. "Port=80"); otherwise, a port string (eg. "80") or a port list
string (eg. "80,8080")
port_specified: boolean; true if a value was supplied with the Port
cookie-attribute
domain: string;
domain_specified: boolean; true if Domain was explicitly set
domain_initial_dot: boolean; true if Domain as set in HTTP header by server
started with a dot (yes, this really is necessary!)
path: string;
path_specified: boolean; true if Path was explicitly set
secure: boolean; true if should only be returned over secure connection
expires: integer; seconds since epoch (RFC 2965 cookies should calculate
this value from the Max-Age attribute)
discard: boolean, true if this is a session cookie; (if no expires value,
this should be true)
comment: string;
comment_url: string;
rfc2109: boolean; true if cookie arrived in a Set-Cookie: (not
Set-Cookie2:) header, but had a version cookie-attribute of 1
rest: mapping of other cookie-attributes
Note that the port may be present in the headers, but unspecified ("Port"
rather than"Port=80", for example); if this is the case, port is None.
"""
def __init__(self, version, name, value,
port, port_specified,
domain, domain_specified, domain_initial_dot,
path, path_specified,
secure,
expires,
discard,
comment,
comment_url,
rest,
rfc2109=False,
):
if version is not None: version = int(version)
if expires is not None: expires = int(expires)
if port is None and port_specified is True:
raise ValueError("if port is None, port_specified must be false")
self.version = version
self.name = name
self.value = value
self.port = port
self.port_specified = port_specified
# normalise case, as per RFC 2965 section 3.3.3
self.domain = domain.lower()
self.domain_specified = domain_specified
# Sigh. We need to know whether the domain given in the
# cookie-attribute had an initial dot, in order to follow RFC 2965
# (as clarified in draft errata). Needed for the returned $Domain
# value.
self.domain_initial_dot = domain_initial_dot
self.path = path
self.path_specified = path_specified
self.secure = secure
self.expires = expires
self.discard = discard
self.comment = comment
self.comment_url = comment_url
self.rfc2109 = rfc2109
self._rest = copy.copy(rest)
def has_nonstandard_attr(self, name):
return self._rest.has_key(name)
def get_nonstandard_attr(self, name, default=None):
return self._rest.get(name, default)
def set_nonstandard_attr(self, name, value):
self._rest[name] = value
def nonstandard_attr_keys(self):
return self._rest.keys()
def is_expired(self, now=None):
if now is None: now = time.time()
return (self.expires is not None) and (self.expires <= now)
def __str__(self):
if self.port is None: p = ""
else: p = ":"+self.port
limit = self.domain + p + self.path
if self.value is not None:
namevalue = "%s=%s" % (self.name, self.value)
else:
namevalue = self.name
return "<Cookie %s for %s>" % (namevalue, limit)
def __repr__(self):
args = []
for name in ["version", "name", "value",
"port", "port_specified",
"domain", "domain_specified", "domain_initial_dot",
"path", "path_specified",
"secure", "expires", "discard", "comment", "comment_url",
]:
attr = getattr(self, name)
args.append("%s=%s" % (name, repr(attr)))
args.append("rest=%s" % repr(self._rest))
args.append("rfc2109=%s" % repr(self.rfc2109))
return "Cookie(%s)" % ", ".join(args)
class CookiePolicy:
"""Defines which cookies get accepted from and returned to server.
May also modify cookies.
The subclass DefaultCookiePolicy defines the standard rules for Netscape
and RFC 2965 cookies -- override that if you want a customised policy.
As well as implementing set_ok and return_ok, implementations of this
interface must also supply the following attributes, indicating which
protocols should be used, and how. These can be read and set at any time,
though whether that makes complete sense from the protocol point of view is
doubtful.
Public attributes:
netscape: implement netscape protocol
rfc2965: implement RFC 2965 protocol
rfc2109_as_netscape:
WARNING: This argument will change or go away if is not accepted into
the Python standard library in this form!
If true, treat RFC 2109 cookies as though they were Netscape cookies. The
default is for this attribute to be None, which means treat 2109 cookies
as RFC 2965 cookies unless RFC 2965 handling is switched off (which it is,
by default), and as Netscape cookies otherwise.
hide_cookie2: don't add Cookie2 header to requests (the presence of
this header indicates to the server that we understand RFC 2965
cookies)
"""
def set_ok(self, cookie, request):
"""Return true if (and only if) cookie should be accepted from server.
Currently, pre-expired cookies never get this far -- the CookieJar
class deletes such cookies itself.
cookie: mechanize.Cookie object
request: object implementing the interface defined by
CookieJar.extract_cookies.__doc__
"""
raise NotImplementedError()
def return_ok(self, cookie, request):
"""Return true if (and only if) cookie should be returned to server.
cookie: mechanize.Cookie object
request: object implementing the interface defined by
CookieJar.add_cookie_header.__doc__
"""
raise NotImplementedError()
def domain_return_ok(self, domain, request):
"""Return false if cookies should not be returned, given cookie domain.
This is here as an optimization, to remove the need for checking every
cookie with a particular domain (which may involve reading many files).
The default implementations of domain_return_ok and path_return_ok
(return True) leave all the work to return_ok.
If domain_return_ok returns true for the cookie domain, path_return_ok
is called for the cookie path. Otherwise, path_return_ok and return_ok
are never called for that cookie domain. If path_return_ok returns
true, return_ok is called with the Cookie object itself for a full
check. Otherwise, return_ok is never called for that cookie path.
Note that domain_return_ok is called for every *cookie* domain, not
just for the *request* domain. For example, the function might be
called with both ".acme.com" and "www.acme.com" if the request domain is
"www.acme.com". The same goes for path_return_ok.
For argument documentation, see the docstring for return_ok.
"""
return True
def path_return_ok(self, path, request):
"""Return false if cookies should not be returned, given cookie path.
See the docstring for domain_return_ok.
"""
return True
class DefaultCookiePolicy(CookiePolicy):
"""Implements the standard rules for accepting and returning cookies.
Both RFC 2965 and Netscape cookies are covered. RFC 2965 handling is
switched off by default.
The easiest way to provide your own policy is to override this class and
call its methods in your overriden implementations before adding your own
additional checks.
import mechanize
class MyCookiePolicy(mechanize.DefaultCookiePolicy):
def set_ok(self, cookie, request):
if not mechanize.DefaultCookiePolicy.set_ok(
self, cookie, request):
return False
if i_dont_want_to_store_this_cookie():
return False
return True
In addition to the features required to implement the CookiePolicy
interface, this class allows you to block and allow domains from setting
and receiving cookies. There are also some strictness switches that allow
you to tighten up the rather loose Netscape protocol rules a little bit (at
the cost of blocking some benign cookies).
A domain blacklist and whitelist is provided (both off by default). Only
domains not in the blacklist and present in the whitelist (if the whitelist
is active) participate in cookie setting and returning. Use the
blocked_domains constructor argument, and blocked_domains and
set_blocked_domains methods (and the corresponding argument and methods for
allowed_domains). If you set a whitelist, you can turn it off again by
setting it to None.
Domains in block or allow lists that do not start with a dot must
string-compare equal. For example, "acme.com" matches a blacklist entry of
"acme.com", but "www.acme.com" does not. Domains that do start with a dot
are matched by more specific domains too. For example, both "www.acme.com"
and "www.munitions.acme.com" match ".acme.com" (but "acme.com" itself does
not). IP addresses are an exception, and must match exactly. For example,
if blocked_domains contains "192.168.1.2" and ".168.1.2" 192.168.1.2 is
blocked, but 193.168.1.2 is not.
Additional Public Attributes:
General strictness switches
strict_domain: don't allow sites to set two-component domains with
country-code top-level domains like .co.uk, .gov.uk, .co.nz. etc.
This is far from perfect and isn't guaranteed to work!
RFC 2965 protocol strictness switches
strict_rfc2965_unverifiable: follow RFC 2965 rules on unverifiable
transactions (usually, an unverifiable transaction is one resulting from
a redirect or an image hosted on another site); if this is false, cookies
are NEVER blocked on the basis of verifiability
Netscape protocol strictness switches
strict_ns_unverifiable: apply RFC 2965 rules on unverifiable transactions
even to Netscape cookies
strict_ns_domain: flags indicating how strict to be with domain-matching
rules for Netscape cookies:
DomainStrictNoDots: when setting cookies, host prefix must not contain a
dot (eg. www.foo.bar.com can't set a cookie for .bar.com, because
www.foo contains a dot)
DomainStrictNonDomain: cookies that did not explicitly specify a Domain
cookie-attribute can only be returned to a domain that string-compares
equal to the domain that set the cookie (eg. rockets.acme.com won't
be returned cookies from acme.com that had no Domain cookie-attribute)
DomainRFC2965Match: when setting cookies, require a full RFC 2965
domain-match
DomainLiberal and DomainStrict are the most useful combinations of the
above flags, for convenience
strict_ns_set_initial_dollar: ignore cookies in Set-Cookie: headers that
have names starting with '$'
strict_ns_set_path: don't allow setting cookies whose path doesn't
path-match request URI
"""
DomainStrictNoDots = 1
DomainStrictNonDomain = 2
DomainRFC2965Match = 4
DomainLiberal = 0
DomainStrict = DomainStrictNoDots|DomainStrictNonDomain
def __init__(self,
blocked_domains=None, allowed_domains=None,
netscape=True, rfc2965=False,
# WARNING: this argument will change or go away if is not
# accepted into the Python standard library in this form!
# default, ie. treat 2109 as netscape iff not rfc2965
rfc2109_as_netscape=None,
hide_cookie2=False,
strict_domain=False,
strict_rfc2965_unverifiable=True,
strict_ns_unverifiable=False,
strict_ns_domain=DomainLiberal,
strict_ns_set_initial_dollar=False,
strict_ns_set_path=False,
):
"""
Constructor arguments should be used as keyword arguments only.
blocked_domains: sequence of domain names that we never accept cookies
from, nor return cookies to
allowed_domains: if not None, this is a sequence of the only domains
for which we accept and return cookies
For other arguments, see CookiePolicy.__doc__ and
DefaultCookiePolicy.__doc__..
"""
self.netscape = netscape
self.rfc2965 = rfc2965
self.rfc2109_as_netscape = rfc2109_as_netscape
self.hide_cookie2 = hide_cookie2
self.strict_domain = strict_domain
self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable
self.strict_ns_unverifiable = strict_ns_unverifiable
self.strict_ns_domain = strict_ns_domain
self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar
self.strict_ns_set_path = strict_ns_set_path
if blocked_domains is not None:
self._blocked_domains = tuple(blocked_domains)
else:
self._blocked_domains = ()
if allowed_domains is not None:
allowed_domains = tuple(allowed_domains)
self._allowed_domains = allowed_domains
def blocked_domains(self):
"""Return the sequence of blocked domains (as a tuple)."""
return self._blocked_domains
def set_blocked_domains(self, blocked_domains):
"""Set the sequence of blocked domains."""
self._blocked_domains = tuple(blocked_domains)
def is_blocked(self, domain):
for blocked_domain in self._blocked_domains:
if user_domain_match(domain, blocked_domain):
return True
return False
def allowed_domains(self):
"""Return None, or the sequence of allowed domains (as a tuple)."""
return self._allowed_domains
def set_allowed_domains(self, allowed_domains):
"""Set the sequence of allowed domains, or None."""
if allowed_domains is not None:
allowed_domains = tuple(allowed_domains)
self._allowed_domains = allowed_domains
def is_not_allowed(self, domain):
if self._allowed_domains is None:
return False
for allowed_domain in self._allowed_domains:
if user_domain_match(domain, allowed_domain):
return False
return True
def set_ok(self, cookie, request):
"""
If you override set_ok, be sure to call this method. If it returns
false, so should your subclass (assuming your subclass wants to be more
strict about which cookies to accept).
"""
debug(" - checking cookie %s", cookie)
assert cookie.name is not None
for n in "version", "verifiability", "name", "path", "domain", "port":
fn_name = "set_ok_"+n
fn = getattr(self, fn_name)
if not fn(cookie, request):
return False
return True
def set_ok_version(self, cookie, request):
if cookie.version is None:
# Version is always set to 0 by parse_ns_headers if it's a Netscape
# cookie, so this must be an invalid RFC 2965 cookie.
debug(" Set-Cookie2 without version attribute (%s)", cookie)
return False
if cookie.version > 0 and not self.rfc2965:
debug(" RFC 2965 cookies are switched off")
return False
elif cookie.version == 0 and not self.netscape:
debug(" Netscape cookies are switched off")
return False
return True
def set_ok_verifiability(self, cookie, request):
if request.unverifiable and is_third_party(request):
if cookie.version > 0 and self.strict_rfc2965_unverifiable:
debug(" third-party RFC 2965 cookie during "
"unverifiable transaction")
return False
elif cookie.version == 0 and self.strict_ns_unverifiable:
debug(" third-party Netscape cookie during "
"unverifiable transaction")
return False
return True
def set_ok_name(self, cookie, request):
# Try and stop servers setting V0 cookies designed to hack other
# servers that know both V0 and V1 protocols.
if (cookie.version == 0 and self.strict_ns_set_initial_dollar and
cookie.name.startswith("$")):
debug(" illegal name (starts with '$'): '%s'", cookie.name)
return False
return True
def set_ok_path(self, cookie, request):
if cookie.path_specified:
req_path = request_path(request)
if ((cookie.version > 0 or
(cookie.version == 0 and self.strict_ns_set_path)) and
not req_path.startswith(cookie.path)):
debug(" path attribute %s is not a prefix of request "
"path %s", cookie.path, req_path)
return False
return True
def set_ok_countrycode_domain(self, cookie, request):
"""Return False if explicit cookie domain is not acceptable.
Called by set_ok_domain, for convenience of overriding by
subclasses.
"""
if cookie.domain_specified and self.strict_domain:
domain = cookie.domain
# since domain was specified, we know that:
assert domain.startswith(".")
if domain.count(".") == 2:
# domain like .foo.bar
i = domain.rfind(".")
tld = domain[i+1:]
sld = domain[1:i]
if (sld.lower() in [
"co", "ac",
"com", "edu", "org", "net", "gov", "mil", "int",
"aero", "biz", "cat", "coop", "info", "jobs", "mobi",
"museum", "name", "pro", "travel",
] and
len(tld) == 2):
# domain like .co.uk
return False
return True
def set_ok_domain(self, cookie, request):
if self.is_blocked(cookie.domain):
debug(" domain %s is in user block-list", cookie.domain)
return False
if self.is_not_allowed(cookie.domain):
debug(" domain %s is not in user allow-list", cookie.domain)
return False
if not self.set_ok_countrycode_domain(cookie, request):
debug(" country-code second level domain %s", cookie.domain)
return False
if cookie.domain_specified:
req_host, erhn = eff_request_host(request)
domain = cookie.domain
if domain.startswith("."):
undotted_domain = domain[1:]
else:
undotted_domain = domain
embedded_dots = (undotted_domain.find(".") >= 0)
if not embedded_dots and domain != ".local":
debug(" non-local domain %s contains no embedded dot",
domain)
return False
if cookie.version == 0:
if (not erhn.endswith(domain) and
(not erhn.startswith(".") and
not ("."+erhn).endswith(domain))):
debug(" effective request-host %s (even with added "
"initial dot) does not end end with %s",
erhn, domain)
return False
if (cookie.version > 0 or
(self.strict_ns_domain & self.DomainRFC2965Match)):
if not domain_match(erhn, domain):
debug(" effective request-host %s does not domain-match "
"%s", erhn, domain)
return False
if (cookie.version > 0 or
(self.strict_ns_domain & self.DomainStrictNoDots)):
host_prefix = req_host[:-len(domain)]
if (host_prefix.find(".") >= 0 and
not IPV4_RE.search(req_host)):
debug(" host prefix %s for domain %s contains a dot",
host_prefix, domain)
return False
return True
def set_ok_port(self, cookie, request):
if cookie.port_specified:
req_port = request_port(request)
if req_port is None:
req_port = "80"
else:
req_port = str(req_port)
for p in cookie.port.split(","):
try:
int(p)
except ValueError:
debug(" bad port %s (not numeric)", p)
return False
if p == req_port:
break
else:
debug(" request port (%s) not found in %s",
req_port, cookie.port)
return False
return True
def return_ok(self, cookie, request):
"""
If you override return_ok, be sure to call this method. If it returns
false, so should your subclass (assuming your subclass wants to be more
strict about which cookies to return).
"""
# Path has already been checked by path_return_ok, and domain blocking
# done by domain_return_ok.
debug(" - checking cookie %s", cookie)
for n in "version", "verifiability", "secure", "expires", "port", "domain":
fn_name = "return_ok_"+n
fn = getattr(self, fn_name)
if not fn(cookie, request):
return False
return True
def return_ok_version(self, cookie, request):
if cookie.version > 0 and not self.rfc2965:
debug(" RFC 2965 cookies are switched off")
return False
elif cookie.version == 0 and not self.netscape:
debug(" Netscape cookies are switched off")
return False
return True
def return_ok_verifiability(self, cookie, request):
if request.unverifiable and is_third_party(request):
if cookie.version > 0 and self.strict_rfc2965_unverifiable:
debug(" third-party RFC 2965 cookie during unverifiable "
"transaction")
return False
elif cookie.version == 0 and self.strict_ns_unverifiable:
debug(" third-party Netscape cookie during unverifiable "
"transaction")
return False
return True
def return_ok_secure(self, cookie, request):
if cookie.secure and request.get_type() != "https":
debug(" secure cookie with non-secure request")
return False
return True
def return_ok_expires(self, cookie, request):
if cookie.is_expired(self._now):
debug(" cookie expired")
return False
return True
def return_ok_port(self, cookie, request):
if cookie.port:
req_port = request_port(request)
if req_port is None:
req_port = "80"
for p in cookie.port.split(","):
if p == req_port:
break
else:
debug(" request port %s does not match cookie port %s",
req_port, cookie.port)
return False
return True
def return_ok_domain(self, cookie, request):
req_host, erhn = eff_request_host(request)
domain = cookie.domain
# strict check of non-domain cookies: Mozilla does this, MSIE5 doesn't
if (cookie.version == 0 and
(self.strict_ns_domain & self.DomainStrictNonDomain) and
not cookie.domain_specified and domain != erhn):
debug(" cookie with unspecified domain does not string-compare "
"equal to request domain")
return False
if cookie.version > 0 and not domain_match(erhn, domain):
debug(" effective request-host name %s does not domain-match "
"RFC 2965 cookie domain %s", erhn, domain)
return False
if cookie.version == 0 and not ("."+erhn).endswith(domain):
debug(" request-host %s does not match Netscape cookie domain "
"%s", req_host, domain)
return False
return True
def domain_return_ok(self, domain, request):
# Liberal check of domain. This is here as an optimization to avoid
# having to load lots of MSIE cookie files unless necessary.
# Munge req_host and erhn to always start with a dot, so as to err on
# the side of letting cookies through.
dotted_req_host, dotted_erhn = eff_request_host(request)
if not dotted_req_host.startswith("."):
dotted_req_host = "."+dotted_req_host
if not dotted_erhn.startswith("."):
dotted_erhn = "."+dotted_erhn
if not (dotted_req_host.endswith(domain) or
dotted_erhn.endswith(domain)):
#debug(" request domain %s does not match cookie domain %s",
# req_host, domain)
return False
if self.is_blocked(domain):
debug(" domain %s is in user block-list", domain)
return False
if self.is_not_allowed(domain):
debug(" domain %s is not in user allow-list", domain)
return False
return True
def path_return_ok(self, path, request):
debug("- checking cookie path=%s", path)
req_path = request_path(request)
if not req_path.startswith(path):
debug(" %s does not path-match %s", req_path, path)
return False
return True
def vals_sorted_by_key(adict):
keys = adict.keys()
keys.sort()
return map(adict.get, keys)
class MappingIterator:
"""Iterates over nested mapping, depth-first, in sorted order by key."""
def __init__(self, mapping):
self._s = [(vals_sorted_by_key(mapping), 0, None)] # LIFO stack
def __iter__(self): return self
def next(self):
# this is hairy because of lack of generators
while 1:
try:
vals, i, prev_item = self._s.pop()
except IndexError:
raise StopIteration()
if i < len(vals):
item = vals[i]
i = i + 1
self._s.append((vals, i, prev_item))
try:
item.items
except AttributeError:
# non-mapping
break
else:
# mapping
self._s.append((vals_sorted_by_key(item), 0, item))
continue
return item
# Used as second parameter to dict.get method, to distinguish absent
# dict key from one with a None value.
class Absent: pass
class CookieJar:
"""Collection of HTTP cookies.
You may not need to know about this class: try mechanize.urlopen().
The major methods are extract_cookies and add_cookie_header; these are all
you are likely to need.
CookieJar supports the iterator protocol:
for cookie in cookiejar:
# do something with cookie
Methods:
add_cookie_header(request)
extract_cookies(response, request)
make_cookies(response, request)
set_cookie_if_ok(cookie, request)
set_cookie(cookie)
clear_session_cookies()
clear_expired_cookies()
clear(domain=None, path=None, name=None)
Public attributes
policy: CookiePolicy object
"""
non_word_re = re.compile(r"\W")
quote_re = re.compile(r"([\"\\])")
strict_domain_re = re.compile(r"\.?[^.]*")
domain_re = re.compile(r"[^.]*")
dots_re = re.compile(r"^\.+")
def __init__(self, policy=None):
"""
See CookieJar.__doc__ for argument documentation.
"""
if policy is None:
policy = DefaultCookiePolicy()
self._policy = policy
self._cookies = {}
# for __getitem__ iteration in pre-2.2 Pythons
self._prev_getitem_index = 0
def set_policy(self, policy):
self._policy = policy
def _cookies_for_domain(self, domain, request):
cookies = []
if not self._policy.domain_return_ok(domain, request):
return []
debug("Checking %s for cookies to return", domain)
cookies_by_path = self._cookies[domain]
for path in cookies_by_path.keys():
if not self._policy.path_return_ok(path, request):
continue
cookies_by_name = cookies_by_path[path]
for cookie in cookies_by_name.values():
if not self._policy.return_ok(cookie, request):
debug(" not returning cookie")
continue
debug(" it's a match")
cookies.append(cookie)
return cookies
def _cookies_for_request(self, request):
"""Return a list of cookies to be returned to server."""
cookies = []
for domain in self._cookies.keys():
cookies.extend(self._cookies_for_domain(domain, request))
return cookies
def _cookie_attrs(self, cookies):
"""Return a list of cookie-attributes to be returned to server.
like ['foo="bar"; $Path="/"', ...]
The $Version attribute is also added when appropriate (currently only
once per request).
"""
# add cookies in order of most specific (ie. longest) path first
def decreasing_size(a, b): return cmp(len(b.path), len(a.path))
cookies.sort(decreasing_size)
version_set = False
attrs = []
for cookie in cookies:
# set version of Cookie header
# XXX
# What should it be if multiple matching Set-Cookie headers have
# different versions themselves?
# Answer: there is no answer; was supposed to be settled by
# RFC 2965 errata, but that may never appear...
version = cookie.version
if not version_set:
version_set = True
if version > 0:
attrs.append("$Version=%s" % version)
# quote cookie value if necessary
# (not for Netscape protocol, which already has any quotes
# intact, due to the poorly-specified Netscape Cookie: syntax)
if ((cookie.value is not None) and
self.non_word_re.search(cookie.value) and version > 0):
value = self.quote_re.sub(r"\\\1", cookie.value)
else:
value = cookie.value
# add cookie-attributes to be returned in Cookie header
if cookie.value is None:
attrs.append(cookie.name)
else:
attrs.append("%s=%s" % (cookie.name, value))
if version > 0:
if cookie.path_specified:
attrs.append('$Path="%s"' % cookie.path)
if cookie.domain.startswith("."):
domain = cookie.domain
if (not cookie.domain_initial_dot and
domain.startswith(".")):
domain = domain[1:]
attrs.append('$Domain="%s"' % domain)
if cookie.port is not None:
p = "$Port"
if cookie.port_specified:
p = p + ('="%s"' % cookie.port)
attrs.append(p)
return attrs
def add_cookie_header(self, request):
"""Add correct Cookie: header to request (urllib2.Request object).
The Cookie2 header is also added unless policy.hide_cookie2 is true.
The request object (usually a urllib2.Request instance) must support
the methods get_full_url, get_host, get_type, has_header, get_header,
header_items and add_unredirected_header, as documented by urllib2, and
the port attribute (the port number). Actually,
RequestUpgradeProcessor will automatically upgrade your Request object
to one with has_header, get_header, header_items and
add_unredirected_header, if it lacks those methods, for compatibility
with pre-2.4 versions of urllib2.
"""
debug("add_cookie_header")
self._policy._now = self._now = int(time.time())
req_host, erhn = eff_request_host(request)
strict_non_domain = (
self._policy.strict_ns_domain & self._policy.DomainStrictNonDomain)
cookies = self._cookies_for_request(request)
attrs = self._cookie_attrs(cookies)
if attrs:
if not request.has_header("Cookie"):
request.add_unredirected_header("Cookie", "; ".join(attrs))
# if necessary, advertise that we know RFC 2965
if self._policy.rfc2965 and not self._policy.hide_cookie2:
for cookie in cookies:
if cookie.version != 1 and not request.has_header("Cookie2"):
request.add_unredirected_header("Cookie2", '$Version="1"')
break
self.clear_expired_cookies()
def _normalized_cookie_tuples(self, attrs_set):
"""Return list of tuples containing normalised cookie information.
attrs_set is the list of lists of key,value pairs extracted from
the Set-Cookie or Set-Cookie2 headers.
Tuples are name, value, standard, rest, where name and value are the
cookie name and value, standard is a dictionary containing the standard
cookie-attributes (discard, secure, version, expires or max-age,
domain, path and port) and rest is a dictionary containing the rest of
the cookie-attributes.
"""
cookie_tuples = []
boolean_attrs = "discard", "secure"
value_attrs = ("version",
"expires", "max-age",
"domain", "path", "port",
"comment", "commenturl")
for cookie_attrs in attrs_set:
name, value = cookie_attrs[0]
# Build dictionary of standard cookie-attributes (standard) and
# dictionary of other cookie-attributes (rest).
# Note: expiry time is normalised to seconds since epoch. V0
# cookies should have the Expires cookie-attribute, and V1 cookies
# should have Max-Age, but since V1 includes RFC 2109 cookies (and
# since V0 cookies may be a mish-mash of Netscape and RFC 2109), we
# accept either (but prefer Max-Age).
max_age_set = False
bad_cookie = False
standard = {}
rest = {}
for k, v in cookie_attrs[1:]:
lc = k.lower()
# don't lose case distinction for unknown fields
if lc in value_attrs or lc in boolean_attrs:
k = lc
if k in boolean_attrs and v is None:
# boolean cookie-attribute is present, but has no value
# (like "discard", rather than "port=80")
v = True
if standard.has_key(k):
# only first value is significant
continue
if k == "domain":
if v is None:
debug(" missing value for domain attribute")
bad_cookie = True
break
# RFC 2965 section 3.3.3
v = v.lower()
if k == "expires":
if max_age_set:
# Prefer max-age to expires (like Mozilla)
continue
if v is None:
debug(" missing or invalid value for expires "
"attribute: treating as session cookie")
continue
if k == "max-age":
max_age_set = True
try:
v = int(v)
except ValueError:
debug(" missing or invalid (non-numeric) value for "
"max-age attribute")
bad_cookie = True
break
# convert RFC 2965 Max-Age to seconds since epoch
# XXX Strictly you're supposed to follow RFC 2616
# age-calculation rules. Remember that zero Max-Age is a
# is a request to discard (old and new) cookie, though.
k = "expires"
v = self._now + v
if (k in value_attrs) or (k in boolean_attrs):
if (v is None and
k not in ["port", "comment", "commenturl"]):
debug(" missing value for %s attribute" % k)
bad_cookie = True
break
standard[k] = v
else:
rest[k] = v
if bad_cookie:
continue
cookie_tuples.append((name, value, standard, rest))
return cookie_tuples
def _cookie_from_cookie_tuple(self, tup, request):
# standard is dict of standard cookie-attributes, rest is dict of the
# rest of them
name, value, standard, rest = tup
domain = standard.get("domain", Absent)
path = standard.get("path", Absent)
port = standard.get("port", Absent)
expires = standard.get("expires", Absent)
# set the easy defaults
version = standard.get("version", None)
if version is not None: version = int(version)
secure = standard.get("secure", False)
# (discard is also set if expires is Absent)
discard = standard.get("discard", False)
comment = standard.get("comment", None)
comment_url = standard.get("commenturl", None)
# set default path
if path is not Absent and path != "":
path_specified = True
path = escape_path(path)
else:
path_specified = False
path = request_path(request)
i = path.rfind("/")
if i != -1:
if version == 0:
# Netscape spec parts company from reality here
path = path[:i]
else:
path = path[:i+1]
if len(path) == 0: path = "/"
# set default domain
domain_specified = domain is not Absent
# but first we have to remember whether it starts with a dot
domain_initial_dot = False
if domain_specified:
domain_initial_dot = bool(domain.startswith("."))
if domain is Absent:
req_host, erhn = eff_request_host(request)
domain = erhn
elif not domain.startswith("."):
domain = "."+domain
# set default port
port_specified = False
if port is not Absent:
if port is None:
# Port attr present, but has no value: default to request port.
# Cookie should then only be sent back on that port.
port = request_port(request)
else:
port_specified = True
port = re.sub(r"\s+", "", port)
else:
# No port attr present. Cookie can be sent back on any port.
port = None
# set default expires and discard
if expires is Absent:
expires = None
discard = True
elif expires <= self._now:
# Expiry date in past is request to delete cookie. This can't be
# in DefaultCookiePolicy, because can't delete cookies there.
try:
self.clear(domain, path, name)
except KeyError:
pass
debug("Expiring cookie, domain='%s', path='%s', name='%s'",
domain, path, name)
return None
return Cookie(version,
name, value,
port, port_specified,
domain, domain_specified, domain_initial_dot,
path, path_specified,
secure,
expires,
discard,
comment,
comment_url,
rest)
def _cookies_from_attrs_set(self, attrs_set, request):
cookie_tuples = self._normalized_cookie_tuples(attrs_set)
cookies = []
for tup in cookie_tuples:
cookie = self._cookie_from_cookie_tuple(tup, request)
if cookie: cookies.append(cookie)
return cookies
def _process_rfc2109_cookies(self, cookies):
if self._policy.rfc2109_as_netscape is None:
rfc2109_as_netscape = not self._policy.rfc2965
else:
rfc2109_as_netscape = self._policy.rfc2109_as_netscape
for cookie in cookies:
if cookie.version == 1:
cookie.rfc2109 = True
if rfc2109_as_netscape:
# treat 2109 cookies as Netscape cookies rather than
# as RFC2965 cookies
cookie.version = 0
def make_cookies(self, response, request):
"""Return sequence of Cookie objects extracted from response object.
See extract_cookies.__doc__ for the interfaces required of the
response and request arguments.
"""
# get cookie-attributes for RFC 2965 and Netscape protocols
headers = response.info()
rfc2965_hdrs = headers.getheaders("Set-Cookie2")
ns_hdrs = headers.getheaders("Set-Cookie")
rfc2965 = self._policy.rfc2965
netscape = self._policy.netscape
if ((not rfc2965_hdrs and not ns_hdrs) or
(not ns_hdrs and not rfc2965) or
(not rfc2965_hdrs and not netscape) or
(not netscape and not rfc2965)):
return [] # no relevant cookie headers: quick exit
try:
cookies = self._cookies_from_attrs_set(
split_header_words(rfc2965_hdrs), request)
except:
reraise_unmasked_exceptions()
cookies = []
if ns_hdrs and netscape:
try:
# RFC 2109 and Netscape cookies
ns_cookies = self._cookies_from_attrs_set(
parse_ns_headers(ns_hdrs), request)
except:
reraise_unmasked_exceptions()
ns_cookies = []
self._process_rfc2109_cookies(ns_cookies)
# Look for Netscape cookies (from Set-Cookie headers) that match
# corresponding RFC 2965 cookies (from Set-Cookie2 headers).
# For each match, keep the RFC 2965 cookie and ignore the Netscape
# cookie (RFC 2965 section 9.1). Actually, RFC 2109 cookies are
# bundled in with the Netscape cookies for this purpose, which is
# reasonable behaviour.
if rfc2965:
lookup = {}
for cookie in cookies:
lookup[(cookie.domain, cookie.path, cookie.name)] = None
def no_matching_rfc2965(ns_cookie, lookup=lookup):
key = ns_cookie.domain, ns_cookie.path, ns_cookie.name
return not lookup.has_key(key)
ns_cookies = filter(no_matching_rfc2965, ns_cookies)
if ns_cookies:
cookies.extend(ns_cookies)
return cookies
def set_cookie_if_ok(self, cookie, request):
"""Set a cookie if policy says it's OK to do so.
cookie: mechanize.Cookie instance
request: see extract_cookies.__doc__ for the required interface
"""
self._policy._now = self._now = int(time.time())
if self._policy.set_ok(cookie, request):
self.set_cookie(cookie)
def set_cookie(self, cookie):
"""Set a cookie, without checking whether or not it should be set.
cookie: mechanize.Cookie instance
"""
c = self._cookies
if not c.has_key(cookie.domain): c[cookie.domain] = {}
c2 = c[cookie.domain]
if not c2.has_key(cookie.path): c2[cookie.path] = {}
c3 = c2[cookie.path]
c3[cookie.name] = cookie
def extract_cookies(self, response, request):
"""Extract cookies from response, where allowable given the request.
Look for allowable Set-Cookie: and Set-Cookie2: headers in the response
object passed as argument. Any of these headers that are found are
used to update the state of the object (subject to the policy.set_ok
method's approval).
The response object (usually be the result of a call to
mechanize.urlopen, or similar) should support an info method, which
returns a mimetools.Message object (in fact, the 'mimetools.Message
object' may be any object that provides a getallmatchingheaders
method).
The request object (usually a urllib2.Request instance) must support
the methods get_full_url and get_host, as documented by urllib2, and
the port attribute (the port number). The request is used to set
default values for cookie-attributes as well as for checking that the
cookie is OK to be set.
"""
debug("extract_cookies: %s", response.info())
self._policy._now = self._now = int(time.time())
for cookie in self.make_cookies(response, request):
if self._policy.set_ok(cookie, request):
debug(" setting cookie: %s", cookie)
self.set_cookie(cookie)
def clear(self, domain=None, path=None, name=None):
"""Clear some cookies.
Invoking this method without arguments will clear all cookies. If
given a single argument, only cookies belonging to that domain will be
removed. If given two arguments, cookies belonging to the specified
path within that domain are removed. If given three arguments, then
the cookie with the specified name, path and domain is removed.
Raises KeyError if no matching cookie exists.
"""
if name is not None:
if (domain is None) or (path is None):
raise ValueError(
"domain and path must be given to remove a cookie by name")
del self._cookies[domain][path][name]
elif path is not None:
if domain is None:
raise ValueError(
"domain must be given to remove cookies by path")
del self._cookies[domain][path]
elif domain is not None:
del self._cookies[domain]
else:
self._cookies = {}
def clear_session_cookies(self):
"""Discard all session cookies.
Discards all cookies held by object which had either no Max-Age or
Expires cookie-attribute or an explicit Discard cookie-attribute, or
which otherwise have ended up with a true discard attribute. For
interactive browsers, the end of a session usually corresponds to
closing the browser window.
Note that the save method won't save session cookies anyway, unless you
ask otherwise by passing a true ignore_discard argument.
"""
for cookie in self:
if cookie.discard:
self.clear(cookie.domain, cookie.path, cookie.name)
def clear_expired_cookies(self):
"""Discard all expired cookies.
You probably don't need to call this method: expired cookies are never
sent back to the server (provided you're using DefaultCookiePolicy),
this method is called by CookieJar itself every so often, and the save
method won't save expired cookies anyway (unless you ask otherwise by
passing a true ignore_expires argument).
"""
now = time.time()
for cookie in self:
if cookie.is_expired(now):
self.clear(cookie.domain, cookie.path, cookie.name)
def __getitem__(self, i):
if i == 0:
self._getitem_iterator = self.__iter__()
elif self._prev_getitem_index != i-1: raise IndexError(
"CookieJar.__getitem__ only supports sequential iteration")
self._prev_getitem_index = i
try:
return self._getitem_iterator.next()
except StopIteration:
raise IndexError()
def __iter__(self):
return MappingIterator(self._cookies)
def __len__(self):
"""Return number of contained cookies."""
i = 0
for cookie in self: i = i + 1
return i
def __repr__(self):
r = []
for cookie in self: r.append(repr(cookie))
return "<%s[%s]>" % (self.__class__, ", ".join(r))
def __str__(self):
r = []
for cookie in self: r.append(str(cookie))
return "<%s[%s]>" % (self.__class__, ", ".join(r))
class LoadError(Exception): pass
class FileCookieJar(CookieJar):
"""CookieJar that can be loaded from and saved to a file.
Additional methods
save(filename=None, ignore_discard=False, ignore_expires=False)
load(filename=None, ignore_discard=False, ignore_expires=False)
revert(filename=None, ignore_discard=False, ignore_expires=False)
Additional public attributes
filename: filename for loading and saving cookies
Additional public readable attributes
delayload: request that cookies are lazily loaded from disk; this is only
a hint since this only affects performance, not behaviour (unless the
cookies on disk are changing); a CookieJar object may ignore it (in fact,
only MSIECookieJar lazily loads cookies at the moment)
"""
def __init__(self, filename=None, delayload=False, policy=None):
"""
See FileCookieJar.__doc__ for argument documentation.
Cookies are NOT loaded from the named file until either the load or
revert method is called.
"""
CookieJar.__init__(self, policy)
if filename is not None and not isstringlike(filename):
raise ValueError("filename must be string-like")
self.filename = filename
self.delayload = bool(delayload)
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
"""Save cookies to a file.
filename: name of file in which to save cookies
ignore_discard: save even cookies set to be discarded
ignore_expires: save even cookies that have expired
The file is overwritten if it already exists, thus wiping all its
cookies. Saved cookies can be restored later using the load or revert
methods. If filename is not specified, self.filename is used; if
self.filename is None, ValueError is raised.
"""
raise NotImplementedError()
def load(self, filename=None, ignore_discard=False, ignore_expires=False):
"""Load cookies from a file.
Old cookies are kept unless overwritten by newly loaded ones.
Arguments are as for .save().
If filename is not specified, self.filename is used; if self.filename
is None, ValueError is raised. The named file must be in the format
understood by the class, or LoadError will be raised. This format will
be identical to that written by the save method, unless the load format
is not sufficiently well understood (as is the case for MSIECookieJar).
"""
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename)
try:
self._really_load(f, filename, ignore_discard, ignore_expires)
finally:
f.close()
def revert(self, filename=None,
ignore_discard=False, ignore_expires=False):
"""Clear all cookies and reload cookies from a saved file.
Raises LoadError (or IOError) if reversion is not successful; the
object's state will not be altered if this happens.
"""
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
old_state = copy.deepcopy(self._cookies)
self._cookies = {}
try:
self.load(filename, ignore_discard, ignore_expires)
except (LoadError, IOError):
self._cookies = old_state
raise
|
{
"pile_set_name": "Github"
}
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/crankshaft/ia32/lithium-ia32.h"
#include <sstream>
#if V8_TARGET_ARCH_IA32
#include "src/crankshaft/hydrogen-osr.h"
#include "src/crankshaft/ia32/lithium-codegen-ia32.h"
#include "src/crankshaft/lithium-inl.h"
namespace v8 {
namespace internal {
#define DEFINE_COMPILE(type) \
void L##type::CompileToNative(LCodeGen* generator) { \
generator->Do##type(this); \
}
LITHIUM_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE)
#undef DEFINE_COMPILE
#ifdef DEBUG
void LInstruction::VerifyCall() {
// Call instructions can use only fixed registers as temporaries and
// outputs because all registers are blocked by the calling convention.
// Inputs operands must use a fixed register or use-at-start policy or
// a non-register policy.
DCHECK(Output() == NULL ||
LUnallocated::cast(Output())->HasFixedPolicy() ||
!LUnallocated::cast(Output())->HasRegisterPolicy());
for (UseIterator it(this); !it.Done(); it.Advance()) {
LUnallocated* operand = LUnallocated::cast(it.Current());
DCHECK(operand->HasFixedPolicy() ||
operand->IsUsedAtStart());
}
for (TempIterator it(this); !it.Done(); it.Advance()) {
LUnallocated* operand = LUnallocated::cast(it.Current());
DCHECK(operand->HasFixedPolicy() ||!operand->HasRegisterPolicy());
}
}
#endif
bool LInstruction::HasDoubleRegisterResult() {
return HasResult() && result()->IsDoubleRegister();
}
bool LInstruction::HasDoubleRegisterInput() {
for (int i = 0; i < InputCount(); i++) {
LOperand* op = InputAt(i);
if (op != NULL && op->IsDoubleRegister()) {
return true;
}
}
return false;
}
void LInstruction::PrintTo(StringStream* stream) {
stream->Add("%s ", this->Mnemonic());
PrintOutputOperandTo(stream);
PrintDataTo(stream);
if (HasEnvironment()) {
stream->Add(" ");
environment()->PrintTo(stream);
}
if (HasPointerMap()) {
stream->Add(" ");
pointer_map()->PrintTo(stream);
}
}
void LInstruction::PrintDataTo(StringStream* stream) {
stream->Add("= ");
for (int i = 0; i < InputCount(); i++) {
if (i > 0) stream->Add(" ");
if (InputAt(i) == NULL) {
stream->Add("NULL");
} else {
InputAt(i)->PrintTo(stream);
}
}
}
void LInstruction::PrintOutputOperandTo(StringStream* stream) {
if (HasResult()) result()->PrintTo(stream);
}
void LLabel::PrintDataTo(StringStream* stream) {
LGap::PrintDataTo(stream);
LLabel* rep = replacement();
if (rep != NULL) {
stream->Add(" Dead block replaced with B%d", rep->block_id());
}
}
bool LGap::IsRedundant() const {
for (int i = 0; i < 4; i++) {
if (parallel_moves_[i] != NULL && !parallel_moves_[i]->IsRedundant()) {
return false;
}
}
return true;
}
void LGap::PrintDataTo(StringStream* stream) {
for (int i = 0; i < 4; i++) {
stream->Add("(");
if (parallel_moves_[i] != NULL) {
parallel_moves_[i]->PrintDataTo(stream);
}
stream->Add(") ");
}
}
const char* LArithmeticD::Mnemonic() const {
switch (op()) {
case Token::ADD: return "add-d";
case Token::SUB: return "sub-d";
case Token::MUL: return "mul-d";
case Token::DIV: return "div-d";
case Token::MOD: return "mod-d";
default:
UNREACHABLE();
return NULL;
}
}
const char* LArithmeticT::Mnemonic() const {
switch (op()) {
case Token::ADD: return "add-t";
case Token::SUB: return "sub-t";
case Token::MUL: return "mul-t";
case Token::MOD: return "mod-t";
case Token::DIV: return "div-t";
case Token::BIT_AND: return "bit-and-t";
case Token::BIT_OR: return "bit-or-t";
case Token::BIT_XOR: return "bit-xor-t";
case Token::ROR: return "ror-t";
case Token::SHL: return "sal-t";
case Token::SAR: return "sar-t";
case Token::SHR: return "shr-t";
default:
UNREACHABLE();
return NULL;
}
}
bool LGoto::HasInterestingComment(LCodeGen* gen) const {
return !gen->IsNextEmittedBlock(block_id());
}
void LGoto::PrintDataTo(StringStream* stream) {
stream->Add("B%d", block_id());
}
void LBranch::PrintDataTo(StringStream* stream) {
stream->Add("B%d | B%d on ", true_block_id(), false_block_id());
value()->PrintTo(stream);
}
void LCompareNumericAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if ");
left()->PrintTo(stream);
stream->Add(" %s ", Token::String(op()));
right()->PrintTo(stream);
stream->Add(" then B%d else B%d", true_block_id(), false_block_id());
}
void LIsStringAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if is_string(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LIsSmiAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if is_smi(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LIsUndetectableAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if is_undetectable(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LStringCompareAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if string_compare(");
left()->PrintTo(stream);
right()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LHasInstanceTypeAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if has_instance_type(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LHasCachedArrayIndexAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if has_cached_array_index(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LClassOfTestAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if class_of_test(");
value()->PrintTo(stream);
stream->Add(", \"%o\") then B%d else B%d",
*hydrogen()->class_name(),
true_block_id(),
false_block_id());
}
void LTypeofIsAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if typeof ");
value()->PrintTo(stream);
stream->Add(" == \"%s\" then B%d else B%d",
hydrogen()->type_literal()->ToCString().get(),
true_block_id(), false_block_id());
}
void LStoreCodeEntry::PrintDataTo(StringStream* stream) {
stream->Add(" = ");
function()->PrintTo(stream);
stream->Add(".code_entry = ");
code_object()->PrintTo(stream);
}
void LInnerAllocatedObject::PrintDataTo(StringStream* stream) {
stream->Add(" = ");
base_object()->PrintTo(stream);
stream->Add(" + ");
offset()->PrintTo(stream);
}
void LCallWithDescriptor::PrintDataTo(StringStream* stream) {
for (int i = 0; i < InputCount(); i++) {
InputAt(i)->PrintTo(stream);
stream->Add(" ");
}
stream->Add("#%d / ", arity());
}
void LLoadContextSlot::PrintDataTo(StringStream* stream) {
context()->PrintTo(stream);
stream->Add("[%d]", slot_index());
}
void LStoreContextSlot::PrintDataTo(StringStream* stream) {
context()->PrintTo(stream);
stream->Add("[%d] <- ", slot_index());
value()->PrintTo(stream);
}
void LInvokeFunction::PrintDataTo(StringStream* stream) {
stream->Add("= ");
context()->PrintTo(stream);
stream->Add(" ");
function()->PrintTo(stream);
stream->Add(" #%d / ", arity());
}
void LCallNewArray::PrintDataTo(StringStream* stream) {
stream->Add("= ");
context()->PrintTo(stream);
stream->Add(" ");
constructor()->PrintTo(stream);
stream->Add(" #%d / ", arity());
ElementsKind kind = hydrogen()->elements_kind();
stream->Add(" (%s) ", ElementsKindToString(kind));
}
void LAccessArgumentsAt::PrintDataTo(StringStream* stream) {
arguments()->PrintTo(stream);
stream->Add(" length ");
length()->PrintTo(stream);
stream->Add(" index ");
index()->PrintTo(stream);
}
int LPlatformChunk::GetNextSpillIndex(RegisterKind kind) {
// Skip a slot if for a double-width slot.
if (kind == DOUBLE_REGISTERS) {
current_frame_slots_++;
current_frame_slots_ |= 1;
num_double_slots_++;
}
return current_frame_slots_++;
}
LOperand* LPlatformChunk::GetNextSpillSlot(RegisterKind kind) {
int index = GetNextSpillIndex(kind);
if (kind == DOUBLE_REGISTERS) {
return LDoubleStackSlot::Create(index, zone());
} else {
DCHECK(kind == GENERAL_REGISTERS);
return LStackSlot::Create(index, zone());
}
}
void LStoreNamedField::PrintDataTo(StringStream* stream) {
object()->PrintTo(stream);
std::ostringstream os;
os << hydrogen()->access() << " <- ";
stream->Add(os.str().c_str());
value()->PrintTo(stream);
}
void LStoreNamedGeneric::PrintDataTo(StringStream* stream) {
object()->PrintTo(stream);
stream->Add(".");
stream->Add(String::cast(*name())->ToCString().get());
stream->Add(" <- ");
value()->PrintTo(stream);
}
void LLoadKeyed::PrintDataTo(StringStream* stream) {
elements()->PrintTo(stream);
stream->Add("[");
key()->PrintTo(stream);
if (hydrogen()->IsDehoisted()) {
stream->Add(" + %d]", base_offset());
} else {
stream->Add("]");
}
}
void LStoreKeyed::PrintDataTo(StringStream* stream) {
elements()->PrintTo(stream);
stream->Add("[");
key()->PrintTo(stream);
if (hydrogen()->IsDehoisted()) {
stream->Add(" + %d] <-", base_offset());
} else {
stream->Add("] <- ");
}
if (value() == NULL) {
DCHECK(hydrogen()->IsConstantHoleStore() &&
hydrogen()->value()->representation().IsDouble());
stream->Add("<the hole(nan)>");
} else {
value()->PrintTo(stream);
}
}
void LStoreKeyedGeneric::PrintDataTo(StringStream* stream) {
object()->PrintTo(stream);
stream->Add("[");
key()->PrintTo(stream);
stream->Add("] <- ");
value()->PrintTo(stream);
}
void LTransitionElementsKind::PrintDataTo(StringStream* stream) {
object()->PrintTo(stream);
stream->Add(" %p -> %p", *original_map(), *transitioned_map());
}
LPlatformChunk* LChunkBuilder::Build() {
DCHECK(is_unused());
chunk_ = new(zone()) LPlatformChunk(info(), graph());
LPhase phase("L_Building chunk", chunk_);
status_ = BUILDING;
// If compiling for OSR, reserve space for the unoptimized frame,
// which will be subsumed into this frame.
if (graph()->has_osr()) {
for (int i = graph()->osr()->UnoptimizedFrameSlots(); i > 0; i--) {
chunk_->GetNextSpillIndex(GENERAL_REGISTERS);
}
}
const ZoneList<HBasicBlock*>* blocks = graph()->blocks();
for (int i = 0; i < blocks->length(); i++) {
HBasicBlock* next = NULL;
if (i < blocks->length() - 1) next = blocks->at(i + 1);
DoBasicBlock(blocks->at(i), next);
if (is_aborted()) return NULL;
}
status_ = DONE;
return chunk_;
}
LUnallocated* LChunkBuilder::ToUnallocated(Register reg) {
return new (zone()) LUnallocated(LUnallocated::FIXED_REGISTER, reg.code());
}
LUnallocated* LChunkBuilder::ToUnallocated(XMMRegister reg) {
return new (zone())
LUnallocated(LUnallocated::FIXED_DOUBLE_REGISTER, reg.code());
}
LOperand* LChunkBuilder::UseFixed(HValue* value, Register fixed_register) {
return Use(value, ToUnallocated(fixed_register));
}
LOperand* LChunkBuilder::UseFixedDouble(HValue* value, XMMRegister reg) {
return Use(value, ToUnallocated(reg));
}
LOperand* LChunkBuilder::UseRegister(HValue* value) {
return Use(value, new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER));
}
LOperand* LChunkBuilder::UseRegisterAtStart(HValue* value) {
return Use(value,
new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER,
LUnallocated::USED_AT_START));
}
LOperand* LChunkBuilder::UseTempRegister(HValue* value) {
return Use(value, new(zone()) LUnallocated(LUnallocated::WRITABLE_REGISTER));
}
LOperand* LChunkBuilder::Use(HValue* value) {
return Use(value, new(zone()) LUnallocated(LUnallocated::NONE));
}
LOperand* LChunkBuilder::UseAtStart(HValue* value) {
return Use(value, new(zone()) LUnallocated(LUnallocated::NONE,
LUnallocated::USED_AT_START));
}
static inline bool CanBeImmediateConstant(HValue* value) {
return value->IsConstant() && HConstant::cast(value)->NotInNewSpace();
}
LOperand* LChunkBuilder::UseOrConstant(HValue* value) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: Use(value);
}
LOperand* LChunkBuilder::UseOrConstantAtStart(HValue* value) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: UseAtStart(value);
}
LOperand* LChunkBuilder::UseFixedOrConstant(HValue* value,
Register fixed_register) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: UseFixed(value, fixed_register);
}
LOperand* LChunkBuilder::UseRegisterOrConstant(HValue* value) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: UseRegister(value);
}
LOperand* LChunkBuilder::UseRegisterOrConstantAtStart(HValue* value) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: UseRegisterAtStart(value);
}
LOperand* LChunkBuilder::UseConstant(HValue* value) {
return chunk_->DefineConstantOperand(HConstant::cast(value));
}
LOperand* LChunkBuilder::UseAny(HValue* value) {
return value->IsConstant()
? chunk_->DefineConstantOperand(HConstant::cast(value))
: Use(value, new(zone()) LUnallocated(LUnallocated::ANY));
}
LOperand* LChunkBuilder::Use(HValue* value, LUnallocated* operand) {
if (value->EmitAtUses()) {
HInstruction* instr = HInstruction::cast(value);
VisitInstruction(instr);
}
operand->set_virtual_register(value->id());
return operand;
}
LInstruction* LChunkBuilder::Define(LTemplateResultInstruction<1>* instr,
LUnallocated* result) {
result->set_virtual_register(current_instruction_->id());
instr->set_result(result);
return instr;
}
LInstruction* LChunkBuilder::DefineAsRegister(
LTemplateResultInstruction<1>* instr) {
return Define(instr,
new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER));
}
LInstruction* LChunkBuilder::DefineAsSpilled(
LTemplateResultInstruction<1>* instr,
int index) {
return Define(instr,
new(zone()) LUnallocated(LUnallocated::FIXED_SLOT, index));
}
LInstruction* LChunkBuilder::DefineSameAsFirst(
LTemplateResultInstruction<1>* instr) {
return Define(instr,
new(zone()) LUnallocated(LUnallocated::SAME_AS_FIRST_INPUT));
}
LInstruction* LChunkBuilder::DefineFixed(LTemplateResultInstruction<1>* instr,
Register reg) {
return Define(instr, ToUnallocated(reg));
}
LInstruction* LChunkBuilder::DefineFixedDouble(
LTemplateResultInstruction<1>* instr,
XMMRegister reg) {
return Define(instr, ToUnallocated(reg));
}
LInstruction* LChunkBuilder::AssignEnvironment(LInstruction* instr) {
HEnvironment* hydrogen_env = current_block_->last_environment();
return LChunkBuilderBase::AssignEnvironment(instr, hydrogen_env);
}
LInstruction* LChunkBuilder::MarkAsCall(LInstruction* instr,
HInstruction* hinstr,
CanDeoptimize can_deoptimize) {
info()->MarkAsNonDeferredCalling();
#ifdef DEBUG
instr->VerifyCall();
#endif
instr->MarkAsCall();
instr = AssignPointerMap(instr);
// If instruction does not have side-effects lazy deoptimization
// after the call will try to deoptimize to the point before the call.
// Thus we still need to attach environment to this call even if
// call sequence can not deoptimize eagerly.
bool needs_environment =
(can_deoptimize == CAN_DEOPTIMIZE_EAGERLY) ||
!hinstr->HasObservableSideEffects();
if (needs_environment && !instr->HasEnvironment()) {
instr = AssignEnvironment(instr);
// We can't really figure out if the environment is needed or not.
instr->environment()->set_has_been_used();
}
return instr;
}
LInstruction* LChunkBuilder::AssignPointerMap(LInstruction* instr) {
DCHECK(!instr->HasPointerMap());
instr->set_pointer_map(new(zone()) LPointerMap(zone()));
return instr;
}
LUnallocated* LChunkBuilder::TempRegister() {
LUnallocated* operand =
new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER);
int vreg = allocator_->GetVirtualRegister();
if (!allocator_->AllocationOk()) {
Abort(kOutOfVirtualRegistersWhileTryingToAllocateTempRegister);
vreg = 0;
}
operand->set_virtual_register(vreg);
return operand;
}
LOperand* LChunkBuilder::FixedTemp(Register reg) {
LUnallocated* operand = ToUnallocated(reg);
DCHECK(operand->HasFixedPolicy());
return operand;
}
LOperand* LChunkBuilder::FixedTemp(XMMRegister reg) {
LUnallocated* operand = ToUnallocated(reg);
DCHECK(operand->HasFixedPolicy());
return operand;
}
LInstruction* LChunkBuilder::DoBlockEntry(HBlockEntry* instr) {
return new(zone()) LLabel(instr->block());
}
LInstruction* LChunkBuilder::DoDummyUse(HDummyUse* instr) {
return DefineAsRegister(new(zone()) LDummyUse(UseAny(instr->value())));
}
LInstruction* LChunkBuilder::DoEnvironmentMarker(HEnvironmentMarker* instr) {
UNREACHABLE();
return NULL;
}
LInstruction* LChunkBuilder::DoDeoptimize(HDeoptimize* instr) {
return AssignEnvironment(new(zone()) LDeoptimize);
}
LInstruction* LChunkBuilder::DoShift(Token::Value op,
HBitwiseBinaryOperation* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* left = UseRegisterAtStart(instr->left());
HValue* right_value = instr->right();
LOperand* right = NULL;
int constant_value = 0;
bool does_deopt = false;
if (right_value->IsConstant()) {
HConstant* constant = HConstant::cast(right_value);
right = chunk_->DefineConstantOperand(constant);
constant_value = constant->Integer32Value() & 0x1f;
// Left shifts can deoptimize if we shift by > 0 and the result cannot be
// truncated to smi.
if (instr->representation().IsSmi() && constant_value > 0) {
does_deopt = !instr->CheckUsesForFlag(HValue::kTruncatingToSmi);
}
} else {
right = UseFixed(right_value, ecx);
}
// Shift operations can only deoptimize if we do a logical shift by 0 and
// the result cannot be truncated to int32.
if (op == Token::SHR && constant_value == 0) {
does_deopt = !instr->CheckFlag(HInstruction::kUint32);
}
LInstruction* result =
DefineSameAsFirst(new(zone()) LShiftI(op, left, right, does_deopt));
return does_deopt ? AssignEnvironment(result) : result;
} else {
return DoArithmeticT(op, instr);
}
}
LInstruction* LChunkBuilder::DoArithmeticD(Token::Value op,
HArithmeticBinaryOperation* instr) {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->left()->representation().IsDouble());
DCHECK(instr->right()->representation().IsDouble());
if (op == Token::MOD) {
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
LOperand* right = UseRegisterAtStart(instr->BetterRightOperand());
LArithmeticD* result = new(zone()) LArithmeticD(op, left, right);
return MarkAsCall(DefineSameAsFirst(result), instr);
} else {
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
LOperand* right = UseRegisterAtStart(instr->BetterRightOperand());
LArithmeticD* result = new(zone()) LArithmeticD(op, left, right);
return CpuFeatures::IsSupported(AVX) ? DefineAsRegister(result)
: DefineSameAsFirst(result);
}
}
LInstruction* LChunkBuilder::DoArithmeticT(Token::Value op,
HBinaryOperation* instr) {
HValue* left = instr->left();
HValue* right = instr->right();
DCHECK(left->representation().IsTagged());
DCHECK(right->representation().IsTagged());
LOperand* context = UseFixed(instr->context(), esi);
LOperand* left_operand = UseFixed(left, edx);
LOperand* right_operand = UseFixed(right, eax);
LArithmeticT* result =
new(zone()) LArithmeticT(op, context, left_operand, right_operand);
return MarkAsCall(DefineFixed(result, eax), instr);
}
void LChunkBuilder::DoBasicBlock(HBasicBlock* block, HBasicBlock* next_block) {
DCHECK(is_building());
current_block_ = block;
next_block_ = next_block;
if (block->IsStartBlock()) {
block->UpdateEnvironment(graph_->start_environment());
argument_count_ = 0;
} else if (block->predecessors()->length() == 1) {
// We have a single predecessor => copy environment and outgoing
// argument count from the predecessor.
DCHECK(block->phis()->length() == 0);
HBasicBlock* pred = block->predecessors()->at(0);
HEnvironment* last_environment = pred->last_environment();
DCHECK(last_environment != NULL);
// Only copy the environment, if it is later used again.
if (pred->end()->SecondSuccessor() == NULL) {
DCHECK(pred->end()->FirstSuccessor() == block);
} else {
if (pred->end()->FirstSuccessor()->block_id() > block->block_id() ||
pred->end()->SecondSuccessor()->block_id() > block->block_id()) {
last_environment = last_environment->Copy();
}
}
block->UpdateEnvironment(last_environment);
DCHECK(pred->argument_count() >= 0);
argument_count_ = pred->argument_count();
} else {
// We are at a state join => process phis.
HBasicBlock* pred = block->predecessors()->at(0);
// No need to copy the environment, it cannot be used later.
HEnvironment* last_environment = pred->last_environment();
for (int i = 0; i < block->phis()->length(); ++i) {
HPhi* phi = block->phis()->at(i);
if (phi->HasMergedIndex()) {
last_environment->SetValueAt(phi->merged_index(), phi);
}
}
for (int i = 0; i < block->deleted_phis()->length(); ++i) {
if (block->deleted_phis()->at(i) < last_environment->length()) {
last_environment->SetValueAt(block->deleted_phis()->at(i),
graph_->GetConstantUndefined());
}
}
block->UpdateEnvironment(last_environment);
// Pick up the outgoing argument count of one of the predecessors.
argument_count_ = pred->argument_count();
}
HInstruction* current = block->first();
int start = chunk_->instructions()->length();
while (current != NULL && !is_aborted()) {
// Code for constants in registers is generated lazily.
if (!current->EmitAtUses()) {
VisitInstruction(current);
}
current = current->next();
}
int end = chunk_->instructions()->length() - 1;
if (end >= start) {
block->set_first_instruction_index(start);
block->set_last_instruction_index(end);
}
block->set_argument_count(argument_count_);
next_block_ = NULL;
current_block_ = NULL;
}
void LChunkBuilder::VisitInstruction(HInstruction* current) {
HInstruction* old_current = current_instruction_;
current_instruction_ = current;
LInstruction* instr = NULL;
if (current->CanReplaceWithDummyUses()) {
if (current->OperandCount() == 0) {
instr = DefineAsRegister(new(zone()) LDummy());
} else {
DCHECK(!current->OperandAt(0)->IsControlInstruction());
instr = DefineAsRegister(new(zone())
LDummyUse(UseAny(current->OperandAt(0))));
}
for (int i = 1; i < current->OperandCount(); ++i) {
if (current->OperandAt(i)->IsControlInstruction()) continue;
LInstruction* dummy =
new(zone()) LDummyUse(UseAny(current->OperandAt(i)));
dummy->set_hydrogen_value(current);
chunk_->AddInstruction(dummy, current_block_);
}
} else {
HBasicBlock* successor;
if (current->IsControlInstruction() &&
HControlInstruction::cast(current)->KnownSuccessorBlock(&successor) &&
successor != NULL) {
instr = new(zone()) LGoto(successor);
} else {
instr = current->CompileToLithium(this);
}
}
argument_count_ += current->argument_delta();
DCHECK(argument_count_ >= 0);
if (instr != NULL) {
AddInstruction(instr, current);
}
current_instruction_ = old_current;
}
void LChunkBuilder::AddInstruction(LInstruction* instr,
HInstruction* hydrogen_val) {
// Associate the hydrogen instruction first, since we may need it for
// the ClobbersRegisters() or ClobbersDoubleRegisters() calls below.
instr->set_hydrogen_value(hydrogen_val);
#if DEBUG
// Make sure that the lithium instruction has either no fixed register
// constraints in temps or the result OR no uses that are only used at
// start. If this invariant doesn't hold, the register allocator can decide
// to insert a split of a range immediately before the instruction due to an
// already allocated register needing to be used for the instruction's fixed
// register constraint. In this case, The register allocator won't see an
// interference between the split child and the use-at-start (it would if
// the it was just a plain use), so it is free to move the split child into
// the same register that is used for the use-at-start.
// See https://code.google.com/p/chromium/issues/detail?id=201590
if (!(instr->ClobbersRegisters() &&
instr->ClobbersDoubleRegisters(isolate()))) {
int fixed = 0;
int used_at_start = 0;
for (UseIterator it(instr); !it.Done(); it.Advance()) {
LUnallocated* operand = LUnallocated::cast(it.Current());
if (operand->IsUsedAtStart()) ++used_at_start;
}
if (instr->Output() != NULL) {
if (LUnallocated::cast(instr->Output())->HasFixedPolicy()) ++fixed;
}
for (TempIterator it(instr); !it.Done(); it.Advance()) {
LUnallocated* operand = LUnallocated::cast(it.Current());
if (operand->HasFixedPolicy()) ++fixed;
}
DCHECK(fixed == 0 || used_at_start == 0);
}
#endif
if (FLAG_stress_pointer_maps && !instr->HasPointerMap()) {
instr = AssignPointerMap(instr);
}
if (FLAG_stress_environments && !instr->HasEnvironment()) {
instr = AssignEnvironment(instr);
}
chunk_->AddInstruction(instr, current_block_);
CreateLazyBailoutForCall(current_block_, instr, hydrogen_val);
}
LInstruction* LChunkBuilder::DoPrologue(HPrologue* instr) {
LInstruction* result = new (zone()) LPrologue();
if (info_->scope()->num_heap_slots() > 0) {
result = MarkAsCall(result, instr);
}
return result;
}
LInstruction* LChunkBuilder::DoGoto(HGoto* instr) {
return new(zone()) LGoto(instr->FirstSuccessor());
}
LInstruction* LChunkBuilder::DoBranch(HBranch* instr) {
HValue* value = instr->value();
Representation r = value->representation();
HType type = value->type();
ToBooleanICStub::Types expected = instr->expected_input_types();
if (expected.IsEmpty()) expected = ToBooleanICStub::Types::Generic();
bool easy_case = !r.IsTagged() || type.IsBoolean() || type.IsSmi() ||
type.IsJSArray() || type.IsHeapNumber() || type.IsString();
LOperand* temp = !easy_case && expected.NeedsMap() ? TempRegister() : NULL;
LInstruction* branch = new(zone()) LBranch(UseRegister(value), temp);
if (!easy_case &&
((!expected.Contains(ToBooleanICStub::SMI) && expected.NeedsMap()) ||
!expected.IsGeneric())) {
branch = AssignEnvironment(branch);
}
return branch;
}
LInstruction* LChunkBuilder::DoDebugBreak(HDebugBreak* instr) {
return new(zone()) LDebugBreak();
}
LInstruction* LChunkBuilder::DoCompareMap(HCompareMap* instr) {
DCHECK(instr->value()->representation().IsTagged());
LOperand* value = UseRegisterAtStart(instr->value());
return new(zone()) LCmpMapAndBranch(value);
}
LInstruction* LChunkBuilder::DoArgumentsLength(HArgumentsLength* length) {
info()->MarkAsRequiresFrame();
return DefineAsRegister(new(zone()) LArgumentsLength(Use(length->value())));
}
LInstruction* LChunkBuilder::DoArgumentsElements(HArgumentsElements* elems) {
info()->MarkAsRequiresFrame();
return DefineAsRegister(new(zone()) LArgumentsElements);
}
LInstruction* LChunkBuilder::DoHasInPrototypeChainAndBranch(
HHasInPrototypeChainAndBranch* instr) {
LOperand* object = UseRegister(instr->object());
LOperand* prototype = UseRegister(instr->prototype());
LOperand* temp = TempRegister();
LHasInPrototypeChainAndBranch* result =
new (zone()) LHasInPrototypeChainAndBranch(object, prototype, temp);
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoWrapReceiver(HWrapReceiver* instr) {
LOperand* receiver = UseRegister(instr->receiver());
LOperand* function = UseRegister(instr->function());
LOperand* temp = TempRegister();
LWrapReceiver* result =
new(zone()) LWrapReceiver(receiver, function, temp);
return AssignEnvironment(DefineSameAsFirst(result));
}
LInstruction* LChunkBuilder::DoApplyArguments(HApplyArguments* instr) {
LOperand* function = UseFixed(instr->function(), edi);
LOperand* receiver = UseFixed(instr->receiver(), eax);
LOperand* length = UseFixed(instr->length(), ebx);
LOperand* elements = UseFixed(instr->elements(), ecx);
LApplyArguments* result = new(zone()) LApplyArguments(function,
receiver,
length,
elements);
return MarkAsCall(DefineFixed(result, eax), instr, CAN_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoPushArguments(HPushArguments* instr) {
int argc = instr->OperandCount();
for (int i = 0; i < argc; ++i) {
LOperand* argument = UseAny(instr->argument(i));
AddInstruction(new(zone()) LPushArgument(argument), instr);
}
return NULL;
}
LInstruction* LChunkBuilder::DoStoreCodeEntry(
HStoreCodeEntry* store_code_entry) {
LOperand* function = UseRegister(store_code_entry->function());
LOperand* code_object = UseTempRegister(store_code_entry->code_object());
return new(zone()) LStoreCodeEntry(function, code_object);
}
LInstruction* LChunkBuilder::DoInnerAllocatedObject(
HInnerAllocatedObject* instr) {
LOperand* base_object = UseRegisterAtStart(instr->base_object());
LOperand* offset = UseRegisterOrConstantAtStart(instr->offset());
return DefineAsRegister(
new(zone()) LInnerAllocatedObject(base_object, offset));
}
LInstruction* LChunkBuilder::DoThisFunction(HThisFunction* instr) {
return instr->HasNoUses()
? NULL
: DefineAsRegister(new(zone()) LThisFunction);
}
LInstruction* LChunkBuilder::DoContext(HContext* instr) {
if (instr->HasNoUses()) return NULL;
if (info()->IsStub()) {
return DefineFixed(new(zone()) LContext, esi);
}
return DefineAsRegister(new(zone()) LContext);
}
LInstruction* LChunkBuilder::DoDeclareGlobals(HDeclareGlobals* instr) {
LOperand* context = UseFixed(instr->context(), esi);
return MarkAsCall(new(zone()) LDeclareGlobals(context), instr);
}
LInstruction* LChunkBuilder::DoCallWithDescriptor(
HCallWithDescriptor* instr) {
CallInterfaceDescriptor descriptor = instr->descriptor();
LOperand* target = UseRegisterOrConstantAtStart(instr->target());
ZoneList<LOperand*> ops(instr->OperandCount(), zone());
// Target
ops.Add(target, zone());
// Context
LOperand* op = UseFixed(instr->OperandAt(1), esi);
ops.Add(op, zone());
// Other register parameters
for (int i = LCallWithDescriptor::kImplicitRegisterParameterCount;
i < instr->OperandCount(); i++) {
op =
UseFixed(instr->OperandAt(i),
descriptor.GetRegisterParameter(
i - LCallWithDescriptor::kImplicitRegisterParameterCount));
ops.Add(op, zone());
}
LCallWithDescriptor* result = new(zone()) LCallWithDescriptor(
descriptor, ops, zone());
if (instr->syntactic_tail_call_mode() == TailCallMode::kAllow) {
result->MarkAsSyntacticTailCall();
}
return MarkAsCall(DefineFixed(result, eax), instr, CANNOT_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoInvokeFunction(HInvokeFunction* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* function = UseFixed(instr->function(), edi);
LInvokeFunction* result = new(zone()) LInvokeFunction(context, function);
if (instr->syntactic_tail_call_mode() == TailCallMode::kAllow) {
result->MarkAsSyntacticTailCall();
}
return MarkAsCall(DefineFixed(result, eax), instr, CANNOT_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoUnaryMathOperation(HUnaryMathOperation* instr) {
switch (instr->op()) {
case kMathCos:
return DoMathCos(instr);
case kMathFloor:
return DoMathFloor(instr);
case kMathRound:
return DoMathRound(instr);
case kMathFround:
return DoMathFround(instr);
case kMathAbs:
return DoMathAbs(instr);
case kMathLog:
return DoMathLog(instr);
case kMathExp:
return DoMathExp(instr);
case kMathSqrt:
return DoMathSqrt(instr);
case kMathPowHalf:
return DoMathPowHalf(instr);
case kMathClz32:
return DoMathClz32(instr);
case kMathSin:
return DoMathSin(instr);
default:
UNREACHABLE();
return NULL;
}
}
LInstruction* LChunkBuilder::DoMathFloor(HUnaryMathOperation* instr) {
DCHECK(instr->value()->representation().IsDouble());
LOperand* input = UseRegisterAtStart(instr->value());
if (instr->representation().IsInteger32()) {
LMathFloorI* result = new (zone()) LMathFloorI(input);
return AssignEnvironment(AssignPointerMap(DefineAsRegister(result)));
} else {
DCHECK(instr->representation().IsDouble());
LMathFloorD* result = new (zone()) LMathFloorD(input);
return DefineAsRegister(result);
}
}
LInstruction* LChunkBuilder::DoMathRound(HUnaryMathOperation* instr) {
DCHECK(instr->value()->representation().IsDouble());
LOperand* input = UseRegister(instr->value());
if (instr->representation().IsInteger32()) {
LOperand* temp = FixedTemp(xmm4);
LMathRoundI* result = new (zone()) LMathRoundI(input, temp);
return AssignEnvironment(AssignPointerMap(DefineAsRegister(result)));
} else {
DCHECK(instr->representation().IsDouble());
LMathRoundD* result = new (zone()) LMathRoundD(input);
return DefineAsRegister(result);
}
}
LInstruction* LChunkBuilder::DoMathFround(HUnaryMathOperation* instr) {
LOperand* input = UseRegister(instr->value());
LMathFround* result = new (zone()) LMathFround(input);
return DefineAsRegister(result);
}
LInstruction* LChunkBuilder::DoMathAbs(HUnaryMathOperation* instr) {
LOperand* context = UseAny(instr->context()); // Deferred use.
LOperand* input = UseRegisterAtStart(instr->value());
LInstruction* result =
DefineSameAsFirst(new(zone()) LMathAbs(context, input));
Representation r = instr->value()->representation();
if (!r.IsDouble() && !r.IsSmiOrInteger32()) result = AssignPointerMap(result);
if (!r.IsDouble()) result = AssignEnvironment(result);
return result;
}
LInstruction* LChunkBuilder::DoMathLog(HUnaryMathOperation* instr) {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->value()->representation().IsDouble());
LOperand* input = UseRegisterAtStart(instr->value());
return MarkAsCall(DefineSameAsFirst(new(zone()) LMathLog(input)), instr);
}
LInstruction* LChunkBuilder::DoMathClz32(HUnaryMathOperation* instr) {
LOperand* input = UseRegisterAtStart(instr->value());
LMathClz32* result = new(zone()) LMathClz32(input);
return DefineAsRegister(result);
}
LInstruction* LChunkBuilder::DoMathCos(HUnaryMathOperation* instr) {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->value()->representation().IsDouble());
LOperand* input = UseRegisterAtStart(instr->value());
return MarkAsCall(DefineSameAsFirst(new (zone()) LMathCos(input)), instr);
}
LInstruction* LChunkBuilder::DoMathSin(HUnaryMathOperation* instr) {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->value()->representation().IsDouble());
LOperand* input = UseRegisterAtStart(instr->value());
return MarkAsCall(DefineSameAsFirst(new (zone()) LMathSin(input)), instr);
}
LInstruction* LChunkBuilder::DoMathExp(HUnaryMathOperation* instr) {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->value()->representation().IsDouble());
LOperand* input = UseRegisterAtStart(instr->value());
return MarkAsCall(DefineSameAsFirst(new (zone()) LMathExp(input)), instr);
}
LInstruction* LChunkBuilder::DoMathSqrt(HUnaryMathOperation* instr) {
LOperand* input = UseAtStart(instr->value());
return DefineAsRegister(new(zone()) LMathSqrt(input));
}
LInstruction* LChunkBuilder::DoMathPowHalf(HUnaryMathOperation* instr) {
LOperand* input = UseRegisterAtStart(instr->value());
LOperand* temp = TempRegister();
LMathPowHalf* result = new(zone()) LMathPowHalf(input, temp);
return DefineSameAsFirst(result);
}
LInstruction* LChunkBuilder::DoCallNewArray(HCallNewArray* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* constructor = UseFixed(instr->constructor(), edi);
LCallNewArray* result = new(zone()) LCallNewArray(context, constructor);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoCallRuntime(HCallRuntime* instr) {
LOperand* context = UseFixed(instr->context(), esi);
return MarkAsCall(DefineFixed(new(zone()) LCallRuntime(context), eax), instr);
}
LInstruction* LChunkBuilder::DoRor(HRor* instr) {
return DoShift(Token::ROR, instr);
}
LInstruction* LChunkBuilder::DoShr(HShr* instr) {
return DoShift(Token::SHR, instr);
}
LInstruction* LChunkBuilder::DoSar(HSar* instr) {
return DoShift(Token::SAR, instr);
}
LInstruction* LChunkBuilder::DoShl(HShl* instr) {
return DoShift(Token::SHL, instr);
}
LInstruction* LChunkBuilder::DoBitwise(HBitwise* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
DCHECK(instr->CheckFlag(HValue::kTruncatingToInt32));
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
LOperand* right = UseOrConstantAtStart(instr->BetterRightOperand());
return DefineSameAsFirst(new(zone()) LBitI(left, right));
} else {
return DoArithmeticT(instr->op(), instr);
}
}
LInstruction* LChunkBuilder::DoDivByPowerOf2I(HDiv* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegister(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LInstruction* result = DefineAsRegister(new(zone()) LDivByPowerOf2I(
dividend, divisor));
if ((instr->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) ||
(instr->CheckFlag(HValue::kCanOverflow) && divisor == -1) ||
(!instr->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
divisor != 1 && divisor != -1)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoDivByConstI(HDiv* instr) {
DCHECK(instr->representation().IsInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegister(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LOperand* temp1 = FixedTemp(eax);
LOperand* temp2 = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LDivByConstI(
dividend, divisor, temp1, temp2), edx);
if (divisor == 0 ||
(instr->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) ||
!instr->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoDivI(HDiv* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseFixed(instr->left(), eax);
LOperand* divisor = UseRegister(instr->right());
LOperand* temp = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LDivI(
dividend, divisor, temp), eax);
if (instr->CheckFlag(HValue::kCanBeDivByZero) ||
instr->CheckFlag(HValue::kBailoutOnMinusZero) ||
instr->CheckFlag(HValue::kCanOverflow) ||
!instr->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoDiv(HDiv* instr) {
if (instr->representation().IsSmiOrInteger32()) {
if (instr->RightIsPowerOf2()) {
return DoDivByPowerOf2I(instr);
} else if (instr->right()->IsConstant()) {
return DoDivByConstI(instr);
} else {
return DoDivI(instr);
}
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::DIV, instr);
} else {
return DoArithmeticT(Token::DIV, instr);
}
}
LInstruction* LChunkBuilder::DoFlooringDivByPowerOf2I(HMathFloorOfDiv* instr) {
LOperand* dividend = UseRegisterAtStart(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LInstruction* result = DefineSameAsFirst(new(zone()) LFlooringDivByPowerOf2I(
dividend, divisor));
if ((instr->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) ||
(instr->CheckFlag(HValue::kLeftCanBeMinInt) && divisor == -1)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoFlooringDivByConstI(HMathFloorOfDiv* instr) {
DCHECK(instr->representation().IsInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegister(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LOperand* temp1 = FixedTemp(eax);
LOperand* temp2 = FixedTemp(edx);
LOperand* temp3 =
((divisor > 0 && !instr->CheckFlag(HValue::kLeftCanBeNegative)) ||
(divisor < 0 && !instr->CheckFlag(HValue::kLeftCanBePositive))) ?
NULL : TempRegister();
LInstruction* result =
DefineFixed(new(zone()) LFlooringDivByConstI(dividend,
divisor,
temp1,
temp2,
temp3),
edx);
if (divisor == 0 ||
(instr->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoFlooringDivI(HMathFloorOfDiv* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseFixed(instr->left(), eax);
LOperand* divisor = UseRegister(instr->right());
LOperand* temp = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LFlooringDivI(
dividend, divisor, temp), eax);
if (instr->CheckFlag(HValue::kCanBeDivByZero) ||
instr->CheckFlag(HValue::kBailoutOnMinusZero) ||
instr->CheckFlag(HValue::kCanOverflow)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoMathFloorOfDiv(HMathFloorOfDiv* instr) {
if (instr->RightIsPowerOf2()) {
return DoFlooringDivByPowerOf2I(instr);
} else if (instr->right()->IsConstant()) {
return DoFlooringDivByConstI(instr);
} else {
return DoFlooringDivI(instr);
}
}
LInstruction* LChunkBuilder::DoModByPowerOf2I(HMod* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegisterAtStart(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LInstruction* result = DefineSameAsFirst(new(zone()) LModByPowerOf2I(
dividend, divisor));
if (instr->CheckFlag(HValue::kLeftCanBeNegative) &&
instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoModByConstI(HMod* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegister(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LOperand* temp1 = FixedTemp(eax);
LOperand* temp2 = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LModByConstI(
dividend, divisor, temp1, temp2), eax);
if (divisor == 0 || instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoModI(HMod* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseFixed(instr->left(), eax);
LOperand* divisor = UseRegister(instr->right());
LOperand* temp = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LModI(
dividend, divisor, temp), edx);
if (instr->CheckFlag(HValue::kCanBeDivByZero) ||
instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoMod(HMod* instr) {
if (instr->representation().IsSmiOrInteger32()) {
if (instr->RightIsPowerOf2()) {
return DoModByPowerOf2I(instr);
} else if (instr->right()->IsConstant()) {
return DoModByConstI(instr);
} else {
return DoModI(instr);
}
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::MOD, instr);
} else {
return DoArithmeticT(Token::MOD, instr);
}
}
LInstruction* LChunkBuilder::DoMul(HMul* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
HValue* h_right = instr->BetterRightOperand();
LOperand* right = UseOrConstant(h_right);
LOperand* temp = NULL;
if (instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
temp = TempRegister();
}
LMulI* mul = new(zone()) LMulI(left, right, temp);
int constant_value =
h_right->IsConstant() ? HConstant::cast(h_right)->Integer32Value() : 0;
// |needs_environment| must mirror the cases where LCodeGen::DoMulI calls
// |DeoptimizeIf|.
bool needs_environment =
instr->CheckFlag(HValue::kCanOverflow) ||
(instr->CheckFlag(HValue::kBailoutOnMinusZero) &&
(!right->IsConstantOperand() || constant_value <= 0));
if (needs_environment) {
AssignEnvironment(mul);
}
return DefineSameAsFirst(mul);
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::MUL, instr);
} else {
return DoArithmeticT(Token::MUL, instr);
}
}
LInstruction* LChunkBuilder::DoSub(HSub* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* left = UseRegisterAtStart(instr->left());
LOperand* right = UseOrConstantAtStart(instr->right());
LSubI* sub = new(zone()) LSubI(left, right);
LInstruction* result = DefineSameAsFirst(sub);
if (instr->CheckFlag(HValue::kCanOverflow)) {
result = AssignEnvironment(result);
}
return result;
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::SUB, instr);
} else {
return DoArithmeticT(Token::SUB, instr);
}
}
LInstruction* LChunkBuilder::DoAdd(HAdd* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
// Check to see if it would be advantageous to use an lea instruction rather
// than an add. This is the case when no overflow check is needed and there
// are multiple uses of the add's inputs, so using a 3-register add will
// preserve all input values for later uses.
bool use_lea = LAddI::UseLea(instr);
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
HValue* right_candidate = instr->BetterRightOperand();
LOperand* right = use_lea
? UseRegisterOrConstantAtStart(right_candidate)
: UseOrConstantAtStart(right_candidate);
LAddI* add = new(zone()) LAddI(left, right);
bool can_overflow = instr->CheckFlag(HValue::kCanOverflow);
LInstruction* result = use_lea
? DefineAsRegister(add)
: DefineSameAsFirst(add);
if (can_overflow) {
result = AssignEnvironment(result);
}
return result;
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::ADD, instr);
} else if (instr->representation().IsExternal()) {
DCHECK(instr->IsConsistentExternalRepresentation());
DCHECK(!instr->CheckFlag(HValue::kCanOverflow));
bool use_lea = LAddI::UseLea(instr);
LOperand* left = UseRegisterAtStart(instr->left());
HValue* right_candidate = instr->right();
LOperand* right = use_lea
? UseRegisterOrConstantAtStart(right_candidate)
: UseOrConstantAtStart(right_candidate);
LAddI* add = new(zone()) LAddI(left, right);
LInstruction* result = use_lea
? DefineAsRegister(add)
: DefineSameAsFirst(add);
return result;
} else {
return DoArithmeticT(Token::ADD, instr);
}
}
LInstruction* LChunkBuilder::DoMathMinMax(HMathMinMax* instr) {
LOperand* left = NULL;
LOperand* right = NULL;
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
left = UseRegisterAtStart(instr->BetterLeftOperand());
right = UseOrConstantAtStart(instr->BetterRightOperand());
} else {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->left()->representation().IsDouble());
DCHECK(instr->right()->representation().IsDouble());
left = UseRegisterAtStart(instr->left());
right = UseRegisterAtStart(instr->right());
}
LMathMinMax* minmax = new(zone()) LMathMinMax(left, right);
return DefineSameAsFirst(minmax);
}
LInstruction* LChunkBuilder::DoPower(HPower* instr) {
DCHECK(instr->representation().IsDouble());
// We call a C function for double power. It can't trigger a GC.
// We need to use fixed result register for the call.
Representation exponent_type = instr->right()->representation();
DCHECK(instr->left()->representation().IsDouble());
LOperand* left = UseFixedDouble(instr->left(), xmm2);
LOperand* right =
exponent_type.IsDouble()
? UseFixedDouble(instr->right(), xmm1)
: UseFixed(instr->right(), MathPowTaggedDescriptor::exponent());
LPower* result = new(zone()) LPower(left, right);
return MarkAsCall(DefineFixedDouble(result, xmm3), instr,
CAN_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoCompareGeneric(HCompareGeneric* instr) {
DCHECK(instr->left()->representation().IsSmiOrTagged());
DCHECK(instr->right()->representation().IsSmiOrTagged());
LOperand* context = UseFixed(instr->context(), esi);
LOperand* left = UseFixed(instr->left(), edx);
LOperand* right = UseFixed(instr->right(), eax);
LCmpT* result = new(zone()) LCmpT(context, left, right);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoCompareNumericAndBranch(
HCompareNumericAndBranch* instr) {
Representation r = instr->representation();
if (r.IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(r));
DCHECK(instr->right()->representation().Equals(r));
LOperand* left = UseRegisterOrConstantAtStart(instr->left());
LOperand* right = UseOrConstantAtStart(instr->right());
return new(zone()) LCompareNumericAndBranch(left, right);
} else {
DCHECK(r.IsDouble());
DCHECK(instr->left()->representation().IsDouble());
DCHECK(instr->right()->representation().IsDouble());
LOperand* left;
LOperand* right;
if (CanBeImmediateConstant(instr->left()) &&
CanBeImmediateConstant(instr->right())) {
// The code generator requires either both inputs to be constant
// operands, or neither.
left = UseConstant(instr->left());
right = UseConstant(instr->right());
} else {
left = UseRegisterAtStart(instr->left());
right = UseRegisterAtStart(instr->right());
}
return new(zone()) LCompareNumericAndBranch(left, right);
}
}
LInstruction* LChunkBuilder::DoCompareObjectEqAndBranch(
HCompareObjectEqAndBranch* instr) {
LOperand* left = UseRegisterAtStart(instr->left());
LOperand* right = UseOrConstantAtStart(instr->right());
return new(zone()) LCmpObjectEqAndBranch(left, right);
}
LInstruction* LChunkBuilder::DoCompareHoleAndBranch(
HCompareHoleAndBranch* instr) {
LOperand* value = UseRegisterAtStart(instr->value());
return new(zone()) LCmpHoleAndBranch(value);
}
LInstruction* LChunkBuilder::DoIsStringAndBranch(HIsStringAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
LOperand* temp = TempRegister();
return new(zone()) LIsStringAndBranch(UseRegister(instr->value()), temp);
}
LInstruction* LChunkBuilder::DoIsSmiAndBranch(HIsSmiAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LIsSmiAndBranch(Use(instr->value()));
}
LInstruction* LChunkBuilder::DoIsUndetectableAndBranch(
HIsUndetectableAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LIsUndetectableAndBranch(
UseRegisterAtStart(instr->value()), TempRegister());
}
LInstruction* LChunkBuilder::DoStringCompareAndBranch(
HStringCompareAndBranch* instr) {
DCHECK(instr->left()->representation().IsTagged());
DCHECK(instr->right()->representation().IsTagged());
LOperand* context = UseFixed(instr->context(), esi);
LOperand* left = UseFixed(instr->left(), edx);
LOperand* right = UseFixed(instr->right(), eax);
LStringCompareAndBranch* result = new(zone())
LStringCompareAndBranch(context, left, right);
return MarkAsCall(result, instr);
}
LInstruction* LChunkBuilder::DoHasInstanceTypeAndBranch(
HHasInstanceTypeAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LHasInstanceTypeAndBranch(
UseRegisterAtStart(instr->value()),
TempRegister());
}
LInstruction* LChunkBuilder::DoGetCachedArrayIndex(
HGetCachedArrayIndex* instr) {
DCHECK(instr->value()->representation().IsTagged());
LOperand* value = UseRegisterAtStart(instr->value());
return DefineAsRegister(new(zone()) LGetCachedArrayIndex(value));
}
LInstruction* LChunkBuilder::DoHasCachedArrayIndexAndBranch(
HHasCachedArrayIndexAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LHasCachedArrayIndexAndBranch(
UseRegisterAtStart(instr->value()));
}
LInstruction* LChunkBuilder::DoClassOfTestAndBranch(
HClassOfTestAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LClassOfTestAndBranch(UseRegister(instr->value()),
TempRegister(),
TempRegister());
}
LInstruction* LChunkBuilder::DoSeqStringGetChar(HSeqStringGetChar* instr) {
LOperand* string = UseRegisterAtStart(instr->string());
LOperand* index = UseRegisterOrConstantAtStart(instr->index());
return DefineAsRegister(new(zone()) LSeqStringGetChar(string, index));
}
LOperand* LChunkBuilder::GetSeqStringSetCharOperand(HSeqStringSetChar* instr) {
if (instr->encoding() == String::ONE_BYTE_ENCODING) {
if (FLAG_debug_code) {
return UseFixed(instr->value(), eax);
} else {
return UseFixedOrConstant(instr->value(), eax);
}
} else {
if (FLAG_debug_code) {
return UseRegisterAtStart(instr->value());
} else {
return UseRegisterOrConstantAtStart(instr->value());
}
}
}
LInstruction* LChunkBuilder::DoSeqStringSetChar(HSeqStringSetChar* instr) {
LOperand* string = UseRegisterAtStart(instr->string());
LOperand* index = FLAG_debug_code
? UseRegisterAtStart(instr->index())
: UseRegisterOrConstantAtStart(instr->index());
LOperand* value = GetSeqStringSetCharOperand(instr);
LOperand* context = FLAG_debug_code ? UseFixed(instr->context(), esi) : NULL;
LInstruction* result = new(zone()) LSeqStringSetChar(context, string,
index, value);
if (FLAG_debug_code) {
result = MarkAsCall(result, instr);
}
return result;
}
LInstruction* LChunkBuilder::DoBoundsCheck(HBoundsCheck* instr) {
if (!FLAG_debug_code && instr->skip_check()) return NULL;
LOperand* index = UseRegisterOrConstantAtStart(instr->index());
LOperand* length = !index->IsConstantOperand()
? UseOrConstantAtStart(instr->length())
: UseAtStart(instr->length());
LInstruction* result = new(zone()) LBoundsCheck(index, length);
if (!FLAG_debug_code || !instr->skip_check()) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoAbnormalExit(HAbnormalExit* instr) {
// The control instruction marking the end of a block that completed
// abruptly (e.g., threw an exception). There is nothing specific to do.
return NULL;
}
LInstruction* LChunkBuilder::DoUseConst(HUseConst* instr) {
return NULL;
}
LInstruction* LChunkBuilder::DoForceRepresentation(HForceRepresentation* bad) {
// All HForceRepresentation instructions should be eliminated in the
// representation change phase of Hydrogen.
UNREACHABLE();
return NULL;
}
LInstruction* LChunkBuilder::DoChange(HChange* instr) {
Representation from = instr->from();
Representation to = instr->to();
HValue* val = instr->value();
if (from.IsSmi()) {
if (to.IsTagged()) {
LOperand* value = UseRegister(val);
return DefineSameAsFirst(new(zone()) LDummyUse(value));
}
from = Representation::Tagged();
}
if (from.IsTagged()) {
if (to.IsDouble()) {
LOperand* value = UseRegister(val);
LOperand* temp = TempRegister();
LInstruction* result =
DefineAsRegister(new(zone()) LNumberUntagD(value, temp));
if (!val->representation().IsSmi()) result = AssignEnvironment(result);
return result;
} else if (to.IsSmi()) {
LOperand* value = UseRegister(val);
if (val->type().IsSmi()) {
return DefineSameAsFirst(new(zone()) LDummyUse(value));
}
return AssignEnvironment(DefineSameAsFirst(new(zone()) LCheckSmi(value)));
} else {
DCHECK(to.IsInteger32());
if (val->type().IsSmi() || val->representation().IsSmi()) {
LOperand* value = UseRegister(val);
return DefineSameAsFirst(new(zone()) LSmiUntag(value, false));
} else {
LOperand* value = UseRegister(val);
bool truncating = instr->CanTruncateToInt32();
LOperand* xmm_temp = !truncating ? FixedTemp(xmm1) : NULL;
LInstruction* result =
DefineSameAsFirst(new(zone()) LTaggedToI(value, xmm_temp));
if (!val->representation().IsSmi()) result = AssignEnvironment(result);
return result;
}
}
} else if (from.IsDouble()) {
if (to.IsTagged()) {
info()->MarkAsDeferredCalling();
LOperand* value = UseRegisterAtStart(val);
LOperand* temp = FLAG_inline_new ? TempRegister() : NULL;
LUnallocated* result_temp = TempRegister();
LNumberTagD* result = new(zone()) LNumberTagD(value, temp);
return AssignPointerMap(Define(result, result_temp));
} else if (to.IsSmi()) {
LOperand* value = UseRegister(val);
return AssignEnvironment(
DefineAsRegister(new(zone()) LDoubleToSmi(value)));
} else {
DCHECK(to.IsInteger32());
bool truncating = instr->CanTruncateToInt32();
bool needs_temp = !truncating;
LOperand* value = needs_temp ? UseTempRegister(val) : UseRegister(val);
LOperand* temp = needs_temp ? TempRegister() : NULL;
LInstruction* result =
DefineAsRegister(new(zone()) LDoubleToI(value, temp));
if (!truncating) result = AssignEnvironment(result);
return result;
}
} else if (from.IsInteger32()) {
info()->MarkAsDeferredCalling();
if (to.IsTagged()) {
LOperand* value = UseRegister(val);
if (!instr->CheckFlag(HValue::kCanOverflow)) {
return DefineSameAsFirst(new(zone()) LSmiTag(value));
} else if (val->CheckFlag(HInstruction::kUint32)) {
LOperand* temp = TempRegister();
LNumberTagU* result = new(zone()) LNumberTagU(value, temp);
return AssignPointerMap(DefineSameAsFirst(result));
} else {
LOperand* temp = TempRegister();
LNumberTagI* result = new(zone()) LNumberTagI(value, temp);
return AssignPointerMap(DefineSameAsFirst(result));
}
} else if (to.IsSmi()) {
LOperand* value = UseRegister(val);
LInstruction* result = DefineSameAsFirst(new(zone()) LSmiTag(value));
if (instr->CheckFlag(HValue::kCanOverflow)) {
result = AssignEnvironment(result);
}
return result;
} else {
DCHECK(to.IsDouble());
if (val->CheckFlag(HInstruction::kUint32)) {
return DefineAsRegister(new(zone()) LUint32ToDouble(UseRegister(val)));
} else {
return DefineAsRegister(new(zone()) LInteger32ToDouble(Use(val)));
}
}
}
UNREACHABLE();
return NULL;
}
LInstruction* LChunkBuilder::DoCheckHeapObject(HCheckHeapObject* instr) {
LOperand* value = UseAtStart(instr->value());
LInstruction* result = new(zone()) LCheckNonSmi(value);
if (!instr->value()->type().IsHeapObject()) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoCheckSmi(HCheckSmi* instr) {
LOperand* value = UseRegisterAtStart(instr->value());
return AssignEnvironment(new(zone()) LCheckSmi(value));
}
LInstruction* LChunkBuilder::DoCheckArrayBufferNotNeutered(
HCheckArrayBufferNotNeutered* instr) {
LOperand* view = UseRegisterAtStart(instr->value());
LOperand* scratch = TempRegister();
LCheckArrayBufferNotNeutered* result =
new (zone()) LCheckArrayBufferNotNeutered(view, scratch);
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoCheckInstanceType(HCheckInstanceType* instr) {
LOperand* value = UseRegisterAtStart(instr->value());
LOperand* temp = TempRegister();
LCheckInstanceType* result = new(zone()) LCheckInstanceType(value, temp);
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoCheckValue(HCheckValue* instr) {
// If the object is in new space, we'll emit a global cell compare and so
// want the value in a register. If the object gets promoted before we
// emit code, we will still get the register but will do an immediate
// compare instead of the cell compare. This is safe.
LOperand* value = instr->object_in_new_space()
? UseRegisterAtStart(instr->value()) : UseAtStart(instr->value());
return AssignEnvironment(new(zone()) LCheckValue(value));
}
LInstruction* LChunkBuilder::DoCheckMaps(HCheckMaps* instr) {
if (instr->IsStabilityCheck()) return new(zone()) LCheckMaps;
LOperand* value = UseRegisterAtStart(instr->value());
LInstruction* result = AssignEnvironment(new(zone()) LCheckMaps(value));
if (instr->HasMigrationTarget()) {
info()->MarkAsDeferredCalling();
result = AssignPointerMap(result);
}
return result;
}
LInstruction* LChunkBuilder::DoClampToUint8(HClampToUint8* instr) {
HValue* value = instr->value();
Representation input_rep = value->representation();
if (input_rep.IsDouble()) {
LOperand* reg = UseRegister(value);
return DefineFixed(new(zone()) LClampDToUint8(reg), eax);
} else if (input_rep.IsInteger32()) {
LOperand* reg = UseFixed(value, eax);
return DefineFixed(new(zone()) LClampIToUint8(reg), eax);
} else {
DCHECK(input_rep.IsSmiOrTagged());
LOperand* reg = UseFixed(value, eax);
// Register allocator doesn't (yet) support allocation of double
// temps. Reserve xmm1 explicitly.
LOperand* temp = FixedTemp(xmm1);
LClampTToUint8* result = new(zone()) LClampTToUint8(reg, temp);
return AssignEnvironment(DefineFixed(result, eax));
}
}
LInstruction* LChunkBuilder::DoReturn(HReturn* instr) {
LOperand* context = info()->IsStub() ? UseFixed(instr->context(), esi) : NULL;
LOperand* parameter_count = UseRegisterOrConstant(instr->parameter_count());
return new(zone()) LReturn(
UseFixed(instr->value(), eax), context, parameter_count);
}
LInstruction* LChunkBuilder::DoConstant(HConstant* instr) {
Representation r = instr->representation();
if (r.IsSmi()) {
return DefineAsRegister(new(zone()) LConstantS);
} else if (r.IsInteger32()) {
return DefineAsRegister(new(zone()) LConstantI);
} else if (r.IsDouble()) {
uint64_t const bits = instr->DoubleValueAsBits();
LOperand* temp = bits ? TempRegister() : nullptr;
return DefineAsRegister(new(zone()) LConstantD(temp));
} else if (r.IsExternal()) {
return DefineAsRegister(new(zone()) LConstantE);
} else if (r.IsTagged()) {
return DefineAsRegister(new(zone()) LConstantT);
} else {
UNREACHABLE();
return NULL;
}
}
LInstruction* LChunkBuilder::DoLoadGlobalGeneric(HLoadGlobalGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* vector = FixedTemp(LoadWithVectorDescriptor::VectorRegister());
LLoadGlobalGeneric* result = new (zone()) LLoadGlobalGeneric(context, vector);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoLoadContextSlot(HLoadContextSlot* instr) {
LOperand* context = UseRegisterAtStart(instr->value());
LInstruction* result =
DefineAsRegister(new(zone()) LLoadContextSlot(context));
if (instr->RequiresHoleCheck() && instr->DeoptimizesOnHole()) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoStoreContextSlot(HStoreContextSlot* instr) {
LOperand* value;
LOperand* temp;
LOperand* context = UseRegister(instr->context());
if (instr->NeedsWriteBarrier()) {
value = UseTempRegister(instr->value());
temp = TempRegister();
} else {
value = UseRegister(instr->value());
temp = NULL;
}
LInstruction* result = new(zone()) LStoreContextSlot(context, value, temp);
if (instr->RequiresHoleCheck() && instr->DeoptimizesOnHole()) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoLoadNamedField(HLoadNamedField* instr) {
LOperand* obj = (instr->access().IsExternalMemory() &&
instr->access().offset() == 0)
? UseRegisterOrConstantAtStart(instr->object())
: UseRegisterAtStart(instr->object());
return DefineAsRegister(new(zone()) LLoadNamedField(obj));
}
LInstruction* LChunkBuilder::DoLoadNamedGeneric(HLoadNamedGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object =
UseFixed(instr->object(), LoadDescriptor::ReceiverRegister());
LOperand* vector = FixedTemp(LoadWithVectorDescriptor::VectorRegister());
LLoadNamedGeneric* result = new(zone()) LLoadNamedGeneric(
context, object, vector);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoLoadFunctionPrototype(
HLoadFunctionPrototype* instr) {
return AssignEnvironment(DefineAsRegister(
new(zone()) LLoadFunctionPrototype(UseRegister(instr->function()),
TempRegister())));
}
LInstruction* LChunkBuilder::DoLoadRoot(HLoadRoot* instr) {
return DefineAsRegister(new(zone()) LLoadRoot);
}
LInstruction* LChunkBuilder::DoLoadKeyed(HLoadKeyed* instr) {
DCHECK(instr->key()->representation().IsSmiOrInteger32());
ElementsKind elements_kind = instr->elements_kind();
bool clobbers_key = ExternalArrayOpRequiresTemp(
instr->key()->representation(), elements_kind);
LOperand* key = clobbers_key
? UseTempRegister(instr->key())
: UseRegisterOrConstantAtStart(instr->key());
LInstruction* result = NULL;
if (!instr->is_fixed_typed_array()) {
LOperand* obj = UseRegisterAtStart(instr->elements());
result = DefineAsRegister(new (zone()) LLoadKeyed(obj, key, nullptr));
} else {
DCHECK(
(instr->representation().IsInteger32() &&
!(IsDoubleOrFloatElementsKind(instr->elements_kind()))) ||
(instr->representation().IsDouble() &&
(IsDoubleOrFloatElementsKind(instr->elements_kind()))));
LOperand* backing_store = UseRegister(instr->elements());
LOperand* backing_store_owner = UseAny(instr->backing_store_owner());
result = DefineAsRegister(
new (zone()) LLoadKeyed(backing_store, key, backing_store_owner));
}
bool needs_environment;
if (instr->is_fixed_typed_array()) {
// see LCodeGen::DoLoadKeyedExternalArray
needs_environment = elements_kind == UINT32_ELEMENTS &&
!instr->CheckFlag(HInstruction::kUint32);
} else {
// see LCodeGen::DoLoadKeyedFixedDoubleArray and
// LCodeGen::DoLoadKeyedFixedArray
needs_environment =
instr->RequiresHoleCheck() ||
(instr->hole_mode() == CONVERT_HOLE_TO_UNDEFINED && info()->IsStub());
}
if (needs_environment) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoLoadKeyedGeneric(HLoadKeyedGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object =
UseFixed(instr->object(), LoadDescriptor::ReceiverRegister());
LOperand* key = UseFixed(instr->key(), LoadDescriptor::NameRegister());
LOperand* vector = FixedTemp(LoadWithVectorDescriptor::VectorRegister());
LLoadKeyedGeneric* result =
new(zone()) LLoadKeyedGeneric(context, object, key, vector);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LOperand* LChunkBuilder::GetStoreKeyedValueOperand(HStoreKeyed* instr) {
ElementsKind elements_kind = instr->elements_kind();
// Determine if we need a byte register in this case for the value.
bool val_is_fixed_register =
elements_kind == UINT8_ELEMENTS ||
elements_kind == INT8_ELEMENTS ||
elements_kind == UINT8_CLAMPED_ELEMENTS;
if (val_is_fixed_register) {
return UseFixed(instr->value(), eax);
}
return UseRegister(instr->value());
}
LInstruction* LChunkBuilder::DoStoreKeyed(HStoreKeyed* instr) {
if (!instr->is_fixed_typed_array()) {
DCHECK(instr->elements()->representation().IsTagged());
DCHECK(instr->key()->representation().IsInteger32() ||
instr->key()->representation().IsSmi());
if (instr->value()->representation().IsDouble()) {
LOperand* object = UseRegisterAtStart(instr->elements());
LOperand* val = NULL;
val = UseRegisterAtStart(instr->value());
LOperand* key = UseRegisterOrConstantAtStart(instr->key());
return new (zone()) LStoreKeyed(object, key, val, nullptr);
} else {
DCHECK(instr->value()->representation().IsSmiOrTagged());
bool needs_write_barrier = instr->NeedsWriteBarrier();
LOperand* obj = UseRegister(instr->elements());
LOperand* val;
LOperand* key;
if (needs_write_barrier) {
val = UseTempRegister(instr->value());
key = UseTempRegister(instr->key());
} else {
val = UseRegisterOrConstantAtStart(instr->value());
key = UseRegisterOrConstantAtStart(instr->key());
}
return new (zone()) LStoreKeyed(obj, key, val, nullptr);
}
}
ElementsKind elements_kind = instr->elements_kind();
DCHECK(
(instr->value()->representation().IsInteger32() &&
!IsDoubleOrFloatElementsKind(elements_kind)) ||
(instr->value()->representation().IsDouble() &&
IsDoubleOrFloatElementsKind(elements_kind)));
DCHECK(instr->elements()->representation().IsExternal());
LOperand* backing_store = UseRegister(instr->elements());
LOperand* backing_store_owner = UseAny(instr->backing_store_owner());
LOperand* val = GetStoreKeyedValueOperand(instr);
bool clobbers_key = ExternalArrayOpRequiresTemp(
instr->key()->representation(), elements_kind);
LOperand* key = clobbers_key
? UseTempRegister(instr->key())
: UseRegisterOrConstantAtStart(instr->key());
return new (zone()) LStoreKeyed(backing_store, key, val, backing_store_owner);
}
LInstruction* LChunkBuilder::DoStoreKeyedGeneric(HStoreKeyedGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object =
UseFixed(instr->object(), StoreDescriptor::ReceiverRegister());
LOperand* key = UseFixed(instr->key(), StoreDescriptor::NameRegister());
LOperand* value = UseFixed(instr->value(), StoreDescriptor::ValueRegister());
DCHECK(instr->object()->representation().IsTagged());
DCHECK(instr->key()->representation().IsTagged());
DCHECK(instr->value()->representation().IsTagged());
LOperand* slot = FixedTemp(VectorStoreICDescriptor::SlotRegister());
LOperand* vector = FixedTemp(VectorStoreICDescriptor::VectorRegister());
LStoreKeyedGeneric* result = new (zone())
LStoreKeyedGeneric(context, object, key, value, slot, vector);
return MarkAsCall(result, instr);
}
LInstruction* LChunkBuilder::DoTransitionElementsKind(
HTransitionElementsKind* instr) {
if (IsSimpleMapChangeTransition(instr->from_kind(), instr->to_kind())) {
LOperand* object = UseRegister(instr->object());
LOperand* new_map_reg = TempRegister();
LOperand* temp_reg = TempRegister();
LTransitionElementsKind* result =
new(zone()) LTransitionElementsKind(object, NULL,
new_map_reg, temp_reg);
return result;
} else {
LOperand* object = UseFixed(instr->object(), eax);
LOperand* context = UseFixed(instr->context(), esi);
LTransitionElementsKind* result =
new(zone()) LTransitionElementsKind(object, context, NULL, NULL);
return MarkAsCall(result, instr);
}
}
LInstruction* LChunkBuilder::DoTrapAllocationMemento(
HTrapAllocationMemento* instr) {
LOperand* object = UseRegister(instr->object());
LOperand* temp = TempRegister();
LTrapAllocationMemento* result =
new(zone()) LTrapAllocationMemento(object, temp);
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoMaybeGrowElements(HMaybeGrowElements* instr) {
info()->MarkAsDeferredCalling();
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object = Use(instr->object());
LOperand* elements = Use(instr->elements());
LOperand* key = UseRegisterOrConstant(instr->key());
LOperand* current_capacity = UseRegisterOrConstant(instr->current_capacity());
LMaybeGrowElements* result = new (zone())
LMaybeGrowElements(context, object, elements, key, current_capacity);
DefineFixed(result, eax);
return AssignPointerMap(AssignEnvironment(result));
}
LInstruction* LChunkBuilder::DoStoreNamedField(HStoreNamedField* instr) {
bool is_in_object = instr->access().IsInobject();
bool is_external_location = instr->access().IsExternalMemory() &&
instr->access().offset() == 0;
bool needs_write_barrier = instr->NeedsWriteBarrier();
bool needs_write_barrier_for_map = instr->has_transition() &&
instr->NeedsWriteBarrierForMap();
LOperand* obj;
if (needs_write_barrier) {
obj = is_in_object
? UseRegister(instr->object())
: UseTempRegister(instr->object());
} else if (is_external_location) {
DCHECK(!is_in_object);
DCHECK(!needs_write_barrier);
DCHECK(!needs_write_barrier_for_map);
obj = UseRegisterOrConstant(instr->object());
} else {
obj = needs_write_barrier_for_map
? UseRegister(instr->object())
: UseRegisterAtStart(instr->object());
}
bool can_be_constant = instr->value()->IsConstant() &&
HConstant::cast(instr->value())->NotInNewSpace() &&
!instr->field_representation().IsDouble();
LOperand* val;
if (instr->field_representation().IsInteger8() ||
instr->field_representation().IsUInteger8()) {
// mov_b requires a byte register (i.e. any of eax, ebx, ecx, edx).
// Just force the value to be in eax and we're safe here.
val = UseFixed(instr->value(), eax);
} else if (needs_write_barrier) {
val = UseTempRegister(instr->value());
} else if (can_be_constant) {
val = UseRegisterOrConstant(instr->value());
} else if (instr->field_representation().IsDouble()) {
val = UseRegisterAtStart(instr->value());
} else {
val = UseRegister(instr->value());
}
// We only need a scratch register if we have a write barrier or we
// have a store into the properties array (not in-object-property).
LOperand* temp = (!is_in_object || needs_write_barrier ||
needs_write_barrier_for_map) ? TempRegister() : NULL;
// We need a temporary register for write barrier of the map field.
LOperand* temp_map = needs_write_barrier_for_map ? TempRegister() : NULL;
return new(zone()) LStoreNamedField(obj, val, temp, temp_map);
}
LInstruction* LChunkBuilder::DoStoreNamedGeneric(HStoreNamedGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object =
UseFixed(instr->object(), StoreDescriptor::ReceiverRegister());
LOperand* value = UseFixed(instr->value(), StoreDescriptor::ValueRegister());
LOperand* slot = FixedTemp(VectorStoreICDescriptor::SlotRegister());
LOperand* vector = FixedTemp(VectorStoreICDescriptor::VectorRegister());
LStoreNamedGeneric* result =
new (zone()) LStoreNamedGeneric(context, object, value, slot, vector);
return MarkAsCall(result, instr);
}
LInstruction* LChunkBuilder::DoStringAdd(HStringAdd* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* left = UseFixed(instr->left(), edx);
LOperand* right = UseFixed(instr->right(), eax);
LStringAdd* string_add = new(zone()) LStringAdd(context, left, right);
return MarkAsCall(DefineFixed(string_add, eax), instr);
}
LInstruction* LChunkBuilder::DoStringCharCodeAt(HStringCharCodeAt* instr) {
LOperand* string = UseTempRegister(instr->string());
LOperand* index = UseTempRegister(instr->index());
LOperand* context = UseAny(instr->context());
LStringCharCodeAt* result =
new(zone()) LStringCharCodeAt(context, string, index);
return AssignPointerMap(DefineAsRegister(result));
}
LInstruction* LChunkBuilder::DoStringCharFromCode(HStringCharFromCode* instr) {
LOperand* char_code = UseRegister(instr->value());
LOperand* context = UseAny(instr->context());
LStringCharFromCode* result =
new(zone()) LStringCharFromCode(context, char_code);
return AssignPointerMap(DefineAsRegister(result));
}
LInstruction* LChunkBuilder::DoAllocate(HAllocate* instr) {
LOperand* size = instr->size()->IsConstant() ? UseConstant(instr->size())
: UseRegister(instr->size());
if (instr->IsAllocationFolded()) {
LOperand* temp = TempRegister();
LFastAllocate* result = new (zone()) LFastAllocate(size, temp);
return DefineAsRegister(result);
} else {
info()->MarkAsDeferredCalling();
LOperand* context = UseAny(instr->context());
LOperand* temp = TempRegister();
LAllocate* result = new (zone()) LAllocate(context, size, temp);
return AssignPointerMap(DefineAsRegister(result));
}
}
LInstruction* LChunkBuilder::DoOsrEntry(HOsrEntry* instr) {
DCHECK(argument_count_ == 0);
allocator_->MarkAsOsrEntry();
current_block_->last_environment()->set_ast_id(instr->ast_id());
return AssignEnvironment(new(zone()) LOsrEntry);
}
LInstruction* LChunkBuilder::DoParameter(HParameter* instr) {
LParameter* result = new(zone()) LParameter;
if (instr->kind() == HParameter::STACK_PARAMETER) {
int spill_index = chunk()->GetParameterStackSlot(instr->index());
return DefineAsSpilled(result, spill_index);
} else {
DCHECK(info()->IsStub());
CallInterfaceDescriptor descriptor = graph()->descriptor();
int index = static_cast<int>(instr->index());
Register reg = descriptor.GetRegisterParameter(index);
return DefineFixed(result, reg);
}
}
LInstruction* LChunkBuilder::DoUnknownOSRValue(HUnknownOSRValue* instr) {
// Use an index that corresponds to the location in the unoptimized frame,
// which the optimized frame will subsume.
int env_index = instr->index();
int spill_index = 0;
if (instr->environment()->is_parameter_index(env_index)) {
spill_index = chunk()->GetParameterStackSlot(env_index);
} else {
spill_index = env_index - instr->environment()->first_local_index();
if (spill_index > LUnallocated::kMaxFixedSlotIndex) {
Retry(kNotEnoughSpillSlotsForOsr);
spill_index = 0;
}
spill_index += StandardFrameConstants::kFixedSlotCount;
}
return DefineAsSpilled(new(zone()) LUnknownOSRValue, spill_index);
}
LInstruction* LChunkBuilder::DoArgumentsObject(HArgumentsObject* instr) {
// There are no real uses of the arguments object.
// arguments.length and element access are supported directly on
// stack arguments, and any real arguments object use causes a bailout.
// So this value is never used.
return NULL;
}
LInstruction* LChunkBuilder::DoCapturedObject(HCapturedObject* instr) {
instr->ReplayEnvironment(current_block_->last_environment());
// There are no real uses of a captured object.
return NULL;
}
LInstruction* LChunkBuilder::DoAccessArgumentsAt(HAccessArgumentsAt* instr) {
info()->MarkAsRequiresFrame();
LOperand* args = UseRegister(instr->arguments());
LOperand* length;
LOperand* index;
if (instr->length()->IsConstant() && instr->index()->IsConstant()) {
length = UseRegisterOrConstant(instr->length());
index = UseOrConstant(instr->index());
} else {
length = UseTempRegister(instr->length());
index = Use(instr->index());
}
return DefineAsRegister(new(zone()) LAccessArgumentsAt(args, length, index));
}
LInstruction* LChunkBuilder::DoTypeof(HTypeof* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* value = UseFixed(instr->value(), ebx);
LTypeof* result = new(zone()) LTypeof(context, value);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoTypeofIsAndBranch(HTypeofIsAndBranch* instr) {
return new(zone()) LTypeofIsAndBranch(UseTempRegister(instr->value()));
}
LInstruction* LChunkBuilder::DoSimulate(HSimulate* instr) {
instr->ReplayEnvironment(current_block_->last_environment());
return NULL;
}
LInstruction* LChunkBuilder::DoStackCheck(HStackCheck* instr) {
info()->MarkAsDeferredCalling();
if (instr->is_function_entry()) {
LOperand* context = UseFixed(instr->context(), esi);
return MarkAsCall(new(zone()) LStackCheck(context), instr);
} else {
DCHECK(instr->is_backwards_branch());
LOperand* context = UseAny(instr->context());
return AssignEnvironment(
AssignPointerMap(new(zone()) LStackCheck(context)));
}
}
LInstruction* LChunkBuilder::DoEnterInlined(HEnterInlined* instr) {
HEnvironment* outer = current_block_->last_environment();
outer->set_ast_id(instr->ReturnId());
HConstant* undefined = graph()->GetConstantUndefined();
HEnvironment* inner = outer->CopyForInlining(
instr->closure(), instr->arguments_count(), instr->function(), undefined,
instr->inlining_kind(), instr->syntactic_tail_call_mode());
// Only replay binding of arguments object if it wasn't removed from graph.
if (instr->arguments_var() != NULL && instr->arguments_object()->IsLinked()) {
inner->Bind(instr->arguments_var(), instr->arguments_object());
}
inner->BindContext(instr->closure_context());
inner->set_entry(instr);
current_block_->UpdateEnvironment(inner);
chunk_->AddInlinedFunction(instr->shared());
return NULL;
}
LInstruction* LChunkBuilder::DoLeaveInlined(HLeaveInlined* instr) {
LInstruction* pop = NULL;
HEnvironment* env = current_block_->last_environment();
if (env->entry()->arguments_pushed()) {
int argument_count = env->arguments_environment()->parameter_count();
pop = new(zone()) LDrop(argument_count);
DCHECK(instr->argument_delta() == -argument_count);
}
HEnvironment* outer = current_block_->last_environment()->
DiscardInlined(false);
current_block_->UpdateEnvironment(outer);
return pop;
}
LInstruction* LChunkBuilder::DoForInPrepareMap(HForInPrepareMap* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object = UseFixed(instr->enumerable(), eax);
LForInPrepareMap* result = new(zone()) LForInPrepareMap(context, object);
return MarkAsCall(DefineFixed(result, eax), instr, CAN_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoForInCacheArray(HForInCacheArray* instr) {
LOperand* map = UseRegister(instr->map());
return AssignEnvironment(DefineAsRegister(
new(zone()) LForInCacheArray(map)));
}
LInstruction* LChunkBuilder::DoCheckMapValue(HCheckMapValue* instr) {
LOperand* value = UseRegisterAtStart(instr->value());
LOperand* map = UseRegisterAtStart(instr->map());
return AssignEnvironment(new(zone()) LCheckMapValue(value, map));
}
LInstruction* LChunkBuilder::DoLoadFieldByIndex(HLoadFieldByIndex* instr) {
LOperand* object = UseRegister(instr->object());
LOperand* index = UseTempRegister(instr->index());
LLoadFieldByIndex* load = new(zone()) LLoadFieldByIndex(object, index);
LInstruction* result = DefineSameAsFirst(load);
return AssignPointerMap(result);
}
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_IA32
|
{
"pile_set_name": "Github"
}
|
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: geonetwork@osgeo.org
//==============================================================================
package org.fao.oaipmh.responses;
import org.fao.oaipmh.OaiPmh;
import org.fao.oaipmh.requests.GetRecordRequest;
import org.jdom.Element;
//=============================================================================
public class GetRecordResponse extends AbstractResponse {
//---------------------------------------------------------------------------
//---
//--- Constructor
//---
//---------------------------------------------------------------------------
private Record record;
//---------------------------------------------------------------------------
public GetRecordResponse() {
}
//---------------------------------------------------------------------------
//---
//--- API methods
//---
//---------------------------------------------------------------------------
public GetRecordResponse(Element response) {
super(response);
build(response);
}
//---------------------------------------------------------------------------
public Record getRecord() {
return record;
}
//---------------------------------------------------------------------------
public void setRecord(Record r) {
record = r;
}
//---------------------------------------------------------------------------
//---
//--- Private methods
//---
//---------------------------------------------------------------------------
public Element toXml() {
Element root = new Element(GetRecordRequest.VERB, OaiPmh.Namespaces.OAI_PMH);
root.addContent(record.toXml());
return root;
}
//---------------------------------------------------------------------------
//---
//--- Variables
//---
//---------------------------------------------------------------------------
private void build(Element response) {
Element getRec = response.getChild("GetRecord", OaiPmh.Namespaces.OAI_PMH);
Element record = getRec.getChild("record", OaiPmh.Namespaces.OAI_PMH);
this.record = new Record(record);
}
}
//=============================================================================
|
{
"pile_set_name": "Github"
}
|
{
"@odata.context": "http://localhost:${tomcat.servlet.port}/stub/StaticService/V40/Static.svc/$metadata#People",
"value":
[
{
"@odata.type": "#Microsoft.Test.OData.Services.ODataWCFService.Person",
"@odata.id": "http://localhost:${tomcat.servlet.port}/stub/StaticService/V40/Static.svc/People(6)",
"@odata.editLink": "http://localhost:${tomcat.servlet.port}/stub/StaticService/V40/Static.svc/People(6)",
"PersonID": 6,
"FirstName": "Peter",
"LastName": "Bee",
"MiddleName": null,
"HomeAddress": null,
"Home@odata.type": "#GeographyPoint",
"Home":
{
"type": "Point",
"coordinates":
[
-261.8,
-16
],
"crs":
{
"type": "name",
"properties":
{
"name": "EPSG:4326"
}
}
},
"Numbers@odata.type": "#Collection(String)",
"Numbers":
[
"555-555-5555"
],
"Emails@odata.type": "#Collection(String)",
"Emails":
[
"def@test.msn"
],
"Parent@odata.associationLink": "http://localhost:${tomcat.servlet.port}/stub/StaticService/V40/Static.svc/People(5)/Parent/$ref",
"Parent@odata.navigationLink": "http://localhost:${tomcat.servlet.port}/stub/StaticService/V40/Static.svc/People(5)/Parent",
"#Microsoft.Test.OData.Services.ODataWCFService.ResetAddress":
{
"title": "Microsoft.Test.OData.Services.ODataWCFService.ResetAddress",
"target": "http://localhost:${tomcat.servlet.port}/stub/StaticService/V40/Static.svc/People(5)/Microsoft.Test.OData.Services.ODataWCFService.ResetAddress"
},
"#Microsoft.Test.OData.Services.ODataWCFService.GetHomeAddress":
{
"title": "Microsoft.Test.OData.Services.ODataWCFService.GetHomeAddress",
"target": "http://localhost:${tomcat.servlet.port}/stub/StaticService/V40/Static.svc/People(5)/Microsoft.Test.OData.Services.ODataWCFService.GetHomeAddress"
}
}
]
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@color/nb.widget.button.selected"/>
<item android:state_selected="true"
android:drawable="@color/nb.widget.button.selected"/>
<item
android:drawable="@color/nb.widget.button.normal"/>
</selector>
|
{
"pile_set_name": "Github"
}
|
'use strict';
var compose = require('es5-ext/function/#/compose')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, validTimeout = require('timers-ext/valid-timeout')
, chars = '-\\|/', l = chars.length, ThrobberIterator;
ThrobberIterator = function () {};
Object.defineProperties(ThrobberIterator.prototype, {
index: d(-1),
running: d(false),
next: d(function () {
var str = this.running ? '\u0008' : '';
if (!this.running) this.running = true;
return str + chars[this.index = ((this.index + 1) % l)];
}),
reset: d(function () {
if (!this.running) return '';
this.index = -1;
this.running = false;
return '\u0008';
})
});
module.exports = exports = function (write, interval/*, format*/) {
var format = arguments[2], token, iterator = new ThrobberIterator();
callable(write);
interval = validTimeout(interval);
if (format !== undefined) write = compose.call(write, callable(format));
return {
start: function () {
if (token) return;
token = setInterval(function () { write(iterator.next()); }, interval);
},
restart: function () {
this.stop();
this.start();
},
stop: function () {
if (!token) return;
clearInterval(token);
token = null;
write(iterator.reset());
}
};
};
Object.defineProperty(exports, 'Iterator', d(ThrobberIterator));
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html>
<head>
<title>API-Dokumentation</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap.min.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/prettify.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap-responsive.min.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/application.css'/>
<!-- IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div id='container'>
<ul class='breadcrumb'>
<li>
<a href='../../../apidoc/v2.de.html'>Foreman v2</a>
<span class='divider'>/</span>
</li>
<li>
<a href='../../../apidoc/v2/provisioning_templates.de.html'>
Provisioning templates
</a>
<span class='divider'>/</span>
</li>
<li class='active'>destroy</li>
<li class='pull-right'>
[ <a href="../../../apidoc/v2/provisioning_templates/destroy.pt_BR.html">pt_BR</a> | <b><a href="../../../apidoc/v2/provisioning_templates/destroy.de.html">de</a></b> | <a href="../../../apidoc/v2/provisioning_templates/destroy.it.html">it</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.sv_SE.html">sv_SE</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.zh_CN.html">zh_CN</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.en_GB.html">en_GB</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.cs_CZ.html">cs_CZ</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.fr.html">fr</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.ru.html">ru</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.ja.html">ja</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.es.html">es</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.ko.html">ko</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.ca.html">ca</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.gl.html">gl</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.en.html">en</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.zh_TW.html">zh_TW</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.nl_NL.html">nl_NL</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.pl.html">pl</a> ]
</li>
</ul>
<div class='page-header'>
<h1>
DELETE /api/provisioning_templates/:id
<br>
<small>Bereitstellungsvorlage löschen</small>
</h1>
</div>
<div>
<h2>Beispiele</h2>
<pre class="prettyprint">DELETE /api/provisioning_templates/1007981701-centos5_3_pxelinux
{
"provisioning_template": {}
}
200
{
"id": 1007981701,
"name": "centos5_3_pxelinux",
"template": "default linux~label linux~kernel <%= @kernel %>~append initrd=<%= @initrd %> ks=<%= foreman_url(\"kickstart\")%> ksdevice=bootif network kssendmac",
"snippet": false,
"template_kind_id": 452984334,
"created_at": "2019-02-20T13:35:11.398Z",
"updated_at": "2019-02-20T13:35:11.398Z",
"locked": false,
"default": false,
"vendor": null,
"os_family": null
}</pre>
<h2>Parameter</h2>
<table class='table'>
<thead>
<tr>
<th>Parametername</th>
<th>Beschreibung</th>
</tr>
</thead>
<tbody>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>location_id </strong><br>
<small>
optional
</small>
</td>
<td>
<p>Scope nach Standorten</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>organization_id </strong><br>
<small>
optional
</small>
</td>
<td>
<p>Scope nach Organisationen</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>id </strong><br>
<small>
verpflichtend
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be an identifier, string from 1 to 128 characters containing only alphanumeric characters, space, underscore(_), hypen(-) with no leading or trailing space.</p>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<hr>
<footer></footer>
</div>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/jquery.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/bootstrap-collapse.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/prettify.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/apipie.js'></script>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
This folder contains some sample formatters that may be helpful.
Feel free to change them, extend them, or use them as the basis for your own custom formatter(s).
More information about creating your own custom formatters can be found on the wiki:
https://github.com/CocoaLumberjack/CocoaLumberjack/wiki/CustomFormatters
|
{
"pile_set_name": "Github"
}
|
version: '2'
services:
postgres:
image: postgres:9.6-alpine
environment:
POSTGRES_PASSWORD: palantir
POSTGRES_USER: palantir
POSTGRES_DB: atlas
ports:
- "5432:5432"
|
{
"pile_set_name": "Github"
}
|
import test.test_support
compiler = test.test_support.import_module('compiler', deprecated=True)
from compiler.ast import flatten
import os, sys, time, unittest
from random import random
from StringIO import StringIO
# How much time in seconds can pass before we print a 'Still working' message.
_PRINT_WORKING_MSG_INTERVAL = 5 * 60
class TrivialContext(object):
def __enter__(self):
return self
def __exit__(self, *exc_info):
pass
class CompilerTest(unittest.TestCase):
def testCompileLibrary(self):
# A simple but large test. Compile all the code in the
# standard library and its test suite. This doesn't verify
# that any of the code is correct, merely the compiler is able
# to generate some kind of code for it.
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
# warning: if 'os' or 'test_support' are moved in some other dir,
# they should be changed here.
libdir = os.path.dirname(os.__file__)
testdir = os.path.dirname(test.test_support.__file__)
for dir in [testdir]:
for basename in "test_os.py",:
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
print >>sys.__stdout__, \
' testCompileLibrary still working, be patient...'
sys.__stdout__.flush()
if not basename.endswith(".py"):
continue
if not TEST_ALL and random() < 0.98:
continue
path = os.path.join(dir, basename)
if test.test_support.verbose:
print "compiling", path
f = open(path, "U")
buf = f.read()
f.close()
if "badsyntax" in basename or "bad_coding" in basename:
self.assertRaises(SyntaxError, compiler.compile,
buf, basename, "exec")
else:
try:
compiler.compile(buf, basename, "exec")
except Exception, e:
args = list(e.args)
args.append("in file %s]" % basename)
#args[0] += "[in file %s]" % basename
e.args = tuple(args)
raise
def testNewClassSyntax(self):
compiler.compile("class foo():pass\n\n","<string>","exec")
def testYieldExpr(self):
compiler.compile("def g(): yield\n\n", "<string>", "exec")
def testKeywordAfterStarargs(self):
def f(*args, **kwargs):
self.assertEqual((args, kwargs), ((2,3), {'x': 1, 'y': 4}))
c = compiler.compile('f(x=1, *(2, 3), y=4)', '<string>', 'exec')
exec c in {'f': f}
self.assertRaises(SyntaxError, compiler.parse, "foo(a=1, b)")
self.assertRaises(SyntaxError, compiler.parse, "foo(1, *args, 3)")
def testTryExceptFinally(self):
# Test that except and finally clauses in one try stmt are recognized
c = compiler.compile("try:\n 1//0\nexcept:\n e = 1\nfinally:\n f = 1",
"<string>", "exec")
dct = {}
exec c in dct
self.assertEqual(dct.get('e'), 1)
self.assertEqual(dct.get('f'), 1)
def testDefaultArgs(self):
self.assertRaises(SyntaxError, compiler.parse, "def foo(a=1, b): pass")
def testDocstrings(self):
c = compiler.compile('"doc"', '<string>', 'exec')
self.assertIn('__doc__', c.co_names)
c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
g = {}
exec c in g
self.assertEqual(g['f'].__doc__, "doc")
def testLineNo(self):
# Test that all nodes except Module have a correct lineno attribute.
filename = __file__
if filename.endswith((".pyc", ".pyo")):
filename = filename[:-1]
tree = compiler.parseFile(filename)
self.check_lineno(tree)
def check_lineno(self, node):
try:
self._check_lineno(node)
except AssertionError:
print node.__class__, node.lineno
raise
def _check_lineno(self, node):
if not node.__class__ in NOLINENO:
self.assertIsInstance(node.lineno, int,
"lineno=%s on %s" % (node.lineno, node.__class__))
self.assertTrue(node.lineno > 0,
"lineno=%s on %s" % (node.lineno, node.__class__))
for child in node.getChildNodes():
self.check_lineno(child)
def testFlatten(self):
self.assertEqual(flatten([1, [2]]), [1, 2])
self.assertEqual(flatten((1, (2,))), [1, 2])
def testNestedScope(self):
c = compiler.compile('def g():\n'
' a = 1\n'
' def f(): return a + 2\n'
' return f()\n'
'result = g()',
'<string>',
'exec')
dct = {}
exec c in dct
self.assertEqual(dct.get('result'), 3)
def testGenExp(self):
c = compiler.compile('list((i,j) for i in range(3) if i < 3'
' for j in range(4) if j > 2)',
'<string>',
'eval')
self.assertEqual(eval(c), [(0, 3), (1, 3), (2, 3)])
def testSetLiteral(self):
c = compiler.compile('{1, 2, 3}', '<string>', 'eval')
self.assertEqual(eval(c), {1,2,3})
c = compiler.compile('{1, 2, 3,}', '<string>', 'eval')
self.assertEqual(eval(c), {1,2,3})
def testDictLiteral(self):
c = compiler.compile('{1:2, 2:3, 3:4}', '<string>', 'eval')
self.assertEqual(eval(c), {1:2, 2:3, 3:4})
c = compiler.compile('{1:2, 2:3, 3:4,}', '<string>', 'eval')
self.assertEqual(eval(c), {1:2, 2:3, 3:4})
def testSetComp(self):
c = compiler.compile('{x for x in range(1, 4)}', '<string>', 'eval')
self.assertEqual(eval(c), {1, 2, 3})
c = compiler.compile('{x * y for x in range(3) if x != 0'
' for y in range(4) if y != 0}',
'<string>',
'eval')
self.assertEqual(eval(c), {1, 2, 3, 4, 6})
def testDictComp(self):
c = compiler.compile('{x:x+1 for x in range(1, 4)}', '<string>', 'eval')
self.assertEqual(eval(c), {1:2, 2:3, 3:4})
c = compiler.compile('{(x, y) : y for x in range(2) if x != 0'
' for y in range(3) if y != 0}',
'<string>',
'eval')
self.assertEqual(eval(c), {(1, 2): 2, (1, 1): 1})
def testWith(self):
# SF bug 1638243
c = compiler.compile('from __future__ import with_statement\n'
'def f():\n'
' with TrivialContext():\n'
' return 1\n'
'result = f()',
'<string>',
'exec' )
dct = {'TrivialContext': TrivialContext}
exec c in dct
self.assertEqual(dct.get('result'), 1)
def testWithAss(self):
c = compiler.compile('from __future__ import with_statement\n'
'def f():\n'
' with TrivialContext() as tc:\n'
' return 1\n'
'result = f()',
'<string>',
'exec' )
dct = {'TrivialContext': TrivialContext}
exec c in dct
self.assertEqual(dct.get('result'), 1)
def testWithMult(self):
events = []
class Ctx:
def __init__(self, n):
self.n = n
def __enter__(self):
events.append(self.n)
def __exit__(self, *args):
pass
c = compiler.compile('from __future__ import with_statement\n'
'def f():\n'
' with Ctx(1) as tc, Ctx(2) as tc2:\n'
' return 1\n'
'result = f()',
'<string>',
'exec' )
dct = {'Ctx': Ctx}
exec c in dct
self.assertEqual(dct.get('result'), 1)
self.assertEqual(events, [1, 2])
def testGlobal(self):
code = compiler.compile('global x\nx=1', '<string>', 'exec')
d1 = {'__builtins__': {}}
d2 = {}
exec code in d1, d2
# x should be in the globals dict
self.assertEqual(d1.get('x'), 1)
def testPrintFunction(self):
c = compiler.compile('from __future__ import print_function\n'
'print("a", "b", sep="**", end="++", '
'file=output)',
'<string>',
'exec' )
dct = {'output': StringIO()}
exec c in dct
self.assertEqual(dct['output'].getvalue(), 'a**b++')
def _testErrEnc(self, src, text, offset):
try:
compile(src, "", "exec")
except SyntaxError, e:
self.assertEqual(e.offset, offset)
self.assertEqual(e.text, text)
def testSourceCodeEncodingsError(self):
# Test SyntaxError with encoding definition
sjis = "print '\x83\x70\x83\x43\x83\x5c\x83\x93', '\n"
ascii = "print '12345678', '\n"
encdef = "#! -*- coding: ShiftJIS -*-\n"
# ascii source without encdef
self._testErrEnc(ascii, ascii, 19)
# ascii source with encdef
self._testErrEnc(encdef+ascii, ascii, 19)
# non-ascii source with encdef
self._testErrEnc(encdef+sjis, sjis, 19)
# ShiftJIS source without encdef
self._testErrEnc(sjis, sjis, 19)
NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard)
###############################################################################
# code below is just used to trigger some possible errors, for the benefit of
# testLineNo
###############################################################################
class Toto:
"""docstring"""
pass
a, b = 2, 3
[c, d] = 5, 6
l = [(x, y) for x, y in zip(range(5), range(5,10))]
l[0]
l[3:4]
d = {'a': 2}
d = {}
d = {x: y for x, y in zip(range(5), range(5,10))}
s = {x for x in range(10)}
s = {1}
t = ()
t = (1, 2)
l = []
l = [1, 2]
if l:
pass
else:
a, b = b, a
try:
print yo
except:
yo = 3
else:
yo += 3
try:
a += b
finally:
b = 0
from math import *
###############################################################################
def test_main():
global TEST_ALL
TEST_ALL = test.test_support.is_resource_enabled("cpu")
test.test_support.run_unittest(CompilerTest)
if __name__ == "__main__":
test_main()
|
{
"pile_set_name": "Github"
}
|
//
// C2DXiOSShareSDK.h
// C2DXShareSDKSample
//
// Created by 冯 鸿杰 on 13-12-17.
//
//
#ifndef __C2DXShareSDKSample__C2DXiOSShareSDK__
#define __C2DXShareSDKSample__C2DXiOSShareSDK__
#include <iostream>
#include "cocos2d.h"
#include "C2DXShareSDKTypeDef.h"
USING_NS_CC;
namespace cn
{
namespace sharesdk
{
/**
* @brief ShareSDK (iOS)
*/
class C2DXiOSShareSDK
{
public:
/**
* @brief 初始化ShareSDK
*
* @param appKey 应用Key
* @param useAppTrusteeship 是否使用应用信息托管
*/
static void open(CCString *appKey, bool useAppTrusteeship);
/**
* @brief 关闭ShareSDK
*/
static void close();
/**
* @brief 设置平台配置信息
*
* @param platType 平台类型
* @param configInfo 配置信息
*/
static void setPlatformConfig(C2DXPlatType platType, CCDictionary *configInfo);
/**
* @brief 用户授权
*
* @param platType 平台类型
* @param callback 回调方法
*/
static void authorize(C2DXPlatType platType, C2DXAuthResultEvent callback);
/**
* @brief 取消用户授权
*
* @param platType 平台类型
*/
static void cancelAuthorize(C2DXPlatType platType);
/**
* @brief 用户是否授权
*
* @param platType 平台类型
*
* @return true 已授权, false 尚未授权
*/
static bool hasAutorized(C2DXPlatType platType);
/**
* @brief 获取用户信息
*
* @param platType 平台类型
* @param callback 回调方法
*/
static void getUserInfo(C2DXPlatType platType, C2DXGetUserInfoResultEvent callback);
/**
* @brief 分享内容
*
* @param platType 平台类型
* @param content 分享内容
* @param callback 回调方法
*/
static void shareContent(C2DXPlatType platType, CCDictionary *content, C2DXShareResultEvent callback);
/**
* @brief 一键分享内容
*
* @param platTypes 平台类型列表
* @param content 分享内容
* @param callback 回调方法
*/
static void oneKeyShareContent(CCArray *platTypes, CCDictionary *content, C2DXShareResultEvent callback);
/**
* @brief 显示分享菜单
*
* @param platTypes 平台类型列表
* @param content 分享内容
* @param callback 回调方法
*/
static void showShareMenu(CCArray *platTypes, CCDictionary *content, C2DXShareResultEvent callback);
/**
* @brief 显示分享菜单
*
* @param platTypes 平台类型列表
* @param content 分享内容
* @param pt 弹出分享菜单参位置,仅用于设置iPad分享菜单弹出
* @param direction 弹出分享菜单指向,仅用于设置iPad分享菜单弹出
* @param callback 回调方法
*/
static void showShareMenu(CCArray *platTypes, CCDictionary *content, CCPoint pt, C2DXMenuArrowDirection direction, C2DXShareResultEvent callback);
/**
* @brief 显示分享视图
*
* @param platType 平台类型
* @param content 分享内容
* @param callback 回调方法
*/
static void showShareView(C2DXPlatType platType, CCDictionary *content, C2DXShareResultEvent callback);
};
}
}
#endif /* defined(__C2DXShareSDKSample__C2DXiOSShareSDK__) */
|
{
"pile_set_name": "Github"
}
|
if (UNIX)
# prevent Unknown CMake command "check_function_exists".
include(CheckFunctionExists)
endif()
include(CheckIncludeFile)
include(CheckCSourceCompiles)
include(CheckCSourceRuns)
include(CheckCCompilerFlag)
include(CheckCXXSourceCompiles)
include(CheckCXXCompilerFlag)
include(CMakePushCheckState)
# ---[ If running on Ubuntu, check system version and compiler version.
if(EXISTS "/etc/os-release")
execute_process(COMMAND
"sed" "-ne" "s/^ID=\\([a-z]\\+\\)$/\\1/p" "/etc/os-release"
OUTPUT_VARIABLE OS_RELEASE_ID
OUTPUT_STRIP_TRAILING_WHITESPACE
)
execute_process(COMMAND
"sed" "-ne" "s/^VERSION_ID=\"\\([0-9\\.]\\+\\)\"$/\\1/p" "/etc/os-release"
OUTPUT_VARIABLE OS_RELEASE_VERSION_ID
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(OS_RELEASE_ID STREQUAL "ubuntu")
if(OS_RELEASE_VERSION_ID VERSION_GREATER "17.04")
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS "6.0.0")
message(FATAL_ERROR
"Please use GCC 6 or higher on Ubuntu 17.04 and higher. "
"For more information, see: "
"https://github.com/caffe2/caffe2/issues/1633"
)
endif()
endif()
endif()
endif()
endif()
if (NOT INTERN_BUILD_MOBILE)
# ---[ Check that our programs run. This is different from the native CMake
# compiler check, which just tests if the program compiles and links. This is
# important because with ASAN you might need to help the compiled library find
# some dynamic libraries.
cmake_push_check_state(RESET)
CHECK_C_SOURCE_RUNS("
int main() { return 0; }
" COMPILER_WORKS)
if (NOT COMPILER_WORKS)
# Force cmake to retest next time around
unset(COMPILER_WORKS CACHE)
message(FATAL_ERROR
"Could not run a simple program built with your compiler. "
"If you are trying to use -fsanitize=address, make sure "
"libasan is properly installed on your system (you can confirm "
"if the problem is this by attempting to build and run a "
"small program.)")
endif()
cmake_pop_check_state()
endif()
if (NOT INTERN_BUILD_MOBILE)
# ---[ Check if certain std functions are supported. Sometimes
# _GLIBCXX_USE_C99 macro is not defined and some functions are missing.
cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_FLAGS "-std=c++11")
CHECK_CXX_SOURCE_COMPILES("
#include <cmath>
#include <string>
int main() {
int a = std::isinf(3.0);
int b = std::isnan(0.0);
std::string s = std::to_string(1);
return 0;
}" SUPPORT_GLIBCXX_USE_C99)
if (NOT SUPPORT_GLIBCXX_USE_C99)
# Force cmake to retest next time around
unset(SUPPORT_GLIBCXX_USE_C99 CACHE)
message(FATAL_ERROR
"The C++ compiler does not support required functions. "
"This is very likely due to a known bug in GCC 5 "
"(and maybe other versions) on Ubuntu 17.10 and newer. "
"For more information, see: "
"https://github.com/pytorch/pytorch/issues/5229")
endif()
cmake_pop_check_state()
endif()
# ---[ Check if std::exception_ptr is supported.
cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_FLAGS "-std=c++11")
CHECK_CXX_SOURCE_COMPILES(
"#include <string>
#include <exception>
int main(int argc, char** argv) {
std::exception_ptr eptr;
try {
std::string().at(1);
} catch(...) {
eptr = std::current_exception();
}
}" CAFFE2_EXCEPTION_PTR_SUPPORTED)
if (CAFFE2_EXCEPTION_PTR_SUPPORTED)
message(STATUS "std::exception_ptr is supported.")
set(CAFFE2_USE_EXCEPTION_PTR 1)
else()
message(STATUS "std::exception_ptr is NOT supported.")
endif()
cmake_pop_check_state()
# ---[ Check for NUMA support
if (USE_NUMA)
cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_FLAGS "-std=c++11")
CHECK_CXX_SOURCE_COMPILES(
"#include <numa.h>
#include <numaif.h>
int main(int argc, char** argv) {
}" CAFFE2_IS_NUMA_AVAILABLE)
if (CAFFE2_IS_NUMA_AVAILABLE)
message(STATUS "NUMA is available")
else()
message(STATUS "NUMA is not available")
set(CAFFE2_DISABLE_NUMA 1)
endif()
cmake_pop_check_state()
else()
message(STATUS "NUMA is disabled")
set(CAFFE2_DISABLE_NUMA 1)
endif()
# ---[ Check if we want to turn off deprecated warning due to glog.
# Note(jiayq): on ubuntu 14.04, the default glog install uses ext/hash_set that
# is being deprecated. As a result, we will test if this is the environment we
# are building under. If yes, we will turn off deprecation warning for a
# cleaner build output.
cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_FLAGS "-std=c++11")
CHECK_CXX_SOURCE_COMPILES(
"#include <glog/stl_logging.h>
int main(int argc, char** argv) {
return 0;
}" CAFFE2_NEED_TO_TURN_OFF_DEPRECATION_WARNING
FAIL_REGEX ".*-Wno-deprecated.*")
if(NOT CAFFE2_NEED_TO_TURN_OFF_DEPRECATION_WARNING AND NOT MSVC)
message(STATUS "Turning off deprecation warning due to glog.")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated")
endif()
cmake_pop_check_state()
# ---[ Check if the compiler has AVX/AVX2 support. We only check AVX2.
if (NOT INTERN_BUILD_MOBILE)
cmake_push_check_state(RESET)
if (MSVC)
set(CMAKE_REQUIRED_FLAGS "/arch:AVX2")
else()
set(CMAKE_REQUIRED_FLAGS "-mavx2")
endif()
CHECK_CXX_SOURCE_COMPILES(
"#include <immintrin.h>
int main() {
__m256i a, b;
a = _mm256_set1_epi8 (1);
b = a;
_mm256_add_epi8 (a,a);
__m256i x;
_mm256_extract_epi64(x, 0); // we rely on this in our AVX2 code
return 0;
}" CAFFE2_COMPILER_SUPPORTS_AVX2_EXTENSIONS)
if (CAFFE2_COMPILER_SUPPORTS_AVX2_EXTENSIONS)
message(STATUS "Current compiler supports avx2 extension. Will build perfkernels.")
# Also see CMakeLists.txt under caffe2/perfkernels.
set(CAFFE2_PERF_WITH_AVX 1)
set(CAFFE2_PERF_WITH_AVX2 1)
endif()
cmake_pop_check_state()
endif()
# ---[ Check if the compiler has AVX512 support.
cmake_push_check_state(RESET)
if (MSVC)
# We could've used MSVC's hidden option /arch:AVX512 that defines __AVX512F__,
# __AVX512DQ__, and __AVX512VL__, and /arch:AVX512F that defines __AVX512F__.
# But, we chose not to do that not to rely on hidden options.
set(CMAKE_REQUIRED_FLAGS "/D__AVX512F__ /D__AVX512DQ__ /D__AVX512VL__")
else()
# We only consider the case where all of avx512f, avx512dq, and avx512vl are
# supported.
# Platforms where avx512f is supported by not avx512dq and avx512vl as of
# Jan 15 2019 : linux_manywheel_2.7mu_cpu_build and
# linux_conda_3.7_cu100_build
set(CMAKE_REQUIRED_FLAGS "-mavx512f -mavx512dq -mavx512vl")
endif()
CHECK_CXX_SOURCE_COMPILES(
"#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <immintrin.h>
#endif
// check avx512f
__m512 addConstant(__m512 arg) {
return _mm512_add_ps(arg, _mm512_set1_ps(1.f));
}
// check avx512dq
__m512 andConstant(__m512 arg) {
return _mm512_and_ps(arg, _mm512_set1_ps(1.f));
}
int main() {
__m512i a = _mm512_set1_epi32(1);
__m256i ymm = _mm512_extracti64x4_epi64(a, 0);
ymm = _mm256_abs_epi64(ymm); // check avx512vl
__mmask16 m = _mm512_cmp_epi32_mask(a, a, _MM_CMPINT_EQ);
__m512i r = _mm512_andnot_si512(a, a);
}" CAFFE2_COMPILER_SUPPORTS_AVX512_EXTENSIONS)
if (CAFFE2_COMPILER_SUPPORTS_AVX512_EXTENSIONS)
message(STATUS "Current compiler supports avx512f extension. Will build fbgemm.")
# Also see CMakeLists.txt under caffe2/perfkernels.
set(CAFFE2_PERF_WITH_AVX512 1)
endif()
cmake_pop_check_state()
# ---[ Checks if compiler supports -fvisibility=hidden
check_cxx_compiler_flag("-fvisibility=hidden" COMPILER_SUPPORTS_HIDDEN_VISIBILITY)
check_cxx_compiler_flag("-fvisibility-inlines-hidden" COMPILER_SUPPORTS_HIDDEN_INLINE_VISIBILITY)
if (${COMPILER_SUPPORTS_HIDDEN_INLINE_VISIBILITY})
set(CAFFE2_VISIBILITY_FLAG "-fvisibility-inlines-hidden")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CAFFE2_VISIBILITY_FLAG}")
endif()
# ---[ Checks if linker supports -rdynamic. `-rdynamic` tells linker
# -to add all (including unused) symbols into the dynamic symbol
# -table. We need this to get symbols when generating backtrace at
# -runtime.
check_cxx_compiler_flag("-rdynamic" COMPILER_SUPPORTS_RDYNAMIC)
if (${COMPILER_SUPPORTS_RDYNAMIC})
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -rdynamic")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -rdynamic")
endif()
# ---[ If we are using msvc, set no warning flags
# Note(jiayq): if you are going to add a warning flag, check if this is
# totally necessary, and only add when you see fit. If it is needed due to
# a third party library (like Protobuf), mention it in the comment as
# "THIRD_PARTY_NAME related"
# From https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/
if (${CMAKE_CXX_COMPILER_ID} STREQUAL "MSVC")
add_compile_options(
##########################################
# Protobuf related. Cannot remove.
# This is directly copied from
# https://github.com/google/protobuf/blob/master/cmake/README.md
##########################################
/wd4018 # 'expression' : signed/unsigned mismatch
/wd4065 # (3): switch with default but no case.
/wd4146 # unary minus operator applied to unsigned type, result still unsigned
/wd4244 # Conversion from 'type1' to 'type2', possible loss of data.
/wd4251 # 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2'
/wd4267 # Conversion from 'size_t' to 'type', possible loss of data.
/wd4305 # 'identifier' : truncation from 'type1' to 'type2'
/wd4355 # 'this' : used in base member initializer list
/wd4506 # (1): no definition for inline function. Protobuf related.
/wd4661 # No suitable definition provided for explicit template instantiation request
/wd4800 # 'type' : forcing value to bool 'true' or 'false' (performance warning)
/wd4996 # 'function': was declared deprecated
##########################################
# Third party related. Cannot remove.
##########################################
/wd4141 # (1): inline used twice. google benchmark related.
/wd4503 # (1): decorated name length exceeded, name was truncated.
# Eigen related.
/wd4554 # (3): check operator precedence for possible error.
# Eigen related.
/wd4805 # (1): Unsafe mix of types in gtest/gtest.h. Gtest related.
##########################################
# These are directly ATen related. However, several are covered by
# the above now. We leave them here for documentation purposes only.
#/wd4267 # Conversion from 'size_t' to 'type', possible loss of data.
/wd4522 # (3): 'class' : multiple assignment operators specified
/wd4838 # (1): conversion from 'type_1' to 'type_2' requires a
# narrowing conversion
#/wd4305 # 'identifier' : truncation from 'type1' to 'type2'
#/wd4244 # Conversion from 'type1' to 'type2', possible loss of data.
/wd4190 # (1): 'identifier1' has C-linkage specified, but returns UDT
# 'identifier2' which is incompatible with C
/wd4101 # (3): 'identifier' : unreferenced local variable
#/wd4996 # (3): Use of deprecated POSIX functions. Since we develop
# # mainly on Linux, this is ignored.
/wd4275 # (2): non - DLL-interface classkey 'identifier' used as
# base for DLL-interface classkey 'identifier'
##########################################
# These are directly Caffe2 related. However, several are covered by
# protobuf now. We leave them here for documentation purposes only.
##########################################
#/wd4018 # (3): Signed/unsigned mismatch. We've used it in many places
# # of the code and it would be hard to correct all.
#/wd4244 # (2/3/4): Possible loss of precision. Various cases where we
# # implicitly cast TIndex to int etc. Need cleaning.
#/wd4267 # (3): Conversion of size_t to smaller type. Same as 4244.
#/wd4996 # (3): Use of deprecated POSIX functions. Since we develop
# # mainly on Linux, this is ignored.
/wd4273 # (1): inconsistent dll linkage. This is related to the
# caffe2 FLAGS_* definition using dllimport in header and
# dllexport in cc file. The strategy is copied from gflags.
)
# Make sure windows.h does not include additional headers.
add_definitions("/DWIN32_LEAN_AND_MEAN")
# Make sure windef.h does not define max/min macros.
# Required by ATen among others.
add_definitions("/DNOMINMAX")
set(CMAKE_SHARED_LINKER_FLAGS
"${CMAKE_SHARED_LINKER_FLAGS} /ignore:4049 /ignore:4217")
set(CMAKE_EXE_LINKER_FLAGS
"${CMAKE_EXE_LINKER_FLAGS} /ignore:4049 /ignore:4217")
endif()
# ---[ If we are building on ios, or building with opengl support, we will
# enable -mfpu=neon-fp16 for iOS Metal build. For Android, this fpu setting
# is going to be done with android-cmake by setting
# -DANDROID_ABI="armeabi-v7a with NEON FP16"
# in the build command.
# Also, we will turn off deprecated-declarations
# due to protobuf.
if (IOS)
add_definitions("-mfpu=neon-fp16")
add_definitions("-Wno-deprecated-declarations")
endif()
# ---[ If we use asan, turn on the flags.
# TODO: This only works with new style gcc and clang (not the old -faddress-sanitizer).
# Change if necessary on old platforms.
if (USE_ASAN)
set(CAFFE2_ASAN_FLAG "-fsanitize=address -fPIE -pie")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CAFFE2_ASAN_FLAG}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CAFFE2_ASAN_FLAG}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${CAFFE2_ASAN_FLAG}")
set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${CAFFE2_ASAN_FLAG}")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${CAFFE2_ASAN_FLAG}")
endif()
# ---[ Create CAFFE2_BUILD_SHARED_LIBS for macros.h.in usage.
set(CAFFE2_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS})
if (USE_NATIVE_ARCH)
check_cxx_compiler_flag("-march=native" COMPILER_SUPPORTS_MARCH_NATIVE)
if (COMPILER_SUPPORTS_MARCH_NATIVE)
add_definitions("-march=native")
else()
message(
WARNING
"Your compiler does not support -march=native. Turn off this warning "
"by setting -DUSE_NATIVE_ARCH=OFF.")
endif()
endif()
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "config.h"
#import "WKSessionInternal.h"
#if WK_API_ENABLED
using namespace WebKit;
@implementation WKSession {
API::ObjectStorage<API::Session> _session;
}
- (void)dealloc
{
_session->API::Session::~Session();
[super dealloc];
}
- (bool)ephemeral
{
return _session->isEphemeral();
}
#pragma mark WKObject protocol implementation
- (API::Object&)_apiObject
{
return *_session;
}
@end
#endif // WK_API_ENABLED
|
{
"pile_set_name": "Github"
}
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2015-2020 Zig Contributors
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
/// Deprecated: use `std.io.buffered_writer.BufferedWriter`
pub const BufferedOutStream = @import("./buffered_writer.zig").BufferedWriter;
/// Deprecated: use `std.io.buffered_writer.bufferedWriter`
pub const bufferedOutStream = @import("./buffered_writer.zig").bufferedWriter;
|
{
"pile_set_name": "Github"
}
|
/*!
* ${copyright}
*/
sap.ui.define(["sap/ui/core/library", "sap/ui/core/Renderer", "./ListItemBaseRenderer"],
function(coreLibrary, Renderer, ListItemBaseRenderer) {
"use strict";
// shortcut for sap.ui.core.TextDirection
var TextDirection = coreLibrary.TextDirection;
/**
* DisplayListItem renderer.
* @namespace
*/
var DisplayListItemRenderer = Renderer.extend(ListItemBaseRenderer);
DisplayListItemRenderer.apiVersion = 2;
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager}
* oRenderManager the RenderManager that can be used for writing to the
* Render-Output-Buffer
* @param {sap.ui.core.Control}
* oControl an object representation of the control that should be
* rendered
*/
DisplayListItemRenderer.renderLIAttributes = function(rm, oLI) {
rm.class("sapMDLI");
};
DisplayListItemRenderer.renderLIContent = function(rm, oLI) {
// List item label
var sLabel = oLI.getLabel();
if (sLabel) {
rm.openStart("label");
rm.attr("for", oLI.getId() + "-value");
rm.class("sapMDLILabel");
rm.openEnd();
rm.text(sLabel);
rm.close("label");
}
// List item value
var sValue = oLI.getValue();
if (sValue) {
rm.openStart("div", oLI.getId() + "-value");
rm.class("sapMDLIValue");
var sValueTextDir = oLI.getValueTextDirection();
if (sValueTextDir != TextDirection.Inherit) {
rm.attr("dir", sValueTextDir.toLowerCase());
}
rm.openEnd();
rm.text(sValue);
rm.close("div");
}
};
return DisplayListItemRenderer;
}, /* bExport= */ true);
|
{
"pile_set_name": "Github"
}
|
/*
* The MIT License (MIT)
* Copyright © 2013 Englishtown <opensource@englishtown.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.
*/
package com.englishtown.vertx.jersey;
import io.vertx.core.*;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
/**
* {@link JerseyVerticle} unit tests
*/
public class JerseyVerticleTest {
JerseyVerticle jerseyVerticle;
JsonObject config = new JsonObject();
@Mock
Vertx vertx;
@Mock
Context context;
@Mock
JerseyServer jerseyServer;
@Mock
JerseyOptions options;
@Mock
Future<Void> startedResult;
@Mock
AsyncResult<HttpServer> asyncResult;
@Captor
ArgumentCaptor<Handler<AsyncResult<HttpServer>>> handlerCaptor;
@Rule
public final MockitoRule mockitoRule = MockitoJUnit.rule();
@Before
public void setUp() {
when(vertx.getOrCreateContext()).thenReturn(context);
when(context.config()).thenReturn(config);
jerseyVerticle = new JerseyVerticle(jerseyServer, options);
jerseyVerticle.init(vertx, context);
}
@Test
public void testStart() throws Exception {
jerseyVerticle.start(startedResult);
verify(startedResult, never()).complete();
verify(startedResult, never()).fail(any(Throwable.class));
verify(jerseyServer).start(handlerCaptor.capture());
when(asyncResult.succeeded()).thenReturn(true).thenReturn(false);
handlerCaptor.getValue().handle(asyncResult);
verify(startedResult).complete();
verify(startedResult, never()).fail(any(Throwable.class));
handlerCaptor.getValue().handle(asyncResult);
verify(startedResult).complete();
verify(startedResult).fail(any(Throwable.class));
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="VVVV.System.ComponentModel.Composition.Codeplex" version="2.5.0" targetFramework="net40" />
</packages>
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include "utils_global.h"
#include <qbytearray.h>
#include <qendian.h>
#include <qfile.h>
#include <qvector.h>
#include <qcoreapplication.h>
#include <qsharedpointer.h>
namespace Utils {
class ElfMapper;
enum ElfProgramHeaderType
{
Elf_PT_NULL = 0,
Elf_PT_LOAD = 1,
Elf_PT_DYNAMIC = 2,
Elf_PT_INTERP = 3,
Elf_PT_NOTE = 4,
Elf_PT_SHLIB = 5,
Elf_PT_PHDR = 6,
Elf_PT_TLS = 7,
Elf_PT_NUM = 8
};
enum ElfSectionHeaderType
{
Elf_SHT_NULL = 0,
Elf_SHT_PROGBITS = 1,
Elf_SHT_SYMTAB = 2,
Elf_SHT_STRTAB = 3,
Elf_SHT_RELA = 4,
Elf_SHT_HASH = 5,
Elf_SHT_DYNAMIC = 6,
Elf_SHT_NOTE = 7,
Elf_SHT_NOBITS = 8,
Elf_SHT_REL = 9,
Elf_SHT_SHLIB = 10,
Elf_SHT_DYNSYM = 11,
Elf_SHT_INIT_ARRAY = 14,
Elf_SHT_FINI_ARRAY = 15,
Elf_SHT_PREINIT_ARRAY = 16,
Elf_SHT_GROUP = 17,
Elf_SHT_SYMTAB_SHNDX = 18
};
enum ElfEndian
{
Elf_ELFDATANONE = 0,
Elf_ELFDATA2LSB = 1,
Elf_ELFDATA2MSB = 2,
Elf_ELFDATANUM = 3
};
enum ElfClass
{
Elf_ELFCLASS32 = 1,
Elf_ELFCLASS64 = 2
};
enum ElfType
{
Elf_ET_NONE = 0,
Elf_ET_REL = 1,
Elf_ET_EXEC = 2,
Elf_ET_DYN = 3,
Elf_ET_CORE = 4
};
enum ElfMachine
{
Elf_EM_386 = 3,
Elf_EM_ARM = 40,
Elf_EM_X86_64 = 62
};
enum DebugSymbolsType
{
UnknownSymbols = 0, // Unknown.
NoSymbols = 1, // No usable symbols.
LinkedSymbols = 2, // Link to symols available.
BuildIdSymbols = 4, // BuildId available.
PlainSymbols = 8, // Ordinary symbols available.
FastSymbols = 16 // Dwarf index available.
};
class ElfSectionHeader
{
public:
QByteArray name;
quint32 index;
quint32 type;
quint32 flags;
quint64 offset;
quint64 size;
quint64 addr;
};
class ElfProgramHeader
{
public:
quint32 name;
quint32 type;
quint64 offset;
quint64 filesz;
quint64 memsz;
};
class QTCREATOR_UTILS_EXPORT ElfData
{
public:
ElfData() = default;
int indexOf(const QByteArray &name) const;
public:
ElfEndian endian;
ElfType elftype;
ElfMachine elfmachine;
ElfClass elfclass;
quint64 entryPoint;
QByteArray debugLink;
QByteArray buildId;
DebugSymbolsType symbolsType = UnknownSymbols;
QVector<ElfSectionHeader> sectionHeaders;
QVector<ElfProgramHeader> programHeaders;
};
class QTCREATOR_UTILS_EXPORT ElfReader
{
Q_DECLARE_TR_FUNCTIONS(Utils::ElfReader)
public:
explicit ElfReader(const QString &binary);
enum Result { Ok, NotElf, Corrupt };
ElfData readHeaders();
QSharedPointer<ElfMapper> readSection(const QByteArray §ionName);
QString errorString() const { return m_errorString; }
QByteArray readCoreName(bool *isCore);
private:
friend class ElfMapper;
Result readIt();
QString m_binary;
QString m_errorString;
ElfData m_elfData;
};
class QTCREATOR_UTILS_EXPORT ElfMapper
{
public:
ElfMapper(const ElfReader *reader);
bool map();
public:
QFile file;
QByteArray raw;
union { const char *start; const uchar *ustart; };
quint64 fdlen = 0;
};
} // namespace Utils
|
{
"pile_set_name": "Github"
}
|
using System;
using Xamarin.Forms;
namespace SliderDemo
{
public class App : Application
{
public App()
{
MainPage = new SliderDemoPage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
*/
export function ok(value?: unknown, message?: string) {
if (!value) {
throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
}
}
|
{
"pile_set_name": "Github"
}
|
from sverchok.dependencies import FreeCAD
from sverchok.utils.dummy_nodes import add_dummy
if FreeCAD is None:
add_dummy('SvTransformSolidNode', 'Transform Solid', 'FreeCAD')
else:
import bpy
from bpy.props import FloatProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, match_long_repeat as mlr
from FreeCAD import Base
class SvTransformSolidNode(bpy.types.Node, SverchCustomTreeNode):
"""
Triggers: Apply Matrix to Solid
Tooltip: Transform Solid with Matrix
"""
bl_idname = 'SvTransformSolidNode'
bl_label = 'Transform Solid'
bl_icon = 'MESH_CUBE'
sv_icon = 'SV_TRANSFORM_SOLID'
solid_catergory = "Operators"
precision: FloatProperty(
name="Precision",
default=0.1,
precision=4,
update=updateNode)
def sv_init(self, context):
self.inputs.new('SvSolidSocket', "Solid")
self.inputs.new('SvMatrixSocket', "Matrix")
self.outputs.new('SvSolidSocket', "Solid")
def process(self):
if not any(socket.is_linked for socket in self.outputs):
return
solids_in = self.inputs[0].sv_get()
matrixes = self.inputs[1].sv_get()
solids = []
for solid, matrix in zip(*mlr([solids_in, matrixes])):
mat = Base.Matrix(*[i for v in matrix for i in v])
solid_o = solid.transformGeometry(mat)
solids.append(solid_o)
self.outputs['Solid'].sv_set(solids)
def register():
if FreeCAD is not None:
bpy.utils.register_class(SvTransformSolidNode)
def unregister():
if FreeCAD is not None:
bpy.utils.unregister_class(SvTransformSolidNode)
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package user
// Info describes a user that has been authenticated to the system.
type Info interface {
// GetName returns the name that uniquely identifies this user among all
// other active users.
GetName() string
// GetUID returns a unique value for a particular user that will change
// if the user is removed from the system and another user is added with
// the same name.
GetUID() string
// GetGroups returns the names of the groups the user is a member of
GetGroups() []string
// GetExtra can contain any additional information that the authenticator
// thought was interesting. One example would be scopes on a token.
// Keys in this map should be namespaced to the authenticator or
// authenticator/authorizer pair making use of them.
// For instance: "example.org/foo" instead of "foo"
// This is a map[string][]string because it needs to be serializeable into
// a SubjectAccessReviewSpec.authorization.k8s.io for proper authorization
// delegation flows
// In order to faithfully round-trip through an impersonation flow, these keys
// MUST be lowercase.
GetExtra() map[string][]string
}
// DefaultInfo provides a simple user information exchange object
// for components that implement the UserInfo interface.
type DefaultInfo struct {
Name string
UID string
Groups []string
Extra map[string][]string
}
func (i *DefaultInfo) GetName() string {
return i.Name
}
func (i *DefaultInfo) GetUID() string {
return i.UID
}
func (i *DefaultInfo) GetGroups() []string {
return i.Groups
}
func (i *DefaultInfo) GetExtra() map[string][]string {
return i.Extra
}
// well-known user and group names
const (
SystemPrivilegedGroup = "system:masters"
NodesGroup = "system:nodes"
AllUnauthenticated = "system:unauthenticated"
AllAuthenticated = "system:authenticated"
Anonymous = "system:anonymous"
APIServerUser = "system:apiserver"
// core kubernetes process identities
KubeProxy = "system:kube-proxy"
KubeControllerManager = "system:kube-controller-manager"
KubeScheduler = "system:kube-scheduler"
)
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.ui;
/**
* Top-level interfaces of views.
*/
public interface ViewInterface {
/**
* Get the width of the View object.
*/
int getWidth();
/**
* Get the height of the View object.
*/
int getHeight();
/**
* Reset the view (for next presentation).
*/
void reset();
/**
* Set the visibility of the View object.
*/
void setVisibility(boolean visible);
}
|
{
"pile_set_name": "Github"
}
|
## Process this file with automake to produce Makefile.in
AUTOMAKE_OPTIONS = foreign
INCLUDES = -I$(top_srcdir)/include @OGG_CFLAGS@
check_PROGRAMS = test
check: $(check_PROGRAMS)
./test$(EXEEXT)
test_SOURCES = util.c util.h write_read.c write_read.h test.c
test_LDADD = ../lib/libvorbisenc.la ../lib/libvorbis.la @OGG_LIBS@ @VORBIS_LIBS@
debug:
$(MAKE) check CFLAGS="@DEBUG@"
profile:
$(MAKE) check CFLAGS="@PROFILE@"
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 6 2019 20:12:56).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <AppKit/NSTableCellView.h>
@class NSImageView, NSProgressIndicator, NSTextField;
__attribute__((visibility("hidden")))
@interface _TtC6DVTKit33DVTNavigationPopoverTableCellView : NSTableCellView
{
// Error parsing type: , name: modifierTextField
// Error parsing type: , name: progressIndicator
// Error parsing type: , name: chevronImageView
// Error parsing type: , name: rowView
// Error parsing type: , name: icon
// Error parsing type: , name: tintedIcon
// Error parsing type: , name: isEnabled
// Error parsing type: , name: backgroundVisualEffectView
// Error parsing type: , name: isSelected
// Error parsing type: , name: requiresMoreTime
}
- (void).cxx_destruct;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
- (void)viewDidMoveToSuperview;
- (void)awakeFromNib;
@property(nonatomic, retain) NSImageView *chevronImageView; // @synthesize chevronImageView;
@property(nonatomic, retain) NSProgressIndicator *progressIndicator; // @synthesize progressIndicator;
@property(nonatomic, retain) NSTextField *modifierTextField; // @synthesize modifierTextField;
@end
|
{
"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><link rel="apple-touch-icon" sizes="180x180" href="/glide/apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="/glide/favicon-32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="/glide/favicon-16x16.png"><link rel="manifest" href="/glide/manifest.json">
<!-- Generated by javadoc (1.8.0_144) on Fri Jan 05 11:09:29 PST 2018 -->
<title>com.bumptech.glide.integration.volley (glide API)</title>
<meta name="date" content="2018-01-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../com/bumptech/glide/integration/volley/package-summary.html" target="classFrame">com.bumptech.glide.integration.volley</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="VolleyRequestFactory.html" title="interface in com.bumptech.glide.integration.volley" target="classFrame"><span class="interfaceName">VolleyRequestFactory</span></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="VolleyGlideModule.html" title="class in com.bumptech.glide.integration.volley" target="classFrame">VolleyGlideModule</a></li>
<li><a href="VolleyLibraryGlideModule.html" title="class in com.bumptech.glide.integration.volley" target="classFrame">VolleyLibraryGlideModule</a></li>
<li><a href="VolleyStreamFetcher.html" title="class in com.bumptech.glide.integration.volley" target="classFrame">VolleyStreamFetcher</a></li>
<li><a href="VolleyStreamFetcher.GlideRequest.html" title="class in com.bumptech.glide.integration.volley" target="classFrame">VolleyStreamFetcher.GlideRequest</a></li>
<li><a href="VolleyUrlLoader.html" title="class in com.bumptech.glide.integration.volley" target="classFrame">VolleyUrlLoader</a></li>
<li><a href="VolleyUrlLoader.Factory.html" title="class in com.bumptech.glide.integration.volley" target="classFrame">VolleyUrlLoader.Factory</a></li>
</ul>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/* AUTOGENERATED SOURCE FILE */
#include "../../../firmware/applications/inputtest.c"
|
{
"pile_set_name": "Github"
}
|
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta name="description" content="Flat, Clean, Responsive, application admin template built with bootstrap 3">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Sublime - Web Application Admin Dashboard</title>
<script type="text/javascript">
//<![CDATA[
try{if (!window.CloudFlare) {var CloudFlare=[{verbose:0,p:0,byc:0,owlid:"cf",bag2:1,mirage2:0,oracle:0,paths:{cloudflare:"/cdn-cgi/nexp/dok3v=1613a3a185/"},atok:"1d2df93451ee996cf6eb54afb112e6f6",petok:"4f0a1056def8cea7d68d2579318c2bfc1d62551c-1433395976-1800",zone:"nyasha.me",rocket:"0",apps:{"ga_key":{"ua":"UA-50530436-1","ga_bs":"2"}}}];CloudFlare.push({"apps":{"ape":"471e17e1e42d5aa307edb57070f39a81"}});!function(a,b){a=document.createElement("script"),b=document.getElementsByTagName("script")[0],a.async=!0,a.src="//ajax.cloudflare.com/cdn-cgi/nexp/dok3v=7e13c32551/cloudflare.min.js",b.parentNode.insertBefore(a,b)}()}}catch(e){};
//]]>
</script>
<link rel="stylesheet" href="plugins/chosen/chosen.min.css">
<link rel="stylesheet" href="plugins/datatables/jquery.dataTables.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.css">
<link rel="stylesheet" href="css/themify-icons.css">
<link rel="stylesheet" href="css/animate.min.css">
<link rel="stylesheet" href="css/skins/palette.css">
<link rel="stylesheet" href="css/fonts/font.css">
<link rel="stylesheet" href="css/main.css">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<script src="plugins/modernizr.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-50530436-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
(function(b){(function(a){"__CF"in b&&"DJS"in b.__CF?b.__CF.DJS.push(a):"addEventListener"in b?b.addEventListener("load",a,!1):b.attachEvent("onload",a)})(function(){"FB"in b&&"Event"in FB&&"subscribe"in FB.Event&&(FB.Event.subscribe("edge.create",function(a){_gaq.push(["_trackSocial","facebook","like",a])}),FB.Event.subscribe("edge.remove",function(a){_gaq.push(["_trackSocial","facebook","unlike",a])}),FB.Event.subscribe("message.send",function(a){_gaq.push(["_trackSocial","facebook","send",a])}));"twttr"in b&&"events"in twttr&&"bind"in twttr.events&&twttr.events.bind("tweet",function(a){if(a){var b;if(a.target&&a.target.nodeName=="IFRAME")a:{if(a=a.target.src){a=a.split("#")[0].match(/[^?=&]+=([^&]*)?/g);b=0;for(var c;c=a[b];++b)if(c.indexOf("url")===0){b=unescape(c.split("=")[1]);break a}}b=void 0}_gaq.push(["_trackSocial","twitter","tweet",b])}})})})(window);
/* ]]> */
</script>
</head>
<body>
<div class="app">
<header class="header header-fixed navbar">
<div class="brand">
<a href="javascript:;" class="ti-menu off-left visible-xs" data-toggle="offscreen" data-move="ltr"></a>
<a href="index.html" class="navbar-brand">
<img src="img/logo.png" alt="">
<span class="heading-font">
Sublime
</span>
</a>
</div>
<ul class="nav navbar-nav">
<li class="hidden-xs">
<a href="javascript:;" class="toggle-sidebar">
<i class="ti-menu"></i>
</a>
</li>
<li class="header-search">
<a href="javascript:;" class="toggle-search">
<i class="ti-search"></i>
</a>
<div class="search-container">
<form role="search">
<input type="text" class="form-control search" placeholder="type and press enter">
</form>
</div>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown hidden-xs">
<a href="javascript:;" data-toggle="dropdown">
<i class="ti-more-alt"></i>
</a>
<ul class="dropdown-menu animated zoomIn">
<li class="dropdown-header">Quick Links</li>
<li>
<a href="javascript:;">Start New Campaign</a>
</li>
<li>
<a href="javascript:;">Review Campaigns</a>
</li>
<li class="divider"></li>
<li>
<a href="javascript:;">Settings</a>
</li>
<li>
<a href="javascript:;">Wish List</a>
</li>
<li>
<a href="javascript:;">Purchases History</a>
</li>
<li class="divider"></li>
<li>
<a href="javascript:;">Activity Log</a>
</li>
<li>
<a href="javascript:;">Settings</a>
</li>
<li>
<a href="javascript:;">System Reports</a>
</li>
<li class="divider"></li>
<li>
<a href="javascript:;">Help</a>
</li>
<li>
<a href="javascript:;">Report a Problem</a>
</li>
</ul>
</li>
<li class="notifications dropdown">
<a href="javascript:;" data-toggle="dropdown">
<i class="ti-bell"></i>
<div class="badge badge-top bg-danger animated flash">
<span>3</span>
</div>
</a>
<div class="dropdown-menu animated fadeInLeft">
<div class="panel panel-default no-m">
<div class="panel-heading small"><b>Notifications</b>
</div>
<ul class="list-group">
<li class="list-group-item">
<a href="javascript:;">
<span class="pull-left mt5 mr15">
<img src="img/face4.jpg" class="avatar avatar-sm img-circle" alt="">
</span>
<div class="m-body">
<div class="">
<small><b>CRYSTAL BROWN</b></small>
<span class="label label-danger pull-right">ASSIGN AGENT</span>
</div>
<span>Opened a support query</span>
<span class="time small">2 mins ago</span>
</div>
</a>
</li>
<li class="list-group-item">
<a href="javascript:;">
<div class="pull-left mt5 mr15">
<div class="circle-icon bg-danger">
<i class="ti-download"></i>
</div>
</div>
<div class="m-body">
<span>Upload Progress</span>
<div class="progress progress-xs mt5 mb5">
<div class="progress-bar" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
</div>
</div>
<span class="time small">Submited 23 mins ago</span>
</div>
</a>
</li>
<li class="list-group-item">
<a href="javascript:;">
<span class="pull-left mt5 mr15">
<img src="img/face3.jpg" class="avatar avatar-sm img-circle" alt="">
</span>
<div class="m-body">
<em>Status Update:</em>
<span>All servers now online</span>
<span class="time small">5 days ago</span>
</div>
</a>
</li>
</ul>
<div class="panel-footer">
<a href="javascript:;">See all notifications</a>
</div>
</div>
</div>
</li>
<li class="off-right">
<a href="javascript:;" data-toggle="dropdown">
<img src="img/avatar.jpg" class="header-avatar img-circle" alt="user" title="user">
<span class="hidden-xs ml10">Gerald Morris</span>
<i class="ti-angle-down ti-caret hidden-xs"></i>
</a>
<ul class="dropdown-menu animated fadeInRight">
<li>
<a href="javascript:;">Settings</a>
</li>
<li>
<a href="javascript:;">Upgrade</a>
</li>
<li>
<a href="javascript:;">
<div class="badge bg-danger pull-right">3</div>
<span>Notifications</span>
</a>
</li>
<li>
<a href="javascript:;">Help</a>
</li>
<li>
<a href="signin.html">Logout</a>
</li>
</ul>
</li>
</ul>
</header>
<section class="layout">
<aside class="sidebar offscreen-left">
<nav class="main-navigation" data-height="auto" data-size="6px" data-distance="0" data-rail-visible="true" data-wheel-step="10">
<p class="nav-title">MENU</p>
<ul class="nav">
<li>
<a href="index.html">
<i class="ti-home"></i>
<span>Dashboard</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<i class="ti-layout-media-overlay-alt-2"></i>
<span>UI Elements</span>
</a>
<ul class="sub-menu">
<li>
<a href="buttons.html">
<span>Buttons</span>
</a>
</li>
<li>
<a href="general.html">
<span>General Elements</span>
</a>
</li>
<li>
<a href="typography.html">
<span>Typography</span>
</a>
</li>
<li>
<a href="tabs_accordion.html">
<span>Tabs & Accordions</span>
</a>
</li>
<li>
<a href="icons.html">
<span>Fontawesome</span>
</a>
</li>
<li>
<a href="themify_icons.html">
<span>Themify Icons</span>
</a>
</li>
<li>
<a href="grid.html">
<span>Grid Layout</span>
</a>
</li>
<li>
<a href="widgets.html">
<span>Widgets</span>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<i class="ti-support"></i>
<span>Components</span>
</a>
<ul class="sub-menu">
<li>
<a href="calendar.html">
<span>Calendar</span>
</a>
</li>
<li>
<a href="gallery.html">
<span>Gallery</span>
</a>
</li>
<li>
<a href="sortable.html">
<span>Sortable & Nestable Lists</span>
</a>
</li>
<li>
<a href="chart.html">
<span>Charts</span>
</a>
</li>
<li>
<a href="progress_slider.html">
<span>Progress bars & Sliders</span>
</a>
</li>
<li>
<a href="tree.html">
<span>Tree View</span>
</a>
</li>
<li>
<a href="notifications.html">
<span>Notifications</span>
</a>
</li>
<li>
<a href="animated.html">
<span>Animated Elements</span>
</a>
</li>
<li>
<a href="tour.html">
<span>Tour</span>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<i class="ti-folder"></i>
<span>Forms</span>
</a>
<ul class="sub-menu">
<li>
<a href="forms.html">
<span>Forms Elements</span>
</a>
</li>
<li>
<a href="form_custom.html">
<span>Customized Elements</span>
</a>
</li>
<li>
<a href="form_validation.html">
<span>Form Validation</span>
</a>
</li>
<li>
<a href="form_wizard.html">
<span>Form Wizards</span>
</a>
</li>
<li>
<a href="form_wysiwyg.html">
<span>WYSIWYG/Markdown Editors</span>
</a>
</li>
<li>
<a href="form_inline.html">
<span>Content Editable</span>
</a>
</li>
<li>
<a href="form_dropzone.html">
<span>Dropzone</span>
</a>
</li>
<li>
<a href="xeditable.html">
<span>X-Editable</span>
</a>
</li>
<li>
<a href="form_masks.html">
<span>Input Masks</span>
</a>
</li>
<li>
<a href="form_pickers.html">
<span>Form Pickers</span>
</a>
</li>
<li>
<a href="form_crop.html">
<span>Image Crop</span>
</a>
</li>
</ul>
</li>
<li class="open">
<a href="javascript:;">
<i class="toggle-accordion"></i>
<i class="ti-window"></i>
<span>Tables</span>
</a>
<ul class="sub-menu">
<li>
<a href="table_basic.html">
<span>Basic Tables</span>
</a>
</li>
<li>
<a href="table_responsive.html">
<span>Resonsive Table</span>
</a>
</li>
<li class="active">
<a href="datatable.html">
<span>Data Tables</span>
</a>
</li>
<li>
<a href="table_editable.html">
<span>Editable Table</span>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<i class="ti-map"></i>
<span>Maps</span>
</a>
<ul class="sub-menu">
<li>
<a href="google_maps.html">
<span>Google Maps</span>
</a>
</li>
<li>
<a href="vector.html">
<span>Vector Maps</span>
</a>
</li>
</ul>
</li>
</ul>
<p class="nav-title">MORE</p>
<ul class="nav">
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<i class="ti-layers"></i>
<span>Ready Pages</span>
</a>
<ul class="sub-menu">
<li>
<a href="mail.html">
<span>Mailbox</span>
</a>
</li>
<li>
<a href="mail_view.html">
<span>Mail View</span>
</a>
</li>
<li>
<a href="compose.html">
<span>Compose</span>
</a>
</li>
<li>
<a href="profile.html">
<span>Profile</span>
</a>
</li>
<li>
<a href="invoice.html">
<span>Invoice</span>
</a>
</li>
<li>
<a href="signin.html">
<span>Signin</span>
</a>
</li>
<li>
<a href="signup.html">
<span>Signup</span>
</a>
</li>
<li>
<a href="forgot.html">
<span>Forgot Password</span>
</a>
</li>
<li>
<a href="lock.html">
<span>Lock Screen</span>
</a>
</li>
<li>
<a href="404.html">
<span>404 Page</span>
</a>
</li>
<li>
<a href="500.html">
<span>500 Page</span>
</a>
</li>
<li>
<a href="changelog.html">
<span class="pull-right small label label-danger">Updated</span>
<span>Change Log</span>
</a>
</li>
<li>
<a href="timeline.html">
<span>Timeline</span>
</a>
</li>
<li>
<a href="catalog.html">
<span>Catalog</span>
</a>
</li>
<li>
<a href="chat.html">
<span>Chat</span>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<i class="ti-layout"></i>
<span>Layouts</span>
</a>
<ul class="sub-menu">
<li>
<a href="small_menu.html">
<span>Small Menu</span>
</a>
</li>
<li>
<a href="right_menu.html">
<span>Right Side Menu</span>
</a>
</li>
<li>
<a href="push_sidebar.html">
<span>Chat Sidebar</span>
</a>
</li>
<li>
<a href="language_bar.html">
<span>Language Switcher</span>
</a>
</li>
<li>
<a href="footer_layout.html">
<span>Layout With Footer</span>
</a>
</li>
<li>
<a href="horizontal_menu.html">
<span>Horizontal Menu</span>
</a>
</li>
<li>
<a href="boxed.html">
<span>Boxed Layout</span>
</a>
</li>
<li>
<a href="horizontal_menu_boxed.html">
<span>Horizontal Boxed</span>
</a>
</li>
<li>
<a href="fixed_scroll.html">
<span>Fixed Header & Scrollable Layout</span>
</a>
</li>
<li>
<a href="blank.html">
<span>Blank Page</span>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<i class="ti-menu-alt"></i>
<span>Multi Level Menu</span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<span>Menu Link 1</span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<span>Menu Link 1.1</span>
</a>
</li>
<li>
<a href="javascript:;">
<span>Menu Link 1.2</span>
</a>
</li>
<li>
<a href="javascript:;">
<span>Menu Link 1.3</span>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="toggle-accordion"></i>
<span>Menu Link 2</span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<span>Menu Link 2.1</span>
</a>
</li>
<li>
<a href="javascript:;">
<span>Menu Link 2.2</span>
</a>
</li>
<li>
<a href="javascript:;">
<span>Menu Link 2.3</span>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<span>Menu Link 3</span>
</a>
</li>
</ul>
</li>
<li>
<a href="http://sublime.nyasha.me/frontend">
<i class="ti-layout-media-center"></i>
<span>Frontend Template</span>
</a>
</li>
</ul>
<p class="nav-title">LABELS</p>
<ul class="nav">
<li>
<a href="javascript:;">
<i class="ti-control-record text-warning"></i>
<span>Projects</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="ti-control-record text-success"></i>
<span>Apps</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="ti-control-record text-danger"></i>
<span>Support</span>
</a>
</li>
</ul>
</nav>
</aside>
<section class="main-content">
<div class="content-wrap">
<div class="wrapper">
<section class="panel panel-default">
<header class="panel-heading">
<h5>Data Tables</h5>
</header>
<div class="panel-body">
<div class="table-responsive no-border">
<table class="table table-bordered table-striped mg-t datatable">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start Date</th>
</tr>
</thead>
</table>
</div>
</div>
</section>
</div>
</div>
<a class="exit-offscreen"></a>
</section>
</section>
</div>
<script src="plugins/jquery-1.11.1.min.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
<script src="plugins/jquery.slimscroll.min.js"></script>
<script src="plugins/jquery.easing.min.js"></script>
<script src="plugins/appear/jquery.appear.js"></script>
<script src="plugins/jquery.placeholder.js"></script>
<script src="plugins/fastclick.js"></script>
<script src="plugins/chosen/chosen.jquery.min.js"></script>
<script src="plugins/datatables/jquery.dataTables.js"></script>
<script src="js/offscreen.js"></script>
<script src="js/main.js"></script>
<script src="js/bootstrap-datatables.js"></script>
<script src="js/datatables.js"></script>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.commons.test.db;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.eclipse.che.commons.test.tck.JpaCleaner;
import org.h2.tools.RunScript;
/** @author Yevhenii Voevodin */
public class H2JpaCleaner extends JpaCleaner {
private final DataSource dataSource;
private H2DBTestServer server;
public H2JpaCleaner(H2DBTestServer server) {
this(server.getDataSource());
this.server = server;
}
public H2JpaCleaner(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void clean() {
super.clean();
if (server != null) {
server.shutdown();
} else {
try (Connection conn = dataSource.getConnection()) {
RunScript.execute(conn, new StringReader("SHUTDOWN"));
} catch (SQLException x) {
throw new RuntimeException(x.getMessage(), x);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Diagnostics.ContractsLight;
using BuildXL.Utilities;
namespace BuildXL.Pips.DirectedGraph
{
internal delegate bool VisitNode(NodeId node);
/// <summary>
/// Encapsulates transitive visitation functions against a graph
/// </summary>
internal sealed class NodeVisitor
{
private readonly IReadonlyDirectedGraph m_dataflowGraph;
private readonly ObjectPool<Queue<NodeId>> m_nodeQueuePool = new ObjectPool<Queue<NodeId>>(() => new Queue<NodeId>(), queue => queue.Clear());
/// <summary>
/// Creates a new node visitor
/// </summary>
/// <param name="dataflowGraph">the dataflow graph</param>
public NodeVisitor(IReadonlyDirectedGraph dataflowGraph)
{
m_dataflowGraph = dataflowGraph;
}
/// <summary>
/// Visits the transitive reachable nodes of the given nodes
/// </summary>
public void VisitTransitiveReachableNodes(
IEnumerable<NodeId> startNodes,
VisitationTracker visitedNodes,
VisitNode visitNodeDependencies,
VisitNode visitNodeDependents)
{
using (var queueWrapper = m_nodeQueuePool.GetInstance())
{
var queue = queueWrapper.Instance;
AddIfNotVisited(queue, startNodes, visitedNodes);
VisitTransitiveClosure(
queue,
visitedNodes,
visitNodeDependencies: visitNodeDependencies,
visitNodeDependents: visitNodeDependents,
dependencies: true,
dependents: true);
}
}
/// <summary>
/// Visits the transitive dependencies of the nodes
/// </summary>
public void VisitTransitiveDependencies(
IEnumerable<NodeId> startNodes,
VisitationTracker visitedNodes,
VisitNode visitNode)
{
using (var queueWrapper = m_nodeQueuePool.GetInstance())
{
var queue = queueWrapper.Instance;
AddIfNotVisited(queue, startNodes, visitedNodes);
VisitTransitiveClosure(
queue,
visitedNodes,
visitNodeDependents: null,
visitNodeDependencies: visitNode,
dependencies: true,
dependents: false);
}
}
/// <summary>
/// Visits the transitive dependencies of the node
/// </summary>
public void VisitTransitiveDependencies(
NodeId startNode,
VisitationTracker visitedNodes,
VisitNode visitNode)
{
using (var queueWrapper = m_nodeQueuePool.GetInstance())
{
var queue = queueWrapper.Instance;
AddIfNotVisited(queue, startNode, visitedNodes);
VisitTransitiveClosure(
queue,
visitedNodes,
visitNodeDependents: null,
visitNodeDependencies: visitNode,
dependencies: true,
dependents: false);
}
}
/// <summary>
/// Visits the transitive dependents of the nodes
/// </summary>
public void VisitTransitiveDependents(
IEnumerable<NodeId> startNodes,
VisitationTracker visitedNodes,
VisitNode visitNode)
{
using (var queueWrapper = m_nodeQueuePool.GetInstance())
{
var queue = queueWrapper.Instance;
AddIfNotVisited(queue, startNodes, visitedNodes);
VisitTransitiveClosure(
queue,
visitedNodes,
visitNodeDependents: visitNode,
visitNodeDependencies: null,
dependencies: false,
dependents: true);
}
}
/// <summary>
/// Visits the transitive dependents of the node
/// </summary>
public void VisitTransitiveDependents(
NodeId startNode,
VisitationTracker visitedNodes,
VisitNode visitNode)
{
using (var queueWrapper = m_nodeQueuePool.GetInstance())
{
var queue = queueWrapper.Instance;
AddIfNotVisited(queue, startNode, visitedNodes);
VisitTransitiveClosure(
queue,
visitedNodes,
visitNodeDependents: visitNode,
visitNodeDependencies: null,
dependencies: false,
dependents: true);
}
}
private static void AddIfNotVisited(Queue<NodeId> queue, NodeId node, VisitationTracker visitedNodes)
{
if (visitedNodes.MarkVisited(node))
{
queue.Enqueue(node);
}
}
private static void AddIfNotVisited(Queue<NodeId> queue, IEnumerable<NodeId> nodes, VisitationTracker visitedNodes)
{
foreach (var node in nodes)
{
if (visitedNodes.MarkVisited(node))
{
queue.Enqueue(node);
}
}
}
private void VisitTransitiveClosure(
Queue<NodeId> queue,
VisitationTracker visitedNodes,
VisitNode visitNodeDependencies,
VisitNode visitNodeDependents,
bool dependencies,
bool dependents)
{
Contract.Assert(visitNodeDependencies == null || dependencies);
Contract.Assert(visitNodeDependents == null || dependents);
while (queue.Count != 0)
{
var node = queue.Dequeue();
if (dependencies)
{
if (visitNodeDependencies == null || visitNodeDependencies(node))
{
foreach (Edge inEdge in m_dataflowGraph.GetIncomingEdges(node))
{
if (visitedNodes.MarkVisited(inEdge.OtherNode))
{
queue.Enqueue(inEdge.OtherNode);
}
}
}
}
if (dependents)
{
if (visitNodeDependents == null || visitNodeDependents(node))
{
foreach (Edge outEdge in m_dataflowGraph.GetOutgoingEdges(node))
{
if (visitedNodes.MarkVisited(outEdge.OtherNode))
{
queue.Enqueue(outEdge.OtherNode);
}
}
}
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: exercise_samples.proto
// This CPP symbol can be defined to use imports that match up to the framework
// imports needed when using CocoaPods.
#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
#define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
#import <Protobuf/GPBProtocolBuffers.h>
#else
#import "google/GPBProtocolBuffers.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CF_EXTERN_C_BEGIN
@class PbCalibrationValue;
@class PbDuration;
@class PbExerciseIntervalledSampleList;
@class PbExerciseRRIntervals;
@class PbPauseTime;
@class PbPowerMeasurements;
@class PbSampleSource;
@class PbSensorOffline;
GPB_ENUM_FWD_DECLARE(PbMovingType);
GPB_ENUM_FWD_DECLARE(PbOperationType);
GPB_ENUM_FWD_DECLARE(PbSampleType);
NS_ASSUME_NONNULL_BEGIN
#pragma mark - ExerciseSamplesRoot
/**
* Exposes the extension registry for this file.
*
* The base class provides:
* @code
* + (GPBExtensionRegistry *)extensionRegistry;
* @endcode
* which is a @c GPBExtensionRegistry that includes all the extensions defined by
* this file and all files that it depends on.
**/
@interface ExerciseSamplesRoot : GPBRootObject
@end
#pragma mark - PbPowerMeasurements
typedef GPB_ENUM(PbPowerMeasurements_FieldNumber) {
PbPowerMeasurements_FieldNumber_CurrentPower = 1,
PbPowerMeasurements_FieldNumber_CumulativeCrankRevolutions = 2,
PbPowerMeasurements_FieldNumber_CumulativeTimestamp = 3,
PbPowerMeasurements_FieldNumber_ForceMagnitudeMin = 4,
PbPowerMeasurements_FieldNumber_ForceMagnitudeMax = 5,
PbPowerMeasurements_FieldNumber_ForceMagnitudeMinAngle = 6,
PbPowerMeasurements_FieldNumber_ForceMagnitudeMaxAngle = 7,
PbPowerMeasurements_FieldNumber_BottomDeadSpotAngle = 8,
PbPowerMeasurements_FieldNumber_TopDeadSpotAngle = 9,
PbPowerMeasurements_FieldNumber_PedalPowerBalance = 10,
PbPowerMeasurements_FieldNumber_TorqueMagnitudeMin = 11,
PbPowerMeasurements_FieldNumber_TorqueMagnitudeMax = 12,
};
/**
*
* Power data from crank based power sensors
* See: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.cycling_power_measurement.xml
**/
@interface PbPowerMeasurements : GPBMessage
/** Instantaneous power */
@property(nonatomic, readwrite) int32_t currentPower;
@property(nonatomic, readwrite) BOOL hasCurrentPower;
/**
* Cumulative crank revolutions starting from the first stored sample data
* This is originally overflowing 16 bit unsigned int value
* This value do not necessarily change for every vector data set
* This value is not necessarily provided for every vector data set
**/
@property(nonatomic, readwrite) uint32_t cumulativeCrankRevolutions;
@property(nonatomic, readwrite) BOOL hasCumulativeCrankRevolutions;
/**
* Cumulative timestamp in milliseconds starting from the first stored sample data
* Originally overflowing uint16 value, [1/1024 of second]
* This value do not necessarily change for every vector data set
* This value is not necessarily provided for every vector data set
**/
@property(nonatomic, readwrite) uint32_t cumulativeTimestamp;
@property(nonatomic, readwrite) BOOL hasCumulativeTimestamp;
/** Minimum force magnitude power */
@property(nonatomic, readwrite) int32_t forceMagnitudeMin;
@property(nonatomic, readwrite) BOOL hasForceMagnitudeMin;
/** Maximum force magnitude power */
@property(nonatomic, readwrite) int32_t forceMagnitudeMax;
@property(nonatomic, readwrite) BOOL hasForceMagnitudeMax;
/**
* Minimum force magnitude angle
* Counted clockwise, topmost position is 0 degrees, view point is right side of the bike for both pedals
**/
@property(nonatomic, readwrite) uint32_t forceMagnitudeMinAngle;
@property(nonatomic, readwrite) BOOL hasForceMagnitudeMinAngle;
/**
* Maximum force magnitude angle
* Counted clockwise, topmost position is 0 degrees, view point is right side of the bike for both pedals
**/
@property(nonatomic, readwrite) uint32_t forceMagnitudeMaxAngle;
@property(nonatomic, readwrite) BOOL hasForceMagnitudeMaxAngle;
/**
* Dead spot bottom angle
* Counted clockwise, topmost position is 0 degrees, view point is right side of the bike for both pedals
**/
@property(nonatomic, readwrite) uint32_t bottomDeadSpotAngle;
@property(nonatomic, readwrite) BOOL hasBottomDeadSpotAngle;
/**
* Dead spot top angle
* Counted clockwise, topmost position is 0 degrees, view point is right side of the bike for both pedals
**/
@property(nonatomic, readwrite) uint32_t topDeadSpotAngle;
@property(nonatomic, readwrite) BOOL hasTopDeadSpotAngle;
/**
* Unit is in percentage with a resolution of 1/2. Left foot power percentage of total power.
* pedal_power_balance = [LeftPower/(LeftPower + RightPower)]*100
**/
@property(nonatomic, readwrite) uint32_t pedalPowerBalance;
@property(nonatomic, readwrite) BOOL hasPedalPowerBalance;
/** Unit is in newton metres with a resolution of 1/32. */
@property(nonatomic, readwrite) int32_t torqueMagnitudeMin;
@property(nonatomic, readwrite) BOOL hasTorqueMagnitudeMin;
/** Unit is in newton metres with a resolution of 1/32. */
@property(nonatomic, readwrite) int32_t torqueMagnitudeMax;
@property(nonatomic, readwrite) BOOL hasTorqueMagnitudeMax;
@end
#pragma mark - PbCalibrationValue
typedef GPB_ENUM(PbCalibrationValue_FieldNumber) {
PbCalibrationValue_FieldNumber_StartIndex = 1,
PbCalibrationValue_FieldNumber_Value = 2,
PbCalibrationValue_FieldNumber_Operation = 3,
PbCalibrationValue_FieldNumber_Cause = 4,
};
/**
*
* Sample data calibration value of the exercise
**/
@interface PbCalibrationValue : GPBMessage
/** index of first sample using calibration value "value" */
@property(nonatomic, readwrite) uint32_t startIndex;
@property(nonatomic, readwrite) BOOL hasStartIndex;
/** used calibaration value */
@property(nonatomic, readwrite) float value;
@property(nonatomic, readwrite) BOOL hasValue;
/** used operation type of calibration (multiply/sum) */
@property(nonatomic, readwrite) enum PbOperationType operation;
@property(nonatomic, readwrite) BOOL hasOperation;
/** explaines the cause for calibration change (walking/running) */
@property(nonatomic, readwrite) enum PbMovingType cause;
@property(nonatomic, readwrite) BOOL hasCause;
@end
#pragma mark - PbExerciseIntervalledSampleList
typedef GPB_ENUM(PbExerciseIntervalledSampleList_FieldNumber) {
PbExerciseIntervalledSampleList_FieldNumber_SampleType = 1,
PbExerciseIntervalledSampleList_FieldNumber_RecordingIntervalMs = 2,
PbExerciseIntervalledSampleList_FieldNumber_SampleSourceArray = 3,
PbExerciseIntervalledSampleList_FieldNumber_HeartRateSamplesArray = 4,
PbExerciseIntervalledSampleList_FieldNumber_CadenceSamplesArray = 5,
PbExerciseIntervalledSampleList_FieldNumber_SpeedSamplesArray = 6,
PbExerciseIntervalledSampleList_FieldNumber_DistanceSamplesArray = 7,
PbExerciseIntervalledSampleList_FieldNumber_ForwardAccelerationArray = 8,
PbExerciseIntervalledSampleList_FieldNumber_MovingTypeSamplesArray = 9,
PbExerciseIntervalledSampleList_FieldNumber_AltitudeSamplesArray = 10,
PbExerciseIntervalledSampleList_FieldNumber_AltitudeCalibrationArray = 11,
PbExerciseIntervalledSampleList_FieldNumber_TemperatureSamplesArray = 12,
PbExerciseIntervalledSampleList_FieldNumber_StrideLengthSamplesArray = 13,
PbExerciseIntervalledSampleList_FieldNumber_StrideCalibrationArray = 14,
PbExerciseIntervalledSampleList_FieldNumber_LeftPedalPowerSamplesArray = 15,
PbExerciseIntervalledSampleList_FieldNumber_RightPedalPowerSamplesArray = 16,
PbExerciseIntervalledSampleList_FieldNumber_LeftPowerCalibrationArray = 17,
PbExerciseIntervalledSampleList_FieldNumber_RightPowerCalibrationArray = 18,
PbExerciseIntervalledSampleList_FieldNumber_RrSamples = 19,
PbExerciseIntervalledSampleList_FieldNumber_AccelerationMadSamplesArray = 20,
};
/**
*
* Exercise samples with sample type specific recording intervals
**/
@interface PbExerciseIntervalledSampleList : GPBMessage
/** Sample Type, SPEED, DISTANCE etc. */
@property(nonatomic, readwrite) enum PbSampleType sampleType;
@property(nonatomic, readwrite) BOOL hasSampleType;
/**
* Recording interval of samples in milliseconds
* Note: When this field is set, it will override the default recording interval
* (PbDuration recording_interval) given in the PbExerciseSamples message
**/
@property(nonatomic, readwrite) uint32_t recordingIntervalMs;
@property(nonatomic, readwrite) BOOL hasRecordingIntervalMs;
/** Indicates the source of certain sample: source and start / stop indexes for the given source */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSampleSource*> *sampleSourceArray;
/** The number of items in @c sampleSourceArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger sampleSourceArray_Count;
/** heart rate samples */
@property(nonatomic, readwrite, strong, null_resettable) GPBUInt32Array *heartRateSamplesArray;
/** The number of items in @c heartRateSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger heartRateSamplesArray_Count;
/** cadence samples */
@property(nonatomic, readwrite, strong, null_resettable) GPBUInt32Array *cadenceSamplesArray;
/** The number of items in @c cadenceSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger cadenceSamplesArray_Count;
/**
* speed samples
* Note: Samples are already calibrated samples
**/
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *speedSamplesArray;
/** The number of items in @c speedSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger speedSamplesArray_Count;
/**
* distance samples: total distance from the beginning of the exercise
* Note: Samples are already calibrated samples
**/
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *distanceSamplesArray;
/** The number of items in @c distanceSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger distanceSamplesArray_Count;
/** User 1d acceleration samples as m/s2 */
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *forwardAccelerationArray;
/** The number of items in @c forwardAccelerationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger forwardAccelerationArray_Count;
/** User walking/running/standing status samples */
// |movingTypeSamplesArray| contains |PbMovingType|
@property(nonatomic, readwrite, strong, null_resettable) GPBEnumArray *movingTypeSamplesArray;
/** The number of items in @c movingTypeSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger movingTypeSamplesArray_Count;
/**
* altitude samples
* Note: Samples are already calibrated samples
**/
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *altitudeSamplesArray;
/** The number of items in @c altitudeSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger altitudeSamplesArray_Count;
/** indicate start and stop indexes, used calibration value and operation type of calibration */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbCalibrationValue*> *altitudeCalibrationArray;
/** The number of items in @c altitudeCalibrationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger altitudeCalibrationArray_Count;
/** temperature samples */
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *temperatureSamplesArray;
/** The number of items in @c temperatureSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger temperatureSamplesArray_Count;
/**
* stride length samples
* Note: Samples are already calibrated samples
**/
@property(nonatomic, readwrite, strong, null_resettable) GPBUInt32Array *strideLengthSamplesArray;
/** The number of items in @c strideLengthSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger strideLengthSamplesArray_Count;
/** indicate the information of the stride sensor calibration */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbCalibrationValue*> *strideCalibrationArray;
/** The number of items in @c strideCalibrationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger strideCalibrationArray_Count;
/** Crank based power samples from left pedal */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbPowerMeasurements*> *leftPedalPowerSamplesArray;
/** The number of items in @c leftPedalPowerSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger leftPedalPowerSamplesArray_Count;
/** Crank based power samples from right pedal */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbPowerMeasurements*> *rightPedalPowerSamplesArray;
/** The number of items in @c rightPedalPowerSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger rightPedalPowerSamplesArray_Count;
/**
* Indicate the information of the bike power sensor calibration
* This field is most likely used only for testing purposes
**/
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbCalibrationValue*> *leftPowerCalibrationArray;
/** The number of items in @c leftPowerCalibrationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger leftPowerCalibrationArray_Count;
/**
* Indicate the information of the bike power sensor calibration
* This field is most likely used only for testing purposes
**/
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbCalibrationValue*> *rightPowerCalibrationArray;
/** The number of items in @c rightPowerCalibrationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger rightPowerCalibrationArray_Count;
/** Heart Rate R-R sample data. */
@property(nonatomic, readwrite, strong, null_resettable) PbExerciseRRIntervals *rrSamples;
/** Test to see if @c rrSamples has been set. */
@property(nonatomic, readwrite) BOOL hasRrSamples;
/** Acceleration based Mean Amplitude Deviation (MAD) samples */
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *accelerationMadSamplesArray;
/** The number of items in @c accelerationMadSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger accelerationMadSamplesArray_Count;
@end
#pragma mark - PbExerciseSamples
typedef GPB_ENUM(PbExerciseSamples_FieldNumber) {
PbExerciseSamples_FieldNumber_RecordingInterval = 1,
PbExerciseSamples_FieldNumber_HeartRateSamplesArray = 2,
PbExerciseSamples_FieldNumber_HeartRateOfflineArray = 3,
PbExerciseSamples_FieldNumber_CadenceSamplesArray = 4,
PbExerciseSamples_FieldNumber_CadenceOfflineArray = 5,
PbExerciseSamples_FieldNumber_AltitudeSamplesArray = 6,
PbExerciseSamples_FieldNumber_AltitudeCalibrationArray = 7,
PbExerciseSamples_FieldNumber_TemperatureSamplesArray = 8,
PbExerciseSamples_FieldNumber_SpeedSamplesArray = 9,
PbExerciseSamples_FieldNumber_SpeedOfflineArray = 10,
PbExerciseSamples_FieldNumber_DistanceSamplesArray = 11,
PbExerciseSamples_FieldNumber_DistanceOfflineArray = 12,
PbExerciseSamples_FieldNumber_StrideLengthSamplesArray = 13,
PbExerciseSamples_FieldNumber_StrideLengthOfflineArray = 14,
PbExerciseSamples_FieldNumber_StrideCalibrationArray = 15,
PbExerciseSamples_FieldNumber_ForwardAccelerationArray = 16,
PbExerciseSamples_FieldNumber_MovingTypeSamplesArray = 17,
PbExerciseSamples_FieldNumber_AltitudeOfflineArray = 18,
PbExerciseSamples_FieldNumber_TemperatureOfflineArray = 19,
PbExerciseSamples_FieldNumber_ForwardAccelerationOfflineArray = 20,
PbExerciseSamples_FieldNumber_MovingTypeOfflineArray = 21,
PbExerciseSamples_FieldNumber_LeftPedalPowerSamplesArray = 22,
PbExerciseSamples_FieldNumber_LeftPedalPowerOfflineArray = 23,
PbExerciseSamples_FieldNumber_RightPedalPowerSamplesArray = 24,
PbExerciseSamples_FieldNumber_RightPedalPowerOfflineArray = 25,
PbExerciseSamples_FieldNumber_LeftPowerCalibrationArray = 26,
PbExerciseSamples_FieldNumber_RightPowerCalibrationArray = 27,
PbExerciseSamples_FieldNumber_RrSamples = 28,
PbExerciseSamples_FieldNumber_ExerciseIntervalledSampleListArray = 29,
PbExerciseSamples_FieldNumber_PauseTimesArray = 30,
};
/**
*
* Sample data of the exercise.
* ! All fields are required.
**/
@interface PbExerciseSamples : GPBMessage
/**
* Default recording interval of samples
* Note: Samples listed in the root of the PbExerciseSamples will use this interval
* Note: Samples in the exercise_intervalled_sample_list will use this interval unless
* otherwise specified inside the exercise_intervalled_sample_list
**/
@property(nonatomic, readwrite, strong, null_resettable) PbDuration *recordingInterval;
/** Test to see if @c recordingInterval has been set. */
@property(nonatomic, readwrite) BOOL hasRecordingInterval;
/** heart rate samples */
@property(nonatomic, readwrite, strong, null_resettable) GPBUInt32Array *heartRateSamplesArray;
/** The number of items in @c heartRateSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger heartRateSamplesArray_Count;
/** indicate start and stop indexes when there has not been connection to heart rate sensor */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *heartRateOfflineArray;
/** The number of items in @c heartRateOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger heartRateOfflineArray_Count;
/** cadence samples */
@property(nonatomic, readwrite, strong, null_resettable) GPBUInt32Array *cadenceSamplesArray;
/** The number of items in @c cadenceSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger cadenceSamplesArray_Count;
/** indicate start and stop indexes when there has not been connection to a sensor providing cadence */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *cadenceOfflineArray;
/** The number of items in @c cadenceOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger cadenceOfflineArray_Count;
/**
* altitude samples
* Note: Samples are already calibrated samples
**/
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *altitudeSamplesArray;
/** The number of items in @c altitudeSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger altitudeSamplesArray_Count;
/** Altitude sensor offline status */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *altitudeOfflineArray;
/** The number of items in @c altitudeOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger altitudeOfflineArray_Count;
/** indicate start and stop indexes, used calibration value and operation type of calibration */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbCalibrationValue*> *altitudeCalibrationArray;
/** The number of items in @c altitudeCalibrationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger altitudeCalibrationArray_Count;
/** temperature samples */
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *temperatureSamplesArray;
/** The number of items in @c temperatureSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger temperatureSamplesArray_Count;
/** Temperature sensor offline status */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *temperatureOfflineArray;
/** The number of items in @c temperatureOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger temperatureOfflineArray_Count;
/**
* speed samples
* Note: Samples are already calibrated samples
**/
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *speedSamplesArray;
/** The number of items in @c speedSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger speedSamplesArray_Count;
/** indicate start and stop indexes when there has not been connection to speed sensor */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *speedOfflineArray;
/** The number of items in @c speedOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger speedOfflineArray_Count;
/**
* distance samples: total distance from the beginning of the exercise
* Note: Samples are already calibrated samples
**/
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *distanceSamplesArray;
/** The number of items in @c distanceSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger distanceSamplesArray_Count;
/** indicate start and stop indexes when there has not been connection to distance measure sensor */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *distanceOfflineArray;
/** The number of items in @c distanceOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger distanceOfflineArray_Count;
/**
* stride length samples
* Note: Samples are already calibrated samples
**/
@property(nonatomic, readwrite, strong, null_resettable) GPBUInt32Array *strideLengthSamplesArray;
/** The number of items in @c strideLengthSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger strideLengthSamplesArray_Count;
/** indicate start and stop indexes when there has not been connection to stride sensor */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *strideLengthOfflineArray;
/** The number of items in @c strideLengthOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger strideLengthOfflineArray_Count;
/** indicate the information of the stride sensor calibration */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbCalibrationValue*> *strideCalibrationArray;
/** The number of items in @c strideCalibrationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger strideCalibrationArray_Count;
/** User 1d acceleration samples as m/s2 */
@property(nonatomic, readwrite, strong, null_resettable) GPBFloatArray *forwardAccelerationArray;
/** The number of items in @c forwardAccelerationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger forwardAccelerationArray_Count;
/** indicate start and stop indexes when there has not been connection to sensor that produces forward acceleration */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *forwardAccelerationOfflineArray;
/** The number of items in @c forwardAccelerationOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger forwardAccelerationOfflineArray_Count;
/** User walking/running/standing status samples */
// |movingTypeSamplesArray| contains |PbMovingType|
@property(nonatomic, readwrite, strong, null_resettable) GPBEnumArray *movingTypeSamplesArray;
/** The number of items in @c movingTypeSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger movingTypeSamplesArray_Count;
/** indicate start and stop indexes when there has not been connection to sensor that produces moving_type */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *movingTypeOfflineArray;
/** The number of items in @c movingTypeOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger movingTypeOfflineArray_Count;
/** Crank based power samples from left pedal */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbPowerMeasurements*> *leftPedalPowerSamplesArray;
/** The number of items in @c leftPedalPowerSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger leftPedalPowerSamplesArray_Count;
/** Indicate start and stop indexes when there has not been connection to sensor that produces left_pedal_power_samples */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *leftPedalPowerOfflineArray;
/** The number of items in @c leftPedalPowerOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger leftPedalPowerOfflineArray_Count;
/** Crank based power samples from right pedal */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbPowerMeasurements*> *rightPedalPowerSamplesArray;
/** The number of items in @c rightPedalPowerSamplesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger rightPedalPowerSamplesArray_Count;
/** Indicate start and stop indexes when there has not been connection to sensor that produces right_pedal_power_samples */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbSensorOffline*> *rightPedalPowerOfflineArray;
/** The number of items in @c rightPedalPowerOfflineArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger rightPedalPowerOfflineArray_Count;
/**
* Indicate the information of the bike power sensor calibration
* This field is most likely used only for testing purposes
**/
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbCalibrationValue*> *leftPowerCalibrationArray;
/** The number of items in @c leftPowerCalibrationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger leftPowerCalibrationArray_Count;
/**
* Indicate the information of the bike power sensor calibration
* This field is most likely used only for testing purposes
**/
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbCalibrationValue*> *rightPowerCalibrationArray;
/** The number of items in @c rightPowerCalibrationArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger rightPowerCalibrationArray_Count;
/** Heart Rate R-R sample data. */
@property(nonatomic, readwrite, strong, null_resettable) PbExerciseRRIntervals *rrSamples;
/** Test to see if @c rrSamples has been set. */
@property(nonatomic, readwrite) BOOL hasRrSamples;
/** Exercise samples with sample type specific recording intervals */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbExerciseIntervalledSampleList*> *exerciseIntervalledSampleListArray;
/** The number of items in @c exerciseIntervalledSampleListArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger exerciseIntervalledSampleListArray_Count;
/** Exercise pause times */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<PbPauseTime*> *pauseTimesArray;
/** The number of items in @c pauseTimesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger pauseTimesArray_Count;
@end
NS_ASSUME_NONNULL_END
CF_EXTERN_C_END
#pragma clang diagnostic pop
// @@protoc_insertion_point(global_scope)
|
{
"pile_set_name": "Github"
}
|
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: FlameD
m_Shader: {fileID: 200, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _MainTex:
m_Texture: {fileID: 2800000, guid: d236c2e07976ff942a0e23d979e8f4cb, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats: []
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _TintColor: {r: 0.5, g: 0.5, b: 0.5, a: 0.5}
--- !u!1002 &2100001
EditorExtensionImpl:
serializedVersion: 6
|
{
"pile_set_name": "Github"
}
|
/**
* Aptana Studio
* Copyright (c) 2012-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.js.core.node;
import java.io.FileFilter;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
/**
* @author cwilliams
*/
public interface INodePackageManager
{
public static final String GLOBAL_ARG = "-g"; //$NON-NLS-1$
public static final String PARSEABLE_ARG = "-p"; //$NON-NLS-1$
public static final String SILENT_ARG = "-s"; //$NON-NLS-1$
public static final String PREFIX_PATH = "--prefix"; //$NON-NLS-1$
/**
* Folder where modules live.
*/
public static final String NODE_MODULES = "node_modules"; //$NON-NLS-1$
public static final String PACKAGE_JSON = "package.json"; //$NON-NLS-1$
/**
* Installs a package.
*
* @param packageName
* The name of the npm package to install
* @param displayName
* The UI string to use for the name of the package
* @param global
* Whether to install globally
* @param password
* The password to pass to sudo if installing globally on Mac/Linux/Unix
* @param monitor
* @return
*/
public IStatus install(String packageName, String displayName, boolean global, char[] password,
IProgressMonitor monitor);
/**
* Installs a package.
*
* @param packageName
* The name of the npm package to install
* @param displayName
* The UI string to use for the name of the package
* @param global
* Whether to install globally
* @param password
* The password to pass to sudo if installing globally on Mac/Linux/Unix
* @param workingDirectory
* @param monitor
* @return
*/
public IStatus install(String packageName, String displayName, boolean global, char[] password,
IPath workingDirectory, IProgressMonitor monitor);
/**
* Lists the installed packages.
*
* @param global
* @return
* @throws CoreException
* if an error occurs trying to generate the listing
*/
public Set<String> list(boolean global) throws CoreException;
/**
* Determines if a package is installed. Checks both local and global package listings.
*
* @param packageName
* @return
* @throws CoreException
*/
public boolean isInstalled(String packageName) throws CoreException;
/**
* Retrieves the node modules path for the specific package.
*
* @param packageName
* the package to get the path for
* @return the node modules path
* @throws CoreException
*/
public IPath getModulesPath(String packageName, boolean isGlobal, String... args) throws CoreException;
/**
* Gets the latest installed version of a package.
*
* @param packageName
* @return
* @throws CoreException
*/
public String getInstalledVersion(String packageName) throws CoreException;
public String getInstalledVersion(String packageName, boolean isGlobal, IPath workingDir) throws CoreException;
/**
* Gets the latest version published for a package. Note that there may be "newer" RC/beta/alphas, but the NPM
* "latest" pointer may not refer to them.
*
* @param packageName
* @return
* @throws CoreException
*/
public String getLatestVersionAvailable(String packageName) throws CoreException;
/**
* Gets the full list of published versions for a given package. NEVER RETURNS NULL! if anything goes wrong, we'll
* throw a CoreException.
*
* @param packageName
* @return
* @throws CoreException
*/
public List<String> getAvailableVersions(String packageName) throws CoreException;
public String getConfigValue(String key) throws CoreException;
/**
* Returns the location where node packages' binary scripts get installed.
*
* @return
* @throws CoreException
*/
public IPath getBinariesPath() throws CoreException;
/**
* Returns the location where node modules get installed.
*
* @return
* @throws CoreException
*/
public IPath getModulesPath() throws CoreException;
/**
* Returns the prefix path of npm. The prefix path can be configured either in the environment variable
* NPM_CONFIG_PREFIX, or through the 'prefix' attribute from the npm configuration file.
*
* @return
* @throws CoreException
*/
public IPath getConfigPrefixPath() throws CoreException;
/**
* Clears the npm cache data. This might help to remove the conflicting dependent packages being referenced by new
* installed npm packages.
*
* @param monitor
* @return
* @throws CoreException
*/
public IStatus cleanNpmCache(char[] password, boolean runWithSudo, IProgressMonitor monitor);
/**
* Uninstalls an npm package.
*
* @param packageName
* @param displayName
* @param global
* @param password
* @param monitor
* @return
* @throws CoreException
*/
public IStatus uninstall(String packageName, String displayName, boolean global, char[] password,
IProgressMonitor monitor) throws CoreException;
/**
* Uninstalls an npm package.
*
* @param packageName
* @param displayName
* @param global
* @param password
* @param workingDirectory
* @param monitor
* @return
* @throws CoreException
*/
public IStatus uninstall(String packageName, String displayName, boolean global, char[] password,
IPath workingDirectory, IProgressMonitor monitor) throws CoreException;
/**
* Does the NPM path/install we're pointing to exist?
*
* @return
*/
public boolean exists();
/**
* The path to the NPM binary script. This may return null if we were unable to find npm!
*
* @return
*/
public IPath getPath();
/**
* return the version of NPM.
*
* @return
* @throws CoreException
* if NPM isn't actually installed, or grabbing the version failed.
*/
public String getVersion() throws CoreException;
/**
* A way to generically launch commands under NPM. Use sparingly. Ideally we'd have methods to invoke whatever
* command you're hacking by using this.
*
* @param args
* @return
* @throws CoreException
* May throw a CoreException to indicate that the NPM path is bad.
*/
public IStatus runInBackground(String... args) throws CoreException;
/**
* Search for the npm package installed locally based on the search locations.
*
* @param executableName
* @param appendExtension
* @param searchLocations
* @param fileFilter
* @return
*/
public IPath findNpmPackagePath(String executableName, boolean appendExtension, List<IPath> searchLocations,
FileFilter fileFilter);
/**
* Rebuilds the native libraries for the provided npm package directory.
*
* @param packageDir
* @return
* @throws CoreException
*/
public IStatus rebuild(IPath packageDir) throws CoreException;
// TODO Update
}
|
{
"pile_set_name": "Github"
}
|
package txnbuild
import (
"github.com/stellar/go/amount"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/xdr"
)
// ManageBuyOffer represents the Stellar manage buy offer operation. See
// https://www.stellar.org/developers/guides/concepts/list-of-operations.html
type ManageBuyOffer struct {
Selling Asset
Buying Asset
Amount string
Price string
price price
OfferID int64
SourceAccount Account
}
// BuildXDR for ManageBuyOffer returns a fully configured XDR Operation.
func (mo *ManageBuyOffer) BuildXDR() (xdr.Operation, error) {
xdrSelling, err := mo.Selling.ToXDR()
if err != nil {
return xdr.Operation{}, errors.Wrap(err, "failed to set XDR 'Selling' field")
}
xdrBuying, err := mo.Buying.ToXDR()
if err != nil {
return xdr.Operation{}, errors.Wrap(err, "failed to set XDR 'Buying' field")
}
xdrAmount, err := amount.Parse(mo.Amount)
if err != nil {
return xdr.Operation{}, errors.Wrap(err, "failed to parse 'Amount'")
}
if err = mo.price.parse(mo.Price); err != nil {
return xdr.Operation{}, errors.Wrap(err, "failed to parse 'Price'")
}
opType := xdr.OperationTypeManageBuyOffer
xdrOp := xdr.ManageBuyOfferOp{
Selling: xdrSelling,
Buying: xdrBuying,
BuyAmount: xdrAmount,
Price: mo.price.toXDR(),
OfferId: xdr.Int64(mo.OfferID),
}
body, err := xdr.NewOperationBody(opType, xdrOp)
if err != nil {
return xdr.Operation{}, errors.Wrap(err, "failed to build XDR OperationBody")
}
op := xdr.Operation{Body: body}
SetOpSourceAccount(&op, mo.SourceAccount)
return op, nil
}
// FromXDR for ManageBuyOffer initialises the txnbuild struct from the corresponding xdr Operation.
func (mo *ManageBuyOffer) FromXDR(xdrOp xdr.Operation) error {
result, ok := xdrOp.Body.GetManageBuyOfferOp()
if !ok {
return errors.New("error parsing manage_buy_offer operation from xdr")
}
mo.SourceAccount = accountFromXDR(xdrOp.SourceAccount)
mo.OfferID = int64(result.OfferId)
mo.Amount = amount.String(result.BuyAmount)
if result.Price != (xdr.Price{}) {
mo.price.fromXDR(result.Price)
mo.Price = mo.price.string()
}
buyingAsset, err := assetFromXDR(result.Buying)
if err != nil {
return errors.Wrap(err, "error parsing buying_asset in manage_buy_offer operation")
}
mo.Buying = buyingAsset
sellingAsset, err := assetFromXDR(result.Selling)
if err != nil {
return errors.Wrap(err, "error parsing selling_asset in manage_buy_offer operation")
}
mo.Selling = sellingAsset
return nil
}
// Validate for ManageBuyOffer validates the required struct fields. It returns an error if any
// of the fields are invalid. Otherwise, it returns nil.
func (mo *ManageBuyOffer) Validate() error {
return validateOffer(mo.Buying, mo.Selling, mo.Amount, mo.Price, mo.OfferID)
}
// GetSourceAccount returns the source account of the operation, or nil if not
// set.
func (mo *ManageBuyOffer) GetSourceAccount() Account {
return mo.SourceAccount
}
|
{
"pile_set_name": "Github"
}
|
#.rst:
# ECMAddTests
# -----------
#
# Convenience functions for adding tests.
#
# ::
#
# ecm_add_tests(<sources> LINK_LIBRARIES <library> [<library> [...]]
# [NAME_PREFIX <prefix>]
# [GUI]
# [TARGET_NAMES_VAR <target_names_var>]
# [TEST_NAMES_VAR <test_names_var>])
#
# A convenience function for adding multiple tests, each consisting of a
# single source file. For each file in <sources>, an executable target will be
# created (the name of which will be the basename of the source file). This
# will be linked against the libraries given with LINK_LIBRARIES. Each
# executable will be added as a test with the same name.
#
# If NAME_PREFIX is given, this prefix will be prepended to the test names, but
# not the target names. As a result, it will not prevent clashes between tests
# with the same name in different parts of the project, but it can be used to
# give an indication of where to look for a failing test.
#
# If the flag GUI is passed the test binaries will be GUI executables, otherwise
# the resulting binaries will be console applications (regardless of the value
# of CMAKE_WIN32_EXECUTABLE or CMAKE_MACOSX_BUNDLE). Be aware that this changes
# the executable entry point on Windows (although some frameworks, such as Qt,
# abstract this difference away).
#
# The TARGET_NAMES_VAR and TEST_NAMES_VAR arguments, if given, should specify a
# variable name to receive the list of generated target and test names,
# respectively. This makes it convenient to apply properties to them as a
# whole, for example, using set_target_properties() or set_tests_properties().
#
# The generated target executables will have the effects of ecm_mark_as_test()
# (from the :module:`ECMMarkAsTest` module) applied to it.
#
# ::
#
# ecm_add_test(<sources> LINK_LIBRARIES <library> [<library> [...]]
# [TEST_NAME <name>]
# [NAME_PREFIX <prefix>]
# [GUI])
#
# This is a single-test form of ecm_add_tests that allows multiple source files
# to be used for a single test. If using multiple source files, TEST_NAME must
# be given; this will be used for both the target and test names (and, as with
# ecm_add_tests(), the NAME_PREFIX argument will be prepended to the test name).
#
#
# Since pre-1.0.0.
#=============================================================================
# SPDX-FileCopyrightText: 2013 Alexander Richardson <arichardson.kde@gmail.com>
# SPDX-FileCopyrightText: 2015 Alex Merry <alex.merry@kde.org>
#
# SPDX-License-Identifier: BSD-3-Clause
include(CMakeParseArguments)
include(ECMMarkAsTest)
include(ECMMarkNonGuiExecutable)
function(ecm_add_test)
set(options GUI)
# TARGET_NAME_VAR and TEST_NAME_VAR are undocumented args used by
# ecm_add_tests
set(oneValueArgs TEST_NAME NAME_PREFIX TARGET_NAME_VAR TEST_NAME_VAR)
set(multiValueArgs LINK_LIBRARIES)
cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
set(_sources ${ARG_UNPARSED_ARGUMENTS})
list(LENGTH _sources _sourceCount)
if(ARG_TEST_NAME)
set(_targetname ${ARG_TEST_NAME})
elseif(${_sourceCount} EQUAL "1")
#use the source file name without extension as the testname
get_filename_component(_targetname ${_sources} NAME_WE)
else()
#more than one source file passed, but no test name given -> error
message(FATAL_ERROR "ecm_add_test() called with multiple source files but without setting \"TEST_NAME\"")
endif()
set(_testname ${ARG_NAME_PREFIX}${_targetname})
set(gui_args)
if(ARG_GUI)
set(gui_args WIN32 MACOSX_BUNDLE)
endif()
add_executable(${_targetname} ${gui_args} ${_sources})
if(NOT ARG_GUI)
ecm_mark_nongui_executable(${_targetname})
endif()
add_test(NAME ${_testname} COMMAND ${_targetname})
target_link_libraries(${_targetname} ${ARG_LINK_LIBRARIES})
ecm_mark_as_test(${_targetname})
if (CMAKE_LIBRARY_OUTPUT_DIRECTORY)
if(CMAKE_HOST_SYSTEM MATCHES "Windows")
set(PATHSEP ";")
else() # e.g. Linux
set(PATHSEP ":")
endif()
set(_plugin_path $ENV{QT_PLUGIN_PATH})
set_property(TEST ${_testname} PROPERTY ENVIRONMENT QT_PLUGIN_PATH=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}${PATHSEP}${_plugin_path})
endif()
if (ARG_TARGET_NAME_VAR)
set(${ARG_TARGET_NAME_VAR} "${_targetname}" PARENT_SCOPE)
endif()
if (ARG_TEST_NAME_VAR)
set(${ARG_TEST_NAME_VAR} "${_testname}" PARENT_SCOPE)
endif()
endfunction()
function(ecm_add_tests)
set(options GUI)
set(oneValueArgs NAME_PREFIX TARGET_NAMES_VAR TEST_NAMES_VAR)
set(multiValueArgs LINK_LIBRARIES)
cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(ARG_GUI)
set(_exe_type GUI)
else()
set(_exe_type "")
endif()
set(test_names)
set(target_names)
foreach(_test_source ${ARG_UNPARSED_ARGUMENTS})
ecm_add_test(${_test_source}
NAME_PREFIX ${ARG_NAME_PREFIX}
LINK_LIBRARIES ${ARG_LINK_LIBRARIES}
TARGET_NAME_VAR target_name
TEST_NAME_VAR test_name
${_exe_type}
)
list(APPEND _test_names "${test_name}")
list(APPEND _target_names "${target_name}")
endforeach()
if (ARG_TARGET_NAMES_VAR)
set(${ARG_TARGET_NAMES_VAR} "${_target_names}" PARENT_SCOPE)
endif()
if (ARG_TEST_NAMES_VAR)
set(${ARG_TEST_NAMES_VAR} "${_test_names}" PARENT_SCOPE)
endif()
endfunction()
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.hateoas.examples;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author Greg Turnquist
*/
@SpringBootApplication
public class SpringHateoasHypermediaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringHateoasHypermediaApplication.class, args);
}
}
|
{
"pile_set_name": "Github"
}
|
{
"ramlVersion": "RAML08",
"type": "Api",
"specification": {
"title": "test API",
"schemas": [
{
"MyType": "{\n \"$schema\": \"http://json-schema.org/draft-04/\",\n \"type\": \"object\",\n \"properties\": {\n \"arrayProp\": {\n \"items\": {\n \"type\": \"object\", \"properties\": {\n \"prop1\": { \"type\": \"number\" },\n \"prop2\": { \"type\": \"boolean\" }\n },\n \"additionalProperties\": false\n }\n }\n }\n}\n",
"sourceMap": {
"path": "api.raml"
}
}
],
"resources": [
{
"relativeUri": "/res1",
"methods": [
{
"body": {
"application/json": {
"name": "application/json",
"schema": "MyType",
"example": "{\n \"arrayProp\": [\n {\n \"prop1\": 13,\n \"prop2\": true\n },\n {\n \"prop1\": 13\n \"prop2\": false\n }\n ]\n}\n",
"schemaContent": "{\n \"$schema\": \"http://json-schema.org/draft-04/\",\n \"type\": \"object\",\n \"properties\": {\n \"arrayProp\": {\n \"items\": {\n \"type\": \"object\", \"properties\": {\n \"prop1\": { \"type\": \"number\" },\n \"prop2\": { \"type\": \"boolean\" }\n },\n \"additionalProperties\": false\n }\n }\n }\n}\n",
"sourceMap": {
"scalarsSources": {
"example": [
{
"path": "example.json"
}
]
},
"path": "api.raml"
}
}
},
"method": "post",
"sourceMap": {
"path": "api.raml"
}
}
],
"displayName": "/res1",
"__METADATA__": {
"primitiveValuesMeta": {
"displayName": {
"calculated": true
}
}
},
"sourceMap": {
"path": "api.raml"
},
"relativeUriPathSegments": [
"res1"
],
"absoluteUri": "/res1"
},
{
"relativeUri": "/res2",
"methods": [
{
"body": {
"application/json": {
"name": "application/json",
"schema": "{\n \"$schema\": \"http://json-schema.org/draft-04/\",\n \"type\": \"object\",\n \"properties\": {\n \"arrayProp\": {\n \"items\": {\n \"type\": \"object\", \"properties\": {\n \"prop1\": { \"type\": \"number\" },\n \"prop2\": { \"type\": \"boolean\" }\n },\n \"additionalProperties\": false\n }\n }\n }\n}\n",
"example": "{\n \"arrayProp\": [\n {\n \"prop1\": 13,\n \"prop2\": true\n },\n {\n \"prop1\": 13\n \"prop2\": false\n }\n ]\n}\n",
"schemaContent": "{\n \"$schema\": \"http://json-schema.org/draft-04/\",\n \"type\": \"object\",\n \"properties\": {\n \"arrayProp\": {\n \"items\": {\n \"type\": \"object\", \"properties\": {\n \"prop1\": { \"type\": \"number\" },\n \"prop2\": { \"type\": \"boolean\" }\n },\n \"additionalProperties\": false\n }\n }\n }\n}\n",
"sourceMap": {
"path": "api.raml"
}
}
},
"method": "post",
"sourceMap": {
"path": "api.raml"
}
}
],
"displayName": "/res2",
"__METADATA__": {
"primitiveValuesMeta": {
"displayName": {
"calculated": true
}
}
},
"sourceMap": {
"path": "api.raml"
},
"relativeUriPathSegments": [
"res2"
],
"absoluteUri": "/res2"
}
],
"sourceMap": {
"path": "api.raml"
}
},
"errors": [
{
"code": "CAN_NOT_PARSE_JSON",
"message": "Can not parse JSON example: Unexpected token '\"prop2\"'",
"path": "example.json",
"range": {
"start": {
"line": 8,
"column": 6,
"position": 101
},
"end": {
"line": 8,
"column": 13,
"position": 108
}
},
"isWarning": true,
"trace": [
{
"code": "CAN_NOT_PARSE_JSON",
"message": "Can not parse JSON example: Unexpected token '\"prop2\"'",
"path": "api.raml",
"range": {
"start": {
"line": 26,
"column": 8,
"position": 546
},
"end": {
"line": 26,
"column": 15,
"position": 553
}
},
"isWarning": true
}
]
},
{
"code": "CAN_NOT_PARSE_JSON",
"message": "Can not parse JSON example: Unexpected token '\"prop2\"'",
"path": "example.json",
"range": {
"start": {
"line": 8,
"column": 6,
"position": 101
},
"end": {
"line": 8,
"column": 13,
"position": 108
}
},
"isWarning": true,
"trace": [
{
"code": "CAN_NOT_PARSE_JSON",
"message": "Can not parse JSON example: Unexpected token '\"prop2\"'",
"path": "api.raml",
"range": {
"start": {
"line": 33,
"column": 8,
"position": 662
},
"end": {
"line": 33,
"column": 15,
"position": 669
}
},
"isWarning": true
}
]
}
]
}
|
{
"pile_set_name": "Github"
}
|
module Raindrops (convert) where
import Data.Maybe (fromMaybe)
convert :: Int -> String
convert n = fromMaybe (show n) maybeSound
where
maybeSound = sound "Pling" 3 `mappend`
sound "Plang" 5 `mappend`
sound "Plong" 7
sound noise factor | n `rem` factor == 0 = Just noise
| otherwise = Nothing
|
{
"pile_set_name": "Github"
}
|
<?php
declare(strict_types=1);
/*
* This file is part of Exchanger.
*
* (c) Florian Voutzinos <florian@voutzinos.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Exchanger;
use Exchanger\Contract\ExchangeRate as ExchangeRateContract;
use Exchanger\Contract\CurrencyPair as CurrencyPairContract;
/**
* Represents a rate.
*
* @author Florian Voutzinos <florian@voutzinos.com>
*/
final class ExchangeRate implements ExchangeRateContract
{
/**
* The currency pair.
*
* @var CurrencyPairContract
*/
private $currencyPair;
/**
* The value.
*
* @var float
*/
private $value;
/**
* The date.
*
* @var \DateTimeInterface
*/
private $date;
/**
* The provider.
*
* @var string
*/
private $provider;
/**
* Creates a new rate.
*
* @param CurrencyPairContract $currencyPair The currency pair
* @param float $value The rate value
* @param \DateTimeInterface $date The date at which this rate was calculated
* @param string $provider The class name of the provider that returned this rate
*/
public function __construct(CurrencyPairContract $currencyPair, float $value, \DateTimeInterface $date, string $provider)
{
$this->currencyPair = $currencyPair;
$this->value = $value;
$this->date = $date;
$this->provider = $provider;
}
/**
* {@inheritdoc}
*/
public function getValue(): float
{
return $this->value;
}
/**
* {@inheritdoc}
*/
public function getDate(): \DateTimeInterface
{
return $this->date;
}
/**
* {@inheritdoc}
*/
public function getProviderName(): string
{
return $this->provider;
}
/**
* {@inheritdoc}
*/
public function getCurrencyPair(): CurrencyPairContract
{
return $this->currencyPair;
}
}
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using GlobusLinkedinLib.Authentication;
using GlobusLinkedinLib.LinkedIn.Core.ShareAndSocialStreamMethods;
namespace GlobusLinkedinLib.App.Core
{
public class LinkedInNetwork
{
private XmlDocument xmlResult;
public LinkedInNetwork()
{
xmlResult = new XmlDocument();
}
public List<Network_Updates> NetworkUpdatesList = new List<Network_Updates>();
public struct Network_Updates
{
public string DateTime { get; set; }
public string UpdateType { get; set; }
public string PersonId { get; set; }
public string PersonFirstName { get; set; }
public string PersonLastName { get; set; }
public string PersonHeadLine { get; set; }
public string PictureUrl { get; set; }
public string Message { get; set; }
public string GroupName { get; set; }
public string id { get; set; }
public string Description { get; set; }
public string Title { get; set; }
public string ShortenUrl { get; set; }
public string url { get; set; }
public string ImageUrl { get; set; }
}
/// <summary>
/// The Get Network Updates API returns the users network updates, which is the LinkedIn term for the user's feed.
/// </summary>
/// <param name="OAuth"></param>
/// <param name="Count"></param>
/// <returns></returns>
public List<Network_Updates> GetNetworkUpdates(oAuthLinkedIn OAuth, int Count)
{
Network_Updates network_Updates;
//SocialStream socialStream = new SocialStream();
ShareAndSocialStream socialStream = new ShareAndSocialStream();
xmlResult = socialStream.Get_NetworkUpdates(OAuth, Count);
XmlNodeList xmlNodeList = xmlResult.GetElementsByTagName("update");
foreach (XmlNode xn in xmlNodeList)
{
network_Updates = new Network_Updates();
try
{
XmlElement Element = (XmlElement)xn;
double timestamp = Convert.ToDouble(Element.GetElementsByTagName("timestamp")[0].InnerText);
network_Updates.DateTime = JavaTimeStampToDateTime(timestamp);
try
{
network_Updates.UpdateType = Element.GetElementsByTagName("update-type")[0].InnerText;
}
catch
{ }
try
{
network_Updates.PersonId = Element.GetElementsByTagName("id")[0].InnerText;
}
catch
{ }
try
{
network_Updates.Description = Element.GetElementsByTagName("description")[0].InnerText;
}
catch
{ }
try
{
network_Updates.Title = Element.GetElementsByTagName("title")[0].InnerText;
}
catch
{ }
try
{
network_Updates.ShortenUrl = Element.GetElementsByTagName("shortened-url")[0].InnerText;
}
catch
{ }
try
{
network_Updates.PersonFirstName = Element.GetElementsByTagName("first-name")[0].InnerText;
}
catch
{
network_Updates.PersonFirstName = Element.GetElementsByTagName("name")[0].InnerText;
}
try
{
network_Updates.PersonLastName = Element.GetElementsByTagName("last-name")[0].InnerText;
}
catch
{
network_Updates.PersonLastName = null;
}
try
{
network_Updates.PersonHeadLine = Element.GetElementsByTagName("headline")[0].InnerText;
}
catch
{ }
try
{
network_Updates.PictureUrl = Element.GetElementsByTagName("picture-url")[0].InnerText;
}
catch
{ }
try
{
if (network_Updates.UpdateType == "CMPY")
{
network_Updates.url = Element.GetElementsByTagName("url")[0].InnerText;
}
else {
network_Updates.url = Element.GetElementsByTagName("url")[1].InnerText;
}
}
catch
{ }
try
{
network_Updates.ImageUrl = Element.GetElementsByTagName("submitted-image-url")[0].InnerText;
}
catch
{ }
string MessageType = Element.GetElementsByTagName("update-type")[0].InnerText;
if (MessageType == "CONN")
{
XmlElement innerElement = (XmlElement)xn;
string personFirstName = "";
string personLastName = "";
string Personheadline = "";
if (innerElement.SelectSingleNode("picture-url") == null)
{
personFirstName = innerElement.GetElementsByTagName("first-name")[1].InnerText;
}
if (innerElement.SelectSingleNode("picture-url") == null)
{
personLastName = innerElement.GetElementsByTagName("last-name")[1].InnerText;
}
if (innerElement.SelectSingleNode("picture-url") == null)
{
Personheadline = innerElement.GetElementsByTagName("headline")[1].InnerText;
}
network_Updates.Message = network_Updates.PersonFirstName + " " + network_Updates.PersonLastName + " is now connected to " + personFirstName + " " + personLastName;
}
else if (MessageType == "NCON")
{
XmlElement innerElement = (XmlElement)xn;
string personFirstName = "";
string personLastName = "";
string Personheadline = "";
if (innerElement.SelectSingleNode("picture-url") == null)
{
personFirstName = innerElement.GetElementsByTagName("first-name")[1].InnerText;
}
if (innerElement.SelectSingleNode("picture-url") == null)
{
personLastName = innerElement.GetElementsByTagName("last-name")[1].InnerText;
}
if (innerElement.SelectSingleNode("picture-url") == null)
{
Personheadline = innerElement.GetElementsByTagName("headline")[1].InnerText;
}
network_Updates.Message = network_Updates.PersonFirstName + " " + network_Updates.PersonLastName + " is now connected with " + personFirstName + " " + personLastName;
}
else if (MessageType == "CCEM")
{
XmlElement innerElement = (XmlElement)xn;
string personFirstName = "";
string personLastName = "";
string Personheadline = "";
if (innerElement.SelectSingleNode("picture-url") == null)
{
personFirstName = innerElement.GetElementsByTagName("first-name")[1].InnerText;
}
if (innerElement.SelectSingleNode("picture-url") == null)
{
personLastName = innerElement.GetElementsByTagName("last-name")[1].InnerText;
}
if (innerElement.SelectSingleNode("picture-url") == null)
{
Personheadline = innerElement.GetElementsByTagName("headline")[1].InnerText;
}
network_Updates.Message = network_Updates.PersonFirstName + " " + network_Updates.PersonLastName + " is now connected with " + personFirstName + " " + personLastName;
}
else if (MessageType == "SHAR")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "STAT")
{
network_Updates.Message = Element.GetElementsByTagName("current-status")[0].InnerText;
}
else if (MessageType == "VIRL")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "JGRP")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "QSTN")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "ANSW")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "APPM")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "APPS")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "PRFU")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "PRFX")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "PREC")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "SVPR")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "JOBP")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "CMPY")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.url;
}
else if (MessageType == "MSFC")
{
network_Updates.Message = network_Updates.Title + " " + network_Updates.Description + "" + network_Updates.ShortenUrl;
}
else if (MessageType == "PICU")
{
network_Updates.Message = network_Updates.PersonFirstName + " " + network_Updates.PersonLastName + " Updated their profile picture";
}
else if (MessageType == "PROF")
{
network_Updates.Message = network_Updates.PersonFirstName + " " + network_Updates.PersonLastName + " Updated their profile";
}
NetworkUpdatesList.Add(network_Updates);
}
catch
{
}
}
return NetworkUpdatesList;
}
public static string JavaTimeStampToDateTime(double javaTimeStamp)
{
// Java timestamp is millisecods past epoch
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
dtDateTime = dtDateTime.AddSeconds(Math.Round(javaTimeStamp / 1000)).ToLocalTime();
string date = dtDateTime.ToString("MMMM dd, yy H:mm:ss tt");
return date;
}
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// *Preprocessed* version of the main "advance_backward.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl { namespace aux {
template< long N > struct advance_backward;
template<>
struct advance_backward<0>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef iter0 type;
};
};
template<>
struct advance_backward<1>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename prior<iter0>::type iter1;
typedef iter1 type;
};
};
template<>
struct advance_backward<2>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename prior<iter0>::type iter1;
typedef typename prior<iter1>::type iter2;
typedef iter2 type;
};
};
template<>
struct advance_backward<3>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename prior<iter0>::type iter1;
typedef typename prior<iter1>::type iter2;
typedef typename prior<iter2>::type iter3;
typedef iter3 type;
};
};
template<>
struct advance_backward<4>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename prior<iter0>::type iter1;
typedef typename prior<iter1>::type iter2;
typedef typename prior<iter2>::type iter3;
typedef typename prior<iter3>::type iter4;
typedef iter4 type;
};
};
template< long N >
struct advance_backward
{
template< typename Iterator > struct apply
{
typedef typename apply_wrap1<
advance_backward<4>
, Iterator
>::type chunk_result_;
typedef typename apply_wrap1<
advance_backward<(
(N - 4) < 0
? 0
: N - 4
)>
, chunk_result_
>::type type;
};
};
}}}
|
{
"pile_set_name": "Github"
}
|
namespace Server.Mobiles
{
[CorpseName("a rock mite corpse")]
public class RockMite : BaseCreature
{
[Constructable]
public RockMite()
: base(AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4)
{
Name = "a rock mite";
Body = 787;
BaseSoundID = 1006;
Hue = 2500;
SetStr(733, 754);
SetDex(126, 144);
SetInt(75, 94);
SetHits(803, 817);
SetStam(126, 144);
SetMana(75, 94);
SetDamage(12, 19);
SetDamageType(ResistanceType.Physical, 50);
SetDamageType(ResistanceType.Cold, 50);
SetResistance(ResistanceType.Physical, 50, 59);
SetResistance(ResistanceType.Fire, 80, 90);
SetResistance(ResistanceType.Cold, 52, 59);
SetResistance(ResistanceType.Poison, 80, 85);
SetResistance(ResistanceType.Energy, 80, 90);
SetSkill(SkillName.MagicResist, 88.5, 119.6);
SetSkill(SkillName.Tactics, 84.9, 112.9);
SetSkill(SkillName.Wrestling, 82.7, 119.8);
SetSkill(SkillName.Parry, 90.0, 100.0);
SetSkill(SkillName.DetectHidden, 42.9);
Fame = 3500;
Karma = -3500;
SetSpecialAbility(SpecialAbility.TailSwipe);
}
public RockMite(Serial serial)
: base(serial)
{
}
public override int GetAngerSound()
{
return 0x5A;
}
public override int GetIdleSound()
{
return 0x5A;
}
public override int GetAttackSound()
{
return 0x164;
}
public override int GetHurtSound()
{
return 0x187;
}
public override int GetDeathSound()
{
return 0x1BA;
}
public override void GenerateLoot()
{
AddLoot(LootPack.FilthyRich, 2);
AddLoot(LootPack.Average);
AddLoot(LootPack.Gems, Utility.Random(1, 5));
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
{
"pile_set_name": "Github"
}
|
# kbuild trick to avoid linker error. Can be omitted if a module is built.
obj- := dummy.o
# List of programs to build
hostprogs-y := hid-example
# Tell kbuild to always build the programs
always := $(hostprogs-y)
HOSTCFLAGS_hid-example.o += -I$(objtree)/usr/include
all: hid-example
|
{
"pile_set_name": "Github"
}
|
.heatmap-wrapper {
position: absolute;
}
.my-tickets-stats-indicators-title {
font-size: 19px;
line-height: 24px;
}
.ticket-activity-wrapper {
height: 100%;
margin-left: 42px
}
|
{
"pile_set_name": "Github"
}
|
/**
* @license
* Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';
import * as dom5 from 'dom5';
var p = dom5.predicates;
var isHtmlImportNode = p.AND(
p.hasTagName('link'),
p.hasAttrValue('rel', 'import'),
p.NOT(
p.hasAttrValue('type', 'css')
)
);
var isStyleNode = p.OR(
// inline style
p.hasTagName('style'),
// external stylesheet
p.AND(
p.hasTagName('link'),
p.hasAttrValue('rel', 'stylesheet')
),
// polymer specific external stylesheet
p.AND(
p.hasTagName('link'),
p.hasAttrValue('rel', 'import'),
p.hasAttrValue('type', 'css')
)
);
var isJSScriptNode = p.AND(
p.hasTagName('script'),
p.OR(
p.NOT(p.hasAttr('type')),
p.hasAttrValue('type', 'text/javascript'),
p.hasAttrValue('type', 'application/javascript')
)
);
function addNode(node:LocNode, registry:ParsedImport) {
if (isHtmlImportNode(node)) {
registry.import.push(node);
} else if (isStyleNode(node)) {
registry.style.push(node);
} else if (isJSScriptNode(node)) {
registry.script.push(node);
} else if (node.tagName === 'base') {
registry.base.push(node);
} else if (node.tagName === 'template') {
registry.template.push(node);
} else if (node.tagName === 'dom-module') {
registry['dom-module'].push(node);
} else if (dom5.isCommentNode(node)) {
registry.comment.push(node);
}
}
function getLineAndColumn(string:string, charNumber:number) {
if (charNumber > string.length) {
return undefined;
}
// TODO(ajo): Caching the line lengths of each document could be much faster.
var sliced = string.slice(0,charNumber+1);
var split = sliced.split('\n');
var line = split.length;
var column = split[split.length - 1].length;
return {line: line, column: column};
}
/**
* The ASTs of the HTML elements needed to represent Polymer elements.
*/
export interface ParsedImport {
base: LocNode[];
/**
* The entry points to the AST at each outermost template tag.
*/
template: LocNode[];
/**
* The entry points to the AST at each script tag not inside a template.
*/
script: LocNode[];
/**
* The entry points to the AST at style tag outside a template.
*/
style: LocNode[];
import: LocNode[];
/**
* The entry points to the AST at each outermost dom-module element.
*/
'dom-module': LocNode[];
comment: LocNode[];
/**
* The full parse5 ast for the document.
*/
ast: LocNode;
}
/**
* An extension of the dom5 node type with location information and the
* owner document squirreled away.
*/
export interface LocNode extends dom5.Node {
__locationDetail: {line: number, column: number};
__ownerDocument: string;
__hydrolysisInlined: string;
}
/**
* Parse html into ASTs.
*
* htmlString is a utf8, html5 document containing polymer elements
* or module definitons.
*
* href is the path of the document.
*/
export function importParse(htmlString:string, href:string) {
var doc: LocNode;
try {
doc = <LocNode>dom5.parse(htmlString, {locationInfo: true});
} catch (err) {
console.log(err);
return null;
}
// Add line/column information
dom5.treeMap(doc, function(node:LocNode) {
if (node.__location && node.__location.start >= 0) {
node.__locationDetail = getLineAndColumn(htmlString, node.__location.start);
if (href) {
node.__ownerDocument = href;
}
}
});
var registry: ParsedImport = {
base: [],
template: [],
script: [],
style: [],
import: [],
'dom-module': [],
comment: [],
ast: doc};
var queue = [].concat(doc.childNodes);
var nextNode: LocNode;
while (queue.length > 0) {
nextNode = queue.shift();
if (nextNode) {
queue = queue.concat(nextNode.childNodes);
addNode(nextNode, registry);
}
}
;
return registry;
};
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: 629b14c88d1450049b6a70245a2fc096
timeCreated: 1503738734
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/tips.css">
</head>
<body>
<p>Using <span class="shortcut">&shortcut:Generate;</span> (<span class="control">Code | Generate</span>)
in the editor, you can easily generate getter and setter methods for any fields of your class.</p>
<p class="image"><img src="images/alt_insert_in_editor.png"></p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2019 Alachisoft
//
// 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
using System;
using System.Collections;
using Alachisoft.NCache.Runtime.Serialization;
namespace Alachisoft.NCache.Common.RPCFramework
{
[Serializable]
public class TargetMethodParameter : ICompactSerializable
{
ArrayList _parameterList = new ArrayList();
public ArrayList ParameterList
{
get { return _parameterList; }
}
public void TargetMethodArguments()
{
_parameterList = new ArrayList();
}
public void TargetMethodArguments(ArrayList parameter)
{
_parameterList = parameter;
}
public void AddParameter(object parameter)
{
_parameterList.Add(parameter);
}
#region ICompactSerializable Members
public void Deserialize(Runtime.Serialization.IO.CompactReader reader)
{
int length = reader.ReadInt32();
_parameterList = new ArrayList();
bool isByteArray = false;
for (int i = 0; i < length; i++)
{
isByteArray = reader.ReadBoolean();
if (isByteArray)
{
int count = reader.ReadInt32();
_parameterList.Add(reader.ReadBytes(count));
}
else
_parameterList.Add(reader.ReadObject());
}
}
public void Serialize(Runtime.Serialization.IO.CompactWriter writer)
{
writer.Write(_parameterList.Count);
bool isByteArray = false;
for (int i = 0; i < _parameterList.Count; i++)
{
isByteArray = _parameterList[i] != null && _parameterList[i].GetType() == typeof(byte[]);
writer.Write(isByteArray);
if(isByteArray)
{
byte[] buffer = _parameterList[i] as byte[];
writer.Write(buffer.Length);
writer.Write(buffer);
}
else
writer.WriteObject(_parameterList[i]);
}
}
#endregion
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* max77693.c - Regulator driver for the Maxim 77693 and 77843
*
* Copyright (C) 2013-2015 Samsung Electronics
* Jonghwa Lee <jonghwa3.lee@samsung.com>
* Krzysztof Kozlowski <krzk@kernel.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* This driver is based on max77686.c
*/
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/export.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#include <linux/mfd/max77693.h>
#include <linux/mfd/max77693-common.h>
#include <linux/mfd/max77693-private.h>
#include <linux/mfd/max77843-private.h>
#include <linux/regulator/of_regulator.h>
#include <linux/regmap.h>
/*
* ID for MAX77843 regulators.
* There is no need for such for MAX77693.
*/
enum max77843_regulator_type {
MAX77843_SAFEOUT1 = 0,
MAX77843_SAFEOUT2,
MAX77843_CHARGER,
MAX77843_NUM,
};
/* Register differences between chargers: MAX77693 and MAX77843 */
struct chg_reg_data {
unsigned int linear_reg;
unsigned int linear_mask;
unsigned int uA_step;
unsigned int min_sel;
};
/*
* MAX77693 CHARGER regulator - Min : 20mA, Max : 2580mA, step : 20mA
* 0x00, 0x01, 0x2, 0x03 = 60 mA
* 0x04 ~ 0x7E = (60 + (X - 3) * 20) mA
* Actually for MAX77693 the driver manipulates the maximum input current,
* not the fast charge current (output). This should be fixed.
*
* On MAX77843 the calculation formula is the same (except values).
* Fortunately it properly manipulates the fast charge current.
*/
static int max77693_chg_get_current_limit(struct regulator_dev *rdev)
{
const struct chg_reg_data *reg_data = rdev_get_drvdata(rdev);
unsigned int chg_min_uA = rdev->constraints->min_uA;
unsigned int chg_max_uA = rdev->constraints->max_uA;
unsigned int reg, sel;
unsigned int val;
int ret;
ret = regmap_read(rdev->regmap, reg_data->linear_reg, ®);
if (ret < 0)
return ret;
sel = reg & reg_data->linear_mask;
/* the first four codes for charger current are all 60mA */
if (sel <= reg_data->min_sel)
sel = 0;
else
sel -= reg_data->min_sel;
val = chg_min_uA + reg_data->uA_step * sel;
if (val > chg_max_uA)
return -EINVAL;
return val;
}
static int max77693_chg_set_current_limit(struct regulator_dev *rdev,
int min_uA, int max_uA)
{
const struct chg_reg_data *reg_data = rdev_get_drvdata(rdev);
unsigned int chg_min_uA = rdev->constraints->min_uA;
int sel = 0;
while (chg_min_uA + reg_data->uA_step * sel < min_uA)
sel++;
if (chg_min_uA + reg_data->uA_step * sel > max_uA)
return -EINVAL;
/* the first four codes for charger current are all 60mA */
sel += reg_data->min_sel;
return regmap_write(rdev->regmap, reg_data->linear_reg, sel);
}
/* end of CHARGER regulator ops */
/* Returns regmap suitable for given regulator on chosen device */
static struct regmap *max77693_get_regmap(enum max77693_types type,
struct max77693_dev *max77693,
int reg_id)
{
if (type == TYPE_MAX77693)
return max77693->regmap;
/* Else: TYPE_MAX77843 */
switch (reg_id) {
case MAX77843_SAFEOUT1:
case MAX77843_SAFEOUT2:
return max77693->regmap;
case MAX77843_CHARGER:
return max77693->regmap_chg;
default:
return max77693->regmap;
}
}
static const unsigned int max77693_safeout_table[] = {
4850000,
4900000,
4950000,
3300000,
};
static const struct regulator_ops max77693_safeout_ops = {
.list_voltage = regulator_list_voltage_table,
.is_enabled = regulator_is_enabled_regmap,
.enable = regulator_enable_regmap,
.disable = regulator_disable_regmap,
.get_voltage_sel = regulator_get_voltage_sel_regmap,
.set_voltage_sel = regulator_set_voltage_sel_regmap,
};
static const struct regulator_ops max77693_charger_ops = {
.is_enabled = regulator_is_enabled_regmap,
.enable = regulator_enable_regmap,
.disable = regulator_disable_regmap,
.get_current_limit = max77693_chg_get_current_limit,
.set_current_limit = max77693_chg_set_current_limit,
};
#define max77693_regulator_desc_esafeout(_num) { \
.name = "ESAFEOUT"#_num, \
.id = MAX77693_ESAFEOUT##_num, \
.of_match = of_match_ptr("ESAFEOUT"#_num), \
.regulators_node = of_match_ptr("regulators"), \
.n_voltages = 4, \
.ops = &max77693_safeout_ops, \
.type = REGULATOR_VOLTAGE, \
.owner = THIS_MODULE, \
.volt_table = max77693_safeout_table, \
.vsel_reg = MAX77693_CHG_REG_SAFEOUT_CTRL, \
.vsel_mask = SAFEOUT_CTRL_SAFEOUT##_num##_MASK, \
.enable_reg = MAX77693_CHG_REG_SAFEOUT_CTRL, \
.enable_mask = SAFEOUT_CTRL_ENSAFEOUT##_num##_MASK , \
}
static const struct regulator_desc max77693_supported_regulators[] = {
max77693_regulator_desc_esafeout(1),
max77693_regulator_desc_esafeout(2),
{
.name = "CHARGER",
.id = MAX77693_CHARGER,
.of_match = of_match_ptr("CHARGER"),
.regulators_node = of_match_ptr("regulators"),
.ops = &max77693_charger_ops,
.type = REGULATOR_CURRENT,
.owner = THIS_MODULE,
.enable_reg = MAX77693_CHG_REG_CHG_CNFG_00,
.enable_mask = CHG_CNFG_00_CHG_MASK |
CHG_CNFG_00_BUCK_MASK,
.enable_val = CHG_CNFG_00_CHG_MASK | CHG_CNFG_00_BUCK_MASK,
},
};
static const struct chg_reg_data max77693_chg_reg_data = {
.linear_reg = MAX77693_CHG_REG_CHG_CNFG_09,
.linear_mask = CHG_CNFG_09_CHGIN_ILIM_MASK,
.uA_step = 20000,
.min_sel = 3,
};
#define max77843_regulator_desc_esafeout(num) { \
.name = "SAFEOUT" # num, \
.id = MAX77843_SAFEOUT ## num, \
.ops = &max77693_safeout_ops, \
.of_match = of_match_ptr("SAFEOUT" # num), \
.regulators_node = of_match_ptr("regulators"), \
.type = REGULATOR_VOLTAGE, \
.owner = THIS_MODULE, \
.n_voltages = ARRAY_SIZE(max77693_safeout_table), \
.volt_table = max77693_safeout_table, \
.enable_reg = MAX77843_SYS_REG_SAFEOUTCTRL, \
.enable_mask = MAX77843_REG_SAFEOUTCTRL_ENSAFEOUT ## num, \
.vsel_reg = MAX77843_SYS_REG_SAFEOUTCTRL, \
.vsel_mask = MAX77843_REG_SAFEOUTCTRL_SAFEOUT ## num ## _MASK, \
}
static const struct regulator_desc max77843_supported_regulators[] = {
[MAX77843_SAFEOUT1] = max77843_regulator_desc_esafeout(1),
[MAX77843_SAFEOUT2] = max77843_regulator_desc_esafeout(2),
[MAX77843_CHARGER] = {
.name = "CHARGER",
.id = MAX77843_CHARGER,
.ops = &max77693_charger_ops,
.of_match = of_match_ptr("CHARGER"),
.regulators_node = of_match_ptr("regulators"),
.type = REGULATOR_CURRENT,
.owner = THIS_MODULE,
.enable_reg = MAX77843_CHG_REG_CHG_CNFG_00,
.enable_mask = MAX77843_CHG_MASK,
.enable_val = MAX77843_CHG_MASK,
},
};
static const struct chg_reg_data max77843_chg_reg_data = {
.linear_reg = MAX77843_CHG_REG_CHG_CNFG_02,
.linear_mask = MAX77843_CHG_FAST_CHG_CURRENT_MASK,
.uA_step = MAX77843_CHG_FAST_CHG_CURRENT_STEP,
.min_sel = 2,
};
static int max77693_pmic_probe(struct platform_device *pdev)
{
enum max77693_types type = platform_get_device_id(pdev)->driver_data;
struct max77693_dev *iodev = dev_get_drvdata(pdev->dev.parent);
const struct regulator_desc *regulators;
unsigned int regulators_size;
int i;
struct regulator_config config = { };
config.dev = iodev->dev;
switch (type) {
case TYPE_MAX77693:
regulators = max77693_supported_regulators;
regulators_size = ARRAY_SIZE(max77693_supported_regulators);
config.driver_data = (void *)&max77693_chg_reg_data;
break;
case TYPE_MAX77843:
regulators = max77843_supported_regulators;
regulators_size = ARRAY_SIZE(max77843_supported_regulators);
config.driver_data = (void *)&max77843_chg_reg_data;
break;
default:
dev_err(&pdev->dev, "Unsupported device type: %u\n", type);
return -ENODEV;
}
for (i = 0; i < regulators_size; i++) {
struct regulator_dev *rdev;
config.regmap = max77693_get_regmap(type, iodev,
regulators[i].id);
rdev = devm_regulator_register(&pdev->dev,
®ulators[i], &config);
if (IS_ERR(rdev)) {
dev_err(&pdev->dev,
"Failed to initialize regulator-%d\n", i);
return PTR_ERR(rdev);
}
}
return 0;
}
static const struct platform_device_id max77693_pmic_id[] = {
{ "max77693-pmic", TYPE_MAX77693 },
{ "max77843-regulator", TYPE_MAX77843 },
{},
};
MODULE_DEVICE_TABLE(platform, max77693_pmic_id);
static struct platform_driver max77693_pmic_driver = {
.driver = {
.name = "max77693-pmic",
},
.probe = max77693_pmic_probe,
.id_table = max77693_pmic_id,
};
static int __init max77693_pmic_init(void)
{
return platform_driver_register(&max77693_pmic_driver);
}
subsys_initcall(max77693_pmic_init);
static void __exit max77693_pmic_cleanup(void)
{
platform_driver_unregister(&max77693_pmic_driver);
}
module_exit(max77693_pmic_cleanup);
MODULE_DESCRIPTION("MAXIM 77693/77843 regulator driver");
MODULE_AUTHOR("Jonghwa Lee <jonghwa3.lee@samsung.com>");
MODULE_AUTHOR("Krzysztof Kozlowski <krzk@kernel.org>");
MODULE_LICENSE("GPL");
|
{
"pile_set_name": "Github"
}
|
StartChar: daggerdbl
Encoding: 8225 8225 1194
Width: 440
VWidth: 0
Flags: HMW
LayerCount: 3
Fore
SplineSet
266 163 m 0
266 148 235 125 235 97 c 16
235 92 241 79 246 79 c 8
295 79 322 99 371 99 c 8
389 99 400 83 400 64 c 8
400 46 389 29 371 29 c 16
329 29 298 49 250 49 c 16
243 49 235 46 235 39 c 16
235 -26 255 -23 255 -88 c 8
255 -106 237 -118 220 -118 c 0
203 -118 185 -112 185 -88 c 8
185 -38 205 -11 205 39 c 16
205 45 200 49 194 49 c 16
152 49 122 29 75 29 c 16
52 29 40 41 40 64 c 8
40 82 50 99 71 99 c 8
118 99 149 79 191 79 c 8
200 79 205 91 205 96 c 8
205 125 174 147 174 163 c 0
174 173 201 197 201 232 c 2
201 285 l 2
201 315 174 343 174 350 c 0
174 365 205 388 205 417 c 16
205 422 199 435 194 435 c 8
145 435 118 415 69 415 c 8
51 415 40 431 40 450 c 8
40 468 51 485 69 485 c 16
111 485 142 465 190 465 c 16
197 465 205 468 205 475 c 16
205 540 185 536 185 601 c 8
185 619 203 630 220 630 c 0
237 630 255 625 255 601 c 8
255 551 235 525 235 475 c 16
235 469 240 465 246 465 c 16
288 465 322 485 371 485 c 16
394 485 400 473 400 450 c 8
400 433 396 415 375 415 c 8
325 415 291 435 249 435 c 8
240 435 235 423 235 418 c 8
235 389 266 366 266 350 c 0
266 340 239 320 239 285 c 2
239 232 l 2
239 202 266 170 266 163 c 0
EndSplineSet
Validated: 1
Substitution2: "sups subtable" daggerdbl.sups
Substitution2: "sinf subtable" daggerdbl.sinf
Substitution2: "ordn subtable" daggerdbl.ordn
Substitution2: "subs subtable" daggerdbl.subs
EndChar
|
{
"pile_set_name": "Github"
}
|
// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).
package nl.bzk.brp.model.data.kern;
import java.math.BigDecimal;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import nl.bzk.brp.model.data.kern.HisPartij;
import nl.bzk.brp.model.data.kern.Partij;
import nl.bzk.brp.model.data.kern.Sector;
privileged aspect Sector_Roo_DbManaged {
@OneToMany(mappedBy = "sector")
private Set<HisPartij> Sector.hisPartijs;
@OneToMany(mappedBy = "sector")
private Set<Partij> Sector.partijs;
@Column(name = "naam", columnDefinition = "varchar", length = 40)
@NotNull
private String Sector.naam;
@Column(name = "dataanvgel", columnDefinition = "numeric")
private BigDecimal Sector.dataanvgel;
@Column(name = "dateindegel", columnDefinition = "numeric")
private BigDecimal Sector.dateindegel;
public Set<HisPartij> Sector.getHisPartijs() {
return hisPartijs;
}
public void Sector.setHisPartijs(Set<HisPartij> hisPartijs) {
this.hisPartijs = hisPartijs;
}
public Set<Partij> Sector.getPartijs() {
return partijs;
}
public void Sector.setPartijs(Set<Partij> partijs) {
this.partijs = partijs;
}
public String Sector.getNaam() {
return naam;
}
public void Sector.setNaam(String naam) {
this.naam = naam;
}
public BigDecimal Sector.getDataanvgel() {
return dataanvgel;
}
public void Sector.setDataanvgel(BigDecimal dataanvgel) {
this.dataanvgel = dataanvgel;
}
public BigDecimal Sector.getDateindegel() {
return dateindegel;
}
public void Sector.setDateindegel(BigDecimal dateindegel) {
this.dateindegel = dateindegel;
}
}
|
{
"pile_set_name": "Github"
}
|
var spawn = require('child_process').spawn
var bears = 0
bears += 1
if (process.argv[2] === 'child') {
var net = require('net')
var pipe = new net.Socket({ fd: 3 })
pipe.write('killme')
//console.log('child', bears)
} else {
var child = spawn(process.execPath, [__filename, 'child'], {
stdio: [null, null, null, 'pipe']
})
child.stdio[3].on('data', function (data) {
if (data.toString() === 'killme') {
console.log('RIP')
child.kill()
}
})
//console.log('parent', bears)
//child.stdout.pipe(process.stdout)
}
|
{
"pile_set_name": "Github"
}
|
//
// JDBreaksScene.swift
// JDBreaksLoading
//
// Created by 郭介騵 on 2016/12/14.
// Copyright © 2016年 james12345. All rights reserved.
//
import SpriteKit
import GameplayKit
let BallCategoryName = "ball"
let PaddleCategoryName = "paddle"
let BlockCategoryName = "block"
let GameMessageName = "gameMessage"
let BallCategory : UInt32 = 0x1 << 0
let BottomCategory : UInt32 = 0x1 << 1
let BlockCategory : UInt32 = 0x1 << 2
let PaddleCategory : UInt32 = 0x1 << 3
let BorderCategory : UInt32 = 0x1 << 4
class JDBreaksScene: SKScene{
var isFingerOnPaddle = false
var ball:SKShapeNode!
var gameWon : Bool = false {
didSet {
if(gameWon)
{
addBlock()
}
}
}
var d_ballwidth:CGFloat = 20.0
var ballwidth:CGFloat = 0.0
var ballcolor:UIColor = UIColor.white
var d_paddlewidth:CGFloat = 60
var paddlewidth:CGFloat = 0.0
var paddlecolor:UIColor = UIColor.white
var defaultwindowwidth:CGFloat = 200.0
var windowscale:CGFloat = 1.0
var d_blockwidth:CGFloat = 40.0
var blockwidth:CGFloat = 0.0
var blockscolor:UIColor = UIColor.white
var blockscount:Int = 3
override func update(_ currentTime: TimeInterval) {
}
override init(size: CGSize) {
super.init(size: size)
}
init(size: CGSize,configuration:JDBreaksGameConfiguration) {
super.init(size: size)
ballcolor = configuration.ball_color
paddlecolor = configuration.paddle_color
blockscolor = configuration.block_color
blockscount = configuration.blocks_count
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
super.didMove(to: view)
windowscale = (self.frame.width / defaultwindowwidth)
ballwidth = d_ballwidth * windowscale
paddlewidth = d_paddlewidth * windowscale
blockwidth = d_blockwidth * windowscale
self.backgroundColor = UIColor.clear
//Set Border
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
//Add Ball
ball = SKShapeNode(circleOfRadius: ballwidth/2)
ball.fillColor = ballcolor
ball.position = CGPoint(x: self.frame.width * 0.5, y: self.frame.width * 0.5)
ball.name = BallCategoryName
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width * 0.5)
ball.physicsBody?.isDynamic = true
ball.physicsBody?.friction = 0.0
ball.physicsBody?.restitution = 1.0
ball.physicsBody?.linearDamping = 0.0
ball.physicsBody?.angularDamping = 0.0
ball.physicsBody?.allowsRotation = false
self.addChild(ball)
//No gravity
self.physicsWorld.gravity = CGVector(dx: 0.05, dy: -0.2)
physicsWorld.contactDelegate = self
ball.physicsBody!.applyImpulse(CGVector(dx: 2.0, dy: -2.0))
//Add Paddle
let paddlesize:CGSize = CGSize(width: paddlewidth, height: 15)
let paddle:SKShapeNode = SKShapeNode(rectOf: paddlesize, cornerRadius: 5)
paddle.position = CGPoint(x: self.frame.width * 0.5, y: self.frame.width * 0.2)
paddle.fillColor = paddlecolor
paddle.name = PaddleCategoryName
paddle.physicsBody = SKPhysicsBody(rectangleOf: paddle.frame.size)
paddle.physicsBody?.isDynamic = false
paddle.physicsBody?.allowsRotation = true
paddle.physicsBody?.angularDamping = 0.1
paddle.physicsBody?.linearDamping = 0.1
self.addChild(paddle)
let bottomRect = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: 1)
let bottom = SKNode()
bottom.physicsBody = SKPhysicsBody(edgeLoopFrom: bottomRect)
addChild(bottom)
addBlock()
bottom.physicsBody!.categoryBitMask = BottomCategory
ball.physicsBody!.categoryBitMask = BallCategory
paddle.physicsBody!.categoryBitMask = PaddleCategory
borderBody.categoryBitMask = BorderCategory
ball.physicsBody!.contactTestBitMask = BottomCategory | BlockCategory
}
func addBlock()
{
// 新增方塊
let numberOfBlocks = blockscount
let blockWidth:CGFloat = blockwidth
let totalBlocksWidth = blockWidth * CGFloat(numberOfBlocks)
// 2
let xOffset = (frame.width - totalBlocksWidth) / 2
// 3
for i in 0..<numberOfBlocks {
let block = SKShapeNode(rectOf: CGSize(width: blockWidth, height: 15))
block.strokeColor = UIColor.black
block.fillColor = blockscolor
block.position = CGPoint(x: xOffset + CGFloat(CGFloat(i) + 0.5) * blockWidth,
y: frame.height * 0.8)
block.physicsBody = SKPhysicsBody(rectangleOf: block.frame.size)
block.physicsBody!.allowsRotation = false
block.physicsBody!.friction = 0.0
block.physicsBody!.affectedByGravity = false
block.physicsBody!.isDynamic = false
block.name = BlockCategoryName
block.physicsBody!.categoryBitMask = BlockCategory
block.zPosition = 2
addChild(block)
}
}
func breakBlock(node: SKNode) {
if( SKEmitterNode(fileNamed: "BrokenPlatform") != nil)
{
let particles = SKEmitterNode(fileNamed: "BrokenPlatform")!
particles.position = node.position
particles.zPosition = 3
addChild(particles)
particles.run(SKAction.sequence([SKAction.wait(forDuration: 1.0),
SKAction.removeFromParent()]))
}
node.removeFromParent()
}
func randomFloat(from: CGFloat, to: CGFloat) -> CGFloat {
let rand: CGFloat = CGFloat(Float(arc4random()) / 0xFFFFFFFF)
return (rand) * (to - from) + from
}
/*
This method checks to see how many bricks are left in the scene by going through all the scene’s children. For each child, it checks whether the child name is equal to BlockCategoryName. If there are no bricks left, the player has won the game and the method returns true.
*/
func isGameWon() -> Bool {
var numberOfBricks = 0
self.enumerateChildNodes(withName: BlockCategoryName) {
node, stop in
numberOfBricks = numberOfBricks + 1 //有磚塊存在就+1
}
return numberOfBricks == 0
}
}
extension JDBreaksScene
{
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let touchLocation = touch!.location(in: self)
if let body = physicsWorld.body(at: touchLocation) {
if body.node!.name == PaddleCategoryName {
isFingerOnPaddle = true
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// 是否壓著Bar
if isFingerOnPaddle {
// 2
let touch = touches.first
let touchLocation = touch!.location(in: self)
let previousLocation = touch!.previousLocation(in: self)
// 3
let paddle = childNode(withName: PaddleCategoryName) as! SKShapeNode
// Take the current position and add the difference between the new and the previous touch locations.
var paddleX = paddle.position.x + (touchLocation.x - previousLocation.x)
// Before repositioning the paddle, limit the position so that the paddle will not go off the screen to the left or right.
paddleX = max(paddleX, paddle.frame.size.width/2)
paddleX = min(paddleX, size.width - paddle.frame.size.width/2)
// 6
paddle.position = CGPoint(x: paddleX, y: paddle.position.y)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isFingerOnPaddle = false
}
}
extension JDBreaksScene:SKPhysicsContactDelegate
{
/*
Delegate
*/
func didBegin(_ contact: SKPhysicsContact) {
// 1
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
// 2
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
// 3
if firstBody.categoryBitMask == BallCategory && secondBody.categoryBitMask == BottomCategory {
}
// 球碰到磚塊
if firstBody.categoryBitMask == BallCategory && secondBody.categoryBitMask == BlockCategory {
breakBlock(node: secondBody.node!)
gameWon = isGameWon()
}
}
}
|
{
"pile_set_name": "Github"
}
|
Namespace Services
Public Class SuspensionState
Public Property Data As Object
Public Property SuspensionDate As DateTime
End Class
End Namespace
|
{
"pile_set_name": "Github"
}
|
#[macro_use]
extern crate lopdf;
use lopdf::content::{Content, Operation};
use lopdf::{Document, Object, Stream};
fn main() {
let mut doc = Document::with_version("1.5");
let pages_id = doc.new_object_id();
let font_id = doc.add_object(dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Courier",
});
let resources_id = doc.add_object(dictionary! {
"Font" => dictionary! {
"F1" => font_id,
},
});
let content = Content {
operations: vec![
Operation::new("BT", vec![]),
Operation::new("Tf", vec!["F1".into(), 48.into()]),
Operation::new("Td", vec![100.into(), 600.into()]),
Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
Operation::new("ET", vec![]),
],
};
let content_id = doc.add_object(Stream::new(dictionary!{}, content.encode().unwrap()));
let page_id = doc.add_object(dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"Contents" => content_id,
});
let pages = dictionary! {
"Type" => "Pages",
"Kids" => vec![page_id.into()],
"Count" => 1,
"Resources" => resources_id,
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
};
doc.objects.insert(pages_id, Object::Dictionary(pages));
let catalog_id = doc.add_object(dictionary! {
"Type" => "Catalog",
"Pages" => pages_id,
});
doc.trailer.set("Root", catalog_id);
doc.compress();
doc.save("example.pdf").unwrap();
}
|
{
"pile_set_name": "Github"
}
|
// Code generated by "stringer -type=getSource resource_data_get_source.go"; DO NOT EDIT.
package schema
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[getSourceState-1]
_ = x[getSourceConfig-2]
_ = x[getSourceDiff-4]
_ = x[getSourceSet-8]
_ = x[getSourceExact-16]
_ = x[getSourceLevelMask-15]
}
const (
_getSource_name_0 = "getSourceStategetSourceConfig"
_getSource_name_1 = "getSourceDiff"
_getSource_name_2 = "getSourceSet"
_getSource_name_3 = "getSourceLevelMaskgetSourceExact"
)
var (
_getSource_index_0 = [...]uint8{0, 14, 29}
_getSource_index_3 = [...]uint8{0, 18, 32}
)
func (i getSource) String() string {
switch {
case 1 <= i && i <= 2:
i -= 1
return _getSource_name_0[_getSource_index_0[i]:_getSource_index_0[i+1]]
case i == 4:
return _getSource_name_1
case i == 8:
return _getSource_name_2
case 15 <= i && i <= 16:
i -= 15
return _getSource_name_3[_getSource_index_3[i]:_getSource_index_3[i+1]]
default:
return "getSource(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
|
{
"pile_set_name": "Github"
}
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "winperf.h"
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.