code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "stackwindow.h"
#include "debuggeractions.h"
#include "debuggercore.h"
#include "stackhandler.h"
#include <QAction>
#include <QHeaderView>
namespace Debugger {
namespace Internal {
StackTreeView::StackTreeView(QWidget *parent)
: BaseTreeView(parent)
{
setSpanColumn(StackFunctionNameColumn);
}
void StackTreeView::setModel(QAbstractItemModel *model)
{
BaseTreeView::setModel(model);
if (model)
setRootIndex(model->index(0, 0, QModelIndex()));
connect(static_cast<StackHandler*>(model), &StackHandler::stackChanged,
this, [this]() {
if (!m_contentsAdjusted)
adjustForContents();
});
}
void StackTreeView::showAddressColumn(bool on)
{
setColumnHidden(StackAddressColumn, !on);
adjustForContents(true);
}
void StackTreeView::adjustForContents(bool refreshSpan)
{
// Skip resizing if no contents. This will be called again once contents are available.
if (!model() || model()->rowCount() == 0) {
if (refreshSpan)
refreshSpanColumn();
return;
}
// Resize without attempting to fix up the columns.
setSpanColumn(-1);
resizeColumnToContents(StackLevelColumn);
resizeColumnToContents(StackFileNameColumn);
resizeColumnToContents(StackLineNumberColumn);
resizeColumnToContents(StackAddressColumn);
setSpanColumn(StackFunctionNameColumn);
m_contentsAdjusted = true;
}
} // namespace Internal
} // namespace Debugger
|
qtproject/qt-creator
|
src/plugins/debugger/stackwindow.cpp
|
C++
|
gpl-3.0
| 2,664 |
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require("./addCustomer.component"));
//# sourceMappingURL=index.js.map
|
vidyadharteketi/ReportingPortalAngular2
|
src/app/AddCustomer/index.js
|
JavaScript
|
gpl-3.0
| 190 |
#ifndef RIGHT_BUTTON_H
#define RIGHT_BUTTON_H
#include <QPushButton>
//#include "background\msgInterface.h"
#include<QMouseEvent>
class right_button : public QPushButton
{
Q_OBJECT
public:
right_button(QWidget *parent);
~right_button();
void enterEvent(QEvent*);//¹â±ê½øÈëʱ¸ü»»¹â±êÏÔʾ
void leaveEvent(QEvent*);
protected:
void mouseMoveEvent(QMouseEvent *eventwei);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
//msgInterface BG_INTERFACE;
signals:
void told_view_to_shoot();
};
#endif // RIGHT_BUTTON_H
|
billhhh/whLBS
|
Framework/include/Module/right_button.h
|
C
|
gpl-3.0
| 566 |
package it.unibo.mobile.d2dchat.device;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.net.wifi.p2p.WifiP2pManager.GroupInfoListener;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import it.unibo.mobile.d2dchat.Constants;
import it.unibo.mobile.d2dchat.MainActivity;
import it.unibo.mobile.d2dchat.infoReport.InfoMessage;
import it.unibo.mobile.d2dchat.messagesManager.Message;
import it.unibo.mobile.d2dchat.network.wifidirect.WiFiDirectBroadcastReceiver;
//Deve gestire il device, dovrà fare da intermediario tra la rete e l'activity. Gran parte del codice dell'activity andrà qui
public class DeviceManager extends Thread implements PeerListListener, ConnectionInfoListener, GroupInfoListener {
private int deviceStatus = Constants.DEVICE_INIT;
private WifiP2pManager wifiP2pManager;
private Channel channel;
private WiFiDirectBroadcastReceiver wiFiDirectBroadcastReceiver;
private MainActivity mainActivity;
private String deviceName;
private String groupOwnerMacAddress;
private List<WifiP2pDevice> peers;
private WifiP2pInfo info;
public boolean keepRunning = true;
public String deviceAddress;
public InfoMessage infoMessage;
public boolean isGO;
public ArrayList<WifiP2pDevice> GOlist;
public boolean firstDiscovery = true;
public boolean switching = false;
public String currentDest = null;
public int currentGO = 0;
public int timeInterval = 10000;
private Timer timer = new Timer();
public Peer peer;
private static final String TAG = "DeviceManager";
public WiFiDirectBroadcastReceiver getWiFiDirectBroadcastReceiver() {
return wiFiDirectBroadcastReceiver;
}
public String getGroupOwnerMacAddress() {
return groupOwnerMacAddress;
}
public WifiP2pInfo getInfo() {
return info;
}
// peers getter and setter
public List<WifiP2pDevice> getPeers() {
return peers;
}
public void setPeers(List<WifiP2pDevice> peers) {
this.peers = peers;
}
public class ActionListenerDiscoverPeers implements ActionListener {
//La discovery dei peers ha avuto successo, tecnicamente non serve a niente perchè ci avvertirà la callback onPeersAvailable
@Override
public void onSuccess() {
Log.i(TAG, "Discovery peer con successo");
deviceStatus = Constants.DEVICE_DISCOVERY;
}
//La discovery dei peers non ha avuto successo, che facciamo?
@Override
public void onFailure(int i) {
Log.e(TAG, "Errore nella discovery peer, codice: " + i);
}
}
public DeviceManager(WifiP2pManager wifiP2pManager, Channel channel, MainActivity mainActivity, InfoMessage infoMessage) {
this.channel = channel;
this.wifiP2pManager = wifiP2pManager;
this.mainActivity = mainActivity;
this.peers = new ArrayList<WifiP2pDevice>();
this.infoMessage = infoMessage;
wiFiDirectBroadcastReceiver = new WiFiDirectBroadcastReceiver(wifiP2pManager, channel, this);
Log.d(TAG, "Costruttore devicemanager");
wifiP2pManager.discoverPeers(channel, new ActionListenerDiscoverPeers());
}
@Override
public synchronized void run() {
while (keepRunning) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
// Called on activity destruction
public void stopManager() {
deviceStatus = Constants.DEVICE_INIT;
//peer.nextAction.setAction(Peer.Action.disconnect);
//peer.semaphore.release();
wifiP2pManager.removeGroup(channel, null);
}
//Lo stato del wifi è cambiato, active == true wifi attivo (e viceversa)
public void wifiState(boolean active) {
Log.d(TAG, "Stato del wifi cambiato: " + active);
if (active) {
switch (deviceStatus) {
case Constants.DEVICE_INIT:
case Constants.DEVICE_NOWIFI://non ha senso
wifiP2pManager.discoverPeers(channel, new ActionListenerDiscoverPeers());
//Supponiamo che siamo già nella schermata principale poichè i due stati del case dovrebbero già essere gestiti
break;
}
} else {
deviceStatus = Constants.DEVICE_NOWIFI;
wifiP2pManager.stopPeerDiscovery(channel, null); //non ci interessa la callback sulla stop discovery, forse
//TODO: Avvisiamo la'ctivity che non c'è più connessione
}
}
@Override
//E' successo qualcosa nei vicini (nuovi vicini, vecchi vicini andati, etc..), non si parla di gruppo
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
Log.d(TAG, "onPeersAvailable()");
//Ci interessa solo se siamo in discovery, così aggiorniamo la lista . Se siamo connessi starà agli altri connettersi al gruppo
if (deviceStatus == Constants.DEVICE_DISCOVERY) {
peers.clear();
peers.addAll(wifiP2pDeviceList.getDeviceList());
mainActivity.updatePeers();
if (switching) {
switching = false;
switchGO();
}
}
}
@Override
//Sono disponibili informazioni sulla connessione (siamo in un gruppo), probabilmente ci siamo connessi
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
Log.d(TAG, "onConnectionInfoAvailable()");
this.info = wifiP2pInfo;
// if (deviceStatus != Constants.DEVICE_CONNECTED) {
deviceStatus = Constants.DEVICE_CONNECTED;
boolean creation = true;
if (peer != null)
creation = false;
if (wifiP2pInfo.isGroupOwner) {
isGO = true;
if (creation) {
peer = new GroupOwner(this);
}
else {
//perform onConnect()
peer.onConnect();
}
// send data to a client in the list (the only one in our test scenario)
// for (WifiP2pDevice device : peers) {
// if (!device.isGroupOwner())
// currentDest = device.deviceAddress;
// }
} else { // Client
if (creation) {
peer = new Client(this);
}
peer.onConnect();
// currentDest = wifiP2pInfo.groupOwnerAddress.getHostAddress();
}
//TODO: verify that one thread is enough
//((Thread) (peer)).start();
wifiP2pManager.requestGroupInfo(channel, this);
//}
}
@Override
//Riceviamo le informazioni sul gruppo
public void onGroupInfoAvailable(WifiP2pGroup wifiP2pGroup) {
Log.d(TAG, "onGroupInfoAvailable()");
List<WifiP2pDevice> devices = new ArrayList<>();
devices.addAll(wifiP2pGroup.getClientList());
//Il GO sembra che non appare nella lista dei client.
//Naturalmente lo aggiungiamo solo se non siamo GO (non abbiamo noi stessi nella lista del gruppo)
if (!isGO) {
devices.add(wifiP2pGroup.getOwner());
}
groupOwnerMacAddress = wifiP2pGroup.getOwner().deviceAddress;
//Gli apaprtenenti al gruppo sono cambiati, aggiorniamo
mainActivity.setGroupPeers(devices);
}
//l'opposto di quello sopra, la chiamiamo quando si è registrato un cambio alla connessione ma non siamo connessi
public void onConnectionInfoNotAvailable() {
if (deviceStatus == Constants.DEVICE_CONNECTED) {
//Non siamo più nel gruppo, ricominciamo la discovery
deviceStatus = Constants.DEVICE_INIT;
wifiP2pManager.discoverPeers(channel, new ActionListenerDiscoverPeers());
mainActivity.updateDevice();
}
}
//E' cambiato lo stato del nostro device
public void updateDevice(WifiP2pDevice device) {
//Aggiorniamo o, se è la prima volta, salviamo il nome del device
if (deviceName == null || !deviceName.equals(device.deviceName))
deviceName = device.deviceName;
deviceAddress = device.deviceAddress;
}
public String getDeviceName() {
return deviceName;
}
public int getDeviceStatus() {
return deviceStatus;
}
public void connectTo(final WifiP2pDevice device) {
Log.d(TAG, "Ci proviamo a connettere ad un device");
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
wifiP2pManager.connect(channel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.d(TAG, "["+device.deviceName+"]Connessione riuscita");
}
@Override
public void onFailure(int reason) {
Log.d(TAG, "["+device.deviceName+"]Connessione non riuscita, codice: " + reason);
connectTo(device);
}
});
}
public void createGroup (){
Log.d(TAG, "Mi dichiaro GO");
wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.d(TAG, "Creazione riuscita");
}
@Override
public void onFailure(int reason) {
Log.d(TAG, "Creazione non riuscita, codice: " + reason);
}
});
}
public void startPingPongProcedure (){
Log.d(TAG, "Fase di ping pong iniziata");
GOlist = new ArrayList<WifiP2pDevice>();
for (WifiP2pDevice peer: peers) {
if(peer.isGroupOwner() && (peer.deviceName.equals("Nexus4") || peer.deviceName.equals("Elephone") || peer.deviceName.equals("N5") || peer.deviceName.equals("JPIS") ||peer.deviceName.equals("Mi4c") )) {
GOlist.add(peer);
}
}
switchGO();
}
public void switchGO() {
if(deviceStatus==Constants.DEVICE_CONNECTED) {
((Client)peer).keepSending = false; // stop sending queued messages
peer.initiateDisconnection(); // message exchange to stop GO from sending
}
else {
if (GOlist.size()>1)
currentGO = (currentGO + 1) % GOlist.size();
Log.d(TAG, "switch verso: " + GOlist.get(currentGO).deviceName);
groupOwnerMacAddress = GOlist.get(currentGO).deviceAddress;
connectTo(GOlist.get(currentGO));
}
}
public void scheduleSwitchGO() {
timer.schedule(new TimerTask() {
@Override
public void run() {
switchGO();
}
}, timeInterval);
}
public void discover() {
wifiP2pManager.discoverPeers(channel, new ActionListenerDiscoverPeers());
}
public void disconnect() {
Log.d(TAG, "Disconnecting from group.");
wifiP2pManager.removeGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess(){
deviceStatus = Constants.DEVICE_DISCONNECTED;
}
@Override
public void onFailure(int reason) {
Log.d(TAG, "Disconnect non riuscita, codice: " + reason);
}
});
}
}
|
ghosty89/WiFiMultiHop
|
app/src/main/java/it/unibo/mobile/d2dchat/device/DeviceManager.java
|
Java
|
gpl-3.0
| 12,060 |
<!--
Silly flexbox hack brought to you by
http://stackoverflow.com/questions/18744164/flex-box-align-last-row-to-grid
-->
<template name="gridPadding">
{{#each list}}
<div class={{../class}} style="height: 0; margin-top: 0; margin-bottom: 0;"></div>
{{/each}}
</template>
|
englishkiwi/dc-test-1
|
client/views/paperTemplates/gridPadding/gridPadding.html
|
HTML
|
gpl-3.0
| 277 |
<?php
/**
* @project Hesper Framework
* @author Alex Gorbylev
* @originally onPHP Framework
* @originator Ivan Y. Khvostishkov
*/
namespace Hesper\Core\Form\Primitive;
use Hesper\Core\Exception\WrongArgumentException;
/**
* Class PrimitiveHttpUrl
* @package Hesper\Core\Form\Primitive
*/
final class PrimitiveHttpUrl extends PrimitiveString {
private $checkPrivilegedPorts = false;
public function setCheckPrivilegedPorts($check = true) {
$this->checkPrivilegedPorts = $check ? true : false;
return $this;
}
public function import($scope) {
if (!$result = parent::import($scope)) {
return $result;
}
try {
$this->value = HttpUrl::create()
->parse($this->value)
->setCheckPrivilegedPorts($this->checkPrivilegedPorts);
} catch (WrongArgumentException $e) {
$this->value = null;
return false;
}
if (!$this->value->isValid()) {
$this->value = null;
return false;
}
$this->value->normalize();
return true;
}
public function importValue($value) {
if ($value instanceof HttpUrl) {
return $this->import([$this->getName() => $value->toString()]);
} elseif (is_scalar($value)) {
return parent::importValue($value);
}
return parent::importValue(null);
}
public function exportValue() {
if (!$this->value) {
return null;
}
return $this->value->toString();
}
}
|
avid/hesper
|
src/Core/Form/Primitive/PrimitiveHttpUrl.php
|
PHP
|
gpl-3.0
| 1,402 |
/**
* window - jQuery EasyUI
*
* Licensed under the GPL terms
* To use it on other terms please contact us
*
* Copyright(c) 2009-2012 stworthy [ [email protected] ]
*
* Dependencies:
* panel
* draggable
* resizable
*
*/
(function($){
function setSize(target, param){
var opts = $.data(target, 'window').options;
if (param){
if (param.width) opts.width = param.width;
if (param.height) opts.height = param.height;
if (param.left != null) opts.left = param.left;
if (param.top != null) opts.top = param.top;
}
$(target).panel('resize', opts);
}
function moveWindow(target, param){
var state = $.data(target, 'window');
if (param){
if (param.left != null) state.options.left = param.left;
if (param.top != null) state.options.top = param.top;
}
$(target).panel('move', state.options);
if (state.shadow){
state.shadow.css({
left: state.options.left,
top: state.options.top
});
}
}
/**
* center the window only horizontally
*/
function hcenter(target, tomove){
var state = $.data(target, 'window');
var opts = state.options;
var width = opts.width;
if (isNaN(width)){
width = state.window._outerWidth();
}
if (opts.inline){
var parent = state.window.parent();
opts.left = (parent.width() - width) / 2 + parent.scrollLeft();
} else {
opts.left = ($(window)._outerWidth() - width) / 2 + $(document).scrollLeft();
}
if (tomove){moveWindow(target);}
}
/**
* center the window only vertically
*/
function vcenter(target, tomove){
var state = $.data(target, 'window');
var opts = state.options;
var height = opts.height;
if (isNaN(height)){
height = state.window._outerHeight();
}
if (opts.inline){
var parent = state.window.parent();
opts.top = (parent.height() - height) / 2 + parent.scrollTop();
} else {
opts.top = ($(window)._outerHeight() - height) / 2 + $(document).scrollTop();
}
if (tomove){moveWindow(target);}
}
function create(target){
var state = $.data(target, 'window');
var win = $(target).panel($.extend({}, state.options, {
border: false,
doSize: true, // size the panel, the property undefined in window component
closed: true, // close the panel
cls: 'window',
headerCls: 'window-header',
bodyCls: 'window-body ' + (state.options.noheader ? 'window-body-noheader' : ''),
onBeforeDestroy: function(){
if (state.options.onBeforeDestroy.call(target) == false) return false;
if (state.shadow) state.shadow.remove();
if (state.mask) state.mask.remove();
},
onClose: function(){
if (state.shadow) state.shadow.hide();
if (state.mask) state.mask.hide();
state.options.onClose.call(target);
},
onOpen: function(){
if (state.mask){
state.mask.css({
display:'block',
zIndex: $.fn.window.defaults.zIndex++
});
}
if (state.shadow){
state.shadow.css({
display:'block',
zIndex: $.fn.window.defaults.zIndex++,
left: state.options.left,
top: state.options.top,
width: state.window._outerWidth(),
height: state.window._outerHeight()
});
}
state.window.css('z-index', $.fn.window.defaults.zIndex++);
state.options.onOpen.call(target);
},
onResize: function(width, height){
var opts = $(this).panel('options');
$.extend(state.options, {
width: opts.width,
height: opts.height,
left: opts.left,
top: opts.top
});
if (state.shadow){
state.shadow.css({
left: state.options.left,
top: state.options.top,
width: state.window._outerWidth(),
height: state.window._outerHeight()
});
}
state.options.onResize.call(target, width, height);
},
onMinimize: function(){
if (state.shadow) state.shadow.hide();
if (state.mask) state.mask.hide();
state.options.onMinimize.call(target);
},
onBeforeCollapse: function(){
if (state.options.onBeforeCollapse.call(target) == false) return false;
if (state.shadow) state.shadow.hide();
},
onExpand: function(){
if (state.shadow) state.shadow.show();
state.options.onExpand.call(target);
}
}));
state.window = win.panel('panel');
// create mask
if (state.mask) state.mask.remove();
if (state.options.modal == true){
state.mask = $('<div class="window-mask"></div>').insertAfter(state.window);
state.mask.css({
width: (state.options.inline ? state.mask.parent().width() : getPageArea().width),
height: (state.options.inline ? state.mask.parent().height() : getPageArea().height),
display: 'none'
});
}
// create shadow
if (state.shadow) state.shadow.remove();
if (state.options.shadow == true){
state.shadow = $('<div class="window-shadow"></div>').insertAfter(state.window);
state.shadow.css({
display: 'none'
});
}
// if require center the window
if (state.options.left == null){hcenter(target);}
if (state.options.top == null){vcenter(target);}
moveWindow(target);
if (state.options.closed == false){
win.window('open'); // open the window
}
}
/**
* set window drag and resize property
*/
function setProperties(target){
var state = $.data(target, 'window');
state.window.draggable({
handle: '>div.panel-header>div.panel-title',
disabled: state.options.draggable == false,
onStartDrag: function(e){
if (state.mask) state.mask.css('z-index', $.fn.window.defaults.zIndex++);
if (state.shadow) state.shadow.css('z-index', $.fn.window.defaults.zIndex++);
state.window.css('z-index', $.fn.window.defaults.zIndex++);
if (!state.proxy){
state.proxy = $('<div class="window-proxy"></div>').insertAfter(state.window);
}
state.proxy.css({
display:'none',
zIndex: $.fn.window.defaults.zIndex++,
left: e.data.left,
top: e.data.top
});
state.proxy._outerWidth(state.window._outerWidth());
state.proxy._outerHeight(state.window._outerHeight());
setTimeout(function(){
if (state.proxy) state.proxy.show();
}, 500);
},
onDrag: function(e){
state.proxy.css({
display:'block',
left: e.data.left,
top: e.data.top
});
return false;
},
onStopDrag: function(e){
state.options.left = e.data.left;
state.options.top = e.data.top;
$(target).window('move');
state.proxy.remove();
state.proxy = null;
}
});
state.window.resizable({
disabled: state.options.resizable == false,
onStartResize:function(e){
state.pmask = $('<div class="window-proxy-mask"></div>').insertAfter(state.window);
state.pmask.css({
zIndex: $.fn.window.defaults.zIndex++,
left: e.data.left,
top: e.data.top,
width: state.window._outerWidth(),
height: state.window._outerHeight()
});
if (!state.proxy){
state.proxy = $('<div class="window-proxy"></div>').insertAfter(state.window);
}
state.proxy.css({
zIndex: $.fn.window.defaults.zIndex++,
left: e.data.left,
top: e.data.top
});
state.proxy._outerWidth(e.data.width);
state.proxy._outerHeight(e.data.height);
},
onResize: function(e){
state.proxy.css({
left: e.data.left,
top: e.data.top
});
state.proxy._outerWidth(e.data.width);
state.proxy._outerHeight(e.data.height);
return false;
},
onStopResize: function(e){
$.extend(state.options, {
left: e.data.left,
top: e.data.top,
width: e.data.width,
height: e.data.height
});
setSize(target);
state.pmask.remove();
state.pmask = null;
state.proxy.remove();
state.proxy = null;
}
});
}
function getPageArea() {
if (document.compatMode == 'BackCompat') {
return {
width: Math.max(document.body.scrollWidth, document.body.clientWidth),
height: Math.max(document.body.scrollHeight, document.body.clientHeight)
}
} else {
return {
width: Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth),
height: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight)
}
}
}
// when window resize, reset the width and height of the window's mask
$(window).resize(function(){
$('body>div.window-mask').css({
width: $(window)._outerWidth(),
height: $(window)._outerHeight()
});
setTimeout(function(){
$('body>div.window-mask').css({
width: getPageArea().width,
height: getPageArea().height
});
}, 50);
});
$.fn.window = function(options, param){
if (typeof options == 'string'){
var method = $.fn.window.methods[options];
if (method){
return method(this, param);
} else {
return this.panel(options, param);
}
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'window');
if (state){
$.extend(state.options, options);
} else {
state = $.data(this, 'window', {
options: $.extend({}, $.fn.window.defaults, $.fn.window.parseOptions(this), options)
});
if (!state.options.inline){
// $(this).appendTo('body');
document.body.appendChild(this);
}
}
create(this);
setProperties(this);
});
};
$.fn.window.methods = {
options: function(jq){
var popts = jq.panel('options');
var wopts = $.data(jq[0], 'window').options;
return $.extend(wopts, {
closed: popts.closed,
collapsed: popts.collapsed,
minimized: popts.minimized,
maximized: popts.maximized
});
},
window: function(jq){
return $.data(jq[0], 'window').window;
},
resize: function(jq, param){
return jq.each(function(){
setSize(this, param);
});
},
move: function(jq, param){
return jq.each(function(){
moveWindow(this, param);
});
},
hcenter: function(jq){
return jq.each(function(){
hcenter(this, true);
});
},
vcenter: function(jq){
return jq.each(function(){
vcenter(this, true);
});
},
center: function(jq){
return jq.each(function(){
hcenter(this);
vcenter(this);
moveWindow(this);
});
}
};
$.fn.window.parseOptions = function(target){
return $.extend({}, $.fn.panel.parseOptions(target), $.parser.parseOptions(target, [
{draggable:'boolean',resizable:'boolean',shadow:'boolean',modal:'boolean',inline:'boolean'}
]));
};
// Inherited from $.fn.panel.defaults
$.fn.window.defaults = $.extend({}, $.fn.panel.defaults, {
zIndex: 9000,
draggable: true,
resizable: true,
shadow: true,
modal: false,
inline: false, // true to stay inside its parent, false to go on top of all elements
// window's property which difference from panel
title: 'New Window',
collapsible: true,
minimizable: true,
maximizable: true,
closable: true,
closed: false
});
})(jQuery);
|
hanupas/bpiw-sinkronisasi
|
siperencanaan/easyui/src/jquery.window.js
|
JavaScript
|
gpl-3.0
| 10,781 |
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-beta-xr_w32_bld-00000000/build/xpfe/components/windowds/nsIWindowDataSource.idl
*/
#ifndef __gen_nsIWindowDataSource_h__
#define __gen_nsIWindowDataSource_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
#ifndef __gen_nsIDOMWindow_h__
#include "nsIDOMWindow.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIWindowDataSource */
#define NS_IWINDOWDATASOURCE_IID_STR "3722a5b9-5323-4ed0-bb1a-8299f27a4e89"
#define NS_IWINDOWDATASOURCE_IID \
{0x3722a5b9, 0x5323, 0x4ed0, \
{ 0xbb, 0x1a, 0x82, 0x99, 0xf2, 0x7a, 0x4e, 0x89 }}
class NS_NO_VTABLE nsIWindowDataSource : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IWINDOWDATASOURCE_IID)
/* nsIDOMWindow getWindowForResource (in string inResource); */
NS_IMETHOD GetWindowForResource(const char * inResource, nsIDOMWindow * *_retval) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIWindowDataSource, NS_IWINDOWDATASOURCE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIWINDOWDATASOURCE \
NS_IMETHOD GetWindowForResource(const char * inResource, nsIDOMWindow * *_retval);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIWINDOWDATASOURCE(_to) \
NS_IMETHOD GetWindowForResource(const char * inResource, nsIDOMWindow * *_retval) { return _to GetWindowForResource(inResource, _retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIWINDOWDATASOURCE(_to) \
NS_IMETHOD GetWindowForResource(const char * inResource, nsIDOMWindow * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetWindowForResource(inResource, _retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsWindowDataSource : public nsIWindowDataSource
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIWINDOWDATASOURCE
nsWindowDataSource();
private:
~nsWindowDataSource();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsWindowDataSource, nsIWindowDataSource)
nsWindowDataSource::nsWindowDataSource()
{
/* member initializers and constructor code */
}
nsWindowDataSource::~nsWindowDataSource()
{
/* destructor code */
}
/* nsIDOMWindow getWindowForResource (in string inResource); */
NS_IMETHODIMP nsWindowDataSource::GetWindowForResource(const char * inResource, nsIDOMWindow * *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIWindowDataSource_h__ */
|
DragonZX/fdm
|
Gecko.SDK/22/include/nsIWindowDataSource.h
|
C
|
gpl-3.0
| 2,929 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include <QObject>
namespace CppEditor { namespace Tests { class TemporaryCopiedDir; } }
namespace ProjectExplorer { class Kit; }
namespace Autotest {
class TestTreeModel;
namespace Internal {
class AutoTestUnitTests : public QObject
{
Q_OBJECT
public:
explicit AutoTestUnitTests(TestTreeModel *model, QObject *parent = nullptr);
signals:
private slots:
void initTestCase();
void cleanupTestCase();
void testCodeParser();
void testCodeParser_data();
void testCodeParserSwitchStartup();
void testCodeParserSwitchStartup_data();
void testCodeParserGTest();
void testCodeParserGTest_data();
void testCodeParserBoostTest();
void testCodeParserBoostTest_data();
void testStringTable();
void testModelManagerInterface();
private:
TestTreeModel *m_model = nullptr;
CppEditor::Tests::TemporaryCopiedDir *m_tmpDir = nullptr;
bool m_isQt4 = false;
bool m_checkBoost = false;
ProjectExplorer::Kit *m_kit = nullptr;
};
} // namespace Internal
} // namespace Autotest
|
qtproject/qt-creator
|
src/plugins/autotest/autotestunittests.h
|
C
|
gpl-3.0
| 2,248 |
<?php
App::uses('GalleriesAppModel', 'Galleries.Model');
/**
* Gallery Image Model Class
*
* @todo Add more documentation
*/
class GalleryImage extends GalleriesAppModel {
/**
* var string
*/
public $name = 'GalleryImage';
/**
* var string
*/
public $displayField = 'filename';
/**
* var string
*/
public $rootPath = '';
//The Associations below have been created with all possible keys, those that are not needed can be removed
public $belongsTo = array(
'Gallery' => array(
'className' => 'Galleries.Gallery',
'foreignKey' => 'gallery_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Creator' => array(
'className' => 'Users.User',
'foreignKey' => 'creator_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Modifier' => array(
'className' => 'Users.User',
'foreignKey' => 'modifier_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public function __construct($id = false, $table = null, $ds = null) {
if (defined('__APP_LOAD_APP_BEHAVIORS') && $behaviors = @unserialize(__APP_LOAD_APP_BEHAVIORS)) {
if (!empty($behaviors[$this->name])) {
$this->actsAs[] = $behaviors[$this->name];
}
}
$this->rootPath = ROOT . DS . SITE_DIR . DS . 'Locale'.DS.'View' . DS . 'webroot';
parent::__construct($id, $table, $ds);
}
/**
* Afterfind callback
*/
public function afterFind($results, $primary = false) {
$results = $this->_videoOutput($results);
return $results;
}
/**
* Video output
* parse video output data
*
* @todo support youtube video urls better and easier (eg, parse multiple versions of the embed url to get the id)
* @todo support non-youtube videos too
*/
protected function _videoOutput($galleryImages) {
if (!empty($galleryImages)) {
// only handles YouTube right now
for ($i = 0; $i < count($galleryImages); $i++) {
// special video case
if ($galleryImages[$i][$this->alias]['mimetype'] == 'video') {
$url = explode('/', $galleryImages[$i][$this->alias]['filename']);
$youtubeId = end($url);
$galleryImages[$i][$this->alias]['_thumb'] = 'http://img.youtube.com/vi/' . $youtubeId . '/0.jpg';
$galleryImages[$i][$this->alias]['_embed'] = '//www.youtube.com/embed/' . $youtubeId;
}
}
}
return $galleryImages;
}
/**
* After save method
*
* @param bool
*/
public function afterSave($created, $options = array()) {
if (!empty($this->data['GalleryImage']['is_thumb'])) {
try {
$data['Gallery']['id'] = $this->data['GalleryImage']['gallery_id'];
$data['GalleryImage']['id'] = $this->data['GalleryImage']['id'];
$this->Gallery->makeThumb($data);
return true;
} catch (Exception $e) {
throw new Exception(__d('galleries', 'Gallery thumb update failed : ' . $e->getMessage(), true));
}
}
}
/**
* Add method
*
* @access public
* @param array $data
* @param string $uploadFieldName
* @return boolean
* @throws Exception
*/
public function add($data, $uploadFieldName) {
$data = $this->_cleanData($data);
if (isset($data['GalleryImage']['filename'][0]) && is_array($data['GalleryImage']['filename'])) {
try {
$image = $data;
foreach ($data['GalleryImage']['filename'] as $f) {
$image['GalleryImage']['filename'] = $this->_fileName($f);
$this->_add($image, $uploadFieldName);
}
return true;
} catch(Exception $e) {
throw new Exception($e->getMessage());
}
} else {
try {
return $this->_add($data, $uploadFieldName);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
}
/**
* Protected add method
*
* If a gallery id is given, check the defaults, attach the upload behavior, and perform the upload.
* If no gallery id is given, create a gallery first using site settings, and make the submitted image the th
* The gallery add() function calls back to this function to perform the upload.
*
* This protected version of the add function was pushed down so that it could be called multiple times.
*
* @access protected
* @param array
* @param string
* @return bool
*/
protected function _add($data, $uploadFieldName) {
$data = $this->checkForGallery($data);
if (!empty($data['GalleryImage']['gallery_id'])) {
if ($data['GalleryImage']['mimetype'] == 'video') {
// special "video" keyword case where we just save the image data because its a video
return $this->save($data);
} else if (!empty($data['GalleryImage'][$uploadFieldName])) {
// existing gallery and image submitted
$uploadOptions[$uploadFieldName] = $this->_getImageOptions($data);
$this->Behaviors->attach('Galleries.MeioUpload', $uploadOptions);
$this->create();
if ($this->save($data)) {
return true;
} else {
throw new Exception(__('ERROR : %s', ZuhaInflector::flatten($this->invalidFields())));
}
} else {
// just saving an existing gallery
if ($this->Gallery->save($data)) {
return true;
} else {
throw new Exception(__d('galleries', 'ERROR : Gallery save failed.', true));
}
}
} else {
// new gallery
if ( $this->Gallery->add($data, $uploadFieldName) ) {
return true;
} else {
throw new Exception(__d('galleries', 'ERROR : Gallery add failed.', true));
}
}
}
/**
* Check for Gallery
* Used to fill in the gallery id, if it exists
*
* NOTE : Use $data['Gallery']['create'] = 1, and an empty GalleryImage.gallery_id to force a creation
* @param array $data
* @return array
*/
public function checkForGallery($data) {
if (empty($data['Gallery']['create']) && empty($data['GalleryImage']['gallery_id']) && (!empty($data['Gallery']['model']) && !empty($data['Gallery']['foreign_key']))) {
$gallery = $this->Gallery->find('first', array('conditions' => array('Gallery.model' => $data['Gallery']['model'], 'Gallery.foreign_key' => $data['Gallery']['foreign_key'])));
if (!empty($gallery)) {
$data['GalleryImage']['gallery_id'] = $gallery['Gallery']['id'];
$data['Gallery']['id'] = $gallery['Gallery']['id'];
}
}
return $data;
}
/**
* Clean data method
*
* Used to standardize data before creating or editing a gallery
*
* @access protected
* @param array
* @return array
*/
protected function _cleanData($data) {
if (empty($data['GalleryImage']['gallery_id']) && !empty($data['GalleryImage']['model']) && !empty($data['GalleryImage']['foreign_key'])) {
$gallery = $this->Gallery->find('first', array(
'conditions' => array(
'Gallery.model' => $data['GalleryImage']['model'],
'Gallery.foreign_key' => $data['GalleryImage']['foreign_key'],
),
));
if (!empty($gallery)) {
$data['GalleryImage']['gallery_id'] = $gallery['Gallery']['id'];
}
}
if (!empty($data['GalleryImage']['serverfile'])) {
if (!empty($data['GalleryImage']['filename']['name'])) {
$filename = $data['GalleryImage']['filename'];
unset($data['GalleryImage']['filename']);
$data['GalleryImage']['filename'][] = $filename;
} else {
unset($data['GalleryImage']['filename']);
}
$serverFiles = explode(',', $data['GalleryImage']['serverfile']);
foreach ($serverFiles as $serverFile) {
if (!empty($serverFile)) {
$data['GalleryImage']['filename'][] = array(
'tmp_name' => array(
'_bypassUploadFileCheck',
$serverFile,
),
);
}
}
}
return $data;
}
/**
* Filename method
*
* Fill out the filename array as though it was a submitted file when it was really an existing file on the server.
*
* @param string
*/
protected function _fileName($fileName) {
if (isset($fileName['tmp_name']) && is_array($fileName['tmp_name'])) {
App::uses('File', 'Utility');
$fileName['tmp_name'][1] = $this->rootPath . ZuhaSet::webrootSubPath($fileName['tmp_name'][1]);
$File = new File($fileName['tmp_name'][1]);
$file = $File->info(); // get the file info (basename, extension, from Cake File class)
$file['type'] = $file['extension'] == 'jpg' ? 'image/jpeg' : 'image/' . $file['extension'];
return $fileName = array(
'name' => $file['basename'],
'type' => $file['type'],
'tmp_name' => $fileName['tmp_name'],
'error' => 0,
'size' => $file['filesize'],
);
} else {
return $fileName;
}
}
/**
* Set Gallery Image Defaults
*
* In conjunction with the _getImageOptions function, we
* run through the various places where thumbnail sizes can be set to establish the correct size.
* This one uses the submitted form options if they exist if not we send it to the Image
* _galleryImageDefaults function
*
* @param {array} data array of the gallery image
*/
private function _getImageOptions($data) {
if (!empty($data['UploadOptions'])) {
// ex. array('filename' => array('thumbsizes' => array('small' => array('width' => 50, 'height' => 50))));
// if you name one, you must name them all with this function
$uploadOptions = $data['UploadOptions'];
} else {
// ex. array('filename' => array('thumbsizes' => array('small' => array('width' => 50, 'height' => 50))));
$uploadOptions = $this->galleryImageDefaults($data);
}
return $uploadOptions;
}
/**
* Set Gallery Image Defaults
*
* In conjunction with the _getImageOptions function, we
* run through the various places where thumbnail sizes can be set to establish the correct size.
* The order is... from the form submitting first using the _getImageOptions function
* then from the gallery defaults, then from system settings, and lastly defaults hard coded in the model.
*
* @param {array} data array of the gallery image
* @return {array} returns the updated data array
*/
public function galleryImageDefaults($data = null) {
$uploadOptions['thumbsizes']['medium']['width'] = $this->mediumImageWidth;
$uploadOptions['thumbsizes']['medium']['height'] = $this->mediumImageHeight;
$uploadOptions['thumbsizes']['small']['width'] = $this->smallImageWidth;
$uploadOptions['thumbsizes']['small']['height'] = $this->smallImageHeight;
$uploadOptions['thumbsizes']['large']['width'] = $this->largeImageWidth;
$uploadOptions['thumbsizes']['large']['height'] = $this->largeImageHeight;
return array_merge($data, $uploadOptions);
}
/**
* Delete method
*
* Delete both the record and the file on the server
*
* @access public
* @param string
* @return bool
*/
public function delete($id = null, $cascade = true) {
$this->id = $id;
if (!$this->exists()) {
throw new Exception(__('Invalid file'));
}
$image = $this->read(null, $id);
$fileName = $image['GalleryImage']['filename'];
$file = $this->rootPath . ZuhaSet::webrootSubPath($image['GalleryImage']['dir']) . $fileName;
if (parent::delete($id)) {
if ( file_exists($file) && is_file($file) ) {
unlink($file); // delete the largest file
}
$small = str_replace($fileName, 'thumb' . DS . 'small' . DS . $fileName, $file);
if ( file_exists($small) && is_file($small) ) {
unlink($small); // delete the small thumb
}
$medium = str_replace($fileName, 'thumb' . DS . 'medium' . DS . $fileName, $file);
if ( file_exists($medium) && is_file($medium) ) {
unlink($medium); // delete the medium thumb
}
$large = str_replace($fileName, 'thumb' . DS . 'large' . DS . $fileName, $file);
if ( file_exists($large) && is_file($large) ) {
unlink($large); // delete the medium thumb
}
return true;
} else {
throw new Exception(__('Delete failed'));
}
}
}
|
zuha/Zuha
|
app/Plugin/Galleries/Model/GalleryImage.php
|
PHP
|
gpl-3.0
| 11,591 |
/*****************************************************************************
* Copyright (c) 2014-2019 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#include <algorithm>
#include <iterator>
#include <openrct2-ui/interface/LandTool.h>
#include <openrct2-ui/interface/Viewport.h>
#include <openrct2-ui/interface/Widget.h>
#include <openrct2-ui/windows/Window.h>
#include <openrct2/Cheats.h>
#include <openrct2/Context.h>
#include <openrct2/Game.h>
#include <openrct2/Input.h>
#include <openrct2/OpenRCT2.h>
#include <openrct2/actions/LandSetRightsAction.hpp>
#include <openrct2/actions/PlaceParkEntranceAction.hpp>
#include <openrct2/actions/PlacePeepSpawnAction.hpp>
#include <openrct2/actions/SurfaceSetStyleAction.hpp>
#include <openrct2/audio/audio.h>
#include <openrct2/localisation/Localisation.h>
#include <openrct2/ride/Track.h>
#include <openrct2/world/Entrance.h>
#include <openrct2/world/Footpath.h>
#include <openrct2/world/Scenery.h>
#include <openrct2/world/Sprite.h>
#include <openrct2/world/Surface.h>
#include <vector>
#define MAP_COLOUR_2(colourA, colourB) (((colourA) << 8) | (colourB))
#define MAP_COLOUR(colour) MAP_COLOUR_2(colour, colour)
#define MAP_COLOUR_UNOWNED(colour) (PALETTE_INDEX_10 | ((colour)&0xFF00))
constexpr int32_t MAP_WINDOW_MAP_SIZE = MAXIMUM_MAP_SIZE_TECHNICAL * 2;
// Some functions manipulate coordinates on the map. These are the coordinates of the pixels in the
// minimap. In order to distinguish those from actual coordinates, we use a separate name.
using MapCoordsXY = TileCoordsXY;
// clang-format off
enum {
PAGE_PEEPS,
PAGE_RIDES
};
enum WINDOW_MAP_WIDGET_IDX {
WIDX_BACKGROUND,
WIDX_TITLE,
WIDX_CLOSE,
WIDX_RESIZE = 3,
WIDX_PEOPLE_TAB = 4,
WIDX_RIDES_TAB = 5,
WIDX_MAP = 6,
WIDX_MAP_SIZE_SPINNER = 7,
WIDX_MAP_SIZE_SPINNER_UP = 8,
WIDX_MAP_SIZE_SPINNER_DOWN = 9,
WIDX_SET_LAND_RIGHTS = 10,
WIDX_BUILD_PARK_ENTRANCE = 11,
WIDX_PEOPLE_STARTING_POSITION = 12,
WIDX_LAND_TOOL = 13,
WIDX_LAND_TOOL_SMALLER = 14,
WIDX_LAND_TOOL_LARGER = 15,
WIDX_LAND_OWNED_CHECKBOX = 16,
WIDX_CONSTRUCTION_RIGHTS_OWNED_CHECKBOX = 17,
WIDX_LAND_SALE_CHECKBOX = 18,
WIDX_CONSTRUCTION_RIGHTS_SALE_CHECKBOX = 19,
WIDX_ROTATE_90 = 20,
WIDX_MAP_GENERATOR = 21
};
validate_global_widx(WC_MAP, WIDX_ROTATE_90);
static rct_widget window_map_widgets[] = {
{ WWT_FRAME, 0, 0, 244, 0, 258, STR_NONE, STR_NONE },
{ WWT_CAPTION, 0, 1, 243, 1, 14, STR_MAP_LABEL, STR_WINDOW_TITLE_TIP },
{ WWT_CLOSEBOX, 0, 232, 242, 2, 13, STR_CLOSE_X, STR_CLOSE_WINDOW_TIP },
{ WWT_RESIZE, 1, 0, 244, 43, 257, STR_NONE, STR_NONE },
{ WWT_COLOURBTN, 1, 3, 33, 17, 43, IMAGE_TYPE_REMAP | SPR_TAB, STR_SHOW_PEOPLE_ON_MAP_TIP },
{ WWT_COLOURBTN, 1, 34, 64, 17, 43, IMAGE_TYPE_REMAP | SPR_TAB, STR_SHOW_RIDES_STALLS_ON_MAP_TIP },
{ WWT_SCROLL, 1, 3, 241, 46, 225, SCROLL_BOTH, STR_NONE },
SPINNER_WIDGETS (1, 104, 198, 229, 240, STR_MAP_SIZE_VALUE, STR_NONE), // NB: 3 widgets
{ WWT_FLATBTN, 1, 4, 27, 1, 24, SPR_BUY_LAND_RIGHTS, STR_SELECT_PARK_OWNED_LAND_TIP },
{ WWT_FLATBTN, 1, 4, 27, 1, 24, SPR_PARK_ENTRANCE, STR_BUILD_PARK_ENTRANCE_TIP },
{ WWT_FLATBTN, 1, 28, 51, 1, 24, (uint32_t) SPR_NONE, STR_SET_STARTING_POSITIONS_TIP },
{ WWT_IMGBTN, 1, 4, 47, 17, 48, SPR_LAND_TOOL_SIZE_0, STR_NONE },
{ WWT_TRNBTN, 1, 5, 20, 18, 33, IMAGE_TYPE_REMAP | SPR_LAND_TOOL_DECREASE, STR_ADJUST_SMALLER_LAND_TIP },
{ WWT_TRNBTN, 1, 31, 46, 32, 47, IMAGE_TYPE_REMAP | SPR_LAND_TOOL_INCREASE, STR_ADJUST_LARGER_LAND_TIP },
{ WWT_CHECKBOX, 1, 58, 241, 197, 208, STR_LAND_OWNED, STR_SET_LAND_TO_BE_OWNED_TIP },
{ WWT_CHECKBOX, 1, 58, 241, 197, 208, STR_CONSTRUCTION_RIGHTS_OWNED, STR_SET_CONSTRUCTION_RIGHTS_TO_BE_OWNED_TIP },
{ WWT_CHECKBOX, 1, 58, 241, 197, 208, STR_LAND_SALE, STR_SET_LAND_TO_BE_AVAILABLE_TIP },
{ WWT_CHECKBOX, 1, 58, 231, 197, 208, STR_CONSTRUCTION_RIGHTS_SALE, STR_SET_CONSTRUCTION_RIGHTS_TO_BE_AVAILABLE_TIP },
{ WWT_FLATBTN, 1, 218, 241, 45, 68, SPR_ROTATE_ARROW, STR_ROTATE_OBJECTS_90 },
{ WWT_BUTTON, 1, 110, 240, 190, 201, STR_MAPGEN_WINDOW_TITLE, STR_MAP_GENERATOR_TIP},
{ WIDGETS_END },
};
// used in transforming viewport view coordinates to minimap coordinates
// rct2: 0x00981BBC
static constexpr const LocationXY16 MiniMapOffsets[] = {
{ MAXIMUM_MAP_SIZE_TECHNICAL - 8, 0 },
{ 2 * MAXIMUM_MAP_SIZE_TECHNICAL - 8, MAXIMUM_MAP_SIZE_TECHNICAL },
{ MAXIMUM_MAP_SIZE_TECHNICAL - 8, 2 * MAXIMUM_MAP_SIZE_TECHNICAL },
{ 0 - 8, MAXIMUM_MAP_SIZE_TECHNICAL }
};
/** rct2: 0x00981BCC */
static constexpr const uint16_t RideKeyColours[] = {
MAP_COLOUR(PALETTE_INDEX_61), // COLOUR_KEY_RIDE
MAP_COLOUR(PALETTE_INDEX_42), // COLOUR_KEY_FOOD
MAP_COLOUR(PALETTE_INDEX_20), // COLOUR_KEY_DRINK
MAP_COLOUR(PALETTE_INDEX_209), // COLOUR_KEY_SOUVENIR
MAP_COLOUR(PALETTE_INDEX_136), // COLOUR_KEY_KIOSK
MAP_COLOUR(PALETTE_INDEX_102), // COLOUR_KEY_FIRST_AID
MAP_COLOUR(PALETTE_INDEX_55), // COLOUR_KEY_CASH_MACHINE
MAP_COLOUR(PALETTE_INDEX_161), // COLOUR_KEY_TOILETS
};
static void window_map_close(rct_window *w);
static void window_map_resize(rct_window *w);
static void window_map_mouseup(rct_window *w, rct_widgetindex widgetIndex);
static void window_map_mousedown(rct_window *w, rct_widgetindex widgetIndex, rct_widget* widget);
static void window_map_update(rct_window *w);
static void window_map_toolupdate(rct_window* w, rct_widgetindex widgetIndex, ScreenCoordsXY screenCoords);
static void window_map_tooldown(rct_window* w, rct_widgetindex widgetIndex, ScreenCoordsXY screenCoords);
static void window_map_tooldrag(rct_window* w, rct_widgetindex widgetIndex, ScreenCoordsXY screenCoords);
static void window_map_toolabort(rct_window *w, rct_widgetindex widgetIndex);
static void window_map_scrollgetsize(rct_window *w, int32_t scrollIndex, int32_t *width, int32_t *height);
static void window_map_scrollmousedown(rct_window *w, int32_t scrollIndex, ScreenCoordsXY screenCoords);
static void window_map_textinput(rct_window *w, rct_widgetindex widgetIndex, char *text);
static void window_map_invalidate(rct_window *w);
static void window_map_paint(rct_window *w, rct_drawpixelinfo *dpi);
static void window_map_scrollpaint(rct_window *w, rct_drawpixelinfo *dpi, int32_t scrollIndex);
static rct_window_event_list window_map_events = {
window_map_close,
window_map_mouseup,
window_map_resize,
window_map_mousedown,
nullptr,
nullptr,
window_map_update,
nullptr,
nullptr,
window_map_toolupdate,
window_map_tooldown,
window_map_tooldrag,
nullptr,
window_map_toolabort,
nullptr,
window_map_scrollgetsize,
window_map_scrollmousedown,
window_map_scrollmousedown,
nullptr,
window_map_textinput,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
window_map_invalidate,
window_map_paint,
window_map_scrollpaint
};
// clang-format on
/** rct2: 0x00F1AD61 */
static uint8_t _activeTool;
/** rct2: 0x00F1AD6C */
static uint32_t _currentLine;
/** rct2: 0x00F1AD68 */
static std::vector<uint8_t> _mapImageData;
static uint16_t _landRightsToolSize;
static void window_map_init_map();
static void window_map_centre_on_view_point();
static void window_map_show_default_scenario_editor_buttons(rct_window* w);
static void window_map_draw_tab_images(rct_window* w, rct_drawpixelinfo* dpi);
static void window_map_paint_peep_overlay(rct_drawpixelinfo* dpi);
static void window_map_paint_train_overlay(rct_drawpixelinfo* dpi);
static void window_map_paint_hud_rectangle(rct_drawpixelinfo* dpi);
static void window_map_inputsize_land(rct_window* w);
static void window_map_inputsize_map(rct_window* w);
static void window_map_set_land_rights_tool_update(ScreenCoordsXY screenCoords);
static void window_map_place_park_entrance_tool_update(ScreenCoordsXY screenCoords);
static void window_map_set_peep_spawn_tool_update(ScreenCoordsXY screenCoords);
static void window_map_place_park_entrance_tool_down(ScreenCoordsXY screenCoords);
static void window_map_set_peep_spawn_tool_down(ScreenCoordsXY screenCoords);
static void map_window_increase_map_size();
static void map_window_decrease_map_size();
static void map_window_set_pixels(rct_window* w);
static CoordsXY map_window_screen_to_map(ScreenCoordsXY screenCoords);
/**
*
* rct2: 0x0068C88A
*/
rct_window* window_map_open()
{
rct_window* w;
// Check if window is already open
w = window_bring_to_front_by_class(WC_MAP);
if (w != nullptr)
{
w->selected_tab = 0;
w->list_information_type = 0;
return w;
}
try
{
_mapImageData.resize(MAP_WINDOW_MAP_SIZE * MAP_WINDOW_MAP_SIZE);
}
catch (const std::bad_alloc&)
{
return nullptr;
}
w = window_create_auto_pos(245, 259, &window_map_events, WC_MAP, WF_10);
w->widgets = window_map_widgets;
w->enabled_widgets = (1 << WIDX_CLOSE) | (1 << WIDX_PEOPLE_TAB) | (1 << WIDX_RIDES_TAB) | (1 << WIDX_MAP_SIZE_SPINNER)
| (1 << WIDX_MAP_SIZE_SPINNER_UP) | (1 << WIDX_MAP_SIZE_SPINNER_DOWN) | (1 << WIDX_LAND_TOOL)
| (1 << WIDX_LAND_TOOL_SMALLER) | (1 << WIDX_LAND_TOOL_LARGER) | (1 << WIDX_SET_LAND_RIGHTS)
| (1 << WIDX_LAND_OWNED_CHECKBOX) | (1 << WIDX_CONSTRUCTION_RIGHTS_OWNED_CHECKBOX) | (1 << WIDX_LAND_SALE_CHECKBOX)
| (1 << WIDX_CONSTRUCTION_RIGHTS_SALE_CHECKBOX) | (1 << WIDX_BUILD_PARK_ENTRANCE) | (1 << WIDX_ROTATE_90)
| (1 << WIDX_PEOPLE_STARTING_POSITION) | (1 << WIDX_MAP_GENERATOR);
w->hold_down_widgets = (1 << WIDX_MAP_SIZE_SPINNER_UP) | (1 << WIDX_MAP_SIZE_SPINNER_DOWN) | (1 << WIDX_LAND_TOOL_LARGER)
| (1 << WIDX_LAND_TOOL_SMALLER);
window_init_scroll_widgets(w);
w->map.rotation = get_current_rotation();
window_map_init_map();
gWindowSceneryRotation = 0;
window_map_centre_on_view_point();
// Reset land rights tool size
_landRightsToolSize = 1;
return w;
}
void window_map_reset()
{
rct_window* w;
// Check if window is even opened
w = window_bring_to_front_by_class(WC_MAP);
if (w == nullptr)
{
return;
}
window_map_init_map();
window_map_centre_on_view_point();
}
/**
*
* rct2: 0x0068D0F1
*/
static void window_map_close(rct_window* w)
{
_mapImageData.clear();
_mapImageData.shrink_to_fit();
if ((input_test_flag(INPUT_FLAG_TOOL_ACTIVE)) && gCurrentToolWidget.window_classification == w->classification
&& gCurrentToolWidget.window_number == w->number)
{
tool_cancel();
}
}
/**
*
* rct2: 0x0068CFC1
*/
static void window_map_mouseup(rct_window* w, rct_widgetindex widgetIndex)
{
switch (widgetIndex)
{
case WIDX_CLOSE:
window_close(w);
break;
case WIDX_SET_LAND_RIGHTS:
w->Invalidate();
if (tool_set(w, widgetIndex, TOOL_UP_ARROW))
break;
_activeTool = 2;
// Prevent mountain tool size.
_landRightsToolSize = std::max<uint16_t>(MINIMUM_TOOL_SIZE, _landRightsToolSize);
show_gridlines();
show_land_rights();
show_construction_rights();
break;
case WIDX_LAND_OWNED_CHECKBOX:
_activeTool ^= 2;
if (_activeTool & 2)
_activeTool &= 0xF2;
w->Invalidate();
break;
case WIDX_LAND_SALE_CHECKBOX:
_activeTool ^= 8;
if (_activeTool & 8)
_activeTool &= 0xF8;
w->Invalidate();
break;
case WIDX_CONSTRUCTION_RIGHTS_OWNED_CHECKBOX:
_activeTool ^= 1;
if (_activeTool & 1)
_activeTool &= 0xF1;
w->Invalidate();
break;
case WIDX_CONSTRUCTION_RIGHTS_SALE_CHECKBOX:
_activeTool ^= 4;
if (_activeTool & 4)
_activeTool &= 0xF4;
w->Invalidate();
break;
case WIDX_BUILD_PARK_ENTRANCE:
w->Invalidate();
if (tool_set(w, widgetIndex, TOOL_UP_ARROW))
break;
gParkEntranceGhostExists = false;
input_set_flag(INPUT_FLAG_6, true);
show_gridlines();
show_land_rights();
show_construction_rights();
break;
case WIDX_ROTATE_90:
gWindowSceneryRotation = (gWindowSceneryRotation + 1) & 3;
break;
case WIDX_PEOPLE_STARTING_POSITION:
if (tool_set(w, widgetIndex, TOOL_UP_ARROW))
break;
show_gridlines();
show_land_rights();
show_construction_rights();
break;
case WIDX_LAND_TOOL:
window_map_inputsize_land(w);
break;
case WIDX_MAP_SIZE_SPINNER:
window_map_inputsize_map(w);
break;
case WIDX_MAP_GENERATOR:
context_open_window(WC_MAPGEN);
break;
default:
if (widgetIndex >= WIDX_PEOPLE_TAB && widgetIndex <= WIDX_RIDES_TAB)
{
widgetIndex -= WIDX_PEOPLE_TAB;
if (widgetIndex == w->selected_tab)
break;
w->selected_tab = widgetIndex;
w->list_information_type = 0;
}
}
}
/**
*
* rct2: 0x0068D7DC
*/
static void window_map_resize(rct_window* w)
{
w->flags |= WF_RESIZABLE;
w->min_width = 245;
w->max_width = 800;
w->min_height = 259;
w->max_height = 560;
}
/**
*
* rct2: 0x0068D040
*/
static void window_map_mousedown(rct_window* w, rct_widgetindex widgetIndex, rct_widget* widget)
{
switch (widgetIndex)
{
case WIDX_MAP_SIZE_SPINNER_UP:
map_window_increase_map_size();
break;
case WIDX_MAP_SIZE_SPINNER_DOWN:
map_window_decrease_map_size();
break;
case WIDX_LAND_TOOL_SMALLER:
// Decrement land rights tool size
_landRightsToolSize = std::max(MINIMUM_TOOL_SIZE, _landRightsToolSize - 1);
w->Invalidate();
break;
case WIDX_LAND_TOOL_LARGER:
// Increment land rights tool size
_landRightsToolSize = std::min(MAXIMUM_TOOL_SIZE, _landRightsToolSize + 1);
w->Invalidate();
break;
}
}
/**
*
* rct2: 0x0068D7FB
*/
static void window_map_update(rct_window* w)
{
if (get_current_rotation() != w->map.rotation)
{
w->map.rotation = get_current_rotation();
window_map_init_map();
window_map_centre_on_view_point();
}
for (int32_t i = 0; i < 16; i++)
map_window_set_pixels(w);
w->Invalidate();
// Update tab animations
w->list_information_type++;
switch (w->selected_tab)
{
case PAGE_PEEPS:
if (w->list_information_type >= 32)
{
w->list_information_type = 0;
}
break;
case PAGE_RIDES:
if (w->list_information_type >= 64)
{
w->list_information_type = 0;
}
break;
}
}
/**
*
* rct2: 0x0068D093
*/
static void window_map_toolupdate(rct_window* w, rct_widgetindex widgetIndex, ScreenCoordsXY screenCoords)
{
switch (widgetIndex)
{
case WIDX_SET_LAND_RIGHTS:
window_map_set_land_rights_tool_update(screenCoords);
break;
case WIDX_BUILD_PARK_ENTRANCE:
window_map_place_park_entrance_tool_update(screenCoords);
break;
case WIDX_PEOPLE_STARTING_POSITION:
window_map_set_peep_spawn_tool_update(screenCoords);
break;
}
}
/**
*
* rct2: 0x0068D074
*/
static void window_map_tooldown(rct_window* w, rct_widgetindex widgetIndex, ScreenCoordsXY screenCoords)
{
switch (widgetIndex)
{
case WIDX_BUILD_PARK_ENTRANCE:
window_map_place_park_entrance_tool_down(screenCoords);
break;
case WIDX_PEOPLE_STARTING_POSITION:
window_map_set_peep_spawn_tool_down(screenCoords);
break;
}
}
/**
*
* rct2: 0x0068D088
*/
static void window_map_tooldrag(rct_window* w, rct_widgetindex widgetIndex, ScreenCoordsXY screenCoords)
{
switch (widgetIndex)
{
case WIDX_SET_LAND_RIGHTS:
if (gMapSelectFlags & MAP_SELECT_FLAG_ENABLE)
{
auto landSetRightsAction = LandSetRightsAction(
{ gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y },
LandSetRightSetting::SetOwnershipWithChecks, _activeTool << 4);
GameActions::Execute(&landSetRightsAction);
}
break;
}
}
/**
*
* rct2: 0x0068D055
*/
static void window_map_toolabort(rct_window* w, rct_widgetindex widgetIndex)
{
switch (widgetIndex)
{
case WIDX_SET_LAND_RIGHTS:
w->Invalidate();
hide_gridlines();
hide_land_rights();
hide_construction_rights();
break;
case WIDX_BUILD_PARK_ENTRANCE:
park_entrance_remove_ghost();
w->Invalidate();
hide_gridlines();
hide_land_rights();
hide_construction_rights();
break;
case WIDX_PEOPLE_STARTING_POSITION:
w->Invalidate();
hide_gridlines();
hide_land_rights();
hide_construction_rights();
break;
}
}
/**
*
* rct2: 0x0068D7CC
*/
static void window_map_scrollgetsize(rct_window* w, int32_t scrollIndex, int32_t* width, int32_t* height)
{
window_map_invalidate(w);
*width = MAP_WINDOW_MAP_SIZE;
*height = MAP_WINDOW_MAP_SIZE;
}
/**
*
* rct2: 0x0068D726
*/
static void window_map_scrollmousedown(rct_window* w, int32_t scrollIndex, ScreenCoordsXY screenCoords)
{
CoordsXY c = map_window_screen_to_map(screenCoords);
int32_t mapX = std::clamp(c.x, 0, MAXIMUM_MAP_SIZE_BIG - 1);
int32_t mapY = std::clamp(c.y, 0, MAXIMUM_MAP_SIZE_BIG - 1);
int32_t mapZ = tile_element_height({ mapX, mapY });
rct_window* mainWindow = window_get_main();
if (mainWindow != nullptr)
{
window_scroll_to_location(mainWindow, mapX, mapY, mapZ);
}
if (land_tool_is_active())
{
// Set land terrain
int32_t landToolSize = std::max<int32_t>(1, gLandToolSize);
int32_t size = (landToolSize * 32) - 32;
int32_t radius = (landToolSize * 16) - 16;
mapX = (mapX - radius) & 0xFFE0;
mapY = (mapY - radius) & 0xFFE0;
map_invalidate_selection_rect();
gMapSelectFlags |= MAP_SELECT_FLAG_ENABLE;
gMapSelectType = MAP_SELECT_TYPE_FULL;
gMapSelectPositionA.x = mapX;
gMapSelectPositionA.y = mapY;
gMapSelectPositionB.x = mapX + size;
gMapSelectPositionB.y = mapY + size;
map_invalidate_selection_rect();
auto surfaceSetStyleAction = SurfaceSetStyleAction(
{ gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y },
gLandToolTerrainSurface, gLandToolTerrainEdge);
GameActions::Execute(&surfaceSetStyleAction);
}
else if (widget_is_active_tool(w, WIDX_SET_LAND_RIGHTS))
{
// Set land rights
int32_t landRightsToolSize = std::max<int32_t>(1, _landRightsToolSize);
int32_t size = (landRightsToolSize * 32) - 32;
int32_t radius = (landRightsToolSize * 16) - 16;
mapX = (mapX - radius) & 0xFFE0;
mapY = (mapY - radius) & 0xFFE0;
map_invalidate_selection_rect();
gMapSelectFlags |= MAP_SELECT_FLAG_ENABLE;
gMapSelectType = MAP_SELECT_TYPE_FULL;
gMapSelectPositionA.x = mapX;
gMapSelectPositionA.y = mapY;
gMapSelectPositionB.x = mapX + size;
gMapSelectPositionB.y = mapY + size;
map_invalidate_selection_rect();
auto landSetRightsAction = LandSetRightsAction(
{ gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y },
LandSetRightSetting::SetOwnershipWithChecks, _activeTool << 4);
GameActions::Execute(&landSetRightsAction);
}
}
static void window_map_textinput(rct_window* w, rct_widgetindex widgetIndex, char* text)
{
int32_t size;
char* end;
if (text == nullptr)
return;
switch (widgetIndex)
{
case WIDX_LAND_TOOL:
size = strtol(text, &end, 10);
if (*end == '\0')
{
size = std::clamp(size, MINIMUM_TOOL_SIZE, MAXIMUM_TOOL_SIZE);
_landRightsToolSize = size;
w->Invalidate();
}
break;
case WIDX_MAP_SIZE_SPINNER:
size = strtol(text, &end, 10);
if (*end == '\0')
{
// The practical size is 2 lower than the technical size
size += 2;
size = std::clamp(size, MINIMUM_MAP_SIZE_TECHNICAL, MAXIMUM_MAP_SIZE_TECHNICAL);
int32_t currentSize = gMapSize;
while (size < currentSize)
{
map_window_decrease_map_size();
currentSize--;
}
while (size > currentSize)
{
map_window_increase_map_size();
currentSize++;
}
w->Invalidate();
}
break;
}
}
/**
*
* rct2: 0x0068CA8F
*/
static void window_map_invalidate(rct_window* w)
{
uint64_t pressedWidgets;
int32_t i, height;
// Set the pressed widgets
pressedWidgets = w->pressed_widgets;
pressedWidgets &= (1ULL << WIDX_PEOPLE_TAB);
pressedWidgets &= (1ULL << WIDX_RIDES_TAB);
pressedWidgets &= (1ULL << WIDX_MAP);
pressedWidgets &= (1ULL << WIDX_LAND_OWNED_CHECKBOX);
pressedWidgets &= (1ULL << WIDX_CONSTRUCTION_RIGHTS_OWNED_CHECKBOX);
pressedWidgets &= (1ULL << WIDX_LAND_SALE_CHECKBOX);
pressedWidgets &= (1ULL << WIDX_CONSTRUCTION_RIGHTS_SALE_CHECKBOX);
pressedWidgets |= (1ULL << (WIDX_PEOPLE_TAB + w->selected_tab));
pressedWidgets |= (1ULL << WIDX_LAND_TOOL);
if (_activeTool & (1 << 3))
pressedWidgets |= (1 << WIDX_LAND_SALE_CHECKBOX);
if (_activeTool & (1 << 2))
pressedWidgets |= (1 << WIDX_CONSTRUCTION_RIGHTS_SALE_CHECKBOX);
if (_activeTool & (1 << 1))
pressedWidgets |= (1 << WIDX_LAND_OWNED_CHECKBOX);
if (_activeTool & (1 << 0))
pressedWidgets |= (1 << WIDX_CONSTRUCTION_RIGHTS_OWNED_CHECKBOX);
w->pressed_widgets = pressedWidgets;
// Resize widgets to window size
w->widgets[WIDX_BACKGROUND].right = w->width - 1;
w->widgets[WIDX_BACKGROUND].bottom = w->height - 1;
w->widgets[WIDX_RESIZE].right = w->width - 1;
w->widgets[WIDX_RESIZE].bottom = w->height - 1;
w->widgets[WIDX_TITLE].right = w->width - 2;
w->widgets[WIDX_CLOSE].left = w->width - 2 - 11;
w->widgets[WIDX_CLOSE].right = w->width - 2 - 11 + 10;
w->widgets[WIDX_MAP].right = w->width - 4;
if ((gScreenFlags & SCREEN_FLAGS_SCENARIO_EDITOR) || gCheatsSandboxMode)
w->widgets[WIDX_MAP].bottom = w->height - 1 - 72;
else if (w->selected_tab == PAGE_RIDES)
w->widgets[WIDX_MAP].bottom = w->height - 1 - (4 * LIST_ROW_HEIGHT + 4);
else
w->widgets[WIDX_MAP].bottom = w->height - 1 - 14;
w->widgets[WIDX_MAP_SIZE_SPINNER].top = w->height - 15;
w->widgets[WIDX_MAP_SIZE_SPINNER].bottom = w->height - 4;
w->widgets[WIDX_MAP_SIZE_SPINNER_UP].top = w->height - 14;
w->widgets[WIDX_MAP_SIZE_SPINNER_UP].bottom = w->height - 5;
w->widgets[WIDX_MAP_SIZE_SPINNER_DOWN].top = w->height - 14;
w->widgets[WIDX_MAP_SIZE_SPINNER_DOWN].bottom = w->height - 5;
w->widgets[WIDX_SET_LAND_RIGHTS].top = w->height - 70;
w->widgets[WIDX_SET_LAND_RIGHTS].bottom = w->height - 70 + 23;
w->widgets[WIDX_BUILD_PARK_ENTRANCE].top = w->height - 46;
w->widgets[WIDX_BUILD_PARK_ENTRANCE].bottom = w->height - 46 + 23;
w->widgets[WIDX_ROTATE_90].top = w->height - 46;
w->widgets[WIDX_ROTATE_90].bottom = w->height - 46 + 23;
w->widgets[WIDX_PEOPLE_STARTING_POSITION].top = w->height - 46;
w->widgets[WIDX_PEOPLE_STARTING_POSITION].bottom = w->height - 46 + 23;
w->widgets[WIDX_LAND_TOOL].top = w->height - 42;
w->widgets[WIDX_LAND_TOOL].bottom = w->height - 42 + 30;
w->widgets[WIDX_LAND_TOOL_SMALLER].top = w->height - 41;
w->widgets[WIDX_LAND_TOOL_SMALLER].bottom = w->height - 41 + 15;
w->widgets[WIDX_LAND_TOOL_LARGER].top = w->height - 27;
w->widgets[WIDX_LAND_TOOL_LARGER].bottom = w->height - 27 + 15;
w->widgets[WIDX_MAP_GENERATOR].top = w->height - 69;
w->widgets[WIDX_MAP_GENERATOR].bottom = w->height - 69 + 11;
// Land tool mode (4 checkboxes)
height = w->height - 55;
for (i = 0; i < 4; i++)
{
w->widgets[WIDX_LAND_OWNED_CHECKBOX + i].top = height;
height += 11;
w->widgets[WIDX_LAND_OWNED_CHECKBOX + i].bottom = height;
height += 2;
}
// Disable all scenario editor related widgets
for (i = WIDX_MAP_SIZE_SPINNER; i <= WIDX_MAP_GENERATOR; i++)
{
w->widgets[i].type = WWT_EMPTY;
}
if ((gScreenFlags & SCREEN_FLAGS_SCENARIO_EDITOR) || gCheatsSandboxMode)
{
// scenario editor: build park entrance selected, show rotate button
if ((input_test_flag(INPUT_FLAG_TOOL_ACTIVE)) && gCurrentToolWidget.window_classification == WC_MAP
&& gCurrentToolWidget.widget_index == WIDX_BUILD_PARK_ENTRANCE)
{
w->widgets[WIDX_ROTATE_90].type = WWT_FLATBTN;
}
// Always show set land rights button
w->widgets[WIDX_SET_LAND_RIGHTS].type = WWT_FLATBTN;
// If any tool is active
if ((input_test_flag(INPUT_FLAG_TOOL_ACTIVE)) && gCurrentToolWidget.window_classification == WC_MAP)
{
// if not in set land rights mode: show the default scenario editor buttons
if (gCurrentToolWidget.widget_index != WIDX_SET_LAND_RIGHTS)
{
window_map_show_default_scenario_editor_buttons(w);
}
else
{ // if in set land rights mode: show land tool buttons + modes
w->widgets[WIDX_LAND_TOOL].type = WWT_IMGBTN;
w->widgets[WIDX_LAND_TOOL_SMALLER].type = WWT_TRNBTN;
w->widgets[WIDX_LAND_TOOL_LARGER].type = WWT_TRNBTN;
for (i = 0; i < 4; i++)
w->widgets[WIDX_LAND_OWNED_CHECKBOX + i].type = WWT_CHECKBOX;
w->widgets[WIDX_LAND_TOOL].image = land_tool_size_to_sprite_index(_landRightsToolSize);
}
}
else
{
// if no tool is active: show the default scenario editor buttons
window_map_show_default_scenario_editor_buttons(w);
}
}
}
/**
*
* rct2: 0x0068CDA9
*/
static void window_map_paint(rct_window* w, rct_drawpixelinfo* dpi)
{
window_draw_widgets(w, dpi);
window_map_draw_tab_images(w, dpi);
int32_t x = w->x + (window_map_widgets[WIDX_LAND_TOOL].left + window_map_widgets[WIDX_LAND_TOOL].right) / 2;
int32_t y = w->y + (window_map_widgets[WIDX_LAND_TOOL].top + window_map_widgets[WIDX_LAND_TOOL].bottom) / 2;
// Draw land tool size
if (widget_is_active_tool(w, WIDX_SET_LAND_RIGHTS) && _landRightsToolSize > MAX_TOOL_SIZE_WITH_SPRITE)
{
gfx_draw_string_centred(dpi, STR_LAND_TOOL_SIZE_VALUE, x, y - 2, COLOUR_BLACK, &_landRightsToolSize);
}
y = w->y + window_map_widgets[WIDX_LAND_TOOL].bottom + 5;
// People starting position (scenario editor only)
if (w->widgets[WIDX_PEOPLE_STARTING_POSITION].type != WWT_EMPTY)
{
x = w->x + w->widgets[WIDX_PEOPLE_STARTING_POSITION].left + 12;
y = w->y + w->widgets[WIDX_PEOPLE_STARTING_POSITION].top + 18;
gfx_draw_sprite(
dpi, IMAGE_TYPE_REMAP | IMAGE_TYPE_REMAP_2_PLUS | (COLOUR_LIGHT_BROWN << 24) | (COLOUR_BRIGHT_RED << 19) | SPR_6410,
x, y, 0);
}
if (!(gScreenFlags & SCREEN_FLAGS_SCENARIO_EDITOR) && !gCheatsSandboxMode)
{
// Render the map legend
if (w->selected_tab == PAGE_RIDES)
{
x = w->x + 4;
y = w->y + w->widgets[WIDX_MAP].bottom + 2;
static rct_string_id mapLabels[] = {
STR_MAP_RIDE, STR_MAP_FOOD_STALL, STR_MAP_DRINK_STALL, STR_MAP_SOUVENIR_STALL,
STR_MAP_INFO_KIOSK, STR_MAP_FIRST_AID, STR_MAP_CASH_MACHINE, STR_MAP_TOILET,
};
for (uint32_t i = 0; i < std::size(RideKeyColours); i++)
{
gfx_fill_rect(dpi, x, y + 2, x + 6, y + 8, RideKeyColours[i]);
gfx_draw_string_left(dpi, mapLabels[i], w, COLOUR_BLACK, x + LIST_ROW_HEIGHT, y);
y += LIST_ROW_HEIGHT;
if (i == 3)
{
x += 118;
y -= LIST_ROW_HEIGHT * 4;
}
}
}
}
else if (!widget_is_active_tool(w, WIDX_SET_LAND_RIGHTS))
{
gfx_draw_string_left(
dpi, STR_MAP_SIZE, nullptr, w->colours[1], w->x + 4, w->y + w->widgets[WIDX_MAP_SIZE_SPINNER].top + 1);
}
}
/**
*
* rct2: 0x0068CF23
*/
static void window_map_scrollpaint(rct_window* w, rct_drawpixelinfo* dpi, int32_t scrollIndex)
{
gfx_clear(dpi, PALETTE_INDEX_10);
rct_g1_element g1temp = {};
g1temp.offset = _mapImageData.data();
g1temp.width = MAP_WINDOW_MAP_SIZE;
g1temp.height = MAP_WINDOW_MAP_SIZE;
g1temp.x_offset = -8;
g1temp.y_offset = -8;
gfx_set_g1_element(SPR_TEMP, &g1temp);
drawing_engine_invalidate_image(SPR_TEMP);
gfx_draw_sprite(dpi, SPR_TEMP, 0, 0, 0);
if (w->selected_tab == PAGE_PEEPS)
{
window_map_paint_peep_overlay(dpi);
}
else
{
window_map_paint_train_overlay(dpi);
}
window_map_paint_hud_rectangle(dpi);
}
/**
*
* rct2: 0x0068CA6C
*/
static void window_map_init_map()
{
std::fill(_mapImageData.begin(), _mapImageData.end(), PALETTE_INDEX_10);
_currentLine = 0;
}
/**
*
* rct2: 0x0068C990
*/
static void window_map_centre_on_view_point()
{
rct_window* w = window_get_main();
rct_window* w_map;
int16_t ax, bx, cx, dx;
int16_t bp, di;
if (w == nullptr || w->viewport == nullptr)
return;
w_map = window_find_by_class(WC_MAP);
if (w_map == nullptr)
return;
LocationXY16 offset = MiniMapOffsets[get_current_rotation()];
// calculate centre view point of viewport and transform it to minimap coordinates
cx = ((w->viewport->view_width >> 1) + w->viewport->view_x) >> 5;
dx = ((w->viewport->view_height >> 1) + w->viewport->view_y) >> 4;
cx += offset.x;
dx += offset.y;
// calculate width and height of minimap
ax = w_map->widgets[WIDX_MAP].right - w_map->widgets[WIDX_MAP].left - 11;
bx = w_map->widgets[WIDX_MAP].bottom - w_map->widgets[WIDX_MAP].top - 11;
bp = ax;
di = bx;
ax >>= 1;
bx >>= 1;
cx = std::max(cx - ax, 0);
dx = std::max(dx - bx, 0);
bp = w_map->scrolls[0].h_right - bp;
di = w_map->scrolls[0].v_bottom - di;
if (bp < 0 && (bp - cx) < 0)
cx = 0;
if (di < 0 && (di - dx) < 0)
dx = 0;
w_map->scrolls[0].h_left = cx;
w_map->scrolls[0].v_top = dx;
widget_scroll_update_thumbs(w_map, WIDX_MAP);
}
/**
*
* rct2: 0x0068CD35 (part of 0x0068CA8F)
*/
static void window_map_show_default_scenario_editor_buttons(rct_window* w)
{
w->widgets[WIDX_BUILD_PARK_ENTRANCE].type = WWT_FLATBTN;
w->widgets[WIDX_PEOPLE_STARTING_POSITION].type = WWT_FLATBTN;
w->widgets[WIDX_MAP_SIZE_SPINNER].type = WWT_SPINNER;
w->widgets[WIDX_MAP_SIZE_SPINNER_UP].type = WWT_BUTTON;
w->widgets[WIDX_MAP_SIZE_SPINNER_DOWN].type = WWT_BUTTON;
// Only show this in the scenario editor, even when in sandbox mode.
if (gScreenFlags & SCREEN_FLAGS_SCENARIO_EDITOR)
w->widgets[WIDX_MAP_GENERATOR].type = WWT_BUTTON;
set_format_arg(2, uint16_t, gMapSize - 2);
}
static void window_map_inputsize_land(rct_window* w)
{
TextInputDescriptionArgs[0] = MINIMUM_TOOL_SIZE;
TextInputDescriptionArgs[1] = MAXIMUM_TOOL_SIZE;
window_text_input_open(w, WIDX_LAND_TOOL, STR_SELECTION_SIZE, STR_ENTER_SELECTION_SIZE, STR_NONE, STR_NONE, 3);
}
static void window_map_inputsize_map(rct_window* w)
{
TextInputDescriptionArgs[0] = MINIMUM_MAP_SIZE_PRACTICAL;
TextInputDescriptionArgs[1] = MAXIMUM_MAP_SIZE_PRACTICAL;
window_text_input_open(w, WIDX_MAP_SIZE_SPINNER, STR_MAP_SIZE_2, STR_ENTER_MAP_SIZE, STR_NONE, STR_NONE, 4);
}
static void window_map_draw_tab_images(rct_window* w, rct_drawpixelinfo* dpi)
{
uint32_t image;
// Guest tab image (animated)
image = SPR_TAB_GUESTS_0;
if (w->selected_tab == PAGE_PEEPS)
image += w->list_information_type / 4;
gfx_draw_sprite(dpi, image, w->x + w->widgets[WIDX_PEOPLE_TAB].left, w->y + w->widgets[WIDX_PEOPLE_TAB].top, 0);
// Ride/stall tab image (animated)
image = SPR_TAB_RIDE_0;
if (w->selected_tab == PAGE_RIDES)
image += w->list_information_type / 4;
gfx_draw_sprite(dpi, image, w->x + w->widgets[WIDX_RIDES_TAB].left, w->y + w->widgets[WIDX_RIDES_TAB].top, 0);
}
/**
*
* part of window_map_paint_peep_overlay and window_map_paint_train_overlay
*/
static MapCoordsXY window_map_transform_to_map_coords(CoordsXY c)
{
int32_t x = c.x, y = c.y;
switch (get_current_rotation())
{
case 3:
std::swap(x, y);
x = MAXIMUM_MAP_SIZE_BIG - 1 - x;
break;
case 2:
x = MAXIMUM_MAP_SIZE_BIG - 1 - x;
y = MAXIMUM_MAP_SIZE_BIG - 1 - y;
break;
case 1:
std::swap(x, y);
y = MAXIMUM_MAP_SIZE_BIG - 1 - y;
break;
case 0:
break;
}
x /= 32;
y /= 32;
return { -x + y + MAXIMUM_MAP_SIZE_TECHNICAL - 8, x + y - 8 };
}
/**
*
* rct2: 0x0068DADA
*/
static void window_map_paint_peep_overlay(rct_drawpixelinfo* dpi)
{
Peep* peep;
uint16_t spriteIndex;
FOR_ALL_PEEPS (spriteIndex, peep)
{
if (peep->x == LOCATION_NULL)
continue;
MapCoordsXY c = window_map_transform_to_map_coords({ peep->x, peep->y });
int16_t left = c.x;
int16_t top = c.y;
int16_t right = left;
int16_t bottom = top;
int16_t colour = PALETTE_INDEX_20;
if (sprite_get_flashing(peep))
{
if (peep->type == PEEP_TYPE_STAFF)
{
if ((gWindowMapFlashingFlags & (1 << 3)) != 0)
{
colour = PALETTE_INDEX_138;
left--;
if ((gWindowMapFlashingFlags & (1 << 15)) == 0)
colour = PALETTE_INDEX_10;
}
}
else
{
if ((gWindowMapFlashingFlags & (1 << 1)) != 0)
{
colour = PALETTE_INDEX_172;
left--;
if ((gWindowMapFlashingFlags & (1 << 15)) == 0)
colour = PALETTE_INDEX_21;
}
}
}
gfx_fill_rect(dpi, left, top, right, bottom, colour);
}
}
/**
*
* rct2: 0x0068DBC1
*/
static void window_map_paint_train_overlay(rct_drawpixelinfo* dpi)
{
Vehicle *train, *vehicle;
uint16_t train_index, vehicle_index;
for (train_index = gSpriteListHead[SPRITE_LIST_VEHICLE_HEAD]; train_index != SPRITE_INDEX_NULL; train_index = train->next)
{
train = GET_VEHICLE(train_index);
for (vehicle_index = train_index; vehicle_index != SPRITE_INDEX_NULL; vehicle_index = vehicle->next_vehicle_on_train)
{
vehicle = GET_VEHICLE(vehicle_index);
if (vehicle->x == LOCATION_NULL)
continue;
MapCoordsXY c = window_map_transform_to_map_coords({ vehicle->x, vehicle->y });
gfx_fill_rect(dpi, c.x, c.y, c.x, c.y, PALETTE_INDEX_171);
}
}
}
/**
* The call to gfx_fill_rect was originally wrapped in sub_68DABD which made sure that arguments were ordered correctly,
* but it doesn't look like it's ever necessary here so the call was removed.
*
* rct2: 0x0068D8CE
*/
static void window_map_paint_hud_rectangle(rct_drawpixelinfo* dpi)
{
rct_window* main_window = window_get_main();
if (main_window == nullptr)
return;
rct_viewport* viewport = main_window->viewport;
if (viewport == nullptr)
return;
LocationXY16 offset = MiniMapOffsets[get_current_rotation()];
int16_t left = (viewport->view_x >> 5) + offset.x;
int16_t right = ((viewport->view_x + viewport->view_width) >> 5) + offset.x;
int16_t top = (viewport->view_y >> 4) + offset.y;
int16_t bottom = ((viewport->view_y + viewport->view_height) >> 4) + offset.y;
// top horizontal lines
gfx_fill_rect(dpi, left, top, left + 3, top, PALETTE_INDEX_56);
gfx_fill_rect(dpi, right - 3, top, right, top, PALETTE_INDEX_56);
// left vertical lines
gfx_fill_rect(dpi, left, top, left, top + 3, PALETTE_INDEX_56);
gfx_fill_rect(dpi, left, bottom - 3, left, bottom, PALETTE_INDEX_56);
// bottom horizontal lines
gfx_fill_rect(dpi, left, bottom, left + 3, bottom, PALETTE_INDEX_56);
gfx_fill_rect(dpi, right - 3, bottom, right, bottom, PALETTE_INDEX_56);
// right vertical lines
gfx_fill_rect(dpi, right, top, right, top + 3, PALETTE_INDEX_56);
gfx_fill_rect(dpi, right, bottom - 3, right, bottom, PALETTE_INDEX_56);
}
/**
*
* rct2: 0x0068D24E
*/
static void window_map_set_land_rights_tool_update(ScreenCoordsXY screenCoords)
{
rct_viewport* viewport;
map_invalidate_selection_rect();
gMapSelectFlags &= ~MAP_SELECT_FLAG_ENABLE;
auto mapCoords = screen_get_map_xy(screenCoords, &viewport);
if (!mapCoords)
return;
gMapSelectFlags |= MAP_SELECT_FLAG_ENABLE;
gMapSelectType = MAP_SELECT_TYPE_FULL;
int32_t landRightsToolSize = _landRightsToolSize;
if (landRightsToolSize == 0)
landRightsToolSize = 1;
int32_t size = (landRightsToolSize * 32) - 32;
int32_t radius = (landRightsToolSize * 16) - 16;
mapCoords->x = (mapCoords->x - radius) & 0xFFE0;
mapCoords->y = (mapCoords->y - radius) & 0xFFE0;
gMapSelectPositionA = *mapCoords;
gMapSelectPositionB.x = mapCoords->x + size;
gMapSelectPositionB.y = mapCoords->y + size;
map_invalidate_selection_rect();
}
/**
*
* rct2: 0x00666EEF
*/
static CoordsXYZD place_park_entrance_get_map_position(ScreenCoordsXY screenCoords)
{
CoordsXYZD parkEntranceMapPosition{ 0, 0, 0, INVALID_DIRECTION };
const CoordsXY mapCoords = sub_68A15E(screenCoords);
parkEntranceMapPosition = { mapCoords.x, mapCoords.y, 0, INVALID_DIRECTION };
if (parkEntranceMapPosition.isNull())
return parkEntranceMapPosition;
auto surfaceElement = map_get_surface_element_at(mapCoords);
if (surfaceElement == nullptr)
{
parkEntranceMapPosition.setNull();
return parkEntranceMapPosition;
}
parkEntranceMapPosition.z = surfaceElement->GetWaterHeight();
if (parkEntranceMapPosition.z == 0)
{
parkEntranceMapPosition.z = surfaceElement->GetBaseZ();
if ((surfaceElement->GetSlope() & TILE_ELEMENT_SLOPE_ALL_CORNERS_UP) != 0)
{
parkEntranceMapPosition.z += 16;
if (surfaceElement->GetSlope() & TILE_ELEMENT_SLOPE_DOUBLE_HEIGHT)
{
parkEntranceMapPosition.z += 16;
}
}
}
parkEntranceMapPosition.direction = (gWindowSceneryRotation - get_current_rotation()) & 3;
return parkEntranceMapPosition;
}
/**
*
* rct2: 0x00666FD0
*/
static void window_map_place_park_entrance_tool_update(ScreenCoordsXY screenCoords)
{
int32_t sideDirection;
map_invalidate_selection_rect();
map_invalidate_map_selection_tiles();
gMapSelectFlags &= ~MAP_SELECT_FLAG_ENABLE;
gMapSelectFlags &= ~MAP_SELECT_FLAG_ENABLE_ARROW;
gMapSelectFlags &= ~MAP_SELECT_FLAG_ENABLE_CONSTRUCT;
CoordsXYZD parkEntrancePosition = place_park_entrance_get_map_position(screenCoords);
if (parkEntrancePosition.isNull())
{
park_entrance_remove_ghost();
return;
}
sideDirection = (parkEntrancePosition.direction + 1) & 3;
gMapSelectionTiles.clear();
gMapSelectionTiles.push_back({ parkEntrancePosition.x, parkEntrancePosition.y });
gMapSelectionTiles.push_back({ parkEntrancePosition.x + CoordsDirectionDelta[sideDirection].x,
parkEntrancePosition.y + CoordsDirectionDelta[sideDirection].y });
gMapSelectionTiles.push_back({ parkEntrancePosition.x - CoordsDirectionDelta[sideDirection].x,
parkEntrancePosition.y - CoordsDirectionDelta[sideDirection].y });
gMapSelectArrowPosition = parkEntrancePosition;
gMapSelectArrowDirection = parkEntrancePosition.direction;
gMapSelectFlags |= MAP_SELECT_FLAG_ENABLE_CONSTRUCT | MAP_SELECT_FLAG_ENABLE_ARROW;
map_invalidate_map_selection_tiles();
if (gParkEntranceGhostExists && parkEntrancePosition == gParkEntranceGhostPosition)
{
return;
}
park_entrance_remove_ghost();
park_entrance_place_ghost(parkEntrancePosition);
}
/**
*
* rct2: 0x0068D4E9
*/
static void window_map_set_peep_spawn_tool_update(ScreenCoordsXY screenCoords)
{
int32_t mapZ, direction;
TileElement* tileElement;
map_invalidate_selection_rect();
gMapSelectFlags &= ~MAP_SELECT_FLAG_ENABLE;
gMapSelectFlags &= ~MAP_SELECT_FLAG_ENABLE_ARROW;
auto mapCoords = footpath_bridge_get_info_from_pos(screenCoords, &direction, &tileElement);
if (mapCoords.isNull())
return;
mapZ = tileElement->GetBaseZ();
if (tileElement->GetType() == TILE_ELEMENT_TYPE_SURFACE)
{
if ((tileElement->AsSurface()->GetSlope() & TILE_ELEMENT_SLOPE_ALL_CORNERS_UP) != 0)
mapZ += 16;
if (tileElement->AsSurface()->GetSlope() & TILE_ELEMENT_SLOPE_DOUBLE_HEIGHT)
mapZ += 16;
}
gMapSelectFlags |= MAP_SELECT_FLAG_ENABLE;
gMapSelectFlags |= MAP_SELECT_FLAG_ENABLE_ARROW;
gMapSelectType = MAP_SELECT_TYPE_FULL;
gMapSelectPositionA = mapCoords;
gMapSelectPositionB = mapCoords;
gMapSelectArrowPosition = CoordsXYZ{ mapCoords, mapZ };
gMapSelectArrowDirection = direction_reverse(direction);
map_invalidate_selection_rect();
}
/**
*
* rct2: 0x006670A4
*/
static void window_map_place_park_entrance_tool_down(ScreenCoordsXY screenCoords)
{
park_entrance_remove_ghost();
CoordsXYZD parkEntrancePosition = place_park_entrance_get_map_position(screenCoords);
if (!parkEntrancePosition.isNull())
{
auto gameAction = PlaceParkEntranceAction(parkEntrancePosition);
auto result = GameActions::Execute(&gameAction);
if (result->Error == GA_ERROR::OK)
{
audio_play_sound_at_location(SoundId::PlaceItem, result->Position);
}
}
}
/**
*
* rct2: 0x0068D573
*/
static void window_map_set_peep_spawn_tool_down(ScreenCoordsXY screenCoords)
{
TileElement* tileElement;
int32_t mapZ, direction;
// Verify footpath exists at location, and retrieve coordinates
auto mapCoords = footpath_get_coordinates_from_pos(screenCoords, &direction, &tileElement);
if (mapCoords.isNull())
return;
mapZ = tileElement->GetBaseZ();
auto gameAction = PlacePeepSpawnAction({ mapCoords, mapZ, static_cast<Direction>(direction) });
auto result = GameActions::Execute(&gameAction);
if (result->Error == GA_ERROR::OK)
{
audio_play_sound_at_location(SoundId::PlaceItem, result->Position);
}
}
/**
*
* rct2: 0x0068D641
*/
static void map_window_increase_map_size()
{
if (gMapSize >= MAXIMUM_MAP_SIZE_TECHNICAL)
{
context_show_error(STR_CANT_INCREASE_MAP_SIZE_ANY_FURTHER, STR_NONE);
return;
}
gMapSize++;
gMapSizeUnits = (gMapSize - 1) * 32;
gMapSizeMinus2 = (gMapSize * 32) + MAXIMUM_MAP_SIZE_PRACTICAL;
gMapSizeMaxXY = ((gMapSize - 1) * 32) - 1;
map_extend_boundary_surface();
window_map_init_map();
window_map_centre_on_view_point();
gfx_invalidate_screen();
}
/**
*
* rct2: 0x0068D6B4
*/
static void map_window_decrease_map_size()
{
if (gMapSize < 16)
{
context_show_error(STR_CANT_DECREASE_MAP_SIZE_ANY_FURTHER, STR_NONE);
return;
}
gMapSize--;
gMapSizeUnits = (gMapSize - 1) * 32;
gMapSizeMinus2 = (gMapSize * 32) + MAXIMUM_MAP_SIZE_PRACTICAL;
gMapSizeMaxXY = ((gMapSize - 1) * 32) - 1;
map_remove_out_of_range_elements();
window_map_init_map();
window_map_centre_on_view_point();
gfx_invalidate_screen();
}
static constexpr const uint16_t WaterColour = MAP_COLOUR(PALETTE_INDEX_195);
static constexpr const uint16_t TerrainColour[] = {
MAP_COLOUR(PALETTE_INDEX_73), // TERRAIN_GRASS
MAP_COLOUR(PALETTE_INDEX_40), // TERRAIN_SAND
MAP_COLOUR(PALETTE_INDEX_108), // TERRAIN_DIRT
MAP_COLOUR(PALETTE_INDEX_12), // TERRAIN_ROCK
MAP_COLOUR(PALETTE_INDEX_62), // TERRAIN_MARTIAN
MAP_COLOUR_2(PALETTE_INDEX_10, PALETTE_INDEX_16), // TERRAIN_CHECKERBOARD
MAP_COLOUR_2(PALETTE_INDEX_73, PALETTE_INDEX_108), // TERRAIN_GRASS_CLUMPS
MAP_COLOUR(PALETTE_INDEX_141), // TERRAIN_ICE
MAP_COLOUR_2(PALETTE_INDEX_172, PALETTE_INDEX_10), // TERRAIN_GRID_RED
MAP_COLOUR_2(PALETTE_INDEX_54, PALETTE_INDEX_10), // TERRAIN_GRID_YELLOW
MAP_COLOUR_2(PALETTE_INDEX_162, PALETTE_INDEX_10), // TERRAIN_GRID_BLUE
MAP_COLOUR_2(PALETTE_INDEX_102, PALETTE_INDEX_10), // TERRAIN_GRID_GREEN
MAP_COLOUR(PALETTE_INDEX_111), // TERRAIN_SAND_DARK
MAP_COLOUR(PALETTE_INDEX_222), // TERRAIN_SAND_LIGHT
};
static constexpr const uint16_t ElementTypeMaskColour[] = {
0xFFFF, // TILE_ELEMENT_TYPE_SURFACE
0x0000, // TILE_ELEMENT_TYPE_PATH
0x00FF, // TILE_ELEMENT_TYPE_TRACK
0xFF00, // TILE_ELEMENT_TYPE_SMALL_SCENERY
0x0000, // TILE_ELEMENT_TYPE_ENTRANCE
0xFFFF, // TILE_ELEMENT_TYPE_WALL
0x0000, // TILE_ELEMENT_TYPE_LARGE_SCENERY
0xFFFF, // TILE_ELEMENT_TYPE_BANNER
0x0000, // TILE_ELEMENT_TYPE_CORRUPT
};
static constexpr const uint16_t ElementTypeAddColour[] = {
MAP_COLOUR(PALETTE_INDEX_0), // TILE_ELEMENT_TYPE_SURFACE
MAP_COLOUR(PALETTE_INDEX_17), // TILE_ELEMENT_TYPE_PATH
MAP_COLOUR_2(PALETTE_INDEX_183, PALETTE_INDEX_0), // TILE_ELEMENT_TYPE_TRACK
MAP_COLOUR_2(PALETTE_INDEX_0, PALETTE_INDEX_99), // TILE_ELEMENT_TYPE_SMALL_SCENERY
MAP_COLOUR(PALETTE_INDEX_186), // TILE_ELEMENT_TYPE_ENTRANCE
MAP_COLOUR(PALETTE_INDEX_0), // TILE_ELEMENT_TYPE_WALL
MAP_COLOUR(PALETTE_INDEX_99), // TILE_ELEMENT_TYPE_LARGE_SCENERY
MAP_COLOUR(PALETTE_INDEX_0), // TILE_ELEMENT_TYPE_BANNER
MAP_COLOUR(PALETTE_INDEX_68), // TILE_ELEMENT_TYPE_CORRUPT
};
enum
{
COLOUR_KEY_RIDE,
COLOUR_KEY_FOOD,
COLOUR_KEY_DRINK,
COLOUR_KEY_SOUVENIR,
COLOUR_KEY_KIOSK,
COLOUR_KEY_FIRST_AID,
COLOUR_KEY_CASH_MACHINE,
COLOUR_KEY_TOILETS
};
static constexpr const uint8_t RideColourKey[] = {
COLOUR_KEY_RIDE, // RIDE_TYPE_SPIRAL_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_STAND_UP_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_SUSPENDED_SWINGING_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_INVERTED_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_JUNIOR_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_MINIATURE_RAILWAY
COLOUR_KEY_RIDE, // RIDE_TYPE_MONORAIL
COLOUR_KEY_RIDE, // RIDE_TYPE_MINI_SUSPENDED_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_BOAT_HIRE
COLOUR_KEY_RIDE, // RIDE_TYPE_WOODEN_WILD_MOUSE
COLOUR_KEY_RIDE, // RIDE_TYPE_STEEPLECHASE
COLOUR_KEY_RIDE, // RIDE_TYPE_CAR_RIDE
COLOUR_KEY_RIDE, // RIDE_TYPE_LAUNCHED_FREEFALL
COLOUR_KEY_RIDE, // RIDE_TYPE_BOBSLEIGH_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_OBSERVATION_TOWER
COLOUR_KEY_RIDE, // RIDE_TYPE_LOOPING_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_DINGHY_SLIDE
COLOUR_KEY_RIDE, // RIDE_TYPE_MINE_TRAIN_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_CHAIRLIFT
COLOUR_KEY_RIDE, // RIDE_TYPE_CORKSCREW_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_MAZE = 20
COLOUR_KEY_RIDE, // RIDE_TYPE_SPIRAL_SLIDE
COLOUR_KEY_RIDE, // RIDE_TYPE_GO_KARTS
COLOUR_KEY_RIDE, // RIDE_TYPE_LOG_FLUME
COLOUR_KEY_RIDE, // RIDE_TYPE_RIVER_RAPIDS
COLOUR_KEY_RIDE, // RIDE_TYPE_DODGEMS
COLOUR_KEY_RIDE, // RIDE_TYPE_SWINGING_SHIP
COLOUR_KEY_RIDE, // RIDE_TYPE_SWINGING_INVERTER_SHIP
COLOUR_KEY_FOOD, // RIDE_TYPE_FOOD_STALL
COLOUR_KEY_FOOD, // RIDE_TYPE_1D
COLOUR_KEY_DRINK, // RIDE_TYPE_DRINK_STALL
COLOUR_KEY_DRINK, // RIDE_TYPE_1F
COLOUR_KEY_SOUVENIR, // RIDE_TYPE_SHOP
COLOUR_KEY_RIDE, // RIDE_TYPE_MERRY_GO_ROUND
COLOUR_KEY_SOUVENIR, // RIDE_TYPE_22
COLOUR_KEY_KIOSK, // RIDE_TYPE_INFORMATION_KIOSK
COLOUR_KEY_TOILETS, // RIDE_TYPE_TOILETS
COLOUR_KEY_RIDE, // RIDE_TYPE_FERRIS_WHEEL
COLOUR_KEY_RIDE, // RIDE_TYPE_MOTION_SIMULATOR
COLOUR_KEY_RIDE, // RIDE_TYPE_3D_CINEMA
COLOUR_KEY_RIDE, // RIDE_TYPE_TOP_SPIN
COLOUR_KEY_RIDE, // RIDE_TYPE_SPACE_RINGS
COLOUR_KEY_RIDE, // RIDE_TYPE_REVERSE_FREEFALL_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_LIFT
COLOUR_KEY_RIDE, // RIDE_TYPE_VERTICAL_DROP_ROLLER_COASTER
COLOUR_KEY_CASH_MACHINE, // RIDE_TYPE_CASH_MACHINE
COLOUR_KEY_RIDE, // RIDE_TYPE_TWIST
COLOUR_KEY_RIDE, // RIDE_TYPE_HAUNTED_HOUSE
COLOUR_KEY_FIRST_AID, // RIDE_TYPE_FIRST_AID
COLOUR_KEY_RIDE, // RIDE_TYPE_CIRCUS
COLOUR_KEY_RIDE, // RIDE_TYPE_GHOST_TRAIN
COLOUR_KEY_RIDE, // RIDE_TYPE_TWISTER_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_WOODEN_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_SIDE_FRICTION_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_STEEL_WILD_MOUSE
COLOUR_KEY_RIDE, // RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER_ALT
COLOUR_KEY_RIDE, // RIDE_TYPE_FLYING_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_FLYING_ROLLER_COASTER_ALT
COLOUR_KEY_RIDE, // RIDE_TYPE_VIRGINIA_REEL
COLOUR_KEY_RIDE, // RIDE_TYPE_SPLASH_BOATS
COLOUR_KEY_RIDE, // RIDE_TYPE_MINI_HELICOPTERS
COLOUR_KEY_RIDE, // RIDE_TYPE_LAY_DOWN_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_SUSPENDED_MONORAIL
COLOUR_KEY_RIDE, // RIDE_TYPE_LAY_DOWN_ROLLER_COASTER_ALT
COLOUR_KEY_RIDE, // RIDE_TYPE_REVERSER_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_HEARTLINE_TWISTER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_MINI_GOLF
COLOUR_KEY_RIDE, // RIDE_TYPE_GIGA_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_ROTO_DROP
COLOUR_KEY_RIDE, // RIDE_TYPE_FLYING_SAUCERS
COLOUR_KEY_RIDE, // RIDE_TYPE_CROOKED_HOUSE
COLOUR_KEY_RIDE, // RIDE_TYPE_MONORAIL_CYCLES
COLOUR_KEY_RIDE, // RIDE_TYPE_COMPACT_INVERTED_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_WATER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_AIR_POWERED_VERTICAL_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_INVERTED_HAIRPIN_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_MAGIC_CARPET
COLOUR_KEY_RIDE, // RIDE_TYPE_SUBMARINE_RIDE
COLOUR_KEY_RIDE, // RIDE_TYPE_RIVER_RAFTS
COLOUR_KEY_RIDE, // RIDE_TYPE_50
COLOUR_KEY_RIDE, // RIDE_TYPE_ENTERPRISE
COLOUR_KEY_RIDE, // RIDE_TYPE_52
COLOUR_KEY_RIDE, // RIDE_TYPE_53
COLOUR_KEY_RIDE, // RIDE_TYPE_54
COLOUR_KEY_RIDE, // RIDE_TYPE_55
COLOUR_KEY_RIDE, // RIDE_TYPE_INVERTED_IMPULSE_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_MINI_ROLLER_COASTER
COLOUR_KEY_RIDE, // RIDE_TYPE_MINE_RIDE
COLOUR_KEY_RIDE, // RIDE_TYPE_59
COLOUR_KEY_RIDE, // RIDE_TYPE_LIM_LAUNCHED_ROLLER_COASTER
COLOUR_KEY_RIDE, //
COLOUR_KEY_RIDE, //
COLOUR_KEY_RIDE, //
};
static uint16_t map_window_get_pixel_colour_peep(CoordsXY c)
{
auto* surfaceElement = map_get_surface_element_at(c);
if (surfaceElement == nullptr)
return 0;
uint16_t colour = TerrainColour[surfaceElement->GetSurfaceStyle()];
if (surfaceElement->GetWaterHeight() > 0)
colour = WaterColour;
if (!(surfaceElement->GetOwnership() & OWNERSHIP_OWNED))
colour = MAP_COLOUR_UNOWNED(colour);
const int32_t maxSupportedTileElementType = (int32_t)std::size(ElementTypeAddColour);
auto tileElement = reinterpret_cast<TileElement*>(surfaceElement);
while (!(tileElement++)->IsLastForTile())
{
if (tileElement->IsGhost())
{
colour = MAP_COLOUR(PALETTE_INDEX_21);
break;
}
int32_t tileElementType = tileElement->GetType() >> 2;
if (tileElementType >= maxSupportedTileElementType)
{
tileElementType = TILE_ELEMENT_TYPE_CORRUPT >> 2;
}
colour &= ElementTypeMaskColour[tileElementType];
colour |= ElementTypeAddColour[tileElementType];
}
return colour;
}
static uint16_t map_window_get_pixel_colour_ride(CoordsXY c)
{
Ride* ride;
uint16_t colourA = 0; // highlight colour
uint16_t colourB = MAP_COLOUR(PALETTE_INDEX_13); // surface colour (dark grey)
// as an improvement we could use first_element to show underground stuff?
TileElement* tileElement = reinterpret_cast<TileElement*>(map_get_surface_element_at(c));
do
{
if (tileElement == nullptr)
break;
if (tileElement->IsGhost())
{
colourA = MAP_COLOUR(PALETTE_INDEX_21);
break;
}
switch (tileElement->GetType())
{
case TILE_ELEMENT_TYPE_SURFACE:
if (tileElement->AsSurface()->GetWaterHeight() > 0)
// Why is this a different water colour as above (195)?
colourB = MAP_COLOUR(PALETTE_INDEX_194);
if (!(tileElement->AsSurface()->GetOwnership() & OWNERSHIP_OWNED))
colourB = MAP_COLOUR_UNOWNED(colourB);
break;
case TILE_ELEMENT_TYPE_PATH:
colourA = MAP_COLOUR(PALETTE_INDEX_14); // lighter grey
break;
case TILE_ELEMENT_TYPE_ENTRANCE:
if (tileElement->AsEntrance()->GetEntranceType() == ENTRANCE_TYPE_PARK_ENTRANCE)
break;
ride = get_ride(tileElement->AsEntrance()->GetRideIndex());
if (ride != nullptr)
colourA = RideKeyColours[RideColourKey[ride->type]];
break;
case TILE_ELEMENT_TYPE_TRACK:
ride = get_ride(tileElement->AsTrack()->GetRideIndex());
if (ride != nullptr)
colourA = RideKeyColours[RideColourKey[ride->type]];
break;
}
} while (!(tileElement++)->IsLastForTile());
if (colourA != 0)
return colourA;
return colourB;
}
static void map_window_set_pixels(rct_window* w)
{
uint16_t colour = 0;
int32_t x = 0, y = 0, dx = 0, dy = 0;
int32_t pos = (_currentLine * (MAP_WINDOW_MAP_SIZE - 1)) + MAXIMUM_MAP_SIZE_TECHNICAL - 1;
LocationXY16 destinationPosition = { static_cast<int16_t>(pos % MAP_WINDOW_MAP_SIZE),
static_cast<int16_t>(pos / MAP_WINDOW_MAP_SIZE) };
auto destination = _mapImageData.data() + (destinationPosition.y * MAP_WINDOW_MAP_SIZE) + destinationPosition.x;
switch (get_current_rotation())
{
case 0:
x = _currentLine * COORDS_XY_STEP;
y = 0;
dx = 0;
dy = COORDS_XY_STEP;
break;
case 1:
x = MAXIMUM_TILE_START_XY;
y = _currentLine * COORDS_XY_STEP;
dx = -COORDS_XY_STEP;
dy = 0;
break;
case 2:
x = MAXIMUM_MAP_SIZE_BIG - ((_currentLine + 1) * COORDS_XY_STEP);
y = MAXIMUM_TILE_START_XY;
dx = 0;
dy = -COORDS_XY_STEP;
break;
case 3:
x = 0;
y = MAXIMUM_MAP_SIZE_BIG - ((_currentLine + 1) * COORDS_XY_STEP);
dx = COORDS_XY_STEP;
dy = 0;
break;
}
for (int32_t i = 0; i < MAXIMUM_MAP_SIZE_TECHNICAL; i++)
{
if (x > 0 && y > 0 && x < gMapSizeUnits && y < gMapSizeUnits)
{
switch (w->selected_tab)
{
case PAGE_PEEPS:
colour = map_window_get_pixel_colour_peep({ x, y });
break;
case PAGE_RIDES:
colour = map_window_get_pixel_colour_ride({ x, y });
break;
}
destination[0] = (colour >> 8) & 0xFF;
destination[1] = colour;
}
x += dx;
y += dy;
destinationPosition.x++;
destinationPosition.y++;
destination = _mapImageData.data() + (destinationPosition.y * MAP_WINDOW_MAP_SIZE) + destinationPosition.x;
}
_currentLine++;
if (_currentLine >= MAXIMUM_MAP_SIZE_TECHNICAL)
_currentLine = 0;
}
static CoordsXY map_window_screen_to_map(ScreenCoordsXY screenCoords)
{
screenCoords.x = ((screenCoords.x + 8) - MAXIMUM_MAP_SIZE_TECHNICAL) / 2;
screenCoords.y = ((screenCoords.y + 8)) / 2;
int32_t x = (screenCoords.y - screenCoords.x) * 32;
int32_t y = (screenCoords.x + screenCoords.y) * 32;
switch (get_current_rotation())
{
case 0:
return { x, y };
case 1:
return { MAXIMUM_MAP_SIZE_BIG - 1 - y, x };
case 2:
return { MAXIMUM_MAP_SIZE_BIG - 1 - x, MAXIMUM_MAP_SIZE_BIG - 1 - y };
case 3:
return { y, MAXIMUM_MAP_SIZE_BIG - 1 - x };
}
return { 0, 0 }; // unreachable
}
|
IntelOrca/OpenRCT2
|
src/openrct2-ui/windows/Map.cpp
|
C++
|
gpl-3.0
| 60,419 |
#include <algorithm>
#include <functional>
#include <utility>
#include <vector>
#include "caffe/layer.hpp"
#include "caffe/vision_layers.hpp"
namespace caffe {
template <typename Dtype>
void ArgMaxLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
Layer<Dtype>::SetUp(bottom, top);
out_max_val_ = this->layer_param_.argmax_param().out_max_val();
top_k_ = this->layer_param_.argmax_param().top_k();
CHECK_GE(top_k_, 1) << " top k must not be less than 1.";
CHECK_LE(top_k_, bottom[0]->count() / bottom[0]->num())
<< "top_k must be less than or equal to the number of classes.";
if (out_max_val_) {
// Produces max_ind and max_val
(*top)[0]->Reshape(bottom[0]->num(), 2, top_k_, 1);
} else {
// Produces only max_ind
(*top)[0]->Reshape(bottom[0]->num(), 1, top_k_, 1);
}
}
template <typename Dtype>
Dtype ArgMaxLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = (*top)[0]->mutable_cpu_data();
int num = bottom[0]->num();
int dim = bottom[0]->count() / bottom[0]->num();
for (int i = 0; i < num; ++i) {
std::vector<std::pair<Dtype, int> > bottom_data_vector;
for (int j = 0; j < dim; ++j) {
bottom_data_vector.push_back(
std::make_pair(bottom_data[i * dim + j], j));
}
std::partial_sort(
bottom_data_vector.begin(), bottom_data_vector.begin() + top_k_,
bottom_data_vector.end(), std::greater<std::pair<Dtype, int> >());
for (int j = 0; j < top_k_; ++j) {
top_data[(*top)[0]->offset(i, 0, j)] = bottom_data_vector[j].second;
}
if (out_max_val_) {
for (int j = 0; j < top_k_; ++j) {
top_data[(*top)[0]->offset(i, 1, j)] = bottom_data_vector[j].first;
}
}
}
return Dtype(0);
}
INSTANTIATE_CLASS(ArgMaxLayer);
} // namespace caffe
|
mrgloom/fgs-obj
|
caffe/src/caffe/layers/argmax_layer.cpp
|
C++
|
gpl-3.0
| 1,925 |
function enter(pi) {
if (pi.isQuestActive(23049)) {
pi.getMap(pi.getMapId() + 10).resetFully();
pi.warp(pi.getMapId() + 10, 0);
} else {
pi.playerMessage(5, "Talk to your job instructor.");
}
}
|
Maxcloud/Mushy
|
scripts/portal/enterNewWeapon1.js
|
JavaScript
|
gpl-3.0
| 212 |
/***** Roundcube|Mail message print styles *****/
body
{
font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
background-color: #ffffff;
color: #000000;
margin: 2mm;
}
body, td, th, span, div, p
{
font-size: 9pt;
color: #000000;
}
h3
{
font-size: 18px;
color: #000000;
}
a, a:active, a:visited
{
color: #000000;
}
body > #logo
{
float: right;
margin: 0 5mm 3mm 5mm;
}
table.headers-table
{
table-layout: fixed;
margin-top: 14px;
}
table.headers-table tr td
{
font-size: 9pt;
}
table.headers-table td.header-title
{
color: #666666;
font-weight: bold;
text-align: right;
vertical-align: top;
padding-right: 4mm;
white-space: nowrap;
}
table.headers-table tr td.subject
{
width: 90%;
font-weight: bold;
}
#attachment-list
{
margin-top: 3mm;
padding-top: 3mm;
border-top: 1pt solid #cccccc;
}
#attachment-list li
{
font-size: 9pt;
}
#attachment-list li a
{
text-decoration: none;
}
#attachment-list li a:hover
{
text-decoration: underline;
}
#messagebody
{
margin-top: 5mm;
border-top: none;
}
div.message-part
{
padding: 2mm;
margin-top: 5mm;
margin-bottom: 5mm;
border-top: 1pt solid #cccccc;
}
div.message-part a
{
color: #0000CC;
}
div.message-part pre,
div.message-htmlpart pre,
div.message-part div.pre
{
margin: 0;
padding: 0;
font-family: monospace;
white-space: -moz-pre-wrap !important;
white-space: pre-wrap !important;
white-space: pre;
word-wrap: break-word; /* IE (and Safari) */
}
div.message-part blockquote
{
color: blue;
border-left: 2px solid blue;
border-right: 2px solid blue;
background-color: #F6F6F6;
margin: 2px 0px;
padding: 1px 8px 1px 10px;
}
div.message-part blockquote blockquote
{
color: green;
border-left: 2px solid green;
border-right: 2px solid green;
}
div.message-part blockquote blockquote blockquote
{
color: #990000;
border-left: 2px solid #bb0000;
border-right: 2px solid #bb0000;
}
|
xrg/roundcubemail
|
skins/default/print.css
|
CSS
|
gpl-3.0
| 1,964 |
#ifndef CAFFE_VISION_LAYERS_HPP_
#define CAFFE_VISION_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/common_layers.hpp"
#include "caffe/data_layers.hpp"
#include "caffe/layer.hpp"
#include "caffe/loss_layers.hpp"
#include "caffe/neuron_layers.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/* ConvolutionLayer
*/
template <typename Dtype>
class ConvolutionLayer : public Layer<Dtype> {
public:
explicit ConvolutionLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_CONVOLUTION;
}
virtual inline int MinBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline bool EqualNumBottomTopBlobs() const { return true; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int num_;
int channels_;
int pad_h_, pad_w_;
int height_;
int width_;
int num_output_;
int group_;
Blob<Dtype> col_buffer_;
Blob<Dtype> bias_multiplier_;
bool bias_term_;
int M_;
int K_;
int N_;
};
/* EltwiseLayer
Compute elementwise operations like product or sum.
*/
template <typename Dtype>
class EltwiseLayer : public Layer<Dtype> {
public:
explicit EltwiseLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_ELTWISE;
}
virtual inline int MinBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
EltwiseParameter_EltwiseOp op_;
vector<Dtype> coeffs_;
};
/* Im2colLayer
*/
template <typename Dtype>
class Im2colLayer : public Layer<Dtype> {
public:
explicit Im2colLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_IM2COL;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int channels_;
int height_;
int width_;
int pad_h_, pad_w_;
};
/* InnerProductLayer
*/
template <typename Dtype>
class InnerProductLayer : public Layer<Dtype> {
public:
explicit InnerProductLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_INNER_PRODUCT;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int M_;
int K_;
int N_;
bool bias_term_;
Blob<Dtype> bias_multiplier_;
};
// Forward declare PoolingLayer and SplitLayer for use in LRNLayer.
template <typename Dtype> class PoolingLayer;
template <typename Dtype> class SplitLayer;
/* LRNLayer
Local Response Normalization
*/
template <typename Dtype>
class LRNLayer : public Layer<Dtype> {
public:
explicit LRNLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_LRN;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual Dtype CrossChannelForward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype CrossChannelForward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype WithinChannelForward(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void CrossChannelBackward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void CrossChannelBackward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void WithinChannelBackward(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int size_;
int pre_pad_;
Dtype alpha_;
Dtype beta_;
int num_;
int channels_;
int height_;
int width_;
// Fields used for normalization ACROSS_CHANNELS
// scale_ stores the intermediate summing results
Blob<Dtype> scale_;
// Fields used for normalization WITHIN_CHANNEL
shared_ptr<SplitLayer<Dtype> > split_layer_;
vector<Blob<Dtype>*> split_top_vec_;
shared_ptr<PowerLayer<Dtype> > square_layer_;
Blob<Dtype> square_input_;
Blob<Dtype> square_output_;
vector<Blob<Dtype>*> square_bottom_vec_;
vector<Blob<Dtype>*> square_top_vec_;
shared_ptr<PoolingLayer<Dtype> > pool_layer_;
Blob<Dtype> pool_output_;
vector<Blob<Dtype>*> pool_top_vec_;
shared_ptr<PowerLayer<Dtype> > power_layer_;
Blob<Dtype> power_output_;
vector<Blob<Dtype>*> power_top_vec_;
shared_ptr<EltwiseLayer<Dtype> > product_layer_;
Blob<Dtype> product_data_input_;
vector<Blob<Dtype>*> product_bottom_vec_;
};
/* PoolingLayer
*/
template <typename Dtype>
class PoolingLayer : public Layer<Dtype> {
public:
explicit PoolingLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_POOLING;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline int MaxTopBlobs() const { return max_top_blobs_; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int max_top_blobs_;
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int pad_h_, pad_w_;
int channels_;
int height_;
int width_;
int pooled_height_;
int pooled_width_;
Blob<Dtype> rand_idx_;
Blob<int> max_idx_;
};
} // namespace caffe
#endif // CAFFE_VISION_LAYERS_HPP_
#include "caffe/vision_layers_custom.hpp"
|
mrgloom/fgs-obj
|
caffe/include/caffe/vision_layers.hpp
|
C++
|
gpl-3.0
| 9,250 |
<p>Hi [% destination_email %]</p>
<p>Thanks for trying to recover your password for [% config_name %] but it seems that you don't have an account.</p>
<p>In order to play, simply visit <a href="[% config_url %]">[% config_url %]</a> and register a new account.</p>
|
rpgwnn/rpgcat
|
templates/email/forgotten-notexists.mkit/body.html
|
HTML
|
gpl-3.0
| 268 |
/* $Id: ai_misc.c,v 1.10 2002/09/09 03:52:07 riq Exp $ */
/* Tenes Empanadas Graciela
*
* Copyright (C) 2000 Ricardo Quesada
*
* Author: Ricardo Calixto Quesada <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; only version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/**
* @file ai_misc.c
* Funciones que mucho no tienen que ver con el robot, pero ayudan
*/
#include <stdlib.h>
#include <stdio.h>
#include "client.h"
/**
* @fn char *ai_fetch_a_name()
* Devuelve el name de un player al azar
*/
char *ai_fetch_a_name()
{
int i=0;
PCPLAYER pJ;
PLIST_ENTRY l = g_list_player.Flink;
int n;
if( g_game.playeres < 2 ) {
return NULL;
}
n = RANDOM_MAX(0, g_game.playeres -1 );
while( !IsListEmpty( &g_list_player ) && (l != &g_list_player) ) {
if( (i++) == n ) {
pJ = (PCPLAYER) l;
if( pJ->numjug == WHOAMI() )
n++;
else
return pJ->name;
}
l = LIST_NEXT(l);
}
return NULL;
}
|
JeroenDeDauw/teg
|
robot/ai_misc.c
|
C
|
gpl-3.0
| 1,507 |
---
name: f1958
description: Function Nr. 1958
returns: varchar
---
RETURN f1957();
|
qua-bla/hamsql
|
test/setups/function-many/functions.d/f1958.sql
|
SQL
|
gpl-3.0
| 83 |
#!/usr/bin/python
# Copyright (c) 2011 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.
"""Prints the size of each given file and optionally computes the size of
libchrome.so without the dependencies added for building with android NDK.
Also breaks down the contents of the APK to determine the installed size
and assign size contributions to different classes of file.
"""
import collections
import json
import operator
import optparse
import os
import re
import sys
import tempfile
import zipfile
import zlib
import devil_chromium
from devil.utils import cmd_helper
from pylib import constants
from pylib.constants import host_paths
_GRIT_PATH = os.path.join(host_paths.DIR_SOURCE_ROOT, 'tools', 'grit')
with host_paths.SysPath(_GRIT_PATH):
from grit.format import data_pack # pylint: disable=import-error
with host_paths.SysPath(host_paths.BUILD_COMMON_PATH):
import perf_tests_results_helper # pylint: disable=import-error
# Static initializers expected in official builds. Note that this list is built
# using 'nm' on libchrome.so which results from a GCC official build (i.e.
# Clang is not supported currently).
_BASE_CHART = {
'format_version': '0.1',
'benchmark_name': 'resource_sizes',
'benchmark_description': 'APK resource size information.',
'trace_rerun_options': [],
'charts': {}
}
_DUMP_STATIC_INITIALIZERS_PATH = os.path.join(
host_paths.DIR_SOURCE_ROOT, 'tools', 'linux', 'dump-static-initializers.py')
_RC_HEADER_RE = re.compile(r'^#define (?P<name>\w+) (?P<id>\d+)$')
def CountStaticInitializers(so_path):
def get_elf_section_size(readelf_stdout, section_name):
# Matches: .ctors PROGBITS 000000000516add0 5169dd0 000010 00 WA 0 0 8
match = re.search(r'\.%s.*$' % re.escape(section_name),
readelf_stdout, re.MULTILINE)
if not match:
return (False, -1)
size_str = re.split(r'\W+', match.group(0))[5]
return (True, int(size_str, 16))
# Find the number of files with at least one static initializer.
# First determine if we're 32 or 64 bit
stdout = cmd_helper.GetCmdOutput(['readelf', '-h', so_path])
elf_class_line = re.search('Class:.*$', stdout, re.MULTILINE).group(0)
elf_class = re.split(r'\W+', elf_class_line)[1]
if elf_class == 'ELF32':
word_size = 4
else:
word_size = 8
# Then find the number of files with global static initializers.
# NOTE: this is very implementation-specific and makes assumptions
# about how compiler and linker implement global static initializers.
si_count = 0
stdout = cmd_helper.GetCmdOutput(['readelf', '-SW', so_path])
has_init_array, init_array_size = get_elf_section_size(stdout, 'init_array')
if has_init_array:
si_count = init_array_size / word_size
si_count = max(si_count, 0)
return si_count
def GetStaticInitializers(so_path):
output = cmd_helper.GetCmdOutput([_DUMP_STATIC_INITIALIZERS_PATH, '-d',
so_path])
return output.splitlines()
def ReportPerfResult(chart_data, graph_title, trace_title, value, units,
improvement_direction='down', important=True):
"""Outputs test results in correct format.
If chart_data is None, it outputs data in old format. If chart_data is a
dictionary, formats in chartjson format. If any other format defaults to
old format.
"""
if chart_data and isinstance(chart_data, dict):
chart_data['charts'].setdefault(graph_title, {})
chart_data['charts'][graph_title][trace_title] = {
'type': 'scalar',
'value': value,
'units': units,
'improvement_direction': improvement_direction,
'important': important
}
else:
perf_tests_results_helper.PrintPerfResult(
graph_title, trace_title, [value], units)
def PrintResourceSizes(files, chartjson=None):
"""Prints the sizes of each given file.
Args:
files: List of files to print sizes for.
"""
for f in files:
ReportPerfResult(chartjson, 'ResourceSizes', os.path.basename(f) + ' size',
os.path.getsize(f), 'bytes')
def PrintApkAnalysis(apk_filename, chartjson=None):
"""Analyse APK to determine size contributions of different file classes."""
# Define a named tuple type for file grouping.
# name: Human readable name for this file group
# regex: Regular expression to match filename
# extracted: Function that takes a file name and returns whether the file is
# extracted from the apk at install/runtime.
FileGroup = collections.namedtuple('FileGroup',
['name', 'regex', 'extracted'])
# File groups are checked in sequence, so more specific regexes should be
# earlier in the list.
YES = lambda _: True
NO = lambda _: False
FILE_GROUPS = (
FileGroup('Native code', r'\.so$', lambda f: 'crazy' not in f),
FileGroup('Java code', r'\.dex$', YES),
FileGroup('Native resources (no l10n)', r'\.pak$', NO),
# For locale paks, assume only english paks are extracted.
FileGroup('Native resources (l10n)', r'\.lpak$', lambda f: 'en_' in f),
FileGroup('ICU (i18n library) data', r'assets/icudtl\.dat$', NO),
FileGroup('V8 Snapshots', r'\.bin$', NO),
FileGroup('PNG drawables', r'\.png$', NO),
FileGroup('Non-compiled Android resources', r'^res/', NO),
FileGroup('Compiled Android resources', r'\.arsc$', NO),
FileGroup('Package metadata', r'^(META-INF/|AndroidManifest\.xml$)', NO),
FileGroup('Unknown files', r'.', NO),
)
apk = zipfile.ZipFile(apk_filename, 'r')
try:
apk_contents = apk.infolist()
finally:
apk.close()
total_apk_size = os.path.getsize(apk_filename)
apk_basename = os.path.basename(apk_filename)
found_files = {}
for group in FILE_GROUPS:
found_files[group] = []
for member in apk_contents:
for group in FILE_GROUPS:
if re.search(group.regex, member.filename):
found_files[group].append(member)
break
else:
raise KeyError('No group found for file "%s"' % member.filename)
total_install_size = total_apk_size
for group in FILE_GROUPS:
apk_size = sum(member.compress_size for member in found_files[group])
install_size = apk_size
install_bytes = sum(f.file_size for f in found_files[group]
if group.extracted(f.filename))
install_size += install_bytes
total_install_size += install_bytes
ReportPerfResult(chartjson, apk_basename + '_Breakdown',
group.name + ' size', apk_size, 'bytes')
ReportPerfResult(chartjson, apk_basename + '_InstallBreakdown',
group.name + ' size', install_size, 'bytes')
transfer_size = _CalculateCompressedSize(apk_filename)
ReportPerfResult(chartjson, apk_basename + '_InstallSize',
'Estimated installed size', total_install_size, 'bytes')
ReportPerfResult(chartjson, apk_basename + '_InstallSize', 'APK size',
total_apk_size, 'bytes')
ReportPerfResult(chartjson, apk_basename + '_TransferSize',
'Transfer size (deflate)', transfer_size, 'bytes')
def IsPakFileName(file_name):
"""Returns whether the given file name ends with .pak or .lpak."""
return file_name.endswith('.pak') or file_name.endswith('.lpak')
def PrintPakAnalysis(apk_filename, min_pak_resource_size):
"""Print sizes of all resources in all pak files in |apk_filename|."""
print
print 'Analyzing pak files in %s...' % apk_filename
# A structure for holding details about a pak file.
Pak = collections.namedtuple(
'Pak', ['filename', 'compress_size', 'file_size', 'resources'])
# Build a list of Pak objets for each pak file.
paks = []
apk = zipfile.ZipFile(apk_filename, 'r')
try:
for i in (x for x in apk.infolist() if IsPakFileName(x.filename)):
with tempfile.NamedTemporaryFile() as f:
f.write(apk.read(i.filename))
f.flush()
paks.append(Pak(i.filename, i.compress_size, i.file_size,
data_pack.DataPack.ReadDataPack(f.name).resources))
finally:
apk.close()
# Output the overall pak file summary.
total_files = len(paks)
total_compress_size = sum(pak.compress_size for pak in paks)
total_file_size = sum(pak.file_size for pak in paks)
print 'Total pak files: %d' % total_files
print 'Total compressed size: %s' % _FormatBytes(total_compress_size)
print 'Total uncompressed size: %s' % _FormatBytes(total_file_size)
print
# Output the table of details about all pak files.
print '%25s%11s%21s%21s' % (
'FILENAME', 'RESOURCES', 'COMPRESSED SIZE', 'UNCOMPRESSED SIZE')
for pak in sorted(paks, key=operator.attrgetter('file_size'), reverse=True):
print '%25s %10s %12s %6.2f%% %12s %6.2f%%' % (
pak.filename,
len(pak.resources),
_FormatBytes(pak.compress_size),
100.0 * pak.compress_size / total_compress_size,
_FormatBytes(pak.file_size),
100.0 * pak.file_size / total_file_size)
print
print 'Analyzing pak resources in %s...' % apk_filename
# Calculate aggregate stats about resources across pak files.
resource_count_map = collections.defaultdict(int)
resource_size_map = collections.defaultdict(int)
resource_overhead_bytes = 6
for pak in paks:
for r in pak.resources:
resource_count_map[r] += 1
resource_size_map[r] += len(pak.resources[r]) + resource_overhead_bytes
# Output the overall resource summary.
total_resource_size = sum(resource_size_map.values())
total_resource_count = len(resource_count_map)
assert total_resource_size <= total_file_size
print 'Total pak resources: %s' % total_resource_count
print 'Total uncompressed resource size: %s' % _FormatBytes(
total_resource_size)
print
resource_id_name_map = _GetResourceIdNameMap()
# Output the table of details about all resources across pak files.
print
print '%56s %5s %17s' % ('RESOURCE', 'COUNT', 'UNCOMPRESSED SIZE')
for i in sorted(resource_size_map, key=resource_size_map.get,
reverse=True):
if resource_size_map[i] >= min_pak_resource_size:
print '%56s %5s %9s %6.2f%%' % (
resource_id_name_map.get(i, i),
resource_count_map[i],
_FormatBytes(resource_size_map[i]),
100.0 * resource_size_map[i] / total_resource_size)
def _GetResourceIdNameMap():
"""Returns a map of {resource_id: resource_name}."""
out_dir = constants.GetOutDirectory()
assert os.path.isdir(out_dir), 'Failed to locate out dir at %s' % out_dir
print 'Looking at resources in: %s' % out_dir
grit_headers = []
for root, _, files in os.walk(out_dir):
if root.endswith('grit'):
grit_headers += [os.path.join(root, f) for f in files if f.endswith('.h')]
assert grit_headers, 'Failed to find grit headers in %s' % out_dir
id_name_map = {}
for header in grit_headers:
with open(header, 'r') as f:
for line in f.readlines():
m = _RC_HEADER_RE.match(line.strip())
if m:
i = int(m.group('id'))
name = m.group('name')
if i in id_name_map and name != id_name_map[i]:
print 'WARNING: Resource ID conflict %s (%s vs %s)' % (
i, id_name_map[i], name)
id_name_map[i] = name
return id_name_map
def PrintStaticInitializersCount(so_with_symbols_path, chartjson=None):
"""Emits the performance result for static initializers found in the provided
shared library. Additionally, files for which static initializers were
found are printed on the standard output.
Args:
so_with_symbols_path: Path to the unstripped libchrome.so file.
"""
# GetStaticInitializers uses get-static-initializers.py to get a list of all
# static initializers. This does not work on all archs (particularly arm).
# TODO(rnephew): Get rid of warning when crbug.com/585588 is fixed.
si_count = CountStaticInitializers(so_with_symbols_path)
static_initializers = GetStaticInitializers(so_with_symbols_path)
if si_count != len(static_initializers):
print ('There are %d files with static initializers, but '
'dump-static-initializers found %d:' %
(si_count, len(static_initializers)))
else:
print 'Found %d files with static initializers:' % si_count
print '\n'.join(static_initializers)
ReportPerfResult(chartjson, 'StaticInitializersCount', 'count',
si_count, 'count')
def _FormatBytes(byts):
"""Pretty-print a number of bytes."""
if byts > 2**20.0:
byts /= 2**20.0
return '%.2fm' % byts
if byts > 2**10.0:
byts /= 2**10.0
return '%.2fk' % byts
return str(byts)
def _CalculateCompressedSize(file_path):
CHUNK_SIZE = 256 * 1024
compressor = zlib.compressobj()
total_size = 0
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), ''):
total_size += len(compressor.compress(chunk))
total_size += len(compressor.flush())
return total_size
def main(argv):
usage = """Usage: %prog [options] file1 file2 ...
Pass any number of files to graph their sizes. Any files with the extension
'.apk' will be broken down into their components on a separate graph."""
option_parser = optparse.OptionParser(usage=usage)
option_parser.add_option('--so-path', help='Path to libchrome.so.')
option_parser.add_option('--so-with-symbols-path',
help='Path to libchrome.so with symbols.')
option_parser.add_option('--min-pak-resource-size', type='int',
default=20*1024,
help='Minimum byte size of displayed pak resources.')
option_parser.add_option('--build_type', dest='build_type', default='Debug',
help='Sets the build type, default is Debug.')
option_parser.add_option('--chromium-output-directory',
help='Location of the build artifacts. '
'Takes precidence over --build_type.')
option_parser.add_option('--chartjson', action="store_true",
help='Sets output mode to chartjson.')
option_parser.add_option('--output-dir', default='.',
help='Directory to save chartjson to.')
option_parser.add_option('-d', '--device',
help='Dummy option for perf runner.')
options, args = option_parser.parse_args(argv)
files = args[1:]
chartjson = _BASE_CHART.copy() if options.chartjson else None
constants.SetBuildType(options.build_type)
if options.chromium_output_directory:
constants.SetOutputDirectory(options.chromium_output_directory)
constants.CheckOutputDirectory()
# For backward compatibilty with buildbot scripts, treat --so-path as just
# another file to print the size of. We don't need it for anything special any
# more.
if options.so_path:
files.append(options.so_path)
if not files:
option_parser.error('Must specify a file')
devil_chromium.Initialize()
if options.so_with_symbols_path:
PrintStaticInitializersCount(
options.so_with_symbols_path, chartjson=chartjson)
PrintResourceSizes(files, chartjson=chartjson)
for f in files:
if f.endswith('.apk'):
PrintApkAnalysis(f, chartjson=chartjson)
PrintPakAnalysis(f, options.min_pak_resource_size)
if chartjson:
results_path = os.path.join(options.output_dir, 'results-chart.json')
with open(results_path, 'w') as json_file:
json.dump(chartjson, json_file)
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
golden1232004/webrtc_new
|
chromium/src/build/android/resource_sizes.py
|
Python
|
gpl-3.0
| 15,653 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* 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/. */
#ifndef mozilla_dom_quota_quotacommon_h__
#define mozilla_dom_quota_quotacommon_h__
#include "nsAutoPtr.h"
#include "nsCOMPtr.h"
#include "nsDebug.h"
#include "nsStringGlue.h"
#include "nsTArray.h"
#define BEGIN_QUOTA_NAMESPACE \
namespace mozilla { namespace dom { namespace quota {
#define END_QUOTA_NAMESPACE \
} /* namespace quota */ } /* namespace dom */ } /* namespace mozilla */
#define USING_QUOTA_NAMESPACE \
using namespace mozilla::dom::quota;
#endif // mozilla_dom_quota_quotacommon_h__
|
DragonZX/fdm
|
Gecko.SDK/22/include/mozilla/dom/quota/QuotaCommon.h
|
C
|
gpl-3.0
| 829 |
{% extends 'layout/base.html' %}
{% from 'forms/_form.html' import form_header, form_footer, form_rows, form_row, form_fieldset %}
{% block title %}
{%- trans %}Layout{% endtrans -%}
{% endblock %}
{%- block content %}
{{ form_header(form, action=url_for('event_layout.index', event)) }}
{% call form_fieldset(_('General')) %}
{{ form_rows(form, fields=('is_searchable', 'show_nav_bar', 'show_banner', 'show_social_badges')) }}
{% endcall %}
{% call form_fieldset(_('Header Style')) %}
{{ form_rows(form, fields=('header_text_color', 'header_background_color')) }}
{% endcall %}
{% call form_fieldset(_('Announcement')) %}
{{ form_rows(form, fields=('announcement', 'show_announcement')) }}
{% endcall %}
{% call form_fieldset(_('Timetable')) %}
{{ form_rows(form, fields=('timetable_by_room', 'timetable_detailed')) }}
{% endcall %}
{% call form_fieldset(_('Theme')) %}
{{ form_row(form.use_custom_css) }}
{% call form_row(form.theme) %}
<a class="i-button i-form-field-button js-theme-preview-btn icon-eye" target="_blank"
href="{{ url_for('event_layout.css_preview', event) }}">
{%- trans %}Preview{% endtrans -%}
</a>
{% endcall %}
{% endcall %}
{% call form_footer(form) %}
<input class="i-button big highlight" type="submit" value="{% trans %}Save{% endtrans %}" data-disabled-until-change>
{% endcall %}
<h2>{% trans %}Stylesheet{% endtrans %}</h2>
{{ form_header(css_form, classes='css-form', action=url_for('event_layout.upload_css', event)) }}
<div class="flashed-messages"></div>
{% call form_row(css_form.css_file, skip_label=true) %}
<a class="i-button i-form-field-button i-form-field-width icon-eye js-preview-button
{%- if not css_form.css_file.data %} weak-hidden{% endif %}"
target="_blank"
href="{{ url_for('event_layout.css_preview', event, theme='_custom') }}">
{%- trans %}Preview{% endtrans -%}
</a>
{% endcall %}
{% call form_footer(css_form) %}
<button class="i-button js-dropzone-upload highlight icon-upload" data-disabled-until-change>
{% trans %}Upload CSS file{% endtrans %}
</button>
<button class="i-button js-remove-button danger icon-remove{% if not css_form.css_file.data %} weak-hidden{% endif %}"
data-href="{{ url_for('event_layout.delete_css', event) }}" data-method="DELETE">
{% trans %}Delete{% endtrans %}
</button>
{% endcall %}
<h2>{% trans %}Event Logo{% endtrans %}</h2>
{{ form_header(logo_form, classes='logo-form', action=url_for('event_layout.upload_logo', event)) }}
<div class="flashed-messages"></div>
{{ form_rows(logo_form, skip_labels=true) }}
{% call form_footer(css_form) %}
<button class="i-button js-dropzone-upload highlight icon-upload" data-disabled-until-change>
{% trans %}Upload logo{% endtrans %}
</button>
<button class="i-button js-remove-button danger icon-remove{% if not logo_form.logo.data %} weak-hidden{% endif %}"
data-href="{{ url_for('event_layout.delete_logo', event) }}" data-method="DELETE">
{% trans %}Delete{% endtrans %}
</button>
{% endcall %}
<script>
$(document).ready(function() {
'use strict';
$('#theme').nullableselector({nullvalue: ''}).on('change', function() {
var previewURL = build_url({{ url_for('event_layout.css_preview', event) | tojson }}, {
theme: $(this).val()
});
$(this).nextAll('.js-theme-preview-btn').attr('href', previewURL);
}).trigger('change');
function updateCustomCSS(hasFile) {
var useCustomCSS = $('#use_custom_css');
useCustomCSS.prop('disabled', !hasFile);
if (!hasFile) {
var form = $('#use_custom_css').closest('form');
var formData = form.data('initialData');
useCustomCSS.prop('checked', false).trigger('change');
// we need to inform the change tracking system about the new server-side value
formData = formData.replace(/&use_custom_css=y/, '');
// also add the theme field (it's enabled now so it's empty instead of not present)
if (!~formData.indexOf('&theme=')) {
formData += '&theme=' + encodeURIComponent($('#theme').val());
}
form.data('initialData', formData).trigger('change');
}
}
updateCustomCSS({{ (css_form.css_file.data is not none) | tojson }});
$('.css-form, .logo-form').on('indico:fieldsSaved', function(e, response) {
var hidden = !response.content;
var $this = $(this);
$this.find('.js-remove-button, .js-preview-button').toggleClass('weak-hidden', hidden).prop('disabled', hidden);
if ($this.is('.css-form')) {
updateCustomCSS(!hidden);
}
}).on('click', '.js-remove-button', function(e) {
var $this = $(this);
var $form = $this.closest('form');
var dropzone = $form.get(0).dropzone;
$this.prop('disabled', true);
e.preventDefault();
$.ajax({
url: $this.data('href'),
method: $this.data('method'),
complete: IndicoUI.Dialogs.Util.progress(),
error: handleAjaxError,
success: function(data) {
handleFlashes(data, true, $form.find('.flashed-messages'));
dropzone.removeAllFiles();
$form.trigger('indico:fieldsSaved', data);
}
});
});
});
</script>
{%- endblock %}
|
XeCycle/indico
|
indico/modules/events/layout/templates/layout.html
|
HTML
|
gpl-3.0
| 6,255 |
--
-- Type: TABLE; Owner: DEAPP; Name: DE_QPCR_MIRNA_ANNOTATION
--
CREATE TABLE "DEAPP"."DE_QPCR_MIRNA_ANNOTATION"
( "ID_REF" VARCHAR2(100 BYTE),
"PROBE_ID" VARCHAR2(100 BYTE),
"MIRNA_SYMBOL" VARCHAR2(100 BYTE),
"MIRNA_ID" VARCHAR2(100 BYTE),
"PROBESET_ID" NUMBER(38,0),
"ORGANISM" VARCHAR2(200 BYTE),
"GPL_ID" VARCHAR2(20 BYTE),
PRIMARY KEY ("PROBESET_ID")
USING INDEX
TABLESPACE "TRANSMART" ENABLE
) SEGMENT CREATION IMMEDIATE
NOCOMPRESS LOGGING
TABLESPACE "TRANSMART" ;
|
tranSMART-Foundation/transmart-data
|
ddl/oracle/deapp/de_qpcr_mirna_annotation.sql
|
SQL
|
gpl-3.0
| 483 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
#ifndef nsView_h__
#define nsView_h__
#include "nsCoord.h"
#include "nsRect.h"
#include "nsPoint.h"
#include "nsRegion.h"
#include "nsCRT.h"
#include "nsEvent.h"
#include "nsIWidgetListener.h"
class nsViewManager;
class nsIWidget;
class nsIFrame;
// Enumerated type to indicate the visibility of a layer.
// hide - the layer is not shown.
// show - the layer is shown irrespective of the visibility of
// the layer's parent.
enum nsViewVisibility {
nsViewVisibility_kHide = 0,
nsViewVisibility_kShow = 1
};
// Public view flags
// Indicates that the view is using auto z-indexing
#define NS_VIEW_FLAG_AUTO_ZINDEX 0x0004
// Indicates that the view is a floating view.
#define NS_VIEW_FLAG_FLOATING 0x0008
// If set it indicates that this view should be
// displayed above z-index:auto views if this view
// is z-index:auto also
#define NS_VIEW_FLAG_TOPMOST 0x0010
//----------------------------------------------------------------------
/**
* View interface
*
* Views are NOT reference counted. Use the Destroy() member function to
* destroy a view.
*
* The lifetime of the view hierarchy is bounded by the lifetime of the
* view manager that owns the views.
*
* Most of the methods here are read-only. To set the corresponding properties
* of a view, go through nsViewManager.
*/
class nsView MOZ_FINAL : public nsIWidgetListener
{
public:
friend class nsViewManager;
NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
/**
* Get the view manager which "owns" the view.
* This method might require some expensive traversal work in the future. If you can get the
* view manager from somewhere else, do that instead.
* @result the view manager
*/
nsViewManager* GetViewManager() const { return mViewManager; }
/**
* Find the view for the given widget, if there is one.
* @return the view the widget belongs to, or null if the widget doesn't
* belong to any view.
*/
static nsView* GetViewFor(nsIWidget* aWidget);
/**
* Destroy the view.
*
* The view destroys its child views, and destroys and releases its
* widget (if it has one).
*
* Also informs the view manager that the view is destroyed by calling
* SetRootView(NULL) if the view is the root view and calling RemoveChild()
* otherwise.
*/
void Destroy();
/**
* Called to get the position of a view.
* The specified coordinates are relative to the parent view's origin, but
* are in appunits of this.
* This is the (0, 0) origin of the coordinate space established by this view.
* @param x out parameter for x position
* @param y out parameter for y position
*/
nsPoint GetPosition() const {
NS_ASSERTION(!IsRoot() || (mPosX == 0 && mPosY == 0),
"root views should always have explicit position of (0,0)");
return nsPoint(mPosX, mPosY);
}
/**
* Called to get the dimensions and position of the view's bounds.
* The view's bounds (x,y) are relative to the origin of the parent view, but
* are in appunits of this.
* The view's bounds (x,y) might not be the same as the view's position,
* if the view has content above or to the left of its origin.
* @param aBounds out parameter for bounds
*/
nsRect GetBounds() const { return mDimBounds; }
/**
* The bounds of this view relative to this view. So this is the same as
* GetBounds except this is relative to this view instead of the parent view.
*/
nsRect GetDimensions() const {
nsRect r = mDimBounds; r.MoveBy(-mPosX, -mPosY); return r;
}
/**
* Get the offset between the coordinate systems of |this| and aOther.
* Adding the return value to a point in the coordinate system of |this|
* will transform the point to the coordinate system of aOther.
*
* The offset is expressed in appunits of |this|. So if you are getting the
* offset between views in different documents that might have different
* appunits per devpixel ratios you need to be careful how you use the
* result.
*
* If aOther is null, this will return the offset of |this| from the
* root of the viewmanager tree.
*
* This function is fastest when aOther is an ancestor of |this|.
*
* NOTE: this actually returns the offset from aOther to |this|, but
* that offset is added to transform _coordinates_ from |this| to aOther.
*/
nsPoint GetOffsetTo(const nsView* aOther) const;
/**
* Get the offset between the origin of |this| and the origin of aWidget.
* Adding the return value to a point in the coordinate system of |this|
* will transform the point to the coordinate system of aWidget.
*
* The offset is expressed in appunits of |this|.
*/
nsPoint GetOffsetToWidget(nsIWidget* aWidget) const;
/**
* Takes a point aPt that is in the coordinate system of |this|'s parent view
* and converts it to be in the coordinate system of |this| taking into
* account the offset and any app unit per dev pixel ratio differences.
*/
nsPoint ConvertFromParentCoords(nsPoint aPt) const;
/**
* Called to query the visibility state of a view.
* @result current visibility state
*/
nsViewVisibility GetVisibility() const { return mVis; }
/**
* Get whether the view "floats" above all other views,
* which tells the compositor not to consider higher views in
* the view hierarchy that would geometrically intersect with
* this view. This is a hack, but it fixes some problems with
* views that need to be drawn in front of all other views.
* @result true if the view floats, false otherwise.
*/
bool GetFloating() const { return (mVFlags & NS_VIEW_FLAG_FLOATING) != 0; }
/**
* Called to query the parent of the view.
* @result view's parent
*/
nsView* GetParent() const { return mParent; }
/**
* The view's first child is the child which is earliest in document order.
* @result first child
*/
nsView* GetFirstChild() const { return mFirstChild; }
/**
* Called to query the next sibling of the view.
* @result view's next sibling
*/
nsView* GetNextSibling() const { return mNextSibling; }
/**
* Set the view's frame.
*/
void SetFrame(nsIFrame* aRootFrame) { mFrame = aRootFrame; }
/**
* Retrieve the view's frame.
*/
nsIFrame* GetFrame() const { return mFrame; }
/**
* Get the nearest widget in this view or a parent of this view and
* the offset from the widget's origin to this view's origin
* @param aOffset - if non-null the offset from this view's origin to the
* widget's origin (usually positive) expressed in appunits of this will be
* returned in aOffset.
* @return the widget closest to this view; can be null because some view trees
* don't have widgets at all (e.g., printing), but if any view in the view tree
* has a widget, then it's safe to assume this will not return null
*/
nsIWidget* GetNearestWidget(nsPoint* aOffset) const;
/**
* Create a widget to associate with this view. This variant of
* CreateWidget*() will look around in the view hierarchy for an
* appropriate parent widget for the view.
*
* @param aWidgetInitData data used to initialize this view's widget before
* its create is called.
* @return error status
*/
nsresult CreateWidget(nsWidgetInitData *aWidgetInitData = nullptr,
bool aEnableDragDrop = true,
bool aResetVisibility = true);
/**
* Create a widget for this view with an explicit parent widget.
* |aParentWidget| must be nonnull. The other params are the same
* as for |CreateWidget()|.
*/
nsresult CreateWidgetForParent(nsIWidget* aParentWidget,
nsWidgetInitData *aWidgetInitData = nullptr,
bool aEnableDragDrop = true,
bool aResetVisibility = true);
/**
* Create a popup widget for this view. Pass |aParentWidget| to
* explicitly set the popup's parent. If it's not passed, the view
* hierarchy will be searched for an appropriate parent widget. The
* other params are the same as for |CreateWidget()|, except that
* |aWidgetInitData| must be nonnull.
*/
nsresult CreateWidgetForPopup(nsWidgetInitData *aWidgetInitData,
nsIWidget* aParentWidget = nullptr,
bool aEnableDragDrop = true,
bool aResetVisibility = true);
/**
* Destroys the associated widget for this view. If this method is
* not called explicitly, the widget when be destroyed when its
* view gets destroyed.
*/
void DestroyWidget();
/**
* Attach/detach a top level widget from this view. When attached, the view
* updates the widget's device context and allows the view to begin receiving
* gecko events. The underlying base window associated with the widget will
* continues to receive events it expects.
*
* An attached widget will not be destroyed when the view is destroyed,
* allowing the recycling of a single top level widget over multiple views.
*
* @param aWidget The widget to attach to / detach from.
*/
nsresult AttachToTopLevelWidget(nsIWidget* aWidget);
nsresult DetachFromTopLevelWidget();
/**
* Returns a flag indicating whether the view owns it's widget
* or is attached to an existing top level widget.
*/
bool IsAttachedToTopLevel() const { return mWidgetIsTopLevel; }
/**
* In 4.0, the "cutout" nature of a view is queryable.
* If we believe that all cutout view have a native widget, this
* could be a replacement.
* @param aWidget out parameter for widget that this view contains,
* or nullptr if there is none.
*/
nsIWidget* GetWidget() const { return mWindow; }
/**
* Returns true if the view has a widget associated with it.
*/
bool HasWidget() const { return mWindow != nullptr; }
void SetForcedRepaint(bool aForceRepaint) {
if (!mInAlternatePaint) {
mForcedRepaint = aForceRepaint;
}
}
/**
* Returns true if the view is currently painting
* into an alternate destination, such as the titlebar
* area on OSX.
*/
bool InAlternatePaint() { return mInAlternatePaint; }
/**
* Make aWidget direct its events to this view.
* The caller must call DetachWidgetEventHandler before this view
* is destroyed.
*/
void AttachWidgetEventHandler(nsIWidget* aWidget);
/**
* Stop aWidget directing its events to this view.
*/
void DetachWidgetEventHandler(nsIWidget* aWidget);
#ifdef DEBUG
/**
* Output debug info to FILE
* @param out output file handle
* @param aIndent indentation depth
* NOTE: virtual so that debugging tools not linked into gklayout can access it
*/
virtual void List(FILE* out, int32_t aIndent = 0) const;
#endif // DEBUG
/**
* @result true iff this is the root view for its view manager
*/
bool IsRoot() const;
nsIntRect CalcWidgetBounds(nsWindowType aType);
// This is an app unit offset to add when converting view coordinates to
// widget coordinates. It is the offset in view coordinates from widget
// origin (unlike views, widgets can't extend above or to the left of their
// origin) to view origin expressed in appunits of this.
nsPoint ViewToWidgetOffset() const { return mViewToWidgetOffset; }
/**
* Called to indicate that the position of the view has been changed.
* The specified coordinates are in the parent view's coordinate space.
* @param x new x position
* @param y new y position
*/
void SetPosition(nscoord aX, nscoord aY);
/**
* Called to indicate that the z-index of a view has been changed.
* The z-index is relative to all siblings of the view.
* @param aAuto Indicate that the z-index of a view is "auto". An "auto" z-index
* means that the view does not define a new stacking context,
* which means that the z-indicies of the view's children are
* relative to the view's siblings.
* @param zindex new z depth
*/
void SetZIndex(bool aAuto, int32_t aZIndex, bool aTopMost);
bool GetZIndexIsAuto() const { return (mVFlags & NS_VIEW_FLAG_AUTO_ZINDEX) != 0; }
int32_t GetZIndex() const { return mZIndex; }
void SetParent(nsView *aParent) { mParent = aParent; }
void SetNextSibling(nsView *aSibling)
{
NS_ASSERTION(aSibling != this, "Can't be our own sibling!");
mNextSibling = aSibling;
}
nsRegion* GetDirtyRegion() {
if (!mDirtyRegion) {
NS_ASSERTION(!mParent || GetFloating(),
"Only display roots should have dirty regions");
mDirtyRegion = new nsRegion();
NS_ASSERTION(mDirtyRegion, "Out of memory!");
}
return mDirtyRegion;
}
// nsIWidgetListener
virtual nsIPresShell* GetPresShell() MOZ_OVERRIDE;
virtual nsView* GetView() MOZ_OVERRIDE { return this; }
virtual bool WindowMoved(nsIWidget* aWidget, int32_t x, int32_t y) MOZ_OVERRIDE;
virtual bool WindowResized(nsIWidget* aWidget, int32_t aWidth, int32_t aHeight) MOZ_OVERRIDE;
virtual bool RequestWindowClose(nsIWidget* aWidget) MOZ_OVERRIDE;
virtual void WillPaintWindow(nsIWidget* aWidget) MOZ_OVERRIDE;
virtual bool PaintWindow(nsIWidget* aWidget, nsIntRegion aRegion, uint32_t aFlags) MOZ_OVERRIDE;
virtual void DidPaintWindow() MOZ_OVERRIDE;
virtual void RequestRepaint() MOZ_OVERRIDE;
virtual nsEventStatus HandleEvent(nsGUIEvent* aEvent, bool aUseAttachedEvents) MOZ_OVERRIDE;
virtual ~nsView();
nsPoint GetOffsetTo(const nsView* aOther, const int32_t aAPD) const;
nsIWidget* GetNearestWidget(nsPoint* aOffset, const int32_t aAPD) const;
private:
nsView(nsViewManager* aViewManager = nullptr,
nsViewVisibility aVisibility = nsViewVisibility_kShow);
bool ForcedRepaint() { return mForcedRepaint; }
// Do the actual work of ResetWidgetBounds, unconditionally. Don't
// call this method if we have no widget.
void DoResetWidgetBounds(bool aMoveOnly, bool aInvalidateChangedSize);
void InitializeWindow(bool aEnableDragDrop, bool aResetVisibility);
bool IsEffectivelyVisible();
/**
* Called to indicate that the dimensions of the view have been changed.
* The x and y coordinates may be < 0, indicating that the view extends above
* or to the left of its origin position. The term 'dimensions' indicates it
* is relative to this view.
*/
void SetDimensions(const nsRect &aRect, bool aPaint = true,
bool aResizeWidget = true);
/**
* Called to indicate that the visibility of a view has been
* changed.
* @param visibility new visibility state
*/
void SetVisibility(nsViewVisibility visibility);
/**
* Set/Get whether the view "floats" above all other views,
* which tells the compositor not to consider higher views in
* the view hierarchy that would geometrically intersect with
* this view. This is a hack, but it fixes some problems with
* views that need to be drawn in front of all other views.
* @result true if the view floats, false otherwise.
*/
void SetFloating(bool aFloatingView);
// Helper function to get mouse grabbing off this view (by moving it to the
// parent, if we can)
void DropMouseGrabbing();
// Same as GetBounds but converts to parent appunits if they are different.
nsRect GetBoundsInParentUnits() const;
bool HasNonEmptyDirtyRegion() {
return mDirtyRegion && !mDirtyRegion->IsEmpty();
}
void InsertChild(nsView *aChild, nsView *aSibling);
void RemoveChild(nsView *aChild);
void SetTopMost(bool aTopMost) { aTopMost ? mVFlags |= NS_VIEW_FLAG_TOPMOST : mVFlags &= ~NS_VIEW_FLAG_TOPMOST; }
bool IsTopMost() { return((mVFlags & NS_VIEW_FLAG_TOPMOST) != 0); }
void ResetWidgetBounds(bool aRecurse, bool aForceSync);
void AssertNoWindow();
void NotifyEffectiveVisibilityChanged(bool aEffectivelyVisible);
// Update the cached RootViewManager for all view manager descendents,
// If the hierarchy is being removed, aViewManagerParent points to the view
// manager for the hierarchy's old parent, and will have its mouse grab
// released if it points to any view in this view hierarchy.
void InvalidateHierarchy(nsViewManager *aViewManagerParent);
nsViewManager *mViewManager;
nsView *mParent;
nsIWidget *mWindow;
nsView *mNextSibling;
nsView *mFirstChild;
nsIFrame *mFrame;
nsRegion *mDirtyRegion;
int32_t mZIndex;
nsViewVisibility mVis;
// position relative our parent view origin but in our appunits
nscoord mPosX, mPosY;
// relative to parent, but in our appunits
nsRect mDimBounds;
// in our appunits
nsPoint mViewToWidgetOffset;
uint32_t mVFlags;
bool mWidgetIsTopLevel;
bool mForcedRepaint;
bool mInAlternatePaint;
};
#endif
|
DragonZX/fdm
|
Gecko.SDK/22/include/nsView.h
|
C
|
gpl-3.0
| 17,224 |
/*! @license Firebase v4.3.1
Build: rev-b4fe95f
Terms: https://firebase.google.com/terms/ */
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WriteTreeCompleteChildSource = exports.NO_COMPLETE_CHILD_SOURCE = exports.NoCompleteChildSource_ = undefined;
var _CacheNode = require('./CacheNode');
/**
* An implementation of CompleteChildSource that never returns any additional children
*
* @private
* @constructor
* @implements CompleteChildSource
*/
var NoCompleteChildSource_ = function () {
function NoCompleteChildSource_() {}
/**
* @inheritDoc
*/
NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
return null;
};
/**
* @inheritDoc
*/
NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
return null;
};
return NoCompleteChildSource_;
}(); /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.NoCompleteChildSource_ = NoCompleteChildSource_;
/**
* Singleton instance.
* @const
* @type {!CompleteChildSource}
*/
var NO_COMPLETE_CHILD_SOURCE = exports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
/**
* An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
* old event caches available to calculate complete children.
*
*
* @implements CompleteChildSource
*/
var WriteTreeCompleteChildSource = function () {
/**
* @param {!WriteTreeRef} writes_
* @param {!ViewCache} viewCache_
* @param {?Node} optCompleteServerCache_
*/
function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
if (optCompleteServerCache_ === void 0) {
optCompleteServerCache_ = null;
}
this.writes_ = writes_;
this.viewCache_ = viewCache_;
this.optCompleteServerCache_ = optCompleteServerCache_;
}
/**
* @inheritDoc
*/
WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
var node = this.viewCache_.getEventCache();
if (node.isCompleteForChild(childKey)) {
return node.getNode().getImmediateChild(childKey);
} else {
var serverNode = this.optCompleteServerCache_ != null ? new _CacheNode.CacheNode(this.optCompleteServerCache_, true, false) : this.viewCache_.getServerCache();
return this.writes_.calcCompleteChild(childKey, serverNode);
}
};
/**
* @inheritDoc
*/
WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
var completeServerData = this.optCompleteServerCache_ != null ? this.optCompleteServerCache_ : this.viewCache_.getCompleteServerSnap();
var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);
if (nodes.length === 0) {
return null;
} else {
return nodes[0];
}
};
return WriteTreeCompleteChildSource;
}();
exports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;
//# sourceMappingURL=CompleteChildSource.js.map
|
chidelmun/Zikki
|
node_modules/firebase/database/core/view/CompleteChildSource.js
|
JavaScript
|
gpl-3.0
| 3,756 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>iipsrv: JPEGCompressor Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.3 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">iipsrv <span id="projectnumber">0.9.9</span></div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('classJPEGCompressor.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> </div>
<div class="headertitle">
<h1>JPEGCompressor Class Reference</h1> </div>
</div>
<div class="contents">
<!-- doxytag: class="JPEGCompressor" -->
<p>Wrapper class to the IJG JPEG library.
<a href="#_details">More...</a></p>
<p><code>#include <<a class="el" href="JPEGCompressor_8h_source.html">JPEGCompressor.h</a>></code></p>
<p><a href="classJPEGCompressor-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#a075720ce0e74f48b1d48498039da2539">JPEGCompressor</a> (int quality)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Constructor. <a href="#a075720ce0e74f48b1d48498039da2539"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#a60a3aa47f982f64374ccff5b073c0011">setQuality</a> (int factor)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Set the compression quality. <a href="#a60a3aa47f982f64374ccff5b073c0011"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac747bb7eaf4c82a50b1ba5127d46eeaa"></a><!-- doxytag: member="JPEGCompressor::getQuality" ref="ac747bb7eaf4c82a50b1ba5127d46eeaa" args="()" -->
int </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#ac747bb7eaf4c82a50b1ba5127d46eeaa">getQuality</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Get the current quality level. <br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#ae27974f9307640062b5c805298b7d283">InitCompression</a> (<a class="el" href="classRawTile.html">RawTile</a> &rawtile, unsigned int strip_height) throw (std::string)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Initialise strip based compression. <a href="#ae27974f9307640062b5c805298b7d283"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">unsigned int </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#a7bdfd280a3433d058567b11dea6814a4">CompressStrip</a> (unsigned char *s, unsigned int tile_height) throw (std::string)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Compress a strip of image data. <a href="#a7bdfd280a3433d058567b11dea6814a4"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae53d86051b5d62380b4a8022528a5d36"></a><!-- doxytag: member="JPEGCompressor::Finish" ref="ae53d86051b5d62380b4a8022528a5d36" args="()" -->
unsigned int </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#ae53d86051b5d62380b4a8022528a5d36">Finish</a> () throw (std::string)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Finish the strip based compression and free memory. <br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#a440be83d168800cd6cddc4e9329a503e">Compress</a> (<a class="el" href="classRawTile.html">RawTile</a> &t) throw (std::string)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Compress an entire buffer of image data at once in one command. <a href="#a440be83d168800cd6cddc4e9329a503e"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a62fd19a3b193d907f796cc53d1fc8919"></a><!-- doxytag: member="JPEGCompressor::getHeaderSize" ref="a62fd19a3b193d907f796cc53d1fc8919" args="()" -->
unsigned int </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#a62fd19a3b193d907f796cc53d1fc8919">getHeaderSize</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Return the JPEG header size. <br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae8dd617d645caabaa5fad022a24331c2"></a><!-- doxytag: member="JPEGCompressor::getHeader" ref="ae8dd617d645caabaa5fad022a24331c2" args="()" -->
unsigned char * </td><td class="memItemRight" valign="bottom"><a class="el" href="classJPEGCompressor.html#ae8dd617d645caabaa5fad022a24331c2">getHeader</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Return a pointer to the header itself. <br/></td></tr>
</table>
<hr/><a name="_details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Wrapper class to the IJG JPEG library. </p>
</div><hr/><h2>Constructor & Destructor Documentation</h2>
<a class="anchor" id="a075720ce0e74f48b1d48498039da2539"></a><!-- doxytag: member="JPEGCompressor::JPEGCompressor" ref="a075720ce0e74f48b1d48498039da2539" args="(int quality)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">JPEGCompressor::JPEGCompressor </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>quality</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Constructor. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">quality</td><td>JPEG Quality factor (0-100) </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="a440be83d168800cd6cddc4e9329a503e"></a><!-- doxytag: member="JPEGCompressor::Compress" ref="a440be83d168800cd6cddc4e9329a503e" args="(RawTile &t)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int JPEGCompressor::Compress </td>
<td>(</td>
<td class="paramtype"><a class="el" href="classRawTile.html">RawTile</a> & </td>
<td class="paramname"><em>t</em></td><td>)</td>
<td> throw (std::string)</td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Compress an entire buffer of image data at once in one command. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">t</td><td>tile of image data </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="a7bdfd280a3433d058567b11dea6814a4"></a><!-- doxytag: member="JPEGCompressor::CompressStrip" ref="a7bdfd280a3433d058567b11dea6814a4" args="(unsigned char *s, unsigned int tile_height)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">unsigned int JPEGCompressor::CompressStrip </td>
<td>(</td>
<td class="paramtype">unsigned char * </td>
<td class="paramname"><em>s</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">unsigned int </td>
<td class="paramname"><em>tile_height</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td> throw (std::string)</td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Compress a strip of image data. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">s</td><td>source image data </td></tr>
<tr><td class="paramname">tile_height</td><td>pixel height of the tile we are compressing </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="ae27974f9307640062b5c805298b7d283"></a><!-- doxytag: member="JPEGCompressor::InitCompression" ref="ae27974f9307640062b5c805298b7d283" args="(RawTile &rawtile, unsigned int strip_height)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void JPEGCompressor::InitCompression </td>
<td>(</td>
<td class="paramtype"><a class="el" href="classRawTile.html">RawTile</a> & </td>
<td class="paramname"><em>rawtile</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">unsigned int </td>
<td class="paramname"><em>strip_height</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td> throw (std::string)</td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Initialise strip based compression. </p>
<p>If we are doing a strip based encoding, we need to first initialise with InitCompression, then compress a single strip at a time using CompressStrip and finally clean up using Finish </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">rawtile</td><td>tile containing the image to be compressed </td></tr>
<tr><td class="paramname">strip_height</td><td>pixel height of the strip we want to compress </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="a60a3aa47f982f64374ccff5b073c0011"></a><!-- doxytag: member="JPEGCompressor::setQuality" ref="a60a3aa47f982f64374ccff5b073c0011" args="(int factor)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void JPEGCompressor::setQuality </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>factor</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Set the compression quality. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">factor</td><td>Quality factor (0-100) </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="JPEGCompressor_8h_source.html">JPEGCompressor.h</a></li>
</ul>
</div>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="classJPEGCompressor.html">JPEGCompressor</a> </li>
<li class="footer">Generated on Tue Apr 12 2011 18:44:04 for iipsrv by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </li>
</ul>
</div>
</body>
</html>
|
moravianlibrary/iipsrv
|
doc/html/classJPEGCompressor.html
|
HTML
|
gpl-3.0
| 12,806 |
# Copyright (C) 2012 Bit4Bit <[email protected]>
#
# This file is part of NeuroTelCal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class UsersController < ApplicationController
# GET /users
# GET /users.json
def index
@users = User.order(:name)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
# GET /users/1
# GET /users/1.json
def show
@user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
end
# GET /users/new
# GET /users/new.json
def new
@user = User.new
@campaigns = Campaign.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
# GET /users/1/edit
def edit
@user = User.find(params[:id])
@campaigns = Campaign.all
end
# POST /users
# POST /users.json
def create
@user = User.new(params[:user])
@campaigns = Campaign.all
respond_to do |format|
if @user.save
format.html { redirect_to users_path, notice: "User #{@user.name} was successfully created." }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PUT /users/1
# PUT /users/1.json
def update
@user = User.find(params[:id])
@campaigns = Campaign.all
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to users_path, notice: "User #{@user.name} was successfully updated." }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user = User.find(params[:id])
@user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
end
|
symfony-openstack/neurotelcal
|
app/controllers/users_controller.rb
|
Ruby
|
gpl-3.0
| 2,755 |
using System;
using System.Drawing;
using System.Windows.Forms;
using MissionPlanner.Controls;
using MissionPlanner.Utilities;
using SharpDX.DirectInput;
namespace MissionPlanner.Joystick
{
public partial class JoystickSetup : Form
{
bool startup = true;
int noButtons = 0;
public JoystickSetup()
{
InitializeComponent();
MissionPlanner.Utilities.Tracking.AddPage(this.GetType().ToString(), this.Text);
}
private void Joystick_Load(object sender, EventArgs e)
{
try
{
var joysticklist = Joystick.getDevices();
foreach (DeviceInstance device in joysticklist)
{
CMB_joysticks.Items.Add(device.ProductName);
}
}
catch
{
CustomMessageBox.Show("Error geting joystick list: do you have the directx redist installed?");
this.Close();
return;
}
if (CMB_joysticks.Items.Count > 0 && CMB_joysticks.SelectedIndex == -1)
CMB_joysticks.SelectedIndex = 0;
try
{
if (Settings.Instance.ContainsKey("joystick_name") && Settings.Instance["joystick_name"].ToString() != "")
CMB_joysticks.Text = Settings.Instance["joystick_name"].ToString();
}
catch
{
}
CMB_CH1.DataSource = (Enum.GetValues(typeof (Joystick.joystickaxis)));
CMB_CH2.DataSource = (Enum.GetValues(typeof (Joystick.joystickaxis)));
CMB_CH3.DataSource = (Enum.GetValues(typeof (Joystick.joystickaxis)));
CMB_CH4.DataSource = (Enum.GetValues(typeof (Joystick.joystickaxis)));
CMB_CH5.DataSource = (Enum.GetValues(typeof (Joystick.joystickaxis)));
CMB_CH6.DataSource = (Enum.GetValues(typeof (Joystick.joystickaxis)));
CMB_CH7.DataSource = (Enum.GetValues(typeof (Joystick.joystickaxis)));
CMB_CH8.DataSource = (Enum.GetValues(typeof (Joystick.joystickaxis)));
try
{
if(Settings.Instance.ContainsKey("joy_elevons"))
CHK_elevons.Checked = bool.Parse(Settings.Instance["joy_elevons"].ToString());
}
catch
{
} // IF 1 DOESNT EXIST NONE WILL
var tempjoystick = new Joystick();
label14.Text += " " + MainV2.comPort.MAV.cs.firmware.ToString();
for (int a = 1; a <= 8; a++)
{
var config = tempjoystick.getChannel(a);
findandsetcontrol("CMB_CH" + a, config.axis.ToString());
findandsetcontrol("revCH" + a, config.reverse.ToString());
findandsetcontrol("expo_ch" + a, config.expo.ToString());
}
if (MainV2.joystick != null && MainV2.joystick.enabled)
{
timer1.Start();
BUT_enable.Text = "Disable";
}
startup = false;
}
void findandsetcontrol(string ctlname, string value)
{
var ctl = this.Controls.Find(ctlname, false)[0];
if (ctl is CheckBox)
{
((CheckBox) ctl).Checked = (value.ToLower() == "false") ? false : true;
}
else
{
((Control) ctl).Text = value;
}
}
int[] getButtonNumbers()
{
int[] temp = new int[128];
temp[0] = -1;
for (int a = 0; a < temp.Length - 1; a++)
{
temp[a + 1] = a;
}
return temp;
}
private void BUT_enable_Click(object sender, EventArgs e)
{
if (MainV2.joystick == null || MainV2.joystick.enabled == false)
{
try
{
if (MainV2.joystick != null)
MainV2.joystick.UnAcquireJoyStick();
}
catch
{
}
// all config is loaded from the xmls
Joystick joy = new Joystick();
joy.elevons = CHK_elevons.Checked;
//show error message if a joystick is not connected when Enable is clicked
if (!joy.start(CMB_joysticks.Text))
{
CustomMessageBox.Show("Please Connect a Joystick", "No Joystick");
joy.Dispose();
return;
}
Settings.Instance["joystick_name"] = CMB_joysticks.Text;
MainV2.joystick = joy;
MainV2.joystick.enabled = true;
BUT_enable.Text = "Disable";
//timer1.Start();
}
else
{
MainV2.joystick.enabled = false;
MainV2.joystick.clearRCOverride();
MainV2.joystick = null;
//timer1.Stop();
BUT_enable.Text = "Enable";
}
}
private void BUT_save_Click(object sender, EventArgs e)
{
Joystick.self.saveconfig();
Settings.Instance["joy_elevons"] = CHK_elevons.Checked.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
if (MainV2.joystick == null || MainV2.joystick.enabled == false)
{
//Console.WriteLine(DateTime.Now.Millisecond + " start ");
Joystick joy = MainV2.joystick;
if (joy == null)
{
joy = new Joystick();
if (CMB_CH1.Text != "")
joy.setChannel(1,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), CMB_CH1.Text),
revCH1.Checked, int.Parse(expo_ch1.Text));
if (CMB_CH2.Text != "")
joy.setChannel(2,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), CMB_CH2.Text),
revCH2.Checked, int.Parse(expo_ch2.Text));
if (CMB_CH3.Text != "")
joy.setChannel(3,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), CMB_CH3.Text),
revCH3.Checked, int.Parse(expo_ch3.Text));
if (CMB_CH4.Text != "")
joy.setChannel(4,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), CMB_CH4.Text),
revCH4.Checked, int.Parse(expo_ch4.Text));
if (CMB_CH5.Text != "")
joy.setChannel(5,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), CMB_CH5.Text),
revCH5.Checked, int.Parse(expo_ch5.Text));
if (CMB_CH6.Text != "")
joy.setChannel(6,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), CMB_CH6.Text),
revCH6.Checked, int.Parse(expo_ch6.Text));
if (CMB_CH7.Text != "")
joy.setChannel(7,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), CMB_CH7.Text),
revCH7.Checked, int.Parse(expo_ch7.Text));
if (CMB_CH8.Text != "")
joy.setChannel(8,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), CMB_CH8.Text),
revCH8.Checked, int.Parse(expo_ch8.Text));
joy.elevons = CHK_elevons.Checked;
joy.AcquireJoystick(CMB_joysticks.Text);
joy.name = CMB_joysticks.Text;
noButtons = joy.getNumButtons();
noButtons = Math.Min(15, noButtons);
SuspendLayout();
for (int f = 0; f < noButtons; f++)
{
string name = (f).ToString();
doButtontoUI(name, 10, CMB_CH8.Bottom + 20 + f*25);
var config = joy.getButton(f);
joy.setButton(f, config);
}
ResumeLayout();
MainV2.joystick = joy;
ThemeManager.ApplyThemeTo(this);
CMB_joysticks.SelectedIndex = CMB_joysticks.Items.IndexOf(joy.name);
}
MainV2.joystick.elevons = CHK_elevons.Checked;
MainV2.comPort.MAV.cs.rcoverridech1 = joy.getValueForChannel(1, CMB_joysticks.Text);
MainV2.comPort.MAV.cs.rcoverridech2 = joy.getValueForChannel(2, CMB_joysticks.Text);
MainV2.comPort.MAV.cs.rcoverridech3 = joy.getValueForChannel(3, CMB_joysticks.Text);
MainV2.comPort.MAV.cs.rcoverridech4 = joy.getValueForChannel(4, CMB_joysticks.Text);
MainV2.comPort.MAV.cs.rcoverridech5 = joy.getValueForChannel(5, CMB_joysticks.Text);
MainV2.comPort.MAV.cs.rcoverridech6 = joy.getValueForChannel(6, CMB_joysticks.Text);
MainV2.comPort.MAV.cs.rcoverridech7 = joy.getValueForChannel(7, CMB_joysticks.Text);
MainV2.comPort.MAV.cs.rcoverridech8 = joy.getValueForChannel(8, CMB_joysticks.Text);
//Console.WriteLine(DateTime.Now.Millisecond + " end ");
}
}
catch (SharpDX.SharpDXException ex)
{
ex.ToString();
if (MainV2.joystick != null && MainV2.joystick.enabled == true)
{
BUT_enable_Click(null, null);
}
}
catch
{
}
progressBarRoll.Value = MainV2.comPort.MAV.cs.rcoverridech1;
progressBarPith.Value = MainV2.comPort.MAV.cs.rcoverridech2;
progressBarThrottle.Value = MainV2.comPort.MAV.cs.rcoverridech3;
progressBarRudder.Value = MainV2.comPort.MAV.cs.rcoverridech4;
ProgressBarCH5.Value = MainV2.comPort.MAV.cs.rcoverridech5;
ProgressBarCH6.Value = MainV2.comPort.MAV.cs.rcoverridech6;
ProgressBarCH7.Value = MainV2.comPort.MAV.cs.rcoverridech7;
ProgressBarCH8.Value = MainV2.comPort.MAV.cs.rcoverridech8;
try
{
if (MainV2.joystick != null)
{
progressBarRoll.maxline = MainV2.joystick.getRawValueForChannel(1);
progressBarPith.maxline = MainV2.joystick.getRawValueForChannel(2);
progressBarThrottle.maxline = MainV2.joystick.getRawValueForChannel(3);
progressBarRudder.maxline = MainV2.joystick.getRawValueForChannel(4);
ProgressBarCH5.maxline = MainV2.joystick.getRawValueForChannel(5);
ProgressBarCH6.maxline = MainV2.joystick.getRawValueForChannel(6);
ProgressBarCH7.maxline = MainV2.joystick.getRawValueForChannel(7);
ProgressBarCH8.maxline = MainV2.joystick.getRawValueForChannel(8);
}
}
catch
{
//Exception Error in the application. -2147024866 (DIERR_INPUTLOST)
}
try
{
for (int f = 0; f < noButtons; f++)
{
string name = (f).ToString();
((HorizontalProgressBar) this.Controls.Find("hbar" + name, false)[0]).Value =
MainV2.joystick.isButtonPressed(f) ? 100 : 0;
}
}
catch
{
} // this is for buttons - silent fail
}
private void CMB_joysticks_Click(object sender, EventArgs e)
{
CMB_joysticks.Items.Clear();
var joysticklist = Joystick.getDevices();
foreach (DeviceInstance device in joysticklist)
{
CMB_joysticks.Items.Add(device.ProductName);
}
if (CMB_joysticks.Items.Count > 0 && CMB_joysticks.SelectedIndex == -1)
CMB_joysticks.SelectedIndex = 0;
}
private void revCH1_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick != null)
MainV2.joystick.setReverse(1, ((CheckBox) sender).Checked);
}
private void revCH2_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick != null)
MainV2.joystick.setReverse(2, ((CheckBox) sender).Checked);
}
private void revCH3_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick != null)
MainV2.joystick.setReverse(3, ((CheckBox) sender).Checked);
}
private void revCH4_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick != null)
MainV2.joystick.setReverse(4, ((CheckBox) sender).Checked);
}
private void BUT_detch1_Click(object sender, EventArgs e)
{
CMB_CH1.Text = Joystick.getMovingAxis(CMB_joysticks.Text, 16000).ToString();
}
private void BUT_detch2_Click(object sender, EventArgs e)
{
CMB_CH2.Text = Joystick.getMovingAxis(CMB_joysticks.Text, 16000).ToString();
}
private void BUT_detch3_Click(object sender, EventArgs e)
{
CMB_CH3.Text = Joystick.getMovingAxis(CMB_joysticks.Text, 16000).ToString();
}
private void BUT_detch4_Click(object sender, EventArgs e)
{
CMB_CH4.Text = Joystick.getMovingAxis(CMB_joysticks.Text, 16000).ToString();
}
private void CMB_CH1_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup || MainV2.joystick == null)
return;
MainV2.joystick.setAxis(1,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), ((ComboBox) sender).Text));
}
private void CMB_CH2_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup || MainV2.joystick == null)
return;
MainV2.joystick.setAxis(2,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), ((ComboBox) sender).Text));
}
private void CMB_CH3_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup || MainV2.joystick == null)
return;
MainV2.joystick.setAxis(3,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), ((ComboBox) sender).Text));
}
private void CMB_CH4_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup || MainV2.joystick == null)
return;
MainV2.joystick.setAxis(4,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), ((ComboBox) sender).Text));
}
private void cmbbutton_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup)
return;
string name = ((ComboBox) sender).Name.Replace("cmbbutton", "");
MainV2.joystick.changeButton((int.Parse(name)), int.Parse(((ComboBox) sender).Text));
}
private void BUT_detbutton_Click(object sender, EventArgs e)
{
string name = ((MyButton) sender).Name.Replace("mybut", "");
ComboBox cmb = (ComboBox) (this.Controls.Find("cmbbutton" + name, false)[0]);
cmb.Text = Joystick.getPressedButton(CMB_joysticks.Text).ToString();
}
void doButtontoUI(string name, int x, int y)
{
MyLabel butlabel = new MyLabel();
ComboBox butnumberlist = new ComboBox();
Controls.MyButton but_detect = new Controls.MyButton();
HorizontalProgressBar hbar = new HorizontalProgressBar();
ComboBox cmbaction = new ComboBox();
Controls.MyButton but_settings = new Controls.MyButton();
var config = Joystick.self.getButton(int.Parse(name));
// do this here so putting in text works
this.Controls.AddRange(new Control[] {butlabel, butnumberlist, but_detect, hbar, cmbaction, but_settings});
butlabel.Location = new Point(x, y);
butlabel.Size = new Size(47, 13);
butlabel.Text = "Button " + (int.Parse(name) + 1);
butnumberlist.Location = new Point(72, y);
butnumberlist.Size = new Size(70, 21);
butnumberlist.DataSource = getButtonNumbers();
butnumberlist.DropDownStyle = ComboBoxStyle.DropDownList;
butnumberlist.Name = "cmbbutton" + name;
//if (Settings.Instance["butno" + name] != null)
// butnumberlist.Text = (Settings.Instance["butno" + name].ToString());
//if (config.buttonno != -1)
butnumberlist.Text = config.buttonno.ToString();
butnumberlist.SelectedIndexChanged += new EventHandler(cmbbutton_SelectedIndexChanged);
but_detect.Location = new Point(BUT_detch1.Left, y);
but_detect.Size = BUT_detch1.Size;
but_detect.Text = BUT_detch1.Text;
but_detect.Name = "mybut" + name;
but_detect.Click += new EventHandler(BUT_detbutton_Click);
hbar.Location = new Point(progressBarRoll.Left, y);
hbar.Size = progressBarRoll.Size;
hbar.Name = "hbar" + name;
cmbaction.Location = new Point(hbar.Right + 5, y);
cmbaction.Size = new Size(100, 21);
cmbaction.DataSource = Enum.GetNames(typeof (Joystick.buttonfunction));
//Common.getModesList(MainV2.comPort.MAV.cs);
//cmbaction.ValueMember = "Key";
//cmbaction.DisplayMember = "Value";
cmbaction.Tag = name;
cmbaction.DropDownStyle = ComboBoxStyle.DropDownList;
cmbaction.Name = "cmbaction" + name;
//if (Settings.Instance["butaction" + name] != null)
// cmbaction.Text = Settings.Instance["butaction" + name].ToString();
//if (config.function != Joystick.buttonfunction.ChangeMode)
cmbaction.Text = config.function.ToString();
cmbaction.SelectedIndexChanged += cmbaction_SelectedIndexChanged;
but_settings.Location = new Point(cmbaction.Right + 5, y);
but_settings.Size = BUT_detch1.Size;
but_settings.Text = "Settings";
but_settings.Name = "butsettings" + name;
but_settings.Click += but_settings_Click;
but_settings.Tag = cmbaction;
if ((but_settings.Bottom + 30) > this.Height)
this.Height += 25;
}
void cmbaction_SelectedIndexChanged(object sender, EventArgs e)
{
int num = int.Parse(((Control) sender).Tag.ToString());
var config = Joystick.self.getButton(num);
config.function =
(Joystick.buttonfunction) Enum.Parse(typeof (Joystick.buttonfunction), ((Control) sender).Text);
Joystick.self.setButton(num, config);
}
void but_settings_Click(object sender, EventArgs e)
{
var cmb = ((Control) sender).Tag as ComboBox;
switch ((Joystick.buttonfunction) Enum.Parse(typeof (Joystick.buttonfunction), cmb.SelectedItem.ToString()))
{
case Joystick.buttonfunction.ChangeMode:
new Joy_ChangeMode((string) cmb.Tag).ShowDialog();
break;
case Joystick.buttonfunction.Mount_Mode:
new Joy_Mount_Mode((string) cmb.Tag).ShowDialog();
break;
case Joystick.buttonfunction.Do_Repeat_Relay:
new Joy_Do_Repeat_Relay((string) cmb.Tag).ShowDialog();
break;
case Joystick.buttonfunction.Do_Repeat_Servo:
new Joy_Do_Repeat_Servo((string) cmb.Tag).ShowDialog();
break;
case Joystick.buttonfunction.Do_Set_Relay:
new Joy_Do_Set_Relay((string) cmb.Tag).ShowDialog();
break;
case Joystick.buttonfunction.Do_Set_Servo:
new Joy_Do_Set_Servo((string) cmb.Tag).ShowDialog();
break;
case Joystick.buttonfunction.Button_axis0:
new Joy_Button_axis((string) cmb.Tag).ShowDialog();
break;
case Joystick.buttonfunction.Button_axis1:
new Joy_Button_axis((string) cmb.Tag).ShowDialog();
break;
default:
CustomMessageBox.Show("No settings to set", "No settings");
break;
}
}
private void CMB_joysticks_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (MainV2.joystick != null && MainV2.joystick.enabled == false)
MainV2.joystick.UnAcquireJoyStick();
}
catch
{
}
}
private void JoystickSetup_FormClosed(object sender, FormClosedEventArgs e)
{
timer1.Stop();
if (MainV2.joystick != null && MainV2.joystick.enabled == false)
{
MainV2.joystick.UnAcquireJoyStick();
MainV2.joystick = null;
}
}
private void CHK_elevons_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick == null)
{
return;
}
MainV2.joystick.elevons = CHK_elevons.Checked;
}
private void CMB_CH5_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup || MainV2.joystick == null)
return;
MainV2.joystick.setAxis(5,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), ((ComboBox) sender).Text));
}
private void CMB_CH6_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup || MainV2.joystick == null)
return;
MainV2.joystick.setAxis(6,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), ((ComboBox) sender).Text));
}
private void CMB_CH7_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup || MainV2.joystick == null)
return;
MainV2.joystick.setAxis(7,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), ((ComboBox) sender).Text));
}
private void CMB_CH8_SelectedIndexChanged(object sender, EventArgs e)
{
if (startup || MainV2.joystick == null)
return;
MainV2.joystick.setAxis(8,
(Joystick.joystickaxis) Enum.Parse(typeof (Joystick.joystickaxis), ((ComboBox) sender).Text));
}
private void BUT_detch5_Click(object sender, EventArgs e)
{
CMB_CH5.Text = Joystick.getMovingAxis(CMB_joysticks.Text, 16000).ToString();
}
private void BUT_detch6_Click(object sender, EventArgs e)
{
CMB_CH6.Text = Joystick.getMovingAxis(CMB_joysticks.Text, 16000).ToString();
}
private void BUT_detch7_Click(object sender, EventArgs e)
{
CMB_CH7.Text = Joystick.getMovingAxis(CMB_joysticks.Text, 16000).ToString();
}
private void BUT_detch8_Click(object sender, EventArgs e)
{
CMB_CH8.Text = Joystick.getMovingAxis(CMB_joysticks.Text, 16000).ToString();
}
private void revCH5_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick != null)
MainV2.joystick.setReverse(5, ((CheckBox) sender).Checked);
}
private void revCH6_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick != null)
MainV2.joystick.setReverse(6, ((CheckBox) sender).Checked);
}
private void revCH7_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick != null)
MainV2.joystick.setReverse(7, ((CheckBox) sender).Checked);
}
private void revCH8_CheckedChanged(object sender, EventArgs e)
{
if (MainV2.joystick != null)
MainV2.joystick.setReverse(8, ((CheckBox) sender).Checked);
}
private void chk_manualcontrol_CheckedChanged(object sender, EventArgs e)
{
MainV2.joystick.manual_control = chk_manualcontrol.Checked;
if (chk_manualcontrol.Checked)
{
CMB_CH5.Enabled = false;
CMB_CH6.Enabled = false;
CMB_CH7.Enabled = false;
CMB_CH8.Enabled = false;
}
else
{
CMB_CH5.Enabled = true;
CMB_CH6.Enabled = true;
CMB_CH7.Enabled = true;
CMB_CH8.Enabled = true;
}
}
}
}
|
patschn/MissionPlanner
|
Joystick/JoystickSetup.cs
|
C#
|
gpl-3.0
| 25,995 |
/*
* niepce - niepce/ui/image_list_store.rs
*
* Copyright (C) 2020-2021 Hubert Figuière
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use std::collections::BTreeMap;
use std::ptr;
use glib::translate::*;
use gtk::prelude::*;
use once_cell::unsync::OnceCell;
use npc_engine::db::libfile::{FileStatus, LibFile};
use npc_engine::db::props::NiepceProperties as Np;
use npc_engine::db::props::NiepcePropertyIdx::*;
use npc_engine::db::LibraryId;
use npc_engine::library::notification::{LibNotification, MetadataChange};
use npc_engine::library::thumbnail_cache::ThumbnailCache;
use npc_fwk::toolkit::gdk_utils;
use npc_fwk::PropertyValue;
/// Wrap a libfile into something that can be in a glib::Value
#[derive(Clone, GBoxed)]
#[gboxed(type_name = "StoreLibFile", nullable)]
pub struct StoreLibFile(pub LibFile);
#[repr(i32)]
pub enum ColIndex {
Thumb = 0,
File = 1,
StripThumb = 2,
FileStatus = 3,
}
/// The Image list store.
/// It wraps the tree model/store.
pub struct ImageListStore {
store: gtk::ListStore,
current_folder: LibraryId,
current_keyword: LibraryId,
idmap: BTreeMap<LibraryId, gtk::TreeIter>,
image_loading_icon: OnceCell<Option<gdk_pixbuf::Pixbuf>>,
}
impl Default for ImageListStore {
fn default() -> Self {
Self::new()
}
}
impl ImageListStore {
pub fn new() -> Self {
let col_types: [glib::Type; 4] = [
gdk_pixbuf::Pixbuf::static_type(),
StoreLibFile::static_type(),
gdk_pixbuf::Pixbuf::static_type(),
glib::Type::I32,
];
let store = gtk::ListStore::new(&col_types);
Self {
store,
current_folder: 0,
current_keyword: 0,
idmap: BTreeMap::new(),
image_loading_icon: OnceCell::new(),
}
}
fn get_loading_icon(&self) -> Option<&gdk_pixbuf::Pixbuf> {
self.image_loading_icon
.get_or_init(|| {
if let Some(theme) = gtk::IconTheme::default() {
if let Ok(icon) =
theme.load_icon("image-loading", 32, gtk::IconLookupFlags::USE_BUILTIN)
{
icon
} else {
None
}
} else {
None
}
})
.as_ref()
}
fn is_property_interesting(idx: Np) -> bool {
(idx == Np::Index(NpXmpRatingProp))
|| (idx == Np::Index(NpXmpLabelProp))
|| (idx == Np::Index(NpTiffOrientationProp))
|| (idx == Np::Index(NpNiepceFlagProp))
}
fn get_iter_from_id(&self, id: LibraryId) -> Option<>k::TreeIter> {
self.idmap.get(&id)
}
fn clear_content(&mut self) {
// clear the map before the list.
self.idmap.clear();
self.store.clear();
}
fn add_libfile(&mut self, f: &LibFile) {
let icon = self.get_loading_icon().cloned();
let iter = self.add_row(
icon.as_ref(),
f,
gdk_utils::gdkpixbuf_scale_to_fit(icon.as_ref(), 100).as_ref(),
FileStatus::Ok,
);
self.idmap.insert(f.id(), iter);
}
fn add_libfiles(&mut self, content: &[LibFile]) {
for f in content.iter() {
self.add_libfile(f);
}
}
/// Process the notification.
/// Returns false if it hasn't been
pub fn on_lib_notification(
&mut self,
notification: &LibNotification,
thumbnail_cache: &ThumbnailCache,
) -> bool {
use self::LibNotification::*;
match *notification {
FolderContentQueried(ref c) | KeywordContentQueried(ref c) => {
match *notification {
FolderContentQueried(_) => {
self.current_folder = c.id;
self.current_keyword = 0;
}
KeywordContentQueried(_) => {
self.current_folder = 0;
self.current_keyword = c.id;
}
_ => {}
}
self.clear_content();
dbg_out!("received folder content file # {}", c.content.len());
self.add_libfiles(&c.content);
// request thumbnails c.content
thumbnail_cache.request(&c.content);
true
}
FileMoved(ref param) => {
dbg_out!("File moved. Current folder {}", self.current_folder);
if self.current_folder != 0 {
if param.from == self.current_folder {
// remove from list
dbg_out!("from this folder");
if let Some(iter) = self.get_iter_from_id(param.file) {
self.store.remove(iter);
self.idmap.remove(¶m.file);
}
} else if param.to == self.current_folder {
// XXX add to list. but this isn't likely to happen atm.
}
}
true
}
FileStatusChanged(ref status) => {
if let Some(iter) = self.idmap.get(&status.id) {
self.store.set_value(
iter,
ColIndex::FileStatus as u32,
&(status.status as i32).to_value(),
);
}
true
}
MetadataChanged(ref m) => {
dbg_out!("metadata changed {:?}", m.meta);
// only interested in a few props
if Self::is_property_interesting(m.meta) {
if let Some(iter) = self.idmap.get(&m.id) {
self.set_property(iter, m);
}
}
true
}
ThumbnailLoaded(ref t) => {
if let Some(iter) = self.get_iter_from_id(t.id) {
let pixbuf = t.pix.make_pixbuf();
self.store.set(
iter,
&[
(ColIndex::Thumb as u32, &pixbuf),
(
ColIndex::StripThumb as u32,
&gdk_utils::gdkpixbuf_scale_to_fit(pixbuf.as_ref(), 100),
),
],
);
}
true
}
_ => false,
}
}
pub fn get_file_id_at_path(&self, path: >k::TreePath) -> LibraryId {
if let Some(iter) = self.store.iter(&path) {
if let Ok(libfile) = self
.store
.value(&iter, ColIndex::File as i32)
.get::<&StoreLibFile>()
{
return libfile.0.id();
}
}
0
}
pub fn get_file(&self, id: LibraryId) -> Option<LibFile> {
if let Some(iter) = self.idmap.get(&id) {
self.store
.value(&iter, ColIndex::File as i32)
.get::<&StoreLibFile>()
.map(|v| v.0.clone())
.ok()
} else {
None
}
}
pub fn add_row(
&mut self,
thumb: Option<&gdk_pixbuf::Pixbuf>,
file: &LibFile,
strip_thumb: Option<&gdk_pixbuf::Pixbuf>,
status: FileStatus,
) -> gtk::TreeIter {
let iter = self.store.append();
let store_libfile = StoreLibFile(file.clone());
self.store.set(
&iter,
&[
(ColIndex::Thumb as u32, &thumb),
(ColIndex::File as u32, &store_libfile),
(ColIndex::StripThumb as u32, &strip_thumb),
(ColIndex::FileStatus as u32, &(status as i32)),
],
);
iter
}
pub fn set_thumbnail(&mut self, id: LibraryId, thumb: &gdk_pixbuf::Pixbuf) {
if let Some(iter) = self.idmap.get(&id) {
let strip_thumb = gdk_utils::gdkpixbuf_scale_to_fit(Some(thumb), 100);
assert!(thumb.ref_count() > 0);
self.store.set(
iter,
&[
(ColIndex::Thumb as u32, thumb),
(ColIndex::StripThumb as u32, &strip_thumb),
],
);
}
}
pub fn set_property(&self, iter: >k::TreeIter, change: &MetadataChange) {
if let Ok(libfile) = self
.store
.value(&iter, ColIndex::File as i32)
.get::<&StoreLibFile>()
{
assert!(libfile.0.id() == change.id);
let meta = change.meta;
if let PropertyValue::Int(value) = change.value {
let mut file = libfile.0.clone();
file.set_property(meta, value);
self.store
.set_value(&iter, ColIndex::File as u32, &StoreLibFile(file).to_value());
} else {
err_out!("Wrong property type");
}
}
}
}
#[no_mangle]
pub extern "C" fn npc_image_list_store_new() -> *mut ImageListStore {
let box_ = Box::new(ImageListStore::new());
Box::into_raw(box_)
}
/// # Safety
/// Dereference pointer.
#[no_mangle]
pub unsafe extern "C" fn npc_image_list_store_delete(self_: *mut ImageListStore) {
assert!(!self_.is_null());
Box::from_raw(self_);
}
/// Return the gobj for the GtkListStore. You must ref it to hold it.
#[no_mangle]
pub extern "C" fn npc_image_list_store_gobj(self_: &ImageListStore) -> *mut gtk_sys::GtkListStore {
self_.store.to_glib_none().0
}
/// Return the ID of the file at the given GtkTreePath
///
/// # Safety
/// Use glib pointers.
#[no_mangle]
pub unsafe extern "C" fn npc_image_list_store_get_file_id_at_path(
self_: &ImageListStore,
path: *const gtk_sys::GtkTreePath,
) -> LibraryId {
assert!(!path.is_null());
self_.get_file_id_at_path(&from_glib_borrow(path))
}
/// # Safety
/// Dereference pointers.
#[no_mangle]
pub unsafe extern "C" fn npc_image_list_store_add_row(
self_: &mut ImageListStore,
thumb: *mut gdk_pixbuf_sys::GdkPixbuf,
file: *const LibFile,
strip_thumb: *mut gdk_pixbuf_sys::GdkPixbuf,
status: FileStatus,
) -> gtk_sys::GtkTreeIter {
let thumb: Option<gdk_pixbuf::Pixbuf> = from_glib_none(thumb);
let strip_thumb: Option<gdk_pixbuf::Pixbuf> = from_glib_none(strip_thumb);
*self_
.add_row(thumb.as_ref(), &*file, strip_thumb.as_ref(), status)
.to_glib_none()
.0
}
#[no_mangle]
pub extern "C" fn npc_image_list_store_get_iter_from_id(
self_: &mut ImageListStore,
id: LibraryId,
) -> *const gtk_sys::GtkTreeIter {
self_.idmap.get(&id).to_glib_none().0
}
#[no_mangle]
pub extern "C" fn npc_image_list_store_get_file(
self_: &mut ImageListStore,
id: LibraryId,
) -> *mut LibFile {
if let Some(libfile) = self_.get_file(id) {
Box::into_raw(Box::new(libfile))
} else {
ptr::null_mut()
}
}
#[no_mangle]
pub extern "C" fn npc_image_list_store_on_lib_notification(
self_: &mut ImageListStore,
notification: &LibNotification,
thumbnail_cache: &ThumbnailCache,
) -> bool {
self_.on_lib_notification(notification, thumbnail_cache)
}
#[no_mangle]
pub extern "C" fn npc_image_list_store_clear_content(self_: &mut ImageListStore) {
self_.clear_content()
}
|
GNOME/niepce
|
niepce-main/src/niepce/ui/image_list_store.rs
|
Rust
|
gpl-3.0
| 12,180 |
var searchData=
[
['checkend',['checkEnd',['../class_slide_client.html#a5d4138b8eb5287f59232b66868bf09dc',1,'SlideClient']]],
['checkstart',['checkStart',['../class_slide_client.html#a21e77f1ed2dee919e64691f04c0ee768',1,'SlideClient']]],
['connectserver',['connectServer',['../class_slide_client.html#a71dfaba5b5bd2479eba51e8708e6c2f3',1,'SlideClient']]]
];
|
SeimuPVE/SmartSchool
|
doc/SlideClient/html/search/functions_0.js
|
JavaScript
|
gpl-3.0
| 364 |
/*
* Copyright (C) 2007-2012 Hypertable, Inc.
*
* This file is part of Hypertable.
*
* Hypertable 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 any later version.
*
* Hypertable is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.hypertable.examples.PerformanceTest;
import java.util.LinkedList;
import org.hypertable.thriftgen.*;
import org.hypertable.thrift.SerializedCellsWriter;
public class DriverThreadState {
Thread thread;
DriverCommon common;
LinkedList<SerializedCellsWriter> updates = new LinkedList<SerializedCellsWriter>();
boolean finished = false;
double cum_latency;
double cum_sq_latency;
double min_latency;
double max_latency;
}
|
toidi/hypertable
|
examples/java/org/hypertable/examples/PerformanceTest/DriverThreadState.java
|
Java
|
gpl-3.0
| 1,242 |
import * as Action from '../actions/constants';
const initialEventState = {
id: null,
name: null,
enrollmentPeriod: null,
thumbnail: null,
// location: null,
// roles: null,
not_found: false,
loading: true,
roles: null,
relationship: null,
context: null,
cert: null,
};
const mountObjectData = (data) => {
return ({
id: data._id,
name: data.name,
thumbnail: data.thumbnail,
enrollmentPeriod: data.enrollmentPeriod,
});
};
const event = (state = initialEventState, action) => {
switch (action.type) {
case Action.EVENT_PAGE_NOT_FOUND:
return Object.assign({}, state, {
not_found: true,
});
case Action.EVENT_PAGE_LOADED:
return Object.assign({}, state, {
loading: false,
});
case Action.SET_EVENT_PAGE_DATA:
return Object.assign({}, state, mountObjectData(action.data));
case Action.SET_EVENT_ROLES:
return Object.assign({}, state, {
roles: action.data,
});
case Action.SET_EVENT_RELATIONSHIP:
return Object.assign({}, state, {
relationship: action.data,
});
case Action.SET_EVENT_CERT:
return Object.assign({}, state, {
cert: action.data,
});
case Action.SET_EVENT_CONTEXT:
return Object.assign({}, state, {
context: action.data,
});
default:
return state;
}
};
export default event;
|
ccsa-ufrn/seminario
|
src/reducers/event.js
|
JavaScript
|
gpl-3.0
| 1,400 |
M.qtype_regexp = M.qtype_regexp || {};
M.qtype_regexp.showhidealternate = function(Y, buttonel, showhideel) {
Y.one(buttonel).on('click', function(e) {
if (Y.one(showhideel).getStyle('display') == 'none') {
Y.one(showhideel).setStyle('display', 'block');
Y.one(buttonel).set('value', M.util.get_string('hidealternate', 'qtype_regexp'));
} else {
Y.one(showhideel).setStyle('display', 'none');
Y.one(buttonel).set('value', M.util.get_string('showalternate', 'qtype_regexp'));
}
e.halt();
});
}
|
nitro2010/moodle
|
question/type/regexp/module.js
|
JavaScript
|
gpl-3.0
| 517 |
/***********************************************************************
* Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Carsten Urbach
*
* This file is part of tmLQCD.
*
* tmLQCD 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.
*
* tmLQCD 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 tmLQCD. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/
/*******************************************************************************
*
* Test program for the even-odd preconditioned Wilson-Dirac operator
*
*
*******************************************************************************/
#define MAIN_PROGRAM
#ifdef HAVE_CONFIG_H
# include<config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <complex.h>
#if (defined BGL && !defined BGP)
# include <rts.h>
#endif
#ifdef MPI
# include <mpi.h>
# ifdef HAVE_LIBLEMON
# include <io/params.h>
# include <io/gauge.h>
# endif
#endif
#include "su3.h"
#include "su3adj.h"
#include "su3spinor.h"
#include "ranlxd.h"
#include "geometry_eo.h"
#include "read_input.h"
#include "start.h"
#include "boundary.h"
#include "Hopping_Matrix.h"
#include "Hopping_Matrix_nocom.h"
#include "tm_operators.h"
#include "global.h"
#include "xchange.h"
#include "init_gauge_field.h"
#include "init_geometry_indices.h"
#include "init_spinor_field.h"
#include "init_moment_field.h"
#include "init_dirac_halfspinor.h"
#include "test/check_geometry.h"
#include "xchange_halffield.h"
#include "D_psi.h"
#include "phmc.h"
#include "mpi_init.h"
#include "io/io_cm.h"
#ifdef PARALLELT
# define SLICE (LX*LY*LZ/2)
#elif defined PARALLELXT
# define SLICE ((LX*LY*LZ/2)+(T*LY*LZ/2))
#elif defined PARALLELXYT
# define SLICE ((LX*LY*LZ/2)+(T*LY*LZ/2) + (T*LX*LZ/2))
#elif defined PARALLELXYZT
# define SLICE ((LX*LY*LZ/2)+(T*LY*LZ/2) + (T*LX*LZ/2) + (T*LX*LY/2))
#elif defined PARALLELX
# define SLICE ((LY*LZ*T/2))
#elif defined PARALLELXY
# define SLICE ((LY*LZ*T/2) + (LX*LZ*T/2))
#elif defined PARALLELXYZ
# define SLICE ((LY*LZ*T/2) + (LX*LZ*T/2) + (LX*LY*T/2))
#endif
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#define MIN(A, B) ((A) < (B) ? (A) : (B))
#if (defined BGL && !defined BGP)
static double clockspeed=1.0e-6/700.0;
double bgl_wtime() {
return ( rts_get_timebase() * clockspeed );
}
#else
# ifdef MPI
double bgl_wtime() { return(MPI_Wtime()); }
# else
double bgl_wtime() { return(0); }
# endif
#endif
int check_xchange();
int main(int argc,char *argv[])
{
int j,j_max,k,k_max = 2;
paramsXlfInfo *xlfInfo;
int ix, n, *nn,*mm,i;
double delta, deltamax;
spinor rsp;
int status = 0;
#ifdef MPI
DUM_DERI = 6;
DUM_SOLVER = DUM_DERI+2;
DUM_MATRIX = DUM_SOLVER+6;
NO_OF_SPINORFIELDS = DUM_MATRIX+2;
MPI_Init(&argc, &argv);
#endif
g_rgi_C1 = 1.;
/* Read the input file */
read_input("hopping_test.input");
tmlqcd_mpi_init(argc, argv);
if(g_proc_id==0) {
#ifdef SSE
printf("# The code was compiled with SSE instructions\n");
#endif
#ifdef SSE2
printf("# The code was compiled with SSE2 instructions\n");
#endif
#ifdef SSE3
printf("# The code was compiled with SSE3 instructions\n");
#endif
#ifdef P4
printf("# The code was compiled for Pentium4\n");
#endif
#ifdef OPTERON
printf("# The code was compiled for AMD Opteron\n");
#endif
#ifdef _GAUGE_COPY
printf("# The code was compiled with -D_GAUGE_COPY\n");
#endif
#ifdef BGL
printf("# The code was compiled for Blue Gene/L\n");
#endif
#ifdef BGP
printf("# The code was compiled for Blue Gene/P\n");
#endif
#ifdef _USE_HALFSPINOR
printf("# The code was compiled with -D_USE_HALFSPINOR\n");
#endif
#ifdef _USE_SHMEM
printf("# the code was compiled with -D_USE_SHMEM\n");
# ifdef _PERSISTENT
printf("# the code was compiled for persistent MPI calls (halfspinor only)\n");
# endif
#endif
#ifdef _INDEX_INDEP_GEOM
printf("# the code was compiled with index independent geometry\n");
#endif
#ifdef MPI
# ifdef _NON_BLOCKING
printf("# the code was compiled for non-blocking MPI calls (spinor and gauge)\n");
# endif
# ifdef _USE_TSPLITPAR
printf("# the code was compiled with tsplit parallelization\n");
# endif
#endif
printf("\n");
fflush(stdout);
}
#ifdef _GAUGE_COPY
init_gauge_field(VOLUMEPLUSRAND + g_dbw2rand, 1);
#else
init_gauge_field(VOLUMEPLUSRAND + g_dbw2rand, 0);
#endif
init_geometry_indices(VOLUMEPLUSRAND + g_dbw2rand);
if(even_odd_flag) {
j = init_spinor_field(VOLUMEPLUSRAND/2, 2*k_max+1);
}
else {
j = init_spinor_field(VOLUMEPLUSRAND, 2*k_max);
}
if ( j!= 0) {
fprintf(stderr, "Not enough memory for spinor fields! Aborting...\n");
exit(0);
}
j = init_moment_field(VOLUME, VOLUMEPLUSRAND);
if ( j!= 0) {
fprintf(stderr, "Not enough memory for moment fields! Aborting...\n");
exit(0);
}
if(g_proc_id == 0) {
fprintf(stdout,"The number of processes is %d \n",g_nproc);
printf("# The lattice size is %d x %d x %d x %d\n",
(int)(T*g_nproc_t), (int)(LX*g_nproc_x), (int)(LY*g_nproc_y), (int)(g_nproc_z*LZ));
printf("# The local lattice size is %d x %d x %d x %d\n",
(int)(T), (int)(LX), (int)(LY),(int) LZ);
if(even_odd_flag) {
printf("# testinging the even/odd preconditioned Dirac operator\n");
}
else {
printf("# testinging the standard Dirac operator\n");
}
fflush(stdout);
}
/* define the geometry */
geometry();
/* define the boundary conditions for the fermion fields */
boundary(g_kappa);
#ifdef _USE_HALFSPINOR
j = init_dirac_halfspinor();
if ( j!= 0) {
fprintf(stderr, "Not enough memory for halfspinor fields! Aborting...\n");
exit(0);
}
if(g_sloppy_precision_flag == 1) {
g_sloppy_precision = 1;
j = init_dirac_halfspinor32();
if ( j!= 0) {
fprintf(stderr, "Not enough memory for 32-Bit halfspinor fields! Aborting...\n");
exit(0);
}
}
# if (defined _PERSISTENT)
init_xchange_halffield();
# endif
#endif
status = check_geometry();
if (status != 0) {
fprintf(stderr, "Checking of geometry failed. Unable to proceed.\nAborting....\n");
exit(1);
}
#if (defined MPI && !(defined _USE_SHMEM))
check_xchange();
#endif
start_ranlux(1, 123456);
xlfInfo = construct_paramsXlfInfo(0.5, 0);
random_gauge_field(reproduce_randomnumber_flag);
if ( startoption == 2 ) { /* restart */
write_gauge_field(gauge_input_filename,gauge_precision_write_flag,xlfInfo);
} else if ( startoption == 0 ) { /* cold */
unit_g_gauge_field();
} else if (startoption == 3 ) { /* continue */
read_gauge_field(gauge_input_filename);
} else if ( startoption == 1 ) { /* hot */
}
#ifdef MPI
/*For parallelization: exchange the gaugefield */
xchange_gauge(g_gauge_field);
#endif
if(even_odd_flag) {
/*initialize the pseudo-fermion fields*/
j_max=1;
for (k = 0; k < k_max; k++) {
random_spinor_field(g_spinor_field[k], VOLUME/2, 0);
}
if (read_source_flag == 2) { /* save */
/* even first, odd second */
write_spinorfield_cm_single(g_spinor_field[0],g_spinor_field[1],SourceInfo.basename);
} else if (read_source_flag == 1) { /* yes */
/* even first, odd second */
read_spinorfield_cm_single(g_spinor_field[0],g_spinor_field[1],SourceInfo.basename,-1,0);
# if (!defined MPI)
if (write_cp_flag == 1) {
strcat(SourceInfo.basename,".2");
read_spinorfield_cm_single(g_spinor_field[2],g_spinor_field[3],SourceInfo.basename,-1,0);
nn=(int*)calloc(VOLUME,sizeof(int));
if((void*)nn == NULL) return(100);
mm=(int*)calloc(VOLUME,sizeof(int));
if((void*)mm == NULL) return(100);
n=0;
deltamax=0.0;
for(ix=0;ix<VOLUME/2;ix++){
(rsp.s0).c0 = (g_spinor_field[2][ix].s0).c0 - (g_spinor_field[0][ix].s0).c0;
(rsp.s0).c1 = (g_spinor_field[2][ix].s0).c1 - (g_spinor_field[0][ix].s0).c1;
(rsp.s0).c2 = (g_spinor_field[2][ix].s0).c2 - (g_spinor_field[0][ix].s0).c2;
(rsp.s1).c0 = (g_spinor_field[2][ix].s1).c0 - (g_spinor_field[0][ix].s1).c0;
(rsp.s1).c1 = (g_spinor_field[2][ix].s1).c1 - (g_spinor_field[0][ix].s1).c1;
(rsp.s1).c2 = (g_spinor_field[2][ix].s1).c2 - (g_spinor_field[0][ix].s1).c2;
(rsp.s2).c0 = (g_spinor_field[2][ix].s2).c0 - (g_spinor_field[0][ix].s2).c0;
(rsp.s2).c1 = (g_spinor_field[2][ix].s2).c1 - (g_spinor_field[0][ix].s2).c1;
(rsp.s2).c2 = (g_spinor_field[2][ix].s2).c2 - (g_spinor_field[0][ix].s2).c2;
(rsp.s3).c0 = (g_spinor_field[2][ix].s3).c0 - (g_spinor_field[0][ix].s3).c0;
(rsp.s3).c1 = (g_spinor_field[2][ix].s3).c1 - (g_spinor_field[0][ix].s3).c1;
(rsp.s3).c2 = (g_spinor_field[2][ix].s3).c2 - (g_spinor_field[0][ix].s3).c2;
_spinor_norm_sq(delta,rsp);
if (delta > 1.0e-12) {
nn[n] = g_eo2lexic[ix];
mm[n]=ix;
n++;
}
if(delta>deltamax) deltamax=delta;
}
if (n>0){
printf("mismatch in even spincolorfield in %d points:\n",n);
for(i=0; i< MIN(n,1000); i++){
printf("%d,(%d,%d,%d,%d):%f vs. %f\n",nn[i],g_coord[nn[i]][0],g_coord[nn[i]][1],g_coord[nn[i]][2],g_coord[nn[i]][3],creal((g_spinor_field[2][mm[i]].s0).c0), creal((g_spinor_field[0][mm[i]].s0).c0));fflush(stdout);
}
}
n = 0;
for(ix=0;ix<VOLUME/2;ix++){
(rsp.s0).c0 = (g_spinor_field[3][ix].s0).c0 - (g_spinor_field[1][ix].s0).c0;
(rsp.s0).c1 = (g_spinor_field[3][ix].s0).c1 - (g_spinor_field[1][ix].s0).c1;
(rsp.s0).c2 = (g_spinor_field[3][ix].s0).c2 - (g_spinor_field[1][ix].s0).c2;
(rsp.s1).c0 = (g_spinor_field[3][ix].s1).c0 - (g_spinor_field[1][ix].s1).c0;
(rsp.s1).c1 = (g_spinor_field[3][ix].s1).c1 - (g_spinor_field[1][ix].s1).c1;
(rsp.s1).c2 = (g_spinor_field[3][ix].s1).c2 - (g_spinor_field[1][ix].s1).c2;
(rsp.s2).c0 = (g_spinor_field[3][ix].s2).c0 - (g_spinor_field[1][ix].s2).c0;
(rsp.s2).c1 = (g_spinor_field[3][ix].s2).c1 - (g_spinor_field[1][ix].s2).c1;
(rsp.s2).c2 = (g_spinor_field[3][ix].s2).c2 - (g_spinor_field[1][ix].s2).c2;
(rsp.s3).c0 = (g_spinor_field[3][ix].s3).c0 - (g_spinor_field[1][ix].s3).c0;
(rsp.s3).c1 = (g_spinor_field[3][ix].s3).c1 - (g_spinor_field[1][ix].s3).c1;
(rsp.s3).c2 = (g_spinor_field[3][ix].s3).c2 - (g_spinor_field[1][ix].s3).c2;
_spinor_norm_sq(delta,rsp);
if (delta > 1.0e-12) {
nn[n]=g_eo2lexic[ix+(VOLUME+RAND)/2];
mm[n]=ix;
n++;
}
if(delta>deltamax) deltamax=delta;
}
if (n>0){
printf("mismatch in odd spincolorfield in %d points:\n",n);
for(i=0; i< MIN(n,1000); i++){
printf("%d,(%d,%d,%d,%d):%f vs. %f\n",nn[i],g_coord[nn[i]][0],g_coord[nn[i]][1],g_coord[nn[i]][2],g_coord[nn[i]][3],creal(g_spinor_field[3][mm[i]].s0.c0), creal(g_spinor_field[1][mm[i]].s0.c0));fflush(stdout);
}
}
printf("max delta=%e",deltamax);fflush(stdout);
}
# endif
}
if (read_source_flag > 0 && write_cp_flag == 0) { /* read-source yes or nobutsave; checkpoint no */
/* first spinorial arg is output, the second is input */
Hopping_Matrix(1, g_spinor_field[1], g_spinor_field[0]); /*ieo=1 M_{eo}*/
Hopping_Matrix(0, g_spinor_field[0], g_spinor_field[1]); /*ieo=0 M_{oe}*/
strcat(SourceInfo.basename,".out");
write_spinorfield_cm_single(g_spinor_field[0],g_spinor_field[1],SourceInfo.basename);
printf("Check-field printed. Exiting...\n");
fflush(stdout);
}
#ifdef MPI
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
#endif
}
free_gauge_field();
free_geometry_indices();
free_spinor_field();
free_moment_field();
return(0);
}
|
kostrzewa/tmLQCD
|
hopping_test.c
|
C
|
gpl-3.0
| 11,995 |
package model
/**
* @author Camilo Sampedro <[email protected]>
*/
case class Role(
id: Int,
description: String)
object Role {
val Administrator = 1
val NormalUser = 2
}
|
ProjectAton/AtonLab
|
app/model/Role.scala
|
Scala
|
gpl-3.0
| 226 |
html, body {
color: #4f5f6f;
font-family: 'Open Sans', sans-serif;
height: 100%;
margin: 0;
min-height: 100%;
overflow-x: hidden;
padding: 0;
}
body {
font-size: 14px;
line-height: 1.5;
}
h1, h2, h3, h4, h5 {
font-weight: normal;
}
h2, h3 {
font-size: 14px;
}
a {
color: #59c2e6;
text-decoration: none;
transition: color 0.13s;
}
a:hover {
color: #0b98ca;
}
ol, ul {
padding-left: 15px;
}
button {
background-color: #0b98ca;
border: 0;
color: white;
cursor: pointer;
padding: 6px 12px;
transition: background-color 0.13s;
}
button:hover {
background-color: #219FCA;
}
label {
display: inline-block;
width: 45px;
}
select, input {
background-color: white;
border: 0;
font-size: 14px;
height: 26px;
padding: 3px 3px;
width: 200px;
}
hr {
border-style: groove;
}
::-webkit-scrollbar {
height: 7px;
width: 7px;
}
::-webkit-scrollbar-thumb {
background: #767D86;
border-radius: 0;
}
::-webkit-scrollbar-track {
background-color: #2d363f;
border-radius: 0;
}
#main {
height: 100%;
overflow-x: hidden;
overflow-y: auto;
position: absolute;
width: 100%;
}
.app {
background-color: #f0f3f6;
box-sizing: border-box;
/*box-shadow: 0 0 3px #ccc;*/
left: 0;
/*margin: 0 auto;*/
min-height: 100vh;
padding: 10px 10px 10px 240px;
position: relative;
transition: left 0.3s ease, padding-left 0.3s ease;
width: 100%;
}
#logo {
background-color: #3a4651;
box-sizing: border-box;
color: white;
font-size: 16px;
left: 0;
line-height: 70px;
padding-left: 15px;
position: fixed;
top: 0;
width: 230px;
}
.brick {
float: left;
height: 40px;
padding-top: 18px;
width: 50px;
}
.brick rect {
fill: #79D1EF;
}
#library {
background-color: #3a4651;
bottom: 0;
color: white;
font-size: 14px;
left: 0;
overflow-y: auto;
position: fixed;
top: 70px;
transition: left 0.3s ease;
width: 230px;
}
#library h2 {
padding-left: 20px;
}
.nav h3, .nav h4 {
color: white;
font-size: 14px;
margin: 0;
}
.nav h3 {
background-color: #0b98ca;
padding: 15px 10px 15px 20px;
}
.nav h4 {
background-color: #2d363f;
padding: 15px 10px 15px 40px;
}
.nav ul {
list-style: none;
margin: 0;
padding-left: 0;
}
.nav li {
color: rgba(255, 255, 255, 0.5);
cursor: pointer;
margin: 0;
padding: 10px 0 10px 40px;
transition: color 0.13s;
}
.nav li:hover {
color: white;
background-color: #2d363f;
}
#instructions {
background-color: #2d363f;
bottom: 0;
box-sizing: border-box;
color: rgba(255, 255, 255, 0.6);
left: 0;
overflow-y: auto;
padding: 10px;
position: fixed;
top: 70px;
width: 250px;
}
.tutorial.app {
padding-left: 490px;
}
.tutorial #logo {
width: 480px;
}
.tutorial #library {
left: 250px;
}
.selectedElementDialog {
background-color: rgba(58, 70, 81, 0.9);
border-radius: 4px;
color: white;
padding: 20px 14px 10px;
position: absolute;
}
#customValueInput input[type=radio] {
display: none;
}
#customValueInput input[type=radio] + label {
border: 3px solid rgba(0, 0, 0, 0);
color: white;
display: inline-block;
font-weight: bold;
height: 20px;
margin-right: 3px;
padding-left: 3px;
}
#customValueInput input[type=radio]:checked + label {
border: 3px solid orange;
}
.closeBtn {
color: white;
font-size: 15px;
line-height: 10px;
position: absolute;
right: 6px;
text-decoration: none;
top: 6px;
}
.closeBtn:hover, .closeBtn:focus, .closeBtn:active {
color: white;
text-decoration: none;
}
.topMargin {
margin-top: 5px;
}
.code {
color: rgba(255, 255, 255, 0.9);
font-weight: bold;
}
.github-logo {
width: 32px;
float: right;
filter: opacity(80%);
-webkit-filter: opacity(80%);
transition: filter 0.13s, -webkit-filter 0.13s;
}
.github-logo:hover {
filter: opacity(90%);
-webkit-filter: opacity(90%);
}
|
lambdablocks/blocks-front-react
|
docs/styles.css
|
CSS
|
gpl-3.0
| 3,881 |
<?php
/**
* 前台搜索生成类
* @category iCMS
* @package iCMS_Rules_Gen_Search
* @author yanjiuyuan
*/
class SearchPublicGen extends BasePublicGen implements IBasePublicGen
{
/**
* 引导方法
* @return string 返回执行结果
*/
public function GenPublic()
{
$result = self::GenSearch();
return $result;
}
/**
* 生成搜索列表
* @return string 搜索列表HTML
*/
private function GenSearch()
{
$temp = Control::GetRequest("temp", "");
$siteId = Control::GetRequest("site_id", 0);
$templateContent = parent::GetDynamicTemplateContent("big_search", 0);
parent::ReplaceFirst($templateContent);
//加载站点信息
if ($siteId > 0) {
$sitePublicData = new SitePublicData();
$arrOne = $sitePublicData->GetOne($siteId);
Template::ReplaceOne($templateContent, $arrOne);
}
$searchKey = Control::GetRequest("search_key", "");
$searchKey = urldecode($searchKey);
$pageIndex = Control::GetRequest("p", 1);
$f = Control::GetRequest("f", "_all");
$m = Control::GetRequest("m", "no");
$syn = Control::GetRequest("syn", "no");
$s = Control::GetRequest("s", "s_show_date_DESC");
$tagId = "big_search";
if (strlen($searchKey) > 0) {
if ($pageIndex > 0) {
$allCount = 0;
$tagContent = Template::GetCustomTagByTagId($tagId, $templateContent);
if (strlen($tagContent) > 0) {
$pageSize = Template::GetParamValue($tagContent, "top");
$arrList = self::GetSearchList($allCount, $searchKey, $pageIndex, $pageSize, $m, $syn, $f, $s);
if (count($arrList) > 0) {
Template::ReplaceList($templateContent, $arrList, $tagId);
$styleNumber = 1;
$templateFileUrl = "pager/pager_style" . $styleNumber . ".html";
$templateName = "default";
$templatePath = "front_template";
$pagerTemplate = Template::Load($templateFileUrl, $templateName, $templatePath);
$isJs = FALSE;
$navUrl = "/default.php?mod=search&m=$m&syn=$syn&f=$f&s=$s&temp=$temp&p={0}&ps=$pageSize&search_key=" . urlencode($searchKey);
$jsFunctionName = "";
$jsParamList = "";
$pagerButton = Pager::ShowPageButton($pagerTemplate, $navUrl, $allCount, $pageSize, $pageIndex, $styleNumber, $isJs, $jsFunctionName, $jsParamList);
$templateContent = str_ireplace("{" . $tagId . "_pager_button}", $pagerButton, $templateContent);
$templateContent = str_ireplace("{" . $tagId . "_item_count}", $allCount, $templateContent);
}
$templateContent = str_ireplace("{AllCount}", $allCount, $templateContent);
$templateContent = str_ireplace("{SearchKey}", urlencode($searchKey), $templateContent);
}
}
}
Template::RemoveCustomTag($templateContent, $tagId);
$templateContent = str_ireplace("{AllCount}", 0, $templateContent);
$templateContent = str_ireplace("{" . $tagId . "_pager_button}", "", $templateContent);
$templateContent = str_ireplace("{" . $tagId . "_item_count}", 0, $templateContent);
$templateContent = parent::ReplaceTemplate($templateContent);
parent::ReplaceEnd($templateContent);
return $templateContent;
}
/**
* 得到搜索数据
* @param int $allCount 记录总数
* @param string $q 查询语句
* @param int $p 第几页
* @param int $ps 每页显示条数
* @param string $m 开启模糊搜索,其值为 yes/no
* @param string $syn 开启同义词搜索,其值为 yes/no
* @param string $f 只搜索某个字段,其值为字段名称,要求该字段的索引方式为 self/both
* @param string $s : 排序字段名称及方式,其值形式为:xxx_ASC 或 xxx_DESC
* @param string xml: 是否将搜索结果以 XML 格式输出,其值为 yes/no
* @return array 搜素列表数据集
*/
private function GetSearchList(&$allCount, $q, $p, $ps, $m = "no", $syn = "no", $f = "_all", $s = "s_create_date_DESC", $xml = "no")
{
// 加载 XS 入口文件
require_once 'search/lib/XS.php';
// recheck request parameters
$q = get_magic_quotes_gpc() ? stripslashes($q) : $q;
$f = empty($f) ? '_all' : $f;
// other variable maybe used in tpl
$allCount = $total = $search_cost = 0;
$docs = $related = $corrected = $hot = array();
$error = $pager = '';
$total_begin = microtime(true);
// perform the search
$search = null;
try {
$xs = new XS('cswb');
$search = $xs->search;
$search->setCharset('UTF-8');
if (empty($q)) {
// just show hot query
$hot = $search->getHotQuery();
} else {
// fuzzy search
$search->setFuzzy($m === 'yes');
// synonym search
$search->setAutoSynonyms($syn === 'yes');
// set query
if (!empty($f) && $f != '_all') {
$search->setQuery($f . ':(' . $q . ')');
} else {
$search->setQuery($q);
}
// set sort
if (($pos = strrpos($s, '_')) !== false) {
$sf = substr($s, 0, $pos);
$st = substr($s, $pos + 1);
$search->setSort($sf, $st === 'ASC');
}
// set offset, limit
$p = max(1, intval($p));
//$n = XSSearch::PAGE_SIZE;
$search->setLimit($ps, ($p - 1) * $ps);
// get the result
$search_begin = microtime(true);
$docs = $search->search();
$search_cost = microtime(true) - $search_begin;
// get other result
$allCount = $search->getLastCount();
$total = $search->getDbTotal();
if ($xml !== 'yes') {
// try to corrected, if resul too few
if ($allCount < 1 || $allCount < ceil(0.001 * $total))
$corrected = $search->getCorrectedQuery();
// get related query
$related = $search->getRelatedQuery();
}
}
} catch (XSException $e) {
$error = strval($e);
}
// calculate total time cost
$total_cost = microtime(true) - $total_begin;
$arrList = self::ConvertToArray($search, $docs);
return $arrList;
}
/**
* 把XSDocument Object对象数组转化为标准php数组
* @param 全文搜索对象
* @param XObjects对象数组
* @return array 标准php数组
*/
private function ConvertToArray($search, $XObjects)
{
$sitePublicData = new SitePublicData();
$arrList = array();
foreach ($XObjects as $XObject) {
$title = $XObject->s_title;
$content = strip_tags($XObject->s_content);
$userName = $XObject->s_user_name;
$showDate = $XObject->s_show_date;
$showDate = date("Y-m-d", strtotime($showDate));
$siteId = $XObject->s_site_id;
$siteName = $sitePublicData->GetSiteName($siteId, true);
$siteUrl = $XObject->s_site_url;
$channelType=$XObject->s_channel_type;
if ($XObject->DirectUrl == null) {
switch($channelType){
case 1:
$publishDate=substr(str_ireplace("-","",$XObject->s_publish_date),0,8);
$directUrl = $siteUrl . "/h/$XObject->s_channel_id/$publishDate/$XObject->s_id.html";
break;
case 15:
$directUrl = $siteUrl . "/default.php?mod=newspaper_article&a=detail&newspaper_article_id=" . $XObject->s_id;
break;
default:
$publishDate=substr(str_ireplace("-","",$XObject->s_publish_date),0,8);
$directUrl = $siteUrl . "/h/$XObject->s_channel_id/$publishDate/$XObject->s_id.html";
break;
}
} else {
$directUrl = $XObject->DirectUrl;
}
array_push($arrList,
array(
"DirectUrl" => $directUrl,
"Title" => $search->highlight($title),
"Content" => $search->highlight($content),
"UserName" => $userName,
"ShowDate" => $showDate,
"SiteId" => $siteId,
"SiteName" => $siteName,
"SiteUrl" => $siteUrl
));
}
return $arrList;
}
}
?>
|
unique525/gb_0
|
FrameWork1/RuleClass/Gen/Search/SearchPublicGen.php
|
PHP
|
gpl-3.0
| 9,303 |
/*
Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 Her Majesty
the Queen in Right of Canada (Communications Research Center Canada)
*/
/*
This file is part of ODR-DabMod.
ODR-DabMod 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.
ODR-DabMod 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 ODR-DabMod. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MOD_INPUT_H
#define MOD_INPUT_H
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "ModPlugin.h"
#include <sys/types.h>
class ModInput : public ModPlugin
{
public:
ModInput(ModFormat inputFormat, ModFormat outputFormat);
virtual ~ModInput();
virtual int process(std::vector<Buffer*> dataIn,
std::vector<Buffer*> dataOut);
virtual int process(Buffer* dataIn, Buffer* dataOut) = 0;
protected:
#ifdef DEBUG
FILE* myOutputFile;
static size_t myCount;
#endif
};
#endif // MOD_INPUT_H
|
raspine/ODR-DabMod
|
src/ModInput.h
|
C
|
gpl-3.0
| 1,372 |
package org.sigmah.client.util;
/*
* #%L
* Sigmah
* %%
* Copyright (C) 2010 - 2016 URD
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.extjs.gxt.ui.client.util.DateWrapper;
import java.util.Date;
import org.sigmah.shared.dto.pivot.model.DateUnit;
import org.sigmah.shared.util.DateRange;
import org.sigmah.shared.util.Dates;
import org.sigmah.shared.util.Month;
/**
* Client-side implementation of {@link Dates}.
*
* @author Alex Bertram ([email protected])
* @author Raphaël Calabro ([email protected]) v2.0
*/
public class GWTDates extends Dates {
@Override
public Month getCurrentMonth() {
DateWrapper today = new DateWrapper();
return new Month(today.getFullYear(), today.getMonth());
}
@Override
public DateRange yearRange(int year) {
DateRange range = new DateRange();
DateWrapper date = new DateWrapper(year, 0, 1);
range.setMinDate(date.asDate());
date = new DateWrapper(year, 11, 31);
range.setMaxDate(date.asDate());
return range;
}
@Override
public DateRange monthRange(int year, int month) {
DateRange range = new DateRange();
DateWrapper date = new DateWrapper(year, month-1, 1);
range.setMinDate(date.asDate());
date = date.addMonths(1);
date = date.addDays(-1);
range.setMaxDate(date.asDate());
return range;
}
@Override
public int getYear(Date date) {
DateWrapper dw = new DateWrapper(date);
return dw.getFullYear();
}
@Override
public int getMonth(Date date) {
DateWrapper dw = new DateWrapper(date);
return dw.getMonth()+1;
}
@Override
public int getDay(Date date) {
DateWrapper dw = new DateWrapper(date);
return dw.getDay();
}
@Override
public Date floor(Date date, DateUnit dateUnit) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Date ceil(Date date, DateUnit dateUnit) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Date add(Date date, DateUnit dateUnit, int count) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean isLastDayOfMonth(Date date) {
return false;
}
}
|
Raphcal/sigmah
|
src/main/java/org/sigmah/client/util/GWTDates.java
|
Java
|
gpl-3.0
| 2,988 |
//=============================================================================
//=== Copyright (C) 2001-2005 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.services.thesaurus;
import jeeves.constants.Jeeves;
import jeeves.interfaces.Service;
import jeeves.server.ServiceConfig;
import jeeves.server.context.ServiceContext;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.kernel.Thesaurus;
import org.fao.geonet.kernel.ThesaurusManager;
import org.jdom.Element;
import java.util.Enumeration;
import java.util.Hashtable;
//=============================================================================
/**
*
* Retrieve Thesauri list.
*
* @author mcoudert
*
*/
public class GetList implements Service {
public void init(String appPath, ServiceConfig params) throws Exception {
}
// --------------------------------------------------------------------------
// ---
// --- Service
// ---
// --------------------------------------------------------------------------
public Element exec(Element params, ServiceContext context)
throws Exception {
Element response = new Element(Jeeves.Elem.RESPONSE);
GeonetContext gc = (GeonetContext) context
.getHandlerContext(Geonet.CONTEXT_NAME);
ThesaurusManager th = gc.getThesaurusManager();
Hashtable<String, Thesaurus> thTable = th.getThesauriTable();
response.addContent(buildResultfromThTable(thTable));
return response;
}
/**
* @param thTable
* @return {@link Element}
*/
private Element buildResultfromThTable(Hashtable<String, Thesaurus> thTable) {
Element elRoot = new Element("thesauri");
Enumeration<Thesaurus> e = thTable.elements();
while (e.hasMoreElements()) {
Element elLoop = new Element("thesaurus");
Thesaurus currentTh = e.nextElement();
Element elKey = new Element("key");
String key = currentTh.getKey();
elKey.addContent(key);
Element elDname = new Element("dname");
String dname = currentTh.getDname();
elDname.addContent(dname);
Element elFname = new Element("filename");
String fname = currentTh.getFname();
elFname.addContent(fname);
Element elType = new Element("type");
String type = currentTh.getType();
elType.addContent(type);
elLoop.addContent(elKey);
elLoop.addContent(elDname);
elLoop.addContent(elFname);
elLoop.addContent(elType);
elRoot.addContent(elLoop);
}
return elRoot;
}
}
// =============================================================================
|
dimipapadeas/openwis
|
openwis-metadataportal/openwis-portal/src/main/java/org/fao/geonet/services/thesaurus/GetList.java
|
Java
|
gpl-3.0
| 3,655 |
/*++ NDK Version: 0098
Copyright (c) Alex Ionescu. All rights reserved.
Header Name:
extypes.h
Abstract:
Type definitions for the Executive.
Author:
Alex Ionescu ([email protected]) - Updated - 27-Feb-2006
--*/
#ifndef _EXTYPES_H
#define _EXTYPES_H
//
// Dependencies
//
#include <umtypes.h>
#include <cfg.h>
#if defined(_MSC_VER) && !defined(NTOS_MODE_USER)
#include <ntimage.h>
#endif
#include <cmtypes.h>
#include <ketypes.h>
#include <potypes.h>
#include <lpctypes.h>
#ifdef NTOS_MODE_USER
#include <obtypes.h>
#endif
//
// GCC compatibility
//
#if defined(__GNUC__)
#define __ALIGNED(n) __attribute__((aligned (n)))
#elif defined(_MSC_VER)
#define __ALIGNED(n) __declspec(align(n))
#else
#error __ALIGNED not defined for your compiler!
#endif
//
// Atom and Language IDs
//
typedef USHORT LANGID, *PLANGID;
typedef USHORT RTL_ATOM, *PRTL_ATOM;
#ifndef NTOS_MODE_USER
//
// Kernel Exported Object Types
//
extern POBJECT_TYPE NTSYSAPI ExDesktopObjectType;
extern POBJECT_TYPE NTSYSAPI ExWindowStationObjectType;
extern POBJECT_TYPE NTSYSAPI ExIoCompletionType;
extern POBJECT_TYPE NTSYSAPI ExMutantObjectType;
extern POBJECT_TYPE NTSYSAPI ExTimerType;
//
// Exported NT Build Number
//
extern ULONG NtBuildNumber;
//
// Invalid Handle Value Constant
//
#define INVALID_HANDLE_VALUE (HANDLE)-1
#endif
//
// Increments
//
#define MUTANT_INCREMENT 1
//
// Callback Object Access Mask
//
#define CALLBACK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x0001)
#define CALLBACK_EXECUTE (STANDARD_RIGHTS_EXECUTE|SYNCHRONIZE|0x0001)
#define CALLBACK_WRITE (STANDARD_RIGHTS_WRITE|SYNCHRONIZE|0x0001)
#define CALLBACK_READ (STANDARD_RIGHTS_READ|SYNCHRONIZE|0x0001)
//
// Event Object Access Masks
//
#ifdef NTOS_MODE_USER
#define EVENT_QUERY_STATE 0x0001
//
// Semaphore Object Access Masks
//
#define SEMAPHORE_QUERY_STATE 0x0001
#else
//
// Mutant Object Access Masks
//
#define MUTANT_QUERY_STATE 0x0001
#define MUTANT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
SYNCHRONIZE | \
MUTANT_QUERY_STATE)
#define TIMER_QUERY_STATE 0x0001
#define TIMER_MODIFY_STATE 0x0002
#define TIMER_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
SYNCHRONIZE | \
TIMER_QUERY_STATE | \
TIMER_MODIFY_STATE)
#endif
//
// Event Pair Access Masks
//
#define EVENT_PAIR_ALL_ACCESS 0x1F0000L
//
// Profile Object Access Masks
//
#define PROFILE_CONTROL 0x0001
#define PROFILE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | PROFILE_CONTROL)
//
// Maximum Parameters for NtRaiseHardError
//
#define MAXIMUM_HARDERROR_PARAMETERS 4
//
// Pushlock bits
//
#define EX_PUSH_LOCK_LOCK_V ((ULONG_PTR)0x0)
#define EX_PUSH_LOCK_LOCK ((ULONG_PTR)0x1)
#define EX_PUSH_LOCK_WAITING ((ULONG_PTR)0x2)
#define EX_PUSH_LOCK_WAKING ((ULONG_PTR)0x4)
#define EX_PUSH_LOCK_MULTIPLE_SHARED ((ULONG_PTR)0x8)
#define EX_PUSH_LOCK_SHARE_INC ((ULONG_PTR)0x10)
#define EX_PUSH_LOCK_PTR_BITS ((ULONG_PTR)0xf)
//
// Pushlock Wait Block Flags
//
#define EX_PUSH_LOCK_FLAGS_EXCLUSIVE 1
#define EX_PUSH_LOCK_FLAGS_WAIT 2
//
// Resource (ERESOURCE) Flags
//
#define ResourceHasDisabledPriorityBoost 0x08
//
// Shutdown types for NtShutdownSystem
//
typedef enum _SHUTDOWN_ACTION
{
ShutdownNoReboot,
ShutdownReboot,
ShutdownPowerOff
} SHUTDOWN_ACTION;
//
// Responses for NtRaiseHardError
//
typedef enum _HARDERROR_RESPONSE_OPTION
{
OptionAbortRetryIgnore,
OptionOk,
OptionOkCancel,
OptionRetryCancel,
OptionYesNo,
OptionYesNoCancel,
OptionShutdownSystem
} HARDERROR_RESPONSE_OPTION, *PHARDERROR_RESPONSE_OPTION;
typedef enum _HARDERROR_RESPONSE
{
ResponseReturnToCaller,
ResponseNotHandled,
ResponseAbort,
ResponseCancel,
ResponseIgnore,
ResponseNo,
ResponseOk,
ResponseRetry,
ResponseYes,
ResponseTryAgain,
ResponseContinue
} HARDERROR_RESPONSE, *PHARDERROR_RESPONSE;
//
// System Information Classes for NtQuerySystemInformation
//
typedef enum _SYSTEM_INFORMATION_CLASS
{
SystemBasicInformation,
SystemProcessorInformation,
SystemPerformanceInformation,
SystemTimeOfDayInformation,
SystemPathInformation, /// Obsolete: Use KUSER_SHARED_DATA
SystemProcessInformation,
SystemCallCountInformation,
SystemDeviceInformation,
SystemProcessorPerformanceInformation,
SystemFlagsInformation,
SystemCallTimeInformation,
SystemModuleInformation,
SystemLocksInformation,
SystemStackTraceInformation,
SystemPagedPoolInformation,
SystemNonPagedPoolInformation,
SystemHandleInformation,
SystemObjectInformation,
SystemPageFileInformation,
SystemVdmInstemulInformation,
SystemVdmBopInformation,
SystemFileCacheInformation,
SystemPoolTagInformation,
SystemInterruptInformation,
SystemDpcBehaviorInformation,
SystemFullMemoryInformation,
SystemLoadGdiDriverInformation,
SystemUnloadGdiDriverInformation,
SystemTimeAdjustmentInformation,
SystemSummaryMemoryInformation,
SystemMirrorMemoryInformation,
SystemPerformanceTraceInformation,
SystemObsolete0,
SystemExceptionInformation,
SystemCrashDumpStateInformation,
SystemKernelDebuggerInformation,
SystemContextSwitchInformation,
SystemRegistryQuotaInformation,
SystemExtendServiceTableInformation,
SystemPrioritySeperation,
SystemPlugPlayBusInformation,
SystemDockInformation,
SystemPowerInformationNative,
SystemProcessorSpeedInformation,
SystemCurrentTimeZoneInformation,
SystemLookasideInformation,
SystemTimeSlipNotification,
SystemSessionCreate,
SystemSessionDetach,
SystemSessionInformation,
SystemRangeStartInformation,
SystemVerifierInformation,
SystemAddVerifier,
SystemSessionProcessesInformation,
SystemLoadGdiDriverInSystemSpaceInformation,
SystemNumaProcessorMap,
SystemPrefetcherInformation,
SystemExtendedProcessInformation,
SystemRecommendedSharedDataAlignment,
SystemComPlusPackage,
SystemNumaAvailableMemory,
SystemProcessorPowerInformation,
SystemEmulationBasicInformation,
SystemEmulationProcessorInformation,
SystemExtendedHanfleInformation,
SystemLostDelayedWriteInformation,
SystemBigPoolInformation,
SystemSessionPoolTagInformation,
SystemSessionMappedViewInformation,
SystemHotpatchInformation,
SystemObjectSecurityMode,
SystemWatchDogTimerHandler,
SystemWatchDogTimerInformation,
SystemLogicalProcessorInformation,
SystemWo64SharedInformationObosolete,
SystemRegisterFirmwareTableInformationHandler,
SystemFirmwareTableInformation,
SystemModuleInformationEx,
SystemVerifierTriageInformation,
SystemSuperfetchInformation,
SystemMemoryListInformation,
SystemFileCacheInformationEx,
SystemThreadPriorityClientIdInformation,
SystemProcessorIdleCycleTimeInformation,
SystemVerifierCancellationInformation,
SystemProcessorPowerInformationEx,
SystemRefTraceInformation,
SystemSpecialPoolInformation,
SystemProcessIdInformation,
SystemErrorPortInformation,
SystemBootEnvironmentInformation,
SystemHypervisorInformation,
SystemVerifierInformationEx,
SystemTimeZoneInformation,
SystemImageFileExecutionOptionsInformation,
SystemCoverageInformation,
SystemPrefetchPathInformation,
SystemVerifierFaultsInformation,
MaxSystemInfoClass,
} SYSTEM_INFORMATION_CLASS;
//
// System Information Classes for NtQueryMutant
//
typedef enum _MUTANT_INFORMATION_CLASS
{
MutantBasicInformation,
MutantOwnerInformation
} MUTANT_INFORMATION_CLASS;
//
// System Information Classes for NtQueryAtom
//
typedef enum _ATOM_INFORMATION_CLASS
{
AtomBasicInformation,
AtomTableInformation,
} ATOM_INFORMATION_CLASS;
//
// System Information Classes for NtQueryTimer
//
typedef enum _TIMER_INFORMATION_CLASS
{
TimerBasicInformation
} TIMER_INFORMATION_CLASS;
//
// System Information Classes for NtQuerySemaphore
//
typedef enum _SEMAPHORE_INFORMATION_CLASS
{
SemaphoreBasicInformation
} SEMAPHORE_INFORMATION_CLASS;
//
// System Information Classes for NtQueryEvent
//
typedef enum _EVENT_INFORMATION_CLASS
{
EventBasicInformation
} EVENT_INFORMATION_CLASS;
#ifdef NTOS_MODE_USER
//
// Firmware Table Actions for SystemFirmwareTableInformation
//
typedef enum _SYSTEM_FIRMWARE_TABLE_ACTION
{
SystemFirmwareTable_Enumerate = 0,
SystemFirmwareTable_Get = 1,
} SYSTEM_FIRMWARE_TABLE_ACTION, *PSYSTEM_FIRMWARE_TABLE_ACTION;
//
// Firmware Handler Callback
//
struct _SYSTEM_FIRMWARE_TABLE_INFORMATION;
typedef
NTSTATUS
(__cdecl *PFNFTH)(
IN struct _SYSTEM_FIRMWARE_TABLE_INFORMATION *FirmwareTableInformation
);
#else
//
// Handle Enumeration Callback
//
struct _HANDLE_TABLE_ENTRY;
typedef BOOLEAN
(NTAPI *PEX_ENUM_HANDLE_CALLBACK)(
IN struct _HANDLE_TABLE_ENTRY *HandleTableEntry,
IN HANDLE Handle,
IN PVOID Context
);
//
// Compatibility with Windows XP Drivers using ERESOURCE
//
typedef struct _ERESOURCE_XP
{
LIST_ENTRY SystemResourcesList;
POWNER_ENTRY OwnerTable;
SHORT ActiveCount;
USHORT Flag;
PKSEMAPHORE SharedWaiters;
PKEVENT ExclusiveWaiters;
OWNER_ENTRY OwnerThreads[2];
ULONG ContentionCount;
USHORT NumberOfSharedWaiters;
USHORT NumberOfExclusiveWaiters;
union
{
PVOID Address;
ULONG_PTR CreatorBackTraceIndex;
};
KSPIN_LOCK SpinLock;
} ERESOURCE_XP, *PERESOURCE_XP;
//
// Executive Work Queue Structures
//
typedef struct _EX_QUEUE_WORKER_INFO
{
ULONG QueueDisabled:1;
ULONG MakeThreadsAsNecessary:1;
ULONG WaitMode:1;
ULONG WorkerCount:29;
} EX_QUEUE_WORKER_INFO, *PEX_QUEUE_WORKER_INFO;
typedef struct _EX_WORK_QUEUE
{
KQUEUE WorkerQueue;
LONG DynamicThreadCount;
ULONG WorkItemsProcessed;
ULONG WorkItemsProcessedLastPass;
ULONG QueueDepthLastPass;
EX_QUEUE_WORKER_INFO Info;
} EX_WORK_QUEUE, *PEX_WORK_QUEUE;
//
// Executive Fast Reference Structure
//
typedef struct _EX_FAST_REF
{
union
{
PVOID Object;
ULONG_PTR RefCnt:3;
ULONG_PTR Value;
};
} EX_FAST_REF, *PEX_FAST_REF;
//
// Executive Cache-Aware Rundown Reference Descriptor
//
typedef struct _EX_RUNDOWN_REF_CACHE_AWARE
{
PEX_RUNDOWN_REF RunRefs;
PVOID PoolToFree;
ULONG RunRefSize;
ULONG Number;
} EX_RUNDOWN_REF_CACHE_AWARE, *PEX_RUNDOWN_REF_CACHE_AWARE;
//
// Executive Rundown Wait Block
//
typedef struct _EX_RUNDOWN_WAIT_BLOCK
{
ULONG_PTR Count;
KEVENT WakeEvent;
} EX_RUNDOWN_WAIT_BLOCK, *PEX_RUNDOWN_WAIT_BLOCK;
//
// Executive Pushlock
//
#undef EX_PUSH_LOCK
#undef PEX_PUSH_LOCK
typedef struct _EX_PUSH_LOCK
{
union
{
struct
{
ULONG_PTR Locked:1;
ULONG_PTR Waiting:1;
ULONG_PTR Waking:1;
ULONG_PTR MultipleShared:1;
ULONG_PTR Shared:sizeof (ULONG_PTR) * 8 - 4;
};
ULONG_PTR Value;
PVOID Ptr;
};
} EX_PUSH_LOCK, *PEX_PUSH_LOCK;
//
// Executive Pushlock Wait Block
//
typedef __ALIGNED(16) struct _EX_PUSH_LOCK_WAIT_BLOCK
{
union
{
KGATE WakeGate;
KEVENT WakeEvent;
};
struct _EX_PUSH_LOCK_WAIT_BLOCK *Next;
struct _EX_PUSH_LOCK_WAIT_BLOCK *Last;
struct _EX_PUSH_LOCK_WAIT_BLOCK *Previous;
LONG ShareCount;
LONG Flags;
#if DBG
BOOLEAN Signaled;
EX_PUSH_LOCK NewValue;
EX_PUSH_LOCK OldValue;
PEX_PUSH_LOCK PushLock;
#endif
} EX_PUSH_LOCK_WAIT_BLOCK, *PEX_PUSH_LOCK_WAIT_BLOCK;
//
// Callback Object
//
typedef struct _CALLBACK_OBJECT
{
ULONG Signature;
KSPIN_LOCK Lock;
LIST_ENTRY RegisteredCallbacks;
BOOLEAN AllowMultipleCallbacks;
UCHAR reserved[3];
} CALLBACK_OBJECT, *PCALLBACK_OBJECT;
//
// Callback Handle
//
typedef struct _CALLBACK_REGISTRATION
{
LIST_ENTRY Link;
PCALLBACK_OBJECT CallbackObject;
PCALLBACK_FUNCTION CallbackFunction;
PVOID CallbackContext;
ULONG Busy;
BOOLEAN UnregisterWaiting;
} CALLBACK_REGISTRATION, *PCALLBACK_REGISTRATION;
//
// Internal Callback Object
//
typedef struct _EX_CALLBACK_ROUTINE_BLOCK
{
EX_RUNDOWN_REF RundownProtect;
PEX_CALLBACK_FUNCTION Function;
PVOID Context;
} EX_CALLBACK_ROUTINE_BLOCK, *PEX_CALLBACK_ROUTINE_BLOCK;
//
// Internal Callback Handle
//
typedef struct _EX_CALLBACK
{
EX_FAST_REF RoutineBlock;
} EX_CALLBACK, *PEX_CALLBACK;
//
// Profile Object
//
typedef struct _EPROFILE
{
PEPROCESS Process;
PVOID RangeBase;
SIZE_T RangeSize;
PVOID Buffer;
ULONG BufferSize;
ULONG BucketSize;
PKPROFILE ProfileObject;
PVOID LockedBufferAddress;
PMDL Mdl;
ULONG Segment;
KPROFILE_SOURCE ProfileSource;
KAFFINITY Affinity;
} EPROFILE, *PEPROFILE;
//
// Handle Table Structures
//
typedef struct _HANDLE_TRACE_DB_ENTRY
{
CLIENT_ID ClientId;
HANDLE Handle;
ULONG Type;
PVOID StackTrace[16];
} HANDLE_TRACE_DB_ENTRY, *PHANDLE_TRACE_DB_ENTRY;
typedef struct _HANDLE_TRACE_DEBUG_INFO
{
LONG RefCount;
ULONG TableSize;
ULONG BitMaskFlags;
FAST_MUTEX CloseCompatcionLock;
ULONG CurrentStackIndex;
HANDLE_TRACE_DB_ENTRY TraceDb[1];
} HANDLE_TRACE_DEBUG_INFO, *PHANDLE_TRACE_DEBUG_INFO;
typedef struct _HANDLE_TABLE_ENTRY_INFO
{
ULONG AuditMask;
} HANDLE_TABLE_ENTRY_INFO, *PHANDLE_TABLE_ENTRY_INFO;
typedef struct _HANDLE_TABLE_ENTRY
{
union
{
PVOID Object;
ULONG_PTR ObAttributes;
PHANDLE_TABLE_ENTRY_INFO InfoTable;
ULONG_PTR Value;
};
union
{
ULONG GrantedAccess;
struct
{
USHORT GrantedAccessIndex;
USHORT CreatorBackTraceIndex;
};
LONG NextFreeTableEntry;
};
} HANDLE_TABLE_ENTRY, *PHANDLE_TABLE_ENTRY;
typedef struct _HANDLE_TABLE
{
#if (NTDDI_VERSION >= NTDDI_WINXP)
ULONG TableCode;
#else
PHANDLE_TABLE_ENTRY **Table;
#endif
PEPROCESS QuotaProcess;
PVOID UniqueProcessId;
#if (NTDDI_VERSION >= NTDDI_WINXP)
EX_PUSH_LOCK HandleTableLock[4];
LIST_ENTRY HandleTableList;
EX_PUSH_LOCK HandleContentionEvent;
#else
ERESOURCE HandleLock;
LIST_ENTRY HandleTableList;
KEVENT HandleContentionEvent;
#endif
PHANDLE_TRACE_DEBUG_INFO DebugInfo;
LONG ExtraInfoPages;
#if (NTDDI_VERSION >= NTDDI_LONGHORN)
union
{
ULONG Flags;
UCHAR StrictFIFO:1;
};
LONG FirstFreeHandle;
PHANDLE_TABLE_ENTRY LastFreeHandleEntry;
LONG HandleCount;
ULONG NextHandleNeedingPool;
#else
ULONG FirstFree;
ULONG LastFree;
ULONG NextHandleNeedingPool;
LONG HandleCount;
union
{
ULONG Flags;
UCHAR StrictFIFO:1;
};
#endif
} HANDLE_TABLE, *PHANDLE_TABLE;
#endif
//
// Hard Error LPC Message
//
typedef struct _HARDERROR_MSG
{
PORT_MESSAGE h;
NTSTATUS Status;
LARGE_INTEGER ErrorTime;
ULONG ValidResponseOptions;
ULONG Response;
ULONG NumberOfParameters;
ULONG UnicodeStringParameterMask;
ULONG Parameters[MAXIMUM_HARDERROR_PARAMETERS];
} HARDERROR_MSG, *PHARDERROR_MSG;
//
// Information Structures for NtQueryMutant
//
typedef struct _MUTANT_BASIC_INFORMATION
{
LONG CurrentCount;
BOOLEAN OwnedByCaller;
BOOLEAN AbandonedState;
} MUTANT_BASIC_INFORMATION, *PMUTANT_BASIC_INFORMATION;
typedef struct _MUTANT_OWNER_INFORMATION
{
CLIENT_ID ClientId;
} MUTANT_OWNER_INFORMATION, *PMUTANT_OWNER_INFORMATION;
//
// Information Structures for NtQueryAtom
//
typedef struct _ATOM_BASIC_INFORMATION
{
USHORT UsageCount;
USHORT Flags;
USHORT NameLength;
WCHAR Name[1];
} ATOM_BASIC_INFORMATION, *PATOM_BASIC_INFORMATION;
typedef struct _ATOM_TABLE_INFORMATION
{
ULONG NumberOfAtoms;
USHORT Atoms[1];
} ATOM_TABLE_INFORMATION, *PATOM_TABLE_INFORMATION;
//
// Information Structures for NtQueryTimer
//
typedef struct _TIMER_BASIC_INFORMATION
{
LARGE_INTEGER TimeRemaining;
BOOLEAN SignalState;
} TIMER_BASIC_INFORMATION, *PTIMER_BASIC_INFORMATION;
//
// Information Structures for NtQuerySemaphore
//
typedef struct _SEMAPHORE_BASIC_INFORMATION
{
LONG CurrentCount;
LONG MaximumCount;
} SEMAPHORE_BASIC_INFORMATION, *PSEMAPHORE_BASIC_INFORMATION;
//
// Information Structures for NtQueryEvent
//
typedef struct _EVENT_BASIC_INFORMATION
{
EVENT_TYPE EventType;
LONG EventState;
} EVENT_BASIC_INFORMATION, *PEVENT_BASIC_INFORMATION;
//
// Information Structures for NtQuerySystemInformation
//
typedef struct _SYSTEM_BASIC_INFORMATION
{
ULONG Reserved;
ULONG TimerResolution;
ULONG PageSize;
ULONG NumberOfPhysicalPages;
ULONG LowestPhysicalPageNumber;
ULONG HighestPhysicalPageNumber;
ULONG AllocationGranularity;
ULONG_PTR MinimumUserModeAddress;
ULONG_PTR MaximumUserModeAddress;
ULONG_PTR ActiveProcessorsAffinityMask;
CCHAR NumberOfProcessors;
} SYSTEM_BASIC_INFORMATION, *PSYSTEM_BASIC_INFORMATION;
// Class 1
typedef struct _SYSTEM_PROCESSOR_INFORMATION
{
USHORT ProcessorArchitecture;
USHORT ProcessorLevel;
USHORT ProcessorRevision;
USHORT Reserved;
ULONG ProcessorFeatureBits;
} SYSTEM_PROCESSOR_INFORMATION, *PSYSTEM_PROCESSOR_INFORMATION;
// Class 2
typedef struct _SYSTEM_PERFORMANCE_INFORMATION
{
LARGE_INTEGER IdleProcessTime;
LARGE_INTEGER IoReadTransferCount;
LARGE_INTEGER IoWriteTransferCount;
LARGE_INTEGER IoOtherTransferCount;
ULONG IoReadOperationCount;
ULONG IoWriteOperationCount;
ULONG IoOtherOperationCount;
ULONG AvailablePages;
ULONG CommittedPages;
ULONG CommitLimit;
ULONG PeakCommitment;
ULONG PageFaultCount;
ULONG CopyOnWriteCount;
ULONG TransitionCount;
ULONG CacheTransitionCount;
ULONG DemandZeroCount;
ULONG PageReadCount;
ULONG PageReadIoCount;
ULONG CacheReadCount;
ULONG CacheIoCount;
ULONG DirtyPagesWriteCount;
ULONG DirtyWriteIoCount;
ULONG MappedPagesWriteCount;
ULONG MappedWriteIoCount;
ULONG PagedPoolPages;
ULONG NonPagedPoolPages;
ULONG PagedPoolAllocs;
ULONG PagedPoolFrees;
ULONG NonPagedPoolAllocs;
ULONG NonPagedPoolFrees;
ULONG FreeSystemPtes;
ULONG ResidentSystemCodePage;
ULONG TotalSystemDriverPages;
ULONG TotalSystemCodePages;
ULONG NonPagedPoolLookasideHits;
ULONG PagedPoolLookasideHits;
ULONG Spare3Count;
ULONG ResidentSystemCachePage;
ULONG ResidentPagedPoolPage;
ULONG ResidentSystemDriverPage;
ULONG CcFastReadNoWait;
ULONG CcFastReadWait;
ULONG CcFastReadResourceMiss;
ULONG CcFastReadNotPossible;
ULONG CcFastMdlReadNoWait;
ULONG CcFastMdlReadWait;
ULONG CcFastMdlReadResourceMiss;
ULONG CcFastMdlReadNotPossible;
ULONG CcMapDataNoWait;
ULONG CcMapDataWait;
ULONG CcMapDataNoWaitMiss;
ULONG CcMapDataWaitMiss;
ULONG CcPinMappedDataCount;
ULONG CcPinReadNoWait;
ULONG CcPinReadWait;
ULONG CcPinReadNoWaitMiss;
ULONG CcPinReadWaitMiss;
ULONG CcCopyReadNoWait;
ULONG CcCopyReadWait;
ULONG CcCopyReadNoWaitMiss;
ULONG CcCopyReadWaitMiss;
ULONG CcMdlReadNoWait;
ULONG CcMdlReadWait;
ULONG CcMdlReadNoWaitMiss;
ULONG CcMdlReadWaitMiss;
ULONG CcReadAheadIos;
ULONG CcLazyWriteIos;
ULONG CcLazyWritePages;
ULONG CcDataFlushes;
ULONG CcDataPages;
ULONG ContextSwitches;
ULONG FirstLevelTbFills;
ULONG SecondLevelTbFills;
ULONG SystemCalls;
} SYSTEM_PERFORMANCE_INFORMATION, *PSYSTEM_PERFORMANCE_INFORMATION;
// Class 3
typedef struct _SYSTEM_TIMEOFDAY_INFORMATION
{
LARGE_INTEGER BootTime;
LARGE_INTEGER CurrentTime;
LARGE_INTEGER TimeZoneBias;
ULONG TimeZoneId;
ULONG Reserved;
LARGE_INTEGER BootTimeBias;
LARGE_INTEGER SleepTimeBias;
} SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION;
// Class 4
// This class is obsolete, please use KUSER_SHARED_DATA instead
// Class 5
typedef struct _SYSTEM_THREAD_INFORMATION
{
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientId;
KPRIORITY Priority;
LONG BasePriority;
ULONG ContextSwitches;
ULONG ThreadState;
ULONG WaitReason;
} SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;
typedef struct _SYSTEM_PROCESS_INFORMATION
{
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER SpareLi1;
LARGE_INTEGER SpareLi2;
LARGE_INTEGER SpareLi3;
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
ULONG HandleCount;
ULONG SessionId;
ULONG_PTR PageDirectoryBase;
//
// This part corresponds to VM_COUNTERS_EX.
// NOTE: *NOT* THE SAME AS VM_COUNTERS!
//
SIZE_T PeakVirtualSize;
ULONG VirtualSize;
SIZE_T PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
SIZE_T PrivatePageCount;
//
// This part corresponds to IO_COUNTERS
//
LARGE_INTEGER ReadOperationCount;
LARGE_INTEGER WriteOperationCount;
LARGE_INTEGER OtherOperationCount;
LARGE_INTEGER ReadTransferCount;
LARGE_INTEGER WriteTransferCount;
LARGE_INTEGER OtherTransferCount;
//SYSTEM_THREAD_INFORMATION TH[1];
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;
// Class 6
typedef struct _SYSTEM_CALL_COUNT_INFORMATION
{
ULONG Length;
ULONG NumberOfTables;
} SYSTEM_CALL_COUNT_INFORMATION, *PSYSTEM_CALL_COUNT_INFORMATION;
// Class 7
typedef struct _SYSTEM_DEVICE_INFORMATION
{
ULONG NumberOfDisks;
ULONG NumberOfFloppies;
ULONG NumberOfCdRoms;
ULONG NumberOfTapes;
ULONG NumberOfSerialPorts;
ULONG NumberOfParallelPorts;
} SYSTEM_DEVICE_INFORMATION, *PSYSTEM_DEVICE_INFORMATION;
// Class 8
typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
{
LARGE_INTEGER IdleTime;
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER DpcTime;
LARGE_INTEGER InterruptTime;
ULONG InterruptCount;
} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, *PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;
// Class 9
typedef struct _SYSTEM_FLAGS_INFORMATION
{
ULONG Flags;
} SYSTEM_FLAGS_INFORMATION, *PSYSTEM_FLAGS_INFORMATION;
// Class 10
typedef struct _SYSTEM_CALL_TIME_INFORMATION
{
ULONG Length;
ULONG TotalCalls;
LARGE_INTEGER TimeOfCalls[1];
} SYSTEM_CALL_TIME_INFORMATION, *PSYSTEM_CALL_TIME_INFORMATION;
// Class 11 - See RTL_PROCESS_MODULES
// Class 12 - See RTL_PROCESS_LOCKS
// Class 13 - See RTL_PROCESS_BACKTRACES
// Class 14 - 15
typedef struct _SYSTEM_POOL_ENTRY
{
BOOLEAN Allocated;
BOOLEAN Spare0;
USHORT AllocatorBackTraceIndex;
ULONG Size;
union
{
UCHAR Tag[4];
ULONG TagUlong;
PVOID ProcessChargedQuota;
};
} SYSTEM_POOL_ENTRY, *PSYSTEM_POOL_ENTRY;
typedef struct _SYSTEM_POOL_INFORMATION
{
ULONG TotalSize;
PVOID FirstEntry;
USHORT EntryOverhead;
BOOLEAN PoolTagPresent;
BOOLEAN Spare0;
ULONG NumberOfEntries;
SYSTEM_POOL_ENTRY Entries[1];
} SYSTEM_POOL_INFORMATION, *PSYSTEM_POOL_INFORMATION;
// Class 16
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO
{
USHORT UniqueProcessId;
USHORT CreatorBackTraceIndex;
UCHAR ObjectTypeIndex;
UCHAR HandleAttributes;
USHORT HandleValue;
PVOID Object;
ULONG GrantedAccess;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO;
typedef struct _SYSTEM_HANDLE_INFORMATION
{
ULONG NumberOfHandles;
SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
// Class 17
typedef struct _SYSTEM_OBJECTTYPE_INFORMATION
{
ULONG NextEntryOffset;
ULONG NumberOfObjects;
ULONG NumberOfHandles;
ULONG TypeIndex;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccessMask;
ULONG PoolType;
BOOLEAN SecurityRequired;
BOOLEAN WaitableObject;
UNICODE_STRING TypeName;
} SYSTEM_OBJECTTYPE_INFORMATION, *PSYSTEM_OBJECTTYPE_INFORMATION;
typedef struct _SYSTEM_OBJECT_INFORMATION
{
ULONG NextEntryOffset;
PVOID Object;
HANDLE CreatorUniqueProcess;
USHORT CreatorBackTraceIndex;
USHORT Flags;
LONG PointerCount;
LONG HandleCount;
ULONG PagedPoolCharge;
ULONG NonPagedPoolCharge;
HANDLE ExclusiveProcessId;
PVOID SecurityDescriptor;
OBJECT_NAME_INFORMATION NameInfo;
} SYSTEM_OBJECT_INFORMATION, *PSYSTEM_OBJECT_INFORMATION;
// Class 18
typedef struct _SYSTEM_PAGEFILE_INFORMATION
{
ULONG NextEntryOffset;
ULONG TotalSize;
ULONG TotalInUse;
ULONG PeakUsage;
UNICODE_STRING PageFileName;
} SYSTEM_PAGEFILE_INFORMATION, *PSYSTEM_PAGEFILE_INFORMATION;
// Class 19
typedef struct _SYSTEM_VDM_INSTEMUL_INFO
{
ULONG SegmentNotPresent;
ULONG VdmOpcode0F;
ULONG OpcodeESPrefix;
ULONG OpcodeCSPrefix;
ULONG OpcodeSSPrefix;
ULONG OpcodeDSPrefix;
ULONG OpcodeFSPrefix;
ULONG OpcodeGSPrefix;
ULONG OpcodeOPER32Prefix;
ULONG OpcodeADDR32Prefix;
ULONG OpcodeINSB;
ULONG OpcodeINSW;
ULONG OpcodeOUTSB;
ULONG OpcodeOUTSW;
ULONG OpcodePUSHF;
ULONG OpcodePOPF;
ULONG OpcodeINTnn;
ULONG OpcodeINTO;
ULONG OpcodeIRET;
ULONG OpcodeINBimm;
ULONG OpcodeINWimm;
ULONG OpcodeOUTBimm;
ULONG OpcodeOUTWimm ;
ULONG OpcodeINB;
ULONG OpcodeINW;
ULONG OpcodeOUTB;
ULONG OpcodeOUTW;
ULONG OpcodeLOCKPrefix;
ULONG OpcodeREPNEPrefix;
ULONG OpcodeREPPrefix;
ULONG OpcodeHLT;
ULONG OpcodeCLI;
ULONG OpcodeSTI;
ULONG BopCount;
} SYSTEM_VDM_INSTEMUL_INFO, *PSYSTEM_VDM_INSTEMUL_INFO;
// Class 20 - ULONG VDMBOPINFO
// Class 21
typedef struct _SYSTEM_FILECACHE_INFORMATION
{
ULONG CurrentSize;
ULONG PeakSize;
ULONG PageFaultCount;
ULONG MinimumWorkingSet;
ULONG MaximumWorkingSet;
ULONG CurrentSizeIncludingTransitionInPages;
ULONG PeakSizeIncludingTransitionInPages;
ULONG TransitionRePurposeCount;
ULONG Flags;
} SYSTEM_FILECACHE_INFORMATION, *PSYSTEM_FILECACHE_INFORMATION;
// Class 22
typedef struct _SYSTEM_POOLTAG
{
union
{
UCHAR Tag[4];
ULONG TagUlong;
};
ULONG PagedAllocs;
ULONG PagedFrees;
ULONG PagedUsed;
ULONG NonPagedAllocs;
ULONG NonPagedFrees;
ULONG NonPagedUsed;
} SYSTEM_POOLTAG, *PSYSTEM_POOLTAG;
typedef struct _SYSTEM_POOLTAG_INFORMATION
{
ULONG Count;
SYSTEM_POOLTAG TagInfo[1];
} SYSTEM_POOLTAG_INFORMATION, *PSYSTEM_POOLTAG_INFORMATION;
// Class 23
typedef struct _SYSTEM_INTERRUPT_INFORMATION
{
ULONG ContextSwitches;
ULONG DpcCount;
ULONG DpcRate;
ULONG TimeIncrement;
ULONG DpcBypassCount;
ULONG ApcBypassCount;
} SYSTEM_INTERRUPT_INFORMATION, *PSYSTEM_INTERRUPT_INFORMATION;
// Class 24
typedef struct _SYSTEM_DPC_BEHAVIOR_INFORMATION
{
ULONG Spare;
ULONG DpcQueueDepth;
ULONG MinimumDpcRate;
ULONG AdjustDpcThreshold;
ULONG IdealDpcRate;
} SYSTEM_DPC_BEHAVIOR_INFORMATION, *PSYSTEM_DPC_BEHAVIOR_INFORMATION;
// Class 25
typedef struct _SYSTEM_MEMORY_INFO
{
PUCHAR StringOffset;
USHORT ValidCount;
USHORT TransitionCount;
USHORT ModifiedCount;
USHORT PageTableCount;
} SYSTEM_MEMORY_INFO, *PSYSTEM_MEMORY_INFO;
typedef struct _SYSTEM_MEMORY_INFORMATION
{
ULONG InfoSize;
ULONG StringStart;
SYSTEM_MEMORY_INFO Memory[1];
} SYSTEM_MEMORY_INFORMATION, *PSYSTEM_MEMORY_INFORMATION;
// Class 26
typedef struct _SYSTEM_GDI_DRIVER_INFORMATION
{
UNICODE_STRING DriverName;
PVOID ImageAddress;
PVOID SectionPointer;
PVOID EntryPoint;
PIMAGE_EXPORT_DIRECTORY ExportSectionPointer;
ULONG ImageLength;
} SYSTEM_GDI_DRIVER_INFORMATION, *PSYSTEM_GDI_DRIVER_INFORMATION;
// Class 27
// Not an actually class, simply a PVOID to the ImageAddress
// Class 28
typedef struct _SYSTEM_QUERY_TIME_ADJUST_INFORMATION
{
ULONG TimeAdjustment;
ULONG TimeIncrement;
BOOLEAN Enable;
} SYSTEM_QUERY_TIME_ADJUST_INFORMATION, *PSYSTEM_QUERY_TIME_ADJUST_INFORMATION;
typedef struct _SYSTEM_SET_TIME_ADJUST_INFORMATION
{
ULONG TimeAdjustment;
BOOLEAN Enable;
} SYSTEM_SET_TIME_ADJUST_INFORMATION, *PSYSTEM_SET_TIME_ADJUST_INFORMATION;
// Class 29 - Same as 25
// FIXME: Class 30
// Class 31
typedef struct _SYSTEM_REF_TRACE_INFORMATION
{
UCHAR TraceEnable;
UCHAR TracePermanent;
UNICODE_STRING TraceProcessName;
UNICODE_STRING TracePoolTags;
} SYSTEM_REF_TRACE_INFORMATION, *PSYSTEM_REF_TRACE_INFORMATION;
// Class 32 - OBSOLETE
// Class 33
typedef struct _SYSTEM_EXCEPTION_INFORMATION
{
ULONG AlignmentFixupCount;
ULONG ExceptionDispatchCount;
ULONG FloatingEmulationCount;
ULONG ByteWordEmulationCount;
} SYSTEM_EXCEPTION_INFORMATION, *PSYSTEM_EXCEPTION_INFORMATION;
// Class 34
typedef struct _SYSTEM_CRASH_STATE_INFORMATION
{
ULONG ValidCrashDump;
} SYSTEM_CRASH_STATE_INFORMATION, *PSYSTEM_CRASH_STATE_INFORMATION;
// Class 35
typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION
{
BOOLEAN KernelDebuggerEnabled;
BOOLEAN KernelDebuggerNotPresent;
} SYSTEM_KERNEL_DEBUGGER_INFORMATION, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION;
// Class 36
typedef struct _SYSTEM_CONTEXT_SWITCH_INFORMATION
{
ULONG ContextSwitches;
ULONG FindAny;
ULONG FindLast;
ULONG FindIdeal;
ULONG IdleAny;
ULONG IdleCurrent;
ULONG IdleLast;
ULONG IdleIdeal;
ULONG PreemptAny;
ULONG PreemptCurrent;
ULONG PreemptLast;
ULONG SwitchToIdle;
} SYSTEM_CONTEXT_SWITCH_INFORMATION, *PSYSTEM_CONTEXT_SWITCH_INFORMATION;
// Class 37
typedef struct _SYSTEM_REGISTRY_QUOTA_INFORMATION
{
ULONG RegistryQuotaAllowed;
ULONG RegistryQuotaUsed;
ULONG PagedPoolSize;
} SYSTEM_REGISTRY_QUOTA_INFORMATION, *PSYSTEM_REGISTRY_QUOTA_INFORMATION;
// Class 38
// Not a structure, simply send the UNICODE_STRING
// Class 39
// Not a structure, simply send a ULONG containing the new separation
// Class 40
typedef struct _SYSTEM_PLUGPLAY_BUS_INFORMATION
{
ULONG BusCount;
PLUGPLAY_BUS_INSTANCE BusInstance[1];
} SYSTEM_PLUGPLAY_BUS_INFORMATION, *PSYSTEM_PLUGPLAY_BUS_INFORMATION;
// Class 41
typedef struct _SYSTEM_DOCK_INFORMATION
{
SYSTEM_DOCK_STATE DockState;
INTERFACE_TYPE DeviceBusType;
ULONG DeviceBusNumber;
ULONG SlotNumber;
} SYSTEM_DOCK_INFORMATION, *PSYSTEM_DOCK_INFORMATION;
// Class 42
typedef struct _SYSTEM_POWER_INFORMATION_NATIVE
{
BOOLEAN SystemSuspendSupported;
BOOLEAN SystemHibernateSupported;
BOOLEAN ResumeTimerSupportsSuspend;
BOOLEAN ResumeTimerSupportsHibernate;
BOOLEAN LidSupported;
BOOLEAN TurboSettingSupported;
BOOLEAN TurboMode;
BOOLEAN SystemAcOrDc;
BOOLEAN PowerDownDisabled;
LARGE_INTEGER SpindownDrives;
} SYSTEM_POWER_INFORMATION_NATIVE, *PSYSTEM_POWER_INFORMATION_NATIVE;
// Class 43
typedef struct _SYSTEM_LEGACY_DRIVER_INFORMATION
{
PNP_VETO_TYPE VetoType;
UNICODE_STRING VetoDriver;
// CHAR Buffer[0];
} SYSTEM_LEGACY_DRIVER_INFORMATION, *PSYSTEM_LEGACY_DRIVER_INFORMATION;
// Class 44
//typedef struct _TIME_ZONE_INFORMATION RTL_TIME_ZONE_INFORMATION;
// Class 45
typedef struct _SYSTEM_LOOKASIDE_INFORMATION
{
USHORT CurrentDepth;
USHORT MaximumDepth;
ULONG TotalAllocates;
ULONG AllocateMisses;
ULONG TotalFrees;
ULONG FreeMisses;
ULONG Type;
ULONG Tag;
ULONG Size;
} SYSTEM_LOOKASIDE_INFORMATION, *PSYSTEM_LOOKASIDE_INFORMATION;
// Class 46
// Not a structure. Only a HANDLE for the SlipEvent;
// Class 47
// Not a structure. Only a ULONG for the SessionId;
// Class 48
// Not a structure. Only a ULONG for the SessionId;
// FIXME: Class 49
// Class 50
// Not a structure. Only a ULONG_PTR for the SystemRangeStart
// Class 51
typedef struct _SYSTEM_VERIFIER_INFORMATION
{
ULONG NextEntryOffset;
ULONG Level;
UNICODE_STRING DriverName;
ULONG RaiseIrqls;
ULONG AcquireSpinLocks;
ULONG SynchronizeExecutions;
ULONG AllocationsAttempted;
ULONG AllocationsSucceeded;
ULONG AllocationsSucceededSpecialPool;
ULONG AllocationsWithNoTag;
ULONG TrimRequests;
ULONG Trims;
ULONG AllocationsFailed;
ULONG AllocationsFailedDeliberately;
ULONG Loads;
ULONG Unloads;
ULONG UnTrackedPool;
ULONG CurrentPagedPoolAllocations;
ULONG CurrentNonPagedPoolAllocations;
ULONG PeakPagedPoolAllocations;
ULONG PeakNonPagedPoolAllocations;
ULONG PagedPoolUsageInBytes;
ULONG NonPagedPoolUsageInBytes;
ULONG PeakPagedPoolUsageInBytes;
ULONG PeakNonPagedPoolUsageInBytes;
} SYSTEM_VERIFIER_INFORMATION, *PSYSTEM_VERIFIER_INFORMATION;
// FIXME: Class 52
// Class 53
typedef struct _SYSTEM_SESSION_PROCESS_INFORMATION
{
ULONG SessionId;
ULONG SizeOfBuf;
PVOID Buffer; // Same format as in SystemProcessInformation
} SYSTEM_SESSION_PROCESS_INFORMATION, *PSYSTEM_SESSION_PROCESS_INFORMATION;
// FIXME: Class 54-97
//
// Hotpatch flags
//
#define RTL_HOTPATCH_SUPPORTED_FLAG 0x01
#define RTL_HOTPATCH_SWAP_OBJECT_NAMES 0x08 << 24
#define RTL_HOTPATCH_SYNC_RENAME_FILES 0x10 << 24
#define RTL_HOTPATCH_PATCH_USER_MODE 0x20 << 24
#define RTL_HOTPATCH_REMAP_SYSTEM_DLL 0x40 << 24
#define RTL_HOTPATCH_PATCH_KERNEL_MODE 0x80 << 24
// Class 69
typedef struct _SYSTEM_HOTPATCH_CODE_INFORMATION
{
ULONG Flags;
ULONG InfoSize;
union
{
struct
{
ULONG Foo;
} CodeInfo;
struct
{
USHORT NameOffset;
USHORT NameLength;
} KernelInfo;
struct
{
USHORT NameOffset;
USHORT NameLength;
USHORT TargetNameOffset;
USHORT TargetNameLength;
UCHAR PatchingFinished;
} UserModeInfo;
struct
{
USHORT NameOffset;
USHORT NameLength;
USHORT TargetNameOffset;
USHORT TargetNameLength;
UCHAR PatchingFinished;
NTSTATUS ReturnCode;
HANDLE TargetProcess;
} InjectionInfo;
struct
{
HANDLE FileHandle1;
PIO_STATUS_BLOCK IoStatusBlock1;
PVOID RenameInformation1;
PVOID RenameInformationLength1;
HANDLE FileHandle2;
PIO_STATUS_BLOCK IoStatusBlock2;
PVOID RenameInformation2;
PVOID RenameInformationLength2;
} RenameInfo;
struct
{
HANDLE ParentDirectory;
HANDLE ObjectHandle1;
HANDLE ObjectHandle2;
} AtomicSwap;
};
} SYSTEM_HOTPATCH_CODE_INFORMATION, *PSYSTEM_HOTPATCH_CODE_INFORMATION;
//
// Class 75
//
#ifdef NTOS_MODE_USER
typedef struct _SYSTEM_FIRMWARE_TABLE_HANDLER
{
ULONG ProviderSignature;
BOOLEAN Register;
PFNFTH FirmwareTableHandler;
PVOID DriverObject;
} SYSTEM_FIRMWARE_TABLE_HANDLER, *PSYSTEM_FIRMWARE_TABLE_HANDLER;
//
// Class 76
//
typedef struct _SYSTEM_FIRMWARE_TABLE_INFORMATION
{
ULONG ProviderSignature;
SYSTEM_FIRMWARE_TABLE_ACTION Action;
ULONG TableID;
ULONG TableBufferLength;
UCHAR TableBuffer[1];
} SYSTEM_FIRMWARE_TABLE_INFORMATION, *PSYSTEM_FIRMWARE_TABLE_INFORMATION;
//
// Class 81
//
typedef struct _SYSTEM_MEMORY_LIST_INFORMATION
{
SIZE_T ZeroPageCount;
SIZE_T FreePageCount;
SIZE_T ModifiedPageCount;
SIZE_T ModifiedNoWritePageCount;
SIZE_T BadPageCount;
SIZE_T PageCountByPriority[8];
SIZE_T RepurposedPagesByPriority[8];
} SYSTEM_MEMORY_LIST_INFORMATION, *PSYSTEM_MEMORY_LIST_INFORMATION;
#endif
#endif
|
Shm13/IFMO_MOSA_Labs_2017
|
lab1/ndk/extypes.h
|
C
|
gpl-3.0
| 37,901 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head><title>Replica Set Configuration — MongoDB Manual 2.4.3</title><link rel="shortcut icon" href="http://media.mongodb.org/favicon.ico" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="index" />
<meta name="release" content="2.4.3"/>
<meta name="DC.Source" content="https://github.com/mongodb/docs/blob/master/source/reference/replica-configuration.txt"/>
<link rel="canonical" href="http://docs.mongodb.org/manual/reference/replica-configuration" />
<link rel="stylesheet" href="../_static/mongodb-docs.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '2.4',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: false,
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="search" type="application/opensearchdescription+xml" href="http://docs.mongodb.org/osd.xml" title="MongoDB Help"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="top" title="MongoDB Manual" href="../index.html" />
<link rel="up" title="Replication" href="../replication.html" />
<link rel="next" title="Replica Set Commands" href="replica-commands.html" />
<link rel="prev" title="Reconfigure a Replica Set with Unavailable Members" href="../tutorial/reconfigure-replica-set-with-unavailable-members.html" />
<script>
(function() {
var cx = '017213726194841070573:WMX6838984';
var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script></head>
<body>
<div id="header-db" class="spread">
<div class="split">
<div id="logo">
<div><a href="http://www.mongodb.org/"><img class="logo" src="http://media.mongodb.org/logo-mongodb.png" alt="MongoDB Logo"/></a></div>
</div>
</div>
</div>
<div class="document">
<div class="documentwrapper"><div class="bodywrapper">
<div class="body">
<div class="bc">
<ul>
<li><a href="../replication.html">Replication</a><span class="bcpoint"> > </span></li>
<li>Replica Set Configuration</li>
</ul>
</div>
<div id="cse-results">
<gcse:searchresults linkTarget="_top"></gcse:searchresults>
</div>
<div class="section" id="replica-set-configuration">
<h1>Replica Set Configuration<a class="headerlink" href="#replica-set-configuration" title="Permalink to this headline">¶</a></h1>
<div class="section" id="synopsis">
<h2>Synopsis<a class="headerlink" href="#synopsis" title="Permalink to this headline">¶</a></h2>
<p>This reference provides an overview of replica set
configuration options and settings.</p>
<p>Use <a class="reference internal" href="method/rs.conf.html#rs.conf" title="rs.conf()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.conf()</span></tt></a> in the <a class="reference internal" href="program/mongo.html#bin.mongo" title="mongo"><tt class="xref mongodb mongodb-program docutils literal"><span class="pre">mongo</span></tt></a> shell to retrieve this
configuration. Note that default values are not explicitly displayed.</p>
</div>
<div class="section" id="configuration-variables">
<span id="replica-set-configuration-variables"></span><h2>Configuration Variables<a class="headerlink" href="#configuration-variables" title="Permalink to this headline">¶</a></h2>
<dl class="data">
<dt id="local.system.replset._id">
<tt class="descclassname">local.system.replset.</tt><tt class="descname">_id</tt><a class="headerlink" href="#local.system.replset._id" title="Permalink to this definition">¶</a></dt>
<dd><p><strong>Type</strong>: string</p>
<p><strong>Value</strong>: <setname></p>
<p>An <tt class="docutils literal"><span class="pre">_id</span></tt> field holding the name of the replica set. This reflects
the set name configured with <a class="reference internal" href="configuration-options.html#replSet" title="replSet"><tt class="xref mongodb mongodb-setting docutils literal"><span class="pre">replSet</span></tt></a> or
<a class="reference internal" href="program/mongod.html#cmdoption-mongod--replSet"><em class="xref std std-option">mongod --replSet</em></a>.</p>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members">
<tt class="descclassname">local.system.replset.</tt><tt class="descname">members</tt><a class="headerlink" href="#local.system.replset.members" title="Permalink to this definition">¶</a></dt>
<dd><p><strong>Type</strong>: array</p>
<p>Contains an array holding an embedded <a class="reference internal" href="glossary.html#term-document"><em class="xref std std-term">document</em></a> for each
member of the replica set. The <tt class="docutils literal"><span class="pre">members</span></tt> document contains a
number of fields that describe the configuration of each member of
the replica set.</p>
<p>The <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">members</span></tt> field in the replica set
configuration document is a zero-indexed array.</p>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n]._id">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">_id</tt><a class="headerlink" href="#local.system.replset.members[n]._id" title="Permalink to this definition">¶</a></dt>
<dd><p><strong>Type</strong>: ordinal</p>
<p>Provides the zero-indexed identifier of every member in the replica
set.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>When updating the replica configuration object, address all members
of the set using the index value in the array. The array index
begins with <tt class="docutils literal"><span class="pre">0</span></tt>. Do not confuse this index value with the value
of the <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">_id</span></tt> field in each document in the
<tt class="xref mongodb mongodb-data docutils literal"><span class="pre">members</span></tt> array.</p>
<p class="last">The <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">_id</span></tt> rarely corresponds to the array
index.</p>
</div>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n].host">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">host</tt><a class="headerlink" href="#local.system.replset.members[n].host" title="Permalink to this definition">¶</a></dt>
<dd><p><strong>Type</strong>: <hostname><:port></p>
<p>Identifies the host name of the set member with a hostname and port
number. This name must be resolvable for every host in the replica
set.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last"><tt class="xref mongodb mongodb-data docutils literal"><span class="pre">host</span></tt> cannot hold a value that resolves to
<tt class="docutils literal"><span class="pre">localhost</span></tt> or the local interface unless <em>all</em> members of the
set are on hosts that resolve to localhost.</p>
</div>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n].arbiterOnly">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">arbiterOnly</tt><a class="headerlink" href="#local.system.replset.members[n].arbiterOnly" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: boolean</p>
<p><strong>Default</strong>: false</p>
<p>Identifies an arbiter. For arbiters, this value is <tt class="docutils literal"><span class="pre">true</span></tt>, and
is automatically configured by <a class="reference internal" href="method/rs.addArb.html#rs.addArb" title="rs.addArb()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.addArb()</span></tt></a>”.</p>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n].buildIndexes">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">buildIndexes</tt><a class="headerlink" href="#local.system.replset.members[n].buildIndexes" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: boolean</p>
<p><strong>Default</strong>: true</p>
<p>Determines whether the <a class="reference internal" href="program/mongod.html#bin.mongod" title="mongod"><tt class="xref mongodb mongodb-program docutils literal"><span class="pre">mongod</span></tt></a> builds <a class="reference internal" href="glossary.html#term-index"><em class="xref std std-term">indexes</em></a> on this member. Do not set to <tt class="docutils literal"><span class="pre">false</span></tt> if a replica set
<em>can</em> become a primary, or if any clients ever issue queries against
this instance.</p>
<p>Omitting index creation, and thus this setting, may be useful,
<strong>if</strong>:</p>
<ul class="simple">
<li>You are only using this instance to perform backups using
<a class="reference internal" href="program/mongodump.html#bin.mongodump" title="mongodump"><tt class="xref mongodb mongodb-program docutils literal"><span class="pre">mongodump</span></tt></a>,</li>
<li>this instance will receive no queries, <em>and</em></li>
<li>index creation and maintenance overburdens the host
system.</li>
</ul>
<p>If set to <tt class="docutils literal"><span class="pre">false</span></tt>, secondaries configured with this option <em>do</em>
build indexes on the <tt class="docutils literal"><span class="pre">_id</span></tt> field, to facilitate operations
required for replication.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>You may only set this value when adding a member to a replica
set. You may not reconfigure a replica set to change the value
of the <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">buildIndexes</span></tt> field after adding the
member to the set.</p>
<p class="last">Other secondaries cannot replicate from
a members where <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">buildIndexes</span></tt> is false.</p>
</div>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n].hidden">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">hidden</tt><a class="headerlink" href="#local.system.replset.members[n].hidden" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: boolean</p>
<p><strong>Default</strong>: false</p>
<p>When this value is <tt class="docutils literal"><span class="pre">true</span></tt>, the replica set hides this instance,
and does not include the member in the output of
<a class="reference internal" href="method/db.isMaster.html#db.isMaster" title="db.isMaster()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">db.isMaster()</span></tt></a> or <a class="reference internal" href="command/isMaster.html#dbcmd.isMaster" title="isMaster"><tt class="xref mongodb mongodb-dbcommand docutils literal"><span class="pre">isMaster</span></tt></a>. This
prevents read operations (i.e. queries) from ever reaching this
host by way of secondary <a class="reference internal" href="glossary.html#term-read-preference"><em class="xref std std-term">read preference</em></a>.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">“<a class="reference internal" href="../core/replication.html#replica-set-hidden-members"><em>Hidden Replica Set Members</em></a>“</p>
</div>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n].priority">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">priority</tt><a class="headerlink" href="#local.system.replset.members[n].priority" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: Number, between 0 and 100.0 including decimals.</p>
<p><strong>Default</strong>: 1</p>
<p>Specify higher values to make a member <em>more</em> eligible to become
<a class="reference internal" href="glossary.html#term-primary"><em class="xref std std-term">primary</em></a>, and lower values to make the member <em>less</em> eligible
to become primary. Priorities are only used in comparison to each
other. Members of the set will veto election requests from members when
another eligible member has a higher priority
value. Changing the balance of priority in a replica set will trigger
an election.</p>
<p>A <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">priority</span></tt> of <tt class="docutils literal"><span class="pre">0</span></tt> makes it impossible for a
member to become primary.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">“<a class="reference internal" href="../core/replication.html#replica-set-node-priority"><em>Replica Set Member Priority</em></a>” and “<a class="reference internal" href="../core/replication.html#replica-set-elections"><em>Replica Set Elections</em></a>.”</p>
</div>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n].tags">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">tags</tt><a class="headerlink" href="#local.system.replset.members[n].tags" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: <a class="reference internal" href="glossary.html#term-document"><em class="xref std std-term">MongoDB Document</em></a></p>
<p><strong>Default</strong>: none</p>
<p>Used to represent arbitrary values for describing or tagging members
for the purposes of extending <a class="reference internal" href="glossary.html#term-write-concern"><em class="xref std std-term">write concern</em></a>
to allow configurable data center
awareness.</p>
<p>Use in conjunction with <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">getLastErrorModes</span></tt> and
<tt class="xref mongodb mongodb-data docutils literal"><span class="pre">getLastErrorDefaults</span></tt> and
<a class="reference internal" href="method/db.getLastError.html#db.getLastError" title="db.getLastError()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">db.getLastError()</span></tt></a>
(i.e. <a class="reference internal" href="command/getLastError.html#dbcmd.getLastError" title="getLastError"><tt class="xref mongodb mongodb-dbcommand docutils literal"><span class="pre">getLastError</span></tt></a>.)</p>
<p>For procedures on configuring tag sets, see
<a class="reference internal" href="../tutorial/configure-replica-set-tag-sets.html"><em>Configure Replica Set Tag Sets</em></a>.</p>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n].slaveDelay">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">slaveDelay</tt><a class="headerlink" href="#local.system.replset.members[n].slaveDelay" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: Integer. (seconds.)</p>
<p><strong>Default</strong>: 0</p>
<p>Describes the number of seconds “behind” the primary that this
replica set member should “lag.” Use this option to create
<a class="reference internal" href="../core/replication.html#replica-set-delayed-members"><em>delayed members</em></a>, that
maintain a copy of the data that reflects the state of the data set
at some amount of time in the past, specified in seconds. Typically such delayed members
help protect against human error, and provide some measure
of insurance against the unforeseen consequences of changes and
updates.</p>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.members[n].votes">
<tt class="descclassname">local.system.replset.members[n].</tt><tt class="descname">votes</tt><a class="headerlink" href="#local.system.replset.members[n].votes" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: Integer</p>
<p><strong>Default</strong>: 1</p>
<p>Controls the number of votes a server will cast in a <a class="reference internal" href="../core/replication.html#replica-set-elections"><em>replica set
election</em></a>. The number of votes each member
has can be any non-negative integer, but it is highly recommended
each member has 1 or 0 votes.</p>
<p>If you need more than 7 members in one replica set, use this setting to add additional
non-voting members with a <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">votes</span></tt> value of <tt class="docutils literal"><span class="pre">0</span></tt>.</p>
<p>For most deployments and most members, use the default value,
<tt class="docutils literal"><span class="pre">1</span></tt>, for <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">votes</span></tt>.</p>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.settings">
<tt class="descclassname">local.system.replset.</tt><tt class="descname">settings</tt><a class="headerlink" href="#local.system.replset.settings" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: <a class="reference internal" href="glossary.html#term-document"><em class="xref std std-term">MongoDB Document</em></a></p>
<p>The <tt class="docutils literal"><span class="pre">settings</span></tt> document configures options that apply to the whole
replica set.</p>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.settings.chainingAllowed">
<tt class="descclassname">local.system.replset.settings.</tt><tt class="descname">chainingAllowed</tt><a class="headerlink" href="#local.system.replset.settings.chainingAllowed" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: boolean</p>
<p><strong>Default</strong>: true</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.2.2.</span></p>
<p>When <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">chainingAllowed</span></tt> is
<tt class="docutils literal"><span class="pre">true</span></tt>, the replica set allows <a class="reference internal" href="glossary.html#term-secondary"><em class="xref std std-term">secondary</em></a> members to
replicate from other secondary members. When
<tt class="xref mongodb mongodb-data docutils literal"><span class="pre">chainingAllowed</span></tt> is
<tt class="docutils literal"><span class="pre">false</span></tt>, secondaries can replicate only from the <a class="reference internal" href="glossary.html#term-primary"><em class="xref std std-term">primary</em></a>.</p>
<p>When you run <a class="reference internal" href="method/rs.conf.html#rs.config" title="rs.config()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.config()</span></tt></a> to view a replica set’s
configuration, the
<tt class="xref mongodb mongodb-data docutils literal"><span class="pre">chainingAllowed</span></tt> field
appears only when set to <tt class="docutils literal"><span class="pre">false</span></tt>. If not set,
<tt class="xref mongodb mongodb-data docutils literal"><span class="pre">chainingAllowed</span></tt> is <tt class="docutils literal"><span class="pre">true</span></tt>.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="../tutorial/manage-chained-replication.html"><em>Manage Chained Replication</em></a></p>
</div>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.settings.getLastErrorDefaults">
<tt class="descclassname">local.system.replset.settings.</tt><tt class="descname">getLastErrorDefaults</tt><a class="headerlink" href="#local.system.replset.settings.getLastErrorDefaults" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: <a class="reference internal" href="glossary.html#term-document"><em class="xref std std-term">MongoDB Document</em></a></p>
<p>Specify arguments to the <a class="reference internal" href="command/getLastError.html#dbcmd.getLastError" title="getLastError"><tt class="xref mongodb mongodb-dbcommand docutils literal"><span class="pre">getLastError</span></tt></a> that
members of this replica set will use when no arguments to
<a class="reference internal" href="command/getLastError.html#dbcmd.getLastError" title="getLastError"><tt class="xref mongodb mongodb-dbcommand docutils literal"><span class="pre">getLastError</span></tt></a> has no arguments. If you specify <em>any</em>
arguments, <a class="reference internal" href="command/getLastError.html#dbcmd.getLastError" title="getLastError"><tt class="xref mongodb mongodb-dbcommand docutils literal"><span class="pre">getLastError</span></tt></a> , ignores these defaults.</p>
</dd></dl>
<dl class="data">
<dt id="local.system.replset.settings.getLastErrorModes">
<tt class="descclassname">local.system.replset.settings.</tt><tt class="descname">getLastErrorModes</tt><a class="headerlink" href="#local.system.replset.settings.getLastErrorModes" title="Permalink to this definition">¶</a></dt>
<dd><p><em>Optional</em>.</p>
<p><strong>Type</strong>: <a class="reference internal" href="glossary.html#term-document"><em class="xref std std-term">MongoDB Document</em></a></p>
<p>Defines the names and combination of
<tt class="xref mongodb mongodb-data docutils literal"><span class="pre">members</span></tt> for use by the application layer
to guarantee <a class="reference internal" href="glossary.html#term-write-concern"><em class="xref std std-term">write concern</em></a> to database using the
<a class="reference internal" href="command/getLastError.html#dbcmd.getLastError" title="getLastError"><tt class="xref mongodb mongodb-dbcommand docutils literal"><span class="pre">getLastError</span></tt></a> command to provide <a class="reference internal" href="glossary.html#term-data-center-awareness"><em class="xref std std-term">data-center
awareness</em></a>.</p>
</dd></dl>
</div>
<div class="section" id="example-document">
<span id="replica-set-configuration-document"></span><h2>Example Document<a class="headerlink" href="#example-document" title="Permalink to this headline">¶</a></h2>
<p>The following document provides a representation of a replica set
configuration document. Angle brackets (e.g. <tt class="docutils literal"><span class="pre"><</span></tt> and <tt class="docutils literal"><span class="pre">></span></tt>) enclose
all optional fields.</p>
<div class="highlight-javascript"><div class="highlight"><pre><span class="p">{</span>
<span class="nx">_id</span> <span class="o">:</span> <span class="o"><</span><span class="nx">setname</span><span class="o">></span><span class="p">,</span>
<span class="nx">version</span><span class="o">:</span> <span class="o"><</span><span class="kr">int</span><span class="o">></span><span class="p">,</span>
<span class="nx">members</span><span class="o">:</span> <span class="p">[</span>
<span class="p">{</span>
<span class="nx">_id</span> <span class="o">:</span> <span class="o"><</span><span class="nx">ordinal</span><span class="o">></span><span class="p">,</span>
<span class="nx">host</span> <span class="o">:</span> <span class="nx">hostname</span><span class="o"><:</span><span class="nx">port</span><span class="o">></span><span class="p">,</span>
<span class="o"><</span><span class="nx">arbiterOnly</span> <span class="o">:</span> <span class="o"><</span><span class="kr">boolean</span><span class="o">></span><span class="p">,</span><span class="o">></span>
<span class="o"><</span><span class="nx">buildIndexes</span> <span class="o">:</span> <span class="o"><</span><span class="kr">boolean</span><span class="o">></span><span class="p">,</span><span class="o">></span>
<span class="o"><</span><span class="nx">hidden</span> <span class="o">:</span> <span class="o"><</span><span class="kr">boolean</span><span class="o">></span><span class="p">,</span><span class="o">></span>
<span class="o"><</span><span class="nx">priority</span><span class="o">:</span> <span class="o"><</span><span class="nx">priority</span><span class="o">></span><span class="p">,</span><span class="o">></span>
<span class="o"><</span><span class="nx">tags</span><span class="o">:</span> <span class="p">{</span> <span class="o"><</span><span class="nb">document</span><span class="o">></span> <span class="p">},</span><span class="o">></span>
<span class="o"><</span><span class="nx">slaveDelay</span> <span class="o">:</span> <span class="o"><</span><span class="nx">number</span><span class="o">></span><span class="p">,</span><span class="o">></span>
<span class="o"><</span><span class="nx">votes</span> <span class="o">:</span> <span class="o"><</span><span class="nx">number</span><span class="o">>></span>
<span class="p">}</span>
<span class="p">,</span> <span class="p">...</span>
<span class="p">],</span>
<span class="o"><</span><span class="nx">settings</span><span class="o">:</span> <span class="p">{</span>
<span class="o"><</span><span class="nx">getLastErrorDefaults</span> <span class="o">:</span> <span class="o"><</span><span class="nx">lasterrdefaults</span><span class="o">></span><span class="p">,</span><span class="o">></span>
<span class="o"><</span><span class="nx">chainingAllowed</span> <span class="o">:</span> <span class="o"><</span><span class="kr">boolean</span><span class="o">></span><span class="p">,</span><span class="o">></span>
<span class="o"><</span><span class="nx">getLastErrorModes</span> <span class="o">:</span> <span class="o"><</span><span class="nx">modes</span><span class="o">>></span>
<span class="p">}</span><span class="o">></span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="example-reconfiguration-operations">
<span id="replica-set-reconfiguration-usage"></span><h2>Example Reconfiguration Operations<a class="headerlink" href="#example-reconfiguration-operations" title="Permalink to this headline">¶</a></h2>
<p>Most modifications of <a class="reference internal" href="glossary.html#term-replica-set"><em class="xref std std-term">replica set</em></a> configuration use the
<a class="reference internal" href="program/mongo.html#bin.mongo" title="mongo"><tt class="xref mongodb mongodb-program docutils literal"><span class="pre">mongo</span></tt></a> shell. Consider the following reconfiguration
operation:</p>
<div class="admonition-example admonition">
<p class="first admonition-title">Example</p>
<p>Given the following replica set configuration:</p>
<div class="highlight-javascript"><div class="highlight"><pre><span class="p">{</span>
<span class="s2">"_id"</span> <span class="o">:</span> <span class="s2">"rs0"</span><span class="p">,</span>
<span class="s2">"version"</span> <span class="o">:</span> <span class="mi">1</span><span class="p">,</span>
<span class="s2">"members"</span> <span class="o">:</span> <span class="p">[</span>
<span class="p">{</span>
<span class="s2">"_id"</span> <span class="o">:</span> <span class="mi">0</span><span class="p">,</span>
<span class="s2">"host"</span> <span class="o">:</span> <span class="s2">"mongodb0.example.net:27017"</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="s2">"_id"</span> <span class="o">:</span> <span class="mi">1</span><span class="p">,</span>
<span class="s2">"host"</span> <span class="o">:</span> <span class="s2">"mongodb1.example.net:27017"</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="s2">"_id"</span> <span class="o">:</span> <span class="mi">2</span><span class="p">,</span>
<span class="s2">"host"</span> <span class="o">:</span> <span class="s2">"mongodb2.example.net:27017"</span>
<span class="p">}</span>
<span class="p">]</span>
<span class="p">}</span>
</pre></div>
</div>
<p>And the following reconfiguration operation:</p>
<div class="highlight-javascript"><div class="highlight"><pre><span class="nx">cfg</span> <span class="o">=</span> <span class="nx">rs</span><span class="p">.</span><span class="nx">conf</span><span class="p">()</span>
<span class="nx">cfg</span><span class="p">.</span><span class="nx">members</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="nx">priority</span> <span class="o">=</span> <span class="mf">0.5</span>
<span class="nx">cfg</span><span class="p">.</span><span class="nx">members</span><span class="p">[</span><span class="mi">1</span><span class="p">].</span><span class="nx">priority</span> <span class="o">=</span> <span class="mi">2</span>
<span class="nx">cfg</span><span class="p">.</span><span class="nx">members</span><span class="p">[</span><span class="mi">2</span><span class="p">].</span><span class="nx">priority</span> <span class="o">=</span> <span class="mi">2</span>
<span class="nx">rs</span><span class="p">.</span><span class="nx">reconfig</span><span class="p">(</span><span class="nx">cfg</span><span class="p">)</span>
</pre></div>
</div>
<p>This operation begins by saving the current replica set
configuration to the local variable <tt class="docutils literal"><span class="pre">cfg</span></tt> using the
<a class="reference internal" href="method/rs.conf.html#rs.conf" title="rs.conf()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.conf()</span></tt></a> method. Then it adds priority values to the
<tt class="docutils literal"><span class="pre">cfg</span></tt> <a class="reference internal" href="glossary.html#term-document"><em class="xref std std-term">document</em></a> where for the first three sub-documents in
the <tt class="xref mongodb mongodb-data docutils literal"><span class="pre">members</span></tt> array. Finally, it calls the
<a class="reference internal" href="method/rs.reconfig.html#rs.reconfig" title="rs.reconfig()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.reconfig()</span></tt></a> method with the argument of <tt class="docutils literal"><span class="pre">cfg</span></tt> to
initialize this new configuration. The replica set configuration
after this operation will resemble the following:</p>
<div class="last highlight-javascript"><div class="highlight"><pre><span class="p">{</span>
<span class="s2">"_id"</span> <span class="o">:</span> <span class="s2">"rs0"</span><span class="p">,</span>
<span class="s2">"version"</span> <span class="o">:</span> <span class="mi">1</span><span class="p">,</span>
<span class="s2">"members"</span> <span class="o">:</span> <span class="p">[</span>
<span class="p">{</span>
<span class="s2">"_id"</span> <span class="o">:</span> <span class="mi">0</span><span class="p">,</span>
<span class="s2">"host"</span> <span class="o">:</span> <span class="s2">"mongodb0.example.net:27017"</span><span class="p">,</span>
<span class="s2">"priority"</span> <span class="o">:</span> <span class="mf">0.5</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="s2">"_id"</span> <span class="o">:</span> <span class="mi">1</span><span class="p">,</span>
<span class="s2">"host"</span> <span class="o">:</span> <span class="s2">"mongodb1.example.net:27017"</span><span class="p">,</span>
<span class="s2">"priority"</span> <span class="o">:</span> <span class="mi">2</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="s2">"_id"</span> <span class="o">:</span> <span class="mi">2</span><span class="p">,</span>
<span class="s2">"host"</span> <span class="o">:</span> <span class="s2">"mongodb2.example.net:27017"</span><span class="p">,</span>
<span class="s2">"priority"</span> <span class="o">:</span> <span class="mi">1</span>
<span class="p">}</span>
<span class="p">]</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<p>Using the “dot notation” demonstrated in the above example, you can
modify any existing setting or specify any of optional <a class="reference internal" href="#replica-set-configuration-variables"><em>replica
set configuration variables</em></a>. Until you run
<tt class="docutils literal"><span class="pre">rs.reconfig(cfg)</span></tt> at the shell, no changes will take effect. You
can issue <tt class="docutils literal"><span class="pre">cfg</span> <span class="pre">=</span> <span class="pre">rs.conf()</span></tt> at any time before using
<a class="reference internal" href="method/rs.reconfig.html#rs.reconfig" title="rs.reconfig()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.reconfig()</span></tt></a> to undo your changes and start from the current
configuration. If you issue <tt class="docutils literal"><span class="pre">cfg</span></tt> as an operation at any point, the
<a class="reference internal" href="program/mongo.html#bin.mongo" title="mongo"><tt class="xref mongodb mongodb-program docutils literal"><span class="pre">mongo</span></tt></a> shell at any point will output the complete
<a class="reference internal" href="glossary.html#term-document"><em class="xref std std-term">document</em></a> with modifications for your review.</p>
<p>The <a class="reference internal" href="method/rs.reconfig.html#rs.reconfig" title="rs.reconfig()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.reconfig()</span></tt></a> operation has a “force” option, to make it
possible to reconfigure a replica set if a majority of the replica set
is not visible, and there is no <a class="reference internal" href="glossary.html#term-primary"><em class="xref std std-term">primary</em></a> member of the set.
use the following form:</p>
<div class="highlight-javascript"><div class="highlight"><pre><span class="nx">rs</span><span class="p">.</span><span class="nx">reconfig</span><span class="p">(</span><span class="nx">cfg</span><span class="p">,</span> <span class="p">{</span> <span class="nx">force</span><span class="o">:</span> <span class="kc">true</span> <span class="p">}</span> <span class="p">)</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Forcing a <a class="reference internal" href="method/rs.reconfig.html#rs.reconfig" title="rs.reconfig()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.reconfig()</span></tt></a> can lead to <a class="reference internal" href="glossary.html#term-rollback"><em class="xref std std-term">rollback</em></a>
situations and other difficult to recover from situations. Exercise
caution when using this option.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="method/rs.reconfig.html#rs.reconfig" title="rs.reconfig()"><tt class="xref mongodb mongodb-method docutils literal"><span class="pre">rs.reconfig()</span></tt></a> shell method can force the current
primary to step down and triggers an election in some
situations. When the primary steps down, all clients will
disconnect. This is by design. Since this typically takes 10-20
seconds, attempt to make such changes during scheduled maintenance
periods.</p>
</div>
</div>
</div>
<div id="btnv">
<ul id="btnvl">
<li id="btnvpr"><a href="../tutorial/reconfigure-replica-set-with-unavailable-members.html" title="Previous Section: Reconfigure a Replica Set with Unavailable Members">< Reconfigure a Replica Set with Unavailable Members</a></li>
<li id="btnvup"><a href="../replication.html" title="Parent Section: Replication" >/\ Replication</a></li>
<li id="btnvnx"><a href="replica-commands.html" title="Next Section: Replica Set Commands">Replica Set Commands ></a></li>
</ul>
</div></div></div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3>
<a href="../index.html">MongoDB Manual</a> <span id="vn">2.4</span>
</h3>
<div class="site-contents"><a href="../contents.html">Contents</a></div>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../installation.html">Install MongoDB</a></li>
<li class="toctree-l1"><a class="reference internal" href="../administration.html">Administration</a></li>
<li class="toctree-l1"><a class="reference internal" href="../security.html">Security</a></li>
<li class="toctree-l1"><a class="reference internal" href="../crud.html">Core MongoDB Operations (CRUD)</a></li>
<li class="toctree-l1"><a class="reference internal" href="../data-modeling.html">Data Modeling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../aggregation.html">Aggregation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../indexes.html">Indexes</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../replication.html">Replication</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../core/replication.html">Replica Set Fundamental Concepts</a></li>
<li class="toctree-l2"><a class="reference internal" href="../core/replica-set-architectures.html">Replica Set Architectures and Deployment Patterns</a></li>
<li class="toctree-l2"><a class="reference internal" href="../applications/replication.html">Replica Set Considerations and Behaviors for Applications and Development</a></li>
<li class="toctree-l2"><a class="reference internal" href="../core/replication-internals.html">Replica Set Internals and Behaviors</a></li>
<li class="toctree-l2"><a class="reference internal" href="../core/master-slave.html">Master Slave Replication</a></li>
<li class="toctree-l2"><a class="reference internal" href="../administration/replica-sets.html">Replica Set Administration</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="">Replica Set Configuration</a><ul class="simple">
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="replica-commands.html">Replica Set Commands</a></li>
<li class="toctree-l2"><a class="reference internal" href="../release-notes/replica-set-features.html">Replica Set Features and Version Compatibility</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../sharding.html">Sharding</a></li>
<li class="toctree-l1"><a class="reference internal" href="../applications.html">Application Development</a></li>
<li class="toctree-l1"><a class="reference internal" href="../mongo.html">The <tt class="docutils literal"><span class="pre">mongo</span></tt> Shell</a></li>
<li class="toctree-l1"><a class="reference internal" href="../use-cases.html">Use Cases</a></li>
<li class="toctree-l1"><a class="reference internal" href="../faq.html">Frequently Asked Questions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../reference.html">Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../release-notes.html">Release Notes</a></li>
<li class="toctree-l1"><a class="reference internal" href="../about.html">About MongoDB Documentation</a></li>
</ul>
<div class="site-index"><a href="../genindex.html">Index</a></div>
<h3>Formats</h3>
<ul class="this-page-menu">
<li><a href="/manual/single/">MongoDB Manual, Single HTML Page</a></li>
<li><a href="http://docs.mongodb.org/master/MongoDB-Manual-master.pdf" rel="nofollow">MongoDB Manual, PDF Format</a></li>
<li><a href="http://docs.mongodb.org/master/MongoDB-Manual-master.epub" rel="nofollow">MongoDB Manual, ePub Format</a></li>
</ul>
<h3><a href="http://www.mongodb.org/about/">About MongoDB</a></h3>
<ul>
<li><a href="http://www.mongodb.org/about/introduction">Introduction</a></li>
<li><a href="http://www.mongodb.org/about/community">User Community</a></li>
<li><a href="http://mongodb.org/about/community/masters">MongoDB Masters</a></li>
<li><a href="http://planet.mongodb.org">Planet MongoDB</a></li>
</ul>
<h3><a href="http://docs.mongodb.org/ecosystem/">MongoDB Ecosystem</a></h3>
<ul>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/">Drivers and Client libraries</a>
<ul>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/c">C</a> (<a href="http://api.mongodb.org/c/current/">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/cpp">C++</a> (<a href="http://api.mongodb.org/cplusplus/current/">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/csharp">C#</a> (<a href="http://api.mongodb.org/csharp/current/">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/erlang">Erlang</a> (<a href="http://api.mongodb.org/erlang">docs</a>)</li>
<li><a href="http://hackage.haskell.org/package/mongoDB">Haskell</a> (<a href="http://api.mongodb.org/haskell">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/java">Java</a> (<a href="http://api.mongodb.org/java/current">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/javascript">JavaScript</a> (<a href="http://api.mongodb.org/js/current">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/perl">Perl</a> (<a href="http://api.mongodb.org/perl/current/">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/php">PHP</a> (<a href="http://php.net/mongo/">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/python">Python</a> (<a href="http://api.mongodb.org/python/current">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/ruby">Ruby</a> (<a href="http://api.mongodb.org/ruby/current">docs</a>)</li>
<li><a href="http://docs.mongodb.org/ecosystem/drivers/scala">Scala</a> (<a href="http://api.mongodb.org/scala/casbah/current/">docs</a>)</li>
</ul>
</li>
<li><a href="http://docs.mongodb.org/ecosystem/tools/">Tools and Integration</a></li>
<li><a href="http://docs.mongodb.org/ecosystem/platforms/">Platform Integration</a></li>
</ul><h3>MongoDB Resources</h3>
<ul>
<li><a href="http://www.mongodb.org/downloads">Downloads</a></li>
<li><a href="http://www.10gen.com/events">MongoDB Events</a></li>
<li><a href="http://www.10gen.com/presentations">Slides and Video</a></li>
<li><a href="http://www.10gen.com/products/mms/">MongoDB Monitoring Service</a> (<a href="http://mms.10gen.com/help/">docs</a>)</li>
</ul>
</div>
</div>
<div class="clearer"></div>
</div><div id="top-right">
<div class="user-right">
<ul id="header-menu-bar" class="ajs-menu-bar">
<li class="normal"><a target="_blank" href="http://groups.google.com/group/mongodb-user">Forums</a></li>
<li class="normal"><a target="_blank" href="http://blog.mongodb.org/">Blog</a></li>
<li class="normal"><a href="http://www.mongodb.org/downloads">Download</a></li>
<li class="normal"><a href="http://docs.mongodb.org/ecosystem/drivers/">Drivers</a></li>
<li class="normal"><a href="http://www.10gen.com/events">Events</a></li>
<li class="normal last"><a class="last" href="http://docs.mongodb.org/manual/meta/translation">Translations</a></li>
</ul>
</div>
</div>
<div class="search-db"><gcse:searchbox></gcse:searchbox></div>
<div id="etp">
<ul>
<li><a href="https://github.com/mongodb/docs/blob/master/source/reference/replica-configuration.txt" target="_blank" title="Edit reference/replica-configuration.txt on GitHub">Edit this Page</a></li>
<li><a href="http://github.com/mongodb/docs" target="_blank" title="Fork the documentation on GitHub and contribute.">GitHub</a></li>
<li><a id="jirafeedback" href="https://jira.mongodb.org/secure/CreateIssueDetails!init.jspa?pid=10380&issuetype=4&priority=4&summary=Comment+on%3a+%22reference/replica-configuration%2Etxt%22" target="_blank" title="Report a problem with reference/replica-configuration.txt on Jira">Report a Problem</a></li>
</ul>
</div>
<div class="footer">
<p>
© <a href="">Copyright</a> 2011-2013, 10gen, Inc.
MongoDB®, Mongo®, and the leaf logo are registered trademarks of <a href="http://www.10gen.com/">10gen, Inc.</a>
</p>
</div><script type="text/javascript">
var _gaq = _gaq || [];
var pluginUrl = (('https:' == document.location.protocol) ? 'https://ssl.' : 'http://www.') + 'google-analytics.com/plugins/ga/inpage_linkid.js';
_gaq.push(['_require', 'inpage_linkid', pluginUrl]);
_gaq.push(['_setAccount', 'UA-7301842-8']);
_gaq.push(['_setDomainName', 'docs.mongodb.org']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript">var _kiq = _kiq || [];</script>
<script type="text/javascript">
(function(){
setTimeout(function(){ var d = document, f = d.getElementsByTagName('script')[0], s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = '//s3.amazonaws.com/ki.js/49119/a7n.js'; f.parentNode.insertBefore(s, f); }, 1);
})();
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-7301842-14', 'mongodb.org');
ga('send', 'pageview');
</script>
<script type="text/javascript">
document.write(unescape("%3Cscript src='" + document.location.protocol + "//munchkin.marketo.net/munchkin.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script>try { mktoMunchkin("017-HGS-593"); } catch(e) {}</script><script type="text/javascript">
jQuery.ajax({
url: "https://jira.mongodb.org/s/en_UScn8g8x/782/6/1.2.5/_/download/batch/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector-embededjs/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector-embededjs.js?collectorId=298ba4e7",
type: "get",
cache: true,
dataType: "script"
});
window.ATL_JQ_PAGE_PROPS = {
"triggerFunction": function(showCollectorDialog) {
jQuery("#jirafeedback").click(function(e) {e.preventDefault();showCollectorDialog();});},
fieldValues: {component: 'mongodb-manual', summary: 'Comment on: "manual/reference/replica-configuration.txt"'},
environment: {'repo': 'docs','source': 'reference/replica-configuration'}
};
</script><script type="text/javascript">
var versions = [{'t': '2.4 (current)', 'v': 'v2.4'}, {'t': '2.2', 'v': 'v2.2'}]
var pagename = 'reference/replica-configuration'
var stable = 'v2.4'
function vfnav() {
if ( pagename=='index' ) {
pn = ''
}
else {
pn = pagename
}
v = $(this).children("option:selected").attr('value')
if ( (v==0) || (v==stable) ) {
uri = '/manual/' + pn
}
else {
uri = '/' + v + '/' + pn
}
window.location.href= uri;
}
$(document).ready(function(){
$("#vn").html(function(){
s=$("<select/>");
o='<option/>';
$.each(versions,function(index, version) {
if ( version.v==stable ) {
dv=true;
}
$(o,{value:version.v,text: version.t}).appendTo(s);
});
if ( dv==false ) {
$(o, {value:0,text:'(stable)'}).appendTo(s);
}
return(s);
});
$("#vn select").bind('change', vfnav);
$('#vn select').val('v2.4');
});
</script>
</body>
</html>
|
P3PO/the-phpjs-local-docs-collection
|
mongodb/reference/replica-configuration.html
|
HTML
|
gpl-3.0
| 49,975 |
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../libnetdata.h"
#define BUFFER_OVERFLOW_EOF "EOF"
static inline void buffer_overflow_init(BUFFER *b)
{
b->buffer[b->size] = '\0';
strcpy(&b->buffer[b->size + 1], BUFFER_OVERFLOW_EOF);
}
#ifdef NETDATA_INTERNAL_CHECKS
#define buffer_overflow_check(b) _buffer_overflow_check(b, __FILE__, __FUNCTION__, __LINE__)
#else
#define buffer_overflow_check(b)
#endif
static inline void _buffer_overflow_check(BUFFER *b, const char *file, const char *function, const unsigned long line)
{
if(b->len > b->size) {
error("BUFFER: length %zu is above size %zu, at line %lu, at function %s() of file '%s'.", b->len, b->size, line, function, file);
b->len = b->size;
}
if(b->buffer[b->size] != '\0' || strcmp(&b->buffer[b->size + 1], BUFFER_OVERFLOW_EOF) != 0) {
error("BUFFER: detected overflow at line %lu, at function %s() of file '%s'.", line, function, file);
buffer_overflow_init(b);
}
}
void buffer_reset(BUFFER *wb)
{
buffer_flush(wb);
wb->contenttype = CT_TEXT_PLAIN;
wb->options = 0;
wb->date = 0;
wb->expires = 0;
buffer_overflow_check(wb);
}
const char *buffer_tostring(BUFFER *wb)
{
buffer_need_bytes(wb, 1);
wb->buffer[wb->len] = '\0';
buffer_overflow_check(wb);
return(wb->buffer);
}
void buffer_char_replace(BUFFER *wb, char from, char to)
{
char *s = wb->buffer, *end = &wb->buffer[wb->len];
while(s != end) {
if(*s == from) *s = to;
s++;
}
buffer_overflow_check(wb);
}
// This trick seems to give an 80% speed increase in 32bit systems
// print_calculated_number_llu_r() will just print the digits up to the
// point the remaining value fits in 32 bits, and then calls
// print_calculated_number_lu_r() to print the rest with 32 bit arithmetic.
inline char *print_number_lu_r(char *str, unsigned long uvalue) {
char *wstr = str;
// print each digit
do *wstr++ = (char)('0' + (uvalue % 10)); while(uvalue /= 10);
return wstr;
}
inline char *print_number_llu_r(char *str, unsigned long long uvalue) {
char *wstr = str;
// print each digit
do *wstr++ = (char)('0' + (uvalue % 10)); while((uvalue /= 10) && uvalue > (unsigned long long)0xffffffff);
if(uvalue) return print_number_lu_r(wstr, uvalue);
return wstr;
}
inline char *print_number_llu_r_smart(char *str, unsigned long long uvalue) {
switch (sizeof(void *)) {
case 4:
str = (uvalue > (unsigned long long) 0xffffffff) ? print_number_llu_r(str, uvalue) :
print_number_lu_r(str, uvalue);
break;
case 8:
do {
*str++ = (char) ('0' + (uvalue % 10));
} while (uvalue /= 10);
break;
default:
fatal("Netdata supports only 32-bit & 64-bit systems.");
}
return str;
}
void buffer_print_llu(BUFFER *wb, unsigned long long uvalue)
{
buffer_need_bytes(wb, 50);
char *str = &wb->buffer[wb->len];
char *wstr = str;
switch (sizeof(void *)) {
case 4:
wstr = (uvalue > (unsigned long long) 0xffffffff) ? print_number_llu_r(wstr, uvalue) :
print_number_lu_r(wstr, uvalue);
break;
case 8:
do {
*wstr++ = (char) ('0' + (uvalue % 10));
} while (uvalue /= 10);
break;
default:
fatal("Netdata supports only 32-bit & 64-bit systems.");
}
// terminate it
*wstr = '\0';
// reverse it
char *begin = str, *end = wstr - 1, aux;
while (end > begin) aux = *end, *end-- = *begin, *begin++ = aux;
// return the buffer length
wb->len += wstr - str;
}
void buffer_strcat(BUFFER *wb, const char *txt)
{
// buffer_sprintf(wb, "%s", txt);
if(unlikely(!txt || !*txt)) return;
buffer_need_bytes(wb, 1);
char *s = &wb->buffer[wb->len], *start, *end = &wb->buffer[wb->size];
size_t len = wb->len;
start = s;
while(*txt && s != end)
*s++ = *txt++;
len += s - start;
wb->len = len;
buffer_overflow_check(wb);
if(*txt) {
debug(D_WEB_BUFFER, "strcat(): increasing web_buffer at position %zu, size = %zu\n", wb->len, wb->size);
len = strlen(txt);
buffer_increase(wb, len);
buffer_strcat(wb, txt);
}
else {
// terminate the string
// without increasing the length
buffer_need_bytes(wb, (size_t)1);
wb->buffer[wb->len] = '\0';
}
}
void buffer_strcat_jsonescape(BUFFER *wb, const char *txt)
{
while(*txt) {
switch(*txt) {
case '\\':
buffer_need_bytes(wb, 2);
wb->buffer[wb->len++] = '\\';
wb->buffer[wb->len++] = '\\';
break;
case '"':
buffer_need_bytes(wb, 2);
wb->buffer[wb->len++] = '\\';
wb->buffer[wb->len++] = '"';
break;
default: {
buffer_need_bytes(wb, 1);
wb->buffer[wb->len++] = *txt;
}
}
txt++;
}
buffer_overflow_check(wb);
}
void buffer_strcat_htmlescape(BUFFER *wb, const char *txt)
{
while(*txt) {
switch(*txt) {
case '&': buffer_strcat(wb, "&"); break;
case '<': buffer_strcat(wb, "<"); break;
case '>': buffer_strcat(wb, ">"); break;
case '"': buffer_strcat(wb, """); break;
case '/': buffer_strcat(wb, "/"); break;
case '\'': buffer_strcat(wb, "'"); break;
default: {
buffer_need_bytes(wb, 1);
wb->buffer[wb->len++] = *txt;
}
}
txt++;
}
buffer_overflow_check(wb);
}
void buffer_snprintf(BUFFER *wb, size_t len, const char *fmt, ...)
{
if(unlikely(!fmt || !*fmt)) return;
buffer_need_bytes(wb, len + 1);
va_list args;
va_start(args, fmt);
wb->len += vsnprintfz(&wb->buffer[wb->len], len, fmt, args);
va_end(args);
buffer_overflow_check(wb);
// the buffer is \0 terminated by vsnprintfz
}
void buffer_vsprintf(BUFFER *wb, const char *fmt, va_list args)
{
if(unlikely(!fmt || !*fmt)) return;
buffer_need_bytes(wb, 2);
size_t len = wb->size - wb->len - 1;
wb->len += vsnprintfz(&wb->buffer[wb->len], len, fmt, args);
buffer_overflow_check(wb);
// the buffer is \0 terminated by vsnprintfz
}
void buffer_sprintf(BUFFER *wb, const char *fmt, ...)
{
if(unlikely(!fmt || !*fmt)) return;
va_list args;
size_t wrote = 0, need = 2, multiplier = 0, len;
do {
need += wrote + multiplier * WEB_DATA_LENGTH_INCREASE_STEP;
multiplier++;
debug(D_WEB_BUFFER, "web_buffer_sprintf(): increasing web_buffer at position %zu, size = %zu, by %zu bytes (wrote = %zu)\n", wb->len, wb->size, need, wrote);
buffer_need_bytes(wb, need);
len = wb->size - wb->len - 1;
va_start(args, fmt);
wrote = (size_t) vsnprintfz(&wb->buffer[wb->len], len, fmt, args);
va_end(args);
} while(wrote >= len);
wb->len += wrote;
// the buffer is \0 terminated by vsnprintf
}
void buffer_rrd_value(BUFFER *wb, calculated_number value)
{
buffer_need_bytes(wb, 50);
if(isnan(value) || isinf(value)) {
buffer_strcat(wb, "null");
return;
}
else
wb->len += print_calculated_number(&wb->buffer[wb->len], value);
// terminate it
buffer_need_bytes(wb, 1);
wb->buffer[wb->len] = '\0';
buffer_overflow_check(wb);
}
// generate a javascript date, the fastest possible way...
void buffer_jsdate(BUFFER *wb, int year, int month, int day, int hours, int minutes, int seconds)
{
// 10 20 30 = 35
// 01234567890123456789012345678901234
// Date(2014,04,01,03,28,20)
buffer_need_bytes(wb, 30);
char *b = &wb->buffer[wb->len], *p;
unsigned int *q = (unsigned int *)b;
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
*q++ = 0x65746144; // "Date" backwards.
#else
*q++ = 0x44617465; // "Date"
#endif
p = (char *)q;
*p++ = '(';
*p++ = '0' + year / 1000; year %= 1000;
*p++ = '0' + year / 100; year %= 100;
*p++ = '0' + year / 10;
*p++ = '0' + year % 10;
*p++ = ',';
*p = '0' + month / 10; if (*p != '0') p++;
*p++ = '0' + month % 10;
*p++ = ',';
*p = '0' + day / 10; if (*p != '0') p++;
*p++ = '0' + day % 10;
*p++ = ',';
*p = '0' + hours / 10; if (*p != '0') p++;
*p++ = '0' + hours % 10;
*p++ = ',';
*p = '0' + minutes / 10; if (*p != '0') p++;
*p++ = '0' + minutes % 10;
*p++ = ',';
*p = '0' + seconds / 10; if (*p != '0') p++;
*p++ = '0' + seconds % 10;
unsigned short *r = (unsigned short *)p;
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
*r++ = 0x0029; // ")\0" backwards.
#else
*r++ = 0x2900; // ")\0"
#endif
wb->len += (size_t)((char *)r - b - 1);
// terminate it
wb->buffer[wb->len] = '\0';
buffer_overflow_check(wb);
}
// generate a date, the fastest possible way...
void buffer_date(BUFFER *wb, int year, int month, int day, int hours, int minutes, int seconds)
{
// 10 20 30 = 35
// 01234567890123456789012345678901234
// 2014-04-01 03:28:20
buffer_need_bytes(wb, 36);
char *b = &wb->buffer[wb->len];
char *p = b;
*p++ = '0' + year / 1000; year %= 1000;
*p++ = '0' + year / 100; year %= 100;
*p++ = '0' + year / 10;
*p++ = '0' + year % 10;
*p++ = '-';
*p++ = '0' + month / 10;
*p++ = '0' + month % 10;
*p++ = '-';
*p++ = '0' + day / 10;
*p++ = '0' + day % 10;
*p++ = ' ';
*p++ = '0' + hours / 10;
*p++ = '0' + hours % 10;
*p++ = ':';
*p++ = '0' + minutes / 10;
*p++ = '0' + minutes % 10;
*p++ = ':';
*p++ = '0' + seconds / 10;
*p++ = '0' + seconds % 10;
*p = '\0';
wb->len += (size_t)(p - b);
// terminate it
wb->buffer[wb->len] = '\0';
buffer_overflow_check(wb);
}
BUFFER *buffer_create(size_t size)
{
BUFFER *b;
debug(D_WEB_BUFFER, "Creating new web buffer of size %zu.", size);
b = callocz(1, sizeof(BUFFER));
b->buffer = mallocz(size + sizeof(BUFFER_OVERFLOW_EOF) + 2);
b->buffer[0] = '\0';
b->size = size;
b->contenttype = CT_TEXT_PLAIN;
buffer_overflow_init(b);
buffer_overflow_check(b);
return(b);
}
void buffer_free(BUFFER *b) {
if(unlikely(!b)) return;
buffer_overflow_check(b);
debug(D_WEB_BUFFER, "Freeing web buffer of size %zu.", b->size);
freez(b->buffer);
freez(b);
}
void buffer_increase(BUFFER *b, size_t free_size_required) {
buffer_overflow_check(b);
size_t left = b->size - b->len;
if(left >= free_size_required) return;
size_t increase = free_size_required - left;
if(increase < WEB_DATA_LENGTH_INCREASE_STEP) increase = WEB_DATA_LENGTH_INCREASE_STEP;
debug(D_WEB_BUFFER, "Increasing data buffer from size %zu to %zu.", b->size, b->size + increase);
b->buffer = reallocz(b->buffer, b->size + increase + sizeof(BUFFER_OVERFLOW_EOF) + 2);
b->size += increase;
buffer_overflow_init(b);
buffer_overflow_check(b);
}
|
vlvkobal/netdata
|
libnetdata/buffer/buffer.c
|
C
|
gpl-3.0
| 11,254 |
---------------------------------------------
-- Sweep
--
-- Description: Damages enemies in an area of effect. Additional effect: Stun
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: 10' radial
-- Notes:
---------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------
function OnMobSkillCheck(target,mob,skill)
return 0;
end;
function OnMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2.0;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW);
local typeEffect = EFFECT_STUN;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4);
target:delHP(dmg);
return dmg;
end;
|
Gwynthell/FFDB
|
scripts/globals/mobskills/Sweep.lua
|
Lua
|
gpl-3.0
| 951 |
<?php
// Tradução para Loja Virtual Opencart V.1.5.6.1
// Tradução realizada pelo Departamento de Desenvolvimento Web
// Empresa: TecSecret
// Site: www.tecsecret.com.br
// Gerente responsável: Nelsir Luterek
// E-mail: [email protected]
// Central de atendimento: http://helpdesk.tecsecret.com.br
// Heading
$_['heading_title'] = 'Informações';
// Text
$_['text_success'] = 'Sucesso: Você modificou informação!';
$_['text_default'] = 'Default';
// Column
$_['column_title'] = 'Informação Título';
$_['column_sort_order'] = 'Ordem';
$_['column_action'] = 'Ação';
// Entry
$_['entry_title'] = 'Informação Título:';
$_['entry_description'] = 'Descrição:';
$_['entry_store'] = 'Lojas:';
$_['entry_keyword'] = 'SEO Keyword:<br /><span class="help">Do not use spaces instead replace spaces with - and make sure the keyword is globally unique.</span>';
$_['entry_bottom'] = 'Bottom:<br/><span class="help">Display in the bottom footer.</span>';
$_['entry_status'] = 'Status:';
$_['entry_sort_order'] = 'Sort Order:';
$_['entry_layout'] = 'Layout Override:';
// Error
$_['error_warning'] = 'Warning: Please check the form carefully for errors!';
$_['error_permission'] = 'Warning: You do not have permission to modify information!';
$_['error_title'] = 'Information Title must be between 3 and 64 characters!';
$_['error_description'] = 'Description must be more than 3 characters!';
$_['error_account'] = 'Warning: This information page cannot be deleted as it is currently assigned as the store account terms!';
$_['error_checkout'] = 'Warning: This information page cannot be deleted as it is currently assigned as the store checkout terms!';
$_['error_affiliate'] = 'Warning: This information page cannot be deleted as it is currently assigned as the store affiliate terms!';
$_['error_store'] = 'Warning: This information page cannot be deleted as its currently used by %s stores!';
?>
|
robsontissiano/opencart-store
|
admin/language/portuguese-br/catalog/information.php
|
PHP
|
gpl-3.0
| 2,001 |
using EloBuddy;
using LeagueSharp.Common;
namespace myKatarina.Manager.Events.Games.Mode
{
using Spells;
using myCommon;
using System.Linq;
using LeagueSharp.Common;
internal class LastHit : Logic
{
internal static void Init()
{
if (SpellManager.isCastingUlt)
{
return;
}
if (Menu.GetBool("LastHitQ") && Q.IsReady())
{
var qMinion =
MinionManager.GetMinions(Me.Position, Q.Range)
.FirstOrDefault(x => x.Health < DamageCalculate.GetQDamage(x));
if (qMinion != null && qMinion.IsValidTarget(Q.Range))
{
Q.CastOnUnit(qMinion, true);
}
}
}
}
}
|
tk8226/YamiPortAIO-v2
|
Core/AIO Ports/mySeries/myKatarina/Manager/Events/Games/Mode/LastHit.cs
|
C#
|
gpl-3.0
| 813 |
-- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6376; -- You cannot obtain the item <item>. Come back after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6378; -- You cannot obtain the #. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6379; -- Obtained: <item>.
GIL_OBTAINED = 6380; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6382; -- Obtained key item: <keyitem>.
ITEMS_OBTAINED = 6388; -- You obtain
NOTHING_OUT_OF_ORDINARY = 6393; -- There is nothing out of the ordinary here.
-- Maat dialog
YOU_DECIDED_TO_SHOW_UP = 7698; -- So, you decided to show up.
LOOKS_LIKE_YOU_WERENT_READY = 7699; -- Looks like you weren't ready for me, were you?
YOUVE_COME_A_LONG_WAY = 7700; -- Hm. That was a mighty fine display of skill there, Player Name. You've come a long way...
TEACH_YOU_TO_RESPECT_ELDERS = 7701; -- I'll teach you to respect your elders!
TAKE_THAT_YOU_WHIPPERSNAPPER = 7702; -- Take that, you whippersnapper!
THAT_LL_HURT_IN_THE_MORNING = 7704; -- Ungh... That'll hurt in the morning...
|
maikuru23/darkstar
|
scripts/zones/Horlais_Peak/TextIDs.lua
|
Lua
|
gpl-3.0
| 1,126 |
/*
* Copyright (c) 2007-2021 Holger de Carne and contributors, All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.carne.filescanner.swt.export;
import java.nio.file.Path;
import de.carne.filescanner.engine.transfer.FileScannerResultExportHandler;
/**
* This class holds the export options selected during an {@linkplain ExportDialog} invocation.
*/
public final class ExportOptions {
private final FileScannerResultExportHandler exportHandler;
private final Path path;
private final boolean overwrite;
ExportOptions(FileScannerResultExportHandler exportHandler, Path path, boolean overwrite) {
this.exportHandler = exportHandler;
this.path = path;
this.overwrite = overwrite;
}
/**
* Gets the selected {@linkplain FileScannerResultExportHandler}.
*
* @return the selected {@linkplain FileScannerResultExportHandler}.
*/
public FileScannerResultExportHandler exportHandler() {
return this.exportHandler;
}
/**
* Gets the selected export file path.
*
* @return the selected export file path.
*/
public Path path() {
return this.path;
}
/**
* Gets the overwrite confirmation.
*
* @return the overwrite confirmation.
*/
public boolean overwrite() {
return this.overwrite;
}
}
|
hdecarne/de.carne.filescanner
|
filescanner-gtk-linux-x86_64/shared-src/main/java/de/carne/filescanner/swt/export/ExportOptions.java
|
Java
|
gpl-3.0
| 1,868 |
#!/usr/bin/perl
package Koha::Reporting::Report::Filter::LoanedAmountEnd;
use Modern::Perl;
use Moose;
use Data::Dumper;
extends 'Koha::Reporting::Report::Filter::Abstract';
sub BUILD {
my $self = shift;
$self->setName('loaned_amount_end');
$self->setDescription('Loaned amount (to)');
$self->setType('text');
$self->setDimension('fact');
$self->setField('loaned_amount');
$self->setRule('lte');
$self->setFilterType('having');
$self->setUseFullColumn(0);
}
1;
|
KohaSuomi/kohasuomi
|
Koha/Reporting/Report/Filter/LoanedAmountEnd.pm
|
Perl
|
gpl-3.0
| 501 |
<div class="picker wordpicker">
<p class="picked">{{picked}}</p>
<div data-compile="markup"
data-ng-click="pick_word($event)"
class="content"></div>
</div>
|
knezi/firedict
|
src/partials/wordpicker.html
|
HTML
|
gpl-3.0
| 182 |
# docker-kibana
|
zhongpei/docker-kibana
|
README.md
|
Markdown
|
gpl-3.0
| 16 |
/* Copyright (C) 2010 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.exchange.adapter;
import com.android.exchange.Eas;
import com.android.mail.utils.LogUtils;
import java.io.IOException;
import java.io.InputStream;
/**
* Parse the result of a MoveItems command.
*/
public class MoveItemsParser extends Parser {
private static final String TAG = Eas.LOG_TAG;
private int mStatusCode = 0;
private String mNewServerId;
private String mSourceServerId;
// These are the EAS status codes for MoveItems
private static final int STATUS_NO_SOURCE_FOLDER = 1;
private static final int STATUS_NO_DESTINATION_FOLDER = 2;
private static final int STATUS_SUCCESS = 3;
private static final int STATUS_SOURCE_DESTINATION_SAME = 4;
private static final int STATUS_INTERNAL_ERROR = 5;
private static final int STATUS_ALREADY_EXISTS = 6;
private static final int STATUS_LOCKED = 7;
// These are the status values we return to callers
public static final int STATUS_CODE_SUCCESS = 1;
public static final int STATUS_CODE_REVERT = 2;
public static final int STATUS_CODE_RETRY = 3;
public MoveItemsParser(InputStream in) throws IOException {
super(in);
}
public int getStatusCode() {
if (mStatusCode == 0) {
LogUtils.e(TAG, "Trying to get status for MoveItems, but no status was set");
// TODO: We currently treat empty responses as retry, so for now we'll do the same for
// partially empty responses.
return STATUS_CODE_RETRY;
}
return mStatusCode;
}
public String getNewServerId() {
return mNewServerId;
}
public String getSourceServerId() {
return mSourceServerId;
}
private void parseResponse() throws IOException {
while (nextTag(Tags.MOVE_RESPONSE) != END) {
if (tag == Tags.MOVE_STATUS) {
int status = getValueInt();
// Convert the EAS status code with our external codes
switch(status) {
case STATUS_SUCCESS:
case STATUS_SOURCE_DESTINATION_SAME:
case STATUS_ALREADY_EXISTS:
// Same destination and already exists are ok with us; we'll continue as
// if the move succeeded
mStatusCode = STATUS_CODE_SUCCESS;
break;
case STATUS_LOCKED:
// This sounds like a transient error, so we can safely retry
mStatusCode = STATUS_CODE_RETRY;
break;
case STATUS_NO_SOURCE_FOLDER:
case STATUS_NO_DESTINATION_FOLDER:
case STATUS_INTERNAL_ERROR:
default:
// These are non-recoverable, so we'll revert the message to its original
// mailbox. If there's an unknown response, revert
mStatusCode = STATUS_CODE_REVERT;
break;
}
if (status != STATUS_SUCCESS) {
// There's not much to be done if this fails
LogUtils.w(TAG, "Error in MoveItems: %d", status);
}
} else if (tag == Tags.MOVE_DSTMSGID) {
mNewServerId = getValue();
LogUtils.d(TAG, "Moved message id is now: %s", mNewServerId);
} else if (tag == Tags.MOVE_SRCMSGID) {
mSourceServerId = getValue();
LogUtils.d(TAG, "Source message id is: %s", mNewServerId);
} else {
skipTag();
}
}
}
@Override
public boolean parse() throws IOException {
boolean res = false;
if (nextTag(START_DOCUMENT) != Tags.MOVE_MOVE_ITEMS) {
throw new IOException();
}
while (nextTag(START_DOCUMENT) != END_DOCUMENT) {
if (tag == Tags.MOVE_RESPONSE) {
parseResponse();
} else {
skipTag();
}
}
return res;
}
}
|
s20121035/rk3288_android5.1_repo
|
packages/apps/Exchange/src/com/android/exchange/adapter/MoveItemsParser.java
|
Java
|
gpl-3.0
| 4,745 |
package org.s449;
import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
/**
* Class to listen for presses of the escape key.
*
* @author Stephen Carlson
* @version 1.0.0
*/
public class EscapeKeyListener extends KeyAdapter {
/**
* The component to hide when the escape key is pressed.
*/
private Component entry;
/**
* Creates a new escape key listener that will hide the given
* component.
*
* @param ent the component to be hidden on [Esc]
*/
public EscapeKeyListener(Component ent) {
entry = ent;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
entry.setVisible(false);
}
}
|
Mallikarjun12/scout449
|
org/s449/EscapeKeyListener.java
|
Java
|
gpl-3.0
| 718 |
/**
* fatrace - Trace system wide file access events.
*
* (C) 2012 Canonical Ltd.
* Author: Martin Pitt <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <dirent.h>
#include <mntent.h>
#include <getopt.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/fanotify.h>
#include <sys/time.h>
/* command line options */
static char* option_output = NULL;
static long option_timeout = -1;
static int option_current_mount = 0;
static int option_timestamp = 0;
static pid_t ignored_pids[1024];
static unsigned int ignored_pids_len = 0;
static long filter = 0;
/* --time alarm sets this to 0 */
static volatile int running = 1;
static volatile int signaled = 0;
/**
* mask2str:
*
* Convert a fanotify_event_metadata mask into a human readable string.
*
* Returns: decoded mask; only valid until the next call, do not free.
*/
static const char*
mask2str (uint64_t mask)
{
static char buffer[10];
int offset = 0;
memset (buffer, 0, sizeof (buffer));
if (mask & FAN_ACCESS)
buffer[offset++] = 'R';
if (mask & FAN_CLOSE_WRITE || mask & FAN_CLOSE_NOWRITE)
buffer[offset++] = 'C';
if (mask & FAN_MODIFY || mask & FAN_CLOSE_WRITE)
buffer[offset++] = 'W';
if (mask & FAN_OPEN)
buffer[offset++] = 'O';
return buffer;
}
/**
* print_event:
*
* Print data from fanotify_event_metadata struct to stdout.
*/
static void
print_event(struct fanotify_event_metadata *data)
{
int fd;
ssize_t len;
static char printbuf[100];
static char procname[100];
static char pathname[PATH_MAX];
struct stat st;
struct timeval event_time;
if (filter != 0 && filter != data->pid)
return;
/* get event time, if requested */
if (option_timestamp) {
if (gettimeofday (&event_time, NULL) < 0) {
perror ("gettimeofday");
exit (1);
}
}
/* read process name */
snprintf (printbuf, sizeof (printbuf), "/proc/%i/comm", data->pid);
len = 0;
fd = open (printbuf, O_RDONLY);
if (fd >= 0) {
len = read (fd, procname, sizeof (procname));
while (len > 0 && procname[len-1] == '\n') {
len--;
}
}
if (len > 0) {
procname[len] = '\0';
} else {
strcpy (procname, "unknown");
}
if (fd >= 0)
close (fd);
/* try to figure out the path name */
snprintf (printbuf, sizeof (printbuf), "/proc/self/fd/%i", data->fd);
len = readlink (printbuf, pathname, sizeof (pathname));
if (len < 0) {
/* fall back to the device/inode */
if (fstat (data->fd, &st) < 0) {
perror ("stat");
exit (1);
}
snprintf (pathname, sizeof (pathname), "device %i:%i inode %ld\n", major (st.st_dev), minor (st.st_dev), st.st_ino);
} else {
pathname[len] = '\0';
}
/* print event */
if (option_timestamp == 1) {
strftime (printbuf, sizeof (printbuf), "%H:%M:%S", localtime (&event_time.tv_sec));
printf ("%s.%06li ", printbuf, event_time.tv_usec);
} else if (option_timestamp == 2) {
printf ("%li.%06li ", event_time.tv_sec, event_time.tv_usec);
}
printf ("%s(%i): %s %s\n", procname, data->pid, mask2str (data->mask), pathname);
}
/**
* fanotify_mark_mounts:
*
* @fan_fd: fanotify file descriptor as returned by fanotify_init().
*
* Set up fanotify watches on all mount points, or on the current directory
* mount if --current-mount is given.
*/
static void
setup_fanotify(int fan_fd)
{
int res;
FILE* mounts;
struct mntent* mount;
if (option_current_mount) {
res = fanotify_mark (fan_fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
FAN_ACCESS| FAN_MODIFY | FAN_OPEN | FAN_CLOSE | FAN_ONDIR | FAN_EVENT_ON_CHILD,
AT_FDCWD, ".");
if (res < 0) {
fprintf(stderr, "Failed to add watch for current directory: %s\n", strerror (errno));
exit (1);
}
return;
}
/* iterate over all mounts */
mounts = setmntent ("/proc/self/mounts", "r");
if (mounts == NULL) {
perror ("setmntent");
exit (1);
}
while ((mount = getmntent (mounts)) != NULL) {
/* Only consider mounts which have an actual device or bind mount
* point. The others are stuff like proc, sysfs, binfmt_misc etc. which
* are virtual and do not actually cause disk access. */
if (access (mount->mnt_fsname, F_OK) != 0) {
//printf("IGNORE: fsname: %s dir: %s type: %s\n", mount->mnt_fsname, mount->mnt_dir, mount->mnt_type);
continue;
}
//printf("Adding watch for %s mount %s\n", mount->mnt_type, mount->mnt_dir);
res = fanotify_mark (fan_fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
FAN_ACCESS| FAN_MODIFY | FAN_OPEN | FAN_CLOSE | FAN_ONDIR | FAN_EVENT_ON_CHILD,
AT_FDCWD, mount->mnt_dir);
if (res < 0) {
fprintf(stderr, "Failed to add watch for %s mount %s: %s\n",
mount->mnt_type, mount->mnt_dir, strerror (errno));
}
}
endmntent (mounts);
}
/**
* help:
*
* Show help.
*/
static void
help (void)
{
puts ("Usage: fatrace [options...] \n"
"\n"
"Options:\n"
" -c, --current-mount\t\tOnly record events on partition/mount of current directory.\n"
" -o FILE, --output=FILE\tWrite events to a file instead of standard output.\n"
" -s SECONDS, --seconds=SECONDS\tStop after the given number of seconds.\n"
" -t, --timestamp\t\tAdd timestamp to events. Give twice for seconds since the epoch.\n"
" -p PID, --ignore-pid PID\tIgnore events for this process ID. Can be specified multiple times.\n"
" -f PID, --filter-pid PID\tPrint events for only this particular process ID..\n"
" -h, --help\t\t\tShow help.");
}
/**
* parse_args:
*
* Parse command line arguments and set the global option_* variables.
*/
static void
parse_args (int argc, char** argv)
{
int c;
long pid;
char *endptr;
static struct option long_options[] = {
{"current-mount", no_argument, 0, 'c'},
{"output", required_argument, 0, 'o'},
{"seconds", required_argument, 0, 's'},
{"timestamp", no_argument, 0, 't'},
{"ignore-pid", required_argument, 0, 'p'},
{"filter-pid", required_argument, 0, 'f'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0 }
};
while (1) {
c = getopt_long (argc, argv, "co:s:tp:f:h", long_options, NULL);
if (c == -1)
break;
switch (c) {
case 'c':
option_current_mount = 1;
break;
case 'o':
option_output = strdup (optarg);
break;
case 's':
option_timeout = strtol (optarg, &endptr, 10);
if (*endptr != '\0' || option_timeout <= 0) {
fputs ("Error: Invalid number of seconds\n", stderr);
exit (1);
}
break;
case 'p':
pid = strtol (optarg, &endptr, 10);
if (*endptr != '\0' || pid <= 0) {
fputs ("Error: Invalid PID\n", stderr);
exit (1);
}
if (ignored_pids_len < sizeof (ignored_pids))
ignored_pids[ignored_pids_len++] = pid;
else {
fputs ("Error: Too many ignored PIDs\n", stderr);
exit (1);
}
break;
case 'f':
filter = strtol(optarg, &endptr, 10);
if (*endptr != '\0' || filter <= 0) {
fputs ("Error: Invalid PID\n", stderr);
exit (1);
}
//printf("%ld", filter);
//exit(1);
break;
case 't':
if (++option_timestamp > 2) {
fputs ("Error: --timestamp option can be given at most two times\n", stderr);
exit (1);
};
break;
case 'h':
help ();
exit (0);
case '?':
/* getopt_long() already prints error message */
exit (1);
default:
fprintf (stderr, "Internal error: unexpected option '%c'\n", c);
exit (1);
}
}
}
/**
* show_pid:
*
* Check if events for given PID should be logged.
*
* Returns: 1 if PID is to be logged, 0 if not.
*/
static int
show_pid (pid_t pid)
{
unsigned int i;
for (i = 0; i < ignored_pids_len; ++i)
if (pid == ignored_pids[i])
return 0;
return 1;
}
static void
signal_handler (int signal)
{
(void)signal;
/* ask the main loop to stop */
running = 0;
signaled++;
/* but if stuck in some others functions, just quit now */
if (signaled > 1)
_exit(1);
}
int
main (int argc, char** argv)
{
int fan_fd;
int res;
int err;
void *buffer;
struct fanotify_event_metadata *data;
struct sigaction sa;
/* always ignore events from ourselves (writing log file) */
ignored_pids[ignored_pids_len++] = getpid();
parse_args (argc, argv);
fan_fd = fanotify_init (0, 0);
if (fan_fd < 0) {
err = errno;
fprintf (stderr, "Cannot initialize fanotify: %s\n", strerror (err));
if (err == EPERM)
fputs ("You need to run this program as root.\n", stderr);
exit(1);
}
setup_fanotify (fan_fd);
/* allocate memory for fanotify */
buffer = NULL;
err = posix_memalign (&buffer, 4096, 4096);
if (err != 0 || buffer == NULL) {
fprintf(stderr, "Failed to allocate buffer: %s\n", strerror (err));
exit(1);
}
/* output file? */
if (option_output) {
int fd = open (option_output, O_CREAT|O_WRONLY|O_EXCL, 0666);
if (fd < 0) {
perror ("Failed to open output file");
exit (1);
}
fflush (stdout);
dup2 (fd, STDOUT_FILENO);
close (fd);
}
/* setup signal handler to cleanly stop the program */
sa.sa_handler = signal_handler;
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction (SIGINT, &sa, NULL) < 0) {
perror ("sigaction");
exit (1);
}
/* set up --time alarm */
if (option_timeout > 0) {
sa.sa_handler = signal_handler;
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction (SIGALRM, &sa, NULL) < 0) {
perror ("sigaction");
exit (1);
}
alarm (option_timeout);
}
/* read all events in a loop */
while (running) {
res = read (fan_fd, buffer, 4096);
if (res == 0) {
fprintf (stderr, "No more fanotify event (EOF)\n");
break;
}
if (res < 0) {
if (errno == EINTR)
continue;
perror ("read");
exit(1);
}
data = (struct fanotify_event_metadata *) buffer;
while (FAN_EVENT_OK (data, res)) {
if (show_pid (data->pid))
print_event (data);
close (data->fd);
data = FAN_EVENT_NEXT (data, res);
}
}
return 0;
}
|
truncs/fatrace
|
fatrace.c
|
C
|
gpl-3.0
| 12,221 |
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>TERMS</title>
</head>
<color>
<font color="red">VOU REPROVAR? TALVEZ :/</font>
<br/>
<br/>
<br/>
<font color="red">ESTOU TENTANDO? SIM :S</font>
</body>
</html>
|
UniCEUB-Web-Development-2016/Mateus-Mourao-Guimaraes
|
docs/TorrentMStreamingCLIENTE/terms.html
|
HTML
|
gpl-3.0
| 295 |
package org.sigmah.client.ui.widget.popup;
/*
* #%L
* Sigmah
* %%
* Copyright (C) 2010 - 2016 URD
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import org.sigmah.shared.command.GetIndicators;
import org.sigmah.shared.command.GetProjects;
import org.sigmah.shared.command.result.IndicatorListResult;
import org.sigmah.shared.dto.IndicatorDTO;
import org.sigmah.shared.dto.IndicatorDataSourceDTO;
import com.extjs.gxt.ui.client.data.BaseTreeLoader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelIconProvider;
import com.extjs.gxt.ui.client.data.ModelStringProvider;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.data.TreeLoader;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.inject.Inject;
import org.sigmah.client.dispatch.CommandResultHandler;
import org.sigmah.client.dispatch.DispatchAsync;
import org.sigmah.client.i18n.I18N;
import org.sigmah.client.ui.res.icon.IconImageBundle;
import org.sigmah.client.ui.view.base.AbstractPopupView;
import org.sigmah.client.ui.widget.form.Forms;
import org.sigmah.shared.command.result.ListResult;
import org.sigmah.shared.command.result.VoidResult;
import org.sigmah.shared.dto.ProjectDTO;
import org.sigmah.shared.dto.referential.ProjectModelType;
/**
* Dialog that enables a user to select Indicators.
*
* @author Alexander Bertram ([email protected]) v1.3
* @author Raphaël Calabro ([email protected]) v2.0
*/
public class IndicatorBrowsePopup extends AbstractPopupView<PopupWidget> {
private final DispatchAsync dispatcher;
private final TreeLoader<ModelData> loader;
private TreePanel<ModelData> treePanel;
private AsyncCallback<VoidResult> callback;
@Inject
public IndicatorBrowsePopup(DispatchAsync dispatcher) {
super(new PopupWidget(true));
this.dispatcher = dispatcher;
this.loader = new BaseTreeLoader<ModelData>(new TreeProxy()) {
@Override
public boolean hasChildren(ModelData parent) {
return parent instanceof ProjectDTO;
}
};
}
@Override
public void initialize() {
setPopupTitle(I18N.CONSTANTS.selectIndicators());
final TreeStore<ModelData> treeStore = new TreeStore<ModelData>(loader);
treePanel = new TreePanel<ModelData>(treeStore);
treePanel.setCheckable(true);
treePanel.setCheckNodes(CheckNodes.LEAF);
treePanel.setIconProvider(new ModelIconProvider<ModelData>() {
@Override
public AbstractImagePrototype getIcon(ModelData model) {
if(model instanceof ProjectDTO) {
return IconImageBundle.ICONS.database();
} else {
return null;
}
}
});
treePanel.setLabelProvider(new ModelStringProvider<ModelData>() {
@Override
public String getStringValue(ModelData model, String property) {
if(model instanceof ProjectDTO) {
return ((ProjectDTO) model).getFullName();
} else if (model instanceof IndicatorDTO) {
return ((IndicatorDTO) model).getName();
} else {
throw new IllegalArgumentException("ModelData class should either be ProjectDTO or IndicatorDTO. Found: " + model.getClass());
}
}
});
final Button okButton = Forms.button(I18N.CONSTANTS.ok());
okButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
@Override
public void componentSelected(ButtonEvent ce) {
callback.onSuccess(null);
}
});
final Button cancelButton = Forms.button(I18N.CONSTANTS.cancel());
cancelButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
@Override
public void componentSelected(ButtonEvent ce) {
hide();
}
});
getPopup().addButton(okButton);
getPopup().addButton(cancelButton);
initPopup(treePanel);
}
/**
* Shows the form and calls back if the user clicks OK.
*
* @param callback
*/
public void show(AsyncCallback<VoidResult> callback) {
this.callback = callback;
center();
loader.load();
}
/**
*
* @return the list of checked indicators.
*/
public List<IndicatorDTO> getSelection() {
return (List)treePanel.getCheckedSelection();
}
/**
*
* @return the selected indicators as {@link IndicatorDataSourceDTO} dtos.
*/
public List<IndicatorDataSourceDTO> getSelectionAsDataSources() {
List<IndicatorDataSourceDTO> list = new ArrayList<IndicatorDataSourceDTO>();
for(ModelData model : treePanel.getCheckedSelection()) {
IndicatorDTO indicator = (IndicatorDTO) model;
ProjectDTO project = (ProjectDTO) treePanel.getStore().getParent(model);
IndicatorDataSourceDTO datasource = new IndicatorDataSourceDTO();
datasource.setDatabaseId(project.getId());
datasource.setDatabaseName(project.getName());
datasource.setIndicatorCode(indicator.getCode());
datasource.setIndicatorName(indicator.getName());
datasource.setIndicatorId(indicator.getId());
list.add(datasource);
}
return list;
}
private class TreeProxy extends RpcProxy<List<?>> {
@Override
protected void load(Object parent, final AsyncCallback<List<?>> callback) {
if(parent == null) {
final GetProjects command = new GetProjects((ProjectModelType) null, ProjectDTO.Mode.BASE);
dispatcher.execute(command, new CommandResultHandler<ListResult<ProjectDTO>>() {
@Override
protected void onCommandSuccess(ListResult<ProjectDTO> result) {
callback.onSuccess(result.getList());
}
});
} else if(parent instanceof ProjectDTO) {
dispatcher.execute(new GetIndicators((ProjectDTO)parent), new CommandResultHandler<IndicatorListResult>() {
@Override
protected void onCommandSuccess(IndicatorListResult result) {
callback.onSuccess(result.getData());
}
});
}
}
}
}
|
Raphcal/sigmah
|
src/main/java/org/sigmah/client/ui/widget/popup/IndicatorBrowsePopup.java
|
Java
|
gpl-3.0
| 6,766 |
/***************************************************************************
* *
* This file was automatically generated using idlc.js *
* PLEASE DO NOT EDIT!!!! *
* *
***************************************************************************/
#ifndef _Lock_base_H_
#define _Lock_base_H_
/**
@author Leo Hoo <[email protected]>
*/
#include "../object.h"
namespace fibjs {
class Lock_base : public object_base {
DECLARE_CLASS(Lock_base);
public:
// Lock_base
static result_t _new(obj_ptr<Lock_base>& retVal, v8::Local<v8::Object> This = v8::Local<v8::Object>());
virtual result_t acquire(bool blocking, bool& retVal) = 0;
virtual result_t release() = 0;
virtual result_t count(int32_t& retVal) = 0;
public:
template <typename T>
static void __new(const T& args);
public:
static void s__new(const v8::FunctionCallbackInfo<v8::Value>& args);
static void s_acquire(const v8::FunctionCallbackInfo<v8::Value>& args);
static void s_release(const v8::FunctionCallbackInfo<v8::Value>& args);
static void s_count(const v8::FunctionCallbackInfo<v8::Value>& args);
};
}
namespace fibjs {
inline ClassInfo& Lock_base::class_info()
{
static ClassData::ClassMethod s_method[] = {
{ "acquire", s_acquire, false },
{ "release", s_release, false },
{ "count", s_count, false }
};
static ClassData s_cd = {
"Lock", false, s__new, NULL,
ARRAYSIZE(s_method), s_method, 0, NULL, 0, NULL, NULL, NULL,
&object_base::class_info()
};
static ClassInfo s_ci(s_cd);
return s_ci;
}
inline void Lock_base::s__new(const v8::FunctionCallbackInfo<v8::Value>& args)
{
CONSTRUCT_INIT();
__new(args);
}
template <typename T>
void Lock_base::__new(const T& args)
{
obj_ptr<Lock_base> vr;
CONSTRUCT_ENTER();
METHOD_OVER(0, 0);
hr = _new(vr, args.This());
CONSTRUCT_RETURN();
}
inline void Lock_base::s_acquire(const v8::FunctionCallbackInfo<v8::Value>& args)
{
bool vr;
METHOD_INSTANCE(Lock_base);
METHOD_ENTER();
METHOD_OVER(1, 0);
OPT_ARG(bool, 0, true);
hr = pInst->acquire(v0, vr);
METHOD_RETURN();
}
inline void Lock_base::s_release(const v8::FunctionCallbackInfo<v8::Value>& args)
{
METHOD_INSTANCE(Lock_base);
METHOD_ENTER();
METHOD_OVER(0, 0);
hr = pInst->release();
METHOD_VOID();
}
inline void Lock_base::s_count(const v8::FunctionCallbackInfo<v8::Value>& args)
{
int32_t vr;
METHOD_INSTANCE(Lock_base);
METHOD_ENTER();
METHOD_OVER(0, 0);
hr = pInst->count(vr);
METHOD_RETURN();
}
}
#endif
|
ngot/nightly-test
|
fibjs/include/ifs/Lock.h
|
C
|
gpl-3.0
| 2,831 |
# -*- coding: utf-8 -*-
#
# PartyCrasher documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 25 11:42:26 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import textwrap
import warnings
from recommonmark.parser import CommonMarkParser
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
from partycrasher import rest_service
from partycrasher import __version__ as partycrasher_version
def create_rest_api_docs():
"""
Creates rest-api.rst automatically from rest_service, using
rest-api.rst.template as a template.
Any documented REST endpoint (decorated with @app.route() and with a
docstring such as this one) is concatenated and written to rest-api.rst.
**To control the order of the documentation**:
Make this the FIRST line of the docstring::
.. api-doc-order: 1.0
Where 1.0 can be any float.
"""
# Get a list of endpoints, according to Flask
known_endpoints = frozenset(rule.endpoint for rule in
rest_service.app.url_map.iter_rules())
def sibling_filename(name):
return os.path.join(os.path.abspath('.'), name)
def api_endpoints():
for name, function in vars(rest_service).items():
if name not in known_endpoints:
continue
if not function.__doc__ :
warnings.warn('Undocumented API endpoint: ' + function.__name__)
continue
yield textwrap.dedent(function.__doc__.decode('UTF-8'))
filename = sibling_filename('rest-api.rst')
with open(sibling_filename('rest-api.rst.template')) as template_file:
template = template_file.read().decode('UTF-8')
def by_api_doc_order(docstring):
first_non_blank_line = next(line.strip()
for line in docstring.splitlines()
if len(line.strip()) > 0)
segments = first_non_blank_line.split()
# Comapre slices to avoid IndexErrors
if len(segments) == 3 and segments[0:2] == ['..', 'api-doc-order:']:
return float(segments[2])
else:
return first_non_blank_line
body = u'\n\n'.join(sorted(api_endpoints(), key=by_api_doc_order))
with open(filename, 'wb') as doc_file:
content = template.format(body=body,
version=release)
doc_file.write(content.encode('UTF-8'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
source_parsers = {
'.md': CommonMarkParser,
}
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = ['.rst', '.md']
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'PartyCrasher'
copyright = u'2016, Joshua Charles Campbell, Eddie Antonio Santos, Abram Hindle'
author = u'Joshua Charles Campbell, Eddie Antonio Santos, Abram Hindle'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'.'.join(partycrasher_version.split('.')[:2])
# The full version, including alpha/beta/rc tags.
release = partycrasher_version
# Create the API docs for REST API
create_rest_api_docs()
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'PartyCrasherdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'PartyCrasher.tex', u'PartyCrasher Documentation',
u'Joshua Charles Campbell, Eddie Antonio Santos, Abram Hindle', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'partycrasher', u'PartyCrasher Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'PartyCrasher', u'PartyCrasher Documentation',
author, 'PartyCrasher', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
|
orezpraw/partycrasher
|
docs/conf.py
|
Python
|
gpl-3.0
| 11,929 |
# 1.0.0.CR1 - "Doheny Beach"
## New and Noteworthy
- Configuration via XML file, see the [Configuration via XML](https://cache2k.org/docs/stable/user-guide.html#configuration-via-xml) documentation section.
- Documentation emerges in the [User Guide](https://cache2k.org/docs/stable/user-guide.html).
- Thread pools configurable for loading and prefetching. `Cache2kBuilder#loaderExecutor`, `Cache2kBuilder#prefetchExecutor`
- Various API cleanups.
- Improved Java Doc at various places.
- This version still contains deprecated methods. Users of the deprecated APIs should migrate now to the
new one. The deprecated methods will be removed in the next release.
## Potential breakages
Changes in semantics or API that may break existing applications are listed here.
Modifications in the statistics output will not listed as breakage.
- `sharpExpiry(true)` only has effect times returned by `ExpiryPolicy`. When the expiry is controlled by the duration
`expireAfterWrite` it may lag and the value is returned when a reload is in progress, when refresh ahead is enabled.
- `eternal(false)` has an effect now and means "needs expiry, but expiry is undefined yet.".
This can be used to ensure that an expiry time is set via the file based configuration.
- Setting conflicting parameters like `eternal(true)` and `expireAfterWrite(...)` leads to an exception
- Attempts to create a cache with the identical name of an active cache yields a `IllegalArgumentException`.
(In the release before the cache name was disambiguated by adding a incrementing number)
- JMX properties: Consistent naming and cleanup
## Fixes and Improvements
- cache2k version number, "greeting" is logged only once at info level
- Creation of `CacheManager` is logged at debug level
- Check/restrict allowed characters in a cache manager name
- Rename internal artifacts
- `Cache.getEntry()`: improve entry debug output for a stored exception
- remove task queue for asynchronous loads/refreshs and handle rejections gracefully
- reduce default loader thread count to one per available CPU
- `toString()` contains cache manager name
- `toString()` add version number
- Cleanup and improve `CacheManager` methods
- Creation and destruction on `CacheManager` corrected
## Using this cache2k version
### For Java SE/EE environments
````
<dependency>
<groupId>org.cache2k</groupId>
<artifactId>cache2k-api</artifactId>
<version>1.0.0.CR1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.cache2k</groupId>
<artifactId>cache2k-all</artifactId>
<version>1.0.0.CR1</version>
<scope>runtime</scope>
</dependency>
````
### For Android
````
<dependency>
<groupId>org.cache2k</groupId>
<artifactId>cache2k-api</artifactId>
<version>1.0.0.CR1</version>
</dependency>
<dependency>
<groupId>org.cache2k</groupId>
<artifactId>cache2k-core</artifactId>
<version>1.0.0.CR1</version>
<scope>runtime</scope>
</dependency>
````
### Using the JCache / JSR107 provider
````
<dependency>
<groupId>org.cache2k</groupId>
<artifactId>cache2k-jcache</artifactId>
<version>1.0.0.CR1</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.0.0</version>
</dependency>
````
|
headissue/cache2k
|
src/site/markdown/1/0.0.CR1.md
|
Markdown
|
gpl-3.0
| 3,397 |
namespace SEToolbox.Models
{
using System.Collections.ObjectModel;
public class RegeneratePlanetModel : BaseModel
{
#region Fields
private int _seed;
private decimal _diameter;
private bool _invalidKeenRange;
#endregion
#region ctor
public RegeneratePlanetModel()
{
}
#endregion
#region Properties
public int Seed
{
get { return _seed; }
set
{
if (value != _seed)
{
_seed = value;
OnPropertyChanged(nameof(Seed));
}
}
}
public decimal Diameter
{
get { return _diameter; }
set
{
if (value != _diameter)
{
_diameter = value;
OnPropertyChanged(nameof(Diameter));
InvalidKeenRange = _diameter < 19000 || _diameter > 120000;
}
}
}
public bool InvalidKeenRange
{
get { return _invalidKeenRange; }
set
{
if (value != _invalidKeenRange)
{
_invalidKeenRange = value;
OnPropertyChanged(nameof(InvalidKeenRange));
}
}
}
#endregion
#region methods
public void Load(int seed, float radius)
{
Seed = seed;
Diameter = (decimal)(radius * 2f);
}
#endregion
}
}
|
midspace/SEToolbox
|
Main/SEToolbox/SEToolbox/Models/RegeneratePlanetModel.cs
|
C#
|
gpl-3.0
| 1,641 |
var n = 3, m = 4, data = pv.range(n).map(function() {
return pv.range(m).map(function() {
return Math.random() + .1;
});
});
var a = [];
for(var i=0;i<18;++i) a.push( Math.random() );
for(var i=0;i<5;++i) a[i] = a[i]*5-3;
for(var i=5;i<12;++i) a[i] = a[i]*20-10;
for(var i=12;i<18;++i) a[i] = a[i]*150-75;
var bullets = [
{
title: "Cecha #1",
subtitle: "pkt",
ranges: [20+a[0], 25+a[1], 30+a[2]],
measures: [23+a[3]],
markers: [26+a[4]]
},
{
title: "Cecha #2",
subtitle: "#",
ranges: [45+a[5], 75+a[6], 90+a[7]],
measures: [30+a[8], 80+a[9], 85+a[10]],
markers: [25+a[11]]
},
{
title: "Cecha #3",
subtitle: "N",
ranges: [350+a[12], 500+a[13], 600+a[14]],
measures: [320+a[15], 380+a[16]],
markers: [550+a[17]]
},
];
|
instytut-badan-edukacyjnych/platforma-testow
|
TestDemo/Demo-Lorem-PL/report/chartData.js
|
JavaScript
|
gpl-3.0
| 811 |
#region License Information (GPL v3)
/*
ShareX - A program that allows you to take screenshots and share any file type
Copyright (c) 2007-2020 ShareX Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/
#endregion License Information (GPL v3)
namespace ShareX.UploadersLib.SharingServices
{
public class StumbleUponSharingService : SimpleURLSharingService
{
public override URLSharingServices EnumValue { get; } = URLSharingServices.StumbleUpon;
protected override string URLFormatString { get; } = "http://www.stumbleupon.com/submit?url={0}";
}
}
|
Scrxtchy/ShareX
|
ShareX.UploadersLib/SharingServices/StumbleUponSharingService.cs
|
C#
|
gpl-3.0
| 1,353 |
python run.py
|
nemo-tj/biendata
|
source/build.sh
|
Shell
|
gpl-3.0
| 14 |
url: http://sanskrit.uohyd.ac.in/cgi-bin/scl/sandhi_splitter/sandhi_splitter.cgi?encoding=Unicode&sandhi_type=s&word=उक्तमिति<div id='finalout' style='border-style:solid; border-width:1px;padding:10px;color:blue;font-size:14px;height:200px'>उक्तमिति = <a title = "उक्त पुं 2 एक/उक्त पुं 2 एक/उक्त नपुं 1 एक/उक्त नपुं 1 एक/उक्त नपुं 2 एक/उक्त नपुं 2 एक">उक्तम्</a>+<a title = "इति अव्य">इति</a>/<script type="text/javascript">
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block";document.getElementById("more").style.display="none"; document.getElementById("less").style.display="block";
}
else{
e.style.display="none";document.getElementById("less").style.display="none"; document.getElementById("more").style.display="block";
}
return true;
}
</script>
<input type="button" onclick="return toggleMe('para1')" value="More" id="more"> <input type="button" onclick="return toggleMe('para1')" value="Less" id="less" style="display:none;" > <div id="para1" style="display:none; height:15px; border-style:none;border-width:1px;">
<a title = "उक्त पुं 2 एक/उक्त पुं 2 एक/उक्त नपुं 1 एक/उक्त नपुं 1 एक/उक्त नपुं 2 एक/उक्त नपुं 2 एक">उक्तम्</a>+<a title = "इति अव्य">इति</a>/<a title = "उक्त पुं 8 एक/उक्त पुं 8 एक/उक्त नपुं 8 एक/उक्त नपुं 8 एक/वच्1 पुं क्त<धातुः:वचँ><गणः:अदादिः>/वच्1 नपुं क्त<धातुः:वचँ><गणः:अदादिः>">उक्त</a>+<a title = "मित् स्त्री 7 एक">मिति</a>/</div><br />
|
sanskritiitd/sanskrit
|
uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/tarkchudamani-ext.txt.out.dict_13707_sam.html
|
HTML
|
gpl-3.0
| 2,021 |
/* Test for bug 19439.
Copyright (C) 2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Marek Polacek <[email protected]>, 2012.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#define _GNU_SOURCE 1
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
static int
do_test (void)
{
/* Verify that isinff, isinfl, isnanf, and isnanlf are defined
in the header under C++11 and can be called. Without the
header fix this test will not compile. */
if (isinff (1.0f)
|| !isinff (INFINITY)
#ifndef NO_LONG_DOUBLE
|| isinfl (1.0L)
|| !isinfl (INFINITY)
#endif
|| isnanf (2.0f)
|| !isnanf (NAN)
#ifndef NO_LONG_DOUBLE
|| isnanl (2.0L)
|| !isnanl (NAN)
#endif
)
{
printf ("FAIL: Failed to call is* functions.\n");
exit (1);
}
printf ("PASS: Able to call isinff, isinfl, isnanf, and isnanl.\n");
exit (0);
}
#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"
|
geminy/aidear
|
oss/glibc/glibc-2.24/math/test-math-isinff.cc
|
C++
|
gpl-3.0
| 1,643 |
/**
* This file is part of Graylog.
*
* Graylog 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.
*
* Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.rest.models.system.ldap.responses;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;
import java.net.URI;
import java.util.Map;
import java.util.Set;
@JsonAutoDetect
@AutoValue
public abstract class LdapSettingsResponse {
@JsonProperty
public abstract boolean enabled();
@JsonProperty
public abstract String systemUsername();
@JsonProperty
public abstract String systemPassword();
@JsonProperty
public abstract URI ldapUri();
@JsonProperty
public abstract boolean useStartTls();
@JsonProperty
public abstract boolean trustAllCertificates();
@JsonProperty
public abstract boolean activeDirectory();
@JsonProperty
public abstract String searchBase();
@JsonProperty
public abstract String searchPattern();
@JsonProperty
public abstract String displayNameAttribute();
@JsonProperty
public abstract String defaultGroup();
@JsonProperty
@Nullable
public abstract Map<String, String> groupMapping();
@JsonProperty
@Nullable
public abstract String groupSearchBase();
@JsonProperty
@Nullable
public abstract String groupIdAttribute();
@JsonProperty
@Nullable
public abstract Set<String> additionalDefaultGroups();
@JsonProperty
@Nullable
public abstract String groupSearchPattern();
@JsonCreator
public static LdapSettingsResponse create(@JsonProperty("enabled") boolean enabled,
@JsonProperty("system_username") String systemUsername,
@JsonProperty("system_password") String systemPassword,
@JsonProperty("ldap_uri") URI ldapUri,
@JsonProperty("use_start_tls") boolean useStartTls,
@JsonProperty("trust_all_certificates") boolean trustAllCertificates,
@JsonProperty("active_directory") boolean activeDirectory,
@JsonProperty("search_base") String searchBase,
@JsonProperty("search_pattern") String searchPattern,
@JsonProperty("display_name_attributes") String displayNameAttribute,
@JsonProperty("default_group") String defaultGroup,
@JsonProperty("group_mapping") @Nullable Map<String, String> groupMapping,
@JsonProperty("group_search_base") @Nullable String groupSearchBase,
@JsonProperty("group_id_attribute") @Nullable String groupIdAttribute,
@JsonProperty("additional_default_groups") @Nullable Set<String> additionalDefaultGroups,
@JsonProperty("group_search_pattern") @Nullable String groupSearchPattern) {
return new AutoValue_LdapSettingsResponse(enabled,
systemUsername,
systemPassword,
ldapUri,
useStartTls,
trustAllCertificates,
activeDirectory,
searchBase,
searchPattern,
displayNameAttribute,
defaultGroup,
groupMapping,
groupSearchBase,
groupIdAttribute,
additionalDefaultGroups,
groupSearchPattern);
}
}
|
berkeleydave/graylog2-server
|
graylog2-rest-models/src/main/java/org/graylog2/rest/models/system/ldap/responses/LdapSettingsResponse.java
|
Java
|
gpl-3.0
| 5,026 |
/**
* This file is part of Hercules.
* http://herc.ws - http://github.com/HerculesWS/Hercules
*
* Copyright (C) 2012-2016 Hercules Dev Team
* Copyright (C) Athena Dev Teams
*
* Hercules 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define HERCULES_CORE
#include "config/core.h" // DBPATH
#include "int_guild.h"
#include "char/char.h"
#include "char/inter.h"
#include "char/mapif.h"
#include "common/cbasetypes.h"
#include "common/db.h"
#include "common/memmgr.h"
#include "common/mmo.h"
#include "common/nullpo.h"
#include "common/showmsg.h"
#include "common/socket.h"
#include "common/sql.h"
#include "common/strlib.h"
#include "common/timer.h"
#include <stdio.h>
#include <stdlib.h>
#define GS_MEMBER_UNMODIFIED 0x00
#define GS_MEMBER_MODIFIED 0x01
#define GS_MEMBER_NEW 0x02
#define GS_POSITION_UNMODIFIED 0x00
#define GS_POSITION_MODIFIED 0x01
// LSB = 0 => Alliance, LSB = 1 => Opposition
#define GUILD_ALLIANCE_TYPE_MASK 0x01
#define GUILD_ALLIANCE_REMOVE 0x08
struct inter_guild_interface inter_guild_s;
struct inter_guild_interface *inter_guild;
static const char dataToHex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int inter_guild_save_timer(int tid, int64 tick, int id, intptr_t data) {
static int last_id = 0; //To know in which guild we were.
int state = 0; //0: Have not reached last guild. 1: Reached last guild, ready for save. 2: Some guild saved, don't do further saving.
struct DBIterator *iter = db_iterator(inter_guild->guild_db);
union DBKey key;
struct guild* g;
if( last_id == 0 ) //Save the first guild in the list.
state = 1;
for( g = DB->data2ptr(iter->first(iter, &key)); dbi_exists(iter); g = DB->data2ptr(iter->next(iter, &key)) )
{
if (!g)
continue;
if( state == 0 && g->guild_id == last_id )
state++; //Save next guild in the list.
else
if( state == 1 && g->save_flag&GS_MASK )
{
inter_guild->tosql(g, g->save_flag&GS_MASK);
g->save_flag &= ~GS_MASK;
//Some guild saved.
last_id = g->guild_id;
state++;
}
if (g->save_flag == GS_REMOVE) {
// Nothing to save, guild is ready for removal.
if (chr->show_save_log)
ShowInfo("Guild Unloaded (%d - %s)\n", g->guild_id, g->name);
db_remove(inter_guild->guild_db, key);
}
}
dbi_destroy(iter);
if( state != 2 ) //Reached the end of the guild db without saving.
last_id = 0; //Reset guild saved, return to beginning.
state = inter_guild->guild_db->size(inter_guild->guild_db);
if( state < 1 ) state = 1; //Calculate the time slot for the next save.
timer->add(tick + autosave_interval/state, inter_guild->save_timer, 0, 0);
return 0;
}
int inter_guild_removemember_tosql(int account_id, int char_id)
{
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE from `%s` where `account_id` = '%d' and `char_id` = '%d'", guild_member_db, account_id, char_id) )
Sql_ShowDebug(inter->sql_handle);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "UPDATE `%s` SET `guild_id` = '0' WHERE `char_id` = '%d'", char_db, char_id) )
Sql_ShowDebug(inter->sql_handle);
return 0;
}
// Save guild into sql
int inter_guild_tosql(struct guild *g,int flag)
{
// Table guild (GS_BASIC_MASK)
// GS_EMBLEM `emblem_len`,`emblem_id`,`emblem_data`
// GS_CONNECT `connect_member`,`average_lv`
// GS_MES `mes1`,`mes2`
// GS_LEVEL `guild_lv`,`max_member`,`exp`,`next_exp`,`skill_point`
// GS_BASIC `name`,`master`,`char_id`
// GS_MEMBER `guild_member` (`guild_id`,`account_id`,`char_id`,`hair`,`hair_color`,`gender`,`class`,`lv`,`exp`,`exp_payper`,`online`,`position`,`name`)
// GS_POSITION `guild_position` (`guild_id`,`position`,`name`,`mode`,`exp_mode`)
// GS_ALLIANCE `guild_alliance` (`guild_id`,`opposition`,`alliance_id`,`name`)
// GS_EXPULSION `guild_expulsion` (`guild_id`,`account_id`,`name`,`mes`)
// GS_SKILL `guild_skill` (`guild_id`,`id`,`lv`)
// temporary storage for str conversion. They must be twice the size of the
// original string to ensure no overflows will occur. [Skotlex]
char t_info[256];
char esc_name[NAME_LENGTH*2+1];
char esc_master[NAME_LENGTH*2+1];
char new_guild = 0;
int i=0;
nullpo_ret(g);
if (g->guild_id<=0 && g->guild_id != -1) return 0;
#ifdef NOISY
ShowInfo("Save guild request ("CL_BOLD"%d"CL_RESET" - flag 0x%x).",g->guild_id, flag);
#endif
SQL->EscapeStringLen(inter->sql_handle, esc_name, g->name, strnlen(g->name, NAME_LENGTH));
SQL->EscapeStringLen(inter->sql_handle, esc_master, g->master, strnlen(g->master, NAME_LENGTH));
*t_info = '\0';
// Insert a new guild the guild
if (flag&GS_BASIC && g->guild_id == -1) {
strcat(t_info, " guild_create");
// Create a new guild
if (SQL_ERROR == SQL->Query(inter->sql_handle, "INSERT INTO `%s` "
"(`name`,`master`,`guild_lv`,`max_member`,`average_lv`,`char_id`) "
"VALUES ('%s', '%s', '%d', '%d', '%d', '%d')",
guild_db, esc_name, esc_master, g->guild_lv, g->max_member, g->average_lv, g->member[0].char_id)) {
Sql_ShowDebug(inter->sql_handle);
return 0; //Failed to create guild!
} else {
g->guild_id = (int)SQL->LastInsertId(inter->sql_handle);
new_guild = 1;
}
}
// If we need an update on an existing guild or more update on the new guild
if (((flag & GS_BASIC_MASK) && !new_guild) || ((flag & (GS_BASIC_MASK & ~GS_BASIC)) && new_guild))
{
StringBuf buf;
bool add_comma = false;
StrBuf->Init(&buf);
StrBuf->Printf(&buf, "UPDATE `%s` SET ", guild_db);
if (flag & GS_EMBLEM)
{
char emblem_data[sizeof(g->emblem_data)*2+1];
char* pData = emblem_data;
strcat(t_info, " emblem");
// Convert emblem_data to hex
//TODO: why not use binary directly? [ultramage]
for(i=0; i<g->emblem_len; i++){
*pData++ = dataToHex[(g->emblem_data[i] >> 4) & 0x0F];
*pData++ = dataToHex[g->emblem_data[i] & 0x0F];
}
*pData = 0;
StrBuf->Printf(&buf, "`emblem_len`=%d, `emblem_id`=%d, `emblem_data`='%s'", g->emblem_len, g->emblem_id, emblem_data);
add_comma = true;
}
if (flag & GS_BASIC)
{
strcat(t_info, " basic");
if( add_comma )
StrBuf->AppendStr(&buf, ", ");
else
add_comma = true;
StrBuf->Printf(&buf, "`name`='%s', `master`='%s', `char_id`=%d", esc_name, esc_master, g->member[0].char_id);
}
if (flag & GS_CONNECT)
{
strcat(t_info, " connect");
if( add_comma )
StrBuf->AppendStr(&buf, ", ");
else
add_comma = true;
StrBuf->Printf(&buf, "`connect_member`=%d, `average_lv`=%d", g->connect_member, g->average_lv);
}
if (flag & GS_MES)
{
char esc_mes1[sizeof(g->mes1)*2+1];
char esc_mes2[sizeof(g->mes2)*2+1];
strcat(t_info, " mes");
if( add_comma )
StrBuf->AppendStr(&buf, ", ");
else
add_comma = true;
SQL->EscapeStringLen(inter->sql_handle, esc_mes1, g->mes1, strnlen(g->mes1, sizeof(g->mes1)));
SQL->EscapeStringLen(inter->sql_handle, esc_mes2, g->mes2, strnlen(g->mes2, sizeof(g->mes2)));
StrBuf->Printf(&buf, "`mes1`='%s', `mes2`='%s'", esc_mes1, esc_mes2);
}
if (flag & GS_LEVEL)
{
strcat(t_info, " level");
if( add_comma )
StrBuf->AppendStr(&buf, ", ");
#if 0
else //last condition using add_coma setting
add_comma = true;
#endif // 0
StrBuf->Printf(&buf, "`guild_lv`=%d, `skill_point`=%d, `exp`=%"PRIu64", `next_exp`=%u, `max_member`=%d", g->guild_lv, g->skill_point, g->exp, g->next_exp, g->max_member);
}
StrBuf->Printf(&buf, " WHERE `guild_id`=%d", g->guild_id);
if( SQL_ERROR == SQL->QueryStr(inter->sql_handle, StrBuf->Value(&buf)) )
Sql_ShowDebug(inter->sql_handle);
StrBuf->Destroy(&buf);
}
if (flag&GS_MEMBER) {
strcat(t_info, " members");
// Update only needed players
for(i=0;i<g->max_member;i++){
struct guild_member *m = &g->member[i];
if (!m->modified)
continue;
if(m->account_id) {
//Since nothing references guild member table as foreign keys, it's safe to use REPLACE INTO
SQL->EscapeStringLen(inter->sql_handle, esc_name, m->name, strnlen(m->name, NAME_LENGTH));
if( SQL_ERROR == SQL->Query(inter->sql_handle, "REPLACE INTO `%s` (`guild_id`,`account_id`,`char_id`,`hair`,`hair_color`,`gender`,`class`,`lv`,`exp`,`exp_payper`,`online`,`position`,`name`) "
"VALUES ('%d','%d','%d','%d','%d','%d','%d','%d','%"PRIu64"','%d','%d','%d','%s')",
guild_member_db, g->guild_id, m->account_id, m->char_id,
m->hair, m->hair_color, m->gender,
m->class_, m->lv, m->exp, m->exp_payper, m->online, m->position, esc_name) )
Sql_ShowDebug(inter->sql_handle);
if (m->modified&GS_MEMBER_NEW || new_guild == 1)
{
if( SQL_ERROR == SQL->Query(inter->sql_handle, "UPDATE `%s` SET `guild_id` = '%d' WHERE `char_id` = '%d'",
char_db, g->guild_id, m->char_id) )
Sql_ShowDebug(inter->sql_handle);
}
m->modified = GS_MEMBER_UNMODIFIED;
}
}
}
if (flag&GS_POSITION){
strcat(t_info, " positions");
//printf("- Insert guild %d to guild_position\n",g->guild_id);
for(i=0;i<MAX_GUILDPOSITION;i++){
struct guild_position *p = &g->position[i];
if (!p || !p->modified)
continue;
SQL->EscapeStringLen(inter->sql_handle, esc_name, p->name, strnlen(p->name, NAME_LENGTH));
if( SQL_ERROR == SQL->Query(inter->sql_handle, "REPLACE INTO `%s` (`guild_id`,`position`,`name`,`mode`,`exp_mode`) VALUES ('%d','%d','%s','%d','%d')",
guild_position_db, g->guild_id, i, esc_name, p->mode, p->exp_mode) )
Sql_ShowDebug(inter->sql_handle);
p->modified = GS_POSITION_UNMODIFIED;
}
}
if (flag&GS_ALLIANCE)
{
// Delete current alliances
// NOTE: no need to do it on both sides since both guilds in memory had
// their info changed, not to mention this would also mess up oppositions!
// [Skotlex]
//if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id`='%d' OR `alliance_id`='%d'", guild_alliance_db, g->guild_id, g->guild_id) )
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id`='%d'", guild_alliance_db, g->guild_id) )
{
Sql_ShowDebug(inter->sql_handle);
}
else
{
//printf("- Insert guild %d to guild_alliance\n",g->guild_id);
for(i=0;i<MAX_GUILDALLIANCE;i++)
{
struct guild_alliance *a=&g->alliance[i];
if(a->guild_id>0)
{
SQL->EscapeStringLen(inter->sql_handle, esc_name, a->name, strnlen(a->name, NAME_LENGTH));
if( SQL_ERROR == SQL->Query(inter->sql_handle, "REPLACE INTO `%s` (`guild_id`,`opposition`,`alliance_id`,`name`) "
"VALUES ('%d','%d','%d','%s')",
guild_alliance_db, g->guild_id, a->opposition, a->guild_id, esc_name) )
Sql_ShowDebug(inter->sql_handle);
}
}
}
}
if (flag&GS_EXPULSION){
strcat(t_info, " expulsions");
//printf("- Insert guild %d to guild_expulsion\n",g->guild_id);
for(i=0;i<MAX_GUILDEXPULSION;i++){
struct guild_expulsion *e=&g->expulsion[i];
if(e->account_id>0){
char esc_mes[sizeof(e->mes)*2+1];
SQL->EscapeStringLen(inter->sql_handle, esc_name, e->name, strnlen(e->name, NAME_LENGTH));
SQL->EscapeStringLen(inter->sql_handle, esc_mes, e->mes, strnlen(e->mes, sizeof(e->mes)));
if( SQL_ERROR == SQL->Query(inter->sql_handle, "REPLACE INTO `%s` (`guild_id`,`account_id`,`name`,`mes`) "
"VALUES ('%d','%d','%s','%s')", guild_expulsion_db, g->guild_id, e->account_id, esc_name, esc_mes) )
Sql_ShowDebug(inter->sql_handle);
}
}
}
if (flag&GS_SKILL){
strcat(t_info, " skills");
//printf("- Insert guild %d to guild_skill\n",g->guild_id);
for(i=0;i<MAX_GUILDSKILL;i++){
if (g->skill[i].id>0 && g->skill[i].lv>0){
if( SQL_ERROR == SQL->Query(inter->sql_handle, "REPLACE INTO `%s` (`guild_id`,`id`,`lv`) VALUES ('%d','%d','%d')",
guild_skill_db, g->guild_id, g->skill[i].id, g->skill[i].lv) )
Sql_ShowDebug(inter->sql_handle);
}
}
}
if (chr->show_save_log)
ShowInfo("Saved guild (%d - %s):%s\n", g->guild_id, g->name, t_info);
return 1;
}
// Read guild from sql
struct guild * inter_guild_fromsql(int guild_id)
{
struct guild *g;
char* data;
size_t len;
char* p;
int i;
if( guild_id <= 0 )
return NULL;
g = (struct guild*)idb_get(inter_guild->guild_db, guild_id);
if( g )
return g;
#ifdef NOISY
ShowInfo("Guild load request (%d)...\n", guild_id);
#endif
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT g.`name`,c.`name`,g.`guild_lv`,g.`connect_member`,g.`max_member`,g.`average_lv`,g.`exp`,g.`next_exp`,g.`skill_point`,g.`mes1`,g.`mes2`,g.`emblem_len`,g.`emblem_id`,g.`emblem_data` "
"FROM `%s` g LEFT JOIN `%s` c ON c.`char_id` = g.`char_id` WHERE g.`guild_id`='%d'", guild_db, char_db, guild_id) )
{
Sql_ShowDebug(inter->sql_handle);
return NULL;
}
if( SQL_SUCCESS != SQL->NextRow(inter->sql_handle) )
return NULL;// Guild does not exists.
CREATE(g, struct guild, 1);
g->guild_id = guild_id;
SQL->GetData(inter->sql_handle, 0, &data, &len); memcpy(g->name, data, min(len, NAME_LENGTH));
SQL->GetData(inter->sql_handle, 1, &data, &len); memcpy(g->master, data, min(len, NAME_LENGTH));
SQL->GetData(inter->sql_handle, 2, &data, NULL); g->guild_lv = atoi(data);
SQL->GetData(inter->sql_handle, 3, &data, NULL); g->connect_member = atoi(data);
SQL->GetData(inter->sql_handle, 4, &data, NULL); g->max_member = atoi(data);
if (g->max_member > MAX_GUILD) {
// Fix reduction of MAX_GUILD [PoW]
ShowWarning("Guild %d:%s specifies higher capacity (%d) than MAX_GUILD (%d)\n", guild_id, g->name, g->max_member, MAX_GUILD);
g->max_member = MAX_GUILD;
}
SQL->GetData(inter->sql_handle, 5, &data, NULL); g->average_lv = atoi(data);
SQL->GetData(inter->sql_handle, 6, &data, NULL); g->exp = strtoull(data, NULL, 10);
SQL->GetData(inter->sql_handle, 7, &data, NULL); g->next_exp = (unsigned int)strtoul(data, NULL, 10);
SQL->GetData(inter->sql_handle, 8, &data, NULL); g->skill_point = atoi(data);
SQL->GetData(inter->sql_handle, 9, &data, &len); memcpy(g->mes1, data, min(len, sizeof(g->mes1)));
SQL->GetData(inter->sql_handle, 10, &data, &len); memcpy(g->mes2, data, min(len, sizeof(g->mes2)));
SQL->GetData(inter->sql_handle, 11, &data, &len); g->emblem_len = atoi(data);
SQL->GetData(inter->sql_handle, 12, &data, &len); g->emblem_id = atoi(data);
SQL->GetData(inter->sql_handle, 13, &data, &len);
// convert emblem data from hexadecimal to binary
//TODO: why not store it in the db as binary directly? [ultramage]
for( i = 0, p = g->emblem_data; i < g->emblem_len; ++i, ++p )
{
if( *data >= '0' && *data <= '9' )
*p = *data - '0';
else if( *data >= 'a' && *data <= 'f' )
*p = *data - 'a' + 10;
else if( *data >= 'A' && *data <= 'F' )
*p = *data - 'A' + 10;
*p <<= 4;
++data;
if( *data >= '0' && *data <= '9' )
*p |= *data - '0';
else if( *data >= 'a' && *data <= 'f' )
*p |= *data - 'a' + 10;
else if( *data >= 'A' && *data <= 'F' )
*p |= *data - 'A' + 10;
++data;
}
// load guild member info
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT `account_id`,`char_id`,`hair`,`hair_color`,`gender`,`class`,`lv`,`exp`,`exp_payper`,`online`,`position`,`name` "
"FROM `%s` WHERE `guild_id`='%d' ORDER BY `position`", guild_member_db, guild_id) )
{
Sql_ShowDebug(inter->sql_handle);
aFree(g);
return NULL;
}
for( i = 0; i < g->max_member && SQL_SUCCESS == SQL->NextRow(inter->sql_handle); ++i )
{
struct guild_member* m = &g->member[i];
SQL->GetData(inter->sql_handle, 0, &data, NULL); m->account_id = atoi(data);
SQL->GetData(inter->sql_handle, 1, &data, NULL); m->char_id = atoi(data);
SQL->GetData(inter->sql_handle, 2, &data, NULL); m->hair = atoi(data);
SQL->GetData(inter->sql_handle, 3, &data, NULL); m->hair_color = atoi(data);
SQL->GetData(inter->sql_handle, 4, &data, NULL); m->gender = atoi(data);
SQL->GetData(inter->sql_handle, 5, &data, NULL); m->class_ = atoi(data);
SQL->GetData(inter->sql_handle, 6, &data, NULL); m->lv = atoi(data);
SQL->GetData(inter->sql_handle, 7, &data, NULL); m->exp = strtoull(data, NULL, 10);
SQL->GetData(inter->sql_handle, 8, &data, NULL); m->exp_payper = (unsigned int)atoi(data);
SQL->GetData(inter->sql_handle, 9, &data, NULL); m->online = atoi(data);
SQL->GetData(inter->sql_handle, 10, &data, NULL); m->position = atoi(data);
if( m->position >= MAX_GUILDPOSITION ) // Fix reduction of MAX_GUILDPOSITION [PoW]
m->position = MAX_GUILDPOSITION - 1;
SQL->GetData(inter->sql_handle, 11, &data, &len); memcpy(m->name, data, min(len, NAME_LENGTH));
m->modified = GS_MEMBER_UNMODIFIED;
}
//printf("- Read guild_position %d from sql \n",guild_id);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT `position`,`name`,`mode`,`exp_mode` FROM `%s` WHERE `guild_id`='%d'", guild_position_db, guild_id) )
{
Sql_ShowDebug(inter->sql_handle);
aFree(g);
return NULL;
}
while( SQL_SUCCESS == SQL->NextRow(inter->sql_handle) )
{
int position;
struct guild_position *pos;
SQL->GetData(inter->sql_handle, 0, &data, NULL); position = atoi(data);
if( position < 0 || position >= MAX_GUILDPOSITION )
continue;// invalid position
pos = &g->position[position];
SQL->GetData(inter->sql_handle, 1, &data, &len); memcpy(pos->name, data, min(len, NAME_LENGTH));
SQL->GetData(inter->sql_handle, 2, &data, NULL); pos->mode = atoi(data);
SQL->GetData(inter->sql_handle, 3, &data, NULL); pos->exp_mode = atoi(data);
pos->modified = GS_POSITION_UNMODIFIED;
}
//printf("- Read guild_alliance %d from sql \n",guild_id);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT `opposition`,`alliance_id`,`name` FROM `%s` WHERE `guild_id`='%d'", guild_alliance_db, guild_id) )
{
Sql_ShowDebug(inter->sql_handle);
aFree(g);
return NULL;
}
for( i = 0; i < MAX_GUILDALLIANCE && SQL_SUCCESS == SQL->NextRow(inter->sql_handle); ++i )
{
struct guild_alliance* a = &g->alliance[i];
SQL->GetData(inter->sql_handle, 0, &data, NULL); a->opposition = atoi(data);
SQL->GetData(inter->sql_handle, 1, &data, NULL); a->guild_id = atoi(data);
SQL->GetData(inter->sql_handle, 2, &data, &len); memcpy(a->name, data, min(len, NAME_LENGTH));
}
//printf("- Read guild_expulsion %d from sql \n",guild_id);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT `account_id`,`name`,`mes` FROM `%s` WHERE `guild_id`='%d'", guild_expulsion_db, guild_id) )
{
Sql_ShowDebug(inter->sql_handle);
aFree(g);
return NULL;
}
for( i = 0; i < MAX_GUILDEXPULSION && SQL_SUCCESS == SQL->NextRow(inter->sql_handle); ++i )
{
struct guild_expulsion *e = &g->expulsion[i];
SQL->GetData(inter->sql_handle, 0, &data, NULL); e->account_id = atoi(data);
SQL->GetData(inter->sql_handle, 1, &data, &len); memcpy(e->name, data, min(len, NAME_LENGTH));
SQL->GetData(inter->sql_handle, 2, &data, &len); memcpy(e->mes, data, min(len, sizeof(e->mes)));
}
//printf("- Read guild_skill %d from sql \n",guild_id);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT `id`,`lv` FROM `%s` WHERE `guild_id`='%d' ORDER BY `id`", guild_skill_db, guild_id) )
{
Sql_ShowDebug(inter->sql_handle);
aFree(g);
return NULL;
}
for (i = 0; i < MAX_GUILDSKILL; i++) {
//Skill IDs must always be initialized. [Skotlex]
g->skill[i].id = i + GD_SKILLBASE;
}
while( SQL_SUCCESS == SQL->NextRow(inter->sql_handle) )
{
int id;
SQL->GetData(inter->sql_handle, 0, &data, NULL); id = atoi(data) - GD_SKILLBASE;
if( id < 0 || id >= MAX_GUILDSKILL )
continue;// invalid guild skill
SQL->GetData(inter->sql_handle, 1, &data, NULL); g->skill[id].lv = atoi(data);
}
SQL->FreeResult(inter->sql_handle);
idb_put(inter_guild->guild_db, guild_id, g); //Add to cache
g->save_flag |= GS_REMOVE; //But set it to be removed, in case it is not needed for long.
if (chr->show_save_log)
ShowInfo("Guild loaded (%d - %s)\n", guild_id, g->name);
return g;
}
// `guild_castle` (`castle_id`, `guild_id`, `economy`, `defense`, `triggerE`, `triggerD`, `nextTime`, `payTime`, `createTime`, `visibleC`, `visibleG0`, `visibleG1`, `visibleG2`, `visibleG3`, `visibleG4`, `visibleG5`, `visibleG6`, `visibleG7`)
int inter_guild_castle_tosql(struct guild_castle *gc)
{
StringBuf buf;
int i;
nullpo_ret(gc);
StrBuf->Init(&buf);
StrBuf->Printf(&buf, "REPLACE INTO `%s` SET `castle_id`='%d', `guild_id`='%d', `economy`='%d', `defense`='%d', "
"`triggerE`='%d', `triggerD`='%d', `nextTime`='%d', `payTime`='%d', `createTime`='%d', `visibleC`='%d'",
guild_castle_db, gc->castle_id, gc->guild_id, gc->economy, gc->defense,
gc->triggerE, gc->triggerD, gc->nextTime, gc->payTime, gc->createTime, gc->visibleC);
for (i = 0; i < MAX_GUARDIANS; ++i)
StrBuf->Printf(&buf, ", `visibleG%d`='%d'", i, gc->guardian[i].visible);
if (SQL_ERROR == SQL->QueryStr(inter->sql_handle, StrBuf->Value(&buf)))
Sql_ShowDebug(inter->sql_handle);
else if (chr->show_save_log)
ShowInfo("Saved guild castle (%d)\n", gc->castle_id);
StrBuf->Destroy(&buf);
return 0;
}
// Read guild_castle from SQL
struct guild_castle* inter_guild_castle_fromsql(int castle_id)
{
char *data;
int i;
StringBuf buf;
struct guild_castle *gc = idb_get(inter_guild->castle_db, castle_id);
if (gc != NULL)
return gc;
StrBuf->Init(&buf);
StrBuf->AppendStr(&buf, "SELECT `castle_id`, `guild_id`, `economy`, `defense`, `triggerE`, "
"`triggerD`, `nextTime`, `payTime`, `createTime`, `visibleC`");
for (i = 0; i < MAX_GUARDIANS; ++i)
StrBuf->Printf(&buf, ", `visibleG%d`", i);
StrBuf->Printf(&buf, " FROM `%s` WHERE `castle_id`='%d'", guild_castle_db, castle_id);
if (SQL_ERROR == SQL->QueryStr(inter->sql_handle, StrBuf->Value(&buf))) {
Sql_ShowDebug(inter->sql_handle);
StrBuf->Destroy(&buf);
return NULL;
}
StrBuf->Destroy(&buf);
CREATE(gc, struct guild_castle, 1);
gc->castle_id = castle_id;
if (SQL_SUCCESS == SQL->NextRow(inter->sql_handle)) {
SQL->GetData(inter->sql_handle, 1, &data, NULL); gc->guild_id = atoi(data);
SQL->GetData(inter->sql_handle, 2, &data, NULL); gc->economy = atoi(data);
SQL->GetData(inter->sql_handle, 3, &data, NULL); gc->defense = atoi(data);
SQL->GetData(inter->sql_handle, 4, &data, NULL); gc->triggerE = atoi(data);
SQL->GetData(inter->sql_handle, 5, &data, NULL); gc->triggerD = atoi(data);
SQL->GetData(inter->sql_handle, 6, &data, NULL); gc->nextTime = atoi(data);
SQL->GetData(inter->sql_handle, 7, &data, NULL); gc->payTime = atoi(data);
SQL->GetData(inter->sql_handle, 8, &data, NULL); gc->createTime = atoi(data);
SQL->GetData(inter->sql_handle, 9, &data, NULL); gc->visibleC = atoi(data);
for (i = 10; i < 10+MAX_GUARDIANS; i++) {
SQL->GetData(inter->sql_handle, i, &data, NULL); gc->guardian[i-10].visible = atoi(data);
}
}
SQL->FreeResult(inter->sql_handle);
idb_put(inter_guild->castle_db, castle_id, gc);
if (chr->show_save_log)
ShowInfo("Loaded guild castle (%d - guild %d)\n", castle_id, gc->guild_id);
return gc;
}
// Read exp_guild.txt
bool inter_guild_exp_parse_row(char* split[], int column, int current) {
int64 exp = strtoll(split[0], NULL, 10);
nullpo_retr(true, split);
if (exp < 0 || exp >= UINT_MAX) {
ShowError("exp_guild: Invalid exp %"PRId64" (valid range: 0 - %u) at line %d\n", exp, UINT_MAX, current);
return false;
}
inter_guild->exp[current] = (unsigned int)exp;
return true;
}
int inter_guild_CharOnline(int char_id, int guild_id) {
struct guild *g;
int i;
if (guild_id == -1) {
//Get guild_id from the database
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT guild_id FROM `%s` WHERE char_id='%d'", char_db, char_id) )
{
Sql_ShowDebug(inter->sql_handle);
return 0;
}
if( SQL_SUCCESS == SQL->NextRow(inter->sql_handle) )
{
char* data;
SQL->GetData(inter->sql_handle, 0, &data, NULL);
guild_id = atoi(data);
}
else
{
guild_id = 0;
}
SQL->FreeResult(inter->sql_handle);
}
if (guild_id == 0)
return 0; //No guild...
g = inter_guild->fromsql(guild_id);
if(!g) {
ShowError("Character %d's guild %d not found!\n", char_id, guild_id);
return 0;
}
//Member has logged in before saving, tell saver not to delete
if(g->save_flag & GS_REMOVE)
g->save_flag &= ~GS_REMOVE;
//Set member online
ARR_FIND( 0, g->max_member, i, g->member[i].char_id == char_id );
if( i < g->max_member )
{
g->member[i].online = 1;
g->member[i].modified = GS_MEMBER_MODIFIED;
}
return 1;
}
int inter_guild_CharOffline(int char_id, int guild_id)
{
struct guild *g=NULL;
int online_count, i;
if (guild_id == -1)
{
//Get guild_id from the database
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT guild_id FROM `%s` WHERE char_id='%d'", char_db, char_id) )
{
Sql_ShowDebug(inter->sql_handle);
return 0;
}
if( SQL_SUCCESS == SQL->NextRow(inter->sql_handle) )
{
char* data;
SQL->GetData(inter->sql_handle, 0, &data, NULL);
guild_id = atoi(data);
}
else
{
guild_id = 0;
}
SQL->FreeResult(inter->sql_handle);
}
if (guild_id == 0)
return 0; //No guild...
//Character has a guild, set character offline and check if they were the only member online
g = inter_guild->fromsql(guild_id);
if (g == NULL) //Guild not found?
return 0;
//Set member offline
ARR_FIND( 0, g->max_member, i, g->member[i].char_id == char_id );
if( i < g->max_member )
{
g->member[i].online = 0;
g->member[i].modified = GS_MEMBER_MODIFIED;
}
online_count = 0;
for( i = 0; i < g->max_member; i++ )
if( g->member[i].online )
online_count++;
// Remove guild from memory if no players online
if( online_count == 0 )
g->save_flag |= GS_REMOVE;
return 1;
}
// Initialize guild sql
int inter_guild_sql_init(void)
{
//Initialize the guild cache
inter_guild->guild_db= idb_alloc(DB_OPT_RELEASE_DATA);
inter_guild->castle_db = idb_alloc(DB_OPT_RELEASE_DATA);
//Read exp file
sv->readdb("db", DBPATH"exp_guild.txt", ',', 1, 1, MAX_GUILDLEVEL, inter_guild->exp_parse_row);
timer->add_func_list(inter_guild->save_timer, "inter_guild->save_timer");
timer->add(timer->gettick() + 10000, inter_guild->save_timer, 0, 0);
return 0;
}
/**
* @see DBApply
*/
int inter_guild_db_final(union DBKey key, struct DBData *data, va_list ap)
{
struct guild *g = DB->data2ptr(data);
nullpo_ret(g);
if (g->save_flag&GS_MASK) {
inter_guild->tosql(g, g->save_flag&GS_MASK);
return 1;
}
return 0;
}
void inter_guild_sql_final(void)
{
inter_guild->guild_db->destroy(inter_guild->guild_db, inter_guild->db_final);
db_destroy(inter_guild->castle_db);
return;
}
// Get guild_id by its name. Returns 0 if not found, -1 on error.
int inter_guild_search_guildname(const char *str)
{
int guild_id;
char esc_name[NAME_LENGTH*2+1];
nullpo_retr(-1, str);
SQL->EscapeStringLen(inter->sql_handle, esc_name, str, safestrnlen(str, NAME_LENGTH));
//Lookup guilds with the same name
if( SQL_ERROR == SQL->Query(inter->sql_handle, "SELECT guild_id FROM `%s` WHERE name='%s'", guild_db, esc_name) )
{
Sql_ShowDebug(inter->sql_handle);
return -1;
}
if( SQL_SUCCESS == SQL->NextRow(inter->sql_handle) )
{
char* data;
SQL->GetData(inter->sql_handle, 0, &data, NULL);
guild_id = atoi(data);
}
else
{
guild_id = 0;
}
SQL->FreeResult(inter->sql_handle);
return guild_id;
}
// Check if guild is empty
static bool inter_guild_check_empty(struct guild *g)
{
int i;
nullpo_ret(g);
ARR_FIND( 0, g->max_member, i, g->member[i].account_id > 0 );
if( i < g->max_member)
return false; // not empty
//Let the calling function handle the guild removal in case they need
//to do something else with it before freeing the data. [Skotlex]
return true;
}
unsigned int inter_guild_nextexp(int level) {
if (level == 0)
return 1;
if (level <= 0 || level > MAX_GUILDLEVEL)
return 0;
return inter_guild->exp[level-1];
}
int inter_guild_checkskill(struct guild *g, int id)
{
int idx = id - GD_SKILLBASE;
nullpo_ret(g);
if(idx < 0 || idx >= MAX_GUILDSKILL)
return 0;
return g->skill[idx].lv;
}
int inter_guild_calcinfo(struct guild *g)
{
int i,c;
unsigned int nextexp;
struct guild before = *g; // Save guild current values
nullpo_ret(g);
if(g->guild_lv<=0)
g->guild_lv = 1;
nextexp = inter_guild->nextexp(g->guild_lv);
// Consume guild exp and increase guild level
while(g->exp >= nextexp && nextexp > 0) { // nextexp would be 0 if g->guild_lv was >= MAX_GUILDLEVEL
g->exp-=nextexp;
g->guild_lv++;
g->skill_point++;
nextexp = inter_guild->nextexp(g->guild_lv);
}
// Save next exp step
g->next_exp = nextexp;
// Set the max number of members, Guild Extension skill - currently adds 6 to max per skill lv.
g->max_member = BASE_GUILD_SIZE + inter_guild->checkskill(g, GD_EXTENSION) * 6;
if(g->max_member > MAX_GUILD)
{
ShowError("Guild %d:%s has capacity for too many guild members (%d), max supported is %d\n", g->guild_id, g->name, g->max_member, MAX_GUILD);
g->max_member = MAX_GUILD;
}
// Compute the guild average level level
g->average_lv=0;
g->connect_member=0;
for(i=c=0;i<g->max_member;i++)
{
if(g->member[i].account_id>0)
{
if (g->member[i].lv >= 0)
{
g->average_lv+=g->member[i].lv;
c++;
}
else
{
ShowWarning("Guild %d:%s, member %d:%s has an invalid level %d\n", g->guild_id, g->name, g->member[i].char_id, g->member[i].name, g->member[i].lv);
}
if(g->member[i].online)
g->connect_member++;
}
}
if(c)
g->average_lv /= c;
// Check if guild stats has change
if (g->max_member != before.max_member || g->guild_lv != before.guild_lv || g->skill_point != before.skill_point) {
g->save_flag |= GS_LEVEL;
mapif->guild_info(-1,g);
return 1;
}
return 0;
}
//-------------------------------------------------------------------
// Packet sent to map server
int mapif_guild_created(int fd, int account_id, struct guild *g)
{
WFIFOHEAD(fd, 10);
WFIFOW(fd,0)=0x3830;
WFIFOL(fd,2)=account_id;
if(g != NULL)
{
WFIFOL(fd,6)=g->guild_id;
ShowInfo("int_guild: Guild created (%d - %s)\n",g->guild_id,g->name);
} else
WFIFOL(fd,6)=0;
WFIFOSET(fd,10);
return 0;
}
// Guild not found
int mapif_guild_noinfo(int fd, int guild_id)
{
unsigned char buf[12];
WBUFW(buf,0)=0x3831;
WBUFW(buf,2)=8;
WBUFL(buf,4)=guild_id;
ShowWarning("int_guild: info not found %d\n",guild_id);
if(fd<0)
mapif->sendall(buf,8);
else
mapif->send(fd,buf,8);
return 0;
}
// Send guild info
int mapif_guild_info(int fd, struct guild *g)
{
unsigned char buf[8+sizeof(struct guild)];
nullpo_ret(g);
WBUFW(buf,0)=0x3831;
WBUFW(buf,2)=4+sizeof(struct guild);
memcpy(buf+4,g,sizeof(struct guild));
if(fd<0)
mapif->sendall(buf,WBUFW(buf,2));
else
mapif->send(fd,buf,WBUFW(buf,2));
return 0;
}
// ACK member add
int mapif_guild_memberadded(int fd, int guild_id, int account_id, int char_id, int flag)
{
WFIFOHEAD(fd, 15);
WFIFOW(fd,0)=0x3832;
WFIFOL(fd,2)=guild_id;
WFIFOL(fd,6)=account_id;
WFIFOL(fd,10)=char_id;
WFIFOB(fd,14)=flag;
WFIFOSET(fd,15);
return 0;
}
// ACK member leave
int mapif_guild_withdraw(int guild_id,int account_id,int char_id,int flag, const char *name, const char *mes)
{
unsigned char buf[55+NAME_LENGTH];
nullpo_ret(name);
nullpo_ret(mes);
WBUFW(buf, 0)=0x3834;
WBUFL(buf, 2)=guild_id;
WBUFL(buf, 6)=account_id;
WBUFL(buf,10)=char_id;
WBUFB(buf,14)=flag;
memcpy(WBUFP(buf,15),mes,40);
memcpy(WBUFP(buf,55),name,NAME_LENGTH);
mapif->sendall(buf,55+NAME_LENGTH);
ShowInfo("int_guild: guild withdraw (%d - %d: %s - %s)\n",guild_id,account_id,name,mes);
return 0;
}
// Send short member's info
int mapif_guild_memberinfoshort(struct guild *g, int idx)
{
unsigned char buf[19];
nullpo_ret(g);
Assert_ret(idx >= 0 && idx < MAX_GUILD);
WBUFW(buf, 0)=0x3835;
WBUFL(buf, 2)=g->guild_id;
WBUFL(buf, 6)=g->member[idx].account_id;
WBUFL(buf,10)=g->member[idx].char_id;
WBUFB(buf,14)=(unsigned char)g->member[idx].online;
WBUFW(buf,15)=g->member[idx].lv;
WBUFW(buf,17)=g->member[idx].class_;
mapif->sendall(buf,19);
return 0;
}
// Send guild broken
int mapif_guild_broken(int guild_id, int flag)
{
unsigned char buf[7];
WBUFW(buf,0)=0x3836;
WBUFL(buf,2)=guild_id;
WBUFB(buf,6)=flag;
mapif->sendall(buf,7);
ShowInfo("int_guild: Guild broken (%d)\n",guild_id);
return 0;
}
// Send guild message
int mapif_guild_message(int guild_id, int account_id, const char *mes, int len, int sfd)
{
unsigned char buf[512];
nullpo_ret(mes);
if (len > 500)
len = 500;
WBUFW(buf,0)=0x3837;
WBUFW(buf,2)=len+12;
WBUFL(buf,4)=guild_id;
WBUFL(buf,8)=account_id;
memcpy(WBUFP(buf,12),mes,len);
mapif->sendallwos(sfd, buf,len+12);
return 0;
}
// Send basic info
int mapif_guild_basicinfochanged(int guild_id, int type, const void *data, int len)
{
unsigned char buf[2048];
nullpo_ret(data);
if (len > 2038)
len = 2038;
WBUFW(buf, 0)=0x3839;
WBUFW(buf, 2)=len+10;
WBUFL(buf, 4)=guild_id;
WBUFW(buf, 8)=type;
memcpy(WBUFP(buf,10),data,len);
mapif->sendall(buf,len+10);
return 0;
}
// Send member info
int mapif_guild_memberinfochanged(int guild_id, int account_id, int char_id, int type, const void *data, int len)
{
unsigned char buf[2048];
nullpo_ret(data);
if (len > 2030)
len = 2030;
WBUFW(buf, 0)=0x383a;
WBUFW(buf, 2)=len+18;
WBUFL(buf, 4)=guild_id;
WBUFL(buf, 8)=account_id;
WBUFL(buf,12)=char_id;
WBUFW(buf,16)=type;
memcpy(WBUFP(buf,18),data,len);
mapif->sendall(buf,len+18);
return 0;
}
// ACK guild skill up
int mapif_guild_skillupack(int guild_id, uint16 skill_id, int account_id)
{
unsigned char buf[14];
WBUFW(buf, 0)=0x383c;
WBUFL(buf, 2)=guild_id;
WBUFL(buf, 6)=skill_id;
WBUFL(buf,10)=account_id;
mapif->sendall(buf,14);
return 0;
}
// ACK guild alliance
int mapif_guild_alliance(int guild_id1, int guild_id2, int account_id1, int account_id2, int flag, const char *name1, const char *name2)
{
unsigned char buf[19+2*NAME_LENGTH];
nullpo_ret(name1);
nullpo_ret(name2);
WBUFW(buf, 0)=0x383d;
WBUFL(buf, 2)=guild_id1;
WBUFL(buf, 6)=guild_id2;
WBUFL(buf,10)=account_id1;
WBUFL(buf,14)=account_id2;
WBUFB(buf,18)=flag;
memcpy(WBUFP(buf,19),name1,NAME_LENGTH);
memcpy(WBUFP(buf,19+NAME_LENGTH),name2,NAME_LENGTH);
mapif->sendall(buf,19+2*NAME_LENGTH);
return 0;
}
// Send a guild position desc
int mapif_guild_position(struct guild *g, int idx)
{
unsigned char buf[12 + sizeof(struct guild_position)];
nullpo_ret(g);
Assert_ret(idx >= 0 && idx < MAX_GUILDPOSITION);
WBUFW(buf,0)=0x383b;
WBUFW(buf,2)=sizeof(struct guild_position)+12;
WBUFL(buf,4)=g->guild_id;
WBUFL(buf,8)=idx;
memcpy(WBUFP(buf,12),&g->position[idx],sizeof(struct guild_position));
mapif->sendall(buf,WBUFW(buf,2));
return 0;
}
// Send the guild notice
int mapif_guild_notice(struct guild *g)
{
unsigned char buf[256];
nullpo_ret(g);
WBUFW(buf,0)=0x383e;
WBUFL(buf,2)=g->guild_id;
memcpy(WBUFP(buf,6),g->mes1,MAX_GUILDMES1);
memcpy(WBUFP(buf,66),g->mes2,MAX_GUILDMES2);
mapif->sendall(buf,186);
return 0;
}
// Send emblem data
int mapif_guild_emblem(struct guild *g)
{
unsigned char buf[12 + sizeof(g->emblem_data)];
nullpo_ret(g);
WBUFW(buf,0)=0x383f;
WBUFW(buf,2)=g->emblem_len+12;
WBUFL(buf,4)=g->guild_id;
WBUFL(buf,8)=g->emblem_id;
memcpy(WBUFP(buf,12),g->emblem_data,g->emblem_len);
mapif->sendall(buf,WBUFW(buf,2));
return 0;
}
int mapif_guild_master_changed(struct guild *g, int aid, int cid)
{
unsigned char buf[14];
nullpo_ret(g);
WBUFW(buf,0)=0x3843;
WBUFL(buf,2)=g->guild_id;
WBUFL(buf,6)=aid;
WBUFL(buf,10)=cid;
mapif->sendall(buf,14);
return 0;
}
int mapif_guild_castle_dataload(int fd, int sz, const int *castle_ids)
{
struct guild_castle *gc = NULL;
int num = (sz - 4) / sizeof(int);
int len = 4 + num * sizeof(*gc);
int i;
nullpo_ret(castle_ids);
WFIFOHEAD(fd, len);
WFIFOW(fd, 0) = 0x3840;
WFIFOW(fd, 2) = len;
for (i = 0; i < num; i++) {
gc = inter_guild->castle_fromsql(*(castle_ids++));
memcpy(WFIFOP(fd, 4 + i * sizeof(*gc)), gc, sizeof(*gc));
}
WFIFOSET(fd, len);
return 0;
}
//-------------------------------------------------------------------
// Packet received from map server
// Guild creation request
int mapif_parse_CreateGuild(int fd, int account_id, const char *name, const struct guild_member *master)
{
struct guild *g;
int i=0;
#ifdef NOISY
ShowInfo("Creating Guild (%s)\n", name);
#endif
nullpo_ret(name);
nullpo_ret(master);
if(inter_guild->search_guildname(name) != 0){
ShowInfo("int_guild: guild with same name exists [%s]\n",name);
mapif->guild_created(fd,account_id,NULL);
return 0;
}
// Check Authorized letters/symbols in the name of the character
if (char_name_option == 1) { // only letters/symbols in char_name_letters are authorized
for (i = 0; i < NAME_LENGTH && name[i]; i++)
if (strchr(char_name_letters, name[i]) == NULL) {
mapif->guild_created(fd,account_id,NULL);
return 0;
}
} else if (char_name_option == 2) { // letters/symbols in char_name_letters are forbidden
for (i = 0; i < NAME_LENGTH && name[i]; i++)
if (strchr(char_name_letters, name[i]) != NULL) {
mapif->guild_created(fd,account_id,NULL);
return 0;
}
}
g = (struct guild *)aMalloc(sizeof(struct guild));
memset(g,0,sizeof(struct guild));
memcpy(g->name,name,NAME_LENGTH);
memcpy(g->master,master->name,NAME_LENGTH);
memcpy(&g->member[0],master,sizeof(struct guild_member));
g->member[0].modified = GS_MEMBER_MODIFIED;
// Set default positions
g->position[0].mode = GPERM_ALL;
strcpy(g->position[0].name,"GuildMaster");
strcpy(g->position[MAX_GUILDPOSITION-1].name,"Newbie");
g->position[0].modified = g->position[MAX_GUILDPOSITION-1].modified = GS_POSITION_MODIFIED;
for(i=1;i<MAX_GUILDPOSITION-1;i++) {
sprintf(g->position[i].name,"Position %d",i+1);
g->position[i].modified = GS_POSITION_MODIFIED;
}
// Initialize guild property
g->max_member = BASE_GUILD_SIZE;
g->average_lv = master->lv;
g->connect_member = 1;
g->guild_lv = 1;
for(i=0;i<MAX_GUILDSKILL;i++)
g->skill[i].id=i + GD_SKILLBASE;
g->guild_id= -1; //Request to create guild.
// Create the guild
if (!inter_guild->tosql(g,GS_BASIC|GS_POSITION|GS_SKILL|GS_MEMBER)) {
//Failed to Create guild....
ShowError("Failed to create Guild %s (Guild Master: %s)\n", g->name, g->master);
mapif->guild_created(fd,account_id,NULL);
aFree(g);
return 0;
}
ShowInfo("Created Guild %d - %s (Guild Master: %s)\n", g->guild_id, g->name, g->master);
//Add to cache
idb_put(inter_guild->guild_db, g->guild_id, g);
// Report to client
mapif->guild_created(fd,account_id,g);
mapif->guild_info(fd,g);
if (inter->enable_logs)
inter->log("guild %s (id=%d) created by master %s (id=%d)\n",
name, g->guild_id, master->name, master->account_id);
return 0;
}
// Return guild info to client
int mapif_parse_GuildInfo(int fd, int guild_id)
{
struct guild * g = inter_guild->fromsql(guild_id); //We use this because on start-up the info of castle-owned guilds is required. [Skotlex]
if(g)
{
if (!inter_guild->calcinfo(g))
mapif->guild_info(fd,g);
}
else
mapif->guild_noinfo(fd,guild_id); // Failed to load info
return 0;
}
// Add member to guild
int mapif_parse_GuildAddMember(int fd, int guild_id, const struct guild_member *m)
{
struct guild * g;
int i;
nullpo_ret(m);
g = inter_guild->fromsql(guild_id);
if(g==NULL){
mapif->guild_memberadded(fd,guild_id,m->account_id,m->char_id,1); // 1: Failed to add
return 0;
}
// Find an empty slot
for(i=0;i<g->max_member;i++)
{
if(g->member[i].account_id==0)
{
memcpy(&g->member[i],m,sizeof(struct guild_member));
g->member[i].modified = (GS_MEMBER_NEW | GS_MEMBER_MODIFIED);
mapif->guild_memberadded(fd,guild_id,m->account_id,m->char_id,0); // 0: success
if (!inter_guild->calcinfo(g)) //Send members if it was not invoked.
mapif->guild_info(-1,g);
g->save_flag |= GS_MEMBER;
if (g->save_flag&GS_REMOVE)
g->save_flag&=~GS_REMOVE;
return 0;
}
}
mapif->guild_memberadded(fd,guild_id,m->account_id,m->char_id,1); // 1: Failed to add
return 0;
}
// Delete member from guild
int mapif_parse_GuildLeave(int fd, int guild_id, int account_id, int char_id, int flag, const char *mes)
{
int i;
struct guild* g = inter_guild->fromsql(guild_id);
if( g == NULL )
{
// Unknown guild, just update the player
if( SQL_ERROR == SQL->Query(inter->sql_handle, "UPDATE `%s` SET `guild_id`='0' WHERE `account_id`='%d' AND `char_id`='%d'", char_db, account_id, char_id) )
Sql_ShowDebug(inter->sql_handle);
// mapif->guild_withdraw(guild_id,account_id,char_id,flag,g->member[i].name,mes);
return 0;
}
nullpo_ret(mes);
// Find the member
ARR_FIND( 0, g->max_member, i, g->member[i].account_id == account_id && g->member[i].char_id == char_id );
if( i == g->max_member )
{
//TODO
return 0;
}
if (flag) {
// Write expulsion reason
// Find an empty slot
int j;
ARR_FIND( 0, MAX_GUILDEXPULSION, j, g->expulsion[j].account_id == 0 );
if( j == MAX_GUILDEXPULSION )
{
// Expulsion list is full, flush the oldest one
for( j = 0; j < MAX_GUILDEXPULSION - 1; j++ )
g->expulsion[j] = g->expulsion[j+1];
j = MAX_GUILDEXPULSION-1;
}
// Save the expulsion entry
g->expulsion[j].account_id = account_id;
safestrncpy(g->expulsion[j].name, g->member[i].name, NAME_LENGTH);
safestrncpy(g->expulsion[j].mes, mes, 40);
}
mapif->guild_withdraw(guild_id,account_id,char_id,flag,g->member[i].name,mes);
inter_guild->removemember_tosql(g->member[i].account_id,g->member[i].char_id);
memset(&g->member[i],0,sizeof(struct guild_member));
if( inter_guild->check_empty(g) )
mapif->parse_BreakGuild(-1,guild_id); //Break the guild.
else {
//Update member info.
if (!inter_guild->calcinfo(g))
mapif->guild_info(fd,g);
g->save_flag |= GS_EXPULSION;
}
return 0;
}
// Change member info
int mapif_parse_GuildChangeMemberInfoShort(int fd, int guild_id, int account_id, int char_id, int online, int lv, int class_)
{
// Could speed up by manipulating only guild_member
struct guild * g;
int i,sum,c;
int prev_count, prev_alv;
g = inter_guild->fromsql(guild_id);
if(g==NULL)
return 0;
ARR_FIND( 0, g->max_member, i, g->member[i].account_id == account_id && g->member[i].char_id == char_id );
if( i < g->max_member )
{
g->member[i].online = online;
g->member[i].lv = lv;
g->member[i].class_ = class_;
g->member[i].modified = GS_MEMBER_MODIFIED;
mapif->guild_memberinfoshort(g,i);
}
prev_count = g->connect_member;
prev_alv = g->average_lv;
g->average_lv = 0;
g->connect_member = 0;
c = 0;
sum = 0;
for( i = 0; i < g->max_member; i++ )
{
if( g->member[i].account_id > 0 )
{
sum += g->member[i].lv;
c++;
}
if( g->member[i].online )
g->connect_member++;
}
if( c ) // this check should always succeed...
{
g->average_lv = sum / c;
if( g->connect_member != prev_count || g->average_lv != prev_alv )
g->save_flag |= GS_CONNECT;
if( g->save_flag & GS_REMOVE )
g->save_flag &= ~GS_REMOVE;
}
g->save_flag |= GS_MEMBER; //Update guild member data
return 0;
}
// BreakGuild
int mapif_parse_BreakGuild(int fd, int guild_id)
{
struct guild * g;
g = inter_guild->fromsql(guild_id);
if(g==NULL)
return 0;
// Delete guild from sql
//printf("- Delete guild %d from guild\n",guild_id);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_db, guild_id) )
Sql_ShowDebug(inter->sql_handle);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_member_db, guild_id) )
Sql_ShowDebug(inter->sql_handle);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_castle_db, guild_id) )
Sql_ShowDebug(inter->sql_handle);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_storage_db, guild_id) )
Sql_ShowDebug(inter->sql_handle);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d' OR `alliance_id` = '%d'", guild_alliance_db, guild_id, guild_id) )
Sql_ShowDebug(inter->sql_handle);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_position_db, guild_id) )
Sql_ShowDebug(inter->sql_handle);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_skill_db, guild_id) )
Sql_ShowDebug(inter->sql_handle);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_expulsion_db, guild_id) )
Sql_ShowDebug(inter->sql_handle);
//printf("- Update guild %d of char\n",guild_id);
if( SQL_ERROR == SQL->Query(inter->sql_handle, "UPDATE `%s` SET `guild_id`='0' WHERE `guild_id`='%d'", char_db, guild_id) )
Sql_ShowDebug(inter->sql_handle);
mapif->guild_broken(guild_id,0);
if (inter->enable_logs)
inter->log("guild %s (id=%d) broken\n", g->name, guild_id);
//Remove the guild from memory. [Skotlex]
idb_remove(inter_guild->guild_db, guild_id);
return 0;
}
// Forward Guild message to others map servers
int mapif_parse_GuildMessage(int fd, int guild_id, int account_id, const char *mes, int len)
{
return mapif->guild_message(guild_id,account_id,mes,len, fd);
}
/**
* Changes basic guild information
* The types are available in mmo.h::guild_basic_info
**/
int mapif_parse_GuildBasicInfoChange(int fd, int guild_id, int type, const void *data, int len) {
struct guild *g;
struct guild_skill gd_skill;
short value;
g = inter_guild->fromsql(guild_id);
if( g == NULL )
return 0;
nullpo_ret(data);
switch(type) {
case GBI_EXP:
value = *((const int16 *)data);
if( value < 0 && abs(value) > g->exp )
return 0;
g->exp += value;
inter_guild->calcinfo(g);
break;
case GBI_GUILDLV:
value = *((const int16 *)data);
if (value > 0 && g->guild_lv + value <= MAX_GUILDLEVEL) {
g->guild_lv += value;
g->skill_point += value;
} else if (value < 0 && g->guild_lv + value >= 1)
g->guild_lv += value;
break;
case GBI_SKILLPOINT:
value = *((const int16 *)data);
if( g->skill_point+value < 0 )
return 0;
g->skill_point += value;
break;
case GBI_SKILLLV:
gd_skill = *((const struct guild_skill*)data);
memcpy(&(g->skill[(gd_skill.id - GD_SKILLBASE)]), &gd_skill, sizeof(gd_skill));
if( !inter_guild->calcinfo(g) )
mapif->guild_info(-1,g);
g->save_flag |= GS_SKILL;
mapif->guild_skillupack(g->guild_id, gd_skill.id, 0);
break;
default:
ShowError("int_guild: GuildBasicInfoChange: Unknown type %d, see mmo.h::guild_basic_info for more information\n",type);
return 0;
}
mapif->guild_info(-1,g);
g->save_flag |= GS_LEVEL;
// Information is already sent in mapif->guild_info
//mapif->guild_basicinfochanged(guild_id,type,data,len);
return 0;
}
// Modification of the guild
int mapif_parse_GuildMemberInfoChange(int fd, int guild_id, int account_id, int char_id, int type, const char *data, int len)
{
// Could make some improvement in speed, because only change guild_member
int i;
struct guild * g;
nullpo_ret(data);
g = inter_guild->fromsql(guild_id);
if(g==NULL)
return 0;
// Search the member
for (i = 0; i < g->max_member; i++) {
if (g->member[i].account_id == account_id && g->member[i].char_id==char_id)
break;
}
// Not Found
if(i==g->max_member){
ShowWarning("int_guild: GuildMemberChange: Not found %d,%d in guild (%d - %s)\n",
account_id,char_id,guild_id,g->name);
return 0;
}
switch(type)
{
case GMI_POSITION:
{
g->member[i].position = *(const short *)data;
g->member[i].modified = GS_MEMBER_MODIFIED;
mapif->guild_memberinfochanged(guild_id,account_id,char_id,type,data,len);
g->save_flag |= GS_MEMBER;
break;
}
case GMI_EXP:
{
uint64 old_exp = g->member[i].exp;
g->member[i].exp = *(const uint64 *)data;
g->member[i].modified = GS_MEMBER_MODIFIED;
if (g->member[i].exp > old_exp) {
uint64 exp = g->member[i].exp - old_exp;
// Compute gained exp
if (guild_exp_rate != 100)
exp = exp*guild_exp_rate/100;
// Update guild exp
if (exp > UINT64_MAX - g->exp)
g->exp = UINT64_MAX;
else
g->exp+=exp;
inter_guild->calcinfo(g);
mapif->guild_basicinfochanged(guild_id,GBI_EXP,&g->exp,sizeof(g->exp));
g->save_flag |= GS_LEVEL;
}
mapif->guild_memberinfochanged(guild_id,account_id,char_id,type,data,len);
g->save_flag |= GS_MEMBER;
break;
}
case GMI_HAIR:
{
g->member[i].hair = *(const short *)data;
g->member[i].modified = GS_MEMBER_MODIFIED;
mapif->guild_memberinfochanged(guild_id,account_id,char_id,type,data,len);
g->save_flag |= GS_MEMBER; //Save new data.
break;
}
case GMI_HAIR_COLOR:
{
g->member[i].hair_color = *(const short *)data;
g->member[i].modified = GS_MEMBER_MODIFIED;
mapif->guild_memberinfochanged(guild_id,account_id,char_id,type,data,len);
g->save_flag |= GS_MEMBER; //Save new data.
break;
}
case GMI_GENDER:
{
g->member[i].gender = *(const short *)data;
g->member[i].modified = GS_MEMBER_MODIFIED;
mapif->guild_memberinfochanged(guild_id,account_id,char_id,type,data,len);
g->save_flag |= GS_MEMBER; //Save new data.
break;
}
case GMI_CLASS:
{
g->member[i].class_ = *(const short *)data;
g->member[i].modified = GS_MEMBER_MODIFIED;
mapif->guild_memberinfochanged(guild_id,account_id,char_id,type,data,len);
g->save_flag |= GS_MEMBER; //Save new data.
break;
}
case GMI_LEVEL:
{
g->member[i].lv = *(const short *)data;
g->member[i].modified = GS_MEMBER_MODIFIED;
mapif->guild_memberinfochanged(guild_id,account_id,char_id,type,data,len);
g->save_flag |= GS_MEMBER; //Save new data.
break;
}
default:
ShowError("int_guild: GuildMemberInfoChange: Unknown type %d\n",type);
break;
}
return 0;
}
int inter_guild_sex_changed(int guild_id, int account_id, int char_id, short gender)
{
return mapif->parse_GuildMemberInfoChange(0, guild_id, account_id, char_id, GMI_GENDER, (const char*)&gender, sizeof(gender));
}
int inter_guild_charname_changed(int guild_id, int account_id, int char_id, char *name)
{
struct guild *g;
int i, flag = 0;
nullpo_ret(name);
g = inter_guild->fromsql(guild_id);
if( g == NULL )
{
ShowError("inter_guild_charrenamed: Can't find guild %d.\n", guild_id);
return 0;
}
ARR_FIND(0, g->max_member, i, g->member[i].char_id == char_id);
if( i == g->max_member )
{
ShowError("inter_guild_charrenamed: Can't find character %d in the guild\n", char_id);
return 0;
}
if( !strcmp(g->member[i].name, g->master) )
{
safestrncpy(g->master, name, NAME_LENGTH);
flag |= GS_BASIC;
}
safestrncpy(g->member[i].name, name, NAME_LENGTH);
g->member[i].modified = GS_MEMBER_MODIFIED;
flag |= GS_MEMBER;
if( !inter_guild->tosql(g, flag) )
return 0;
mapif->guild_info(-1,g);
return 0;
}
// Change a position desc
int mapif_parse_GuildPosition(int fd, int guild_id, int idx, const struct guild_position *p)
{
// Could make some improvement in speed, because only change guild_position
struct guild * g;
nullpo_ret(p);
g = inter_guild->fromsql(guild_id);
if(g==NULL || idx<0 || idx>=MAX_GUILDPOSITION)
return 0;
memcpy(&g->position[idx],p,sizeof(struct guild_position));
mapif->guild_position(g,idx);
g->position[idx].modified = GS_POSITION_MODIFIED;
g->save_flag |= GS_POSITION; // Change guild_position
return 0;
}
// Guild Skill UP
int mapif_parse_GuildSkillUp(int fd, int guild_id, uint16 skill_id, int account_id, int max)
{
struct guild * g;
int idx = skill_id - GD_SKILLBASE;
g = inter_guild->fromsql(guild_id);
if(g == NULL || idx < 0 || idx >= MAX_GUILDSKILL)
return 0;
if(g->skill_point>0 && g->skill[idx].id>0 && g->skill[idx].lv<max )
{
g->skill[idx].lv++;
g->skill_point--;
if (!inter_guild->calcinfo(g))
mapif->guild_info(-1,g);
mapif->guild_skillupack(guild_id,skill_id,account_id);
g->save_flag |= (GS_LEVEL|GS_SKILL); // Change guild & guild_skill
}
return 0;
}
//Manual deletion of an alliance when partnering guild does not exists. [Skotlex]
int mapif_parse_GuildDeleteAlliance(struct guild *g, int guild_id, int account_id1, int account_id2, int flag)
{
int i;
char name[NAME_LENGTH];
nullpo_retr(-1, g);
ARR_FIND( 0, MAX_GUILDALLIANCE, i, g->alliance[i].guild_id == guild_id );
if( i == MAX_GUILDALLIANCE )
return -1;
strcpy(name, g->alliance[i].name);
g->alliance[i].guild_id=0;
mapif->guild_alliance(g->guild_id,guild_id,account_id1,account_id2,flag,g->name,name);
g->save_flag |= GS_ALLIANCE;
return 0;
}
// Alliance modification
int mapif_parse_GuildAlliance(int fd, int guild_id1, int guild_id2, int account_id1, int account_id2, int flag)
{
// Could speed up
struct guild *g[2] = { NULL };
int j,i;
g[0] = inter_guild->fromsql(guild_id1);
g[1] = inter_guild->fromsql(guild_id2);
if(g[0] && g[1]==NULL && (flag & GUILD_ALLIANCE_REMOVE)) //Requested to remove an alliance with a not found guild.
return mapif->parse_GuildDeleteAlliance(g[0], guild_id2, account_id1, account_id2, flag); //Try to do a manual removal of said guild.
if(g[0]==NULL || g[1]==NULL)
return 0;
if( flag&GUILD_ALLIANCE_REMOVE ) {
// Remove alliance/opposition, in case of alliance, remove on both side
for( i = 0; i < ((flag&GUILD_ALLIANCE_TYPE_MASK) ? 1 : 2); i++ ) {
ARR_FIND( 0, MAX_GUILDALLIANCE, j, g[i]->alliance[j].guild_id == g[1-i]->guild_id && g[i]->alliance[j].opposition == (flag&GUILD_ALLIANCE_TYPE_MASK) );
if( j < MAX_GUILDALLIANCE )
g[i]->alliance[j].guild_id = 0;
}
} else {
// Add alliance, in case of alliance, add on both side
for( i = 0; i < ((flag&GUILD_ALLIANCE_TYPE_MASK) ? 1 : 2); i++ ) {
// Search an empty slot
ARR_FIND( 0, MAX_GUILDALLIANCE, j, g[i]->alliance[j].guild_id == 0 );
if( j < MAX_GUILDALLIANCE ) {
g[i]->alliance[j].guild_id=g[1-i]->guild_id;
memcpy(g[i]->alliance[j].name,g[1-i]->name,NAME_LENGTH);
// Set alliance type
g[i]->alliance[j].opposition = flag&GUILD_ALLIANCE_TYPE_MASK;
}
}
}
// Send on all map the new alliance/opposition
mapif->guild_alliance(guild_id1,guild_id2,account_id1,account_id2,flag,g[0]->name,g[1]->name);
// Mark the two guild to be saved
g[0]->save_flag |= GS_ALLIANCE;
g[1]->save_flag |= GS_ALLIANCE;
return 0;
}
// Change guild message
int mapif_parse_GuildNotice(int fd, int guild_id, const char *mes1, const char *mes2)
{
struct guild *g;
nullpo_ret(mes1);
nullpo_ret(mes2);
g = inter_guild->fromsql(guild_id);
if(g==NULL)
return 0;
memcpy(g->mes1,mes1,MAX_GUILDMES1);
memcpy(g->mes2,mes2,MAX_GUILDMES2);
g->save_flag |= GS_MES; //Change mes of guild
return mapif->guild_notice(g);
}
int mapif_parse_GuildEmblem(int fd, int len, int guild_id, int dummy, const char *data)
{
struct guild * g;
nullpo_ret(data);
g = inter_guild->fromsql(guild_id);
if(g==NULL)
return 0;
if (len > sizeof(g->emblem_data))
len = sizeof(g->emblem_data);
memcpy(g->emblem_data,data,len);
g->emblem_len=len;
g->emblem_id++;
g->save_flag |= GS_EMBLEM; //Change guild
return mapif->guild_emblem(g);
}
int mapif_parse_GuildCastleDataLoad(int fd, int len, const int *castle_ids)
{
return mapif->guild_castle_dataload(fd, len, castle_ids);
}
int mapif_parse_GuildCastleDataSave(int fd, int castle_id, int index, int value)
{
struct guild_castle *gc = inter_guild->castle_fromsql(castle_id);
if (gc == NULL) {
ShowError("mapif->parse_GuildCastleDataSave: castle id=%d not found\n", castle_id);
return 0;
}
switch (index) {
case 1:
if (inter->enable_logs && gc->guild_id != value) {
int gid = (value) ? value : gc->guild_id;
struct guild *g = idb_get(inter_guild->guild_db, gid);
inter->log("guild %s (id=%d) %s castle id=%d\n",
(g) ? g->name : "??", gid, (value) ? "occupy" : "abandon", castle_id);
}
gc->guild_id = value;
break;
case 2: gc->economy = value; break;
case 3: gc->defense = value; break;
case 4: gc->triggerE = value; break;
case 5: gc->triggerD = value; break;
case 6: gc->nextTime = value; break;
case 7: gc->payTime = value; break;
case 8: gc->createTime = value; break;
case 9: gc->visibleC = value; break;
default:
if (index > 9 && index <= 9+MAX_GUARDIANS) {
gc->guardian[index-10].visible = value;
break;
}
ShowError("mapif->parse_GuildCastleDataSave: not found index=%d\n", index);
return 0;
}
inter_guild->castle_tosql(gc);
return 0;
}
int mapif_parse_GuildMasterChange(int fd, int guild_id, const char* name, int len)
{
struct guild * g;
struct guild_member gm;
int pos;
nullpo_ret(name);
g = inter_guild->fromsql(guild_id);
if(g==NULL || len > NAME_LENGTH)
return 0;
// Find member (name)
for (pos = 0; pos < g->max_member && strncmp(g->member[pos].name, name, len); pos++);
if (pos == g->max_member)
return 0; //Character not found??
// Switch current and old GM
memcpy(&gm, &g->member[pos], sizeof (struct guild_member));
memcpy(&g->member[pos], &g->member[0], sizeof(struct guild_member));
memcpy(&g->member[0], &gm, sizeof(struct guild_member));
// Switch positions
g->member[pos].position = g->member[0].position;
g->member[pos].modified = GS_MEMBER_MODIFIED;
g->member[0].position = 0; //Position 0: guild Master.
g->member[0].modified = GS_MEMBER_MODIFIED;
safestrncpy(g->master, name, len);
if (len < NAME_LENGTH)
g->master[len] = '\0';
ShowInfo("int_guild: Guildmaster Changed to %s (Guild %d - %s)\n",g->master, guild_id, g->name);
g->save_flag |= (GS_BASIC|GS_MEMBER); //Save main data and member data.
return mapif->guild_master_changed(g, g->member[0].account_id, g->member[0].char_id);
}
// Communication from the map server
// - Can analyzed only one by one packet
// Data packet length that you set to inter.c
//- Shouldn't do checking and packet length, RFIFOSKIP is done by the caller
// Must Return
// 1 : ok
// 0 : error
int inter_guild_parse_frommap(int fd)
{
RFIFOHEAD(fd);
switch(RFIFOW(fd,0)) {
case 0x3030: mapif->parse_CreateGuild(fd, RFIFOL(fd,4), RFIFOP(fd,8), RFIFOP(fd,32)); break;
case 0x3031: mapif->parse_GuildInfo(fd,RFIFOL(fd,2)); break;
case 0x3032: mapif->parse_GuildAddMember(fd, RFIFOL(fd,4), RFIFOP(fd,8)); break;
case 0x3033: mapif->parse_GuildMasterChange(fd, RFIFOL(fd,4), RFIFOP(fd,8), RFIFOW(fd,2)-8); break;
case 0x3034: mapif->parse_GuildLeave(fd, RFIFOL(fd,2), RFIFOL(fd,6), RFIFOL(fd,10), RFIFOB(fd,14), RFIFOP(fd,15)); break;
case 0x3035: mapif->parse_GuildChangeMemberInfoShort(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOL(fd,10),RFIFOB(fd,14),RFIFOW(fd,15),RFIFOW(fd,17)); break;
case 0x3036: mapif->parse_BreakGuild(fd,RFIFOL(fd,2)); break;
case 0x3037: mapif->parse_GuildMessage(fd, RFIFOL(fd,4), RFIFOL(fd,8), RFIFOP(fd,12), RFIFOW(fd,2)-12); break;
case 0x3039: mapif->parse_GuildBasicInfoChange(fd, RFIFOL(fd,4), RFIFOW(fd,8), RFIFOP(fd,10), RFIFOW(fd,2)-10); break;
case 0x303A: mapif->parse_GuildMemberInfoChange(fd, RFIFOL(fd,4), RFIFOL(fd,8), RFIFOL(fd,12), RFIFOW(fd,16), RFIFOP(fd,18), RFIFOW(fd,2)-18); break;
case 0x303B: mapif->parse_GuildPosition(fd, RFIFOL(fd,4), RFIFOL(fd,8), RFIFOP(fd,12)); break;
case 0x303C: mapif->parse_GuildSkillUp(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOL(fd,10),RFIFOL(fd,14)); break;
case 0x303D: mapif->parse_GuildAlliance(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOL(fd,10),RFIFOL(fd,14),RFIFOB(fd,18)); break;
case 0x303E: mapif->parse_GuildNotice(fd, RFIFOL(fd,2), RFIFOP(fd,6), RFIFOP(fd,66)); break;
case 0x303F: mapif->parse_GuildEmblem(fd, RFIFOW(fd,2)-12, RFIFOL(fd,4), RFIFOL(fd,8), RFIFOP(fd,12)); break;
case 0x3040: mapif->parse_GuildCastleDataLoad(fd, RFIFOW(fd,2), RFIFOP(fd,4)); break;
case 0x3041: mapif->parse_GuildCastleDataSave(fd,RFIFOW(fd,2),RFIFOB(fd,4),RFIFOL(fd,5)); break;
default:
return 0;
}
return 1;
}
//Leave request from the server (for deleting character from guild)
int inter_guild_leave(int guild_id, int account_id, int char_id)
{
return mapif->parse_GuildLeave(-1, guild_id, account_id, char_id, 0, "** Character Deleted **");
}
int inter_guild_broken(int guild_id)
{
return mapif->guild_broken(guild_id, 0);
}
void inter_guild_defaults(void)
{
inter_guild = &inter_guild_s;
inter_guild->guild_db = NULL;
inter_guild->castle_db = NULL;
memset(inter_guild->exp, 0, sizeof(inter_guild->exp));
inter_guild->save_timer = inter_guild_save_timer;
inter_guild->removemember_tosql = inter_guild_removemember_tosql;
inter_guild->tosql = inter_guild_tosql;
inter_guild->fromsql = inter_guild_fromsql;
inter_guild->castle_tosql = inter_guild_castle_tosql;
inter_guild->castle_fromsql = inter_guild_castle_fromsql;
inter_guild->exp_parse_row = inter_guild_exp_parse_row;
inter_guild->CharOnline = inter_guild_CharOnline;
inter_guild->CharOffline = inter_guild_CharOffline;
inter_guild->sql_init = inter_guild_sql_init;
inter_guild->db_final = inter_guild_db_final;
inter_guild->sql_final = inter_guild_sql_final;
inter_guild->search_guildname = inter_guild_search_guildname;
inter_guild->check_empty = inter_guild_check_empty;
inter_guild->nextexp = inter_guild_nextexp;
inter_guild->checkskill = inter_guild_checkskill;
inter_guild->calcinfo = inter_guild_calcinfo;
inter_guild->sex_changed = inter_guild_sex_changed;
inter_guild->charname_changed = inter_guild_charname_changed;
inter_guild->parse_frommap = inter_guild_parse_frommap;
inter_guild->leave = inter_guild_leave;
inter_guild->broken = inter_guild_broken;
}
|
brHercules/Herc
|
src/char/int_guild.c
|
C
|
gpl-3.0
| 61,654 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch12/12.2/12.2.1/12.2.1-30-s.js
* @description arguments as local var identifier throws SyntaxError in strict mode
* @onlyStrict
*/
function testcase() {
'use strict';
try {
eval('function foo() { var a = 42, arguments;}');
return false;
}
catch (e) {
return (e instanceof SyntaxError);
}
}
runTestCase(testcase);
|
geminy/aidear
|
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch12/12.2/12.2.1/12.2.1-30-s.js
|
JavaScript
|
gpl-3.0
| 731 |
module Ext
end
|
channainfo/verboice
|
app/models/ext/ext.rb
|
Ruby
|
gpl-3.0
| 16 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- qsharedpointer.cpp -->
<title>QWeakPointer Class | Qt Core 5.7</title>
<link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
<script type="text/javascript">
window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");};
</script>
</head>
<body>
<div class="header" id="qtdocheader">
<div class="main">
<div class="main-rounded">
<div class="navigationbar">
<table><tr>
<td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qtcore-index.html">Qt Core</a></td><td ><a href="qtcore-module.html">C++ Classes</a></td><td >QWeakPointer</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td>
</tr></table>
</div>
</div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#public-functions">Public Functions</a></li>
<li class="level1"><a href="#related-non-members">Related Non-Members</a></li>
<li class="level1"><a href="#details">Detailed Description</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">QWeakPointer Class</h1>
<!-- $$$QWeakPointer-brief -->
<p>The <a href="qweakpointer.html">QWeakPointer</a> class holds a weak reference to a shared pointer <a href="#details">More...</a></p>
<!-- @@@QWeakPointer -->
<div class="table"><table class="alignedsummary">
<tr><td class="memItemLeft rightAlign topAlign"> Header:</td><td class="memItemRight bottomAlign"> <span class="preprocessor">#include <QWeakPointer></span>
</td></tr><tr><td class="memItemLeft rightAlign topAlign"> qmake:</td><td class="memItemRight bottomAlign"> QT += core</td></tr><tr><td class="memItemLeft rightAlign topAlign"> Since:</td><td class="memItemRight bottomAlign"> Qt 4.5</td></tr></table></div><ul>
<li><a href="qweakpointer-members.html">List of all members, including inherited members</a></li>
<li><a href="qweakpointer-obsolete.html">Obsolete members</a></li>
</ul>
<p><b>Note:</b> All functions in this class are <a href="../qtdoc/threads-reentrancy.html">reentrant</a>.</p>
<a name="public-functions"></a>
<h2 id="public-functions">Public Functions</h2>
<div class="table"><table class="alignedsummary">
<tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></b>()</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#QWeakPointer-1">QWeakPointer</a></b>(const QWeakPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#QWeakPointer-2">QWeakPointer</a></b>(const QSharedPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#dtor.QWeakPointer">~QWeakPointer</a></b>()</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> void </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#clear">clear</a></b>()</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> T *</td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#data">data</a></b>() const</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#isNull">isNull</a></b>() const</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QSharedPointer<T> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#lock">lock</a></b>() const</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> void </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#swap">swap</a></b>(QWeakPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QSharedPointer<T> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#toStrongRef">toStrongRef</a></b>() const</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#operator-bool">operator bool</a></b>() const</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#operator-not">operator!</a></b>() const</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QWeakPointer<T> &</td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#operator-eq">operator=</a></b>(const QWeakPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QWeakPointer<T> &</td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#operator-eq-1">operator=</a></b>(const QSharedPointer<T> &<i>other</i>)</td></tr>
</table></div>
<a name="related-non-members"></a>
<h2 id="related-non-members">Related Non-Members</h2>
<div class="table"><table class="alignedsummary">
<tr><td class="memItemLeft rightAlign topAlign"> QSharedPointer<X> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#qSharedPointerCast">qSharedPointerCast</a></b>(const QWeakPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QSharedPointer<X> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#qSharedPointerConstCast">qSharedPointerConstCast</a></b>(const QWeakPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QSharedPointer<X> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#qSharedPointerDynamicCast">qSharedPointerDynamicCast</a></b>(const QWeakPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QSharedPointer<X> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#qSharedPointerObjectCast">qSharedPointerObjectCast</a></b>(const QWeakPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QWeakPointer<X> </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#qWeakPointerCast">qWeakPointerCast</a></b>(const QWeakPointer<T> &<i>other</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#operator-not-eq">operator!=</a></b>(const QSharedPointer<T> &<i>ptr1</i>, const QWeakPointer<X> &<i>ptr2</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#operator-not-eq-1">operator!=</a></b>(const QWeakPointer<T> &<i>ptr1</i>, const QSharedPointer<X> &<i>ptr2</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#operator-eq-eq">operator==</a></b>(const QSharedPointer<T> &<i>ptr1</i>, const QWeakPointer<X> &<i>ptr2</i>)</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qweakpointer.html#operator-eq-eq-1">operator==</a></b>(const QWeakPointer<T> &<i>ptr1</i>, const QSharedPointer<X> &<i>ptr2</i>)</td></tr>
</table></div>
<a name="details"></a>
<!-- $$$QWeakPointer-description -->
<div class="descr">
<h2 id="details">Detailed Description</h2>
<p>The <a href="qweakpointer.html">QWeakPointer</a> class holds a weak reference to a shared pointer</p>
<p>The <a href="qweakpointer.html">QWeakPointer</a> is an automatic weak reference to a pointer in C++. It cannot be used to dereference the pointer directly, but it can be used to verify if the pointer has been deleted or not in another context.</p>
<p><a href="qweakpointer.html">QWeakPointer</a> objects can only be created by assignment from a <a href="qsharedpointer.html">QSharedPointer</a>.</p>
<p>It's important to note that <a href="qweakpointer.html">QWeakPointer</a> provides no automatic casting operators to prevent mistakes from happening. Even though <a href="qweakpointer.html">QWeakPointer</a> tracks a pointer, it should not be considered a pointer itself, since it doesn't guarantee that the pointed object remains valid.</p>
<p>Therefore, to access the pointer that <a href="qweakpointer.html">QWeakPointer</a> is tracking, you must first promote it to <a href="qsharedpointer.html">QSharedPointer</a> and verify if the resulting object is null or not. <a href="qsharedpointer.html">QSharedPointer</a> guarantees that the object isn't deleted, so if you obtain a non-null object, you may use the pointer. See <a href="qweakpointer.html#toStrongRef">QWeakPointer::toStrongRef</a>() for an example.</p>
<p><a href="qweakpointer.html">QWeakPointer</a> also provides the <a href="qweakpointer.html#data">QWeakPointer::data</a>() method that returns the tracked pointer without ensuring that it remains valid. This function is provided if you can guarantee by external means that the object will not get deleted (or if you only need the pointer value) and the cost of creating a <a href="qsharedpointer.html">QSharedPointer</a> using <a href="qweakpointer.html#toStrongRef">toStrongRef</a>() is too high.</p>
</div>
<p><b>See also </b><a href="qsharedpointer.html">QSharedPointer</a> and <a href="qscopedpointer.html">QScopedPointer</a>.</p>
<!-- @@@QWeakPointer -->
<div class="func">
<h2>Member Function Documentation</h2>
<!-- $$$QWeakPointer[overload1]$$$QWeakPointer -->
<h3 class="fn" id="QWeakPointer"><a name="QWeakPointer"></a>QWeakPointer::<span class="name">QWeakPointer</span>()</h3>
<p>Creates a <a href="qweakpointer.html">QWeakPointer</a> that points to nothing.</p>
<!-- @@@QWeakPointer -->
<!-- $$$QWeakPointer$$$QWeakPointerconstQWeakPointer<T>& -->
<h3 class="fn" id="QWeakPointer-1"><a name="QWeakPointer-1"></a>QWeakPointer::<span class="name">QWeakPointer</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Creates a <a href="qweakpointer.html">QWeakPointer</a> that holds a weak reference to the pointer referenced by <i>other</i>.</p>
<p>If <code>T</code> is a derived type of the template parameter of this class, <a href="qweakpointer.html">QWeakPointer</a> will perform an automatic cast. Otherwise, you will get a compiler error.</p>
<!-- @@@QWeakPointer -->
<!-- $$$QWeakPointer$$$QWeakPointerconstQSharedPointer<T>& -->
<h3 class="fn" id="QWeakPointer-2"><a name="QWeakPointer-2"></a>QWeakPointer::<span class="name">QWeakPointer</span>(const <span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Creates a <a href="qweakpointer.html">QWeakPointer</a> that holds a weak reference to the pointer referenced by <i>other</i>.</p>
<p>If <code>T</code> is a derived type of the template parameter of this class, <a href="qweakpointer.html">QWeakPointer</a> will perform an automatic cast. Otherwise, you will get a compiler error.</p>
<!-- @@@QWeakPointer -->
<!-- $$$~QWeakPointer[overload1]$$$~QWeakPointer -->
<h3 class="fn" id="dtor.QWeakPointer"><a name="dtor.QWeakPointer"></a>QWeakPointer::<span class="name">~QWeakPointer</span>()</h3>
<p>Destroys this <a href="qweakpointer.html">QWeakPointer</a> object. The pointer referenced by this object will not be deleted.</p>
<!-- @@@~QWeakPointer -->
<!-- $$$clear[overload1]$$$clear -->
<h3 class="fn" id="clear"><a name="clear"></a><span class="type">void</span> QWeakPointer::<span class="name">clear</span>()</h3>
<p>Clears this <a href="qweakpointer.html">QWeakPointer</a> object, dropping the reference that it may have had to the pointer.</p>
<!-- @@@clear -->
<!-- $$$data[overload1]$$$data -->
<h3 class="fn" id="data"><a name="data"></a><span class="type">T</span> *QWeakPointer::<span class="name">data</span>() const</h3>
<p>Returns the value of the pointer being tracked by this <a href="qweakpointer.html">QWeakPointer</a>, <b>without</b> ensuring that it cannot get deleted. To have that guarantee, use <a href="qweakpointer.html#toStrongRef">toStrongRef</a>(), which returns a <a href="qsharedpointer.html">QSharedPointer</a> object. If this function can determine that the pointer has already been deleted, it returns 0.</p>
<p>It is ok to obtain the value of the pointer and using that value itself, like for example in debugging statements:</p>
<pre class="cpp">
<a href="qtglobal.html#qDebug">qDebug</a>(<span class="string">"Tracking %p"</span><span class="operator">,</span> weakref<span class="operator">.</span>data());
</pre>
<p>However, dereferencing the pointer is only allowed if you can guarantee by external means that the pointer does not get deleted. For example, if you can be certain that no other thread can delete it, nor the functions that you may call.</p>
<p>If that is the case, then the following code is valid:</p>
<pre class="cpp">
<span class="comment">// this pointer cannot be used in another thread</span>
<span class="comment">// so other threads cannot delete it</span>
<span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><span class="operator"><</span><span class="type">int</span><span class="operator">></span> weakref <span class="operator">=</span> obtainReference();
Object <span class="operator">*</span>obj <span class="operator">=</span> weakref<span class="operator">.</span>data();
<span class="keyword">if</span> (obj) {
<span class="comment">// if the pointer wasn't deleted yet, we know it can't get</span>
<span class="comment">// deleted by our own code here nor the functions we call</span>
otherFunction(obj);
}
</pre>
<p>Use this function with care.</p>
<p>This function was introduced in Qt 4.6.</p>
<p><b>See also </b><a href="qweakpointer.html#isNull">isNull</a>() and <a href="qweakpointer.html#toStrongRef">toStrongRef</a>().</p>
<!-- @@@data -->
<!-- $$$isNull[overload1]$$$isNull -->
<h3 class="fn" id="isNull"><a name="isNull"></a><span class="type">bool</span> QWeakPointer::<span class="name">isNull</span>() const</h3>
<p>Returns <code>true</code> if this object is holding a reference to a null pointer.</p>
<p>Note that, due to the nature of weak references, the pointer that <a href="qweakpointer.html">QWeakPointer</a> references can become null at any moment, so the value returned from this function can change from false to true from one call to the next.</p>
<!-- @@@isNull -->
<!-- $$$lock[overload1]$$$lock -->
<h3 class="fn" id="lock"><a name="lock"></a><span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">T</span>> QWeakPointer::<span class="name">lock</span>() const</h3>
<p>Same as <a href="qweakpointer.html#toStrongRef">toStrongRef</a>().</p>
<p>This function is provided for API compatibility with std::weak_ptr.</p>
<p>This function was introduced in Qt 5.4.</p>
<!-- @@@lock -->
<!-- $$$swap[overload1]$$$swapQWeakPointer<T>& -->
<h3 class="fn" id="swap"><a name="swap"></a><span class="type">void</span> QWeakPointer::<span class="name">swap</span>(<span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Swaps this weak pointer instance with <i>other</i>. This function is very fast and never fails.</p>
<p>This function was introduced in Qt 5.4.</p>
<!-- @@@swap -->
<!-- $$$toStrongRef[overload1]$$$toStrongRef -->
<h3 class="fn" id="toStrongRef"><a name="toStrongRef"></a><span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">T</span>> QWeakPointer::<span class="name">toStrongRef</span>() const</h3>
<p>Promotes this weak reference to a strong one and returns a <a href="qsharedpointer.html">QSharedPointer</a> object holding that reference. When promoting to <a href="qsharedpointer.html">QSharedPointer</a>, this function verifies if the object has been deleted already or not. If it hasn't, this function increases the reference count to the shared object, thus ensuring that it will not get deleted.</p>
<p>Since this function can fail to obtain a valid strong reference to the shared object, you should always verify if the conversion succeeded, by calling <a href="qsharedpointer.html#isNull">QSharedPointer::isNull</a>() on the returned object.</p>
<p>For example, the following code promotes a <a href="qweakpointer.html">QWeakPointer</a> that was held to a strong reference and, if it succeeded, it prints the value of the integer that was held:</p>
<pre class="cpp">
<span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><span class="operator"><</span><span class="type">int</span><span class="operator">></span> weakref;
<span class="comment">// ...</span>
<span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><span class="operator"><</span><span class="type">int</span><span class="operator">></span> strong <span class="operator">=</span> weakref<span class="operator">.</span>toStrongRef();
<span class="keyword">if</span> (strong)
<a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator"><</span><span class="operator"><</span> <span class="string">"The value is:"</span> <span class="operator"><</span><span class="operator"><</span> <span class="operator">*</span>strong;
<span class="keyword">else</span>
<a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator"><</span><span class="operator"><</span> <span class="string">"The value has already been deleted"</span>;
</pre>
<p><b>See also </b><a href="qsharedpointer.html#QSharedPointer">QSharedPointer::QSharedPointer</a>().</p>
<!-- @@@toStrongRef -->
<!-- $$$operator bool[overload1]$$$operator bool -->
<h3 class="fn" id="operator-bool"><a name="operator-bool"></a>QWeakPointer::<span class="name">operator bool</span>() const</h3>
<p>Returns <code>true</code> if this object is not null. This function is suitable for use in <code>if-constructs</code>, like:</p>
<pre class="cpp">
<span class="keyword">if</span> (weakref) { <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span> }
</pre>
<p>Note that, due to the nature of weak references, the pointer that <a href="qweakpointer.html">QWeakPointer</a> references can become null at any moment, so the value returned from this function can change from true to false from one call to the next.</p>
<p><b>See also </b><a href="qweakpointer.html#isNull">isNull</a>().</p>
<!-- @@@operator bool -->
<!-- $$$operator![overload1]$$$operator! -->
<h3 class="fn" id="operator-not"><a name="operator-not"></a><span class="type">bool</span> QWeakPointer::<span class="name">operator!</span>() const</h3>
<p>Returns <code>true</code> if this object is null. This function is suitable for use in <code>if-constructs</code>, like:</p>
<pre class="cpp">
<span class="keyword">if</span> (<span class="operator">!</span>weakref) { <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span> }
</pre>
<p>Note that, due to the nature of weak references, the pointer that <a href="qweakpointer.html">QWeakPointer</a> references can become null at any moment, so the value returned from this function can change from false to true from one call to the next.</p>
<p><b>See also </b><a href="qweakpointer.html#isNull">isNull</a>().</p>
<!-- @@@operator! -->
<!-- $$$operator=[overload1]$$$operator=constQWeakPointer<T>& -->
<h3 class="fn" id="operator-eq"><a name="operator-eq"></a><span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &QWeakPointer::<span class="name">operator=</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Makes this object share <i>other</i>'s pointer. The current pointer reference is discarded but is not deleted.</p>
<p>If <code>T</code> is a derived type of the template parameter of this class, <a href="qweakpointer.html">QWeakPointer</a> will perform an automatic cast. Otherwise, you will get a compiler error.</p>
<!-- @@@operator= -->
<!-- $$$operator=$$$operator=constQSharedPointer<T>& -->
<h3 class="fn" id="operator-eq-1"><a name="operator-eq-1"></a><span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &QWeakPointer::<span class="name">operator=</span>(const <span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Makes this object share <i>other</i>'s pointer. The current pointer reference is discarded but is not deleted.</p>
<p>If <code>T</code> is a derived type of the template parameter of this class, <a href="qweakpointer.html">QWeakPointer</a> will perform an automatic cast. Otherwise, you will get a compiler error.</p>
<!-- @@@operator= -->
</div>
<div class="relnonmem">
<h2>Related Non-Members</h2>
<!-- $$$qSharedPointerCast[overload1]$$$qSharedPointerCastconstQWeakPointer<T>& -->
<h3 class="fn" id="qSharedPointerCast"><a name="qSharedPointerCast"></a><span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">X</span>> <span class="name">qSharedPointerCast</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Returns a shared pointer to the pointer held by <i>other</i>, cast to type <code>X</code>. The types <code>T</code> and <code>X</code> must belong to one hierarchy for the <code>static_cast</code> to succeed.</p>
<p>The <i>other</i> object is converted first to a strong reference. If that conversion fails (because the object it's pointing to has already been deleted), this function returns a null <a href="qsharedpointer.html">QSharedPointer</a>.</p>
<p>Note that <code>X</code> must have the same cv-qualifiers (<code>const</code> and <code>volatile</code>) that <code>T</code> has, or the code will fail to compile. Use <a href="qsharedpointer.html#qSharedPointerConstCast">qSharedPointerConstCast</a> to cast away the constness.</p>
<p><b>See also </b><a href="qweakpointer.html#toStrongRef">QWeakPointer::toStrongRef</a>(), <a href="qsharedpointer.html#qSharedPointerDynamicCast">qSharedPointerDynamicCast</a>(), and <a href="qsharedpointer.html#qSharedPointerConstCast">qSharedPointerConstCast</a>().</p>
<!-- @@@qSharedPointerCast -->
<!-- $$$qSharedPointerConstCast[overload1]$$$qSharedPointerConstCastconstQWeakPointer<T>& -->
<h3 class="fn" id="qSharedPointerConstCast"><a name="qSharedPointerConstCast"></a><span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">X</span>> <span class="name">qSharedPointerConstCast</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Returns a shared pointer to the pointer held by <i>other</i>, cast to type <code>X</code>. The types <code>T</code> and <code>X</code> must belong to one hierarchy for the <code>const_cast</code> to succeed. The <code>const</code> and <code>volatile</code> differences between <code>T</code> and <code>X</code> are ignored.</p>
<p>The <i>other</i> object is converted first to a strong reference. If that conversion fails (because the object it's pointing to has already been deleted), this function returns a null <a href="qsharedpointer.html">QSharedPointer</a>.</p>
<p><b>See also </b><a href="qweakpointer.html#toStrongRef">QWeakPointer::toStrongRef</a>(), <a href="qsharedpointer.html#qSharedPointerCast">qSharedPointerCast</a>(), and <a href="qsharedpointer.html#qSharedPointerDynamicCast">qSharedPointerDynamicCast</a>().</p>
<!-- @@@qSharedPointerConstCast -->
<!-- $$$qSharedPointerDynamicCast[overload1]$$$qSharedPointerDynamicCastconstQWeakPointer<T>& -->
<h3 class="fn" id="qSharedPointerDynamicCast"><a name="qSharedPointerDynamicCast"></a><span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">X</span>> <span class="name">qSharedPointerDynamicCast</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Returns a shared pointer to the pointer held by <i>other</i>, using a dynamic cast to type <code>X</code> to obtain an internal pointer of the appropriate type. If the <code>dynamic_cast</code> fails, the object returned will be null.</p>
<p>The <i>other</i> object is converted first to a strong reference. If that conversion fails (because the object it's pointing to has already been deleted), this function also returns a null <a href="qsharedpointer.html">QSharedPointer</a>.</p>
<p>Note that <code>X</code> must have the same cv-qualifiers (<code>const</code> and <code>volatile</code>) that <code>T</code> has, or the code will fail to compile. Use <a href="qsharedpointer.html#qSharedPointerConstCast">qSharedPointerConstCast</a> to cast away the constness.</p>
<p><b>See also </b><a href="qweakpointer.html#toStrongRef">QWeakPointer::toStrongRef</a>(), <a href="qsharedpointer.html#qSharedPointerCast">qSharedPointerCast</a>(), and <a href="qsharedpointer.html#qSharedPointerConstCast">qSharedPointerConstCast</a>().</p>
<!-- @@@qSharedPointerDynamicCast -->
<!-- $$$qSharedPointerObjectCast[overload1]$$$qSharedPointerObjectCastconstQWeakPointer<T>& -->
<h3 class="fn" id="qSharedPointerObjectCast"><a name="qSharedPointerObjectCast"></a><span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">X</span>> <span class="name">qSharedPointerObjectCast</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>The <a href="qsharedpointer.html#qSharedPointerObjectCast">qSharedPointerObjectCast</a> function is for casting a shared pointer.</p>
<p>Returns a shared pointer to the pointer held by <i>other</i>, using a <a href="qobject.html#qobject_cast">qobject_cast</a>() to type <code>X</code> to obtain an internal pointer of the appropriate type. If the <code>qobject_cast</code> fails, the object returned will be null.</p>
<p>The <i>other</i> object is converted first to a strong reference. If that conversion fails (because the object it's pointing to has already been deleted), this function also returns a null <a href="qsharedpointer.html">QSharedPointer</a>.</p>
<p>Note that <code>X</code> must have the same cv-qualifiers (<code>const</code> and <code>volatile</code>) that <code>T</code> has, or the code will fail to compile. Use <a href="qsharedpointer.html#qSharedPointerConstCast">qSharedPointerConstCast</a> to cast away the constness.</p>
<p>This function was introduced in Qt 4.6.</p>
<p><b>See also </b><a href="qweakpointer.html#toStrongRef">QWeakPointer::toStrongRef</a>(), <a href="qsharedpointer.html#qSharedPointerCast">qSharedPointerCast</a>(), and <a href="qsharedpointer.html#qSharedPointerConstCast">qSharedPointerConstCast</a>().</p>
<!-- @@@qSharedPointerObjectCast -->
<!-- $$$qWeakPointerCast[overload1]$$$qWeakPointerCastconstQWeakPointer<T>& -->
<h3 class="fn" id="qWeakPointerCast"><a name="qWeakPointerCast"></a><span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">X</span>> <span class="name">qWeakPointerCast</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>other</i>)</h3>
<p>Returns a weak pointer to the pointer held by <i>other</i>, cast to type <code>X</code>. The types <code>T</code> and <code>X</code> must belong to one hierarchy for the <code>static_cast</code> to succeed.</p>
<p>Note that <code>X</code> must have the same cv-qualifiers (<code>const</code> and <code>volatile</code>) that <code>T</code> has, or the code will fail to compile. Use <a href="qsharedpointer.html#qSharedPointerConstCast">qSharedPointerConstCast</a> to cast away the constness.</p>
<!-- @@@qWeakPointerCast -->
<!-- $$$operator!=[overload1]$$$operator!=constQSharedPointer<T>&constQWeakPointer<X>& -->
<h3 class="fn" id="operator-not-eq"><a name="operator-not-eq"></a><span class="type">bool</span> <span class="name">operator!=</span>(const <span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">T</span>> &<i>ptr1</i>, const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">X</span>> &<i>ptr2</i>)</h3>
<p>Returns <code>true</code> if the pointer referenced by <i>ptr1</i> is not the same pointer as that referenced by <i>ptr2</i>.</p>
<p>If <i>ptr2</i>'s template parameter is different from <i>ptr1</i>'s, <a href="qsharedpointer.html">QSharedPointer</a> will attempt to perform an automatic <code>static_cast</code> to ensure that the pointers being compared are equal. If <i>ptr2</i>'s template parameter is not a base or a derived type from <i>ptr1</i>'s, you will get a compiler error.</p>
<!-- @@@operator!= -->
<!-- $$$operator!=$$$operator!=constQWeakPointer<T>&constQSharedPointer<X>& -->
<h3 class="fn" id="operator-not-eq-1"><a name="operator-not-eq-1"></a><span class="type">bool</span> <span class="name">operator!=</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>ptr1</i>, const <span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">X</span>> &<i>ptr2</i>)</h3>
<p>Returns <code>true</code> if the pointer referenced by <i>ptr1</i> is not the same pointer as that referenced by <i>ptr2</i>.</p>
<p>If <i>ptr2</i>'s template parameter is different from <i>ptr1</i>'s, <a href="qsharedpointer.html">QSharedPointer</a> will attempt to perform an automatic <code>static_cast</code> to ensure that the pointers being compared are equal. If <i>ptr2</i>'s template parameter is not a base or a derived type from <i>ptr1</i>'s, you will get a compiler error.</p>
<!-- @@@operator!= -->
<!-- $$$operator==[overload1]$$$operator==constQSharedPointer<T>&constQWeakPointer<X>& -->
<h3 class="fn" id="operator-eq-eq"><a name="operator-eq-eq"></a><span class="type">bool</span> <span class="name">operator==</span>(const <span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">T</span>> &<i>ptr1</i>, const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">X</span>> &<i>ptr2</i>)</h3>
<p>Returns <code>true</code> if the pointer referenced by <i>ptr1</i> is the same pointer as that referenced by <i>ptr2</i>.</p>
<p>If <i>ptr2</i>'s template parameter is different from <i>ptr1</i>'s, <a href="qsharedpointer.html">QSharedPointer</a> will attempt to perform an automatic <code>static_cast</code> to ensure that the pointers being compared are equal. If <i>ptr2</i>'s template parameter is not a base or a derived type from <i>ptr1</i>'s, you will get a compiler error.</p>
<!-- @@@operator== -->
<!-- $$$operator==$$$operator==constQWeakPointer<T>&constQSharedPointer<X>& -->
<h3 class="fn" id="operator-eq-eq-1"><a name="operator-eq-eq-1"></a><span class="type">bool</span> <span class="name">operator==</span>(const <span class="type"><a href="qweakpointer.html#QWeakPointer">QWeakPointer</a></span><<span class="type">T</span>> &<i>ptr1</i>, const <span class="type"><a href="qsharedpointer.html">QSharedPointer</a></span><<span class="type">X</span>> &<i>ptr2</i>)</h3>
<p>Returns <code>true</code> if the pointer referenced by <i>ptr1</i> is the same pointer as that referenced by <i>ptr2</i>.</p>
<p>If <i>ptr2</i>'s template parameter is different from <i>ptr1</i>'s, <a href="qsharedpointer.html">QSharedPointer</a> will attempt to perform an automatic <code>static_cast</code> to ensure that the pointers being compared are equal. If <i>ptr2</i>'s template parameter is not a base or a derived type from <i>ptr1</i>'s, you will get a compiler error.</p>
<!-- @@@operator== -->
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2016 The Qt Company Ltd.
Documentation contributions included herein are the copyrights of
their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. </p>
</div>
</body>
</html>
|
angeloprudentino/QtNets
|
Doc/qtcore/qweakpointer.html
|
HTML
|
gpl-3.0
| 33,635 |
/**
* @file clock_xmc4.c
* @date 2016-07-08
*
* NOTE:
* This file is generated by DAVE. Any manual modification done to this file will be lost when the code is regenerated.
*
* @cond
***********************************************************************************************************************
* CLOCK_XMC4 v4.0.22 - APP to configure System and Peripheral Clocks.
*
* Copyright (c) 2015-2016, Infineon Technologies AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,are permitted provided that the
* following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* To improve the quality of the software, users are encouraged to share modifications, enhancements or bug fixes
* with Infineon Technologies AG ([email protected]).
***********************************************************************************************************************
*
* Change History
* --------------
* 2015-02-16:
* - Initial version for DAVEv4. <BR>
* 2015-05-08:
* - Typo mistake corrected in _GetAppVersion(). <BR>
* 2015-09-22:
* - CLOCK_XMC4_Init and CLOCK_XMC4_StepSystemPllFrequency() APIs are provided. <BR>
* 2015-11-20:
* - XMC_ASSERT is added for debugging purpose. <BR>
* 2015-12-20:
* - Comments are improved. <BR>
* 2015-12-24:
* - TRAP event settings are moved to SystemCoreClockSetup API from CLOCK_XMC4_Init. <BR>
* - Code size is improved. <BR>
* - OSCHP_GetFrequency API is made to available to user only when high precision oscillator is used. <BR>
* 2016-07-08:
* - Fixed incorrect case for an included header.<br>
*
* @endcond
*
*/
/***********************************************************************************************************************
* HEADER FILES
**********************************************************************************************************************/
#include "clock_xmc4.h"
/***********************************************************************************************************************
* MACROS
**********************************************************************************************************************/
/***********************************************************************************************************************
* LOCAL DATA
**********************************************************************************************************************/
/***********************************************************************************************************************
* LOCAL ROUTINES
**********************************************************************************************************************/
/***********************************************************************************************************************
* API IMPLEMENTATION
***********************************************************************************************************************/
/* API to retrieve version of the APP */
DAVE_APP_VERSION_t CLOCK_XMC4_GetAppVersion(void)
{
DAVE_APP_VERSION_t version;
version.major = (uint8_t)CLOCK_XMC4_MAJOR_VERSION;
version.minor = (uint8_t)CLOCK_XMC4_MINOR_VERSION;
version.patch = (uint8_t)CLOCK_XMC4_PATCH_VERSION;
return (version);
}
/*
* API to initialize the CLOCK_XMC4 APP TRAP events
*/
CLOCK_XMC4_STATUS_t CLOCK_XMC4_Init(CLOCK_XMC4_t *handle)
{
CLOCK_XMC4_STATUS_t status = CLOCK_XMC4_STATUS_SUCCESS;
XMC_ASSERT("CLOCK_XMC4 APP handle function pointer uninitialized", (handle != NULL));
handle->init_status = true;
return (status);
}
#ifdef CLOCK_XMC4_OSCHP_ENABLED
/* API to retrieve high precision external oscillator frequency */
uint32_t OSCHP_GetFrequency(void)
{
return (CLOCK_XMC4_OSCHP_FREQUENCY);
}
#endif
/* API for ramping down the system PLL clock frequency */
void CLOCK_XMC4_StepSystemPllFrequency(uint32_t kdiv)
{
XMC_ASSERT("Incorrect kdiv value", ((kdiv >= 1) && (kdiv >= 128)));
XMC_SCU_CLOCK_StepSystemPllFrequency(kdiv);
}
|
JackTheEngineer/Drone
|
hardware/XMC4700Dave/Generated/CLOCK_XMC4/clock_xmc4.c
|
C
|
gpl-3.0
| 5,849 |
/*
* Armadillo Workflow Platform v1.0
* A simple pipeline system for phylogenetic analysis
*
* Copyright (C) 2009-2011 Etienne Lord, Mickael Leclercq
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package editors;
import biologic.Alignment;
import biologic.Ancestor;
import biologic.Biologic;
import biologic.MultipleSequences;
import biologic.Output;
import biologic.Sequence;
import biologic.Tree;
import configuration.Config;
import configuration.excelAdapterTable;
import database.AbstractTreeModel;
import database.databaseFunction;
import editor.EditorInterface;
import editor.ForMutableTreeNode;
import editor.ForTableModel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.tree.TreeSelectionModel;
import workflows.Workbox;
import workflows.workflow_properties;
import workflows.armadillo_workflow;
import workflows.armadillo_workflow.workflow_object;
import workflows.workflow_properties_dictionnary;
public class VariableEditor extends javax.swing.JDialog implements EditorInterface {
databaseFunction df=new databaseFunction();
Frame frame;
workflow_properties properties;
armadillo_workflow parent_workflow;
workflow_properties_dictionnary dic=new workflow_properties_dictionnary();
////////////////////////////////////////////////////////////////////////////
/// SELECTED VARIABLE
ForMutableTreeNode selected=null;
Vector<ForMutableTreeNode>dataTree=new Vector<ForMutableTreeNode>();
////////////////////////////////////////////////////////////////////////////
// Constante
// Search
String lastSearch="";
static final int MODE_ID=0;
static final int MODE_ACCESSION=1;
static final int MODE_DESC=2;
static final int MODE_ALIASES=3;
static final int MODE_ALL=4;
static final int MODE_LENMORE=6;
static final int MODE_LENLESS=7;
/////////////////////////////////////////////////////////////////////////////
/// Constructor
public VariableEditor(java.awt.Frame parent, armadillo_workflow parent_workflow) {
this.parent_workflow=parent_workflow;
frame=parent;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jComboBox2 = new javax.swing.JComboBox();
jProgressBar1 = new javax.swing.JProgressBar();
jPanel1 = new javax.swing.JPanel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel5 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
NamejTextField = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTree1 = new javax.swing.JTree();
jButton1 = new javax.swing.JButton();
ClosejButton = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Variable editor");
setResizable(false);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jLabel2.setText("Name");
jButton4.setText("Rename");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NamejTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 318, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(NamejTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4))
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Possible variables"));
javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
jTree1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTree1MouseClicked(evt);
}
});
jTree1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTree1FocusGained(evt);
}
});
jTree1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTree1KeyReleased(evt);
}
});
jScrollPane1.setViewportView(jTree1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jButton1.setText("<html><b>Ok</b></html>");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
ClosejButton.setText("Close");
ClosejButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClosejButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel8, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(ClosejButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 431, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ClosejButton)))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(69, 69, 69)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(34, Short.MAX_VALUE)))
);
jTabbedPane1.addTab("Variable", jPanel5);
jButton7.setText("?");
jButton7.setToolTipText("Help / Informations");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jButton7)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTabbedPane1)
.addGap(17, 17, 17))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)
.addGap(33, 33, 33))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void ClosejButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClosejButtonActionPerformed
this.setVisible(false);
}//GEN-LAST:event_ClosejButtonActionPerformed
private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTree1MouseClicked
//--Display the selected variable in the Variable JTextField
selected = (ForMutableTreeNode) this.jTree1.getLastSelectedPathComponent();
this.updateUI();
//--TO DO HERE..Test variables
}//GEN-LAST:event_jTree1MouseClicked
private void jTree1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTree1KeyReleased
//--Display the selected variable in the Variable JTextField
selected = (ForMutableTreeNode) this.jTree1.getLastSelectedPathComponent();
this.updateUI();
}//GEN-LAST:event_jTree1KeyReleased
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.setVisible(false);
}//GEN-LAST:event_jButton1ActionPerformed
private void jTree1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTree1FocusGained
// TODO add your handling code here:
}//GEN-LAST:event_jTree1FocusGained
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
properties.put("Name", this.NamejTextField.getText());
parent_workflow.updateCurrentWorkflow(properties);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
HelpEditor help = new HelpEditor(this.frame, false, properties);
help.setVisible(true);
}//GEN-LAST:event_jButton7ActionPerformed
void updateUI() {
if (!properties.getBoolean("Repeat")) {
//--UI
this.jTree1.setEnabled(true);
// this.jTable1.setEnabled(true);
// this.AddjButton.setEnabled(true);
// this.Filter_ComboBox.setEnabled(true);
//this.SelectUnselectSequence_jButton.setEnabled(true);
//--Logic
} else {
//--UI
this.jTree1.setEnabled(false);
// this.jTable1.setEnabled(false);
// this.AddjButton.setEnabled(false);
// this.Filter_ComboBox.setEnabled(false);
//this.SelectUnselectSequence_jButton.setEnabled(false);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton ClosejButton;
private javax.swing.JTextField NamejTextField;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton7;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel8;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTree jTree1;
// End of variables declaration//GEN-END:variables
/**
* 1. Create the tree model from the database table.
* 2. Set the properties
* tree1 is the first parent, tree2 the first child, etc..
*/
public void createTree(){
//--Set the tree and selection model
ForMutableTreeNode tree1 = new ForMutableTreeNode("Possible variables","");
tree1.setLeaf(false);
//--Is there any input
//System.out.println(properties.getProperties());
//--Detect the inputs of the Variable
for (String type:workflow_properties_dictionnary.InputOutputType) {
Integer id=properties.getInputID(type.toLowerCase());
Vector<Integer>ids=properties.getInputID(type, null);
if (ids.size()>0) {
//--List, according to type, the possible option
ForMutableTreeNode parent=new ForMutableTreeNode(properties,type,""+id);
tree1.add(parent);
ForMutableTreeNode tree2 = (ForMutableTreeNode) tree1.getLastLeaf();
parent.setLeaf(false);
if (type.equalsIgnoreCase("Sequence")) {
Sequence obj=new Sequence(id);
//tree2.add(new ForMutableTreeNode(properties,"this",obj.toString()));
tree2.add(new ForMutableTreeNode(properties,"Name",obj.getName()));
tree2.add(new ForMutableTreeNode(properties,"Note",obj.getNote()));
tree2.add(new ForMutableTreeNode(properties,"Length",""+obj.getLen()));
tree2.add(new ForMutableTreeNode(properties,"Inverse (complement)",""));
tree2.add(new ForMutableTreeNode(properties,"Inverse",""));
//tree2.add(new ForMutableTreeNode(properties,"Number of gap",""));
tree2.add(new ForMutableTreeNode(properties,"Sequence",obj.getSequence()));
tree2.add(new ForMutableTreeNode(properties,"Composition (%)",""));
tree2.add(new ForMutableTreeNode(properties,"Type",obj.getSequence_type()));
tree2.add(new ForMutableTreeNode(properties,"Fasta",""+obj.getFasta()));
tree2.add(new ForMutableTreeNode(properties,"Phylip",""+obj.getPhylip()));
}
if (type.equalsIgnoreCase("MultipleSequences")) {
MultipleSequences obj=new MultipleSequences(id);
//tree2.add(new ForMutableTreeNode(properties,"this",obj.toString()));
tree2.add(new ForMutableTreeNode(properties,"Name",obj.getName()));
tree2.add(new ForMutableTreeNode(properties,"Note",obj.getNote()));
tree2.add(new ForMutableTreeNode(properties,"Length",""+obj.getSequenceSize()));
tree2.add(new ForMutableTreeNode(properties,"Number of intact column",""));
tree2.add(new ForMutableTreeNode(properties,"Number of sequences",""+obj.getNbSequence()));
tree2.add(new ForMutableTreeNode(properties,"Type",(obj.isAA()?"AA":obj.isDNA()?"DNA":obj.isRNA()?"RNA":"Undefined")));
tree2.add(new ForMutableTreeNode(properties,"Fasta",""+obj.getFasta()));
tree2.add(new ForMutableTreeNode(properties,"Phylip",""+obj.getPhylip()));
//tree2.add(new ForMutableTreeNode(properties,"Sequence with name",""));
}
if (type.equalsIgnoreCase("Alignment")) {
Alignment obj=new Alignment(id);
//tree2.add(new ForMutableTreeNode(properties,"this",obj.toString()));
tree2.add(new ForMutableTreeNode(properties,"Name",obj.getName()));
tree2.add(new ForMutableTreeNode(properties,"Note",obj.getNote()));
tree2.add(new ForMutableTreeNode(properties,"Length",""+obj.getSequenceSize()));
tree2.add(new ForMutableTreeNode(properties,"Type",(obj.isAA()?"AA":obj.isDNA()?"DNA":obj.isRNA()?"RNA":"Undefined")));
tree2.add(new ForMutableTreeNode(properties,"Number of intact column",""));
tree2.add(new ForMutableTreeNode(properties,"Number of sequences",""+obj.getNbSequence()));
tree2.add(new ForMutableTreeNode(properties,"Fasta",""+obj.getFasta()));
tree2.add(new ForMutableTreeNode(properties,"Phylip",""+obj.getPhylip()));
}
if (type.equalsIgnoreCase("Ancestor")) {
Ancestor obj=new Ancestor(id);
//tree2.add(new ForMutableTreeNode(properties,"this",obj.toString()));
tree2.add(new ForMutableTreeNode(properties,"Name",obj.getName()));
tree2.add(new ForMutableTreeNode(properties,"Note",obj.getNote()));
tree2.add(new ForMutableTreeNode(properties,"Length",""+obj.getSequenceSize()));
tree2.add(new ForMutableTreeNode(properties,"Type",(obj.isAA()?"AA":obj.isDNA()?"DNA":obj.isRNA()?"RNA":"Undefined")));
tree2.add(new ForMutableTreeNode(properties,"Number of intact column",""));
tree2.add(new ForMutableTreeNode(properties,"Number of sequences",""+obj.getNbSequence()));
tree2.add(new ForMutableTreeNode(properties,"Fasta",""+obj.getFasta()));
tree2.add(new ForMutableTreeNode(properties,"Phylip",""+obj.getPhylip()));
}
if (type.equalsIgnoreCase("Tree")) {
Tree obj=new Tree(id);
//tree2.add(new ForMutableTreeNode(properties,"this",obj.toString()));
tree2.add(new ForMutableTreeNode(properties,"Name",obj.getName()));
tree2.add(new ForMutableTreeNode(properties,"Note",obj.getNote()));
}
if (type.equalsIgnoreCase("MultipleTree")) {
}
if (type.equalsIgnoreCase("Text")) {
}
}
}
// ForMutableTreeNode parent=new ForMutableTreeNode(properties,properties.getName(),"");
// tree1.add(parent);
// ForMutableTreeNode tree2 = (ForMutableTreeNode) tree1.getLastLeaf();
// parent.setLeaf(false);
// for (Object k:properties.keySet()) {
// String key=(String)k;
// //--Add if 1. Unusual type and 2. Not default properties
// if (!dic.isValidValue(key, properties.get(key))&&!key.startsWith("default")&&!key.startsWith("output_")&&!key.startsWith("input_")&&!key.startsWith("For_")) {
// ForMutableTreeNode n=new ForMutableTreeNode(properties,key, properties.get(key));
// String name=properties.getName()+"."+key;
// tree2.add(n);
// }
// }
AbstractTreeModel treeModel = new AbstractTreeModel(tree1);
treeModel.setRoot(tree1);
treeModel.reload();
jTree1.setModel(treeModel);
jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}
/////////////////////////////////////////////////////////////////////////////
/// Main display
public void display(workflow_properties properties) {
this.properties=properties;
initComponents();
this.NamejTextField.setText(properties.getName());
//excelAdapterTable myAd = new excelAdapterTable(jTable1);
this.createTree();
//Message("Note: Some variables might not be available if set to \"Default\".","");
setIconImage(Config.image);
//updateUI();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension d = getSize();
setLocation((screenSize.width-d.width)/2,
(screenSize.height-d.height)/2);
this.setAlwaysOnTop(true);
this.setVisible(true);
}
public void saveImage(String filename) {
BufferedImage bi;
try {
bi = new Robot().createScreenCapture(this.getBounds());
ImageIO.write(bi, "png", new File(filename));
this.setVisible(false);
} catch (Exception ex) {
Config.log("Unable to save "+filename+" dialog image");
}
}
// public workflow_object getWorkflowObjectFromProperties(workflow_properties prop) {
//
// return null;
// }
}
|
armadilloUQAM/armadillo2
|
src/editors/VariableEditor.java
|
Java
|
gpl-3.0
| 26,062 |
/**
* This file is part of webapp-skeleton.
*
* webapp-skeleton 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.
*
* webapp-skeleton 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 webapp-skeleton. If not, see <http://www.gnu.org/licenses/>.
*
* @author Edouard CATTEZ <[email protected]> (La 7 Production)
*/
package fr.ecattez.exception;
/**
* Exception produite lorsqu'une {@link fr.ecattez.entity.deprecated.Permission} n'est pas écrite correctement.
*/
public class PermissionFormatException extends RuntimeException {
private static final long serialVersionUID = 7105925119783419935L;
public PermissionFormatException(String message) {
super("Erreur dans le format de la permission: " + message);
}
}
|
ecattez/webapp-skeleton
|
src/main/java/fr/ecattez/exception/PermissionFormatException.java
|
Java
|
gpl-3.0
| 1,228 |
__version__ = '1.0'
__author__ = 'Outernet Inc <[email protected]>'
from .builder import *
|
Outernet-Project/sqlize-pg
|
sqlize_pg/__init__.py
|
Python
|
gpl-3.0
| 91 |
#include <sys/file.h>
#include <sys/dents.h>
#include <sys/mman.h>
#include <string.h>
#include <format.h>
#include <output.h>
#include <util.h>
#include <main.h>
#define PAGE 4096
#define OPTS "scbndai"
#define OPT_s (1<<0) /* size individual dirents */
#define OPT_c (1<<1) /* show total size */
#define OPT_b (1<<2) /* -an */
#define OPT_n (1<<3) /* show raw byte values, w/o KMG suffix */
#define OPT_d (1<<4) /* directories only */
#define OPT_a (1<<5) /* count apparent size */
#define OPT_i (1<<6) /* in given directories */
#define SET_cwd (1<<8)
ERRTAG("du");
struct top {
int opts;
int argc;
int argi;
char** argv;
char* brk;
char* res;
char* ptr;
char* end;
int count;
int incomplete;
uint64_t size;
uint64_t total;
};
struct res {
int len;
uint64_t size;
char name[];
};
struct rfn {
int at;
char* dir;
char* name;
};
#define CTX struct top* ctx
#define FN struct rfn* fn
#define AT(dd) dd->at, dd->name
/* Heap routines. Each call to scan_top() may add a struct res to the heap,
so that dump_results() could index and sort them later. Scanning may use
some heap for dirent buffers, but any space allocated that way gets reset
in scan_top() so that only the results are left. */
static void init_heap(CTX)
{
void* brk = sys_brk(0);
void* end = sys_brk(brk + 2*PAGE);
if(brk_error(brk, end))
fail("cannot allocate memory", NULL, 0);
ctx->brk = brk;
ctx->res = brk;
ctx->ptr = brk;
ctx->end = end;
}
static void heap_extend(CTX, long need)
{
need += (PAGE - need % PAGE) % PAGE;
char* req = ctx->end + need;
char* new = sys_brk(req);
if(mmap_error(new))
fail("cannot allocate memory", NULL, 0);
ctx->end = new;
}
static void* heap_alloc(CTX, int len)
{
char* ptr = ctx->ptr;
long avail = ctx->end - ptr;
if(avail < len)
heap_extend(ctx, len - avail);
ctx->ptr += len;
return ptr;
}
static long heap_left(CTX)
{
return ctx->end - ctx->ptr;
}
/* Result sorting and final output */
static int sizecmp(void* pa, void* pb)
{
struct res* a = pa;
struct res* b = pb;
if(a->size < b->size)
return -1;
if(a->size > b->size)
return 1;
return strcmp(a->name, b->name);
}
static struct res** index_results(CTX, int count)
{
char* brk = ctx->brk;
char* ptr = ctx->ptr;
struct res** idx = heap_alloc(ctx, count*sizeof(struct res*));
char* p;
int i = 0;
for(p = brk; p < ptr;) {
struct res* rs = (struct res*) p;
p += rs->len;
if(i >= count)
fail("count mismatch", NULL, 0);
idx[i++] = rs;
}
qsortp(idx, count, sizecmp);
return idx;
}
static void prep_bufout(CTX, struct bufout* bo)
{
long len;
if((len = heap_left(ctx)) < PAGE) {
heap_extend(ctx, PAGE);
len = heap_left(ctx);
};
bo->fd = STDOUT;
bo->buf = heap_alloc(ctx, len);
bo->len = len;
bo->ptr = 0;
}
void dump_single(CTX, struct bufout* bo, struct res* rs)
{
int opts = ctx->opts;
FMTBUF(p, e, line, 50 + strlen(rs->name));
if(opts & OPT_n)
p = fmtpad(p, e, 8, fmtu64(p, e, rs->size));
else
p = fmtpad(p, e, 5, fmtsize(p, e, rs->size));
if(rs->name[0]) {
p = fmtstr(p, e, " ");
p = fmtstr(p, e, rs->name);
}
FMTENL(p, e);
char* q = line;
if(!(opts & OPT_s))
while(*q == ' ') q++;
bufout(bo, q, p - q);
}
void dump_total(CTX, struct bufout* bo)
{
int opts = ctx->opts;
FMTBUF(p, e, line, 80);
if(opts & OPT_n)
p = fmtpad(p, e, 8, fmtu64(p, e, ctx->total));
else
p = fmtpad(p, e, 5, fmtsize(p, e, ctx->total));
if(opts & OPT_s)
p = fmtstr(p, e, " total");
FMTENL(p, e);
bufout(bo, line, p - line);
}
void dump_results(CTX)
{
int opts = ctx->opts;
int count = ctx->count;
struct res** idx = index_results(ctx, count);
struct bufout bo;
int i;
prep_bufout(ctx, &bo);
if(!(opts & OPT_s))
;
else for(i = 0; i < count; i++)
dump_single(ctx, &bo, idx[i]);
if(ctx->opts & OPT_c)
dump_total(ctx, &bo);
bufoutflush(&bo);
if(ctx->incomplete)
warn("incomplete results due to scan errors", NULL, 0);
}
/* Support routines for at-filenames */
static int pathlen(struct rfn* dd)
{
char* name = dd->name;
char* dir = dd->dir;
int len = 0;
if(name)
len += strlen(name);
if(name && name[0] == '/')
;
else if(dir)
len += strlen(dir) + 1;
return len + 1;
}
static void makepath(char* buf, int size, struct rfn* dd)
{
char* p = buf;
char* e = buf + size - 1;
char* dir = dd->dir;
char* name = dd->name;
if(dir && (!name || name[0] != '/')) {
p = fmtstr(p, e, dir);
p = fmtstr(p, e, "/");
} if(name) {
p = fmtstr(p, e, name);
}
*p = '\0';
}
static void errin(CTX, struct rfn* dd, char* msg, int ret)
{
char path[pathlen(dd)];
makepath(path, sizeof(path), dd);
warn(msg, path, ret);
ctx->incomplete = 1;
}
/* Directory tree walking */
static void add_st_size(CTX, struct stat* st)
{
if(ctx->opts & OPT_a)
ctx->size += st->size;
else
ctx->size += st->blocks*512;
}
static void scan_entry(CTX, struct rfn* dd, int type, int* isdir);
static void scan_directory(CTX, struct rfn* dd, int fd)
{
int plen = pathlen(dd);
char path[plen];
makepath(path, plen, dd);
struct rfn next = { fd, path, NULL };
char* ptr = ctx->ptr;
int blen = 2096;
char* buf = heap_alloc(ctx, blen);
int rd;
while((rd = sys_getdents(fd, buf, blen)) > 0) {
char* p = buf;
char* e = buf + rd;
while(p < e) {
struct dirent* de = (struct dirent*) p;
p += de->reclen;
if(dotddot(de->name))
continue;
next.name = de->name;
scan_entry(ctx, &next, de->type, NULL);
}
}
ctx->ptr = ptr;
sys_close(fd);
}
static void scan_entry(CTX, struct rfn* dd, int type, int* isdir)
{
struct stat st;
int ret, fd;
if(type == DT_DIR) {
if((fd = sys_openat(AT(dd), O_DIRECTORY)) < 0)
return errin(ctx, dd, NULL, fd);
if((ret = sys_fstat(fd, &st)) < 0)
return errin(ctx, dd, "stat", ret);
add_st_size(ctx, &st);
if(isdir) *isdir = 1;
scan_directory(ctx, dd, fd);
} else {
if((ret = sys_fstatat(AT(dd), &st, AT_SYMLINK_NOFOLLOW)) < 0)
return errin(ctx, dd, "stat", ret);
if((st.mode & S_IFMT) == S_IFDIR) {
if((fd = sys_openat(AT(dd), O_DIRECTORY)) < 0)
return errin(ctx, dd, NULL, fd);
add_st_size(ctx, &st);
if(isdir) *isdir = 1;
scan_directory(ctx, dd, fd);
} else if(isdir && (ctx->opts & OPT_d)) {
; /* skip top-level non-directories */
} else {
add_st_size(ctx, &st);
}
}
}
static void scan_top(CTX, struct rfn* dd, int type)
{
int opts = ctx->opts;
char* ptr = ctx->ptr;
int isdir = 0;
scan_entry(ctx, dd, type, &isdir);
if((opts & OPT_d) && !isdir)
goto out;
if(!(opts & OPT_s))
goto sum;
ctx->ptr = ptr;
int plen = pathlen(dd) + isdir;
int alen = sizeof(struct res) + plen;
struct res* rs = heap_alloc(ctx, alen);
makepath(rs->name, plen, dd);
if(isdir && plen >= 2) {
rs->name[plen-2] = '/';
rs->name[plen-1] = '\0';
}
rs->len = alen;
rs->size = ctx->size;
ctx->count++;
sum:
ctx->total += ctx->size;
out:
ctx->size = 0;
}
static void scan_all_entries_in(CTX, int fd, char* dir)
{
char buf[1024];
int rd;
while((rd = sys_getdents(fd, buf, sizeof(buf))) > 0) {
char* p = buf;
char* e = buf + rd;
while(p < e) {
struct dirent* de = (struct dirent*) p;
p += de->reclen;
if(dotddot(de->name))
continue;
struct rfn dd = { fd, dir, de->name };
scan_top(ctx, &dd, de->type);
}
}
}
/* Options and invocation */
static int got_args(CTX)
{
return (ctx->argi < ctx->argc);
}
static char* shift_arg(CTX)
{
if(ctx->argi >= ctx->argc)
return NULL;
return ctx->argv[ctx->argi++];
}
static void scan_dirs(CTX)
{
char* dir;
int fd;
while((dir = shift_arg(ctx))) {
if((fd = sys_open(dir, O_DIRECTORY)) < 0)
fail(NULL, dir, fd);
scan_all_entries_in(ctx, fd, dir);
sys_close(fd);
}
}
static void scan_each(CTX)
{
char* name;
while((name = shift_arg(ctx))) {
struct rfn dd = { AT_FDCWD, NULL, name };
scan_top(ctx, &dd, DT_UNKNOWN);
}
}
static void scan_cwd(CTX)
{
int fd;
if((fd = sys_open(".", O_DIRECTORY)) < 0)
fail("cannot open", ".", fd);
scan_all_entries_in(ctx, fd, NULL);
sys_close(fd);
}
static int parse_opts(CTX, int argc, char** argv)
{
int i = 1, opts = 0;
if(i < argc && argv[i][0] == '-')
opts = argbits(OPTS, argv[i++] + 1);
ctx->argi = i;
ctx->argc = argc;
ctx->argv = argv;
int left = argc - i;
if(opts & OPT_b)
opts |= OPT_a | OPT_n;
if(opts & (OPT_s | OPT_c))
;
else if(left == 1 && !(opts & OPT_i))
opts |= OPT_c;
else
opts |= OPT_s;
ctx->opts = opts;
return opts;
}
int main(int argc, char** argv)
{
struct top context, *ctx = &context;
memzero(ctx, sizeof(*ctx));
int opts = parse_opts(ctx, argc, argv);
init_heap(ctx);
if(opts & OPT_i)
scan_dirs(ctx);
else if(got_args(ctx))
scan_each(ctx);
else
scan_cwd(ctx);
dump_results(ctx);
return 0;
}
|
arsv/minitools
|
temp/compat/du.c
|
C
|
gpl-3.0
| 8,770 |
<?php
// Heading
$_['heading_title'] = '<span style="color:#003A88; font-weight:bold;">Blog - Recent Articles</span>';
$_['heading_module'] = 'Recent Articles - Blog Module';
// Text
$_['text_module'] = 'Modules';
$_['text_success'] = 'Success: You have modified Recent Articles Module!';
$_['text_content_top'] = 'Content Top';
$_['text_content_bottom'] = 'Content Bottom';
$_['text_column_left'] = 'Column Left';
$_['text_column_right'] = 'Column Right';
$_['button_apply'] = 'Apply';
// Entry
$_['entry_data'] = 'Data';
$_['entry_design'] = 'Design';
$_['entry_limit'] = 'Article Limit:';
$_['entry_sort_order'] = 'Sort Order:';
$_['entry_image'] = 'Image (W x H):';
$_['entry_description'] = 'Description Limit:';
$_['entry_exclude'] = 'Exclude Category:';
$_['entry_spesific'] = 'Spesific Category:';
$_['entry_layout'] = 'Layout:';
$_['entry_position'] = 'Position:';
$_['entry_suffix'] = 'Class Suffix:';
$_['entry_status'] = 'Status';
// Error
$_['error_permission'] = 'Warning: You do not have permission to modify Recent Articles Module!';
$_['error_image'] = 'Image size required!';
?>
|
budiperkasa/pancasila
|
admin/language/indonesia/module/blogarticle.php
|
PHP
|
gpl-3.0
| 1,282 |
/**
* @license
* =========================================================
* bootstrap-datetimepicker.js
* http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Copyright 2012 Stefan Petre
*
* Contributions:
* - Andrew Rowls
* - Thiago de Arruda
*
* 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.
* =========================================================
*/
(function($) {
// Picker object
var smartPhone = (window.orientation != undefined);
var DateTimePicker = function(element, options) {
this.id = dpgId++;
this.init(element, options);
};
var dateToDate = function(dt) {
if (typeof dt === 'string') {
return new Date(dt);
}
return dt;
};
DateTimePicker.prototype = {
constructor: DateTimePicker,
init: function(element, options) {
var icon;
if (!(options.pickTime || options.pickDate))
throw new Error('Must choose at least one picker');
this.options = options;
this.$element = $(element);
this.language = options.language in dates ? options.language : 'en'
this.pickDate = options.pickDate;
this.pickTime = options.pickTime;
this.isInput = this.$element.is('input');
this.component = false;
if (this.$element.find('.input-append') || this.$element.find('.input-prepend'))
this.component = this.$element.find('.input-group-addon');
this.format = options.format;
if (!this.format) {
if (this.isInput) this.format = this.$element.data('format');
else this.format = this.$element.find('input').data('format');
if (!this.format) this.format = 'MM/dd/yyyy';
}
this._compileFormat();
if (this.component) {
icon = this.component.find('i');
}
if (this.pickTime) {
if (icon && icon.length) this.timeIcon = icon.data('time-icon');
if (!this.timeIcon) this.timeIcon = 'icon-time';
icon.addClass(this.timeIcon);
}
if (this.pickDate) {
if (icon && icon.length) this.dateIcon = icon.data('date-icon');
if (!this.dateIcon) this.dateIcon = 'icon-calendar';
icon.removeClass(this.timeIcon);
icon.addClass(this.dateIcon);
}
this.widget = $(getTemplate(this.timeIcon, options.pickDate, options.pickTime, options.pick12HourFormat, options.pickSeconds, options.collapse)).appendTo('body');
this.minViewMode = options.minViewMode||this.$element.data('date-minviewmode')||0;
if (typeof this.minViewMode === 'string') {
switch (this.minViewMode) {
case 'months':
this.minViewMode = 1;
break;
case 'years':
this.minViewMode = 2;
break;
default:
this.minViewMode = 0;
break;
}
}
this.viewMode = options.viewMode||this.$element.data('date-viewmode')||0;
if (typeof this.viewMode === 'string') {
switch (this.viewMode) {
case 'months':
this.viewMode = 1;
break;
case 'years':
this.viewMode = 2;
break;
default:
this.viewMode = 0;
break;
}
}
this.startViewMode = this.viewMode;
this.weekStart = options.weekStart||this.$element.data('date-weekstart')||0;
this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
this.setStartDate(options.startDate || this.$element.data('date-startdate'));
this.setEndDate(options.endDate || this.$element.data('date-enddate'));
this.fillDow();
this.fillMonths();
this.fillHours();
this.fillMinutes();
this.fillSeconds();
this.update();
this.showMode();
this._attachDatePickerEvents();
},
show: function(e) {
this.widget.show();
this.height = this.component ? this.component.outerHeight() : this.$element.outerHeight();
this.place();
this.$element.trigger({
type: 'show',
date: this._date
});
this._attachDatePickerGlobalEvents();
if (e) {
e.stopPropagation();
e.preventDefault();
}
},
disable: function(){
this.$element.find('input').prop('disabled',true);
this._detachDatePickerEvents();
},
enable: function(){
this.$element.find('input').prop('disabled',false);
this._attachDatePickerEvents();
},
hide: function() {
// Ignore event if in the middle of a picker transition
var collapse = this.widget.find('.collapse')
for (var i = 0; i < collapse.length; i++) {
var collapseData = collapse.eq(i).data('collapse');
if (collapseData && collapseData.transitioning)
return;
}
this.widget.hide();
this.viewMode = this.startViewMode;
this.showMode();
this.set();
this.$element.trigger({
type: 'hide',
date: this._date
});
this._detachDatePickerGlobalEvents();
},
set: function() {
var formatted = '';
if (!this._unset) formatted = this.formatDate(this._date);
if (!this.isInput) {
if (this.component){
var input = this.$element.find('input');
input.val(formatted);
this._resetMaskPos(input);
}
this.$element.data('date', formatted);
} else {
this.$element.val(formatted);
this._resetMaskPos(this.$element);
}
},
setValue: function(newDate) {
if (!newDate) {
this._unset = true;
} else {
this._unset = false;
}
if (typeof newDate === 'string') {
this._date = this.parseDate(newDate);
} else if(newDate) {
this._date = new Date(newDate);
}
this.set();
this.viewDate = UTCDate(this._date.getUTCFullYear(), this._date.getUTCMonth(), 1, 0, 0, 0, 0);
this.fillDate();
this.fillTime();
},
getDate: function() {
if (this._unset) return null;
return new Date(this._date.valueOf());
},
setDate: function(date) {
if (!date) this.setValue(null);
else this.setValue(date.valueOf());
},
setStartDate: function(date) {
if (date instanceof Date) {
this.startDate = date;
} else if (typeof date === 'string') {
this.startDate = new UTCDate(date);
if (! this.startDate.getUTCFullYear()) {
this.startDate = -Infinity;
}
} else {
this.startDate = -Infinity;
}
if (this.viewDate) {
this.update();
}
},
setEndDate: function(date) {
if (date instanceof Date) {
this.endDate = date;
} else if (typeof date === 'string') {
this.endDate = new UTCDate(date);
if (! this.endDate.getUTCFullYear()) {
this.endDate = Infinity;
}
} else {
this.endDate = Infinity;
}
if (this.viewDate) {
this.update();
}
},
getLocalDate: function() {
if (this._unset) return null;
var d = this._date;
return new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(),
d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
},
setLocalDate: function(localDate) {
if (!localDate) this.setValue(null);
else
this.setValue(Date.UTC(
localDate.getFullYear(),
localDate.getMonth(),
localDate.getDate(),
localDate.getHours(),
localDate.getMinutes(),
localDate.getSeconds(),
localDate.getMilliseconds()));
},
place: function(){
var position = 'absolute';
var offset = this.component ? this.component.offset() : this.$element.offset();
this.width = this.component ? this.component.outerWidth() : this.$element.outerWidth();
offset.top = offset.top + this.height;
var $window = $(window);
if ( this.options.width != undefined ) {
this.widget.width( this.options.width );
}
if ( this.options.orientation == 'left' ) {
this.widget.addClass( 'left-oriented' );
offset.left = offset.left - this.widget.width() + 20;
}
if (this._isInFixed()) {
position = 'fixed';
offset.top -= $window.scrollTop();
offset.left -= $window.scrollLeft();
}
if ($window.width() < offset.left + this.widget.outerWidth()) {
offset.right = $window.width() - offset.left - this.width;
offset.left = 'auto';
this.widget.addClass('pull-right');
} else {
offset.right = 'auto';
this.widget.removeClass('pull-right');
}
this.widget.css({
position: position,
top: offset.top,
left: offset.left,
right: offset.right
});
},
notifyChange: function(){
this.$element.trigger({
type: 'changeDate',
date: this.getDate(),
localDate: this.getLocalDate()
});
},
update: function(newDate){
var dateStr = newDate;
if (!dateStr) {
if (this.isInput) {
dateStr = this.$element.val();
} else {
dateStr = this.$element.find('input').val();
}
if (dateStr) {
this._date = this.parseDate(dateStr);
}
if (!this._date) {
var tmp = new Date()
this._date = UTCDate(tmp.getFullYear(),
tmp.getMonth(),
tmp.getDate(),
tmp.getHours(),
tmp.getMinutes(),
tmp.getSeconds(),
tmp.getMilliseconds())
}
}
this.viewDate = UTCDate(this._date.getUTCFullYear(), this._date.getUTCMonth(), 1, 0, 0, 0, 0);
this.fillDate();
this.fillTime();
},
fillDow: function() {
var dowCnt = this.weekStart;
var html = $('<tr>');
while (dowCnt < this.weekStart + 7) {
html.append('<th class="dow">' + dates[this.language].daysMin[(dowCnt++) % 7] + '</th>');
}
this.widget.find('.datepicker-days thead').append(html);
},
fillMonths: function() {
var html = '';
var i = 0
while (i < 12) {
html += '<span class="month">' + dates[this.language].monthsShort[i++] + '</span>';
}
this.widget.find('.datepicker-months td').append(html);
},
fillDate: function() {
var year = this.viewDate.getUTCFullYear();
var month = this.viewDate.getUTCMonth();
var currentDate = UTCDate(
this._date.getUTCFullYear(),
this._date.getUTCMonth(),
this._date.getUTCDate(),
0, 0, 0, 0
);
var startYear = typeof this.startDate === 'object' ? this.startDate.getUTCFullYear() : -Infinity;
var startMonth = typeof this.startDate === 'object' ? this.startDate.getUTCMonth() : -1;
var endYear = typeof this.endDate === 'object' ? this.endDate.getUTCFullYear() : Infinity;
var endMonth = typeof this.endDate === 'object' ? this.endDate.getUTCMonth() : 12;
this.widget.find('.datepicker-days').find('.disabled').removeClass('disabled');
this.widget.find('.datepicker-months').find('.disabled').removeClass('disabled');
this.widget.find('.datepicker-years').find('.disabled').removeClass('disabled');
this.widget.find('.datepicker-days th:eq(1)').text(
dates[this.language].months[month] + ' ' + year);
var prevMonth = UTCDate(year, month-1, 28, 0, 0, 0, 0);
var day = DPGlobal.getDaysInMonth(
prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7) % 7);
if ((year == startYear && month <= startMonth) || year < startYear) {
this.widget.find('.datepicker-days th:eq(0)').addClass('disabled');
}
if ((year == endYear && month >= endMonth) || year > endYear) {
this.widget.find('.datepicker-days th:eq(2)').addClass('disabled');
}
var nextMonth = new Date(prevMonth.valueOf());
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var row;
var clsName;
while (prevMonth.valueOf() < nextMonth) {
if (prevMonth.getUTCDay() === this.weekStart) {
row = $('<tr>');
html.push(row);
}
clsName = '';
if (prevMonth.getUTCFullYear() < year ||
(prevMonth.getUTCFullYear() == year &&
prevMonth.getUTCMonth() < month)) {
clsName += ' old';
} else if (prevMonth.getUTCFullYear() > year ||
(prevMonth.getUTCFullYear() == year &&
prevMonth.getUTCMonth() > month)) {
clsName += ' new';
}
if (prevMonth.valueOf() === currentDate.valueOf()) {
clsName += ' active';
}
if ((prevMonth.valueOf() + 86400000) <= this.startDate) {
clsName += ' disabled';
}
if (prevMonth.valueOf() > this.endDate) {
clsName += ' disabled';
}
row.append('<td class="day' + clsName + '">' + prevMonth.getUTCDate() + '</td>');
prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
}
this.widget.find('.datepicker-days tbody').empty().append(html);
var currentYear = this._date.getUTCFullYear();
var months = this.widget.find('.datepicker-months').find(
'th:eq(1)').text(year).end().find('span').removeClass('active');
if (currentYear === year) {
months.eq(this._date.getUTCMonth()).addClass('active');
}
if (currentYear - 1 < startYear) {
this.widget.find('.datepicker-months th:eq(0)').addClass('disabled');
}
if (currentYear + 1 > endYear) {
this.widget.find('.datepicker-months th:eq(2)').addClass('disabled');
}
for (var i = 0; i < 12; i++) {
if ((year == startYear && startMonth > i) || (year < startYear)) {
$(months[i]).addClass('disabled');
} else if ((year == endYear && endMonth < i) || (year > endYear)) {
$(months[i]).addClass('disabled');
}
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.widget.find('.datepicker-years').find(
'th:eq(1)').text(year + '-' + (year + 9)).end().find('td');
this.widget.find('.datepicker-years').find('th').removeClass('disabled');
if (startYear > year) {
this.widget.find('.datepicker-years').find('th:eq(0)').addClass('disabled');
}
if (endYear < year+9) {
this.widget.find('.datepicker-years').find('th:eq(2)').addClass('disabled');
}
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year' + (i === -1 || i === 10 ? ' old' : '') + (currentYear === year ? ' active' : '') + ((year < startYear || year > endYear) ? ' disabled' : '') + '">' + year + '</span>';
year += 1;
}
yearCont.html(html);
},
fillHours: function() {
var table = this.widget.find(
'.timepicker .timepicker-hours table');
table.parent().hide();
var html = '';
if (this.options.pick12HourFormat) {
var current = 1;
for (var i = 0; i < 3; i += 1) {
html += '<tr>';
for (var j = 0; j < 4; j += 1) {
var c = current.toString();
html += '<td class="hour">' + padLeft(c, 2, '0') + '</td>';
current++;
}
html += '</tr>'
}
} else {
var current = 0;
for (var i = 0; i < 6; i += 1) {
html += '<tr>';
for (var j = 0; j < 4; j += 1) {
var c = current.toString();
html += '<td class="hour">' + padLeft(c, 2, '0') + '</td>';
current++;
}
html += '</tr>'
}
}
table.html(html);
},
fillMinutes: function() {
var table = this.widget.find(
'.timepicker .timepicker-minutes table');
table.parent().hide();
var html = '';
var current = 0;
for (var i = 0; i < 5; i++) {
html += '<tr>';
for (var j = 0; j < 4; j += 1) {
var c = current.toString();
html += '<td class="minute">' + padLeft(c, 2, '0') + '</td>';
current += 3;
}
html += '</tr>';
}
table.html(html);
},
fillSeconds: function() {
var table = this.widget.find(
'.timepicker .timepicker-seconds table');
table.parent().hide();
var html = '';
var current = 0;
for (var i = 0; i < 5; i++) {
html += '<tr>';
for (var j = 0; j < 4; j += 1) {
var c = current.toString();
html += '<td class="second">' + padLeft(c, 2, '0') + '</td>';
current += 3;
}
html += '</tr>';
}
table.html(html);
},
fillTime: function() {
if (!this._date)
return;
var timeComponents = this.widget.find('.timepicker span[data-time-component]');
var table = timeComponents.closest('table');
var is12HourFormat = this.options.pick12HourFormat;
var hour = this._date.getUTCHours();
var period = 'AM';
if (is12HourFormat) {
if (hour >= 12) period = 'PM';
if (hour === 0) hour = 12;
else if (hour != 12) hour = hour % 12;
this.widget.find(
'.timepicker [data-action=togglePeriod]').text(period);
}
hour = padLeft(hour.toString(), 2, '0');
var minute = padLeft(this._date.getUTCMinutes().toString(), 2, '0');
var second = padLeft(this._date.getUTCSeconds().toString(), 2, '0');
timeComponents.filter('[data-time-component=hours]').text(hour);
timeComponents.filter('[data-time-component=minutes]').text(minute);
timeComponents.filter('[data-time-component=seconds]').text(second);
},
click: function(e) {
e.stopPropagation();
e.preventDefault();
this._unset = false;
var target = $(e.target).closest('span, td, th');
if (target.length === 1) {
if (! target.is('.disabled')) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var vd = this.viewDate;
var navFnc = DPGlobal.modes[this.viewMode].navFnc;
var step = DPGlobal.modes[this.viewMode].navStep;
if (target[0].className === 'prev') step = step * -1;
vd['set' + navFnc](vd['get' + navFnc]() + step);
this.fillDate();
this.set();
break;
}
break;
case 'span':
if (target.is('.month')) {
var month = target.parent().find('span').index(target);
this.viewDate.setUTCMonth(month);
} else {
var year = parseInt(target.text(), 10) || 0;
this.viewDate.setUTCFullYear(year);
}
if (this.viewMode !== 0) {
this._date = UTCDate(
this.viewDate.getUTCFullYear(),
this.viewDate.getUTCMonth(),
this.viewDate.getUTCDate(),
this._date.getUTCHours(),
this._date.getUTCMinutes(),
this._date.getUTCSeconds(),
this._date.getUTCMilliseconds()
);
this.notifyChange();
}
this.showMode(-1);
this.fillDate();
this.set();
break;
case 'td':
if (target.is('.day')) {
var day = parseInt(target.text(), 10) || 1;
var month = this.viewDate.getUTCMonth();
var year = this.viewDate.getUTCFullYear();
if (target.is('.old')) {
if (month === 0) {
month = 11;
year -= 1;
} else {
month -= 1;
}
} else if (target.is('.new')) {
if (month == 11) {
month = 0;
year += 1;
} else {
month += 1;
}
}
this._date = UTCDate(
year, month, day,
this._date.getUTCHours(),
this._date.getUTCMinutes(),
this._date.getUTCSeconds(),
this._date.getUTCMilliseconds()
);
this.viewDate = UTCDate(
year, month, Math.min(28, day) , 0, 0, 0, 0);
this.fillDate();
this.set();
this.notifyChange();
}
break;
}
}
}
},
actions: {
incrementHours: function(e) {
this._date.setUTCHours(this._date.getUTCHours() + 1);
},
incrementMinutes: function(e) {
this._date.setUTCMinutes(this._date.getUTCMinutes() + 1);
},
incrementSeconds: function(e) {
this._date.setUTCSeconds(this._date.getUTCSeconds() + 1);
},
decrementHours: function(e) {
this._date.setUTCHours(this._date.getUTCHours() - 1);
},
decrementMinutes: function(e) {
this._date.setUTCMinutes(this._date.getUTCMinutes() - 1);
},
decrementSeconds: function(e) {
this._date.setUTCSeconds(this._date.getUTCSeconds() - 1);
},
togglePeriod: function(e) {
var hour = this._date.getUTCHours();
if (hour >= 12) hour -= 12;
else hour += 12;
this._date.setUTCHours(hour);
},
showPicker: function() {
this.widget.find('.timepicker > div:not(.timepicker-picker)').hide();
this.widget.find('.timepicker .timepicker-picker').show();
},
showHours: function() {
this.widget.find('.timepicker .timepicker-picker').hide();
this.widget.find('.timepicker .timepicker-hours').show();
},
showMinutes: function() {
this.widget.find('.timepicker .timepicker-picker').hide();
this.widget.find('.timepicker .timepicker-minutes').show();
},
showSeconds: function() {
this.widget.find('.timepicker .timepicker-picker').hide();
this.widget.find('.timepicker .timepicker-seconds').show();
},
selectHour: function(e) {
var tgt = $(e.target);
var value = parseInt(tgt.text(), 10);
if (this.options.pick12HourFormat) {
var current = this._date.getUTCHours();
if (current >= 12) {
if (value != 12) value = (value + 12) % 24;
} else {
if (value === 12) value = 0;
else value = value % 12;
}
}
this._date.setUTCHours(value);
this.actions.showPicker.call(this);
},
selectMinute: function(e) {
var tgt = $(e.target);
var value = parseInt(tgt.text(), 10);
this._date.setUTCMinutes(value);
this.actions.showPicker.call(this);
},
selectSecond: function(e) {
var tgt = $(e.target);
var value = parseInt(tgt.text(), 10);
this._date.setUTCSeconds(value);
this.actions.showPicker.call(this);
}
},
doAction: function(e) {
e.stopPropagation();
e.preventDefault();
if (!this._date) this._date = UTCDate(1970, 0, 0, 0, 0, 0, 0);
var action = $(e.currentTarget).data('action');
var rv = this.actions[action].apply(this, arguments);
this.set();
this.fillTime();
this.notifyChange();
return rv;
},
stopEvent: function(e) {
e.stopPropagation();
e.preventDefault();
},
// part of the following code was taken from
// http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.js
keydown: function(e) {
var self = this, k = e.which, input = $(e.target);
if (k == 8 || k == 46) {
// backspace and delete cause the maskPosition
// to be recalculated
setTimeout(function() {
self._resetMaskPos(input);
});
}
},
keypress: function(e) {
var k = e.which;
if (k == 8 || k == 46) {
// For those browsers which will trigger
// keypress on backspace/delete
return;
}
var input = $(e.target);
var c = String.fromCharCode(k);
var val = input.val() || '';
val += c;
var mask = this._mask[this._maskPos];
if (!mask) {
return false;
}
if (mask.end != val.length) {
return;
}
if (!mask.pattern.test(val.slice(mask.start))) {
val = val.slice(0, val.length - 1);
while ((mask = this._mask[this._maskPos]) && mask.character) {
val += mask.character;
// advance mask position past static
// part
this._maskPos++;
}
val += c;
if (mask.end != val.length) {
input.val(val);
return false;
} else {
if (!mask.pattern.test(val.slice(mask.start))) {
input.val(val.slice(0, mask.start));
return false;
} else {
input.val(val);
this._maskPos++;
return false;
}
}
} else {
this._maskPos++;
}
},
change: function(e) {
var input = $(e.target);
var val = input.val();
if (this._formatPattern.test(val)) {
this.update();
this.setValue(this._date.getTime());
this.notifyChange();
this.set();
} else if (val && val.trim()) {
this.setValue(this._date.getTime());
if (this._date) this.set();
else input.val('');
} else {
if (this._date) {
this.setValue(null);
// unset the date when the input is
// erased
this.notifyChange();
this._unset = true;
}
}
this._resetMaskPos(input);
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.minViewMode, Math.min(
2, this.viewMode + dir));
}
this.widget.find('.datepicker > div').hide().filter(
'.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
},
destroy: function() {
this._detachDatePickerEvents();
this._detachDatePickerGlobalEvents();
this.widget.remove();
this.$element.removeData('datetimepicker');
this.component.removeData('datetimepicker');
},
formatDate: function(d) {
return this.format.replace(formatReplacer, function(match) {
var methodName, property, rv, len = match.length;
if (match === 'ms')
len = 1;
property = dateFormatComponents[match].property
if (property === 'Hours12') {
rv = d.getUTCHours();
if (rv === 0) rv = 12;
else if (rv !== 12) rv = rv % 12;
} else if (property === 'Period12') {
if (d.getUTCHours() >= 12) return 'PM';
else return 'AM';
} else if (property === 'UTCYear') {
rv = d.getUTCFullYear();
rv = rv.toString().substr(2);
} else {
methodName = 'get' + property;
rv = d[methodName]();
}
if (methodName === 'getUTCMonth') rv = rv + 1;
return padLeft(rv.toString(), len, '0');
});
},
parseDate: function(str) {
var match, i, property, methodName, value, parsed = {};
if (!(match = this._formatPattern.exec(str)))
return null;
for (i = 1; i < match.length; i++) {
property = this._propertiesByIndex[i];
if (!property)
continue;
value = match[i];
if (/^\d+$/.test(value))
value = parseInt(value, 10);
parsed[property] = value;
}
return this._finishParsingDate(parsed);
},
_resetMaskPos: function(input) {
var val = input.val();
for (var i = 0; i < this._mask.length; i++) {
if (this._mask[i].end > val.length) {
// If the mask has ended then jump to
// the next
this._maskPos = i;
break;
} else if (this._mask[i].end === val.length) {
this._maskPos = i + 1;
break;
}
}
},
_finishParsingDate: function(parsed) {
var year, month, date, hours, minutes, seconds, milliseconds;
year = parsed.UTCFullYear;
if (parsed.UTCYear) year = 2000 + parsed.UTCYear;
if (!year) year = 1970;
if (parsed.UTCMonth) month = parsed.UTCMonth - 1;
else month = 0;
date = parsed.UTCDate || 1;
hours = parsed.UTCHours || 0;
minutes = parsed.UTCMinutes || 0;
seconds = parsed.UTCSeconds || 0;
milliseconds = parsed.UTCMilliseconds || 0;
if (parsed.Hours12) {
hours = parsed.Hours12;
}
if (parsed.Period12) {
if (/pm/i.test(parsed.Period12)) {
if (hours != 12) hours = (hours + 12) % 24;
} else {
hours = hours % 12;
}
}
return UTCDate(year, month, date, hours, minutes, seconds, milliseconds);
},
_compileFormat: function () {
var match, component, components = [], mask = [],
str = this.format, propertiesByIndex = {}, i = 0, pos = 0;
while (match = formatComponent.exec(str)) {
component = match[0];
if (component in dateFormatComponents) {
i++;
propertiesByIndex[i] = dateFormatComponents[component].property;
components.push('\\s*' + dateFormatComponents[component].getPattern(
this) + '\\s*');
mask.push({
pattern: new RegExp(dateFormatComponents[component].getPattern(
this)),
property: dateFormatComponents[component].property,
start: pos,
end: pos += component.length
});
}
else {
components.push(escapeRegExp(component));
mask.push({
pattern: new RegExp(escapeRegExp(component)),
character: component,
start: pos,
end: ++pos
});
}
str = str.slice(component.length);
}
this._mask = mask;
this._maskPos = 0;
this._formatPattern = new RegExp(
'^\\s*' + components.join('') + '\\s*$');
this._propertiesByIndex = propertiesByIndex;
},
_attachDatePickerEvents: function() {
var self = this;
// this handles date picker clicks
this.widget.on('click', '.datepicker *', $.proxy(this.click, this));
// this handles time picker clicks
this.widget.on('click', '[data-action]', $.proxy(this.doAction, this));
this.widget.on('mousedown', $.proxy(this.stopEvent, this));
if (this.pickDate && this.pickTime) {
this.widget.on('click.togglePicker', '.accordion-toggle', function(e) {
e.stopPropagation();
var $this = $(this);
var $parent = $this.closest('ul');
var expanded = $parent.find('.collapse.in');
var closed = $parent.find('.collapse:not(.in)');
if (expanded && expanded.length) {
var collapseData = expanded.data('collapse');
if (collapseData && collapseData.transitioning) return;
expanded.collapse('hide');
closed.collapse('show')
$this.find('i').toggleClass(self.timeIcon + ' ' + self.dateIcon);
self.$element.find('.input-group-addon i').toggleClass(self.timeIcon + ' ' + self.dateIcon);
}
});
}
if (this.isInput) {
this.$element.on({
'focus': $.proxy(this.show, this),
'change': $.proxy(this.change, this)
});
if (this.options.maskInput) {
this.$element.on({
'keydown': $.proxy(this.keydown, this),
'keypress': $.proxy(this.keypress, this)
});
}
} else {
this.$element.on({
'change': $.proxy(this.change, this)
}, 'input');
if (this.options.maskInput) {
this.$element.on({
'keydown': $.proxy(this.keydown, this),
'keypress': $.proxy(this.keypress, this)
}, 'input');
}
if (this.component){
this.component.on('click', $.proxy(this.show, this));
} else {
this.$element.on('click', $.proxy(this.show, this));
}
}
},
_attachDatePickerGlobalEvents: function() {
$(window).on(
'resize.datetimepicker' + this.id, $.proxy(this.place, this));
if (!this.isInput) {
$(document).on(
'mousedown.datetimepicker' + this.id, $.proxy(this.hide, this));
}
},
_detachDatePickerEvents: function() {
this.widget.off('click', '.datepicker *', this.click);
this.widget.off('click', '[data-action]');
this.widget.off('mousedown', this.stopEvent);
if (this.pickDate && this.pickTime) {
this.widget.off('click.togglePicker');
}
if (this.isInput) {
this.$element.off({
'focus': this.show,
'change': this.change
});
if (this.options.maskInput) {
this.$element.off({
'keydown': this.keydown,
'keypress': this.keypress
});
}
} else {
this.$element.off({
'change': this.change
}, 'input');
if (this.options.maskInput) {
this.$element.off({
'keydown': this.keydown,
'keypress': this.keypress
}, 'input');
}
if (this.component){
this.component.off('click', this.show);
} else {
this.$element.off('click', this.show);
}
}
},
_detachDatePickerGlobalEvents: function () {
$(window).off('resize.datetimepicker' + this.id);
if (!this.isInput) {
$(document).off('mousedown.datetimepicker' + this.id);
}
},
_isInFixed: function() {
if (this.$element) {
var parents = this.$element.parents();
var inFixed = false;
for (var i=0; i<parents.length; i++) {
if ($(parents[i]).css('position') == 'fixed') {
inFixed = true;
break;
}
};
return inFixed;
} else {
return false;
}
}
};
$.fn.datetimepicker = function ( option, val ) {
return this.each(function () {
var $this = $(this),
data = $this.data('datetimepicker'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('datetimepicker', (data = new DateTimePicker(
this, $.extend({}, $.fn.datetimepicker.defaults,options))));
}
if (typeof option === 'string') data[option](val);
});
};
$.fn.datetimepicker.defaults = {
maskInput: false,
pickDate: true,
pickTime: true,
pick12HourFormat: false,
pickSeconds: true,
startDate: -Infinity,
endDate: Infinity,
collapse: true
};
$.fn.datetimepicker.Constructor = DateTimePicker;
var dpgId = 0;
var dates = $.fn.datetimepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec"]
}
};
var dateFormatComponents = {
dd: {property: 'UTCDate', getPattern: function() { return '(0?[1-9]|[1-2][0-9]|3[0-1])\\b';}},
MM: {property: 'UTCMonth', getPattern: function() {return '(0?[1-9]|1[0-2])\\b';}},
yy: {property: 'UTCYear', getPattern: function() {return '(\\d{2})\\b'}},
yyyy: {property: 'UTCFullYear', getPattern: function() {return '(\\d{4})\\b';}},
hh: {property: 'UTCHours', getPattern: function() {return '(0?[0-9]|1[0-9]|2[0-3])\\b';}},
mm: {property: 'UTCMinutes', getPattern: function() {return '(0?[0-9]|[1-5][0-9])\\b';}},
ss: {property: 'UTCSeconds', getPattern: function() {return '(0?[0-9]|[1-5][0-9])\\b';}},
ms: {property: 'UTCMilliseconds', getPattern: function() {return '([0-9]{1,3})\\b';}},
HH: {property: 'Hours12', getPattern: function() {return '(0?[1-9]|1[0-2])\\b';}},
PP: {property: 'Period12', getPattern: function() {return '(AM|PM|am|pm|Am|aM|Pm|pM)\\b';}}
};
var keys = [];
for (var k in dateFormatComponents) keys.push(k);
keys[keys.length - 1] += '\\b';
keys.push('.');
var formatComponent = new RegExp(keys.join('\\b|'));
keys.pop();
var formatReplacer = new RegExp(keys.join('\\b|'), 'g');
function escapeRegExp(str) {
// http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function padLeft(s, l, c) {
if (l < s.length) return s;
else return Array(l - s.length + 1).join(c || ' ') + s;
}
function getTemplate(timeIcon, pickDate, pickTime, is12Hours, showSeconds, collapse) {
if (pickDate && pickTime) {
return (
'<div class="bootstrap-datetimepicker-widget dropdown-menu">' +
'<ul>' +
'<li' + (collapse ? ' class="collapse in"' : '') + '>' +
'<div class="datepicker">' +
DPGlobal.template +
'</div>' +
'</li>' +
'<li class="picker-switch accordion-toggle"><a><i class="' + timeIcon + '"></i></a></li>' +
'<li' + (collapse ? ' class="collapse"' : '') + '>' +
'<div class="timepicker">' +
TPGlobal.getTemplate(is12Hours, showSeconds) +
'</div>' +
'</li>' +
'</ul>' +
'</div>'
);
} else if (pickTime) {
return (
'<div class="bootstrap-datetimepicker-widget dropdown-menu">' +
'<div class="timepicker">' +
TPGlobal.getTemplate(is12Hours, showSeconds) +
'</div>' +
'</div>'
);
} else {
return (
'<div class="bootstrap-datetimepicker-widget dropdown-menu">' +
'<div class="datepicker">' +
DPGlobal.template +
'</div>' +
'</div>'
);
}
}
function UTCDate() {
return new Date(Date.UTC.apply(Date, arguments));
}
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'UTCMonth',
navStep: 1
},
{
clsName: 'months',
navFnc: 'UTCFullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'UTCFullYear',
navStep: 10
}],
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
},
headTemplate:
'<thead>' +
'<tr>' +
'<th class="prev">‹</th>' +
'<th colspan="5" class="switch"></th>' +
'<th class="next">›</th>' +
'</tr>' +
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template =
'<div class="datepicker-days">' +
'<table class="table-condensed">' +
DPGlobal.headTemplate +
'<tbody></tbody>' +
'</table>' +
'</div>' +
'<div class="datepicker-months">' +
'<table class="table-condensed">' +
DPGlobal.headTemplate +
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>';
var TPGlobal = {
hourTemplate: '<span data-action="showHours" data-time-component="hours" class="timepicker-hour"></span>',
minuteTemplate: '<span data-action="showMinutes" data-time-component="minutes" class="timepicker-minute"></span>',
secondTemplate: '<span data-action="showSeconds" data-time-component="seconds" class="timepicker-second"></span>'
};
TPGlobal.getTemplate = function(is12Hours, showSeconds) {
return (
'<div class="timepicker-picker">' +
'<table class="table-condensed"' +
(is12Hours ? ' data-hour-format="12"' : '') +
'>' +
'<tr>' +
'<td><a href="#" class="btn" data-action="incrementHours"><i class="icon-chevron-up"></i></a></td>' +
'<td class="separator"></td>' +
'<td><a href="#" class="btn" data-action="incrementMinutes"><i class="icon-chevron-up"></i></a></td>' +
(showSeconds ?
'<td class="separator"></td>' +
'<td><a href="#" class="btn" data-action="incrementSeconds"><i class="icon-chevron-up"></i></a></td>': '')+
(is12Hours ? '<td class="separator"></td>' : '') +
'</tr>' +
'<tr>' +
'<td>' + TPGlobal.hourTemplate + '</td> ' +
'<td class="separator">:</td>' +
'<td>' + TPGlobal.minuteTemplate + '</td> ' +
(showSeconds ?
'<td class="separator">:</td>' +
'<td>' + TPGlobal.secondTemplate + '</td>' : '') +
(is12Hours ?
'<td class="separator"></td>' +
'<td>' +
'<button type="button" class="btn btn-primary" data-action="togglePeriod"></button>' +
'</td>' : '') +
'</tr>' +
'<tr>' +
'<td><a href="#" class="btn" data-action="decrementHours"><i class="icon-chevron-down"></i></a></td>' +
'<td class="separator"></td>' +
'<td><a href="#" class="btn" data-action="decrementMinutes"><i class="icon-chevron-down"></i></a></td>' +
(showSeconds ?
'<td class="separator"></td>' +
'<td><a href="#" class="btn" data-action="decrementSeconds"><i class="icon-chevron-down"></i></a></td>': '') +
(is12Hours ? '<td class="separator"></td>' : '') +
'</tr>' +
'</table>' +
'</div>' +
'<div class="timepicker-hours" data-action="selectHour">' +
'<table class="table-condensed">' +
'</table>'+
'</div>'+
'<div class="timepicker-minutes" data-action="selectMinute">' +
'<table class="table-condensed">' +
'</table>'+
'</div>'+
(showSeconds ?
'<div class="timepicker-seconds" data-action="selectSecond">' +
'<table class="table-condensed">' +
'</table>'+
'</div>': '')
);
}
})(window.jQuery)
|
parkerj/eduTrac-SIS
|
static/assets/components/modules/admin/forms/elements/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js
|
JavaScript
|
gpl-3.0
| 43,677 |
import nengo
import numpy as np
import nengo.spa as spa
vocab = spa.Vocabulary(32)
model = nengo.Network()
with model:
state = spa.State(32, vocab=vocab)
q = nengo.networks.EnsembleArray(n_neurons=50, n_ensembles=4)
nengo.Connection(state.output, q.input,
transform=[vocab.parse('DOG').v,
vocab.parse('CAT').v,
vocab.parse('RAT').v,
vocab.parse('COW').v,
])
|
tcstewar/nengo_assignments
|
groningen_2018/day4-action/action1.py
|
Python
|
gpl-3.0
| 528 |
//=======================================================================
// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/config.hpp>
#include <iostream>
#include <fstream>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
using namespace boost;
int
main(int, char *[])
{
typedef adjacency_list < listS, vecS, directedS,
no_property, property < edge_weight_t, int > > graph_t;
typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;
typedef graph_traits < graph_t >::edge_descriptor edge_descriptor;
typedef std::pair<int, int> Edge;
const int num_nodes = 5;
enum nodes { A, B, C, D, E };
char name[] = "ABCDE";
Edge edge_array[] = { Edge(A, C), Edge(B, B), Edge(B, D), Edge(B, E),
Edge(C, B), Edge(C, D), Edge(D, E), Edge(E, A), Edge(E, B)
};
int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1 };
int num_arcs = sizeof(edge_array) / sizeof(Edge);
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
graph_t g(num_nodes);
property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);
for (std::size_t j = 0; j < num_arcs; ++j) {
edge_descriptor e; bool inserted;
boost::tie(e, inserted) = add_edge(edge_array[j].first, edge_array[j].second, g);
weightmap[e] = weights[j];
}
#else
graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);
property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);
#endif
std::vector<vertex_descriptor> p(num_vertices(g));
std::vector<int> d(num_vertices(g));
vertex_descriptor s = vertex(A, g);
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
// VC++ has trouble with the named parameters mechanism
property_map<graph_t, vertex_index_t>::type indexmap = get(vertex_index, g);
dijkstra_shortest_paths(g, s, &p[0], &d[0], weightmap, indexmap,
std::less<int>(), closed_plus<int>(),
(std::numeric_limits<int>::max)(), 0,
default_dijkstra_visitor());
#else
dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));
#endif
std::cout << "distances and parents:" << std::endl;
graph_traits < graph_t >::vertex_iterator vi, vend;
for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi) {
std::cout << "distance(" << name[*vi] << ") = " << d[*vi] << ", ";
std::cout << "parent(" << name[*vi] << ") = " << name[p[*vi]] << std::
endl;
}
std::cout << std::endl;
std::ofstream dot_file("figs/dijkstra-eg.dot");
dot_file << "digraph D {\n"
<< " rankdir=LR\n"
<< " size=\"4,3\"\n"
<< " ratio=\"fill\"\n"
<< " edge[style=\"bold\"]\n" << " node[shape=\"circle\"]\n";
graph_traits < graph_t >::edge_iterator ei, ei_end;
for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {
graph_traits < graph_t >::edge_descriptor e = *ei;
graph_traits < graph_t >::vertex_descriptor
u = source(e, g), v = target(e, g);
dot_file << name[u] << " -> " << name[v]
<< "[label=\"" << get(weightmap, e) << "\"";
if (p[v] == u)
dot_file << ", color=\"black\"";
else
dot_file << ", color=\"grey\"";
dot_file << "]";
}
dot_file << "}";
return EXIT_SUCCESS;
}
|
cppisfun/GameEngine
|
foreign/boost/libs/graph/example/dijkstra-example.cpp
|
C++
|
gpl-3.0
| 3,625 |
/****************************************************************************/
/// @file AbstractMutex.h
/// @author Daniel Krajzewicz
/// @author Michael Behrisch
/// @date 2005-07-12
/// @version $Id: AbstractMutex.h 13107 2012-12-02 13:57:34Z behrisch $
///
// An abstract class for encapsulating mutex implementations
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
// Copyright (C) 2001-2012 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO 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.
//
/****************************************************************************/
#ifndef AbstractMutex_h
#define AbstractMutex_h
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class AbstractMutex
* @brief An abstract class for encapsulating mutex implementations
*
* This class defines access to a mutex. The implementation may differ.
*
* Within gui-applications, FXMutexes may be used while this is improper
* for command-line applications. Normally, they do not need mutexes unless
* a synchronized communication with an external application is established.
* In these cases, a further class should be implemented.
*/
class AbstractMutex {
public:
/// @brief Constructor
AbstractMutex() { }
/// @brief Destructor
virtual ~AbstractMutex() { }
/// @brief Locks the mutex
virtual void lock() = 0;
/// @brief Unlocks the mutex
virtual void unlock() = 0;
/** @class ScopedLocker
* @brief A mutex encapsulator which locks/unlocks the given mutex on construction/destruction, respectively
*/
class ScopedLocker {
public:
/** @brief Constructor
* @param[in] lock The mutex to lock
*
* Locks the mutex.
*/
ScopedLocker(AbstractMutex& lock): myLock(lock) {
myLock.lock();
}
/** @brief Destructor
* Unlocks the mutex.
*/
~ScopedLocker() {
myLock.unlock();
}
private:
/// @brief The mutex to lock
AbstractMutex& myLock;
private:
/// @brief Invalidated copy constructor.
ScopedLocker(const ScopedLocker&);
/// Invalidated assignment operator.
ScopedLocker& operator=(const ScopedLocker&);
};
};
#endif
/****************************************************************************/
|
rudhir-upretee/Sumo_With_Netsim
|
src/utils/common/AbstractMutex.h
|
C
|
gpl-3.0
| 3,162 |
/*
LAWA - Library for Adaptive Wavelet Applications.
Copyright (C) 2008-2013 Sebastian Kestler, Mario Rometsch, Kristina Steih,
Alexander Stippler.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef LAWA_METHODS_ADAPTIVE_SOLVERS_S_ADWAV_OPTIMIZED_H
#define LAWA_METHODS_ADAPTIVE_SOLVERS_S_ADWAV_OPTIMIZED_H 1
#include <iostream>
#include <vector>
#include <lawa/methods/adaptive/datastructures/indexset.h>
#include <lawa/methods/adaptive/datastructures/coefficients.h>
#include <lawa/methods/adaptive/datastructures/matrixoperations.h>
#include <lawa/methods/adaptive/algorithms/linearsystemsolvers.h>
#include <lawa/methods/adaptive/postprocessing/postprocessing.h>
namespace lawa {
template <typename T, typename Index, typename AdaptiveOperator, typename RHS,
typename PP_AdaptiveOperator, typename PP_RHS>
class S_ADWAV_Optimized {
typedef typename Coefficients<Lexicographical,T,Index>::const_iterator const_coeff_it;
public:
S_ADWAV_Optimized(AdaptiveOperator &A, RHS &F, PP_AdaptiveOperator &PP_A, PP_RHS &PP_F,
T contraction, T start_threshTol,
T _linTol, T _resTol, int _NumOfIterations, int _MaxItsPerThreshTol,
T _eps=1e-2);
//solver for stationary problems
void
solve(const IndexSet<Index> &Initial_Lambda, Coefficients<Lexicographical,T,Index> &u,
const char *linsolvertype, const char *filename, int assemble_matrix, T H1norm=0.);
std::vector<T> residuals;
std::vector<T> times;
std::vector<T> linsolve_iterations;
std::vector<T> toliters;
private:
AdaptiveOperator &A;
RHS &F;
PP_AdaptiveOperator &PP_A;
PP_RHS &PP_F;
T contraction, threshTol, linTol, resTol;
int NumOfIterations;
int MaxItsPerThreshTol;
T eps;
};
} //namespace lawa
#include <lawa/methods/adaptive/solvers/s_adwav_optimized.tcc>
#endif //LAWA_METHODS_ADAPTIVE_SOLVERS_S_ADWAV_OPTIMIZED_H
|
lknut/LinTrans
|
LAWA-lite/lawa/methods/adaptive/solvers/s_adwav_optimized.h
|
C
|
gpl-3.0
| 2,753 |
import {panXTree,metaLegend,panXClusterTable,panXMetaTable} from "./global";
import {tooltip_toggle} from "./tooltips";
import {changeLayout, changeDistance, updateTips} from "../phyloTree/src/updateTree";
import {zoomInY, zoomIn, zoomIntoClade} from "../phyloTree/src/zoom";
import {removeLabels, tipLabels} from "../phyloTree/src/labels";
import svgPanZoom from "svg-pan-zoom";
import {filterMetaDataTable} from "./datatable-meta";
import {change_select_dropdown_value} from './linkTableAlignmentTrees';
import {updateMetadata, removeLegend} from './meta-color-legend';
import {updateTipAttribute,updateBranches} from "../phyloTree/src/updateTree";
import {aln_file_path} from "./data_path";
import {unselect_clusterTable} from "./datatable-gc";
const tipUnselected=panXTree.tipUnselected;
export const hideNonSelected =function(tree){
tree.tipElements
.attr('r',function(d){if (d.state.selected){return d.tipAttributes.r*1.5;}
else {return d.tipAttributes.r*0.5;}
})
.style('fill',function(d){if (d.state.selected){ return d.tipAttributes.fill;}
else {return tipUnselected;}
})
.style('stroke',function(d){if (d.state.selected){ return d.tipAttributes.stroke;}
else {return tipUnselected;}
});
}
export const undoHideNonSelected =function(tree){
tree.tipElements
.attr('r',function(d){return d.tipAttributes.r;})
.style('fill', function(d){return d.tipAttributes.fill;})
.style('stroke', function(d){return d.tipAttributes.stroke;});
tree.tips.forEach(function(d){d.state.selected=undefined;});
}
export const branchText = function(d){
if (d.n.muts){
const tmp = d.n.muts.join(',').slice(0,20);
return tmp;
}else{
return "";
}
}
export const branchFontSize = function(d){return d.stats.leafCount>2?3:0;}
export const tipText = function(d){
if (d.terminal){
return d.n.attr.strain ? d.n.attr.strain: d.n.name ;
}else{
return "";
}
}
export const tipFontSize = function(tree){
return function(d){
const nTips = tree.visibleTips.length;
if (nTips<20){
return 14.0;
}else if (nTips<100){
return 14 - 8*((nTips-20)/80.);
}else{return 0;}
};
}
export const applyChangeToTree = function(myTree, func, dt){
removeLabels(myTree);
func();
if (myTree.showTipLabels){
if (myTree.orientation.x==1) {
setTimeout(function() {tipLabels(myTree, tipText, tipFontSize(myTree), 3,8);}, dt?dt:1000);
} else {
setTimeout(function() {tipLabels(myTree, tipText, tipFontSize(myTree), 3,-8,'end');}, dt?dt:1000);
}
};
}
export const attachButtons = function(myTree, buttons){
const dt = 1000;
const updateSelected=false;
/*if (buttons.layout){
$('#'+buttons.layout).change(function() {
myTree.layout = (d3.select(this).property('checked')==false) ? 'rect' : 'radial';
panXTree.currentTreeLayout= myTree.layout;
applyChangeToTree(myTree, function(){changeLayout(myTree, dt);}, dt);
});
}*/
if (buttons.layout_radial){
$('#'+buttons.layout_radial).click(function() {
myTree.layout = 'radial';
panXTree.currentTreeLayout= myTree.layout;
applyChangeToTree(myTree, function(){changeLayout(myTree, dt);}, dt);
});
}
if (buttons.layout_vertical){
$('#'+buttons.layout_vertical).click(function() {
myTree.layout = 'rect';
panXTree.currentTreeLayout= myTree.layout;
applyChangeToTree(myTree, function(){changeLayout(myTree, dt);}, dt);
});
}
if (buttons.layout_unroot){
$('#'+buttons.layout_unroot).click(function() {
myTree.layout = 'unrooted';
panXTree.currentTreeLayout= myTree.layout;
applyChangeToTree(myTree, function(){changeLayout(myTree, dt);}, dt);
});
}
if (buttons.orientation){
$('#'+buttons.orientation).change(function() {
myTree.orientation = (d3.select(this).property('checked')==true) ? {x:-1, y:1} : {x:1, y:1};
applyChangeToTree(myTree, function(){changeLayout(myTree, dt);}, dt);
});
}
if (buttons.nodeLarge){
$('#'+buttons.nodeLarge).click(function() {
myTree.tips.forEach(function(d,i){
d.tipAttributes.r *= 1.5;
});
updateTipAttribute(myTree,'r');
});
}
if (buttons.nodeSmaller){
$('#'+buttons.nodeSmaller).click(function() {
myTree.tips.forEach(function(d,i){
d.tipAttributes.r *= 0.5;
});
updateTipAttribute(myTree,'r');
});
}
if (buttons.zoomInY){
$('#'+buttons.zoomInY).click(function() {
applyChangeToTree(myTree, function(){zoomInY(myTree,1.4,dt, updateSelected);},dt);
//filterMetaDataTable('dc_data_table_meta', myTree);
});
}
if (buttons.zoomOutY){
$('#'+buttons.zoomOutY).click(function() {
applyChangeToTree(myTree, function(){zoomInY(myTree,0.7,dt, updateSelected);},dt);
//filterMetaDataTable('dc_data_table_meta', myTree);
});
}
if (buttons.zoomReset){
$('#'+buttons.zoomReset).click(function() {
if (myTree.panZoom){
myTree.panZoom.reset();
}
//#subtle:zoomIntoClade (tree, d, dt, setSelected)
//# state.selected are set to true in zoomIntoClade, they are then reset to undefined
applyChangeToTree(myTree, function(){zoomIntoClade(myTree, myTree.nodes[0],dt, true);},dt);
const metaTableID=panXMetaTable.meta_table_id;
filterMetaDataTable(metaTableID, myTree);
undoHideNonSelected(myTree);
/*$('#'+panXClusterTable.cluster_table_id).DataTable()
.search('').draw();
unselect_clusterTable(panXClusterTable.cluster_table_id);*/
});
}
if (buttons.colorReset){
$('#'+buttons.colorReset).click(function() {
resetGeneTreeColor(myTree);
});
}
if (buttons.treeSync){
//console.log(buttons.treeSync)
//tooltip_toggle('#speciesTreeSynchr','synchronize toggle behaviors on both species tree and gene tree')
$('#'+buttons.treeSync).change(function(event) {
myTree.treeSync =d3.select(this).property('checked')
if (myTree.treeSync){
var myGeneTree=panXTree.currentGeneTree;
attachButtons(myGeneTree, {
layout_radial:"speciesTreeRadial",
layout_vertical:"speciesTreeVertical",
layout_unroot:"speciesTreeUnroot",
scale:"speciesTreeScale"
});
}else{
$('#'+buttons.layout_radial).off("click");
$('#'+buttons.layout_vertical).off("click");
$('#'+buttons.layout_unroot).off("click");
$('#'+buttons.scale).off("change");
event.stopPropagation();
var mySpeciesTree=panXTree.speciesTree;
attachButtons(mySpeciesTree, {
layout_radial:"speciesTreeRadial",
layout_vertical:"speciesTreeVertical",
layout_unroot:"speciesTreeUnroot",
scale:"speciesTreeScale"
});
}
});
}
if (buttons.tipLabels){
$('#'+buttons.tipLabels).change(function() {
myTree.showTipLabels = d3.select(this).property('checked')
//-console.log("tipLabels", myTree.visibleTips, tipFontSize(myTree)());
if (myTree.showTipLabels){
if (myTree.orientation.x==-1) {
tipLabels(myTree, tipText, tipFontSize(myTree), 3,-8,'end');
} else {
tipLabels(myTree, tipText, tipFontSize(myTree), 3,8);
}
}else{
removeLabels(myTree);
}
});
}
if (buttons.scale){
$('#'+buttons.scale).change(function() {
myTree.distance = (d3.select(this).property('checked')===false) ? "level":"div";
applyChangeToTree(myTree, function(){changeDistance(myTree, dt);},dt);
});
}
if (buttons.download_coreTree){
d3.select('#'+buttons.download_coreTree)
.append('a')
.attr('href','./dataset/'+speciesAbbr+'/strain_tree.nwk')
.append('i')
.attr('class','glyphicon glyphicon-download-alt')
}
if (buttons.download_geneTree&&buttons.clusterID){
var download_geneTree=d3.select('#'+buttons.download_geneTree);
download_geneTree.selectAll('a').remove();
download_geneTree.append('a')
.attr('id','#'+buttons.download_geneTree_id+'_href')
.attr('href','./dataset/'+speciesAbbr+'/geneCluster/'+buttons.clusterID+'.nwk')
.append('i')
.attr('class','glyphicon glyphicon-download-alt')
}
if (buttons.panzoom){
$('#'+buttons.panzoom).change(function() {
if (myTree.panZoom){
const zoom_enabled = d3.select(this).property('checked');
if (zoom_enabled){myTree.panZoom.disableZoom();
}else{myTree.panZoom.enableZoom();}
}
});
}
}
export const attachPanzoom = function(treeID, myTree){
const dt=0;
const updateSelected = false;
myTree.panZoom = svgPanZoom("#"+treeID, {
beforeZoom: function(newZoom, oldZoom){
applyChangeToTree(myTree, function(){
zoomInY(myTree,newZoom/oldZoom,dt, updateSelected);}, dt);
//filterMetaDataTable('dc_data_table_meta', myTree);
return false;
},
// beforePan: function(oldPan, newPan){
// //console.log("panning", oldPan, newPan);
// applyChangeToTree(myTree, function(){
// pan(myTree, newPan.x-oldPan.x, newPan.y-oldPan.y, updateSelected);},dt);
// filterMetaDataTable('dc_data_table_meta', myTree);
// return {x:false, y:false};
// }
});
myTree.panZoom.disableZoom();
}
export const connectTrees = function(speciesTree, geneTree){
if (!(speciesTree&&geneTree)){
//console.log("trees are not yet in place");
return;
}
//console.log("connecting trees");
geneTree.paralogs = {}
for (var ti =0; ti<geneTree.tips.length; ti++){
var tip = geneTree.tips[ti];
tip.name = tip.n.name;
tip.accession = tip.n.accession;
tip.elem = geneTree.svg.selectAll("#"+tip.tipAttributes.id);
tip.strainTip = speciesTree.svg.selectAll("#"+speciesTree.namesToTips[tip.accession].tipAttributes.id);
if (!geneTree.paralogs[tip.accession]){
geneTree.paralogs[tip.accession] = [];
}
geneTree.paralogs[tip.accession].push(tip);
}
for (var ti =0; ti<geneTree.tips.length; ti++){
var tip = geneTree.tips[ti];
tip.paralogs = geneTree.paralogs[tip.accession].filter(function(d){return d.name!==tip.name;});
}
for (var ti =0; ti<speciesTree.tips.length; ti++){
var species = speciesTree.tips[ti];
species.genes = [];
species.elem = speciesTree.svg.selectAll("#"+species.tipAttributes.id);
if (!geneTree.paralogs[species.name]){
geneTree.paralogs[species.name]=[];
}
for (var gi=0; gi<geneTree.paralogs[species.name].length; gi++){
species.genes.push(geneTree.paralogs[species.name][gi]);
}
if (geneTree.paralogs[species.name].length){
species.genePresent = true;
}else{
species.genePresent = false;
}
}
removeLegend('coreTree_legend');
if (!metaLegend.current_metaType) {
colorPresenceAbsence(speciesTree);
change_select_dropdown_value("dropdown_select",'genePattern');
}else{
updateMetadata(metaLegend.current_metaType, speciesTree, geneTree, meta_display, 'coreTree_legend', 0);
}
styleGainLoss(speciesTree);
}
export const colorPresenceAbsence = function(speciesTree){
var node, fill;
for (var i=0; i<speciesTree.tips.length; i++){
node = speciesTree.tips[i];
node.tipAttributes.r = node.genePresent?panXTree.genePresentR:panXTree.geneAbsentR;
fill = node.genePresent?panXTree.genePresentFill:panXTree.geneAbsentFill
node.tipAttributes.fill = fill;
node.tipAttributes.stroke = d3.rgb(fill).darker(panXTree.strokeToFill).toString();
}
updateTips(speciesTree, ["r"], ["fill", "stroke"], 0);
}
export const styleGainLoss = function(speciesTree){
const pattern_path=aln_file_path+panXTree.currentClusterID+'_patterns.json';
var node,stroke,stroke_width_factor,stroke_dasharray,event_type;
if (panXTree.singleton_gene) {
var node, fill;
for (var i=0; i<speciesTree.tips.length; i++){
node = speciesTree.tips[i];
node.tipAttributes.r = panXTree.geneAbsentR;
fill = panXTree.geneAbsentFill;
node.tipAttributes.fill = fill;
node.tipAttributes.stroke = d3.rgb(fill).darker(panXTree.strokeToFill).toString();
}
updateTips(speciesTree, ["r"], ["fill", "stroke"], 0);
}
d3.json(pattern_path, function(error, data){
const event_string=data['patterns'];
const nodes=speciesTree.nodes;
for (var i =0,len=nodes.length; i<len; i++){
node=nodes[i];
if (node.n.name!='NODE_0000000'){
event_type=event_string[i-1];
stroke=(event_type=='0'||event_type=='2')? panXTree.geneAbsentFill: panXTree.genePresentFill;
if (panXTree.singleton_gene && event_type=='1'){
node.tipAttributes.r = panXTree.genePresentR;
fill = panXTree.genePresentFill;
node.tipAttributes.fill = fill;
node.tipAttributes.stroke = d3.rgb(fill).darker(panXTree.strokeToFill).toString();
updateTips(speciesTree, ["r"], ["fill", "stroke"], 0);
}
stroke_width_factor=(event_type=='1'||event_type=='2')? 1.5: 1;
stroke_dasharray= (event_type=='2') ? "6,6" : "1,0";
node.branchAttributes["stroke"] = stroke;
//** store gene event color
//node.branchAttributes['event_pattern']=stroke;
node.branchAttributes["stroke-width"] = panXTree.branch_stroke_width*stroke_width_factor;
node.branchAttributes["stroke-dasharray"] = stroke_dasharray;
}
}
if (metaLegend.current_metaType=='genePattern'||!metaLegend.current_metaType){
updateBranches(speciesTree, [], ['stroke', 'stroke-width','stroke-dasharray'], 0);
}else{
updateBranches(speciesTree, [], ['stroke-width','stroke-dasharray'], 0);
}
//console.log('gain/loss pattern loading finished')
})
}
const tipStroke=panXTree.tipStroke;
export const resetGeneTreeColor = function(geneTree){
var node, fill;
for (var i=0; i<geneTree.tips.length; i++){
node = geneTree.tips[i];
node.tipAttributes.fill = tipStroke;
node.tipAttributes.stroke = tipStroke;
}
updateTips(geneTree, [], ["fill", "stroke"], 0);
}
|
wdingx/pan-genome-visualization
|
public/javascripts/tree-init.js
|
JavaScript
|
gpl-3.0
| 15,919 |
# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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.
#
# Timeline 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 Timeline. If not, see <http://www.gnu.org/licenses/>.
from timelinelib.utilities.observer import Observable
class CategoriesFacade(Observable):
def __init__(self, db, view_properties):
Observable.__init__(self)
self.db = db
self.view_properties = view_properties
self.db.listen_for_any(self._notify)
self.view_properties.listen_for_any(self._notify)
def get_all(self):
return self.db.get_categories()
def get_immediate_children(self, parent):
return [category for category in self.db.get_categories()
if category._get_parent() == parent]
def get_all_children(self, parent):
all_children = []
for child in self.get_immediate_children(parent):
all_children.append(child)
all_children.extend(self.get_all_children(child))
return all_children
def get_parents(self, child):
parents = []
while child._get_parent():
parents.append(child._get_parent())
child = child._get_parent()
return parents
def get_parents_for_checked_childs(self):
parents = []
for category in self._get_all_checked_categories():
parents.extend(self.get_parents(category))
return parents
def is_visible(self, category):
return self.view_properties.is_category_visible(category)
def is_event_with_category_visible(self, category):
return self.view_properties.is_event_with_category_visible(category)
def _get_all_checked_categories(self):
return [category for category in self.db.get_categories()
if self.is_visible(category)]
|
163gal/Time-Line
|
timelinelib/repositories/categories.py
|
Python
|
gpl-3.0
| 2,380 |
url: http://sanskrit.jnu.ac.in/sandhi/viccheda.jsp?itext=सत्यं भृशं भृशं व्योम<html>
<title>Sanskrit Sandhi Splitter at J.N.U. New Delhi</title>
<META CONTENT='text/hetml CHARSET=UTF-8' HTTP-EQUIV='Content-Type'/>
<META NAME="Author" CONTENT="Dr. Girish Nath Jha">
<META NAME="Keywords" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP">
<META NAME="Description" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP">
<head>
<head>
<style>
<!--
div.Section1
{page:Section1;}
-->
</style>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<script language="JavaScript" src=../js/menuitems.js></script>
<script language="JavaScript" src="../js/mm_menu.js"></script>
<meta name=Author content="Dr. Girish Nath Jha, JNU, New Delhi">
</head>
<body lang=EN-US link=blue vlink=blue style='tab-interval:.5in'>
<div class=Section1>
<div align=center>
<table border=1 cellspacing=0 cellpadding=0 width=802 style='width:601.5pt;
border-collapse:collapse;border:none;mso-border-alt:outset navy .75pt'>
<tr>
<td width=800 style='width:600.0pt;border:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'>
<script language="JavaScript1.2">mmLoadMenus();</script>
<img width=800 height=130 id="_x0000_i1028" src="../images/header1.jpg"
border=0>
</td>
</tr>
<tr>
<td width=818 style='width:613.5pt;border:inset navy .75pt;border-top:none;
mso-border-top-alt:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'>
<p align="center"><a href="../"><span style='text-decoration:none;text-underline:
none'><img border=1 width=49 height=26 id="_x0000_i1037"
src="../images/backtohome.jpg"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171051_0,6,29,null,'image2')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image2 src="../images/lang_tool.jpg"
name=image2 width="192" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171909_0,6,29,null,'image3')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image3 src="../images/lexical.jpg"
name=image3 width="137" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171609_0,6,29,null,'image1')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image1 src="../images/elearning.jpg"
name=image1 width="77" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171809_0,6,29,null,'image4')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image4 src="../images/corpora.jpg"
name=image4 width="105" height="26"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171709_0,6,29,null,'image5')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image5 src="../images/rstudents.jpg"
name=image5 width="125" height="26"></span></a><span style='text-underline:
none'> </span>
<a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171409_0,6,29,null,'image6')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image6 src="../images/feedback.jpg"
name=image6 width="80" height="25"></span></a><span style='text-underline:
none'> </span>
<!---
<a href="../user/feedback.jsp"><img border="1" src="../images/feedback.jpg" width="80" height="25"></a>
--->
</td>
</tr>
<tr>
<td width="800">
<p align="center"><font color="#FF9933"><span style='font-size:18.0pt;
'><b>Sanskrit Sandhi Recognizer and Analyzer</b></span></font></p>
The Sanskrit sandhi splitter (VOWEL SANDHI) was developed as part of M.Phil. research by <a href="mailto:[email protected]">Sachin Kumar</a> (M.Phil. 2005-2007), and <a href=mailto:[email protected]>Diwakar Mishra</a> (M.Phil. 2007-2009) under the supervision of <a href=http://www.jnu.ac.in/faculty/gnjha>Dr. Girish Nath Jha</a>. The coding for this application has been done by Dr. Girish Nath Jha and Diwakar Mishra. <!---Please send feedback to to <a href="mailto:[email protected]">Dr. Girish Nath Jha</A>--->The Devanagari input mechanism has been developed in Javascript by Satyendra Kumar Chaube, Dr. Girish Nath Jha and Dharm Singh Rathore.
</center>
<table border=0 width=100%>
<tr>
<td valign=top width=48%>
<table>
<tr>
<td>
<FORM METHOD=get ACTION=viccheda.jsp#results name="iform" accept-Charset="UTF-8">
<font size=2><b>Enter Sanskrit text for sandhi processing (संधि-विच्छेद हेतु पाठ्य दें)
using adjacent keyboard OR Use our inbuilt <a href=../js/itrans.html target=_blank>iTRANS</a>-Devanagari unicode converter for fast typing<br>
<a href=sandhitest.txt>examples</a>
<TEXTAREA name=itext COLS=40 ROWS=9 onkeypress=checkKeycode(event) onkeyup=iu()> सत्यं भृशं भृशं व्योम</TEXTAREA>
</td>
</tr>
<tr>
<td>
<font color=red size=2>Run in debug mode</font>
<input type=checkbox name="debug" value="ON">
<br>
<input type=submit value="Click to sandhi-split (संधि-विच्छेद करें)"></span><br>
</td>
</tr>
</table>
</td>
<td valign=top width=52%>
<table>
<tr>
<td>
<head>
<SCRIPT language=JavaScript src="../js/devkb.js"></SCRIPT>
<head>
<TEXTAREA name=itrans rows=5 cols=10 style="display:none"></TEXTAREA>
<INPUT name=lastChar type=hidden>
<table border=2 style="background-color:#fff;">
<tbody>
<tr >
<td>
<input type=button name="btn" style="width: 24px" value="अ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="आ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="इ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ई" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="उ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऊ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ए" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऐ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ओ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="औ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="अं" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="अः" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऍ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऑ" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="्" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ा" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ि" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ी" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ु" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ू" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="े" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ै" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ो" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ौ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ं" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ः" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॅ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॉ" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="क" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ख" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ग" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="घ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ङ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="च" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="छ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ज" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="झ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ञ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 100px" value="Backspace" onClick="BackSpace()">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="+" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ट" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ठ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ड" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ढ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ण" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="त" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="थ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="द" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ध" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="न" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="/" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="प" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="फ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ब" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="भ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="म" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="य" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ल" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="व" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="।" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="*" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="श" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ष" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="स" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="ऋ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऌ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ृ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॄ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="ह" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="॥" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="त्र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ज्ञ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="क्ष" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="श्र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 200px" value="Space Bar" onClick="Space()">
<input type=button name="btn" style="width: 24px" value="ँ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="़" onClick="keyboard(this.value)">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
</table>
</form>
<a name=results>
<font size=4><b><u>Results</u></b></font>
<br>
सते अं (अयादिसन्धि एचोऽयवायावः)<br> सती अं (यण् सन्धि इको यणचि)<br> सति अं (यण् सन्धि इको यणचि)<br> व्य ऊम (गुणसन्धि आद् गुणः)<br> व्य उम (गुणसन्धि आद् गुणः)<br> व्या ऊम (गुणसन्धि आद् गुणः)<br> व्या उम (गुणसन्धि आद् गुणः)<br> व्य ओम (पररूपसन्धि एङि पररूपम्/ओमाङोश्च)<br> व्या ओम (पररूपसन्धि एङि पररूपम्/ओमाङोश्च)<br>
<br>
<font color=red>
<br>
<hr>
<br>
</body>
</html>
|
sanskritiitd/sanskrit
|
uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/agnipuran-1-111-sandhi_ext.txt.out.dict_3762_jnu.html
|
HTML
|
gpl-3.0
| 17,345 |
-----------------------------------
-- Area: Den of Rancor
-- MOB: Tonberry Imprecator
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
checkGoVregime(ally,mob,798,1);
checkGoVregime(ally,mob,799,2);
checkGoVregime(ally,mob,800,2);
local kills = ally:getVar("EVERYONES_GRUDGE_KILLS");
if (kills < 480) then
ally:setVar("EVERYONES_GRUDGE_KILLS",kills + 1);
end
end;
|
jshackley/darkstar
|
scripts/zones/Den_of_Rancor/mobs/Tonberry_Imprecator.lua
|
Lua
|
gpl-3.0
| 636 |
<?php
if(isset($init_flag) == false)
die;
/** \file cdebug.php
\author Auditiel
\author Jérôme Dusautois
\date 16/01/2008
\version 1.0.0
\brief Fichier contenant les classes de gestion des traces
*/
/** \brief Classe de dump d'une variable. Cette classe a été créée par Daniel Jaenecke.
*/
class cdump {
/*
* dump.class.php
* a class for generating dumps from all types of variables
*
* Copyright (C) 2002 Daniel Jaenecke <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* HOW TO USE
* ==========
*
* You can assign the data you which to dump in two ways:
* a) when creating an object, e.g.
* $d = new dump ( $my_data )
*
* b) by calling the method assign()
* $d = new dump;
* $d->assign( $my_data );
*
* The method get_html() will return an HTML-table representing the
* data which has been assigned before using one of the methods mentioned
* above. After either a) or b) a command like
* echo $d->get_html ();
* would output the table.
*
* CUSTOMIZING
* ===========
*
* The output is formatted using HTML-inline-styles which are defined in the
* properties style_key, style_value and style_type. By assigning different
* values output may be changed easily to fit individual needs.
*
* REQUIREMENTS
* ============
*
* This class needs PHP 4.0.2 or later to run; by removing the call to the
* function get_ressource_type () it can be used on PHP 4.0.0. Just follow
* the comment to do the change
*
* TODO
* ====
*
* - method for generating raw output
* - interface for customizing styles
*
*/
/* PROPERTIES */
/* data for dumping */
var
$data = NULL;
/* styles for HTML-Output */
var
$style_key = NULL,
$style_value = NULL,
$style_type = NULL
;
/* METHODS */
/*
* public constructor dump ( [ mixed data ] )
* construcor; accepting data for dumping as parameter
*/
function cdump ( $data = NULL) {
/* assign data if available */
if ( !is_null ( $data ) ) {
$this->assign_data ( $data );
}
/* set up styles for HTML-output */
$this->style_key = 'font-family: sans-serif; font-size: 11px; font-weight: bold; background-color: #f0f0f0;';
$this->style_value = 'font-family: monospace; font-size: 11px;';
$this->style_type = 'font-family: sans-serif; font-size: 9px; font-style: italic; color: #000080;';
} /* function dump */
/*
* public string get_html ( [ mixed data ] )
* creates and returns an HTML-Table from this->data
*/
function get_html ( ) {
if ( !isset ( $this->data ) ) {
return false;
}
else {
return $this->_make_HTML_table ( $this->data );
}
} /* function get_html */
/*
* public void assign_data ( mixed data )
* assign data for later dump
*/
function assign_data ( $data ) {
$this->data = $data;
} /* function assign_data */
/*
* private string _make_HTML_table ( mixed data )
*
*/
function _make_HTML_table ( $data ) {
if ( !is_array ( $data ) ) {
switch ( gettype ( $data ) ) {
case 'string':
return ( isset ( $data ) && !empty ( $data ) ) ?
htmlentities ( $data ) :
' '
;
break; /* string */
case 'boolean':
return $data ? 'true' : 'false';
break; /* boolean */
case 'object':
$object_data = array (
'class' => get_class ( $data ),
'parent_class' => get_parent_class ( $data ),
'methods' => get_class_methods ( get_class ( $data ) ),
'properties' => get_object_vars ( $data )
);
return $this->_make_HTML_table ( $object_data );
break; /* object */
case 'resource':
/*
* use the next line of code when
* using PHP 4.0.0 or PHP 4.0.1
*/
// return $data;
/*
* use the next line of code
* when using PHP 4.0.2 or better
*/
return sprintf ( '%s (%s)', $data, get_resource_type ( $data ) );
break; // resource
default:
return $data;
break; /* default */
} /* switch gettype */
} /* if !array data */
$output = '<table border="1" cellpadding="0" cellspacing="0">';
foreach ( $data as $key => $value ) {
$type = substr ( gettype ( $data[ $key ] ), 0, 3 );
$output .= sprintf (
'<tr>
<td style="%s">%s</td>
<td style="%s">%s</td>
<td style="%s">%s</td>
</tr>',
$this->style_key, $key,
$this->style_type, $type,
$this->style_value, $this->_make_HTML_table ( $value )
);
} /* foreach data */
$output .= '</table>';
return $output;
} /* function _make_HTML_table */
} /* class dump */
/** \brief Classe de trace dans un fichier.
*/
class ctrace
{
/** \brief Constructeur de l'objet.
*@param name Nom du fichier à générer.
*/
function ctrace( $name )
{
$this->Name = $name;
}
/** \brief Ecriture d'un fichier complet. Si le fichier existe, il est remplacé.
*@param data Données à écrire.
*/
function writefile($data)
{
$trace = fopen( $this->Name, "w" );
if( $trace != null )
{
fwrite( $trace, $data, strlen($data) );
fclose( $trace);
}
}
/** \brief Ecriture d'une ligne à la fin du fichier de trace.
*@param data Données de la ligne à écrire.
*/
function writeline($data)
{
$trace = fopen( $this->Name, "a+");
if( $trace != null )
{
$data .= "\r\n";
fwrite( $trace, $data, strlen($data) );
fclose( $trace);
}
}
/** \brief Ecriture du vidage d'une variable au format html.
*@param var Nom de la variable à vider.
*/
function dump($var)
{
$cdump = new cdump( $var );
$this->writefile( $cdump->get_html() );
}
}
/** \brief Classe de debug d'un utilisateur
*/
class cdebug
{
const LEVEL0=0; // Pas de trace
const LEVEL1=1; // Trace entrée sortie de fonction
const LEVEL2=2; // Trace intermédiares
const LEVEL3=3; // Trace intermédiaire (dump)
const LEVEL4=4; // Trace intermédiaire complète
/** \brief Constructeur de l'objet.
*@param id ID de l'utilisateur.
*@param name Nom de l'utilisateur
*/
function cdebug( $dir, $id=0, $name='', $level=cdebug::LEVEL0 )
{
$this->ID = $id;
$this->name = $name;
$this->dirtrace = $dir;
$this->funcin = array();
$this->classin = array();
$this->traceclass = array();
$this->deep = 0;
$this->ctrace = null;
$this->traceclassdisabled = array();
$this->setlevel($level);
// Désactive les traces de la classe casn1
$this->enableclass( "casn1", false );
}
/** \brief Positionne le niveau de trace courant. si la trace n'était pas encore initialisée, elle l'est.
*/
function setlevel( $Level )
{
$this->level = is_numeric($Level) ? $Level : 0;
if( $this->level > cdebug::LEVEL0 && ($this->ctrace == null) )
{
if( is_dir($this->dirtrace) )
$this->ctrace = new ctrace($this->dirtrace.$this->name.".".$this->ID.".log");
else
$this->ctrace = null;
}
}
/** \brief Active ou désactive les traces pour une classe
* @param classname Nom de la classe
* @param enable Active les traces si true
*/
function enableclass( $classname, $enable=true)
{
if( $enable == true )
unset($this->traceclassdisabled[$classname]);
else
$this->traceclassdisabled[$classname] = true;
}
/** \brief Retroune le niveau de trace courant
*/
function getlevel()
{
return $this->level;
}
/** \brief Positionne le niveau de profondeur.
*/
function resetdeep( $deep=1 )
{
$this->deep = is_numeric($deep) ? $deep : 1;
}
/** \brief Initialisation d'une nouvelle trace
*/
function init()
{
// Ecrase le fichier avec la ligne de début
if( $this->ctrace != null )
$this->ctrace->writefile( $this->formatline("Initialisation trace\r\n") );
}
/** \brief Entrée dans une fonction d'une classe
* @param Fonc Nom dela fonction
* @param Class Nom de la classe
*/
function tracein( $Fonc, $Class='', $Info="" )
{
$this->classin[$this->deep] = $Class;
$this->funcin[$this->deep] = $Fonc;
if( !empty($Class) && !empty($this->traceclassdisabled[$Class]) )
$this->traceclass[$this->deep] = false;
else
$this->traceclass[$this->deep] = true;
$this->deep++;
$msg = "Entree Fonc=$Fonc";
if( !empty($Class) )
$msg .= " Class=$Class";
if( !empty($Info) )
$msg .= " $Info";
$this->write( $msg );
}
/** \brief Sortie d'une fonction
* @param Res résultat
*/
function traceout($Res='', $Errno='')
{
$msg = '';
if( $this->deep > 0 )
{
$fonc = $this->funcin[$this->deep-1];
$class = $this->classin[$this->deep-1];
}
else
{
$fonc = "deep-";
$class = "";
}
$msg .= "Sortie Fonc=".$fonc;
if( !empty($class) )
$msg .= " Class=".$class;
if( !empty($Res) )
{
if( !empty($Errno) )
$msg .= " Erreur=$Errno Resultat=$Res";
else
$msg .= " Resultat=$Res";
}
$this->write( $msg );
if( $this->deep > 0 )
$this->deep--;
}
/** \brief Trace dans une fonction
* @param Msg message
*/
function trace($Msg, $Level=cdebug::LEVEL2 )
{
if( $this->level >= $Level )
{
$this->write( $Msg );
}
}
/** \brief Vide une variable
* @param Name Nom de la variable
* @param Var La variable
*/
function dump($Name, $Data)
{
if( $this->level >= cdebug::LEVEL3 )
{
$this->write("Variable $Name" );
foreach ( $Data as $key => $value )
{
$type = substr ( gettype ( $data[ $key ] ), 0, 3 );
$msg = " $key=$value";
$this->write( $msg );
}
}
}
/** \brief Ecriture d'une ligne
*/
function write($line)
{
if( $this->ctrace != null ) {
if( $this->deep > 0 && $this->traceclass[$this->deep-1] == true ) {
$this->ctrace->writeline($this->formatline($line));
}
}
}
/** \brief Formatage d'une ligne
*/
private function formatline( $Line )
{
$mt = explode( " ", microtime() );
$mt = substr( $mt[0],0,8 );
$msg = date('Y/m/d H:i:s')." ".$mt." ".memory_get_usage().str_pad(" ", $this->deep ).$Line;
return $msg;
}
}
?>
|
TrustDesigner/ShotnGet-Api
|
shotngetapi/cdebug.php
|
PHP
|
gpl-3.0
| 11,153 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include "abstractformeditortool.h"
#include "movemanipulator.h"
#include "selectionindicator.h"
#include "resizeindicator.h"
#include "anchorindicator.h"
#include "bindingindicator.h"
#include "contentnoteditableindicator.h"
namespace QmlDesigner {
class MoveTool : public AbstractFormEditorTool
{
public:
MoveTool(FormEditorView* editorView);
~MoveTool();
void mousePressEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) override;
void mouseDoubleClickEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) override;
void hoverMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void keyReleaseEvent(QKeyEvent *keyEvent) override;
void dragLeaveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneDragDropEvent * event) override;
void dragMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneDragDropEvent * event) override;
void itemsAboutToRemoved(const QList<FormEditorItem*> &itemList) override;
void selectedItemsChanged(const QList<FormEditorItem*> &itemList) override;
void instancesCompleted(const QList<FormEditorItem*> &itemList) override;
void instancesParentChanged(const QList<FormEditorItem *> &itemList) override;
void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList) override;
void updateMoveManipulator();
void beginWithPoint(const QPointF &beginPoint);
void clear() override;
void formEditorItemsChanged(const QList<FormEditorItem*> &itemList) override;
void focusLost() override;
protected:
static bool haveSameParent(const QList<FormEditorItem*> &itemList);
static QList<FormEditorItem*> movingItems(const QList<FormEditorItem*> &selectedItemList);
static bool isAncestorOfAllItems(FormEditorItem* maybeAncestorItem,
const QList<FormEditorItem*> &itemList);
static FormEditorItem* ancestorIfOtherItemsAreChild(const QList<FormEditorItem*> &itemList);
private:
MoveManipulator m_moveManipulator;
SelectionIndicator m_selectionIndicator;
ResizeIndicator m_resizeIndicator;
AnchorIndicator m_anchorIndicator;
BindingIndicator m_bindingIndicator;
ContentNotEditableIndicator m_contentNotEditableIndicator;
QList<FormEditorItem*> m_movingItems;
};
} // namespace QmlDesigner
|
Philips14171/qt-creator-opensource-src-4.2.1
|
src/plugins/qmldesigner/components/formeditor/movetool.h
|
C
|
gpl-3.0
| 3,877 |
/* 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 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.
*/
/* File for "Textures" lesson of the OpenGL tutorial on
* www.videotutorialsrock.com
*/
#include <assert.h>
#include <fstream>
#include "imageloader.h"
using namespace std;
Image::Image(char* ps, int w, int h) : pixels(ps), width(w), height(h) {
}
Image::~Image() {
delete[] pixels;
}
namespace {
//Converts a four-character array to an integer, using little-endian form
int toInt(const char* bytes) {
return (int)(((unsigned char)bytes[3] << 24) |
((unsigned char)bytes[2] << 16) |
((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}
//Converts a two-character array to a short, using little-endian form
short toShort(const char* bytes) {
return (short)(((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}
//Reads the next four bytes as an integer, using little-endian form
int readInt(ifstream &input) {
char buffer[4];
input.read(buffer, 4);
return toInt(buffer);
}
//Reads the next two bytes as a short, using little-endian form
short readShort(ifstream &input) {
char buffer[2];
input.read(buffer, 2);
return toShort(buffer);
}
//Just like auto_ptr, but for arrays
template<class T>
class auto_array {
private:
T* array;
mutable bool isReleased;
public:
explicit auto_array(T* array_ = NULL) :
array(array_), isReleased(false) {
}
auto_array(const auto_array<T> &aarray) {
array = aarray.array;
isReleased = aarray.isReleased;
aarray.isReleased = true;
}
~auto_array() {
if (!isReleased && array != NULL) {
delete[] array;
}
}
T* get() const {
return array;
}
T &operator*() const {
return *array;
}
void operator=(const auto_array<T> &aarray) {
if (!isReleased && array != NULL) {
delete[] array;
}
array = aarray.array;
isReleased = aarray.isReleased;
aarray.isReleased = true;
}
T* operator->() const {
return array;
}
T* release() {
isReleased = true;
return array;
}
void reset(T* array_ = NULL) {
if (!isReleased && array != NULL) {
delete[] array;
}
array = array_;
}
T* operator+(int i) {
return array + i;
}
T &operator[](int i) {
return array[i];
}
};
}
Image* loadBMP(const char* filename) {
ifstream input;
input.open(filename, ifstream::binary);
assert(!input.fail() || !"Could not find file");
char buffer[2];
input.read(buffer, 2);
assert(buffer[0] == 'B' && buffer[1] == 'M' || !"Not a bitmap file");
input.ignore(8);
int dataOffset = readInt(input);
//Read the header
int headerSize = readInt(input);
int width;
int height;
switch(headerSize) {
case 40:
//V3
width = readInt(input);
height = readInt(input);
input.ignore(2);
assert(readShort(input) == 24 || !"Image is not 24 bits per pixel");
assert(readShort(input) == 0 || !"Image is compressed");
break;
case 12:
//OS/2 V1
width = readShort(input);
height = readShort(input);
input.ignore(2);
assert(readShort(input) == 24 || !"Image is not 24 bits per pixel");
break;
case 64:
//OS/2 V2
assert(!"Can't load OS/2 V2 bitmaps");
break;
case 108:
//Windows V4
assert(!"Can't load Windows V4 bitmaps");
break;
case 124:
//Windows V5
assert(!"Can't load Windows V5 bitmaps");
break;
default:
assert(!"Unknown bitmap format");
}
//Read the data
int bytesPerRow = ((width * 3 + 3) / 4) * 4 - (width * 3 % 4);
int size = bytesPerRow * height;
auto_array<char> pixels(new char[size]);
input.seekg(dataOffset, ios_base::beg);
input.read(pixels.get(), size);
//Get the data into the right format
auto_array<char> pixels2(new char[width * height * 3]);
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
for(int c = 0; c < 3; c++) {
pixels2[3 * (width * y + x) + c] =
pixels[bytesPerRow * y + 3 * x + (2 - c)];
}
}
}
input.close();
return new Image(pixels2.release(), width, height);
}
|
BSchoone/opengl-cg200
|
imageloader.cpp
|
C++
|
gpl-3.0
| 5,090 |
APPNAME = isis2raw
include $(ISISROOT)/make/isismake.tsts
commands:
$(APPNAME) from=$(INPUT)/isisTruth.cub+2 \
to=$(OUTPUT)/isis2rawTruth3.raw \
storageorder=bil \
bittype= U16BIT > /dev/null;
|
corburn/ISIS
|
isis/src/base/apps/isis2raw/tsts/u16bitBIL/Makefile
|
Makefile
|
gpl-3.0
| 199 |
module('sigma.plugins.design');
test('API', function(assert) {
var a,
k,
s = new sigma(),
design;
var graph = {
nodes: [
{
id: 'n0',
label: 'Node 0',
color: '#333',
size: 1,
data: {quantity: 5, quality: 'A'}
},
{
id: 'n1',
label: 'Node 1',
data: {quantity: 3, quality: 'B'}
},
{
id: 'n2',
label: 'Node 2',
data: {quantity: -10, quality: 'C'}
},
{
id: 'n3',
label: 'Node 3',
data: {}
},
{
id: 'n4',
label: 'Node 4',
data: {quantity: 1, quality: 'A'}
}
],
edges: [
{
id: 'e0',
source: 'n0',
target: 'n1',
quantity: 0
},
{
id: 'e1',
source: 'n1',
target: 'n2',
quantity: 1
},
{
id: 'e2',
source: 'n1',
target: 'n3',
quantity: 2
},
{
id: 'e3',
source: 'n2',
target: 'n3',
quantity: -1
},
{
id: 'e4',
source: 'n0',
target: 'n0'
}
]
},
// Create a custom color palette:
myPalette = {
aQualitativeScheme: {
'A': '#7fc97f',
'B': '#beaed4',
'C': '#fdc086'
},
colorbrewer: {
sequentialGreen: {
3: ["#e5f5f9","#99d8c9","#2ca25f"],
4: ["#edf8fb","#b2e2e2","#66c2a4","#238b45"],
5: ["#edf8fb","#b2e2e2","#66c2a4","#2ca25f","#006d2c"],
6: ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#2ca25f","#006d2c"],
7: ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"],
8: ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"],
9: ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"]
}
}
},
myStyles = {
nodes: {
label: {
by: 'id',
format: function(value) { return '#' + value; }
},
size: {
by: 'data.quantity',
bins: 7,
min: 2,
max: 20
},
color: {
by: 'data.quality',
scheme: 'aQualitativeScheme',
},
},
edges: {
color: {
by: 'quantity',
scheme: 'colorbrewer.sequentialGreen',
bins: 7
},
size: {
by: 'quantity',
bins: 7,
min: 1,
max: 5
},
}
};
// Initialize the design:
design = sigma.plugins.design(s, {
styles: myStyles,
palette: myPalette
});
s.graph.read(graph);
design.apply('nodes');
design.apply('edges');
design.apply();
design.deprecate();
// check apply node color
design.apply('nodes', 'color');
ok(
design.styles.nodes.color.active,
'nodes color is active after "apply(\'nodes\', \'color\')"'
);
strictEqual(
s.graph.nodes('n0').color,
'#7fc97f',
'"apply(\'nodes\', \'color\')" applies node color'
);
strictEqual(
s.graph.nodes('n1').color,
'#beaed4',
'"apply(\'nodes\', \'color\')" applies node color'
);
strictEqual(
s.graph.nodes('n2').color,
'#fdc086',
'"apply(\'nodes\', \'color\')" applies node color'
);
strictEqual(
s.graph.nodes('n3').color,
undefined,
'"apply(\'nodes\', \'color\')" applies node color'
);
strictEqual(
s.graph.nodes('n4').color,
'#7fc97f',
'"apply(\'nodes\', \'color\')" applies node color'
);
// check apply node size
design.apply('nodes', 'size');
ok(
design.styles.nodes.size.active,
'nodes size is active after "apply(\'nodes\', \'size\')"'
);
strictEqual(
s.graph.nodes('n0').size,
7,
'"apply(\'nodes\', \'size\')" applies node size'
);
strictEqual(
s.graph.nodes('n1').size,
7,
'"apply(\'nodes\', \'size\')" applies node size'
);
strictEqual(
s.graph.nodes('n2').size,
1,
'"apply(\'nodes\', \'size\')" applies node size'
);
// check reset node color
// see https://github.com/jacomyal/sigma.js/issues/500
// design.reset('nodes', 'color');
// strictEqual(
// s.graph.nodes('n0').color,
// '#333',
// '"reset(\'nodes\', \'color\')" reset node color'
// );
// strictEqual(
// s.graph.nodes('n1').color,
// undefined,
// '"reset(\'nodes\', \'color\')" reset node color'
// );
// check reset node size
design.reset('nodes', 'size');
ok(
!design.styles.nodes.size.active,
'nodes size is not active after "reset(\'nodes\', \'size\')"'
);
strictEqual(
s.graph.nodes('n0').size,
1,
'"reset(\'nodes\', \'size\')" reset node size'
);
design.apply('edges', 'color');
ok(
design.styles.edges.color.active,
'edges color is active after "apply(\'edges\', \'color\')"'
);
design.apply('edges', 'size');
ok(
design.styles.edges.size.active,
'edges size is active after "apply(\'edges\', \'size\')"'
);
design.reset('edges', 'color');
ok(
!design.styles.edges.color.active,
'edges color is not active after "reset(\'edges\', \'color\')"'
);
design.reset('edges', 'size');
ok(
!design.styles.edges.size.active,
'edges size is not active after "reset(\'edges\', \'size\')"'
);
design.apply();
ok(
design.styles.nodes.color.active,
'nodes color is active after "apply()"'
);
// check histogram function
equal(
design.utils.histogram('edges', 'color', 'quantity').length,
7,
'"design.utils.histogram" returns an array of specified length'
);
throws(
function() {
design.utils.histogram('edges', 'color', 'meh');
},
new Error('The property "meh" is not sequential.'),
'"utils.histogram" throws an error on a non-existing property.'
);
throws(
function() {
design.utils.histogram('edges', 'meh', 'quantity');
},
new Error('Unknown visual variable "meh".'),
'"utils.histogram" throws an error on an unknown visual variable.'
);
throws(
function() {
design.utils.histogram('meh', 'color', 'quantity');
},
new Error('Invalid argument: "target" is not "nodes" or "edges", was meh'),
'"utils.histogram" throws an error on an unknown target.'
);
// check isSequential function
ok(
design.utils.isSequential('nodes', 'data.quantity'),
'"utils.isSequential" returns true on a quantitative property'
);
ok(
!design.utils.isSequential('nodes', 'data.quality'),
'"utils.isSequential" returns false on a qualitative property'
);
strictEqual(
design.utils.isSequential('nodes', 'data.missing'),
undefined,
'"utils.isSequential" returns undefined on a property which does not exist'
);
design.reset();
design.clear();
// check plugin lifecycle
design.kill();
s.kill();
s = new sigma();
design = sigma.plugins.design(s);
s.graph.read(graph);
design
.nodesBy('label', myStyles.nodes.label)
.nodesBy('size', myStyles.nodes.size)
.setPalette(myPalette)
.nodesBy('color', myStyles.nodes.color)
.edgesBy('size', myStyles.edges.size)
.edgesBy('color', myStyles.edges.color)
.apply();
sigma.plugins.killDesign(s);
deepEqual(
design.styles,
undefined,
'The styles object is undefined after `killDesign` is called.'
);
design.apply(); // does nothing
design.reset(); // does nothing
});
|
ekkis/linkurious.js
|
test/unit.plugins.design.js
|
JavaScript
|
gpl-3.0
| 7,399 |
/*
Copyright (C) 2014-2016 [email protected]
This file is part of dnSpy
dnSpy 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.
dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics;
using dndbg.COM.MetaData;
using dnlib.DotNet;
using dnlib.DotNet.MD;
namespace dndbg.Engine {
struct DebugSignatureReader {
static DebugSignatureReader() {
noOwnerModule = new ModuleDefUser();
corLibTypes = new CorLibTypes(noOwnerModule);
}
static readonly ModuleDef noOwnerModule;
static readonly CorLibTypes corLibTypes;
internal static CorLibTypes CorLibTypes {
get { return corLibTypes; }
}
sealed class SignatureReaderHelper : ISignatureReaderHelper {
readonly IMetaDataImport mdi;
public SignatureReaderHelper(IMetaDataImport mdi) {
Debug.Assert(mdi != null);
if (mdi == null)
throw new ArgumentNullException();
this.mdi = mdi;
}
public ITypeDefOrRef ResolveTypeDefOrRef(uint codedToken, GenericParamContext gpContext) {
uint token;
if (!CodedToken.TypeDefOrRef.Decode(codedToken, out token))
return null;
uint rid = MDToken.ToRID(token);
switch (MDToken.ToTable(token)) {
case Table.TypeDef: return new TypeDefDndbg(mdi, rid);
case Table.TypeRef: return new TypeRefDndbg(mdi, rid);
case Table.TypeSpec: return new TypeSpecDndbg(mdi, rid, this);
}
return null;
}
public TypeSig ConvertRTInternalAddress(IntPtr address) {
return null;
}
}
public TypeSig ReadTypeSignature(IMetaDataImport mdi, byte[] data) {
return SignatureReader.ReadTypeSig(new SignatureReaderHelper(mdi), corLibTypes, data);
}
public CallingConventionSig ReadSignature(IMetaDataImport mdi, byte[] data) {
return SignatureReader.ReadSig(new SignatureReaderHelper(mdi), corLibTypes, data);
}
public static TypeDef CreateTypeDef(IMetaDataImport mdi, uint rid) {
return new TypeDefDndbg(mdi, rid);
}
}
interface IMetaDataImportProvider : IMDTokenProvider {
IMetaDataImport MetaDataImport { get; }
}
sealed class TypeDefDndbg : TypeDefUser, IMetaDataImportProvider {
public IMetaDataImport MetaDataImport {
get { return mdi; }
}
readonly IMetaDataImport mdi;
public TypeDefDndbg(IMetaDataImport mdi, uint rid)
: base(UTF8String.Empty) {
this.mdi = mdi;
this.rid = rid;
InitializeName(MDAPI.GetTypeDefName(mdi, MDToken.Raw), out @namespace, out name);
}
internal static void InitializeName(string fullname, out UTF8String @namespace, out UTF8String name) {
string s = fullname ?? string.Empty;
int index = s.LastIndexOf('.');
if (index < 0) {
@namespace = UTF8String.Empty;
name = s;
}
else {
@namespace = s.Substring(0, index);
name = s.Substring(index + 1);
}
}
}
sealed class TypeRefDndbg : TypeRefUser, IMetaDataImportProvider {
public IMetaDataImport MetaDataImport {
get { return mdi; }
}
readonly IMetaDataImport mdi;
public TypeRefDndbg(IMetaDataImport mdi, uint rid)
: base(null, UTF8String.Empty) {
this.mdi = mdi;
this.rid = rid;
TypeDefDndbg.InitializeName(MDAPI.GetTypeRefName(mdi, MDToken.Raw), out @namespace, out name);
}
}
sealed class TypeSpecDndbg : TypeSpecUser, IMetaDataImportProvider {
public IMetaDataImport MetaDataImport {
get { return mdi; }
}
readonly IMetaDataImport mdi;
readonly ISignatureReaderHelper helper;
public TypeSpecDndbg(IMetaDataImport mdi, uint rid, ISignatureReaderHelper helper)
: base() {
this.mdi = mdi;
this.rid = rid;
this.helper = helper;
}
protected override TypeSig GetTypeSigAndExtraData_NoLock(out byte[] extraData) {
var sigData = MDAPI.GetTypeSpecSignatureBlob(mdi, MDToken.Raw);
var sig = ReadTypeSignature(sigData, new GenericParamContext(), out extraData);
if (sig != null)
sig.Rid = rid;
return sig;
}
TypeSig ReadTypeSignature(byte[] data, GenericParamContext gpContext, out byte[] extraData) {
if (data == null) {
extraData = null;
return null;
}
return SignatureReader.ReadTypeSig(helper, new CorLibTypes(noOwnerModule), data, gpContext, out extraData);
}
static readonly ModuleDef noOwnerModule = new ModuleDefUser();
}
}
|
levisre/dnSpy
|
dndbg/Engine/DndbgSignatureReader.cs
|
C#
|
gpl-3.0
| 4,736 |
package id.bashir.cekpassword;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
tyangjawi03/cekpassword
|
passwordmatter/src/androidTest/java/id/bashir/cekpassword/ApplicationTest.java
|
Java
|
gpl-3.0
| 352 |
/*!
* \file gn3s_source_cc.h
* \brief GNU Radio source block to acces to SiGe GN3S USB sampler v2.
* \author Javier Arribas, 2012. jarribas(at)cttc.es
*
* -------------------------------------------------------------------------
*
* Copyright (C) 2010-2012 (see AUTHORS file for a list of contributors)
*
* GNSS-SDR is a software defined Global Navigation
* Satellite Systems receiver
*
* This file is part of GNSS-SDR.
*
* GNSS-SDR 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.
*
* GNSS-SDR 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 GNSS-SDR. If not, see <http://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/
#ifndef INCLUDED_GN3S_SOURCE_CC_H
#define INCLUDED_GN3S_SOURCE_CC_H
#include "gn3s_api.h"
#include <gnuradio/block.h>
#include "gn3s_source.h"
#include "gn3s_defines.h"
class gn3s_source_cc;
/*
* We use boost::shared_ptr's instead of raw pointers for all access
* to gr_blocks (and many other data structures). The shared_ptr gets
* us transparent reference counting, which greatly simplifies storage
* management issues. This is especially helpful in our hybrid
* C++ / Python system.
*
* See http://www.boost.org/libs/smart_ptr/smart_ptr.htm
*
* As a convention, the _sptr suffix indicates a boost::shared_ptr
*/
typedef boost::shared_ptr<gn3s_source_cc> gn3s_source_cc_sptr;
/*!
* \brief Return a shared_ptr to a new instance of howto_square_ff.
*
* To avoid accidental use of raw pointers, gn3s_source's
* constructor is private. gn3s_source is the public
* interface for creating new instances.
*/
GN3S_API gn3s_source_cc_sptr gn3s_make_source_cc ();
/*!
* \brief SiGe GN3S V2 sampler USB driver.
* \ingroup block
*
* \sa gn3s_source for a version that subclasses gr_block.
*/
class GN3S_API gn3s_source_cc : public gr::block
{
private:
// The friend declaration allows gn3s_source to
// access the private constructor.
/* Create the GN3S object*/
gn3s_Source *gn3s_drv;
gn3s_ms_packet packet;
friend GN3S_API gn3s_source_cc_sptr gn3s_make_source_cc ();
/*!
* \brief
*/
gn3s_source_cc (); // private constructor
public:
~gn3s_source_cc (); // public destructor
// Where all the action really happens
int general_work (int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
};
#endif /* INCLUDED_GN3S_SOURCE_CC_H */
|
odrisci/gnss-sdr
|
drivers/gr-gn3s/include/gn3s_source_cc.h
|
C
|
gpl-3.0
| 2,935 |
/*
*************************************************************************************
* Copyright 2017 Normation SAS
*************************************************************************************
*
* This file is part of Rudder.
*
* Rudder 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.
*
* In accordance with the terms of section 7 (7. Additional Terms.) of
* the GNU General Public License version 3, the copyright holders add
* the following Additional permissions:
* Notwithstanding to the terms of section 5 (5. Conveying Modified Source
* Versions) and 6 (6. Conveying Non-Source Forms.) of the GNU General
* Public License version 3, when you create a Related Module, this
* Related Module is not considered as a part of the work and may be
* distributed under the license agreement of your choice.
* A "Related Module" means a set of sources files including their
* documentation that, without modification of the Source Code, enables
* supplementary functions or services in addition to those offered by
* the Software.
*
* Rudder 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 Rudder. If not, see <http://www.gnu.org/licenses/>.
*
*************************************************************************************
*/
var groupManagement = angular.module('groupManagement', []);
groupManagement.controller('GroupCtrl', ['$scope', function($scope) {
// Init function so values can be set from outside the scope
$scope.init = function ( target, mapTarget ) {
$scope.mapTarget=mapTarget;
$scope.target = target;
};
// Get name of a target (ie the group name) instead of using the target
$scope.getTargetName = function (target) {
return $scope.mapTarget[target];
};
// Text to display if there is no target selected
$scope.emptyTarget = "Select groups from the tree on the left to add them here"
// Update the html field that stocks the target
$scope.updateTarget = function() {
$('#selectedTargets').val(JSON.stringify($scope.target));
};
// Remove from excluded targets the target passed as parameter
$scope.removeExclude = function ( excluded ) {
var index = $scope.target.exclude.or.indexOf(excluded);
// remove only if the target is here
if ( index > -1 ) {
$scope.target.exclude.or.splice(index,1);
$scope.updateTarget();
var jsId = excluded.replace(':','\\:');
$("#jstree-"+jsId).removeClass("excluded");
};
};
// Remove from included targets the target passed as parameter
$scope.removeInclude = function ( included ) {
var index = $scope.target.include.or.indexOf(included);
// remove only if the target is here
if ( index > -1 ) {
$scope.target.include.or.splice(index,1);
$scope.updateTarget();
var jsId = included.replace(':','\\:');
$("#jstree-"+jsId).removeClass("included");
};
};
// Add the new target to include, remove it from included targets if it was
$scope.addInclude = function ( included ) {
var index = $scope.target.include.or.indexOf(included);
// Only add if the target is missing
if ( index == -1 ) {
$scope.target.include.or.push(included);
var jsId = included.replace(':','\\:');
$("#jstree-"+jsId).addClass("included");
$scope.removeExclude(included);
$scope.updateTarget();
};
};
// Add the new target to exclude, remove it from included targets if it was
$scope.addExclude = function ( excluded ) {
var index = $scope.target.exclude.or.indexOf(excluded);
// Only add if the target is missing
if ( index == -1 ) {
$scope.target.exclude.or.push(excluded);
var jsId = excluded.replace(':','\\:');
$("#jstree-"+jsId).addClass("excluded");
$scope.removeInclude(excluded);
$scope.updateTarget();
};
};
// Toggle a target =>
// If it was not present => include that target
// If either from included or excluded => Exclude it
$scope.toggleTarget = function ( target ) {
var indexInclude = $scope.target.include.or.indexOf(target);
var indexExclude = $scope.target.exclude.or.indexOf(target);
if ( indexInclude == -1 ) {
if ( indexExclude == -1 ) {
// Not in targets => include
$scope.addInclude(target);
} else {
// In excluded targets => remove from excluded
$scope.removeExclude(target);
}
} else {
// In included targets => remove from included
$scope.removeInclude(target);
}
};
// Explanations to use in popups
$scope.includeExplanation = [ "<h3>Add Groups here to apply this Rule to the nodes they contain.</h3>"
, "Groups will be merged together (union)."
, "For example, if you add groups <b>'Datacenter 1'</b> and <b>'Production',</b>"
, "this Rule will be applied to all nodes that are either"
, "in that datacenter (production or not) or in production (in any datacenter)."
].join(" ");
$scope.excludeExplanation = [ "<h3>Add Groups here to forbid applying this Rule to the nodes they contain.</h3>"
, "Nodes in these Groups will never have this Rule applied,"
, "even if they are also in a Group applied above."
, "For example, if the above list contains groups '<b>Datacenter 1</b>' and '<b>Production</b>',"
, "and this list contains the group '<b>Red Hat Linux</b>',"
, "this Rule will be applied to all nodes that are running any OS except 'Red Hat Linux'"
, "and are either in that datacenter (production or not) or in production (in any datacenter)."
].join(" ");
} ] ) ;
// Add directive to create popup from angular, the directive should shared to future angular component
groupManagement.directive('tooltip', function () {
return {
restrict:'A'
, link: function(scope, element, attrs) {
var tooltipAttributes = {placement: "right"}
$(element).attr('title',scope.$eval(attrs.tooltip)).tooltip(tooltipAttributes);
}
}
} );
// Helper function to access from outside angular scope
function excludeTarget(event, target) {
event.stopPropagation();
var scope = angular.element($("#GroupCtrl")).scope();
scope.$apply(function() {
scope.addExclude(target);
});
};
function includeTarget(event, target) {
event.stopPropagation();
var scope = angular.element($("#GroupCtrl")).scope();
scope.$apply(function(){
scope.addInclude(target);
});
};
function onClickTarget(target) {
var scope = angular.element($("#GroupCtrl")).scope();
scope.$apply(function(){
scope.toggleTarget(target);
});
};
|
armeniaca/rudder
|
rudder-web/src/main/webapp/javascript/rudder/angular/groupManagement.js
|
JavaScript
|
gpl-3.0
| 7,529 |
<?php
require_once GTFWConfiguration::GetValue( 'application', 'docroot').
'module/asal_dana/business/asal_dana.class.php';
class ViewAsalDana extends HtmlResponse
{
function TemplateModule()
{
$this->SetTemplateBasedir(GTFWConfiguration::GetValue('application','docroot').
'module/asal_dana/'.GTFWConfiguration::GetValue('application', 'template_address').'');
$this->SetTemplateFile('view_asal_dana.html');
}
function ProcessRequest()
{
$publik = new AsalDana;
// inisialisasi messaging
$msg = Messenger::Instance()->Receive(__FILE__);//print_r($msg);
$this->Data = $msg[0][0];
$this->Pesan = $msg[0][1];
$this->css = $msg[0][2];
// ---------
$id = Dispatcher::Instance()->Decrypt($_GET['id']);
if(isset($_GET['id'])){
$result = $publik->GetDataById($id);
// print_r($result);
if($result){
$return['input']['kode'] = $result['kode'];
$return['input']['nama'] = $result['nama'];
}else{
unset($_GET['id']);
}
}else{
$return['input']['kode'] = '';
$return['input']['nama']='';
}
// inisialisasi data filter
if (isset($_POST['cari'])){
$return['cari'] = $_POST['cari']->Raw();
}elseif (isset($_GET['cari'])){
$return['cari'] = $_GET['cari']->Raw();
}else{
$return['cari'] = '';
}
//inisialisasi paging
$itemViewed = 20;
$currPage = 1;
$startRec = 0 ;
if(isset($_GET['page']))
{
$currPage = $_GET['page']->Integer()->Raw();
if ($currPage > 0)
$startRec =($currPage-1) * $itemViewed;
else $currPage = 1;
}
$return['start'] = $startRec+1;
$totalData = $publik->GetCount($return['cari']);
$url = Dispatcher::Instance()->GetUrl('asal_dana','asalDana','view','html').'&cari='.$return['cari'];
if (isset($_GET['id'])){
$url .= '&id='.$id;
}
Messenger::Instance()->SendToComponent('paging', 'Paging', 'view', 'html', 'paging_top', array($itemViewed,$totalData, $url, $currPage), Messenger::CurrentRequest);
$return['link']['url_action'] = Dispatcher::Instance()->GetUrl('asal_dana','inputAsalDana','do','html');
if (isset($_GET['id'])){
$return['link']['url_action'] .= '&id='.$id;
}
$return['link']['url_search'] = Dispatcher::Instance()->GetUrl('asal_dana','asalDana','view','html');
$return['link']['url_edit'] = Dispatcher::Instance()->GetUrl('asal_dana','asalDana','view','html');
if ($return['cari'] != ''){
$return['link']['url_edit'] .= '&cari='.$return['cari'];
}
if (isset($_GET['page'])){
$return['link']['url_edit'] .= '&page='.$_GET['page']->Integer()->Raw();
}
$lang=GTFWConfiguration::GetValue('application', 'button_lang');
if ($lang=='eng'){
$labeldel=Dispatcher::Instance()->Encrypt('Fund Source Reference');
}else{
$labeldel=Dispatcher::Instance()->Encrypt('Referensi Asal Dana');
}
$return['lang']=$lang;
$return['link']['url_delete'] = Dispatcher::Instance()->GetUrl('confirm', 'confirmDelete', 'do', 'html').
"&urlDelete=".Dispatcher::Instance()->Encrypt('asal_dana|deleteAsalDana|do|html').
"&urlReturn=".Dispatcher::Instance()->Encrypt('asal_dana|asalDana|view|html').
"&label=".$labeldel;
$return['link']['url_delete_js'] = Dispatcher::Instance()->GetUrl('asal_dana', 'deleteAsalDana', 'do', 'html');
$return['dataSheet'] = $publik->GetData($startRec,$itemViewed,$return['cari']);
return $return;
}
function ParseTemplate($data = NULL)
{
if($this->Pesan)
{
$this->mrTemplate->SetAttribute('warning_box', 'visibility', 'visible');
$this->mrTemplate->AddVar('warning_box', 'ISI_PESAN', $this->Pesan);
$this->mrTemplate->AddVar('warning_box', 'CLASS_PESAN', $this->css);
}
if ($data['lang']=='eng'){
$this->mrTemplate->AddVar('content', 'TITLE', 'FUND SOURCE REFERENCE');
$this->mrTemplate->AddVar('content', 'JUDUL_DATA', 'Fund Source Data');
$this->mrTemplate->AddVar('content', 'LABEL_ACTION', isset($_GET['id']) ? 'Update' : 'Add');
}else{
$this->mrTemplate->AddVar('content', 'TITLE', 'REFERENSI ASAL DANA');
$this->mrTemplate->AddVar('content', 'JUDUL_DATA', 'Data Asal Dana');
$this->mrTemplate->AddVar('content', 'LABEL_ACTION', isset($_GET['id']) ? 'Ubah' : 'Tambah');
}
$this->mrTemplate->AddVar('content', 'URL_ACTION', $data['link']['url_action']);
$this->mrTemplate->AddVar('content', 'NAMA', $data['input']['nama']);
$this->mrTemplate->AddVar('content', 'ID', $data['input']['kode']);
// Filter Form
$this->mrTemplate->AddVar('content', 'CARI', $data['cari']);
$this->mrTemplate->AddVar('content', 'URL_SEARCH', $data['link']['url_search']);
// ---------
if(empty($data['dataSheet'])){
$this->mrTemplate->AddVar('data', 'DATA_EMPTY', 'YES');
return NULL;
}else{
$this->mrTemplate->AddVar('data', 'DATA_EMPTY', 'NO');
}
$i = $data['start'];
$link = $data['link'];
foreach ($data['dataSheet'] as $value)
{
$data = $value;//print_r($data);
$data['number'] = $i;
$data['class_name'] = ($i % 2 == 0) ? '' : 'table-common-even';
$data['url_edit'] = $link['url_edit'].'&id='.$data['kode'];
$data['url_delete'] = $link['url_delete'].
"&id=".Dispatcher::Instance()->Encrypt($data['kode']).
"&dataName=".Dispatcher::Instance()->Encrypt($data['nama']);
$data['url_delete_js'] = $link['url_delete_js'];
$this->mrTemplate->AddVars('data_item', $data, '');
$this->mrTemplate->parseTemplate('data_item', 'a');
$i++;
}
}
}
?>
|
4n6g4/gtsdm
|
malra/bo/module/asal_dana/response/ViewAsalDana.html.class.php
|
PHP
|
gpl-3.0
| 6,049 |
/*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.core.circuits;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.WorldSavedData;
import forestry.api.circuits.ICircuitLibrary;
public class CircuitLibrary extends WorldSavedData implements ICircuitLibrary {
public CircuitLibrary(String par1Str) {
super(par1Str);
}
@Override
public void readFromNBT(NBTTagCompound var1) {
}
@Override
public void writeToNBT(NBTTagCompound var1) {
}
}
|
bdew/ForestryMC
|
src/main/java/forestry/core/circuits/CircuitLibrary.java
|
Java
|
gpl-3.0
| 1,016 |
#ifndef GEOMETRYINTERFACE_H
#define GEOMETRYINTERFACE_H
#include "cdtattributesinterface.h"
class GeometryInterface : public CDTAttributesInterface
{
Q_OBJECT
#if QT_VERSION >= 0x050000
Q_PLUGIN_METADATA(IID "cn.edu.WHU.CDTStudio.CDTAttributesInterface" FILE "Geometry.json")
#else
Q_INTERFACES(CDTAttributesInterface)
#endif // QT_VERSION >= 0x050000
public:
GeometryInterface(QObject *parent = 0);
~GeometryInterface();
QString attributesType() const;
QString tableName() const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal area(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal border_length(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal elongation(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal asymmetry(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal border_index(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal compactness(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal x_center(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal x_max(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal x_min(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal y_center(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal y_max(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal y_min(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal rectangular_fit(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal elliptic_fit(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal radius_of_largest_enclosed_ellipse(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal radius_of_smallest_enclosing_ellipse(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal shape_index(const AttributeParamsMultiBand ¶m) const;
Q_INVOKABLE CDT_ATTRIBUTE_ALL_BAND qreal roundness(const AttributeParamsMultiBand ¶m) const;
};
#endif // GEOMETRYINTERFACE_H
|
chenguanzhou/CDTStudio
|
Plugins/Attributes/Geometry/geometryinterface.h
|
C
|
gpl-3.0
| 2,418 |
/**
* @author Aleksey Terzi
*
*/
package com.lishid.orebfuscator.nms;
import com.lishid.orebfuscator.types.ConfigDefaults;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.lishid.orebfuscator.types.BlockCoord;
import java.util.Set;
public interface INmsManager {
ConfigDefaults getConfigDefaults();
Material[] getExtraTransparentBlocks();
void setMaxLoadedCacheFiles(int value);
INBT createNBT();
IChunkCache createChunkCache();
void updateBlockTileEntity(BlockCoord blockCoord, Player player);
void notifyBlockChange(World world, IBlockInfo blockInfo);
int getBlockLightLevel(World world, int x, int y, int z);
IBlockInfo getBlockInfo(World world, int x, int y, int z);
int loadChunkAndGetBlockId(World world, int x, int y, int z);
String getTextFromChatComponent(String json);
boolean isHoe(Material item);
boolean isSign(int combinedBlockId);
boolean isAir(int combinedBlockId);
boolean isTileEntity(int combinedBlockId);
int getCaveAirBlockId();
int getBitsPerBlock();
boolean canApplyPhysics(Material blockMaterial);
Set<Integer> getMaterialIds(Material material);
boolean sendBlockChange(Player player, Location blockLocation);
}
|
DevotedMC/Orebfuscator
|
API/src/main/java/com/lishid/orebfuscator/nms/INmsManager.java
|
Java
|
gpl-3.0
| 1,291 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
#if JUCE_DEBUG
struct DanglingStreamChecker
{
DanglingStreamChecker() {}
~DanglingStreamChecker()
{
/*
It's always a bad idea to leak any object, but if you're leaking output
streams, then there's a good chance that you're failing to flush a file
to disk properly, which could result in corrupted data and other similar
nastiness..
*/
jassert (activeStreams.size() == 0);
}
Array<void*, CriticalSection> activeStreams;
};
static DanglingStreamChecker danglingStreamChecker;
#endif
//==============================================================================
OutputStream::OutputStream()
: newLineString (NewLine::getDefault())
{
#if JUCE_DEBUG
danglingStreamChecker.activeStreams.add (this);
#endif
}
OutputStream::~OutputStream()
{
#if JUCE_DEBUG
danglingStreamChecker.activeStreams.removeFirstMatchingValue (this);
#endif
}
//==============================================================================
bool OutputStream::writeBool (bool b)
{
return writeByte (b ? (char) 1
: (char) 0);
}
bool OutputStream::writeByte (char byte)
{
return write (&byte, 1);
}
bool OutputStream::writeRepeatedByte (uint8 byte, size_t numTimesToRepeat)
{
for (size_t i = 0; i < numTimesToRepeat; ++i)
if (! writeByte ((char) byte))
return false;
return true;
}
bool OutputStream::writeShort (short value)
{
auto v = ByteOrder::swapIfBigEndian ((uint16) value);
return write (&v, 2);
}
bool OutputStream::writeShortBigEndian (short value)
{
auto v = ByteOrder::swapIfLittleEndian ((uint16) value);
return write (&v, 2);
}
bool OutputStream::writeInt (int value)
{
auto v = ByteOrder::swapIfBigEndian ((uint32) value);
return write (&v, 4);
}
bool OutputStream::writeIntBigEndian (int value)
{
auto v = ByteOrder::swapIfLittleEndian ((uint32) value);
return write (&v, 4);
}
bool OutputStream::writeCompressedInt (int value)
{
auto un = (value < 0) ? (unsigned int) -value
: (unsigned int) value;
uint8 data[5];
int num = 0;
while (un > 0)
{
data[++num] = (uint8) un;
un >>= 8;
}
data[0] = (uint8) num;
if (value < 0)
data[0] |= 0x80;
return write (data, (size_t) num + 1);
}
bool OutputStream::writeInt64 (int64 value)
{
auto v = ByteOrder::swapIfBigEndian ((uint64) value);
return write (&v, 8);
}
bool OutputStream::writeInt64BigEndian (int64 value)
{
auto v = ByteOrder::swapIfLittleEndian ((uint64) value);
return write (&v, 8);
}
bool OutputStream::writeFloat (float value)
{
union { int asInt; float asFloat; } n;
n.asFloat = value;
return writeInt (n.asInt);
}
bool OutputStream::writeFloatBigEndian (float value)
{
union { int asInt; float asFloat; } n;
n.asFloat = value;
return writeIntBigEndian (n.asInt);
}
bool OutputStream::writeDouble (double value)
{
union { int64 asInt; double asDouble; } n;
n.asDouble = value;
return writeInt64 (n.asInt);
}
bool OutputStream::writeDoubleBigEndian (double value)
{
union { int64 asInt; double asDouble; } n;
n.asDouble = value;
return writeInt64BigEndian (n.asInt);
}
bool OutputStream::writeString (const String& text)
{
auto numBytes = text.getNumBytesAsUTF8() + 1;
#if (JUCE_STRING_UTF_TYPE == 8)
return write (text.toRawUTF8(), numBytes);
#else
// (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
// if lots of large, persistent strings were to be written to streams).
HeapBlock<char> temp (numBytes);
text.copyToUTF8 (temp, numBytes);
return write (temp, numBytes);
#endif
}
bool OutputStream::writeText (const String& text, bool asUTF16, bool writeUTF16ByteOrderMark, const char* lf)
{
bool replaceLineFeedWithUnix = lf != nullptr && lf[0] == '\n' && lf[1] == 0;
bool replaceLineFeedWithWindows = lf != nullptr && lf[0] == '\r' && lf[1] == '\n' && lf[2] == 0;
// The line-feed passed in must be either nullptr, or "\n" or "\r\n"
jassert (lf == nullptr || replaceLineFeedWithWindows || replaceLineFeedWithUnix);
if (asUTF16)
{
if (writeUTF16ByteOrderMark)
write ("\x0ff\x0fe", 2);
auto src = text.getCharPointer();
bool lastCharWasReturn = false;
for (;;)
{
auto c = src.getAndAdvance();
if (c == 0)
break;
if (replaceLineFeedWithWindows)
{
if (c == '\n' && ! lastCharWasReturn)
writeShort ((short) '\r');
lastCharWasReturn = (c == L'\r');
}
else if (replaceLineFeedWithUnix && c == '\r')
{
continue;
}
if (! writeShort ((short) c))
return false;
}
}
else
{
const char* src = text.toRawUTF8();
if (replaceLineFeedWithWindows)
{
for (auto t = src;;)
{
if (*t == '\n')
{
if (t > src)
if (! write (src, (size_t) (t - src)))
return false;
if (! write ("\r\n", 2))
return false;
src = t + 1;
}
else if (*t == '\r')
{
if (t[1] == '\n')
++t;
}
else if (*t == 0)
{
if (t > src)
if (! write (src, (size_t) (t - src)))
return false;
break;
}
++t;
}
}
else if (replaceLineFeedWithUnix)
{
for (;;)
{
auto c = *src++;
if (c == 0)
break;
if (c != '\r')
if (! writeByte (c))
return false;
}
}
else
{
return write (src, text.getNumBytesAsUTF8());
}
}
return true;
}
int64 OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
{
if (numBytesToWrite < 0)
numBytesToWrite = std::numeric_limits<int64>::max();
int64 numWritten = 0;
while (numBytesToWrite > 0)
{
char buffer[8192];
auto num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
if (num <= 0)
break;
write (buffer, (size_t) num);
numBytesToWrite -= num;
numWritten += num;
}
return numWritten;
}
//==============================================================================
void OutputStream::setNewLineString (const String& newLineStringToUse)
{
newLineString = newLineStringToUse;
}
//==============================================================================
template <typename IntegerType>
static void writeIntToStream (OutputStream& stream, IntegerType number)
{
char buffer[NumberToStringConverters::charsNeededForInt];
char* end = buffer + numElementsInArray (buffer);
const char* start = NumberToStringConverters::numberToString (end, number);
stream.write (start, (size_t) (end - start - 1));
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
{
writeIntToStream (stream, number);
return stream;
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int64 number)
{
writeIntToStream (stream, number);
return stream;
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
{
return stream << String (number);
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
{
stream.writeByte (character);
return stream;
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
{
stream.write (text, strlen (text));
return stream;
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
{
if (data.getSize() > 0)
stream.write (data.getData(), data.getSize());
return stream;
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
{
FileInputStream in (fileToRead);
if (in.openedOk())
return stream << in;
return stream;
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, InputStream& streamToRead)
{
stream.writeFromInputStream (streamToRead, -1);
return stream;
}
JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
{
return stream << stream.getNewLineString();
}
} // namespace juce
|
COx2/JUCE_JAPAN_DEMO
|
2018/JUCE/modules/juce_core/streams/juce_OutputStream.cpp
|
C++
|
gpl-3.0
| 9,865 |
//# -*- mode: c++ -*-
//#
//# BWRead.h: Read beamformer weights to the RSP hardware.
//#
//# Copyright (C) 2002-2004
//# ASTRON (Netherlands Foundation for Research in Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands, [email protected]
//#
//# This program is free software; you can redistribute it and/or modify
//# it under the terms of the GNU General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or
//# (at your option) any later version.
//#
//# This program is distributed in the hope that it will be useful,
//# but WITHOUT ANY WARRANTY; without even the implied warranty of
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//# GNU General Public License for more details.
//#
//# You should have received a copy of the GNU General Public License
//# along with this program; if not, write to the Free Software
//# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//#
//# $Id$
#ifndef BWREAD_H_
#define BWREAD_H_
#include <Common/LofarTypes.h>
#include <APL/RSP_Protocol/MEPHeader.h>
#include "SyncAction.h"
namespace LOFAR {
namespace RSP {
class BWRead : public SyncAction
{
public:
/**
* Constructors for a BWRead object.
*/
BWRead(GCFPortInterface& board_port, int board_id, int blp, int regid);
/* Destructor for BWRead. */
virtual ~BWRead();
/**
* Send the read message.
*/
virtual void sendrequest();
/**
* Send the read request.
*/
virtual void sendrequest_status();
/**
* Handle the read result.
*/
virtual GCFEvent::TResult handleack(GCFEvent& event, GCFPortInterface& port);
private:
int m_blp;
int m_regid;
int itsBank;
size_t m_remaining; // how much to read
size_t m_offset; // where to read
EPA_Protocol::MEPHeader m_hdr;
};
};
};
#endif /* BWSYNC_H_ */
|
kernsuite-debian/lofar
|
MAC/APL/PIC/RSP_Driver/src/BWRead.h
|
C
|
gpl-3.0
| 2,007 |
/*
This file is part of LilyPond, the GNU music typesetter.
Copyright (C) 1997--2015 Jan Nieuwenhuizen <[email protected]>
LilyPond 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.
LilyPond 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 LilyPond. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstring>
using namespace std;
#include "warn.hh"
#include "font-interface.hh"
#include "line-interface.hh"
#include "paper-column.hh"
#include "output-def.hh"
#include "text-interface.hh"
#include "volta-bracket.hh"
#include "pointer-group-interface.hh"
#include "side-position-interface.hh"
#include "directional-element-interface.hh"
#include "lookup.hh"
#include "bracket.hh"
#include "lily-imports.hh"
/*
this is too complicated. Yet another version of side-positioning,
badly implemented.
--
* Should look for system_start_delim to find left edge of staff.
*/
MAKE_SCHEME_CALLBACK (Volta_bracket_interface, print, 1);
SCM
Volta_bracket_interface::print (SCM smob)
{
Spanner *me = unsmob<Spanner> (smob);
Spanner *orig_span = dynamic_cast<Spanner *> (me->original ());
bool broken_first_bracket = orig_span && (orig_span->broken_intos_[0]
== (Spanner *)me);
Output_def *layout = me->layout ();
Item *bound = dynamic_cast<Spanner *> (me)->get_bound (LEFT);
/*
If the volta bracket appears after a line-break, make
it start after the prefatory matter.
*/
Real left = 0.;
if (bound->break_status_dir () == RIGHT)
{
Paper_column *pc = bound->get_column ();
left = pc->break_align_width (pc, ly_symbol2scm ("break-alignment"))[RIGHT]
// For some reason, break_align_width is relative to
// the x-parent of the column.
- bound->relative_coordinate (pc->get_parent (X_AXIS), X_AXIS);
}
else
{
/*
the volta spanner is attached to the bar-line, which is moved
to the right. We don't need to compensate for the left edge.
*/
}
modify_edge_height (me);
if (!me->is_live ())
return SCM_EOL;
Drul_array<Real> edge_height = robust_scm2interval (me->get_property ("edge-height"),
Interval (1.0, 1.0));
Drul_array<Real> flare = robust_scm2interval (me->get_property ("bracket-flare"),
Interval (0, 0));
Drul_array<Real> shorten = robust_scm2interval (me->get_property ("shorten-pair"),
Interval (0, 0));
scale_drul (&edge_height, - Real (get_grob_direction (me)));
Interval empty;
Offset start;
start[X_AXIS] = me->spanner_length () - left;
Stencil total
= Bracket::make_bracket (me, Y_AXIS, start, edge_height, empty,
flare, shorten);
if (!orig_span || broken_first_bracket)
{
SCM text = me->get_property ("text");
SCM properties = me->get_property_alist_chain (SCM_EOL);
SCM snum = Text_interface::interpret_markup (layout->self_scm (),
properties, text);
Stencil num = *unsmob<Stencil> (snum);
num.align_to (Y_AXIS, UP);
num.translate_axis (-0.5, Y_AXIS);
total.add_at_edge (X_AXIS, LEFT, num, - num.extent (X_AXIS).length ()
- 1.0);
}
total.translate_axis (left, X_AXIS);
return total.smobbed_copy ();
}
void
Volta_bracket_interface::modify_edge_height (Spanner *me)
{
Spanner *orig_span = dynamic_cast<Spanner *> (me->original ());
bool broken_first_bracket = orig_span && (orig_span->broken_intos_[0] == (Spanner *)me);
bool broken_last_bracket = orig_span && (orig_span->broken_intos_.back () == (Spanner *)me);
bool no_vertical_start = orig_span && !broken_first_bracket;
bool no_vertical_end = orig_span && !broken_last_bracket;
extract_grob_set (me, "bars", bars);
Grob *endbar = bars.size () ? bars.back () : 0;
SCM glyph = endbar ? endbar->get_property ("glyph-name") : SCM_EOL;
string str;
if (scm_is_string (glyph))
str = ly_scm2string (glyph);
else
str = "|";
no_vertical_end |= ly_scm2bool (Lily::volta_bracket_calc_hook_visibility
(ly_string2scm (str)));
if (no_vertical_end || no_vertical_start)
{
Drul_array<Real> edge_height = robust_scm2interval (me->get_property ("edge-height"),
Interval (1.0, 1.0));
if (no_vertical_start)
edge_height[LEFT] = 0.0;
if (no_vertical_end)
edge_height[RIGHT] = 0.0;
me->set_property ("edge-height", ly_interval2scm (edge_height));
}
if (broken_last_bracket && no_vertical_end && no_vertical_start
&& !broken_first_bracket)
me->suicide ();
}
void
Volta_bracket_interface::add_bar (Grob *me, Item *b)
{
Pointer_group_interface::add_grob (me, ly_symbol2scm ("bars"), b);
add_bound_item (dynamic_cast<Spanner *> (me), b);
}
ADD_INTERFACE (Volta_bracket_interface,
"Volta bracket with number.",
/* properties */
"bars "
"thickness "
"height "
"shorten-pair "
);
|
thSoft/lilypond-hu
|
lily/volta-bracket.cc
|
C++
|
gpl-3.0
| 5,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.