repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
eosnationftw/geojsonpoint
|
contracts/faucet/src/request.cpp
|
void faucet::request( const name owner )
{
asset quantity = asset{ 50000, symbol{"XY", 4} };
auto request_itr = _request.find( owner.value );
// update owner's timestamp
if (request_itr == _request.end()) {
_request.emplace( get_self(), [&]( auto & row ) {
row.owner = owner;
row.timestamp = current_time_point();
});
} else {
// enforce 24 hour faucet limit
check( request_itr->timestamp < time_point_sec(current_time_point()) - 60 * 60 * 24, "owner can only request faucet every 24 hours");
_request.modify( request_itr, get_self(), [&]( auto & row ) {
row.timestamp = current_time_point();
});
}
// check existing balance of faucet
asset balance = token::get_balance( "token.xy"_n, get_self(), symbol_code{"XY"} );
check( balance.amount >= quantity.amount, "faucet is empty, please check again later" );
// external actions
token::transfer_action token_transfer( "token.xy"_n, { get_self(), "active"_n });
// issue & transfer XY tokens to user
token_transfer.send( get_self(), owner, quantity, "XY.network::faucet:request");
}
|
shawven/security
|
security-verification/src/main/java/com/github/shawven/security/verification/DefaultValidateSuccessHandler.java
|
<reponame>shawven/security
package com.github.shawven.security.verification;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DefaultValidateSuccessHandler implements ValidateSuccessHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) {
}
}
|
IasonasPap/Evolution
|
cli-client/admin.js
|
const axios = require("axios");
const FormData = require('form-data');
const fs = require('fs');
const https = require('https');
const agent = new https.Agent({
rejectUnauthorized: false
})
exports.healthcheck = () => {
axios({
"url": "https://localhost:8765/evcharge/api/admin/healthcheck",
"method": "get",
httpsAgent: agent
}).then ((response) => {
console.log(response.data)
})
}
exports.resetsessions = () => {
axios({
"url": "https://localhost:8765/evcharge/api/admin/resetsessions",
"method": "post",
httpsAgent: agent
}).then ((response) => {
console.log(response.data)
}).catch( (err) => {
console.error(err)
})
}
exports.usermod = (username, password, isAdmin, isStationManager, key) => {
axios({
"url": 'https://localhost:8765/evcharge/api/admin/usermod/' + username + '/' + password,
"method": "post",
httpsAgent: agent,
"data": {
"isAdmin": isAdmin,
"isStationManager": isStationManager
},
"headers": {'x-observatory-auth': key}
}).then (() => {
return axios({
"url": "https://localhost:8765/evcharge/api/login",
"method": "post",
httpsAgent: agent,
"data": {
"username": username,
"password": password
}
}).then ((response) => {
console.log(response.data.token)
})
}).catch( (err) => {
console.error(err.response.data)
})
}
exports.users = (username, key) => {
axios({
"url": 'https://localhost:8765/evcharge/api/admin/users/' + username,
"method": "get",
httpsAgent: agent,
"headers": {'x-observatory-auth': key}
}).then ((response) => {
delete response.data.password
console.log(response.data)
process.exit()
})
.catch((err) => {
console.error(err.response.data)
})
}
exports.sessionsupd = (source, key) => {
const form_data = new FormData();
form_data.append("file", fs.createReadStream(source));
axios({
"url": 'https://localhost:8765/evcharge/api/admin/system/sessionsupd',
"method": "post",
httpsAgent: agent,
"headers": {
'x-observatory-auth': key,
'Content-Type': 'multipart/form-data',
...form_data.getHeaders()
},
"data": form_data
}).then ((response) => {
console.log({message : response.data})
process.exit()
})
.catch((err) => {
if (!err.respone){
console.error({error: err.message})
}
else {
console.error(err.response.data)
}
process.exit()
})
}
|
DrMerfy/CardSorterClient-1
|
sorter/src/elements/Category.js
|
<filename>sorter/src/elements/Category.js<gh_stars>1-10
/**
* Represents the data model of the category
*/
export default class Category {
/**
*
* @param {int} id
* @param {String} title
*/
constructor(id, title) {
this.id = id;
this.title = title;
this.cards = [];
this.isMinimized = false;
}
/**
*
* @param {int} cardId
*/
addCard(cardId) {
this.cards.push(cardId);
}
/**
*
* @param {int} cardId
*/
removeCard(cardId) {
this.cards = this.cards.filter((id)=> {
return id !== cardId;
});
}
}
|
alexchao26/advent-of-code-go
|
2017/day24/main.go
|
<gh_stars>10-100
package main
import (
"flag"
"fmt"
"strings"
"github.com/alexchao26/advent-of-code-go/util"
)
func main() {
var part int
flag.IntVar(&part, "part", 1, "part 1 or 2")
flag.Parse()
fmt.Println("Running part", part)
ans := magneticMoat(util.ReadFile("./input.txt"), part)
fmt.Println("Output:", ans)
}
func magneticMoat(input string, part int) int {
edges := getEdges(input)
// start the bridge with a zero
bridge := [][2]int{
{0, 0},
}
usedEdges := map[[2]int]bool{}
for _, edge := range edges {
usedEdges[edge] = false
}
bestStrength, longestBridge := backtrackBridge(bridge, usedEdges)
if part == 1 {
return bestStrength
}
return calcStrengthOfBridge(longestBridge)
}
// backtracking algo that returns strongest bridge
func backtrackBridge(bridge [][2]int, usedEdges map[[2]int]bool) (bestStrength int, longestBridge [][2]int) {
lastVal := bridge[len(bridge)-1][1]
for edge, isUsed := range usedEdges {
// skip edges that are marked as used
if !isUsed {
clonedEdge := edge
// swap the edge vals if the first doesn't match
if clonedEdge[0] != lastVal {
clonedEdge[0], clonedEdge[1] = clonedEdge[1], clonedEdge[0]
}
// if match is found, add it to bridge, mark as used
// add to strength, recurse
if clonedEdge[0] == lastVal {
bridge = append(bridge, clonedEdge)
usedEdges[edge] = true
strength := clonedEdge[0] + clonedEdge[1]
// recurse and bestStrength and longestLength
subStrength, subLongestBridge := backtrackBridge(bridge, usedEdges)
strength += subStrength
// if current bridge is longest (or wins tiebreak) set the longestBridge
if len(bridge) > len(longestBridge) ||
(len(bridge) == len(longestBridge) &&
calcStrengthOfBridge(bridge) > calcStrengthOfBridge(longestBridge)) {
// use this hacky append to create a copy of the bridge slice
// otherwise appends could modify the underlying array
longestBridge = append([][2]int{}, bridge...)
}
// also check if a recursive call had the longest bridge, update longest
if len(subLongestBridge) > len(longestBridge) ||
(len(subLongestBridge) == len(longestBridge) &&
calcStrengthOfBridge(subLongestBridge) > calcStrengthOfBridge(longestBridge)) {
longestBridge = append([][2]int{}, subLongestBridge...)
}
// backtrack
usedEdges[edge] = false
bridge = bridge[:len(bridge)-1]
if strength > bestStrength {
bestStrength = strength
}
}
}
}
return bestStrength, longestBridge
}
func calcStrengthOfBridge(bridge [][2]int) int {
var sum int
for _, edge := range bridge {
sum += edge[0] + edge[1]
}
return sum
}
func getEdges(input string) (edges [][2]int) {
for _, line := range strings.Split(input, "\n") {
var pair [2]int
fmt.Sscanf(line, "%d/%d", &pair[0], &pair[1])
edges = append(edges, pair)
}
return edges
}
|
OS2World/DEV-UTIL-ScitechOS_PML
|
include/pmint.h
|
/****************************************************************************
*
* SciTech OS Portability Manager Library
*
* ========================================================================
*
* The contents of this file are subject to the SciTech MGL Public
* License Version 1.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.scitechsoft.com/mgl-license.txt
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Copyright (C) 1991-1998 SciTech Software, Inc.
*
* The Initial Developer of the Original Code is SciTech Software, Inc.
* All Rights Reserved.
*
* ========================================================================
*
* Language: ANSI C
* Environment: Real mode and 16/32 bit Protected Mode
*
* Description: Header file for the interrupt handling extensions to the OS
* Portability Manager Library. These extensions includes
* simplified interrupt handling, allowing all common interrupt
* handlers to be hooked and handled directly with normal C
* functions, both in 16 bit and 32 bit modes. Note however that
* simplified handling does not mean slow performance! All low
* level interrupt handling is done efficiently in assembler
* for speed (well actually necessary to insulate the
* application from the lack of far pointers in 32 bit PM). The
* interrupt handlers currently supported are:
*
* Mouse (0x33 callback)
* Timer Tick (0x8)
* Keyboard (0x9 and 0x15)
* Control C/Break (0x23/0x1B)
* Critical Error (0x24)
*
****************************************************************************/
#ifndef __PMINT_H
#define __PMINT_H
/*--------------------------- Macros and Typedefs -------------------------*/
#ifdef __SMX32__
/* PC interrupts (Ensure consistent with pme.inc) */
#define PM_IRQ0 0x40
#define PM_IRQ1 (PM_IRQ0+1)
#define PM_IRQ6 (PM_IRQ0+6)
#define PM_IRQ14 (PM_IRQ0+14)
#endif
/* Define the different types of interrupt handlers that we support */
typedef uint (PMAPIP PM_criticalHandler)(uint axValue,uint diValue);
typedef void (PMAPIP PM_breakHandler)(uint breakHit);
typedef short (PMAPIP PM_key15Handler)(short scanCode);
typedef void (PMAPIP PM_mouseHandler)(uint event, uint butstate,int x,int y,int mickeyX,int mickeyY);
/* Create a type for representing far pointers in both 16 and 32 bit
* protected mode.
*/
#ifdef PM386
typedef struct {
long off;
short sel;
} PMFARPTR;
#define PMNULL {0,0}
#else
typedef void *PMFARPTR;
#define PMNULL NULL
#endif
/*--------------------------- Function Prototypes -------------------------*/
#ifdef __cplusplus
extern "C" { /* Use "C" linkage when in C++ mode */
#endif
/* Routine to load save default data segment selector value into a code
* segment variable, and another to load the value into the DS register.
*/
void PMAPI PM_loadDS(void);
void PMAPI PM_saveDS(void);
/* Routine to install a mouse interrupt handling routine. The
* mouse handler routine is a normal C function, and the PM library
* will take care of passing the correct parameters to the function,
* and switching to a local stack.
*
* Note that you _must_ lock the memory containing the mouse interrupt
* handler with the PM_lockPages() function otherwise you may encounter
* problems in virtual memory environments.
*/
int PMAPI PM_setMouseHandler(int mask,PM_mouseHandler mh);
void PMAPI PM_restoreMouseHandler(void);
/* Routine to reset the mouse driver, and re-install the current
* mouse interrupt handler if one was currently installed (since the
* mouse reset will automatically remove this handler.
*/
void PMAPI PM_resetMouseDriver(int hardReset);
/* Routine to reset the mouse driver, and re-install the current
* mouse interrupt handler if one was currently installed (since the
* mouse reset will automatically remove this handler.
*/
void PMAPI PM_resetMouseDriver(int hardReset);
/* Routines to install and remove timer interrupt handlers.
*
* Note that you _must_ lock the memory containing the interrupt
* handlers with the PM_lockPages() function otherwise you may encounter
* problems in virtual memory environments.
*/
void PMAPI PM_setTimerHandler(PM_intHandler ih);
void PMAPI PM_chainPrevTimer(void);
void PMAPI PM_restoreTimerHandler(void);
/* Routines to install and keyboard interrupt handlers.
*
* Note that you _must_ lock the memory containing the interrupt
* handlers with the PM_lockPages() function otherwise you may encounter
* problems in virtual memory environments.
*/
void PMAPI PM_setKeyHandler(PM_intHandler ih);
void PMAPI PM_chainPrevKey(void);
void PMAPI PM_restoreKeyHandler(void);
/* Routines to hook and unhook the alternate Int 15h keyboard intercept
* callout routine. Your event handler will need to return the following:
*
* scanCode - Let the BIOS process scan code (chains to previous handler)
* 0 - You have processed the scan code so flush from BIOS
*
* Note that this is not available under all DOS extenders, but does
* work under real mode, DOS4GW and X32-VM. It does not work under the
* PowerPack 32 bit DOS extenders. If you figure out how to do it let us know!
*/
void PMAPI PM_setKey15Handler(PM_key15Handler ih);
void PMAPI PM_restoreKey15Handler(void);
/* Routines to install and remove the control c/break interrupt handlers.
* Interrupt handling is performed by the PM/Pro library, and you can call
* the supplied routines to test the status of the Ctrl-C and Ctrl-Break
* flags. If you pass the value TRUE for 'clearFlag' to these routines,
* the internal flags will be reset in order to catch another Ctrl-C or
* Ctrl-Break interrupt.
*/
void PMAPI PM_installBreakHandler(void);
int PMAPI PM_ctrlCHit(int clearFlag);
int PMAPI PM_ctrlBreakHit(int clearFlag);
void PMAPI PM_restoreBreakHandler(void);
/* Routine to install an alternate break handler that will call your
* code directly. This is not available under all DOS extenders, but does
* work under real mode, DOS4GW and X32-VM. It does not work under the
* PowerPack 32 bit DOS extenders. If you figure out how to do it let us know!
*
* Note that you should either install one or the other, but not both!
*/
void PMAPI PM_installAltBreakHandler(PM_breakHandler bh);
/* Routines to install and remove the critical error handler. The interrupt
* is handled by the PM/Pro library, and the operation will always be failed.
* You can check the status of the critical error handler with the
* appropriate function. If you pass the value TRUE for 'clearFlag', the
* internal flag will be reset ready to catch another critical error.
*/
void PMAPI PM_installCriticalHandler(void);
int PMAPI PM_criticalError(int *axValue, int *diValue, int clearFlag);
void PMAPI PM_restoreCriticalHandler(void);
/* Routine to install an alternate critical handler that will call your
* code directly. This is not available under all DOS extenders, but does
* work under real mode, DOS4GW and X32-VM. It does not work under the
* PowerPack 32 bit DOS extenders. If you figure out how to do it let us know!
*
* Note that you should either install one or the other, but not both!
*/
void PMAPI PM_installAltCriticalHandler(PM_criticalHandler);
/* Functions to manage protected mode only interrupt handlers */
void PMAPI PM_getPMvect(int intno, PMFARPTR *isr);
void PMAPI PM_setPMvect(int intno, PM_intHandler ih);
void PMAPI PM_restorePMvect(int intno, PMFARPTR isr);
#ifdef __cplusplus
} /* End of "C" linkage for C++ */
#endif
#endif /* __PMINT_H */
|
evleria/leetcode-in-go
|
problems/0037-sudoku-solver/solve_sudoku_test.go
|
package _037_sudoku_solver
import (
"testing"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestSolveSudoku(t *testing.T) {
testCases := []struct {
got [][]byte
want [][]byte
}{
{
got: [][]byte{
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'},
},
want: [][]byte{
{'5', '3', '4', '6', '7', '8', '9', '1', '2'},
{'6', '7', '2', '1', '9', '5', '3', '4', '8'},
{'1', '9', '8', '3', '4', '2', '5', '6', '7'},
{'8', '5', '9', '7', '6', '1', '4', '2', '3'},
{'4', '2', '6', '8', '5', '3', '7', '9', '1'},
{'7', '1', '3', '9', '2', '4', '8', '5', '6'},
{'9', '6', '1', '5', '3', '7', '2', '8', '4'},
{'2', '8', '7', '4', '1', '9', '6', '3', '5'},
{'3', '4', '5', '2', '8', '6', '1', '7', '9'},
},
},
}
for _, testCase := range testCases {
solveSudoku(testCase.got)
assert.Check(t, is.DeepEqual(testCase.got, testCase.want))
}
}
|
ncl-teu/ncl_workflow-engine
|
src/org/ncl/workflow/ccn/sfc/forwarding/BroadcastForwarding.java
|
<reponame>ncl-teu/ncl_workflow-engine
package org.ncl.workflow.ccn.sfc.forwarding;
/**
* Created by <NAME> on 2020/01/29
* ICN上でBroadcastを行うためのクラスです.
*
*/
public class BroadcastForwarding {
}
|
VZhiLinCorp/Kooboo
|
Kooboo.Web/_Admin/Scripts/inlineEditor/converter/DataConverter.js
|
function DataConverter(beforeSave){
var param={
_jstreeObj:null,
_dataType:null,
treeTextField:"content"
}
function doGetEditData(jstreeObject) {
var finalData = {};
if (!jstreeObject || !jstreeObject._model || !jstreeObject._model.data) return finalData;
var collectedId = [],
treeData = jstreeObject._model.data;
var keys = _.sortBy(Object.keys(treeData), [function(o) {
return o.indexOf("_") > -1 && parseInt(o.split("_")[1]);
}]);
//filter jstree root key
keys = _.filter(keys, function(key) {
return key != "#"
});
$.each(keys, function(index, key) {
if (collectedId.indexOf(key) == -1) {
if (treeData[key].children && treeData[key].children.length) {
var children = getChildren(treeData[key].children);
if (param._dataType == "Menu") {
finalData["children"] = children;
} else {
$.each(children, function(idx, child) {
finalData[idx] = child;
});
}
} else {
if ($.type(treeData[key].original.customData) == "string") {
finalData[treeData[key].text] = treeData[key].original.customData;
}
}
collectedId.push(key);
}
});
return finalData;
function getChildren(children) {
var list = [];
$.each(children, function(index, key) {
var childObj = treeData[key],
data = childObj.original.customData;
if (childObj.children && childObj.children.length) {
data["children"] = getChildren(childObj.children);
}
list.push(data);
collectedId.push(key);
});
return list;
}
}
function addTreeItem() {
var jstreeObj = param._jstreeObj,
selected = jstreeObj.get_selected();
if (!selected.length) return false;
if (param._dataType == "Menu") {
addMenuTreeItem();
} else if (param._dataType == "ContentList") {
addListTreeItem();
}
}
function addMenuTreeItem() {
var jstreeObj = param._jstreeObj,
selected = jstreeObj.get_selected(),
newItem = {
url: "",
name: "",
template: "",
};
var oriData = _.cloneDeep(jstreeObj._model.data[selected].original.customData);
if (oriData && !oriData["SubItemContainer"]) {
oriData["SubItemContainer"] = "";
}
jstreeObj._model.data[selected].original.customData = oriData;
selected = jstreeObj.create_node(selected, { icon: "fa fa-folder icon-state-warning", type: "default", customData: newItem });
if (selected) {
jstreeObj.edit(selected);
}
}
function addListTreeItem() {
var jstreeObj = param._jstreeObj,
selected = jstreeObj.get_selected(),
newItem = {};
var temp = _.cloneDeep(param.data);
//create ListItem Data
if (temp instanceof Object) {
$.each(temp, function(key, tempDetail) {
$.each(tempDetail, function(detailKey, value) {
newItem[detailKey] = "";
})
return false;
})
}
selected = jstreeObj.create_node(selected, { icon: "fa fa-file icon-state-warning", type: "file", customData: newItem });
if (selected) {
jstreeObj.edit(selected);
}
}
function deleteTreeItem() {
var jstreeObj = param._jstreeObj,
selected = jstreeObj.get_selected();
if (selected && selected.length) {
var parentId = jstreeObj._model.data[selected[0]].parent;
if (!jstreeObj._model.data[parentId].children.length) {
delete jstreeObj._model.data[parentId].original.customData["SubItemContainer"];
}
jstreeObj.delete_node(selected);
$(".data-converter").find(".btnAdd").hide();
$(".data-converter").find(".btnDelete").hide();
$(".data-converter").find(".pEditContainer").empty();
} else {
return false;
}
}
function generateJsTree(jstreeData) {
$(".data-converter").find(".pMenuContainer").jstree({
"core": {
"check_callback": true,
"data": function(obj, cb) {
cb.call(this, jstreeData);
},
"themes": {
"responsive": true
}
},
"types": {
"default": {
"icon": "fa fa-folder icon-state-warning"
},
"file": {
"icon": "fa fa-file icon-state-warning"
}
},
"plugins": ["types"]
})
.on("loaded.jstree", function(e, tree) {
param._jstreeObj = tree.instance;
}).on("changed.jstree", function(e, data) {
if (data.selected && data.selected.length) {
var jstreeData = param._jstreeObj._model.data;
var selected = data.selected[0];
if (jstreeData && jstreeData[selected] && jstreeData[selected].original) {
var originalData=jstreeData[selected].original;
originalData.text=jstreeData[selected].text;
if(param._dataType=="Menu"){
if(originalData.customData && originalData && !originalData.name &&originalData.text && !originalData.existNode){
originalData.customData.name=originalData.text;
}
}else if(param._dataType=="ContentList"){
if( originalData.customData && !originalData.existNode){
originalData.customData[param.treeTextField]=originalData.text
}
}
generateArea(originalData);
}
}
}).on("select_node.jstree", function(e, selected) {
controllBtnVisible(selected);
});
}
function controllBtnVisible(selected) {
var selectedText = selected.node.text;
var $btnAdd = $(".data-converter").find(".btnAdd");
var $btnDelete = $(".data-converter").find(".btnDelete");
switch (selectedText) {
case "List": //contentList
case "children": //menu
$btnAdd.css("display", "inline-block");
$btnDelete.hide();
break;
case "SubItemContainer": //menu
$btnAdd.hide();
$btnDelete.hide();
break;
default:
$btnDelete.css("display", "inline-block");
$btnAdd.hide();
// selectedNodeType ?
// $btnAdd.css("display", "inline-block") :
// $btnAdd.hide();
break;
}
}
function generateArea(treeOriginal) {
var originalData = treeOriginal.customData,
$pEditContainer = $(".data-converter").find(".pEditContainer");
$pEditContainer.empty();
switch ($.type(originalData)) {
case "object":
$.each(originalData, function(key, data) {
if (key !== "children") {
var formGroup = $("<div>");
$(formGroup).addClass("form-group");
//add lable
var label = $("<lable>");
var showLabelKey = getShowKeyName(key);
$(label).text(showLabelKey);
//add input
var input = $("<textarea>");
$(input).addClass("form-control autosize").attr("data-key", key).css({
"min-height": 0
}).val(originalData[key]);
$(input).on("blur", function() {
var saveKey = $(this).attr("data-key");
originalData[saveKey] = $(this).val();
//select Text
if((param._dataType=="Menu" && saveKey == "name")||
(param._dataType=="ContentList" && saveKey == param.treeTextField)){
resetSelectNodeText($(this).val());
}
});
$(formGroup).append(label).append(input);
$pEditContainer.append(formGroup);
}
})
break;
case "string": //SubItemContainer
var input = $("<textarea>");
$(input).addClass("form-control autosize").css({
"min-height": 120
}).val(originalData);
$(input).on("blur", function() {
treeOriginal.customData = $(this).val();
});
$pEditContainer.append(input);
break;
}
setTimeout(function() {
$(".autosize").textareaAutoSize().trigger("keyup");
}, 20);
}
function getShowKeyName(key) {
if (key == "url")
key = "href";
else if (key == "name") {
key = "text";
}
return key;
}
function resetSelectNodeText(newText) {
var jstree = $(".data-converter").find(".pMenuContainer").jstree(true);
var selectednode = jstree.get_selected(true);
newText=getTreeTextValue(newText);
jstree.rename_node(selectednode, newText);
}
function getTreeData(data, type) {
var keys = Object.keys(data);
param._dataType = type;
var jstreeData = [];
if (param._dataType == "Menu") {
jstreeData = getMenuData(data);
} else if (param._dataType == "ContentList") {
jstreeData = getContentListData(data);
}
return jstreeData;
}
function getMenuData(data) {
var keys = Object.keys(data),
menuData = [];
$.each(data, function(key, dataDetail) {
var menuItem = {};
var text=getTreeTextValue(key);
if (dataDetail instanceof Array) {
var children = getTreeChildrenData(dataDetail);
menuItem = { text: text,existNode:true, children: children, type: "default" };
} else {
menuItem = { text: text,existNode:true, icon: "fa fa-file icon-state-warning", type: "file", customData: dataDetail };
}
menuData.push(menuItem);
});
return menuData;
}
function getTreeTextField(data){
var field="content";
var contentFields=[];
$.each(data, function(key, dataDetail) {
var keys=Object.keys(dataDetail);
contentFields=_.filter(keys,function(detailKey){return detailKey.indexOf("content")==0});
return false;
});
contentFields=_.sortBy(contentFields);
$.each(contentFields,function(key,contentField){
var hasValueContents=_.filter(data,function(detail){return detail[contentField]});
if(hasValueContents.length>0){
field=contentField;
return false;;
}
});
return field;
}
//some filed has html elements
function getTreeTextValue(value){
if(!value) return "";
//html with <br> will cause $(value) error,so use $.parseHTML
var parseValue=$($.parseHTML(value));
if(parseValue.length==0) return value;
return parseValue.text();
}
function getContentListData(data) {
var listData = [];
var listTitleItem = {
text: "List",
type: "default",
icon: "fa fa-folder icon-state-warning"
};
var childListItem = [];
param.treeTextField=getTreeTextField(data);
$.each(data, function(key, dataDetail) {
var originalText=dataDetail[param.treeTextField];
var value=getTreeTextValue(originalText);
var item = {
text: value,
existNode:true,
icon: "fa fa-file icon-state-warning",
type: "file",
customData: dataDetail
}
childListItem.push(item);
});
listTitleItem["children"] = childListItem;
listData.push(listTitleItem);
return listData;
}
function getTreeChildrenData(data) {
var children = [];
$.each(data, function(key, dataDetial) {
var text=getTreeTextValue(dataDetial.name);
var child = {
text: text,
existNode:true,
icon: "fa fa-file icon-state-warning",
type: "file",
customData: dataDetial
};
if (dataDetial["children"]) {
var subchildren = getTreeChildrenData(dataDetial["children"]);
$.extend(child, {
children: subchildren,
icon: "fa fa-folder icon-state-warning",
type: "default"
});
}
children.push(child);
});
return children;
}
return {
dialogSetting:{
title:Kooboo.text.inlineEditor.editData,
width:"800px",
zIndex:Kooboo.InlineEditor.zIndex.middleZIndex,
beforeSave:beforeSave
},
getHtml:function(){
k.setHtml("dataHtml","DataConverter.html");
var data={
deletetag : Kooboo.text.common.delete,
add : Kooboo.text.common.add,
list : Kooboo.text.common.listName,
editArea : Kooboo.text.inlineEditor.editArea
};
return _.template(dataHtml)(data);
},
init:function(){
$(".data-converter").find(".btnAdd").bind("click", function() {
addTreeItem();
});
$(".data-converter").find(".btnDelete").bind("click", function() {
deleteTreeItem();
});
},
setData:function(data, type) {
param.data = _.cloneDeep(data);
//clear edit content
$(".data-converter").find(".pEditContainer").empty();
$(".data-converter").find(".btnDelete").hide();
$(".data-converter").find(".btnAdd").hide();
param.convertType = type;
param._jstreeData = getTreeData(param.data, type);
generateJsTree(param._jstreeData);
},
getEditData:function() {
var jstreeObject = param._jstreeObj;
return doGetEditData(jstreeObject);
}
}
}
|
sbh04101989/msgraph-beta-sdk-java
|
src/main/java/com/microsoft/graph/requests/extensions/IPrintTaskTriggerRequest.java
|
// Template Source: IBaseEntityRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.models.extensions.PrintTaskTrigger;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.http.IHttpRequest;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Print Task Trigger Request.
*/
public interface IPrintTaskTriggerRequest extends IHttpRequest {
/**
* Gets the PrintTaskTrigger from the service
*
* @param callback the callback to be called after success or failure
*/
void get(final ICallback<? super PrintTaskTrigger> callback);
/**
* Gets the PrintTaskTrigger from the service
*
* @return the PrintTaskTrigger from the request
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
PrintTaskTrigger get() throws ClientException;
/**
* Delete this item from the service
*
* @param callback the callback when the deletion action has completed
*/
void delete(final ICallback<? super PrintTaskTrigger> callback);
/**
* Delete this item from the service
*
* @throws ClientException if there was an exception during the delete operation
*/
void delete() throws ClientException;
/**
* Patches this PrintTaskTrigger with a source
*
* @param sourcePrintTaskTrigger the source object with updates
* @param callback the callback to be called after success or failure
*/
void patch(final PrintTaskTrigger sourcePrintTaskTrigger, final ICallback<? super PrintTaskTrigger> callback);
/**
* Patches this PrintTaskTrigger with a source
*
* @param sourcePrintTaskTrigger the source object with updates
* @return the updated PrintTaskTrigger
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
PrintTaskTrigger patch(final PrintTaskTrigger sourcePrintTaskTrigger) throws ClientException;
/**
* Posts a PrintTaskTrigger with a new object
*
* @param newPrintTaskTrigger the new object to create
* @param callback the callback to be called after success or failure
*/
void post(final PrintTaskTrigger newPrintTaskTrigger, final ICallback<? super PrintTaskTrigger> callback);
/**
* Posts a PrintTaskTrigger with a new object
*
* @param newPrintTaskTrigger the new object to create
* @return the created PrintTaskTrigger
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
PrintTaskTrigger post(final PrintTaskTrigger newPrintTaskTrigger) throws ClientException;
/**
* Posts a PrintTaskTrigger with a new object
*
* @param newPrintTaskTrigger the object to create/update
* @param callback the callback to be called after success or failure
*/
void put(final PrintTaskTrigger newPrintTaskTrigger, final ICallback<? super PrintTaskTrigger> callback);
/**
* Posts a PrintTaskTrigger with a new object
*
* @param newPrintTaskTrigger the object to create/update
* @return the created PrintTaskTrigger
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
PrintTaskTrigger put(final PrintTaskTrigger newPrintTaskTrigger) throws ClientException;
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
IPrintTaskTriggerRequest select(final String value);
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
IPrintTaskTriggerRequest expand(final String value);
}
|
IBMStreams/OSStreams
|
src/java/platform/com.ibm.streams.platform/src/main/java/com/ibm/streams/sch/composer/IEUComposer.java
|
/*
* Copyright 2021 IBM 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.
*/
package com.ibm.streams.sch.composer;
import com.api.json.JSONArray;
import com.ibm.streams.admin.internal.api.StreamsException;
import com.ibm.streams.admin.internal.api.config.PropertyDefinition.JobResourceSharing;
import com.ibm.streams.admin.internal.api.trace.Trace;
import com.ibm.streams.admin.internal.api.trace.TraceLogger.Level;
import com.ibm.streams.instance.sam.model.composer.ContainerSpecification;
import com.ibm.streams.instance.sam.model.topology.Hostpool;
import com.ibm.streams.instance.sam.model.topology.MembershipMode;
import com.ibm.streams.instance.sam.model.topology.Partitions;
import com.ibm.streams.instance.sam.model.topology.Resources;
import com.ibm.streams.instance.sam.model.topology.TopologyApplication;
import com.ibm.streams.instance.sam.model.topology.TopologyNode;
import com.ibm.streams.messages.StreamsRuntimeMessagesKey;
import com.ibm.streams.platform.services.AdditionalExceptionDataType;
import com.ibm.streams.platform.services.MessageElementType;
import com.ibm.streams.sch.SCHLocationGroupManager;
import com.ibm.streams.sch.SCHPartitionColocationGroup;
import com.ibm.streams.sch.SupportFunctions;
import com.ibm.streams.sch.composer.fusingRules.ComposerContainerComparator;
import com.ibm.streams.sch.composer.fusingRules.FusableUnitComparator;
import com.ibm.streams.sch.composer.fusingRules.FusingCycleComparator;
import com.ibm.streams.sch.exceptions.IncompatibleFusingConstraintsException;
import com.ibm.streams.sch.exceptions.InvalidPlacementStrategyException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class IEUComposer {
/*
* Constant definitions.
*/
private static final String PARTITIONS = "P_CFG:";
private static final String RESOURCES = "R_CFG:";
private static final String FC_PREFIX = "$_$_FC: ";
private static final int OPS_PER_RESOURCE = 8;
/*
* Static members.
*/
private static Map<String /*groupType*/, Map<String /*groupId*/, String /*alias*/>>
_groupAliasIds;
/*
* Members.
*/
private TopologyApplication _topApp;
private Set<ContainerSpecification> _precomposedContSpecs; // passed in
private Set<ComposedContainer>
_precomposedContainers; // derived from contSpecs, after model built.
private List<FusableUnit> _fusUnits;
private Map<BigInteger, ComposerCriteriaNode> _compCriteriaNodes;
private SCHLocationGroupManager _locGrpMgr;
private long _nextFuId;
private long _nextContainerId;
private long _nextCritNode;
private SortedMap<TopologyNode, FusableUnit> _topNodeToFuMap;
private long _fusionPhaseBeginTime_ms;
private Map<BigInteger, Integer> _resToRequest;
private List<ResourceRequest> _additionalResToRequest;
private Set<String> _resToRemove;
private Integer _peToCoreRatio;
private Integer _fusionCurfew;
private Integer _minOpsPerPe;
private Integer _proposedOpsPerResource;
private JobResourceSharing _jobResourceSharing;
private boolean _jobSubmission;
private Set<ResourceAcquistionMessage> _resAcquistionMessages;
private int _numOfAugmentedContainers = 0;
private JSONArray _resTruncatedMessages;
/*
* Inner class definitions.
*/
static class ContainerSpecInfo {
int _numOfContainers;
int _minNumOfOpsPerContainer;
ContainerSpecInfo(int numOfConts, int minNumOpsPerPe) {
_numOfContainers = numOfConts;
_minNumOfOpsPerContainer = minNumOpsPerPe;
}
public String toString() {
return "HostSpecInfo: numOfCont["
+ _numOfContainers
+ "] minNumOpsCont["
+ _minNumOfOpsPerContainer
+ "]";
}
}
public static class ComposerConfig {
public Integer _peToCoreRatio;
public Integer _minOpsPerPe;
public Integer _fusionCurfew;
// public Integer _numOfTargetOperators;
public Integer _proposedOpsPerResource;
public JobResourceSharing _jobResourceSharing;
public boolean _jobSubmission;
public ComposerConfig() {
_jobSubmission = true;
}
}
public static class PreComposedInfo {
Set<ComposedContainer> _nonTargetComposedContainers;
Set<FusableUnit> _nonTargetFus;
PreComposedInfo(
Set<ComposedContainer> relevantPreComposedContainers,
Set<FusableUnit> relevantPreComposedFus) {
_nonTargetComposedContainers = relevantPreComposedContainers;
_nonTargetFus = relevantPreComposedFus;
}
}
public static class ResourceAcquistionMessage {
public String _resAcqType;
public String _acquiredNum;
public String _requestedNum;
public String _taggingRequirements;
public String _opsPerRes;
public ResourceAcquistionMessage(
String resAcqType,
String acquiredNum,
String requestedNum,
String tagRqmts,
String opsPerRes) {
_resAcqType = resAcqType;
_acquiredNum = acquiredNum;
_requestedNum = requestedNum;
_taggingRequirements = tagRqmts;
_opsPerRes = opsPerRes;
}
}
public static class ResourceRequest {
int _num;
public Set<String> _tags;
boolean _considerResourcesWithinJobForAddition;
public ResourceRequest(
int num, Set<String> tags, boolean considerResourcesWithinJobForAddition) {
_num = num;
_tags = tags;
_considerResourcesWithinJobForAddition = considerResourcesWithinJobForAddition;
}
public String toString() {
return "ResRqst["
+ _num
+ "] {"
+ _tags
+ "} consider("
+ _considerResourcesWithinJobForAddition
+ ")";
}
}
/*
* Duplicated STD functions.
*/
private int roundUp(int num, int div) {
return ((num + div - 1) / div);
}
private static String pad(String target, int numOfSpaces) {
StringBuilder st = new StringBuilder();
for (int x = 0; x < numOfSpaces; x++) {
st.append(" ");
}
st.append(target);
return st.toString();
}
/*
* Constructor.
*/
public IEUComposer(TopologyApplication topApp, Set<ContainerSpecification> precomposedContSpecs) {
_fusUnits = new ArrayList<>();
_compCriteriaNodes = new HashMap<BigInteger, ComposerCriteriaNode>();
_nextFuId = 0;
_nextContainerId = 0;
_nextCritNode = 0;
_topNodeToFuMap = new TreeMap<>();
_topApp = topApp;
if (precomposedContSpecs != null) {
_precomposedContSpecs = precomposedContSpecs;
} else {
_precomposedContSpecs = new HashSet<>();
}
_precomposedContainers = new HashSet<>();
_peToCoreRatio = null;
_fusionCurfew = null;
_minOpsPerPe = null;
_locGrpMgr = new SCHLocationGroupManager();
_resToRequest = new HashMap<>();
_additionalResToRequest = new ArrayList<>();
_resToRemove = new HashSet<>();
_resAcquistionMessages = new HashSet<>();
_resTruncatedMessages = new JSONArray();
_groupAliasIds = new HashMap<>();
}
/*
* Class methods.
*/
private static List<String> alignNodeAbstracts(List<String> nodeAbstracts, String keyword) {
int maxPartIndex = 0;
for (String line : nodeAbstracts) {
int partIndex = line.indexOf(keyword);
if (partIndex > maxPartIndex) {
maxPartIndex = partIndex;
}
}
List<String> alignedNodeAbstracts = new ArrayList<>();
for (String line : nodeAbstracts) {
int partIndex = line.indexOf(keyword);
alignedNodeAbstracts.add(line.replaceFirst(keyword, pad(keyword, maxPartIndex - partIndex)));
}
return alignedNodeAbstracts;
}
private static String traceTopologyNodeAbstract(TopologyNode node) {
StringBuilder st = new StringBuilder();
st.append(node.getName() + " (" + node.getIndex() + ") ");
Partitions partConstr = node.getPartitions();
if (partConstr != null) {
st.append(PARTITIONS + "<");
if ((partConstr.getCoLocations() != null) && (partConstr.getCoLocations().size() > 0)) {
st.append("c[" + getAliases(partConstr.getCoLocations(), "c") + "] ");
}
if ((partConstr.getExLocations() != null) && (partConstr.getExLocations().size() > 0)) {
st.append("x[" + getAliases(partConstr.getExLocations(), "x") + "] ");
}
if (partConstr.isIsolation()) {
st.append("i[true] ");
}
if (partConstr.isSoftIsolation()) {
st.append("j[true] ");
}
if ((partConstr.getProvisionalLocations() != null)
&& (partConstr.getProvisionalLocations().size() > 0)) {
st.append("v[" + partConstr.getProvisionalLocations() + "] ");
}
if ((partConstr.getSoftProvisionalLocations() != null)
&& (partConstr.getSoftProvisionalLocations().size() > 0)) {
st.append("u[" + partConstr.getSoftProvisionalLocations() + "] ");
}
if ((partConstr.getSegregatedLocations() != null)
&& (partConstr.getSegregatedLocations().size() > 0)) {
st.append("g[" + partConstr.getSegregatedLocations() + "] ");
}
if ((partConstr.getSoftSegregatedLocations() != null)
&& (partConstr.getSoftSegregatedLocations().size() > 0)) {
st.append("f[" + partConstr.getSoftSegregatedLocations() + "] ");
}
st.append("> ");
}
Resources resConstr = node.getResources();
if (resConstr != null) {
st.append(RESOURCES + "<");
if ((resConstr.getCoLocations() != null) && (resConstr.getCoLocations().size() > 0)) {
Set<String> scrubbedCoLoc = new HashSet<>();
for (String cgId : resConstr.getCoLocations()) {
if (!cgId.startsWith(ComposerCriteriaNode.INFERRED_COLOCATION)) {
scrubbedCoLoc.add(cgId);
}
}
if (scrubbedCoLoc.size() > 0) {
st.append("C[" + getAliases(scrubbedCoLoc, "C") + "] ");
}
}
if ((resConstr.getExLocations() != null) && (resConstr.getExLocations().size() > 0)) {
st.append("X[" + getAliases(resConstr.getExLocations(), "X") + "] ");
}
if (resConstr.isIsolation()) {
st.append("I[true] ");
}
if (resConstr.getHostLocation() != null) {
st.append("H[" + resConstr.getHostLocation() + "] ");
} else {
if (resConstr.getPoolLocation() != null) {
st.append("P[" + resConstr.getPoolLocation().getPoolIndex() + "");
if (resConstr.getPoolLocation().getInpoolIndex() != null) {
st.append("(" + resConstr.getPoolLocation().getInpoolIndex() + ")");
}
st.append("] ");
}
}
st.append("> ");
}
if (!node.isRestartable()) {
st.append("!R ");
}
if (!node.isRelocatable()) {
st.append("!r ");
}
return st.toString();
}
private static Set<String> getAliases(Set<String> groupIds, String groupType) {
Set<String> aliases = new HashSet<>();
for (String groupId : groupIds) {
aliases.add(getAlias(groupId, groupType));
}
return aliases;
}
private static String getAlias(String groupId, String groupType) {
if (_groupAliasIds == null) {
_groupAliasIds = new HashMap<>();
}
Map<String, String> aliasMap = _groupAliasIds.computeIfAbsent(groupType, k -> new HashMap<>());
String alias = aliasMap.get(groupId);
if (alias == null) {
alias = groupType + aliasMap.size();
aliasMap.put(groupId, alias);
}
return alias;
}
public static void traceTopologyModelAbstract(String header, TopologyApplication topApp) {
StringBuilder st = new StringBuilder();
st.append(header + "$@$@ TopologyModelAbstract:\n");
st.append("Hostpools: \n");
for (Hostpool hPool : topApp.getHostpools().values()) {
st.append(
" pool["
+ hPool.getIndex()
+ ","
+ hPool.getName()
+ "] "
+ ((hPool.getSize() != null) ? "size[" + hPool.getSize() + "] " : " ")
+ ((hPool.getMembershipMode().equals(MembershipMode.exclusive))
? "mMode[" + hPool.getMembershipMode().toString() + "]"
: " ")
+ " tags{"
+ hPool.getTags()
+ "}\n");
for (String hostName : hPool.getHosts()) {
st.append(" " + hostName + "\n");
}
}
List<String> nodeAbstracts = new ArrayList<>();
for (TopologyNode node : topApp.getNodes()) {
nodeAbstracts.add(traceTopologyNodeAbstract(node));
}
for (String nodeAbst :
alignNodeAbstracts(alignNodeAbstracts(nodeAbstracts, PARTITIONS), RESOURCES)) {
st.append(nodeAbst + "\n");
}
st.append("Alias ID Map:" + "\n");
st.append(_groupAliasIds);
st.append(" \n");
Trace.logDebug(st.toString());
Trace.logDebug("abstract complete.");
}
/*
* Methods.
*/
// only return new container specs...
// - don't return precomposed ones.
public Set<ContainerSpecification> composeContainerSpecs(ComposingInstructions inst)
throws StreamsException {
if (Trace.isEnabled(Level.DEBUG)) {
Trace.logDebug("$_$_$_cmp_b4");
Trace.logDebug(">>>>>>>>>>>>>> composeContainerSpecs[" + inst.toString() + "]");
// Trace.logDebug("Topology to compose ... \n" + _topApp.toString());
Trace.logDebug(dumpConfig());
Trace.logDebug("composer cfg: " + getConfigSettings());
traceTopologyModelAbstract("decorated ", _topApp);
}
_fusionPhaseBeginTime_ms = System.currentTimeMillis();
// best container collection after all fusing cycles done.
List<ComposedContainer> bestContainerCollection = new ArrayList<>();
Trace.logDebug("Fusing Cycles[" + inst.getFusingCycles().size() + "]");
int fusCycleNum = 1;
Integer fixedTargetNumOfContainers = null;
// fusing cycle
fusCycleLoop:
for (FusingCycle fusCycle : inst.getFusingCycles()) {
List<ComposedContainer> completedCompContainers = null;
Trace.logDebug("*************************************************************");
Trace.logDebug(
"************** Fusing cycle ["
+ fusCycleNum
+ "] StrategyScript["
+ fusCycle.toString()
+ "] ***************");
switch (inst.getComposingStyle()) {
case FUSE_TO_ONE:
{
Trace.logDebug("$$$Comp: Fuse_to_one");
validateFusableUnits();
ComposedContainer cont = new ComposedContainer(this);
cont.addFusableUnits(_fusUnits);
bestContainerCollection.add(cont);
Trace.logDebug("fuse to one - complete.");
break fusCycleLoop;
}
case FUSE_LEGACY:
{
Trace.logDebug("$$$Comp: FUSE_LEGACY");
validateFusableUnits();
PreComposedInfo preCompInfo =
processPreComposedContainers(_precomposedContainers, _fusUnits);
bestContainerCollection.addAll(preCompInfo._nonTargetComposedContainers);
Set<FusableUnit> remainingFus = new HashSet<>(_fusUnits);
remainingFus.removeAll(preCompInfo._nonTargetFus);
for (FusableUnit fu : remainingFus) {
ComposedContainer cont = new ComposedContainer(this);
cont.addFusableUnit(fu);
bestContainerCollection.add(cont);
}
Trace.logDebug("FUSE_LEGACY done.");
break fusCycleLoop;
}
case FUSE_MANUAL:
{
Trace.logDebug("$$$Comp: FUSE_MANUAL");
validateFusableUnits();
fixedTargetNumOfContainers = inst.getFixedNumOfContainers();
completedCompContainers = performManualFusion(fixedTargetNumOfContainers, fusCycle);
Trace.logDebug("fuse to avail - complete.");
break;
}
default:
{
Trace.logError("Invalid comp style.");
break fusCycleLoop;
}
}
Trace.logDebug(
"****** completed containers["
+ completedCompContainers.size()
+ "] after fusCycle["
+ fusCycleNum
+ "]");
int numInterConns = 0;
for (ComposedContainer cont : completedCompContainers) {
Trace.logDebug("***** Container: " + cont.getAbstract());
numInterConns += cont.numOfInterContainerConnections();
}
Trace.logDebug(
"FusCycle_Results["
+ fusCycleNum
+ "] numConts["
+ completedCompContainers.size()
+ "] numInterConns["
+ numInterConns
+ "]");
fusCycleNum++;
bestContainerCollection =
selectBestContainerAssignments(
bestContainerCollection, completedCompContainers, inst, fixedTargetNumOfContainers);
if (pastCurfew()) {
break;
}
}
// bestContainerCollection contains the results.
// create container specs...
int actualNumOfContainers = bestContainerCollection.size();
Trace.logDebug("Total PE Count[" + actualNumOfContainers + "] ");
Trace.logDebug("<<<<<<<<<<< numOfContainersReturned[" + actualNumOfContainers + "]");
if ((fixedTargetNumOfContainers != null)
&& fixedTargetNumOfContainers != actualNumOfContainers) {
Trace.logWarn(
"Num of containers not able to be achieved. Target["
+ fixedTargetNumOfContainers
+ "] Actual["
+ actualNumOfContainers
+ "]");
SupportFunctions.productLog(
StreamsRuntimeMessagesKey.Key.SCHUnattainableFusionCount,
SupportFunctions.SCH_COMPUTE_PLACEMENT_FOR_JOB,
fixedTargetNumOfContainers,
actualNumOfContainers);
}
Set<ContainerSpecification> containerSpecs = new HashSet<>();
for (ComposedContainer compCont : bestContainerCollection) {
containerSpecs.add(new ContainerSpecification(compCont));
Trace.logDebug(" Container: " + compCont.toString());
}
Trace.logDebug("$_$_$_cmp_af");
for (ComposedContainer cont : bestContainerCollection) {
Trace.logDebug("***** Container: " + cont.getAbstract());
}
Trace.logDebug("complete set of containerSpecs: " + containerSpecs);
Trace.logDebug("remove pre-composed containers: " + _precomposedContSpecs);
containerSpecs.removeAll(_precomposedContSpecs);
Trace.logDebug("only new containerSpecs: " + containerSpecs);
return containerSpecs;
}
private boolean pastCurfew() {
if (_fusionCurfew == null) {
return false;
}
long currentTime_ms = System.currentTimeMillis();
long elapsedTime_ms = currentTime_ms - _fusionPhaseBeginTime_ms;
return (elapsedTime_ms > (_fusionCurfew * 1000));
}
public JSONArray getResourceRequestTruncationMessage() {
return _resTruncatedMessages;
}
private List<ComposedContainer> performManualFusion(
Integer fixedNumOfContainers, FusingCycle fusCycle) {
List<ComposedContainer> completedCompContainers = new ArrayList<>();
// determine of containers to target.
int numOfCcs = 1;
Trace.logDebug("initialized num of containers[" + numOfCcs + "]");
if (fixedNumOfContainers != null) {
numOfCcs = fixedNumOfContainers;
Trace.logDebug("Inst: fixed num of containers[" + numOfCcs + "]");
} else {
if (fusCycle._numOfContainers != null) {
numOfCcs = fusCycle._numOfContainers;
Trace.logDebug("fusCycle: numOfContainers[" + numOfCcs + "]");
}
}
Trace.logDebug("num of containers[" + numOfCcs + "]");
if (numOfCcs > _topApp.getNodes().size()) {
Trace.logDebug(
"Adjusting numOfContainers from specifed["
+ numOfCcs
+ "] to numOfNodes["
+ _topApp.getNodes().size()
+ "]");
numOfCcs = _topApp.getNodes().size();
}
// move isolation FUs to their own completed containers
List<FusableUnit> nonPlacedFus = new ArrayList<>(_fusUnits);
Trace.logDebug(FC_PREFIX + "Manual: numOfCcs[" + numOfCcs + "]");
// populate containers with FUs
completedCompContainers.addAll(
populateContainers(nonPlacedFus, fusCycle, numOfCcs, _precomposedContainers));
return completedCompContainers;
}
// preprocess the precomposed containers
// - create initial containers
// - extract FUs included in these containers from the FUs remaining to be composed.
private PreComposedInfo processPreComposedContainers(
Set<ComposedContainer> precomposedContainers, List<FusableUnit> hSpec_fus) {
Set<FusableUnit> preplacedFus = new HashSet<>();
Set<ComposedContainer> preplacedCompContainers = new HashSet<>();
for (FusableUnit fu : hSpec_fus) {
for (ComposedContainer cont : precomposedContainers) {
if (cont.contains(fu)) {
preplacedFus.add(fu);
preplacedCompContainers.add(cont);
break;
}
}
}
return new PreComposedInfo(preplacedCompContainers, preplacedFus);
}
// input:
// - hSpec - (null = all resources considered)
// - num of containers (null = no fixed number)
// - min num of ops per container
// - fus to be placed into containers
// - fusing rules
// - pre-composed containers, and related pre-composed fu's
// output:
// - new composed containers (i.e. not including precomposed containers)
private Set<ComposedContainer> populateContainers(
List<FusableUnit> hSpec_fus,
FusingCycle fusCycle,
Integer fixedNumOfContainers,
Set<ComposedContainer> nonTargetContainers) {
Trace.logDebug(
FC_PREFIX
+ " populateContainers nonPlacedFus: \n"
+ hSpec_fus.toString()
+ " fusCycle: "
+ fusCycle.toString());
Set<ComposedContainer> completedCompContainers;
Set<String> tagSet = new HashSet<>();
boolean numOfContainersFixed = (fixedNumOfContainers != null);
PreComposedInfo hSpec_nonTargetCompInfo =
processPreComposedContainers(nonTargetContainers, hSpec_fus);
Set<FusableUnit> targetFus = new HashSet<>(hSpec_fus);
targetFus.removeAll(hSpec_nonTargetCompInfo._nonTargetFus);
ContainerSpecInfo peContInfo = determineNumContainersPerHostSpec(fixedNumOfContainers);
int predictedNumOfContainersRemaining = peContInfo._numOfContainers;
int minNumOfOpsPerContainer = peContInfo._minNumOfOpsPerContainer;
// $upo$ target ops & res's
Trace.logDebug(
"NumPreplacedConts[" + hSpec_nonTargetCompInfo._nonTargetComposedContainers.size() + "]");
Trace.logDebug(
"Preplaced containers{" + hSpec_nonTargetCompInfo._nonTargetComposedContainers + "}");
Trace.logDebug("NumOfTargetFus[" + targetFus.size() + "]");
Trace.logDebug(
"Initial fus to be placed{"
+ hSpec_fus
+ "} \n Remaining fus to be placed{"
+ targetFus
+ "}");
clearAugContCnt();
// true initial value disables spillOver function.
// spillOver may not be functional anymore. check b4 enabling.
boolean spillOver = false;
completedCompContainers = new HashSet<>(hSpec_nonTargetCompInfo._nonTargetComposedContainers);
List<FusableUnit> remainingTargetFusToBePlaced = new ArrayList<>(targetFus);
Set<FusableUnit> isolatedFuConts = new HashSet<>();
int numIsolatedContainers = 0;
Trace.logDebug("move isolation FUs to their own containers.");
for (FusableUnit fu : remainingTargetFusToBePlaced) {
if (fu.isPartitionIsolated() || fu.isPartitionSoftIsolated()) {
Trace.logDebug("isolated FU found[" + fu.getAbstract() + "]");
ComposedContainer targetCont = new ComposedContainer(this);
targetCont.addFusableUnit(fu);
completedCompContainers.add(targetCont);
numIsolatedContainers++;
isolatedFuConts.add(fu);
}
}
remainingTargetFusToBePlaced.removeAll(isolatedFuConts);
// setup available containers.
Set<ComposedContainer> availCompContainers = new HashSet<>();
predictedNumOfContainersRemaining -= numIsolatedContainers;
if (predictedNumOfContainersRemaining < 0) {
Trace.logDebug(
"predictedNumOfConts["
+ predictedNumOfContainersRemaining
+ "] numIsolatedConts["
+ numIsolatedContainers
+ "]");
predictedNumOfContainersRemaining = 0;
}
for (int i = 0; i < (predictedNumOfContainersRemaining); i++) {
availCompContainers.add(new ComposedContainer(this));
}
// continue until all FUs have been placed into a container
Trace.logDebug("place all remaining FUs to best containers.");
FusableUnitComparator fuComp = new FusableUnitComparator(fusCycle);
ComposedContainer targetCont = null;
boolean chainInProgress = false;
// minimize chance of empty containers in manual scheme, go into shortcut mode.
while (remainingTargetFusToBePlaced.size() > 0) {
if (numOfContainersFixed) {
// detect if running out of operators to place in empty containers.
// if so, break the chain.
if (remainingTargetFusToBePlaced.size() <= availCompContainers.size()) {
for (ComposedContainer cont : availCompContainers) {
if (cont.isEmpty()) {
// break the chain.
targetCont = null;
break;
}
}
Trace.logDebug(
"short cut mode. remainingFus["
+ remainingTargetFusToBePlaced.size()
+ "] availConts["
+ availCompContainers.size()
+ "]");
}
}
Trace.logDebug("===== remaining FUs = [" + remainingTargetFusToBePlaced.size() + "]");
if (targetCont != null && (fuComp.anySecondaryCompareRulesSpecified())) {
Trace.logDebug("chain continuation");
// secondary compare
chainInProgress = true;
fuComp.setPrimaryCompare(false);
} else {
// primary compare
Trace.logDebug("head of chain.");
targetCont = selectBestContainer(fusCycle, availCompContainers);
fuComp.setPrimaryCompare(true);
}
Trace.logDebug(
" BestCont"
+ ((chainInProgress) ? "*CH" : "")
+ "["
+ targetCont.getDisplayName()
+ "] remainingFus["
+ remainingTargetFusToBePlaced.size()
+ "]");
// disabled dynamic updating of target num of ops. didn't behave well at end of cycle.
int targetNumOfOpsPerContainer =
determineNumOfOpsPerContainer(
remainingTargetFusToBePlaced, availCompContainers, minNumOfOpsPerContainer);
Trace.logDebug(
"targetNumOfOpsCont["
+ targetNumOfOpsPerContainer
+ "] numNonPlacedFus["
+ remainingTargetFusToBePlaced.size()
+ "] availCompCont["
+ availCompContainers.size()
+ "] minNumOfOpsCont["
+ minNumOfOpsPerContainer
+ "]");
targetCont.setNumberOfTargetOperators(targetNumOfOpsPerContainer);
// find best FU for container
FusableUnit fusUnit =
selectBestFuForContainer(targetCont, remainingTargetFusToBePlaced, fuComp);
if (fusUnit != null) {
// FU found
Trace.logDebug("acceptable FU[" + fusUnit.getAbstract() + "] found for container");
Trace.logDebug("before adding FU to container => " + targetCont.getAbstract());
targetCont.addFusableUnit(fusUnit);
Trace.logDebug(
"after adding Fu[" + fusUnit.getId() + "] to Container: " + targetCont.getAbstract());
remainingTargetFusToBePlaced.remove(fusUnit);
Trace.logDebug(" BestFu_found" + "[" + fusUnit.getId() + "] ");
if (targetCont.full() /* || shortCut*/) {
Trace.logDebug(" Container=FULL:" + targetCont.getDisplayName());
if ((fixedNumOfContainers == null) /* || shortCut*/) {
Trace.logDebug("full container[" + targetCont.getId() + "] detected.. completing it.");
promoteContainerToCompleted(targetCont, availCompContainers, completedCompContainers);
}
chainInProgress = false;
targetCont = null;
}
} else {
// no FU found
Trace.logDebug("no FU found.");
if (!chainInProgress) {
Trace.logDebug(
"not in chain continuation. so completing container[" + targetCont.getId() + "]");
promoteContainerToCompleted(targetCont, availCompContainers, completedCompContainers);
}
Trace.logDebug(" BestFu_found[NONE]" + ((!chainInProgress) ? "=Completed" : ""));
chainInProgress = false;
targetCont = null;
}
}
// promote remaining containers to completed
int releasedContainers =
promoteAllRemainingContainersToCompleted(availCompContainers, completedCompContainers);
int numOfNewContainers =
completedCompContainers.size()
- hSpec_nonTargetCompInfo._nonTargetComposedContainers.size();
Trace.logDebug(
"ComposedPE Summary: HSpec["
+ null
+ "] TotalPEs["
+ completedCompContainers.size()
+ "] NewPEs["
+ numOfNewContainers
+ "] InitPeCnt["
+ peContInfo._numOfContainers
+ "] AugPeCont["
+ getAugContCnt()
+ "] RlsdPeCont["
+ releasedContainers
+ "] ");
if (Trace.isEnabled(Level.DEBUG)) {
Trace.logDebug(" containers: ");
StringBuilder str = new StringBuilder();
str.append("\n");
for (ComposedContainer compCont : completedCompContainers) {
str.append(" " + compCont.getAbstract());
}
Trace.logDebug(str.toString() + "\n");
}
Trace.logDebug("populate containers end.");
return completedCompContainers;
}
// determine how many PEs per hostSpec (derived from num of resources & FUs)
// - also, min num of procs per host
// special handling
// - declared hosts
// - indexed w/in hostpool
private ContainerSpecInfo determineNumContainersPerHostSpec(Integer fixedNumPes) {
return new ContainerSpecInfo(fixedNumPes, 1);
}
private int determineNumOfOpsPerContainer(
List<FusableUnit> nonPlacedFus,
Set<ComposedContainer> availCompContainers,
int minNumOfOpsPerContainer) {
if (availCompContainers.size() == 0) {
return minNumOfOpsPerContainer;
}
int numOfRemainingOps = 0;
for (FusableUnit fu : nonPlacedFus) {
numOfRemainingOps += fu.getCompositeCcNodes().size();
}
int numOfPendingCompletionOps = 0;
int numOfNonFullContainers = 0;
for (ComposedContainer cont : availCompContainers) {
if (!cont.full()) {
numOfPendingCompletionOps += cont.getNumOfFusedNodes();
numOfNonFullContainers++;
}
;
}
int numOfOpsPerCont =
roundUp(
(numOfRemainingOps + numOfPendingCompletionOps),
((numOfNonFullContainers != 0) ? numOfNonFullContainers : 1));
if (minNumOfOpsPerContainer > numOfOpsPerCont) {
numOfOpsPerCont = minNumOfOpsPerContainer;
}
return (numOfOpsPerCont);
}
private List<ComposedContainer> selectBestContainerAssignments(
List<ComposedContainer> bestContainerCollection,
List<ComposedContainer> challengerCompContainers,
ComposingInstructions inst,
Integer fixedTargetNumOfContainers)
throws InvalidPlacementStrategyException {
FusingCycleComparator comp =
new FusingCycleComparator(inst.getFusingCycleCompareVector(), fixedTargetNumOfContainers);
List<ComposedContainer> selectedColl = bestContainerCollection;
boolean newChamp = false;
if (bestContainerCollection.size() == 0) {
selectedColl = challengerCompContainers;
newChamp = true;
} else {
Integer result = comp.compare(bestContainerCollection, challengerCompContainers);
if (result != null) {
if (result > 0) {
selectedColl = challengerCompContainers;
newChamp = true;
}
}
}
Trace.logDebug(" " + (newChamp ? "Champ=new" : "Champ=same"));
return selectedColl;
}
private void promoteContainerToCompleted(
ComposedContainer cont,
Set<ComposedContainer> availCompContainers,
Set<ComposedContainer> completedCompContainers) {
completedCompContainers.add(cont);
availCompContainers.remove(cont);
}
private int promoteAllRemainingContainersToCompleted(
Set<ComposedContainer> availCompContainers, Set<ComposedContainer> completedCompContainers) {
int releasedContainers = 0;
for (ComposedContainer cont : availCompContainers) {
if (!cont.isEmpty()) {
completedCompContainers.add(cont);
} else {
releasedContainers++;
}
}
availCompContainers.clear();
return releasedContainers;
}
private FusableUnit selectBestFuForContainer(
ComposedContainer cont, List<FusableUnit> fus, FusableUnitComparator fuComp) {
Trace.logDebug("select best FU for container.");
FusableUnit champFu = null;
List<MessageElementType> problemMessages = null;
// init comparator to this container
fuComp.setContainer(cont);
fuComp.clearJrnlMsg();
FusableUnitComparator.addJrnlMsg("FusJrnl:");
// sort fus according to best match with container.
Collections.sort(fus, fuComp);
Trace.logDebug("======== Sorted FUs: ============ " + "\n" + fus.toString());
for (FusableUnit fu : fus) {
// through priority order, look for first one that is compatible.
problemMessages = new ArrayList<>();
if (FusingConstraintChecker._internalDebugMessages) {
Trace.logDebug(
"FCR_CC compare fu[" + fu.getAbstract() + "] against cc[" + cont.getAbstract() + "]");
Trace.logDebug("--- FU operator constraints for: " + fu.getAbstract());
for (ComposerCriteriaNode ccNode : fu.getCompositeCcNodes()) {
Trace.logDebug(
ComposerSupportHelper.convertMessageToText(
ccNode.getCurrentConstraintMessage(null, false)));
}
Trace.logDebug("--- container constraints for: " + cont.getAbstract());
for (ComposerCriteriaNode ccNode : cont.getCompositeCcNodes()) {
Trace.logDebug(
ComposerSupportHelper.convertMessageToText(
ccNode.getCurrentConstraintMessage(null, false)));
}
}
// check if compatible with chain
if (fuComp.compatibleWithChain(fu, cont)) {
// check if constraints are compatible
Set<ComposerCriteriaNode> hostColocatedNodes = new HashSet<>();
FusingConstraintChecker fcc = new FusingConstraintChecker(fu, cont, this);
if (fcc.checkForIncompatibleConstraints(
false, false, true, problemMessages, hostColocatedNodes)
== null) {
champFu = fu;
break;
} else {
Trace.logDebug(" FU" + fu.getId() + " =Rejected, not constraint compatible");
for (String textMsg : ComposerSupportHelper.convertMessagesToText(problemMessages)) {
Trace.logDebug(textMsg);
}
continue;
}
} else {
Trace.logDebug(" FU" + fu.getId() + " =Rejected, not chain compatible");
continue;
}
}
// Trace.logDebug("BestFU[] from Journal= " + _fuComp.getJrnlMsg());
return champFu;
}
private void clearAugContCnt() {
_numOfAugmentedContainers = 0;
}
private void incAugContCnt() {
_numOfAugmentedContainers++;
}
private int getAugContCnt() {
return _numOfAugmentedContainers;
}
private ComposedContainer createNewContainer(Set<ComposedContainer> availCompContainers) {
ComposedContainer newCont = new ComposedContainer(this);
availCompContainers.add(newCont);
incAugContCnt();
return (newCont);
}
private ComposedContainer selectBestContainer(
FusingCycle fusCycle, Set<ComposedContainer> out_availCompContainers) {
// Trace.logDebug("===== Select best container from availContainers["+availCompContainers+"]");
List<ComposedContainer> orderedAvailCompContainers = new ArrayList<>(out_availCompContainers);
ComposedContainer bestContainer = null;
if (orderedAvailCompContainers.size() > 0) {
ComposerContainerComparator ccComp =
new ComposerContainerComparator(fusCycle._containerCompareVector);
Collections.sort(orderedAvailCompContainers, ccComp);
Trace.logDebug("Sorted: availCompContainers: " + orderedAvailCompContainers.toString());
bestContainer = orderedAvailCompContainers.get(0);
} else {
Trace.logDebug("No avail containers, so create new one.");
bestContainer = createNewContainer(out_availCompContainers);
}
// _availCompContainers.remove(bestContainer);
Trace.logDebug("===== best container = " + bestContainer.toString() + "\n");
return (bestContainer);
}
private void validateFusableUnits() throws StreamsException {
AdditionalExceptionDataType jobAedt = new AdditionalExceptionDataType();
boolean problemFound = false;
for (FusableUnit fusUnit : _fusUnits) {
AdditionalExceptionDataType peAedt = fusUnit.validate(true);
if (peAedt != null) {
jobAedt.getNestedAdditionalExceptionData().add(peAedt);
problemFound = true;
}
}
if (problemFound) {
throw new IncompatibleFusingConstraintsException(jobAedt);
}
}
FusableUnit getFuForTopNode(TopologyNode tNode) {
return (_topNodeToFuMap.get(tNode));
}
private void buildTopNodeToFuMap() {
for (FusableUnit fu : _fusUnits) {
for (TopologyNode node : fu.getTopologyNodes()) {
_topNodeToFuMap.put(node, fu);
}
}
}
private void buildComposerCriteriaNodeGraph() {
_compCriteriaNodes = new HashMap<>();
for (TopologyNode node : _topApp.getNodes()) {
if (node == null) {
Trace.logError("!!!!!!!!!!!!!!!!! null node found !!!!!!!!!!!!!!!!!!!");
}
ComposerCriteriaNode ccNode = new ComposerCriteriaNode(node, this);
_compCriteriaNodes.put(ccNode.getNodeIndex(), ccNode);
_locGrpMgr.addCcNodeToAssociatedOperatorHostLocationGroups(ccNode);
}
for (ComposerCriteriaNode ccn : _compCriteriaNodes.values()) {
ccn.setCpuUsage(5);
}
int pCg_id = 0;
// synthesize partition co-locates for hostIsol/co-locate nodes.
for (ComposerCriteriaNode ccN : _compCriteriaNodes.values()) {
if (ccN.isHostIsolation()) {
for (ComposerCriteriaNode ccN_hcg : _locGrpMgr.getCgCoMembers(ccN)) {
ccN_hcg.addPartitionColocationGroupId(
ComposerCriteriaNode.INFERRED_COLOCATION_PARTITION + pCg_id);
}
pCg_id++;
}
}
for (ComposerCriteriaNode ccNode : _compCriteriaNodes.values()) {
_locGrpMgr.addNodeToAssociatedPartitionLocationGroups(ccNode);
}
}
private ComposerCriteriaNode getCcNode(BigInteger index) {
return _compCriteriaNodes.get(index);
}
private Collection<ComposerCriteriaNode> getCcNodes() {
return (_compCriteriaNodes.values());
}
/// Build fusable Units from nodes in topology
private void buildFusableUnits(boolean fuseToOne) {
Set<BigInteger> alreadyAcctdFor = new HashSet<>();
if (fuseToOne) {
FusableUnit fu = new FusableUnit(this);
fu.addCriteriaNodes(getCcNodes());
_fusUnits.add(fu);
} else {
for (TopologyNode node : _topApp.getNodes()) {
if (!alreadyAcctdFor.contains(node.getIndex())) {
// not already accounted for, then ...
FusableUnit newFu = new FusableUnit(this);
_fusUnits.add(newFu);
// add CCN to FU (this will also add all co-located CCNs as well)
Set<BigInteger> newAcctdNodes = newFu.addCriteriaNode(getCcNode(node.getIndex()));
alreadyAcctdFor.addAll(newAcctdNodes);
} else {
Trace.logDebug(" node[" + node.getIndex() + "] already acctd for, skipping.");
}
}
}
buildTopNodeToFuMap();
for (FusableUnit fu : _fusUnits) {
fu.populateConnections();
if (fu.speciallyFused()) {
fu.setPartitionSoftIsolated(true);
}
}
Trace.logDebug("freshly built fusable units: ");
for (FusableUnit fu : _fusUnits) {
Trace.logDebug(fu.toString());
}
}
SCHPartitionColocationGroup getColocatedPartitionGroup(String id) {
return (_locGrpMgr.getPartitionColocGroup(id));
}
long getNextFusableUnitId() {
return (_nextFuId++);
}
long getNextContainerId() {
return (_nextContainerId++);
}
long getNextCritNodeId() {
return (_nextCritNode++);
}
Set<BigInteger> getExclusiveHostPools() {
Set<BigInteger> hpIndexes = new HashSet<>();
for (Hostpool hostPool : _topApp.getHostpools().values()) {
if (hostPool.getMembershipMode() == MembershipMode.exclusive) {
hpIndexes.add(hostPool.getIndex());
}
}
return hpIndexes;
}
Hostpool getHostPool(BigInteger poolIndex) {
return _topApp.getHostpools().get(poolIndex);
}
public TopologyApplication getApplication() {
return (_topApp);
}
public void buildComposerModel(boolean standAloneMode) {
buildComposerCriteriaNodeGraph();
buildFusableUnits(standAloneMode);
buildPrecomposedContainers();
}
private void buildPrecomposedContainers() {
for (ContainerSpecification cSpec : _precomposedContSpecs) {
_precomposedContainers.add(new ComposedContainer(this, cSpec));
}
}
public void setComposerConfig(ComposerConfig compCfg) throws StreamsException {
_peToCoreRatio = compCfg._peToCoreRatio;
_minOpsPerPe = compCfg._minOpsPerPe;
_fusionCurfew = compCfg._fusionCurfew;
_proposedOpsPerResource = compCfg._proposedOpsPerResource;
if (compCfg._jobResourceSharing != null) {
_jobResourceSharing = compCfg._jobResourceSharing;
} else {
_jobResourceSharing = JobResourceSharing.SAME_INSTANCE;
}
_jobSubmission = compCfg._jobSubmission;
}
Set<ComposerCriteriaNode> expandHostColocatedNodes(Set<ComposerCriteriaNode> origNodes) {
Set<ComposerCriteriaNode> expandedSet = new HashSet<>(origNodes);
Set<Set<ComposerCriteriaNode>> cohabitationSets = new HashSet<>();
for (Set<ComposerCriteriaNode> dGroup : getHostColocationGroups()) {
for (ComposerCriteriaNode ccN : dGroup) {
cohabitationSets.add(ccN.getFusingSets());
}
}
Set<Set<ComposerCriteriaNode>> workingDefinedGroups = new HashSet<>(getHostColocationGroups());
workingDefinedGroups.addAll(cohabitationSets);
Set<Set<ComposerCriteriaNode>> intersectSets = new HashSet<>();
do {
intersectSets.clear();
for (Set<ComposerCriteriaNode> definedGroup : workingDefinedGroups) {
Set<ComposerCriteriaNode> intSet = (new HashSet<>(expandedSet));
intSet.retainAll(definedGroup);
if (intSet.size() > 0) {
// intersection exists.
intersectSets.add(definedGroup);
}
}
for (Set<ComposerCriteriaNode> nSet : intersectSets) {
expandedSet.addAll(nSet);
}
workingDefinedGroups.removeAll(intersectSets);
} while (intersectSets.size() > 0);
return expandedSet;
}
public void setResourcesToRequest(
Map<BigInteger, Integer> resToRequest,
List<ResourceRequest> additionalResToRequest,
Set<String> resourceNamesToBeRemoved) {
_resToRequest = resToRequest;
_additionalResToRequest = additionalResToRequest;
_resToRemove = resourceNamesToBeRemoved;
}
private Collection<Set<ComposerCriteriaNode>> getHostColocationGroups() {
return _locGrpMgr.getColocOpGroups();
}
public Set<ResourceAcquistionMessage> getResourceAcquistionMessages() {
return _resAcquistionMessages;
}
public Integer getProposedOpsPerResource() {
if (_proposedOpsPerResource != null) {
return _proposedOpsPerResource;
} else {
return OPS_PER_RESOURCE;
}
}
private String getConfigSettings() {
return "peToCore["
+ _peToCoreRatio
+ "] minOpsPerPe["
+ _minOpsPerPe
+ "] resToRequest["
+ _resToRequest
+ "] additionalResToRequest["
+ _additionalResToRequest
+ "] opsPerRes["
+ _proposedOpsPerResource
+ "] jResSharingEnabled["
+ _jobResourceSharing
+ "] jobSubmit["
+ _jobSubmission
+ "] precomposedContSpes{"
+ _precomposedContSpecs
+ "}";
}
private String dumpConfig() {
return "Composer.config: minOpsPerPe["
+ _minOpsPerPe
+ "] peToCore["
+ _peToCoreRatio
+ "] proposedOpsPerRes["
+ _proposedOpsPerResource
+ "] jobSub["
+ _jobSubmission
+ "] resToRqst["
+ _resToRequest
+ "] adtlnRes["
+ _additionalResToRequest
+ "] removeRes["
+ _resToRemove
+ "] \npreComposed["
+ _precomposedContSpecs
+ "]\nfus["
+ _fusUnits
+ "]";
}
}
|
GaryChengld/spring-rest-auth
|
oauth2-jwt-secretkey/resource-server/src/main/java/com/example/oauth2/jwk/secretkey/JwtSecretKeyResourceServerApp.java
|
package com.example.oauth2.jwk.secretkey;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JwtSecretKeyResourceServerApp {
public static void main(String[] args) {
SpringApplication.run(JwtSecretKeyResourceServerApp.class, args);
}
}
|
seashell/aqueduct
|
ui/src/views/files/tree.js
|
<reponame>seashell/aqueduct<filename>ui/src/views/files/tree.js
import React from 'react'
import styled from 'styled-components'
import Collapse from '_components/collapse'
import File from './file'
const StyledCollapse = styled(Collapse)`
padding-left: 16px;
`
const Tree = ({ nodes, isSelecting, onNodeSelect, onNodeDeselect, onNodeClick }) => {
const handleTreeNodeClick = (node) => {
onNodeClick(node.path)
}
//
const handleTreeNodeSelect = (node) => {
const shouldSelect = !node.attrs.isSelected
if (shouldSelect) {
onNodeSelect(node.path)
} else {
onNodeDeselect(node.path)
}
Object.keys(node).forEach((k) => {
if (k !== 'attrs' && k !== 'path') {
if (shouldSelect) {
onNodeSelect(node[k].path)
} else {
onNodeDeselect(node[k].path)
}
}
})
}
const keys = Object.keys(nodes)
const sortedKeys = keys.sort((k) => {
if (k === 'attrs' || k === 'path') return 0
if (nodes[k].attrs.isDir) {
return -1
}
return 1
})
return sortedKeys.map((key) => {
if (key === 'attrs' || key === 'path') return false
const node = nodes[key]
return node.attrs.isDir ? (
<StyledCollapse
title={
<File
path={node.path}
name={node.attrs.name}
isDir={node.attrs.isDir}
isSelected={node.attrs.isSelected}
isSelecting={isSelecting}
onSelect={() => handleTreeNodeSelect(node)}
onClick={() => handleTreeNodeClick(node)}
/>
}
>
<Tree
nodes={node}
isSelecting={isSelecting}
onNodeClick={onNodeClick}
onNodeSelect={onNodeSelect}
onNodeDeselect={onNodeDeselect}
/>
</StyledCollapse>
) : (
<File
path={node.path}
name={node.attrs.name}
isDir={node.attrs.isDir}
isSelected={node.attrs.isSelected}
isSelecting={isSelecting}
onSelect={() => handleTreeNodeSelect(node)}
onClick={() => handleTreeNodeClick(node)}
/>
)
})
}
export default Tree
|
msyoon222/so
|
adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/BpelRestClient.java
|
/*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.adapters.network;
import java.security.GeneralSecurityException;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.PostConstruct;
import javax.xml.bind.DatatypeConverter;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.onap.so.logger.MessageEnum;
import org.onap.so.logger.MsoLogger;
import org.onap.so.utils.CryptoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
* This is the class that is used to POST replies from the MSO adapters to the BPEL engine.
* It can be configured via property file, or modified using the member methods.
* The properties to use are:
* org.onap.so.adapters.vnf.bpelauth encrypted authorization string to send to BEPL engine
* org.onap.so.adapters.vnf.sockettimeout socket timeout value
* org.onap.so.adapters.vnf.connecttimeout connect timeout value
* org.onap.so.adapters.vnf.retrycount number of times to retry failed connections
* org.onap.so.adapters.vnf.retryinterval interval (in seconds) between retries
* org.onap.so.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code
* 900 means "connection was not established")
*/
@Component("NetworkBpel")
@Scope("prototype")
public class BpelRestClient {
public static final String MSO_PROP_NETWORK_ADAPTER = "MSO_PROP_NETWORK_ADAPTER";
private static final String PROPERTY_DOMAIN = "org.onap.so.adapters.network";
private static final String BPEL_AUTH_PROPERTY = PROPERTY_DOMAIN+".bpelauth";
private static final String SOCKET_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".sockettimeout";
private static final String CONN_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".connecttimeout";
private static final String RETRY_COUNT_PROPERTY = PROPERTY_DOMAIN+".retrycount";
private static final String RETRY_INTERVAL_PROPERTY = PROPERTY_DOMAIN+".retryinterval";
private static final String RETRY_LIST_PROPERTY = PROPERTY_DOMAIN+".retrylist";
private static final String ENCRYPTION_KEY_PROP = PROPERTY_DOMAIN + ".encryptionKey";
private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, BpelRestClient.class);
@Autowired
private Environment env;
/** Default socket timeout (in seconds) */
public static final int DEFAULT_SOCKET_TIMEOUT = 5;
/** Default connect timeout (in seconds) */
public static final int DEFAULT_CONNECT_TIMEOUT = 5;
/** By default, retry up to five times */
public static final int DEFAULT_RETRY_COUNT = 5;
/** Default interval to wait between retries (in seconds), negative means use backoff algorithm */
public static final int DEFAULT_RETRY_INTERVAL = -15;
/** Default list of response codes to trigger a retry */
public static final String DEFAULT_RETRY_LIST = "408,429,500,502,503,504,900"; // 900 is "connection failed"
/** Default credentials */
public static final String DEFAULT_CREDENTIALS = "";
// Properties of the BPEL client -- all are configurable
private int socketTimeout;
private int connectTimeout;
private int retryCount;
private int retryInterval;
private Set<Integer> retryList;
private String credentials;
// last response from BPEL engine
private int lastResponseCode;
private String lastResponse;
/**
* Create a client to send results to the BPEL engine, using configuration from the
* MSO_PROP_NETWORK_ADAPTER properties.
*/
public BpelRestClient() {
socketTimeout = DEFAULT_SOCKET_TIMEOUT;
connectTimeout = DEFAULT_CONNECT_TIMEOUT;
retryCount = DEFAULT_RETRY_COUNT;
retryInterval = DEFAULT_RETRY_INTERVAL;
setRetryList(DEFAULT_RETRY_LIST);
credentials = DEFAULT_CREDENTIALS;
lastResponseCode = 0;
lastResponse = "";
}
@PostConstruct
protected void init() {
socketTimeout = env.getProperty(SOCKET_TIMEOUT_PROPERTY, Integer.class, DEFAULT_SOCKET_TIMEOUT);
connectTimeout = env.getProperty(CONN_TIMEOUT_PROPERTY, Integer.class, DEFAULT_CONNECT_TIMEOUT);
retryCount = env.getProperty(RETRY_COUNT_PROPERTY, Integer.class, DEFAULT_RETRY_COUNT);
retryInterval = env.getProperty(RETRY_INTERVAL_PROPERTY, Integer.class, DEFAULT_RETRY_INTERVAL);
setRetryList(env.getProperty(RETRY_LIST_PROPERTY, DEFAULT_RETRY_LIST));
credentials = getEncryptedProperty(BPEL_AUTH_PROPERTY, DEFAULT_CREDENTIALS, env.getProperty(ENCRYPTION_KEY_PROP));
}
public int getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getRetryCount() {
return retryCount;
}
public void setRetryCount(int retryCount) {
int retCnt = 0;
if (retryCount < 0)
retCnt = DEFAULT_RETRY_COUNT;
this.retryCount = retCnt;
}
public int getRetryInterval() {
return retryInterval;
}
public void setRetryInterval(int retryInterval) {
this.retryInterval = retryInterval;
}
public String getCredentials() {
return credentials;
}
public void setCredentials(String credentials) {
this.credentials = credentials;
}
public String getRetryList() {
if (retryList.isEmpty())
return "";
String t = retryList.toString();
return t.substring(1, t.length()-1);
}
public void setRetryList(String retryList) {
Set<Integer> s = new TreeSet<>();
for (String t : retryList.split("[, ]")) {
try {
s.add(Integer.parseInt(t));
} catch (NumberFormatException x) {
LOGGER.debug("Exception while parsing", x);
}
}
this.retryList = s;
}
public int getLastResponseCode() {
return lastResponseCode;
}
public String getLastResponse() {
return lastResponse;
}
/**
* Post a response to the URL of the BPEL engine. As long as the response code is one of those in
* the retryList, the post will be retried up to "retrycount" times with an interval (in seconds)
* of "retryInterval". If retryInterval is negative, then each successive retry interval will be
* double the previous one.
* @param toBpelStr the content (XML or JSON) to post
* @param bpelUrl the URL to post to
* @param isxml true if the content is XML, otherwise assumed to be JSON
* @return true if the post succeeded, false if all retries failed
*/
public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) {
debug("Sending response to BPEL: " + toBpelStr);
int totalretries = 0;
int retryint = retryInterval;
while (true) {
sendOne(toBpelStr, bpelUrl, isxml);
// Note: really should handle response code 415 by switching between content types if needed
if (!retryList.contains(lastResponseCode)) {
debug("Got response code: " + lastResponseCode + ": returning.");
return true;
}
if (totalretries >= retryCount) {
debug("Retried " + totalretries + " times, giving up.");
LOGGER.error(MessageEnum.RA_SEND_VNF_NOTIF_ERR, "Could not deliver response to BPEL after "+totalretries+" tries: "+toBpelStr, "Camunda", "", MsoLogger.ErrorCode.DataError, "Could not deliver response to BPEL");
return false;
}
totalretries++;
int sleepinterval = retryint;
if (retryint < 0) {
// if retry interval is negative double the retry on each pass
sleepinterval = -retryint;
retryint *= 2;
}
debug("Sleeping for " + sleepinterval + " seconds.");
try {
Thread.sleep(sleepinterval * 1000L);
} catch (InterruptedException e) {
LOGGER.debug("Exception while Thread sleep", e);
Thread.currentThread().interrupt();
}
}
}
private void debug(String m) {
LOGGER.debug(m);
}
private void sendOne(final String toBpelStr, final String bpelUrl, final boolean isxml) {
LOGGER.debug("Sending to BPEL server: "+bpelUrl);
LOGGER.debug("Content is: "+toBpelStr);
//POST
HttpPost post = new HttpPost(bpelUrl);
if (credentials != null && !credentials.isEmpty())
post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
//ContentType
ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON;
post.setEntity(new StringEntity(toBpelStr, ctype));
//Timeouts
RequestConfig requestConfig = RequestConfig
.custom()
.setSocketTimeout(socketTimeout * 1000)
.setConnectTimeout(connectTimeout * 1000)
.build();
post.setConfig(requestConfig);
//Client 4.3+
//Execute & GetResponse
try (CloseableHttpClient client = HttpClients.createDefault()) {
CloseableHttpResponse response = client.execute(post);
if (response != null) {
lastResponseCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
lastResponse = (entity != null) ? EntityUtils.toString(entity) : "";
} else {
lastResponseCode = 900;
lastResponse = "";
}
} catch (Exception e) {
String error = "Error sending Bpel notification:" + toBpelStr;
LOGGER.error (MessageEnum.RA_SEND_VNF_NOTIF_ERR, error, "Camunda", "", MsoLogger.ErrorCode.AvailabilityError, "Exception sending Bpel notification", e);
lastResponseCode = 900;
lastResponse = "";
}
LOGGER.debug("Response code from BPEL server: "+lastResponseCode);
LOGGER.debug("Response body is: "+lastResponse);
}
private String getEncryptedProperty(String key, String defaultValue, String encryptionKey) {
if (env.getProperty(key) != null) {
try {
return CryptoUtils.decrypt(env.getProperty(key), encryptionKey);
} catch (GeneralSecurityException e) {
LOGGER.debug("Exception while decrypting property: " + env.getProperty(key), e);
}
}
return defaultValue;
}
}
|
zcgitzc/qaplus
|
src/main/java/com/qaplus/mapper/QaClassMapperExt.java
|
package com.qaplus.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.qaplus.entity.QaClass;
import com.qaplus.entity.vo.Page;
@Repository
public interface QaClassMapperExt extends QaClassMapper {
List<QaClass> queryAllClassForPage(@Param("page") Page page);
int countAllClassForPage();
List<QaClass> queryClassByUserId(@Param("userId")Long userId);
}
|
nengliangZ/React-Starter-Kit
|
node_modules/react-jss/lib/ns.js
|
<filename>node_modules/react-jss/lib/ns.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Namespaces to avoid conflicts on the context.
*/
var jss = exports.jss = '64a55d578f856d258dc345b094a2a2b3';
var sheetsRegistry = exports.sheetsRegistry = 'd4bd0baacbc52bbd48bbb9eb24344ecd';
var providerId = exports.providerId = 'd9f144a51454eae08eb84ab3ade674a5';
var sheetOptions = exports.sheetOptions = '6fc570d6bd61383819d0f9e7407c452d';
|
lindsaygelle/animalcrossing
|
villager/tiger/villagers.go
|
<reponame>lindsaygelle/animalcrossing
package tiger
import (
"github.com/lindsaygelle/animalcrossing/villager"
"github.com/lindsaygelle/animalcrossing/villager/tiger/bangle"
"github.com/lindsaygelle/animalcrossing/villager/tiger/bianca"
"github.com/lindsaygelle/animalcrossing/villager/tiger/claudia"
"github.com/lindsaygelle/animalcrossing/villager/tiger/leonardo"
"github.com/lindsaygelle/animalcrossing/villager/tiger/rolf"
"github.com/lindsaygelle/animalcrossing/villager/tiger/rowan"
"github.com/lindsaygelle/animalcrossing/villager/tiger/tybalt"
)
var (
Villagers = villager.NewVillagers(
bangle.Villager,
bianca.Villager,
claudia.Villager,
leonardo.Villager,
rolf.Villager,
rowan.Villager,
tybalt.Villager)
)
|
DanielSBrown/osf.io
|
scripts/migrate_spam.py
|
import logging
import sys
from modularodm import Q
from website.app import init_app
from website.project.model import Comment
from framework.transactions.context import TokuTransaction
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def migrate_status(records):
for record in records:
if len(record.reports) > 0:
record.spam_status = Comment.FLAGGED
else:
record.spam_status = Comment.UNKNOWN
record.save()
logger.info('Migrated spam_status for comment {}'.format(record._id))
def migrate_latest(records):
for record in records:
date = None
for user, report in record.reports.iteritems():
if date is None:
date = report.get('date')
elif date < report.get('date'):
date = report.get('date')
record.date_last_reported = date
record.save()
logger.info('Migrated date_last_reported for comment {}'.format(record._id))
def get_no_status_targets():
return Comment.find(
Q('spam_status', 'eq', 0)
)
def get_no_latest_targets():
query = (
Q('date_last_reported', 'eq', None) &
Q('spam_status', 'ne', Comment.UNKNOWN)
)
return Comment.find(query)
def main():
dry_run = False
status = True
latest = True
if '--dry' in sys.argv:
dry_run = True
if '--no_status' in sys.argv:
status = False
if '--no_latest' in sys.argv:
latest = False
if not dry_run:
script_utils.add_file_logger(logger, __file__)
init_app(set_backends=True, routes=False)
with TokuTransaction():
if status:
migrate_status(get_no_status_targets())
if latest:
migrate_latest(get_no_latest_targets())
if dry_run:
raise Exception('Dry Run -- Aborting Transaction')
if __name__ == '__main__':
main()
|
panda2ici/Advanced-C-plusplus
|
Design-Pattern/composite/Blank.cpp
|
<reponame>panda2ici/Advanced-C-plusplus<filename>Design-Pattern/composite/Blank.cpp
//
// Created by ling on 03/12/17.
//
#include "Blank.h"
//void Blank::accept(Visitor & v){
// v.visitBlank(this);
//}
|
neemoh/ART
|
src/gui/RosBridge.cpp
|
<reponame>neemoh/ART
//
// Created by nearlab on 14/12/16.
//
#include <stdexcept>
#include <cv_bridge/cv_bridge.h>
#include "RosBridge.hpp"
#include <custom_msgs/ActiveConstraintParameters.h>
#include "custom_msgs/TaskState.h"
#include <std_msgs/Int8.h>
#include <kdl/frames.hpp>
#include <tf_conversions/tf_kdl.h>
RosBridge::RosBridge(QObject *parent, std::string node_name)
: n(node_name), ros_freq(0), node_name(node_name),
state_label(0), recording(false), new_task_state_msg(false)
{
slave_pose_current_callbacks[0] = &RosBridge::Slave0CurrentPoseCallback;
slave_pose_current_callbacks[1] = &RosBridge::Slave1CurrentPoseCallback;
slave_pose_desired_callbacks[0] = &RosBridge::Slave0DesiredPoseCallback;
slave_pose_desired_callbacks[1] = &RosBridge::Slave1DesiredPoseCallback;
master_pose_current_callbacks[0] = &RosBridge::Master0CurrentPoseCallback;
master_pose_current_callbacks[1] = &RosBridge::Master1CurrentPoseCallback;
slave_twist_callbacks[0] = &RosBridge::Slave0TwistCallback;
slave_twist_callbacks[1] = &RosBridge::Slave1TwistCallback;
master_joint_state_callbacks[0] = &RosBridge::Master0JointStateCallback;
master_joint_state_callbacks[1] = &RosBridge::Master1JointStateCallback;
gripper_callbacks[0] = &RosBridge::Master1GripperCallback;
gripper_callbacks[1] = &RosBridge::Master2GripperCallback;
master_twist_callbacks[0] = &RosBridge::Master0TwistCallback;
master_twist_callbacks[1] = &RosBridge::Master1TwistCallback;
master_wrench_callbacks[0] = &RosBridge::Master0WrenchCallback;
master_wrench_callbacks[1] = &RosBridge::Master1WrenchCallback;
task_frame_to_slave_frame[0] = std::vector<double>(7, 0.0);
task_frame_to_slave_frame[1] = std::vector<double>(7, 0.0);
GetROSParameterValues();
// this saves all the samples during an acquisition
ongoing_acq_buffer = new std::vector< std::vector<double> >;
// ACTIVE CONSTRAINT
for (int i = 0; i < n_arms; ++i) {
ac_parameters[i].method = 0; // 0 for visco/elastic
ac_parameters[i].activation = 0.0; // this will be set later
ac_parameters[i].max_force = 4.0;
ac_parameters[i].linear_elastic_coeff = 1000.0;
ac_parameters[i].linear_damping_coeff = 30.0;
//ac_parameters[0].max_torque = 0.03;
ac_parameters[i].max_torque = 0.03;
ac_parameters[i].angular_elastic_coeff = 0.04;
ac_parameters[i].angular_damping_coeff = 0.000;
// publish the params
publisher_ac_params[i].publish(ac_parameters[i]);
}
}
RosBridge::~RosBridge(){
ros::shutdown();
}
//-----------------------------------------------------------------------------------
// GetROSParameterValues
//-----------------------------------------------------------------------------------
void RosBridge::GetROSParameterValues() {
// spinning frequency. THe recording happens at the freq of task_state
ros_rate = new ros::Rate(100);
n.param<int>("number_of_arms", n_arms, 0);
ROS_INFO("Expecting '%d' arm(s)", n_arms);
if (n_arms < 1)
ROS_WARN("No arm specified. Can't perform data recording");
subscriber_slave_pose_current = new ros::Subscriber[n_arms];
subscriber_master_pose_current = new ros::Subscriber[n_arms];
subscriber_slave_pose_desired = new ros::Subscriber[n_arms];
subscriber_slave_twist = new ros::Subscriber[n_arms];
subscriber_master_joint_state = new ros::Subscriber[n_arms];
subscriber_master_current_gripper = new ros::Subscriber[n_arms];
subscriber_master_twist = new ros::Subscriber[n_arms];
subscriber_master_wrench = new ros::Subscriber[n_arms];
publisher_ac_params = new ros::Publisher[(uint)n_arms];
// arm names
for (int n_arm = 0; n_arm < n_arms; n_arm++) {
//getting the name of the arms
std::stringstream param_name;
param_name << std::string("slave_") << n_arm + 1 << "_name";
if(!n.getParam(param_name.str(), slave_names[n_arm]))
throw std::runtime_error("No slave names found");
param_name.str("");
param_name << std::string("master_") << n_arm + 1 << "_name";
if(!n.getParam(param_name.str(), master_names[n_arm]))
throw std::runtime_error("No Master names found");
// subscribers
param_name.str("");
param_name << std::string("/atar/")
<< slave_names[n_arm]<< "/tool_pose_desired";
subscriber_slave_pose_desired[n_arm] = n.subscribe(
param_name.str(), 1, slave_pose_desired_callbacks[n_arm],this);
// the current pose of the slaves
param_name.str("");
param_name << std::string("/dvrk/") << slave_names[n_arm]
<< "/position_cartesian_current";
subscriber_slave_pose_current[n_arm] = n.subscribe(param_name.str(), 1
,slave_pose_current_callbacks[n_arm],this);
// the current pose of the masters
param_name.str("");
param_name << std::string("/dvrk/") << master_names[n_arm]
<< "/position_cartesian_current";
subscriber_master_pose_current[n_arm] = n.subscribe(param_name.str(), 1
,master_pose_current_callbacks[n_arm], this);
// master's joint state
param_name.str("");
param_name << std::string("/dvrk/") << master_names[n_arm]
<< "/state_joint_current";
subscriber_master_joint_state[n_arm] = n.subscribe(param_name.str(), 1
, master_joint_state_callbacks[n_arm], this);
// master's gripper
param_name.str("");
param_name << std::string("/dvrk/") <<master_names[n_arm]
<< "/gripper_position_current";
subscriber_master_current_gripper[n_arm] =n.subscribe(param_name.str()
, 1, gripper_callbacks[n_arm], this);
// master's twist
param_name.str("");
param_name << std::string("/atar/") << master_names[n_arm]
<< "/twist_filtered";
subscriber_master_twist[n_arm] = n.subscribe(param_name.str(),1
,master_twist_callbacks[n_arm], this);
// Slave's twist
param_name.str("");
param_name << std::string("/dvrk/") << slave_names[n_arm]
<< "/twist_body_current";
subscriber_slave_twist[n_arm] = n.subscribe(param_name.str(), 1
,slave_twist_callbacks[n_arm], this);
//master's wrench
param_name.str("");
param_name << std::string("/dvrk/") << master_names[n_arm]
<< "/set_wrench_body";
subscriber_master_wrench[n_arm] = n.subscribe(param_name.str(), 1
,master_wrench_callbacks[n_arm], this);
// Publishing the active constraint parameters that may change during
// the task
param_name.str("");
param_name << std::string("/atar/")<< master_names[n_arm]
<< "/active_constraint_param";
publisher_ac_params[n_arm] =
n.advertise<custom_msgs::ActiveConstraintParameters>(
param_name.str().c_str(), 1 );
}
// common subscriber
subscriber_foot_pedal_coag = n.subscribe("/dvrk/footpedals/coag", 1,
&RosBridge::CoagFootSwitchCallback,
this);
subscriber_foot_pedal_clutch = n.subscribe("/dvrk/footpedals/clutch", 1,
&RosBridge::ClutchFootSwitchCallback,
this);
subscriber_task_state = n.subscribe("/atar/task_state", 1,
&RosBridge::TaskSTateCallback,
this);
//publisher
publisher_control_events = n.advertise<std_msgs::Int8>
("/atar/control_events", 1);
std::string topic_name = std::string("/atar/ring_pose_current");
subscriber_ring_pose_current = n.subscribe(
topic_name.c_str(), 1, &RosBridge::RingPoseCurrentCallback, this);
topic_name = std::string("/atar/ring_pose_desired");
subscriber_ring_pose_desired= n.subscribe(
topic_name.c_str(), 1, &RosBridge::RingPoseDesiredCallback, this);
}
//-----------------------------------------------------------------------------------
// Callbacks
//-----------------------------------------------------------------------------------
// PSMs current pose
void RosBridge::RingPoseCurrentCallback(const geometry_msgs::PoseConstPtr &msg) {
ring_pose_current.position = msg->position;
ring_pose_current.orientation = msg->orientation;
}
void RosBridge::RingPoseDesiredCallback(const geometry_msgs::PoseConstPtr &msg) {
ring_pose_desired.position = msg->position;
ring_pose_desired.orientation = msg->orientation;
}
// PSMs current pose
void RosBridge::Slave0CurrentPoseCallback(const geometry_msgs::PoseStamped::ConstPtr &msg) {
slave_current_pose[0].position = msg->pose.position;
slave_current_pose[0].orientation = msg->pose.orientation;
}
void RosBridge::Slave1CurrentPoseCallback(const geometry_msgs::PoseStamped::ConstPtr &msg) {
slave_current_pose[1].position = msg->pose.position;
slave_current_pose[1].orientation = msg->pose.orientation;
}
// PSMs Desired pose
void RosBridge::Slave0DesiredPoseCallback(const geometry_msgs::PoseStamped::ConstPtr &msg) {
slave_desired_pose[0].position = msg->pose.position;
slave_desired_pose[0].orientation = msg->pose.orientation;
}
void RosBridge::Slave1DesiredPoseCallback(const geometry_msgs::PoseStamped::ConstPtr &msg) {
slave_desired_pose[1].position = msg->pose.position;
slave_desired_pose[1].orientation = msg->pose.orientation;
}
// MTMs current pose
void RosBridge::Master0CurrentPoseCallback(const geometry_msgs::PoseStampedConstPtr &msg) {
master_current_pose[0].position = msg->pose.position;
master_current_pose[0].orientation = msg->pose.orientation;
}
void RosBridge::Master1CurrentPoseCallback(const geometry_msgs::PoseStampedConstPtr &msg) {
master_current_pose[1].position = msg->pose.position;
master_current_pose[1].orientation = msg->pose.orientation;
}
// Slave Twist
void RosBridge::Slave0TwistCallback(const geometry_msgs::TwistStampedConstPtr &msg) {
slave_twist[0].linear = msg->twist.linear;
slave_twist[0].angular = msg->twist.angular;
}
void RosBridge::Slave1TwistCallback(const geometry_msgs::TwistStampedConstPtr &msg) {
slave_twist[1].linear = msg->twist.linear;
slave_twist[1].angular = msg->twist.angular;
}
// MTMs joint state
void RosBridge::Master0JointStateCallback(const sensor_msgs::JointStateConstPtr &msg) {
master_joint_state[0].position = msg->position;
master_joint_state[0].velocity = msg->velocity;
master_joint_state[0].effort = msg->effort;
}
void RosBridge::Master1JointStateCallback(const sensor_msgs::JointStateConstPtr &msg) {
master_joint_state[1].position = msg->position;
master_joint_state[1].velocity = msg->velocity;
master_joint_state[1].effort = msg->effort;
}
// -----------------------------------------------------------------------------
// Reading the gripper positions
void RosBridge::Master1GripperCallback(
const std_msgs::Float32::ConstPtr &msg) {
gripper_position[0] = msg->data;
}
void RosBridge::Master2GripperCallback(
const std_msgs::Float32::ConstPtr &msg) {
gripper_position[1] = msg->data;
}
// MTMs Twist
void RosBridge::Master0TwistCallback(const geometry_msgs::TwistConstPtr &msg) {
master_twist[0].linear = msg->linear;
master_twist[0].linear = msg->linear;
}
void RosBridge::Master1TwistCallback(const geometry_msgs::TwistConstPtr &msg) {
master_twist[1].linear = msg->linear;
master_twist[1].linear = msg->linear;
}
// MTMs Wrench
void RosBridge::Master0WrenchCallback(const geometry_msgs::WrenchConstPtr &msg) {
master_wrench[0].force= msg->force;
master_wrench[0].torque= msg->torque;
}
void RosBridge::Master1WrenchCallback(const geometry_msgs::WrenchConstPtr &msg) {
master_wrench[1].force= msg->force;
master_wrench[1].torque= msg->torque;
}
// task state
void RosBridge::TaskSTateCallback(const custom_msgs::TaskStateConstPtr &msg){
// save last task state
last_task_state = task_state;
task_state.task_name = msg->task_name;
task_state.number_of_repetition = msg->number_of_repetition;
task_state.task_state = msg->task_state;
task_state.time_stamp = msg->time_stamp;
task_state.uint_slot = msg->uint_slot;
task_state.error_field_1 = msg->error_field_1;
task_state.error_field_2 = msg->error_field_2;
new_task_state_msg = true;
}
// foot pedals
void RosBridge::CoagFootSwitchCallback(const sensor_msgs::Joy &msg){
clutch_pedal_pressed = (bool) msg.buttons[0];
}
void RosBridge::ClutchFootSwitchCallback(const sensor_msgs::Joy &msg){
coag_pedal_pressed = (bool) msg.buttons[0];
}
//void RosBridge::OnCameraImageMessage(const sensor_msgs::ImageConstPtr &msg) {
// try
// {
// image_msg = cv_bridge::toCvShare(msg, "bgr8")->image;
// }
// catch (cv_bridge::Exception& e)
// {
// ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
// }
//}
//cv::Mat& RosBridge::Image(ros::Duration timeout) {
// ros::Rate loop_rate(100);
// ros::Time timeout_time = ros::Time::now() + timeout;
//
// while(image_msg.empty()) {
// ros::spinOnce();
// loop_rate.sleep();
//
// if (ros::Time::now() > timeout_time) {
// ROS_ERROR("Timeout whilst waiting for a new image from the image topic. "
// "Is the camera still publishing ?");
// }
// }
//
// return image_msg;
//}
void RosBridge::run(){
while(ros::ok() ) {
if (recording && new_task_state_msg){
new_task_state_msg = false;
// -----------------------------------------------------------------
// ------------------- Transition from idle to ongoing
if (last_task_state.task_state == 0 && task_state.task_state == 1) {
if(haptics_mode>0)
PublishACActivation(assistance_activation);
}
// -----------------------------------------------------------------
// ------------------- ONGOING
if (task_state.task_state == 1 ) {
// save data sample
ongoing_acq_buffer->push_back(VectorizeData());
// increment the evaluation
KDL::Frame desired, current;
tf::poseMsgToKDL(ring_pose_desired, desired);
tf::poseMsgToKDL(ring_pose_current, current);
perf_eval->Increment(desired, current);
}
// -----------------------------------------------------------------
// -------------------- Transition from ongoing to end
if (last_task_state.task_state == 1 && task_state.task_state == 2) {
// ----------- saving the acquisition in the file
DumpDataToFileAndClearBuffer();
repetition_num++;
// -------- performance evaluation
perf_history.push_back(
perf_eval->GetPerformanceAndReset(last_task_state.time_stamp));
if(haptics_mode == 2)
assistance_activation =
perf_eval->GetHapticAssistanceActivation(perf_history);
// activation will be published
PublishACActivation(0.0);
}
// -----------------------------------------------------------------
}
ros::spinOnce();
ros_rate->sleep();
}
}
void RosBridge::CloseRecordingFile(){
reporting_file.close();
qDebug() << "Closed reporting file";
}
void RosBridge::ResetCurrentAcquisition() {
ongoing_acq_buffer->clear();
if(perf_eval)
perf_eval->Reset();
};
void RosBridge::ResetTask(){
repetition_num = 1;
perf_history.clear();
if(recording){
recording = false;
ongoing_acq_buffer->clear();
CloseRecordingFile();
if(perf_eval)
delete perf_eval;
}
};
void RosBridge::InitializeAdaptiveAssistance(
const uint n_session,
const double last_session_perf,
const double last_last_session_perf
) {
perf_eval = new SteadyHandPerfEval(n_session, last_session_perf,
last_last_session_perf);
assistance_activation =
perf_eval->GetHapticAssistanceActivation(perf_history);
}
void RosBridge::PublishACActivation(const double &activation){
for (int i = 0; i < n_arms; ++i) {
ac_parameters[i].activation = activation;
publisher_ac_params[i].publish(ac_parameters[i]);
}
}
void RosBridge::StartRecording(
const int session,
const double last_session_perf,
const double last_last_session_perf
) {
InitializeAdaptiveAssistance((uint) session, last_session_perf, last_last_session_perf);
recording = true;
}
void RosBridge::DumpDataToFileAndClearBuffer() {
qDebug() << "Writing the last to the file";
for (int j = 0; j < ongoing_acq_buffer->size(); ++j) {
for (int i = 0; i < ongoing_acq_buffer->at(j).size() - 1; i++) {
reporting_file << ongoing_acq_buffer->at(j)[i] << ", ";
}
reporting_file << ongoing_acq_buffer->at(j).back() << std::endl;
}
ongoing_acq_buffer->clear();
}
void RosBridge::OverrideACActivation(const double act){
assistance_activation=act;
PublishACActivation(assistance_activation);
};
void RosBridge::OpenRecordingFile(std::string filename){
reporting_file.open(filename);
//first line is the name of the arms
reporting_file
<< (std::string)"slave_names[0]: " << slave_names[0]
<< ", slave_names[1]: " << slave_names[1]
<< ", master_names[0]: " << master_names[0]
<< ", master_names[1]: " << master_names[1]
<< std::endl;
reporting_file
<< "number_of_repetition"
<< ", task_state"
<< ", time_stamp"
<< ", gripper_in_contact"
<< ", error_field_1"
<< ", error_field_2"
<< ", clutch_pedal_pressed"
<< ", coag_pedal_pressed"
<< ", ring_current_pose.position.x"
<< ", ring_current_pose.position.y"
<< ", ring_current_pose.position.z"
<< ", ring_current_pose.orientation.x"
<< ", ring_current_pose.orientation.y"
<< ", ring_current_pose.orientation.z"
<< ", ring_current_pose.orientation.w"
<< ", ring_desired_pose.position.x"
<< ", ring_desired_pose.position.y"
<< ", ring_desired_pose.position.z"
<< ", ring_desired_pose.orientation.x"
<< ", ring_desired_pose.orientation.y"
<< ", ring_desired_pose.orientation.z"
<< ", ring_desired_pose.orientation.w";;
for (int i = 0; i < n_arms; ++i) {
reporting_file
<< ", slave_current_pose.position.x"
<< ", slave_current_pose.position.y"
<< ", slave_current_pose.position.z"
<< ", slave_current_pose.orientation.x"
<< ", slave_current_pose.orientation.y"
<< ", slave_current_pose.orientation.z"
<< ", slave_current_pose.orientation.w"
<< ", slave_desired_pose.position.x"
<< ", slave_desired_pose.position.y"
<< ", slave_desired_pose.position.z"
<< ", slave_desired_pose.orientation.x"
<< ", slave_desired_pose.orientation.y"
<< ", slave_desired_pose.orientation.z"
<< ", slave_desired_pose.orientation.w"
<< ", master_current_pose.position.x"
<< ", master_current_pose.position.y"
<< ", master_current_pose.position.z"
<< ", master_current_pose.orientation.x"
<< ", master_current_pose.orientation.y"
<< ", master_current_pose.orientation.z"
<< ", master_current_pose.orientation.w"
<< ", master_joint_state.position[0]"
<< ", master_joint_state.position[1]"
<< ", master_joint_state.position[2]"
<< ", master_joint_state.position[3]"
<< ", master_joint_state.position[4]"
<< ", master_joint_state.position[5]"
<< ", master_joint_state.position[6]"
<< ", master_joint_state.position[7]"
<< ", gripper_position"
<< ", slave_twist.linear.x"
<< ", slave_twist.linear.y"
<< ", slave_twist.linear.z"
<< ", slave_twist.angular.x"
<< ", slave_twist.angular.y"
<< ", slave_twist.angular.z"
<< ", master_twist.linear.x"
<< ", master_twist.linear.y"
<< ", master_twist.linear.z"
<< ", master_twist.angular.x"
<< ", master_twist.angular.y"
<< ", master_twist.angular.z"
<< ", master_wrench.force.x"
<< ", master_wrench.force.y"
<< ", master_wrench.force.z"
<< ", master_wrench.torque.x"
<< ", master_wrench.torque.y"
<< ", master_wrench.torque.z"
<< ",ac_params.activation"
<< ",ac_params.method"
<< ",ac_params.angular_damping_coeff"
<< ",ac_params.angular_elastic_coeff"
<< ",ac_params.linear_damping_coeff"
<< ",ac_params.linear_elastic_coeff"
<< ",ac_params.max_force"
<< ",ac_params.max_torque";
}
reporting_file << std::endl;
}
std::vector<double> RosBridge::VectorizeData(){
std::vector<double> data_sample;
data_sample.push_back(double(repetition_num));
data_sample.push_back(double(task_state.task_state));
data_sample.push_back(task_state.time_stamp);
data_sample.push_back(double((task_state.uint_slot)));
data_sample.push_back(task_state.error_field_1);
data_sample.push_back(task_state.error_field_2);
data_sample.push_back(double(clutch_pedal_pressed));
data_sample.push_back(double(coag_pedal_pressed));
data_sample.push_back(ring_pose_current.position.x);
data_sample.push_back(ring_pose_current.position.y);
data_sample.push_back(ring_pose_current.position.z);
data_sample.push_back(ring_pose_current.orientation.x);
data_sample.push_back(ring_pose_current.orientation.y);
data_sample.push_back(ring_pose_current.orientation.z);
data_sample.push_back(ring_pose_current.orientation.w);
data_sample.push_back(ring_pose_desired.position.x);
data_sample.push_back(ring_pose_desired.position.y);
data_sample.push_back(ring_pose_desired.position.z);
data_sample.push_back(ring_pose_desired.orientation.x);
data_sample.push_back(ring_pose_desired.orientation.y);
data_sample.push_back(ring_pose_desired.orientation.z);
data_sample.push_back(ring_pose_desired.orientation.w);
for(uint j=0; j<n_arms; j++){
data_sample.push_back(slave_current_pose[j].position.x);
data_sample.push_back(slave_current_pose[j].position.y);
data_sample.push_back(slave_current_pose[j].position.z);
data_sample.push_back(slave_current_pose[j].orientation.x);
data_sample.push_back(slave_current_pose[j].orientation.y);
data_sample.push_back(slave_current_pose[j].orientation.z);
data_sample.push_back(slave_current_pose[j].orientation.w);
data_sample.push_back(slave_desired_pose[j].position.x);
data_sample.push_back(slave_desired_pose[j].position.y);
data_sample.push_back(slave_desired_pose[j].position.z);
data_sample.push_back(slave_desired_pose[j].orientation.x);
data_sample.push_back(slave_desired_pose[j].orientation.y);
data_sample.push_back(slave_desired_pose[j].orientation.z);
data_sample.push_back(slave_desired_pose[j].orientation.w);
data_sample.push_back(master_current_pose[j].position.x);
data_sample.push_back(master_current_pose[j].position.y);
data_sample.push_back(master_current_pose[j].position.z);
data_sample.push_back(master_current_pose[j].orientation.x);
data_sample.push_back(master_current_pose[j].orientation.y);
data_sample.push_back(master_current_pose[j].orientation.z);
data_sample.push_back(master_current_pose[j].orientation.w);
data_sample.push_back(master_joint_state[j].position[0]);
data_sample.push_back(master_joint_state[j].position[1]);
data_sample.push_back(master_joint_state[j].position[2]);
data_sample.push_back(master_joint_state[j].position[3]);
data_sample.push_back(master_joint_state[j].position[4]);
data_sample.push_back(master_joint_state[j].position[5]);
data_sample.push_back(master_joint_state[j].position[6]);
data_sample.push_back(master_joint_state[j].position[7]);
data_sample.push_back(gripper_position[j]);
data_sample.push_back(slave_twist[j].linear.x);
data_sample.push_back(slave_twist[j].linear.y);
data_sample.push_back(slave_twist[j].linear.z);
data_sample.push_back(slave_twist[j].angular.x);
data_sample.push_back(slave_twist[j].angular.y);
data_sample.push_back(slave_twist[j].angular.z);
data_sample.push_back(master_twist[j].linear.x);
data_sample.push_back(master_twist[j].linear.y);
data_sample.push_back(master_twist[j].linear.z);
data_sample.push_back(master_twist[j].angular.x);
data_sample.push_back(master_twist[j].angular.y);
data_sample.push_back(master_twist[j].angular.z);
data_sample.push_back(master_wrench[j].force.x);
data_sample.push_back(master_wrench[j].force.y);
data_sample.push_back(master_wrench[j].force.z);
data_sample.push_back(master_wrench[j].torque.x);
data_sample.push_back(master_wrench[j].torque.y);
data_sample.push_back(master_wrench[j].torque.z);
data_sample.push_back(ac_parameters[j].activation);
data_sample.push_back(double(ac_parameters[j].method));
data_sample.push_back(ac_parameters[j].angular_damping_coeff);
data_sample.push_back(ac_parameters[j].angular_elastic_coeff);
data_sample.push_back(ac_parameters[j].linear_damping_coeff);
data_sample.push_back(ac_parameters[j].linear_elastic_coeff);
data_sample.push_back(ac_parameters[j].max_force);
data_sample.push_back(ac_parameters[j].max_torque);
}
return data_sample;
}
void RosBridge::CleanUpAndQuit(){
ros::shutdown();
ros::Rate pause(2);
pause.sleep();
delete [] subscriber_slave_pose_current;
delete [] subscriber_master_pose_current;
delete [] subscriber_slave_pose_desired;
delete [] subscriber_slave_twist ;
delete [] subscriber_master_joint_state ;
delete [] subscriber_master_twist ;
delete [] subscriber_master_wrench;
delete [] publisher_ac_params;
if(perf_eval)
delete perf_eval;
delete ros_rate;
quit();
}
|
suggestio/suggestio
|
src1/shared/common/shared/src/main/scala/io/suggest/sc/app/MScAppGetQs.scala
|
<reponame>suggestio/suggestio
package io.suggest.sc.app
import io.suggest.dev.MOsFamily
import io.suggest.n2.edge.{MPredicate, MPredicates}
import japgolly.univeq._
import monocle.macros.GenLens
import play.api.libs.json._
import play.api.libs.functional.syntax._
/**
* Suggest.io
* User: <NAME> <<EMAIL>>
* Created: 12.12.2019 18:53
* Description: Модель аргументов для реквеста на сервер для получения инфы
* по скачиванию приложения (получения ссылки/метаданных на скачивание).
*/
object MScAppGetQs {
object Fields {
def OS_FAMILY = "o"
def RDR = "r"
def ON_NODE_ID = "n"
def PREDICATE = "p"
}
/** Поддержка play-json. */
implicit def scAppGetQsJson: OFormat[MScAppGetQs] = {
val F = Fields
(
(__ \ F.OS_FAMILY).format[MOsFamily] and
(__ \ F.RDR).format[Boolean] and
(__ \ F.ON_NODE_ID).formatNullable[String] and
{
val fmt = (__ \ F.PREDICATE).formatNullable[MPredicate]
val readsFiltered = fmt
.filter { predOpt =>
predOpt
.fold(true) { _ eqOrHasParent MPredicates.Blob.File }
}
OFormat(readsFiltered, fmt)
}
)(apply, unlift(unapply))
}
@inline implicit def univEq: UnivEq[MScAppGetQs] = UnivEq.derive
def rdr = GenLens[MScAppGetQs]( _.rdr )
def onNodeId = GenLens[MScAppGetQs]( _.onNodeId )
def predicate = GenLens[MScAppGetQs]( _.predicate )
}
/** Контейнер данных запроса ссылки доступа к приложению.
*
* @param onNodeId id узла, на котором запрошено приложение.
* @param rdr Вернуть редирект? Тогда нужно, чтобы был задан предикат и остальные координаты.
* @param osFamily Платформа дистрибуции.
* None - означает локальную раздачу файлов.
* @param predicate Предикат, если требуется строго-конкретный результат.
*/
case class MScAppGetQs(
osFamily : MOsFamily,
rdr : Boolean,
onNodeId : Option[String] = None,
predicate : Option[MPredicate] = None,
)
|
rpayeras/freecodecamp-challenges
|
Front-End-Libraries-Certification/React/44-Render-Conditionally-from-Props.js
|
// So far, you've seen how to use if/else, &&, null and the ternary operator (condition ? expressionIfTrue : expressionIfFalse) to make conditional decisions about what to render and when. However, there's one important topic left to discuss that lets you combine any or all of these concepts with another powerful React feature: props. Using props to conditionally render code is very common with React developers — that is, they use the value of a given prop to automatically make decisions about what to render.
// In this challenge, you'll set up a child component to make rendering decisions based on props. You'll also use the ternary operator, but you can see how several of the other concepts that were covered in the last few challenges might be just as useful in this context.
// The code editor has two components that are partially defined for you: a parent called GameOfChance, and a child called Results. They are used to create a simple game where the user presses a button to see if they win or lose.
// First, you'll need a simple expression that randomly returns a different value every time it is run. You can use Math.random(). This method returns a value between 0 (inclusive) and 1 (exclusive) each time it is called. So for 50/50 odds, use Math.random() > .5 in your expression. Statistically speaking, this expression will return true 50% of the time, and false the other 50%. On line 30, replace the comment with this expression to complete the variable declaration.
// Now you have an expression that you can use to make a randomized decision in the code. Next you need to implement this. Render the Results component as a child of GameOfChance, and pass in expression as a prop called fiftyFifty. In the Results component, write a ternary expression to render the text "You win!" or "You lose!" based on the fiftyFifty prop that's being passed in from GameOfChance. Finally, make sure the handleClick() method is correctly counting each turn so the user knows how many times they've played. This also serves to let the user know the component has actually updated in case they win or lose twice in a row.
class Results extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h1>{this.props.fiftyFifty ? "You win!" : "You lose!"}</h1>;
}
}
class GameOfChance extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
counter: this.state.counter + 1
});
}
render() {
let expression = Math.random() > 0.5;
return (
<div>
<button onClick={this.handleClick}>Play Again</button>
{/* change code below this line */}
<Results fiftyFifty={expression} />
{/* change code above this line */}
<p>{"Turn: " + this.state.counter}</p>
</div>
);
}
}
|
buckelieg/simple-tools
|
src/main/java/buckelieg/jdbc/MutableResultSet.java
|
<gh_stars>1-10
package buckelieg.jdbc;
import javax.annotation.Nonnull;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.*;
final class MutableResultSet extends ImmutableResultSet {
boolean updated = false;
MutableResultSet(@Nonnull ResultSet delegate) {
super(delegate);
}
@Override
public void updateNull(int columnIndex) throws SQLException {
delegate.updateNull(columnIndex);
updated = true;
}
@Override
public void updateBoolean(int columnIndex, boolean x) throws SQLException {
delegate.updateBoolean(columnIndex, x);
updated = true;
}
@Override
public void updateByte(int columnIndex, byte x) throws SQLException {
delegate.updateByte(columnIndex, x);
updated = true;
}
@Override
public void updateShort(int columnIndex, short x) throws SQLException {
delegate.updateShort(columnIndex, x);
updated = true;
}
@Override
public void updateInt(int columnIndex, int x) throws SQLException {
delegate.updateInt(columnIndex, x);
updated = true;
}
@Override
public void updateLong(int columnIndex, long x) throws SQLException {
delegate.updateLong(columnIndex, x);
updated = true;
}
@Override
public void updateFloat(int columnIndex, float x) throws SQLException {
delegate.updateFloat(columnIndex, x);
updated = true;
}
@Override
public void updateDouble(int columnIndex, double x) throws SQLException {
delegate.updateDouble(columnIndex, x);
updated = true;
}
@Override
public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException {
delegate.updateBigDecimal(columnIndex, x);
updated = true;
}
@Override
public void updateString(int columnIndex, String x) throws SQLException {
delegate.updateString(columnIndex, x);
updated = true;
}
@Override
public void updateBytes(int columnIndex, byte[] x) throws SQLException {
delegate.updateBytes(columnIndex, x);
updated = true;
}
@Override
public void updateDate(int columnIndex, Date x) throws SQLException {
delegate.updateDate(columnIndex, x);
updated = true;
}
@Override
public void updateTime(int columnIndex, Time x) throws SQLException {
delegate.updateTime(columnIndex, x);
updated = true;
}
@Override
public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException {
delegate.updateTimestamp(columnIndex, x);
updated = true;
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException {
delegate.updateAsciiStream(columnIndex, x, length);
updated = true;
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException {
delegate.updateBinaryStream(columnIndex, x, length);
updated = true;
}
@Override
public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException {
delegate.updateCharacterStream(columnIndex, x, length);
updated = true;
}
@Override
public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException {
delegate.updateObject(columnIndex, x, scaleOrLength);
updated = true;
}
@Override
public void updateObject(int columnIndex, Object x) throws SQLException {
delegate.updateObject(columnIndex, x);
updated = true;
}
@Override
public void updateNull(String columnLabel) throws SQLException {
delegate.updateNull(columnLabel);
updated = true;
}
@Override
public void updateBoolean(String columnLabel, boolean x) throws SQLException {
delegate.updateBoolean(columnLabel, x);
updated = true;
}
@Override
public void updateByte(String columnLabel, byte x) throws SQLException {
delegate.updateByte(columnLabel, x);
updated = true;
}
@Override
public void updateShort(String columnLabel, short x) throws SQLException {
delegate.updateShort(columnLabel, x);
updated = true;
}
@Override
public void updateInt(String columnLabel, int x) throws SQLException {
delegate.updateInt(columnLabel, x);
updated = true;
}
@Override
public void updateLong(String columnLabel, long x) throws SQLException {
delegate.updateLong(columnLabel, x);
updated = true;
}
@Override
public void updateFloat(String columnLabel, float x) throws SQLException {
delegate.updateFloat(columnLabel, x);
updated = true;
}
@Override
public void updateDouble(String columnLabel, double x) throws SQLException {
delegate.updateDouble(columnLabel, x);
updated = true;
}
@Override
public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException {
delegate.updateBigDecimal(columnLabel, x);
updated = true;
}
@Override
public void updateString(String columnLabel, String x) throws SQLException {
delegate.updateString(columnLabel, x);
updated = true;
}
@Override
public void updateBytes(String columnLabel, byte[] x) throws SQLException {
delegate.updateBytes(columnLabel, x);
updated = true;
}
@Override
public void updateDate(String columnLabel, Date x) throws SQLException {
delegate.updateDate(columnLabel, x);
updated = true;
}
@Override
public void updateTime(String columnLabel, Time x) throws SQLException {
delegate.updateTime(columnLabel, x);
updated = true;
}
@Override
public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException {
delegate.updateTimestamp(columnLabel, x);
updated = true;
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException {
delegate.updateAsciiStream(columnLabel, x, length);
updated = true;
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException {
delegate.updateBinaryStream(columnLabel, x, length);
updated = true;
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException {
delegate.updateCharacterStream(columnLabel, reader, length);
updated = true;
}
@Override
public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException {
delegate.updateObject(columnLabel, x, scaleOrLength);
updated = true;
}
@Override
public void updateObject(String columnLabel, Object x) throws SQLException {
delegate.updateObject(columnLabel, x);
updated = true;
}
@Override
public void updateRef(int columnIndex, Ref x) throws SQLException {
delegate.updateRef(columnIndex, x);
updated = true;
}
@Override
public void updateRef(String columnLabel, Ref x) throws SQLException {
delegate.updateRef(columnLabel, x);
updated = true;
}
@Override
public void updateBlob(int columnIndex, Blob x) throws SQLException {
delegate.updateBlob(columnIndex, x);
updated = true;
}
@Override
public void updateBlob(String columnLabel, Blob x) throws SQLException {
delegate.updateBlob(columnLabel, x);
updated = true;
}
@Override
public void updateClob(int columnIndex, Clob x) throws SQLException {
delegate.updateClob(columnIndex, x);
updated = true;
}
@Override
public void updateClob(String columnLabel, Clob x) throws SQLException {
delegate.updateClob(columnLabel, x);
updated = true;
}
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
delegate.updateArray(columnIndex, x);
updated = true;
}
@Override
public void updateArray(String columnLabel, Array x) throws SQLException {
delegate.updateArray(columnLabel, x);
updated = true;
}
@Override
public void updateRowId(int columnIndex, RowId x) throws SQLException {
delegate.updateRowId(columnIndex, x);
updated = true;
}
@Override
public void updateRowId(String columnLabel, RowId x) throws SQLException {
delegate.updateRowId(columnLabel, x);
updated = true;
}
@Override
public void updateNString(int columnIndex, String nString) throws SQLException {
delegate.updateNString(columnIndex, nString);
updated = true;
}
@Override
public void updateNString(String columnLabel, String nString) throws SQLException {
delegate.updateNString(columnLabel, nString);
updated = true;
}
@Override
public void updateNClob(int columnIndex, NClob nClob) throws SQLException {
delegate.updateNClob(columnIndex, nClob);
updated = true;
}
@Override
public void updateNClob(String columnLabel, NClob nClob) throws SQLException {
delegate.updateNClob(columnLabel, nClob);
updated = true;
}
@Override
public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException {
delegate.updateSQLXML(columnIndex, xmlObject);
updated = true;
}
@Override
public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException {
delegate.updateSQLXML(columnLabel, xmlObject);
updated = true;
}
@Override
public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException {
delegate.updateNCharacterStream(columnIndex, x, length);
updated = true;
}
@Override
public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException {
delegate.updateNCharacterStream(columnLabel, reader, length);
updated = true;
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException {
delegate.updateAsciiStream(columnIndex, x, length);
updated = true;
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException {
delegate.updateBinaryStream(columnIndex, x, length);
updated = true;
}
@Override
public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException {
delegate.updateCharacterStream(columnIndex, x, length);
updated = true;
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException {
delegate.updateAsciiStream(columnLabel, x, length);
updated = true;
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException {
delegate.updateBinaryStream(columnLabel, x, length);
updated = true;
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException {
delegate.updateCharacterStream(columnLabel, reader, length);
updated = true;
}
@Override
public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException {
delegate.updateBlob(columnIndex, inputStream, length);
updated = true;
}
@Override
public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException {
delegate.updateBlob(columnLabel, inputStream, length);
updated = true;
}
@Override
public void updateClob(int columnIndex, Reader reader, long length) throws SQLException {
delegate.updateClob(columnIndex, reader, length);
updated = true;
}
@Override
public void updateClob(String columnLabel, Reader reader, long length) throws SQLException {
delegate.updateClob(columnLabel, reader, length);
updated = true;
}
@Override
public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException {
delegate.updateNClob(columnIndex, reader, length);
updated = true;
}
@Override
public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException {
delegate.updateNClob(columnLabel, reader, length);
updated = true;
}
@Override
public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException {
delegate.updateNCharacterStream(columnIndex, x);
updated = true;
}
@Override
public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException {
delegate.updateNCharacterStream(columnLabel, reader);
updated = true;
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException {
delegate.updateAsciiStream(columnIndex, x);
updated = true;
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException {
delegate.updateBinaryStream(columnIndex, x);
updated = true;
}
@Override
public void updateCharacterStream(int columnIndex, Reader x) throws SQLException {
delegate.updateCharacterStream(columnIndex, x);
updated = true;
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException {
delegate.updateAsciiStream(columnLabel, x);
updated = true;
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException {
delegate.updateBinaryStream(columnLabel, x);
updated = true;
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException {
delegate.updateCharacterStream(columnLabel, reader);
updated = true;
}
@Override
public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException {
delegate.updateBlob(columnIndex, inputStream);
updated = true;
}
@Override
public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException {
delegate.updateBlob(columnLabel, inputStream);
updated = true;
}
@Override
public void updateClob(int columnIndex, Reader reader) throws SQLException {
delegate.updateClob(columnIndex, reader);
updated = true;
}
@Override
public void updateClob(String columnLabel, Reader reader) throws SQLException {
delegate.updateClob(columnLabel, reader);
updated = true;
}
@Override
public void updateNClob(int columnIndex, Reader reader) throws SQLException {
delegate.updateNClob(columnIndex, reader);
updated = true;
}
@Override
public void updateNClob(String columnLabel, Reader reader) throws SQLException {
delegate.updateNClob(columnLabel, reader);
updated = true;
}
}
|
JaneliaSciComp/osgpyplusplus
|
src/modules/osgFX/generated_code/EffectMap.pypp.hpp
|
// This file has been generated by Py++.
#ifndef EffectMap_hpp__pyplusplus_wrapper
#define EffectMap_hpp__pyplusplus_wrapper
void register_EffectMap_class();
#endif//EffectMap_hpp__pyplusplus_wrapper
|
ford442/GWork
|
attic/renderers/GDIPlus/GDIPlusRenderer.h
|
<filename>attic/renderers/GDIPlus/GDIPlusRenderer.h
#include <Gwork/BaseRender.h>
#include <Gwork/Gwork.h>
#include <Gwork/Utility.h>
#include <Gwork/Font.h>
#include <Gwork/Texture.h>
#include <windows.h>
#include <gdiplus.h>
#include <math.h>
using namespace Gdiplus;
//
// Without double buffering it's flickery
// With double buffering it gets slow at high resolutions
//
#define USE_GDIPLUS_DOUBLE_BUFFERING
class GworkRender_Windows : public Gwk::Gwk::Renderer::Base
{
public:
GworkRender_Windows(HWND hWND)
{
m_hWND = hWND;
m_hDC = nullptr;
m_width = 0;
m_height = 0;
#ifdef USE_GDIPLUS_DOUBLE_BUFFERING
m_bitmap = nullptr;
m_cachedBitmap = nullptr;
#endif
graphics = nullptr;
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, nullptr);
}
~GworkRender_Windows()
{
#ifdef USE_GDIPLUS_DOUBLE_BUFFERING
DestroyOffscreenBitmap();
#endif
GdiplusShutdown(m_gdiplusToken);
}
void CreateOffscreenBitmap()
{
RECT rect;
GetClientRect(m_hWND, &rect);
int width = rect.right-rect.left;
int height = rect.bottom-rect.top;
if (m_width != width)
DestroyOffscreenBitmap();
if (m_height != height)
DestroyOffscreenBitmap();
#ifdef USE_GDIPLUS_DOUBLE_BUFFERING
if (m_bitmap)
return;
m_width = width;
m_height = height;
Graphics gfx(m_hDC);
m_bitmap = new Bitmap(m_width, m_height, &gfx);
graphics = Graphics::FromImage(m_bitmap);
#endif
}
void DestroyOffscreenBitmap()
{
#ifdef USE_GDIPLUS_DOUBLE_BUFFERING
if (m_bitmap)
{
delete m_bitmap; m_bitmap = nullptr;
}
graphics = nullptr;
#endif
}
virtual void Begin()
{
m_hDC = BeginPaint(m_hWND, &m_paintStruct);
// Create the backbuffer if it doesn't exist
// (or recreate if the size has changed)
CreateOffscreenBitmap();
#ifndef USE_GDIPLUS_DOUBLE_BUFFERING
graphics = Graphics::FromHDC(m_hDC);
#endif
}
virtual void End()
{
#ifdef USE_GDIPLUS_DOUBLE_BUFFERING
Graphics gfx(m_hDC);
gfx.DrawImage(m_bitmap, 0, 0);
#endif
#ifndef USE_GDIPLUS_DOUBLE_BUFFERING
if (graphics)
{
delete graphics;
graphics = nullptr;
}
#endif
m_hDC = nullptr;
EndPaint(m_hWND, &m_paintStruct);
}
virtual void DrawLine(int x, int y, int a, int b)
{
Translate(x, y);
Translate(a, b);
Pen pen(GetGDIColor(), 1.0f);
graphics->DrawLine(&pen, x, y, a, b);
}
virtual void DrawFilledRect(Gwk::Rect rect)
{
Translate(rect);
SolidBrush solidBrush(GetGDIColor());
graphics->FillRectangle(&solidBrush, rect.x, rect.y, rect.w, rect.h);
}
virtual void DrawRectRotated(const Gwk::Rect& rect, float fAngle, const Gwk::Point& pntHandle)
{
}
virtual void PushMaterial(const char* material)
{
}
virtual void PushMaterial(const void* material)
{
// IGet::Render()->PushMaterial((IMaterial*)material);
}
virtual void PopMaterial(void)
{
// IGet::Render()->PopMaterial();
}
// Why is this here
virtual const char* GetMaterial(void)
{
return "";
}
virtual void* ImagePointer(const char* image)
{
// return IGet::Render()->LoadMaterial( image );
return nullptr;
}
virtual void SetDrawColor(Gwk::Color color)
{
m_col = Color(color.a, color.r, color.g, color.b);
}
Color GetGDIColor()
{
return m_col;
}
virtual void LoadFont(Gwk::Font* font)
{
Gwk::Debug::Msg("LOAD FONT %s\n", font->facename.c_str());
FontStyle fs = FontStyleRegular;
font->realsize = font->size*Scale();
Font* font = new Font(Gwk::Utility::StringToUnicode(
font->facename).c_str(), font->realsize, fs, UnitPixel, nullptr);
font->data = font;
}
virtual void FreeFont(Gwk::Font* font)
{
Gwk::Debug::Msg("FREE FONT %s\n", font->facename.c_str());
if (!font->data)
return;
Font* font = ((Font*)font->data);
delete font;
font->data = nullptr;
}
virtual void RenderText(Gwk::Font* font, Gwk::Rect rect, const Gwk::UnicodeString& text)
{
/*
* SetDrawColor( Gwk::Color( 255, 0, 0, 100 ) );
* DrawFilledRect( rect );
* SetDrawColor( Gwk::Color( 0, 0, 0, 255 ) );
*/
Translate(rect);
if (!font->data || fabs(font->realsize-font->size*Scale()) > 2)
{
FreeFont(font);
LoadFont(font);
}
StringFormat strFormat(StringFormat::GenericDefault());
SolidBrush solidBrush(GetGDIColor());
RectF r(rect.x, rect.y, rect.w, rect.h);
Font* gDIFont = (Font*)font->data;
graphics->DrawString(text.c_str(), text.length()+1, gDIFont, r, &strFormat, &solidBrush);
}
virtual Gwk::Point MeasureText(Gwk::Font* font, const Gwk::UnicodeString& text)
{
Gwk::Point p(32, 32);
if (!font->data || fabs(font->realsize-font->size*Scale()) > 2)
{
FreeFont(font);
LoadFont(font);
}
StringFormat strFormat(StringFormat::GenericDefault());
strFormat.SetFormatFlags(StringFormatFlagsMeasureTrailingSpaces|
strFormat.GetFormatFlags());
SizeF size;
Graphics g(m_hWND);
Font* gDIFont = (Font*)font->data;
Status s = g.MeasureString(text.c_str(), -1, gDIFont, &strFormat, &size);
return Gwk::Point(size.Width+1, size.Height+1);
}
void StartClip()
{
const Gwk::Rect& rect = ClipRegion();
graphics->SetClip(Rect(rect.x*Scale(), rect.y*Scale(), rect.w*Scale(),
rect.h*Scale()), CombineMode::CombineModeReplace);
// Pen pen( Color( 100, 255, 0, 255 ) );
// graphics->DrawRectangle( &pen, Rect( rect.x*Scale(), rect.y*Scale(),
// rect.w*Scale(), rect.h*Scale() ) );
}
void EndClip()
{
graphics->ResetClip();
}
bool ProcessTexture(Gwk::Texture* texture)
{
return true;
}
void DrawMissingImage(Gwk::Rect targetRect)
{
SetDrawColor(Gwk::Colors::Red);
DrawFilledRect(targetRect);
}
void DrawTexturedRect(Gwk::Texture* texture, Gwk::Rect targetRect, float u1 = 0.0f,
float v1 = 0.0f, float u2 = 1.0f, float v2 = 1.0f)
{
Image* image = (Image*)texture->data;
// Missing image, not loaded properly?
if (image->GetType() == ImageTypeUnknown)
return DrawMissingImage(targetRect);
Translate(targetRect);
RectF TargetRect(targetRect.x, targetRect.y, targetRect.w, targetRect.h);
if (u1 == 0.0f && v1 == 0.0f && u2 == 1.0f && v2 == 1.0f)
{
graphics->DrawImage(image, TargetRect);
return;
}
float fW = image->GetWidth();
float fH = image->GetHeight();
u1 *= fW;
v1 *= fH;
u2 *= fW;
u2 -= u1;
v2 *= fH;
v2 -= v1;
graphics->DrawImage(image, TargetRect, u1, v1, u2, v2, UnitPixel);
}
void LoadTexture(Gwk::Texture* texture)
{
Gwk::Debug::Msg("LOAD TEXTURE %s\n", texture->name.c_str());
Image* image = new Image(Gwk::Utility::StringToUnicode(texture->name).c_str());
texture->data = image;
texture->width = image->GetWidth();
texture->height = image->GetHeight();
}
void FreeTexture(Gwk::Texture* texture)
{
Gwk::Debug::Msg("RELEASED TEXTURE %s\n", texture->name.c_str());
Image* image = (Image*)texture->data;
if (!image)
return;
delete image;
}
private:
Color m_col;
HWND m_hWND;
HDC m_hDC;
PAINTSTRUCT m_paintStruct;
int m_width;
int m_height;
ULONG_PTR m_gdiplusToken;
#ifdef USE_GDIPLUS_DOUBLE_BUFFERING
Bitmap* m_bitmap;
CachedBitmap* m_cachedBitmap;
#endif
Graphics* graphics;
};
|
sunggyu-kam/apk-scanner
|
src/com/apkscanner/gui/easymode/test/SliderSkinDemo2.java
|
package com.apkscanner.gui.easymode.test;
import java.awt.*;
import javax.swing.*;
public class SliderSkinDemo2 {
public JComponent makeUI() {
UIDefaults d = new UIDefaults();
d.put("Slider:SliderTrack[Enabled].backgroundPainter", new Painter<JSlider>() {
@Override public void paint(Graphics2D g, JSlider c, int w, int h) {
int arc = 10;
int trackHeight = 8;
int trackWidth = w - 2;
int fillTop = 4;
int fillLeft = 1;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(1.5f));
g.setColor(Color.GRAY);
g.fillRoundRect(fillLeft, fillTop, trackWidth, trackHeight, arc, arc);
int fillBottom = fillTop + trackHeight;
int fillRight = xPositionForValue(
c.getValue(), c,
new Rectangle(fillLeft, fillTop, trackWidth, fillBottom - fillTop));
g.setColor(Color.ORANGE);
g.fillRect(fillLeft + 1, fillTop + 1, fillRight - fillLeft, fillBottom - fillTop);
g.setColor(Color.WHITE);
g.drawRoundRect(fillLeft, fillTop, trackWidth, trackHeight, arc, arc);
}
//@see javax/swing/plaf/basic/BasicSliderUI#xPositionForValue(int value)
protected int xPositionForValue(int value, JSlider slider, Rectangle trackRect) {
int min = slider.getMinimum();
int max = slider.getMaximum();
int trackLength = trackRect.width;
double valueRange = (double) max - (double) min;
double pixelsPerValue = (double) trackLength / valueRange;
int trackLeft = trackRect.x;
int trackRight = trackRect.x + (trackRect.width - 1);
int xPosition;
xPosition = trackLeft;
xPosition += Math.round(pixelsPerValue * ((double) value - min));
xPosition = Math.max(trackLeft, xPosition);
xPosition = Math.min(trackRight, xPosition);
return xPosition;
}
});
JSlider slider = new JSlider();
slider.putClientProperty("Nimbus.Overrides", d);
JPanel p = new JPanel();
p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
p.setBackground(Color.DARK_GRAY);
p.add(new JSlider());
p.add(Box.createRigidArea(new Dimension(200, 20)));
p.add(slider);
return p;
}
public static void main(String... args) {
try {
for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new SliderSkinDemo2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
|
moshik1/mcas
|
src/components/net/fabric/src/fabric_runtime_error.h
|
<reponame>moshik1/mcas<filename>src/components/net/fabric/src/fabric_runtime_error.h
/*
Copyright [2017-2019] [IBM 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 _FABRIC_ERROR_H_
#define _FABRIC_ERROR_H_
/*
* Authors:
*
*/
#include <api/fabric_itf.h>
#include <stdexcept>
#include <string>
/**
* Fabric/RDMA-based network component
*/
struct fabric_runtime_error
: public component::IFabric_runtime_error
{
private:
unsigned _i;
const char *_file;
int _line;
public:
explicit fabric_runtime_error(unsigned i, const char *file, int line);
explicit fabric_runtime_error(unsigned i, const char *file, int line, const std::string &desc);
fabric_runtime_error(const fabric_runtime_error &) = default;
fabric_runtime_error& operator=(const fabric_runtime_error &) = default;
fabric_runtime_error add(const std::string &added) const;
unsigned id() const noexcept { return _i; }
};
#endif
|
heroku/gobits
|
cmdutil/metrics/otel/config.go
|
package otel
import (
"net/url"
"github.com/heroku/x/cmdutil/metrics/honeycomb"
)
// Config is a reusable configuration struct that contains the necessary
// environment variables to setup an metrics.Provider
type Config struct {
Enabled bool `env:"ENABLE_OTEL_COLLECTION"`
CollectorURL *url.URL `env:"OTEL_COLLECTOR_URL"`
MetricsDestinations []string `env:"OTEL_METRICS_DESTINATIONS,default=honeycomb;argus"`
Honeycomb honeycomb.Config
}
|
ShockwaveNN/rubocop-ast
|
spec/rubocop/ast/in_pattern_node_spec.rb
|
<filename>spec/rubocop/ast/in_pattern_node_spec.rb
# frozen_string_literal: true
RSpec.describe RuboCop::AST::InPatternNode do
context 'when using Ruby 2.7 or newer', :ruby27 do
let(:in_pattern_node) { parse_source(source).ast.children[1] }
describe '.new' do
let(:source) do
['case condition',
'in [42] then foo',
'end'].join("\n")
end
it { expect(in_pattern_node).to be_a(described_class) }
end
describe '#pattern' do
context 'with a value pattern' do
let(:source) do
['case condition',
'in 42 then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_int_type }
end
context 'with a variable pattern' do
let(:source) do
['case condition',
'in var then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_match_var_type }
end
context 'with an alternative pattern' do
let(:source) do
['case condition',
'in :foo | :bar | :baz then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_match_alt_type }
end
context 'with an as pattern' do
let(:source) do
['case condition',
'in Integer => var then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_match_as_type }
end
context 'with an array pattern' do
let(:source) do
['case condition',
'in :foo, :bar, :baz then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_array_pattern_type }
end
context 'with a hash pattern' do
let(:source) do
['case condition',
'in foo:, bar:, baz: then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_hash_pattern_type }
end
context 'with a pin operator', :ruby31 do
let(:source) do
['case condition',
'in ^(2 + 2) then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_pin_type }
end
end
describe '#then?' do
context 'with a then keyword' do
let(:source) do
['case condition',
'in [42] then foo',
'end'].join("\n")
end
it { expect(in_pattern_node).to be_then }
end
context 'without a then keyword' do
let(:source) do
['case condition',
'in [42]',
' foo',
'end'].join("\n")
end
it { expect(in_pattern_node).not_to be_then }
end
end
describe '#body' do
context 'with a then keyword' do
let(:source) do
['case condition',
'in [42] then :foo',
'end'].join("\n")
end
it { expect(in_pattern_node.body).to be_sym_type }
end
context 'without a then keyword' do
let(:source) do
['case condition',
'in [42]',
' [:foo, :bar]',
'end'].join("\n")
end
it { expect(in_pattern_node.body).to be_array_type }
end
end
describe '#branch_index' do
let(:source) do
['case condition',
'in [42] then 1',
'in [43] then 2',
'in [44] then 3',
'end'].join("\n")
end
let(:in_patterns) { parse_source(source).ast.children[1...-1] }
it { expect(in_patterns[0].branch_index).to eq(0) }
it { expect(in_patterns[1].branch_index).to eq(1) }
it { expect(in_patterns[2].branch_index).to eq(2) }
end
end
end
|
thehyve/hypercube-api-server
|
src/main/java/nl/thehyve/hypercubeapi/patientset/QueryInstanceEntity.java
|
<gh_stars>0
package nl.thehyve.hypercubeapi.patientset;
import lombok.*;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(schema = "i2b2demodata", name = "qt_query_instance")
@Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(of = "id")
public class QueryInstanceEntity {
@Id
@GeneratedValue
@Column(name = "query_instance_id")
private Long id;
@ManyToOne
@JoinColumn(name = "query_master_id")
private QueryMasterEntity queryMaster;
@Column(name = "user_id", nullable = false)
private String userId;
@Column(name = "group_id", nullable = false)
private String groupId;
@Column(name = "start_date", nullable = false)
private Date startDate;
@Column(name = "end_date")
private Date endDate;
@Column(name = "delete_flag")
private Boolean deleted;
@OneToOne
@JoinColumn(name = "status_type_id", nullable = false)
private QueryStatusTypeEntity statusType;
@Column(name = "message", columnDefinition = "text")
private String message;
}
|
ijjk/studentlife
|
feathers/services/usersService.js
|
import app from '../../util/getApp'
import { userUpdated, userRemoved } from '../../redux/actions'
export const usersService = app.service('users')
if (typeof window !== 'undefined') {
usersService.on('patched', user => userUpdated(user))
usersService.on('removed', user => userRemoved(user))
}
|
stefvra/energy_app
|
services/commands.py
|
import asyncio
import logging
import io
import datetime
from tools import tools
logger = logging.getLogger('commands')
class Command():
def __init__(self):
pass
async def execute():
pass
class Store_Put_Command(Command):
def __init__(self, store):
self.store = store
super().__init__()
async def execute(self, df):
self.store.put(df)
class Store_Remove_Command(Command):
def __init__(self, store):
self.store = store
super().__init__()
async def execute(self, start, stop):
self.store.remove(start=start, stop=stop)
class GPIO_Command(Command):
def __init__(self, GPIO_Output):
self.GPIO_Output = GPIO_Output
super().__init__()
async def execute(self, mode):
self.GPIO_Output.set_mode(mode)
|
SMASH-INC/API
|
Supported Languages/Java/src/main/java/SMASH/Environments.java
|
<gh_stars>0
/*
* SMASH
*
* This file was automatically generated for the SMASH API by SMASH, INC ( https://smashlabs.io ).
*/
package SMASH;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public enum Environments {
PRODUCTION, //Production Enviroment
SANDBOX, //Testing and Debugging
BETA; //Updated Nightly (May Contain Bugs)
private static TreeMap<String, Environments> valueMap = new TreeMap<String, Environments>();
private String value;
static {
PRODUCTION.value = "Production";
SANDBOX.value = "Sandbox";
BETA.value = "Beta";
valueMap.put("Production", PRODUCTION);
valueMap.put("Sandbox", SANDBOX);
valueMap.put("Beta", BETA);
}
/**
* Returns the enum member associated with the given string value
* @return The enum member against the given string value */
@com.fasterxml.jackson.annotation.JsonCreator
public static Environments fromString(String toConvert) {
return valueMap.get(toConvert);
}
/**
* Returns the string value associated with the enum member
* @return The string value against enum member */
@com.fasterxml.jackson.annotation.JsonValue
public String value() {
return value;
}
/**
* Get string representation of this enum
*/
@Override
public String toString() {
return value.toString();
}
/**
* Convert list of Environments values to list of string values
* @param toConvert The list of Environments values to convert
* @return List of representative string values */
public static List<String> toValue(List<Environments> toConvert) {
if(toConvert == null)
return null;
List<String> convertedValues = new ArrayList<String>();
for (Environments enumValue : toConvert) {
convertedValues.add(enumValue.value);
}
return convertedValues;
}
}
|
shartte/Mekanism
|
src/minecraft/mekanism/generators/client/GuiWindTurbine.java
|
<gh_stars>0
package mekanism.generators.client;
import mekanism.api.EnumColor;
import mekanism.generators.common.ContainerWindTurbine;
import mekanism.generators.common.TileEntityWindTurbine;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import universalelectricity.core.electricity.ElectricityDisplay;
import universalelectricity.core.electricity.ElectricityDisplay.ElectricUnit;
@SideOnly(Side.CLIENT)
public class GuiWindTurbine extends GuiContainer
{
public TileEntityWindTurbine tileEntity;
private int guiWidth;
private int guiHeight;
public GuiWindTurbine(InventoryPlayer inventory, TileEntityWindTurbine tentity)
{
super(new ContainerWindTurbine(inventory, tentity));
tileEntity = tentity;
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
{
int xAxis = (mouseX - (width - xSize) / 2);
int yAxis = (mouseY - (height - ySize) / 2);
fontRenderer.drawString(tileEntity.fullName, 45, 6, 0x404040);
fontRenderer.drawString("Inventory", 8, (ySize - 96) + 2, 0x404040);
fontRenderer.drawString(ElectricityDisplay.getDisplayShort(tileEntity.electricityStored, ElectricUnit.JOULES), 51, 26, 0x00CD00);
fontRenderer.drawString("Power: " + tileEntity.GENERATION_RATE*tileEntity.getMultiplier(), 51, 35, 0x00CD00);
fontRenderer.drawString(tileEntity.getVoltage() + "v", 51, 44, 0x00CD00);
int size = 44;
if(!tileEntity.checkBounds())
{
size += 9;
fontRenderer.drawString(EnumColor.DARK_RED + "Invalid bounds", 51, size, 0x00CD00);
}
if(!tileEntity.worldObj.canBlockSeeTheSky(tileEntity.xCoord, tileEntity.yCoord+4, tileEntity.zCoord))
{
size += 9;
fontRenderer.drawString(EnumColor.DARK_RED + "Sky blocked", 51, size, 0x00CD00);
}
if(xAxis >= 165 && xAxis <= 169 && yAxis >= 17 && yAxis <= 69)
{
drawCreativeTabHoveringText(ElectricityDisplay.getDisplayShort(tileEntity.electricityStored, ElectricUnit.JOULES), xAxis, yAxis);
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3)
{
mc.renderEngine.bindTexture("/mods/mekanism/gui/GuiWindTurbine.png");
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
guiWidth = (width - xSize) / 2;
guiHeight = (height - ySize) / 2;
drawTexturedModalRect(guiWidth, guiHeight, 0, 0, xSize, ySize);
int displayInt;
displayInt = tileEntity.getScaledEnergyLevel(52);
drawTexturedModalRect(guiWidth + 165, guiHeight + 17 + 52 - displayInt, 176, 52 - displayInt, 4, displayInt);
drawTexturedModalRect(guiWidth + 20, guiHeight + 37, 176, (tileEntity.getVolumeMultiplier() > 0 ? 52 : 64), 12, 12);
}
}
|
Abce/boost
|
libs/type_index/examples/inheritance.cpp
|
<reponame>Abce/boost<filename>libs/type_index/examples/inheritance.cpp
// Copyright 2013-2014 <NAME>
// Distributed under the Boost Software License, Version 1.0.
// (See the accompanying file LICENSE_1_0.txt
// or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)
//[type_index_derived_example
/*`
The following example shows that `type_info` is able to store the real type, successfully getting through
all the inheritances.
Example works with and without RTTI."
*/
#include <boost/type_index.hpp>
#include <iostream>
struct A {
BOOST_TYPE_INDEX_REGISTER_CLASS
virtual ~A(){}
};
struct B: public A { BOOST_TYPE_INDEX_REGISTER_CLASS };
struct C: public B { BOOST_TYPE_INDEX_REGISTER_CLASS };
void print_real_type(const A& a) {
std::cout << boost::typeindex::type_id_runtime(a).pretty_name() << '\n';
}
int main() {
C c;
const A& c_as_a = c;
print_real_type(c_as_a); // Outputs `struct C`
print_real_type(B()); // Outputs `struct B`
}
//] [/type_index_derived_example]
|
TheDoubleB/acpl
|
src/Types.h
|
#ifndef ACPL_TYPES_H
#define ACPL_TYPES_H
#include "Defines.h"
#if (acplCRuntime == acplCRuntimeGlibc)
# include <stdint.h>
# include <stdlib.h>
#elif (acplCRuntime == acplCRuntimeMscrt)
# include <stddef.h> // Needed for definition of NULL, other types are simulated here.
#else
# error Include files for this CRT.
#endif
namespace acpl
{
//
// Platform-specific types
//
#if (acplCRuntime == acplCRuntimeGlibc)
typedef int8_t SInt8;
typedef int16_t SInt16;
typedef int32_t SInt32;
typedef int64_t SInt64;
typedef uint8_t UInt8;
typedef uint16_t UInt16;
typedef uint32_t UInt32;
typedef uint64_t UInt64;
typedef float Float32;
typedef double Float64;
typedef size_t SizeT;
typedef ssize_t SSizeT;
typedef off_t OffT;
typedef time_t TimeT;
typedef char Pathchar;
#elif (acplCRuntime == acplCRuntimeMscrt)
typedef __int8 SInt8;
typedef __int16 SInt16;
typedef __int32 SInt32;
typedef __int64 SInt64;
typedef unsigned __int8 UInt8;
typedef unsigned __int16 UInt16;
typedef unsigned __int32 UInt32;
typedef unsigned __int64 UInt64;
typedef float Float32;
typedef double Float64;
# if defined(_WIN64)
typedef unsigned __int64 SizeT;
typedef __int64 SSizeT;
# else
typedef unsigned long SizeT;
typedef long SSizeT;
# endif
typedef __int64 OffT;
typedef __int64 TimeT;
typedef wchar_t Pathchar;
#else
# error Type definitions for this CRT.
// This is necessary for doxygen documentation; compilers should never get up-to this point.
typedef __PLATFORM_SPECIFIC_TYPE__ SInt8;
typedef __PLATFORM_SPECIFIC_TYPE__ SInt16;
typedef __PLATFORM_SPECIFIC_TYPE__ SInt32;
typedef __PLATFORM_SPECIFIC_TYPE__ SInt64;
typedef __PLATFORM_SPECIFIC_TYPE__ UInt8;
typedef __PLATFORM_SPECIFIC_TYPE__ UInt16;
typedef __PLATFORM_SPECIFIC_TYPE__ UInt32;
typedef __PLATFORM_SPECIFIC_TYPE__ UInt64;
typedef __PLATFORM_SPECIFIC_TYPE__ Float32;
typedef __PLATFORM_SPECIFIC_TYPE__ Float64;
typedef __PLATFORM_SPECIFIC_TYPE__ SizeT;
typedef __PLATFORM_SPECIFIC_TYPE__ SSizeT;
typedef __PLATFORM_SPECIFIC_TYPE__ OffT;
typedef __PLATFORM_SPECIFIC_TYPE__ TimeT;
typedef __PLATFORM_SPECIFIC_TYPE__ Pathchar;
#endif
//
// Platform-independant types
//
typedef acpl::UInt32 Unichar;
//
// Other
//
class Const
{
public:
static inline acpl::UInt64 UI64(acpl::UInt32 nUpper, acpl::UInt32 nLower)
{
return ((static_cast<acpl::UInt64>(nUpper) << 32) | static_cast<acpl::UInt64>(nLower));
}
static inline acpl::SInt64 SI64(acpl::UInt32 nUpper, acpl::UInt32 nLower)
{
return static_cast<acpl::SInt64>(acpl::Const::UI64(nUpper, nLower));
}
};
//
// Forward-declaration
//
template <class tType>
class Num;
//
// Floating-point type manipulation class
//
class Float
{
private:
template <class tFloatType, class tBinRep>
union Rep
{
tFloatType uFloat;
tBinRep uBin;
};
public:
typedef long double Largest; // largest floating-point type
struct Parts
{
typedef acpl::UInt64 Mantissa;
typedef acpl::UInt16 Exponent;
typedef acpl::UInt8 Sign;
acpl::Float::Parts::Mantissa sMan;
acpl::Float::Parts::Exponent sExp;
acpl::Float::Parts::Sign sSign;
};
private:
static inline void I_TypeCheck(const acpl::Float32 &) { }
static inline void I_TypeCheck(const acpl::Float64 &) { }
static inline void I_TypeCheck(const acpl::Float::Largest &) { }
template <class tType>
static inline tType I_Create(acpl::UInt8 nSign, acpl::UInt16 nExp, acpl::UInt64 nMan)
{
if (sizeof(tType) == sizeof(acpl::Float32))
return static_cast<tType>(acpl::Float::Create<acpl::Float32>(nSign, nExp, nMan));
else
if (sizeof(tType) == sizeof(acpl::Float64))
return static_cast<tType>(acpl::Float::Create<acpl::Float64>(nSign, nExp, nMan));
else
return static_cast<tType>(acpl::Float::Create<acpl::Float::Largest>(nSign, nExp, nMan));
}
protected:
template<class tNumType> friend class Num;
template <class tType>
static inline tType I_Min()
{
return acpl::Float::I_Create<tType>(1, 0x7FFE, acpl::Const::UI64(0xFFFFFFFF, 0xFFFFFFFF));
}
template <class tType>
static inline tType I_Max()
{
return acpl::Float::I_Create<tType>(0, 0x7FFE, acpl::Const::UI64(0xFFFFFFFF, 0xFFFFFFFF));
}
template <class tType>
static inline tType I_QNaN()
{
return static_cast<tType>(acpl::Float::Create<acpl::Float64>(0, 0x7FF, acpl::Const::UI64(0x00080000, 0x00000000)));
}
template <class tType>
static inline tType I_SNaN()
{
acpl::Float64 oSNaN = acpl::Float::Create<acpl::Float64>(0, 0x7FF, acpl::Const::UI64(0x00040000, 0x00000000));
acpl::Float::Parts oParts;
acpl::Float::GetParts(oSNaN, oParts);
return ((oParts.sMan == acpl::Const::UI64(0x00040000, 0x00000000)) ? static_cast<tType>(oSNaN) : acpl::Float::I_QNaN<tType>());
}
public:
static inline bool HasExtPrec()
{
return (sizeof(acpl::Float::Largest) > sizeof(acpl::Float64));
}
static inline bool HasExtPrecRT()
{
return (acpl::Float::HasExtPrec() == true && acpl::Float::Max<acpl::Float::Largest>() != acpl::Float::Inf<acpl::Float::Largest>());
}
static inline void GetParts(acpl::Float32 nVal, acpl::Float::Parts &nParts)
{
acpl::Float::Rep<acpl::Float32, acpl::UInt32> oRep = { nVal };
nParts.sSign = (oRep.uBin >> 31);
nParts.sExp = ((oRep.uBin >> 23) & 0xFF);
nParts.sMan = (oRep.uBin & 0x7FFFFF);
}
static inline void GetParts(acpl::Float64 nVal, acpl::Float::Parts &nParts)
{
acpl::Float::Rep<acpl::Float64, acpl::UInt64> oRep = { nVal };
nParts.sSign = (oRep.uBin >> 63);
nParts.sExp = ((oRep.uBin >> 52) & 0x7FF);
nParts.sMan = (oRep.uBin & acpl::Const::UI64(0x000FFFFF, 0xFFFFFFFF));
}
static inline void GetParts(acpl::Float::Largest nVal, acpl::Float::Parts &nParts)
{
// if `long double` is the same size as `double`
if (sizeof(acpl::Float::Largest) == sizeof(acpl::Float64))
return acpl::Float::GetParts(static_cast<acpl::Float64>(nVal), nParts);
// x86 extended precision (80 bits), always little-endian
acpl::Float::Rep<acpl::Float::Largest, acpl::UInt64[2]> oRep = { nVal };
nParts.sSign = ((oRep.uBin[1] >> 15) & 0x01);
nParts.sExp = (oRep.uBin[1] & 0x7FFF);
nParts.sMan = oRep.uBin[0];
}
static inline void SetParts(acpl::Float32 &nVal, acpl::UInt8 nSign, acpl::UInt16 nExp, acpl::UInt64 nMan)
{
acpl::Float::Rep<acpl::Float32, acpl::UInt32> oRep;
oRep.uBin =
(static_cast<acpl::UInt32>(nSign) << 31) |
(static_cast<acpl::UInt32>(nExp & 0xFF) << 23) |
(nMan & 0x7FFFFF);
nVal = oRep.uFloat;
}
static inline void SetParts(acpl::Float64 &nVal, acpl::UInt8 nSign, acpl::UInt16 nExp, acpl::UInt64 nMan)
{
acpl::Float::Rep<acpl::Float64, acpl::UInt64> oRep;
oRep.uBin =
(static_cast<acpl::UInt64>(nSign) << 63) |
(static_cast<acpl::UInt64>(nExp & 0x7FF) << 52) |
(nMan & acpl::Const::UI64(0x000FFFFF, 0xFFFFFFFF));
nVal = oRep.uFloat;
}
static inline void SetParts(acpl::Float::Largest &nVal, acpl::UInt8 nSign, acpl::UInt16 nExp, acpl::UInt64 nMan)
{
// if `long double` is the same size as `double`
if (sizeof(acpl::Float::Largest) == sizeof(acpl::Float64))
{
acpl::Float64 oVal;
acpl::Float::SetParts(oVal, nSign, nExp, nMan);
nVal = oVal;
return;
}
// x86 extended precision (80 bits), always little-endian
acpl::Float::Rep<acpl::Float::Largest, acpl::UInt64[2]> oRep;
oRep.uBin[1] =
(static_cast<acpl::UInt64>(nSign & 0x01) << 15) |
(static_cast<acpl::UInt64>(nExp & 0x7FFF));
oRep.uBin[0] = nMan;
nVal = oRep.uFloat;
}
template <class tType>
static inline tType Create(acpl::UInt8 nSign, acpl::UInt16 nExp, acpl::UInt64 nMan)
{
tType oVal;
acpl::Float::SetParts(oVal, nSign, nExp, nMan);
return oVal;
}
template <class tType>
static inline tType FractMin()
{
return acpl::Float::Create<tType>(0, 0, 1);
}
template <class tType>
static inline tType Min()
{
return acpl::Float::Create<tType>(1, 0x7FFE, acpl::Const::UI64(0xFFFFFFFF, 0xFFFFFFFF));
}
template <class tType>
static inline tType Max()
{
return acpl::Float::Create<tType>(0, 0x7FFE, acpl::Const::UI64(0xFFFFFFFF, 0xFFFFFFFF));
}
template <class tType>
static inline tType Inf()
{
return acpl::Float::Create<tType>(0, 0x7FFF, acpl::Const::UI64(0x80000000, 0x00000000));
}
template <class tType>
static inline tType NaN()
{
return acpl::Float::QNaN<tType>();
}
template <class tType>
static inline tType QNaN()
{
acpl::Float::I_TypeCheck(tType(0.0));
return acpl::Float::I_QNaN<tType>();
}
template <class tType>
static inline tType SNaN()
{
acpl::Float::I_TypeCheck(tType(0.0));
return acpl::Float::I_SNaN<tType>();
}
template <class tType>
static inline bool IsNaN(tType nVal)
{
acpl::Float::Parts oParts;
acpl::Float::Parts::Exponent oInfExp;
acpl::Float::GetParts(acpl::Float::Inf<tType>(), oParts);
oInfExp = oParts.sExp;
acpl::Float::GetParts(nVal, oParts);
return (oParts.sExp == oInfExp && (oParts.sMan & acpl::Const::UI64(0x7FFFFFFF, 0xFFFFFFFF)) != 0);
}
template <class tType>
static inline bool IsNeg(tType nVal)
{
acpl::Float::Parts oParts;
acpl::Float::GetParts(nVal, oParts);
return (oParts.sSign != 0);
}
};
//
// Numeric type information class
//
template <class tType>
class Num
{
public:
static inline bool IsSigned()
{
// The `<=` is used instead of just `<` because GCC goes bonkers
// when `tType` is an unsigned type. The expression itself will
// never equal 0, so `<=` is the same as `<` and the GCC warning
// is gone.
return (tType(-1) <= 0);
}
static inline bool IsFloat()
{
return (static_cast<acpl::Float::Largest>(tType(1.5)) == static_cast<acpl::Float::Largest>(1.5));
}
static inline tType Min()
{
// Such a complicated expression for signed type is due to GCC's
// and MSVC's overflow warning outcries and to avoid bitwise
// shifting due to compatibility with the float types. It is
// resolved at the time of compiling so this ridiculous
// expressions have absolutely no strain on at run-time.
if (IsFloat() == true)
return acpl::Float::I_Min<tType>();
else
if (IsSigned() == true)
return (((tType(1) * (static_cast<acpl::UInt64>(0x40) << ((((sizeof(tType) > sizeof(acpl::UInt64)) ? sizeof(acpl::UInt64) : sizeof(tType)) - 1) * 8))) * static_cast<tType>((IsSigned() == true) ? -1 : 1)) * 2);
else
return 0;
}
static inline tType Max()
{
// Such a complicated expression for signed type is due to GCC's
// and MSVC's overflow warning outcries and to avoid bitwise
// shifting due to compatibility with the float types. It is
// resolved at the time of compiling so this ridiculous
// expressions have absolutely no strain on at run-time.
if (IsFloat() == true)
return acpl::Float::I_Max<tType>();
else
if (IsSigned() == true)
return (tType(-1) - (((tType(1) * (static_cast<acpl::UInt64>(0x40) << ((((sizeof(tType) > sizeof(acpl::UInt64)) ? sizeof(acpl::UInt64) : sizeof(tType)) - 1) * 8))) * static_cast<tType>((IsSigned() == true) ? -1 : 1)) * 2));
else
return tType(-1);
}
};
//
// Enumerator container class
//
template <class tEnumType, class tHolderType>
class Enum
{
private:
tHolderType mHolder;
public:
inline Enum() { }
inline Enum(const acpl::Enum<tEnumType, tHolderType> &nObj) : mHolder(nObj.mHolder) { }
inline Enum(const tEnumType &nVal) : mHolder(static_cast<tHolderType>(nVal)) { }
inline virtual ~Enum() { }
inline tEnumType Value() const { return static_cast<tEnumType>(this->mHolder); }
inline acpl::Enum<tEnumType, tHolderType> &operator=(const acpl::Enum<tEnumType, tHolderType> &nObj) { this->mHolder = nObj.mHolder; return *this; }
inline bool operator==(const acpl::Enum<tEnumType, tHolderType> &nObj) { return (this->mHolder == nObj.mHolder); }
inline bool operator!=(const acpl::Enum<tEnumType, tHolderType> &nObj) { return (this->mHolder != nObj.mHolder); }
inline bool operator< (const acpl::Enum<tEnumType, tHolderType> &nObj) { return (this->mHolder < nObj.mHolder); }
inline bool operator> (const acpl::Enum<tEnumType, tHolderType> &nObj) { return (this->mHolder > nObj.mHolder); }
inline bool operator<=(const acpl::Enum<tEnumType, tHolderType> &nObj) { return (this->mHolder <= nObj.mHolder); }
inline bool operator>=(const acpl::Enum<tEnumType, tHolderType> &nObj) { return (this->mHolder >= nObj.mHolder); }
};
}
#endif // ACPL_TYPES_H
|
vishal-panchal611/Smart_Farming_using_IoT
|
node_modules/@carbon/icons-react/es/tornado/20.js
|
<reponame>vishal-panchal611/Smart_Farming_using_IoT
import { Tornado20 } from '..';
export default Tornado20;
|
zevgenia/Python_shultais
|
Course/syntax/example_15.py
|
<gh_stars>0
age = 18
if age > 18:
credit = True
else:
credit = False
credit = True if age > 18 else False
print(credit)
|
zhonglh/zzboot-framework
|
component-zzboot-framework/src/main/java/com/zzboot/framework/core/enums/EnumMessageType.java
|
<filename>component-zzboot-framework/src/main/java/com/zzboot/framework/core/enums/EnumMessageType.java
package com.zzboot.framework.core.enums;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Administrator
*/
public enum EnumMessageType {
LOGIN("1" , "登录信息") ,
TEXT("2" , "文本信息") ;
private String code ;
private String name ;
EnumMessageType(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static List<Map<String,String>> getAllNotifyType(){
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
for(EnumMessageType enum1 : EnumMessageType.values()){
Map<String,String> map = new HashMap<String,String>();
map.put("code",enum1.getCode());
map.put("name",enum1.getName());
list.add(map);
}
return list;
}
}
|
tmciver/rww-play
|
app/Global.scala
|
<filename>app/Global.scala
/**
* @author <EMAIL>
* Date: 24/11/2013
*/
import controllers.ldp
import controllers.ldp.ReadWriteWebController
import play.api._
import play.api.mvc.RequestHeader
object Global extends GlobalSettings {
override def onRouteRequest(req: RequestHeader) = {
import _root_.rww.play.EnhancedRequestHeader
Logger.info(s"~~~> ${req.method} ${req.path} \n"+req.headers)
val uri = req.getAbsoluteURI
if (
uri.getPath.startsWith("/assets/")
|| uri.getPath.startsWith("/srv/")
|| uri.getHost().startsWith("www") ) {
super.onRouteRequest(req)
}
else if (uri.getHost != _root_.controllers.RdfSetup.host) {
req.method match {
case "GET" => Some(ReadWriteWebController.get(req.path))
case "POST" => Some(ldp.ReadWriteWebController.post(req.path))
case "PATCH" => Some(ldp.ReadWriteWebController.patch(req.path))
case "HEAD" => Some(ldp.ReadWriteWebController.head(req.path))
case "SEARCH" => Some(ldp.ReadWriteWebController.search(req.path))
case "OPTIONS" => Some(ReadWriteWebController.options(req.path))
case "PUT" => Some(ldp.ReadWriteWebController.put(req.path))
case "DELETE" => Some(ldp.ReadWriteWebController.delete(req.path))
}
}
else {
super.onRouteRequest(req)
}
}
}
|
olegood/boosti
|
src/main/java/boosti/service/conversion/target/XmlAsQuestionDataCollection.java
|
package boosti.service.conversion.target;
import java.io.IOException;
import java.util.Collection;
import boosti.service.conversion.SourceAsTarget;
import boosti.web.model.QuestionData;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
* XML file as string converted to collection of {@link QuestionData}.
*
* @author <NAME>
*/
public class XmlAsQuestionDataCollection extends SourceAsTarget<String, Collection<QuestionData>> {
/** {@inheritDoc} */
protected XmlAsQuestionDataCollection(String source) {
super(source);
}
@Override
public Collection<QuestionData> content() throws IOException {
return new XmlMapper().readValue(source, new TypeReference<>() {});
}
}
|
yohan-pg/stylegan2-ada-pytorch
|
encoding/stylegan_encoder_network.py
|
# Taken from https://github.com/genforce/idinvert_pytorch/blob/master/models/stylegan_encoder_network.py
"""Contains the implementation of encoder for StyleGAN inversion.
For more details, please check the paper:
https://arxiv.org/pdf/2004.00049.pdf
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import torch_utils.persistence as persistence
__all__ = ["StyleGANEncoderNet"]
# Resolutions allowed.
_RESOLUTIONS_ALLOWED = [8, 16, 32, 64, 128, 256, 512, 1024]
# Initial resolution.
_INIT_RES = 4
class Splitter(nn.Module):
def __init__(self, num_style_vectors, w_space_dim, out_channels, num_ws):
super().__init__()
self.heads = nn.Parameter(
torch.randn(
num_style_vectors,
w_space_dim,
out_channels,
).cuda()
)
with torch.no_grad():
self.heads /= math.sqrt((out_channels + w_space_dim) / 2)
assert not num_ws > 1
def forward(self, x):
return (self.heads @ x.t()).transpose(2, 1).transpose(1, 0)
class MultiLinear(nn.Module):
def __init__(self, num_lanes, input_size, output_size):
super().__init__()
self.heads = nn.Parameter(
torch.randn(
num_lanes,
input_size,
output_size,
).cuda()
)
self.bias = nn.Parameter(torch.zeros(output_size).cuda())
with torch.no_grad():
self.heads /= math.sqrt(output_size)
def forward(self, x):
return (self.heads @ x.t()).transpose(2, 1).transpose(1, 0)
class SingleLayerSplitter(nn.Module):
def __init__(self, num_style_vectors, w_space_dim, out_channels, num_ws):
super().__init__()
self.num_style_vectors = num_style_vectors
self.w_space_dim = w_space_dim
self.num_ws = num_ws
self.layers = nn.ParameterList([
nn.Sequential(
nn.Linear(out_channels, out_channels // num_ws),
nn.Linear(out_channels // num_ws, num_style_vectors * w_space_dim),
).cuda()
for _ in range(num_ws)
])
for layer in self.layers:
with torch.no_grad():
nn.init.zeros_(layer[0].bias)
nn.init.normal_(layer[0].weight)
layer[0].weight /= math.sqrt(out_channels)
nn.init.zeros_(layer[-1].bias)
nn.init.normal_(layer[-1].weight)
layer[-1].weight /= math.sqrt(out_channels // num_ws) #!!!
def forward(self, x):
return torch.cat(
[
layer(x).reshape(-1, self.num_style_vectors, self.w_space_dim)
for layer in self.layers
],
dim=1,
)
class ChunkingSplitter(nn.Module):
def __init__(
self, num_style_vectors, w_space_dim, out_channels, num_ws, chunk_size=512 #!!! should be lower
):
super().__init__()
self.num_style_vectors = num_style_vectors
self.w_space_dim = w_space_dim
self.num_ws = num_ws
self.l1 = nn.Linear(
out_channels * num_style_vectors,
w_space_dim
)
self.l2 = Splitter(
num_style_vectors,
w_space_dim,
chunk_size,
1
)
def forward(self, x):
return self.l2(self.l1(x.unsqueeze(1).repeat(1, 512, 1)))
@persistence.persistent_class
class StyleGANEncoderNet(nn.Module):
"""Defines the encoder network for StyleGAN inversion.
NOTE: The encoder takes images with `RGB` color channels and range [-1, 1]
as inputs, and encode the input images to W+ space of StyleGAN.
"""
@staticmethod
def configure_for(G, **kwargs):
return StyleGANEncoderNet(
w_space_dim=G.w_dim,
num_ws=G.mapping.num_ws,
resolution=G.img_resolution,
num_style_vectors=G.num_required_vectors(),
**kwargs,
)
def __init__(
self,
resolution,
w_space_dim,
num_style_vectors,
image_channels=3,
encoder_channels_base=64,
encoder_channels_max=1024,
use_wscale=True,
w_plus=True,
use_bn=True,
splitter=Splitter,
num_ws: int = 1,
):
"""Initializes the encoder with basic settings.
Args:
resolution: The resolution of the input image.
w_space_dim: The dimension of the disentangled latent vectors, w.
(default: 512)
image_channels: Number of channels of the input image. (default: 3)
encoder_channels_base: Base factor of the number of channels used in
residual blocks of encoder. (default: 64)
encoder_channels_max: Maximum number of channels used in residual blocks
of encoder. (default: 1024)
use_wscale: Whether to use `wscale` layer. (default: False)
use_bn: Whether to use batch normalization layer. (default: False)
Raises:
ValueError: If the input `resolution` is not supported.
"""
super().__init__()
if resolution not in _RESOLUTIONS_ALLOWED:
raise ValueError(
f"Invalid resolution: {resolution}!\n"
f"Resolutions allowed: {_RESOLUTIONS_ALLOWED}."
)
self.init_res = _INIT_RES
self.resolution = resolution
self.w_space_dim = w_space_dim
self.image_channels = image_channels
self.encoder_channels_base = encoder_channels_base
self.encoder_channels_max = encoder_channels_max
self.use_wscale = use_wscale
self.use_bn = use_bn
self.num_style_vectors = num_style_vectors
# Blocks used in encoder.
self.num_blocks = int(np.log2(resolution))
# Layers used in generator.
self.num_layers = int(np.log2(self.resolution // self.init_res * 2)) * 2
in_channels = self.image_channels
out_channels = self.encoder_channels_base
for block_idx in range(self.num_blocks):
if block_idx == 0:
self.add_module(
f"block{block_idx}",
FirstBlock(
in_channels=in_channels,
out_channels=out_channels,
use_wscale=self.use_wscale,
use_bn=self.use_bn,
),
)
elif block_idx == self.num_blocks - 1:
in_channels = in_channels * self.init_res * self.init_res
out_channels = self.w_space_dim
if w_plus:
out_channels *= 2 * block_idx
self.add_module(
f"block{block_idx}",
LastBlock(
in_channels=in_channels,
out_channels=out_channels,
use_wscale=True,
use_bn=True,
),
)
if num_style_vectors > 1:
self.heads = splitter(
num_style_vectors,
w_space_dim,
out_channels,
num_ws if w_plus else 1,
)
else:
self.add_module(
f"block{block_idx}",
ResBlock(
in_channels=in_channels,
out_channels=out_channels,
use_wscale=self.use_wscale,
use_bn=self.use_bn,
),
)
in_channels = out_channels
out_channels = min(out_channels * 2, self.encoder_channels_max)
self.downsample = AveragePoolingLayer()
def _forward(self, x):
x = x * 2 - 1
for block_idx in range(self.num_blocks):
if 0 < block_idx < self.num_blocks - 1:
x = self.downsample(x)
x = self.__getattr__(f"block{block_idx}")(x)
if self.num_style_vectors > 1:
return self.heads(x)
else:
return x.reshape(x.shape[0], -1, self.w_space_dim)
def forward(self, x):
if x.ndim != 4 or x.shape[1:] != (
self.image_channels,
self.resolution,
self.resolution,
):
raise ValueError(
f"The input image should be with shape [batch_size, "
f"channel, height, width], where "
f"`channel` equals to {self.image_channels}, "
f"`height` and `width` equal to {self.resolution}!\n"
f"But {x.shape} is received!"
)
return self._forward(x)
class AveragePoolingLayer(nn.Module):
def __init__(self, scale_factor=2):
super().__init__()
self.scale_factor = scale_factor
def forward(self, x):
ksize = [self.scale_factor, self.scale_factor]
strides = [self.scale_factor, self.scale_factor]
return F.avg_pool2d(x, kernel_size=ksize, stride=strides, padding=0)
class BatchNorm(nn.Module):
def __init__(self, channels, gamma=False, beta=True, decay=0.9, epsilon=1e-5):
"""Initializes with basic settings.
Args:
channels: Number of channels of the input tensor.
gamma: Whether the scale (weight) of the affine mapping is learnable.
beta: Whether the center (bias) of the affine mapping is learnable.
decay: Decay factor for moving average operations in this layer.
epsilon: A value added to the denominator for numerical stability.
"""
super().__init__()
self.bn = nn.BatchNorm2d(
num_features=channels,
affine=True,
track_running_stats=True,
momentum=1 - decay,
eps=epsilon,
)
self.bn.weight.requires_grad = gamma
self.bn.bias.requires_grad = beta
def forward(self, x):
return self.bn(x)
class WScaleLayer(nn.Module):
"""Implements the layer to scale weight variable and add bias.
NOTE: The weight variable is trained in `nn.Conv2d` layer (or `nn.Linear`
layer), and only scaled with a constant number, which is not trainable in
this layer. However, the bias variable is trainable in this layer.
"""
def __init__(self, in_channels, out_channels, kernel_size, gain=np.sqrt(2.0)):
super().__init__()
fan_in = in_channels * kernel_size * kernel_size
self.scale = gain / np.sqrt(fan_in)
self.bias = nn.Parameter(torch.zeros(out_channels))
def forward(self, x):
if x.ndim == 4:
return x * self.scale + self.bias.view(1, -1, 1, 1)
if x.ndim == 2:
return x * self.scale + self.bias.view(1, -1)
raise ValueError(
f"The input tensor should be with shape [batch_size, "
f"channel, height, width], or [batch_size, channel]!\n"
f"But {x.shape} is received!"
)
class FirstBlock(nn.Module):
def __init__(
self,
in_channels,
out_channels,
use_wscale=False,
wscale_gain=np.sqrt(2.0),
use_bn=False,
activation_type="lrelu",
):
super().__init__()
self.conv = nn.Sequential(
nn.ReflectionPad2d(1),
nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=1,
bias=False,
),
)
self.scale = wscale_gain / np.sqrt(in_channels * 3 * 3) if use_wscale else 1.0
self.bn = Normalization(out_channels) if use_bn else nn.Identity()
if activation_type == "linear":
self.activate = nn.Identity()
elif activation_type == "lrelu":
self.activate = nn.LeakyReLU(negative_slope=0.2, inplace=True)
else:
raise NotImplementedError(
f"Not implemented activation function: " f"{activation_type}!"
)
def forward(self, x):
return self.activate(self.bn(self.conv(x) * self.scale))
class ResBlock(nn.Module):
"""
Usually, each residual block contains two convolutional layers, each of which
is followed by batch normalization layer and activation layer.
"""
def __init__(
self,
in_channels,
out_channels,
use_wscale=False,
wscale_gain=np.sqrt(2.0),
use_bn=False,
activation_type="lrelu",
):
"""Initializes the class with block settings.
Args:
in_channels: Number of channels of the input tensor fed into this block.
out_channels: Number of channels of the output tensor.
kernel_size: Size of the convolutional kernels.
stride: Stride parameter for convolution operation.
padding: Padding parameter for convolution operation.
use_wscale: Whether to use `wscale` layer.
wscale_gain: The gain factor for `wscale` layer.
use_bn: Whether to use batch normalization layer.
activation_type: Type of activation. Support `linear` and `lrelu`.
Raises:
NotImplementedError: If the input `activation_type` is not supported.
"""
super().__init__()
# Add shortcut if needed.
if in_channels != out_channels:
self.add_shortcut = True
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0,
bias=False,
)
self.scale = wscale_gain / np.sqrt(in_channels) if use_wscale else 1.0
self.bn = Normalization(out_channels) if use_bn else nn.Identity()
else:
self.add_shortcut = False
self.identity = nn.Identity()
hidden_channels = min(in_channels, out_channels)
# First convolutional block.
self.conv1 = nn.Sequential(
nn.ReflectionPad2d(1),
nn.Conv2d(
in_channels=in_channels,
out_channels=hidden_channels,
kernel_size=3,
stride=1,
bias=False,
),
)
self.scale1 = 1.0 if use_wscale else wscale_gain / np.sqrt(in_channels * 3 * 3)
# NOTE: WScaleLayer is employed to add bias.
self.wscale1 = WScaleLayer(
in_channels=in_channels,
out_channels=hidden_channels,
kernel_size=3,
gain=wscale_gain,
)
self.bn1 = Normalization(hidden_channels) if use_bn else nn.Identity()
# Second convolutional block.
self.conv2 = nn.Sequential(
nn.Conv2d(
in_channels=hidden_channels,
out_channels=out_channels,
kernel_size=3,
stride=1,
bias=False,
),
nn.ReflectionPad2d(1),
)
self.scale2 = (
1.0 if use_wscale else wscale_gain / np.sqrt(hidden_channels * 3 * 3)
)
self.wscale2 = WScaleLayer(
in_channels=hidden_channels,
out_channels=out_channels,
kernel_size=3,
gain=wscale_gain,
)
self.bn2 = Normalization(out_channels) if use_bn else nn.Identity()
if activation_type == "linear":
self.activate = nn.Identity()
elif activation_type == "lrelu":
self.activate = nn.LeakyReLU(negative_slope=0.2, inplace=True)
else:
raise NotImplementedError(
f"Not implemented activation function: " f"{activation_type}!"
)
def forward(self, x):
if self.add_shortcut:
y = self.activate(self.bn(self.conv(x) * self.scale))
else:
y = self.identity(x)
x = self.activate(self.bn1(self.wscale1(self.conv1(x) / self.scale1)))
x = self.activate(self.bn2(self.wscale2(self.conv2(x) / self.scale2)))
return x + y
class LastBlock(nn.Module):
"""Implements the last block, which is a dense block."""
def __init__(
self, in_channels, out_channels, use_wscale=False, wscale_gain=1.0, use_bn=False
):
super().__init__()
self.fc = nn.Linear(
in_features=in_channels, out_features=out_channels, bias=False
)
self.scale = wscale_gain / np.sqrt(in_channels) if use_wscale else 1.0
self.bn = Normalization(out_channels) if use_bn else nn.Identity()
def forward(self, x):
x = x.view(x.shape[0], -1)
x = self.fc(x) * self.scale
x = x.view(x.shape[0], x.shape[1], 1, 1)
return self.bn(x).view(x.shape[0], x.shape[1])
def Normalization(*args, **kwargs):
return nn.GroupNorm(8, *args, **kwargs)
|
jesushilarioh/C-Plus-Plus
|
Chapter-7-Arrays/Review Questions and Exercises/Programming Challenges/01.cpp
|
/************************************************************
*
* 01. Largest/Smallest Array Values
*
* Write a program that lets the user enter 10 values into
* an array. The program should then display the largest
* and smallest values stored in the array.
*
* <NAME>
* 1/12/20
*
*************************************************************/
#include <iostream>
using namespace std;
// Global constants
const int ARRAY_SIZE = 10;
// Prototypes
int inputValidate(int);
void getValues(int [], int);
void displayValues(int []);
int getLargestValue(int []);
int getSmallestValue(int []);
int main()
{
int user_value_array[ARRAY_SIZE];
int user_number;
getValues(user_value_array, user_number);
// displayValues(user_value_array);
int largest_value = getLargestValue(user_value_array);
cout << "Largest value = " << largest_value << endl;
int smallest_value = getSmallestValue(user_value_array);
cout << "Smallest value = " << smallest_value << endl;
return 0;
}
/********************************************************
* function definitions *
********************************************************/
int inputValidate(int user_number)
{
while(!(cin >> user_number))
{
cout << "Error: an integer must be entered. "
<< "Try again: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return user_number;
}
void getValues(int array[], int user_number)
{
for(int i = 0; i < ARRAY_SIZE; i++)
{
cout << "Enter number for element #"
<< (i + 1) << ": ";
array[i] = inputValidate(array[i]);
}
}
void displayValues(int array[])
{
for(int i = 0; i < ARRAY_SIZE; i++)
{
cout << "array[" << (i) << "] = "
<< array[i]
<< endl;
}
}
int getLargestValue(int array[])
{
int largest = array[0];
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (array[i] >= largest)
largest = array[i];
}
return largest;
}
int getSmallestValue(int array[])
{
int smallest = array[0];
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (array[i] <= smallest)
smallest = array[i];
}
return smallest;
}
|
shah198/abc
|
dist/submodules/Portfolio-Platform-Common/RequestModel.js
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestModelQuery = exports.RequestModel = void 0;
const requestModelBase_1 = require("./requestModelBase");
const filter_1 = require("./filter");
class RequestModel extends requestModelBase_1.RequestModelBase {
constructor() {
super(0, "", "");
this.DataCollection = [];
this.ErrorCode = 200;
this.Error = "";
this.DataCollection = new Array();
this.SocketId = "";
this.token = "";
this.CommunityUrl = "sample_community_url";
this.CommunityId = 0;
this.RequestGuid = "sample_guid";
}
getData() {
let t_temp = this.DataCollection != null && this.DataCollection[0] != null
? this.DataCollection[0]
: null;
return t_temp;
}
CreateRequestModel() {
let requestModel = new RequestModel();
return requestModel;
}
CreateFailureModel(errorCode, error) {
let requestModel = new RequestModel();
requestModel.Error = error;
requestModel.ErrorCode = errorCode;
return requestModel;
}
CreateSuccessModel(tDtos) {
let requestModel = new RequestModel();
requestModel.DataCollection = tDtos;
return requestModel;
}
}
exports.RequestModel = RequestModel;
class RequestModelQuery {
constructor() {
this.Children = [];
this.Filter = new filter_1.Filter();
}
}
exports.RequestModelQuery = RequestModelQuery;
//# sourceMappingURL=RequestModel.js.map
|
nickrfer/lava-codigo
|
repos/main/jason/stdlib/ground.java
|
<gh_stars>1-10
package jason.stdlib;
import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
/**
<p>Internal action: <b><code>.ground</code></b>.
<p>Description: checks whether the argument is ground, i.e., it has no free
variables. Numbers, Strings, and Atoms are always ground.
<p>Parameters:<ul>
<li>+ argument (any term): the term to be checked.<br/>
</ul>
<p>Examples:<ul>
<li> <code>.ground(b(10))</code>: true.
<li> <code>.ground(10)</code>: true.
<li> <code>.ground(X)</code>: false if X is free or bound to a term with free variables.
<li> <code>.ground(a(X))</code>: false if X is free or bound to a term with free variables.
<li> <code>.ground([a,b,c])</code>: true.
<li> <code>.ground([a,b,c(X)])</code>: false if X is free or bound to a term with free variables.
</ul>
@see jason.stdlib.atom
@see jason.stdlib.list
@see jason.stdlib.literal
@see jason.stdlib.number
@see jason.stdlib.string
@see jason.stdlib.structure
*/
public class ground extends DefaultInternalAction {
private static InternalAction singleton = null;
public static InternalAction create() {
if (singleton == null)
singleton = new ground();
return singleton;
}
@Override public int getMinArgs() { return 1; }
@Override public int getMaxArgs() { return 1; }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
checkArguments(args);
return args[0].isGround();
}
}
|
throneless-tech/web-science
|
src/content-scripts/linkResolution.twitter.content.js
|
/**
* Content script for the `linkResolution` module that parses links from Twitter pages.
* This parsing is fragile and, by design, degrades gracefully to resolving links with
* HTTP requests.
* @module linkResolution.twitter.content
*/
function pageManagerLoaded() {
const pageManager = window.webScience.pageManager;
/**
* How often, in milliseconds, to tick the timer for checking links when the page has attention.
* @constant {number}
*/
const timerInterval = 500;
/**
* The anchor elements that have already been checked on the page.
* @type {WeakSet<HTMLAnchorElement>}
*/
let checkedAnchorElements = new WeakSet();
/**
* The timeout ID for timer ticks when the page has attention.
* @type {number}
*/
let timeoutID = -1;
/**
* Whether the page is currently between page visit start and
* page visit stop events.
*/
let inPageVisit = false;
/**
* A listener for pageManager.onPageVisitStart that resets
* page variables and starts the timer ticking if the page
* has attention.
*/
function pageVisitStartListener() {
checkedAnchorElements = new WeakSet();
timeoutID = -1;
inPageVisit = true;
if(pageManager.pageHasAttention) {
timerTick();
}
}
pageManager.onPageVisitStart.addListener(pageVisitStartListener);
if(pageManager.pageVisitStarted) {
pageVisitStartListener();
}
/**
* A listener for pageManager.onPageVisitStop that
* clears the ticking timer.
*/
function pageVisitStopListener() {
clearTimeout(timeoutID);
}
pageManager.onPageVisitStop.addListener(pageVisitStopListener);
/**
* A listener for pageManager.onPageAttentionUpdate that
* clears the ticking timer if the page loses attention
* and starts the ticking timer if the page gains
* attention.
*/
function pageAttentionUpdateListener() {
// Ignore attention events when we aren't between page visit
// start and page visit stop events
if(!inPageVisit) {
return;
}
if(!pageManager.pageHasAttention) {
clearTimeout(timerTick);
}
else {
timerTick();
}
}
pageManager.onPageAttentionUpdate.addListener(pageAttentionUpdateListener);
/**
* When the timer ticks, check all the anchor elements in the document that haven't already been
* checked.
*/
function timerTick() {
const urlMappings = [ ];
// Iterate through all the anchor elements in the document with an href that starts with
// https://t.co/
const anchorElements = document.querySelectorAll(`a[href^="https://t.co/"]`);
for(const anchorElement of anchorElements) {
try {
// Ignore links that we've already checked
if(checkedAnchorElements.has(anchorElement)) {
continue;
}
checkedAnchorElements.add(anchorElement);
// If the inner text for the link parses as a valid URL, that's the destination
// URL for the mapping
const urlObj = new URL(anchorElement.innerText);
urlMappings.push({
sourceUrl: anchorElement.href,
destinationUrl: urlObj.href,
ignoreSourceUrlParameters: true
});
}
catch {
continue;
}
}
// Notify the background script
if(urlMappings.length > 0) {
browser.runtime.sendMessage({
type: "webScience.linkResolution.registerUrlMappings",
pageId: pageManager.pageId,
urlMappings
});
}
// If the page has attention, set another timer tick
if(pageManager.pageHasAttention) {
timeoutID = setTimeout(timerTick, timerInterval);
}
}
}
// Wait for pageManager load
if (("webScience" in window) && ("pageManager" in window.webScience)) {
pageManagerLoaded();
}
else {
if(!("pageManagerHasLoaded" in window))
window.pageManagerHasLoaded = [];
window.pageManagerHasLoaded.push(pageManagerLoaded);
}
|
wiltonicp/Wilton-File
|
src/main/java/cn/wilton/framework/file/common/entity/Role.java
|
<gh_stars>1-10
package cn.wilton.framework.file.common.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.vihackerframework.common.entity.ViHackerEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
* @author Ranger
* @email <EMAIL>
* @since 2021/4/2
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_role")
public class Role extends ViHackerEntity {
@TableId(value = "id",type = IdType.AUTO)
private Long id;
private String roleName;
private String description;
private Integer status;
}
|
Noldor85/condrpxdenominusadm
|
www/js/pushDriver.js
|
<filename>www/js/pushDriver.js
function pushDriver(ev){
var payload = ev.payload
switch (payload.type){
case "chat":
var inTheChat =false
if(currentChat != null){
inTheChat = currentChat != null && ev.foreground && (currentChat.chatId == payload.chatId) && ($(".section_active").attr("section-name") == "msgChat")
}
console.log(inTheChat)
console.log(ev.payload.chatId)
getMessages(ev.payload.chatId,inTheChat,false)
chat.getChats()
home.init()
console.log(inTheChat)
if(inTheChat){
$(".qtyNewMsg").attr("qty",(parseInt($(".qtyNewMsg").attr("qty"))+1)).html($(".qtyNewMsg").attr("qty"))
}
break;
default:
console.log("this version do not recognize the type: "+ payload.type)
chat.getChats()
break;
}
}
|
ricosjp/siml
|
siml/__init__.py
|
<reponame>ricosjp/siml<gh_stars>10-100
"""
SiML
"""
import toml
from pathlib import Path
from siml import datasets # NOQA
from siml import inferer # NOQA
from siml import networks # NOQA
from siml import optimize # NOQA
from siml import prepost # NOQA
from siml import setting # NOQA
from siml import study # NOQA
from siml import trainer # NOQA
from siml import util # NOQA
def get_version():
path = Path(__file__).resolve().parent.parent / 'pyproject.toml'
pyproject = toml.loads(open(str(path)).read())
return pyproject['tool']['poetry']['version']
__version__ = get_version()
|
vfx-rs/openexr-bind
|
openexr-c/include.in/imf_flatimage.h
|
<reponame>vfx-rs/openexr-bind
#pragma once
#include "openexr-api-export.h"
#include <imf_pixeltype.h>
#include <imf_tiledescription.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct Imath_3_0__Box_Imath_3_0__Vec2_int___t_s Imath_3_0__Box_Imath_3_0__Vec2_int___t;
typedef Imath_3_0__Box_Imath_3_0__Vec2_int___t Imath_Box2i_t;
typedef struct std__string_t_s std__string_t;
typedef std__string_t std_string_t;
typedef struct Imf_3_0__FlatImageLevel_t_s Imf_3_0__FlatImageLevel_t;
typedef Imf_3_0__FlatImageLevel_t Imf_FlatImageLevel_t;
typedef struct Imf_3_0__FlatImage_t_s {
char _unused;
} OPENEXR_CPPMM_ALIGN(8) Imf_3_0__FlatImage_t;
typedef Imf_3_0__FlatImage_t Imf_FlatImage_t;
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_levelMode(
Imf_FlatImage_t const * this_
, Imf_LevelMode * return_);
#define Imf_FlatImage_levelMode Imf_3_0__FlatImage_levelMode
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_levelRoundingMode(
Imf_FlatImage_t const * this_
, Imf_LevelRoundingMode * return_);
#define Imf_FlatImage_levelRoundingMode Imf_3_0__FlatImage_levelRoundingMode
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_numLevels(
Imf_FlatImage_t const * this_
, int * return_);
#define Imf_FlatImage_numLevels Imf_3_0__FlatImage_numLevels
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_numXLevels(
Imf_FlatImage_t const * this_
, int * return_);
#define Imf_FlatImage_numXLevels Imf_3_0__FlatImage_numXLevels
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_numYLevels(
Imf_FlatImage_t const * this_
, int * return_);
#define Imf_FlatImage_numYLevels Imf_3_0__FlatImage_numYLevels
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_dataWindow(
Imf_FlatImage_t const * this_
, Imath_Box2i_t const * * return_);
#define Imf_FlatImage_dataWindow Imf_3_0__FlatImage_dataWindow
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_dataWindowForLevel(
Imf_FlatImage_t const * this_
, Imath_Box2i_t const * * return_
, int lx
, int ly);
#define Imf_FlatImage_dataWindowForLevel Imf_3_0__FlatImage_dataWindowForLevel
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_levelWidth(
Imf_FlatImage_t const * this_
, int * return_
, int lx);
#define Imf_FlatImage_levelWidth Imf_3_0__FlatImage_levelWidth
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_levelHeight(
Imf_FlatImage_t const * this_
, int * return_
, int ly);
#define Imf_FlatImage_levelHeight Imf_3_0__FlatImage_levelHeight
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_resize(
Imf_FlatImage_t * this_
, Imath_Box2i_t const * dataWindow
, Imf_LevelMode levelMode
, Imf_LevelRoundingMode levelRoundingMode);
#define Imf_FlatImage_resize Imf_3_0__FlatImage_resize
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_shiftPixels(
Imf_FlatImage_t * this_
, int dx
, int dy);
#define Imf_FlatImage_shiftPixels Imf_3_0__FlatImage_shiftPixels
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_insertChannel(
Imf_FlatImage_t * this_
, std_string_t const * name
, Imf_PixelType type
, int xSampling
, int ySampling
, _Bool pLinear);
#define Imf_FlatImage_insertChannel Imf_3_0__FlatImage_insertChannel
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_eraseChannel(
Imf_FlatImage_t * this_
, std_string_t const * name);
#define Imf_FlatImage_eraseChannel Imf_3_0__FlatImage_eraseChannel
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_clearChannels(
Imf_FlatImage_t * this_);
#define Imf_FlatImage_clearChannels Imf_3_0__FlatImage_clearChannels
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_renameChannel(
Imf_FlatImage_t * this_
, std_string_t const * oldName
, std_string_t const * newName);
#define Imf_FlatImage_renameChannel Imf_3_0__FlatImage_renameChannel
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_default(
Imf_FlatImage_t * * this_);
#define Imf_FlatImage_default Imf_3_0__FlatImage_default
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_ctor(
Imf_FlatImage_t * * this_
, Imath_Box2i_t const * dataWindow
, Imf_LevelMode levelMode
, Imf_LevelRoundingMode levelRoundingMode);
#define Imf_FlatImage_ctor Imf_3_0__FlatImage_ctor
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_dtor(
Imf_FlatImage_t * this_);
#define Imf_FlatImage_dtor Imf_3_0__FlatImage_dtor
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_level(
Imf_FlatImage_t * this_
, Imf_FlatImageLevel_t * * return_
, int lx
, int ly);
#define Imf_FlatImage_level Imf_3_0__FlatImage_level
OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImage_level_const(
Imf_FlatImage_t const * this_
, Imf_FlatImageLevel_t const * * return_
, int lx
, int ly);
#define Imf_FlatImage_level_const Imf_3_0__FlatImage_level_const
#ifdef __cplusplus
}
#endif
|
nahratzah/monsoon_plus_plus
|
intf/include/monsoon/metric_value.h
|
<gh_stars>1-10
#ifndef MONSOON_METRIC_VALUE_H
#define MONSOON_METRIC_VALUE_H
///\file
///\ingroup intf
#include <monsoon/intf_export_.h>
#include <cstdint>
#include <functional>
#include <string>
#include <string_view>
#include <monsoon/histogram.h>
#include <monsoon/cache/allocator.h>
#include <iosfwd>
#include <type_traits>
#include <optional>
#include <variant>
namespace monsoon {
/**
* \brief Metric value.
* \ingroup intf
*
* \details A metric value is either:
* \li <em>\ref monsoon::metric_value::empty</em> representing an empty value.
* \li <em>a boolean</em> value representing true or false.
* \li <em>a scalar</em> representing an integral or floating point value.
* \li <em>a \ref monsoon::histogram "histogram"</em>
* \li <em>a std::string</em> representing a textual value.
*/
class monsoon_intf_export_ metric_value {
public:
/**
* \brief The empty value.
*
* An empty metric value is defined as existing, but holds no meaningful information.
* \todo Maybe we should get rid of this and use std::optional<metric_value> where appropriate instead?
*/
struct empty {
///\brief Equality.
constexpr bool operator==(const empty&) const noexcept { return true; }
///\brief Inequality.
constexpr bool operator!=(const empty&) const noexcept { return false; }
};
/**
* \brief The unsigned integral scalar.
*
* This value is used for integral values that are not negative.
*/
using unsigned_type = std::uint64_t;
/**
* \brief The signed integral scalar.
*
* This value is only used for integral values that are negative.
*/
using signed_type = std::int64_t;
/**
* \brief The floating point scalar.
*/
using fp_type = std::double_t;
static_assert(std::is_copy_constructible_v<empty>
&& std::is_move_constructible_v<empty>,
"empty type constructors are borked.");
static_assert(std::is_copy_constructible_v<bool>
&& std::is_move_constructible_v<bool>,
"bool type constructors are borked.");
static_assert(std::is_copy_constructible_v<signed_type>
&& std::is_move_constructible_v<signed_type>,
"signed_type type constructors are borked.");
static_assert(std::is_copy_constructible_v<unsigned_type>
&& std::is_move_constructible_v<unsigned_type>,
"unsigned_type type constructors are borked.");
static_assert(std::is_copy_constructible_v<fp_type> &&
std::is_move_constructible_v<fp_type>,
"fp_type type constructors are borked.");
static_assert(std::is_copy_constructible_v<std::string>
&& std::is_move_constructible_v<std::string>,
"std::string type constructors are borked.");
static_assert(std::is_copy_constructible_v<histogram>
&& std::is_move_constructible_v<histogram>,
"histogram type constructors are borked.");
static_assert(std::is_copy_assignable_v<empty> &&
std::is_move_assignable_v<empty>,
"empty type assignment is borked.");
static_assert(std::is_copy_assignable_v<bool> &&
std::is_move_assignable_v<bool>,
"bool type assignment is borked.");
static_assert(std::is_copy_assignable_v<signed_type> &&
std::is_move_assignable_v<signed_type>,
"signed_type type assignment is borked.");
static_assert(std::is_copy_assignable_v<unsigned_type> &&
std::is_move_assignable_v<unsigned_type>,
"unsigned_type type assignment is borked.");
static_assert(std::is_copy_assignable_v<fp_type> &&
std::is_move_assignable_v<fp_type>,
"fp_type type assignment is borked.");
static_assert(std::is_copy_assignable_v<std::string> &&
std::is_move_assignable_v<std::string>,
"std::string type assignment is borked.");
static_assert(std::is_copy_assignable_v<histogram> &&
std::is_move_assignable_v<histogram>,
"histogram type assignment is borked.");
using string_type = std::basic_string<
char,
std::char_traits<char>,
cache_allocator<std::allocator<char>>>;
using string_ptr = std::shared_ptr<const string_type>;
/**
* \brief Underlying variant holding any one of the permitted values.
*/
using types = std::variant<
empty, bool, signed_type, unsigned_type, fp_type, std::string_view, histogram>;
private:
using internal_types = std::variant<
empty, bool, signed_type, unsigned_type, fp_type, string_ptr, histogram>;
public:
///@{
/**
* \brief Default constructor creates an \ref empty metric value.
*/
constexpr metric_value() noexcept = default;
metric_value(const metric_value&);
metric_value(metric_value&&) noexcept;
metric_value& operator=(const metric_value&);
metric_value& operator=(metric_value&&) noexcept;
~metric_value() noexcept;
/**
* \brief Create a metric value from a boolean.
*/
explicit metric_value(bool) noexcept;
/**
* \brief Create a metric value from a floating point type.
*/
explicit metric_value(fp_type) noexcept;
/**
* \brief Create a metric value from a string.
*/
explicit metric_value(std::string_view) noexcept;
/**
* \brief Create a metric value from a string.
*/
explicit metric_value(const char*) noexcept;
/**
* \brief Create a metric value from a \ref histogram.
*/
explicit metric_value(histogram) noexcept;
/**
* \brief Create a metric value from an integral.
*/
template<typename T,
typename =
std::enable_if_t<
std::is_integral<T>()
&& !std::is_same<bool, T>()
&& !std::is_same<char, T>()
&& !std::is_same<char16_t, T>()
&& !std::is_same<char32_t, T>()
&& !std::is_same<wchar_t, T>(),
void
>>
explicit metric_value(const T&) noexcept;
///@}
///@{
///\brief Test if two metric values hold the same type and value.
bool operator==(const metric_value&) const noexcept;
///\brief Test if two metric values do not hold the same type and value.
bool operator!=(const metric_value&) const noexcept;
///@}
/**
* \brief Parse metric value expression.
* \param s A string representation of an expression.
* \return A metric value, as represented by the expression.
* \throw std::invalid_argument indicating \p s does not hold a valid expression.
*/
static metric_value parse(std::string_view s);
///\brief Retrieve underlying variant.
types get() const noexcept;
///@{
/**
* \brief Interpret the metric value as a boolean.
*
* \return
* \li If the metric value holds a boolean, the underlying boolean is returned unmodified.
* \li If the metric value holds a histogram, the returned boolean represents if the histogram holds values (i.e., is not empty).
* \li If the metric value holds a numeric type, the returned boolean is true iff the numeric type is non zero.
* \li Otherwise, an empty optional is returned.
*
* \note string and \ref empty are not representable as booleans.
*/
std::optional<bool> as_bool() const noexcept;
/**
* \brief Interpret the metric value as a numeric value.
*
* \return
* \li If the metric value holds a boolean, the value 0 or 1 is returned.
* \li If the metric value holds a numeric type, the returned boolean is true iff the numeric type is non zero.
* \li Otherwise, an empty optional is returned.
*
* \note string, \ref histogram and \ref empty are not representable as numbers.
* \note the \ref signed_type is only used for negative values.
*/
std::optional<std::variant<signed_type, unsigned_type, fp_type>> as_number()
const noexcept;
/**
* \brief Interpret the metric value as a numeric value or a histogram.
*
* \return
* \li If the metric value holds a boolean, the value 0 or 1 is returned.
* \li If the metric value holds a numeric type, the returned boolean is true iff the numeric type is non zero.
* \li If the metric value holds a histogram, the histogram is returned.
* \li Otherwise, an empty optional is returned.
*
* \note string and \ref empty are not representable.
* \note the \ref signed_type is only used for negative values.
*/
std::optional<std::variant<signed_type, unsigned_type, fp_type, histogram>>
as_number_or_histogram() const noexcept;
/**
* \brief Interpret the metric value as a string value.
*
* \return
* \li If the metric value holds a boolean, the text \c "false" or \c "true" is returned.
* \li If the metric value holds a numeric value, the \c to_string() of that value is returned.
* \li If the metric value holds a string value, that value is returned.
* \li Otherwise, an empty optional is returned.
*
* \note \ref histogram and \ref empty are not representable.
*/
std::optional<std::string> as_string() const;
///@}
/**
* \brief Weak ordering support.
*
* Use this function to compare metric values in a stable ordering.
*
* \note The ordering is not lexicographic, nor is it based on the value of the metric value.
*/
static bool before(const metric_value&, const metric_value&) noexcept;
private:
internal_types value_;
};
///\brief Logical \em not operation.
///\ingroup intf
///\relates metric_value
///\code !x \endcode
monsoon_intf_export_
metric_value operator!(const metric_value& x) noexcept;
///\brief Logical \em and operation.
///\ingroup intf
///\relates metric_value
///\code x && y \endcode
monsoon_intf_export_
metric_value operator&&(const metric_value& x, const metric_value& y) noexcept;
///\brief Logical \em or operation.
///\ingroup intf
///\relates metric_value
///\code x || y \endcode
monsoon_intf_export_
metric_value operator||(const metric_value& x, const metric_value& y) noexcept;
///\brief Negate operation.
///\ingroup intf
///\relates metric_value
///\code -x \endcode
monsoon_intf_export_
metric_value operator-(const metric_value& x) noexcept;
///\brief Addition operation.
///\ingroup intf
///\relates metric_value
///\code x + y \endcode
monsoon_intf_export_
metric_value operator+(const metric_value& x, const metric_value& y) noexcept;
///\brief Subtract operation.
///\ingroup intf
///\relates metric_value
///\code x - y \endcode
monsoon_intf_export_
metric_value operator-(const metric_value& x, const metric_value& y) noexcept;
///\brief Multiply operation.
///\ingroup intf
///\relates metric_value
///\code x * y \endcode
monsoon_intf_export_
metric_value operator*(const metric_value& x, const metric_value& y) noexcept;
///\brief Divide operation.
///\ingroup intf
///\relates metric_value
///\code x / y \endcode
monsoon_intf_export_
metric_value operator/(const metric_value& x, const metric_value& y) noexcept;
///\brief Modulo operation.
///\ingroup intf
///\relates metric_value
///\code x % y \endcode
monsoon_intf_export_
metric_value operator%(const metric_value& x, const metric_value& y) noexcept;
///\brief Shift operation.
///\ingroup intf
///\relates metric_value
///\code x << y \endcode
monsoon_intf_export_
metric_value operator<<(const metric_value& x, const metric_value& y) noexcept;
///\brief Shift operation.
///\ingroup intf
///\relates metric_value
///\code x >> y \endcode
monsoon_intf_export_
metric_value operator>>(const metric_value& x, const metric_value& y) noexcept;
/**
* \brief Emit metric value to output stream.
* \ingroup intf_io
*
* \param out The stream to which to write.
* \param v The metric value to write to the stream.
* \return \p out
*/
monsoon_intf_export_
std::ostream& operator<<(std::ostream& out, const metric_value& v);
///\brief Compare metric value.
///\ingroup intf
///\relates metric_value
///\code x == y \endcode
monsoon_intf_export_
metric_value equal(const metric_value& x, const metric_value& y) noexcept;
///\brief Compare metric value.
///\ingroup intf
///\relates metric_value
///\code x != y \endcode
monsoon_intf_export_
metric_value unequal(const metric_value& x, const metric_value& y) noexcept;
///\brief Compare metric value.
///\ingroup intf
///\relates metric_value
///\code x < y \endcode
monsoon_intf_export_
metric_value less(const metric_value& x, const metric_value& y) noexcept;
///\brief Compare metric value.
///\ingroup intf
///\relates metric_value
///\code x > y \endcode
monsoon_intf_export_
metric_value greater(const metric_value& x, const metric_value& y) noexcept;
///\brief Compare metric value.
///\ingroup intf
///\relates metric_value
///\code x <= y \endcode
monsoon_intf_export_
metric_value less_equal(const metric_value& x, const metric_value& y) noexcept;
///\brief Compare metric value.
///\ingroup intf
///\relates metric_value
///\code x >= y \endcode
monsoon_intf_export_
metric_value greater_equal(const metric_value& x, const metric_value& y) noexcept;
/**
* \return Textual representation of a metric value.
* \ingroup intf_io
*/
monsoon_intf_export_
std::string to_string(const monsoon::metric_value&);
} /* namespace monsoon */
namespace std {
///\brief STL Hash support.
///\ingroup intf_stl
template<>
struct hash<monsoon::metric_value::empty> {
///\brief Hashed type.
using argument_type = const monsoon::metric_value::empty&;
///\brief Hash outcome.
using result_type = size_t;
///\brief Compute hash code for empty metric value.
size_t operator()(argument_type) const noexcept { return 0; }
};
///\brief STL Hash support.
///\ingroup intf_stl
template<>
struct hash<monsoon::metric_value> {
///\brief Hashed type.
using argument_type = const monsoon::metric_value&;
///\brief Hash outcome.
using result_type = size_t;
///\brief Compute hash code for metric value.
monsoon_intf_export_
size_t operator()(const monsoon::metric_value&) const noexcept;
};
} /* namespace std */
#include "metric_value-inl.h"
#endif /* MONSOON_METRIC_VALUE_H */
|
zhuochu/mand-mobile-rn
|
samples/demo/chart/data-store.demo.js
|
import { Dimensions } from "react-native";
export const width = Dimensions.get("window").width - 40; //40 is card & container component paddings
export const height = Math.round((width * 2) / 3);
export const labels = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
|
linyingzhen/btnew
|
components/index.js
|
/**
* const prefixCls = 'style-844716';
* const images = '/static/images/components';
* @Author: czy0729
* @Date: 2018-06-14 18:39:46
* @Last Modified by: czy0729
* @Last Modified time: 2018-11-02 11:26:54
* @Path m.benting.com.cn /components/index.js
*/
export { default as AffixTabs } from './AffixTabs';
export { default as Animate } from './Animate';
export { default as Button } from './Button';
export { default as Carousel } from './Carousel';
export { default as Content } from './Content';
export { default as CountDown } from './CountDown';
export { default as DiscuzContent } from './DiscuzContent';
export { default as EmojiPicker } from './EmojiPicker';
export { default as Empty } from './Empty';
export { default as FixedInput } from './FixedInput';
export { default as FixedTextarea } from './FixedTextarea';
export { default as Flex } from './Flex';
export { default as Form } from './Form';
export { default as Global } from './Global';
export { default as Header } from './Header';
export { default as Icon } from './Icon';
export { default as Img } from './Img';
export { default as ImgView } from './ImgView';
export { default as Lazy } from './Lazy';
export { default as Link } from './Link';
export { default as List } from './List';
export { default as ListView } from './ListView';
export { default as NativeShare } from './NativeShare';
export { default as Page } from './Page';
export { default as PayConfirm } from './PayConfirm';
export { default as Result } from './Result';
export { default as Reward } from './Reward';
export { default as Rule } from './Rule';
export { default as Tabs } from './Tabs';
export { default as Textarea } from './Textarea';
export { default as Upload } from './Upload';
export { default as Video } from './Video';
export { default as WaterMark } from './WaterMark';
|
getnacelle/nacelle-js
|
reference-stores/next/components/Nav/NavOverlay.js
|
<reponame>getnacelle/nacelle-js<filename>reference-stores/next/components/Nav/NavOverlay.js
import { CSSTransition } from 'react-transition-group';
import { useUi } from 'hooks/useUi';
import styles from './NavOverlay.module.css';
const NavOverlay = () => {
const { navVisible, setNavVisible } = useUi();
return (
<CSSTransition
in={navVisible}
timeout={0}
classNames={{
enterActive: styles.enterActive,
exitActive: styles.exitActive,
enter: styles.enter,
exit: styles.exit
}}
>
<div
className="fixed inset-0 bg-black bg-opacity-25 ease-linear duration-300"
aria-hidden="true"
onClick={() => setNavVisible(false)}
/>
</CSSTransition>
);
};
export default NavOverlay;
|
scscgit/XchangeCrypt-AndroidClient
|
app/src/main/java/bit/xchangecrypt/client/ui/BaseActivity.java
|
package bit.xchangecrypt.client.ui;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import bit.xchangecrypt.client.R;
import bit.xchangecrypt.client.listeners.ConnectionListener;
import bit.xchangecrypt.client.listeners.DialogOkClickListener;
import bit.xchangecrypt.client.util.ApplicationStorage;
import bit.xchangecrypt.client.util.FragmentsManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public abstract class BaseActivity extends AppCompatActivity {
protected Toolbar toolbar;
protected RelativeLayout content;
protected ActionBarDrawerToggle mDrawerToggle;
protected DrawerLayout mDrawerLayout;
protected LinearLayout mDrawerView;
protected ListView mDrawerMenu;
protected BottomNavigationView bottomNavigationView;
protected BroadcastReceiver networkStateReceiver;
private static ProgressDialog progress;
private AlertDialog alertDialog;
private boolean isOnline;
private ConnectionListener connectionListener;
protected LinearLayout bottomNavigationLayout;
private volatile String progressDialogMessage = "";
// Just to make sure customer isn't annoyed by a random dialog hazard
private final Object dialogLock = new Object();
public void showErrorDialog(int message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
alertDialog = builder.create();
alertDialog.show();
}
public void showDialogWindow(int message) {
if (alertDialog != null && alertDialog.isShowing()) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
public void showDialogWithAction(String message, final DialogOkClickListener listener, boolean showNegativeButton) {
if (alertDialog != null && alertDialog.isShowing()) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton(showNegativeButton ? R.string.positive_btn : R.string.ok_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
listener.onPositiveButtonClicked(BaseActivity.this);
}
});
if (showNegativeButton)
builder.setNegativeButton(R.string.negative_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
/*
ProgressDialog progressDialog = null;
public void showProgressDialog( CharSequence title, CharSequence message){
progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setCancelable(false);
progressDialog.setTitle(title);
progressDialog.setMessage(message);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
public void closeProgressDialog( ){
if (progressDialog != null){
progressDialog.dismiss();
}
}
*/
public void hideKeyboard() {
if (getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
public ApplicationStorage getAppStorage() {
return ApplicationStorage.getInstance(this);
}
public FragmentsManager getFragmentsManager() {
return FragmentsManager.getInstance(this);
}
public void showTopFragmentInMainBS() {
getFragmentsManager().showTopFragmentInMainBS();
}
public boolean isProgressDialog() {
return progress != null;
}
public void showProgressDialog(String message) {
runOnUiThread(() -> {
synchronized (this.dialogLock) {
this.progressDialogMessage = message;
Log.i(BaseActivity.class.getSimpleName(), "Setting dialog to: " + message);
if (progress != null) {
progress.setMessage(message);
} else {
progress = ProgressDialog.show(BaseActivity.this, null, message, true);
}
}
});
}
public void setProgressDialogPostfix(String postfix) {
runOnUiThread(() -> {
synchronized (this.dialogLock) {
// Only display the postfix if there is a context!
if (progress != null && !"".equals(progressDialogMessage)) {
progress.setMessage(this.progressDialogMessage + postfix);
Log.i(BaseActivity.class.getSimpleName(), "Setting dialog with postfix to: " + this.progressDialogMessage + postfix);
}
}
});
}
public void hideProgressDialog() {
runOnUiThread(() -> {
synchronized (this.dialogLock) {
this.progressDialogMessage = "";
if (progress != null) {
progress.dismiss();
Log.i(BaseActivity.class.getSimpleName(), "Dismissed dialog");
}
progress = null;
}
});
}
public void disableGestures() {
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
public void enableGestures() {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
public void showKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromInputMethod(view.getWindowToken(), 0);
}
public void hideKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void hideActionBarImmediately() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toolbar.setVisibility(View.GONE);
}
public void hideActionBar() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toolbar.animate().translationY(-getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material)).setInterpolator(new AccelerateInterpolator(2)).start();
}
public void showActionBar() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
toolbar.setVisibility(View.VISIBLE);
toolbar.animate().translationY(0).setInterpolator(new AccelerateInterpolator(2)).start();
}
public void hideStatusBar() {
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(attrs);
}
public void showStatusBar() {
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(attrs);
}
public void hideBottomNavigationView() {
collapse(bottomNavigationLayout, 0);
}
public void showBottomNavigationView() {
expand(bottomNavigationLayout, 500);
}
public void hideActionBarWithAnimation() {
collapse(toolbar, 500);
}
public void hideActionBarWithoutAnimation() {
collapse(toolbar, 0);
}
public void showActionBarWithAnimation() {
expand(toolbar, 500);
}
public void showActionBarWithoutAnimation() {
expand(toolbar, 0);
}
public BottomNavigationView getBottomNavigationView() {
return bottomNavigationView;
}
public void expand(final View v, final int duration) {
if (duration == 0) {
v.setVisibility(View.VISIBLE);
return;
}
if (v.getVisibility() != View.VISIBLE) {
v.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final int targetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 1;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? LinearLayout.LayoutParams.WRAP_CONTENT
: (int) (targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration(duration);
v.startAnimation(a);
}
}
public void collapse(final View v, final int duration) {
final int initialHeight = v.getMeasuredHeight();
if (duration != 0) {
if (v.getVisibility() != View.GONE) {
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration(duration);
//a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
} else {
v.setVisibility(View.GONE);
}
}
public ConnectionListener getConnectionListener() {
return connectionListener;
}
public void setConnectionListener(ConnectionListener connectionListener) {
this.connectionListener = connectionListener;
}
public boolean isOnline() {
return isOnline;
}
public void setContentMarginOn() {
if (content == null) {
return;
}
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) content.getLayoutParams();
params.topMargin = getResources().getDimensionPixelSize(R.dimen.toolbar_height);
content.setLayoutParams(params);
}
public void setContentMarginOff() {
if (content == null) {
return;
}
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) content.getLayoutParams();
params.topMargin = 0;
content.setLayoutParams(params);
}
@Override
protected void onStop() {
super.onStop();
}
public void setIsOnline(boolean isOnline) {
this.isOnline = isOnline;
}
}
|
eltld/ezEngine
|
Code/Engine/Core/ResourceManager/ResourceBase.h
|
<reponame>eltld/ezEngine<gh_stars>0
#pragma once
#include <Core/Basics.h>
#include <Foundation/Strings/HashedString.h>
#include <Foundation/IO/Stream.h>
#include <Foundation/Reflection/Reflection.h>
#include <Foundation/Time/Time.h>
#include <Foundation/Time/Timestamp.h>
#include <Core/ResourceManager/Implementation/Declarations.h>
#include <Core/ResourceManager/ResourceHandle.h>
class ezResourceTypeLoader;
/// \brief The case class for all resources.
///
/// \note Never derive directly from ezResourceBase, but derive from ezResource instead.
class EZ_CORE_DLL ezResourceBase : public ezReflectedClass
{
EZ_ADD_DYNAMIC_REFLECTION(ezResourceBase);
protected:
enum class DoUpdate
{
OnMainThread,
OnAnyThread
};
enum class Unload
{
AllQualityLevels,
OneQualityLevel
};
/// \brief Default constructor.
ezResourceBase(DoUpdate ResourceUpdateThread, ezUInt8 uiQualityLevelsLoadable);
/// \brief virtual destructor.
virtual ~ezResourceBase() { }
public:
struct MemoryUsage
{
MemoryUsage()
{
m_uiMemoryCPU = 0;
m_uiMemoryGPU = 0;
}
ezUInt32 m_uiMemoryCPU;
ezUInt32 m_uiMemoryGPU;
};
/// \brief Returns the unique ID that identifies this resource. On a file resource this might be a path. Can also be a GUID or any other scheme that uniquely identifies the resource.
const ezString& GetResourceID() const { return m_UniqueID; }
/// \brief The resource description allows to store an additional string that might be more descriptive during debugging, than the unique ID.
void SetResourceDescription(const char* szDescription);
/// \brief The resource description allows to store an additional string that might be more descriptive during debugging, than the unique ID.
const ezString& GetResourceDescription() const { return m_sResourceDescription; }
/// \brief Returns the current state in which this resource is in.
ezResourceState GetLoadingState() const { return m_LoadingState; }
/// \brief Returns the current maximum quality level that the resource could have.
///
/// This is used to scale the amount data used. Once a resource is in the 'Loaded' state, it can still have different
/// quality levels. E.g. a texture can be fully used with n mipmap levels, but there might be more that could be loaded.
/// On the other hand a resource could have a higher 'loaded quality level' then the 'max quality level', if the user
/// just changed settings and reduced the maximum quality level that should be used. In this case the resource manager
/// will instruct the resource to unload some of its data soon.
///
/// The quality level is a purely logical concept that can be handled very different by different resource types.
/// E.g. a texture resource could theoretically use one quality level per available mipmap level. However, since
/// the resource should generally be able to load and unload each quality level separately, it might make more sense
/// for a texture resource, to use one quality level for everything up to 64*64, and then one quality level for each
/// mipmap above that, which would result in 5 quality levels for a 1024*1024 texture.
///
/// Most resource will have zero or one quality levels (which is the same) as they are either loaded or not.
ezUInt8 GetNumQualityLevelsDiscardable() const { return m_uiQualityLevelsDiscardable; }
/// \brief Returns how many quality levels the resource may additionally load.
ezUInt8 GetNumQualityLevelsLoadable() const { return m_uiQualityLevelsLoadable; }
/// \brief Sets the current priority of this resource.
///
/// This is one way for the engine to specify how important this resource is, in relation to others.
/// The runtime can use any arbitrary scheme to compute the priority for resources, e.g. it could use
/// distance to the camera, on screen size, or random chance.
/// However, it should be consistent with the priority computation of other resources, to prevent
/// preferring or penalizing other resources too much.
///
/// Also make sure to always update the priority of resources when it becomes unimportant.
/// If a resource is set to high priority and then never changed back, it will be kept loaded
/// longer than others.
///
/// The due date is an absolute deadline, whereas the priority is a relative value compared to other resources.
/// Both can be combined. The due date always take precedence when it approaches, however as long as it is further away, priority has the most influence.
///
/// \sa SetDueDate
void SetPriority(ezResourcePriority priority);
/// \brief Returns the currently user-specified priority of this resource. \see SetPriority
ezResourcePriority GetPriority() const { return m_Priority; }
/// \brief Specifies the time (usually in the future) at which this resource is needed and should be fully loaded.
///
/// This is another way in which the loading priority of the resource can be influenced by the runtime.
/// By specifying a 'due date' or 'deadline', the resource manager is instructed to make sure that this resource
/// gets loaded in due time. The closer that the due date is, the higher the priority for loading this resource becomes.
///
/// Calling this function without parameters 'resets' the due date to a date into the far future, which practically disables it.
///
/// The due date is an absolute deadline, whereas the priority is a relative value compared to other resources.
/// Both can be combined. The due date always take precedence when it approaches, however as long as it is further away, priority has the most influence.
///
/// \sa SetPriority
void SetDueDate(ezTime date = ezTime::Seconds(60.0 * 60.0 * 24.0 * 365.0 * 1000.0));
/// \brief Returns the deadline (tNow + x) at which this resource is required to be loaded.
///
/// This represents the final priority that is used by the resource manager to determine which resource to load next.
/// \note It is fully valid to return a time in the past.
///
/// \note Although it is possible to override this function, it is advised not to do so.
/// The default algorithm is tweaked well enough already, it should not be necessary to modify it.
virtual ezTime GetLoadingDeadline(ezTime tNow) const;
/// \brief Returns the basic flags for the resource type. Mostly used the resource manager.
const ezBitflags<ezResourceFlags>& GetBaseResourceFlags() const { return m_Flags; }
/// \brief Returns the information about the current memory usage of the resource.
const MemoryUsage& GetMemoryUsage() const { return m_MemoryUsage; }
/// \brief Returns the time at which the resource was (tried to be) acquired last.
/// If a resource is acquired using ezResourceAcquireMode::PointerOnly, this does not update the last acquired time, since the resource is not acquired for full use.
ezTime GetLastAcquireTime() const { return m_LastAcquire; }
/// \brief Returns the reference count of this resource.
ezInt32 GetReferenceCount() const { return m_iReferenceCount; }
/// \brief Returns the modification date of the file from which this resource was loaded.
///
/// The date may be invalid, if it cannot be retrieved or the resource was created and not loaded.
const ezTimestamp& GetLoadedFileModificationTime() const { return m_LoadedFileModificationTime; }
private:
friend class ezResourceManager;
friend class ezResourceManagerWorker;
friend class ezResourceManagerWorkerGPU;
/// \brief Called by ezResourceManager shortly after resource creation.
void SetUniqueID(const char* szUniqueID, bool bIsReloadable);
void CallUnloadData(Unload WhatToUnload);
/// \brief Requests the resource to unload another quality level. If bFullUnload is true, the resource should unload all data, because it is going to be deleted afterwards.
virtual ezResourceLoadDesc UnloadData(Unload WhatToUnload) = 0;
void CallUpdateContent(ezStreamReaderBase* Stream);
/// \brief Called whenever more data for the resource is available. The resource must read the stream to update it's data.
virtual ezResourceLoadDesc UpdateContent(ezStreamReaderBase* Stream) = 0;
/// \brief Returns the resource type loader that should be used for this type of resource, unless it has been overridden on the ezResourceManager.
///
/// By default, this redirects to ezResourceManager::GetDefaultResourceLoader. So there is one global default loader, that can be set
/// on the resource manager. Overriding this function will then allow to use a different resource loader on a specific type.
/// Additionally, one can override the resource loader from the outside, by setting it via ezResourceManager::SetResourceTypeLoader.
/// That last method always takes precedence and allows to modify the behavior without modifying the code for the resource.
/// But in the default case, the resource defines which loader is used.
virtual ezResourceTypeLoader* GetDefaultResourceTypeLoader() const;
volatile ezResourceState m_LoadingState;
ezUInt8 m_uiQualityLevelsDiscardable;
ezUInt8 m_uiQualityLevelsLoadable;
protected:
/// \brief Non-const version for resources that want to write this variable directly.
MemoryUsage& ModifyMemoryUsage() { return m_MemoryUsage; }
/// \brief Call this to specify whether a resource is reloadable.
///
/// By default all created resources are flagged as not reloadable.
/// All resources loaded from file are automatically flagged as reloadable.
void SetIsReloadable(bool bIsReloadable) { m_Flags.AddOrRemove(ezResourceFlags::IsReloadable, bIsReloadable); }
private:
template<typename ResourceType>
friend class ezResourceHandle;
template<typename SELF, typename SELF_DESCRIPTOR>
friend class ezResource;
friend EZ_CORE_DLL void IncreaseResourceRefCount(ezResourceBase* pResource);
friend EZ_CORE_DLL void DecreaseResourceRefCount(ezResourceBase* pResource);
/// \brief This function must be overridden by all resource types.
///
/// It has to compute the memory used by this resource.
/// It is called by the resource manager whenever the resource's data has been loaded or unloaded.
virtual void UpdateMemoryUsage(MemoryUsage& out_NewMemoryUsage) = 0;
ezBitflags<ezResourceFlags> m_Flags;
ezResourcePriority m_Priority;
ezAtomicInteger32 m_iReferenceCount;
ezAtomicInteger32 m_iLockCount;
ezString m_UniqueID;
ezString m_sResourceDescription;
MemoryUsage m_MemoryUsage;
ezTime m_LastAcquire;
ezTime m_DueDate;
ezTimestamp m_LoadedFileModificationTime;
};
|
anduintransaction/rivendell
|
utils/templater.go
|
<reponame>anduintransaction/rivendell
package utils
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/base64"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/palantir/stacktrace"
)
var cwdStack = NewStringStack()
// ExecuteTemplate .
func ExecuteTemplate(templateFile string, variables map[string]string) ([]byte, error) {
content, err := ioutil.ReadFile(templateFile)
if err != nil {
return nil, stacktrace.Propagate(err, "cannot read template file %q", templateFile)
}
currentFolder := filepath.Dir(templateFile)
cwdStack.Push(currentFolder)
contentWithEnvExpand := ExpandEnv(string(content))
tmpl, err := template.
New(templateFile).
Funcs(sprig.TxtFuncMap()).
Funcs(map[string]interface{}{
"import": importFunc,
"indent": indentFunc,
"loadFile": loadFileFunc,
"trim": trimFunc,
"hash": hashFunc,
"base64": base64Func,
"asGenericMap": asGenericMap,
"asMapString": asMapString,
}).
Parse(contentWithEnvExpand)
if err != nil {
return nil, stacktrace.Propagate(err, "cannot parse template file %q", templateFile)
}
tmpl = tmpl.Option("missingkey=error")
b := &bytes.Buffer{}
err = tmpl.Execute(b, variables)
if err != nil {
return nil, stacktrace.Propagate(err, "cannot execute template file %q", templateFile)
}
cwdStack.Pop()
return b.Bytes(), nil
}
func importFunc(templateFile string, variables map[string]string) (string, error) {
realPath, err := resolveRealpath(templateFile)
if err != nil {
return "", err
}
content, err := ExecuteTemplate(realPath, variables)
return string(content), err
}
func indentFunc(indent int, content string) string {
indentStr := strings.Repeat(" ", indent)
result := ""
scanner := bufio.NewScanner(bytes.NewReader([]byte(content)))
for scanner.Scan() {
result += indentStr + scanner.Text() + "\n"
}
return result
}
func loadFileFunc(filename string) (string, error) {
realPath, err := resolveRealpath(filename)
if err != nil {
return "", err
}
content, err := ioutil.ReadFile(realPath)
if err != nil {
return "", err
}
return string(content), nil
}
func resolveRealpath(filename string) (string, error) {
var realPath string
if strings.HasPrefix(filename, "/") {
realPath = filename
} else {
currentFolder, err := cwdStack.Head()
if err != nil {
return "", err
}
realPath = filepath.Join(currentFolder, filename)
}
return realPath, nil
}
func trimFunc(content string) string {
return strings.TrimSpace(content)
}
func hashFunc(filename string) (string, error) {
realPath, err := resolveRealpath(filename)
if err != nil {
return "", err
}
content, err := ioutil.ReadFile(realPath)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", sha256.Sum256(content)), nil
}
func base64Func(content string) string {
return base64.StdEncoding.EncodeToString([]byte(content))
}
func asGenericMap(m map[string]string) map[string]interface{} {
ret := make(map[string]interface{}, len(m))
for k, v := range m {
ret[k] = v
}
return ret
}
func asMapString(m map[string]interface{}) map[string]string {
ret := make(map[string]string)
for k, v := range m {
if strVal, ok := v.(string); ok {
ret[k] = strVal
}
if strg, ok := v.(fmt.Stringer); ok {
ret[k] = strg.String()
}
}
return ret
}
|
coocox/cox
|
CoX/CoX_Peripheral/CoX_Peripheral_KLx/libcox/xhw_wdt.h
|
<reponame>coocox/cox
//*****************************************************************************
//
//! \file xhw_wdt.h
//! \brief Macros and defines used when accessing the WATCHDOG hardware.
//! \version V2.2.1.0
//! \date 11/14/2012
//! \author CooCox
//! \copy
//!
//! Copyright (c) 2012, CooCox
//! All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//! * Redistributions of source code must retain the above copyright
//! notice, this list of conditions and the following disclaimer.
//! * Redistributions in binary form must reproduce the above copyright
//! notice, this list of conditions and the following disclaimer in the
//! documentation and/or other materials provided with the distribution.
//! * Neither the name of the <ORGANIZATION> nor the names of its
//! contributors may be used to endorse or promote products derived
//! from this software without specific prior written permission.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
//! THE POSSIBILITY OF SUCH DAMAGE.
//
//****************************************************************************
#ifndef __XHW_WDT_H__
#define __XHW_WDT_H__
//*****************************************************************************
//
//! \addtogroup CoX_Peripheral_Lib
//! @{
//
//*****************************************************************************
//*****************************************************************************
//
//! \addtogroup WDT
//! @{
//
//*****************************************************************************
//*****************************************************************************
//
//! \addtogroup KLxx_WDT_Register KLxx WDT Register
//! \brief Here are the detailed info of WDT registers.
//!
//! it contains:
//! - Register offset.
//! - detailed bit-field of the registers.
//! - Enum and mask of the registers.
//! .
//! Users can read or write the registers through xHWREG().
//!
//! @{
//
//*****************************************************************************
//*****************************************************************************
//
//! \addtogroup KLxx_WDT_Register_Address WDT Address Register(WDT_Address)
//! \brief Defines the address of the WDT_Register_Address register
//! @{
//
//*****************************************************************************
//
//! Watchdog Timer Control Register (SIM_COPC)
//
#define SIM_COPC 0x40048100
//
//! Watchdog Timer Service Register (SIM_SRVCOP)
//
#define SIM_SRVCOP 0x40048104
//*****************************************************************************
//
//! @}
//
//*****************************************************************************
//*****************************************************************************
//
//! \addtogroup KLxx_WDT_Register_SIM_COPC WDT SIM_COPC Register(SIM_COPC)
//! \brief Defines for the bit fields in the WDT_Register_Address register
//! @{
//
//*****************************************************************************
//
//! Watchdog timeout
//
#define SIM_COPC_COPT_MASK 0x0000000C
//
//! Watchdog clock select
//
#define SIM_COPC_COPCLKS 0x00000002
//
//! Watchdog windowed mode
//
#define SIM_COPC_COPW 0x00000001
//*****************************************************************************
//
//! @}
//
//*****************************************************************************
//*****************************************************************************
//
//! @}
//
//*****************************************************************************
//*****************************************************************************
//
//! @}
//
//*****************************************************************************
//*****************************************************************************
//
//! @}
//
//*****************************************************************************
#endif // __XHW_WADT_H__
|
dalayLama/2020-06-otus-java-skorik
|
hw08-json-object-writer/src/main/java/ru/otus/types/DefaultFactoryDefinerType.java
|
package ru.otus.types;
import ru.otus.types.checkers.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DefaultFactoryDefinerType implements FactoryDefinerType {
private final Set<WritableTypeChecker> checkers = new HashSet<>();
private TypeDefiner typeDefiner;
public DefaultFactoryDefinerType(Collection<? extends WritableTypeChecker> checkers) {
this.checkers.addAll(checkers);
}
public DefaultFactoryDefinerType() {
this(List.of(
new CustomObjectWritableTypeChecker(),
new StringWritableTypeChecker(),
new NumberWritableTypeChecker(),
new IterableWritableTypeChecker(),
new ArrayWritableTypeChecker(),
new CharWritableTypeChecker(),
new BooleanWritableTypeChecker(),
new NullWritableTypeChecker()
));
}
@Override
public TypeDefiner createDefinerType() {
if (typeDefiner == null) {
typeDefiner = new TypeDefinerImpl(checkers);
}
return typeDefiner;
}
}
|
Daniel-Fonseca-da-Silva/Agilidade-e-TDD-um-dia-no-desenvolvimento-de-software
|
src/main/java/br/com/caelum/clines/api/airports/AircraftLocationView.java
|
<reponame>Daniel-Fonseca-da-Silva/Agilidade-e-TDD-um-dia-no-desenvolvimento-de-software
package br.com.caelum.clines.api.airports;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@Getter
@AllArgsConstructor
@EqualsAndHashCode
public class AircraftLocationView {
private String country;
private String state;
private String city;
}
|
norjs/nopg
|
src/scan.js
|
"use strict";
import is from '@norjs/is';
import debug from '@norjs/debug';
import Cache from './Cache.js';
/** Scan object(s) recursively and returns every scanned object mapped with identification property $id
* @param objs {Array|object} Object or array of objects to scan
* @returns {object} Object like `{'<ID>': [{'$id':'<ID>',...}, '<ID2>': ...]}`
*/
module.exports = function scan(objs, opts) {
if(!is.array(objs)) {
objs = [objs];
}
debug.assert(objs).is('array');
opts = opts || {};
debug.assert(opts).is('object');
//debug.log('Creating cache...');
var cache = new Cache({
cursors: opts.cursors ? true : false
});
//debug.log('Scanning into cache...');
cache.scanArray(objs);
return cache;
};
/* EOF */
|
copyit/SBtream
|
sbtream-server/src/main/java/com/borber/sbtream/server/mapper/WatchHistoryMapper.java
|
package com.borber.sbtream.server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.borber.sbtream.server.model.entity.WatchHistoryDO;
/**
* @author x
* @description 针对表【watch_history(观看记录表)】的数据库操作Mapper
* @createDate 2021-11-06 14:58:04
* @Entity com.borber.sbtream.server.model.entity.WatchHistoryDO
*/
public interface WatchHistoryMapper extends BaseMapper<WatchHistoryDO> {
}
|
chrisGoad/prototypetrees
|
src/dom/dom1.js
|
<reponame>chrisGoad/prototypetrees<filename>src/dom/dom1.js<gh_stars>0
// Copyright 2019 <NAME>
// License: MIT
const domr = codeRoot.set("dom",core.ObjectNode.mk());
/* the two varieties of dom elements are svg.shape and html.Element
* each particular element, such as an svg rect or an html div, is represented by its own prototype.
*/
domr.set("Element",core.ObjectNode.mk()).__namedType();
let Element = domr.Element;
/* how dom objects are represented: <tag att1=22 att2=23>abcd <tag2 id="abc"></tag2>
The tag names the prototype of this item. In svg mode the attributes are primitive __properties of the item.
The id attribute determines the __name. Shorthand; instead of id="abc" #abc will also work.
example
<chart.component.bubble <#caption>foob</#caption><#value>66</#value>
item.bubbe.caption
item.set("rectP","<rectangle style='color:red'>
dom.set("Style",core.ObjectNode.mk()).namedType();
*/
domr.set("Style",core.ObjectNode.mk()).__namedType();
let Style = domr.Style;
Style.mk = function (o) {
let rs = Object.create(Style);
core.extend(rs,o);
return rs;
}
const parseStyle = function(st,dst) {
let rs = dst?dst:Style.mk();
let sp0 = st.split(';');
sp0.forEach(function (c) {
let sp1 = c.split(":");
if (sp1.length===2) {
rs[sp1[0]] = sp1[1];
}
});
return rs;
}
core.ObjectNode.__tag = function () {
// march two prototypes p0 p1, adjacent elements of the prototype chain, down the chain
// until p1 === svg.shape
let p0 = this;
let p1 = Object.getPrototypeOf(p0);
while (true) {
if ((p1 === SvgElement) || (codeRoot.html && (p1 === codeRoot.html.Element))) {
return p0.__name;
}
if (p1 === core.ObjectNode) {
return undefined;
}
p0 = p1;
p1 = Object.getPrototypeOf(p1);
}
}
// an Array functions as a <g>
core.ArrayNode.__tag = function () {
return "g";
}
const isSvgTag = function (itag) {
if (svg) {
let tag = svg.tag;
if (tag) {
return tag[itag];
}
}
}
const toCamelCase = function (str) {
let dashPos = str.indexOf("-"),
beforeDash,oneAfterDash,rs;
if (dashPos < 0) {
return str;
}
beforeDash = str.substr(0,dashPos);
oneAfterDash = str.substr(dashPos+2);
rs = beforeDash + str[dashPos+1].toUpperCase() + oneAfterDash;
return rs;
}
domr.Element.__setStyle = function () {
let st = this.style;
let el = this.__element;
if (st && el) {
core.mapNonCoreLeaves(st,function (sv,iprop) {
let prop = toCamelCase(iprop);
el.style[prop] = sv;
});
}
}
Element.__applyDomMap = function () {
let transfers = this.__domTransfers;
let el = this.__element;
let thisHere = this;
if (transfers) {
transfers.forEach(function (att) {
let val = thisHere[att];
if (val !== undefined) {
el.setAttribute(att,val);
}
});
}
if (this.setDomAttributes) {
this.setDomAttributes(el);
}
}
Element.__setAttributes = function (tag) {
let forSvg = isSvgTag(tag);
let tagv = forSvg?svg.tag[tag]:codeRoot.html.tag[tag];
if (!tagv) {
core.error('dom','uknown tag '+tag);
}
let el = this.__get("__element");
let id,xf,tc,cl;
if (!el) {
return;
}
id = this.__svgId?this.__svgId:(this.id?this.id:this.__name);
this.__applyDomMap();
this.__setStyle();
el.setAttribute('id',id);
xf = this.transform;
if (xf) {
el.setAttribute("transform",xf.toSvg());
}
tc = this.text;
if (tc && (tag==="text")) {
this.updateSvgText();
}
cl = this.class;
if (cl) {
el.className = cl;
}
}
Element.__setAttribute = function (att,av) {
let el;
this[att] = av;
el = this.__get("__element");
if (el) {
el.setAttribute(att,av);
}
}
Element.setDomAttribute = Element.__setAttribute;
// the only attribute that an Array has is an id. This is only for use as the g element in svg
core.ArrayNode.__setAttributes = function () {
let el = this.__get("__element");
let id,vis;
if (!el) {
return;
}
id = this.id?this.id:this.__name;
el.setAttribute("id",id);
vis = this.visibility;
if (vis) {
el.setAttribute("visibility",vis);
}
};
Element.__removeAttribute = function (att) {
let el = this.__element;
if (el) {
el.removeAttribute(att);
}
}
const stashDom = function (nd,stash) {
let el = nd.__element;
let cn = nd.__container;
if (!(el||cn)) {
return;
}
if (el) {
stash.__element = el;
}
if (cn) {
stash.__container = cn;
}
delete nd.__element;
delete nd.__container;
//delete nd.__domAttributes;
core.forEachTreeProperty(nd,function (v,k) {
let chst;
if (stash) {
chst = stash[k] = {};
} else {
chst = undefined;
}
stashDom(v,chst);
});
}
const restoreDom = function (nd,stash) {
if (!stash) {
return;
}
if (stash.__element) {
nd.__element = stash.__element;
}
if (stash.__container) {
nd.__container = stash.__container;
}
core.forEachTreeProperty(nd,function (ch,k) {
let stch = stash[k];
restoreDom(ch,stch);
});
}
// for adding event listeners to the DOM for newly added Elements
const addEventListeners = function (el) {
let cv = el;
let eel = el.__element;
let done = false;
let evl;
while (!done) {
evl = cv.__get("__eventListeners");
if (evl) {
core.mapOwnProperties(evl,function (fns,nm) {
fns.forEach(function (f) {eel.addEventListener(nm,f);});
});
}
cv = Object.getPrototypeOf(cv);
done = cv === Element;
}
}
/* add this one element to the DOM. Does not recurse.
* todo need to take __setIndex of this into account
* appends to to the element of the parent, if present, ow uses rootEl
*/
Element.__addToDom1 = function (itag,rootEl) {
let pr,pel,isLNode,forSvg,tag;
let cel = this.__get("__element");
if (cel) {
return cel;
}
pr = this.__parent;
if (pr) {
pel = pr.__get("__element");
}
if (rootEl && !pel) {
pel = rootEl;
this.__container = pel;//=rootEl;
} else {
if (!pel) {
return;
}
}
isLNode = core.ArrayNode.isPrototypeOf(this);
forSvg = isSvgTag(itag);
tag = itag?itag:this.tagOf();
cel = forSvg?document.createElementNS("http://www.w3.org/2000/svg",tag):document.createElement(tag);
this.__element = cel;
cel.__prototypeJungleElement = this;
this.__setAttributes(tag,forSvg);
if (!pel || !pel.appendChild) {
core.error('dom','unexpected condition');
}
pel.appendChild(cel);
if (this.__color__) {
$(cel).spectrum({change:this.__newColor__,
color:this.__color__,showInput:true,showInitial:true,preferredFormat:"rgb"});
}
if (!forSvg && this.text) {
cel.innerHTML = this.text;
}
if (!isLNode && !forSvg) {
addEventListeners(this);
}
return cel;
}
core.ArrayNode.__addToDom1 = Element.__addToDom1
Element.__addToDom = function (rootEl,idepth) {
let depth = idepth?idepth:0;
let el = this.__get("__element");
let tg = this.__tag();
let wr;
if (el) {
this.__setAttributes(tg); // update
} else {
if (this.visibility === 'hidden') {
return;
}
wr = this.__wraps;// if this wraps an element already on the page, no need for a root.
if (wr) {
el = document.getElementById(wr);
if (!el) {
core.error('Missing element for wrap of ',wr);
return;
}
if (el.tagName.toLowerCase() !== tg) {
core.error('Tag mismatch for wrap of ',wr);
return;
}
this.__element = el;
this.__setAttributes(tg); // update
} else {
el = this.__addToDom1(tg,rootEl);
}
}
if (el) {
this.__iterDomTree(function (ch) {
ch.__addToDom(undefined,depth+1);
},true); // iterate over objects only
}
}
core.ArrayNode.__addToDom = function (unused,idepth) {
let depth = idepth?idepth:0;
Element.__addToDom.call(this,undefined,depth+1);
}
Element.draw = Element.__addToDom;
Element.updateAndDraw = function () {
if (this.update) {
this.update();
} else {
this.__update();
}
this.draw();
}
core.ArrayNode.draw = Element.__addToDom;
Element.__installChild = function (nd) {
let el = this.__element;
let nel;
if (!el) {
return;
}
nel = core.getval(nd,"__element");
if (nel) {
return;
}
nd.__addToDom(el);
}
core.ArrayNode.__installChild = Element.__installChild;
Element.__mkFromTag = function (itag) {
let tag = itag;
let tv,rs,html,dv;
if (tag) {
tv = (svg&&(svg.tag))?svg.tag[tag]:undefined;
}
if (tv) {
rs = Object.create(tv);
} else {
html = codeRoot.html;
if (!html) {
core.error("No definition for tag",tag);
}
dv = html.tag[tag];
if (dv) {
rs = dv.instantiate();
} else{
core.error("No definition for tag",tag);
}
}
return rs;
}
const __isDomEl = function (x) {
if (core.ArrayNode.isPrototypeOf(x)) {
return !x.__notInDom
} else {
return Element.isPrototypeOf(x);
}
}
Element.push = function (ind) {
let nd,scnt;
if (typeof ind === "string") {
core.error("OBSOLETE option");
} else {
nd = ind;
if (!__isDomEl(nd)) {
core.error("Expected dom Element");
}
}
scnt = core.getval(this,'__setCount');
scnt = scnt?scnt+1:1;
nd.__name = scnt;
this.__setCount = scnt;
this[scnt] = nd;
nd.__parent = this;
this.__installChild(nd);
}
const removeElement = function (x) {
let el = x.__element;
if (el) {
let pel = el.parentNode;
if (pel) {
pel.removeChild(el);
}
}
delete x.__element;
// delete x.__domAttributes;
}
core.removeHooks.push(removeElement);
// called just before the main reparenting
const reparentElement = function (x,newParent,newName) {
let el = x.__element;
let npEl = newParent.__element;
let pel;
if (el) {
if (!npEl) {
core.error(newParent.__name," is not in the svg tree in reparent");
}
pel = el.parentNode;
if (pel) {
pel.removeChild(el);
}
npEl.appendChild(el);
if (!el.id) {
el.setAttribute("id",newName);
}
}
}
core.reparentHooks.push(reparentElement);
let tryParse = false;
let alwaysXMLparse = true; // didn't have luck with the html variant, for some reason. Later, use resig's javascript html parser
const parseWithDOM = function (s,forXML) {
let domParser,rs,dm;
let prs = domParser;
if (!prs) {
domParser = prs = new DOMParser();// built into js
}
dm = prs.parseFromString(s,forXML||alwaysXMLparse?'application/xml':'text/html');
if ((!dm) || (!dm.firstChild) || (dm.firstChild.tagName === "html")) { // an error message
core.error("Error in parsing XML",s);
}
if (tryParse) {
try {
rs = domToElement(dm.childNodes[0],forXML);// the DOMParser returns the node wrapped in a document object
} catch (e) {
core.error("Error in parsing XML",s);
}
} else {
rs = domToElement(dm.childNodes[0],forXML);// the DOMParser returns the node wrapped in a document object
}
return rs;
}
const sortByIndex = function (ar) {
let cmf = function (a,b) {
let ai = a.__setIndex;
let bi;
if (ai === undefined) {
ai = parseInt(a.__name);
}
ai = isNaN(ai)?0:ai;
bi = b.__setIndex;
if (bi === undefined) {
bi = parseInt(b.__name);
}
bi = isNaN(bi)?0:bi;
return (ai < bi)?-1:1;
}
ar.sort(cmf);
}
core.ObjectNode.__iterDomTree = function (fn) {
let ownprops = Object.getOwnPropertyNames(this);
let thisHere = this;
let sch = [];
ownprops.forEach(function (k) {
let ch;
if (core.treeProperty(thisHere,k,true,true)) { //true: already known to be an owned property
ch = thisHere[k];
if (__isDomEl(ch)) {
sch.push(ch);
}
}
});// now sort by __setIndex
sortByIndex(sch);
sch.forEach(function (ch) {
fn(ch,ch.__name);
});
return this;
}
core.ArrayNode.__iterDomTree = function (fn) {
this.forEach((ch) => {
if (__isDomEl(ch) && (ch.__parent === this)) {
fn(ch);
}
});
return this;
}
// this causes sets of ELements to be added to the DOM
core.preSetChildHooks.push(function(node,nm) {
// this needs to work before core.ComputedField is defined
let prv = node.__get(nm);
if (prv && __isDomEl(prv)) {
let isArray = Array.isArray(node);
removeElement(prv);
// prv.remove(); changed to removeElement 3/22/19
}
});
/* since order is important for drawing, order of set operations is preserved here.
* specifically, each Object has a __setCount just counting how many sets have been done over time
* each of its Node __children has a __setIndex, which was the value of __setCount when it was set
* then drawing draws __children in setIndex order
*/
let disableAdditionToDomOnSet = false;
core.setChildHooks.push(function(node,nm,c) {
// this needs to work before core.ComputedField is defined
let scnt;
if (disableAdditionToDomOnSet) {
return;
}
if (__isDomEl(node)) {
// keep track of shape and Arrays __children order
if ((nm === "transform") && Transform.isPrototypeOf(c)) { //special treatment for transforms
node.realizeTransform();
return;
}
if (__isDomEl(c)) {
scnt = node.__setCount;
if (scnt === undefined) {
scnt = 0;
}
scnt = scnt?scnt+1:1;
node.__setCount = scnt;
c.__setIndex = scnt;
node.__installChild(c);
}
}
});
core.addToArrayHooks.push(function (node,c) {
let ndom = __isDomEl(node),
cdom = __isDomEl(c);
if ((ndom || core.ArrayNode.isPrototypeOf(node)) && (cdom || core.ArrayNode.isPrototypeOf(c)) && (ndom || cdom)) {
node.__installChild(c);
}
});
// an Element may have a property __eventListeners, which is a dictionary, each of whose
// values is an array of functions, the listeners for the id of that value
Element.addEventListener = function (id,fn) {
let listeners = this.__get("__eventListeners");
let element,listenerArray;
if (!listeners) {
listeners = core.ObjectNode.mk();
this.set("__eventListeners",listeners);
}
element = this.__element;
listenerArray = listeners[id];
if (listenerArray===undefined) {
listenerArray = listeners.set(id,core.ArrayNode.mk());
}
listenerArray.push(fn);
if (element) {
element.addEventListener(id,fn);
}
}
// remove listener needs to be applied at each object in the prototype chain, since __eventListeners can appear at various levels
Element.__removeEventListener1 = function (nm,f) {
let ev = this.__get("__eventListeners");
let evl,eel;
if (!ev) {
return;
}
evl = ev[nm];
eel = this.__element;
if (evl) {
if (f === undefined) { // remove all listeners of this type
delete ev[nm];
if (eel) {
evl.forEach(function (ff) {
eel.removeEventListener(nm,ff);
});
}
} else {
let idx = evl.indexOf(f);
if (idx >= 0) {
evl.splice(idx,1);
}
}
}
}
Element.removeEventListener = function (nm,f) {
let eel = this.__element;
let cv,done;
if (eel && (f !== undefined)) { // remove all listeners of this type
eel.removeEventListener(nm,f);
}
cv = this;
done = false;
while (!done) {
cv.__removeEventListener1(nm,f);
done = cv === Element;
cv = Object.getPrototypeOf(cv);
}
}
const getStyle = function (e) {
let cst = e.style;
if (!cst) {
cst = Style.mk();
e.set("style",cst);
}
return cst;
}
Element.__rootElement = function () { // find the most distant ancestor which is an Element
let cv = this;
let nv;
while (true) {
nv = cv.__parent;
if (!Element.isPrototypeOf(nv)) {
return cv;
}
cv = nv;
}
}
// dom events are transduced into PrototypeJungle events if they are listened for (not in use as of 2/18)
const findAncestorListeningFor = function (nd,evn) {
let cv = nd;
let lf;
while (true) {
lf = cv.__listenFor;
if (lf && (lf.indexOf(evn)>=0)) {
return cv;
}
cv = cv.__parent;
}
}
const eventTransducer = function (e) {
let trg = e.target.__prototypeJungleElement;
let evn = e.type;
let ev = core.Event.mk(trg,"dom_"+evn);
ev.domEvent = e;
ev.emit();
}
const addTransducers = function (nd,events) {
let el = this.__element;
if (el) {
events.forEach(function (evn) {el.addEventListener(evn,svg.eventTransducer)});
}
}
Element.__listenFor = function (events) {
let el = this.__element;
let prv = this.__listenFor;
if (prv) {
events.forEach(function (evn) {
if (prv.indexOf(evn)<0) {
prv.push(evn);
if (el) {
el.addEventListener(evn,svg.eventTransducer);
}
}
});
} else {
this.set("__listenFor",core.lift(events));
addTransducers(this,events);
}
}
// used when nd is first added to the DOM
const addListenFors = function (nd) {
let lf = nd.__listenFor;
if (lf) {
addTransducers(nd,lf);
}
}
const elementWidth = function (node) {
let el = node.__element;
if (el) {
return el.offsetWidth;
}
}
const parentElementWidth = function (node) {
let el = node.__element;
let cel;
if (el) {
cel = el.parentNode;
return cel.offsetWidth;
}
}
const elementHeight = function (node) {
let el = node.__element;
if (el) {
return el.offsetHeight;
}
}
const parentElementHeight = function (node) {
let el = node.__element;
if (el) {
let cel = el.parentNode;
return cel.offsetHeight;
}
}
core.ObjectNode.setData = function (xdt,dontUpdate) {
this.data = xdt;
this.__newData = true;
if (!dontUpdate) {
this.__update();
}
}
// sometimes, data needs processing. In this case, the internalized data is put in __idata
//core.ObjectNode.__dataInInternalForm = function () {
core.ObjectNode.getData = function () {
return this.data;
}
export {Style,removeElement,parseWithDOM};
|
harry-wood/chef
|
cookbooks/mysql/libraries/mysql.rb
|
<filename>cookbooks/mysql/libraries/mysql.rb
require "chef/mixin/command"
require "rexml/document"
class Chef
class MySQL
include Chef::Mixin::Command
USER_PRIVILEGES = [
:select, :insert, :update, :delete, :create, :drop, :reload,
:shutdown, :process, :file, :grant, :references, :index, :alter,
:show_db, :super, :create_tmp_table, :lock_tables, :execute,
:repl_slave, :repl_client, :create_view, :show_view, :create_routine,
:alter_routine, :create_user, :event, :trigger, :create_tablespace
].freeze
DATABASE_PRIVILEGES = [
:select, :insert, :update, :delete, :create, :drop, :grant,
:references, :index, :alter, :create_tmp_table, :lock_tables,
:create_view, :show_view, :create_routine, :alter_routine,
:execute, :event, :trigger
].freeze
def execute(options)
# Create argument array
args = []
# Work out how to authenticate
if options[:user]
args.push("--username=#{options[:user]}")
args.push("--password=#{options[:password]}") if options[:password]
else
args.push("--defaults-file=/etc/mysql/debian.cnf")
end
# Build the other arguments
args.push("--execute=\"#{options[:command]}\"") if options[:command]
# Get the database to use
database = options[:database] || "mysql"
# Build the command to run
command = "/usr/bin/mysql #{args.join(' ')} #{database}"
# Escape backticks in the command
command.gsub!(/`/, "\\\\`")
# Run the command
run_command(:command => command, :user => "root", :group => "root")
end
def query(sql, options = {})
# Get the database to use
database = options[:database] || "mysql"
# Construct the command string
command = "/usr/bin/mysql --defaults-file=/etc/mysql/debian.cnf --xml --execute='#{sql}' #{database}"
# Run the query
status, stdout, stderr = output_of_command(command, :user => "root", :group => "root")
handle_command_failures(status, "STDOUT: #{stdout}\nSTDERR: #{stderr}", :output_on_failure => true)
# Parse the output
document = REXML::Document.new(stdout)
# Create
records = []
# Loop over the rows in the result set
document.root.each_element("/resultset/row") do |row|
# Create a record
record = {}
# Loop over the fields, adding them to the record
row.each_element("field") do |field|
name = field.attributes["name"].downcase
value = field.text
record[name.to_sym] = value
end
# Add the record to the record list
records << record
end
# Return the record list
records
end
def users
@users ||= query("SELECT * FROM user").each_with_object({}) do |user, users|
name = "'#{user[:user]}'@'#{user[:host]}'"
users[name] = USER_PRIVILEGES.each_with_object({}) do |privilege, privileges|
privileges[privilege] = user["#{privilege}_priv".to_sym] == "Y"
end
end
end
def databases
@databases ||= query("SHOW databases").each_with_object({}) do |database, databases|
databases[database[:database]] = {
:permissions => {}
}
end
query("SELECT * FROM db").each do |record|
database = @databases[record[:db]]
next unless database
user = "'#{record[:user]}'@'#{record[:host]}'"
database[:permissions][user] = DATABASE_PRIVILEGES.each_with_object([]) do |privilege, privileges|
privileges << privilege if record["#{privilege}_priv".to_sym] == "Y"
end
end
@databases
end
def canonicalise_user(user)
local, host = user.split("@")
host = "%" unless host
local = "'#{local}'" unless local =~ /^'.*'$/
host = "'#{host}'" unless host =~ /^'.*'$/
"#{local}@#{host}"
end
def privilege_name(privilege)
case privilege
when :grant
"GRANT OPTION"
when :create_tmp_table
"CREATE TEMPORARY TABLES"
else
privilege.to_s.upcase.tr("_", " ")
end
end
end
end
|
cy4n/urlaubsverwaltung
|
src/main/java/org/synyx/urlaubsverwaltung/absence/AbsenceService.java
|
<filename>src/main/java/org/synyx/urlaubsverwaltung/absence/AbsenceService.java
package org.synyx.urlaubsverwaltung.absence;
import org.synyx.urlaubsverwaltung.person.Person;
import java.time.LocalDate;
import java.util.List;
public interface AbsenceService {
/**
* Get all open absences for the given person and date range.
* "Open" means it has one of the status ALLOWED, WAITING, TEMPORARY_ALLOWED, ALLOWED_CANCELLATION_REQUESTED
*
* @param person {@link Person} to get the absences for
* @param start start of the date range (inclusive)
* @param end end of the date range (inclusive)
* @return list of all matching absences
*/
List<AbsencePeriod> getOpenAbsences(Person person, LocalDate start, LocalDate end);
/**
* Get all open absences for the given persons and date range.
* "Open" means it has one of the status ALLOWED, WAITING, TEMPORARY_ALLOWED, ALLOWED_CANCELLATION_REQUESTED
*
* @param persons list of {@link Person}s to get the absences for
* @param start start of the date range (inclusive)
* @param end end of the date range (inclusive)
* @return list of all matching absences
*/
List<AbsencePeriod> getOpenAbsences(List<Person> persons, LocalDate start, LocalDate end);
/**
* Get absences from a list of persons
*
* @param persons to get absences for
* @return list of absences for the given person
*/
List<Absence> getOpenAbsencesSince(List<Person> persons, LocalDate since);
/**
* Get all absences with one of the status:
* ALLOWED, WAITING, TEMPORARY_ALLOWED
*
* @param since
* @return list of all open absences
*/
List<Absence> getOpenAbsencesSince(LocalDate since);
}
|
sarang-apps/darshan_browser
|
chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrConsentTestFramework.java
|
<reponame>sarang-apps/darshan_browser<filename>chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrConsentTestFramework.java
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.vr;
import org.chromium.chrome.test.ChromeActivityTestRule;
import org.chromium.content_public.browser.WebContents;
/**
* Extension class of WebXrVrTestFramework that allows explicitly specifying whether or not the
* consent dialog is expected.
*/
public class WebXrVrConsentTestFramework extends WebXrVrTestFramework {
private boolean mConsentDialogExpected = true;
public WebXrVrConsentTestFramework(ChromeActivityTestRule testRule) {
super(testRule);
}
/**
* Sets whether or not the consent dialog is expected to be shown.
*
* @param consentDialogExpected whether or not to expect the consent dialog
*/
public void setConsentDialogExpected(boolean consentDialogExpected) {
mConsentDialogExpected = consentDialogExpected;
}
/**
* Determines whether or not the consent dialog is expected to be shown.
*
* @param webContents The webContents of the tab to check if it expects the consent dialog.
*/
@Override
public boolean shouldExpectConsentDialog(WebContents webContents) {
return mConsentDialogExpected;
}
}
|
mikaelstaldal/caliban
|
core/src/main/scala-2/caliban/GraphQLWSOutputJsonCompat.scala
|
package caliban
import caliban.interop.play.{ IsPlayJsonReads, IsPlayJsonWrites }
import caliban.interop.zio.{ IsZIOJsonDecoder, IsZIOJsonEncoder }
private[caliban] trait GraphQLWSOutputJsonCompat {
implicit def playJsonReads[F[_]: IsPlayJsonReads]: F[GraphQLWSOutput] =
caliban.interop.play.json.GraphQLWSOutputPlayJson.graphQLWSOutputReads.asInstanceOf[F[GraphQLWSOutput]]
implicit def playJsonWrites[F[_]: IsPlayJsonWrites]: F[GraphQLWSOutput] =
caliban.interop.play.json.GraphQLWSOutputPlayJson.graphQLWSOutputWrites.asInstanceOf[F[GraphQLWSOutput]]
implicit def zioJsonDecoder[F[_]: IsZIOJsonDecoder]: F[GraphQLWSOutput] =
caliban.interop.zio.GraphQLWSOutputZioJson.graphQLWSOutputDecoder.asInstanceOf[F[GraphQLWSOutput]]
implicit def zioJsonEncoder[F[_]: IsZIOJsonEncoder]: F[GraphQLWSOutput] =
caliban.interop.zio.GraphQLWSOutputZioJson.graphQLWSOutputEncoder.asInstanceOf[F[GraphQLWSOutput]]
}
|
Mike-Leo-Smith/LuisaCompute
|
src/backends/cuda/cuda_ring_buffer.h
|
<reponame>Mike-Leo-Smith/LuisaCompute
//
// Created by Mike on 8/1/2021.
//
#pragma once
#include <span>
#include <cuda.h>
#include <core/spin_mutex.h>
#include <core/mathematics.h>
#include <backends/cuda/cuda_error.h>
namespace luisa::compute::cuda {
class CUDARingBuffer {
public:
static constexpr auto alignment = static_cast<size_t>(16u);
private:
std::byte *_memory{nullptr};
size_t _size;
size_t _free_begin;
size_t _free_end;
uint _alloc_count;
spin_mutex _mutex;
bool _write_combined;
public:
CUDARingBuffer(size_t size, bool write_combined) noexcept;
~CUDARingBuffer() noexcept;
[[nodiscard]] std::span<std::byte> allocate(size_t size) noexcept;
void recycle(std::span<std::byte> buffer) noexcept;
};
}// namespace luisa::compute::cuda
|
neerajp99/evnt
|
speaker/client/src/components/talk/styles/talk.js
|
import styled from "styled-components";
export const TalkHeading = styled.h1`
font-size: calc(1.1em + 1.3vw);
position: relative;
top: -14%;
text-align: left;
font-family: Lato;
font-weight: 400;
color: #22343b;
@media (max-width: 1100px) {
top: -8vh !important;
}
@media (max-width: 768px) {
top: -8vh !important;
font-size: 2rem;
}
`;
export const TalkContainer = styled.div`
/* height: 80vh; */
${'' /* min-height: 100%; */}
height: auto;
width: 90%;
margin: 0 auto;
/* background: #fff; */
margin-top: 10%;
/* padding-bottom: 10%; */
/* border-radius: 12px; */
margin-bottom: 5%;
@media (max-width: 1200px) {
margin-top: 15% !important;
}
@media (max-width: 768px) {
margin-top: 15% !important;
}
`;
export const Container = styled.div`
width: 100%;
margin-top: 0.8rem;
`;
export const Input = styled.input`
width: 85%;
height: 50px;
border-radius: 3px;
border: 1px solid #55636b40;
padding-left: 15px;
font-size: 15px;
font-family: Lato;
::placeholder,
::-webkit-input-placeholder {
color: #5b6a84;
}
:-ms-input-placeholder {
color: #5b6a84;
}
&:focus {
border: 1px solid #4ca1ff;
}
color: #3a414a;
`;
export const Label = styled.h4`
width: 86%;
margin: 0 auto;
text-align: left;
text-transform: uppercase;
margin-bottom: 1.5vh;
color: #384e5e;
font-family: Lato;
font-size: 15px;
margin-top: 5%;
`;
export const FormGroup = styled.div`
color: palevioletred;
display: block;
margin: 0 auto;
justify-content: center;
text-align: center;
/* width: 95%; */
margin-top: -10%;
padding-top: 1%;
padding-bottom: 3%;
background: #fff;
border-radius: 12px;
margin-bottom: 7%;
`;
export const TextArea = styled.textarea`
width: 84%;
height: 20vh;
margin: 0 auto;
/* margin-top: 5%; */
resize: none;
border-radius: 3px;
border: 1px solid #55636b40;
padding-left: 15px;
font-size: 15px;
::placeholder,
::-webkit-input-placeholder {
color: #5b6a84;
}
:-ms-input-placeholder {
color: #5b6a84;
}
&:focus {
border: 1px solid #4ca1ff;
}
color: #3a414a;
font-family: Lato;
font-size: 15px;
padding-top: 15px;
padding-bottom: 15px;
padding-right: 15px;
`;
export const LabelBottom = styled.h5`
font-size: 16px;
margin-top: 0.2%;
text-align: left;
position: relative;
left: 89%;
font-weight: 400;
color: ${props => (props.length === props.limit ? "#af2c56" : "#4ca1ff")};
@media (max-width: 1200px) {
left: 86%;
}
@media (max-width: 768px) {
left: 83%;
}
`;
export const TalkSubmitButton = styled.div`
height: 60px;
background: #4ca1ff;
color: #fff;
/* margin-bottom: 10%; */
width: 88%;
margin: 0 auto;
border-radius: 6px;
line-height: 60px;
font-weight: 600;
font-family: Lato;
font-size: 1.1rem;
text-transform: uppercase;
margin: 0 auto;
margin-top: 5%;
margin-bottom: 5%;
// margin-left: 4%;
transition: 0.3s all ease-in-out;
-webkit-transition: 0.3s all ease-in-out;
-moz-transition: 0.3s all ease-in-out;
cursor: pointer;
&:hover {
transition: 0.3s all ease-in-out;
-webkit-transition: 0.3s all ease-in-out;
-moz-transition: 0.3s all ease-in-out;
transform: translateY(-4px);
}
@media (max-width: 768px) {
width: 92%;
}
`;
export const NullInfo = styled.h3`
font-family: "Lato";
font-size: 25px;
font-weight: 400;
color: #ffffff;
background: #4ca1ff;
height: 50%;
border-radius: 14px;
padding: 20px;
text-align: center;
align-items: center;
justify-content: center;
display: flex;
`;
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/DeviceManagement/DMFRequestAirPlayMirroringResultObject.h
|
<gh_stars>10-100
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "CATTaskResultObject.h"
@interface DMFRequestAirPlayMirroringResultObject : CATTaskResultObject
{
unsigned long long _status;
}
+ (BOOL)supportsSecureCoding;
@property(readonly, nonatomic) unsigned long long status; // @synthesize status=_status;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)initWithStatus:(unsigned long long)arg1;
@end
|
VanirLab/vanir-gui-agent-linux
|
pulse/pulsecore-12.0/cpu-arm.h
|
<filename>pulse/pulsecore-12.0/cpu-arm.h
#ifndef foocpuarmhfoo
#define foocpuarmhfoo
/***
This file is part of PulseAudio.
Copyright 2004-2006 <NAME>
Copyright 2009 <NAME> <<EMAIL>>
PulseAudio is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License,
or (at your option) any later version.
PulseAudio 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 Lesser General Public License
along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
***/
#include <stdint.h>
#include <pulsecore/macro.h>
#ifndef PACKAGE
#error "Please include config.h before including this file!"
#endif
typedef enum pa_cpu_arm_flag {
PA_CPU_ARM_V6 = (1 << 0),
PA_CPU_ARM_V7 = (1 << 1),
PA_CPU_ARM_VFP = (1 << 2),
PA_CPU_ARM_EDSP = (1 << 3),
PA_CPU_ARM_NEON = (1 << 4),
PA_CPU_ARM_VFPV3 = (1 << 5),
PA_CPU_ARM_CORTEX_A8 = (1 << 6),
} pa_cpu_arm_flag_t;
void pa_cpu_get_arm_flags(pa_cpu_arm_flag_t *flags);
bool pa_cpu_init_arm(pa_cpu_arm_flag_t *flags);
/* some optimized functions */
void pa_volume_func_init_arm(pa_cpu_arm_flag_t flags);
#ifdef HAVE_NEON
void pa_convert_func_init_neon(pa_cpu_arm_flag_t flags);
void pa_mix_func_init_neon(pa_cpu_arm_flag_t flags);
void pa_remap_func_init_neon(pa_cpu_arm_flag_t flags);
#endif
#endif /* foocpuarmhfoo */
|
cap-lab/MidapSim
|
midap_software/fmem_info.py
|
from collections import deque
from copy import copy
from acc_utils.errors import CompilerError
from config import cfg
class Snapshot(object):
def __init__(self):
self._reserved_banks = None
self._available_queue = None
self._mapping_info = None
def backup(self, fmem_info):
self._reserved_banks = copy(fmem_info._reserved_banks)
self._available_queue = copy(fmem_info._available_queue)
self._mapping_info = copy(fmem_info._mapping_info)
def restore(self, fmem_info):
fmem_info._reserved_banks = copy(self._reserved_banks)
fmem_info._available_queue = copy(self._available_queue)
fmem_info._mapping_info = copy(self._mapping_info)
class FMEMInfo(object):
def __init__(self):
self._reserved_banks = set([])
self._available_queue = deque([i for i in range(cfg.MIDAP.FMEM.NUM)])
self._mapping_info = []
self._snapshot = Snapshot()
def backup(self):
self._snapshot.backup(self)
def restore(self):
self._snapshot.restore(self)
def discard_data_by_layer(self, name, reverse_order=False):
discard_list = []
for idx, data in enumerate(self._mapping_info):
n = data[0]
if n == name:
discard_list.append(idx)
# discard the data in the order used by CIMs. (available_queue)
for idx in (reversed(discard_list) if reverse_order else discard_list):
_, bank, _ = self._mapping_info[idx]
if reverse_order:
self._available_queue.appendleft(bank)
else:
self._available_queue.append(bank)
self._reserved_banks.discard(bank)
for idx in reversed(discard_list):
del self._mapping_info[idx]
def discard_data(self, bank):
discard_idx = -1
for idx, data in enumerate(self._mapping_info):
b = data[1]
if b == bank:
discard_idx = idx
break
if bank not in self._reserved_banks:
self._available_queue.append(bank)
del self._mapping_info[discard_idx]
def _pop_available_bank(self):
if not self._available_queue:
return None
bank = self._available_queue.popleft()
return bank
def get_num_available_bank(self):
return len(self._available_queue)
def get_num_unreserved_bank(self):
return cfg.MIDAP.FMEM.NUM - len(self._reserved_banks)
def save_data_to_empty_bank(self, layer, data):
name = layer.name
# FIXME check that data is already in fmem.
for n, b, d in self._mapping_info:
if name == n and d == data:
return None
bank = self._pop_available_bank()
if bank is not None:
self._save_data(name, bank, data)
return bank
def _save_data(self, name, bank, data):
self._mapping_info.append((name, bank, data))
if len(self._mapping_info) > cfg.MIDAP.FMEM.NUM:
raise CompilerError("Use more banks than exists: " + str(self._mapping_info) + self.__repr__())
def reverse_mapping(self, name):
mapping_list = []
discard_list = []
for idx, data in enumerate(self._mapping_info):
n = data[0] if data else None
if n == name:
mapping_list.append(data)
discard_list.append(idx)
for idx in reversed(discard_list):
del self._mapping_info[idx]
self._mapping_info = self._mapping_info + list(reversed(mapping_list))
def reserve_input_banks(self, mapping, input_stationary):
if mapping and input_stationary >= 0:
banks = [v[0] for v in mapping[:input_stationary]]
self._reserved_banks = set(banks)
def reserve_output_banks(self, next_layer, output_stationary):
# FIXME
# set output bank once per path(or branch)
for data in self._mapping_info:
n = data[0] if data else None
if n == next_layer.name:
return
fragments = next_layer.get_output_fragments(cfg.MIDAP.FMEM.NUM - 1)
for f in fragments[:output_stationary]:
bank = self.save_data_to_empty_bank(next_layer, f)
if bank is None:
raise CompilerError("There is no bank to save output of " + next_layer.name + " " + self.__repr__())
self._reserved_banks.add(bank)
def get_fmem_mapping_info(self, name):
mapping = []
for data in self._mapping_info:
n = data[0] if data else None
if n == name:
mapping.append([data[1], data[2], False])
return mapping
def __repr__(self):
usage = ['O'] * cfg.MIDAP.FMEM.NUM
for data in self._mapping_info:
usage[data[1]] = data[0]
return "FMEM Available Bank {}".format(usage)
|
cquoss/jboss-4.2.3.GA-jdk8
|
messaging/src/main/org/jboss/mq/il/oil/OILClientILService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.mq.il.oil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.RemoteException;
import org.jboss.mq.Connection;
import org.jboss.mq.ReceiveRequest;
import org.jboss.mq.SpyDestination;
/**
* The RMI implementation of the ConnectionReceiver object
*
* @author <NAME> (<EMAIL>)
* @author <NAME> (<EMAIL>)
* @version $Revision: 57198 $
* @created August 16, 2001
*/
public final class OILClientILService
implements java.lang.Runnable,
org.jboss.mq.il.ClientILService
{
private final static org.jboss.logging.Logger cat = org.jboss.logging.Logger.getLogger(OILClientILService.class);
//the client IL
private OILClientIL clientIL;
//The thread that is doing the Socket reading work
private Thread worker;
// the connected client
private Socket socket = null;
//A link on my connection
private Connection connection;
//Should this service be running ?
private boolean running;
//The server socket we listen for a connection on
private ServerSocket serverSocket;
/**
* Number of OIL Worker threads started.
*/
private static int threadNumber= 0;
/**
* If the TcpNoDelay option should be used on the socket.
*/
private boolean enableTcpNoDelay=false;
/**
* getClientIL method comment.
*
* @return The ClientIL value
* @exception java.lang.Exception Description of Exception
*/
public org.jboss.mq.il.ClientIL getClientIL()
throws java.lang.Exception
{
return clientIL;
}
/**
* init method comment.
*
* @param connection Description of Parameter
* @param props Description of Parameter
* @exception java.lang.Exception Description of Exception
*/
public void init(org.jboss.mq.Connection connection, java.util.Properties props)
throws java.lang.Exception
{
this.connection = connection;
serverSocket = new ServerSocket(0);
String t = props.getProperty(OILServerILFactory.OIL_TCPNODELAY_KEY);
if (t != null)
enableTcpNoDelay = t.equals("yes");
clientIL = new OILClientIL(java.net.InetAddress.getLocalHost(), serverSocket.getLocalPort(), enableTcpNoDelay);
}
/**
* Main processing method for the OILClientILService object
*/
public void run()
{
int code = 0;
ObjectOutputStream out = null;
ObjectInputStream in = null;
socket = null;
int serverPort = serverSocket.getLocalPort();
try
{
if( cat.isDebugEnabled() )
cat.debug("Waiting for the server to connect to me on port " +serverSocket.getLocalPort());
// We may close() before we get a connection so we need to
// periodicaly check to see if we were !running.
//
serverSocket.setSoTimeout(1000);
while (running && socket == null)
{
try
{
socket = serverSocket.accept();
}
catch (java.io.InterruptedIOException e)
{
// do nothing, running flag will be checked
continue;
}
catch (IOException e)
{
if (running)
connection.asynchFailure("Error accepting connection from server in OILClientILService.", e);
return; // finally block will clean up!
}
}
if(running)
{
socket.setTcpNoDelay(enableTcpNoDelay);
socket.setSoTimeout(0);
out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
out.flush();
in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
}
else
{
// not running so exit
// let the finally block do the clean up
//
return;
}
}
catch (IOException e)
{
connection.asynchFailure("Could not initialize the OILClientIL Service.", e);
return;
}
finally
{
try
{
serverSocket.close();
serverSocket = null;
}
catch (IOException e)
{
if(cat.isDebugEnabled())
cat.debug("run: an error occured closing the server socket", e);
}
}
// now process request from the client.
//
while (running)
{
try
{
code = in.readByte();
}
catch (java.io.InterruptedIOException e)
{
continue;
}
catch (IOException e)
{
// Server has gone, bye, bye
break;
}
try
{
switch (code)
{
case OILConstants.RECEIVE:
int numReceives = in.readInt();
org.jboss.mq.ReceiveRequest[] messages = new org.jboss.mq.ReceiveRequest[numReceives];
for (int i = 0; i < numReceives; ++i)
{
messages[i] = new ReceiveRequest();
messages[i].readExternal(in);
}
connection.asynchDeliver(messages);
break;
case OILConstants.DELETE_TEMPORARY_DESTINATION:
connection.asynchDeleteTemporaryDestination((SpyDestination)in.readObject());
break;
case OILConstants.CLOSE:
connection.asynchClose();
break;
case OILConstants.PONG:
connection.asynchPong(in.readLong());
break;
default:
throw new RemoteException("Bad method code !");
}
//Everthing was OK
//
try
{
out.writeByte(OILConstants.SUCCESS);
out.flush();
}
catch (IOException e)
{
connection.asynchFailure("Connection failure(1)", e);
break; // exit the loop
}
}
catch (Exception e)
{
if (!running)
{
// if not running then don't bother to log an error
//
break;
}
try
{
cat.error("Exception handling server request", e);
out.writeByte(OILConstants.EXCEPTION);
out.writeObject(e);
out.reset();
out.flush();
}
catch (IOException e2)
{
connection.asynchFailure("Connection failure(2)", e2);
break;
}
}
} // end while
// exited loop, so clean up the conection
//
try
{
cat.debug("Closing receiver connections on port: " + serverPort);
out.close();
in.close();
socket.close();
socket = null;
}
catch (IOException e)
{
connection.asynchFailure("Connection failure", e);
}
// ensure the flag is set correctly
//
running = false;
}
/**
* start method comment.
*
* @exception java.lang.Exception Description of Exception
*/
public void start()
throws java.lang.Exception
{
running = true;
worker = new Thread(Connection.getThreadGroup(), this, "OILClientILService-" +threadNumber++);
worker.setDaemon(true);
worker.start();
}
/**
* @exception java.lang.Exception Description of Exception
*/
public void stop()
throws java.lang.Exception
{
cat.trace("Stop called on OILClientService");
running = false;
worker.interrupt();
}
}
// vim:expandtab:tabstop=3:shiftwidth=3
|
KiriBogach/sql-jpql-compiler
|
source/ZqlParserDemo/src/org/gibello/zql/ZOrderBy.java
|
<reponame>KiriBogach/sql-jpql-compiler<filename>source/ZqlParserDemo/src/org/gibello/zql/ZOrderBy.java
/*
* This file is part of Zql.
*
* Zql 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.
*
* Zql 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 Zql. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gibello.zql;
/**
* An SQL query ORDER BY clause.
*/
public class ZOrderBy implements java.io.Serializable {
boolean asc_ = true;
ZExp exp_;
public ZOrderBy(ZExp e) {
exp_ = e;
}
/**
* Get the order (ascending or descending)
*
* @return true if ascending order, false if descending order.
*/
public boolean getAscOrder() {
return asc_;
}
/**
* Get the ORDER BY expression.
*
* @return An expression (generally, a ZConstant that represents a column name).
*/
public ZExp getExpression() {
return exp_;
}
/**
* Set the order to ascending or descending (defailt is ascending order).
*
* @param a true for ascending order, false for descending order.
*/
public void setAscOrder(boolean a) {
asc_ = a;
}
public String toString() {
return exp_.toString() + " " + (asc_ ? "ASC" : "DESC");
}
};
|
nbtdev/teardrop
|
tech/Physics/HeightfieldShape.cpp
|
<reponame>nbtdev/teardrop<filename>tech/Physics/HeightfieldShape.cpp
/******************************************************************************
Copyright (c) 2015 Teardrop Games
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
******************************************************************************/
#include "stdafx.h"
#include "HeightfieldShape.h"
#include "Util/Environment.h"
#include "Util/Logger.h"
#include "Memory/Allocators.h"
using namespace CoS;
//---------------------------------------------------------------------------
HeightfieldShape::HeightfieldShape()
{
m_pData = 0;
}
//---------------------------------------------------------------------------
HeightfieldShape::~HeightfieldShape()
{
}
//---------------------------------------------------------------------------
bool HeightfieldShape::initialize(
void* pData, // this object makes a copy of this data
size_t width,
size_t height,
size_t bpp, // bytes/pixel, i.e. 8-bit greyscale = 1 byte/pixel
const Vector4& scale // world scaling terms (x, y, z)
)
{
if (!pData)
{
return false;
}
size_t bufSize = width * height * bpp;
m_pData = COS_ALLOCATE_ALIGNED(DEFAULT, bufSize, 16);
memcpy(m_pData, pData, bufSize);
m_width = width;
m_height = height;
m_bpp = bpp;
m_scale = scale;
return true;
}
//---------------------------------------------------------------------------
bool HeightfieldShape::destroy()
{
if (m_pData)
{
COS_DEALLOCATE(DEFAULT, m_pData);
m_pData = 0;
}
return true;
}
//---------------------------------------------------------------------------
bool HeightfieldShape::update(float deltaT)
{
return true;
}
|
Playtika/nosql-batch-updater
|
batch-updater/src/test/java/nosql/batch/update/RecoveryTest.java
|
<gh_stars>1-10
package nosql.batch.update;
import nosql.batch.update.wal.CompletionStatistic;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Predicate;
import static nosql.batch.update.util.HangingUtil.hanged;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.awaitility.Duration.FIVE_MINUTES;
/**
* Check that hanged batch get recovered by WriteAheadLogCompleter
*/
abstract public class RecoveryTest {
protected abstract void cleanUp() throws InterruptedException;
protected abstract void runUpdate();
protected abstract CompletionStatistic runCompleter();
protected abstract void checkForConsistency();
protected static final AtomicBoolean hangsAcquire = new AtomicBoolean();
protected static final AtomicBoolean hangsUpdate = new AtomicBoolean();
protected static final AtomicBoolean hangsRelease = new AtomicBoolean();
protected static final AtomicBoolean hangsDeleteBatchInWal = new AtomicBoolean();
@Test
public void shouldBecameConsistentAfterAcquireLockHanged() throws InterruptedException {
shouldBecameConsistentAfterHangAndCompletion(
() -> hangsAcquire.set(true),
completionStatisticAssertion(1, 1, 0));
}
@Test
public void shouldBecameConsistentAfterMutateHanged() throws InterruptedException {
shouldBecameConsistentAfterHangAndCompletion(
() -> hangsUpdate.set(true),
completionStatisticAssertion(1, 1, 0));
}
@Test
public void shouldBecameConsistentAfterReleaseLockHanged() throws InterruptedException {
shouldBecameConsistentAfterHangAndCompletion(
() -> hangsRelease.set(true),
completionStatisticAssertion(1));
}
@Test
public void shouldBecameConsistentAfterDeleteTransactionHanged() throws InterruptedException {
shouldBecameConsistentAfterHangAndCompletion(
() -> hangsDeleteBatchInWal.set(true),
completionStatisticAssertion(
staleBatchesFound -> staleBatchesFound >= 1,
staleBatchesComplete -> staleBatchesComplete == 0,
staleBatchesIgnored -> staleBatchesIgnored >= 1));
}
protected void shouldBecameConsistentAfterHangAndCompletion(
Runnable breaker, Consumer<CompletionStatistic> completionStatisticAssertion) throws InterruptedException {
for(int i = 0; i < 10; i++) {
cleanUp();
fixAll();
breaker.run();
new Thread(this::runUpdate).start();
await().dontCatchUncaughtExceptions()
.timeout(FIVE_MINUTES)
.until(hanged::get);
fixAll();
CompletionStatistic completionStat = runCompleter();
completionStatisticAssertion.accept(completionStat);
//check state. It should be fixed at this time
checkForConsistency();
//check normal update is possible
runUpdate();
checkForConsistency();
}
}
protected void fixAll() {
hangsAcquire.set(false);
hangsUpdate.set(false);
hangsRelease.set(false);
hangsDeleteBatchInWal.set(false);
hanged.set(false);
}
static Consumer<CompletionStatistic> completionStatisticAssertion(
int staleBatchesFound, int staleBatchesComplete, int staleBatchesIgnored){
return completionStatistic -> {
assertThat(completionStatistic.staleBatchesFound).isEqualTo(staleBatchesFound);
assertThat(completionStatistic.staleBatchesComplete).isEqualTo(staleBatchesComplete);
assertThat(completionStatistic.staleBatchesIgnored).isEqualTo(staleBatchesIgnored);
};
}
static Consumer<CompletionStatistic> completionStatisticAssertion(
Predicate<Integer> staleBatchesFound, Predicate<Integer> staleBatchesComplete, Predicate<Integer> staleBatchesIgnored){
return completionStatistic -> {
assertThat(completionStatistic.staleBatchesFound).matches(staleBatchesFound);
assertThat(completionStatistic.staleBatchesComplete).matches(staleBatchesComplete);
assertThat(completionStatistic.staleBatchesIgnored).matches(staleBatchesIgnored);
};
}
static Consumer<CompletionStatistic> completionStatisticAssertion(int staleBatchesFound){
return completionStatistic ->
assertThat(completionStatistic.staleBatchesFound).isEqualTo(staleBatchesFound);
}
}
|
alfonsserra/java-pdf-generator
|
src/main/java/com/werfen/report/model/GridReportDataSource.java
|
package com.werfen.report.model;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.data.JRAbstractBeanDataSource;
import java.util.Iterator;
import java.util.Optional;
public class GridReportDataSource extends JRAbstractBeanDataSource {
private final GridPageDataSource dataSource;
private Iterator<GridReportRow> currentPageRowIterator;
private GridReportRow currentRow;
public GridReportDataSource(GridPageDataSource dataSource) {
super(true);
this.dataSource = dataSource;
this.moveFirst();
}
@Override
public void moveFirst() {
this.dataSource.moveFirst();
this.currentPageRowIterator = this.dataSource.getCurrentPageRows().listIterator();
}
@Override
public boolean next() {
if (this.currentPageRowIterator.hasNext()) {
this.currentRow = this.currentPageRowIterator.next();
return true;
} else if (this.dataSource.nextPage()) {
this.currentPageRowIterator = this.dataSource.getCurrentPageRows().listIterator();
this.currentRow = this.currentPageRowIterator.next();
return true;
} else {
return false;
}
}
@Override
public Object getFieldValue(JRField jrField) {
String name = jrField.getName();
Optional<GridReportField> currentReportField = this.currentRow.getValues().stream().filter(reportField -> name.equals(reportField.getName())).findFirst();
return currentReportField.orElseThrow(() -> new RuntimeException("The field name '" + name + "' in the Jasper Report is not valid")).getValue();
}
}
|
james-s-willis/kotekan
|
lib/hsa/hsaInputData.hpp
|
#ifndef HSA_INPUT_DATA_H
#define HSA_INPUT_DATA_H
#include "hsaCommand.hpp"
class hsaInputData : public hsaCommand {
public:
hsaInputData(kotekan::Config& config, const string& unique_name,
kotekan::bufferContainer& host_buffers, hsaDeviceInterface& device);
virtual ~hsaInputData();
int wait_on_precondition(int gpu_frame_id) override;
hsa_signal_t execute(int gpu_frame_id, hsa_signal_t precede_signal) override;
void finalize_frame(int frame_id) override;
private:
int32_t network_buffer_id;
int32_t network_buffer_precondition_id;
int32_t network_buffer_finalize_id;
Buffer* network_buf;
int32_t input_frame_len;
// TODO maybe factor these into a CHIME command object class?
int32_t _num_local_freq;
int32_t _num_elements;
int32_t _samples_per_data_set;
float _delay_max_fraction;
// Random delay in seconds
double _random_delay;
// Apply a random delay to spread out the power load if set to true.
bool _enable_delay;
const double _sample_arrival_rate = 390625.0;
};
#endif
|
peacetrue/log
|
peacetrue-log-aspect/src/main/java/com/github/peacetrue/log/aspect/DefaultLogAspectService.java
|
<filename>peacetrue-log-aspect/src/main/java/com/github/peacetrue/log/aspect/DefaultLogAspectService.java
package com.github.peacetrue.log.aspect;
import com.github.peacetrue.aspect.AfterParams;
import com.github.peacetrue.aspect.supports.DurationAroundInterceptor;
import com.github.peacetrue.log.aspect.config.LogPointcutInfoProvider;
import com.github.peacetrue.log.service.LogAddDTO;
import com.github.peacetrue.log.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.scheduling.annotation.Async;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* @author xiayx
*/
public class DefaultLogAspectService implements LogAspectService, BeanFactoryAware {
private static final DefaultParameterNameDiscoverer DEFAULT_PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer();
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private LogService logService;
@Autowired
private LogBuilder logBuilder;
@Autowired
private LogPointcutInfoProvider logPointcutInfoProvider;
private BeanFactoryResolver beanFactoryResolver;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactoryResolver = new BeanFactoryResolver(beanFactory);
}
@Override
@SuppressWarnings("unchecked")
@Async(AspectLogAutoConfiguration.LOG_TASK_EXECUTOR_NAME)
public void addLog(AfterParams<Long> afterParams) {
ProceedingJoinPoint joinPoint = afterParams.getAroundParams().getProceedingJoinPoint();
LogPointcutInfo logPointcutInfo = this.getLogPointcutInfo(afterParams);
logger.debug("取得日志切面信息[{}]", logPointcutInfo);
if (logPointcutInfo == null) {
throw new IllegalStateException(String.format("未找到与切点[%s]匹配的日志切面信息", joinPoint.getSignature().toShortString()));
}
LogEvaluationContext evaluationContext = this.buildEvaluationContext(joinPoint, afterParams.getReturnValue());
logger.debug("创建日志表达式取值上下文[{}]", evaluationContext);
LogAddDTO log = logBuilder.build(logPointcutInfo, evaluationContext);
log.setDuration(DurationAroundInterceptor.getDuration(Objects.requireNonNull(afterParams.getData())));
log.setInput(joinPoint.getArgs());
log.setOutput(afterParams.getReturnValue());
log.setException(afterParams.getThrowable());
logger.debug("取得日志信息[{}]", log);
logService.add(log);
}
protected LogPointcutInfo getLogPointcutInfo(AfterParams<Long> afterParams) {
if (afterParams.getAroundParams() instanceof LogAroundParams) {
return ((LogAroundParams) afterParams.getAroundParams()).getLogPointcutInfo();
}
ProceedingJoinPoint joinPoint = afterParams.getAroundParams().getProceedingJoinPoint();
LogPointcut logPointcut = getMethod(joinPoint).getAnnotation(LogPointcut.class);
if (logPointcut != null) {
return LogPointcutInfo.fromLogPointcut(logPointcut);
} else {
return logPointcutInfoProvider.findLogPointcutInfo(joinPoint);
}
}
protected LogEvaluationContext buildEvaluationContext(ProceedingJoinPoint joinPoint, @Nullable Object returnValue) {
LogEvaluationContext evaluationContext = new LogEvaluationContext(
joinPoint.getTarget(), getMethod(joinPoint), joinPoint.getArgs(),
DEFAULT_PARAMETER_NAME_DISCOVERER,
returnValue
);
evaluationContext.setVariable("returning", returnValue);
evaluationContext.setBeanResolver(beanFactoryResolver);
return evaluationContext;
}
private static Method getMethod(JoinPoint joinPoint) {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
if (!method.getDeclaringClass().isInterface()) return method;
try {
return joinPoint.getTarget().getClass().getDeclaredMethod(method.getName(), method.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new IllegalStateException(String.format("未能找到切点[%s]对应的方法", joinPoint.getSignature().toShortString()), e);
}
}
}
|
yangge0301/jfinalshop-b2b2c
|
src/main/java/com/jfinalshop/controller/member/ReviewController.java
|
package com.jfinalshop.controller.member;
import java.util.ArrayList;
import java.util.List;
import net.hasor.core.Inject;
import com.jfinal.aop.Before;
import com.jfinal.core.ActionKey;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.jfinalshop.Pageable;
import com.jfinalshop.Results;
import com.jfinalshop.interceptor.MobileInterceptor;
import com.jfinalshop.model.Member;
import com.jfinalshop.model.Product;
import com.jfinalshop.model.Review;
import com.jfinalshop.model.Store;
import com.jfinalshop.service.MemberService;
import com.jfinalshop.service.ReviewService;
import com.xiaoleilu.hutool.util.CollectionUtil;
/**
* Controller - 评论
*
*/
@ControllerBind(controllerKey = "/member/review")
public class ReviewController extends BaseController {
/**
* 每页记录数
*/
private static final int PAGE_SIZE = 10;
@Inject
private ReviewService reviewService;
@Inject
private MemberService memberService;
/**
* 列表
*/
@Before(MobileInterceptor.class)
public void list() {
Integer pageNumber = getParaToInt("pageNumber");
Member currentUser = memberService.getCurrentUser();
Pageable pageable = new Pageable(pageNumber, PAGE_SIZE);
setAttr("pageable", pageable);
setAttr("page", reviewService.findPage(currentUser, null, null, null, null, pageable));
render("/member/review/list.ftl");
}
/**
* 列表
*/
@ActionKey("/member/review/m_list")
public void mList() {
Integer pageNumber = getParaToInt("pageNumber", 1);
Member currentUser = memberService.getCurrentUser();
Pageable pageable = new Pageable(pageNumber, PAGE_SIZE);
Page<Review> pages = reviewService.findPage(currentUser, null, null, null, null, pageable);
List<Review> reviews = new ArrayList<Review>();
if (CollectionUtil.isNotEmpty(pages.getList())) {
for (Review review : pages.getList()) {
Product product = review.getProduct();
product.put("type", product.getTypeName());
product.put("thumbnail", product.getThumbnail());
Store store = product.getStore();
store.put("type", store.getTypeName());
product.put("store", store);
product.put("defaultSku", product.getDefaultSku());
product.put("path", product.getPath());
review.put("product", product);
reviews.add(review);
}
}
renderJson(reviews);
}
/**
* 删除
*/
public void delete() {
Long id = getParaToLong("id");
Member currentUser = memberService.getCurrentUser();
if (id == null) {
Results.notFound(getResponse(), Results.DEFAULT_NOT_FOUND_MESSAGE);
return;
}
Review review = reviewService.find(id);
if (review == null || !currentUser.equals(review.getMember())) {
Results.unprocessableEntity(getResponse(), Results.DEFAULT_UNPROCESSABLE_ENTITY_MESSAGE);
return;
}
reviewService.delete(review);
renderJson(Results.OK);
}
}
|
ZorTsou/orc
|
java/tools/src/java/org/apache/orc/tools/PrintVersion.java
|
/*
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.orc.tools;
import org.apache.hadoop.conf.Configuration;
import java.io.IOException;
import java.util.Properties;
/**
* Print the version of this ORC tool.
*/
public class PrintVersion {
public static final String UNKNOWN = "UNKNOWN";
public static final String FILE_NAME = "META-INF/maven/org.apache.orc/orc-tools/pom.properties";
static void main(Configuration conf, String[] args) throws IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try (java.io.InputStream resourceStream = classLoader.getResourceAsStream(FILE_NAME)) {
if (resourceStream == null) {
throw new IOException("Could not find " + FILE_NAME);
}
Properties props = new Properties();
props.load(resourceStream);
System.out.println("ORC " + props.getProperty("version", UNKNOWN));
}
}
}
|
dmgerman/gerrit
|
java/com/google/gerrit/sshd/SshPluginStarterCallback.java
|
<reponame>dmgerman/gerrit
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|// Copyright (C) 2012 The Android Open Source Project
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Licensed under the Apache License, Version 2.0 (the "License");
end_comment
begin_comment
comment|// you may not use this file except in compliance with the License.
end_comment
begin_comment
comment|// You may obtain a copy of the License at
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// http://www.apache.org/licenses/LICENSE-2.0
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Unless required by applicable law or agreed to in writing, software
end_comment
begin_comment
comment|// distributed under the License is distributed on an "AS IS" BASIS,
end_comment
begin_comment
comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
end_comment
begin_comment
comment|// See the License for the specific language governing permissions and
end_comment
begin_comment
comment|// limitations under the License.
end_comment
begin_package
DECL|package|com.google.gerrit.sshd
package|package
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|sshd
package|;
end_package
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|flogger
operator|.
name|FluentLogger
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|extensions
operator|.
name|registration
operator|.
name|DynamicMap
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|DynamicOptions
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|plugins
operator|.
name|Plugin
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|plugins
operator|.
name|ReloadPluginListener
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|plugins
operator|.
name|StartPluginListener
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|inject
operator|.
name|Inject
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|inject
operator|.
name|Key
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|inject
operator|.
name|Provider
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|inject
operator|.
name|Singleton
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|sshd
operator|.
name|server
operator|.
name|command
operator|.
name|Command
import|;
end_import
begin_class
annotation|@
name|Singleton
DECL|class|SshPluginStarterCallback
class|class
name|SshPluginStarterCallback
implements|implements
name|StartPluginListener
implements|,
name|ReloadPluginListener
block|{
DECL|field|logger
specifier|private
specifier|static
specifier|final
name|FluentLogger
name|logger
init|=
name|FluentLogger
operator|.
name|forEnclosingClass
argument_list|()
decl_stmt|;
DECL|field|root
specifier|private
specifier|final
name|DispatchCommandProvider
name|root
decl_stmt|;
DECL|field|dynamicBeans
specifier|private
specifier|final
name|DynamicMap
argument_list|<
name|DynamicOptions
operator|.
name|DynamicBean
argument_list|>
name|dynamicBeans
decl_stmt|;
annotation|@
name|Inject
DECL|method|SshPluginStarterCallback ( @ommandNameCommands.ROOT) DispatchCommandProvider root, DynamicMap<DynamicOptions.DynamicBean> dynamicBeans)
name|SshPluginStarterCallback
parameter_list|(
annotation|@
name|CommandName
argument_list|(
name|Commands
operator|.
name|ROOT
argument_list|)
name|DispatchCommandProvider
name|root
parameter_list|,
name|DynamicMap
argument_list|<
name|DynamicOptions
operator|.
name|DynamicBean
argument_list|>
name|dynamicBeans
parameter_list|)
block|{
name|this
operator|.
name|root
operator|=
name|root
expr_stmt|;
name|this
operator|.
name|dynamicBeans
operator|=
name|dynamicBeans
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|onStartPlugin (Plugin plugin)
specifier|public
name|void
name|onStartPlugin
parameter_list|(
name|Plugin
name|plugin
parameter_list|)
block|{
name|Provider
argument_list|<
name|Command
argument_list|>
name|cmd
init|=
name|load
argument_list|(
name|plugin
argument_list|)
decl_stmt|;
if|if
condition|(
name|cmd
operator|!=
literal|null
condition|)
block|{
name|plugin
operator|.
name|add
argument_list|(
name|root
operator|.
name|register
argument_list|(
name|Commands
operator|.
name|named
argument_list|(
name|plugin
operator|.
name|getName
argument_list|()
argument_list|)
argument_list|,
name|cmd
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|onReloadPlugin (Plugin oldPlugin, Plugin newPlugin)
specifier|public
name|void
name|onReloadPlugin
parameter_list|(
name|Plugin
name|oldPlugin
parameter_list|,
name|Plugin
name|newPlugin
parameter_list|)
block|{
name|Provider
argument_list|<
name|Command
argument_list|>
name|cmd
init|=
name|load
argument_list|(
name|newPlugin
argument_list|)
decl_stmt|;
if|if
condition|(
name|cmd
operator|!=
literal|null
condition|)
block|{
name|newPlugin
operator|.
name|add
argument_list|(
name|root
operator|.
name|replace
argument_list|(
name|Commands
operator|.
name|named
argument_list|(
name|newPlugin
operator|.
name|getName
argument_list|()
argument_list|)
argument_list|,
name|cmd
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|load (Plugin plugin)
specifier|private
name|Provider
argument_list|<
name|Command
argument_list|>
name|load
parameter_list|(
name|Plugin
name|plugin
parameter_list|)
block|{
if|if
condition|(
name|plugin
operator|.
name|getSshInjector
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|Key
argument_list|<
name|Command
argument_list|>
name|key
init|=
name|Commands
operator|.
name|key
argument_list|(
name|plugin
operator|.
name|getName
argument_list|()
argument_list|)
decl_stmt|;
try|try
block|{
return|return
name|plugin
operator|.
name|getSshInjector
argument_list|()
operator|.
name|getProvider
argument_list|(
name|key
argument_list|)
return|;
block|}
catch|catch
parameter_list|(
name|RuntimeException
name|err
parameter_list|)
block|{
if|if
condition|(
operator|!
name|providesDynamicOptions
argument_list|(
name|plugin
argument_list|)
condition|)
block|{
name|logger
operator|.
name|atWarning
argument_list|()
operator|.
name|withCause
argument_list|(
name|err
argument_list|)
operator|.
name|log
argument_list|(
literal|"Plugin %s did not define its top-level command nor any DynamicOptions"
argument_list|,
name|plugin
operator|.
name|getName
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
block|}
return|return
literal|null
return|;
block|}
DECL|method|providesDynamicOptions (Plugin plugin)
specifier|private
name|boolean
name|providesDynamicOptions
parameter_list|(
name|Plugin
name|plugin
parameter_list|)
block|{
return|return
name|dynamicBeans
operator|.
name|plugins
argument_list|()
operator|.
name|contains
argument_list|(
name|plugin
operator|.
name|getName
argument_list|()
argument_list|)
return|;
block|}
block|}
end_class
end_unit
|
supersat/nnlib
|
hexagon/ops/src/op_add_f.c
|
<reponame>supersat/nnlib<filename>hexagon/ops/src/op_add_f.c
/*
* Copyright (c) 2016-2019, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the
* disclaimer below) provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of The Linux Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
* GRANTED BY THIS LICENSE. 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.
*
*/
#include <nn_graph.h>
#include <string.h>
#include <quantize.h>
#include <math.h>
#include <nn_broadcast.h>
// add vector to vector
#define OPERATOR_ADD(X,Y) ((X)+(Y))
BROADCAST_STRIDE_11_FUNC( add_f_stride_11, float, float, OPERATOR_ADD)
// add vector to scalar
BROADCAST_STRIDE_10_FUNC( add_f_stride_10, float, float, OPERATOR_ADD )
static const struct elementwise_funcs Add_f_funcs = {
.op_stride_11 = add_f_stride_11,
.op_stride_10 = add_f_stride_10,
.op_rev_stride_01 = add_f_stride_10,
.in_elbytes = 4,
.out_elbytes = 4,
.out_typecode = NN_TYPE_FLOAT
};
static int add_f_execute(struct nn_node *self, struct nn_graph *nn)
{
return nn_elementwise_with_broadcast( self, nn, &Add_f_funcs, NULL, NULL, NULL );
}
/// Add int32
BROADCAST_STRIDE_11_FUNC(add_int32_stride_11, int32_t, int32_t, OPERATOR_ADD)
// subtract scalar from vector
BROADCAST_STRIDE_10_FUNC(add_int32_stride_10, int32_t, int32_t, OPERATOR_ADD)
static const struct elementwise_funcs Add_int32_funcs = {
.op_stride_11 = add_int32_stride_11,
.op_stride_10 = add_int32_stride_10,
.op_rev_stride_01 = add_int32_stride_10, // same since + commutes
.in_elbytes = 4,
.out_elbytes = 4,
.out_typecode = NN_TYPE_INT32
};
static int add_int32_execute(struct nn_node *self, struct nn_graph *nn)
{
return nn_elementwise_with_broadcast( self, nn, &Add_int32_funcs, NULL, NULL, NULL );
}
struct nn_node_ops nn_ops_for_Add_f = {
.execute = add_f_execute,
.check = NULL,
.ctor = node_alloc_common,
.dtor = node_free_common,
.n_inputs = NN_IOCOUNT(2),
.n_outputs = NN_IOCOUNT(1),
};
struct nn_node_ops nn_ops_for_Add_int32 = {
.execute = add_int32_execute,
.check = NULL,
.ctor = node_alloc_common,
.dtor = node_free_common,
.n_inputs = NN_IOCOUNT(2),
.n_outputs = NN_IOCOUNT(1),
};
|
nodchip/QMAClone
|
src/test/java/tv/dyndns/kishibe/qmaclone/server/relevance/TrieCacheIntegrationTest.java
|
<filename>src/test/java/tv/dyndns/kishibe/qmaclone/server/relevance/TrieCacheIntegrationTest.java<gh_stars>10-100
package tv.dyndns.kishibe.qmaclone.server.relevance;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import tv.dyndns.kishibe.qmaclone.server.testing.QMACloneTestEnv;
import com.google.common.collect.Lists;
import com.google.guiceberry.junit4.GuiceBerryRule;
import com.google.inject.Inject;
public class TrieCacheIntegrationTest {
private static final String TEST_DATA = "少年時代から無鉄砲な江戸っ子の坊っちゃんと、肉親から疎んじられる彼に無償の愛を注ぐ女中である清の描写から『坊っちゃん』の物語は幕を開く。"
+ "坊っちゃんは両親と死別後、清とも離れ、四国の旧制中学校に数学の教師として赴任する。"
+ "着任早々、校長には狸、教頭には赤シャツ、画学の教師には野だいこ、英語の教師にはうらなり、数学の主任教師には山嵐と、それぞれにあだ名を付けた。"
+ "坊っちゃんは授業の時に生徒達から、てんぷらそばを四杯食べた件等の私事について執拗に冷やかされる。"
+ "また初めての宿直の夜には、寄宿生達から蒲団の中に大量のバッタ(厳密にはイナゴ)を入れられる等の嫌がらせを受け、激怒して、何としても犯人を突き止めようとしたため、大事になってしまう。"
+ "坊っちゃんは赤シャツとその腰巾着である野だいこから、生徒による嫌がらせは山嵐の扇動によるものであると婉曲的に吹き込まれ、一時は真に受けてしまう。"
+ "しかし、後日の職員会議において、先の寄宿生の不祥事に坊っちゃんが毅然とした措置を主張したところ、狸をはじめとする事なかれ主義の職員達は取り合ってくれなかったのに対し、山嵐だけが坊っちゃんを支持してくれた。"
+ "お互いに対する誤解は解けていき、坊っちゃんと山嵐とは、かえって強い友情で結ばれるようになる。"
+ "うらなりには、マドンナとあだ名される婚約者がいたが、赤シャツがマドンナへの横恋慕から、お人好しのうらなりを体良く延岡に左遷したという事実を知り、坊っちゃんは義憤にかられる。"
+ "実は山嵐も、赤シャツの横恋慕を糾弾したため、逆恨みされていたのであった。"
+ "日露戦争の祝勝会の日に、坊っちゃんと山嵐は赤シャツの謀略により、中学校と師範学校の生徒同士の乱闘騒ぎに巻き込まれた上、いわれ無き生徒扇動の罪を着せられ、山嵐が辞職に追い込まれる。"
+ "卑劣な仕打ちに憤激した坊っちゃんと山嵐は、赤シャツと野だいこの不祥事を暴くための監視を始め、ついに芸者遊び帰りの赤シャツと野だいこを取り押さえる。"
+ "そして芸者遊びについて詰問するも、しらを切られたため、業を煮やし、激しく暴行を加えた。"
+ "即刻辞職した坊っちゃんは、帰郷後、街鉄(現在の都電)の技手となって、再び、清と同居生活を始めるが、清が亡くなり、遺言通り小日向の養源寺に葬った事を記して、『坊っちゃん』の物語は幕を閉じる。";
@Rule
public final GuiceBerryRule rule = new GuiceBerryRule(QMACloneTestEnv.class);
@Inject
private TrieCache trieCache;
@Test
public void testParse() {
List<Integer> extractedWordIndexes = Lists.newArrayList();
trieCache.get().parse(TEST_DATA, extractedWordIndexes, null, null);
assertThat(extractedWordIndexes, not(empty()));
}
}
|
weucode/COMFORT
|
artifact_evaluation/data/codeCoverage/comfort_generate/287.js
|
var NISLFuzzingFunc = function(n, t) {
var i = Object.create(null);
var a = n.length;
null === a && (a = 1), i.generateMarkup(t, a);
};
var NISLParameter0 = [true];
var NISLParameter1 = [[[undefined, undefined, undefined], [[null, [false, true, true, false, false, true, false, false, false, true, false, true, true, true, false], -352016596.2418480950273929, 0.7328827749273653, -510.6576786808938094, null, null, false]], null, true, null], false, false];
NISLFuzzingFunc(NISLParameter0, NISLParameter1);
|
PowerOlive/garnet
|
bin/debugserver/io_loop.cc
|
// Copyright 2016 The Fuchsia 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 "io_loop.h"
#include <unistd.h>
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include "garnet/lib/debugger_utils/util.h"
#include "lib/fxl/logging.h"
namespace debugserver {
RspIOLoop::RspIOLoop(int in_fd, Delegate* delegate, async::Loop* loop)
: IOLoop(in_fd, delegate, loop) {}
void RspIOLoop::OnReadTask() {
FXL_DCHECK(async_get_default_dispatcher() == read_dispatcher());
ssize_t read_size = read(fd(), in_buffer_.data(), kMaxBufferSize);
// 0 bytes means that the remote end closed the TCP connection.
if (read_size == 0) {
FXL_VLOG(1) << "Client closed connection";
ReportDisconnected();
return;
}
// There was an error
if (read_size < 0) {
FXL_LOG(ERROR) << "Error occurred while waiting for a packet"
<< ", " << debugger_utils::ErrnoString(errno);
ReportError();
return;
}
fxl::StringView bytes_read(in_buffer_.data(), read_size);
FXL_VLOG(2) << "-> " << debugger_utils::EscapeNonPrintableString(bytes_read);
// Notify the delegate that we read some bytes. We copy the buffer data
// into the closure as |in_buffer_| can get modified before the closure
// runs.
// TODO(armansito): Pass a weakptr to |delegate_|?
async::PostTask(origin_dispatcher(),
[bytes_read = bytes_read.ToString(), this] {
delegate()->OnBytesRead(bytes_read);
});
if (!quit_called()) {
async::PostTask(read_dispatcher(), std::bind(&RspIOLoop::OnReadTask, this));
}
}
} // namespace debugserver
|
wilebeast/FireFox-OS
|
B2G/gecko/toolkit/components/places/tests/autocomplete/test_enabled.js
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Test for bug 471903 to make sure searching in autocomplete can be turned on
* and off. Also test bug 463535 for pref changing search.
*/
// Define some shared uris and titles (each page needs its own uri)
let kURIs = [
"http://url/0",
];
let kTitles = [
"title",
];
addPageBook(0, 0); // visited page
// Provide for each test: description; search terms; array of gPages indices of
// pages that should match; optional function to be run before the test
let gTests = [
["1: plain search",
"url", [0]],
["2: search disabled",
"url", [], function() setSearch(0)],
["3: resume normal search",
"url", [0], function() setSearch(1)],
];
function setSearch(aSearch) {
prefs.setBoolPref("browser.urlbar.autocomplete.enabled", !!aSearch);
}
|
iootclab/openjdk
|
openjdk11/test/nashorn/script/basic/JDK-8130853.js
|
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* JDK-8130853: Non-extensible global is not handled property
*
* @test
* @run
*/
// don't allow extensions to global
Object.preventExtensions(this);
try {
eval("var x = 34;");
throw new Error("should have thrown TypeError");
} catch (e) {
if (! (e instanceof TypeError)) {
throw e;
}
}
try {
eval("function func() {}");
throw new Error("should have thrown TypeError");
} catch (e) {
if (! (e instanceof TypeError)) {
throw e;
}
}
function checkLoad(code) {
try {
load({ name: "test", script: code });
throw new Error("should have thrown TypeError for load: " + code);
} catch (e) {
if (! (e instanceof TypeError)) {
throw e;
}
}
}
checkLoad("var y = 55");
checkLoad("function f() {}");
// check script engine eval
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
var e = new ScriptEngineManager().getEngineByName("nashorn");
var global = e.eval("this");
e.eval("Object.preventExtensions(this);");
try {
e.eval("var myVar = 33;");
throw new Error("should have thrown TypeError");
} catch (e) {
if (! (e.cause.ecmaError instanceof global.TypeError)) {
throw e;
}
}
// Object.bindProperties on arbitrary non-extensible object
var obj = {};
Object.preventExtensions(obj);
try {
Object.bindProperties(obj, { foo: 434 });
throw new Error("should have thrown TypeError");
} catch (e) {
if (! (e instanceof TypeError)) {
throw e;
}
}
|
Tom1975/CPCCore
|
CPCCoreEmu/simple_filesystem.cpp
|
<filename>CPCCoreEmu/simple_filesystem.cpp
#include "simple_filesystem.h"
#ifdef MINIMUM_DEPENDENCIES
#define PATH_SLASH '/'
#define PATH_SLASH_STRING "/"
namespace std::filesystem
{
path::path(const char* path_file)
{
path_ = path_file;
}
path path::filename()
{
int lg = path_.length();
if (lg == 0) return path("");
lg--;
for (lg; lg >= 0; lg--)
{
if (path_[lg] == PATH_SLASH)
{
return path(&path_[lg + 1]);
}
}
}
path& path::operator /=(const char*ext)
{
path_.append(PATH_SLASH_STRING);
path_.append(ext);
return *this;
}
std::string path::string() const
{ // return path as basic_string<char> native
return path_;
}
}
#else
#endif
|
stlyash/prutor
|
PuP4/Q3 (Ackermann Limited)/Ackermann Limited.py
|
# Defining a function to calculate ackermann,
# Including globals to find base case of the recursion
def acker(a,b):
global numCalls,T
if numCalls == T:
return
numCalls += 1
if a == 0:
return b + 1
elif b == 0:
return acker(a - 1,1)
elif a > 0 and b > 0:
return acker(a - 1, acker(a, b - 1))
else:
return
# Taking input as a list in int
lis = list(map(int,input().split(',')))
m = lis[0]
n = lis[1]
T = lis[2]
numCalls = 0
# Calling the recursive ackermann function
result = acker(m,n)
# Printing result in desired format
if numCalls < T:
print("Result = {} in {} calls".format(result,numCalls))
else:
print("Aborted")
|
specs-feup/matisse
|
MatisseLib/src/org/specs/matisselib/passes/posttype/loopinterchange/MemoryLoopInterchangeFormat.java
|
<gh_stars>0
/**
* Copyright 2017 SPeCS.
*
* 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. under the License.
*/
package org.specs.matisselib.passes.posttype.loopinterchange;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.specs.matisselib.ssa.instructions.BranchInstruction;
import org.specs.matisselib.ssa.instructions.ForInstruction;
import org.specs.matisselib.ssa.instructions.GetOrFirstInstruction;
import org.specs.matisselib.ssa.instructions.IndexedInstruction;
import org.specs.matisselib.ssa.instructions.SimpleGetInstruction;
import org.specs.matisselib.ssa.instructions.SimpleSetInstruction;
import org.specs.matisselib.ssa.instructions.SsaInstruction;
import org.specs.matisselib.typeinference.TypedInstance;
public class MemoryLoopInterchangeFormat implements LoopInterchangeFormat {
private static final boolean ENABLE_LOG = false;
public List<String> computeAccessIndices(TypedInstance instance,
int blockId,
List<String> iterationVars,
List<String> iterIndices,
Map<String, String> derivedFromIndex,
Map<String, String> safeDerivedFrom,
List<LoopVariableImportContext> sortedLoopData) {
log("Iteration vars: " + iterationVars);
log("Safe derived from: " + safeDerivedFrom);
for (SsaInstruction instruction : instance.getBlock(blockId).getInstructions()) {
if (instruction instanceof SimpleSetInstruction
|| instruction instanceof SimpleGetInstruction
|| instruction instanceof GetOrFirstInstruction) {
List<String> usedIterIndices = new ArrayList<>();
for (String input : ((IndexedInstruction) instruction).getIndices()) {
if (derivedFromIndex.containsKey(input)) {
String source = instruction instanceof SimpleSetInstruction ? input
: safeDerivedFrom.getOrDefault(input, input);
usedIterIndices.add(source);
}
}
if (usedIterIndices.size() > 0) {
if (iterIndices == null) {
iterIndices = usedIterIndices;
} else if (!iterIndices.equals(usedIterIndices)) {
log("Different access formats: " + usedIterIndices + " vs " + iterIndices);
return null;
}
}
}
if (instruction instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) instruction;
return computeAccessIndices(instance, branch.getEndBlock(), iterationVars, iterIndices,
derivedFromIndex,
safeDerivedFrom,
sortedLoopData);
}
if (instruction instanceof ForInstruction) {
ForInstruction xfor = (ForInstruction) instruction;
return computeAccessIndices(instance, xfor.getEndBlock(), iterationVars, iterIndices, derivedFromIndex,
safeDerivedFrom, sortedLoopData);
}
if (instruction.getOwnedBlocks().size() != 0) {
log("TODO: " + instruction);
return null;
}
}
if (iterIndices == null) {
log("No iteration variables used in matrix accesses. Interchange would be pointless.");
return null;
}
return iterIndices;
}
private static void log(String message) {
if (ENABLE_LOG) {
System.out.print("[memory_loop_interchange_format] ");
System.out.println(message);
}
}
}
|
Lyude/open-gpu-doc
|
classes/display/cl837d.h
|
<reponame>Lyude/open-gpu-doc
/*
* Copyright (c) 1993-2014, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef _cl837d_h_
#define _cl837d_h_
#ifdef __cplusplus
extern "C" {
#endif
#define NV837D_CORE_CHANNEL_DMA (0x0000837D)
#define NV837D_CORE_NOTIFIER_1 0x00000000
#define NV837D_CORE_NOTIFIER_1_SIZEOF 0x00000054
#define NV837D_CORE_NOTIFIER_1_COMPLETION_0 0x00000000
#define NV837D_CORE_NOTIFIER_1_COMPLETION_0_DONE 0:0
#define NV837D_CORE_NOTIFIER_1_COMPLETION_0_DONE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_COMPLETION_0_DONE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_COMPLETION_0_R0 15:1
#define NV837D_CORE_NOTIFIER_1_COMPLETION_0_TIMESTAMP 29:16
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_DONE 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_DONE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_DONE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_VM_USABLE4ISO 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_VM_USABLE4ISO_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_VM_USABLE4ISO_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_NVM_USABLE4ISO 2:2
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_NVM_USABLE4ISO_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_NVM_USABLE4ISO_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_R0 3:3
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_FOS_FETCH_X4AA 20:20
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_FOS_FETCH_X4AA_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_FOS_FETCH_X4AA_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_FP16CONVERSION_GAIN_OFS 21:21
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_FP16CONVERSION_GAIN_OFS_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_FP16CONVERSION_GAIN_OFS_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_1_R1 31:22
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_2 0x00000002
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_2_R2 31:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_3 0x00000003
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_3_R3 31:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_4 0x00000004
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_4_R4 31:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5 0x00000005
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_RGB_USABLE 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_RGB_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_RGB_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_TV_USABLE 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_TV_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_TV_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_SCART_USABLE 3:3
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_SCART_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC0_5_SCART_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6 0x00000006
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_RGB_USABLE 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_RGB_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_RGB_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_TV_USABLE 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_TV_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_TV_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_SCART_USABLE 3:3
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_SCART_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC1_6_SCART_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7 0x00000007
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_RGB_USABLE 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_RGB_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_RGB_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_TV_USABLE 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_TV_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_TV_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_SCART_USABLE 3:3
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_SCART_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_DAC2_7_SCART_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8 0x00000008
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_LVDS18 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_LVDS18_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_LVDS18_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_LVDS24 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_LVDS24_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_LVDS24_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_LVDS18 2:2
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_LVDS18_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_LVDS18_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_LVDS24 3:3
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_LVDS24_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_LVDS24_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_TMDS_A 4:4
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_TMDS_A_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_TMDS_A_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_TMDS_B 5:5
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_TMDS_B_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_SINGLE_TMDS_B_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_SINGLE_TMDS 6:6
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_SINGLE_TMDS_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_SINGLE_TMDS_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_TMDS 7:7
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_TMDS_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DUAL_TMDS_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DDI 9:9
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DDI_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR0_8_DDI_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9 0x00000009
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_LVDS18 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_LVDS18_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_LVDS18_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_LVDS24 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_LVDS24_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_LVDS24_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_LVDS18 2:2
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_LVDS18_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_LVDS18_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_LVDS24 3:3
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_LVDS24_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_LVDS24_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_TMDS_A 4:4
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_TMDS_A_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_TMDS_A_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_TMDS_B 5:5
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_TMDS_B_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_SINGLE_TMDS_B_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_SINGLE_TMDS 6:6
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_SINGLE_TMDS_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_SINGLE_TMDS_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_TMDS 7:7
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_TMDS_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DUAL_TMDS_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DDI 9:9
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DDI_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_SOR1_9_DDI_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10 0x0000000A
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TMDS_ENC 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TMDS_ENC_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TMDS_ENC_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TV_ENC 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TV_ENC_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TV_ENC_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TMDS10BPC_ALLOWED 6:6
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TMDS10BPC_ALLOWED_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR0_10_EXT_TMDS10BPC_ALLOWED_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11 0x0000000B
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TMDS_ENC 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TMDS_ENC_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TMDS_ENC_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TV_ENC 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TV_ENC_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TV_ENC_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TMDS10BPC_ALLOWED 6:6
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TMDS10BPC_ALLOWED_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR1_11_EXT_TMDS10BPC_ALLOWED_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12 0x0000000C
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TMDS_ENC 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TMDS_ENC_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TMDS_ENC_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TV_ENC 1:1
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TV_ENC_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TV_ENC_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TMDS10BPC_ALLOWED 6:6
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TMDS10BPC_ALLOWED_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_PIOR2_12_EXT_TMDS10BPC_ALLOWED_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_13 0x0000000D
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_13_USABLE 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_13_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_13_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_13_R0 31:2
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_14 0x0000000E
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_14_MAX_PIXELS5TAP444 14:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_14_R1 15:15
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_14_MAX_PIXELS5TAP422 30:16
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_14_R2 31:31
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_15 0x0000000F
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_15_MAX_PIXELS3TAP444 14:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_15_R3 15:15
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_15_MAX_PIXELS3TAP422 30:16
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_15_R4 31:31
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_16 0x00000010
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_16_MAX_PIXELS2TAP444 14:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_16_R5 15:15
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_16_MAX_PIXELS2TAP422 30:16
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD0_16_R6 31:31
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_17 0x00000011
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_17_USABLE 0:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_17_USABLE_FALSE 0x00000000
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_17_USABLE_TRUE 0x00000001
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_17_R0 31:2
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_18 0x00000012
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_18_MAX_PIXELS5TAP444 14:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_18_R1 15:15
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_18_MAX_PIXELS5TAP422 30:16
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_18_R2 31:31
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_19 0x00000013
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_19_MAX_PIXELS3TAP444 14:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_19_R3 15:15
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_19_MAX_PIXELS3TAP422 30:16
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_19_R4 31:31
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_20 0x00000014
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_20_MAX_PIXELS2TAP444 14:0
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_20_R5 15:15
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_20_MAX_PIXELS2TAP422 30:16
#define NV837D_CORE_NOTIFIER_1_CAPABILITIES_CAP_HEAD1_20_R6 31:31
// dma opcode instructions
#define NV837D_DMA 0x00000000
#define NV837D_DMA_OPCODE 31:29
#define NV837D_DMA_OPCODE_METHOD 0x00000000
#define NV837D_DMA_OPCODE_JUMP 0x00000001
#define NV837D_DMA_OPCODE_NONINC_METHOD 0x00000002
#define NV837D_DMA_OPCODE_SET_SUBDEVICE_MASK 0x00000003
#define NV837D_DMA_OPCODE 31:29
#define NV837D_DMA_OPCODE_METHOD 0x00000000
#define NV837D_DMA_OPCODE_NONINC_METHOD 0x00000002
#define NV837D_DMA_METHOD_COUNT 27:18
#define NV837D_DMA_METHOD_OFFSET 11:2
#define NV837D_DMA_DATA 31:0
#define NV837D_DMA_NOP 0x00000000
#define NV837D_DMA_OPCODE 31:29
#define NV837D_DMA_OPCODE_JUMP 0x00000001
#define NV837D_DMA_JUMP_OFFSET 11:2
#define NV837D_DMA_OPCODE 31:29
#define NV837D_DMA_OPCODE_SET_SUBDEVICE_MASK 0x00000003
#define NV837D_DMA_SET_SUBDEVICE_MASK_VALUE 11:0
// class methods
#define NV837D_PUT (0x00000000)
#define NV837D_PUT_PTR 11:2
#define NV837D_GET (0x00000004)
#define NV837D_GET_PTR 11:2
#define NV837D_UPDATE (0x00000080)
#define NV837D_UPDATE_INTERLOCK_WITH_CURSOR0 0:0
#define NV837D_UPDATE_INTERLOCK_WITH_CURSOR0_DISABLE (0x00000000)
#define NV837D_UPDATE_INTERLOCK_WITH_CURSOR0_ENABLE (0x00000001)
#define NV837D_UPDATE_INTERLOCK_WITH_CURSOR1 8:8
#define NV837D_UPDATE_INTERLOCK_WITH_CURSOR1_DISABLE (0x00000000)
#define NV837D_UPDATE_INTERLOCK_WITH_CURSOR1_ENABLE (0x00000001)
#define NV837D_UPDATE_INTERLOCK_WITH_BASE0 1:1
#define NV837D_UPDATE_INTERLOCK_WITH_BASE0_DISABLE (0x00000000)
#define NV837D_UPDATE_INTERLOCK_WITH_BASE0_ENABLE (0x00000001)
#define NV837D_UPDATE_INTERLOCK_WITH_BASE1 9:9
#define NV837D_UPDATE_INTERLOCK_WITH_BASE1_DISABLE (0x00000000)
#define NV837D_UPDATE_INTERLOCK_WITH_BASE1_ENABLE (0x00000001)
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY0 2:2
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY0_DISABLE (0x00000000)
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY0_ENABLE (0x00000001)
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY1 10:10
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY1_DISABLE (0x00000000)
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY1_ENABLE (0x00000001)
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY_IMM0 3:3
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY_IMM0_DISABLE (0x00000000)
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY_IMM0_ENABLE (0x00000001)
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY_IMM1 11:11
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY_IMM1_DISABLE (0x00000000)
#define NV837D_UPDATE_INTERLOCK_WITH_OVERLAY_IMM1_ENABLE (0x00000001)
#define NV837D_UPDATE_NOT_DRIVER_FRIENDLY 31:31
#define NV837D_UPDATE_NOT_DRIVER_FRIENDLY_FALSE (0x00000000)
#define NV837D_UPDATE_NOT_DRIVER_FRIENDLY_TRUE (0x00000001)
#define NV837D_UPDATE_NOT_DRIVER_UNFRIENDLY 30:30
#define NV837D_UPDATE_NOT_DRIVER_UNFRIENDLY_FALSE (0x00000000)
#define NV837D_UPDATE_NOT_DRIVER_UNFRIENDLY_TRUE (0x00000001)
#define NV837D_UPDATE_INHIBIT_INTERRUPTS 29:29
#define NV837D_UPDATE_INHIBIT_INTERRUPTS_FALSE (0x00000000)
#define NV837D_UPDATE_INHIBIT_INTERRUPTS_TRUE (0x00000001)
#define NV837D_SET_NOTIFIER_CONTROL (0x00000084)
#define NV837D_SET_NOTIFIER_CONTROL_MODE 30:30
#define NV837D_SET_NOTIFIER_CONTROL_MODE_WRITE (0x00000000)
#define NV837D_SET_NOTIFIER_CONTROL_MODE_WRITE_AWAKEN (0x00000001)
#define NV837D_SET_NOTIFIER_CONTROL_OFFSET 11:2
#define NV837D_SET_NOTIFIER_CONTROL_NOTIFY 31:31
#define NV837D_SET_NOTIFIER_CONTROL_NOTIFY_DISABLE (0x00000000)
#define NV837D_SET_NOTIFIER_CONTROL_NOTIFY_ENABLE (0x00000001)
#define NV837D_SET_CONTEXT_DMA_NOTIFIER (0x00000088)
#define NV837D_SET_CONTEXT_DMA_NOTIFIER_HANDLE 31:0
#define NV837D_GET_CAPABILITIES (0x0000008C)
#define NV837D_GET_CAPABILITIES_DUMMY 31:0
#define NV837D_SET_SPARE (0x000003BC)
#define NV837D_SET_SPARE_UNUSED 31:0
#define NV837D_SET_SPARE_NOOP(b) (0x000003C0 + (b)*0x00000004)
#define NV837D_SET_SPARE_NOOP_UNUSED 31:0
#define NV837D_DAC_SET_CONTROL(a) (0x00000400 + (a)*0x00000080)
#define NV837D_DAC_SET_CONTROL_OWNER 3:0
#define NV837D_DAC_SET_CONTROL_OWNER_NONE (0x00000000)
#define NV837D_DAC_SET_CONTROL_OWNER_HEAD0 (0x00000001)
#define NV837D_DAC_SET_CONTROL_OWNER_HEAD1 (0x00000002)
#define NV837D_DAC_SET_CONTROL_SUB_OWNER 5:4
#define NV837D_DAC_SET_CONTROL_SUB_OWNER_NONE (0x00000000)
#define NV837D_DAC_SET_CONTROL_SUB_OWNER_SUBHEAD0 (0x00000001)
#define NV837D_DAC_SET_CONTROL_SUB_OWNER_SUBHEAD1 (0x00000002)
#define NV837D_DAC_SET_CONTROL_SUB_OWNER_BOTH (0x00000003)
#define NV837D_DAC_SET_CONTROL_PROTOCOL 13:8
#define NV837D_DAC_SET_CONTROL_PROTOCOL_RGB_CRT (0x00000000)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_CPST_NTSC_M (0x00000001)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_CPST_NTSC_J (0x00000002)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_CPST_PAL_BDGHI (0x00000003)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_CPST_PAL_M (0x00000004)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_CPST_PAL_N (0x00000005)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_CPST_PAL_CN (0x00000006)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_NTSC_M (0x00000007)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_NTSC_J (0x00000008)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_PAL_BDGHI (0x00000009)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_PAL_M (0x0000000A)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_PAL_N (0x0000000B)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_PAL_CN (0x0000000C)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_480P_60 (0x0000000D)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_576P_50 (0x0000000E)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_720P_50 (0x0000000F)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_720P_60 (0x00000010)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_1080I_50 (0x00000011)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_COMP_1080I_60 (0x00000012)
#define NV837D_DAC_SET_CONTROL_PROTOCOL_CUSTOM (0x0000003F)
#define NV837D_DAC_SET_CONTROL_INVALIDATE_FIRST_FIELD 14:14
#define NV837D_DAC_SET_CONTROL_INVALIDATE_FIRST_FIELD_FALSE (0x00000000)
#define NV837D_DAC_SET_CONTROL_INVALIDATE_FIRST_FIELD_TRUE (0x00000001)
#define NV837D_DAC_SET_POLARITY(a) (0x00000404 + (a)*0x00000080)
#define NV837D_DAC_SET_POLARITY_HSYNC 0:0
#define NV837D_DAC_SET_POLARITY_HSYNC_POSITIVE_TRUE (0x00000000)
#define NV837D_DAC_SET_POLARITY_HSYNC_NEGATIVE_TRUE (0x00000001)
#define NV837D_DAC_SET_POLARITY_VSYNC 1:1
#define NV837D_DAC_SET_POLARITY_VSYNC_POSITIVE_TRUE (0x00000000)
#define NV837D_DAC_SET_POLARITY_VSYNC_NEGATIVE_TRUE (0x00000001)
#define NV837D_DAC_SET_POLARITY_RESERVED 31:2
#define NV837D_DAC_SET_ENCODE_QUALITY(a) (0x00000420 + (a)*0x00000080)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_FILTER_BANDPASS 7:7
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_FILTER_BANDPASS_BW_3_375 (0x00000000)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_FILTER_BANDPASS_BW_6_75 (0x00000001)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_GAIN 2:0
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_GAIN_GN_0 (0x00000000)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_GAIN_GN_0_0625 (0x00000001)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_GAIN_GN_0_125 (0x00000002)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_GAIN_GN_0_25 (0x00000003)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_GAIN_GN_0_5 (0x00000004)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_GAIN_GN_1_0 (0x00000005)
#define NV837D_DAC_SET_ENCODE_QUALITY_SHARPEN_GAIN 6:4
#define NV837D_DAC_SET_ENCODE_QUALITY_SHARPEN_GAIN_GN_0 (0x00000000)
#define NV837D_DAC_SET_ENCODE_QUALITY_SHARPEN_GAIN_GN_0_0625 (0x00000001)
#define NV837D_DAC_SET_ENCODE_QUALITY_SHARPEN_GAIN_GN_0_125 (0x00000002)
#define NV837D_DAC_SET_ENCODE_QUALITY_SHARPEN_GAIN_GN_0_25 (0x00000003)
#define NV837D_DAC_SET_ENCODE_QUALITY_SHARPEN_GAIN_GN_0_5 (0x00000004)
#define NV837D_DAC_SET_ENCODE_QUALITY_SHARPEN_GAIN_GN_1_0 (0x00000005)
#define NV837D_DAC_SET_ENCODE_QUALITY_NOISE_THRSH 15:8
#define NV837D_DAC_SET_ENCODE_QUALITY_SHARPEN_THRSH 23:16
#define NV837D_DAC_SET_ENCODE_QUALITY_TINT 31:24
#define NV837D_DAC_UPDATE_ENCODER_PRESET(a) (0x0000047C + (a)*0x00000080)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL 5:0
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_RGB_CRT (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_CPST_NTSC_M (0x00000001)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_CPST_NTSC_J (0x00000002)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_CPST_PAL_BDGHI (0x00000003)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_CPST_PAL_M (0x00000004)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_CPST_PAL_N (0x00000005)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_CPST_PAL_CN (0x00000006)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_NTSC_M (0x00000007)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_NTSC_J (0x00000008)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_PAL_BDGHI (0x00000009)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_PAL_M (0x0000000A)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_PAL_N (0x0000000B)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_PAL_CN (0x0000000C)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_480P_60 (0x0000000D)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_576P_50 (0x0000000E)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_720P_50 (0x0000000F)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_720P_60 (0x00000010)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_1080I_50 (0x00000011)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_COMP_1080I_60 (0x00000012)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_PROTOCOL_CUSTOM (0x0000003F)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_COMP_FORMAT 6:6
#define NV837D_DAC_UPDATE_ENCODER_PRESET_COMP_FORMAT_RGB (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_COMP_FORMAT_YUV (0x00000001)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_R 7:7
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_R_DISABLE (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_R_ENABLE (0x00000001)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_G 8:8
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_G_DISABLE (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_G_ENABLE (0x00000001)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_B 9:9
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_B_DISABLE (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_ENABLE_SYNC_ON_B_ENABLE (0x00000001)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_LUMA_NOTCH 12:10
#define NV837D_DAC_UPDATE_ENCODER_PRESET_LUMA_NOTCH_NONE (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_LUMA_NOTCH_NARROW_358 (0x00000001)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_LUMA_NOTCH_WIDE_358 (0x00000002)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_LUMA_NOTCH_NARROW_443 (0x00000003)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_LUMA_NOTCH_WIDE_443 (0x00000004)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_CHROMA_BW_NARROW 13:13
#define NV837D_DAC_UPDATE_ENCODER_PRESET_CHROMA_BW_NARROW_BW_0_6 (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_CHROMA_BW_NARROW_BW_1_4 (0x00000001)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_CPST_FILTER 15:15
#define NV837D_DAC_UPDATE_ENCODER_PRESET_CPST_FILTER_NARROW (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_CPST_FILTER_WIDE (0x00000001)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_COMP_FILTER 16:16
#define NV837D_DAC_UPDATE_ENCODER_PRESET_COMP_FILTER_NARROW (0x00000000)
#define NV837D_DAC_UPDATE_ENCODER_PRESET_COMP_FILTER_WIDE (0x00000001)
#define NV837D_SOR_SET_CONTROL(a) (0x00000600 + (a)*0x00000040)
#define NV837D_SOR_SET_CONTROL_OWNER 3:0
#define NV837D_SOR_SET_CONTROL_OWNER_NONE (0x00000000)
#define NV837D_SOR_SET_CONTROL_OWNER_HEAD0 (0x00000001)
#define NV837D_SOR_SET_CONTROL_OWNER_HEAD1 (0x00000002)
#define NV837D_SOR_SET_CONTROL_SUB_OWNER 5:4
#define NV837D_SOR_SET_CONTROL_SUB_OWNER_NONE (0x00000000)
#define NV837D_SOR_SET_CONTROL_SUB_OWNER_SUBHEAD0 (0x00000001)
#define NV837D_SOR_SET_CONTROL_SUB_OWNER_SUBHEAD1 (0x00000002)
#define NV837D_SOR_SET_CONTROL_SUB_OWNER_BOTH (0x00000003)
#define NV837D_SOR_SET_CONTROL_PROTOCOL 11:8
#define NV837D_SOR_SET_CONTROL_PROTOCOL_LVDS_CUSTOM (0x00000000)
#define NV837D_SOR_SET_CONTROL_PROTOCOL_SINGLE_TMDS_A (0x00000001)
#define NV837D_SOR_SET_CONTROL_PROTOCOL_SINGLE_TMDS_B (0x00000002)
#define NV837D_SOR_SET_CONTROL_PROTOCOL_SINGLE_TMDS_AB (0x00000003)
#define NV837D_SOR_SET_CONTROL_PROTOCOL_DUAL_SINGLE_TMDS (0x00000004)
#define NV837D_SOR_SET_CONTROL_PROTOCOL_DUAL_TMDS (0x00000005)
#define NV837D_SOR_SET_CONTROL_PROTOCOL_DDI_OUT (0x00000007)
#define NV837D_SOR_SET_CONTROL_PROTOCOL_CUSTOM (0x0000000F)
#define NV837D_SOR_SET_CONTROL_HSYNC_POLARITY 12:12
#define NV837D_SOR_SET_CONTROL_HSYNC_POLARITY_POSITIVE_TRUE (0x00000000)
#define NV837D_SOR_SET_CONTROL_HSYNC_POLARITY_NEGATIVE_TRUE (0x00000001)
#define NV837D_SOR_SET_CONTROL_VSYNC_POLARITY 13:13
#define NV837D_SOR_SET_CONTROL_VSYNC_POLARITY_POSITIVE_TRUE (0x00000000)
#define NV837D_SOR_SET_CONTROL_VSYNC_POLARITY_NEGATIVE_TRUE (0x00000001)
#define NV837D_SOR_SET_CONTROL_DE_SYNC_POLARITY 14:14
#define NV837D_SOR_SET_CONTROL_DE_SYNC_POLARITY_POSITIVE_TRUE (0x00000000)
#define NV837D_SOR_SET_CONTROL_DE_SYNC_POLARITY_NEGATIVE_TRUE (0x00000001)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH 19:16
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_DEFAULT (0x00000000)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_16_422 (0x00000001)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_18_444 (0x00000002)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_20_422 (0x00000003)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_24_422 (0x00000004)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_24_444 (0x00000005)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_30_444 (0x00000006)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_32_422 (0x00000007)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_36_444 (0x00000008)
#define NV837D_SOR_SET_CONTROL_PIXEL_DEPTH_BPP_48_444 (0x00000009)
#define NV837D_PIOR_SET_CONTROL(a) (0x00000700 + (a)*0x00000040)
#define NV837D_PIOR_SET_CONTROL_OWNER 3:0
#define NV837D_PIOR_SET_CONTROL_OWNER_NONE (0x00000000)
#define NV837D_PIOR_SET_CONTROL_OWNER_HEAD0 (0x00000001)
#define NV837D_PIOR_SET_CONTROL_OWNER_HEAD1 (0x00000002)
#define NV837D_PIOR_SET_CONTROL_SUB_OWNER 5:4
#define NV837D_PIOR_SET_CONTROL_SUB_OWNER_NONE (0x00000000)
#define NV837D_PIOR_SET_CONTROL_SUB_OWNER_SUBHEAD0 (0x00000001)
#define NV837D_PIOR_SET_CONTROL_SUB_OWNER_SUBHEAD1 (0x00000002)
#define NV837D_PIOR_SET_CONTROL_SUB_OWNER_BOTH (0x00000003)
#define NV837D_PIOR_SET_CONTROL_PROTOCOL 11:8
#define NV837D_PIOR_SET_CONTROL_PROTOCOL_EXT_TMDS_ENC (0x00000000)
#define NV837D_PIOR_SET_CONTROL_PROTOCOL_EXT_TV_ENC (0x00000001)
#define NV837D_PIOR_SET_CONTROL_HSYNC_POLARITY 12:12
#define NV837D_PIOR_SET_CONTROL_HSYNC_POLARITY_POSITIVE_TRUE (0x00000000)
#define NV837D_PIOR_SET_CONTROL_HSYNC_POLARITY_NEGATIVE_TRUE (0x00000001)
#define NV837D_PIOR_SET_CONTROL_VSYNC_POLARITY 13:13
#define NV837D_PIOR_SET_CONTROL_VSYNC_POLARITY_POSITIVE_TRUE (0x00000000)
#define NV837D_PIOR_SET_CONTROL_VSYNC_POLARITY_NEGATIVE_TRUE (0x00000001)
#define NV837D_PIOR_SET_CONTROL_DE_SYNC_POLARITY 14:14
#define NV837D_PIOR_SET_CONTROL_DE_SYNC_POLARITY_POSITIVE_TRUE (0x00000000)
#define NV837D_PIOR_SET_CONTROL_DE_SYNC_POLARITY_NEGATIVE_TRUE (0x00000001)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH 19:16
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_DEFAULT (0x00000000)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_16_422 (0x00000001)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_18_444 (0x00000002)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_20_422 (0x00000003)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_24_422 (0x00000004)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_24_444 (0x00000005)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_30_444 (0x00000006)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_32_422 (0x00000007)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_36_444 (0x00000008)
#define NV837D_PIOR_SET_CONTROL_PIXEL_DEPTH_BPP_48_444 (0x00000009)
#define NV837D_HEAD_SET_PRESENT_CONTROL(a) (0x00000800 + (a)*0x00000400)
#define NV837D_HEAD_SET_PRESENT_CONTROL_MIN_PRESENT_INTERVAL 3:0
#define NV837D_HEAD_SET_PRESENT_CONTROL_USE_BEGIN_FIELD 8:8
#define NV837D_HEAD_SET_PRESENT_CONTROL_USE_BEGIN_FIELD_DISABLE (0x00000000)
#define NV837D_HEAD_SET_PRESENT_CONTROL_USE_BEGIN_FIELD_ENABLE (0x00000001)
#define NV837D_HEAD_SET_PRESENT_CONTROL_BEGIN_FIELD 6:4
#define NV837D_HEAD_SET_PIXEL_CLOCK(a) (0x00000804 + (a)*0x00000400)
#define NV837D_HEAD_SET_PIXEL_CLOCK_FREQUENCY 21:0
#define NV837D_HEAD_SET_PIXEL_CLOCK_MODE 23:22
#define NV837D_HEAD_SET_PIXEL_CLOCK_MODE_CLK_25 (0x00000000)
#define NV837D_HEAD_SET_PIXEL_CLOCK_MODE_CLK_28 (0x00000001)
#define NV837D_HEAD_SET_PIXEL_CLOCK_MODE_CLK_CUSTOM (0x00000002)
#define NV837D_HEAD_SET_PIXEL_CLOCK_ADJ1000DIV1001 24:24
#define NV837D_HEAD_SET_PIXEL_CLOCK_ADJ1000DIV1001_FALSE (0x00000000)
#define NV837D_HEAD_SET_PIXEL_CLOCK_ADJ1000DIV1001_TRUE (0x00000001)
#define NV837D_HEAD_SET_PIXEL_CLOCK_NOT_DRIVER 25:25
#define NV837D_HEAD_SET_PIXEL_CLOCK_NOT_DRIVER_FALSE (0x00000000)
#define NV837D_HEAD_SET_PIXEL_CLOCK_NOT_DRIVER_TRUE (0x00000001)
#define NV837D_HEAD_SET_CONTROL(a) (0x00000808 + (a)*0x00000400)
#define NV837D_HEAD_SET_CONTROL_STRUCTURE 2:1
#define NV837D_HEAD_SET_CONTROL_STRUCTURE_PROGRESSIVE (0x00000000)
#define NV837D_HEAD_SET_CONTROL_STRUCTURE_INTERLACED (0x00000001)
#define NV837D_HEAD_SET_OVERSCAN_COLOR(a) (0x00000810 + (a)*0x00000400)
#define NV837D_HEAD_SET_OVERSCAN_COLOR_RED 9:0
#define NV837D_HEAD_SET_OVERSCAN_COLOR_GRN 19:10
#define NV837D_HEAD_SET_OVERSCAN_COLOR_BLU 29:20
#define NV837D_HEAD_SET_RASTER_SIZE(a) (0x00000814 + (a)*0x00000400)
#define NV837D_HEAD_SET_RASTER_SIZE_WIDTH 14:0
#define NV837D_HEAD_SET_RASTER_SIZE_HEIGHT 30:16
#define NV837D_HEAD_SET_RASTER_SYNC_END(a) (0x00000818 + (a)*0x00000400)
#define NV837D_HEAD_SET_RASTER_SYNC_END_X 14:0
#define NV837D_HEAD_SET_RASTER_SYNC_END_Y 30:16
#define NV837D_HEAD_SET_RASTER_BLANK_END(a) (0x0000081C + (a)*0x00000400)
#define NV837D_HEAD_SET_RASTER_BLANK_END_X 14:0
#define NV837D_HEAD_SET_RASTER_BLANK_END_Y 30:16
#define NV837D_HEAD_SET_RASTER_BLANK_START(a) (0x00000820 + (a)*0x00000400)
#define NV837D_HEAD_SET_RASTER_BLANK_START_X 14:0
#define NV837D_HEAD_SET_RASTER_BLANK_START_Y 30:16
#define NV837D_HEAD_SET_RASTER_VERT_BLANK2(a) (0x00000824 + (a)*0x00000400)
#define NV837D_HEAD_SET_RASTER_VERT_BLANK2_YSTART 14:0
#define NV837D_HEAD_SET_RASTER_VERT_BLANK2_YEND 30:16
#define NV837D_HEAD_SET_RASTER_VERT_BLANK_DMI(a) (0x00000828 + (a)*0x00000400)
#define NV837D_HEAD_SET_RASTER_VERT_BLANK_DMI_DURATION 11:0
#define NV837D_HEAD_SET_DEFAULT_BASE_COLOR(a) (0x0000082C + (a)*0x00000400)
#define NV837D_HEAD_SET_DEFAULT_BASE_COLOR_RED 9:0
#define NV837D_HEAD_SET_DEFAULT_BASE_COLOR_GREEN 19:10
#define NV837D_HEAD_SET_DEFAULT_BASE_COLOR_BLUE 29:20
#define NV837D_HEAD_SET_BASE_LUT_LO(a) (0x00000840 + (a)*0x00000400)
#define NV837D_HEAD_SET_BASE_LUT_LO_ENABLE 31:31
#define NV837D_HEAD_SET_BASE_LUT_LO_ENABLE_DISABLE (0x00000000)
#define NV837D_HEAD_SET_BASE_LUT_LO_ENABLE_ENABLE (0x00000001)
#define NV837D_HEAD_SET_BASE_LUT_LO_MODE 30:30
#define NV837D_HEAD_SET_BASE_LUT_LO_MODE_LORES (0x00000000)
#define NV837D_HEAD_SET_BASE_LUT_LO_MODE_HIRES (0x00000001)
#define NV837D_HEAD_SET_BASE_LUT_LO_ORIGIN 7:2
#define NV837D_HEAD_SET_BASE_LUT_HI(a) (0x00000844 + (a)*0x00000400)
#define NV837D_HEAD_SET_BASE_LUT_HI_ORIGIN 31:0
#define NV837D_HEAD_SET_OUTPUT_LUT_LO(a) (0x00000848 + (a)*0x00000400)
#define NV837D_HEAD_SET_OUTPUT_LUT_LO_ENABLE 31:31
#define NV837D_HEAD_SET_OUTPUT_LUT_LO_ENABLE_DISABLE (0x00000000)
#define NV837D_HEAD_SET_OUTPUT_LUT_LO_ENABLE_ENABLE (0x00000001)
#define NV837D_HEAD_SET_OUTPUT_LUT_LO_MODE 30:30
#define NV837D_HEAD_SET_OUTPUT_LUT_LO_MODE_LORES (0x00000000)
#define NV837D_HEAD_SET_OUTPUT_LUT_LO_MODE_HIRES (0x00000001)
#define NV837D_HEAD_SET_OUTPUT_LUT_LO_ORIGIN 7:2
#define NV837D_HEAD_SET_OUTPUT_LUT_HI(a) (0x0000084C + (a)*0x00000400)
#define NV837D_HEAD_SET_OUTPUT_LUT_HI_ORIGIN 31:0
#define NV837D_HEAD_SET_CONTEXT_DMA_LUT(a) (0x0000085C + (a)*0x00000400)
#define NV837D_HEAD_SET_CONTEXT_DMA_LUT_HANDLE 31:0
#define NV837D_HEAD_SET_OFFSET(a,b) (0x00000860 + (a)*0x00000400 + (b)*0x00000004)
#define NV837D_HEAD_SET_OFFSET_ORIGIN 31:0
#define NV837D_HEAD_SET_SIZE(a) (0x00000868 + (a)*0x00000400)
#define NV837D_HEAD_SET_SIZE_WIDTH 14:0
#define NV837D_HEAD_SET_SIZE_HEIGHT 30:16
#define NV837D_HEAD_SET_STORAGE(a) (0x0000086C + (a)*0x00000400)
#define NV837D_HEAD_SET_STORAGE_BLOCK_HEIGHT 3:0
#define NV837D_HEAD_SET_STORAGE_BLOCK_HEIGHT_ONE_GOB (0x00000000)
#define NV837D_HEAD_SET_STORAGE_BLOCK_HEIGHT_TWO_GOBS (0x00000001)
#define NV837D_HEAD_SET_STORAGE_BLOCK_HEIGHT_FOUR_GOBS (0x00000002)
#define NV837D_HEAD_SET_STORAGE_BLOCK_HEIGHT_EIGHT_GOBS (0x00000003)
#define NV837D_HEAD_SET_STORAGE_BLOCK_HEIGHT_SIXTEEN_GOBS (0x00000004)
#define NV837D_HEAD_SET_STORAGE_BLOCK_HEIGHT_THIRTYTWO_GOBS (0x00000005)
#define NV837D_HEAD_SET_STORAGE_PITCH 17:8
#define NV837D_HEAD_SET_STORAGE_MEMORY_LAYOUT 20:20
#define NV837D_HEAD_SET_STORAGE_MEMORY_LAYOUT_BLOCKLINEAR (0x00000000)
#define NV837D_HEAD_SET_STORAGE_MEMORY_LAYOUT_PITCH (0x00000001)
#define NV837D_HEAD_SET_PARAMS(a) (0x00000870 + (a)*0x00000400)
#define NV837D_HEAD_SET_PARAMS_FORMAT 15:8
#define NV837D_HEAD_SET_PARAMS_FORMAT_I8 (0x0000001E)
#define NV837D_HEAD_SET_PARAMS_FORMAT_VOID16 (0x0000001F)
#define NV837D_HEAD_SET_PARAMS_FORMAT_VOID32 (0x0000002E)
#define NV837D_HEAD_SET_PARAMS_FORMAT_RF16_GF16_BF16_AF16 (0x000000CA)
#define NV837D_HEAD_SET_PARAMS_FORMAT_A8R8G8B8 (0x000000CF)
#define NV837D_HEAD_SET_PARAMS_FORMAT_A2B10G10R10 (0x000000D1)
#define NV837D_HEAD_SET_PARAMS_FORMAT_A8B8G8R8 (0x000000D5)
#define NV837D_HEAD_SET_PARAMS_FORMAT_R5G6B5 (0x000000E8)
#define NV837D_HEAD_SET_PARAMS_FORMAT_A1R5G5B5 (0x000000E9)
#define NV837D_HEAD_SET_PARAMS_SUPER_SAMPLE 1:0
#define NV837D_HEAD_SET_PARAMS_SUPER_SAMPLE_X1_AA (0x00000000)
#define NV837D_HEAD_SET_PARAMS_SUPER_SAMPLE_X4_AA (0x00000002)
#define NV837D_HEAD_SET_PARAMS_GAMMA 2:2
#define NV837D_HEAD_SET_PARAMS_GAMMA_LINEAR (0x00000000)
#define NV837D_HEAD_SET_PARAMS_GAMMA_SRGB (0x00000001)
#define NV837D_HEAD_SET_PARAMS_RESERVED0 22:16
#define NV837D_HEAD_SET_PARAMS_RESERVED1 24:24
#define NV837D_HEAD_SET_CONTEXT_DMAS_ISO(a,b) (0x00000874 + (a)*0x00000400 + (b)*0x00000004)
#define NV837D_HEAD_SET_CONTEXT_DMAS_ISO_HANDLE 31:0
#define NV837D_HEAD_SET_CONTROL_CURSOR(a) (0x00000880 + (a)*0x00000400)
#define NV837D_HEAD_SET_CONTROL_CURSOR_ENABLE 31:31
#define NV837D_HEAD_SET_CONTROL_CURSOR_ENABLE_DISABLE (0x00000000)
#define NV837D_HEAD_SET_CONTROL_CURSOR_ENABLE_ENABLE (0x00000001)
#define NV837D_HEAD_SET_CONTROL_CURSOR_FORMAT 25:24
#define NV837D_HEAD_SET_CONTROL_CURSOR_FORMAT_A1R5G5B5 (0x00000000)
#define NV837D_HEAD_SET_CONTROL_CURSOR_FORMAT_A8R8G8B8 (0x00000001)
#define NV837D_HEAD_SET_CONTROL_CURSOR_SIZE 26:26
#define NV837D_HEAD_SET_CONTROL_CURSOR_SIZE_W32_H32 (0x00000000)
#define NV837D_HEAD_SET_CONTROL_CURSOR_SIZE_W64_H64 (0x00000001)
#define NV837D_HEAD_SET_CONTROL_CURSOR_HOT_SPOT_X 13:8
#define NV837D_HEAD_SET_CONTROL_CURSOR_HOT_SPOT_Y 21:16
#define NV837D_HEAD_SET_CONTROL_CURSOR_COMPOSITION 29:28
#define NV837D_HEAD_SET_CONTROL_CURSOR_COMPOSITION_ALPHA_BLEND (0x00000000)
#define NV837D_HEAD_SET_CONTROL_CURSOR_COMPOSITION_PREMULT_ALPHA_BLEND (0x00000001)
#define NV837D_HEAD_SET_CONTROL_CURSOR_COMPOSITION_XOR (0x00000002)
#define NV837D_HEAD_SET_CONTROL_CURSOR_SUB_OWNER 5:4
#define NV837D_HEAD_SET_CONTROL_CURSOR_SUB_OWNER_NONE (0x00000000)
#define NV837D_HEAD_SET_CONTROL_CURSOR_SUB_OWNER_SUBHEAD0 (0x00000001)
#define NV837D_HEAD_SET_CONTROL_CURSOR_SUB_OWNER_SUBHEAD1 (0x00000002)
#define NV837D_HEAD_SET_CONTROL_CURSOR_SUB_OWNER_BOTH (0x00000003)
#define NV837D_HEAD_SET_OFFSET_CURSOR(a) (0x00000884 + (a)*0x00000400)
#define NV837D_HEAD_SET_OFFSET_CURSOR_ORIGIN 31:0
#define NV837D_HEAD_SET_CONTEXT_DMA_CURSOR(a) (0x0000089C + (a)*0x00000400)
#define NV837D_HEAD_SET_CONTEXT_DMA_CURSOR_HANDLE 31:0
#define NV837D_HEAD_SET_DITHER_CONTROL(a) (0x000008A0 + (a)*0x00000400)
#define NV837D_HEAD_SET_DITHER_CONTROL_ENABLE 0:0
#define NV837D_HEAD_SET_DITHER_CONTROL_ENABLE_DISABLE (0x00000000)
#define NV837D_HEAD_SET_DITHER_CONTROL_ENABLE_ENABLE (0x00000001)
#define NV837D_HEAD_SET_DITHER_CONTROL_BITS 2:1
#define NV837D_HEAD_SET_DITHER_CONTROL_BITS_DITHER_TO_6_BITS (0x00000000)
#define NV837D_HEAD_SET_DITHER_CONTROL_BITS_DITHER_TO_8_BITS (0x00000001)
#define NV837D_HEAD_SET_DITHER_CONTROL_MODE 6:3
#define NV837D_HEAD_SET_DITHER_CONTROL_MODE_DYNAMIC_ERR_ACC (0x00000000)
#define NV837D_HEAD_SET_DITHER_CONTROL_MODE_STATIC_ERR_ACC (0x00000001)
#define NV837D_HEAD_SET_DITHER_CONTROL_MODE_DYNAMIC_2X2 (0x00000002)
#define NV837D_HEAD_SET_DITHER_CONTROL_MODE_STATIC_2X2 (0x00000003)
#define NV837D_HEAD_SET_DITHER_CONTROL_PHASE 8:7
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER(a) (0x000008A4 + (a)*0x00000400)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_VERTICAL_TAPS 2:0
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_VERTICAL_TAPS_TAPS_1 (0x00000000)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_VERTICAL_TAPS_TAPS_2 (0x00000001)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_VERTICAL_TAPS_TAPS_3 (0x00000002)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_VERTICAL_TAPS_TAPS_3_ADAPTIVE (0x00000003)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_VERTICAL_TAPS_TAPS_5 (0x00000004)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_HORIZONTAL_TAPS 4:3
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_HORIZONTAL_TAPS_TAPS_1 (0x00000000)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_HORIZONTAL_TAPS_TAPS_2 (0x00000001)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_HORIZONTAL_TAPS_TAPS_8 (0x00000002)
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_HRESPONSE_BIAS 23:16
#define NV837D_HEAD_SET_CONTROL_OUTPUT_SCALER_VRESPONSE_BIAS 31:24
#define NV837D_HEAD_SET_PROCAMP(a) (0x000008A8 + (a)*0x00000400)
#define NV837D_HEAD_SET_PROCAMP_COLOR_SPACE 1:0
#define NV837D_HEAD_SET_PROCAMP_COLOR_SPACE_RGB (0x00000000)
#define NV837D_HEAD_SET_PROCAMP_COLOR_SPACE_YUV_601 (0x00000001)
#define NV837D_HEAD_SET_PROCAMP_COLOR_SPACE_YUV_709 (0x00000002)
#define NV837D_HEAD_SET_PROCAMP_CHROMA_LPF 2:2
#define NV837D_HEAD_SET_PROCAMP_CHROMA_LPF_AUTO (0x00000000)
#define NV837D_HEAD_SET_PROCAMP_CHROMA_LPF_ON (0x00000001)
#define NV837D_HEAD_SET_PROCAMP_SAT_COS 19:8
#define NV837D_HEAD_SET_PROCAMP_SAT_SINE 31:20
#define NV837D_HEAD_SET_PROCAMP_TRANSITION 4:3
#define NV837D_HEAD_SET_PROCAMP_TRANSITION_HARD (0x00000000)
#define NV837D_HEAD_SET_PROCAMP_TRANSITION_NTSC (0x00000001)
#define NV837D_HEAD_SET_PROCAMP_TRANSITION_PAL (0x00000002)
#define NV837D_HEAD_SET_VIEWPORT_POINT_IN(a,b) (0x000008C0 + (a)*0x00000400 + (b)*0x00000004)
#define NV837D_HEAD_SET_VIEWPORT_POINT_IN_X 14:0
#define NV837D_HEAD_SET_VIEWPORT_POINT_IN_Y 30:16
#define NV837D_HEAD_SET_VIEWPORT_SIZE_IN(a) (0x000008C8 + (a)*0x00000400)
#define NV837D_HEAD_SET_VIEWPORT_SIZE_IN_WIDTH 14:0
#define NV837D_HEAD_SET_VIEWPORT_SIZE_IN_HEIGHT 30:16
#define NV837D_HEAD_SET_VIEWPORT_POINT_OUT_ADJUST(a) (0x000008D4 + (a)*0x00000400)
#define NV837D_HEAD_SET_VIEWPORT_POINT_OUT_ADJUST_X 15:0
#define NV837D_HEAD_SET_VIEWPORT_POINT_OUT_ADJUST_Y 31:16
#define NV837D_HEAD_SET_VIEWPORT_SIZE_OUT(a) (0x000008D8 + (a)*0x00000400)
#define NV837D_HEAD_SET_VIEWPORT_SIZE_OUT_WIDTH 14:0
#define NV837D_HEAD_SET_VIEWPORT_SIZE_OUT_HEIGHT 30:16
#define NV837D_HEAD_SET_VIEWPORT_SIZE_OUT_MIN(a) (0x000008DC + (a)*0x00000400)
#define NV837D_HEAD_SET_VIEWPORT_SIZE_OUT_MIN_WIDTH 14:0
#define NV837D_HEAD_SET_VIEWPORT_SIZE_OUT_MIN_HEIGHT 30:16
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS(a) (0x00000900 + (a)*0x00000400)
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_USABLE 0:0
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_USABLE_FALSE (0x00000000)
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_USABLE_TRUE (0x00000001)
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_PIXEL_DEPTH 11:8
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_PIXEL_DEPTH_BPP_8 (0x00000000)
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_PIXEL_DEPTH_BPP_16 (0x00000001)
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_PIXEL_DEPTH_BPP_32 (0x00000003)
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_PIXEL_DEPTH_BPP_64 (0x00000005)
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_SUPER_SAMPLE 13:12
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_SUPER_SAMPLE_X1_AA (0x00000000)
#define NV837D_HEAD_SET_BASE_CHANNEL_USAGE_BOUNDS_SUPER_SAMPLE_X4_AA (0x00000002)
#define NV837D_HEAD_SET_OVERLAY_USAGE_BOUNDS(a) (0x00000904 + (a)*0x00000400)
#define NV837D_HEAD_SET_OVERLAY_USAGE_BOUNDS_USABLE 0:0
#define NV837D_HEAD_SET_OVERLAY_USAGE_BOUNDS_USABLE_FALSE (0x00000000)
#define NV837D_HEAD_SET_OVERLAY_USAGE_BOUNDS_USABLE_TRUE (0x00000001)
#define NV837D_HEAD_SET_OVERLAY_USAGE_BOUNDS_PIXEL_DEPTH 11:8
#define NV837D_HEAD_SET_OVERLAY_USAGE_BOUNDS_PIXEL_DEPTH_BPP_16 (0x00000001)
#define NV837D_HEAD_SET_OVERLAY_USAGE_BOUNDS_PIXEL_DEPTH_BPP_32 (0x00000003)
#define NV837D_HEAD_SET_PROCESSING(a) (0x00000910 + (a)*0x00000400)
#define NV837D_HEAD_SET_PROCESSING_USE_GAIN_OFS 0:0
#define NV837D_HEAD_SET_PROCESSING_USE_GAIN_OFS_DISABLE (0x00000000)
#define NV837D_HEAD_SET_PROCESSING_USE_GAIN_OFS_ENABLE (0x00000001)
#define NV837D_HEAD_SET_CONVERSION(a) (0x00000914 + (a)*0x00000400)
#define NV837D_HEAD_SET_CONVERSION_GAIN 15:0
#define NV837D_HEAD_SET_CONVERSION_OFS 31:16
#define NV837D_HEAD_SET_SPARE(a) (0x00000BBC + (a)*0x00000400)
#define NV837D_HEAD_SET_SPARE_UNUSED 31:0
#define NV837D_HEAD_SET_SPARE_NOOP(a,b) (0x00000BC0 + (a)*0x00000400 + (b)*0x00000004)
#define NV837D_HEAD_SET_SPARE_NOOP_UNUSED 31:0
#ifdef __cplusplus
}; /* extern "C" */
#endif
#endif // _cl837d_h
|
sunshl/incubator-weex
|
weex_core/Source/include/JavaScriptCore/bytecode/ValueProfile.h
|
/**
* 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.
*/
#pragma once
#include "ConcurrentJSLock.h"
#include "Heap.h"
#include "JSArray.h"
#include "SpeculatedType.h"
#include "Structure.h"
#include "TagRegistersMode.h"
#include "WriteBarrier.h"
#include <wtf/PrintStream.h>
#include <wtf/StringPrintStream.h>
namespace JSC {
template<unsigned numberOfBucketsArgument>
struct ValueProfileBase {
static const unsigned numberOfBuckets = numberOfBucketsArgument;
static const unsigned numberOfSpecFailBuckets = 1;
static const unsigned bucketIndexMask = numberOfBuckets - 1;
static const unsigned totalNumberOfBuckets = numberOfBuckets + numberOfSpecFailBuckets;
ValueProfileBase()
: m_bytecodeOffset(-1)
, m_prediction(SpecNone)
, m_numberOfSamplesInPrediction(0)
{
for (unsigned i = 0; i < totalNumberOfBuckets; ++i)
m_buckets[i] = JSValue::encode(JSValue());
}
ValueProfileBase(int bytecodeOffset)
: m_bytecodeOffset(bytecodeOffset)
, m_prediction(SpecNone)
, m_numberOfSamplesInPrediction(0)
{
for (unsigned i = 0; i < totalNumberOfBuckets; ++i)
m_buckets[i] = JSValue::encode(JSValue());
}
EncodedJSValue* specFailBucket(unsigned i)
{
ASSERT(numberOfBuckets + i < totalNumberOfBuckets);
return m_buckets + numberOfBuckets + i;
}
const ClassInfo* classInfo(unsigned bucket) const
{
#if 1
EncodedJSValue tmp = __atomic_load_n(&m_buckets[bucket], __ATOMIC_RELAXED);
JSValue value = JSValue::decode(tmp);
#else
JSValue value = JSValue::decode(m_buckets[bucket]);
#endif // WTF_ARM_ARCH_VERSION == 7
if (!!value) {
if (!value.isCell())
return 0;
return value.asCell()->structure()->classInfo();
}
return 0;
}
unsigned numberOfSamples() const
{
unsigned result = 0;
for (unsigned i = 0; i < totalNumberOfBuckets; ++i) {
#if 1
EncodedJSValue tmp = __atomic_load_n(&m_buckets[i], __ATOMIC_RELAXED);
JSValue value = JSValue::decode(tmp);
#else
JSValue value = JSValue::decode(m_buckets[i]);
#endif // WTF_ARM_ARCH_VERSION == 7
if (!!value)
result++;
}
return result;
}
unsigned totalNumberOfSamples() const
{
return numberOfSamples() + m_numberOfSamplesInPrediction;
}
bool isLive() const
{
for (unsigned i = 0; i < totalNumberOfBuckets; ++i) {
#if 1
EncodedJSValue tmp = __atomic_load_n(&m_buckets[i], __ATOMIC_RELAXED);
JSValue value = JSValue::decode(tmp);
#else
JSValue value = JSValue::decode(m_buckets[i]);
#endif // WTF_ARM_ARCH_VERSION == 7
if (!!value)
return true;
}
return false;
}
CString briefDescription(const ConcurrentJSLocker& locker)
{
computeUpdatedPrediction(locker);
StringPrintStream out;
out.print("predicting ", SpeculationDump(m_prediction));
return out.toCString();
}
void dump(PrintStream& out)
{
out.print("samples = ", totalNumberOfSamples(), " prediction = ", SpeculationDump(m_prediction));
bool first = true;
for (unsigned i = 0; i < totalNumberOfBuckets; ++i) {
#if 1
EncodedJSValue tmp = __atomic_load_n(&m_buckets[i], __ATOMIC_RELAXED);
JSValue value = JSValue::decode(tmp);
#else
JSValue value = JSValue::decode(m_buckets[i]);
#endif // WTF_ARM_ARCH_VERSION == 7
if (!!value) {
if (first) {
out.printf(": ");
first = false;
} else
out.printf(", ");
out.print(value);
}
}
}
// Updates the prediction and returns the new one. Never call this from any thread
// that isn't executing the code.
SpeculatedType computeUpdatedPrediction(const ConcurrentJSLocker&)
{
for (unsigned i = 0; i < totalNumberOfBuckets; ++i) {
#if 1
EncodedJSValue tmp = __atomic_load_n(&m_buckets[i], __ATOMIC_RELAXED);
JSValue value = JSValue::decode(tmp);
#else
JSValue value = JSValue::decode(m_buckets[i]);
#endif // WTF_ARM_ARCH_VERSION == 7
if (!value)
continue;
m_numberOfSamplesInPrediction++;
mergeSpeculation(m_prediction, speculationFromValue(value));
#if 1
__atomic_store_n(&m_buckets[i], JSValue::encode(JSValue()), __ATOMIC_SEQ_CST);
#else
m_buckets[i] = JSValue::encode(JSValue());
#endif // WTF_ARM_ARCH_VERSION == 7
}
WTF::memoryBarrierBeforeUnlock();
return m_prediction;
}
int m_bytecodeOffset; // -1 for prologue
SpeculatedType m_prediction;
unsigned m_numberOfSamplesInPrediction;
EncodedJSValue m_buckets[totalNumberOfBuckets];
};
struct MinimalValueProfile : public ValueProfileBase<0> {
MinimalValueProfile(): ValueProfileBase<0>() { }
MinimalValueProfile(int bytecodeOffset): ValueProfileBase<0>(bytecodeOffset) { }
};
template<unsigned logNumberOfBucketsArgument>
struct ValueProfileWithLogNumberOfBuckets : public ValueProfileBase<1 << logNumberOfBucketsArgument> {
static const unsigned logNumberOfBuckets = logNumberOfBucketsArgument;
ValueProfileWithLogNumberOfBuckets()
: ValueProfileBase<1 << logNumberOfBucketsArgument>()
{
}
ValueProfileWithLogNumberOfBuckets(int bytecodeOffset)
: ValueProfileBase<1 << logNumberOfBucketsArgument>(bytecodeOffset)
{
}
};
struct ValueProfile : public ValueProfileWithLogNumberOfBuckets<0> {
ValueProfile(): ValueProfileWithLogNumberOfBuckets<0>() { }
ValueProfile(int bytecodeOffset): ValueProfileWithLogNumberOfBuckets<0>(bytecodeOffset) { }
};
template<typename T>
inline int getValueProfileBytecodeOffset(T* valueProfile)
{
return valueProfile->m_bytecodeOffset;
}
// This is a mini value profile to catch pathologies. It is a counter that gets
// incremented when we take the slow path on any instruction.
struct RareCaseProfile {
RareCaseProfile(int bytecodeOffset)
: m_bytecodeOffset(bytecodeOffset)
, m_counter(0)
{
}
int m_bytecodeOffset;
uint32_t m_counter;
};
inline int getRareCaseProfileBytecodeOffset(RareCaseProfile* rareCaseProfile)
{
return rareCaseProfile->m_bytecodeOffset;
}
} // namespace JSC
|
blockchainnativeapplications/framework
|
src/blockchain-native-core/src/main/java/org/blockchainnative/registry/ContractRegistry.java
|
package org.blockchainnative.registry;
import org.blockchainnative.metadata.ContractInfo;
import java.io.IOException;
import java.util.Collection;
/**
* @author <NAME>
*/
public interface ContractRegistry {
@SuppressWarnings("unchecked")
<T extends ContractInfo> T getContractInfo(String contractIdentifier);
void addContractInfo(ContractInfo contractInfo);
void addOrUpdateContractInfo(ContractInfo contractInfo);
void addContractInfoIfNotExisting(ContractInfo contractInfo);
boolean isRegistered(ContractInfo contractInfo);
boolean isRegistered(String contractIdentifier);
Collection<? extends ContractInfo> getContractInfos();
/**
* Saves all {@code ContractInfo} registered with this {@code ContractRegistry}.
* How and where the {@code ContractInfo} objects are stored depends on the concrete implementation.
*
* @throws IOException in case of errors during persisting the contract infos
*/
void persist() throws IOException;
/**
* Loads previously persisted {@code ContractInfo}.
* How and where the {@code ContractInfo} objects are loaded from depends on the concrete implementation.
*
* @throws IOException in case of errors during loading the contract infos
*/
void load() throws IOException;
}
|
srinunagulapalli/server
|
cmd/vela-server/secret.go
|
// Copyright (c) 2022 Target Brands, Inc. All rights reserved.
//
// Use of this source code is governed by the LICENSE file in this repository.
package main
import (
"github.com/go-vela/server/database"
"github.com/go-vela/server/secret"
"github.com/go-vela/types/constants"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
// helper function to setup the secrets engines from the CLI arguments.
func setupSecrets(c *cli.Context, d database.Service) (map[string]secret.Service, error) {
logrus.Debug("Creating secret clients from CLI configuration")
secrets := make(map[string]secret.Service)
// native secret configuration
_native := &secret.Setup{
Driver: constants.DriverNative,
Database: d,
}
// setup the native secret service
//
// https://pkg.go.dev/github.com/go-vela/server/secret?tab=doc#New
native, err := secret.New(_native)
if err != nil {
return nil, err
}
secrets[constants.DriverNative] = native
// check if the vault driver is enabled
if c.Bool("secret.vault.driver") {
// vault secret configuration
_vault := &secret.Setup{
Driver: constants.DriverVault,
Address: c.String("secret.vault.addr"),
AuthMethod: c.String("secret.vault.auth-method"),
AwsRole: c.String("secret.vault.aws-role"),
Prefix: c.String("secret.vault.prefix"),
Token: c.String("secret.vault.token"),
TokenDuration: c.Duration("secret.vault.renewal"),
Version: c.String("secret.vault.version"),
}
// setup the vault secret service
//
// https://pkg.go.dev/github.com/go-vela/server/secret?tab=doc#New
vault, err := secret.New(_vault)
if err != nil {
return nil, err
}
secrets[constants.DriverVault] = vault
}
return secrets, nil
}
|
AsamK/dmix
|
MPDroid/src/main/java/com/namelessdev/mpdroid/helpers/CachedMPD.java
|
<gh_stars>0
/*
* Copyright (C) 2010-2016 The MPDroid 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.namelessdev.mpdroid.helpers;
import com.anpmech.mpd.MPD;
import com.anpmech.mpd.exception.MPDException;
import com.anpmech.mpd.item.Album;
import com.anpmech.mpd.item.AlbumBuilder;
import com.anpmech.mpd.item.Artist;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
/*
* Cached Version of MPD
*
* Certain methods of MPD are overridden to call the cache.
*
* All public methods should call cache.refresh() to see whether the cache is up to date.
*/
public class CachedMPD extends MPD {
private final AlbumCache mCache;
public CachedMPD() {
super();
mCache = AlbumCache.getInstance(this);
}
/**
* Returns the artist name if it's available, blank otherwise.
*
* @param artist The Artist object to extract the artist name from.
* @return The artist name, if it's available, blank otherwise.
*/
private static String getArtistName(final Artist artist) {
final String artistName;
if (artist == null) {
artistName = "";
} else {
artistName = artist.getName();
}
return artistName;
}
/*
* add path info to all albums
*/
/**
* Add detail information to all albums.
*
* @param albums The albums to add detail information to.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
@Override
protected void addAlbumDetails(final List<Album> albums)
throws IOException, MPDException {
final ListIterator<Album> iterator = albums.listIterator();
final AlbumBuilder albumBuilder = new AlbumBuilder();
mCache.refresh();
while (iterator.hasNext()) {
final Album album = iterator.next();
albumBuilder.setAlbum(album);
final Artist artist = album.getArtist();
final String artistName = getArtistName(artist);
final AlbumCache.AlbumDetails details;
details =
mCache.getAlbumDetails(artistName, album.getName(), album.hasAlbumArtist());
if (details != null) {
albumBuilder.setAlbumDetails(details.mNumTracks, details.mTotalTime);
albumBuilder.setLastMod(details.mLastMod);
albumBuilder.setSongDetails(details.mDate, details.mPath);
iterator.set(albumBuilder.build());
}
}
Log.d("MPD CACHED", "Details of " + albums.size());
}
/**
* Adds path information to all album objects in a list.
*
* @param albums List of Album objects to add path information.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
@Override
protected void addAlbumSongDetails(final List<Album> albums) throws IOException, MPDException {
final ListIterator<Album> iterator = albums.listIterator();
final AlbumBuilder albumBuilder = new AlbumBuilder();
mCache.refresh();
while (iterator.hasNext()) {
final Album album = iterator.next();
final Artist artist = album.getArtist();
final String artistName = getArtistName(artist);
final AlbumCache.AlbumDetails details =
mCache.getAlbumDetails(artistName, album.getName(), album.hasAlbumArtist());
if (details != null) {
albumBuilder.setAlbum(album);
albumBuilder.setSongDetails(details.mDate, details.mPath);
iterator.set(albumBuilder.build());
}
}
Log.d("MPD CACHED", "addAlbumSongDetails " + albums.size());
}
/**
* Forced cache refresh.
*/
public void clearCache() {
mCache.refresh(true);
}
/**
* Get all albums.
*
* @return A list of Album objects.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
@Override
public List<Album> getAllAlbums()
throws IOException, MPDException {
final List<Album> allAlbums;
mCache.refresh();
final Set<List<String>> albumListSet = mCache.getUniqueAlbumSet();
if (albumListSet == null) return new ArrayList<>();
final Set<Album> albums = new HashSet<>(albumListSet.size());
final AlbumBuilder albumBuilder = new AlbumBuilder();
for (final List<String> ai : albumListSet) {
final String thirdList = ai.get(2);
albumBuilder.setName(ai.get(0));
if (thirdList != null && thirdList.isEmpty()) { // no album artist
albumBuilder.setArtist(ai.get(1));
} else {
albumBuilder.setAlbumArtist(ai.get(2));
}
albums.add(albumBuilder.build());
}
if (albums.isEmpty()) {
allAlbums = Collections.emptyList();
} else {
allAlbums = new ArrayList<>(albums);
Collections.sort(allAlbums);
addAlbumDetails(allAlbums);
}
return allAlbums;
}
/**
* Gets a list of all album artists in the database.
*
* @param albums List of Album objects to get Album Artists from.
* @return A list of album artists.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
@Override
public List<List<String>> listAlbumArtists(final List<Album> albums)
throws IOException, MPDException {
final List<List<String>> albumArtists = new ArrayList<>(albums.size());
mCache.refresh();
for (final Album album : albums) {
final Artist artist = album.getArtist();
final Set<String> albumArtist;
final String artistName = getArtistName(artist);
albumArtist = mCache.getAlbumArtists(album.getName(), artistName);
albumArtists.add(new ArrayList<>(albumArtist));
}
return albumArtists;
}
/**
* List all albums of given artist from database.
*
* @param artist artist to list albums
* @param useAlbumArtist use AlbumArtist instead of Artist
* @return List of albums.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
@Override
public List<String> listAlbums(final Artist artist, final boolean useAlbumArtist)
throws IOException, MPDException {
mCache.refresh();
return new ArrayList(mCache.getAlbums(artist, useAlbumArtist));
}
}
|
kokeroulis/dagger-reflect
|
reflect/src/main/java/dagger/reflect/UnlinkedSubcomponentBinding.java
|
package dagger.reflect;
import dagger.reflect.Binding.UnlinkedBinding;
final class UnlinkedSubcomponentBinding extends UnlinkedBinding {
static UnlinkedBinding forBuilder(Class<?> builderClass) {
return new UnlinkedSubcomponentBinding(true, builderClass);
}
static UnlinkedBinding forFactory(Class<?> factoryClass) {
return new UnlinkedSubcomponentBinding(false, factoryClass);
}
private final boolean isBuilder;
private final Class<?> cls;
private UnlinkedSubcomponentBinding(boolean isBuilder, Class<?> cls) {
this.isBuilder = isBuilder;
this.cls = cls;
}
@Override
public LinkedBinding<?> link(Linker linker, Scope scope) {
Object factory;
if (isBuilder) {
factory = ComponentBuilderInvocationHandler.forSubcomponentBuilder(cls, scope);
} else {
factory = ComponentFactoryInvocationHandler.forSubcomponentFactory(cls, scope);
}
return new LinkedInstanceBinding<>(factory);
}
}
|
tf-enya/free5gc
|
lib/nas/nasType/NAS_IMEISVRequest_test.go
|
//go:binary-only-package
package nasType_test
import (
"free5gc/lib/nas/nasType"
"testing"
"github.com/stretchr/testify/assert"
)
var SecurityModeCommandIMEISVRequestTypeIeiInput uint8 = 0x0E
func TestNasTypeNewIMEISVRequest(t *testing.T) {}
var nasTypePDUSessionEstablishmentRequestIMEISVRequestTable = []NasTypeIeiData{
{SecurityModeCommandIMEISVRequestTypeIeiInput, 0x0E},
}
func TestNasTypeIMEISVRequestGetSetIei(t *testing.T) {}
type nasTypeIMEISVRequestIMEISVRequestValue struct {
in uint8
out uint8
}
var nasTypeIMEISVRequestIMEISVRequestValueTable = []nasTypeIMEISVRequestIMEISVRequestValue{
{0x07, 0x07},
}
func TestNasTypeIMEISVRequestGetSetIMEISVRequestValue(t *testing.T) {}
type testIMEISVRequestDataTemplate struct {
inIei uint8
inIMEISVRequestValue uint8
outIei uint8
outIMEISVRequestValue uint8
}
var iMEISVRequestTestTable = []testIMEISVRequestDataTemplate{
{SecurityModeCommandIMEISVRequestTypeIeiInput, 0x07,
0x0E, 0x07},
}
func TestNasTypeIMEISVRequest(t *testing.T) {}
|
jj4jj/playground
|
app/ChannelProxyDispatcher.cpp
|
#include "base/stdinc.h"
#include "base/Log.h"
#include "ChannelMsgProxy.h"
#include "channel/ChannelAgent.h"
#include "ChannelProxyDispatcher.h"
#include "channel/ChannelAgentMgr.h"
#if 1
int ChannelProxyMessageDispatcher::DispatchMessage(ChannelAgent & agent , const ChannelMessage & msg)
{
LOG_DEBUG("recv a msg from id = %d msg len = %u",msg.iSrc,msg.dwSize);
//find id msg handler dispatch it.
ChannelMessageDispatcher* handler = proxy->FindHandler(msg.iSrc);
if(!handler)
{
LOG_ERROR("channel id = %d not found handler",msg.iSrc);
return -1;
}
ChannelAgent * pAgent = ChannelAgentMgr::Instance().GetChannel(msg.iSrc);
if(!pAgent)
{
LOG_ERROR("get channel agent error id = %d",msg.iSrc);
return -1;
}
handler->DispatchMessage(*pAgent,msg);
return 0;
}
#endif
|
dnuwa/farm-web
|
src/pages/partners.js
|
import Partners from 'containers/Partners';
export default Partners;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.