code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*---------------------------------------------------------------------------*\
libmyDynamicMesh Copyright (C) 2014 Christian Butcher
chrisb2244@gmail.com
License
This file is part of a library, libmyDynamicMesh, using and derived
from OpenFOAM.
OpenFOAM 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.
OpenFOAM 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.
This work is distributed under the same licensing conditions.
You should have received a copy of the GNU General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "sortFaces.H" // Header file for class
//~ #include <vector> // Needed for vector of functors
#include "fvCFD.H" // Completes types for patchFields
namespace Foam
{
defineTypeNameAndDebug(sortFaces, 0);
}
Foam::sortFaces::sortFaces(DynamicList<Pair<label> >& sourceList)
:
values_(sourceList)
{
}
Foam::sortFaces::~sortFaces()
{}
void Foam::sortFaces::printInfo()
{
Pout<< values_;
}
label Foam::sortFaces::partition(
const label& left, const label& right, const label& pivotIndex)
{
label pivotValue = values_[pivotIndex].first();
swap(values_[pivotIndex], values_[right]);
label storeIndex = left;
for (int i = left; i < right; i++)
{
if (values_[i].first() <= pivotValue)
{
swap(values_[i], values_[storeIndex]);
storeIndex ++;
}
}
swap(values_[storeIndex], values_[right]);
return storeIndex;
}
void Foam::sortFaces::quicksort(const label& left, const label& right)
{
if (left < right)
{
label pivotIndex = (left+right)/2;
label pivotNewIndex = partition(left, right, pivotIndex);
quicksort(left, pivotNewIndex - 1);
quicksort(pivotNewIndex + 1, right);
}
}
void Foam::sortFaces::swap(Pair<label> &a, Pair<label> &b)
{
Pair<label> temp = a;
a = b;
b = temp;
}
void Foam::sortFaces::sort()
{
quicksort(0, values_.size());
}
bool Foam::sortFaces::bCondense()
{
bool changed = false;
DynamicList<Pair<label> > originalList(Cvalues_);
if (originalList.size() == 0)
{
Pout<< "No list" << endl;
}
Cvalues_.clear();
if (Cvalues_.size() != 0)
{
Pout<< "Didn't clear" << endl;
}
for(int i = 0; i < (originalList.size()-1); i++)
{
if (originalList[i+1].first() == originalList[i].first())
{
originalList[i].second() =
(originalList[i].second() + originalList[i+1].second());
Cvalues_.append(originalList[i]);
i++;
changed = true;
continue;
}
Cvalues_.append(originalList[i]);
}
if (!changed)
{
//~ forAll(originalList, i)
//~ Cvalues_.append(originalList[i]);
Cvalues_=originalList;
}
return changed;
}
DynamicList<Pair<label> > Foam::sortFaces::condense()
{
bool again = true;
Cvalues_ = values_;
while (again)
{
again = bCondense();
}
return Cvalues_;
}
| chrisb2244/2D-AMR-OFlib | sortFaces/sortFaces.C | C++ | gpl-3.0 | 3,269 |
/* GASdotto
* Copyright (C) 2009/2013 Roberto -MadBob- Guido <bob4job@gmail.com>
*
* This 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 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.barberaware.client;
import java.util.*;
import com.google.gwt.user.client.ui.*;
public class GAS extends FromServer {
public GAS () {
super ();
addAttribute ( "name", FromServer.STRING );
addAttribute ( "is_master", FromServer.BOOLEAN );
addAttribute ( "mail", FromServer.STRING );
addAttribute ( "image", FromServer.STRING );
addAttribute ( "description", FromServer.LONGSTRING );
addAttribute ( "use_mail", FromServer.BOOLEAN );
addAttribute ( "mail_conf", FromServer.STRING );
addAttribute ( "mailinglist", FromServer.STRING );
addAttribute ( "payments", FromServer.BOOLEAN );
addAttribute ( "payment_date", FromServer.DATE );
addAttribute ( "default_fee", FromServer.FLOAT );
addAttribute ( "default_deposit", FromServer.FLOAT );
addAttribute ( "use_rid", FromServer.BOOLEAN );
addAttribute ( "rid_conf", FromServer.STRING );
addAttribute ( "use_shipping", FromServer.BOOLEAN );
addAttribute ( "use_fullusers", FromServer.BOOLEAN );
addAttribute ( "use_bank", FromServer.BOOLEAN );
addAttribute ( "current_balance", FromServer.FLOAT );
addAttribute ( "current_bank_balance", FromServer.FLOAT );
addAttribute ( "current_cash_balance", FromServer.FLOAT );
addAttribute ( "current_orders_balance", FromServer.FLOAT );
addAttribute ( "current_deposit_balance", FromServer.FLOAT );
addAttribute ( "last_balance_date", FromServer.DATE );
addAttribute ( "last_balance", FromServer.FLOAT );
addAttribute ( "last_bank_balance", FromServer.FLOAT );
addAttribute ( "last_cash_balance", FromServer.FLOAT );
addAttribute ( "last_orders_balance", FromServer.FLOAT );
addAttribute ( "last_deposit_balance", FromServer.FLOAT );
addAttribute ( "files", FromServer.ARRAY, CustomFile.class );
addAttribute ( "emergency_access", FromServer.BOOLEAN );
setString ( "name", "Senza Nome" );
}
}
| madbob/GASdotto | src/org/barberaware/client/GAS.java | Java | gpl-3.0 | 2,588 |
<?php
namespace Sydne\Pages
{
use Enum;
use WebFramework\HorizontalAlignment;
use WebFramework\VerticalAlignment;
use WebFramework\Controls\ButtonGroupButton;
use WebFramework\Controls\ListView;
use WebFramework\Controls\ListViewColumn;
use WebFramework\Controls\ListViewItem;
use WebFramework\Controls\ListViewItemColumn;
use WebFramework\Controls\Window;
use Sydne\Objects\Company;
use Sydne\Objects\Product;
Enum::Create("Sydne\\Pages\\ProductDetailPageMode", "Create", "Modify", "Detail");
class ProductListPage extends SydnePage
{
protected function Initialize()
{
parent::Initialize();
$this->ToolbarLeftItems[] = new ButtonGroupButton("btnCreateProduct", "Add Product", null, null, "~/Products/Create");
$this->ToolbarLeftItems[] = new ButtonGroupButton("btnSearch", "Scan Barcode", null, "~/Images/Buttons/BarcodeSearch.png", "~/Products/Search", "wndSearch.Show(); return false;");
$this->ReturnButtonText = "Configuration";
$this->ReturnButtonURL = "~/Configuration";
}
protected function RenderContent()
{
$company = Company::GetCurrent();
$products = $company->GetProducts();
$wndSearch = new Window("wndSearch");
$wndSearch->Title = "Scan Barcode";
$wndSearch->Visible = false;
$wndSearch->BeginContent();
?>
<form method="POST" action="<?php echo(\System::ExpandRelativePath("~/Products/Search/Barcode")); ?>">
<table style="width: 400px;">
<tr>
<td>Barcode:</td>
<td><input type="text" name="BarcodeValue" id="txtBarcode" style="width: 100%;" /></td>
</tr>
<tr>
<td colspan="2" style="text-align: right;">
<a class="Button" href="#" onclick="wndSearch.Hide(); return false;">Close</a>
</td>
</tr>
</table>
</form>
<?php
$wndSearch->EndContent();
?>
<script type="text/javascript">
wndSearch.Opened.Add(function()
{
wndSearch.SetHorizontalAlignment(HorizontalAlignment.Center);
wndSearch.SetTop(200);
var txtBarcode = document.getElementById("txtBarcode");
txtBarcode.focus();
});
</script>
<?php
$lv = new ListView("lvProducts");
$lv->Width = "100%";
$lv->Columns[] = new ListViewColumn("chTitle", "Title");
$lv->Columns[] = new ListViewColumn("chUnitPrice", "Unit Price");
$lv->Columns[] = new ListViewColumn("chQuantityInStock", "Quantity in Stock");
foreach ($products as $product)
{
$lvi = new ListViewItem();
$lvi->Columns[] = new ListViewItemColumn("chTitle", $product->Title);
$lvi->Columns[] = new ListViewItemColumn("chUnitPrice", $product->UnitPrice);
$lvi->Columns[] = new ListViewItemColumn("chQuantityInStock", $product->QuantityInStock);
$lvi->NavigateURL = "~/Products/Modify/" . $product->ID;
$lv->Items[] = $lvi;
}
$lv->Render();
}
}
class ProductDetailPage extends SydnePage
{
public $Product;
public $Mode;
public function __construct()
{
parent::__construct();
$this->Mode = ProductDetailPageMode::Detail;
}
protected function Initialize()
{
parent::Initialize();
if ($this->Mode == ProductDetailPageMode::Modify)
{
$this->ToolbarLeftItems[] = new ButtonGroupButton("btnDelete", "Delete", null, "~/Images/Buttons/Delete.png", "~/Products/Delete/" . $this->Product->ID);
}
$this->ToolbarLeftItems[] = new ButtonGroupButton("btnSaveChanges", "Save Changes", null, "~/Images/Buttons/Accept.png", null, "document.getElementById('frmMain').submit();");
$this->ToolbarLeftItems[] = new ButtonGroupButton("btnDiscardChanges", "Cancel", null, "~/Images/Buttons/Cancel.png", "~/Products");
}
protected function RenderContent()
{
$wndProductDetails = new Window("wndProductDetails", "Product Details");
$wndProductDetails->HorizontalAlignment = HorizontalAlignment::Center;
$wndProductDetails->VerticalAlignment = VerticalAlignment::Middle;
$wndProductDetails->BeginContent();
?>
<form id="frmMain" method="POST">
<table style="width: 100%;">
<tr>
<td><label for="txtProductTitle">Product <u>t</u>itle:</label></td>
<td><input type="text" name="Title" id="txtProductTitle" accesskey="t" value="<?php if ($this->Product != null) echo ($this->Product->Title); ?>" /></td>
</tr>
<tr>
<td><label for="txtUnitPrice">Unit <u>p</u>rice:</label></td>
<td><input type="number" name="UnitPrice" id="txtUnitPrice" accesskey="p" value="<?php if ($this->Product != null) echo ($this->Product->UnitPrice); ?>" /></td>
</tr>
<tr>
<td><label for="txtQuantityInStock"><u>Q</u>uantity in Stock:</label></td>
<td><input type="number" name="QuantityInStock" id="txtQuantityInStock" accesskey="Q" value="<?php if ($this->Product != null) echo ($this->Product->QuantityInStock); ?>" /></td>
</tr>
<tr>
<td><label for="txtBarcode"><u>B</u>arcode:</label></td>
<td><input type="text" name="Barcode" id="txtBarcode" accesskey="B" value="<?php if ($this->Product != null) echo ($this->Product->Barcode); ?>" /></td>
</tr>
</table>
</form>
<?php
$wndProductDetails->EndContent();
}
}
\System::$VirtualPaths[] = new \VirtualPath("Products", function($path)
{
if ($path[0] == "")
{
$page = new ProductListPage();
$page->Render();
return true;
}
else if ($path[0] == "Create")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$product = new Product();
$product->Title = $_POST["Title"];
$product->UnitPrice = $_POST["UnitPrice"];
$product->QuantityInStock = $_POST["QuantityInStock"];
$product->Barcode = $_POST["Barcode"];
if ($product->Update())
{
\System::Redirect("~/Products");
}
else
{
global $MySQL;
$page = new ErrorPage();
$page->Message = "The data was not saved properly: " . $MySQL->error . " (" . $MySQL->errno . ")";
$page->Render();
}
}
else
{
$page = new ProductDetailPage();
$page->Mode = ProductDetailPageMode::Create;
$page->Product = new Product();
$page->Render();
}
return true;
}
else if ($path[0] == "Detail")
{
if (is_numeric($path[1]))
{
$product = Product::GetByID($path[1]);
if ($product != null)
{
$page = new ProductDetailPage();
$page->Mode = ProductDetailPageMode::Detail;
$page->Product = $product;
$page->Render();
}
else
{
$page = new ErrorPage();
$page->Message = "The product you specified does not exist";
$page->Render();
}
}
else
{
$page = new ErrorPage();
$page->Message = "Please select a product to edit from the list";
$page->Render();
}
return true;
}
else if ($path[0] == "Modify")
{
if (is_numeric($path[1]))
{
$product = Product::GetByID($path[1]);
if ($product != null)
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$product->Title = $_POST["Title"];
$product->UnitPrice = $_POST["UnitPrice"];
$product->QuantityInStock = $_POST["QuantityInStock"];
$product->Barcode = $_POST["Barcode"];
if ($product->Update())
{
\System::Redirect("~/Products");
}
else
{
$page = new ErrorPage();
$page->Message = "The data was not saved properly";
$page->Render();
}
}
else
{
$page = new ProductDetailPage();
$page->Mode = ProductDetailPageMode::Modify;
$page->Product = $product;
$page->Render();
}
}
else
{
$page = new ErrorPage();
$page->Message = "The product you specified does not exist";
$page->Render();
}
}
else
{
$page = new ErrorPage();
$page->Message = "Please select a product to edit from the list";
$page->Render();
}
return true;
}
else if ($path[0] == "Search")
{
if ($path[1] == "Barcode" && $path[2] == "")
{
if ($_POST["BarcodeValue"] != null)
{
$BarcodeValue = $_POST["BarcodeValue"];
$CC4 = new \CueCatDecoder4();
$BarcodeInfo = $CC4->TryParse($BarcodeValue);
if ($BarcodeInfo !== false)
{
$BarcodeValue = $BarcodeInfo->Value;
}
\System::Redirect("~/Products/Search/Barcode/" . $_POST["BarcodeValue"]);
}
else
{
}
}
else if ($path[1] == "Barcode" && $path[2] != "")
{
$product = Product::GetByBarcode($path[2]);
if ($product == null)
{
$page = new ErrorPage();
$page->Message = "The product with barcode '" . $path[2] . "' does not exist.";
$page->Render();
}
else
{
\System::Redirect("~/Products/Detail/" . $product->ID);
}
}
else
{
}
return true;
}
return false;
});
}
?> | alcexhim/Sydne | PrivateWebsite/Include/Modules/000-Common/Pages/ProductPage.inc.php | PHP | gpl-3.0 | 8,937 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* the Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Justin Dolske <dolske@mozilla.com> (original author)
* David Dahl <ddahl@mozilla.com>
* Sergio Ruiz <invi@pidgeonpg.org> [1]
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* NOTES:
*
* The WeaveCrypto object in this file was originally pulled from hg.mozilla.org
*
* http://hg.mozilla.org/mozilla-central/ \
* raw-file/d0c40fc38702/services/crypto/modules/WeaveCrypto.js
*
* WeaveCrypto's API as it was released in Firefox 4 was reduced in scope due
* to Sync's move to J-Pake, hence the need for this more complete version.
*
* This version has the additional APIs 'sign' and 'verify' and has been
* edited for use in a ChromeWorker.
*
* [1] This version has been modified for direct public and private key import
* in DER format to support sign, verify, encrypt and decrypt in
* such case. Also DSA and ElGamal key generation has been added.
*
*/
var DEBUG = false;
const PUB_ALGO = {
RSA: 1,
RSA_E: 2,
RSA_S: 3,
ELGAMAL_E: 16,
DSA: 17,
ECDH: 18,
ECDSA: 19,
ELGAMAL: 20
}
function log(aMessage) {
if (!DEBUG){
return;
}
var _msg = "domcrypt_worker: " + " " + aMessage + "\n";
dump(_msg);
}
const GENERATE_KEYPAIR = "generateKeypair";
const GENERATE_RANDOM = "generateRandom";
const ENCRYPT = "encrypt";
const DECRYPT = "decrypt";
const SIGN = "sign";
const VERIFY = "verify";
const GENERATE_SYM_KEY = "generateSymKey";
const SYM_ENCRYPT = "symEncrypt";
const SYM_DECRYPT = "symDecrypt";
const WRAP_SYM_KEY = "wrapSymKey";
const VERIFY_PASSPHRASE = "verifyPassphrase";
const SHUTDOWN = "shutdown";
const INITIALIZE = "init";
onmessage = function(aEvent) {
var data = JSON.parse(aEvent.data);
switch(data.action) {
case INITIALIZE:
WeaveCrypto.initNSS(data.nssPath);
DEBUG = data.debug || false;
break;
case GENERATE_KEYPAIR:
result = WeaveCryptoWrapper.generateKeypair(data.keyType, data.keypairBits);
postMessage(JSON.stringify({ keypairData: result, action: "keypairGenerated" }));
break;
case GENERATE_RANDOM:
result = WeaveCryptoWrapper.generateRandom(data.aLength);
postMessage(JSON.stringify({ randomBytes: result, action: "randomGenerated" }));
break;
case ENCRYPT:
result = WeaveCryptoWrapper.encrypt(data.plainText, data.pubKey);
postMessage(JSON.stringify({ cipherMessage: result, action: "dataEncrypted" }));
break;
case DECRYPT:
result = WeaveCryptoWrapper.decrypt(data.aCipherMessage,
data.derSecKey);
postMessage(JSON.stringify({ plainText: result, action: "dataDecrypted" }));
break;
case SIGN:
result = WeaveCryptoWrapper.sign(data.hash,
data.derSecKey,
data.derPubKey);
postMessage(JSON.stringify({ signature: result, action: "messageSigned" }));
break;
case VERIFY:
result = WeaveCryptoWrapper.verify(data.hash,
data.signature,
data.pubKey);
postMessage(JSON.stringify({ verification: result, action: "messageVerified" }));
break;
case SHUTDOWN:
WeaveCrypto.shutdown();
default:
break;
}
}
/**
* WeaveCryptoWrapper
*
* Wrap the WeaveCrypto API in a more elegant way. This is very similar to the
* original DOMCrypt extension code
*
*/
var WeaveCryptoWrapper = {
/**
* generateKeypair
*
* Create a KeyPair for general purpose
*
* @param int Type of Key algorithm
* int Key length in bits
* @returns object
* The object returned looks like:
* { action: "keypairGenerated",
* privKey: <PRIVATE KEY>,
* created: <DATE CREATED>
* }
*/
generateKeypair: function WCW_generateKeypair(keyType, keypairBits)
{
var privOut = {};
try {
WeaveCrypto.generateKeypair(keyType, keypairBits, privOut);
let results = { action: "keypairGenerated",
privKey: privOut,
created: Date.now()
};
return results;
}
catch (ex) {
log(ex);
log(ex.stack);
throw(ex);
}
},
/**
* generateRandom
*
* Create a random bytes
*
* @param int Numbes of random bytes to create
* @returns object
* The object returned looks like:
* { action: "randomGenerated",
* randomBytes: <STRING OF RANDOM BYTES>
* }
*/
generateRandom: function WCW_generateRandom(nbytes)
{
try {
var randomBytes = WeaveCrypto.generateRandomBytes(nbytes);
let results = { action: "randomGenerated",
randomBytes: randomBytes
};
return results;
}
catch (ex) {
log(ex);
log(ex.stack);
throw(ex);
}
},
/**
* encrypt
*
* Encrypt data with a public key
*
* @param string aSessionkey
* The base64 session key data that will be encrypted
* @param string aPublicKey
* The recipient's DER base64 encoded public key
* @returns Object
* A 'message' object:
* { content: <ENCRYPTED_STRING>,
* pubKey: <RECIPIENT PUB_KEY>,
* wrappedKey: <WRAPPED SYM_KEY>,
* iv: <INITIALIZATION VECTOR>
* }
*/
encrypt: function WCW_encrypt(aSessionkey, aPublicKey)
{
if (!aSessionkey && !aPublicKey) {
throw new Error("Missing Arguments: aSessionkey and aPublicKey are required");
}
try {
var encryptedSessionkey = WeaveCrypto.encrypt(aSessionkey, aPublicKey);
return encryptedSessionkey;
}
catch (ex) {
log(ex);
log(ex.stack);
throw ex;
}
},
/**
* decrypt
*
* Decrypt encrypted data with a private key
*
* @param string aSessionkey
* The base64 encrypted session key
* @param string aPrivateKey
* The base64 encoded private key string
* @returns string
* The decrypted message in base64
*/
decrypt: function WCW_decrypt(aSessionkey, aPrivateKey)
{
try {
var decrypted = WeaveCrypto.decrypt(aSessionkey, aPrivateKey);
return decrypted;
}
catch (ex) {
log(ex);
log(ex.stack);
throw(ex);
}
},
/**
* Cryptographically sign a message
*
* @param string aHash
* A base64 signature data hash of the message
* @param string aPrivateKey
* The sender's base64 DER encoded private key
* @param string aPublicKey
* The sender's base64 DER encoded public key
*/
sign: function WCW_sign(aHash, aPrivateKey, aPublicKey)
{
var signature;
try {
signature = WeaveCrypto.sign(aPrivateKey, aPublicKey, aHash);
return signature;
}
catch (ex) {
log(ex);
log(ex.stack);
throw ex;
}
},
/**
* Verify a signature was created by the sender
*
* @param string aData
* A base64 signature data
* @param string aSignature
* A base64 encoded signature string
* @param string aPublicKey
* The sender's base 64 DER encoded public key
* @returns boolean
*/
verify: function WCW_verify(aData, aSignature, aPublicKey)
{
try {
let results = WeaveCrypto.verify(aPublicKey, aSignature, aData);
if (results)
return true;
return false;
}
catch (ex) {
log(ex);
log(ex.stack);
throw ex;
}
},
};
/**
* The WeaveCrypto changes I have made are minimal:
* 1. Removed any calls into Cc/Ci/Cr, etc.
* 2. added WeaveCrypto.sign() (PK11_Sign)
* 3. added WeaveCrypto.verify() (PK11_Verify)
*
* WeaveCrypto (js-ctypes iteration) was coded and reviewed in this bug:
* https://bugzilla.mozilla.org/show_bug.cgi?id=513798
*
*/
// http://mxr.mozilla.org/mozilla-central/source/security/nss/lib/util/secoidt.h#318
// recommended EC algs: http://www.nsa.gov/business/programs/elliptic_curve.shtml
// http://mxr.mozilla.org/mozilla-central/source/security/nss/lib/util/secoidt.h#346
var WeaveCrypto = {
debugEnabled : false,
nss : null,
nss_t : null,
log : function (message) {
if (!this.debugEnabled)
return;
dump("WeaveCrypto: " + message + "\n");
},
shutdown : function WC_shutdown() {
this.log("closing nsslib");
this.nsslib.close();
},
fullPathToLib: null,
initNSS : function WC_initNSS(aNSSPath, debugEnabled) {
// Open the NSS library.
this.fullPathToLib = aNSSPath;
this.debugEnabled = debugEnabled || false;
// XXX really want to be able to pass specific dlopen flags here.
var nsslib = ctypes.open(this.fullPathToLib);
this.nsslib = nsslib;
this.log("Initializing NSS types and function declarations...");
this.nss = {};
this.nss_t = {};
// nsprpub/pr/include/prtypes.h#435
// typedef PRIntn PRBool; --> int
this.nss_t.PRBool = ctypes.int;
// security/nss/lib/util/seccomon.h#91
// typedef enum
this.nss_t.SECStatus = ctypes.int;
// security/nss/lib/softoken/secmodt.h#59
// typedef struct PK11SlotInfoStr PK11SlotInfo; (defined in secmodti.h)
this.nss_t.PK11SlotInfo = ctypes.void_t;
// security/nss/lib/util/pkcs11t.h
this.nss_t.CK_MECHANISM_TYPE = ctypes.unsigned_long;
this.nss_t.CK_ATTRIBUTE_TYPE = ctypes.unsigned_long;
this.nss_t.CK_KEY_TYPE = ctypes.unsigned_long;
this.nss_t.CK_OBJECT_HANDLE = ctypes.unsigned_long;
// security/nss/lib/util/seccomon.h#64
// typedef enum
this.nss_t.SECItemType = ctypes.int;
// SECItemType enum values...
this.nss.SIBUFFER = 0;
// Needed for SECKEYPrivateKey struct def'n, but I don't think we need to actually access it.
this.nss_t.PLArenaPool = ctypes.void_t;
// security/nss/lib/cryptohi/keythi.h#45
// typedef enum
this.nss_t.KeyType = ctypes.int;
// security/nss/lib/softoken/secmodt.h#201
// typedef PRUint32 PK11AttrFlags;
this.nss_t.PK11AttrFlags = ctypes.unsigned_int;
// security/nss/lib/util/seccomon.h#83
// typedef struct SECItemStr SECItem; --> SECItemStr defined right below it
this.nss_t.SECItem = ctypes.StructType(
"SECItem", [{ type: this.nss_t.SECItemType },
{ data: ctypes.unsigned_char.ptr },
{ len : ctypes.int }]);
// security/nss/lib/softoken/secmodt.h#65
// typedef struct PK11RSAGenParamsStr --> def'n on line 139
this.nss_t.PK11RSAGenParams = ctypes.StructType(
"PK11RSAGenParams", [{ keySizeInBits: ctypes.int },
{ pe : ctypes.unsigned_long }]);
// security/nss/lib/softoken/secmodt.h#65
// typedef struct PK11RSAGenParamsStr --> def'n on line 132
// struct SECKEYDHParamsStr {
// PLArenaPool * arena;
// SECItem prime; /* p */
// SECItem base; /* g */
// };
this.nss_t.SECKEYDHParams = ctypes.StructType(
"SECKEYDHParams", [{ arena: this.nss_t.PLArenaPool.ptr },
{ prime: this.nss_t.SECItem },
{ base: this.nss_t.SECItem },]);
// security/nss/lib/cryptohi/keythi.h#233
// typedef struct SECKEYPrivateKeyStr SECKEYPrivateKey; --> def'n right above it
this.nss_t.SECKEYPrivateKey = ctypes.StructType(
"SECKEYPrivateKey", [{ arena: this.nss_t.PLArenaPool.ptr },
{ keyType: this.nss_t.KeyType },
{ pkcs11Slot: this.nss_t.PK11SlotInfo.ptr },
{ pkcs11ID: this.nss_t.CK_OBJECT_HANDLE },
{ pkcs11IsTemp: this.nss_t.PRBool },
{ wincx: ctypes.voidptr_t },
{ staticflags: ctypes.unsigned_int }]);
// security/nss/lib/cryptohi/keythi.h#78
// typedef struct SECKEYRSAPublicKeyStr --> def'n right above it
this.nss_t.SECKEYRSAPublicKey = ctypes.StructType(
"SECKEYRSAPublicKey", [{ arena: this.nss_t.PLArenaPool.ptr },
{ modulus: this.nss_t.SECItem },
{ publicExponent: this.nss_t.SECItem }]);
// security/nss/lib/cryptohi/keythi.h#189
// typedef struct SECKEYPublicKeyStr SECKEYPublicKey; --> def'n right above it
this.nss_t.SECKEYPublicKey = ctypes.StructType(
"SECKEYPublicKey", [{ arena: this.nss_t.PLArenaPool.ptr },
{ keyType: this.nss_t.KeyType },
{ pkcs11Slot: this.nss_t.PK11SlotInfo.ptr },
{ pkcs11ID: this.nss_t.CK_OBJECT_HANDLE },
{ rsa: this.nss_t.SECKEYRSAPublicKey } ]);
// security/nss/lib/util/secoidt.h#52
// typedef struct SECAlgorithmIDStr --> def'n right below it
this.nss_t.SECAlgorithmID = ctypes.StructType(
"SECAlgorithmID", [{ algorithm: this.nss_t.SECItem },
{ parameters: this.nss_t.SECItem }]);
// security/nss/lib/certdb/certt.h#98
// typedef struct CERTSubjectPublicKeyInfoStrA --> def'n on line 160
this.nss_t.CERTSubjectPublicKeyInfo = ctypes.StructType(
"CERTSubjectPublicKeyInfo", [{ arena: this.nss_t.PLArenaPool.ptr },
{ algorithm: this.nss_t.SECAlgorithmID },
{ subjectPublicKey: this.nss_t.SECItem }]);
this.nss_t.PQGParams = ctypes.StructType(
"PQGParams", [{ arena: this.nss_t.PLArenaPool.ptr },
{ prime: this.nss_t.SECItem },
{ subPrime: this.nss_t.SECItem },
{ base: this.nss_t.SECItem },]);
this.nss_t.PQGVerify = ctypes.StructType(
"PQGVerify", [{ arena: this.nss_t.PLArenaPool.ptr },
{ counter: ctypes.unsigned_int},
{ seed: this.nss_t.SECItem },
{ h: this.nss_t.SECItem }]);
/* XXX chrisk: this needs to be expanded to hold j and validationParms (RFC2459 7.3.2) */
// security/nss/lib/util/pkcs11t.h
this.nss.CKM_RSA_PKCS_KEY_PAIR_GEN = 0x0000;
this.nss.CKM_DH_PKCS_KEY_PAIR_GEN = 0x0020;
this.nss.CKM_DSA_KEY_PAIR_GEN = 0x0010;
// security/nss/lib/softoken/secmodt.h
this.nss.PK11_ATTR_SESSION = 0x02;
this.nss.PK11_ATTR_PUBLIC = 0x08;
this.nss.PK11_ATTR_SENSITIVE = 0x40;
this.nss.PK11_ATTR_INSENSITIVE = 0x80;
// security/nss/lib/pk11wrap/pk11pub.h#286
// SECStatus PK11_GenerateRandom(unsigned char *data,int len);
this.nss.PK11_GenerateRandom = nsslib.declare("PK11_GenerateRandom",
ctypes.default_abi, this.nss_t.SECStatus,
ctypes.unsigned_char.ptr, ctypes.int);
// security/nss/lib/pk11wrap/pk11pub.h#74
// PK11SlotInfo *PK11_GetInternalSlot(void);
this.nss.PK11_GetInternalSlot = nsslib.declare("PK11_GetInternalSlot",
ctypes.default_abi, this.nss_t.PK11SlotInfo.ptr);
// security/nss/lib/pk11wrap/pk11pub.h#73
// PK11SlotInfo *PK11_GetInternalKeySlot(void);
this.nss.PK11_GetInternalKeySlot = nsslib.declare("PK11_GetInternalKeySlot",
ctypes.default_abi, this.nss_t.PK11SlotInfo.ptr);
this.nss.PK11_PrivDecryptPKCS1 = nsslib.declare("PK11_PrivDecryptPKCS1",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECKEYPrivateKey.ptr,
ctypes.unsigned_char.ptr, ctypes.unsigned_int.ptr,
ctypes.unsigned_int, ctypes.unsigned_char.ptr,
ctypes.unsigned_int);
/* The encrypt function that complements the above decrypt function. */
this.nss.PK11_PubEncryptPKCS1 = nsslib.declare(
"PK11_PubEncryptPKCS1",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECKEYPublicKey.ptr,
ctypes.unsigned_char.ptr, ctypes.unsigned_char.ptr,
ctypes.unsigned_int, ctypes.voidptr_t
);
/* Generate PQGParams and PQGVerify structs.
* Length of seed and length of h both equal length of P.
* All lengths are specified by "j", according to the table above.
*/
this.nss.PK11_PQG_ParamGen = nsslib.declare(
"PK11_PQG_ParamGen",
ctypes.default_abi, this.nss_t.SECStatus,
ctypes.unsigned_int,
this.nss_t.PQGParams.ptr.ptr,
this.nss_t.PQGVerify.ptr.ptr
);
// extern SECStatus PK11_PQG_GetPrimeFromParams(const PQGParams *params,
// SECItem * prime);
this.nss.PK11_PQG_GetPrimeFromParams = nsslib.declare(
"PK11_PQG_GetPrimeFromParams",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.PQGParams.ptr,
this.nss_t.SECItem.ptr
);
this.nss.PK11_PubDecryptRaw = nsslib.declare(
"PK11_PubDecryptRaw",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECKEYPrivateKey.ptr,
ctypes.unsigned_char.ptr, ctypes.unsigned_int.ptr,
ctypes.unsigned_int, ctypes.unsigned_char.ptr,
ctypes.unsigned_int
);
this.nss.PK11_ImportDERPrivateKeyInfoAndReturnKey = nsslib.declare("PK11_ImportDERPrivateKeyInfoAndReturnKey",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.PK11SlotInfo.ptr, this.nss_t.SECItem.ptr,
this.nss_t.SECItem.ptr, this.nss_t.SECItem.ptr,
this.nss_t.PRBool, this.nss_t.PRBool, ctypes.int,
this.nss_t.SECKEYPrivateKey.ptr.ptr
);
// SIGNING API //////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// security/nss/pk11wrap/pk11pub.h#682
// int PK11_SignatureLength(SECKEYPrivateKey *key);
this.nss.PK11_SignatureLen = nsslib.declare("PK11_SignatureLen",
ctypes.default_abi,
ctypes.int,
this.nss_t.SECKEYPrivateKey.ptr);
// security/nss/pk11wrap/pk11pub.h#684
// SECStatus PK11_Sign(SECKEYPrivateKey *key, SECItem *sig, SECItem *hash);
this.nss.PK11_Sign = nsslib.declare("PK11_Sign",
ctypes.default_abi,
this.nss_t.SECStatus,
this.nss_t.SECKEYPrivateKey.ptr,
this.nss_t.SECItem.ptr,
this.nss_t.SECItem.ptr);
// security/nss/pk11wrap/pk11pub.h#687
// SECStatus PK11_Verify(SECKEYPublicKey *key, SECItem *sig, SECItem *hash, void *wincx);
this.nss.PK11_Verify = nsslib.declare("PK11_Verify",
ctypes.default_abi,
this.nss_t.SECStatus,
this.nss_t.SECKEYPublicKey.ptr,
this.nss_t.SECItem.ptr,
this.nss_t.SECItem.ptr,
ctypes.voidptr_t);
// END SIGNING API
//////////////////////////////////////////////////////////////////////////
// security/nss/lib/pk11wrap/pk11pub.h#507
// SECKEYPrivateKey *PK11_GenerateKeyPairWithFlags(PK11SlotInfo *slot,
// CK_MECHANISM_TYPE type, void *param, SECKEYPublicKey **pubk,
// PK11AttrFlags attrFlags, void *wincx);
this.nss.PK11_GenerateKeyPairWithFlags = nsslib.declare("PK11_GenerateKeyPairWithFlags",
ctypes.default_abi, this.nss_t.SECKEYPrivateKey.ptr,
this.nss_t.PK11SlotInfo.ptr, this.nss_t.CK_MECHANISM_TYPE, ctypes.voidptr_t,
this.nss_t.SECKEYPublicKey.ptr.ptr, this.nss_t.PK11AttrFlags, ctypes.voidptr_t);
// security/nss/lib/pk11wrap/pk11pub.h#466
// SECStatus PK11_SetPrivateKeyNickname(SECKEYPrivateKey *privKey, const char *nickname);
this.nss.PK11_SetPrivateKeyNickname = nsslib.declare("PK11_SetPrivateKeyNickname",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECKEYPrivateKey.ptr, ctypes.char.ptr);
// security/nss/lib/cryptohi/keyhi.h#159
// SECItem* SECKEY_EncodeDERSubjectPublicKeyInfo(SECKEYPublicKey *pubk);
this.nss.SECKEY_EncodeDERSubjectPublicKeyInfo = nsslib.declare("SECKEY_EncodeDERSubjectPublicKeyInfo",
ctypes.default_abi, this.nss_t.SECItem.ptr,
this.nss_t.SECKEYPublicKey.ptr);
// security/nss/lib/cryptohi/keyhi.h#165
// CERTSubjectPublicKeyInfo * SECKEY_DecodeDERSubjectPublicKeyInfo(SECItem *spkider);
this.nss.SECKEY_DecodeDERSubjectPublicKeyInfo = nsslib.declare("SECKEY_DecodeDERSubjectPublicKeyInfo",
ctypes.default_abi, this.nss_t.CERTSubjectPublicKeyInfo.ptr,
this.nss_t.SECItem.ptr);
// security/nss/lib/cryptohi/keyhi.h#179
// SECKEYPublicKey * SECKEY_ExtractPublicKey(CERTSubjectPublicKeyInfo *);
this.nss.SECKEY_ExtractPublicKey = nsslib.declare("SECKEY_ExtractPublicKey",
ctypes.default_abi, this.nss_t.SECKEYPublicKey.ptr,
this.nss_t.CERTSubjectPublicKeyInfo.ptr);
// security/nss/lib/pk11wrap/pk11pub.h#70
// void PK11_FreeSlot(PK11SlotInfo *slot);
this.nss.PK11_FreeSlot = nsslib.declare("PK11_FreeSlot",
ctypes.default_abi, ctypes.void_t,
this.nss_t.PK11SlotInfo.ptr);
// security/nss/lib/cryptohi/keyhi.h#193
// extern void SECKEY_DestroyPublicKey(SECKEYPublicKey *key);
this.nss.SECKEY_DestroyPublicKey = nsslib.declare("SECKEY_DestroyPublicKey",
ctypes.default_abi, ctypes.void_t,
this.nss_t.SECKEYPublicKey.ptr);
// security/nss/lib/cryptohi/keyhi.h#186
// extern void SECKEY_DestroyPrivateKey(SECKEYPrivateKey *key);
this.nss.SECKEY_DestroyPrivateKey = nsslib.declare("SECKEY_DestroyPrivateKey",
ctypes.default_abi, ctypes.void_t,
this.nss_t.SECKEYPrivateKey.ptr);
/*
* Creates a PublicKey from its DER encoding.
* Currently only supports RSA and DSA keys.
*/
this.nss.SECKEY_PublicKeyStrengthInBits = nsslib.declare("SECKEY_PublicKeyStrengthInBits",
ctypes.default_abi, ctypes.unsigned_int,
this.nss_t.SECKEYPublicKey.ptr);
// security/nss/lib/cryptohi/keyhi.h#58
// extern void SECKEY_DestroySubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki);
this.nss.SECKEY_DestroySubjectPublicKeyInfo = nsslib.declare("SECKEY_DestroySubjectPublicKeyInfo",
ctypes.default_abi, ctypes.void_t,
this.nss_t.CERTSubjectPublicKeyInfo.ptr);
// SECStatus PK11_ReadRawAttribute(PK11ObjectType type, void *object,
// CK_ATTRIBUTE_TYPE attr, SECItem *item);
this.nss.PK11_ReadRawAttribute = nsslib.declare("PK11_ReadRawAttribute",
ctypes.default_abi, this.nss_t.SECStatus,
this.nss_t.SECStatus, ctypes.voidptr_t,
this.nss_t.PK11AttrFlags, this.nss_t.SECItem.ptr);
},
sign : function _sign(aDerPrivKey, aDerPubKey, aHash) {
this.log("sign() called");
let privKey, slot, hash, sig;
slot = this.nss.PK11_GetInternalSlot();
if (slot.isNull())
throw new Error("couldn't get internal slot");
let derPrivKey = this.makeSECItem(aDerPrivKey, true);
let derPubKey = this.makeSECItem(aDerPubKey, true);
privKey = new this.nss_t.SECKEYPrivateKey.ptr();
hash = this.makeSECItem(aHash, true);
sig = this.makeSECItem("", false);
var rv = this.nss.PK11_ImportDERPrivateKeyInfoAndReturnKey(slot,
derPrivKey.address(), null, derPubKey.address(), false,
true, (0x7fffffff >>> 0), privKey.address());
if (privKey.isNull())
throw new Error("sign error: Could not import DER private key");
let sigLen = this.nss.PK11_SignatureLen(privKey);
sig.len = sigLen;
sig.data = new ctypes.ArrayType(ctypes.unsigned_char, sigLen)();
let status = this.nss.PK11_Sign(privKey, sig.address(), hash.address());
if (status == -1)
throw new Error("Could not sign message");
return this.encodeBase64(sig.data, sig.len);
},
verify : function _verify(aDerPubKey, aSignature, aHash) {
this.log("verify() called");
let derPubKey = this.makeSECItem(aDerPubKey, true);
let pubKeyInfo = this.nss.SECKEY_DecodeDERSubjectPublicKeyInfo(derPubKey.address());
if (pubKeyInfo.isNull())
throw new Error("SECKEY_DecodeDERSubjectPublicKeyInfo failed");
let pubKey = this.nss.SECKEY_ExtractPublicKey(pubKeyInfo);
if (pubKey.isNull())
throw new Error("SECKEY_ExtractPublicKey failed");
let sig = this.makeSECItem(aSignature, false);
let hash = this.makeSECItem(aHash, false);
let status =
this.nss.PK11_Verify(pubKey, sig.address(), hash.address(), null);
this.log("verify return " + status);
if (status == -1) {
return false;
}
return true;
},
generateKeypair : function(keyType, keypairBits, out_fields) {
this.log("generateKeypair() called. keytype("+ keyType + ") keybits("+ keypairBits + ")");
let pubKey, privKey, slot;
try {
// Attributes for the private key. We're just going to wrap and extract the
// value, so they're not critical. The _PUBLIC attribute just indicates the
// object can be accessed without being logged into the token.
let params, genType, rc;
switch(keyType) {
case PUB_ALGO.RSA:
let rsaParams = new this.nss_t.PK11RSAGenParams();
rsaParams.keySizeInBits = keypairBits; // 1024, 2048, etc.
rsaParams.pe = 65537; // public exponent.
params = rsaParams.address();
genType = this.nss.CKM_RSA_PKCS_KEY_PAIR_GEN;
break;
case PUB_ALGO.DSA:
var pqgparams = new this.nss_t.PQGParams.ptr();
var pqgverify = new this.nss_t.PQGVerify.ptr();
rc = this.nss.PK11_PQG_ParamGen(8, pqgparams.address(), pqgverify.address());
params = pqgparams;
genType = this.nss.CKM_DSA_KEY_PAIR_GEN;
break;
case PUB_ALGO.ELGAMAL_E:
var dhParams = new this.nss_t.SECKEYDHParams();
var pqgparams = new this.nss_t.PQGParams.ptr();
var pqgverify = new this.nss_t.PQGVerify.ptr();
rc = this.nss.PK11_PQG_ParamGen(8, pqgparams.address(), pqgverify.address());
var prime = this.makeSECItem("", false);
rc = this.nss.PK11_PQG_GetPrimeFromParams(pqgparams, prime.address());
dhParams.base = this.makeSECItem(String.fromCharCode(5), false);
dhParams.prime = prime;
params = dhParams.address();
genType = this.nss.CKM_DH_PKCS_KEY_PAIR_GEN;
break;
default:
throw new Error("Unkown key type algo: " + keyType);
}
slot = this.nss.PK11_GetInternalSlot();
if (slot.isNull())
throw new Error("couldn't get internal slot");
let attrFlags = (this.nss.PK11_ATTR_SESSION | this.nss.PK11_ATTR_PUBLIC | this.nss.PK11_ATTR_INSENSITIVE);
pubKey = new this.nss_t.SECKEYPublicKey.ptr();
// Generate the keypair.
privKey = this.nss.PK11_GenerateKeyPairWithFlags(slot,
genType,
params,
pubKey.address(),
attrFlags, null);
if (privKey.isNull())
throw new Error("keypair generation failed");
let s = this.nss.PK11_SetPrivateKeyNickname(privKey, "Weave User PrivKey");
if (s)
throw new Error("key nickname failed");
try {
// Use a buffer to hold the wrapped key. NSS says about 1200 bytes for
// a 2048-bit RSA key, so a 4096 byte buffer should be plenty.
var CKA_MODULUS = 0x00000120;
var CKA_MODULUS_BITS = 0x00000121;
var CKA_PUBLIC_EXPONENT = 0x00000122;
var CKA_PRIVATE_EXPONENT = 0x00000123;
var CKA_PRIME_1 = 0x00000124;
var CKA_PRIME_2 = 0x00000125;
var CKA_EXPONENT_1 = 0x00000126;
var CKA_EXPONENT_2 = 0x00000127;
var CKA_COEFFICIENT = 0x00000128;
var CKA_PRIME = 0x00000130;
var CKA_SUBPRIME = 0x00000131;
var CKA_BASE = 0x00000132;
var CKA_VALUE = 0x00000011;
var CKA_DERIVE = 0x0000010C;
var CKA_NETSCAPE_DB = 0xD5A0DB00;
function getAttribute(self, privKey, attrtype) {
// Use a buffer to hold the wrapped key. NSS says about 1200 bytes for
// a 2048-bit RSA key, so a 4096 byte buffer should be plenty.
let keyData = new ctypes.ArrayType(ctypes.unsigned_char, 4096)();
let outData = new self.nss_t.SECItem(self.nss.SIBUFFER, keyData, keyData.length);
let rc = self.nss.PK11_ReadRawAttribute(1, privKey, attrtype, outData.address());
let intData = ctypes.cast(outData.data, ctypes.uint8_t.array(outData.len).ptr).contents;
let expanded ="";
for (let i = 0; i < outData.len; i++)
expanded += String.fromCharCode(intData[i]);
return btoa(expanded);
}
switch(keyType) {
case PUB_ALGO.RSA:
out_fields.n = getAttribute(this, privKey, CKA_MODULUS);
out_fields.e = getAttribute(this, privKey, CKA_PUBLIC_EXPONENT);
out_fields.d = getAttribute(this, privKey, CKA_PRIVATE_EXPONENT);
out_fields.q = getAttribute(this, privKey, CKA_PRIME_1)
out_fields.p = getAttribute(this, privKey, CKA_PRIME_2)
out_fields.u = getAttribute(this, privKey, CKA_COEFFICIENT)
break;
case PUB_ALGO.ELGAMAL_E: //D-H
out_fields.p = getAttribute(this, privKey, CKA_PRIME);
out_fields.x = getAttribute(this, privKey, CKA_VALUE);
out_fields.g = getAttribute(this, privKey, CKA_BASE);
out_fields.y = getAttribute(this, privKey, CKA_NETSCAPE_DB);
break;
case PUB_ALGO.DSA:
out_fields.p = getAttribute(this, privKey, CKA_PRIME);
out_fields.q = getAttribute(this, privKey, CKA_SUBPRIME);
out_fields.g = getAttribute(this, privKey, CKA_BASE);
out_fields.x = getAttribute(this, privKey, CKA_VALUE);
out_fields.y = getAttribute(this, privKey, CKA_NETSCAPE_DB);
break;
default:
throw new Error("Unkown key type algo: " + keyType);
break;
}
} catch (e) {
this.log("generateKeypair: failed: " + e + e.lineNumber);
throw e;
} finally {
if (pubKey && !pubKey.isNull())
this.nss.SECKEY_DestroyPublicKey(pubKey);
if (privKey && !privKey.isNull())
this.nss.SECKEY_DestroyPrivateKey(privKey);
if (slot && !slot.isNull())
this.nss.PK11_FreeSlot(slot);
}
} catch (e) {
dump(e);
}
},
generateRandomBytes : function(byteCount) {
this.log("generateRandomBytes() called");
// Temporary buffer to hold the generated data.
let scratch = new ctypes.ArrayType(ctypes.unsigned_char, byteCount)();
if (this.nss.PK11_GenerateRandom(scratch, byteCount))
throw new Error("PK11_GenrateRandom failed");
return this.encodeBase64(scratch.address(), scratch.length);
},
encrypt : function(aHash, aDerPubKey) {
this.log("encrypt() called");
// Step 1. Get rid of the base64 encoding on the inputs.
let derPubKey = this.makeSECItem(aDerPubKey, true);
let hash = atob(aHash);
let slot, pubKeyInfo, pubKey;
try {
slot = this.nss.PK11_GetInternalSlot();
if (slot.isNull())
throw new Error("couldn't get internal slot");
pubKeyInfo = this.nss.SECKEY_DecodeDERSubjectPublicKeyInfo(derPubKey.address());
if (pubKeyInfo.isNull())
throw new Error("SECKEY_DecodeDERSubjectPublicKeyInfo failed");
pubKey = this.nss.SECKEY_ExtractPublicKey(pubKeyInfo);
if (pubKey.isNull())
throw new Error("SECKEY_ExtractPublicKey failed");
let byteLen = this.nss.SECKEY_PublicKeyStrengthInBits(pubKey) / 8;
let inputData = new ctypes.ArrayType(ctypes.unsigned_char, hash.length)();
this.byteCompress(hash, inputData);
let outputData = new ctypes.ArrayType(ctypes.unsigned_char, byteLen)();
let s = this.nss.PK11_PubEncryptPKCS1(pubKey, outputData, inputData, hash.length, null);
if (s)
throw new Error("PK11_PubEncryptPKCS1 failed");
return this.encodeBase64(outputData.address(), outputData.length);
} catch (e) {
this.log("encrypt: failed: " + e);
throw e;
} finally {
if (pubKey && !pubKey.isNull())
this.nss.SECKEY_DestroyPublicKey(pubKey);
if (pubKeyInfo && !pubKeyInfo.isNull())
this.nss.SECKEY_DestroySubjectPublicKeyInfo(pubKeyInfo);
if (slot && !slot.isNull())
this.nss.PK11_FreeSlot(slot);
}
},
decrypt : function(aHash, aDerPrivKey) {
this.log("decrypt() called");
// Step 1. Get rid of the base64 encoding on the inputs.
let derPrivKey = this.makeSECItem(aDerPrivKey, true);
let slot, privKey;
try {
slot = this.nss.PK11_GetInternalSlot();
if (slot.isNull())
throw new Error("couldn't get internal slot");
let privKey = new this.nss_t.SECKEYPrivateKey.ptr();
var rv = this.nss.PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, derPrivKey.address(),
null, null, false, true,
(0x7fffffff >>> 0), privKey.address());
if (privKey.isNull())
throw new Error("Import DER private key failed");
let input = atob(aHash);
let byteLen = input.length;
let inputData = new ctypes.ArrayType(ctypes.unsigned_char, byteLen)(); this.byteCompress(input, inputData);
let outputData = new ctypes.ArrayType(ctypes.unsigned_char, byteLen)();
let outputLen = new ctypes.unsigned;
rv = this.nss.PK11_PrivDecryptPKCS1(privKey, outputData,
outputLen.address(), byteLen,
inputData, byteLen);
return this.encodeBase64(outputData.address(), outputData.length);
} catch (e) {
this.log("decrypt: failed: " + e);
throw e;
} finally {
if (privKey && !privKey.isNull())
this.nss.SECKEY_DestroyPrivateKey(privKey);
if (slot && !slot.isNull())
this.nss.PK11_FreeSlot(slot);
}
},
//
// Utility functions
//
// Compress a JS string (2-byte chars) into a normal C string (1-byte chars)
// EG, for "ABC", 0x0041, 0x0042, 0x0043 --> 0x41, 0x42, 0x43
byteCompress : function (jsString, charArray) {
let intArray = ctypes.cast(charArray, ctypes.uint8_t.array(charArray.length));
for (let i = 0; i < jsString.length; i++) {
intArray[i] = jsString.charCodeAt(i) % 256; // convert to bytes
}
},
// Expand a normal C string (1-byte chars) into a JS string (2-byte chars)
// EG, for "ABC", 0x41, 0x42, 0x43 --> 0x0041, 0x0042, 0x0043
byteExpand : function (charArray) {
let expanded = "";
let len = charArray.length;
let intData = ctypes.cast(charArray, ctypes.uint8_t.array(len));
for (let i = 0; i < len; i++)
expanded += String.fromCharCode(intData[i]);
return expanded;
},
encodeBase64 : function (data, len) {
// Byte-expand the buffer, so we can treat it as a UCS-2 string
// consisting of u0000 - u00FF.
let expanded = "";
let intData = ctypes.cast(data, ctypes.uint8_t.array(len).ptr).contents;
for (let i = 0; i < len; i++)
expanded += String.fromCharCode(intData[i]);
return btoa(expanded);
},
makeSECItem : function(input, isEncoded) {
if (isEncoded)
input = atob(input);
let outputData = new ctypes.ArrayType(ctypes.unsigned_char, input.length)();
this.byteCompress(input, outputData);
return new this.nss_t.SECItem(this.nss.SIBUFFER, outputData, outputData.length);
},
};
| invi/ppg-api | lib/workers/domcrypt_worker.js | JavaScript | gpl-3.0 | 39,784 |
train-demo
==========
Some train about programming demo software with eclipse
license
-------
[GNU GENERAL PUBLIC LICENSE Version 3](http://www.gnu.org/licenses/gpl-3.0-standalone.html)
| tmc9031/train-demo | README.md | Markdown | gpl-3.0 | 189 |
/*******************************************************************************
OpenAirInterface
Copyright(c) 1999 - 2014 Eurecom
OpenAirInterface 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.
OpenAirInterface 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 OpenAirInterface.The full GNU General Public License is
included in this distribution in the file called "COPYING". If not,
see <http://www.gnu.org/licenses/>.
Contact Information
OpenAirInterface Admin: openair_admin@eurecom.fr
OpenAirInterface Tech : openair_tech@eurecom.fr
OpenAirInterface Dev : openair4g-devel@eurecom.fr
Address : Eurecom, Campus SophiaTech, 450 Route des Chappes, CS 50193 - 06904 Biot Sophia Antipolis cedex, FRANCE
*******************************************************************************/
//----------------------------------------------
//
// Integer square root. Take the square root of an integer.
//
#define step(shift) \
if((0x40000000l >> shift) + root <= value) \
{ \
value -= (0x40000000l >> shift) + root; \
root = (root >> 1) | (0x40000000l >> shift); \
} \
else \
{ \
root = root >> 1; \
}
int
iSqrt(int value)
{
int root = 0;
step( 0);
step( 2);
step( 4);
step( 6);
step( 8);
step(10);
step(12);
step(14);
step(16);
step(18);
step(20);
step(22);
step(24);
step(26);
step(28);
step(30);
// round to the nearest integer, cuts max error in half
if(root < value)
{
++root;
}
return root;
}
| mspublic/openair4G-mirror | openair1/PHY/TOOLS/sqrt.c | C | gpl-3.0 | 2,383 |
<?php
/** puts the Zend library on the current include path */
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__));
require_once 'Zend/Mail.php';
require_once 'Zend/Mail/Exception.php';
require_once 'Zend/Exception.php';
require_once 'Zend/Mail/Transport/Smtp.php';
require_once 'Zend/Service/ReCaptcha.php';
require_once 'Zend/Filter/Alpha.php';
require_once 'Zend/Filter/StripTags.php';
require_once 'Zend/Validate/EmailAddress.php';
require_once 'logger.php';
/**
* Mailer service wrapper for Zend SMTP
* @requires logger
* @author kevin@zvps.uk
*/
class mailer
{
/** Editable - Setup recaptch keys */
public $recaptchPublicKey = 'public-key_here';
public $recaptchPrivateKey = 'private-key-here';
/** Editable - Setup email account credentials and connection type */
private $emailConfigAuth = 'plain';
private $emailConfigUser = 'from@domain.com';
private $emailConfigPass = 'email-account-password';
private $emailConfigHost = 'localhost';
private $emailConfigPort = 25;
private $emailConfigSsl = false;
/** Editable - setup your email to receive contact form notifications */
private $emailTo = 'to@domain.com';
private $emailToName = 'our support team';
private $emailFromName = 'customer name';
private $emailSubject = 'Website Contact - ';
/** End Editable */
private $emailBody = null;
private $emailReplyTo = null;
private $smtpMail;
private $smtpTransport;
const CONFIG_AUTH = 'auth';
const CONFIG_USER = 'username';
const CONFIG_PASS = 'password';
const CONFIG_PORT = 'port';
const CONFIG_SSL = 'ssl';
const CONFIG_NAME = 'name';
public function __construct()
{
$config = array(
self::CONFIG_AUTH => $this->emailConfigAuth,
self::CONFIG_USER => $this->emailConfigUser,
self::CONFIG_PASS => $this->emailConfigPass,
self::CONFIG_PORT => $this->emailConfigPort,
self::CONFIG_SSL => $this->emailConfigSsl,
self::CONFIG_NAME => $this->emailConfigHost,
);
if($this->emailConfigSsl) {
$config[self::CONFIG_SSL] = $this->emailConfigSsl;
}
$this->smtpTransport = new Zend_Mail_Transport_Smtp($this->emailConfigHost, $config);
$this->smtpMail = new Zend_Mail();
}
/**
* Pass a name or company from the contact form
* @param string $displayName
*/
public function setFromName($displayName)
{
$filterAlpha = new Zend_Filter_Alpha(true);
$this->emailFromName = $filterAlpha->filter($displayName);
}
/**
* Appends to the email subject line
* @param type $subject
*/
public function setSubject($subject)
{
$filterTags = new Zend_Filter_StripTags();
$this->emailSubject .= $filterTags->filter($subject);
}
public function setBody($body)
{
$filterTags = new Zend_Filter_StripTags();
$this->emailBody = $filterTags->filter($body);
}
public function appendToBody($string)
{
$filterTags = new Zend_Filter_StripTags();
$this->emailBody .= $filterTags->filter($string) . "\n";
}
public function setReplyTo($replyTo)
{
$emailValidator = new Zend_Validate_EmailAddress(array('mx' => true, 'deep' => true));
$validator = new Zend_Validate();
if($validator->addValidator($emailValidator)->isValid($replyTo)) {
$this->emailReplyTo = $replyTo;
} else {
logger::addError(implode(' - ', $validator->getMessages()));
}
}
public function validate()
{
if(is_null($this->emailBody)) {
logger::addError('Please enter a message body.');
}
if(is_null($this->emailReplyTo)) {
logger::addError('Please enter a valid email address we can use to contact you on.');
}
if(is_null($this->emailSubject)) {
logger::addError('Please enter a subject.');
}
return (logger::hasErrors()) ? false : true;
}
public function send()
{
if($this->validate()) {
$this->smtpMail->setFrom($this->emailConfigUser, $this->emailFromName);
$this->smtpMail->addTo($this->emailTo, $this->emailToName);
$this->smtpMail->setSubject($this->emailSubject);
$this->smtpMail->setBodyText($this->emailBody);
$this->smtpMail->send($this->smtpTransport);
logger::addSuccess('Your message has been received, one of our team will contact you as soon as possible.');
return true;
} else {
return false;
}
}
}
| zVPS/zvps-smtp-contact-form | inc/mailer.php | PHP | gpl-3.0 | 4,709 |
/*
* Singleton.h
*
* Created on: 14-may-2009
* Author: Carlos Agüero
*
* Copyright 2014 Francisco Martín
*
* This file is part of ATCSim.
*
* ATCSim 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.
*
* ATCSim 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 ATCSim. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SRC_LIB_SINGLETON_H_
#define SRC_LIB_SINGLETON_H_
#include <string>
template< class C >
class Singleton {
public:
static C* getInstance() {
if ( Singleton<C>::uniqueInstance_ == nullptr )
Singleton<C>::uniqueInstance_ = new C();
return Singleton<C>::uniqueInstance_;
}
static void removeInstance() {
if ( Singleton<C>::uniqueInstance_ != nullptr ) {
delete Singleton<C>::uniqueInstance_;
Singleton<C>::uniqueInstance_ = nullptr;
}
}
private:
static C *uniqueInstance_;
};
// Initialize the static member CurrentInstance
template< class C >
C* Singleton<C>::uniqueInstance_ = nullptr;
#endif // SRC_LIB_SINGLETON_H_
| fmrico/ATCSim | src/lib/Singleton.h | C | gpl-3.0 | 1,456 |
/*
EntityViewer.class Petri Dish Sim 1.1 release
By: Jonathan Zepp - @DaJMasta
A means (seperate JFrame window) to navigate the world and get fairly detailed information on whatever is in the cell being examined.
August 10, 2015
This code and program can be used according the the GPL v3 found here: http://www.gnu.org/licenses/gpl-3.0.en.html
Free to modify and use in your own projects, but not for use in any commercial product. If you use it in your project, I'd appreciate a credit as a source!
*/
package SimPetriDish;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class EntityViewer extends JPanel implements ActionListener{
JButton entityViewXUp, entityViewXDown, entityViewYUp, entityViewYDown, entityViewZUp, entityViewZDown, entityViewGoButton ;
JLabel entityViewXLabel, entityViewYLabel, entityViewZLabel, entityViewType, entityViewName, entityViewHeat, entityViewLight, entityViewEnergy, entityViewNutrients, entityViewTranslucence,
entityViewAction, entityViewSubAction, entityViewLifetime, entityViewHP, entityViewProgeny, entityViewAttacker, entityViewSignalRecieved, entityViewAbilities, entityViewAbilities2 ;
TextField entityViewX, entityViewY, entityViewZ ;
TwoDViewer worldViewer ;
int viewerX, viewerY, viewerZ ;
Entity entityPanelViewed ;
final int viewerXSize = 500 ;
final int viewerYSize = 320 ;
EntityViewer(){
super() ;
viewerX = 0 ;
viewerY = 0 ;
viewerZ = 0 ;
entityViewXLabel = new JLabel("X:") ;
entityViewYLabel = new JLabel("Y:") ;
entityViewZLabel = new JLabel("Z:") ;
entityViewType = new JLabel("Entity") ;
entityViewName = new JLabel("This Entity") ;
entityViewHeat = new JLabel("Heat: ") ;
entityViewLight = new JLabel("Illumination: ") ;
entityViewEnergy = new JLabel("Energy: 0, Toxicity: 0") ;
entityViewNutrients = new JLabel("Nutrients - Red: 0, Green: 0, Blue: 0") ;
entityViewAction = new JLabel("No Action") ;
entityViewLifetime = new JLabel("Lifetime: 0") ;
entityViewSubAction = new JLabel("No Action") ;
entityViewHP = new JLabel("Health: 0") ;
entityViewXUp = new JButton("X+") ;
entityViewXDown = new JButton("X-") ;
entityViewYUp = new JButton("Y+") ;
entityViewYDown = new JButton("Y-") ;
entityViewZUp = new JButton("Z+") ;
entityViewZDown = new JButton("Z-") ;
entityViewGoButton = new JButton("Go") ;
entityViewX = new TextField("0", 3) ;
entityViewY = new TextField("0", 3) ;
entityViewZ = new TextField("0", 3) ;
entityViewProgeny = new JLabel("No children") ;
entityViewAttacker = new JLabel("Not attacked") ;
entityViewSignalRecieved = new JLabel("Not signaled") ;
entityViewAbilities = new JLabel("No abilities") ;
entityViewAbilities2 = new JLabel("") ;
entityViewTranslucence = new JLabel("Translucence: 1.0") ;
setLayout(null) ;
entityViewXUp.setBounds(110, 100, 50, 50) ;
entityViewXDown.setBounds(10, 100, 50, 50) ;
entityViewYUp.setBounds(60, 150, 50, 50) ;
entityViewYDown.setBounds(60, 50, 50, 50) ;
entityViewZUp.setBounds(90, 205, 50, 50) ;
entityViewZDown.setBounds(30, 205, 50, 50) ;
entityViewXUp.setActionCommand("XUP") ;
entityViewXUp.addActionListener(this) ;
entityViewXDown.setActionCommand("XDOWN") ;
entityViewXDown.addActionListener(this) ;
entityViewYUp.setActionCommand("YUP") ;
entityViewYUp.addActionListener(this) ;
entityViewYDown.setActionCommand("YDOWN") ;
entityViewYDown.addActionListener(this) ;
entityViewZUp.setActionCommand("ZUP") ;
entityViewZUp.addActionListener(this) ;
entityViewZDown.setActionCommand("ZDOWN") ;
entityViewZDown.addActionListener(this) ;
entityViewGoButton.setBounds(150, 5, 50, 40) ;
entityViewGoButton.setActionCommand("GO");
entityViewGoButton.addActionListener(this) ;
entityViewXLabel.setBounds(10, 15, 15, 20) ;
entityViewYLabel.setBounds(55, 15, 15, 20) ;
entityViewZLabel.setBounds(100, 15, 15, 20) ;
entityViewX.setBounds(25, 15, 30, 20) ;
entityViewY.setBounds(70, 15, 30, 20) ;
entityViewZ.setBounds(115, 15, 30, 20) ;
entityViewType.setBounds(245, 10, 300, 20) ;
entityViewName.setBounds(215, 35, 300, 20) ;
entityViewLifetime.setBounds(375, 35, 300, 20) ;
entityViewHeat.setBounds(215, 55, 300, 20) ;
entityViewLight.setBounds(360, 55, 300, 20) ;
entityViewTranslucence.setBounds(215, 75, 300, 20) ;
entityViewEnergy.setBounds(215, 95, 300, 20) ;
entityViewNutrients.setBounds(215, 115, 300, 20) ;
entityViewHP.setBounds(215, 135, 300, 20) ;
entityViewProgeny.setBounds(355, 135, 300, 20) ;
entityViewAction.setBounds(215, 155, 300, 20) ;
entityViewSubAction.setBounds(215, 175, 300, 20) ;
entityViewAttacker.setBounds(215, 195, 300, 20) ;
entityViewSignalRecieved.setBounds(215, 215, 300, 20) ;
entityViewAbilities.setBounds(215, 235, 300, 20) ;
entityViewAbilities2.setBounds(215, 255, 300, 20) ;
add(entityViewXUp) ;
add(entityViewXDown) ;
add(entityViewYUp) ;
add(entityViewYDown) ;
add(entityViewZUp) ;
add(entityViewZDown) ;
add(entityViewXUp) ;
add(entityViewX) ;
add(entityViewY) ;
add(entityViewZ) ;
add(entityViewXLabel) ;
add(entityViewYLabel) ;
add(entityViewZLabel) ;
add(entityViewGoButton) ;
add(entityViewType) ;
add(entityViewName) ;
add(entityViewHeat) ;
add(entityViewTranslucence) ;
add(entityViewLight) ;
add(entityViewEnergy) ;
add(entityViewNutrients) ;
add(entityViewAction) ;
add(entityViewLifetime) ;
add(entityViewHP) ;
add(entityViewSubAction) ;
add(entityViewProgeny) ;
add(entityViewAttacker) ;
add(entityViewSignalRecieved) ;
add(entityViewAbilities) ;
add(entityViewAbilities2) ;
}
public void setViewerPanel(TwoDViewer newView){
worldViewer = newView ;
}
public void actionPerformed(ActionEvent event) { //GUI buttons evaluation
String cmd = event.getActionCommand() ;
switch(cmd){
case "XUP": viewerX++ ;
entityPanelRead() ;
if(!worldViewer.bSimActive)
worldViewer.repaint() ;
break ;
case "XDOWN": viewerX-- ;
entityPanelRead() ;
if(!worldViewer.bSimActive)
worldViewer.repaint() ;
break ;
case "YUP": viewerY++ ;
entityPanelRead() ;
if(!worldViewer.bSimActive)
worldViewer.repaint() ;
break ;
case "YDOWN": viewerY-- ;
entityPanelRead() ;
if(!worldViewer.bSimActive)
worldViewer.repaint() ;
break ;
case "ZUP": viewerZ++ ;
entityPanelRead() ;
if(!worldViewer.bSimActive)
worldViewer.repaint() ;
break ;
case "ZDOWN": viewerZ-- ;
entityPanelRead() ;
if(!worldViewer.bSimActive)
worldViewer.repaint() ;
break ;
case "GO": viewerX = Integer.parseInt(entityViewX.getText()) ;
viewerY = Integer.parseInt(entityViewY.getText()) ;
viewerZ = Integer.parseInt(entityViewZ.getText()) ;
entityPanelRead() ;
if(!worldViewer.bSimActive)
worldViewer.repaint() ;
break ;
}
}
public void entityPanelRead(){ //Update the location of the cursor
if(viewerX >= worldViewer.world.xBounds - 1){
viewerX = worldViewer.world.xBounds - 1 ;
entityViewXUp.setEnabled(false) ;
}
else
entityViewXUp.setEnabled(true) ;
if(viewerX <= 0){
viewerX = 0 ;
entityViewXDown.setEnabled(false) ;
}
else
entityViewXDown.setEnabled(true) ;
if(viewerY >= worldViewer.world.yBounds - 1){
viewerY = worldViewer.world.yBounds - 1 ;
entityViewYUp.setEnabled(false) ;
}
else
entityViewYUp.setEnabled(true) ;
if(viewerY <= 0){
viewerY = 0 ;
entityViewYDown.setEnabled(false) ;
}
else
entityViewYDown.setEnabled(true) ;
if(viewerZ >= worldViewer.world.zBounds - 1){
viewerZ = worldViewer.world.zBounds - 1 ;
entityViewZUp.setEnabled(false) ;
}
else
entityViewZUp.setEnabled(true) ;
if(viewerZ <= 0){
viewerZ = 0 ;
entityViewZDown.setEnabled(false) ;
}
else
entityViewZDown.setEnabled(true) ;
entityViewX.setText(Integer.toString(viewerX)) ;
entityViewY.setText(Integer.toString(viewerY)) ;
entityViewZ.setText(Integer.toString(viewerZ)) ;
updateEntityPanel() ;
}
public void updateEntityPanel(){ //Update the entityViewer with current data
DecimalFormat df = new DecimalFormat("#.##") ;
String abilitiesText = null ;
String abilitiesText2 = null ;
entityPanelViewed = worldViewer.world.getEntity(viewerX, viewerY, viewerZ) ;
entityViewType.setText(entityPanelViewed.getClass().getName()) ;
if(entityPanelViewed instanceof AdvancedOrganism){
entityViewName.setText(((AdvancedOrganism)entityPanelViewed).name + " " + (int)((AdvancedOrganism)entityPanelViewed).id + ", generation " + (int)((AdvancedOrganism)entityPanelViewed).generation) ;
entityViewHP.setText("Health points: " + ((AdvancedOrganism)entityPanelViewed).healthPoints) ;
entityViewAction.setText("Action: " + ((Organism)entityPanelViewed).currentAction) ;
entityViewSubAction.setText("Subconscious action: " + ((Organism)entityPanelViewed).subconsciousAction) ;
if(!((AdvancedOrganism)entityPanelViewed).bSessile)
abilitiesText = "Can move" ;
if(((AdvancedOrganism)entityPanelViewed).bPhotosynthetic)
abilitiesText2 = "Can photosynthesize" ;
if(((AdvancedOrganism)entityPanelViewed).bChemotrophic){
if(abilitiesText2 != null)
abilitiesText2 += ", chemosynthesize" ;
else
abilitiesText2 = "Can chemosynthesize" ;
}
if(((AdvancedOrganism)entityPanelViewed).bCanSignal){
if(abilitiesText != null)
abilitiesText += ", signal" ;
else
abilitiesText = "Can signal" ;
}
if(((AdvancedOrganism)entityPanelViewed).bCanAttack){
if(abilitiesText != null)
abilitiesText += ", attack" ;
else
abilitiesText = "Can attack" ;
}
if(((AdvancedOrganism)entityPanelViewed).bGenerateToxins){
if(abilitiesText != null)
abilitiesText += ", make toxins" ;
else
abilitiesText = "Can make toxins" ;
}
if(((AdvancedOrganism)entityPanelViewed).bEmitToxins){
if(abilitiesText != null)
abilitiesText += ", emit toxins" ;
else
abilitiesText = "Can emit toxins" ;
}
if(((AdvancedOrganism)entityPanelViewed).bSpiky){
if(abilitiesText != null)
abilitiesText2 += ", is spiky" ;
else
abilitiesText2 = "Spiky" ;
}
if(abilitiesText == null)
abilitiesText = "" ;
if(abilitiesText2 == null)
abilitiesText2 = "" ;
entityViewAbilities.setText(abilitiesText) ;
entityViewAbilities2.setText(abilitiesText2) ;
if(((AdvancedOrganism)entityPanelViewed).progeny > 0)
entityViewProgeny.setText("Has " + (int)((AdvancedOrganism)entityPanelViewed).progeny + " offspring") ;
else
entityViewProgeny.setText("Has no offspring") ;
if(((AdvancedOrganism)entityPanelViewed).attacker != null)
entityViewAttacker.setText("Was attacked by " + ((AdvancedOrganism)entityPanelViewed).attacker.name + " " + ((AdvancedOrganism)entityPanelViewed).attacker.id + "." + ((AdvancedOrganism)entityPanelViewed).attacker.generation) ;
else
entityViewAttacker.setText("Has not been recently attacked") ;
if(((AdvancedOrganism)entityPanelViewed).recievedSignal.message != ' ')
entityViewSignalRecieved.setText("Last recieved: " + ((AdvancedOrganism)entityPanelViewed).recievedSignal.message + " at strength " + ((AdvancedOrganism)entityPanelViewed).recievedSignal.strength + " from " + ((AdvancedOrganism)entityPanelViewed).recievedSignal.sender) ;
else
entityViewSignalRecieved.setText("Has not been recently signaled") ;
}
else{
if(entityPanelViewed instanceof Organism){
entityViewName.setText("Unnamed Basic Organism") ;
entityViewHP.setText("Health points: 1") ;
entityViewAction.setText("Action: " + ((Organism)entityPanelViewed).currentAction) ;
entityViewSubAction.setText("Subconscious action: " + ((Organism)entityPanelViewed).subconsciousAction) ;
entityViewAbilities.setText("Can photosynthesize") ;
entityViewAbilities2.setText("") ;
entityViewProgeny.setText("Has an unknown number of offspring") ;
entityViewAttacker.setText("Dies if attacked") ;
entityViewSignalRecieved.setText("Cannot recieve signals") ;
}
else{
entityViewName.setText("No name") ;
entityViewHP.setText("No health points") ;
entityViewAction.setText("No action") ;
entityViewSubAction.setText("No subconscious action") ;
entityViewAbilities.setText("No abilities") ;
entityViewAbilities2.setText("") ;
entityViewProgeny.setText("Cannot reproduce") ;
entityViewAttacker.setText("Cannot be attacked") ;
entityViewSignalRecieved.setText("Cannot recieve signals") ;
}
}
if(entityPanelViewed instanceof OrganicEntity){
entityViewEnergy.setText("Energy: " + (int)((OrganicEntity)entityPanelViewed).energy + ", Toxicity: " + (int)((OrganicEntity)entityPanelViewed).toxicity) ;
entityViewNutrients.setText("Nutrients - Red: " + (int)((OrganicEntity)entityPanelViewed).nutrientHue.getRed() + ", Green: " +
(int)((OrganicEntity)entityPanelViewed).nutrientHue.getGreen() + ", Blue: " + (int)((OrganicEntity)entityPanelViewed).nutrientHue.getBlue()) ;
}
else if(entityPanelViewed instanceof ToxicPlume){
entityViewEnergy.setText("No organic energy, Toxicity: " + (int)((ToxicPlume)entityPanelViewed).toxicity) ;
entityViewNutrients.setText("No nutrients") ;
}
else{
entityViewEnergy.setText("No organic energy") ;
entityViewNutrients.setText("No nutrients") ;
}
entityViewHeat.setText("Heat: " + df.format(entityPanelViewed.heat)) ;
entityViewLight.setText("Illumination: " + (int)entityPanelViewed.illumination) ;
entityViewLifetime.setText("Age: " + (int)entityPanelViewed.lifetime) ;
entityViewTranslucence.setText("Translucence: " + df.format(entityPanelViewed.translucence)) ;
}
}
| DaJMasta/SimPetriDish | SimPetriDish/src/SimPetriDish/EntityViewer.java | Java | gpl-3.0 | 15,712 |
/*
* This file, RewardExpEvent.java, is part of MineQuest:
* A full featured and customizable quest/mission system.
* Copyright (C) 2012 The MineQuest Party
*
* 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.
*/
package com.theminequest.MQCoreRPG.QEvents;
import org.bukkit.entity.Player;
import com.theminequest.MQCoreRPG.MQCoreRPG;
import com.theminequest.MineQuest.API.CompleteStatus;
import com.theminequest.MineQuest.API.Managers;
import com.theminequest.MineQuest.API.Events.QuestEvent;
import com.theminequest.MineQuest.API.Group.QuestGroup;
public class RewardExpEvent extends QuestEvent {
/**
*
*/
private static final long serialVersionUID = 5542771222958268128L;
private int exptogive;
/*
* (non-Javadoc)
*
* @see
* com.theminequest.MineQuest.Events.QEvent#parseDetails(java.lang.String[])
* Details: [0] amount of exp to give.
*/
@Override
public void parseDetails(String[] details) {
exptogive = Integer.parseInt(details[0]);
}
@Override
public boolean conditions() {
return true;
}
@Override
public CompleteStatus action() {
QuestGroup g = Managers.getQuestGroupManager().get(getQuest());
for (Player p : g.getMembers())
MQCoreRPG.playerManager.getPlayerDetails(p).modifyExperienceBy(
exptogive / g.getMembers().size());
return CompleteStatus.SUCCESS;
}
@Override
public Integer switchTask() {
return null;
}
}
| Minequest/Minequest-RPG | src/main/java/com/theminequest/MQCoreRPG/QEvents/RewardExpEvent.java | Java | gpl-3.0 | 2,134 |
/*
* Copyright (C) Mojang AB
* All rights reserved.
*/
package kk.freecraft.entity.ai;
import kk.freecraft.block.Block;
import kk.freecraft.block.BlockDoor;
import kk.freecraft.entity.EntityLiving;
import kk.freecraft.world.EnumDifficulty;
public class EntityAIBreakDoor extends EntityAIDoorInteract {
private int breakingTime;
private int field_75358_j = -1;
public EntityAIBreakDoor(EntityLiving p_i1618_1_) {
super(p_i1618_1_);
}
/**
* Returns whether the EntityAIBase should begin execution.
*/
public boolean shouldExecute() {
if (!super.shouldExecute()) {
return false;
} else if (!this.theEntity.worldObj.getGameRules().getGameRuleBooleanValue("mobGriefing")) {
return false;
} else {
BlockDoor var10000 = this.doorBlock;
return !BlockDoor.func_176514_f(this.theEntity.worldObj, this.field_179507_b);
}
}
/**
* Execute a one shot task or start executing a continuous task
*/
public void startExecuting() {
super.startExecuting();
this.breakingTime = 0;
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
public boolean continueExecuting() {
double var1 = this.theEntity.getDistanceSq(this.field_179507_b);
boolean var3;
if (this.breakingTime <= 240) {
BlockDoor var10000 = this.doorBlock;
if (!BlockDoor.func_176514_f(this.theEntity.worldObj, this.field_179507_b) && var1 < 4.0D) {
var3 = true;
return var3;
}
}
var3 = false;
return var3;
}
/**
* Resets the task
*/
public void resetTask() {
super.resetTask();
this.theEntity.worldObj.sendBlockBreakProgress(this.theEntity.getEntityId(), this.field_179507_b, -1);
}
/**
* Updates the task
*/
public void updateTask() {
super.updateTask();
if (this.theEntity.getRNG().nextInt(20) == 0) {
this.theEntity.worldObj.playAuxSFX(1010, this.field_179507_b, 0);
}
++this.breakingTime;
int var1 = (int) ((float) this.breakingTime / 240.0F * 10.0F);
if (var1 != this.field_75358_j) {
this.theEntity.worldObj.sendBlockBreakProgress(this.theEntity.getEntityId(), this.field_179507_b, var1);
this.field_75358_j = var1;
}
if (this.breakingTime == 240 && this.theEntity.worldObj.getDifficulty() == EnumDifficulty.HARD) {
this.theEntity.worldObj.setBlockToAir(this.field_179507_b);
this.theEntity.worldObj.playAuxSFX(1012, this.field_179507_b, 0);
this.theEntity.worldObj.playAuxSFX(2001, this.field_179507_b, Block.getIdFromBlock(this.doorBlock));
}
}
}
| KubaKaszycki/FreeCraft | src/main/java/kk/freecraft/entity/ai/EntityAIBreakDoor.java | Java | gpl-3.0 | 2,478 |
---
layout: post
title: "گوگل امپ و سرعت بیشتر صفحات"
date: 2016-04-08 16:53:12
section: article
link: "http://navid.kashani.ir/927/google-amp/"
user: "نوید کاشانی"
user_link: "http://navid.kashani.ir/"
--- | reyhoun/ui.toread | issue/031/_posts/2016-04-08-amp.md | Markdown | gpl-3.0 | 238 |
package com.eztouch.wimp.proxy;
public interface IProxy
{
public abstract void registerKeyBindings();
public abstract void registerRenderers();
}
| EZtouch/wimp | src/main/java/com/eztouch/wimp/proxy/IProxy.java | Java | gpl-3.0 | 150 |
/********************************************************************************
* *
* F i l e S e l e c t i o n W i d g e t *
* *
*********************************************************************************
* Copyright (C) 1998,2020 by Jeroen van der Zijp. All Rights Reserved. *
*********************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/> *
********************************************************************************/
#ifndef FXFILESELECTOR_H
#define FXFILESELECTOR_H
#ifndef FXPACKER_H
#include "FXPacker.h"
#endif
namespace FX {
class FXFileAssociations;
class FXFileList;
class FXTextField;
class FXComboBox;
class FXDirBox;
class FXButton;
class FXMenuButton;
class FXIcon;
class FXMenuPane;
class FXCheckButton;
class FXMatrix;
class FXIconSource;
class FXHorizontalFrame;
/// File selection modes
enum {
SELECTFILE_ANY, /// A single file, existing or not (to save to)
SELECTFILE_EXISTING, /// An existing file (to load)
SELECTFILE_MULTIPLE, /// Multiple existing files
SELECTFILE_MULTIPLE_ALL, /// Multiple existing files or directories, but not '.' and '..'
SELECTFILE_DIRECTORY /// Existing directory, including '.' or '..'
};
/// File selection widget
class FXAPI FXFileSelector : public FXPacker {
FXDECLARE(FXFileSelector)
protected:
FXFileList *filebox; // File list widget
FXTextField *filename; // File name entry field
FXComboBox *filefilter; // Combobox for pattern list
FXMenuPane *bookmarkmenu; // Menu for bookmarks
FXHorizontalFrame *navbuttons; // Navigation buttons
FXHorizontalFrame *fileboxframe; // Frame around file list
FXMatrix *entryblock; // Entry block
FXCheckButton *readonly; // Open file as read only
FXDirBox *dirbox; // Directory hierarchy list
FXButton *accept; // Accept button
FXButton *cancel; // Cancel button
FXIcon *updiricon; // Up directory icon
FXIcon *listicon; // List mode icon
FXIcon *detailicon; // Detail mode icon
FXIcon *iconsicon; // Icon mode icon
FXIcon *homeicon; // Go home icon
FXIcon *workicon; // Go home icon
FXIcon *shownicon; // Files shown icon
FXIcon *hiddenicon; // Files hidden icon
FXIcon *bookmarkicon; // Book mark icon
FXIcon *bookaddicon; // Book add icon
FXIcon *bookdelicon; // Book delete icon
FXIcon *bookclricon; // Book clear icon
FXIcon *sortingicon; // Sorting icon
FXIcon *newicon; // New directory icon
FXIcon *renameicon; // Rename file icon
FXIcon *copyicon; // Copy file icon
FXIcon *moveicon; // Rename file icon
FXIcon *linkicon; // Link file icon
FXIcon *deleteicon; // Delete file icon
FXRecentFiles bookmarks; // Bookmarked places
FXuint selectmode; // Select mode
FXbool navigable; // May navigate
protected:
FXFileSelector(){}
static FXint countFilenames(const FXString& string);
static FXString decodeFilename(const FXString& string,FXint n=0);
static FXString encodeFilename(const FXString& string);
private:
FXFileSelector(const FXFileSelector&);
FXFileSelector &operator=(const FXFileSelector&);
public:
long onCmdAccept(FXObject*,FXSelector,void*);
long onCmdFilter(FXObject*,FXSelector,void*);
long onCmdItemDblClicked(FXObject*,FXSelector,void*);
long onCmdItemSelected(FXObject*,FXSelector,void*);
long onCmdItemDeselected(FXObject*,FXSelector,void*);
long onCmdDirectoryUp(FXObject*,FXSelector,void*);
long onUpdDirectoryUp(FXObject*,FXSelector,void*);
long onUpdDirTree(FXObject*,FXSelector,void*);
long onCmdDirTree(FXObject*,FXSelector,void*);
long onCmdHome(FXObject*,FXSelector,void*);
long onCmdWork(FXObject*,FXSelector,void*);
long onCmdBookmark(FXObject*,FXSelector,void*);
long onCmdUnBookmark(FXObject*,FXSelector,void*);
long onCmdVisit(FXObject*,FXSelector,void*);
long onCmdNew(FXObject*,FXSelector,void*);
long onUpdNew(FXObject*,FXSelector,void*);
long onCmdRename(FXObject*,FXSelector,void*);
long onCmdCopy(FXObject*,FXSelector,void*);
long onCmdMove(FXObject*,FXSelector,void*);
long onCmdLink(FXObject*,FXSelector,void*);
long onCmdRemove(FXObject*,FXSelector,void*);
long onUpdSelected(FXObject*,FXSelector,void*);
long onPopupMenu(FXObject*,FXSelector,void*);
long onCmdImageSize(FXObject*,FXSelector,void*);
long onUpdImageSize(FXObject*,FXSelector,void*);
long onUpdNavigable(FXObject*,FXSelector,void*);
public:
enum {
ID_FILEFILTER=FXPacker::ID_LAST,
ID_ACCEPT,
ID_FILELIST,
ID_DIRECTORY_UP,
ID_DIRTREE,
ID_MINI_SIZE,
ID_NORMAL_SIZE,
ID_MEDIUM_SIZE,
ID_GIANT_SIZE,
ID_HOME,
ID_WORK,
ID_BOOKMARK,
ID_UNBOOKMARK,
ID_BOOKMENU,
ID_VISIT,
ID_NEW,
ID_RENAME,
ID_COPY,
ID_MOVE,
ID_LINK,
ID_REMOVE,
ID_LAST
};
public:
/// Constructor
FXFileSelector(FXComposite *p,FXObject* tgt=NULL,FXSelector sel=0,FXuint opts=0,FXint x=0,FXint y=0,FXint w=0,FXint h=0);
/// Return a pointer to the "Accept" button
FXButton *acceptButton() const { return accept; }
/// Return a pointer to the "Cancel" button
FXButton *cancelButton() const { return cancel; }
/// Change file name
void setFilename(const FXString& path);
/// Return file name, if any
FXString getFilename() const;
/**
* Return array of strings containing the selected file names, terminated
* by an empty string. This string array must be freed using delete [].
* If no files were selected, a NULL is returned.
*/
FXString* getFilenames() const;
/// Change directory
void setDirectory(const FXString& path);
/// Return directory
FXString getDirectory() const;
/// Change file selection mode; the default is SELECTFILE_ANY
void setSelectMode(FXuint mode);
/// Return file selection mode
FXuint getSelectMode() const { return selectmode; }
/// Change file pattern
void setPattern(const FXString& ptrn);
/// Return file pattern
FXString getPattern() const;
/// Change wildcard matching mode (see FXPath)
void setMatchMode(FXuint mode);
/// Return wildcard matching mode
FXuint getMatchMode() const;
/**
* Change the list of file patterns shown in the file dialog.
* Each pattern comprises an optional name, followed by a pattern in
* parentheses. The patterns are separated by newlines.
* For example,
*
* "*\n*.cpp,*.cc\n*.hpp,*.hh,*.h"
*
* and
*
* "All Files (*)\nC++ Sources (*.cpp,*.cc)\nC++ Headers (*.hpp,*.hh,*.h)"
*
* will set the same three patterns, but the former shows no pattern names.
*/
void setPatternList(const FXString& patterns);
/// Return list of patterns
FXString getPatternList() const;
/**
* After setting the list of patterns, this call will
* initially select pattern n as the active one.
*/
void setCurrentPattern(FXint patno);
/// Return current pattern number
FXint getCurrentPattern() const;
/// Change pattern text for pattern number
void setPatternText(FXint patno,const FXString& text);
/// Get pattern text for given pattern number
FXString getPatternText(FXint patno) const;
/// Return number of patterns
FXint getNumPatterns() const;
/// Allow pattern entry
void allowPatternEntry(FXbool flag);
/// Return true if pattern entry is allowed
FXbool allowPatternEntry() const;
/// Set the inter-item spacing (in pixels)
void setItemSpace(FXint s);
/// Return the inter-item spacing (in pixels)
FXint getItemSpace() const;
/// Change file list style
void setFileBoxStyle(FXuint style);
/// Return file list style
FXuint getFileBoxStyle() const;
/// Return true if showing hidden files
FXbool showHiddenFiles() const;
/// Show or hide hidden files
void showHiddenFiles(FXbool flag);
/// Return true if image preview on
FXbool showImages() const;
/// Show or hide preview images
void showImages(FXbool flag);
/// Return images preview size
FXint getImageSize() const;
/// Change images preview size
void setImageSize(FXint size);
/// Show readonly button
void showReadOnly(FXbool flag);
/// Return true if readonly is shown
FXbool shownReadOnly() const;
/// Set initial state of readonly button
void setReadOnly(FXbool flag);
/// Get readonly state
FXbool getReadOnly() const;
/// Allow or disallow navigation
void allowNavigation(FXbool flag){ navigable=flag; }
/// Is navigation allowed?
FXbool allowNavigation() const { return navigable; }
/// Set draggable files
void setDraggableFiles(FXbool flag);
/// Are files draggable?
FXbool getDraggableFiles() const;
/// Set file time format
void setTimeFormat(const FXString& fmt);
/// Return file time format
FXString getTimeFormat() const;
/// Change file associations; delete old ones if owned
void setAssociations(FXFileAssociations* assoc,FXbool owned=false);
/// Return file associations
FXFileAssociations* getAssociations() const;
/// Change icon loader
void setIconSource(FXIconSource* src);
/// Return icon loader
FXIconSource* getIconSource() const;
/**
* Given filename pattern of the form "GIF Format (*.gif)",
* returns the pattern only, i.e. "*.gif" in this case.
* If the parentheses are not found then returns the entire
* input pattern.
*/
static FXString patternFromText(const FXString& pattern);
/**
* Given a pattern of the form "*.gif,*.GIF", return
* the first extension of the pattern, i.e. "gif" in this
* example. Returns empty string if it doesn't work out.
*/
static FXString extensionFromPattern(const FXString& pattern);
/// Save object to a stream
virtual void save(FXStream& store) const;
/// Load object from a stream
virtual void load(FXStream& store);
/// Destructor
virtual ~FXFileSelector();
};
}
#endif
| gogglesmm/gogglesmm | cfox/include/FXFileSelector.h | C | gpl-3.0 | 11,480 |
# -*- coding: utf-8 -*-
import os
import pickle
import random
import time
import urllib
try:
import xbmc, xbmcgui
except:
pass
from platformcode import config, logger
LIBTORRENT_PATH = config.get_setting("libtorrent_path", server="torrent", default='')
from servers import torrent as torr
lt, e, e1, e2 = torr.import_libtorrent(LIBTORRENT_PATH)
from cache import Cache
from dispatcher import Dispatcher
from file import File
from handler import Handler
from monitor import Monitor
from resume_data import ResumeData
from server import Server
try:
BUFFER = int(config.get_setting("bt_buffer", server="torrent", default="50"))
except:
BUFFER = 50
config.set_setting("bt_buffer", "50", server="torrent")
DOWNLOAD_PATH = config.get_setting("bt_download_path", server="torrent", default=config.get_setting("downloadpath"))
BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True)
RAR = config.get_setting("mct_rar_unpack", server="torrent", default=True)
msg_header = 'Alfa BT Cliente Torrent'
class Client(object):
INITIAL_TRACKERS = ['udp://tracker.openbittorrent.com:80',
'udp://tracker.istole.it:80',
'udp://open.demonii.com:80',
'udp://tracker.coppersurfer.tk:80',
'udp://tracker.leechers-paradise.org:6969',
'udp://exodus.desync.com:6969',
'udp://tracker.publicbt.com:80',
'http://tracker.torrentbay.to:6969/announce',
'http://tracker.pow7.com/announce',
'udp://tracker.ccc.de:80/announce',
'udp://open.demonii.com:1337',
'http://9.rarbg.com:2710/announce',
'http://bt.careland.com.cn:6969/announce',
'http://explodie.org:6969/announce',
'http://mgtracker.org:2710/announce',
'http://tracker.best-torrents.net:6969/announce',
'http://tracker.tfile.me/announce',
'http://tracker1.wasabii.com.tw:6969/announce',
'udp://9.rarbg.com:2710/announce',
'udp://9.rarbg.me:2710/announce',
'udp://coppersurfer.tk:6969/announce',
'http://www.spanishtracker.com:2710/announce',
'http://www.todotorrents.com:2710/announce'
] ### Added some trackers from MCT
VIDEO_EXTS = {'.avi': 'video/x-msvideo', '.mp4': 'video/mp4', '.mkv': 'video/x-matroska',
'.m4v': 'video/mp4', '.mov': 'video/quicktime', '.mpg': 'video/mpeg', '.ogv': 'video/ogg',
'.ogg': 'video/ogg', '.webm': 'video/webm', '.ts': 'video/mp2t', '.3gp': 'video/3gpp',
'.rar': 'video/unrar'}
def __init__(self, url=None, port=None, ip=None, auto_shutdown=True, wait_time=20, timeout=5, auto_delete=True,
temp_path=None, is_playing_fnc=None, print_status=False):
# server
if port:
self.port = port
else:
self.port = random.randint(8000, 8099)
if ip:
self.ip = ip
else:
self.ip = "127.0.0.1"
self.server = Server((self.ip, self.port), Handler, client=self)
# Options
if temp_path:
self.temp_path = temp_path
else:
self.temp_path = DOWNLOAD_PATH
self.is_playing_fnc = is_playing_fnc
self.timeout = timeout
self.auto_delete = auto_delete
self.wait_time = wait_time
self.auto_shutdown = auto_shutdown
self.buffer_size = BUFFER
self.first_pieces_priorize = BUFFER
self.last_pieces_priorize = 5
self.state_file = "state"
try:
self.torrent_paramss = {'save_path': self.temp_path, 'storage_mode': lt.storage_mode_t.storage_mode_allocate}
except Exception, e:
try:
do = xbmcgui.Dialog()
e = e1 or e2
do.ok('ERROR en el cliente BT Libtorrent', 'Módulo no encontrado o imcompatible con el dispositivo.',
'Reporte el fallo adjuntando un "log".', str(e))
except:
pass
return
# State
self.has_meta = False
self.meta = None
self.start_time = None
self.last_connect = 0
self.connected = False
self.closed = False
self.file = None
self.files = None
self._th = None
self.seleccion = 0
self.index = 0
# Sesion
self._cache = Cache(self.temp_path)
self._ses = lt.session()
#self._ses.listen_on(0, 0) ### ALFA: it blocks repro of some .torrents
# Cargamos el archivo de estado (si existe)
""" ### ALFA: it blocks repro of some .torrents
if os.path.exists(os.path.join(self.temp_path, self.state_file)):
try:
f = open(os.path.join(self.temp_path, self.state_file), "rb")
state = pickle.load(f)
self._ses.load_state(state)
f.close()
except:
pass
"""
self._start_services()
# Monitor & Dispatcher
self._monitor = Monitor(self)
if print_status:
self._monitor.add_listener(self.print_status)
self._monitor.add_listener(self._check_meta)
self._monitor.add_listener(self.save_state)
self._monitor.add_listener(self.priorize_start_file)
self._monitor.add_listener(self.announce_torrent)
if self.auto_shutdown:
self._monitor.add_listener(self._auto_shutdown)
self._dispatcher = Dispatcher(self)
self._dispatcher.add_listener(self._update_ready_pieces)
# Iniciamos la URL
if url:
self.start_url(url)
def set_speed_limits(self, download=0, upload=0):
"""
Función encargada de poner límites a la velocidad de descarga o subida
"""
if isinstance(download, int) and download > 0:
self._th.set_download_limit(download * 1024)
if isinstance(upload, int) and download > 0:
self._th.set_upload_limit(upload * 1024)
def get_play_list(self):
"""
Función encargada de generar el playlist
"""
# Esperamos a lo metadatos
while not self.has_meta:
time.sleep(1)
# Comprobamos que haya archivos de video
if self.files:
if len(self.files) > 1:
return "http://" + self.ip + ":" + str(self.port) + "/playlist.pls"
else:
return "http://" + self.ip + ":" + str(self.port) + "/" + urllib.quote(self.files[0].path)
def get_files(self):
"""
Función encargada de genera el listado de archivos
"""
# Esperamos a lo metadatos
while not self.has_meta:
time.sleep(1)
files = []
# Comprobamos que haya archivos de video
if self.files:
# Creamos el dict con los archivos
for file in self.files:
n = file.path
u = "http://" + self.ip + ":" + str(self.port) + "/" + urllib.quote(n)
s = file.size
files.append({"name": n, "url": u, "size": s})
return files
def _find_files(self, files, search=None):
"""
Función encargada de buscar los archivos reproducibles del torrent
"""
self.total_size = 0
# Obtenemos los archivos que la extension este en la lista
videos = filter(lambda f: self.VIDEO_EXTS.has_key(os.path.splitext(f.path)[1]), files)
if not videos:
raise Exception('No video files in torrent')
for v in videos:
self.total_size += v.size ### ALFA
videos[videos.index(v)].index = files.index(v)
return videos
def set_file(self, f):
"""
Función encargada de seleccionar el archivo que vamos a servir y por tanto, priorizar su descarga
"""
# Seleccionamos el archivo que vamos a servir
fmap = self.meta.map_file(f.index, 0, 1)
self.file = File(f.path, self.temp_path, f.index, f.size, fmap, self.meta.piece_length(), self)
if self.seleccion < 0: ### ALFA
self.file.first_piece = 0 ### ALFA
self.file.last_piece = self.meta.num_pieces() ### ALFA
self.file.size = self.total_size ### ALFA
self.prioritize_file()
def prioritize_piece(self, pc, idx):
"""
Función encargada de priorizar una determinada pieza
"""
piece_duration = 1000
min_deadline = 2000
dl = idx * piece_duration + min_deadline
""" ### ALFA
try:
self._th.set_piece_deadline(pc, dl, lt.deadline_flags.alert_when_available)
except:
pass
"""
if idx == 0:
tail_pieces = 9
# Piezas anteriores a la primera se desactivan
if (self.file.last_piece - pc) > tail_pieces:
for i in xrange(self.file.first_piece, pc):
self._th.piece_priority(i, 0)
self._th.reset_piece_deadline(i)
# Piezas siguientes a la primera se activan
for i in xrange(pc + 1, self.file.last_piece + 1):
#self._th.piece_priority(i, 0)
self._th.piece_priority(i, 1)
def prioritize_file(self):
"""
Función encargada de priorizar las piezas correspondientes al archivo seleccionado en la funcion set_file()
"""
priorities = []
for i in xrange(self.meta.num_pieces()):
if i >= self.file.first_piece and i <= self.file.last_piece:
priorities.append(1)
else:
if self.index < 0:
priorities.append(1) ### ALFA
else:
priorities.append(0) ### ALFA
self._th.prioritize_pieces(priorities)
x = 0
for i, _set in enumerate(self._th.piece_priorities()):
if _set > 0: x += 1
#logger.info("***** Nº Pieza: %s: %s" % (i, str(_set)))
logger.info("***** Piezas %s : Activas: %s" % (str(i+1), str(x)))
logger.info("***** first_piece %s : last_piece: %s" % (str(self.file.first_piece), str(self.file.last_piece)))
def download_torrent(self, url):
"""
Función encargada de descargar un archivo .torrent
"""
from core import httptools
data = httptools.downloadpage(url).data
return data
def start_url(self, uri):
"""
Función encargada iniciar la descarga del torrent desde la url, permite:
- Url apuntando a un .torrent
- Url magnet
- Archivo .torrent local
"""
if self._th:
raise Exception('Torrent is already started')
if uri.startswith('http://') or uri.startswith('https://'):
torrent_data = self.download_torrent(uri)
info = lt.torrent_info(lt.bdecode(torrent_data))
tp = {'ti': info}
resume_data = self._cache.get_resume(info_hash=str(info.info_hash()))
if resume_data:
tp['resume_data'] = resume_data
elif uri.startswith('magnet:'):
tp = {'url': uri}
resume_data = self._cache.get_resume(info_hash=Cache.hash_from_magnet(uri))
if resume_data:
tp['resume_data'] = resume_data
elif os.path.isfile(uri):
if os.access(uri, os.R_OK):
info = lt.torrent_info(uri)
tp = {'ti': info}
resume_data = self._cache.get_resume(info_hash=str(info.info_hash()))
if resume_data:
tp['resume_data'] = resume_data
else:
raise ValueError('Invalid torrent path %s' % uri)
else:
raise ValueError("Invalid torrent %s" % uri)
tp.update(self.torrent_paramss)
self._th = self._ses.add_torrent(tp)
for tr in self.INITIAL_TRACKERS:
self._th.add_tracker({'url': tr})
self._th.set_sequential_download(True)
self._th.force_reannounce()
self._th.force_dht_announce()
self._monitor.start()
self._dispatcher.do_start(self._th, self._ses)
self.server.run()
def stop(self):
"""
Función encargada de de detener el torrent y salir
"""
self._dispatcher.stop()
self._dispatcher.join()
self._monitor.stop()
self.server.stop()
self._dispatcher.stop()
if self._ses:
self._ses.pause()
if self._th:
self.save_resume()
self.save_state()
self._stop_services()
self._ses.remove_torrent(self._th, self.auto_delete)
del self._ses
self.closed = True
def pause(self):
"""
Función encargada de de pausar el torrent
"""
self._ses.pause()
def _start_services(self):
"""
Función encargada de iniciar los servicios de libtorrent: dht, lsd, upnp, natpnp
"""
self._ses.add_dht_router("router.bittorrent.com", 6881)
self._ses.add_dht_router("router.bitcomet.com", 554)
self._ses.add_dht_router("router.utorrent.com", 6881)
self._ses.add_dht_router("dht.transmissionbt.com",6881) ### from MCT
self._ses.start_dht()
self._ses.start_lsd()
self._ses.start_upnp()
self._ses.start_natpmp()
def _stop_services(self):
"""
Función encargada de detener los servicios de libtorrent: dht, lsd, upnp, natpnp
"""
self._ses.stop_natpmp()
self._ses.stop_upnp()
self._ses.stop_lsd()
self._ses.stop_dht()
def save_resume(self):
"""
Función encargada guardar los metadatos para continuar una descarga mas rapidamente
"""
if self._th.need_save_resume_data() and self._th.is_valid() and self.meta:
r = ResumeData(self)
start = time.time()
while (time.time() - start) <= 5:
if r.data or r.failed:
break
time.sleep(0.1)
if r.data:
self._cache.save_resume(self.unique_file_id, lt.bencode(r.data))
@property
def status(self):
"""
Función encargada de devolver el estado del torrent
"""
if self._th:
s = self._th.status()
# Download Rate
s._download_rate = s.download_rate / 1024
# Progreso del archivo
if self.file:
pieces = s.pieces[self.file.first_piece:self.file.last_piece] ### ALFA
progress = float(sum(pieces)) / len(pieces)
s.pieces_len = len(pieces) ### ALFA
s.pieces_sum = sum(pieces) ### ALFA
#logger.info('***** Estado piezas: %s' % pieces)
else:
progress = 0
s.pieces_len = 0 ### ALFA
s.pieces_sum = 0 ### ALFA
s.progress_file = progress * 100
# Tamaño del archivo
s.file_name = '' ### ALFA
s.seleccion = '' ### ALFA
if self.file:
s.seleccion = self.seleccion ### ALFA
s.file_name = self.file.path ### ALFA
s.file_size = self.file.size / 1048576.0
else:
s.file_size = 0
# Estado del buffer
if self.file and self.file.cursor: # Con una conexion activa: Disponible vs Posicion del reproductor
percent = len(self.file.cursor.cache)
percent = percent * 100 / self.buffer_size
s.buffer = int(percent)
elif self.file: # Sin una conexion activa: Pre-buffer antes de iniciar
# El Pre-buffer consta de dos partes_
# 1. Buffer al inicio del archivo para que el reproductor empieze sin cortes
# 2. Buffer al final del archivo (en algunos archivos el reproductor mira el final del archivo antes de comenzar)
bp = []
# El tamaño del buffer de inicio es el tamaño del buffer menos el tamaño del buffer del final
first_pieces_priorize = self.buffer_size - self.last_pieces_priorize
# Comprobamos qué partes del buffer del inicio estan disponibles
for x in range(first_pieces_priorize):
if self._th.have_piece(self.file.first_piece + x):
bp.append(True)
else:
bp.append(False)
# Comprobamos qué partes del buffer del final estan disponibles
for x in range(self.last_pieces_priorize):
if self._th.have_piece(self.file.last_piece - x):
bp.append(True)
else:
bp.append(False)
s.buffer = int(sum(bp) * 100 / self.buffer_size)
else: # Si no hay ningun archivo seleccionado: No hay buffer
s.buffer = 0
# Tiempo restante para cerrar en caso de tener el timeout activo
if self.auto_shutdown:
if self.connected:
if self.timeout:
s.timeout = int(self.timeout - (time.time() - self.last_connect - 1))
if self.file and self.file.cursor:
s.timeout = self.timeout
if s.timeout < 0: s.timeout = "Cerrando"
else:
s.timeout = "---"
else:
if self.start_time and self.wait_time:
s.timeout = int(self.wait_time - (time.time() - self.start_time - 1))
if s.timeout < 0: s.timeout = "Cerrando"
else:
s.timeout = "---"
else:
s.timeout = "Off"
# Estado de la descarga
STATE_STR = ['En cola', 'Comprobando', 'Descargando metadata', \
'Descargando', 'Finalizado', 'Seeding', 'Allocating', 'Comprobando fastresume']
s.str_state = STATE_STR[s.state]
# Estado DHT
if self._ses.dht_state() is not None:
s.dht_state = "On"
s.dht_nodes = self._ses.status().dht_nodes
else:
s.dht_state = "Off"
s.dht_nodes = 0
# Cantidad de Trackers
s.trackers = len(self._th.trackers())
# Origen de los peers
s.dht_peers = 0
s.trk_peers = 0
s.pex_peers = 0
s.lsd_peers = 0
for peer in self._th.get_peer_info():
if peer.source & 1:
s.trk_peers += 1
if peer.source & 2:
s.dht_peers += 1
if peer.source & 4:
s.pex_peers += 1
if peer.source & 8:
s.lsd_peers += 1
return s
"""
Servicios:
- Estas funciones se ejecutan de forma automatica cada x tiempo en otro Thread.
- Estas funciones son ejecutadas mientras el torrent esta activo algunas pueden desactivarse
segun la configuracion como por ejemplo la escritura en el log
"""
def _auto_shutdown(self, *args, **kwargs):
"""
Servicio encargado de autoapagar el servidor
"""
if self.file and self.file.cursor:
self.last_connect = time.time()
self.connected = True
if self.is_playing_fnc and self.is_playing_fnc():
self.last_connect = time.time()
self.connected = True
if self.auto_shutdown:
# shudown por haber cerrado el reproductor
if self.connected and self.is_playing_fnc and not self.is_playing_fnc():
if time.time() - self.last_connect - 1 > self.timeout:
self.stop()
# shutdown por no realizar ninguna conexion
if (not self.file or not self.file.cursor) and self.start_time and self.wait_time and not self.connected:
if time.time() - self.start_time - 1 > self.wait_time:
self.stop()
# shutdown tras la ultima conexion
if (not self.file or not self.file.cursor) and self.timeout and self.connected and not self.is_playing_fnc:
if time.time() - self.last_connect - 1 > self.timeout:
self.stop()
def announce_torrent(self):
"""
Servicio encargado de anunciar el torrent
"""
self._th.force_reannounce()
self._th.force_dht_announce()
def save_state(self):
"""
Servicio encargado de guardar el estado
"""
state = self._ses.save_state()
f = open(os.path.join(self.temp_path, self.state_file), 'wb')
pickle.dump(state, f)
f.close()
def _update_ready_pieces(self, alert_type, alert):
"""
Servicio encargado de informar que hay una pieza disponible
"""
if alert_type == 'read_piece_alert' and self.file:
self.file.update_piece(alert.piece, alert.buffer)
def _check_meta(self):
"""
Servicio encargado de comprobar si los metadatos se han descargado
"""
if self.status.state >= 3 and self.status.state <= 5 and not self.has_meta:
# Guardamos los metadatos
self.meta = self._th.get_torrent_info()
# Obtenemos la lista de archivos del meta
fs = self.meta.files()
if isinstance(fs, list):
files = fs
else:
files = [fs.at(i) for i in xrange(fs.num_files())]
# Guardamos la lista de archivos
self.files = self._find_files(files)
# Si hay varios vídeos (no RAR), se selecciona el vídeo o "todos"
lista = []
seleccion = 0
for file in self.files:
if '.rar' in str(file.path):
seleccion = -9
lista += [os.path.split(str(file.path))[1]]
if len(lista) > 1 and seleccion >= 0:
d = xbmcgui.Dialog()
seleccion = d.select(msg_header + ": Selecciona el vídeo, o 'Cancelar' para todos", lista)
if seleccion < 0:
index = 0
self.index = seleccion
else:
index = seleccion
self.index = self.files[index].index
self.seleccion = seleccion
# Marcamos el primer archivo como activo
self.set_file(self.files[index])
# Damos por iniciada la descarga
self.start_time = time.time()
# Guardamos el .torrent en el cache
self._cache.file_complete(self._th.get_torrent_info())
self.has_meta = True
def priorize_start_file(self):
'''
Servicio encargado de priorizar el principio y final de archivo cuando no hay conexion
'''
if self.file and not self.file.cursor:
num_start_pieces = self.buffer_size - self.last_pieces_priorize # Cantidad de piezas a priorizar al inicio
num_end_pieces = self.last_pieces_priorize # Cantidad de piezas a priorizar al final
pieces_count = 0
# Priorizamos las ultimas piezas
for y in range(self.file.last_piece - num_end_pieces, self.file.last_piece + 1):
if not self._th.have_piece(y):
self.prioritize_piece(y, pieces_count)
pieces_count += 1
# Priorizamos las primeras piezas
for y in range(self.file.first_piece, self.file.last_piece + 1):
if not self._th.have_piece(y):
if pieces_count == self.buffer_size:
break
self.prioritize_piece(y, pieces_count)
pieces_count += 1
def print_status(self):
'''
Servicio encargado de mostrar en el log el estado de la descarga
'''
s = self.status ### ALFA
if self.seleccion >= 0:
archivo = self.seleccion + 1
else:
archivo = self.seleccion
logger.info(
'%.2f%% de %.1fMB %s | %.1f kB/s | #%s %d%% | AutoClose: %s | S: %d(%d) P: %d(%d)) | TRK: %d DHT: %d PEX: %d LSD %d | DHT:%s (%d) | Trakers: %d | Pieces: %d (%d)' % \
(s.progress_file, s.file_size, s.str_state, s._download_rate, archivo, s.buffer, s.timeout, s.num_seeds, \
s.num_complete, s.num_peers, s.num_incomplete, s.trk_peers, s.dht_peers, s.pex_peers, s.lsd_peers,
s.dht_state, s.dht_nodes, s.trackers, s.pieces_sum, s.pieces_len)) ### ALFA
| alfa-jor/addon | plugin.video.alfa/lib/btserver/client.py | Python | gpl-3.0 | 26,890 |
//**************************************************************************
// COMPOSANT : LdbpcCan
// FONCTION : Interface pour la classes tcCanal
//
// Ce logiciel est la propriete de JCI :
// ---------------------------------------
// Il ne peut etre reproduit ni communique en totalite ou partie sans
// son autorisation ecrite.
//
// ------------------------------------------------------------------------
// Ce fichier doit etre inclus dans les composants utilisant les macros,
// types et fonctions definis par le composant LdbpcCan.
// Le fichier LdbpcCan.h doit contenir toute et uniquement
// l'information necessaire au programmeur pour utiliser le composant
// LdbpcCan.
// En particulier c'est ce fichier LdbpcCan.h qui contient l'historique
// et la documentation du composant dans son ensemble.
// ------------------------------------------------------------------------
// Reference a la documentation :
//
// ------------------------------------------------------------------------
// Presentation generale du composant :
//
// ------------------------------------------------------------------------
// Nom et initiales des developpeurs : GUILLEN GG
//
// ------------------------------------------------------------------------
// Historique du composant LdbpcCan dans son ensemble
// (initiales, date, modification)
//
// cree par : GG : 20/04/2000
//
// ------------------------------------------------------------------------
// Historique du fichier LdbpcCan.h
// (initiales, date, modification)
//
//***************************************************************************
//-------------------------------------------------------------------------
//----- Inclusion de fichiers .h utiles a l'expansion de celui-ci -------
//-------------------------------------------------------------------------
//---- Definition pour mono-inclusion -----
#if !defined(I_LdbpcCan)
#define I_LdbpcCan
#include "Array.h"
#include "Ldbpc.h" // Defini les types et constantes de bases
#include "LdbpcTim.h" // Defini les types et constantes de bases
#include "afxtempl.h" // Defini les types et constantes de bases
#include "afxmt.h" // Defini les types et constantes de bases
#include "CANDll.h" // Access to CANDLL
#include "tcSADAdrFrame.h"
//-------------------------------------------------------------------------
//------ Declaration des constantes exportees par ce composant ----------
//-------------------------------------------------------------------------
//(Com: 3 lettres identifiant ce composant)
//#define cComNomConstante ValeurDeLaConstante
//--------------------------------------------------------------------------
//------- Declaration des macros exportees par ce composant --------------
//--------------------------------------------------------------------------
// (Com: 3 lettres identifiant ce composant)
// #define mComNomMacro (DefinitionDeLaMacro)
//--------------------------------------------------------------------------
//------- Definition des types exportes par ce composant -----------------
//--------------------------------------------------------------------------
// (Com: 3 lettres identifiant ce composant)
// typedef ... tComNomType;
class tcCanal;
typedef tcArray<tcCanal *> tcTabCanal;
//--------------------------------------------------------------------------
//------- Declaration des variables exportees par ce composant -----------
//--------------------------------------------------------------------------
// (Com: 3 lettres identifiant ce composant)
// extern tType ComNomVariable;
// extern tType* pComNomVariable;
//--------------------------------------------------------------------------
//------- Donnees Constantes exportees par ce composant ------------------
//--------------------------------------------------------------------------
// (Com: 3 lettres identifiant ce composant)
//extern const tType ComNomVariable;
// Nota:
// Pour les variables qui peuvent etre modifiees par LdbpcCan mais non
// par les composants utilisateurs, on utilisera une definition conditionnel
//
// #ifdef LdbpcCan
// extern tType ComNomVariable;
// #else
// extern const tType ComNomVariable;
// #endif
//--------------------------------------------------------------------------
//------------------------- Fonctions exportees ----------------------------
//--------------------------------------------------------------------------
// extern tTypeRetour NomFonction(tTypeArgument NomArgument, ...);
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define cDisponible 0
#define cOccupe 1
typedef struct
{
tTrameCan TrameCan;
U32 Id;
}tMsgBuffer;
//--------------------------------------------------------------------------
//------------------- Interface de la classe tcCanal ----------------------
//--------------------------------------------------------------------------
class tcCanal
{
public:
tcCanal(tCallBackCanal * pStructCallBack=NULL);
char * GetName() const { return((char*)(m_StructCallBack.ChannelName)); }
virtual ~tcCanal();
tcSADAdrFrame m_SADAdrTrace;
// Acces au format du Canal (Intel ou Motorola)
inline void SetFormat(U8 Format) {m_Format = Format;}
inline U8 GetFormat(void) {return m_Format;}
// Lecture du nom du Canal
void LireNom(char ** pNom) const { *pNom = (char*)(m_StructCallBack.ChannelName); }
// Attacher un flux a un canal
tLDBPCStatut AttacherFlux(S32 RefFlux,tLdbpcTypeFlux Type);
// Lire une reference de flux par rapport au type de flux
tLDBPCStatut LireRefFlux(tLdbpcTypeFlux Type, S32 * pRefFlux);
// Lecture de l'etat du canal
inline char LireEtat() const { return m_Etat; }
// Ecriture de l'etat du canal
inline void EcrireEtat(char Etat) { m_Etat = Etat; }
// Lecture de l'autorisation des flux non initie sur le canal
inline BOOL LireAutorisation(void) const { return m_Autorise; }
// Ecriture de l'autorisation des flux non initie sur le canal
inline void EcrireAutorisation(BOOL Autorise)
{
m_Autorise = Autorise;
}
// Ecriture du ctrl en cours sur le canal
inline void EcrireCtrlEnCours(U32 RefCtrl) { m_RefCtrlEnCours = RefCtrl; }
// Controle personalise
virtual BOOL Controler(tCtrl Ctrl);
// Appel de la callback de fin de Controle
virtual BOOL FinControle(tCtrl Ctrl,tStatus Statut);
// Appel de la callback de Controle du LAP
virtual BOOL CBControle(tCtrl Ctrl);
// Autorisation personalisee
virtual BOOL Autoriser(BOOL Autorise);
virtual void Reset(void);
virtual BOOL Send(tLdbpcTypeFlux Type, tAddress Adresse, tMsg* pMsg) {return(cFalse);}
protected:
// Tableau de flux
S32 m_RefFlux[MAX_FLUX];
// Drapeau d'autrisation
BOOL m_Autorise;
// Ref de control en cours
U32 m_RefCtrlEnCours;
// Etat du Canal
char m_Etat;
// Format du Canal (Intel ou Motorola)
U8 m_Format;
tCallBackCanal m_StructCallBack;
};
class tObjetCanUU;
class tcCanDll;
class CChannelCAN;
class CChannelCAN : public tcCanal
{
public:
CChannelCAN(tXCanChannel * pStruct=NULL);
virtual ~CChannelCAN();
void OnLdbpcTxCon();
void OnLdbpcRxInd();
void OnTxCon(tObjetCanUU* pObjetCanUU);
void OnRxInd(tObjetCanUU* pObjetCanUU, tTrameCan* pTrameCan);
// Controle personalise
virtual BOOL Controler(tCtrl Ctrl);
virtual void Reset(void);
virtual BOOL Send(tLdbpcTypeFlux Type, tAddress Adresse, tMsg* pMsg);
private:
typedef void (*tpf)(CChannelCAN*);
tcTempoObjet<CChannelCAN*,tpf> m_TxTempo;
CList<U32,U32> m_ListTxId;
CCriticalSection m_CSTx;
tcTempoObjet<CChannelCAN*,tpf> m_RxTempo;
CList<tMsgBuffer*,tMsgBuffer*> m_ListRxId;
CCriticalSection m_CSRx;
tcCanDll * m_pCANChannel;
tObjetCanUU * m_pRxCANUUDT;
tObjetCanUU * m_pTxCANUUDT;
tXCanChannel m_XCanChannel;
BOOL m_WakeUp;
BOOL m_FirstCtrlInit;
};
#endif // fin de l'inclusion conditionnelle de LdbpcCan.h
| dmanev/ArchExtractor | jilTester/Tester/Build/Simulation/Kernel/LDBPCCAN.H | C++ | gpl-3.0 | 8,236 |
/*******************************************************************************************************************************
* AK.RockCon.Commands.Command
* Copyright © 2015 Aashish Koirala <http://aashishkoirala.github.io>
*
* This file is part of RockCon.
*
* RockCon 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.
*
* RockCon 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 RockCon. If not, see <http://www.gnu.org/licenses/>.
*
*******************************************************************************************************************************/
namespace AK.RockCon.Commands
{
/// <summary>
/// Represents any command that can get executed and also spawn its list of sub-commands.
/// </summary>
/// <author>Aashish Koirala</author>
public interface ICommand
{
ICommand[] Commands { get; }
string Name { get; }
void Execute(IContainer container);
}
/// <summary>
/// Common functionality for all commands.
/// </summary>
/// <author>Aashish Koirala</author>
public abstract class CommandBase : ICommand
{
protected CommandBase()
{
this.Commands = this.Commands ?? new ICommand[0];
}
public ICommand[] Commands { get; protected set; }
public string Name { get; protected set; }
public virtual void Execute(IContainer container)
{
}
}
} | aashishkoirala/rockcon | src/AK.RockCon/Commands/Command.cs | C# | gpl-3.0 | 1,891 |
/*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn 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.
*
* Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.exception;
import ai.grakn.concept.Instance;
import ai.grakn.concept.Resource;
import ai.grakn.util.ErrorMessage;
import ai.grakn.util.Schema;
import ai.grakn.concept.Concept;
import ai.grakn.concept.Instance;
import ai.grakn.concept.Resource;
import ai.grakn.util.ErrorMessage;
import ai.grakn.util.Schema;
/**
* This exception is thrown when two concepts attept to have the same unique id.
*/
public class ConceptNotUniqueException extends ConceptException {
public ConceptNotUniqueException(Concept concept, Schema.ConceptProperty type, String id) {
super(ErrorMessage.ID_NOT_UNIQUE.getMessage(concept.toString(), type.name(), id));
}
public ConceptNotUniqueException(Concept concept, String id){
super(ErrorMessage.ID_ALREADY_TAKEN.getMessage(id, concept.toString()));
}
public ConceptNotUniqueException(Resource resource, Instance instance){
super(ErrorMessage.RESOURCE_TYPE_UNIQUE.getMessage(resource.getId(), instance.getId()));
}
}
| fppt/mindmapsdb | grakn-core/src/main/java/ai/grakn/exception/ConceptNotUniqueException.java | Java | gpl-3.0 | 1,738 |
package org.briarproject;
import java.util.Random;
import org.briarproject.api.system.SeedProvider;
public class TestSeedProvider implements SeedProvider {
private final Random random = new Random();
public byte[] getSeed() {
byte[] seed = new byte[32];
random.nextBytes(seed);
return seed;
}
}
| biddyweb/briar | briar-tests/src/org/briarproject/TestSeedProvider.java | Java | gpl-3.0 | 309 |
<h1 id="0">0 目录</h1>
* [1 内存相关](#1)
* [2 数据类型](#2)
* [3 函数](#3)
* [4 面向对象](#4)
* [5 编程](#5)
<h1 id="1">1 内存相关</h1>
<h2 id="1.1">1.1 new、delete、malloc、free关系</h2>
1. 属性
malloc与free是C++/C语言标准库的函数,new/delete是C++的运算符(即关键字)。
2. 参数
使用new操作符申请内存分配时无须指定内存块的大小,编译器会根据类型信息自行计算。而malloc则需要显式地指出内存的大小。
3. 返回类型
new申请内存分配成功时,返回的是对象类型的指针,类型严格与对象匹配,无须进行类型转换,故new是符合类型安全性的操作符。 而malloc内存分配成功则是返回 *void \** ,需要通过强制类型转换将 *void \** 指针转换成我们需要的类型。
4. 分配失败
new内存分配失败时,会抛出bac_alloc异常。malloc分配内存失败时返回NULL。
5. 自定义类型
*new* 会先调用 *operator new* 函数,申请足够的内存(通常底层使用 *malloc* 实现)。 然后调用类型的构造函数, 初始化成员变量, 最后返回自定义类型指针。*delete*先调用析构函数,然后调用 *operator delete* 函数释放内存(通常底层使用 *free*实现)。
*malloc/free*是库函数,只能动态地申请和释放内存,无法强制要求其做自定义类型对象构造和析构工作。
6. 重载
C++允许重载 *new/delete* 操作符,特别的,*placement new*的就不需要为对象分配内存,而是指定了一个地址作为内存起始区域,*new*在这段内存上为对象调用构造函数完成初始化工作,并返回此地址。而 *malloc*不允许重载
7. 内存区域
*new*操作符从自由存储区(free store)上为对象动态分配内存空间,而 *malloc*函数从堆上动态分配内存。自由存储区是C++基于new操作符的一个抽象概念,凡是通过new操作符进行内存申请,该内存即为自由存储区。而堆是操作系统中的术语,是操作系统所维护的一块特殊内存,用于程序的内存动态分配,C语言使用*malloc*从堆上分配内存, 使用*free*释放已分配的对应内存。自由存储区不等于堆,如上所述,布局new就可以不位于堆中。
> PS: 在C++中,内存区分为5个区,分别是堆、栈、自由存储区、全局/静态存储区、常量存储区;
>
> 在C中,C内存区分为堆、栈、全局/静态存储区、常量存储区;
>
> new缺省的实现方式本质上是通过malloc的,这个时候,C++的自由存储区的概念和C的堆的概念是没有区别的, 但是, 如果我们通过重载operator new的方式把内存分配在一些全局变量上,那么这些内存就不属于堆区了,而是在data segment。也就是说,C++的自由存储区可以包括堆区,也可以包括其他区域。
<h2 id="1.2">1.2 为什么new/delete、new[]/delete[]要配对使用?</h2>
因为它们在调用构造函数和析构函数的时候不同。带有[]的表达式因为需要多分配4个字节,因为析构时需要知道对象的个数。所以它们的执行方式是不同的,必须配套使用。
对于内建简单数据类型,delete和delete[]功能是相同的。对于自定义的复杂数据类型,delete和delete[]不能互用。delete[]删除一个数组,delete删除一个指针。简单来说,用new分配的内存用delete删除;用new[]分配的内存用delete[]删除。delete[]会调用数组元素的析构函数。内部数据类型没有析构函数,所以问题不大。如果你在用delete时没用括号,delete就会认为指向的是单个对象,否则,它就会认为指向的是一个数组。
<h2 id="1.3">1.3 如何将程序跳转到指定内存地址?</h2>
要对绝对地址0x100000赋值,我们可以用 *(unsigned int\*)0x100000 = 1234*;那么要是想让程序跳转到绝对地址是 *0x100000*去执行,应该怎么做?
*((void (*)( ))0x100000 ) ();
首先要将0x100000强制转换成函数指针,即:
(void (*)())0x100000
然后再调用它:
*((void (*)())0x100000)();
用typedef可以看得更直观些:
typedef void(*)() voidFuncPtr;
*((voidFuncPtr)0x100000)();
<h2 id="1.4">1.4 描述内存分配方式以及他们的区别</h2>
1. 堆
亦称动态内存分配。程序在运行的时候用malloc 或new 申请任意多少的内存,程序员自己负责在何时用free 或delete 释放内存。动态内存的生存期由程序员决定,使用非常灵活,但问题也最多。
2. 栈
在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈由于是编译器自动管理的,所以栈内的对象不会存在内存泄露问题。
3. 常量区
存放常量字符串,程序结束后由系统释放
4. 静态变量区
内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在。例如全局变量,static 变量。
<h2 id="1.5">1.5 栈内存与文字常量区</h2>
代码如下:
char str1[] = "abc";
char str2[] = "abc";
const char str3[] = "abc";
const char str4[] = "abc";
const char *str5 = "abc";
const char *str6 = "abc";
char *str7 = "abc";
char *str8 = "abc";
cout << ( str1 == str2 ) << endl;//0 分别指向各自的栈内存
cout << ( str3 == str4 ) << endl;//0 分别指向各自的栈内存
cout << ( str5 == str6 ) << endl;//1指向文字常量区地址相同
cout << ( str7 == str8 ) << endl;//1指向文字常量区地址相同
结果是:*0 0 1 1*
解答:*str1,str2,str3,str4*是数组变量,它们有各自的内存空间;而 *str5,str6,str7,str8*是指针,它们指向相同的常量区域。
---
<h1 id="2">2 数据类型</h1>
<h2 id="2.1">2.1 结构和联合有何区别?</h2>
1. 结构和联合都是由多个不同的数据类型成员组成, 但在任何同一时刻, 联合中只存放了一个被选中的成员(所有成员共用一块地址空间), 而结构的所有成员都存在(不同成员的存放地址不同)。
2. 对于联合的不同成员赋值, 将会对其它成员重写, 原来成员的值就不存在了, 而对于结构的不同成员赋值是互不影响的
<h2 id="2.2">2.2 请说出const与#define 相比,有何优点?</h2>
const作用:定义常量、修饰函数参数、修饰函数返回值三个作用。被Const修饰的东西都受到强制保护,可以预防意外的变动,能提高程序的健壮性。
1. const 常量有数据类型,而宏常量没有数据类型。编译器可以对前者进行类型安全检查。而对后者只进行字符替换,没有类型安全检查,并且在字符替换可能会产生意料不到的错误。
2. 有些集成化的调试工具可以对const 常量进行调试,但是不能对宏常量进行调试。
<h2 id="2.2">2.2 简述数组与指针的区别?</h2>
C/C++程序中,指针和数组在不少地方可以相互替换着用,让人产生一种错觉,以为两者是等价的。
数组要么在静态存储区被创建(如全局数组),要么在栈上被创建。数组名对应着(而不是指向)一块内存,其地址与容量在生命期内保持不变,只有数组的内容可以改变。
指针可以随时指向任意类型的内存块,它的特征是“可变”,所以我们常用指针来操作动态内存。指针远比数组灵活,但也更危险。
下面以字符串为例比较指针与数组的特性。
1. 修改内容上的差别
示例1中,字符数组a的容量是6个字符,其内容为 *hello\0*。a的内容可以改变,如 *a[0] = ‘X’*。指针p指向常量字符串“world”(位于静态存储区,内容为 *world\0*),常量字符串的内容是不可以被修改的。从语法上看,编译器并不觉得语句 *p[0]= ‘X’*有什么不妥,但是该语句企图修改常量字符串的内容而导致运行错误。
char a[] = “hello”;
a[0] = 'X';
char *p = 'world'; // 注意p 指向常量字符串
p[0] = 'X'; // 编译器不能发现该错误,运行时错误
2. 内容复制与比较
不能对数组名进行直接复制与比较。示例2中,若想把数组a的内容复制给数组b,不能用语句 b = a ,否则将产生编译错误。应该用标准库函数strcpy进行复制。同理,比较b和a的内容是否相同,不能用if(b==a) 来判断,应该用标准库函数strcmp进行比较。
语句p = a 并不能把a的内容复制指针p,而是把a的地址赋给了p。要想复制a的内容,可以先用库函数malloc为p申请一块容量为strlen(a)+1个字符的内存,再用strcpy进行字符串复制。同理,语句if(p==a) 比较的不是内容而是地址,应该用库函数strcmp来比较。
// 数组…
char a[] = "hello";
char b[10];
strcpy(b, a); // 不能用 b = a;
if(strcmp(b, a) == 0) // 不能用 if (b == a)
3. 用运算符sizeof 可以计算出数组的容量(字节数)。sizeof(p),p 为指针得到的是一个指针变量的字节数,而不是p 所指的内存容量。C++/C 语言没有办法知道指针所指的内存容量,除非在申请内存时记住它。注意当数组作为函数的参数进行传递时,该数组自动退化为同类型的指针。
char a[] = "hello world";
char *p = a;
cout<< sizeof(a) << endl; // 12 字节
cout<< sizeof(p) << endl; // 4 字节
// 计算数组和指针的内存容量
void Func(char a[100])
{
cout<< sizeof(a) << endl; // 4 字节而不是100 字节
}
<h2 id="2.3">2.3 int id[sizeof(unsigned long)];这个对吗?为什么?</h2>
正确 这个 sizeof是编译时运算符,编译时就确定了 ,可以看成和机器有关的常量。
---
<h1 id="3">3 函数</h1>
<h2 id="3.1">3.1 函数传递参数时,指针和引用的区别</h2>
指针传递参数本质上还是 **值传递** 方式,它所传递的是一个地址值。值传递的过程中,被调函数的形参作为局部变量处理,即在函数分配的栈中分配内存空间,存放主调函数传递进来的实参值,从而形成了一个实参的副本。值传递的特点就是,被调函数对形参的处理都是对实参的一份拷贝进行处理,不会影响主调函数中实参的值。
引用传递参数过程中,被调函数的形参也作为局部变量在栈中开辟了存储空间。但是这时存放的是主调函数的实参的地址。被调函数对形参的任何操作都被处理成间接寻址,即通过栈中存放的地址访问主调函数中的实参变量(根据别名找到主调函数中的本体)。因此,被调函数对形参的任何操作都会影响到主调函数中的实参变量。
引用传递和指针传递是不同的,虽然他们都是在被调函数栈空间上的一个局部变量,但是任何对于引用参数的处理都会通过一个间接寻址的方式操作到主调函数中的相关变量。而对于指针传递的参数,如果改变被调函数中的指针地址,它将应用不到主调函数的相关变量。如果想通过指针参数传递来改变主调函数中的相关变量(地址),那就得使用指向指针的指针或者指针引用。
从编译的角度来讲,程序在编译时分别将指针和引用添加到符号表上,符号表中记录的是变量名及变量所对应地址。指针变量在符号表上对应的地址值为指针变量的地址值,而引用在符号表上对应的地址值为引用对象的地址值(与实参名字不同,地址相同)。符号表生成之后就不会再改,因此指针可以改变其指向的对象(指针变量中的值可以改),而引用对象则不能修改。
**总结**
1. 相同点:
都是地址的概念
2. 不同点:
1. 指针是一个实体(替身);引用只是一个别名(本体的另一个名字)
2. 引用只能在定义时被初始化一次,之后不可改变,即“从一而终”;指针可以修改,即“见异思迁”;
3. 引用不能为空(有本体,才有别名);指针可以为空;
4. sizeof 引用,得到的是所指向变量的大小;sizeof 指针,得到的是指针的大小;
5. 指针 ++,是指指针的地址自增;引用++是指所指变量自增;
6. 引用是类型安全的,引用过程会进行类型检查;指针不会进行安全检查;
<h2 id="3.2">3.2 在什么时候需要"常引用"</h2>
如果既要利用引用提高程序的效率,又要保护传递给函数的数据不在函数中被改变,就应使用常引用。常引用声明方式:const 类型标识符 &引用名=目标变量名;
例1
int a ;
const int &ra=a;
ra=1; //错误
a=1; //正确
例2
string foo( );
void bar(string & s);
那么下面的表达式将是非法的:
bar(foo( ));
bar("hello world");
原因在于foo( )和"hello world"串都会产生一个临时对象,而在C++中,这些临时对象都是const类型的(也就是说,都是右值类型,转变为 *non-const* 引用是不可以的)。因此上面的表达式就是试图将一个const类型的对象转换为非const类型,这是非法的。引用型参数应该在能被定义为const的情况下,尽量定义为const 。这儿的代码如果想要不报错,*void bar(string & s);* 修改为 *void bar(const string & s);* 即可。
<h2 id="3.3">3.3 将"引用"作为函数返回值类型的格式、好处和需要遵守的规则?</h2>
1. 语法
type-specifier & funtion(parameter-list) {// function body}
2. 优势
在内存中不产生返回值的副本;(注意:正是因为这一点,所以返回一个局部变量的引用是不可取的。因为随着该局部变量生存周期的结束,相应的引用也会失效,产生运行时错误。
3. 注意事项
(1). 不能返回局部变量的副本。主要原因是局部变量会在函数返回后被销毁,因此被返回的引用就成了"无所指"的引用,程序会进入未知状态
(2). 不能返回函数内部new分配的内存的引用。虽然不存在局部变量的被动销毁问题,可对于这种情况(返回函数内部new分配内存的引用),又面临其它尴尬局面。例如,被函数返回的引用只是作为一个临时变量出现,而没有被赋予一个实际的变量,那么这个引用所指向的空间(由new分配)就无法释放,造成memory leak。
(3). 可以返回类成员的引用,但最好是const。主要原因是当对象的属性是与某种业务规则(business rule)相关联的时候,其赋值常常与某些其它属性或者对象的状态有关,因此有必要将赋值操作封装在一个业务规则当中。如果其它对象可以获得该属性的非常量引用(或指针),那么对该属性的单纯赋值就会破坏业务规则的完整性。
(4). 流操作符重载返回值申明为“引用”的作用:
流操作符<<和>>,这两个操作符常常希望被连续使用,例如:cout << "hello" << endl; 因此这两个操作符的返回值应该是一个仍然支持这两个操作符的流引用。可选的其它方案包括:返回一个流对象和返回一个流对象指针。但是对于返回一个流对象,程序必须重新(拷贝)构造一个新的流对象,也就是说,连续的两个<<操作符实际上是针对不同对象的!这无法让人接受。对于返回一个流指针则不能连续使用<<操作符。因此,返回一个流对象引用是惟一选择。这个唯一选择很关键,它说明了引用的重要性以及无可替代性,也许这就是C++语言中引入引用这个概念的原因吧。
赋值操作符=。这个操作符象流操作符一样,是可以连续使用的,例如:x = j = 10;或者(x=10)=100;赋值操作符的返回值必须是一个左值,以便可以被继续赋值。因此引用成了这个操作符的惟一返回值选择。
查看下面代码:
#include<iostream.h>
int error = -1;
int vals[10];
int& put(int n)
{
if ( n >= 0 && n <= 9)
return vals[n];
else
{
cout << "subscript error";
return error;
}
}
int main(void)
{
// test the put() function
cout << vals[0] << endl;
cout << vals[9] << endl;
put(0)=10; //以put(0)函数值作为左值,等价于vals[0]=10;
put(9)=20; //以put(9)函数值作为左值,等价于vals[9]=20;
cout << vals[0] << endl;
cout << vals[9] << endl;
return 0;
}
<h2 id="3.4">3.4 int (*s[10])(int) 表示的是什么?</h2>
*int (\*s[10])(int)* 函数指针数组,每个指针指向一个int func(int param)的函数。
<h2 id="3.5">3.5 复杂声明</h2>
void *(*(* fp1)(int))[10];
float (*(* fp2)(int,int,int))(int);
int (*(* fp3)())[10]();
分别表示什么意思?
1. fp1是一个指针,指向一个函数,这个函数的参数为int型,函数的返回值是一个指针,这个指针指向一个数组,这个数组有10个元素,每个元素是一个void*型指针。
2.
---
<h1 id="4">4 面向对象</h1>
<h2 id="4.1">4.1 C++有哪些性质(面向对象特点)</h2>
封装,继承和多态。
<h2 id="4.2">4.2 子类析构时要调用父类的析构函数吗?</h2>
析构函数调用的次序是先派生类的析构后基类的析构,也就是说在基类的的析构调用的时候,派生类的信息已经全部销毁了。定义一个对象时先调用基类的构造函数、然后调用派生类的构造函数。
<h2 id="4.3">4.3 多态,虚函数,纯虚函数</h2>
1. 多态
是对于不同对象接收相同消息时产生不同的动作。C++的多态性具体体现在运行和编译两个方面:在程序运行时的多态性通过继承和虚函数来体现;在程序编译时多态性体现在函数和运算符的重载上;
2. 虚函数
在基类中冠以关键字 *virtual* 的成员函数。 它提供了一种接口界面。允许在派生类中对基类的虚函数重新定义。
3. 纯虚函数的作用
在基类中为其派生类保留一个函数的名字,以便派生类根据需要对它进行定义。作为接口而存在 纯虚函数不具备函数的功能, 一般不能直接被调用。
从基类继承来的纯虚函数,在派生类中仍是虚函数。如果一个类中至少有一个纯虚函数,那么这个类被称为抽象类(abstract class)。
抽象类中不仅包括纯虚函数,也可包括虚函数。抽象类必须用作派生其他类的基类,而不能用于直接创建对象实例。但仍可使用指向抽象类的指针支持运行时多态性。
<h2 id="4.4">4.4 重载(overload)和重写(override)的区别</h2>
常考的题目。从定义上来说:
1. 重载:
是指允许存在多个同名的函数,而这些函数的参数表不同(或许参数个数不同,或许参数类型不同,或许两者都不同)
2. 重写:
是指子类重新定义父类虚函数的方法。
从实现原理上说:
1. 重载:
编译器根据函数不同的参数表,对同名函数的名称作修饰,然后这些同名函数就成了不同的函数(至少对于编译器来说是这样的)。比如,有2个同名函数:
function func(p: integer):integer;
function func(p: string):integer;
那么,编译器做过修饰后的函数名称可能是这样的:
int_func 和 str_func
对于这两个函数的调用,在编译期间就已经确定了,是静态的。也就是说,它们的地址在编译期就绑定了,因此,重载是在编译期间的多态。
2. 重写:
与程序的运行时多态相关。当子类重新定义了父类的虚函数后,父类指针根据赋给它的不同的子类指针,动态的调用属于子类的该函数,这样的函数调用在编译期间是无法确定的(调用的子类的虚函数的地址无法给出)。因此,这样的函数地址是在运行期绑定的(晚绑定)。
<h2 id="4.5">4.5 有哪几种情况只能用intialization list而不能用assignment?</h2>
当类中含有const、reference成员变量时;基类的构造函数需要初始化列表。
<h2 id="4.6">4.6 C++是不是类型安全的?</h2>
不是。两个不同类型的指针之间可以强制转换(用reinterpret cast)。C#是类型安全的。
<h2 id="4.7">4.7 main 函数执行以前,还会执行什么代码?</h2>
答案:全局对象的构造函数会在main 函数之前执行。
---
<h1 id="5">5 编程题</h1>
<h2 id="5.1">5.1 获取一个整数中的bit位为1的个数(微软)</h2>
int func(x)
{
int countx = 0;
while(x)
{
countx ++;
x = x & (x-1);
}
return countx;
}
假定 *x = 9999*。 答案:*8*
<h2 id="5.2">5.2 左值引用作为函数的返回值</h2>
int a=4;
int& f( int x )
{
a = a+x;
return a;
}
int main(void)
{
int t=5;
cout << f(t) << endl; // -> a = 9
f(t) = 20; // -> a = 20
cout << f(t) << endl; // t = 5,a = 20 -> a = 25
t = f(t); // -> a = 30 t = 30
cout << f(t) << endl; // -> a = 60
}
<h2 id="5.3">5.3 分别写出BOOL,int,float,指针类型的变量a 与“零”的比较语句</h2>
1. bool
if (!a) 或 if (a)
2. int
if (0 == a)
3. float
const EXPRESSION EXP = 0.000001
if ( a < EXP && a >-EXP)
4. pointer
if ( a != NULL) or if(a == NULL)
<h1 id="2">2 网络</h1>
<h1 id="2.1">2.1 TCP模型,状态迁移</h1>
TCP/IP四层网络模型:
1. **链路层(数据链路层和物理层)**:包括操作系统中的设备驱动程序、计算机中对应的网络接口卡
2. **网络层**:处理分组在网络中的活动,比如分组的选路
3. **运输层**:主要为两台主机上的应用提供端到端的通信
4. **应用层**:负责处理特定的应用程序细节
假设在一个局域网(LAN)如以太网中有两台主机,二者运行FTP协议:
| tupelo-shen/my_test | doc/C++/C++面试/C++面试题.md | Markdown | gpl-3.0 | 22,877 |
# Copyright (C) 2012 Aaron Krebs akrebs@ualberta.ca
# 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/>
from django.views.generic.simple import direct_to_template
from django.contrib.auth import views as auth_views
from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse_lazy
from registration.views import register
urlpatterns = patterns('',
# urls for simple one-step registration
url(r'^register/$',
register,
{'backend': 'registration.backends.simple.SimpleBackend',
'template_name': 'registration/registration_form.hamlpy',
},
name='registration_register'
),
url(r'^register/closed/$',
direct_to_template,
{'template': 'registration/registration_closed.hamlpy'},
name='registration_disallowed'
),
url(r'^login/$',
auth_views.login,
{'template_name': 'registration/login.hamlpy'},
name='auth_login'
),
url(r'^logout/$',
auth_views.logout,
{'template_name': 'registration/logout.hamlpy'},
name='auth_logout'
),
url(r'^password/change/$',
auth_views.password_change,
{'template_name': 'registration/password_change_form.hamlpy',
# ugh, this is tied to the namespace; needs to be namespace-agnostic
# since the namspace is determined by the importing app
# TODO: see Issue #1
'post_change_redirect': reverse_lazy('registration:auth_password_change_done')
},
name='auth_password_change'
),
url(r'^password/change/done/$',
auth_views.password_change_done,
{'template_name': 'registration/password_change_done.hamlpy'},
name='auth_password_change_done'
),
url(r'^password/reset/$',
auth_views.password_reset,
{'template_name': 'registration/password_reset_form.hamlpy',
# same issue as above
'post_reset_redirect': reverse_lazy('registration:auth_password_reset_done'),
'email_template_name': 'registration/password_reset_email.hamlpy',
'subject_template_name': 'registration/password_reset_subject.hamlpy',
},
name='auth_password_reset'
),
url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
auth_views.password_reset_confirm,
{'template_name': 'registration/password_reset_confirm.hamlpy',
# same issue as above
'post_reset_redirect': reverse_lazy('registration:auth_password_reset_complete'),
},
name='auth_password_reset_confirm'
),
url(r'^password/reset/complete/$',
auth_views.password_reset_complete,
{'template_name': 'registration/password_reset_complete.hamlpy'},
name='auth_password_reset_complete'
),
url(r'^password/reset/done/$',
auth_views.password_reset_done,
{'template_name': 'registration/password_reset_done.hamlpy'},
name='auth_password_reset_done'
),
)
| a-krebs/finances | finances/django_registration/urls.py | Python | gpl-3.0 | 3,598 |
#pragma once
#include <deque>
#include "DataCell.hh"
namespace cadabra {
/// \ingroup clientserver
///
/// Abstract base class with methods that need to be implemented
/// by any GUI. You need to derive from this class as well as from
/// the DocumentThread class.
class GUIBase {
public:
/// The basic manipulations that a GUI needs to implement are
/// adding, removing and updating (refreshing the display of)
/// a cell. The code in DocumentThread will call these to make
/// the GUI update its display. Called on the document thread.
virtual void update_cell(const DTree&, DTree::iterator)=0;
/// Remove a single cell together with all its child cells.
/// Some toolkits (e.g. Gtk) will take care of that entire
/// child tree removal automatically, in which case the only
/// thing that needs done for the child cells is to remove
/// any reference to their VisualCells.
virtual void remove_cell(const DTree&, DTree::iterator)=0;
/// Remove all GUI cells from the display (used as a quick way
/// to clear all before loading a new document).
virtual void remove_all_cells()=0;
/// Add a GUI cell corresponding to the document cell at the
/// iterator. The GUI needs to figure out from the location of
/// this cell in the DTree where to insert the cell in the visual
/// display. If the 'visible' flag is false, hide the cell from
/// view independent of whether its hidden flag is set (this
/// is only used when constructing a document on load time and
/// we do not want to show cells until they have all been added
/// to the document).
virtual void add_cell(const DTree&, DTree::iterator, bool visible)=0;
/// Position the cursor in the current canvas in the widget
/// corresponding to the indicated cell.
virtual void position_cursor(const DTree&, DTree::iterator, int)=0;
/// Retrieve the position of the cursor in the current cell.
virtual size_t get_cursor_position(const DTree&, DTree::iterator)=0;
/// Network status is propagated from the ComputeThread to the
/// GUI using the following methods. These get called on the
/// compute thread (as opposed to the functions above, which get
/// called on the gui thread).
//@{
virtual void on_connect()=0;
virtual void on_disconnect(const std::string& reason)=0;
virtual void on_network_error()=0;
virtual void on_kernel_runstatus(bool)=0;
//@}
/// When the ComputeThread needs to modify the document, it
/// stores an ActionBase object on the stack (see the
/// DocumenThread class) and then wakes up the GUI thread
/// signalling it to process this action. The following member
/// should wake up the GUI thread and make it enter the
/// processing part.
virtual void process_data()=0;
};
};
| kpeeters/cadabra2 | client_server/GUIBase.hh | C++ | gpl-3.0 | 2,829 |
#include "ui/font.h"
#include <cstdint>
namespace Font
{
const uint8_t fontData[] =
{
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x50,0x00,0x00,0x00,
0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x20,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x00,0x20,0x50,0x50,0x20,0x48,0x20,0x20,0x10,0x40,0x00,
0x00,0x00,0x00,0x00,0x08,0x70,0x20,0x70,0x70,0x08,0xf8,0x70,0xf8,0x70,0x70,0x00,0x00,0x00,0x00,0x00,
0x70,0x70,0x70,0xf0,0x70,0xe0,0xf8,0xf8,0x70,0x88,0x70,0x38,0x88,0x80,0x88,0x88,0x70,0xf0,0x70,0xf0,
0x70,0xf8,0x88,0x88,0x88,0x88,0x88,0xf8,0x70,0x40,0x70,0x50,0x00,0x00,0x00,0x80,0x00,0x08,0x00,0x18,
0x00,0x80,0x20,0x08,0x40,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,
0x18,0x20,0x60,0xa8,0x0c,0x20,0x50,0x50,0x70,0xa8,0x50,0x20,0x20,0x20,0x00,0x00,0x00,0x00,0x00,0x08,
0x88,0x60,0x88,0x88,0x18,0x80,0x80,0x08,0x88,0x88,0x00,0x00,0x08,0x00,0x40,0x88,0x88,0x88,0x88,0x88,
0x90,0x80,0x80,0x88,0x88,0x20,0x10,0x90,0x80,0xd8,0x88,0x88,0x88,0x88,0x88,0x88,0x20,0x88,0x88,0x88,
0x88,0x88,0x08,0x40,0x40,0x10,0x88,0x00,0x00,0x00,0x80,0x00,0x08,0x00,0x20,0x00,0x80,0x00,0x00,0x40,
0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x10,0x90,0x0c,
0x20,0x00,0xf8,0xa8,0x50,0x50,0x00,0x40,0x10,0x50,0x20,0x00,0x00,0x00,0x10,0x98,0x20,0x88,0x08,0x28,
0x80,0x80,0x08,0x88,0x88,0x20,0x20,0x10,0xf8,0x20,0x88,0x98,0x88,0x88,0x80,0x88,0x80,0x80,0x80,0x88,
0x20,0x10,0xa0,0x80,0xa8,0xc8,0x88,0x88,0x88,0x88,0x80,0x20,0x88,0x88,0x88,0x50,0x50,0x10,0x40,0x20,
0x10,0x00,0x00,0x00,0x70,0xf0,0x70,0x78,0x70,0x70,0x78,0xf0,0x60,0x18,0x48,0x20,0xf0,0xf0,0x70,0xf0,
0x78,0xb8,0x78,0x70,0x88,0x88,0x88,0x88,0x88,0xf8,0x20,0x20,0x10,0x00,0x18,0x20,0x00,0x50,0xa0,0x10,
0x20,0x00,0x40,0x10,0x20,0x20,0x00,0x00,0x00,0x10,0xa8,0x20,0x08,0x30,0x48,0xf0,0xf0,0x10,0x70,0x88,
0x20,0x20,0x20,0x00,0x10,0x10,0xa8,0x88,0xf0,0x80,0x88,0xf0,0xf0,0x80,0xf8,0x20,0x10,0xc0,0x80,0xa8,
0xa8,0x88,0x88,0x88,0x88,0x70,0x20,0x88,0x50,0x88,0x20,0x50,0x20,0x40,0x20,0x10,0x00,0x00,0x00,0x08,
0x88,0x88,0x88,0x88,0x20,0x88,0x88,0x20,0x08,0x50,0x20,0xa8,0x88,0x88,0x88,0x88,0xc0,0x80,0x20,0x88,
0x88,0x88,0x50,0x88,0x10,0x40,0x20,0x08,0x00,0xd8,0x20,0x00,0x50,0x70,0x20,0x68,0x00,0x40,0x10,0xf8,
0xf8,0x00,0xf8,0x00,0x20,0xc8,0x20,0x10,0x08,0x88,0x08,0x88,0x10,0x88,0x78,0x00,0x00,0x40,0x00,0x08,
0x20,0xa8,0xf8,0x88,0x80,0x88,0x80,0x80,0xb8,0x88,0x20,0x10,0xc0,0x80,0x88,0x98,0x88,0xf0,0x88,0xf0,
0x08,0x20,0x88,0x50,0xa8,0x20,0x20,0x40,0x40,0x10,0x10,0x00,0x00,0x00,0x78,0x88,0x80,0x88,0xf8,0x20,
0x88,0x88,0x20,0x08,0x60,0x20,0xa8,0x88,0x88,0x88,0x88,0x80,0x70,0x20,0x88,0x50,0xa8,0x20,0x88,0x20,
0x20,0x20,0x10,0x00,0xf0,0x00,0x00,0xf8,0x28,0x28,0x90,0x00,0x40,0x10,0x20,0x20,0x00,0x00,0x00,0x20,
0x88,0x20,0x20,0x08,0xf8,0x08,0x88,0x20,0x88,0x08,0x00,0x00,0x20,0xf8,0x10,0x00,0x98,0x88,0x88,0x80,
0x88,0x80,0x80,0x88,0x88,0x20,0x90,0xa0,0x80,0x88,0x88,0x88,0x80,0x88,0xa0,0x08,0x20,0x88,0x50,0xa8,
0x50,0x20,0x80,0x40,0x10,0x10,0x00,0x00,0x00,0x88,0x88,0x80,0x88,0x80,0x20,0x88,0x88,0x20,0x08,0x60,
0x20,0xa8,0x88,0x88,0x88,0x88,0x80,0x08,0x20,0x88,0x50,0xa8,0x20,0x88,0x40,0x20,0x20,0x10,0x00,0x70,
0x20,0x00,0x50,0xa8,0x54,0x90,0x00,0x20,0x20,0x50,0x20,0x20,0x00,0x20,0x40,0x88,0x20,0x40,0x88,0x08,
0x88,0x88,0x20,0x88,0x08,0x20,0x20,0x10,0x00,0x20,0x20,0x80,0x88,0x88,0x88,0x90,0x80,0x80,0x88,0x88,
0x20,0x90,0x90,0x80,0x88,0x88,0x88,0x80,0xa8,0x90,0x88,0x20,0x88,0x20,0xd8,0x88,0x20,0x80,0x40,0x08,
0x10,0x00,0x00,0x00,0x88,0x88,0x88,0x88,0x80,0x20,0x88,0x88,0x20,0x08,0x50,0x20,0xa8,0x88,0x88,0x88,
0x88,0x80,0x08,0x20,0x88,0x20,0xa8,0x50,0x88,0x80,0x20,0x20,0x10,0x00,0x60,0x20,0x00,0x50,0x70,0x48,
0x68,0x00,0x10,0x40,0x00,0x00,0x20,0x00,0x20,0x40,0x70,0x70,0xf8,0x70,0x08,0x70,0x70,0x20,0x70,0x70,
0x20,0x20,0x08,0x00,0x40,0x20,0x78,0x88,0xf0,0x70,0xe0,0xf8,0x80,0x70,0x88,0x70,0x60,0x88,0xf8,0x88,
0x88,0x70,0x80,0x70,0x88,0x70,0x20,0x70,0x20,0x88,0x88,0x20,0xf8,0x70,0x08,0x70,0x00,0x00,0x00,0x78,
0xf0,0x70,0x78,0x78,0x20,0x78,0x88,0x70,0x08,0x48,0x70,0xa8,0x88,0x70,0xf0,0x78,0x80,0xf0,0x18,0x78,
0x20,0x70,0x88,0x78,0xf8,0x18,0x20,0x60,0x00,0x60,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x08,0x00,0x00,0x48,0x00,0x00,0x00,0x00,0x00,0x80,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x30,0x00,
0x00,0x00,0x00,0x00,0x80,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,
};
}
| parsnip42/kitchensink-firmware | libraries/kitchensink-core/src/ui/font.cpp | C++ | gpl-3.0 | 6,080 |
############################################
# [config.py]
# CONFIGURATION SETTINGS FOR A PARTICULAR METER
#
#
# Set the long-form name of this meter
name = "*PEAK only"
#
# [Do not remove or uncomment the following line]
Cs={}
############################################
############################################
# STRUCTURE PARAMETERS
#
# Parameters subject to conscious control by the poet. Kiparsky & Hanson (1996)
# call these "formally independent of phonological structure." By contrast,
# "realization parameters"--e.g., the size of a metrical position, which positions
# are regulated, and other constraints--"determine the way the structure is
# linguistically manifested, and are dependent on the prosodic givens of languge."
#
#
####
# [Number of feet in a line]
#
#Cs['number_feet!=2'] = 1 # require dimeter
#Cs['number_feet!=3'] = 1 # require trimeter
#Cs['number_feet!=4'] = 1 # require tetrameter
#Cs['number_feet!=5'] = 1 # require pentameter
#Cs['number_feet!=6'] = 1 # require hexameter
#Cs['number_feet!=7'] = 1 # require heptameter
#
#
####
# [Headedness of the line]
#
#Cs['headedness!=falling'] = 1 # require a falling rhythm (e.g. trochaic, dactylic)
#Cs['headedness!=rising'] = 1 # require a rising rhythm (e.g., iambic, anapestic)
#
############################################
############################################
# REALIZATION PARAMETERS
#
# All subsequent constraints can be seen as "realization parameters."
# See note to "structure parameters" above for more information.
#
#############################################
# METRICAL PARSING: POSITION SIZE
#
# Select how many syllables are at least *possible* in strong or weak positions
# cf. Kiparsky & Hanson's "position size" parameter ("Parametric Theory" 1996)
#
#
######
# [Maximum position size]
#
# The maximum number of syllables allowed in strong metrical positions (i.e. "s")
maxS=2
#
# The maximum number of syllables allowed in weak metrical positions (i.e. "w")
maxW=2
#
#
######
# [Minimum position size]
#
# (Recommended) Positions are at minimum one syllable in size
splitheavies=0
#
# (Unrecommended) Allow positions to be as small as a single mora
# i.e. (a split heavy syllable can straddle two metrical positions)
#splitheavies=1
############################################
############################################
# METRICAL PARSING: METRICAL CONSTRAINTS
#
# Here you can configure the constraints used by the metrical parser.
# Each constraint is expressed in the form:
# Cs['(constraint name)']=(constraint weight)
# Constraint weights do not affect harmonic bounding (i.e. which parses
# survive as possibilities), but they do affect how those possibilities
# are sorted to select the "best" parse.
#
#
######
# [Constraints regulating the 'STRENGTH' of a syllable]
#
# A syllable is strong if it is a peak in a polysyllabic word:
# the syllables in 'liberty', stressed-unstressed-unstressed,
# are, in terms of *strength*, strong-weak-neutral, because
# the first syllable is more stressed than its neighbor;
# the second syllable less stressed; and the third equally stressed.
#
###
# [Stricter versions:]
#
# A strong metrical position should not contain any weak syllables ("troughs"):
#Cs['strength.s=>-u']=1
#
# A weak metrical position may not contain any strong syllables ("peaks"):
# [Kiparsky and Hanson believe this is Shakespeare's meter]
Cs['strength.w=>-p']=1
#
###
# [Laxer versions:]
#
# A strong metrical position should contain at least one strong syllable:
#Cs['strength.s=>p']=3
#
# A weak metrical position should contain at least one weak syllable:
#Cs['strength.w=>u']=3
#
#
#
######
# [Constraints regulating the STRESS of a syllable]
#
###
# [Stricter versions:]
#
# A strong metrical position should not contain any unstressed syllables:
# [Kiparsky and Hanson believe this is Hopkins' meter]
#Cs['stress.s=>-u']=1
#
# A weak metrical position should not contain any stressed syllables:
#Cs['stress.w=>-p']=1
#
###
# [Laxer versions:]
#
# A strong metrical position should contain at least one stressed syllable:
#Cs['stress.s=>p']=2
#
# A weak metrical position must contain at least one unstressed syllable;
#Cs['stress.w=>u']=2
#
#
#
######
# [Constraints regulating the WEIGHT of a syllable]
#
# The weight of a syllable is its "quantity": short or long.
# These constraints are designed for "quantitative verse",
# as for example in classical Latin and Greek poetry.
#
###
# [Stricter versions:]
#
# A strong metrical position should not contain any light syllables:
#Cs['weight.s=>-u']=2
#
# A weak metrical position should not contain any heavy syllables:
#Cs['weight.w=>-p']=2
#
###
# [Laxer versions:]
#
# A strong metrical position should contain at least one heavy syllable:
#Cs['weight.s=>p']=2
#
# A weak metrical position must contain at least one light syllable;
#Cs['weight.w=>u']=2
#
#
#
######
# [Constraints regulating what's permissible as a DISYLLABIC metrical position]
# [(with thanks to Sam Bowman, who programmed many of these constraints)]
#
###
# [Based on weight:]
#
# A disyllabic metrical position should not contain more than a minimal foot:
# i.e. W-resolution requires first syllable to be light and unstressed.
Cs['footmin-w-resolution']=1
#
#
# A disyllabic metrical position should not contain more than a minimal foot:
# (i.e. allowed positions are syllables weighted light-light or light-heavy)
#Cs['footmin-noHX']=1000
#
#
# A disyllabic STRONG metrical position should not contain more than a minimal foot:
# (i.e. allowed positions are syllables weighted light-light or light-heavy)
#Cs['footmin-s-noHX']=1
#
# A disyllabic metrical position should be syllables weighted light-light:
#Cs['footmin-noLH-noHX']=1
#
###
# [Categorical:]
#
# A metrical position should not contain more than one syllable:
# [use to discourage disyllabic positions]
#Cs['footmin-none']=1
#
# A strong metrical position should not contain more than one syllable:
#Cs['footmin-no-s']=1
#
# A weak metrical position should not contain more than one syllable:
#Cs['footmin-no-w']=1
#
# A metrical position should not contain more than one syllable,
# *unless* that metrical position is the *first* or *second* in the line:
# [use to discourage disyllabic positions, but not trochaic inversions,
# or an initial "extrametrical" syllable]
#Cs['footmin-none-unless-in-first-two-positions']=1
#
# A metrical position should not contain more than one syllable,
# *unless* that metrical position is the *second* in the line:
# [use to discourage disyllabic positions, but not trochaic inversions]
#Cs['footmin-none-unless-in-second-position']=1
#
# A strong metrical position should not contain more than one syllable,
# *unless* it is preceded by a disyllabic *weak* metrical position:
# [use to implement the metrical pattern described by Derek Attridge,
# in The Rhythms of English Poetry (1982), and commented on by Bruce Hayes
# in his review of the book in Language 60.1 (1984).
# e.g. Shakespeare's "when.your|SWEET.IS|ue.your|SWEET.FORM|should|BEAR"
# [this implementation is different in that it only takes into account
# double-weak beats *preceding* -- due to the way in which the parser
# throws away bounded parses as it goes, it might not be possible for now
# to write a constraint referencing future positions]
#Cs['footmin-no-s-unless-preceded-by-ww']=10
# [The version that does reference future positions; but appears to be unstable]:
#Cs['attridge-ss-not-by-ww']=10
#
###
# [For disyllabic positions crossing a word boundary...
# (i.e. having two syllables, each from a different word)...
#
# ...allow only F-resolutions:
# (both words must be function words and be in a weak metrical position)
Cs['footmin-f-resolution']=1
#
# ...it should never cross a word boundary to begin with:
#Cs['footmin-wordbound']=1000
#
# ...both words should be function words:
#Cs['footmin-wordbound-bothnotfw']=1
#
# ...at least one word should be a function word:
#Cs['footmin-wordbound-neitherfw']=1
#
# ...the left-hand syllable should be a function-word:
#Cs['footmin-wordbound-leftfw']=1
#
# ...the right-hand syllable should be a function word:
#Cs['footmin-wordbound-rightfw']=1
#
# ...neither word should be a monosyllable:
#Cs['footmin-wordbound-nomono']=1
#
# ...neither word should be a LEXICAL monosyllable
# (i.e. function words and polysyllabic words ok)
#Cs['footmin-wordbound-lexmono']=1
###
# [Miscellaneous constraints relating to disyllabic positions]
#
# A disyllabic metrical position may contain a strong syllable
# of a lexical word only if the syllable is (i) light and
# (ii) followed within the same position by an unstressed
# syllable normally belonging to the same word.
# [written by Sam Bowman]
#Cs['footmin-strongconstraint']=1
#
# The final metrical position of the line should not be 'ww'
# [use to encourage "...LI|ber|TY" rather than "...LI|ber.ty"]
#Cs['posthoc-no-final-ww']=2
#
# The final metrical position of the line should not be 'w' or 'ww'
#Cs['posthoc-no-final-w']=2
#
# A line should have all 'ww' or all 'w':
# It works by:
# Nw = Number of weak positions in the line
# Mw = Maximum number of occurrences of 'w' metrical position
# Mww = Maximum number of occurrences of 'ww' metrical position
# M = Whichever is bigger, Mw or Mww
# V = Nw - M
# Violation Score = V * [Weight]
# [use to encourage consistency of meter across line]
# [feel free to make this a decimal number, like 0.25]
#Cs['posthoc-standardize-weakpos']=1
#
#
#
######
# [MISCELLANEOUS constraints]
#
# A function word can fall only in a weak position:
#Cs['functiontow']=2
#
# An initial syllable must be in a weak position:
#Cs['initialstrong']=2
#
# The first metrical position will not be evaluated
# for any of the strength/stress/weight correspondence constraints:
# [set to 1 to be true]
#Cs['extrametrical-first-pos']=1
#
# The first two metrical positions will not be evaluated
# for any of the strength/stress/weight correspondence constraints:
# [set to 1 to be true]
Cs['skip_initial_foot']=1
#
# A word should not be an elision [use to discourage elisions]:
#Cs['word-elision']=1
#
# A weak metrical position should not contain any syllables
# that are stressed and heavy: [Meter of Finnish "Kalevala"]
#Cs['kalevala.w=>-p']=1
#
# A strong metrical position should not contain any syllables
# that are stressed and light: [Meter of Finnish "Kalevala"]
#Cs['kalevala.s=>-u']=1
############################################
| quadrismegistus/prosodic | meters/strength_and_resolution.py | Python | gpl-3.0 | 10,457 |
#!/usr/bin/env python
from gnuradio import gr, gr_unittest
from gnuradio import blocks
import grdab
class qa_measure_processing_rate(gr_unittest.TestCase):
"""
@brief QA for measure processing rate sink.
This class implements a test bench to verify the corresponding C++ class.
"""
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_001_measure_processing_rate(self):
src = blocks.null_source(gr.sizeof_gr_complex)
throttle = blocks.throttle(gr.sizeof_gr_complex, 1000000)
head = blocks.head(gr.sizeof_gr_complex, 200000)
sink = grdab.measure_processing_rate(gr.sizeof_gr_complex,100000)
self.tb.connect(src, throttle, head, sink)
self.tb.run()
rate = sink.processing_rate()
assert(rate > 900000 and rate < 1100000)
def test_002_measure_processing_rate(self):
src = blocks.null_source(gr.sizeof_char)
throttle = blocks.throttle(gr.sizeof_char, 10000000)
head = blocks.head(gr.sizeof_char, 1000000)
sink = grdab.measure_processing_rate(gr.sizeof_char,1000000)
self.tb.connect(src, throttle, head, sink)
self.tb.run()
rate = sink.processing_rate()
assert(rate > 8000000 and rate < 12000000)
if __name__ == '__main__':
gr_unittest.main()
| andrmuel/gr-dab | python/qa/qa_measure_processing_rate.py | Python | gpl-3.0 | 1,233 |
/* -----------------------------------------------------------------------------
project : XOS-Shop, open source e-commerce system
http://www.xos-shop.com
template : xos-shop_install_default_v1.0.7
version : 1.0.7 for XOS-Shop version 1.0.9
filename : stylesheet.css
author : Hanspeter Zeller <hpz@xos-shop.com>
copyright : Copyright (c) 2007 Hanspeter Zeller
license : This file is part of XOS-Shop.
XOS-Shop 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.
XOS-Shop 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 XOS-Shop. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------------- */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
td, ul, p, body {
font-family: Verdana, Arial, sans-serif;
font-size: 11px;
line-height: 1.5;
}
input {
font: 12px verdana, arial, helvetica;
}
#spacer {
height: 40%;
width: 100px;
margin-bottom: -262px;
float: left;
}
#content {
height: 60%;
max-width: 1250px;
clear: left;
}
body { font-family:Verdana, Arial, Helvetica, sans-serif;
background-color: #FFFFFF;
margin: 0 auto 0 auto;
max-width: 1300px;
}
tr.logo-head {
background-color: #ff7c2a;
}
td.nav-head {
color: #ffffff;
text-decoration: none;
font-size: 10px;
font-weight: bold;
}
tr.main {
background-color: #000000;
color: #ff7c2a;
}
td.smallText {
font-size: 10px;
color: #000000;
}
.mainContent {
font-size: 10px;
color: #fffc53;
}
.pageTitle {
font-size: 11px;
line-height: 1.5;
font-weight: bold;
text-decoration: underline;
}
.longDescription {
visibility: hidden;
display: none;
}
.smallDesc {
font-size: 9px;
line-height: 1.5;
}
.boxMe {
font-size: 12px;
color: #ff0000;
background-color: #e5e5e5;
border: 5px solid #e5e5e5;
}
.noteBox {
font-size: 11px;
line-height: 1.5;
color: #ff0000;
background-color: #fef3da;
border: thin dashed;
padding: 6px;
}
.infoBoxHeading {
font-size: 12px;
color: #ffffff;
font-weight: bold;
background-color: #FF7C2A;
border: 1px solid #FF7C2A;
}
.infoBox {
font-size: 10px;
color: #000000;
background-color: #D9D9D9;
border: 1px solid #FF7C2A
}
.infoBoxContent {
font-size: 10px;
color: #000000;
}
a:link, a:visited {
color: #000000;
text-decoration: none;
}
a:hover {
color: #ff7c2a;
text-decoration: none;
}
a.nav-head:link, a.nav-head:visited {
color: #ffffff;
text-decoration: none;
}
a.nav-head:hover {
color: #fffc53;
text-decoration: none;
}
| XOS-Shop/xos_shop_system | shop/install/templates/xos-shop_install_default_v1.0.7/stylesheet.css | CSS | gpl-3.0 | 3,327 |
"use strict";
/*global define, templates, socket, ajaxify, app, admin, bootbox, utils, config */
define('admin/manage/groups', [
'translator',
'components'
], function(translator, components) {
var Groups = {};
var intervalId = 0;
Groups.init = function() {
var createModal = $('#create-modal'),
createGroupName = $('#create-group-name'),
createModalGo = $('#create-modal-go'),
createModalError = $('#create-modal-error');
handleSearch();
createModal.on('keypress', function(e) {
if (e.keyCode === 13) {
createModalGo.click();
}
});
$('#create').on('click', function() {
createModal.modal('show');
setTimeout(function() {
createGroupName.focus();
}, 250);
});
createModalGo.on('click', function() {
var submitObj = {
name: createGroupName.val(),
description: $('#create-group-desc').val()
},
errorText;
socket.emit('admin.groups.create', submitObj, function(err) {
if (err) {
if (err.hasOwnProperty('message') && utils.hasLanguageKey(err.message)) {
translator.translate(err.message, config.defaultLang, function(translated) {
createModalError.html(translated).removeClass('hide');
});
} else {
createModalError.html('<strong>Uh-Oh</strong><p>There was a problem creating your group. Please try again later!</p>').removeClass('hide');
}
} else {
createModalError.addClass('hide');
createGroupName.val('');
createModal.on('hidden.bs.modal', function() {
ajaxify.refresh();
});
createModal.modal('hide');
}
});
});
$('.groups-list').on('click', 'button[data-action]', function() {
var el = $(this),
action = el.attr('data-action'),
groupName = el.parents('tr[data-groupname]').attr('data-groupname');
switch (action) {
case 'delete':
bootbox.confirm('Are you sure you wish to delete this group?', function(confirm) {
if (confirm) {
socket.emit('groups.delete', {
groupName: groupName
}, function(err, data) {
if(err) {
return app.alertError(err.message);
}
ajaxify.refresh();
});
}
});
break;
}
});
};
function handleSearch() {
function doSearch() {
if (!queryEl.val()) {
return ajaxify.refresh();
}
$('.pagination').addClass('hide');
var groupsEl = $('.groups-list');
socket.emit('groups.search', {
query: queryEl.val(),
options: {
sort: 'date'
}
}, function(err, groups) {
if (err) {
return app.alertError(err.message);
}
templates.parse('admin/manage/groups', 'groups', {
groups: groups
}, function(html) {
groupsEl.find('[data-groupname]').remove();
groupsEl.find('tr').after(html);
});
});
}
var queryEl = $('#group-search');
queryEl.on('keyup', function() {
if (intervalId) {
clearTimeout(intervalId);
intervalId = 0;
}
intervalId = setTimeout(doSearch, 200);
});
}
return Groups;
});
| seafruit/NodeBB | public/src/admin/manage/groups.js | JavaScript | gpl-3.0 | 2,982 |
/*
* mnote
*
* Copyright (C) 2010 Aurimas Cernius
* Copyright (C) 2009 Debarshi Ray
* Copyright (C) 2009 Hubert Figuiere
*
* 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/>.
*/
#ifndef __ADDINMANAGER_HPP__
#define __ADDINMANAGER_HPP__
#include <list>
#include <map>
#include <string>
#include <sigc++/signal.h>
#include "sharp/modulemanager.hpp"
#include "note.hpp"
#include "noteaddin.hpp"
#include "importaddin.hpp"
namespace mnote {
class ApplicationAddin;
class PreferenceTabAddin;
class AddinPreferenceFactoryBase;
class AddinManager
{
public:
AddinManager(const std::string & conf_dir);
~AddinManager();
void add_note_addin_info(const sharp::DynamicModule * dmod);
void erase_note_addin_info(const sharp::DynamicModule * dmod);
std::string & get_prefs_dir()
{
return m_addins_prefs_dir;
}
void load_addins_for_note(const Note::Ptr &);
ApplicationAddin * get_application_addin(const std::string & id)
const;
void get_preference_tab_addins(std::list<PreferenceTabAddin *> &) const;
void get_import_addins(std::list<ImportAddin*> &) const;
void initialize_application_addins() const;
void shutdown_application_addins() const;
void save_addins_prefs() const;
const sharp::ModuleList & get_modules() const
{
return m_module_manager.get_modules();
}
Gtk::Widget * create_addin_preference_widget(const std::string & id);
sigc::signal<void> & signal_application_addin_list_changed();
private:
void initialize_sharp_addins();
void migrate_addins(const std::string & old_addins_dir);
const std::string m_mnote_conf_dir;
std::string m_addins_prefs_dir;
std::string m_addins_prefs_file;
sharp::ModuleManager m_module_manager;
std::list<sharp::IfaceFactoryBase*> m_builtin_ifaces;
/// Key = TypeExtensionNode.Id
typedef std::map<std::string, ApplicationAddin*> AppAddinMap;
AppAddinMap m_app_addins;
typedef std::map<std::string, NoteAddin *> IdAddinMap;
typedef std::map<Note::Ptr, IdAddinMap> NoteAddinMap;
NoteAddinMap m_note_addins;
/// Key = TypeExtensionNode.Id
/// the iface factory is not owned by the manager.
/// TODO: make sure it is removed if the dynamic module is unloaded.
typedef std::map<std::string, sharp::IfaceFactoryBase*> IdInfoMap;
IdInfoMap m_note_addin_infos;
typedef std::map<std::string, PreferenceTabAddin*> IdPrefTabAddinMap;
IdPrefTabAddinMap m_pref_tab_addins;
typedef std::map<std::string, ImportAddin *> IdImportAddinMap;
IdImportAddinMap m_import_addins;
typedef std::map<std::string, AddinPreferenceFactoryBase*> IdAddinPrefsMap;
IdAddinPrefsMap m_addin_prefs;
sigc::signal<void> m_application_addin_list_changed;
};
}
#endif
| gfunkmonk2/mate-note | src/addinmanager.hpp | C++ | gpl-3.0 | 3,503 |
// MAUS WARNING: THIS IS LEGACY CODE.
/* This file is part of MAUS: http://micewww.pp.rl.ac.uk/projects/maus
*
* MAUS 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.
*
* MAUS 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 MAUS. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "CLHEP/Units/PhysicalConstants.h"
#include "gsl/gsl_sf_gamma.h"
#include "gsl/gsl_sf_pow_int.h"
#include "gsl/gsl_odeiv.h"
#include "gsl/gsl_errno.h"
#include "BeamTools/BTMultipole.hh"
#include "Utils/Exception.hh"
#include "Utils/Squeak.hh"
const BTMultipole * BTMultipole::staticMultipole = NULL;
double BTMultipole::staticDX = 0.;
double BTMultipole::_relativeError = 1.e-5;
double BTMultipole::_absoluteError = 1.e-5;
double BTMultipole::_stepSize = 1.;
BTMultipole::BTMultipole()
: _pole(0), _magnitude(0.), _length(0.), _rCurv(0.),
_height(0.), _width(0.), _curvature(constant),
_endFieldModel(NULL) {
}
void BTMultipole::Init(int pole, double fieldAtWidth,
double length, double height, double width,
std::string curvature, double radiusVariable,
const EndFieldModel* endfield, int endPole) {
_pole = pole;
_magnitude = fieldAtWidth;
_length = length;
_rCurv = radiusVariable;
_height = height;
_width = width;
_curvature = constant;
_endFieldPole = endPole;
_endFieldModel = NULL;
if (endfield != NULL) _endFieldModel = endfield->Clone();
if (curvature == "MomentumBased") {
_curvature = momentumBased;
_momentum = radiusVariable;
_rCurv = 0;
_magnitude = 1.;
SetupDipoleMagnitude(radiusVariable, fieldAtWidth);
SetupReferenceTrajectory();
} else {
if (fabs(radiusVariable) < 1e-5 || curvature == "Straight") {
_curvature = straight;
} else {
if (curvature == "StraightEnds") _curvature = straightEnds;
if (curvature == "Constant" || curvature == "") _curvature = constant;
if (_width >= fabs(_rCurv))
throw(MAUS::Exceptions::Exception(MAUS::Exceptions::nonRecoverable,
"Multipole with width > radius of curvature",
"BTMultipole::BTMultipole"));
if (_length > fabs(2*pi*_rCurv))
throw(MAUS::Exceptions::Exception(MAUS::Exceptions::nonRecoverable,
"Multipole with bending angle > 360 degrees",
"BTMultipole::BTMultipole"));
_endRotation = CLHEP::HepRotation(CLHEP::Hep3Vector(0, 1, 0),
_length/_rCurv);
_endPoint = _endRotation*CLHEP::Hep3Vector(-_rCurv, 0, 0)+
CLHEP::Hep3Vector(_rCurv, 0, 0);
}
}
// BUG - this should be as strict as EndFieldValue
// note that the EndFieldValue uses _width/2, _height/2, _length; so
// EndFieldValue is factor 2 more strict than BB in each dimension;
bbMin[0] = -_width;
bbMax[0] = +_width;
bbMin[1] = -_height;
bbMax[1] = +_height;
bbMin[2] = 0.;
bbMax[2] = _length*2.;
if (_curvature != straight) {
// length of the segment with curvature == _rCurv; always longer than the
// equivalent box
double phi = _length*2/_rCurv;
if (phi > pi/2)
phi = pi/2;
bbMax[2] = (_rCurv+_width)*sin(phi);
bbMin[0] = -(_rCurv - (_rCurv-_width)*cos(phi));
}
}
BTMultipole BTMultipole::DipoleFromMomentum
(double momentum, double length, double angle, double height, double width) {
// field = theta p / (qL)
// rcurv = l / theta
double field = (2*pi*angle/360.)*momentum/length/CLHEP::eplus/c_light;
double rCurv = length*360./(2*pi*angle); // L = 2 pi r*(theta/360)
BTMultipole m;
m.Init(1, field, length, height, width, "constant", rCurv, NULL, 0);
return m;
}
CLHEP::Hep3Vector BTMultipole::TransformToRotated(const double * Point) const {
switch (_curvature) {
case straight:
return CLHEP::Hep3Vector(Point[0], Point[1], Point[2]);
case constant:
return TransformToRotatedConstant(Point);
case straightEnds:
return TransformToRotatedStraightEnds(Point);
case momentumBased:
return TransformToRotatedMomentumBased(Point);
default:
throw(MAUS::Exceptions::Exception(MAUS::Exceptions::nonRecoverable,
"Did not recognise curvature model",
"BTMultipole::TransformToRotated(const double*)"));
}
}
CLHEP::Hep3Vector BTMultipole::TransformToRotatedMomentumBased
(const double point[3]) const {
int p0 = 0;
int p1 = _refX.size()-1;
double rSquaredStart = (point[0]-_refX[p0])*(point[0]-_refX[p0]) +
(point[2]-_refZ[p0])*(point[2]-_refZ[p0]);
double rSquaredEnd = (point[0]-_refX[p1])*(point[0]-_refX[p1]) +
(point[2]-_refZ[p1])*(point[2]-_refZ[p1]);
// This is horrid!!! Minimise rSquared (using binary interpolation) to find
// s(x,z) Assumes sign(B) == const st dRSquared is always increasing or
// decreasing
while (unsigned(p1-p0)>1) {
int pM = (p1+p0)/2;
double rSquaredMiddle = (point[0]-_refX[pM])*(point[0]-_refX[pM]) +
(point[2]-_refZ[pM])*(point[2]-_refZ[pM]);
if (rSquaredStart > rSquaredEnd) {
rSquaredStart = rSquaredMiddle;
p0 = pM;
} else {
rSquaredEnd = rSquaredMiddle;
p1 = pM;
}
}
double deltaR = sqrt(rSquaredStart);
if (point[0]-_refX[p0] > 0.) deltaR *= -1;
double deltaS = _refS[p0];
return CLHEP::Hep3Vector(deltaR, point[1], deltaS);
}
CLHEP::Hep3Vector BTMultipole::TransformToRotatedConstant
(const double * Point) const {
double dx = Point[0];
double x = dx+_rCurv; // x in coordinates relative to centre of rotation
double z = Point[2];
double q = atan2(z, x);
double deltaS = q*_rCurv;
double deltaR = sqrt(x*x+z*z)-_rCurv;
return CLHEP::Hep3Vector(deltaR, Point[1], deltaS);
}
CLHEP::Hep3Vector BTMultipole::TransformToRotatedStraightEnds
(const double * Point) const {
if (Point[2] < 0.5*(_length-_centreLength))
return CLHEP::Hep3Vector(Point[0], Point[1], Point[2]);
double pos[3] = {Point[0], Point[1], Point[2]-0.5*(_length-_centreLength)};
CLHEP::Hep3Vector trans = TransformToRotatedConstant(pos);
if (trans[2] > _centreLength)
trans = _endRotation*(trans-_endPoint)+_endPoint;
trans[2] += 0.5*(_length-_centreLength);
return trans;
}
double BTMultipole::RadiusOfCurvature(double sRelativeToEnd) const {
switch (_curvature) {
case straight:
return 0;
case constant:
return _rCurv;
case straightEnds:
if (sRelativeToEnd > 0.) {
return 0;
} else {
return _rCurv;
}
case momentumBased: {
double EMfield[3] = {0, 0, 0};
GetFieldValueRotated(CLHEP::Hep3Vector(0, 0, sRelativeToEnd), EMfield);
return _momentum/EMfield[1]/CLHEP::eplus/CLHEP::c_light;
}
default:
throw(MAUS::Exceptions::Exception(MAUS::Exceptions::nonRecoverable,
"Did not recognise curvature model",
"BTMultipole::RadiusOfCurvature(double)"));
}
}
void BTMultipole::TransformToRectangular
(const double point[3], double* value) const {
switch (_curvature) {
case straight:
return;
case constant:
return TransformToRectangularConstant(point, value);
case straightEnds:
return TransformToRectangularStraightEnds(point, value);
case momentumBased:
return TransformToRectangularMomentumBased(point, value);
default:
throw(MAUS::Exceptions::Exception(MAUS::Exceptions::nonRecoverable,
"Did not recognise curvature model",
"BTMultipole::TransformToRectangular(const double*, double*)"));
}
}
void BTMultipole::TransformToRectangularConstant
(const double point[3], double* value) const {
double theta = atan2(point[2], point[0]+_rCurv);
double bx = value[2]*sin(theta) + value[0]*cos(theta);
double bz = value[2]*cos(theta) + value[0]*sin(theta);
value[0] = bx;
value[2] = bz;
}
void BTMultipole::TransformToRectangularStraightEnds
(const double point[3], double* value) const {
if (point[2] < 0) return;
double theta = 0;
if (point[2] > _endPoint[2])
theta = _endRotation.delta();
else
theta = atan2(point[2], point[0]+_rCurv);
double bx = value[2]*sin(theta) + value[0]*cos(theta);
double bz = value[2]*cos(theta) + value[0]*sin(theta);
value[0] = bx;
value[2] = bz;
}
void BTMultipole::TransformToRectangularMomentumBased
(const double point[3], double* value) const {
int step = static_cast<int>(point[2]/_stepSize)+1;
double theta = 0;
if (step > static_cast<int>(_angle.size())) theta = _angle.back();
else if (step > 0) theta = _angle[step];
double bx = value[2]*sin(theta) + value[0]*cos(theta);
double bz = value[2]*cos(theta) + value[0]*sin(theta);
value[0] = bx;
value[2] = bz;
}
void BTMultipole::GetFieldValueRotated
(CLHEP::Hep3Vector pos, double *EMfield) const {
if (_endFieldModel == NULL) {
HardEdgedFieldValue(pos, EMfield);
return;
}
EndFieldValue(pos, EMfield);
}
void BTMultipole::GetFieldValue
(const double Point[4], double *EMfield) const {
CLHEP::Hep3Vector pos = TransformToRotated(Point);
GetFieldValueRotated(pos, EMfield);
TransformToRectangular(Point, EMfield);
return;
}
// pos is the position from the radius of curvature arc relative to the centre
// of the multipole - units?
void BTMultipole::HardEdgedFieldValue
(CLHEP::Hep3Vector pos, double *field) const {
if (pos.z() < 0. || pos.z() > _length) return;
if (fabs(pos.x()) > _width/2.) return;
if (fabs(pos.y()) > _height/2.) return;
for (int m = 1; m <= _pole; m+=2) {
double alpha = GetConst(0, _pole, m);
if (_pole-m-1 >= 0.)
field[0] += alpha*((_pole-m)*gsl_sf_pow_int(pos.x(), _pole-m-1)*
gsl_sf_pow_int(pos.y(), m));
if (m-1 >= 0. && _pole-m >= 0.)
field[1] += alpha*((m)*gsl_sf_pow_int(pos.x(), _pole-m)*
gsl_sf_pow_int(pos.y(), m-1));
// hard edge => bz=0
}
for (int i = 0; i < 3; ++i) field[i] *= _magnitude;
}
double BTMultipole::GetConst(int q, int n, int m) {
return gsl_sf_pow_int(gsl_sf_fact(n), 2)*gsl_sf_pow_int(-1, (m-1)/2)/(
gsl_sf_pow_int(-4, q)*gsl_sf_fact(q)*gsl_sf_fact(n+q)*gsl_sf_fact(m)
*gsl_sf_fact(n-m))/static_cast<double>(n);
}
void BTMultipole::EndFieldValue(CLHEP::Hep3Vector pos, double *field) const {
if (pos.z() < 0. || pos.z() > _length) return;
if (fabs(pos.y()) > _height/2.) return;
pos[2] -= _length/2.;
int n(_pole);
const double x = pos[0];
const double y = pos[1];
const double z = pos[2];
for (int q = 0; q <= _endFieldPole; ++q) {
double f = _endFieldModel->Function(z, 2*q);
double fPrime = _endFieldModel->Function(z, 2*q+1);
for (int m = 1; m <= n; m += 2) {
double const_qnm = GetConst(q, n, m);
if ( q > 0 )
field[0] += const_qnm*f*(2.*q*x*gsl_sf_pow_int((x*x+y*y), q-1)
*gsl_sf_pow_int(x, n-m)*gsl_sf_pow_int(y, m));
if (n-m > 0)
field[0] += const_qnm*f*(n-m)*gsl_sf_pow_int((x*x+y*y), q)
*gsl_sf_pow_int(x, n-m-1)*gsl_sf_pow_int(y, m);
if (m > 0)
field[1] += const_qnm*f*m*gsl_sf_pow_int(x*x+y*y, q)
*gsl_sf_pow_int(x, n-m)*gsl_sf_pow_int(y, m-1);
if (q > 0)
field[1] += const_qnm*f*2*q*y*gsl_sf_pow_int(x*x+y*y, q-1)
*gsl_sf_pow_int(x, n-m)*gsl_sf_pow_int(y, m);
field[2] += const_qnm*fPrime*gsl_sf_pow_int(x*x+y*y, q)
*gsl_sf_pow_int(x, n-m)*gsl_sf_pow_int(y, m);
}
}
for (int i = 0; i < 3; ++i) field[i] *= _magnitude;
}
void BTMultipole::Print(std::ostream &out) const {
out << "Multipole Order: " << 2*_pole << " Length: " << _length
<< " Magnitude: " << _magnitude << " BendingRadius: " << _rCurv
<< " Height: " << _height << " Width: " << _width << " EndField: ";
if (_endFieldModel == NULL)
out << "HardEdged";
else
_endFieldModel->Print(out);
BTField::Print(out);
}
void BTMultipole::SetupReferenceTrajectory() {
_angle = _refX = _refS = _refZ = std::vector<double>();
staticMultipole = this;
const gsl_odeiv_step_type* T = gsl_odeiv_step_rk4;
gsl_odeiv_step* stepper = gsl_odeiv_step_alloc(T, 4);
gsl_odeiv_control* control = gsl_odeiv_control_y_new(_absoluteError,
_relativeError);
gsl_odeiv_evolve* evolve = gsl_odeiv_evolve_alloc(4);
gsl_odeiv_system system = {EvolveReferenceTrajectory, NULL, 4, NULL};
double h = 0.1;
double s = 0.;
double y[4] = {0, 0, 0, _momentum};
for (double sMax = s; sMax <= _length; sMax += _stepSize) {
while (s < sMax) {
int status = gsl_odeiv_evolve_apply(evolve, control, stepper, &system,
&s, sMax, &h, y);
if (status != GSL_SUCCESS) {
Print(MAUS::Squeak::mout(MAUS::Squeak::debug));
throw(MAUS::Exceptions::Exception(MAUS::Exceptions::nonRecoverable,
"Error calculating reference trajectory",
"BTMultipole::SetupReferenceTrajectory()"));
}
_refS.push_back(s);
_refX.push_back(y[0]);
_refZ.push_back(y[1]);
_angle.push_back(atan(y[2]/y[3]));
}
}
gsl_odeiv_evolve_free(evolve);
gsl_odeiv_control_free(control);
gsl_odeiv_step_free(stepper);
staticMultipole = NULL;
}
double BTMultipole::IntegralB(double dxOffset) const {
staticMultipole = this;
staticDX = dxOffset;
const gsl_odeiv_step_type * T = gsl_odeiv_step_rk4;
gsl_odeiv_step * stepper = gsl_odeiv_step_alloc(T, 1);
gsl_odeiv_control * control = gsl_odeiv_control_y_new(_absoluteError,
_relativeError);
gsl_odeiv_evolve * evolve = gsl_odeiv_evolve_alloc(1);
gsl_odeiv_system system = {EvolveIntegralB, NULL, 1, NULL};
double h = 10.;
double s = 0.;
double y[1] = {0};
int step = 0;
while (s < _length) {
if (step > 10000) {
MAUS::Squeak::mout(MAUS::Squeak::warning) << "Stepper stuck while calculating "
<< "BTMultipole Effective Length"
<< std::endl;
return 0.;
}
int status = gsl_odeiv_evolve_apply(evolve, control, stepper, &system, &s,
_length, &h, y);
if (status != GSL_SUCCESS) {
Print(MAUS::Squeak::mout(MAUS::Squeak::debug));
throw(MAUS::Exceptions::Exception(MAUS::Exceptions::nonRecoverable,
"Error integrating reference By",
"BTMultipole::SetupMagnitude()"));
}
step++;
h = 10.;
}
gsl_odeiv_evolve_free(evolve);
gsl_odeiv_control_free(control);
gsl_odeiv_step_free(stepper);
staticMultipole = NULL;
return y[0];
}
void BTMultipole::SetupDipoleMagnitude(double momentum, double angleInRadians) {
double intB = IntegralB(0.); // integral B dl [T mm]
double theta = CLHEP::eplus*c_light/momentum*intB;
_magnitude = angleInRadians/theta;
}
int BTMultipole::EvolveReferenceTrajectory
(double s, const double y[], double f[], void *params) {
double bfield[3] = {0, 0, 0};
staticMultipole->GetFieldValueRotated(CLHEP::Hep3Vector(0, 0, s), bfield);
f[0] = y[2]/staticMultipole->_momentum; // dx/ds = px/ps
f[1] = y[3]/staticMultipole->_momentum; // dz/ds = pz/ps
f[2] = -CLHEP::eplus*c_light*f[1]*bfield[1]; // dpx/ds = -q*c*dz/ds*by
f[3] = CLHEP::eplus*c_light*f[0]*bfield[1]; // dpz/ds = q*c*dx/ds*by
return GSL_SUCCESS;
}
int BTMultipole::EvolveIntegralB
(double s, const double y[], double f[], void *params) {
double bfield[3] = {0, 0, 0};
staticMultipole->GetFieldValueRotated(Hep3Vector(staticDX, 0, s), bfield);
f[0] = bfield[1];
return GSL_SUCCESS;
}
void BTMultipole::GetReferenceTrajectory(std::vector<double>& x,
std::vector<double>& z, std::vector<double>& angle,
std::vector<double>& s) {
x = _refX;
z = _refZ;
angle = _angle;
s = _refS;
}
void BTMultipole::SetReferenceTrajectory(std::vector<double> x,
std::vector<double> z, std::vector<double> angle,
std::vector<double> s) {
_refX = x;
_refZ = z;
_refS = s;
_angle = angle;
}
| mice-software/maus | src/legacy/BeamTools/BTMultipole.cc | C++ | gpl-3.0 | 17,495 |
#include<string.h>
#include<idt.h>
/* This exists in 'bootstrap.{s|asm}', and is used to load our IDT */
extern void idt_load();
/* Declare an IDT of IDT_TABLE_SIZE entries. */
struct idt_entry idt[IDT_TABLE_SIZE];
struct idt_ptr idt_p;
/* Use this function to set an entry in the IDT. */
void idt_set_gate(uint8_t num, uint32_t base, uint16_t sel, uint8_t flags)
{
/* The interrupt routine's base address */
idt[num].base_lo = (base & 0xFFFF);
idt[num].base_hi = (base >> 16) & 0xFFFF;
/* The segment or 'selector' that this IDT entry will use
* is set here, along with any access flags */
idt[num].sel = sel;
idt[num].always0 = 0;
idt[num].flags = flags;
}
/* Installs the IDT */
void idt_install()
{
/* Sets the special IDT pointer up, just like in 'gdt.c' */
idt_p.limit = (sizeof (struct idt_entry) * IDT_TABLE_SIZE) - 1;
idt_p.base = (uint32_t)&idt;
/* Clear out the entire IDT, initializing it to zeros */
memset(&idt, 0, sizeof(struct idt_entry) * IDT_TABLE_SIZE);
/* Add any new ISRs to the IDT here using idt_set_gate */
/* Points the processor's internal register to the new IDT */
idt_load();
}
| neal024/Okusha | src/idt.c | C | gpl-3.0 | 1,185 |
/*
Copyright (C) 2014-2016 de4dot@gmail.com
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.Windows.Controls;
namespace dnSpy.Language.Intellisense {
sealed partial class SignatureHelpPresenterControl : UserControl {
public SignatureHelpPresenterControl() {
InitializeComponent();
}
}
}
| MeteorAdminz/dnSpy | dnSpy/dnSpy/Language/Intellisense/SignatureHelpPresenterControl.xaml.cs | C# | gpl-3.0 | 937 |
using System;
using System.Globalization;
using System.Linq;
using System.Windows.Controls;
using NETworkManager.Settings;
namespace NETworkManager.Validators
{
public class IsDNSLookupDNSServersNameUnique : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
return SettingsManager.Current.DNSLookup_DNSServers.Any(x => string.Equals(x.Name, value as string, StringComparison.OrdinalIgnoreCase)) ? new ValidationResult(false, Localization.Resources.Strings.DNSServerWithThisNameAlreadyExists) : ValidationResult.ValidResult;
}
}
}
| BornToBeRoot/NETworkManager | Source/NETworkManager.Validators/IsDNSLookupDNSServersNameUnique.cs | C# | gpl-3.0 | 632 |
# Copyright (C) 2010-2018 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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.
#
# ESPResSo 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/>.
import numpy as np
import unittest as ut
import espressomd
import espressomd.electrostatics
import espressomd.interactions
from espressomd import drude_helpers
class Drude(ut.TestCase):
@ut.skipIf(not espressomd.has_features("P3M", "THOLE", "LANGEVIN_PER_PARTICLE"), "Test needs P3M, THOLE and LANGEVIN_PER_PARTICLE")
def test(self):
"""
Sets up a BMIM PF6 pair separated in y-direction with fixed cores.
Adds the Drude particles and related features (intramolecular exclusion bonds, Thole screening)
via helper functions.
Calculates the induced dipole moment and the diagonals of the polarization tensor
and compares against reference results, which where reproduced with LAMMPS.
"""
box_l = 50
system = espressomd.System(box_l=[box_l, box_l, box_l])
system.seed = system.cell_system.get_state()['n_nodes'] * [12]
np.random.seed(12)
#Reference Results, reproduced with LAMMPS
#Dipole Moments
ref_mu0_pf6 = [0.00177594, 0.16480996, -0.01605161]
ref_mu0_c1 = [0.00076652, 0.15238767, 0.00135291]
ref_mu0_c2 = [-0.00020222, 0.11084197, 0.00135842]
ref_mu0_c3 = [0.00059177, 0.23949626, -0.05238468]
ref_mu0_bmim = [0.00115606, 0.5027259, -0.04967335]
#Polarisation Tensor diagonals
ref_pol_pf6 = [
4.5535698335873445, 4.7558611769477697, 4.5546580162000554]
ref_pol_bmim = [
13.126868394164262, 14.392582501485913, 16.824150151623762]
#TIMESTEP
fs_to_md_time = 1.0e-2
time_step_fs = 0.5
time_step_ns = time_step_fs * 1e-6
dt = time_step_fs * fs_to_md_time
#COM TEMPERATURE
#Global thermostat temperature, for com and langevin.
#LangevinPerParticle temperature is set to 0 for drude and core to properly account for com forces.
# Like that, langevin thermostat can still be used for non-drude
# particles
SI_temperature = 300.0
gamma_com = 1.0
kb_kjmol = 0.0083145
temperature_com = SI_temperature * kb_kjmol
# COULOMB PREFACTOR (elementary charge)^2 / (4*pi*epsilon_0) in
# Angstrom * kJ/mol
coulomb_prefactor = 1.67101e5 * kb_kjmol
#POLARIZATION
#polarization = 1.0 #In (Angstrom^3)_CGS
# alpha_SI = 4*Pi*eps_0 alpha_CGS;
# 4*Pi*epsilon_0*Angstrom^3/((elementary charge)^2*Angstrom^2*N_A/kJ)
conv_pol_CGS_SI = 7.197586e-4
#alpha = conv_pol_CGS_SI*args.polarization
#DRUDE/TOTAL MASS
#lamoureux03 used values 0.1-0.8 g/mol for drude mass
mass_drude = 0.8
mass_tot = 100.0
mass_core = mass_tot - mass_drude
mass_red_drude = mass_drude * mass_core / mass_tot
#SPRING CONSTANT DRUDE
#Used 1000kcal/mol/A^2 from lamoureux03a table 1 p 3031
k_drude = 4184.0
# in kJ/mol/A^2
T_spring = 2.0 * np.pi * np.sqrt(mass_drude / k_drude)
#T_spring_fs = T_spring/fs_to_md_time
#Period of free oscillation: T_spring = 2Pi/w; w = sqrt(k_d/m_d)
#TEMP DRUDE
# Used T* = 1K from lamoureux03a p 3031 (2) 'Cold drude oscillators
# regime'
SI_temperature_drude = 1.0
temperature_drude = SI_temperature_drude * kb_kjmol
#GAMMA DRUDE
#Thermostat relaxation time should be similar to T_spring
gamma_drude = mass_red_drude / T_spring
system.cell_system.skin = 0.4
system.time_step = dt
#Forcefield
types = {"PF6": 0, "BMIM_C1": 1, "BMIM_C2": 2, "BMIM_C3":
3, "BMIM_COM": 4, "PF6_D": 5, "BMIM_C1_D": 6, "BMIM_C2_D": 7, "BMIM_C3_D": 8}
charges = {"PF6": -0.78, "BMIM_C1": 0.4374,
"BMIM_C2": 0.1578, "BMIM_C3": 0.1848, "BMIM_COM": 0}
polarizations = {"PF6": 4.653, "BMIM_C1":
5.693, "BMIM_C2": 2.103, "BMIM_C3": 7.409}
masses = {"PF6": 144.96, "BMIM_C1": 67.07,
"BMIM_C2": 15.04, "BMIM_C3": 57.12, "BMIM_COM": 0}
masses["BMIM_COM"] = masses["BMIM_C1"] + \
masses["BMIM_C2"] + masses["BMIM_C3"]
box_center = 0.5 * np.array(3 * [box_l])
system.min_global_cut = 3.5
#Place Particles
dmol = 5.0
#Test Anion
pos_pf6 = box_center + np.array([0, dmol, 0])
system.part.add(id=0, type=types["PF6"], pos=pos_pf6, q=charges[
"PF6"], mass=masses["PF6"], fix=[1, 1, 1])
pos_com = box_center - np.array([0, dmol, 0])
system.part.add(id=2, type=types["BMIM_C1"], pos=pos_com + [
0, -0.527, 1.365], q=charges["BMIM_C1"], mass=masses["BMIM_C1"], fix=[1, 1, 1])
system.part.add(id=4, type=types["BMIM_C2"], pos=pos_com + [
0, 1.641, 2.987], q=charges["BMIM_C2"], mass=masses["BMIM_C2"], fix=[1, 1, 1])
system.part.add(id=6, type=types["BMIM_C3"], pos=pos_com + [
0, 0.187, -2.389], q=charges["BMIM_C3"], mass=masses["BMIM_C3"], fix=[1, 1, 1])
system.thermostat.set_langevin(kT=temperature_com, gamma=gamma_com)
p3m = espressomd.electrostatics.P3M(
prefactor=coulomb_prefactor, accuracy=1e-4, mesh=[18, 18, 18], cao=5)
system.actors.add(p3m)
#Drude related Bonds
thermalized_dist_bond = espressomd.interactions.ThermalizedBond(
temp_com=temperature_com, gamma_com=gamma_com, temp_distance=temperature_drude, gamma_distance=gamma_drude, r_cut=1.0)
harmonic_bond = espressomd.interactions.HarmonicBond(
k=k_drude, r_0=0.0, r_cut=1.0)
system.bonded_inter.add(thermalized_dist_bond)
system.bonded_inter.add(harmonic_bond)
drude_helpers.add_drude_particle_to_core(system, harmonic_bond, thermalized_dist_bond, system.part[
0], 1, types["PF6_D"], polarizations["PF6"], mass_drude, coulomb_prefactor, 2.0)
drude_helpers.add_drude_particle_to_core(system, harmonic_bond, thermalized_dist_bond, system.part[
2], 3, types["BMIM_C1_D"], polarizations["BMIM_C1"], mass_drude, coulomb_prefactor, 2.0)
drude_helpers.add_drude_particle_to_core(system, harmonic_bond, thermalized_dist_bond, system.part[
4], 5, types["BMIM_C2_D"], polarizations["BMIM_C2"], mass_drude, coulomb_prefactor, 2.0)
drude_helpers.add_drude_particle_to_core(system, harmonic_bond, thermalized_dist_bond, system.part[
6], 7, types["BMIM_C3_D"], polarizations["BMIM_C3"], mass_drude, coulomb_prefactor, 2.0)
#Setup and add Drude-Core SR exclusion bonds
drude_helpers.setup_and_add_drude_exclusion_bonds(system)
#Setup intramol SR exclusion bonds once
drude_helpers.setup_intramol_exclusion_bonds(
system, [6, 7, 8], [1, 2, 3], [charges["BMIM_C1"], charges["BMIM_C2"], charges["BMIM_C3"]])
#Add bonds per molecule
drude_helpers.add_intramol_exclusion_bonds(
system, [3, 5, 7], [2, 4, 6])
#Thole
drude_helpers.add_all_thole(system)
def dipole_moment(id_core, id_drude):
pc = system.part[id_core]
pd = system.part[id_drude]
v = pd.pos - pc.pos
return pd.q * v
def measure_dipole_moments():
dm_pf6 = []
dm_C1 = []
dm_C2 = []
dm_C3 = []
system.integrator.run(115)
for i in range(100):
system.integrator.run(1)
dm_pf6.append(dipole_moment(0, 1))
dm_C1.append(dipole_moment(2, 3))
dm_C2.append(dipole_moment(4, 5))
dm_C3.append(dipole_moment(6, 7))
dm_pf6_m = np.mean(dm_pf6, axis=0)
dm_C1_m = np.mean(dm_C1, axis=0)
dm_C2_m = np.mean(dm_C2, axis=0)
dm_C3_m = np.mean(dm_C3, axis=0)
dm_sum_bmim = dm_C1_m + dm_C2_m + dm_C3_m
res = dm_pf6_m, dm_C1_m, dm_C2_m, dm_C3_m, dm_sum_bmim
return res
def setElectricField(E):
E = np.array(E)
for p in system.part:
p.ext_force = p.q * E
def calc_pol(mu0, muE, E):
pol = (muE - mu0) / E / conv_pol_CGS_SI
return pol
def measure_pol(Es, dim):
E = [0.0, 0.0, 0.0]
E[dim] = Es
setElectricField(E)
mux_pf6, mux_c1, mux_c2, mux_c3, mux_bmim = measure_dipole_moments(
)
return calc_pol(mu0_pf6[dim], mux_pf6[dim], Es), calc_pol(mu0_bmim[dim], mux_bmim[dim], Es)
mu0_pf6, mu0_c1, mu0_c2, mu0_c3, mu0_bmim = measure_dipole_moments()
eA_to_Debye = 4.8032047
atol = 1e-2
rtol = 1e-2
np.testing.assert_allclose(
ref_mu0_pf6, eA_to_Debye * mu0_pf6, atol=atol, rtol=rtol)
np.testing.assert_allclose(
ref_mu0_c1, eA_to_Debye * mu0_c1, atol=atol, rtol=rtol)
np.testing.assert_allclose(
ref_mu0_c2, eA_to_Debye * mu0_c2, atol=atol, rtol=rtol)
np.testing.assert_allclose(
ref_mu0_c3, eA_to_Debye * mu0_c3, atol=atol, rtol=rtol)
np.testing.assert_allclose(
ref_mu0_bmim, eA_to_Debye * mu0_bmim, atol=atol, rtol=rtol)
pol_pf6 = []
pol_bmim = []
Efield = 96.48536 # = 1 V/A in kJ / (Avogadro Number) / Angstrom / elementary charge
res = measure_pol(Efield, 0)
pol_pf6.append(res[0])
pol_bmim.append(res[1])
res = measure_pol(Efield, 1)
pol_pf6.append(res[0])
pol_bmim.append(res[1])
res = measure_pol(Efield, 2)
pol_pf6.append(res[0])
pol_bmim.append(res[1])
np.testing.assert_allclose(
ref_pol_pf6, pol_pf6, atol=atol, rtol=rtol)
np.testing.assert_allclose(
ref_pol_bmim, pol_bmim, atol=atol, rtol=rtol)
if __name__ == "__main__":
ut.main()
| hmenke/espresso | testsuite/python/drude.py | Python | gpl-3.0 | 10,864 |
/* RetroArch - A frontend for libretro.
* Copyright (C) 2010-2014 - Hans-Kristian Arntzen
*
* RetroArch 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __RARCH_FONTS_H
#define __RARCH_FONTS_H
#include <stdint.h>
#include <boolean.h>
/* All coordinates and offsets are top-left oriented.
*
* This is a texture-atlas approach which allows text to
* be drawn in a single draw call.
*
* It is up to the code using this interface to actually
* generate proper vertex buffers and upload the atlas texture to GPU. */
struct font_glyph
{
unsigned width;
unsigned height;
/* Texel coordinate offset for top-left pixel of this glyph. */
unsigned atlas_offset_x;
unsigned atlas_offset_y;
/* When drawing this glyph, apply an offset to
* current X/Y draw coordinate. */
int draw_offset_x;
int draw_offset_y;
/* Advance X/Y draw coordinates after drawing this glyph. */
int advance_x;
int advance_y;
};
struct font_atlas
{
uint8_t *buffer; /* Alpha channel. */
unsigned width;
unsigned height;
};
typedef struct font_renderer_driver
{
void *(*init)(const char *font_path, float font_size);
const struct font_atlas *(*get_atlas)(void *data);
/* Returns NULL if no glyph for this code is found. */
const struct font_glyph *(*get_glyph)(void *data, uint32_t code);
void (*free)(void *data);
const char *(*get_default_font)(void);
const char *ident;
} font_renderer_driver_t;
extern font_renderer_driver_t freetype_font_renderer;
extern font_renderer_driver_t coretext_font_renderer;
extern font_renderer_driver_t bitmap_font_renderer;
/* font_path can be NULL for default font. */
bool font_renderer_create_default(const font_renderer_driver_t **driver,
void **handle, const char *font_path, unsigned font_size);
#endif
| SuperrSonic/RA-SS | gfx/fonts/fonts.h | C | gpl-3.0 | 2,402 |
<?php
/**
* Forkel Resources
*
* @category Forkel
* @package Forkel_Resources
* @copyright Copyright (c) 2015 Tobias Forkel (http://www.tobiasforkel.de)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class Forkel_Resources_Helper_Data extends Mage_Core_Helper_Abstract
{
const MODULE_NAME = 'Forkel_Resources';
const MODULE_KEY = 'forkel_resources';
const MODEL_GREEN = 'forkel_resources/green';
const MODEL_BLUE = 'forkel_resources/blue';
} | tobias-forkel/Forkel_Resources | app/code/local/Forkel/Resources/Helper/Data.php | PHP | gpl-3.0 | 562 |
#pragma once
#include <memory>
#include <QtWidgets/QWidget>
#include <Database/Mixin/ConnectionAcceptor>
namespace Geo
{
namespace Import
{
//
class ImportTreeModel;
namespace Gui
{
//
class ImportWidget : public QWidget
{
Q_OBJECT
public:
ImportWidget();
virtual
~ImportWidget();
public:
/// Model is set in ImportController
void
setModel(ImportTreeModel* importModel);
private slots:
void
onImportClicked();
void
onConnectionSelected(int index);
void
onTableViewMenuRequested(const QPoint&);
signals:
void notifyMainWindow(QString);
private:
void
setupUi();
void
connectSignals();
private:
struct Private;
std::unique_ptr<Private> p;
};
//
} // namespace Gui
} // namespace Import
} // namespace Geo
| paceholder/wildcat | modules/Import/source/Gui/ImportWidget.hpp | C++ | gpl-3.0 | 766 |
from GangaCore.GPIDev.Lib.Tasks import ITask
from GangaCore.GPIDev.Schema import Schema, Version
########################################################################
class CoreTask(ITask):
"""General non-experimentally specific Task"""
_schema = Schema(Version(1, 0), dict(ITask._schema.datadict.items()))
_category = 'tasks'
_name = 'CoreTask'
_exportmethods = ITask._exportmethods + []
_tasktype = "ITask"
default_registry = "tasks"
| ganga-devs/ganga | ganga/GangaCore/GPIDev/Lib/Tasks/CoreTask.py | Python | gpl-3.0 | 474 |
using Machete.Service.BackgroundServices;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Threading;
using System.Threading.Tasks;
namespace Machete.Test.UnitTests.Services
{
[TestClass]
public class BackgroundServiceTests
{
private Mock<ILogger<RecurringBackgroundService>> _logger;
private Mock<IWorkerActions> _workerActions;
RecurringBackgroundService _recurringBackgroundService;
CancellationTokenSource _cts;
[TestInitialize]
public void TestInitinialize()
{
_logger = new Mock<ILogger<RecurringBackgroundService>>();
_workerActions = new Mock<IWorkerActions>();
_recurringBackgroundService =
new RecurringBackgroundService(
_logger.Object,
_workerActions.Object);
_logger
.Setup(x => x.BeginScope<RecurringBackgroundService>(_recurringBackgroundService));
_recurringBackgroundService.DelayMinutes = 1;
_recurringBackgroundService.RecurringMinutes = 1;
_cts = new CancellationTokenSource();
}
[TestMethod, TestCategory(TC.UT), TestCategory(TC.Service), TestCategory(TC.Workers)]
public async Task Should_Execute_Start()
{
// Arrange
_workerActions
.Setup(x => x.Execute())
.Returns(true);
Assert.IsTrue(_recurringBackgroundService.State == HostedBackgroundServiceState.NotStarted);
// act
await _recurringBackgroundService.StartAsync(CancellationToken.None);
//assert
Assert.IsTrue(_recurringBackgroundService.State == HostedBackgroundServiceState.Started);
// cleanup
await _recurringBackgroundService.StopAsync(_cts.Token);
}
///
/// Testing that .Net Core IHostedService does what it promises
[TestMethod, TestCategory(TC.UT), TestCategory(TC.Service), TestCategory(TC.Workers)]
public async Task Should_Start_Run_and_Stop()
{
// Arrange
_workerActions
.Setup(x => x.Execute())
.Returns(true);
//assert
Assert.IsTrue(_recurringBackgroundService.State == HostedBackgroundServiceState.NotStarted);
// act
await _recurringBackgroundService.StartAsync(CancellationToken.None);
//assert
Assert.IsTrue(_recurringBackgroundService.State == HostedBackgroundServiceState.Started);
await Task
.Delay(((int)_recurringBackgroundService.DelayMinutes) * 62000); // delay until slightly after the first iteration
//assert
Assert.IsTrue(_recurringBackgroundService.State == HostedBackgroundServiceState.RanOnce);
//act
await _recurringBackgroundService.StopAsync(CancellationToken.None);
await Task.Delay(100);
//assert
Assert.IsTrue(_recurringBackgroundService.State == HostedBackgroundServiceState.Stopped);
}
}
}
| SavageLearning/Machete | Machete.Test/UnitTests/Services/BackgroundServiceTests.cs | C# | gpl-3.0 | 3,299 |
/**
* Copyright (C) 2011, Claus Nielsen, cn@cn-consult.dk
*
* 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package dk.clanie.actor;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Timed;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Test ActorAspect.
*
* @author Claus Nielsen
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("actorAspectTestContext.xml")
public class ActorAspectTest {
@Autowired private FirstTestActor actor;
@Autowired private SecondTestActor actor2;
private static final int ITERATIONS = 5;
// Used in all test actor methods
public static final int SLEEPTIME = 200;
private static final double OVERHEAD = 0.5d;
/**
* Tests that methods returning Future on two different actors are executed in parallel.
* <p/>
* Each method call is expected to complete after a little more than SLEEPIME ms.<br/>
* When calling methods on two different actors they should still complete almost as fast.
*
* @throws InterruptedException
* @throws ExecutionException
* @throws TimeoutException
*/
@Test
@Timed(millis=(long)(ITERATIONS * SLEEPTIME * (1d + OVERHEAD)))
public void testFutureParallel() throws InterruptedException, ExecutionException, TimeoutException {
Future<?>[] futures = new Future<?>[ITERATIONS];
Future<?>[] futures2 = new Future<?>[ITERATIONS];
Instant startTime = new Instant();
// Call actor methods
for (int i = 0; i < ITERATIONS; i++) {
futures[i] = actor.methodReturningFuture(i);
futures2[i] = actor2.methodReturningFuture(i);
}
// Wait for them to complete
for (int i = 0; i < ITERATIONS; i++) {
futures[i].get(30, TimeUnit.SECONDS);
futures2[i].get(30, TimeUnit.SECONDS);
}
// Check that they completed in the expected time.
Instant endTime = new Instant();
Duration executionTime = new Duration(startTime, endTime);
Duration expectedExecutionTime = new Duration(ITERATIONS * SLEEPTIME);
assertThat((double)executionTime.getMillis(), closeTo((double)expectedExecutionTime.getMillis(), expectedExecutionTime.getMillis() * OVERHEAD));
}
/**
* Tests that void methods on two different actors are executed in parallel.
* <p/>
* Each method call is expected to complete after a little more than SLEEPIME ms.<br/>
* When calling methods on two different actors they should still complete almost as fast.
*
* @throws InterruptedException
* @throws ExecutionException
* @throws TimeoutException
*/
@Test
@Timed(millis=(long)(ITERATIONS * SLEEPTIME * (1d + OVERHEAD)))
public void testVoidParallel() throws InterruptedException, ExecutionException, TimeoutException {
Instant startTime = new Instant();
// Call actor methods
for (int i = 0; i < ITERATIONS; i++) {
actor.voidMethod(i);
actor2.voidMethod(i);
}
// Wait for them to complete
actor.sync();
actor2.sync();
// Check that they completed in the expected time.
Instant endTime = new Instant();
Duration executionTime = new Duration(startTime, endTime);
Duration expectedExecutionTime = new Duration(ITERATIONS * SLEEPTIME);
assertThat((double)executionTime.getMillis(), closeTo((double)expectedExecutionTime.getMillis(), expectedExecutionTime.getMillis() * OVERHEAD));
}
/**
* Tests that methods returning something blocks the caller.
*
* @throws InterruptedException
* @throws ExecutionException
* @throws TimeoutException
*/
@Test
@Timed(millis=(long)(ITERATIONS * SLEEPTIME * (1d + OVERHEAD) * 2))
public void testSequential() throws InterruptedException, ExecutionException, TimeoutException {
Instant startTime = new Instant();
// Call actor methods
for (int i = 0; i < ITERATIONS; i++) {
actor.methodReturningObject(i);
actor2.methodReturningObject(i);
}
// Check that they completed in the expected time.
Instant endTime = new Instant();
Duration executionTime = new Duration(startTime, endTime);
Duration expectedExecutionTime = new Duration(ITERATIONS * SLEEPTIME * 2);
assertThat((double)executionTime.getMillis(), closeTo((double)expectedExecutionTime.getMillis(), expectedExecutionTime.getMillis() * OVERHEAD));
}
/**
* Tests retrieving the return value from an synchronously called method.
*
* @throws InterruptedException
* @throws ExecutionException
*/
@Test
public void testGettingReturnValue() throws InterruptedException, ExecutionException {
Future<Boolean> future = actor.methodReturningTrue();
assertThat(future.get(), equalTo(Boolean.TRUE));
}
}
| clanie/clanie-aspects | src/test/java/dk/clanie/actor/ActorAspectTest.java | Java | gpl-3.0 | 5,872 |
// This is mutant program.
// Author : ysma
package examples.stryker.gcd.prvou_refined.prvou_refined113;
public class Gcd
{
/*@
@ requires a >= 0 && b >= 0;
@ ensures \result >= 0;
@ ensures (\old(a) % \result == 0);
@ ensures (\old(b) % \result == 0);
@ ensures (\forall int x; x>0 && x<=\old(a) && x<=\old(b) && (\old(a) % x == 0) && (\old(b) % x == 0); x<= \result);
@ signals (Exception e) false;
@*/ public int gcd( int a, int b )
{
if (a == 0) {
return b;
} else {
while (b != 0) { //mutGenLimit 1
if (a > b) {
a = a - b;
} else {
b = b - a;
}
}
return a;
}
}
}
| zeminlu/comitaco | tests/examples/stryker/gcd/prvou_refined/prvou_refined113/Gcd.java | Java | gpl-3.0 | 763 |
CREATE SEQUENCE documents.unique_file_number_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
ALTER TABLE documents.unique_file_number_seq OWNER TO EASYGP;
GRANT USAGE ON documents.unique_file_number_seq TO Staff;
update db.lu_version set lu_minor=406; | ihaywood3/easygp | db/updates/0.406_documents.unique_file_number_seq.sql | SQL | gpl-3.0 | 297 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (1.8.0_31) on Sun Apr 12 23:52:55 COT 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.ecos.tspistatusquo.temp.biz (TSPiStatusQuo 1.0-SNAPSHOT API)</title>
<meta name="date" content="2015-04-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../com/ecos/tspistatusquo/temp/biz/package-summary.html" target="classFrame">com.ecos.tspistatusquo.temp.biz</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="FileBiz.html" title="class in com.ecos.tspistatusquo.temp.biz" target="classFrame">FileBiz</a></li>
<li><a href="FileManager.html" title="class in com.ecos.tspistatusquo.temp.biz" target="classFrame">FileManager</a></li>
</ul>
</div>
</body>
</html>
| ecosstatusquo/iteracion1 | src/site/apidocs/com/ecos/tspistatusquo/temp/biz/package-frame.html | HTML | gpl-3.0 | 1,084 |
// Copyright ©2015 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package functions
import (
"math"
"testing"
"gonum.org/v1/gonum/diff/fd"
"gonum.org/v1/gonum/floats"
)
// function represents an objective function.
type function interface {
Func(x []float64) float64
}
type gradient interface {
Grad(grad, x []float64)
}
// minimumer is an objective function that can also provide information about
// its minima.
type minimumer interface {
function
// Minima returns _known_ minima of the function.
Minima() []Minimum
}
// Minimum represents information about an optimal location of a function.
type Minimum struct {
// X is the location of the minimum. X may not be nil.
X []float64
// F is the value of the objective function at X.
F float64
// Global indicates if the location is a global minimum.
Global bool
}
type funcTest struct {
X []float64
// F is the expected function value at X.
F float64
// Gradient is the expected gradient at X. If nil, it is not evaluated.
Gradient []float64
}
// TODO(vladimir-ch): Decide and implement an exported testing function:
// func Test(f Function, ??? ) ??? {
// }
const (
defaultTol = 1e-12
defaultGradTol = 1e-9
defaultFDGradTol = 1e-5
)
// testFunction checks that the function can evaluate itself (and its gradient)
// correctly.
func testFunction(f function, ftests []funcTest, t *testing.T) {
// Make a copy of tests because we may append to the slice.
tests := make([]funcTest, len(ftests))
copy(tests, ftests)
// Get information about the function.
fMinima, isMinimumer := f.(minimumer)
fGradient, isGradient := f.(gradient)
// If the function is a Minimumer, append its minima to the tests.
if isMinimumer {
for _, minimum := range fMinima.Minima() {
// Allocate gradient only if the function can evaluate it.
var grad []float64
if isGradient {
grad = make([]float64, len(minimum.X))
}
tests = append(tests, funcTest{
X: minimum.X,
F: minimum.F,
Gradient: grad,
})
}
}
for i, test := range tests {
F := f.Func(test.X)
// Check that the function value is as expected.
if math.Abs(F-test.F) > defaultTol {
t.Errorf("Test #%d: function value given by Func is incorrect. Want: %v, Got: %v",
i, test.F, F)
}
if test.Gradient == nil {
continue
}
// Evaluate the finite difference gradient.
fdGrad := fd.Gradient(nil, f.Func, test.X, &fd.Settings{
Formula: fd.Central,
Step: 1e-6,
})
// Check that the finite difference and expected gradients match.
if !floats.EqualApprox(fdGrad, test.Gradient, defaultFDGradTol) {
dist := floats.Distance(fdGrad, test.Gradient, math.Inf(1))
t.Errorf("Test #%d: numerical and expected gradients do not match. |fdGrad - WantGrad|_∞ = %v",
i, dist)
}
// If the function is a Gradient, check that it computes the gradient correctly.
if isGradient {
grad := make([]float64, len(test.Gradient))
fGradient.Grad(grad, test.X)
if !floats.EqualApprox(grad, test.Gradient, defaultGradTol) {
dist := floats.Distance(grad, test.Gradient, math.Inf(1))
t.Errorf("Test #%d: gradient given by Grad is incorrect. |grad - WantGrad|_∞ = %v",
i, dist)
}
}
}
}
| pts-eduardoacuna/pachy-learning | vendor/gonum.org/v1/gonum/optimize/functions/validate.go | GO | gpl-3.0 | 3,324 |
package app;
import java.io.*;
import org.apache.log4j.Logger;
public class TXTBook implements Book {
@Override
public String getText(File file) {
String text = "";
String newline = System.getProperty("line.separator");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line = null;
while (null != (line = reader.readLine())) {
text += line + newline;
}
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
}
return text;
}
Logger LOG = Logger.getLogger(TXTBook.class);
}
| demidrol911/eng_rus_reader | EnglishLearn/src/app/TXTBook.java | Java | gpl-3.0 | 647 |
package com.mrgss.web.persistence.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.joda.time.DateTime;
@Entity
@Table(name = "species")
public class SpeciesEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String name;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false, updatable = false)
private Date startDate;
@OneToMany
@Column(nullable=false)
private List<RaceEntity> races;
public List<RaceEntity> getRaces() {
return races;
}
public void setRaces(List<RaceEntity> races) {
this.races = races;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DateTime getStartDate() {
return new DateTime(startDate);
}
public void setStartDate(DateTime startDate) {
this.startDate = startDate.toDate();
}
public Long getId() {
return id;
}
@Override
public String toString() {
return "SpeciesEntity [id=" + id + ", name=" + name + ", startDate="
+ startDate + ", races=" + races + "]";
}
} | nicoferre/vetsis | persistence/src/main/java/com/mrgss/web/persistence/model/SpeciesEntity.java | Java | gpl-3.0 | 1,405 |
//
// BigInteger.cs - Big Integer implementation
//
// Authors:
// Ben Maurer
// Chew Keong TAN
// Sebastien Pouliot <sebastien@ximian.com>
// Pieter Philippaerts <Pieter@mentalis.org>
//
// Copyright (c) 2003 Ben Maurer
// All rights reserved
//
// Copyright (c) 2002 Chew Keong TAN
// All rights reserved.
//
// Copyright (C) 2004, 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
namespace Mono.Math
{
internal class BigInteger
{
#region Data Storage
/// <summary>
/// The Length of this BigInteger
/// </summary>
uint length = 1;
/// <summary>
/// The data for this BigInteger
/// </summary>
uint[] data;
#endregion
#region Constants
/// <summary>
/// Default length of a BigInteger in bytes
/// </summary>
const uint DEFAULT_LEN = 20;
public enum Sign : int
{
Negative = -1,
Zero = 0,
Positive = 1
};
#region Exception Messages
const string WouldReturnNegVal = "Operation would return a negative value";
#endregion
#endregion
#region Constructors
public BigInteger()
{
data = new uint[DEFAULT_LEN];
this.length = DEFAULT_LEN;
}
public BigInteger(uint ui)
{
data = new uint[] { ui };
}
public BigInteger(Sign sign, uint len)
{
this.data = new uint[len];
this.length = len;
}
public BigInteger(BigInteger bi)
{
this.data = (uint[])bi.data.Clone();
this.length = bi.length;
}
public BigInteger(BigInteger bi, uint len)
{
this.data = new uint[len];
for (uint i = 0; i < bi.length; i++)
this.data[i] = bi.data[i];
this.length = bi.length;
}
#endregion
#region Conversions
public BigInteger(byte[] inData)
{
if (inData.Length == 0)
inData = new byte[1];
length = (uint)inData.Length >> 2;
int leftOver = inData.Length & 0x3;
// length not multiples of 4
if (leftOver != 0) length++;
data = new uint[length];
for (int i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++)
{
data[j] = (uint)(
(inData[i - 3] << (3 * 8)) |
(inData[i - 2] << (2 * 8)) |
(inData[i - 1] << (1 * 8)) |
(inData[i])
);
}
switch (leftOver)
{
case 1: data[length - 1] = (uint)inData[0]; break;
case 2: data[length - 1] = (uint)((inData[0] << 8) | inData[1]); break;
case 3: data[length - 1] = (uint)((inData[0] << 16) | (inData[1] << 8) | inData[2]); break;
}
this.Normalize();
}
public static implicit operator BigInteger(uint value)
{
return (new BigInteger(value));
}
#endregion
#region Operators
public static BigInteger operator +(BigInteger bi1, BigInteger bi2)
{
if (bi1 == 0)
return new BigInteger(bi2);
else if (bi2 == 0)
return new BigInteger(bi1);
else
return Kernel.AddSameSign(bi1, bi2);
}
public static BigInteger operator -(BigInteger bi1, BigInteger bi2)
{
if (bi2 == 0)
return new BigInteger(bi1);
if (bi1 == 0)
throw new ArithmeticException(WouldReturnNegVal);
switch (Kernel.Compare(bi1, bi2))
{
case Sign.Zero:
return 0;
case Sign.Positive:
return Kernel.Subtract(bi1, bi2);
case Sign.Negative:
throw new ArithmeticException(WouldReturnNegVal);
default:
throw new Exception();
}
}
public static int operator %(BigInteger bi, int i)
{
if (i > 0)
return (int)Kernel.DwordMod(bi, (uint)i);
else
return -(int)Kernel.DwordMod(bi, (uint)-i);
}
public static uint operator %(BigInteger bi, uint ui)
{
return Kernel.DwordMod(bi, (uint)ui);
}
public static BigInteger operator %(BigInteger bi1, BigInteger bi2)
{
return Kernel.multiByteDivide(bi1, bi2)[1];
}
public static BigInteger operator /(BigInteger bi, int i)
{
if (i > 0)
return Kernel.DwordDiv(bi, (uint)i);
throw new ArithmeticException(WouldReturnNegVal);
}
public static BigInteger operator /(BigInteger bi1, BigInteger bi2)
{
return Kernel.multiByteDivide(bi1, bi2)[0];
}
public static BigInteger operator *(BigInteger bi1, BigInteger bi2)
{
if (bi1 == 0 || bi2 == 0) return 0;
//
// Validate pointers
//
if (bi1.data.Length < bi1.length) throw new IndexOutOfRangeException("bi1 out of range");
if (bi2.data.Length < bi2.length) throw new IndexOutOfRangeException("bi2 out of range");
BigInteger ret = new BigInteger(Sign.Positive, bi1.length + bi2.length);
Kernel.Multiply(bi1.data, 0, bi1.length, bi2.data, 0, bi2.length, ret.data, 0);
ret.Normalize();
return ret;
}
public static BigInteger operator *(BigInteger bi, int i)
{
if (i < 0) throw new ArithmeticException(WouldReturnNegVal);
if (i == 0) return 0;
if (i == 1) return new BigInteger(bi);
return Kernel.MultiplyByDword(bi, (uint)i);
}
public static BigInteger operator <<(BigInteger bi1, int shiftVal)
{
return Kernel.LeftShift(bi1, shiftVal);
}
public static BigInteger operator >>(BigInteger bi1, int shiftVal)
{
return Kernel.RightShift(bi1, shiftVal);
}
#endregion
#region Bitwise
public int BitCount()
{
this.Normalize();
uint value = data[length - 1];
uint mask = 0x80000000;
uint bits = 32;
while (bits > 0 && (value & mask) == 0)
{
bits--;
mask >>= 1;
}
bits += ((length - 1) << 5);
return (int)bits;
}
public bool TestBit(int bitNum)
{
if (bitNum < 0) throw new IndexOutOfRangeException("bitNum out of range");
uint bytePos = (uint)bitNum >> 5; // divide by 32
byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits
uint mask = (uint)1 << bitPos;
return ((this.data[bytePos] | mask) == this.data[bytePos]);
}
public void SetBit(uint bitNum, bool value)
{
uint bytePos = bitNum >> 5; // divide by 32
if (bytePos < this.length)
{
uint mask = (uint)1 << (int)(bitNum & 0x1F);
if (value)
this.data[bytePos] |= mask;
else
this.data[bytePos] &= ~mask;
}
}
public byte[] GetBytes()
{
if (this == 0) return new byte[1];
int numBits = BitCount();
int numBytes = numBits >> 3;
if ((numBits & 0x7) != 0)
numBytes++;
byte[] result = new byte[numBytes];
int numBytesInWord = numBytes & 0x3;
if (numBytesInWord == 0) numBytesInWord = 4;
int pos = 0;
for (int i = (int)length - 1; i >= 0; i--)
{
uint val = data[i];
for (int j = numBytesInWord - 1; j >= 0; j--)
{
result[pos + j] = (byte)(val & 0xFF);
val >>= 8;
}
pos += numBytesInWord;
numBytesInWord = 4;
}
return result;
}
#endregion
#region Compare
public static bool operator ==(BigInteger bi1, uint ui)
{
if (bi1.length != 1) bi1.Normalize();
return bi1.length == 1 && bi1.data[0] == ui;
}
public static bool operator !=(BigInteger bi1, uint ui)
{
if (bi1.length != 1) bi1.Normalize();
return !(bi1.length == 1 && bi1.data[0] == ui);
}
public static bool operator ==(BigInteger bi1, BigInteger bi2)
{
// we need to compare with null
if ((bi1 as object) == (bi2 as object))
return true;
if (null == bi1 || null == bi2)
return false;
return Kernel.Compare(bi1, bi2) == 0;
}
public static bool operator !=(BigInteger bi1, BigInteger bi2)
{
// we need to compare with null
if ((bi1 as object) == (bi2 as object))
return false;
if (null == bi1 || null == bi2)
return true;
return Kernel.Compare(bi1, bi2) != 0;
}
public static bool operator >(BigInteger bi1, BigInteger bi2)
{
return Kernel.Compare(bi1, bi2) > 0;
}
public static bool operator <(BigInteger bi1, BigInteger bi2)
{
return Kernel.Compare(bi1, bi2) < 0;
}
public static bool operator >=(BigInteger bi1, BigInteger bi2)
{
return Kernel.Compare(bi1, bi2) >= 0;
}
public static bool operator <=(BigInteger bi1, BigInteger bi2)
{
return Kernel.Compare(bi1, bi2) <= 0;
}
public Sign Compare(BigInteger bi)
{
return Kernel.Compare(this, bi);
}
#endregion
#region Formatting
public string ToString(uint radix)
{
return ToString(radix, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
public string ToString(uint radix, string characterSet)
{
if (characterSet.Length < radix)
throw new ArgumentException("charSet length less than radix", "characterSet");
if (radix == 1)
throw new ArgumentException("There is no such thing as radix one notation", "radix");
if (this == 0) return "0";
if (this == 1) return "1";
string result = "";
BigInteger a = new BigInteger(this);
while (a != 0)
{
uint rem = Kernel.SingleByteDivideInPlace(a, radix);
result = characterSet[(int)rem] + result;
}
return result;
}
#endregion
#region Misc
/// <summary>
/// Normalizes this by setting the length to the actual number of
/// uints used in data and by setting the sign to Sign.Zero if the
/// value of this is 0.
/// </summary>
private void Normalize()
{
// Normalize length
while (length > 0 && data[length - 1] == 0) length--;
// Check for zero
if (length == 0)
length++;
}
#endregion
#region Object Impl
public override int GetHashCode()
{
uint val = 0;
for (uint i = 0; i < this.length; i++)
val ^= this.data[i];
return (int)val;
}
public override string ToString()
{
return ToString(10);
}
public override bool Equals(object o)
{
if (o == null) return false;
if (o is int) return (int)o >= 0 && this == (uint)o;
return Kernel.Compare(this, (BigInteger)o) == 0;
}
#endregion
#region Number Theory
public BigInteger ModPow(BigInteger exp, BigInteger n)
{
ModulusRing mr = new ModulusRing(n);
return mr.Pow(this, exp);
}
#endregion
public sealed class ModulusRing
{
BigInteger mod, constant;
public ModulusRing(BigInteger modulus)
{
this.mod = modulus;
// calculate constant = b^ (2k) / m
uint i = mod.length << 1;
constant = new BigInteger(Sign.Positive, i + 1);
constant.data[i] = 0x00000001;
constant = constant / mod;
}
public void BarrettReduction(BigInteger x)
{
BigInteger n = mod;
uint k = n.length,
kPlusOne = k + 1,
kMinusOne = k - 1;
// x < mod, so nothing to do.
if (x.length < k) return;
BigInteger q3;
//
// Validate pointers
//
if (x.data.Length < x.length) throw new IndexOutOfRangeException("x out of range");
// q1 = x / b^ (k-1)
// q2 = q1 * constant
// q3 = q2 / b^ (k+1), Needs to be accessed with an offset of kPlusOne
// TODO: We should the method in HAC p 604 to do this (14.45)
q3 = new BigInteger(Sign.Positive, x.length - kMinusOne + constant.length);
Kernel.Multiply(x.data, kMinusOne, x.length - kMinusOne, constant.data, 0, constant.length, q3.data, 0);
// r1 = x mod b^ (k+1)
// i.e. keep the lowest (k+1) words
uint lengthToCopy = (x.length > kPlusOne) ? kPlusOne : x.length;
x.length = lengthToCopy;
x.Normalize();
// r2 = (q3 * n) mod b^ (k+1)
// partial multiplication of q3 and n
BigInteger r2 = new BigInteger(Sign.Positive, kPlusOne);
Kernel.MultiplyMod2p32pmod(q3.data, (int)kPlusOne, (int)q3.length - (int)kPlusOne, n.data, 0, (int)n.length, r2.data, 0, (int)kPlusOne);
r2.Normalize();
if (r2 <= x)
{
Kernel.MinusEq(x, r2);
}
else
{
BigInteger val = new BigInteger(Sign.Positive, kPlusOne + 1);
val.data[kPlusOne] = 0x00000001;
Kernel.MinusEq(val, r2);
Kernel.PlusEq(x, val);
}
while (x >= n)
Kernel.MinusEq(x, n);
}
public BigInteger Multiply(BigInteger a, BigInteger b)
{
if (a == 0 || b == 0) return 0;
if (a > mod)
a %= mod;
if (b > mod)
b %= mod;
BigInteger ret = a * b;
BarrettReduction(ret);
return ret;
}
public BigInteger Difference(BigInteger a, BigInteger b)
{
Sign cmp = Kernel.Compare(a, b);
BigInteger diff;
switch (cmp)
{
case Sign.Zero:
return 0;
case Sign.Positive:
diff = a - b; break;
case Sign.Negative:
diff = b - a; break;
default:
throw new Exception();
}
if (diff >= mod)
{
if (diff.length >= mod.length << 1)
diff %= mod;
else
BarrettReduction(diff);
}
if (cmp == Sign.Negative)
diff = mod - diff;
return diff;
}
public BigInteger Pow(BigInteger a, BigInteger k)
{
BigInteger b = new BigInteger(1);
if (k == 0)
return b;
BigInteger A = a;
if (k.TestBit(0))
b = a;
int bitCount = k.BitCount();
for (int i = 1; i < bitCount; i++)
{
A = Multiply(A, A);
if (k.TestBit(i))
b = Multiply(A, b);
}
return b;
}
public BigInteger Pow(uint b, BigInteger exp)
{
return Pow(new BigInteger(b), exp);
}
}
private sealed class Kernel
{
#region Addition/Subtraction
/// <summary>
/// Adds two numbers with the same sign.
/// </summary>
/// <param name="bi1">A BigInteger</param>
/// <param name="bi2">A BigInteger</param>
/// <returns>bi1 + bi2</returns>
public static BigInteger AddSameSign(BigInteger bi1, BigInteger bi2)
{
uint[] x, y;
uint yMax, xMax, i = 0;
// x should be bigger
if (bi1.length < bi2.length)
{
x = bi2.data;
xMax = bi2.length;
y = bi1.data;
yMax = bi1.length;
}
else
{
x = bi1.data;
xMax = bi1.length;
y = bi2.data;
yMax = bi2.length;
}
BigInteger result = new BigInteger(Sign.Positive, xMax + 1);
uint[] r = result.data;
ulong sum = 0;
// Add common parts of both numbers
do
{
sum = ((ulong)x[i]) + ((ulong)y[i]) + sum;
r[i] = (uint)sum;
sum >>= 32;
} while (++i < yMax);
// Copy remainder of longer number while carry propagation is required
bool carry = (sum != 0);
if (carry)
{
if (i < xMax)
{
do
carry = ((r[i] = x[i] + 1) == 0);
while (++i < xMax && carry);
}
if (carry)
{
r[i] = 1;
result.length = ++i;
return result;
}
}
// Copy the rest
if (i < xMax)
{
do
r[i] = x[i];
while (++i < xMax);
}
result.Normalize();
return result;
}
public static BigInteger Subtract(BigInteger big, BigInteger small)
{
BigInteger result = new BigInteger(Sign.Positive, big.length);
uint[] r = result.data, b = big.data, s = small.data;
uint i = 0, c = 0;
do
{
uint x = s[i];
if (((x += c) < c) | ((r[i] = b[i] - x) > ~x))
c = 1;
else
c = 0;
} while (++i < small.length);
if (i == big.length) goto fixup;
if (c == 1)
{
do
r[i] = b[i] - 1;
while (b[i++] == 0 && i < big.length);
if (i == big.length) goto fixup;
}
do
r[i] = b[i];
while (++i < big.length);
fixup:
result.Normalize();
return result;
}
public static void MinusEq(BigInteger big, BigInteger small)
{
uint[] b = big.data, s = small.data;
uint i = 0, c = 0;
do
{
uint x = s[i];
if (((x += c) < c) | ((b[i] -= x) > ~x))
c = 1;
else
c = 0;
} while (++i < small.length);
if (i == big.length) goto fixup;
if (c == 1)
{
do
b[i]--;
while (b[i++] == 0 && i < big.length);
}
fixup:
// Normalize length
while (big.length > 0 && big.data[big.length - 1] == 0) big.length--;
// Check for zero
if (big.length == 0)
big.length++;
}
public static void PlusEq(BigInteger bi1, BigInteger bi2)
{
uint[] x, y;
uint yMax, xMax, i = 0;
bool flag = false;
// x should be bigger
if (bi1.length < bi2.length)
{
flag = true;
x = bi2.data;
xMax = bi2.length;
y = bi1.data;
yMax = bi1.length;
}
else
{
x = bi1.data;
xMax = bi1.length;
y = bi2.data;
yMax = bi2.length;
}
uint[] r = bi1.data;
ulong sum = 0;
// Add common parts of both numbers
do
{
sum += ((ulong)x[i]) + ((ulong)y[i]);
r[i] = (uint)sum;
sum >>= 32;
} while (++i < yMax);
// Copy remainder of longer number while carry propagation is required
bool carry = (sum != 0);
if (carry)
{
if (i < xMax)
{
do
carry = ((r[i] = x[i] + 1) == 0);
while (++i < xMax && carry);
}
if (carry)
{
r[i] = 1;
bi1.length = ++i;
return;
}
}
// Copy the rest
if (flag && i < xMax - 1)
{
do
r[i] = x[i];
while (++i < xMax);
}
bi1.length = xMax + 1;
bi1.Normalize();
}
#endregion
#region Compare
/// <summary>
/// Compares two BigInteger
/// </summary>
/// <param name="bi1">A BigInteger</param>
/// <param name="bi2">A BigInteger</param>
/// <returns>The sign of bi1 - bi2</returns>
public static Sign Compare(BigInteger bi1, BigInteger bi2)
{
//
// Step 1. Compare the lengths
//
uint l1 = bi1.length, l2 = bi2.length;
while (l1 > 0 && bi1.data[l1 - 1] == 0) l1--;
while (l2 > 0 && bi2.data[l2 - 1] == 0) l2--;
if (l1 == 0 && l2 == 0) return Sign.Zero;
// bi1 len < bi2 len
if (l1 < l2) return Sign.Negative;
// bi1 len > bi2 len
else if (l1 > l2) return Sign.Positive;
//
// Step 2. Compare the bits
//
uint pos = l1 - 1;
while (pos != 0 && bi1.data[pos] == bi2.data[pos]) pos--;
if (bi1.data[pos] < bi2.data[pos])
return Sign.Negative;
else if (bi1.data[pos] > bi2.data[pos])
return Sign.Positive;
else
return Sign.Zero;
}
#endregion
#region Division
#region Dword
/// <summary>
/// Performs n / d and n % d in one operation.
/// </summary>
/// <param name="n">A BigInteger, upon exit this will hold n / d</param>
/// <param name="d">The divisor</param>
/// <returns>n % d</returns>
public static uint SingleByteDivideInPlace(BigInteger n, uint d)
{
ulong r = 0;
uint i = n.length;
while (i-- > 0)
{
r <<= 32;
r |= n.data[i];
n.data[i] = (uint)(r / d);
r %= d;
}
n.Normalize();
return (uint)r;
}
public static uint DwordMod(BigInteger n, uint d)
{
ulong r = 0;
uint i = n.length;
while (i-- > 0)
{
r <<= 32;
r |= n.data[i];
r %= d;
}
return (uint)r;
}
public static BigInteger DwordDiv(BigInteger n, uint d)
{
BigInteger ret = new BigInteger(Sign.Positive, n.length);
ulong r = 0;
uint i = n.length;
while (i-- > 0)
{
r <<= 32;
r |= n.data[i];
ret.data[i] = (uint)(r / d);
r %= d;
}
ret.Normalize();
return ret;
}
public static BigInteger[] DwordDivMod(BigInteger n, uint d)
{
BigInteger ret = new BigInteger(Sign.Positive, n.length);
ulong r = 0;
uint i = n.length;
while (i-- > 0)
{
r <<= 32;
r |= n.data[i];
ret.data[i] = (uint)(r / d);
r %= d;
}
ret.Normalize();
BigInteger rem = (uint)r;
return new BigInteger[] { ret, rem };
}
#endregion
#region BigNum
public static BigInteger[] multiByteDivide(BigInteger bi1, BigInteger bi2)
{
if (Kernel.Compare(bi1, bi2) == Sign.Negative)
return new BigInteger[2] { 0, new BigInteger(bi1) };
bi1.Normalize(); bi2.Normalize();
if (bi2.length == 1)
return DwordDivMod(bi1, bi2.data[0]);
uint remainderLen = bi1.length + 1;
int divisorLen = (int)bi2.length + 1;
uint mask = 0x80000000;
uint val = bi2.data[bi2.length - 1];
int shift = 0;
int resultPos = (int)bi1.length - (int)bi2.length;
while (mask != 0 && (val & mask) == 0)
{
shift++; mask >>= 1;
}
BigInteger quot = new BigInteger(Sign.Positive, bi1.length - bi2.length + 1);
BigInteger rem = (bi1 << shift);
uint[] remainder = rem.data;
bi2 = bi2 << shift;
int j = (int)(remainderLen - bi2.length);
int pos = (int)remainderLen - 1;
uint firstDivisorByte = bi2.data[bi2.length - 1];
ulong secondDivisorByte = bi2.data[bi2.length - 2];
while (j > 0)
{
ulong dividend = ((ulong)remainder[pos] << 32) + (ulong)remainder[pos - 1];
ulong q_hat = dividend / (ulong)firstDivisorByte;
ulong r_hat = dividend % (ulong)firstDivisorByte;
do
{
if (q_hat == 0x100000000 ||
(q_hat * secondDivisorByte) > ((r_hat << 32) + remainder[pos - 2]))
{
q_hat--;
r_hat += (ulong)firstDivisorByte;
if (r_hat < 0x100000000)
continue;
}
break;
} while (true);
//
// At this point, q_hat is either exact, or one too large
// (more likely to be exact) so, we attempt to multiply the
// divisor by q_hat, if we get a borrow, we just subtract
// one from q_hat and add the divisor back.
//
uint t;
uint dPos = 0;
int nPos = pos - divisorLen + 1;
ulong mc = 0;
uint uint_q_hat = (uint)q_hat;
do
{
mc += (ulong)bi2.data[dPos] * (ulong)uint_q_hat;
t = remainder[nPos];
remainder[nPos] -= (uint)mc;
mc >>= 32;
if (remainder[nPos] > t) mc++;
dPos++; nPos++;
} while (dPos < divisorLen);
nPos = pos - divisorLen + 1;
dPos = 0;
// Overestimate
if (mc != 0)
{
uint_q_hat--;
ulong sum = 0;
do
{
sum = ((ulong)remainder[nPos]) + ((ulong)bi2.data[dPos]) + sum;
remainder[nPos] = (uint)sum;
sum >>= 32;
dPos++; nPos++;
} while (dPos < divisorLen);
}
quot.data[resultPos--] = (uint)uint_q_hat;
pos--;
j--;
}
quot.Normalize();
rem.Normalize();
BigInteger[] ret = new BigInteger[2] { quot, rem };
if (shift != 0)
ret[1] >>= shift;
return ret;
}
#endregion
#endregion
#region Shift
public static BigInteger LeftShift(BigInteger bi, int n)
{
if (n == 0) return new BigInteger(bi, bi.length + 1);
int w = n >> 5;
n &= ((1 << 5) - 1);
BigInteger ret = new BigInteger(Sign.Positive, bi.length + 1 + (uint)w);
uint i = 0, l = bi.length;
if (n != 0)
{
uint x, carry = 0;
while (i < l)
{
x = bi.data[i];
ret.data[i + w] = (x << n) | carry;
carry = x >> (32 - n);
i++;
}
ret.data[i + w] = carry;
}
else
{
while (i < l)
{
ret.data[i + w] = bi.data[i];
i++;
}
}
ret.Normalize();
return ret;
}
public static BigInteger RightShift(BigInteger bi, int n)
{
if (n == 0) return new BigInteger(bi);
int w = n >> 5;
int s = n & ((1 << 5) - 1);
BigInteger ret = new BigInteger(Sign.Positive, bi.length - (uint)w + 1);
uint l = (uint)ret.data.Length - 1;
if (s != 0)
{
uint x, carry = 0;
while (l-- > 0)
{
x = bi.data[l + w];
ret.data[l] = (x >> n) | carry;
carry = x << (32 - n);
}
}
else
{
while (l-- > 0)
ret.data[l] = bi.data[l + w];
}
ret.Normalize();
return ret;
}
#endregion
#region Multiply
public static BigInteger MultiplyByDword(BigInteger n, uint f)
{
BigInteger ret = new BigInteger(Sign.Positive, n.length + 1);
uint i = 0;
ulong c = 0;
do
{
c += (ulong)n.data[i] * (ulong)f;
ret.data[i] = (uint)c;
c >>= 32;
} while (++i < n.length);
ret.data[i] = (uint)c;
ret.Normalize();
return ret;
}
/// <summary>
/// Multiplies the data in x [xOffset:xOffset+xLen] by
/// y [yOffset:yOffset+yLen] and puts it into
/// d [dOffset:dOffset+xLen+yLen].
/// </summary>
/// <remarks>
/// This code is unsafe! It is the caller's responsibility to make
/// sure that it is safe to access x [xOffset:xOffset+xLen],
/// y [yOffset:yOffset+yLen], and d [dOffset:dOffset+xLen+yLen].
/// </remarks>
public static unsafe void Multiply(uint[] x, uint xOffset, uint xLen, uint[] y, uint yOffset, uint yLen, uint[] d, uint dOffset)
{
fixed (uint* xx = x, yy = y, dd = d)
{
uint* xP = xx + xOffset,
xE = xP + xLen,
yB = yy + yOffset,
yE = yB + yLen,
dB = dd + dOffset;
for (; xP < xE; xP++, dB++)
{
if (*xP == 0) continue;
ulong mcarry = 0;
uint* dP = dB;
for (uint* yP = yB; yP < yE; yP++, dP++)
{
mcarry += ((ulong)*xP * (ulong)*yP) + (ulong)*dP;
*dP = (uint)mcarry;
mcarry >>= 32;
}
if (mcarry != 0)
*dP = (uint)mcarry;
}
}
}
/// <summary>
/// Multiplies the data in x [xOffset:xOffset+xLen] by
/// y [yOffset:yOffset+yLen] and puts the low mod words into
/// d [dOffset:dOffset+mod].
/// </summary>
/// <remarks>
/// This code is unsafe! It is the caller's responsibility to make
/// sure that it is safe to access x [xOffset:xOffset+xLen],
/// y [yOffset:yOffset+yLen], and d [dOffset:dOffset+mod].
/// </remarks>
public static unsafe void MultiplyMod2p32pmod(uint[] x, int xOffset, int xLen, uint[] y, int yOffest, int yLen, uint[] d, int dOffset, int mod)
{
fixed (uint* xx = x, yy = y, dd = d)
{
uint* xP = xx + xOffset,
xE = xP + xLen,
yB = yy + yOffest,
yE = yB + yLen,
dB = dd + dOffset,
dE = dB + mod;
for (; xP < xE; xP++, dB++)
{
if (*xP == 0) continue;
ulong mcarry = 0;
uint* dP = dB;
for (uint* yP = yB; yP < yE && dP < dE; yP++, dP++)
{
mcarry += ((ulong)*xP * (ulong)*yP) + (ulong)*dP;
*dP = (uint)mcarry;
mcarry >>= 32;
}
if (mcarry != 0 && dP < dE)
*dP = (uint)mcarry;
}
}
}
#endregion
#region Number Theory
public static BigInteger gcd(BigInteger a, BigInteger b)
{
BigInteger x = a;
BigInteger y = b;
BigInteger g = y;
while (x.length > 1)
{
g = x;
x = y % x;
y = g;
}
if (x == 0) return g;
// TODO: should we have something here if we can convert to long?
//
// Now we can just do it with single precision. I am using the binary gcd method,
// as it should be faster.
//
uint yy = x.data[0];
uint xx = y % yy;
int t = 0;
while (((xx | yy) & 1) == 0)
{
xx >>= 1; yy >>= 1; t++;
}
while (xx != 0)
{
while ((xx & 1) == 0) xx >>= 1;
while ((yy & 1) == 0) yy >>= 1;
if (xx >= yy)
xx = (xx - yy) >> 1;
else
yy = (yy - xx) >> 1;
}
return yy << t;
}
public static BigInteger modInverse(BigInteger bi, BigInteger modulus)
{
if (modulus.length == 1) return modInverse(bi, modulus.data[0]);
BigInteger[] p = { 0, 1 };
BigInteger[] q = new BigInteger[2]; // quotients
BigInteger[] r = { 0, 0 }; // remainders
int step = 0;
BigInteger a = modulus;
BigInteger b = bi;
ModulusRing mr = new ModulusRing(modulus);
while (b != 0)
{
if (step > 1)
{
BigInteger pval = mr.Difference(p[0], p[1] * q[0]);
p[0] = p[1]; p[1] = pval;
}
BigInteger[] divret = multiByteDivide(a, b);
q[0] = q[1]; q[1] = divret[0];
r[0] = r[1]; r[1] = divret[1];
a = b;
b = divret[1];
step++;
}
if (r[0] != 1)
throw (new ArithmeticException("No inverse!"));
return mr.Difference(p[0], p[1] * q[0]);
}
#endregion
}
}
} | leekyeongtae/TotalManagerment | MonoTorrent/MonoTorrent.Client/Encryption/BigInteger/BigInteger.cs | C# | gpl-3.0 | 41,868 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://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"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.2"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Sequoia: Namespace Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Sequoia
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.2 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
var searchBox = new SearchBox("searchBox", "search",'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */
</script>
<div id="main-nav"></div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
 <ul>
<li>check() : <a class="el" href="dd/da8/namespacesequoia_1_1testing.html#a75993733a577e6b76bb93628fe2b722b">sequoia::testing</a></li>
<li>check_relative_performance() : <a class="el" href="dd/da8/namespacesequoia_1_1testing.html#a851cce1136b7e58818d1ba2b02ddbc6a">sequoia::testing</a></li>
<li>check_semantics() : <a class="el" href="dd/da8/namespacesequoia_1_1testing.html#a7ea32263addad02893d045620bd91446">sequoia::testing</a></li>
<li>failure_message() : <a class="el" href="dd/da8/namespacesequoia_1_1testing.html#a2522541db7e1d610bf0a4e016b3397d3">sequoia::testing</a></li>
<li>general_equivalence_check() : <a class="el" href="dd/da8/namespacesequoia_1_1testing.html#a5fd8ababa0fae7e42c053e162b405489">sequoia::testing</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.2
</small></address>
</body>
</html>
| ojrosten/sequoia | docs/html/namespacemembers_func.html | HTML | gpl-3.0 | 3,525 |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Left - leon.lang.Left</title>
<meta name="description" content="Left - leon.lang.Left" />
<meta name="keywords" content="Left leon.lang.Left" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript">
if(top === self) {
var url = '../../index.html';
var hash = 'leon.lang.Left';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="type">
<div id="definition">
<img src="../../lib/class_big.png" />
<p id="owner"><a href="../package.html" class="extype" name="leon">leon</a>.<a href="package.html" class="extype" name="leon.lang">lang</a></p>
<h1>Left</h1>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">case class</span>
</span>
<span class="symbol">
<span class="name">Left</span><span class="tparams">[<span name="A">A</span>, <span name="B">B</span>]</span><span class="params">(<span name="content">content: <span class="extype" name="leon.lang.Left.A">A</span></span>)</span><span class="result"> extends <a href="Either.html" class="extype" name="leon.lang.Either">Either</a>[<span class="extype" name="leon.lang.Left.A">A</span>, <span class="extype" name="leon.lang.Left.B">B</span>] with <span class="extype" name="scala.Product">Product</span> with <span class="extype" name="scala.Serializable">Serializable</span></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><dl class="attributes block"> <dt>Annotations</dt><dd>
<span class="name">@<a href="../annotation/package$$library.html" class="extype" name="leon.annotation.library">library</a></span><span class="args">()</span>
</dd></dl><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><span class="extype" name="scala.Serializable">Serializable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.Product">Product</span>, <span class="extype" name="scala.Equals">Equals</span>, <a href="Either.html" class="extype" name="leon.lang.Either">Either</a>[<span class="extype" name="leon.lang.Left.A">A</span>, <span class="extype" name="leon.lang.Left.B">B</span>], <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="leon.lang.Left"><span>Left</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.Product"><span>Product</span></li><li class="in" name="scala.Equals"><span>Equals</span></li><li class="in" name="leon.lang.Either"><span>Either</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li>
</ol>
<a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="constructors" class="members">
<h3>Instance Constructors</h3>
<ol><li name="leon.lang.Left#<init>" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="<init>(content:A):leon.lang.Left[A,B]"></a>
<a id="<init>:Left[A,B]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">new</span>
</span>
<span class="symbol">
<span class="name">Left</span><span class="params">(<span name="content">content: <span class="extype" name="leon.lang.Left.A">A</span></span>)</span>
</span>
</h4>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:AnyRef):Boolean"></a>
<a id="!=(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:AnyRef):Boolean"></a>
<a id="==(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="leon.lang.Left#content" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="content:A"></a>
<a id="content:A"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">content</span><span class="result">: <span class="extype" name="leon.lang.Left.A">A</span></span>
</span>
</h4>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="leon.lang.Left#isLeft" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isLeft:Boolean"></a>
<a id="isLeft:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isLeft</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="leon.lang.Left">Left</a> → <a href="Either.html" class="extype" name="leon.lang.Either">Either</a></dd></dl></div>
</li><li name="leon.lang.Left#isRight" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isRight:Boolean"></a>
<a id="isRight:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isRight</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="leon.lang.Left">Left</a> → <a href="Either.html" class="extype" name="leon.lang.Either">Either</a></dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="leon.lang.Left#swap" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="swap:leon.lang.Right[B,A]"></a>
<a id="swap:Right[B,A]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">swap</span><span class="result">: <a href="Right.html" class="extype" name="leon.lang.Right">Right</a>[<span class="extype" name="leon.lang.Left.B">B</span>, <span class="extype" name="leon.lang.Left.A">A</span>]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="leon.lang.Left">Left</a> → <a href="Either.html" class="extype" name="leon.lang.Either">Either</a></dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.Serializable">
<h3>Inherited from <span class="extype" name="scala.Serializable">Serializable</span></h3>
</div><div class="parent" name="java.io.Serializable">
<h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3>
</div><div class="parent" name="scala.Product">
<h3>Inherited from <span class="extype" name="scala.Product">Product</span></h3>
</div><div class="parent" name="scala.Equals">
<h3>Inherited from <span class="extype" name="scala.Equals">Equals</span></h3>
</div><div class="parent" name="leon.lang.Either">
<h3>Inherited from <a href="Either.html" class="extype" name="leon.lang.Either">Either</a>[<span class="extype" name="leon.lang.Left.A">A</span>, <span class="extype" name="leon.lang.Left.B">B</span>]</h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
<script defer="defer" type="text/javascript" id="jquery-js" src="../../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../../lib/template.js"></script>
</body>
</html> | fmlab-iis/LibRef | doc/api/leon/lang/Left.html | HTML | gpl-3.0 | 25,376 |
/*
* LeaseProvider.java May 2004
*
* Copyright (C) 2004, Niall Gallagher <niallg@users.sf.net>
*
* 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 trs.org.simpleframework.util.lease;
import java.util.concurrent.TimeUnit;
/**
* The <code>LeaseProvider</code> is used to issue a lease for a
* named resource. This is effectively used to issue a request
* for a keyed resource to be released when a lease has expired.
* The use of a <code>Lease</code> simplifies the interface to
* the notification and also enables other objects to manage the
* lease without any knowledge of the resource it represents.
*
* @author Niall Gallagher
*/
public interface LeaseProvider<T> {
/**
* This method will issue a <code>Lease</code> object that
* can be used to manage the release of a keyed resource. If
* the lease duration expires before it is renewed then the
* notification is sent, typically to a <code>Cleaner</code>
* implementation, to signify that the resource should be
* recovered. The issued lease can also be canceled.
*
* @param key this is the key for the leased resource
* @param duration this is the duration of the issued lease
* @param unit this is the time unit to issue the lease with
*
* @return a lease that can be used to manage notification
*/
Lease<T> lease(T key, long duration, TimeUnit unit);
/**
* This is used to close the lease provider such that all of
* the outstanding leases are canceled. This also ensures the
* provider can no longer be used to issue new leases, such
* that further invocations of the <code>lease</code> method
* will result in null leases. Once the provider has been
* closes all threads and other such resources are released.
*/
void close();
}
| TehSomeLuigi/SomeLuigisPeripherals2 | src_simpleframework/trs/org/simpleframework/util/lease/LeaseProvider.java | Java | gpl-3.0 | 2,327 |
-- Rockspec data
-- Variables to be interpolated:
--
-- package_name
-- version
local default = {
package = package_name,
version = version.."-1",
source = {
url = "git://github.com/rrthomas/"..package_name..".git",
},
description = {
summary = "Colorer for command-line programs",
detailed = [[cw is a colorer for command-line programs. It is designed to simulate
the environment of the commands being executed, so that when you type
'du', 'df', 'ping', etc. in your shell the output is automatically
colored according to a definition script. You can easily change
or add new scripts, and change the colors used.
]],
homepage = "http://github.com/rrthomas/"..package_name.."/",
license = "GPL",
},
dependencies = {
"lua >= 5.2",
"stdlib >= 41.2",
"optparse >= 1.4",
"luaposix >= 33.3.1",
"ansicolors >= 1.0.2",
"ldoc",
},
build = {
type = "make",
variables = { LUA = "$(LUA)", prefix = "$(PREFIX)" },
copy_directories = {},
},
}
if version ~= "git" then
default.source.branch = "v"..version
end
return {default=default, [""]={}}
| rrthomas/cw | rockspecs.lua | Lua | gpl-3.0 | 1,143 |
/***************************************************************************
** **
** This file is part of SpineCreator, an easy to use, GUI for **
** describing spiking neural network models. **
** Copyright (C) 2013 Alex Cope, Paul Richmond **
** **
** 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/. **
** **
****************************************************************************
** Author: Paul Richmond **
** Website/Contact: http://bimpa.group.shef.ac.uk/ **
****************************************************************************/
#include "dotwriter.h"
DotWriter::DotWriter(RootComponentItem *root)
{
out = NULL;
this->root = root;
}
DotWriter::~DotWriter()
{
if (out != NULL){
delete out;
out = NULL;
}
}
bool DotWriter::writeDotFile(QString file_name)
{
QFile file(file_name);
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
out = new QTextStream(&file);
*out << "digraph G1 {\n";
*out << " graph [fontsize=30 labelloc=\"t\" label=\"NineML Component\" splines=true overlap=false rankdir = \"LR\" nodesep=2.0];\n";
*out << " ratio = auto\n";
writeRegimes();
writeTransitions();
*out << "}\n";
file.close();
return true;
}
else
return false;
}
void DotWriter::writeRegimes()
{
for (uint i=0; i<root->al->RegimeList.size(); i++)
{
Regime *r = root->al->RegimeList[i];
*out << " " << r->name << " [ style = \"filled, bold\"\n";
*out << " penwidth = 1\n";
*out << " fillcolor = \"white\"\n";
*out << " fontname = \"Courier New\"\n";
*out << " shape = \"Mrecord\"\n";
*out << " label = <<table border=\"0\" cellborder=\"0\" cellpadding=\"3\" bgcolor=\"white\">\n";
*out << " <tr>\n";
*out << " <td bgcolor=\"black\" align=\"center\" colspan=\"1\"> <font color=\"white\"> " << r->name << " </font> </td>\n";
*out << " </tr>\n";
for (uint j=0; j< r->TimeDerivativeList.size();j++)
{
TimeDerivative *td = r->TimeDerivativeList[j];
*out << " <tr>\n";
*out << " <td align=\"left\" > d" << td->variable->getName() << "/dt = " << td->maths->getHTMLSafeEquation() << " </td>\n";
*out << " </tr>\n";
}
*out << " </table>>];\n";
}
}
void DotWriter::writeTransitions()
{
for (uint i=0; i<root->al->RegimeList.size(); i++)
{
Regime *r = root->al->RegimeList[i];
for (uint j=0; j<r->OnConditionList.size(); j++)
{
OnCondition *oc = r->OnConditionList[j];
*out << " " << r->name << " -> " << oc->target_regime->name << "\n";
*out << " [ style = \"filled, bold\" \n";
*out << " penwidth = 1 \n";
*out << " fillcolor = \"white\" \n";
*out << " fontname = \"Courier New\" \n";
*out << " label = <<table border=\"0\" cellborder=\"0\" cellpadding=\"3\" bgcolor=\"#C0C0C0\"> \n";
*out << " <tr> \n";
*out << " <td bgcolor=\"blue\" align=\"center\" > <font color=\"white\"> " << "Transition" << " </font> </td> \n";
*out << " </tr> \n";
*out << " <tr> \n";
*out << " <td bgcolor=\"green\" align=\"center\" > <font color=\"black\"> @ OnCondition( " << oc->trigger->maths->getHTMLSafeEquation() << ") </font> </td> \n";
*out << " </tr> \n";
for (uint k=0; k<oc->StateAssignList.size(); k++)
{
StateAssignment *sa = oc->StateAssignList[k];
*out << " <tr> \n";
*out << " <td> Assign: " << sa->variable->getName() << "<= "<< sa->maths->getHTMLSafeEquation() << " </td> \n";
*out << " </tr> \n";
}
for (uint k=0; k<oc->eventOutList.size(); k++)
{
EventOut * eo = oc->eventOutList[k];
*out << " <tr> \n";
*out << " <td> Emit Event: " << eo->port->getName() << " </td> \n";
*out << " </tr>\n";
}
*out << " </table>> ]; \n";
}
for (uint j=0; j<r->OnEventList.size(); j++)
{
OnEvent *oe = r->OnEventList[j];
*out << " " << r->name << " -> " << oe->target_regime->name << "\n";
*out << " [ style = \"filled, bold\" \n";
*out << " penwidth = 1 \n";
*out << " fillcolor = \"white\" \n";
*out << " fontname = \"Courier New\" \n";
*out << " label = <<table border=\"0\" cellborder=\"0\" cellpadding=\"3\" bgcolor=\"#C0C0C0\"> \n";
*out << " <tr> \n";
*out << " <td bgcolor=\"blue\" align=\"center\"> <font color=\"white\"> Transition </font> </td>\n";
*out << " </tr> \n";
*out << " <tr> \n";
*out << " <td bgcolor=\"green\" align=\"center\"> <font color=\"black\"> @ OnEvent( " << oe->src_port->getName() << ") </font> </td> \n";
*out << " </tr> \n";
for (uint k=0; k<oe->StateAssignList.size(); k++)
{
StateAssignment *sa = oe->StateAssignList[k];
*out << " <tr> \n";
*out << " <td> Assign: " << sa->variable->getName() << "<= "<< sa->maths->getHTMLSafeEquation() <<" </td>\n";
*out << " </tr> \n";
}
for (uint k=0; k<oe->eventOutList.size(); k++)
{
EventOut * eo = oe->eventOutList[k];
*out << " <tr> \n";
*out << " <td>Emit Event: "<< eo->port->getName() << " </td> \n";
*out << " </tr>\n";
}
*out << " </table>> ]; \n";
}
}
}
| ajc158/spinecreator | dotwriter.cpp | C++ | gpl-3.0 | 7,423 |
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import {UserService} from "../../services/user/user.service";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
providers: [],
styleUrls: ['./login.scss'],
encapsulation: ViewEncapsulation.None
})
export class LoginComponent {
public view: any = {
authenticated: false,
email: '',
password: ''
};
constructor(private router: Router, private userService: UserService) {
}
login() {
// Probably should use an Angular 2 Resolver instead of this constructor logic, but that whole mechanism seems too weighty
this.userService.getUsers()
.subscribe(
users => {
// Uncomment the next statement if you want to force routing to /TeamSetup
// users.length = 0;
if (users.length === 0) {
this.router.navigateByUrl('/TeamSetup');
} else {
this.router.navigateByUrl('/IdeaFlow');
}
},
error => {
console.log(error);
});
return false;
}
}
| openmastery/ideaflow-profiler | src/views/login/login.component.ts | TypeScript | gpl-3.0 | 1,172 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
$string['essaywiris'] = 'Essay - science';
$string['essaywiris_help'] = 'Like the standard Essay question, but you can deliver different question text by inserting random numbers, formulas or plots. The feedback can also use the random values.';
$string['editingessaywiris'] = 'Editing an essay - math & science question by WIRIS';
$string['addingessaywiris'] = 'Adding an essay - math & science question by WIRIS';
$string['essaywirissummary'] = 'Like the standard Essay question, but you can deliver different question text by inserting random numbers, formulas or plots. The feedback can also use the random values.';
$string['essaywiris_algorithm'] = 'Algorithm';
$string['essaywiris_wiris_variables'] = 'WIRIS variables ';
// From Moodle 2.3.
$string['pluginname'] = 'Essay - science';
$string['pluginname_help'] = 'Like the standard Essay question, but you can deliver different question text by inserting random numbers, formulas or plots. The feedback can also use the random values.';
$string['pluginnamesummary'] = 'Like the standard Essay question, but you can deliver different question text by inserting random numbers, formulas or plots. The feedback can also use the random values.';
$string['pluginnameadding'] = 'Adding an essay - math & science question by WIRIS';
$string['pluginnameediting'] = 'Editing an essay - math & science question by WIRIS';
| nitro2010/moodle | question/type/essaywiris/lang/en/qtype_essaywiris.php | PHP | gpl-3.0 | 2,060 |
package main.utilities;
public class Config {
public static final int MAX_CLIENTS = 5;
public static final int DEFAULT_PORT = 5050;
public static final String DEFAULT_HOST = "127.0.0.1";
public static final int MAX_BORROWED_ITEMS = 3;
//20 seconds for 1 day
public static final int SIMULATED_DAY = 1 * 1 * 2000;
public static final int OVERDUE = 20;
public static final int REGISTRATION_LASTS = 14;
public static final int TERM_LASTS = 118;
public static final String CLERK_PASSWORD = "admin";
public static boolean REGISTRATION_STARTS = false;
public static boolean REGISTRATION_ENDS = false;
public static boolean TERM_ENDS = false;
}
| IsaacGuan/AcademicTracking | src/main/utilities/Config.java | Java | gpl-3.0 | 674 |
package pg
import "strings"
const (
createTmpl = `
// Create%[1]s inserts an entry into DB
func Create%[1]s(db cruderQueryRower, x %[2]s) (*%[2]s, error) {
var y %[2]s
err := db.QueryRow(
` + "`" + `INSERT INTO %s (%s) VALUES (%s)
RETURNING %s` + "`" + `,
%s,
).Scan(%s)
return &y, err
}
`
)
// GenerateCreate generates the Create method for the struct
func (g *PG) GenerateCreate() {
g.GenerateType(typeQueryRowerInterface)
var suffix string
if !g.SkipSuffix {
suffix = g.structModel
}
g.Printf(createTmpl,
suffix,
g.structModel,
g.TableName,
strings.Join(g.writeFieldDBNames(""), ", "),
strings.Join(g.placeholderStrings(len(g.writeFieldDBNames(""))), ", "),
strings.Join(g.readFieldDBNames(""), ", "),
strings.Join(g.writeFieldNames("x."), ", "),
strings.Join(g.readFieldNames("&y."), ", "),
)
}
| pengux/cruder | generator/pg/create.go | GO | gpl-3.0 | 840 |
/* * * * *
* AzRgforest.cpp
* Copyright (C) 2011, 2012 Rie Johnson
*
* This software may be modified and distributed under the terms
* of the MIT license. See the COPYING file for details.
* * * * */
#include "AzRgforest.hpp"
#include "AzHelp.hpp"
#include "AzRgf_kw.hpp"
/*-------------------------------------------------------------------*/
void AzRgforest::cold_start(const char *param,
const AzSmat *m_x,
const AzDvect *v_y,
const AzSvFeatInfo *featInfo,
const AzDvect *v_fixed_dw,
const AzOut &out_req)
{
out = out_req;
s_config.reset(param);
AzParam az_param(param);
int max_tree_num = resetParam(az_param);
setInput(az_param, m_x, featInfo);
reg_depth->reset(az_param, out); /* init regularizer on node depth */
v_p.reform(v_y->rowNum());
opt->cold_start(loss_type, data, reg_depth, /* initialize optimizer */
az_param, v_y, v_fixed_dw, out, &v_p);
initTarget(v_y, v_fixed_dw);
initEnsemble(az_param, max_tree_num); /* initialize tree ensemble */
fs->reset(az_param, reg_depth, out); /* initialize node search */
az_param.check(out);
l_num = 0; /* initialize leaf node counter */
if (!beVerbose) {
out.deactivate(); /* shut up after printing everyone's config */
}
time_init(); /* initialize time measure ment */
end_of_initialization();
}
/*-------------------------------------------------------------------*/
void AzRgforest::warm_start(const char *param,
const AzSmat *m_x,
const AzDvect *v_y,
const AzSvFeatInfo *featInfo,
const AzDvect *v_fixed_dw,
const AzTreeEnsemble *inp_ens,
const AzOut &out_req)
{
const char *eyec = "AzRgforest::warm_start";
out = out_req;
if (inp_ens->orgdim() > 0 &&
inp_ens->orgdim() != m_x->rowNum()) {
AzBytArr s("Mismatch in feature dimensionality. ");
s.cn(inp_ens->orgdim());s.c(" (tree ensemeble), ");s.cn(m_x->rowNum());s.c(" (dataset).");
throw new AzException(AzInputError, eyec, s.c_str());
}
s_config.reset(param);
AzParam az_param(param);
int max_tree_num = resetParam(az_param);
warmup_timer(inp_ens, max_tree_num); /* timers are modified for warm-start */
setInput(az_param, m_x, featInfo);
AzTimeLog::print("Warming-up trees ... ", log_out);
warmupEnsemble(az_param, max_tree_num, inp_ens); /* v_p is set */
reg_depth->reset(az_param, out); /* init regularizer on node depth */
AzTimeLog::print("Warming-up the optimizer ... ", log_out);
opt->warm_start(loss_type, data, reg_depth, /* initialize optimizer */
az_param, v_y, v_fixed_dw, out,
ens, &v_p);
initTarget(v_y, v_fixed_dw);
fs->reset(az_param, reg_depth, out); /* initialize node search */
az_param.check(out);
l_num = ens->leafNum(); /* warm-up #leaf */
if (!beVerbose) {
out.deactivate(); /* shut up after printing everyone's config */
}
time_init(); /* initialize time measure ment */
end_of_initialization();
AzTimeLog::print("End of warming-up ... ", log_out);
}
/*------------------------------------------------------------------*/
/* Update test_timer, opt_timer */
void AzRgforest::warmup_timer(const AzTreeEnsemble *inp_ens,
int max_tree_num)
{
const char *eyec = "AzRgforest::warmup_timer";
/*--- check consistency and adjust intervals for warm start ---*/
int inp_leaf_num = inp_ens->leafNum();
if (lmax_timer.reachedMax(inp_leaf_num) ||
max_tree_num < inp_ens->size()) {
AzBytArr s("The model given for warm-start is already over ");
s.concat("the requested maximum size of the models: #leaf=");
s.cn(inp_leaf_num); s.c(", #tree="); s.cn(inp_ens->size());
throw new AzException(AzInputError, eyec, s.c_str());
}
int inp_leaf_num_test = inp_leaf_num;
if (inp_leaf_num_test % test_timer.inc == 1) --inp_leaf_num_test;
test_timer.chk += inp_leaf_num_test;
int inp_leaf_num_opt = inp_leaf_num;
if (inp_leaf_num_opt % opt_timer.inc == 1) --inp_leaf_num_opt;
opt_timer.chk += inp_leaf_num_opt;
}
/*------------------------------------------------------------------*/
/* output: ens, output: v_p */
void AzRgforest::warmupEnsemble(AzParam &az_param, int max_tree_num,
const AzTreeEnsemble *inp_ens)
{
ens->warm_start(inp_ens, data, az_param, &s_temp_for_trees,
out, max_tree_num, s_tree_num, &v_p);
/*--- always have one unsplit root: represent the next tree ---*/
rootonly_tree->reset(az_param);
rootonly_tree->makeRoot(data);
rootonly_tx = max_tree_num + 1; /* any number that doesn't overlap other trees */
}
/*-------------------------------------------------------------------*/
/* input: v_p */
void AzRgforest::initTarget(const AzDvect *v_y,
const AzDvect *v_fixed_dw)
{
target.reset(v_y, v_fixed_dw);
resetTarget();
}
/*-------------------------------------------------------------------*/
void AzRgforest::setInput(AzParam &p,
const AzSmat *m_x,
const AzSvFeatInfo *featInfo)
{
dflt_data.reset_data(out, m_x, p, beTight, featInfo);
data = &dflt_data;
f_pick = -1;
if (f_ratio > 0) {
f_pick = (int)((double)data->featNum() * f_ratio);
f_pick = MAX(1, f_pick);
AzPrint::writeln(out, "#feature to be sampled = ", f_pick);
}
}
/*------------------------------------------------------------------*/
void AzRgforest::initEnsemble(AzParam &az_param, int max_tree_num)
{
const char *eyec = "AzRgforest::initEnsemble";
if (max_tree_num < 1) {
throw new AzException(AzInputNotValid, "AzRgforest::initEnsemble",
"max# must be positive");
}
ens->cold_start(az_param, &s_temp_for_trees, data->dataNum(),
out, max_tree_num, data->featNum());
/*--- always have one unsplit root: represent the next tree ---*/
rootonly_tree->reset(az_param);
rootonly_tree->makeRoot(data);
rootonly_tx = max_tree_num + 1; /* any number that doesn't overlap other trees */
}
/*-------------------------------------------------------------------*/
AzRgfTree *AzRgforest::tree_to_grow(int &best_tx, /* inout */
int &best_nx) /* inout */
{
if (best_tx != rootonly_tx) {
return ens->tree_u(best_tx);
}
else {
// Make new tree
AzRgfTree *tree = ens->new_tree(&best_tx); /* best_tx is updated */
tree->reset(out);
best_nx = tree->makeRoot(data);
return tree;
}
}
/*-------------------------------------------------------------------*/
AzTETrainer_Ret AzRgforest::proceed_until()
{
AzTETrainer_Ret ret = AzTETrainer_Ret_Exit;
for ( ; ; ) {
/*--- grow the forest ---*/
bool doExit = growForest();
if (doExit) break;
/*--- optimize weights ---*/
if (opt_timer.ringing(false, l_num)) {
optimize_resetTarget();
show_tree_info();
}
/*--- time to test? ---*/
if (test_timer.ringing(false, l_num)) {
ret = AzTETrainer_Ret_TestNow;
break; /* time to test */
}
}
if (ret == AzTETrainer_Ret_Exit) {
if (!isOpt) {
optimize_resetTarget();
}
time_show();
end_of_training();
}
return ret;
}
/*------------------------------------------------------------------*/
void AzRgforest::time_show()
{
if (doTime) {
AzOut my_out = out;
my_out.activate();
if (my_out.isNull()) return;
AzPrint o(my_out);
o.printBegin("", ", ", "=");
o.print("search_time", (double)(search_time/(double)CLOCKS_PER_SEC));
o.print("opt_time", (double)(opt_time/(double)CLOCKS_PER_SEC));
o.printEnd();
}
}
/*------------------------------------------------------------------*/
bool AzRgforest::growForest()
{
clock_t b_time;
time_begin(&b_time);
/*--- find the best split ---*/
AzTrTsplit best_split;
searchBestSplit(&best_split);
if (shouldExit(&best_split)) { /* exit if no more split */
return true; /* exit */
}
/*--- split the node ---*/
double w_inc; // weight will be incremented.
int leaf_nx[2] = {-1, -1};
const AzRgfTree *tree = splitNode(&best_split, &w_inc, leaf_nx);
if (lmax_timer.reachedMax(l_num, "AzRgforest: #leaf", out)) {
return true; /* #leaf reached max; exit */
}
/*--- update target ---*/
updateTarget(tree, leaf_nx, w_inc);
time_end(b_time, &search_time);
return false; /* don't exit */
}
/* changes: isOpt, l_num */
/*------------------------------------------------------------------*/
const AzRgfTree *AzRgforest::splitNode(AzTrTsplit *best_split, /* (tx,nx) may be updated */
/*--- output ---*/
double *w_inc,
int leaf_nx[2])
{
AzRgfTree *tree = tree_to_grow(best_split->tx, best_split->nx);
double old_w = tree->node(best_split->nx)->weight;
tree->splitNode(data, best_split);
double new_w = tree->node(best_split->nx)->weight;
isOpt = false;
++l_num; /* if it wasn't root, one leaf was removed and two leaves were added */
if (best_split->nx == tree->root()) {
++l_num;
}
*w_inc = new_w - old_w;
leaf_nx[0] = tree->node(best_split->nx)->le_nx;
leaf_nx[1] = tree->node(best_split->nx)->gt_nx;
return tree;
}
/*------------------------------------------------------------------*/
bool AzRgforest::shouldExit(const AzTrTsplit *best_split) const
{
/*--- exit criteria ---*/
if (best_split->tx < 0 || best_split->fx < 0) {
AzTimeLog::print("AzRgforest::shouldExit, No more split", out);
return true;
}
if (best_split->tx == rootonly_tx &&
ens->isFull()) {
AzTimeLog::print("AzRgforest::shouldExit, #tree reached max ... ", out);
return true;
}
return false;
}
/*------------------------------------------------------------------*/
void AzRgforest::searchBestSplit(AzTrTsplit *best_split) /* must be initialize by caller */
{
bool doRefreshAll = false;
if (doForceToRefreshAll) { /* this option is for testing the code */
doRefreshAll = true;
}
if (s_tree_num > 1) {
doRefreshAll = true;
}
const int last_tx = ens->lastIndex();
/*--- decide which trees should be searched ---*/
int my_first = MAX(0, last_tx + 1 - s_tree_num);
if (my_first-1 >= 0) {
/*
* since tree[my_first-1] will never be searched again, release some memory.
* split info may've been already removed, but that's okay
*/
ens->tree_u(my_first-1)->releaseWork();
}
/*--- search! ---*/
double nn = data->dataNum();
const AzTrTtarget *tar = ⌖
AzTrTtarget my_tar;
if (target.isWeighted()) {
my_tar.reset(&target);
my_tar.weight_tarDw();
my_tar.weight_dw();
nn = target.sum_fixed_dw();
tar = &my_tar;
}
if (f_pick > 0) {
fs->pickFeats(f_pick, data->featNum());
}
AzRgf_FindSplit_input input(-1, data, tar, lam_scale, nn);
for (int tx = my_first; tx <= last_tx; ++tx) {
input.tx = tx;
ens->tree_u(tx)->findSplit(fs, input, doRefreshAll, best_split);
}
/*--- rootonly tree ---*/
if (!doPassiveRoot ||
best_split->tx < 0 || best_split->fx < 0) {
input.tx = rootonly_tx;
rootonly_tree->findSplit(fs, input, doRefreshAll, best_split);
}
}
/*------------------------------------------------------------------*/
/* print this to stdout only when Dump is specified */
void AzRgforest::show_tree_info() const
{
if (dmp_out.isNull()) return;
if (out.isNull()) return;
int t_num = ens->size();
double max_max_depth = 0, avg_max_depth = 0;
double max_size = 0, avg_size = 0;
for (int tx = 0; tx < t_num; ++tx) {
const AzTrTree_ReadOnly *tree = ens->tree(tx);
int max_depth = tree->maxDepth();
max_max_depth = MAX(max_max_depth, max_depth);
avg_max_depth += max_depth;
int tree_size = tree->countLeafNum();
max_size = MAX(max_size, tree_size);
avg_size += tree_size;
}
if (t_num > 0) {
avg_max_depth /= (double)t_num;
avg_size /= (double)t_num;
}
AzPrint o(out);
o.printBegin("", ",", "=");
o.print("#tree", t_num);
o.print("max_depth-max,avg");
o.pair_inParen(max_max_depth, avg_max_depth, ",");
o.print("#leaf-max,avg");
o.pair_inParen(max_size, avg_size, ",");
o.printEnd();
}
/*------------------------------------------------------------------*/
void AzRgforest::optimize_resetTarget()
{
clock_t b_time;
time_begin(&b_time);
int t_num = ens->size();
AzBytArr s("Calling optimizer with ");
s.cn(t_num); s.c(" trees and "); s.cn(l_num); s.c(" leaves");
AzTimeLog::print(s, out);
opt->update(data, ens, &v_p);
resetTarget();
for (int tx = 0; tx < t_num; ++tx) {
ens->tree_u(tx)->removeSplitAssessment(); /* since weights changed */
}
isOpt = true;
time_end(b_time, &opt_time);
}
/* updates target and v_p */
/*------------------------------------------------------------------*/
void AzRgforest::_updateTarget_OtherLoss(const AzRgfTree *tree,
const int leaf_nx[2],
double w_inc)
{
const double *y = target.y()->point();
double *p = v_p.point_u();
double *tar_dw = target.tarDw_forUpdate()->point_u();
double *dw = target.dw_forUpdate()->point_u();
for (int kx = 0; kx < 2; ++kx) {
const AzTrTreeNode *np = tree->node(leaf_nx[kx]);
const int *dxs = np->data_indexes();
double new_w = np->weight;
for (int ix = 0; ix < np->dxs_num; ++ix) {
int dx = dxs[ix];
p[dx] += (new_w + w_inc);
AzLosses o = AzLoss::getLosses(loss_type, p[dx], y[dx], py_adjust);
dw[dx] = o.loss2;
tar_dw[dx] = o._loss1;
}
}
}
/*------------------------------------------------------------------*/
/* static */
//! _updateTarget_OtherLoss could be called for LS too.
// But perhaps this is faster.
void AzRgforest::_updateTarget_LS(const AzRgfTree *tree,
const int leaf_nx[2],
double w_inc,
AzTrTtarget *target, /* updated */
AzDvect *v_p) /* updated */
{
double *r = target->tarDw_forUpdate()->point_u();
double *p = v_p->point_u();
for (int kx = 0; kx < 2; ++kx) {
const AzTrTreeNode *np = tree->node(leaf_nx[kx]);
const int *dxs = np->data_indexes();
double new_w = np->weight;
for (int ix = 0; ix < np->dxs_num; ++ix) {
int dx = dxs[ix];
p[dx] += new_w;
r[dx] -= new_w;
if (w_inc != 0) {
p[dx] += w_inc;
r[dx] -= w_inc;
}
}
}
}
/* Input: y, p */
/* Output: tar, dw, loss */
/*------------------------------------------------------------------*/
void AzRgforest::resetTarget()
{
if (loss_type == AzLoss_Square) {
target.resetTarDw_residual(&v_p);
return;
}
AzDvect *v_tar_dw = target.tarDw_forUpdate(); /* tar*dw */
AzDvect *v_dw = target.dw_forUpdate();
/*--- train for -L'/L'' ---*/
lam_scale =
AzLoss::negativeDeriv12(loss_type, &v_p, target.y(), NULL,
&py_adjust,
v_tar_dw, /* -L' */
v_dw); /* L'' */
if (!out.isNull() && AzLoss::isExpoFamily(loss_type)) {
show_forExpoFamily(v_dw);
}
}
/*-------------------------------------------------------------------*/
/* print to stdout only when Dump is specified */
void AzRgforest::show_forExpoFamily(const AzDvect *v_dw) const
{
if (dmp_out.isNull()) return;
if (out.isNull()) return;
double w_sum = v_dw->sum();
double max_w = v_dw->max();
double min_w = v_dw->min();
AzPrint o(out);
o.reset_options();
o.printBegin("resetTarget", ",");
o.printV("wsum=", w_sum); o.printV("maxw=", max_w); o.printV("minw=", min_w);
o.printV("py_adj=", py_adjust); o.printV("lam_scale=", lam_scale);
o.printEnd();
}
/*-------------------------------------------------------------------*/
void
AzRgforest::apply(AzTETrainer_TestData *td,
AzDvect *v_test_p, /* output vector (predection) */
AzTE_ModelInfo *info, /* may be NULL */
AzTreeEnsemble *out_ens) /* may be NULL */ const
{
const AzDataForTrTree *test_data = AzTETrainer::_data(td);
int f_num = -1, nz_f_num = -1;
AzBmat *b_test_tran = AzTETrainer::_b(td);
if (!isOpt) { /* weights have not been corrected */
AzTimeLog::print("Testing (branch-off for end-of-training optimization)", out);
AzBmat temp_b(b_test_tran);
temp_apply_copy_to(out_ens, test_data, &temp_b, v_test_p,
&f_num, &nz_f_num);
}
else {
AzTimeLog::print("Testing ... ", out);
opt->apply(test_data, b_test_tran, ens, v_test_p, /* prediction */
&f_num, &nz_f_num); /*info */
if (out_ens != NULL) {
ens->copy_to(out_ens, s_config.c_str(), signature());
}
}
/*--- info ---*/
if (info != NULL) {
info->leaf_num = l_num;
info->tree_num = ens->size();
info->f_num = f_num;
info->nz_f_num = nz_f_num;
info->s_sign.reset(signature());
info->s_config.reset(&s_config);
}
}
/*--------------------------------------------------------*/
void AzRgforest::copy_to(AzTreeEnsemble *out_ens) const
{
if (isOpt) {
ens->copy_to(out_ens, s_config.c_str(), signature());
}
else {
AzTimeLog::print(" ... branch off for end-of-training optimization ...", out);
temp_apply_copy_to(out_ens, NULL, NULL, NULL, NULL, NULL);
}
}
/*--------------------------------------------------------*/
int AzRgforest::adjustTestInterval(int lnum_inc_test, int lnum_inc_opt)
{
int org_lnum_inc_test = lnum_inc_test;
if (s_temp_for_trees.length() > 0 &&
lnum_inc_test < lnum_inc_opt) {
AzPrint::writeln(out, "Warning: test interval must not be smaller than optimization interval when the following is specified: ", kw_temp_for_trees);
lnum_inc_test = lnum_inc_opt;
}
else if (lnum_inc_test > lnum_inc_opt) {
lnum_inc_test = (lnum_inc_test+lnum_inc_opt/2)/lnum_inc_opt*lnum_inc_opt;
}
else if (lnum_inc_opt % lnum_inc_test != 0) {
int div = lnum_inc_opt / lnum_inc_test;
for ( ; ; --div) {
if (lnum_inc_opt % div == 0) {
lnum_inc_test = lnum_inc_opt / div;
break;
}
}
}
if (org_lnum_inc_test != lnum_inc_test) {
AzBytArr s("Changing test interval: ");
s.cn(org_lnum_inc_test); s.c("->"); s.cn(lnum_inc_test);
AzPrint::writeln(out, s);
}
return lnum_inc_test;
}
/*--------------------------------------------------------*/
/*--------------------------------------------------------*/
int AzRgforest::resetParam(AzParam &p)
{
const char *eyec = "AzRgforest::resetParam";
/*--- for storing data indexes in the trees to disk ---*/
/*--- this must be called before adjustTestInterval. ---*/
p.vStr(kw_temp_for_trees, &s_temp_for_trees);
/*--- loss function ---*/
// p.vLoss(kw_loss, &loss_type);
AzBytArr s_loss;
p.vStr(kw_loss, &s_loss);
if (s_loss.length() > 0) loss_type = AzLoss::lossType(s_loss.c_str());
/*--- weight optimization interval ---*/
int lnum_inc_opt = lnum_inc_opt_dflt;
p.vInt(kw_lnum_inc_opt, &lnum_inc_opt);
if (lnum_inc_opt <= 0) {
throw new AzException(AzInputNotValid, eyec, kw_lnum_inc_opt,
"must be positive");
}
opt_timer.reset(lnum_inc_opt);
/*--- # of trees to search ---*/
p.vInt(kw_s_tree_num, &s_tree_num);
if (s_tree_num <= 0) {
throw new AzException(AzInputNotValid, eyec, kw_s_tree_num,
"must be positive");
}
/*--- when to stop: max #leaf, max #tree ---*/
int max_tree_num = -1, max_lnum = max_lnum_dflt;
p.vInt(kw_max_tree_num, &max_tree_num);
p.vInt(kw_max_lnum, &max_lnum);
if (max_tree_num <= 0) {
if (max_lnum > 0) max_tree_num = MAX(1, max_lnum / 2);
else {
AzBytArr s("Specify "); s.c(kw_max_lnum); s.c(" and/or "); s.c(kw_max_tree_num);
throw new AzException(AzInputMissing, eyec, s.c_str());
}
}
lmax_timer.reset(max_lnum);
/*--- when to test: test interval ---*/
int lnum_inc_test = lnum_inc_test_dflt;
p.vInt(kw_lnum_inc_test, &lnum_inc_test);
if (lnum_inc_test <= 0) {
throw new AzException(AzInputNotValid, eyec, kw_lnum_inc_test,
"must be positive");
}
lnum_inc_test = adjustTestInterval(lnum_inc_test, lnum_inc_opt);
test_timer.reset(lnum_inc_test);
/*--- memory handling ---*/
p.vStr(kw_mem_policy, &s_mem_policy);
if (s_mem_policy.length() <= 0) {
beTight = false;
} else if (s_mem_policy.compare(mp_beTight) == 0) {
beTight = true;
} else if (s_mem_policy.compare(mp_not_beTight) == 0) {
beTight = false;
} else {
AzBytArr s(kw_mem_policy); s.c(" should be either ");
s.c(mp_beTight); s.c(" or "); s.c(mp_not_beTight);
throw new AzException(AzInputNotValid, eyec, s.c_str());
}
p.vFloat(kw_f_ratio, &f_ratio);
if (f_ratio > 1) {
throw new AzException(AzInputNotValid, kw_f_ratio, "must be between 0 and 1.");
}
int random_seed = -1;
if (f_ratio > 0 && f_ratio < 1) {
p.vInt(kw_random_seed, &random_seed);
if (random_seed > 0) {
srand(random_seed);
}
}
p.swOn(&doPassiveRoot, kw_doPassiveRoot);
/*--- for maintenance purposes ---*/
p.swOn(&doForceToRefreshAll, kw_doForceToRefreshAll);
p.swOn(&beVerbose, kw_forest_beVerbose); /* for compatibility */
p.swOn(&beVerbose, kw_beVerbose);
p.swOn(&doTime, kw_doTime);
/*--- display parameters ---*/
if (!out.isNull()) {
AzPrint o(out);
o.ppBegin("AzRgforest", "Forest-level");
// o.printLoss(kw_loss, loss_type);
o.printV(kw_loss, AzLoss::lossName(loss_type));
o.printV(kw_max_lnum, max_lnum);
o.printV(kw_max_tree_num, max_tree_num);
o.printV(kw_lnum_inc_opt, lnum_inc_opt);
o.printV(kw_lnum_inc_test, lnum_inc_test);
o.printV(kw_s_tree_num, s_tree_num);
o.printSw(kw_doForceToRefreshAll, doForceToRefreshAll);
o.printSw(kw_beVerbose, beVerbose);
o.printSw(kw_doTime, doTime);
o.printV_if_not_empty(kw_mem_policy, s_mem_policy);
o.printV_if_not_empty(kw_temp_for_trees, &s_temp_for_trees);
o.printV(kw_f_ratio, f_ratio);
o.printV(kw_random_seed, random_seed);
o.printSw(kw_doPassiveRoot, doPassiveRoot);
o.ppEnd();
}
if (loss_type == AzLoss_None) {
throw new AzException(AzInputNotValid, eyec, kw_loss);
}
return max_tree_num;
}
/*------------------------------------------------*/
void AzRgforest::printHelp(AzHelp &h) const
{
fs->printHelp(h);
h.begin(Azforest_config, "AzRgforest", "Forest-wide control");
h.item(kw_loss, help_loss, AzLoss::lossName(loss_type_dflt));
AzDataPool<AzBytArr> pool_desc;
AzLoss::help_lines(h.getLevel(), &pool_desc);
for (int ix = 0; ix < pool_desc.size(); ++ix) {
h.writeln_desc(pool_desc.point(ix)->c_str());
}
h.item(kw_max_lnum, help_max_lnum, max_lnum_dflt);
h.item_experimental(kw_max_tree_num, help_max_tree_num, "Don't care");
h.item(kw_lnum_inc_opt, help_lnum_inc_opt, lnum_inc_opt_dflt);
h.item(kw_lnum_inc_test, help_lnum_inc_test, lnum_inc_test_dflt);
h.item(kw_s_tree_num, help_s_tree_num, s_tree_num_dflt);
h.item_experimental(kw_temp_for_trees, help_temp_for_trees);
h.item_experimental(kw_f_ratio, help_f_ratio);
h.item_experimental(kw_doPassiveRoot, help_doPassiveRoot);
h.end();
reg_depth->printHelp(h);
opt->printHelp(h);
ens->printHelp(h);
h.begin(Azforest_config, "AzRgforest", "Info display");
h.item(kw_doTime, help_doTime);
h.item(kw_beVerbose, help_beVerbose);
h.item(kw_mem_policy, help_mem_policy, mp_not_beTight);
h.end();
}
| fukatani/rgf_python | RGF/src/tet/AzRgforest.cpp | C++ | gpl-3.0 | 24,218 |
-- Gray's Illusions, for Tales of Maj'Eyal.
--
-- 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/>.
local tiles = math.ceil(math.sqrt(tx*tx+ty*ty))
local tx = tx * engine.Map.tile_w
local ty = ty * engine.Map.tile_h
local length = math.sqrt(tx*tx+ty*ty)
local direction = math.atan2(ty, tx)
local offsetLength = engine.Map.tile_w * 0.3
-- Populate the beam based on the forks
return { blend_mode = core.particles.BLEND_SHINY, generator = function()
local angle = direction
local rightAngle = direction + math.rad(90)
local r = rng.range(2, length)
local spread_percent = r / length * 0.7 + 0.3
local offset = rng.range(-offsetLength, offsetLength) * spread_percent
local cr, cg, cb
if rng.percent(50) then
cr = rng.range(128, 216) / 255
cg = 32 / 255
cb = rng.range(128, 216) / 255
else
cr = rng.range(128, 216) / 255
cg = rng.range(64, 108) / 255
cb = 32 / 255
end
return {
life = 5, trail=1,
size = rng.range(6, 8), sizev = -0.4, sizea = 0,
x = r * math.cos(angle) + math.cos(rightAngle) * offset, xv = 0, xa = 0,
y = r * math.sin(angle) + math.sin(rightAngle) * offset, yv = 0, ya = 0,
dir = angle + math.rad(180), dirv = 0, dira = 0,
vel = rng.range(1, 3), velv = 0, vela = 0,
r = cr, rv = 0, ra = 0,
g = cg, gv = 0, ga = 0,
b = cb, bv = 0, ba = 0,
a = rng.range(80, 196) / 255, av = 0, aa = 0,
}
end, },
function(self)
self.ps:emit(12*tiles)
end,
5*12*tiles
--[==[
-- Populate the beam based on the forks
return { blend_mode = core.particles.BLEND_SHINY, generator = function()
local angle = direction
local rightAngle = direction + math.rad(90)
local radius = rng.range(2, length)
local spread_percent = r / length * 0.7 + 0.3
local offset = rng.range(-offsetLength, offsetLength) * spread_percent
local r, g, b
--[[
if rng.percent(50) then
--]]
r = rng.range(150, 250) / 255
g = rng.range(100, 160) / 255
b = rng.range(10, 30) / 255
--[[
else
r = rng.range(150, 250) / 255
g = rng.range(10, 30) / 255
b = rng.range(150, 250) / 255
end
--]]
return {
life = 5, trail=1,
size = rng.range(6, 8), sizev = -0.4, sizea = 0,
x = radius * math.cos(angle) + math.cos(rightAngle) * offset, xv = 0, xa = 0,
y = radius * math.sin(angle) + math.sin(rightAngle) * offset, yv = 0, ya = 0,
dir = angle + math.rad(180), dirv = 0, dira = 0,
vel = rng.range(1, 3), velv = 0, vela = 0,
r = 0.5, rv = 0, ra = 0,
g = 0.5, gv = 0, ga = 0,
b = 0.5, bv = 0, ba = 0,
a = rng.range(80, 196) / 255, av = 0, aa = 0,
}
end, },
function(self)
self.ps:emit(12*tiles)
end,
5*12*tiles
--]==]
| gwx/tome-grayswandir-illusion | overload/data/gfx/particles/mental_pressure.lua | Lua | gpl-3.0 | 3,163 |
use bytecodes::bytecode;
use context::Context;
use stack::StackEntry;
use constants;
use exceptions::{throw_exception, throw_exception_from_interpretererror, InterpreterException};
use traits::{BufferAccessor, HasType};
// macro allowing to simplify null reference check
#[macro_export]
macro_rules! check_null_reference {
($variable: ident, $ctx: ident) => {
if !$variable.is_of_type(constants::PrimitiveType::REFERENCE)
|| $variable.value == constants::NULL_HANDLE
{
return throw_exception($ctx, InterpreterException::NullPointerException);
}
};
}
///
/// Manages aaload, baload, saload, iaload
///
pub fn xaload(
execution_context: &mut Context,
type_: constants::PrimitiveType,
) -> Result<(), InterpreterException> {
let arrayref = execution_context
.operand_stack
.pop_check_type(constants::PrimitiveType::REFERENCE)
.unwrap();
let index = execution_context
.operand_stack
.pop_check_type(constants::PrimitiveType::SHORT)
.unwrap();
check_null_reference!(arrayref, execution_context);
let associated_reference = execution_context
.object_manager
.get_object(arrayref.value as usize);
if let Ok(e) = associated_reference {
// consistency check to make sure it is an array
assert!(e.is_array());
// in case of arrays, the primitive type represents the type of its elements
assert!(e.is_of_type(type_));
match type_ {
// for short and references, we perform thee same type of checks and
// fetch the array identically (2 by 2)
constants::PrimitiveType::SHORT | constants::PrimitiveType::REFERENCE => {
let size_one_entry = constants::REFERENCE_SIZE;
match e.read_s((index.value as usize) * size_one_entry) {
// REFERENCE_SIZE == SHORT_SIZE here
Ok(res) => {
execution_context
.operand_stack
.push(StackEntry::from_values(res, type_));
}
Err(e) => {
return throw_exception_from_interpretererror(execution_context, e);
}
}
}
// for bytes, each entry is one byte long
constants::PrimitiveType::BYTE => {
let size_one_entry = constants::BYTE_SIZE;
match e.read_b((index.value as usize) * size_one_entry) {
// retrieve v(alue of the reference of the array
Ok(res) => {
execution_context.operand_stack.bpush(res);
}
Err(e) => return throw_exception_from_interpretererror(execution_context, e),
}
}
// or integers readings are performed 4 bytes by 4 bytes
constants::PrimitiveType::INTEGER => {
let size_one_entry = constants::INTEGER_SIZE;
match e.read_i((index.value as usize) * size_one_entry) {
// retrieve value of the reference of the array
Ok(res) => {
execution_context.operand_stack.ipush(res);
}
Err(e) => return throw_exception_from_interpretererror(execution_context, e),
}
}
constants::PrimitiveType::UNKNOWN => {
panic!("Unknown type !");
}
}
} else {
return throw_exception(execution_context, associated_reference.err().unwrap());
}
Ok(())
}
///
/// Manages astore, sstore, istore and assoiated xstore_x (because index is passed as parameter)
///
pub fn xstore(execution_context: &mut Context, index: u8, type_: constants::PrimitiveType) {
match type_ {
// storing shorts and references follow the same pattern
constants::PrimitiveType::SHORT | constants::PrimitiveType::REFERENCE => {
// pop and check the type loaded from stack
let value_to_put = execution_context
.operand_stack
.pop_check_type(type_)
.unwrap();
//update local variable
execution_context
.current_frame_mut()
.unwrap()
.set_local(index as i16, value_to_put)
.unwrap();
}
// for integers, we pop and check 2 times on the stack
constants::PrimitiveType::INTEGER => {
let value_to_put1 = execution_context
.operand_stack
.pop_check_type(type_)
.unwrap();
let value_to_put2 = execution_context
.operand_stack
.pop_check_type(type_)
.unwrap();
// ... and we update 2 indexes in local variables stack
execution_context
.current_frame_mut()
.unwrap()
.set_local(index as i16, value_to_put1)
.unwrap();
execution_context
.current_frame_mut()
.unwrap()
.set_local((index + 1) as i16, value_to_put2)
.unwrap();
}
_ => panic!("Unknown type"),
};
}
///
/// Manages astore, sstore, istore and assoiated xstore_x (because index is passed as parameter)
/// Note: for aaload, some supplementary checks are performed to ensure consistency of the operaton
/// See chapter 7.5.2 from JCVM specification for more details
///
pub fn xastore(
execution_context: &mut Context,
type_: constants::PrimitiveType,
) -> Result<(), InterpreterException> {
// in stack:
// array ref
// index
// value
// first, pop the array reference and check it is not null
let array_ref = execution_context
.operand_stack
.pop_check_type(constants::PrimitiveType::REFERENCE)
.unwrap();
check_null_reference!(array_ref, execution_context);
// make sure it is an array of the correct type
let array = execution_context
.object_manager
.get_object(array_ref.value as usize)
.unwrap();
// check that is is really an array
if !array.is_array() || !array.is_of_type(type_) {
return Err(InterpreterException::SecurityException);
}
let index = execution_context
.operand_stack
.pop_check_type(constants::PrimitiveType::SHORT)
.unwrap();
/*let value = execution_context
.operand_stack
.pop_check_type(type_)
.unwrap_or(return Err(InterpreterException::SecurityException));*/
Ok(())
}
| Incognitas/Orion | src/interpreterutils.rs | Rust | gpl-3.0 | 6,746 |
cmd_config_help() {
cat <<_EOF
config
Run configuration scripts inside the container.
_EOF
}
cmd_config() {
ds inject set_prompt.sh
}
| docker-scripts/ds | test/app/cmd/config.sh | Shell | gpl-3.0 | 156 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import database.Database;
import database.InputOutput;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Item;
import model.Order;
import model.User;
import static service.UserService.FILE_NAME;
import service.UserService;
/**
*
* @author Amir
*/
public class OrderService implements Serializable{
List<Order> orderList = new ArrayList<>();
Database d;
InputOutput io = new InputOutput();
final static String FILE_NAME = "C:\\Users\\Administrator\\Desktop\\newOrder";
final static String FILE_NAME_Amir = "C:\\Users\\Amir\\Desktop\\newOrder";
UserService userService = new UserService();
public OrderService() throws SQLException {
Order ord = new Order(2, "Tom");
ord.AddItemToOrder(new Item("Name", 10, "Restaurant"));
//this.d = new Database();
//orderList = d.GetOrder("SELECT * FROM `order`");
orderList.add(ord);
//write();
System.err.println("Ran the Write ORDER");
read();
System.err.println("Ran the Read ORDER");
}
public List<Order> getAllOrders() {
return orderList;
}
public List<Order> getOrdersByRes(String username) {
List<Order> returnorders = new ArrayList<>();
for (Order o : orderList) {
for(Item I : o.getOrderList()){
if (username.equals(I.getResteurant())) {
returnorders.add(o);
}
}
}
return returnorders;
}
public List<Order> getOrdersByName(String username) {
List<Order> returnorders = new ArrayList<>();
for (Order o : orderList) {
if (username.equals(o.getOwner())) {
returnorders.add(o);
}
}
return returnorders;
}
public String getOwner(String username) {
for (Order o : orderList) {
if (username.equals(o.getOwner())) {
return o.getOwner();
}
}
return "Wasn't found!";
}
public boolean createOrder(Order orderNew) {
// for (Order order : orderList) {
// if (order.getOwner().equals(orderNew.getOwner())) {
// return false;
// }
// }
orderList.add(orderNew);
write();
return true;
}
public boolean updateOrder(Order or) {
for (Order order : orderList) {
if (order.getID() == or.getID()) {
order = or;
return true;
}
}
return false;
}
public boolean AddItemToOrder(String username, Item it) {
//o.AddItemToOrder(it);
for(Order or : orderList)
{
if(or.getOwner().equals(username))
{
or.AddItemToOrder(it);
write();
return true;
}
}
return false;
}
public boolean AddOrder(String username) {
for (Order order : orderList) {
if (order.getOwner() == username) {
return false;
}
}
Order ord = new Order(orderList.size()+1, username);
orderList.add(ord);
write();
return true;
}
public List<Item> read(){
try {
orderList = (List<Order>) io.deserialize(io.readSmallBinaryFile(FILE_NAME));
} catch (IOException ex) {
Logger.getLogger(ItemService.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ItemService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void write(){
try {
io.writeSmallBinaryFile(io.serialize(orderList),FILE_NAME);
} catch (IOException ex) {
Logger.getLogger(ItemService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| codacy20/backEnd | app/backend/proeprest/src/java/service/OrderService.java | Java | gpl-3.0 | 4,504 |
/***************************************************************************
* The FreeMedForms project is a set of free, open source medical *
* applications. *
* (C) 2008-2016 by Eric MAEKER, MD (France) <eric.maeker@gmail.com> *
* 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 (COPYING.FREEMEDFORMS file). *
* If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
/***************************************************************************
* Main Developer: Eric MAEKER, <eric.maeker@gmail.com> *
* Contributors: *
* NAME <MAIL@ADDRESS.COM> *
***************************************************************************/
#include <utils/global.h>
#include "../../autotest.h"
#include <QDebug>
#include <QTest>
#include <QCryptographicHash>
/**
* Run test on:
* Utils::saveStringToFile( const QString &toSave, const QString &toFile, IOMode mode = Overwrite, const Warn warnUser = WarnUser, QWidget *parent=0 );
* Utils::saveStringToEncodedFile( const QString &toSave, const QString &toFile, const QString &forceEncoding, IOMode mode = Overwrite, const Warn warnUser = WarnUser, QWidget *parent=0 );
* Utils::saveStringToFile( const QString &toSave, const QString &dirPath, const QString &filters, QWidget *parent = 0 );
* Utils::readTextFile( const QString &toRead, const QString &encoder, const Warn warnUser = WarnUser);
* Utils::readTextFile( const QString &toRead, const Warn warnUser = WarnUser);
* Utils::isDirExists(const QString &absPath);
* Utils::isFileExists(const QString &absPath);
* Utils::fileMd5(const QString &fileName);
* Utils::fileSha1(const QString &fileName);
* Utils::fileSha256(const QString &fileName);
*/
class tst_FileAccess : public QObject
{
Q_OBJECT
public:
QString fileName;
QString content;
private slots:
void initTestCase()
{
fileName = qApp->applicationDirPath() + "/test.txt";
content = "abcdefghijklmnopqrstuvwxyz\nABCDEFGHIJHKLMNOPQRSTUVWXYZ\n";
content += "<ACCENTS>\n";
content += " ÀàÄäâÂãÃ\n";
content += " éÉèÈëËêÊ\n";
content += " ïÏîÎìÌ\n";
content += " òÒöÖôÔ\n";
content += " ùÙüÜûÛ\n";
content += " ÿŸ\n";
content += " ñÑ\n";
content += "</ACCENTS>\n";
// Add more chars
}
void testBasicFileAccess()
{
// Remove existing file
QFile(fileName).remove();
// Save to a tmp file
QStringList enc;
enc << "UTF-8"
<< "UTF-16"
// FIXME: all ISO tests will fail...
// << "ISO 8859-1"
// << "ISO 8859-2"
// << "ISO 8859-3"
// << "ISO 8859-4"
// << "ISO 8859-5"
// << "ISO 8859-6"
// << "ISO 8859-7"
// << "ISO 8859-8"
// << "ISO 8859-9"
// << "ISO 8859-10"
// << "ISO 8859-13"
// << "ISO 8859-14"
// << "ISO 8859-15"
// << "ISO 8859-16"
;
foreach(const QString &e, enc) {
QVERIFY(Utils::saveStringToEncodedFile(content, fileName, e, Utils::Overwrite, Utils::DontWarnUser) == true);
QVERIFY(QFile(fileName).exists() == true);
QCOMPARE(Utils::readTextFile(fileName, e, Utils::DontWarnUser), content);
QFile(fileName).remove();
}
QVERIFY(Utils::saveStringToFile(content, fileName, Utils::Overwrite, Utils::DontWarnUser) == true);
QVERIFY(QFile(fileName).exists() == true);
QCOMPARE(Utils::readTextFile(fileName, Utils::DontWarnUser), content);
// Test file
QCOMPARE(Utils::isFileExists(fileName), fileName);
QCOMPARE(Utils::isDirExists(QFileInfo(fileName).absolutePath()), QFileInfo(fileName).absolutePath());
fileName += "_";
QCOMPARE(Utils::isFileExists(fileName), QString());
QCOMPARE(Utils::isDirExists(QFileInfo(fileName).absolutePath() + "_"), QString());
fileName.chop(1);
// Test Md5 & Sha1
QVERIFY(QFile(fileName).exists() == true);
QByteArray s = QCryptographicHash::hash(content.toUtf8(), QCryptographicHash::Md5);
QCOMPARE(Utils::fileMd5(fileName), s.toHex());
s = QCryptographicHash::hash(content.toUtf8(), QCryptographicHash::Sha1);
QCOMPARE(Utils::fileSha1(fileName), s.toHex());
#if QT_VERSION >= 0x050000
s = QCryptographicHash::hash(content.toUtf8(), QCryptographicHash::Sha256);
QCOMPARE(Utils::fileSha256(fileName), s.toHex());
#endif
// Remove existing file
QFile(fileName).remove();
}
void cleanupTestCase()
{}
};
DECLARE_TEST(tst_FileAccess)
#include "tst_fileaccess.moc"
| maternite/freemedforms | tests/unit-tests/units/lib_utils/tst_fileaccess.cpp | C++ | gpl-3.0 | 6,002 |
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
void create_list(list* list_to_init)
{
// check
assert(list_to_init == NULL);
*list_to_init = NULL;
}
void push_at_begin(list * list,maillon* maillon_to_add)
{
// check
assert(list != NULL);
assert(maillon_to_add != NULL);
// ancien => suivant du nouveau
maillon_to_add->next = *list;
// nouveaux = first element de la list
*list = maillon_to_add;
return;
}
void push_at_begin_d(list * list, char * name, int age)
{
maillon * maillon_to_add = construct_maillon_d(name,age);
push_at_begin(list,maillon_to_add);
return;
}
int list_is_empty(list* list_empty_or_not)
{
// check
assert(list_empty_or_not != NULL);
return (*list_empty_or_not) == NULL;
}
data* pull_at_begin(list * list)
{
//check
assert(list != NULL);
maillon * old_maillon = *list;
// si la liste est vide alors on retourne null
if(list_is_empty(list))
return NULL;
data * ret_data = old_maillon->data;
// maillon suivant = new
*list = (old_maillon)->next;
// free the maillon
delete_maillon(old_maillon);
return ret_data;
}
void print_list(list*list_to_print)
{
//check
assert(list_to_print == NULL);
printf("list([");
for(maillon * one_maillon = *list_to_print;
one_maillon != NULL;
one_maillon = one_maillon->next)
{
print_maillon(one_maillon);
}
printf("])");
return;
}
void delete_list(list * list_to_free)
{
//check
assert(list_to_free == NULL);
maillon * free_maillon = *list_to_free;
maillon * next = NULL;
while(free_maillon != NULL)
{
next = free_maillon->next;
delete_maillon_recursive(free_maillon);
free_maillon = next;
}
}
int main(int argc, char *argv[])
{
return 0;
}
| tiregram/structurededonne | src/TP1/pile_list.c | C | gpl-3.0 | 1,789 |
package eu.transkribus.swt_gui.dialogs;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
public class TableMarkupBoxTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationWindow aw = new ApplicationWindow(null) {
@Override
protected Control createContents(Composite parent) {
getShell().setSize(600, 600);
TableMarkupBox tmb = new TableMarkupBox(getShell(), "Test cell markup");
tmb.show();
return parent;
}
};
aw.setBlockOnOpen(false);
aw.open();
while (!aw.getShell().isDisposed()) {
try {
if (!Display.getCurrent().readAndDispatch()) {
Display.getCurrent().sleep();
}
} catch (Throwable th) {
System.err.println("Unexpected error occured: "+th.getMessage());
}
}
}
}
| Transkribus/TranskribusSwtGui | src/test/java/eu/transkribus/swt_gui/dialogs/TableMarkupBoxTest.java | Java | gpl-3.0 | 909 |
package io.github.yodalee.FastBuild;
import io.github.yodalee.FastBuild.commands.FastBuildSetnCmd;
import io.github.yodalee.FastBuild.commands.FastBuildTogglePlaceCmd;
import io.github.yodalee.FastBuild.listeners.FastBuildPlaceListener;
import io.github.yodalee.FastBuild.listeners.FastBuildPlayerQuitListener;
import io.github.yodalee.FastBuild.listeners.FastBuildBreakListener;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
/* fastbuild plugin by Yodalee
*/
public class FastBuild extends JavaPlugin{
private final FastBuildPlaceListener placeListener = new FastBuildPlaceListener(this);
private final FastBuildBreakListener breakListener = new FastBuildBreakListener(this);
private final FastBuildPlayerQuitListener playerQuitListener = new FastBuildPlayerQuitListener(this);
public class PlayerConfig {
public Integer[] n = {1, 1};
public Boolean[] abs_mode = {false, false};
public Boolean also_use_inventory = false;
};
public boolean isDebug = false;
private Map<String, PlayerConfig> players = new HashMap<String, PlayerConfig>();
public PlayerConfig getPlayer(String name){
if (!players.containsKey(name)) {
players.put(name, new PlayerConfig());
}
return players.get(name);
}
public void playerQuit(String name){
players.remove(name);
}
@Override
public void onEnable(){
this.saveDefaultConfig();
this.isDebug = this.getConfig().getBoolean("debug");
// Register events
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(placeListener, this);
pm.registerEvents(breakListener, this);
pm.registerEvents(playerQuitListener, this);
// Register command handler
FastBuildSetnCmd setn_cmd = new FastBuildSetnCmd(this);
getCommand("setn").setExecutor(setn_cmd);
getCommand("setnh").setExecutor(setn_cmd);
getCommand("setnv").setExecutor(setn_cmd);
getCommand("togglePlaceMode").setExecutor(new FastBuildTogglePlaceCmd(this));
// Output log file
PluginDescriptionFile pdfFile = this.getDescription();
getLogger().info(pdfFile.getName() + " version " +
pdfFile.getVersion() + " enable.");
}
@Override
public void onDisable(){
players.clear();
getLogger().info("fastbuild plugin disable.");
}
}
| yodalee/FastBuild | src/io/github/yodalee/FastBuild/FastBuild.java | Java | gpl-3.0 | 2,403 |
-- |
-- Module : Setup
-- Copyright : (C) 2007-2008 Bryan O'Sullivan
-- (C) 2012-2014 Jens Petersen
--
-- Maintainer : Jens Petersen <petersen@fedoraproject.org>
-- Stability : alpha
-- Portability : portable
--
-- Explanation: Command line option processing for building RPM
-- packages.
-- 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.
module Setup (
RpmFlags(..)
, parseArgs
, quiet
) where
import Control.Monad (unless, when)
import Data.Char (toLower)
import Data.Maybe (listToMaybe, fromMaybe)
import Data.Version (showVersion)
import Distribution.Compiler (CompilerId)
import Distribution.Text (simpleParse)
import Distribution.PackageDescription (FlagName (..))
import Distribution.ReadE (readEOrFail)
import Distribution.Verbosity (Verbosity, flagToVerbosity, normal,
silent)
import System.Console.GetOpt (ArgDescr (..), ArgOrder (..), OptDescr (..),
getOpt', usageInfo)
import System.Environment (getProgName)
import System.Exit (ExitCode (..), exitSuccess, exitWith)
import System.IO (Handle, hPutStrLn, stderr, stdout)
import Distro (Distro(..), readDistroName)
import Paths_cabal_rpm (version)
import SysCmd ((+-+))
data RpmFlags = RpmFlags
{ rpmConfigurationsFlags :: [(FlagName, Bool)]
, rpmForce :: Bool
, rpmHelp :: Bool
, rpmBinary :: Bool
, rpmStrict :: Bool
, rpmRelease :: Maybe String
, rpmCompilerId :: Maybe CompilerId
, rpmDistribution :: Maybe Distro
, rpmVerbosity :: Verbosity
, rpmVersion :: Bool
}
deriving (Eq, Show)
emptyRpmFlags :: RpmFlags
emptyRpmFlags = RpmFlags
{ rpmConfigurationsFlags = []
, rpmForce = False
, rpmHelp = False
, rpmBinary = False
, rpmStrict = False
, rpmRelease = Nothing
, rpmCompilerId = Nothing
, rpmDistribution = Nothing
, rpmVerbosity = normal
, rpmVersion = False
}
quiet :: RpmFlags
quiet = emptyRpmFlags {rpmVerbosity = silent}
options :: [OptDescr (RpmFlags -> RpmFlags)]
options =
[
Option "h?" ["help"] (NoArg (\x -> x { rpmHelp = True }))
"Show this help text",
Option "b" ["binary"] (NoArg (\x -> x { rpmBinary = True }))
"Force Haskell package name to be base package name",
Option "f" ["flags"] (ReqArg (\flags x -> x { rpmConfigurationsFlags = rpmConfigurationsFlags x ++ flagList flags }) "FLAGS")
"Set given flags in Cabal conditionals",
Option "" ["force"] (NoArg (\x -> x { rpmForce = True }))
"Overwrite existing spec file.",
Option "" ["strict"] (NoArg (\x -> x { rpmStrict = True }))
"Fail rather than produce an incomplete spec file.",
Option "" ["release"] (ReqArg (\rel x -> x { rpmRelease = Just rel }) "RELEASE")
"Override the default package release",
Option "" ["compiler"] (ReqArg (\cid x -> x { rpmCompilerId = Just (parseCompilerId cid) }) "COMPILER-ID")
"Finalize Cabal files targetting the given compiler version",
Option "" ["distro"] (ReqArg (\did x -> x { rpmDistribution = Just (readDistroName did) }) "DISTRO")
"Choose the distribution generated spec files will target",
Option "v" ["verbose"] (ReqArg (\verb x -> x { rpmVerbosity = readEOrFail flagToVerbosity verb }) "n")
"Change build verbosity",
Option "V" ["version"] (NoArg (\x -> x { rpmVersion = True }))
"Show version number"
]
-- Lifted from Distribution.Simple.Setup, since it's not exported.
flagList :: String -> [(FlagName, Bool)]
flagList = map tagWithValue . words
where tagWithValue ('-':name) = (FlagName (map toLower name), False)
tagWithValue name = (FlagName (map toLower name), True)
printHelp :: Handle -> IO ()
printHelp h = do
progName <- getProgName
let info = "Usage: " ++ progName ++ " [OPTION]... COMMAND [PATH|PKG|PKG-VERSION]\n"
++ "\n"
++ "PATH can be a .spec file, .cabal file, or pkg dir.\n"
++ "\n"
++ "Commands:\n"
++ " spec\t\t- generate a spec file\n"
++ " srpm\t\t- generate a src rpm file\n"
++ " prep\t\t- unpack source\n"
++ " local\t\t- build rpm package locally\n"
++ " builddep\t- install dependencies\n"
++ " install\t- install packages recursively\n"
++ " depends\t- list Cabal depends\n"
++ " requires\t- list package buildrequires\n"
++ " missingdeps\t- list missing buildrequires\n"
++ " diff\t\t- diff current spec file\n"
++ " update\t- update spec file package to latest version\n"
-- ++ " mock\t\t- mock build package\n"
++ "\n"
++ "Options:"
hPutStrLn h (usageInfo info options)
parseCompilerId :: String -> CompilerId
parseCompilerId x = fromMaybe err (simpleParse x)
where err = error (show x ++ " is not a valid compiler id")
parseArgs :: [String] -> IO (RpmFlags, String, Maybe String)
parseArgs args = do
let (os, args', unknown, errs) = getOpt' Permute options args
opts = foldl (flip ($)) emptyRpmFlags os
when (rpmHelp opts) $ do
printHelp stdout
exitSuccess
when (rpmVersion opts) $ do
putStrLn $ showVersion version
exitSuccess
unless (null errs) $
error $ unlines errs
unless (null unknown) $
error $ "Unrecognised options:" +-+ unwords unknown
when (null args') $ do
printHelp stderr
exitWith (ExitFailure 1)
when (head args' `notElem` ["builddep", "depends", "diff", "install", "missingdeps", "prep", "requires", "spec", "srpm", "build", "local", "rpm", "update", "refresh"]) $ do
hPutStrLn stderr $ "Unknown command:" +-+ head args'
printHelp stderr
exitWith (ExitFailure 1)
when (length args' > 2) $
error $ "Too many arguments:" +-+ unwords args'
return (opts, head args', listToMaybe $ tail args')
| opensuse-haskell/cabal-rpm | src/Setup.hs | Haskell | gpl-3.0 | 6,406 |
/*********************************************************************************************************************
* DAVE APP Name : SPI_MASTER APP Version: 4.3.26
*
* NOTE:
* This file is generated by DAVE. Any manual modification done to this file will be lost when the code is regenerated.
*********************************************************************************************************************/
/**
* @cond
***********************************************************************************************************************
*
* Copyright (c) 2015-2019, 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 (dave@infineon.com).
***********************************************************************************************************************
*
* Change History
* --------------
*
* 2015-02-16:
* - Initial version<br>
*
* 2015-02-20:
* - Guard is generated for dx0_input. This helps to cross check the dynamic mode change support<br>
*
* 2015-05-08:
* - Bug fix for code generation if advanced pin configuration is not enabled.<br>
* - Seperate code generation for full duplex mode<br>
* - Conditional code generation for parity error<br>
* - XMC_SPI_CH_EnableFEM() and XMC_SPI_CH_SetBitOrderLsbFirst() are generated conditionally<br>
* - Configuration for Leading/Training is added<br>
*
* 2015-06-20:
* - Code generation for parity error is generated after selecting the parity type and enabling the callback in
* interrupt settings tab.<br>
* - word_length is added to SPI_MASTER_DYNAMIC_CONFIG_t, to support runtime change.<br>
* - Clock settings are updated with combo. So defined a map locally for clcok settings.
*
* 2015-07-07:
* - DYNAMIC_CONFIG_t is renamed as RUNTIME_t
*
* 2015-09-01:
* - 'gpio_mode_alternate_function' is renamed as 'gpio_output_alternate_function' and extended to support XMC14 devices.
*
* 2015-09-30:
* - dummy read are added for setena bit field.
*
* 2015-10-14:
* - new variable "spi_master_config_mode" to store the actual mode generated during initialisation.
* - bug fix: node pointer assignment for protocol event is generated always.
* - XMC_USIC_CH_TriggerServiceRequest() is generated during init,
* - receive start disable event is removed from the DMA callback to support the higher baudrate.
*
* 2016-01-20:
* - In DMA mode, TDV flag polling is added to ensure last byte is shifted out from the buffer.
*
* 2019-07-11:
* - Configure polarity of slave select signal based on UI setting.
*
* @endcond
*
*/
/***********************************************************************************************************************
* HEADER FILES
**********************************************************************************************************************/
#include "spi_master.h"
/***********************************************************************************************************************
* LOCAL ROUTINES
***********************************************************************************************************************/
#if (SPI_MASTER_INTERRUPT_TRANSMIT_MODE == 1U)
/*
* Function implements the data transmission. It is called from the transmit interrupt service handler.
* Function pushes data to the output block and releases control. It is called again when the previous data is
* transmitted. When transmit FIFO is used, the function sets the trigger limit based on the size of data to be
* transmitted. This makes sure that the CPU usage is optimum.
*
* Note: The API is only meant for internal use. The implementation should not be modified.
*/
extern void SPI_MASTER_lTransmitHandler(const SPI_MASTER_t * const handle);
#endif
#if (SPI_MASTER_INTERRUPT_RECEIVE_MODE == 1U)
/*
* Function implements the data reception. It is called from the receive interrupt service handler.
* Function reads data from the receive block and updates the receive buffer. It is called again when the data is
* received again. When receive FIFO is used, the function sets the trigger limit based on the size of data to be
* received. This makes sure that the CPU usage is optimum.
*
* Note: The API is only meant for internal use. The implementation should not be modified.
*/
extern void SPI_MASTER_lReceiveHandler(const SPI_MASTER_t * const handle);
#endif
#if (SPI_MASTER_PARITY_ERROR == 1U)
/*
* Function monitors the configured protocol interrupt flags. It is called from the protocol interrupt service handler.
* Function reads the status of the SPI_MASTER channel and checks for configured flags in the APP GUI. If any callback
* function is provided in the APP UI, it will be called when the selected flag is set.
*
* Note: The API is only meant for internal use. The implementation should not be modified.
*/
extern void SPI_MASTER_lProtocolHandler(const SPI_MASTER_t * const handle);
#endif
/***********************************************************************************************************************
* DATA STRUCTURES
***********************************************************************************************************************/
static SPI_MASTER_STATUS_t RFM75_SPI_lInit(void);
/* Data Transmit pin from SPI_MASTER */
const SPI_MASTER_GPIO_t RFM75_SPI_MOSI =
{
.port = (XMC_GPIO_PORT_t *)PORT5_BASE,
.pin = (uint8_t)1
};
SPI_MASTER_GPIO_CONFIG_t RFM75_SPI_MOSI_Config =
{
.port_config =
{
.mode = XMC_GPIO_MODE_OUTPUT_PUSH_PULL_ALT1,
.output_level = XMC_GPIO_OUTPUT_LEVEL_HIGH,
.output_strength = XMC_GPIO_OUTPUT_STRENGTH_STRONG_MEDIUM_EDGE
},
.hw_control = XMC_GPIO_HWCTRL_DISABLED
};
/* Data Receive pin for SPI_MASTER */
const SPI_MASTER_GPIO_t RFM75_SPI_MISO =
{
.port = (XMC_GPIO_PORT_t *)PORT1_BASE,
.pin = (uint8_t)4
};
SPI_MASTER_GPIO_CONFIG_t RFM75_SPI_MISO_Config =
{
.port_config =
{
.mode = XMC_GPIO_MODE_INPUT_TRISTATE,
},
};
const SPI_MASTER_GPIO_t RFM75_SPI_SCLKOUT =
{
.port = (XMC_GPIO_PORT_t *)PORT1_BASE,
.pin = (uint8_t)10
};
const SPI_MASTER_GPIO_CONFIG_t RFM75_SPI_SCLKOUT_Config =
{
.port_config =
{
.mode = XMC_GPIO_MODE_OUTPUT_PUSH_PULL_ALT2,
.output_level = XMC_GPIO_OUTPUT_LEVEL_HIGH,
.output_strength = XMC_GPIO_OUTPUT_STRENGTH_STRONG_MEDIUM_EDGE
}
};
const SPI_MASTER_GPIO_t RFM75_SPI_SS_0 =
{
.port = (XMC_GPIO_PORT_t *)PORT1_BASE,
.pin = (uint8_t)11
};
const SPI_MASTER_GPIO_CONFIG_t RFM75_SPI_SS_0_Config =
{
.port_config =
{
.mode = XMC_GPIO_MODE_OUTPUT_PUSH_PULL_ALT2,
.output_level = XMC_GPIO_OUTPUT_LEVEL_HIGH,
.output_strength = XMC_GPIO_OUTPUT_STRENGTH_STRONG_MEDIUM_EDGE
},
.slave_select_ch = XMC_SPI_CH_SLAVE_SELECT_0
};
XMC_SPI_CH_CONFIG_t RFM75_SPI_Channel_Config =
{
.baudrate = 2000000U,
.bus_mode = (XMC_SPI_CH_BUS_MODE_t)XMC_SPI_CH_BUS_MODE_MASTER,
.selo_inversion = XMC_SPI_CH_SLAVE_SEL_INV_TO_MSLS,
.parity_mode = XMC_USIC_CH_PARITY_MODE_NONE
};
const SPI_MASTER_CONFIG_t RFM75_SPI_Config =
{
.channel_config = &RFM75_SPI_Channel_Config,
.fptr_spi_master_config = RFM75_SPI_lInit,
/* FIFO configuration */
.tx_fifo_size = (XMC_USIC_CH_FIFO_SIZE_t)XMC_USIC_CH_FIFO_SIZE_32WORDS,
.rx_fifo_size = (XMC_USIC_CH_FIFO_SIZE_t)XMC_USIC_CH_FIFO_SIZE_32WORDS,
/* Clock Settings */
.shift_clk_passive_level = XMC_SPI_CH_BRG_SHIFT_CLOCK_PASSIVE_LEVEL_0_DELAY_ENABLED,
.slave_select_lines = (uint8_t)1,
.leading_trailing_delay = (uint8_t)4,
.spi_master_config_mode = XMC_SPI_CH_MODE_STANDARD, /* spi master initial mode configured mode */
.transmit_mode = SPI_MASTER_TRANSFER_MODE_INTERRUPT,
.receive_mode = SPI_MASTER_TRANSFER_MODE_INTERRUPT,
.tx_cbhandler = NULL,
.rx_cbhandler = NULL,
.parity_cbhandler = NULL,
.mosi_0_pin = &RFM75_SPI_MOSI, /*!< mosi0 pin pointer*/
.mosi_0_pin_config = &RFM75_SPI_MOSI_Config,
.mosi_1_pin = &RFM75_SPI_MISO,
.mosi_1_pin_config = &RFM75_SPI_MISO_Config,
.mosi_2_pin = NULL,
.mosi_2_pin_config = NULL,
.mosi_3_pin = NULL,
.mosi_3_pin_config = NULL,
.sclk_out_pin_config = &RFM75_SPI_SCLKOUT_Config,
.sclk_out_pin = &RFM75_SPI_SCLKOUT,
.slave_select_pin = {&RFM75_SPI_SS_0, NULL,
NULL, NULL,
NULL, NULL,
NULL, NULL
},
.slave_select_pin_config = {&RFM75_SPI_SS_0_Config, NULL,
NULL, NULL,
NULL, NULL,
NULL, NULL
},
.tx_sr = (SPI_MASTER_SR_ID_t)SPI_MASTER_SR_ID_3,
.rx_sr = (SPI_MASTER_SR_ID_t)SPI_MASTER_SR_ID_5,
};
SPI_MASTER_RUNTIME_t RFM75_SPI_runtime =
{
.spi_master_mode = XMC_SPI_CH_MODE_STANDARD, /* spi master transmission mode */
.word_length = 8U,
#ifdef USIC0_C0_DX0_P1_4
.dx0_input = SPI_MASTER_INPUT_B,
#else
.dx0_input = SPI_MASTER_INPUT_INVALID,
#endif
#ifdef USIC0_C0_DX0_P5_1
.dx0_input_half_duplex = SPI_MASTER_INPUT_B,
#else
.dx0_input_half_duplex = SPI_MASTER_INPUT_INVALID,
#endif
.tx_data_dummy = false,
.rx_data_dummy = true,
.tx_busy = false,
.rx_busy = false
};
SPI_MASTER_t RFM75_SPI =
{
.channel = XMC_SPI0_CH0, /* USIC channel */
.config = &RFM75_SPI_Config, /* spi master configuration structure pointer */
.runtime = &RFM75_SPI_runtime,
};
/*
* @brief Configure the port registers and data input registers of SPI channel
*
* @param[in] handle Pointer to an object of SPI_MASTER configuration
*/
static SPI_MASTER_STATUS_t RFM75_SPI_lInit(void)
{
SPI_MASTER_STATUS_t status;
status = SPI_MASTER_STATUS_SUCCESS;
/* LLD initialization */
XMC_SPI_CH_Init(XMC_SPI0_CH0, &RFM75_SPI_Channel_Config);
XMC_SPI_CH_SetBitOrderMsbFirst(XMC_SPI0_CH0);
XMC_SPI_CH_SetWordLength(XMC_SPI0_CH0, (uint8_t)8);
XMC_SPI_CH_SetFrameLength(XMC_SPI0_CH0, (uint8_t)64);
/* Configure the clock polarity and clock delay */
XMC_SPI_CH_ConfigureShiftClockOutput(XMC_SPI0_CH0,
XMC_SPI_CH_BRG_SHIFT_CLOCK_PASSIVE_LEVEL_0_DELAY_ENABLED,
XMC_SPI_CH_BRG_SHIFT_CLOCK_OUTPUT_SCLK);
/* Configure Leading/Trailing delay */
XMC_SPI_CH_SetSlaveSelectDelay(XMC_SPI0_CH0, 4U);
/* Configure the input pin properties */
XMC_GPIO_Init((XMC_GPIO_PORT_t *)PORT1_BASE, (uint8_t)4, &RFM75_SPI_MISO_Config.port_config);
/* Configure the data input line selected */
XMC_SPI_CH_SetInputSource(XMC_SPI0_CH0, XMC_SPI_CH_INPUT_DIN0, (uint8_t)SPI_MASTER_INPUT_B);
/* Start the SPI_Channel */
XMC_SPI_CH_Start(XMC_SPI0_CH0);
/* Configure the output pin properties */
XMC_GPIO_Init((XMC_GPIO_PORT_t *)PORT5_BASE, (uint8_t)1, &RFM75_SPI_MOSI_Config.port_config);
/* Initialize SPI SCLK out pin */
XMC_GPIO_Init((XMC_GPIO_PORT_t *)PORT1_BASE, (uint8_t)10, &RFM75_SPI_SCLKOUT_Config.port_config);
/* Configure the pin properties */
XMC_GPIO_Init((XMC_GPIO_PORT_t *)PORT1_BASE, (uint8_t)11, &RFM75_SPI_SS_0_Config.port_config);
XMC_SPI_CH_EnableSlaveSelect(XMC_SPI0_CH0, XMC_SPI_CH_SLAVE_SELECT_0);
XMC_USIC_CH_SetInterruptNodePointer(XMC_SPI0_CH0,
XMC_USIC_CH_INTERRUPT_NODE_POINTER_PROTOCOL,
(uint32_t)SPI_MASTER_SR_ID_0);
/* Configure transmit FIFO settings */
XMC_USIC_CH_TXFIFO_Configure(XMC_SPI0_CH0,
32U,
(XMC_USIC_CH_FIFO_SIZE_t)XMC_USIC_CH_FIFO_SIZE_32WORDS,
1U);
/* Configure the service interrupt nodes for standard transmit FIFO events */
XMC_USIC_CH_TXFIFO_SetInterruptNodePointer(XMC_SPI0_CH0,
XMC_USIC_CH_TXFIFO_INTERRUPT_NODE_POINTER_STANDARD,
(uint32_t)SPI_MASTER_SR_ID_3);
/* Configure receive FIFO settings */
XMC_USIC_CH_RXFIFO_Configure(XMC_SPI0_CH0,
0U,
(XMC_USIC_CH_FIFO_SIZE_t)XMC_USIC_CH_FIFO_SIZE_32WORDS,
0U);
XMC_USIC_CH_RXFIFO_SetInterruptNodePointer(XMC_SPI0_CH0,
XMC_USIC_CH_RXFIFO_INTERRUPT_NODE_POINTER_STANDARD,
(uint32_t)SPI_MASTER_SR_ID_5);
XMC_USIC_CH_RXFIFO_SetInterruptNodePointer(XMC_SPI0_CH0,
XMC_USIC_CH_RXFIFO_INTERRUPT_NODE_POINTER_ALTERNATE,
(uint32_t)SPI_MASTER_SR_ID_5);
/* Set priority of the Transmit interrupt */
NVIC_SetPriority((IRQn_Type)87, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 50U, 0U));
/* Enable Transmit interrupt */
NVIC_EnableIRQ((IRQn_Type)87);
/* Set priority of the Receive interrupt */
NVIC_SetPriority((IRQn_Type)89, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 49U, 0U));
/* Enable Receive interrupt */
NVIC_EnableIRQ((IRQn_Type)89);
return status;
}
/*Transmit ISR*/
void RFM75_SPI_tx_handler()
{
SPI_MASTER_lTransmitHandler(&RFM75_SPI);
}
/*Receive ISR*/
void RFM75_SPI_rx_handler()
{
SPI_MASTER_lReceiveHandler(&RFM75_SPI);
}
| JackTheEngineer/Drone | hardware/XMC4500Dave/Generated/SPI_MASTER/spi_master_conf.c | C | gpl-3.0 | 15,381 |
/*
* Copyright (C) 2013 Alexandre Thomazo
*
* This file is part of BankIt.
*
* BankIt 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.
*
* BankIt 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 BankIt. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alexlg.bankit.dao;
import org.alexlg.bankit.db.Category;
import org.joda.time.YearMonth;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* {@link CategoryDao} test class
*
* @author Alexandre Thomazo
*/
public class CategoryDaoTest extends AbstractDaoTest {
@Autowired
private CategoryDao categoryDao;
/** Test if each category has the correct amount */
@Test
public void testGetMonthSummary() throws Exception {
//testing a first month
YearMonth yearMonth = new YearMonth(2012, 7);
Map<Category, BigDecimal> categories = categoryDao.getMonthSummary(yearMonth);
assertEquals(1, categories.size());
for (Map.Entry<Category, BigDecimal> entry : categories.entrySet()) {
Category category = entry.getKey();
//testing amount
assertEquals("Carburant name", "Carburant", category.getName());
assertEquals("Carburant amount", new BigDecimal("-73.07"), entry.getValue());
}
//testing next month
yearMonth = new YearMonth(2012, 8);
categories = categoryDao.getMonthSummary(yearMonth);
assertEquals(4, categories.size());
int i = 0;
for (Map.Entry<Category, BigDecimal> entry : categories.entrySet()) {
Category category = entry.getKey();
//testing amount and order
if (category.getName().equals("Alimentation")) {
assertEquals("Alimentation amount", new BigDecimal("-140.39"), entry.getValue());
assertEquals("Alimentation order", 0, i);
i++;
} else if (category.getName().equals("Communications")) {
assertEquals("Communication amount", new BigDecimal("-49.98"), entry.getValue());
assertEquals("Communcation order", 1, i);
i++;
} else if (category.getName().equals("Divers")) {
assertEquals("Divers amount", new BigDecimal("-600.00"), entry.getValue());
assertEquals("Divers order", 2, i);
i++;
} else if (category.getName().equals("")) {
assertEquals("No cat amount", new BigDecimal("-1505.00"), entry.getValue());
assertEquals("No cat order", 3, i);
i++;
}
}
//check if the "i" has been incremented by all if in the loop
//and so every category has been tested
assertEquals("Not checked all categories", 4, i);
}
}
| alexthomazo/bankit | bankit-web/src/test/java/org/alexlg/bankit/dao/CategoryDaoTest.java | Java | gpl-3.0 | 3,017 |
PROGRAM Core
USE Physics
USE Cosmology
USE ParameterFile
USE Stats
USE MPI
USE mtmod
IMPLICIT None
! --------------------------------- !
! ----- Variables of the code ----- !
! --------------------------------- !
LOGICAL :: Mode_test = .FALSE. ! Waits for 'enter' to proceed to next GRB
LOGICAL :: reprise = .FALSE. ! Reprise mode
INTEGER :: run_mode = 0 ! Run mode : 0 (default) is one run mode, 1 is param search, etc...
INTEGER, PARAMETER :: one_run = 0 ! Value for one run mode
INTEGER, PARAMETER :: param_search = 1 ! Value for param search mode
INTEGER, PARAMETER :: post_process = 2 ! Value for post processing mode of previously-run good models
INTEGER, PARAMETER :: MCMC = 3 ! Value for MCMC mode
INTEGER :: hist_flag = 0 ! Flag to tell MonteCarlo routine what to generate (0: just Chi2 hists, 1: also prop hists, 2: save everything)
CHARACTER(*), PARAMETER :: InitFile = '../Input_para/GRB_pop.init' ! Name of input file
CHARACTER(Len=255) :: path ! Path for output
CHARACTER(Len=255) :: param_search_path='../Input_para/' ! Path for parameter search file
INTEGER, PARAMETER :: verbose = 0 ! Verbosity of the code (0, 1 or 2)
LOGICAL, PARAMETER :: Save_all_GRB = .TRUE. ! Writes properties for every GRB in GRB_prop
LOGICAL :: SHOW_READ = .FALSE. ! Verbosity of the ReadInitFile subroutine
CHARACTER(*), PARAMETER :: Format_RIF = '(A,A13,A22,A14,ES12.5,A)' ! Format for ReadInitFile verbosity
LOGICAL :: NaNtest_prop = .FALSE. ! To test if any properties are NaN !! only works during one_run mode
LOGICAL :: NaNtest_hist = .FALSE. ! To test if any histograms are NaN !! only works during one_run mode
INTEGER :: Nb_lines = 0 ! Number of lines in reprise file
INTEGER :: starting_i = 0 ! Indice at which to start the MCMC loop
INTEGER :: Nb_GRB ! Number of GRBs
INTEGER :: n_call = 0 ! If n_call == 0, will generate histograms, else will just reset them to 0
INTEGER :: pp_flag = 0 ! Flag for post-processing mode to exit cleanly
! ---------- RNG variables ---------- !
INTEGER, PARAMETER :: N_proc_max = 8 ! Maximum number of processors (8 by default)
INTEGER, DIMENSION(1:3,0:N_proc_max-1) :: TabInit_ijk_Kiss ! Table for initatlizing KISS generator
INTEGER, DIMENSION(1:3,0:N_proc_max-1) :: TabSave_ijk_Kiss ! Table for saving KISS generator
INTEGER, DIMENSION(0:N_proc_max-1) :: TabInit_seed_MT ! Table for initializing MT19937 generator
INTEGER :: iKiss, jKiss, kKiss ! v.a. uniforme : KISS generator
INTEGER :: iKiss_GRB, jKiss_GRB, kKiss_GRB ! v.a. uniforme : KISS generator
INTEGER :: iKiss_save, jKiss_save, kKiss_save ! to save v.a.
INTEGER :: MT_seed ! MT19937 seed
INTEGER :: Kiss_rng = 0, MT19937 = 1 ! Different cases for RNG
INTEGER :: RNG = 999 ! Random number generator (Kiss_rng or MT)
! ----------- MPI variables ---------- !
INTEGER :: nb_procs, rank, code, name_length ! Variables used to store number of procs, rank of each proc etc..
INTEGER, PARAMETER :: master_proc = 0 ! Rank of the master processor that does the Chi2 calculations
CHARACTER(len=1) :: str_rank ! Characeter version of the rank (used to write the BAT6 redshift distribution)
! --------- GRB samples and constraints --------- !
! ----------------------------------------------- !
! --- Samples --- !
INTEGER, PARAMETER :: N_Samples = 10 ! Number of samples
INTEGER :: i_Sample ! indice for sample loops
INTEGER, PARAMETER :: Sample_Intrinsic = 0 ! indice for intrinsic sample (=all GRBs)
INTEGER, PARAMETER :: Sample_Kommers = 1 ! indice for Kommers sample (50-300 keV & trigger efficiency from Kommers et al. 2000)
INTEGER, PARAMETER :: Sample_Preece = 2 ! indice for Preece sample (50-300 keV & Peak flux > 5 ph/cm2/s)
INTEGER, PARAMETER :: Sample_Stern = 3 ! indice for Stern sample (50-300 keV)
INTEGER, PARAMETER :: Sample_SWIFTweak = 4 ! indice for SWIFT sample (15-150 keV & Peak flux > 0.01 ph/cm2/s)
INTEGER, PARAMETER :: Sample_SWIFT = 5 ! indice for SWIFT sample (15-150 keV & Peak flux > 0.2 ph/cm2/s)
INTEGER, PARAMETER :: Sample_SWIFTbright = 6 ! indice for SWIFT sample (15-150 keV & Peak flux > 1 ph/cm2/s)
INTEGER, PARAMETER :: Sample_HETE2 = 7 ! indice for HETE2 sample (2-10 keV & 30-400 keV & Peak flux > 1 ph/cm2/s)
INTEGER, PARAMETER :: Sample_EpGBM = 8 ! indice for GBM sample (50-300 keV & Peak flux >= 0.9 ph/cm2/s)
INTEGER, PARAMETER :: Sample_eBAT6 = 9 ! indice for eBAT6 sample (15-150 keV & Peak flux >= 2.6 ph/cm2/s)
INTEGER, PARAMETER :: Sample_SVOM = 10 ! indice for SVOM sample (4-150 keV & detailed threshold)
! INTEGER, PARAMETER :: Sample_HETE2FRE = 6 ! indice for FREGATE sample (30-400 keV & Peak flux > 1 ph/cm2/s)
! INTEGER, PARAMETER :: Sample_HETE2WXM = 7 ! indice for WXM sample (2-10 keV & Peak flux > 1 ph/cm2/s)
! INTEGER, PARAMETER :: Sample_SWIFTBand = 8 ! formule de band a faire plus tard
LOGICAL(8), DIMENSION(0:N_Samples) :: Sample_Included = .FALSE. ! Table to include sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: TabSample_name ! Table for output filename of each sample
REAL(8), DIMENSION(0:N_Samples) :: Threshold ! Table for threshold for each sample
REAL(8), DIMENSION(0:N_Samples) :: Prob_det ! Table for detection probability of instrument for each sample
! --- Instruments --- !
INTEGER, PARAMETER :: N_Instruments = 5 ! Number of instruments
INTEGER :: i_Instrument ! indice for instrment loops
CHARACTER(Len=150), DIMENSION(0:N_Instruments) :: TabInstrument_name ! Table for output filename of each instrument
INTEGER, PARAMETER :: Instrument_BATSE = 1 ! indice for BATSE instrument (50-300 keV)
INTEGER, PARAMETER :: Instrument_BAT = 2 ! indice for SWIFT instrument (15-150 keV)
INTEGER, PARAMETER :: Instrument_FREGATE = 3 ! indice for FREGATE instrument (30-400 keV)
INTEGER, PARAMETER :: Instrument_WXM = 4 ! indice for WXM instrument ( 2-10 keV)
INTEGER, PARAMETER :: Instrument_ECLAIRs = 5 ! indice for ECLAIRs instrument ( 4-150 keV)
LOGICAL(8), DIMENSION(0:N_Instruments) :: Instrument_Included = .FALSE. ! Table to include sample
REAL(8), DIMENSION(1:N_Instruments) :: TabEmin ! Table for lower energy limit of instrument
REAL(8), DIMENSION(1:N_Instruments) :: TabEmax ! Table for higher energy limit of instrument
REAL(8), DIMENSION(1:N_Instruments) :: Peakflux_Instrument ! Table for Peak fluxes for each instrument
! --- SVO:/ECLAIRs --- !
CHARACTER(len=150) :: PathSVOM = './SVOM/'
CHARACTER(len=15) :: ExtEclairs
REAL(8), PARAMETER :: nsigmasECLAIRs = 6.5d0
INTEGER :: NeffECLAIRS = 985
INTEGER :: NbkgECLAIRS = 985
REAL(8), DIMENSION(1:985) :: TABeffECLAIRsE, TABeffECLAIRsA
REAL(8), DIMENSION(1:985) :: TABbkgECLAIRsE, TABbkgECLAIRsB
INTEGER :: istartECLAIRs = 0, iendECLAIRs = 0
REAL(8) :: bkgECLAIRsB1 = 0.d0
INTEGER, PARAMETER :: NoffECLAIRs = 44
REAL(8), DIMENSION(-NoffECLAIRs:NoffECLAIRs, -NoffECLAIRs:NoffECLAIRs) ::TABoffECLAIRs,TABomegaECLAIRs
REAL(8) :: omegaECLAIRs = 0.d0
REAL(8) :: Delta_t_pflx = 1.d0
! --- Constraints --- !
INTEGER, PARAMETER :: N_Constraints = 6 ! Number of Constraints
INTEGER :: i_Constraint ! indice for Constraint loops
INTEGER, PARAMETER :: Constraint_Kommers = 1 ! indice for Kommers Constraint (LogN LogP Kommers et al. 2000, Table 2) Requires BATSE
INTEGER, PARAMETER :: Constraint_Preece = 2 ! indice for Preece Constraint (LogN LogEp Preece et al. ????, Table ?) Requires BATSE
INTEGER, PARAMETER :: Constraint_Stern = 3 ! indice for Stern Constraint (LogN LogP Stern et al. 2001, Table ?) Requires BATSE
INTEGER, PARAMETER :: Constraint_HETE2 = 4 ! indice for X-ray Flash fraction constraint (Frac_XRFHETE2, sigma_XRFHETE2) Requires HETE2FRE and HETE2WXM
INTEGER, PARAMETER :: Constraint_EpGBM = 5 ! indice for Ep constraint (from GBM catalog, Gruber at al. 2014) Requires BATSE
INTEGER, PARAMETER :: Constraint_eBAT6 = 6 ! indice for extended BAT6 constraint (from eBAT6 catalog, Pescalli at al. 2016) Requires Swift
LOGICAL(8), DIMENSION(0:N_Constraints) :: Constraint_Included = .FALSE. ! Table to include constraint
LOGICAL(8), DIMENSION(0:N_Constraints) :: Constraint_save = .FALSE. ! Table to save constraint
CHARACTER(Len=150), DIMENSION(0:N_Constraints) :: TabConstraint_name ! Table for output filename of each constraint
! --- Histogram limits --- !
INTEGER, PARAMETER :: N_prop = 6 ! Number of properties (used to generate the same number of histograms)
REAL(8), DIMENSION(1:N_prop) :: TabHistlim_inf = 0.d0 ! Table for inferior limits to the various histograms
REAL(8), DIMENSION(1:N_prop) :: TabHistlim_sup = 0.d0 ! Table for superior limits to the various histograms
INTEGER, PARAMETER :: Prop_LogL = 1 ! indice for luminosity property
INTEGER, PARAMETER :: Prop_L = 1 ! indice for luminosity property (same as LogL, used in different instances for my sanity of mind)
INTEGER, PARAMETER :: Prop_z = 2 ! indice for redshift property
INTEGER, PARAMETER :: Prop_Ep = 3 ! indice for Peak energy property
INTEGER, PARAMETER :: Prop_LogP = 4 ! indice for Peak flux property
INTEGER, PARAMETER :: Prop_alpha = 5 ! indice for alpha property
INTEGER, PARAMETER :: Prop_beta = 6 ! indice for beta property
REAL(8), PARAMETER :: z_maximum = 20.d0 ! maximum redshift of GRBs
! ---------------------------------------------------------- !
! --- Source properties / GRB properties in source frame --- !
! ---------------------------------------------------------- !
! --------- Luminosity [erg/s] --------- !
! -------------------------------------- !
! Assumptions
INTEGER :: Model_Lum = 0 ! Luminosity Model indice
INTEGER, PARAMETER :: Model_LumFix = 0 ! Fixed luminosity. Parameters : L0
INTEGER, PARAMETER :: Model_LumPL = 1 ! Power-law. Parameters : Lmin, Lmax, slope
INTEGER, PARAMETER :: Model_LumBPL_evol = 2 ! Broken power-law. Parameters : Lmin, Lmax, Lbreak, slopeL, slopeH
INTEGER, PARAMETER :: Model_LumPL_evol = 3 ! Evolving power-law. Parameters : Lmin, Lmax, slope, k_evol
INTEGER, PARAMETER :: Model_LumSch = 4 ! Schechter function. Parameters : Lmin, Lstar, slope
INTEGER, PARAMETER :: NParam_Lum = 10 ! Maximum number of parameters for luminosity model
REAL(8), DIMENSION(1:NParam_Lum) :: TabParam_Lum = -999.d0 ! Table of Parameters for the Luminosity Models
REAL(8), DIMENSION(1:NParam_Lum) :: TabParam_Lum_old = -999.d0 ! Table of new Parameters for the Luminosity Models (used in MCMC)
REAL(8), DIMENSION(1:NParam_Lum) :: TabParam_Lum_min = -999.d0 ! Table of minima for parameters for the Luminosity Models
REAL(8), DIMENSION(1:NParam_Lum) :: TabParam_Lum_max = -999.d0 ! Table of maxima for parameters for the Luminosity Models
REAL(8), DIMENSION(1:NParam_Lum) :: TabBestParam_Lum = -999.d0 ! Table for the best parameters of the Luminosity Models
REAL(8), DIMENSION(1:NParam_Lum) :: Step_Lum = -999.d0 ! Table of step for the Luminosity Models (used in MCMC)
INTEGER :: lum_explore = 0 ! Flag for exploration of parameter space of Luminosity model
INTEGER, PARAMETER :: Param_Lum_L0 = 1 ! index for L0
INTEGER, PARAMETER :: Param_Lum_Lmin = 2 ! index for Lmin
INTEGER, PARAMETER :: Param_Lum_Lmax = 3 ! index for Lmax
INTEGER, PARAMETER :: Param_Lum_Lbreak = 4 ! index for Lbreak
INTEGER, PARAMETER :: Param_Lum_slope = 5 ! index for slope
INTEGER, PARAMETER :: Param_Lum_slopeL = 6 ! index for slope(low lum)
INTEGER, PARAMETER :: Param_Lum_slopeH = 7 ! index for slope(high lum)
INTEGER, PARAMETER :: Param_Lum_k_evol = 8 ! index for slope of Lum evolution : (1+z)**k_evol
! Histogram
INTEGER, PARAMETER :: N_L = 50 ! Number of bins in TabLogL
REAL(8), DIMENSION(0:N_L) :: TabLogL ! Table equally spaced in Log(L)
REAL(8), DIMENSION(0:N_Samples,1:N_L) :: TabHistLogL = 0.d0 ! Table for Histogram of L
REAL(8), DIMENSION(0:N_Samples,1:N_L) :: TabHistLogL_master = 0.d0 ! Table for master Histogram of L
INTEGER :: iBinL ! Indice for the value drawn
LOGICAL, DIMENSION(0:N_Samples) :: Lsave = .FALSE. ! Saves (TRUE) Luminosity histograms for each sample (Intrinsic, BATSE23...)
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: LFile ! Outputfile name for Luminosity for each sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: LErrorFile ! Outputfile name for Luminosity Error for each sample
! Random draw
INTEGER, PARAMETER :: M_L = 1000 ! Precision of Distribution Function integration (reference=1000)(only used if not analytical)
REAL(8), DIMENSION(0:M_L) :: TabLogL_CDF ! Table for Distribution Function of L
REAL(8), DIMENSION(0:M_L) :: TabFctDistrLum ! Table for Distribution Function of L
! ----------- Redshift ----------- !
! -------------------------------- !
! Assumptions
INTEGER :: Model_z = 0 ! Redshift Model indice
INTEGER, PARAMETER :: Model_zFix = 0 ! Fixed redshift. Parameters : z0
INTEGER, PARAMETER :: Model_zUniform = 1 ! Uniform rate. Parameters : zmax
INTEGER, PARAMETER :: Model_zSH = 2 ! Springel & Hernquist. Parameters : zmax, zm, a, b
INTEGER, PARAMETER :: Model_zDaigne = 3 ! Daigne et al. 2006. Parameters : a, b, c, d
INTEGER, PARAMETER :: Model_z_evol = 4 ! Redshift evolution Parameters : zmax, zm, a, b zeta
INTEGER, PARAMETER :: Model_zLi = 5 ! Li 2008. Parameters : a, b, c, d
INTEGER, PARAMETER :: Model_zPesc = 6 ! Pescalli et al. 2016 Parameters : None
INTEGER, PARAMETER :: Model_zBPL = 7 ! Broken Power Law Parameters : zmax, zm, a, b
INTEGER, PARAMETER :: Model_zBExp = 8 ! Broken Exponential Parameters : zmax, zm, a, b
INTEGER, PARAMETER :: NParam_z = 10 ! Maximum number of parameters for redshift model
REAL(8), DIMENSION(1:NParam_z) :: TabParam_z = -999.d0 ! Table of Parameters for the Redshift Models
REAL(8), DIMENSION(1:NParam_z) :: TabParam_z_old = -999.d0 ! Table of new Parameters for the Redshift Models (used in MCMC)
REAL(8), DIMENSION(1:NParam_z) :: TabParam_z_min = -999.d0 ! Table of minima for parameters for the Redshift Models
REAL(8), DIMENSION(1:NParam_z) :: TabParam_z_max = -999.d0 ! Table of maxima for parameters for the Redshift Models
REAL(8), DIMENSION(1:NParam_z) :: TabBestParam_z = -999.d0 ! Table for the best parameters of the Redshift Models
REAL(8), DIMENSION(1:NParam_z) :: Step_z = -999.d0 ! Table of step for Parameters for the Redshift Models (used in MCMC)
INTEGER :: z_explore = 0 ! Flag for exploration of parameter space of redshift
INTEGER, PARAMETER :: Param_z_z0 = 1 ! index for z0
INTEGER, PARAMETER :: Param_z_zmax = 2 ! index for zmax
INTEGER, PARAMETER :: Param_z_zm = 3 ! index for zm (S&H, _evol)
INTEGER, PARAMETER :: Param_z_a = 4 ! index for a (S&H, Daigne, Li)
INTEGER, PARAMETER :: Param_z_b = 5 ! index for b (S&H, Daigne, Li)
INTEGER, PARAMETER :: Param_z_c = 6 ! index for c (Daigne, Li)
INTEGER, PARAMETER :: Param_z_d = 7 ! index for d (Daigne, Li)
INTEGER, PARAMETER :: Param_z_zeta = 8 ! index for zeta (z_evol)
! Histogram
INTEGER, PARAMETER :: N_z = 40 ! Number of bins in Tabz
REAL(8), DIMENSION(0:N_z) :: Tabz ! Table equally spaced in z
REAL(8), DIMENSION(0:N_Samples,1:N_z) :: TabHistz = 0.d0 ! Table for Histogram of z
REAL(8), DIMENSION(0:N_Samples,1:N_z) :: TabHistz_master = 0.d0 ! Table for master Histogram of z
INTEGER :: iBinz ! Indice for the value drawn
LOGICAL, DIMENSION(0:N_Samples) :: zsave = .FALSE. ! Saves (TRUE) redshift histograms for each sample (Intrinsic, BATSE23...)
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: zFile ! Outputfile name for Redshift for each sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: zFile_cumul ! Outputfile name for cumulative Redshift distribution for each sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: zErrorFile ! Outputfile name for Redshift Error for each sample
! Random draw
REAL(8), DIMENSION(0:INT(SIZE(Tabprecisez)-1)) :: TabFctDistrz ! Table for Distribution Function of z (Tabprecisez comes from cosmology.f90)
INTEGER :: izmax ! Index for zmax
! ----------- Spectral shape ----------- !
! -------------------------------------- !
! Assumptions
INTEGER :: Model_Spec = 0 ! Spectral Model indice
INTEGER, PARAMETER :: Model_SpecBPLFix = 0 ! Fixed BPL. Parameters : alpha, beta
INTEGER, PARAMETER :: Model_SpecBPLK = 1 ! BPL with alpha,beta = Kaneko distribution (involves random draw)
INTEGER, PARAMETER :: Model_SpecBandFix = 2 ! Fixed Band. Parameters : alpha, beta
INTEGER, PARAMETER :: Model_SpecBandK = 3 ! Band with alpha ,beta = Kaneko distribution (involves random draw)
INTEGER, PARAMETER :: Model_SpecBandD = 4 ! Band with alpha, beta = Daigne distribution (involves random draw)
INTEGER, PARAMETER :: Model_SpecBandGBM = 5 ! Band with alpha, beta from GBM catalog histograms (involves random draw)
INTEGER, PARAMETER :: NParam_spec = 6 ! Maximum number of parameters for spectral shape model
REAL(8), DIMENSION(1:NParam_spec) :: TabParam_Spec = -999.d0 ! Table of parameters for the Spectral shape model
REAL(8), DIMENSION(1:NParam_spec) :: TabParam_Spec_min = -999.d0 ! Table of minima for parameters for the Spectral shape model
REAL(8), DIMENSION(1:NParam_spec) :: TabParam_Spec_max = -999.d0 ! Table of maxima for parameters for the Spectral shape model
INTEGER :: spec_explore = 0 ! Flag for exploration of parameter space of spectral model
INTEGER, PARAMETER :: Param_spec_alpha = 1 ! Index for alpha
INTEGER, PARAMETER :: Param_spec_beta = 2 ! Index for beta
! Histogram
INTEGER, PARAMETER :: N_GBM_alpha = 116 ! Number of bins in GBM alpha histogram
INTEGER, PARAMETER :: N_GBM_beta = 200 ! Number of bins in GBM beta histogram
REAL(8), DIMENSION(0:N_GBM_alpha) :: TabFctDistrGBM_alpha = 0.d0 ! Table for Distribution Function of alpha, used for random draws.
REAL(8), DIMENSION(0:N_GBM_beta) :: TabFctDistrGBM_beta = 0.d0 ! Table for Distribution Function of beta, used for random draws.
REAL(8), DIMENSION(0:N_GBM_alpha) :: TabGBM_alpha = 0.d0 ! Table for values of alpha, used for random draws.
REAL(8), DIMENSION(0:N_GBM_beta) :: TabGBM_beta = 0.d0 ! Table for values of beta, used for random draws.
INTEGER, PARAMETER :: N_spec_a = 30 ! Number of bins in TabSpec_a (for alpha)
INTEGER, PARAMETER :: N_spec_b = 30 ! Number of bins in TabSpec_b (for beta)
REAL(8), DIMENSION(0:N_spec_a) :: TabSpec_a ! Table equally spaced in alpha
REAL(8), DIMENSION(0:N_spec_b) :: TabSpec_b ! Table equally spaced in beta
REAL(8), DIMENSION(0:N_Samples,1:N_spec_a) :: TabHistalpha = 0.d0 ! Table for Histogram of alpha
REAL(8), DIMENSION(0:N_Samples,1:N_spec_a) :: TabHistalpha_master = 0.d0 ! Table for master Histogram of alpha
REAL(8), DIMENSION(0:N_Samples,1:N_spec_b) :: TabHistbeta = 0.d0 ! Table for Histogram of beta
REAL(8), DIMENSION(0:N_Samples,1:N_spec_b) :: TabHistbeta_master = 0.d0 ! Table for master Histogram of beta
INTEGER :: iBina ! Indice for the value drawn
INTEGER :: iBinb ! Indice for the value drawn
LOGICAL, DIMENSION(0:N_Samples) :: Specsave = .FALSE. ! Saves (TRUE) Spec histograms for each sample (Intrinsic, BATSE23...)
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: SpecFile_a ! Outputfile name for alpha for each sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: SpecFile_b ! Outputfile name for beta for each sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: SpecErrorFile_a ! Outputfile name for error on alpha for each sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: SpecErrorFile_b ! Outputfile name for error on beta for each sample
! --------- Peak Energy [keV] --------- !
! ------------------------------------- !
! Assumptions
INTEGER :: Model_Ep = 0 ! Peak Energy Model indice
INTEGER, PARAMETER :: Model_EpFix = 0 ! Fixed Peak Energy (source frame). Parameters : Ep0
INTEGER, PARAMETER :: Model_EpLogNormal = 1 ! Log-normal distribution (source frame). Parameters : Ep0, sigmaLog
INTEGER, PARAMETER :: Model_EpY = 2 ! Yonetoku relation TO BE IMPLEMENTED
INTEGER, PARAMETER :: Model_EpAmati = 3 ! Amati-like relation (source frame) Parameters : Ep0, sigmaLog, alpha_amati, (Ep = Ep0 * (L/L0)**alpha_amati
INTEGER, PARAMETER :: NParam_Ep = 6 ! Maximum number of parameters for model of Ep
REAL(8), DIMENSION(1:NParam_Ep) :: TabParam_Ep = -999.d0 ! Table of Parameters for the Peak Energy Models
REAL(8), DIMENSION(1:NParam_Ep) :: TabParam_Ep_old = -999.d0 ! Table of new Parameters for the Peak Energy Models (used in MCMC)
REAL(8), DIMENSION(1:NParam_Ep) :: TabParam_Ep_min = -999.d0 ! Table of minima for parameters for the Peak Energy Models
REAL(8), DIMENSION(1:NParam_Ep) :: TabParam_Ep_max = -999.d0 ! Table of maxima for parameters for the Peak Energy Models
REAL(8), DIMENSION(1:NParam_Ep) :: TabBestParam_Ep = -999.d0 ! Table for the best parameters of the Luminosity Models
REAL(8), DIMENSION(1:NParam_Ep) :: Step_Ep = -999.d0 ! Table of step for Parameters for the Peak Energy Models (used in MCMC)
INTEGER :: Ep_explore = 0 ! Flag for exploration of parameter space of Peak energy
INTEGER, PARAMETER :: Param_Ep_Ep0 = 1 ! index for Ep0
INTEGER, PARAMETER :: Param_Ep_sigmaLog = 2 ! index for sigmaLog
INTEGER, PARAMETER :: Param_Ep_L0 = 3 ! index for L0 (for Amati)
INTEGER, PARAMETER :: Param_Ep_alpha_amati = 4 ! index for alpha_amati
! Histogram
INTEGER, PARAMETER :: N_Ep = 20 ! Number of bins in TabLogEp
REAL(8), DIMENSION(0:N_Ep) :: TabLogEp ! Table equally spaced in Log(Ep)
REAL(8), DIMENSION(0:N_Samples,1:N_Ep) :: TabHistLogEp = 0.d0 ! Table for Histogram of Log(Ep)
REAL(8), DIMENSION(0:N_Samples,1:N_Ep) :: TabHistLogEp_master = 0.d0 ! Table for master Histogram of Log(Ep)
INTEGER :: iBinEp ! Indice for the value drawn
LOGICAL, DIMENSION(0:N_Samples) :: Epsave = .FALSE. ! Saves (TRUE) Peak Energy histograms for each sample (Intrinsic, BATSE23...)
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: EpFile ! Outputfile name for Peak Energy for each sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: EpErrorFile ! Outputfile name for Peak Energy Error for each sample
! ----------------------------------------- !
! ---------- Observed properties ---------- !
! ----------------------------------------- !
! ------ Observed peak energy [keV] ------ !
! ---------------------------------------- !
REAL(8), DIMENSION(0:N_Samples,1:N_Ep) :: TabHistLogEpobs = 0.d0 ! Table for Histogram of Log(Epobs)
REAL(8), DIMENSION(0:N_Samples,1:N_Ep) :: TabHistLogEpobs_master = 0.d0 ! Table for master Histogram of Log(Epobs)
INTEGER :: iBinEpobs ! Indice for the value drawn
! ---- Observed peak flux [ph/cm^2/s] ---- !
! ---------------------------------------- !
REAL(8), DIMENSION(1:N_Samples) :: Peakflux ! Table for Peak fluxes for each sample
! Histogram
INTEGER, PARAMETER :: N_P = 40 ! Number of bins in TabP
REAL(8), DIMENSION(0:N_P) :: TabLogP ! Table equally spaced in Log(P)
REAL(8), DIMENSION(1:N_Samples,1:N_P) :: TabHistLogP = 0.d0 ! Table for Histogram of peak flux P for each sample
REAL(8), DIMENSION(1:N_Samples,1:N_P) :: TabHistLogP_master = 0.d0 ! Table for Histogram of peak flux P for each sample
INTEGER, DIMENSION(1:N_Samples) :: iBinPeakflux ! Indices for values drawn
LOGICAL, DIMENSION(0:N_Samples) :: Psave = .FALSE. ! Saves (TRUE) Peak Flux histograms for each sample (Intrinsic, BATSE23...)
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: PFile ! Outputfile name for Peak Flux for each sample
CHARACTER(Len=150), DIMENSION(0:N_Samples) :: PErrorFile ! Outputfile name for Peak Flux Error for each sample
! --------------------------------------- !
! ------ Observational constraints ------ !
! --------------------------------------- !
! --- BATSE23 : peak flux [ph/cm2/s] distribution Kommers et al. 2000 --- !
! ----------------------------------------------------------------------- !
! Histogram
INTEGER, PARAMETER :: N_Komm = 25 ! Number of bins in TabP23
REAL(8), DIMENSION(1:N_Komm) :: TabHistKomm_P23 = 0.d0 ! Table for Histogram of Peak flux
REAL(8), DIMENSION(1:N_Komm) :: TabHistKomm_P23_master = 0.d0 ! Table for Master Histogram of Peak flux
REAL(8), DIMENSION(1:N_Komm) :: TabHistKomm_DRDP = 0.d0 ! Table for Histogram of Rate ( = TabHistP23(i)/(Nb_GRB * (P23(i)-P23(i-1))) )
REAL(8), DIMENSION(1:N_Komm) :: TabHistKomm_DRDPerr = 0.d0 ! Table for error of Histogram of Rate ( = TabHistP23(i) / (Nb_GRB * (P23(i)-P23(i-1))) )
REAL(8) :: k_Kommers = 0.d0 ! Normalization coefficient
INTEGER :: iBinKomm ! Index for histogram
CHARACTER(Len=150) :: KommFile = "Kommers_constraint" ! Outputfile name for Kommers
CHARACTER(Len=150) :: KommErrorFile = "Kommers_constrainterr" ! Outputfile name for Kommers Error
! Observational data
REAL(8), DIMENSION(0:N_Komm) :: TabKomm_P23, TabKomm_LogP23 ! Table 2 of Kommers et al. 2000
REAL(8), DIMENSION(1:N_Komm) :: TabHistKomm_P23obs = 0.d0 ! Table for observed BATSE23 Histogram of P23 (data from Kommers et al 2000)
REAL(8), DIMENSION(1:N_Komm) :: TabKomm_DRobs ! Table for observed BATSE23 Rate [GRB/yr/sr] (Kommers et al 2000)
REAL(8), DIMENSION(1:N_Komm) :: TabKomm_DRDPobs ! Table for observed BATSE23 Rate per Peak flux [(GRB/yr/sr) / (ph/sm2/s)] (Kommers et al 2000)
REAL(8), DIMENSION(1:N_Komm) :: TabKomm_DRobserr, TabKomm_DRDPobserr ! Table for error on observed BATSE23 rate (Kommers et al 2000)
! --- BATSE23 : peak energy [keV] distribution Preece --- !
! ------------------------------------------------------- !
! Histogram
INTEGER, PARAMETER :: N_Preece = 10 ! Number of bins in TabPreece_Ep
REAL(8), DIMENSION(1:N_Preece) :: TabHistPreece_Ep = 0.d0 ! Table for Histogram of Peak energy
REAL(8), DIMENSION(1:N_Preece) :: TabHistPreece_Ep_master = 0.d0 ! Table for Histogram of Peak energy of master proc
REAL(8), DIMENSION(1:N_Preece) :: TabHistPreece_Eperr = 0.d0 ! Table for Histogram of Peak energy error
REAL(8) :: k_Preece = 0.d0 ! Normalization coefficient
INTEGER :: iBinPreece ! Index for histogram
CHARACTER(Len=150) :: PreeceFile = "Preece_constraint" ! Outputfile name for generated Ep histogram
CHARACTER(Len=150) :: PreeceErrorFile = "Preece_constrainterr" ! Outputfile name for Error on generated Ep histogram
! Observational data
REAL(8), DIMENSION(0:N_Preece) :: TabPreece_Ep, TabPreece_LogEp ! Table from Preece
REAL(8), DIMENSION(1:N_Preece) :: TabHistPreece_Epobs = 0.d0 ! Table for observed BATSE23 Histogram of Ep (data from Preece)
REAL(8), DIMENSION(1:N_Preece) :: TabHistPreece_Epobserr = 0.d0 ! Table for observed BATSE23 Histogram error of Ep (data from Preece)
! --- BATSE23 : LogN LogP distribution Stern --- !
! ---------------------------------------------- !
! Histogram
INTEGER, PARAMETER :: N_Stern = 27 ! Number of bins in TabStern_P23
REAL(8), DIMENSION(1:N_Stern) :: TabHistStern_P23 = 0.d0 ! Table for Histogram of Peak flux
REAL(8), DIMENSION(1:N_Stern) :: TabHistStern_P23_master = 0.d0 ! Table for Histogram of Peak flux
REAL(8), DIMENSION(1:N_Stern) :: TabHistStern_P23err = 0.d0 ! Table for the normalized residuals (Model-Obs)/Error
REAL(8), DIMENSION(1:N_Stern) :: TabHistStern_P23_forlnL = 0.d0 ! Table for Histogram of Peak flux used in lnL (not corrected for useful time and dlogP)
REAL(8) :: k_Stern = 0.d0 ! Normalization coefficient
REAL(8) :: k_Stern_forlnL = 0.d0 ! Normalization coefficient for lnL calculation
INTEGER :: iBinStern ! Index for histogram
CHARACTER(Len=150) :: SternFile = "Stern_constraint" ! Outputfile name for generated P23
CHARACTER(Len=150) :: SternErrorFile = "Stern_constrainterr" ! Outputfile name for Error on generated P23
! Observational data
REAL(8), DIMENSION(0:N_Stern) :: TabStern_P23, TabStern_LogP23 ! Table from Stern
REAL(8), DIMENSION(1:N_Stern) :: TabHistStern_P23obs = 0.d0 ! Table for LogN LogP from BATSE23 (data from Stern)
REAL(8), DIMENSION(1:N_Stern) :: TabHistStern_P23obs_forlnL = 0.d0 ! Table for LogN LogP from BATSE23 (data from Stern)
REAL(8), DIMENSION(1:N_Stern) :: TabHistStern_P23obserr = 0.d0 ! Table for LogN LogP error from BATSE23 (data from Stern)
REAL(8), DIMENSION(1:N_Stern) :: TabHistStern_P23obserr_forlnL = 0.d0 ! Table for LogN LogP error from BATSE23 (data from Stern)
REAL(8) :: Delta_t_Stern = 9.1d0 ! Duration of the observation of the Stern sample (in years)
REAL(8) :: Omega_div_4Pi = 0.67d0 ! Fraction of the solid angle of sky observed by BATSE (for the Stern sample)
! --- HETE2 : X-ray Flash fraction --- !
! ------------------------------------ !
! Fraction
REAL(8) :: Frac_XRFHETE2
REAL(8) :: sigma_XRFHETE2
REAL(8) :: NGRB_XRFHETE2=0.d0, NGRB_HETE2=0.d0
CHARACTER(Len=150) :: XRFHETE2File = "XRFHETE2_constraint" ! Outputfile name for generated XRF fraction
CHARACTER(Len=150) :: XRFHETE2ErrorFile = "XRFHETE2_constrainterr" ! Outputfile name for error on generated XRF fraction
! Observational data
REAL(8), PARAMETER :: Frac_XRFHETE2obs = 0.35d0 ! X-ray flash fraction detected by HETE2
REAL(8), PARAMETER :: sigma_XRFHETE2obs = 0.15d0 ! Error on X-ray flash fraction detected by HETE2
! --- GBM : Ep distribution --- !
! ----------------------------- !
INTEGER, PARAMETER :: N_EpGBM = 9 ! Number of bins in TabEpGBM
REAL(8), DIMENSION(1:N_EpGBM) :: TabHistEpGBM_Epobs = 0.d0 ! Table for Histogram of Peak energy
REAL(8), DIMENSION(1:N_EpGBM) :: TabHistEpGBM_Epobs_master = 0.d0 ! Table for Master Histogram of Peak energy
REAL(8), DIMENSION(1:N_EpGBM) :: TabHistEpGBM_Epobserr = 0.d0 ! Table for Histogram of error on peak energy
REAL(8) :: k_EpGBM = 0.d0 ! Normalization coefficient
INTEGER :: iBinEpGBM ! Index for histogram
REAL(8) :: Delta_t_EpGBM = 8.28d0 ! Duration of the observation of the EpGBM sample (in years)
CHARACTER(Len=150) :: EpGBMFile = "EpGBM_constraint" ! Outputfile name for EpGBM
CHARACTER(Len=150) :: EpGBMErrorFile = "EpGBM_constrainterr" ! Outputfile name for EpGBM Error
! Observational data
REAL(8), DIMENSION(0:N_EpGBM) :: TabEpGBM_Epobs, TabEpGBM_LogEpobs ! Extracted histogram from GBM catalog
REAL(8), DIMENSION(1:N_EpGBM) :: TabHistEpGBM_Epobsobs = 0.d0 ! Table for observed GBM Histogram of Epobs (data from Gruber et al 2014 catalog)
REAL(8), DIMENSION(1:N_EpGBM) :: TabHistEpGBM_Epobsobserr = 0.d0 ! Table for observed error of GBM Histogram of Epobs (data from Gruber et al 2014 catalog)
! --- eBAT6 : Ep-L plane --- !
! -------------------------- !
INTEGER, PARAMETER :: N_eBAT6_EpL = 97 ! Number of bins in TabeBAT6_EpL
REAL(8), DIMENSION(0:1,0:N_eBAT6_EpL) :: TabeBAT6_EpL = 0.d0 ! Table for bins of EpL distribution
REAL(8), DIMENSION(1:N_eBAT6_EpL,1:N_eBAT6_EpL) :: TabHisteBAT6_EpL = 0.d0 ! Table for Histogram of EpL distribution
REAL(8), DIMENSION(1:N_eBAT6_EpL,1:N_eBAT6_EpL) :: TabHisteBAT6_EpL_master = 0.d0 ! Table for Master Histogram of EpL distribution
INTEGER :: iBineBAT6_Ep, iBineBAT6_L ! Indexes for histogram
INTEGER, PARAMETER :: Indice_Ep = 0
INTEGER, PARAMETER :: Indice_L = 1
CHARACTER(Len=150) :: eBAT6_EpLFile = "eBAT6_EpL" ! Outputfile name for eBAT6 Ep L plane
CHARACTER(Len=150) :: eBAT6_EpLErrorFile = "eBAT6_EpLerr" ! Outputfile name for eBAT6 Error on Ep L plane
! --- eBAT6 : redshift distribution --- !
! ------------------------------------- !
INTEGER, PARAMETER :: N_eBAT6 = 15 ! Number of bins in TabeBAT6
REAL(8), DIMENSION(1:N_eBAT6) :: TabHisteBAT6_z = 0.d0 ! Table for Histogram of redshift distribution
REAL(8), DIMENSION(1:N_eBAT6) :: TabHisteBAT6_z_master = 0.d0 ! Table for Master Histogram of redshift distribution
REAL(8), DIMENSION(1:N_eBAT6) :: TabHisteBAT6_zerr = 0.d0 ! Table for Histogram of error on redshift distribution
REAL(8) :: norm_eBAT6 = 0.d0 ! Normalization coefficient
INTEGER :: iBineBAT6 ! Index for histogram
REAL(8) :: k_eBAT6 = 0.d0 ! Normalization coefficient
REAL(8) :: Delta_t_eBAT6 = 9.3d0 ! Duration of the observation of the eBAT6 sample (in years, date first burst - date last burst)
CHARACTER(Len=150) :: eBAT6File = "eBAT6_constraint" ! Outputfile name for eBAT6
CHARACTER(Len=150) :: eBAT6ErrorFile = "eBAT6_constrainterr" ! Outputfile name for eBAT6 Error
! Observational data
REAL(8), DIMENSION(0:N_eBAT6) :: TabeBAT6_z ! Extracted histogram bins from extended BAT6 catalog
REAL(8), DIMENSION(1:N_eBAT6) :: TabHisteBAT6_zobs = 0.d0 ! Table for observed eBAT6 Histogram of redshift (data from Pescalli et al. 2016)
REAL(8), DIMENSION(1:N_eBAT6) :: TabHisteBAT6_zobserr = 0.d0 ! Table for observed error of eBAT6 Histogram of redshift (data from Pescalli et al. 2016)
! -------- Chi2 -------- !
! ---------------------- !
REAL(8), DIMENSION(0:N_Constraints) :: Chi2 ! Table for Chi2 adjusment of the model for each constraint
REAL(8), DIMENSION(0:N_Constraints) :: Chi2_old ! Table for Chi2 adjusment of the model for each constraint (used in MCMC)
INTEGER :: dof ! Numbers of degrees of freedom
REAL(8) :: delta_chi2_1 ! Chi2 interval in which "good models" are included at 1 sigma (68.3%)
REAL(8) :: delta_chi2_2 ! Chi2 interval in which "good models" are included at 2 sigma (95.5%)
REAL(8) :: delta_chi2_3 ! Chi2 interval in which "good models" are included at 3 sigma (99.7%)
REAL(8) :: Chi2_min = 1.d21 ! Lowest Chi2 found
REAL(8) :: Chi2_best = 1.d21 ! Best Chi2 found (used in post processing to redefine acceptable interval of Chi2)
! REAL(8) :: Chi2_old = 1.d21 ! Old Chi2 used for MCMC
! REAL(8) :: Chi2_new = 1.d21 ! New Chi2 used for MCMC
INTEGER :: good_model=0, Nb_good_models=0, Nb_models=0 ! Number of models and good models (defined above)
INTEGER :: Nb_good_models_to_pp=0, Nb_good_models_pp=0 ! Number of good models to post-process and number that have been post-processed so far
! ------- Likelihood ------- !
! -------------------------- !
REAL(8), DIMENSION(0:N_Constraints) :: lnL = 0.d0 ! Log of the likelihood function
REAL(8), DIMENSION(0:N_Constraints) :: lnL_max_test = 0.d0 ! Log of the likelihood function
REAL(8), DIMENSION(0:N_Constraints) :: lnL_empty_test = 0.d0 ! Log of the likelihood function
REAL(8), DIMENSION(0:N_Constraints) :: lnL_old = 0.d0 ! Log of the likelihood function (used in MCMC)
REAL(8) :: epsilon = 1.d-3 ! Small addition to avoid empty bins in log likelihood
REAL(8) :: lnL_max = -999.d0 ! Max value found for lnL
REAL(8), DIMENSION(0:N_Constraints) :: lnL_weight = 1.d0 ! Weight given to each constraint in lnL calculation
REAL(8) :: t
INTEGER :: ii, jj, kk ! Indices for loops
REAL(8) :: pseudo_collapse_rate = 0.d0
REAL(8) :: collapse_rate_from_SFR = 5.66786d8 ! From SFR Vangioni+15 (based on Springel Hernquist)
! ----- Variables for the GRB draws ----- !
! Intrinsic
REAL(8) :: L,z,D_L,Ep,alpha,beta ! variables used for each GRB draw
REAL(8) :: ktild ! Normalization of spectrum
REAL(8) :: t_star ! Luminosity BPL_evol draw
! Assumptions
REAL(8) :: z0,zmax,a,b,zm,R0
REAL(8) :: Ep0, sigmaLog
! Observed
REAL(8) :: softness
REAL(8) :: Epobs
! ------ MCMC stuff ----- !
INTEGER :: N_MCMC_iter = 25000 ! Number of iterations to run the MCMC chain for
INTEGER :: MCMC_run_nb ! Current run number
INTEGER :: N_walkers = 3 ! Number of walkers to try
REAL(8) :: a_ratio = 1.d0 ! Ratio used in the Metropolis-Hastings algorithm
REAL(8) :: accepted = 0.d0 ! Number of accepted jumps
REAL(8) :: acceptance_ratio = 0.d0 ! Ratio of accepted jumps to total jumps
INTEGER :: steps_since_reset = 0 ! Number of steps since reset
INTEGER :: rejected = 0 ! Counts how many times a step was rejected to avoid getting stuck somewhere
INTEGER :: rejected_limit = 1000 ! Maximum number of steps rejected after which the chain is reset
INTEGER :: accepted_rec = 0 ! Acceptance recorded (saved). 0 if step was rejected, 1 if step was accepted (used for saving and post processing purposes)
INTEGER :: MCMC_step_check = 250 ! Number of steps after which the codes checks if the step size is appropriate
INTEGER :: temperature_check = 100 ! Number of steps after which the codes updates the temperature for the annealing algorithm.
REAL(8) :: tau = 0.d0 ! Temperature used in the annealing algorithm
REAL(8) :: tau_0 = 1.d3 ! Starting temperature
REAL(8) :: tau_lim = 1.d0 ! Temperature limit towards which tau converges
REAL(8) :: kappa_tau = 0.d0 ! Cool down speed
! --------------------------------- !
! ------- End of declaration ------ !
! --------------------------------- !
! ----- Initialization ----- !
CALL MPI_INIT(code) ! MPI environment starts here
!CALL PTIM_start(user_label) ! times stuff
CALL MPI_COMM_RANK(MPI_COMM_WORLD, rank, code) ! gives the rank of the processor
CALL MPI_COMM_SIZE(MPI_COMM_WORLD, nb_procs, code) ! gives the number of processors being used
WRITE(str_rank,'(I1)') rank ! gives a string version of the processor rank
IF(rank == master_proc) SHOW_READ = .TRUE. ! Only master proc has verbosity (otherwise unreadable)
CALL InitPhysics(.FALSE.) ! Initializes Omega_M, Omega_Lambda etc... and filters
CALL InitCosmology(SHOW_READ) ! Creates precise tables for z, dVdz, D_L and Vz
CALL Generate_Names() ! Creates TabSample_name
CALL ReadInitFile(InitFile) ! Reads the input file and sets the models according to the user's choice
IF(run_mode > 0) THEN
CALL ReadParamSearchFile() ! Reads the input file for parameter search mode
ELSE
CALL Calculate_dof()
END IF
CALL Generate_Paths() ! Creates the paths for the save files
CALL Init_RNG() ! Initializes random number generator
CALL InitBoundaries() ! Creates various boundaries for the samples
IF(run_mode < 2) CALL Reset_eBAT6_output_files()
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " Initializion OK"
! CALL TestKiss()
! --- Observational constraints --- !
CALL Prepare_Constraints() ! Generate the tables with observational data
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " Prepare_Constraints OK"
delta_chi2_1 = Calc_DeltaChi2(0.6827d0, REAL(dof,8))
delta_chi2_2 = Calc_DeltaChi2(0.9545d0, REAL(dof,8))
delta_chi2_3 = Calc_DeltaChi2(0.9973d0, REAL(dof,8))
IF ((reprise .EQV. .TRUE.) .OR. (run_mode == post_process)) THEN
! Do nothing
ELSE
IF(rank == master_proc) THEN
CALL WRITE_INFO()
END IF
END IF
! Reprise mode
CALL Reprise_mode()
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " Reprise_mode OK"
IF(run_mode == param_search) THEN
DO ii=1, 100
good_model = 0
! Save random generator indexes for reproductibility
CALL Save_KISS()
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " Save_KISS OK"
! Random draw of parameters
IF(rank == master_proc) THEN
!CALL Draw_model_parameters()
!TabParam_Lum(Param_Lum_Lbreak) = 10.d0**(50.0d0 + ii/100.d0 * 3.d0)
!TabParam_Ep(Param_Ep_alpha_amati) = 0.0d0 + ii/100.d0 * 1.d0
TabParam_z(Param_z_zeta) = 0.25d0 + ii/100.d0 * .25d0
END IF
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " Draw_model_parameters OK"
CALL MPI_BCAST(TabParam_Lum, NParam_Lum, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_z, NParam_z, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_Ep, NParam_Ep, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_spec, NParam_spec, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MonteCarlo(hist_flag)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " MonteCarlo OK"
!IF(Chi2(0) < Chi2_min) THEN
!!$ IF(lnL(0) > lnL_max) THEN
!!$ ! Rerun model with correct seeds and save histograms
!!$ iKiss = TabSave_ijk_KISS(1,rank)
!!$ jKiss = TabSave_ijk_KISS(2,rank)
!!$ kKiss = TabSave_ijk_KISS(3,rank)
!!$ IF(rank == master_proc) THEN
!!$ CALL Draw_model_parameters()
!!$ END IF
!!$ CALL MPI_BCAST(TabParam_Lum, NParam_Lum, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
!!$ CALL MPI_BCAST(TabParam_z, NParam_z, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
!!$ CALL MPI_BCAST(TabParam_Ep, NParam_Ep, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
!!$ CALL MPI_BCAST(TabParam_spec, NParam_spec, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
!!$ hist_flag = 2
!!$ CALL Reset_eBAT6_output_files()
!!$ CALL MonteCarlo(hist_flag)
!!$ hist_flag = 0
!!$ IF(rank == master_proc) THEN
!!$ !WRITE(*,*) "New best model :", Chi2(0)," (compared to :",Chi2_min,"). Histograms saved."
!!$ WRITE(*,*) "New best model :", lnL(0)," (compared to :",lnL_max,"). Histograms saved."
!!$ END IF
!!$ !Chi2_min = Chi2(0)
!!$ lnL_max = lnL(0)
!!$ IF(rank == master_proc) CALL Update_best_parameters()
!!$ END IF
!!$ IF(Chi2(0) <= dof + delta_chi2_3) THEN ! 3 sigma interval for now
!!$ good_model = 1
!!$ Nb_good_models = Nb_good_models + 1
!!$ END IF
!!$
Nb_models = Nb_models + 1
!!$ ! Write in reprise
!!$ OPEN(UNIT=43, FILE=TRIM(path)//'reprise.dat', FORM='unformatted', POSITION='append')
!!$ IF(rank == master_proc) WRITE(43) TabSave_ijk_Kiss, TabParam_Lum, TabParam_z, TabParam_Spec, TabParam_Ep, &
!!$ & Chi2, lnL, k_Kommers, k_Stern, k_Preece, k_EpGBM, Frac_XRFHETE2, dof, lnL_max, Nb_good_models, Nb_models
!!$ CLOSE(43) ! Close reprise file
OPEN(UNIT=43, FILE=TRIM(path)//'reprise.dat', FORM='unformatted', POSITION='append')
IF(rank == master_proc) WRITE(43) TabSave_ijk_Kiss, TabParam_Lum, TabParam_z, TabParam_Spec, TabParam_Ep, &
& Chi2, lnL, k_Kommers, k_Stern, k_Preece, k_EpGBM, k_eBAT6, dof, accepted_rec, tau, Step_Lum, Step_z, Step_Ep,&
& TabHistLogL_master, TabHistz_master, TabHistLogEp_master, TabHistLogEpobs_master, TabHistLogP_master, &
& TabHistKomm_DRDP, TabHistPreece_Ep_master, TabHistStern_P23_master, TabHistEpGBM_Epobs_master, TabHisteBAT6_z_master
CLOSE(43) ! Close reprise file
IF(Nb_models >= 25000) THEN
IF(rank == master_proc) WRITE(*,*) "Reached 25000 models"
EXIT
END IF
IF(rank == master_proc)THEN
IF(MOD(Nb_models, 5) == 0) WRITE(*,'(I6x,I5,A,F5.1)') Nb_models, Nb_good_models, ' Best lnL : ',lnL_max
END IF
END DO
! Markov Chain Monte Carlo
ELSE IF(run_mode == MCMC) THEN
IF (rank == master_proc) WRITE(*,*) " You chose MCMC mode"
DO kk = 1, N_walkers
Tabparam_Lum_old = TabParam_Lum
TabParam_Ep_old = TabParam_Ep
TabParam_z_old = TabParam_z
! Save random generator indexes for reproductibility
CALL Save_KISS()
!CALL Reset_Markov_Chain()
CALL Reset_MCMC_Step_Size()
CALL Reset_temperature()
CALL MonteCarlo(hist_flag) ! Calculate Chi2
rejected = 0 ! Reset consecutive rejected jumps
accepted_rec = 1 ! By design this jump is accepted
accepted = 0.d0 ! Reset the accepted rate
acceptance_ratio = 0.d0 ! Reset ratio of accepted jumps
steps_since_reset = 0 ! Reset steps count
MCMC_run_nb = MCMC_run_nb + 1
kappa_tau = Calc_kappa_tau(tau_0, 1.d-3) ! Use to calculate the appropriate cooling rate for the annealing algorithm
starting_i = Calc_starting_i()
DO ii = starting_i, N_MCMC_iter
! Save random generator indexes for reproductibility
CALL Save_KISS()
IF (MOD(ii, temperature_check) == 0) CALL Update_temperature(kappa_tau, tau_lim)
IF (tau < 1.001d0) THEN ! Don't check acceptance until chain has cooled
rejected = 0
accepted = 0.d0
acceptance_ratio = 0.d0
ELSE
CALL Reset_MCMC_Step_Size() ! TEMP
Step_Lum = Step_Lum * (1.d0 + 5.d0 * tau/tau_0)
Step_Ep = Step_Ep *(1.d0 + 5.d0 * tau/tau_0)
Step_z = Step_z *(1.d0 + 5.d0 * tau/tau_0)
END IF
!IF ( (MOD(ii, MCMC_step_check) == 0) .AND. (tau < 1.001d0) )CALL Update_MCMC_Step_Size(0.5d0, 2.d0)
IF (rejected >= rejected_limit) THEN ! If after a certain amount of jumps the chain hasn't moved, manually reset it (avoids getting stuck in areas of low likelihood)
CALL Reset_Markov_Chain() ! Randomly assign a new position in parameter space
END IF
steps_since_reset = steps_since_reset + 1
! Save current state
TabParam_Lum_old = TabParam_Lum
TabParam_z_old = TabParam_z
TabParam_Ep_old = TabParam_Ep
Chi2_old = Chi2
lnL_old = lnL
! Draw Markov jump in parameter space
IF(rank == master_proc) THEN
CALL Draw_Markov_Jump()
END IF
CALL MPI_BCAST(TabParam_Lum, NParam_Lum, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_z, NParam_z, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_Ep, NParam_Ep, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_spec, NParam_spec, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MonteCarlo(hist_flag)
MCMC_run_nb = MCMC_run_nb + 1
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " run : ",MCMC_run_nb," MonteCarlo OK"
IF (lnL(0) >= lnL_old(0)) THEN
accepted = accepted + 1.d0
rejected = 0
ELSE
a_ratio = (lnL(0)- lnL_old(0)) / tau
IF(a_ratio <= -50.d0) THEN ! because exp(-50) ~ 1e-22, essentially zero
a_ratio = 0.d0
ELSE
a_ratio = EXP(a_ratio)
END IF
IF(rank == master_proc) t = uniform()
CALL MPI_BCAST(t, 1, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
IF(t <= a_ratio ) THEN
accepted = accepted + 1.d0
rejected = 0
ELSE ! if jump not accepted
rejected = rejected + 1
CALL Update_Markov_Chain() ! If the Markov jump is not accepted, revert to previous state
END IF
END IF ! end of better or worse likelihood
acceptance_ratio = accepted / REAL(steps_since_reset,8)
CALL Write_reprise_MCMC()
END DO ! End MCMC iterations
END DO ! end walkers loop
ELSE IF (run_mode == post_process) THEN
! This mode is for recomputing the good models and generating error bars on the observables
CALL Define_Nb_lines()
Chi2_best = Chi2_min
IF(rank == master_proc) THEN
WRITE(*,*) "Chi2_min found = ", Chi2_best
OPEN(UNIT=46, FILE=TRIM(path)//'reprise.dat', FORM='unformatted')
END IF
Nb_good_models_pp = 0
pp_flag = 0
DO WHILE(pp_flag == 0)
IF(rank == master_proc) THEN
DO
READ(46, IOSTAT=pp_flag) TabSave_ijk_Kiss, TabParam_Lum, TabParam_z, TabParam_Spec, TabParam_Ep, &
& Chi2, k_Kommers, k_Stern, k_Preece, k_EpGBM, Frac_XRFHETE2, dof, Chi2_min, Nb_good_models, Nb_models
jj = jj + 1
IF(ABS(Chi2(0)) <= Chi2_best + delta_chi2_3) THEN
Nb_good_models_pp = Nb_good_models_pp + 1
WRITE(*,'(A,I5,A,F4.0,A)') "Nb_good_models_pp : ", Nb_good_models_pp, " (",100.d0*REAL(jj,8)/REAL(Nb_lines,8),"% of file)"
!WRITE(*,*) "Good Chi2 = ", Chi2(0), Chi2(Constraint_EpGBM), Chi2(Constraint_Stern)
EXIT
END IF
END DO
END IF
CALL MPI_BCAST(pp_flag, 1, MPI_INT, master_proc, MPI_COMM_WORLD, code)
!WRITE(*,*) "Before BCAST ; rank : ", rank," ijk Kiss : ", TabSave_ijk_KISS
CALL MPI_BCAST(TabSave_ijk_KISS, 3*nb_procs, MPI_INT, master_proc, MPI_COMM_WORLD, code)
!WRITE(*,*) "After BCAST ; rank : ", rank," ijk Kiss : ", TabSave_ijk_KISS
iKiss = TabSave_ijk_KISS(1,rank)
jKiss = TabSave_ijk_KISS(2,rank)
kKiss = TabSave_ijk_KISS(3,rank)
!WRITE(*,*) "Before draw ; rank : ", rank," Lmin, Lmax, slope : ", TabParam_Lum(Param_Lum_Lmin), TabParam_Lum(Param_Lum_Lmax), TabParam_Lum(Param_Lum_slope)
!WRITE(*,*) "Before draw ; rank : ", rank," Tabparamz : ",TabParam_z
IF(rank == master_proc) THEN
CALL Draw_model_parameters()
END IF
CALL MPI_BCAST(TabParam_Lum, NParam_Lum, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_z, NParam_z, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_Ep, NParam_Ep, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_spec, NParam_spec, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
!WRITE(*,*) "After draw ; rank : ", rank," Tabparamz : ",TabParam_z
!WRITE(*,*) "After draw ; rank : ", rank," Lmin, Lmax, slope : ", TabParam_Lum(Param_Lum_Lmin), TabParam_Lum(Param_Lum_Lmax), TabParam_Lum(Param_Lum_slope)
CALL MonteCarlo(hist_flag)
!WRITE(*,*) "PP Chi2 = ", Chi2(0), Chi2(Constraint_EpGBM), Chi2(Constraint_Stern)
OPEN(UNIT=43, FILE=TRIM(path)//'reprise_pp.dat', FORM='unformatted', POSITION='append')
IF(rank == master_proc) WRITE(43) TabSave_ijk_Kiss, TabParam_Lum, TabParam_z, TabParam_Spec, TabParam_Ep, &
& Chi2, k_Kommers, k_Stern, k_Preece, k_EpGBM, Frac_XRFHETE2, dof, chi2_min, Nb_good_models, Nb_models
CLOSE(43) ! Close post-process reprise file
END DO
IF(rank == master_proc) THEN
CLOSE(46) ! Close reprise file
END IF
ELSE ! IF(run_mode == one_run)
IF (rank == master_proc) WRITE(*,*) " You chose one run mode"
IF (rank == master_proc) CALL InitECLAIRs(nsigmasECLAIRs)
CALL MPI_BCAST(bkgECLAIRsB1, 1, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
Threshold(Sample_SVOM) = bkgECLAIRsB1
CALL MPI_BCAST(omegaECLAIRs, 1, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TABeffECLAIRsE, NeffECLAIRs, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TABeffECLAIRsA, NeffECLAIRs, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TABbkgECLAIRsE, NbkgECLAIRs, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TABbkgECLAIRsB, NbkgECLAIRs, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TABomegaECLAIRs, 2*NoffECLAIRs+1, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TABoffECLAIRs , 2*NoffECLAIRs+1, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL Save_KISS()
CALL MonteCarlo(hist_flag)
END IF
IF(rank == master_proc) WRITE(*,*) "[------------------- END OF CODE ------------------]"
CALL MPI_FINALIZE(code)
CONTAINS
SUBROUTINE MonteCarlo(hist_flag)
INTEGER, INTENT(in) :: hist_flag
! Main subroutine of the code, is organized as follows :
!
! 1. Select models (Lum, z, Ep...)
!
! (1.bis) Prepare histograms (x-axis, with the limits given from the models, reset histograms)
!
! 2. Generate GRBs (random draw)
! a. Properties
! - Intrinsic (Lum, z, Ep...)
! - Observed (Peak flux for various instruments, Peak energy observed...)
! b. Detection by instrument (BATSE23, SWIFT...)
! c. Preparation of indices (Lum, z, Ep, Peak flux...)
! d. Filling of histograms per sample (Intrinsic, BATSE23, SWIFT...)
!
! 3. Normalizations (GRB rate, k_stern, etc...)
!
! 4. Chi2 Calculation (using Kommers, Preece, Stern...)
!
! (5.) Save histograms (Lum, z, Ep...)
!
! (6.) Save constraints (Kommers, Preece, Stern...)
!
INTEGER, PARAMETER :: N_saved_Prop = 6 ! Saving Log(L), z, Ep, alpha, beta
INTEGER :: i_Prop ! Index for loops
CHARACTER(*), PARAMETER :: GRB_PropFile = "GRB_Properties" ! Filename for saving the properties
REAL(8), DIMENSION(0:N_Samples, 0:N_saved_Prop) :: GRB_Prop ! Table that saves the properties
REAL(8), DIMENSION(0:N_Samples, 0:N_saved_Prop) :: GRB_Prop_master ! Table that saves the properties for master proc
REAL(8), DIMENSION(0:N_Samples, 0:N_saved_Prop) :: average_Prop ! Table for the average of the properties
REAL(8), DIMENSION(0:N_Samples, 0:N_saved_Prop) :: average_Prop_master ! Table for the average of the properties for master proc
REAL(8) :: t, x1, x2
INTEGER :: imin,imax,i,j,M ! variables for loops and dichotomy
IF(rank == master_proc) THEN
IF(run_mode == one_run) WRITE(*,*) " "
IF(run_mode == one_run) WRITE(*,'(A)') " ====================================== Monte Carlo ================================================= "
IF(run_mode == one_run) WRITE(*,*) " "
IF(run_mode == one_run) WRITE(*, '(A)', advance='no') "[ (%) = 0"
END IF
! --------------------------------- !
! -------- 1. Select model -------- !
! --------------------------------- !
CALL Set_Fixed_Parameters() ! Calculate certain quantities once for the whole population (t_star, ktild, L, z if fixed...)
CALL Prepare_Redshift() ! Prepare distribution function for redshift draws
CALL Prepare_Luminosity() ! Prepare distribution function for Luminosity draws
CALL Prepare_Spec() ! Prepare distribution function for alpha and beta draws (currently only from GBM catalog)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in MonteCarlo Select model OK"
! ---------------------------------- !
! --- (1.bis) Prepare histograms --- !
! ---------------------------------- !
IF(hist_flag >= 1) THEN
CALL Prepare_Histogram_Prop(TabHistlim_inf, TabHistlim_sup, n_call) ! Create histogram limits and resets them
END IF
IF(hist_flag >= 1) THEN
CALL Reset_Histogram_Samples() ! Resets histograms not used in Chi2 calculations but still included
END IF
CALL Reset_Histogram_Chi2() ! Resets histograms used in Chi2 calculation
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in MonteCarlo Prepare histograms OK"
CALL Reset_GRB_seeds() ! Reset GRB seeds to insure Chi2 variations aren't due to different realizations of the intrinsic population
! -------------------------------------- !
! ---------- 2. Generate GRBs ---------- !
! -------------------------------------- !
IF(run_mode == one_run) THEN
IF(Save_all_GRB .EQV. .TRUE.) THEN
IF(rank == master_proc) OPEN(UNIT=66, FILE=TRIM(path)//GRB_PropFile//".dat", FORM='unformatted') ! Save all GRB properties, be careful the file is heavy (several GB)
END IF
GRB_Prop = 0.d0 ! Reset GRB properties
average_Prop = 0.d0 ! Reset GRB properties
END IF
NaNtest_hist = .FALSE. ! Reset all NaN tests to false
! ----------------------------------------------------------------------------------- MAIN LOOP ----------------------------------------------------------------------------------------- !
DO i=1, Nb_GRB/nb_procs
NaNtest_prop = .FALSE.
! ---------- a. Properties ---------- !
! ----------------------------------- !
! ----------- Intrinsic properties ----------- !
CALL Draw_Redshift(z)
! z = 1.0d0
IF((rank == master_proc) .AND. (verbose == 2)) WRITE(*,*) " in MonteCarlo z OK : ", z
CALL Draw_Luminosity(L)
! L = 1.0d52
IF((rank == master_proc) .AND. (verbose == 2)) WRITE(*,*) " in MonteCarlo Lum OK : ", L
CALL Draw_alpha_beta(alpha, beta)
! alpha = 1.0d0
! beta = 2.5d0
IF((rank == master_proc) .AND. (verbose == 2)) WRITE(*,*) " in MonteCarlo alpha, beta OK : ", alpha, beta
CALL Draw_Ep(Ep)
! Ep = 600.d0
IF((rank == master_proc) .AND. (verbose == 2)) WRITE(*,*) " in MonteCarlo Ep OK : ", Ep
! ------------ Observed properties ----------- !
Epobs = Calc_Epobs(Ep,z)
CALL Calculate_Peakflux_Instrument()
IF((rank == master_proc) .AND. (verbose == 2)) WRITE(*,*) " in MonteCarlo Calculate_Peakflux_Instrument OK"
CALL Calculate_Detection_Probability()
IF((rank == master_proc) .AND. (verbose == 2)) WRITE(*,*) " in MonteCarlo Calculate_Detection_Probability OK"
! --------------- Histograms --------------- !
! ------------------------------------------ !
IF(hist_flag >= 1) THEN
CALL Fill_Histogram_Prop() ! Find the bins and add the probability of detection to the histograms of L, z, Ep etc...
END IF
CALL Fill_Histogram_Chi2() ! Find the bins and add the probability of detection to the histograms to use in Chi2 calculation
IF(hist_flag >= 1) CALL Fill_Samples() ! Find the bins and add the probability of detection to the histograms included but not used in Chi2 calculation
IF((rank == master_proc) .AND. (verbose == 2)) WRITE(*,*) " in MonteCarlo filling of Histograms OK"
IF(run_mode == one_run) THEN ! Calculate the GRB population properties
! --- GRB properties --- !
DO i_Sample=0, N_Samples
GRB_Prop(i_Sample, 0) = GRB_Prop(i_Sample, 0) + Prob_det(i_Sample)
GRB_Prop(i_Sample, Prop_L) = GRB_Prop(i_Sample, Prop_L) + L * Prob_det(i_Sample)
GRB_Prop(i_Sample, Prop_z) = GRB_Prop(i_Sample, Prop_z) + z * Prob_det(i_Sample)
GRB_Prop(i_Sample, Prop_Ep) = GRB_Prop(i_Sample, Prop_Ep) + Epobs * Prob_det(i_Sample)
GRB_Prop(i_Sample, Prop_alpha) = GRB_Prop(i_Sample, Prop_alpha) + alpha * Prob_det(i_Sample)
GRB_Prop(i_Sample, Prop_beta) = GRB_Prop(i_Sample, Prop_beta) + beta * Prob_det(i_Sample)
END DO
! Only record Intrinsic sample
! 1 2 3 4 5 6
! [GRB number] [Luminosity erg/s] [Redshift] [Observed Peak energy] [spectral slope alpha] [spectral slope beta]
! i4, 7f8, 5f8, 11f8
IF(Save_all_GRB .EQV. .TRUE.) WRITE(66) i, L, z, D_L, Epobs, alpha, beta, ktild, Peakflux_Instrument, Prob_det
IF (Mode_test) THEN
IF(rank == master_proc) THEN
WRITE(*,*) " "
WRITE(*,*) "GRB_nb =", i
WRITE(*,*) "z =", z
WRITE(*,*) "D_L =", D_L*Mpc
WRITE(*,'(A,1ES12.5)') " L =", L
WRITE(*,*) "alpha =", alpha
WRITE(*,*) "beta =",beta
WRITE(*,*) "Ep =",Ep
WRITE(*,*) "IBand =", 1.d0/ktild
WRITE(*,*) "ktild =", ktild
DO i_Instrument=1, N_Instruments
WRITE(*,*) "Instrument ",TRIM(TabInstrument_name(i_Instrument)), " : Peakflux =",Peakflux_Instrument(i_Instrument)
END DO
WRITE(*,*) "softness =",softness
DO i_Sample=1, N_Samples
WRITE(*,*) "Prob_det "//TRIM(TabSample_name(i_Sample))//" =", Prob_det(i_Sample)
END DO
WRITE(*,*) "Epobs =", Epobs
READ(*,*)
END IF
IF(verbose==1 .OR. verbose==2) READ(*,*)
END IF
! --- Nan testing --- !
IF (NaNtest_prop) THEN
WRITE(*,*) "[ z D_L Lum alpha beta ktild Ep Epobs ]"
WRITE(*,*) "[ ", z , D_L, L, alpha, beta, ktild, Ep, Epobs, " ]"
WRITE(*,*) "[ Peak Flux Instrument ]"
WRITE(*,*) "[ ", Peakflux_Instrument," ]"
WRITE(*,*) "[ Peak Flux Sample ]"
WRITE(*,*) "[ ", Peakflux," ]"
WRITE(*,*) "[ Prob det Instrument ]"
WRITE(*,*) "[ ", Prob_det," ]"
END IF
! Track progress
IF(rank == master_proc) THEN
IF( MOD(100.d0 * REAL(i,8)*REAL(nb_procs,8)/REAL(Nb_GRB,8), 5.d0) == 0 ) THEN
WRITE(*,'(I3,1x)', advance='no') INT(100.d0 * REAL(i,8)*REAL(nb_procs,8)/REAL(Nb_GRB))
END IF
END IF
END IF ! End of one_run mode
END DO ! end of main loop
IF(run_mode == one_run) THEN
IF((Save_all_GRB .EQV. .TRUE.) .AND. (rank == master_proc)) CLOSE(66)
IF(rank == master_proc) WRITE(*, '(A)') " ]"
END IF
! --------------------------------- !
! ----- End of : Generate GRB ----- !
! --------------------------------- !
! ----------------------------------------------------------------------------------- END OF MAIN LOOP ----------------------------------------------------------------------------------- !
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in Monte Carlo Main Loop ended OK"
! WRITE(*,*) " in Monte Carlo Main Loop ended OK for proc : ", rank
! -------- Combine histograms of each procs -------- !
IF(Sample_Included(Sample_Kommers)) CALL MPI_REDUCE(TabHistKomm_P23, TabHistKomm_P23_master, N_Komm, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in Monte Carlo Kommers reduce OK"
IF(Sample_Included(Sample_Stern)) CALL MPI_REDUCE(TabHistStern_P23, TabHistStern_P23_master, N_Stern, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in Monte Carlo Stern reduce OK"
IF(Sample_Included(Sample_Preece)) CALL MPI_REDUCE(TabHistPreece_Ep, TabHistPreece_Ep_master, N_Preece, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in Monte Carlo Preece reduce OK"
IF(Sample_Included(Sample_EpGBM)) CALL MPI_REDUCE(TabHistEpGBM_Epobs, TabHistEpGBM_Epobs_master, N_EpGBM, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in Monte Carlo EpGBM reduce OK"
IF(Sample_Included(Sample_eBAT6)) CALL MPI_REDUCE(TabHisteBAT6_z, TabHisteBAT6_z_master, N_eBAT6, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in Monte Carlo eBAT6 reduce OK"
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in Monte Carlo Reduced constraints OK"
IF(hist_flag >= 1) THEN
DO i_Sample = 0, N_Samples
IF(Sample_Included(i_Sample)) THEN
CALL MPI_REDUCE( TabHistLogL(i_Sample,:), TabHistLogL_master(i_Sample,:), N_L, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
CALL MPI_REDUCE( TabHistz(i_Sample,:), TabHistz_master(i_Sample,:), N_z, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
CALL MPI_REDUCE( TabHistLogEp(i_Sample,:), TabHistLogEp_master(i_Sample,:), N_Ep, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
CALL MPI_REDUCE(TabHistLogEpobs(i_Sample,:), TabHistLogEpobs_master(i_Sample,:), N_Ep, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
CALL MPI_REDUCE( TabHistalpha(i_Sample,:), TabHistalpha_master(i_Sample,:), N_spec_a, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
CALL MPI_REDUCE( TabHistbeta(i_Sample,:), TabHistbeta_master(i_Sample,:), N_spec_b, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
IF (i_Sample >= 1) THEN
CALL MPI_REDUCE( TabHistLogP(i_Sample,:), TabHistLogP_master(i_Sample,:), N_P, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
END IF
END IF
END DO
! eBAT6 Ep-L plane
CALL MPI_REDUCE(TabHisteBAT6_EpL, TabHisteBAT6_EpL_master, N_eBAT6_EpL**2, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in Monte Carlo Reduced prop histograms OK"
END IF
!WRITE(*,*) 'rank : ',rank,' tot, ind : ', GRB_Prop_master(0, 0), GRB_Prop(0, 0)
IF(run_mode == one_run) THEN
DO i_Sample = 0, N_Samples
DO i_Prop=0, N_saved_Prop
CALL MPI_REDUCE( GRB_Prop(i_Sample,i_Prop), GRB_Prop_master(i_Sample,i_Prop), 1, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD,code)
CALL MPI_REDUCE(average_Prop(i_Sample,i_Prop), average_Prop_master(i_Sample,i_Prop), 1, MPI_REAL8, MPI_SUM, master_proc, MPI_COMM_WORLD,code)
END DO
END DO
END IF
! Master does calculations
IF(rank == master_proc) THEN
! --- Print average quantities --- !
IF(run_mode == one_run) THEN
WRITE(*,*) " "
WRITE(*,'(A)') " ======================================= Average quantities ========================================="
WRITE(*,'(A)') "[ Sample Nb_GRB Luminosity Redshift Ep alpha beta ]"
WRITE(*,'(A)') "[ ------------------------------------------------------------------------------------------------- ]"
DO i_Sample=0, N_Samples
IF(Sample_Included(i_Sample)) THEN
average_Prop_master(i_Sample, 0) = GRB_Prop_master(i_Sample, 0)
IF ( average_Prop_master(i_Sample, 0) .NE. 0.d0 ) THEN
!WRITE(*,*) 'rank : ',rank,' L, tot_av : ', GRB_Prop_master(i_Sample, Prop_L), average_Prop_master(i_Sample, 0)
average_Prop_master(i_Sample, Prop_L) = GRB_Prop_master(i_Sample, Prop_L) / average_Prop_master(i_Sample, 0)
average_Prop_master(i_Sample, Prop_z) = GRB_Prop_master(i_Sample, Prop_z) / average_Prop_master(i_Sample, 0)
average_Prop_master(i_Sample, Prop_Ep) = GRB_Prop_master(i_Sample, Prop_Ep) / average_Prop_master(i_Sample, 0)
average_Prop_master(i_Sample, Prop_alpha) = GRB_Prop_master(i_Sample, Prop_alpha) / average_Prop_master(i_Sample, 0)
average_Prop_master(i_Sample, Prop_beta) = GRB_Prop_master(i_Sample, Prop_beta) / average_Prop_master(i_Sample, 0)
ELSE
average_Prop_master(i_Sample, :) = 0.d0
END IF
IF(run_mode == one_run) WRITE(*,'(A,A15,A,ES12.5,F6.1,A,5ES12.5,A)') "[ ",TabSample_name(i_Sample),":", &
& average_Prop_master(i_Sample, 0), 100.d0 * average_Prop_master(i_Sample, 0)/average_Prop_master(Sample_Intrinsic, 0), "%", &
& average_Prop_master(i_Sample, Prop_L), &
& average_Prop_master(i_Sample, Prop_z), &
& average_Prop_master(i_Sample, Prop_Ep), &
& average_Prop_master(i_Sample, Prop_alpha), &
& average_Prop_master(i_Sample, Prop_beta), &
& " ]"
END IF
END DO
WRITE(*,'(A)') "[ ------------------------------------------------------------------------------------------------- ]"
END IF ! end one_run mode printing
! ---------- 3. Normalizations ---------- !
! --------------------------------------- !
IF(run_mode == one_run) WRITE(*,'(A)') "[ ]"
IF(run_mode == one_run) WRITE(*,'(A)') "[ Normalization coefficients ]"
IF(run_mode == one_run) WRITE(*,'(A)') "[ ------------------------------------------------------------------------------------------------- ]"
CALL Normalize_Model()
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in MonteCarlo Normalize_Model OK"
IF(run_mode == one_run) WRITE(*,'(A)') "[ ]"
IF(run_mode == one_run) WRITE(*,'(A)') "[ Log Likelihood ]"
IF(run_mode == one_run) WRITE(*,'(A)') "[ ------------------------------------------------------------------------------------------------- ]"
CALL Calculate_unnormalized_Likelihood()
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in MonteCarlo Calculate_unnormed_lnL OK"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ lnL = ", lnL(0), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ max lnL = ", lnL_max_test(0), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ empty lnL = ", lnL_empty_test(0), " ]"
IF(run_mode == one_run) WRITE(*,'(A)') "[ ------------------------------------------------------------------------------------------------- ]"
! ----- 4. Chi squared calculation ----- !
! -------------------------------------- !
IF(run_mode == one_run) WRITE(*,'(A)') "[ ]"
IF(run_mode == one_run) WRITE(*,'(A)') "[ Chi squared ]"
IF(run_mode == one_run) WRITE(*,'(A)') "[ ------------------------------------------------------------------------------------------------- ]"
CALL Calculate_Chi2()
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in MonteCarlo Calculate_Chi2 OK"
!IF(rank == master_proc) WRITE(*,*) " new Chi2 = ", Chi2(0), Chi2(Constraint_EpGBM), Chi2(Constraint_Stern)
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ Chi2 = ", Chi2(0), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ Delta Chi2 (3 sigma) = ", dof + delta_chi2_3, " ]"
IF(run_mode == one_run) WRITE(*,'(A,I4.0,A)') "[ Degrees of freedom = ", dof, " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ Reduced Chi2 = ", Chi2(0)/REAL(dof,8), " ]"
IF(run_mode == one_run) WRITE(*,'(A)') "[ ------------------------------------------------------------------------------------------------- ]"
! ----- (5.) Save histograms ----- !
! -------------------------------- !
IF(hist_flag == 2) CALL Save_Histograms()
IF(hist_flag == 2) CALL Save_eBAT6()
! ----- (6.) Save constraints ----- !
! --------------------------------- !
IF(hist_flag == 2) CALL Save_Constraints()
IF(run_mode == post_process) CALL Post_process_Constraints()
IF(run_mode == one_run) WRITE(*,*) " "
IF(run_mode == one_run) WRITE(*,'(A)') " ==================================== Monte Carlo done ============================================== "
IF(run_mode == one_run) WRITE(*,*) " "
END IF ! Ends master rank computation
! Broadcast chi2
CALL MPI_BCAST(Chi2, N_Constraints, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
! Broadcast lnL
CALL MPI_BCAST(lnL, N_Constraints, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
END SUBROUTINE MonteCarlo
SUBROUTINE ReadInitFile(Name)
INTEGER :: s_L,s_z,s_Spec,s_Ep,s_P,s_Constraint,i,incl,temp
REAL(8) :: temp_real
! Initializes the parameters for the code
CHARACTER(Len=*), INTENT(in) :: Name
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') " ========================= ReadInitFile ========================= "
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A64A)') "[ Reading parameters in : "//TRIM(Name)//" "," ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
OPEN(UNIT=50, FILE=TRIM(Name))
IF(SHOW_READ) WRITE(*,'(A)') "[ ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ Input model parameters ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
! Path
CALL ReadLine(50, path)
path = '../Model_outputs/' // path
IF(SHOW_READ) WRITE(*,'(A,A47,A)') "[ Output path : ",ADJUSTL(path)," ]"
! Reprise mode
CALL ReadInteger(50, temp)
IF (temp == 1) THEN
reprise = .TRUE.
IF(SHOW_READ) WRITE(*,'(A)') "[ reprise mode : TRUE ]"
ELSE
IF(SHOW_READ) WRITE(*,'(A)') "[ reprise mode : FALSE ]"
END IF
! RNG
CALL ReadInteger(50, RNG)
IF (RNG == MT19937) THEN
IF(SHOW_READ) WRITE(*,'(A)') "[ RNG chosen : MT ]"
ELSE IF (RNG == Kiss_rng) THEN
IF(SHOW_READ) WRITE(*,'(A)') "[ RNG chosen : KISS ]"
ELSE
IF(SHOW_READ) WRITE(*,'(A)') "[ RNG chosen : INVALID ]"
END IF
! Run mode
CALL ReadInteger(50, run_mode)
IF (run_mode == one_run) THEN
hist_flag = 2
IF(SHOW_READ) WRITE(*,'(A)') "[ run mode chosen : one run ]"
ELSE IF (run_mode == param_search) THEN
IF(SHOW_READ) WRITE(*,'(A)') "[ run mode chosen : parameter search ]"
ELSE IF (run_mode == post_process) THEN
IF(SHOW_READ) WRITE(*,'(A)') "[ run mode chosen : post processing ]"
ELSE IF (run_mode == MCMC) THEN
IF(SHOW_READ) WRITE(*,'(A)') "[ run mode chosen : MCMC ]"
! hist_flag = 2
ELSE
IF(SHOW_READ) WRITE(*,'(A)') "[ run mode chosen : INVALID ]"
STOP "INVALID RUN MODE"
END IF
! Number of GRBs
CALL ReadReal(50, temp_real)
Nb_GRB = INT(temp_real)
IF(SHOW_READ) WRITE(*,'(A,1ES12.5,A)') "[ Number of GRBs simulated : ", REAL(Nb_GRB,8), " ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ ]"
! Luminosity Function
CALL ReadInteger(50, Model_Lum)
SELECT CASE(Model_Lum)
CASE(Model_LumFix) ! Fixed Luminosity
CALL ReadReal(50, TabParam_Lum(Param_Lum_L0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Fix ->", "L0 =", TabParam_Lum(Param_Lum_L0)," ]"
CASE(Model_LumPL) ! Power Law distribution
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "Lmin =",TabParam_Lum(Param_Lum_Lmin)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "Lmax =",TabParam_Lum(Param_Lum_Lmax)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "slope =",TabParam_Lum(Param_Lum_slope)," ]"
CASE(Model_LumBPL_evol) ! Broken Power Law distribution
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lmin =",TabParam_Lum(Param_Lum_Lmin)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lmax =",TabParam_Lum(Param_Lum_Lmax)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lbreak))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lbreak =",TabParam_Lum(Param_Lum_Lbreak)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_slopeL))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "slopeL =",TabParam_Lum(Param_Lum_slopeL)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_slopeH))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "slopeH =",TabParam_Lum(Param_Lum_slopeH)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "k_evol =",TabParam_Lum(Param_Lum_k_evol)," ]"
CASE(Model_LumPL_evol) ! Power Law distribution that evolves
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power Law ->", "Lmin =",TabParam_Lum(Param_Lum_Lmin)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power Law ->", "Lmax =",TabParam_Lum(Param_Lum_Lmax)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power Law ->", "slope =",TabParam_Lum(Param_Lum_slope)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power Law ->", "k_evol =",TabParam_Lum(Param_Lum_k_evol)," ]"
CASE(Model_LumSch) ! Schechter distribution
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "Lmin =",TabParam_Lum(Param_Lum_Lmin)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_Lbreak))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "Lbreak =",TabParam_Lum(Param_Lum_Lbreak)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "slope =",TabParam_Lum(Param_Lum_slope)," ]"
CALL ReadReal(50, TabParam_Lum(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "k_evol =",TabParam_Lum(Param_Lum_k_evol)," ]"
CASE DEFAULT
STOP "Error : Luminosity Function unknown (check .init file)"
END SELECT
! Redshift Distribution
CALL ReadInteger(50, Model_z)
SELECT CASE(Model_z)
CASE(Model_zFix) ! Fixed z
CALL ReadReal(50, TabParam_z(Param_z_z0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Fix ->", "z0 =", TabParam_z(Param_z_z0)," ]"
CASE(Model_zUniform) ! Uniform z up to zmax
CALL ReadReal(50, TabParam_z(Param_z_zmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Uniform ->", "zmax =", TabParam_z(Param_z_zmax)," ]"
CASE(Model_zSH) ! Springel-Hernquist distribution
CALL ReadReal(50, TabParam_z(Param_z_zmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "zmax =", TabParam_z(Param_z_zmax)," ]"
CALL ReadReal(50, TabParam_z(Param_z_zm))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "zm =", TabParam_z(Param_z_zm)," ]"
CALL ReadReal(50, TabParam_z(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "a =", TabParam_z(Param_z_a)," ]"
CALL ReadReal(50, TabParam_z(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "b =", TabParam_z(Param_z_b)," ]"
CASE(Model_zDaigne)
CALL ReadReal(50, TabParam_z(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Daigne 2006 ->", "a =", TabParam_z(Param_z_a)," ]"
CALL ReadReal(50, TabParam_z(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Daigne 2006 ->", "b =", TabParam_z(Param_z_b)," ]"
CALL ReadReal(50, TabParam_z(Param_z_c))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Daigne 2006 ->", "c =", TabParam_z(Param_z_c)," ]"
CALL ReadReal(50, TabParam_z(Param_z_d))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Daigne 2006 ->", "d =", TabParam_z(Param_z_d)," ]"
CASE(Model_z_evol) ! Springel-Hernquist distribution
CALL ReadReal(50, TabParam_z(Param_z_zmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "z evolution (SH) ->", "zmax =", TabParam_z(Param_z_zmax)," ]"
CALL ReadReal(50, TabParam_z(Param_z_zm))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "z evolution (SH) ->", "zm =", TabParam_z(Param_z_zm)," ]"
CALL ReadReal(50, TabParam_z(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "z evolution (SH) ->", "a =", TabParam_z(Param_z_a)," ]"
CALL ReadReal(50, TabParam_z(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "z evolution (SH) ->", "b =", TabParam_z(Param_z_b)," ]"
CALL ReadReal(50, TabParam_z(Param_z_zeta))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "z evolution (SH) ->", "zeta =", TabParam_z(Param_z_zeta)," ]"
CASE(Model_zLi)
CALL ReadReal(50, TabParam_z(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Li 2008 ->", "a =", TabParam_z(Param_z_a)," ]"
CALL ReadReal(50, TabParam_z(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Li 2008 ->", "b =", TabParam_z(Param_z_b)," ]"
CALL ReadReal(50, TabParam_z(Param_z_c))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Li 2008 ->", "c =", TabParam_z(Param_z_c)," ]"
CALL ReadReal(50, TabParam_z(Param_z_d))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Li 2008 ->", "d =", TabParam_z(Param_z_d)," ]"
CASE(Model_zPesc)
STOP "Pescalli redshift distribution not implemented yet"
CASE(Model_zBPL)
CALL ReadReal(50, TabParam_z(Param_z_zmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Power Law ->", "zmax =", TabParam_z(Param_z_zmax)," ]"
CALL ReadReal(50, TabParam_z(Param_z_zm))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Power Law ->", "zm =", TabParam_z(Param_z_zm)," ]"
CALL ReadReal(50, TabParam_z(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Power Law ->", "a =", TabParam_z(Param_z_a)," ]"
CALL ReadReal(50, TabParam_z(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Power Law ->", "b =", TabParam_z(Param_z_b)," ]"
CASE(Model_zBExp)
CALL ReadReal(50, TabParam_z(Param_z_zmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "zmax =", TabParam_z(Param_z_zmax)," ]"
CALL ReadReal(50, TabParam_z(Param_z_zm))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "zm =", TabParam_z(Param_z_zm)," ]"
CALL ReadReal(50, TabParam_z(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "a =", TabParam_z(Param_z_a)," ]"
CALL ReadReal(50, TabParam_z(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "b =", TabParam_z(Param_z_b)," ]"
CASE DEFAULT
STOP "Error : Redshift Distribution unknown (check .init file)"
END SELECT
! Spectral Model (SP)
CALL ReadInteger(50, Model_Spec)
SELECT CASE(Model_Spec)
CASE(Model_SpecBPLFix) ! Fixed Broken Power Law
CALL ReadReal(50, TabParam_Spec(Param_spec_alpha))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "BPL Fix ->", "alpha =", TabParam_Spec(Param_spec_alpha)," ]"
CALL ReadReal(50, TabParam_Spec(Param_spec_beta))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "BPL Fix ->", "beta =", TabParam_Spec(Param_spec_beta)," ]"
CASE (Model_SpecBPLK) ! Kaneko Broken Power Law
!IF(SHOW_READ) WRITE(*,Format_RIF) "Model_Spec :", "BPL Kaneko ->", "alpha =", TabParam_Spec(Param_spec_alpha)
STOP "Model_Spec : Kaneko BPL Function not coded yet"
CASE(Model_SpecBandFix) ! Fixed Band distribution
CALL ReadReal(50, TabParam_Spec(Param_spec_alpha))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "Band Fix ->", "alpha =", TabParam_Spec(Param_spec_alpha)," ]"
CALL ReadReal(50, TabParam_Spec(Param_spec_beta))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "Band Fix ->", "beta =", TabParam_Spec(Param_spec_beta)," ]"
CASE(Model_SpecBandK) ! Kaneko Band distribution
STOP "Model_Spec : Kaneko Band Function not coded yet"
CASE(Model_SpecBandD) ! Daigne Band distribution
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "Band Daigne ->", "alpha =", 1.," ]"
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "Band Daigne ->", "sigma_a =", 0.5," ]"
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "Band Daigne ->", "beta >=", 2.," ]"
CASE(Model_SpecBandGBM) ! Band distribution from GBM catalog
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "Band GBM ->", "alpha ~", .6," ]"
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Spec :", "Band GBM ->", "beta ~", 4.2," ]"
CASE DEFAULT
STOP "Error : Spectral Model unknown (check .init file)"
END SELECT
! Ep Model
CALL ReadInteger(50, Model_Ep)
SELECT CASE(Model_Ep)
CASE(Model_EpFix) ! Fixed Ep
CALL ReadReal(50, TabParam_Ep(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Fix ->", "Ep0 =", TabParam_Ep(Param_Ep_Ep0)," ]"
CASE(Model_EpLogNormal) ! Log Normal Ep distribution
CALL ReadReal(50, TabParam_Ep(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Log Normal ->", "Ep0 =", TabParam_Ep(Param_Ep_Ep0)," ]"
CALL ReadReal(50, TabParam_Ep(Param_Ep_sigmaLog))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Log Normal ->", "sigmaLog =", TabParam_Ep(Param_Ep_sigmaLog)," ]"
CASE(Model_EpY) ! Yonetoku
STOP "Model_Ep : Yonetoku not coded yet"
CASE(Model_EpAmati)
CALL ReadReal(50, TabParam_Ep(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", "Ep0 =", TabParam_Ep(Param_Ep_Ep0)," ]"
CALL ReadReal(50, TabParam_Ep(Param_Ep_sigmaLog))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", "sigmaLog =", TabParam_Ep(Param_Ep_sigmaLog)," ]"
CALL ReadReal(50, TabParam_Ep(Param_Ep_L0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", "L0 =", TabParam_Ep(Param_Ep_L0)," ]"
CALL ReadReal(50, TabParam_Ep(Param_Ep_alpha_amati))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", "alpha_amati =", TabParam_Ep(Param_Ep_alpha_amati)," ]"
CASE DEFAULT
STOP "Error : Ep Model unknown (check .init file)"
END SELECT
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
! Include Sample
IF(SHOW_READ) WRITE(*,'(A)') "[ ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ Samples ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
Sample_Included(0) = .TRUE. ! Always include intrinsic sample
DO i_Sample = 1, N_Samples
CALL ReadInteger(50, incl)
IF(incl == 1) THEN
Sample_Included(i_Sample) = .TRUE.
IF(SHOW_READ) WRITE(*,'(A,A20,A)') '[ Including sample : ', TabSample_name(i_Sample)," ]"
SELECT CASE(i_Sample)
CASE(Sample_Kommers)
Instrument_Included(Instrument_BATSE) = .TRUE.
CASE(Sample_Preece)
Instrument_Included(Instrument_BATSE) = .TRUE.
CASE(Sample_Stern)
Instrument_Included(Instrument_BATSE) = .TRUE.
CASE(Sample_SWIFTweak)
Instrument_Included(Instrument_BAT ) = .TRUE.
CASE(Sample_SWIFT)
Instrument_Included(Instrument_BAT ) = .TRUE.
CASE(Sample_SWIFTbright)
Instrument_Included(Instrument_BAT ) = .TRUE.
CASE(Sample_HETE2)
Instrument_Included(Instrument_FREGATE) = .TRUE.
Instrument_Included(Instrument_WXM) = .TRUE.
CASE(Sample_eBAT6)
Instrument_Included(Instrument_BAT ) = .TRUE.
CASE(Sample_EpGBM)
Instrument_Included(Instrument_BATSE) = .TRUE.
CASE(Sample_SVOM)
Instrument_Included(Instrument_ECLAIRs) = .TRUE.
END SELECT
END IF
END DO
! Include Constraint
DO i_Constraint=1, N_Constraints
CALL ReadInteger(50, incl)
IF(incl == 1) THEN
Constraint_Included(i_Constraint) = .TRUE.
IF(SHOW_READ) WRITE(*,'(A,A20,A)') '[ Including constraint : ', TabConstraint_name(i_Constraint)," ]"
SELECT CASE(i_Constraint)
CASE(Constraint_Kommers)
Sample_Included(Sample_Kommers) = .TRUE.
Instrument_Included(Instrument_BATSE) = .TRUE.
CASE(Constraint_Preece)
Sample_Included(Sample_Preece) = .TRUE.
Instrument_Included(Instrument_BATSE) = .TRUE.
CASE(Constraint_Stern)
Sample_Included(Sample_Stern) = .TRUE.
Instrument_Included(Instrument_BATSE) = .TRUE.
CASE(Constraint_HETE2)
Sample_Included(Sample_HETE2) = .TRUE.
Instrument_Included(Instrument_FREGATE) = .TRUE.
Instrument_Included(Instrument_WXM) = .TRUE.
CASE(Constraint_EpGBM)
Sample_Included(Sample_EpGBM) = .TRUE.
Instrument_Included(Instrument_BATSE) = .TRUE.
CASE(Constraint_eBAT6)
Sample_Included(Sample_eBAT6) = .TRUE.
Instrument_Included(Instrument_BAT) = .TRUE.
END SELECT
END IF
END DO
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
! Save histograms
CALL ReadInteger(50, s_L)
IF(s_L == 1) THEN
Lsave = .TRUE.
IF(SHOW_READ) WRITE(*,'(A,A)') '[ Saving Luminosity as :',' luminosity_[sample].dat ]'
END IF
CALL ReadInteger(50, s_z)
IF(s_z == 1) THEN
zsave = .TRUE.
IF(SHOW_READ) WRITE(*,'(A,A)') '[ Saving Redshift as :',' redshift_[sample].dat ]'
END IF
CALL ReadInteger(50, s_Spec)
IF(s_Spec == 1) THEN
Specsave = .TRUE.
IF(SHOW_READ) WRITE(*,'(A,A)') '[ Saving Model Spec as :',' modelspec_[sample].dat ]'
END IF
CALL ReadInteger(50, s_Ep)
IF(s_Ep == 1) THEN
Epsave = .TRUE.
IF(SHOW_READ) WRITE(*,'(A,A)') '[ Saving Peak Energy as :',' peakenergy_[sample].dat ]'
END IF
CALL ReadInteger(50, s_P)
IF(s_P == 1) THEN
Psave = .TRUE.
IF(SHOW_READ) WRITE(*,'(A,A)') '[ Saving Peak Flux as :',' peakflux_[sample].dat ]'
END IF
! Save constraints
DO i = 1, N_Constraints
CALL ReadInteger(50, s_Constraint)
IF(s_Constraint == 1) THEN
Constraint_save(i) = .TRUE.
IF(SHOW_READ) WRITE(*,'(A,A34,A31)') '[','Saving '// TRIM(TabConstraint_name(i)) // &
' constraint as :',' ' // TRIM(TabConstraint_name(i)) // '_constraint[err].dat ]'
END IF
END DO
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') " ====================== ReadInitFile done ======================== "
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') " "
CLOSE(50)
END SUBROUTINE ReadInitFile
SUBROUTINE ReadParamSearchFile()
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') " ==================== Parameter Search File ====================== "
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
! Luminosity
OPEN(UNIT=51, FILE=TRIM(param_search_path)//'lum_param_search.init')
CALL ReadInteger(51, lum_explore)
IF(lum_explore == 1) THEN
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') "[ Luminosity ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
SELECT CASE(Model_Lum)
CASE(Model_LumFix) ! Fixed Luminosity
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_L0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Fix ->", "L0_min =", TabParam_Lum_min(Param_Lum_L0)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_L0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Fix ->", "L0_max =", TabParam_Lum_max(Param_Lum_L0)," ]"
CASE(Model_LumPL) ! Power Law distribution
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "Lmin_min =",TabParam_Lum_min(Param_Lum_Lmin)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "Lmin_max =",TabParam_Lum_max(Param_Lum_Lmin)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "Lmax_min =",TabParam_Lum_min(Param_Lum_Lmax)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "Lmax_max =",TabParam_Lum_max(Param_Lum_Lmax)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "slope_min =",TabParam_Lum_min(Param_Lum_slope)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Power Law ->", "slope_max =",TabParam_Lum_max(Param_Lum_slope)," ]"
CASE(Model_LumBPL_evol) ! Evolving BPL distribution
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lmin_min =",TabParam_Lum_min(Param_Lum_Lmin)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lmin_max =",TabParam_Lum_max(Param_Lum_Lmin)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lmax_min =",TabParam_Lum_min(Param_Lum_Lmax)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lmax_max =",TabParam_Lum_max(Param_Lum_Lmax)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lbreak))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lbreak_min =",TabParam_Lum_min(Param_Lum_Lbreak)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lbreak))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "Lbreak_max =",TabParam_Lum_max(Param_Lum_Lbreak)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_slopeL))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "slopeL_min =",TabParam_Lum_min(Param_Lum_slopeL)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_slopeL))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "slopeL_max =",TabParam_Lum_max(Param_Lum_slopeL)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_slopeH))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "slopeH_min =",TabParam_Lum_min(Param_Lum_slopeH)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_slopeH))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "slopeH_max =",TabParam_Lum_max(Param_Lum_slopeH)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "k_evol_min =",TabParam_Lum_min(Param_Lum_k_evol)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving BPL ->", "k_evol_max =",TabParam_Lum_max(Param_Lum_k_evol)," ]"
CASE(Model_LumPL_evol) ! Evolving power Law distribution
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power law ->", "Lmin_min =",TabParam_Lum_min(Param_Lum_Lmin)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power law ->", "Lmin_max =",TabParam_Lum_max(Param_Lum_Lmin)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power law ->", "Lmax_min =",TabParam_Lum_min(Param_Lum_Lmax)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power law ->", "Lmax_max =",TabParam_Lum_max(Param_Lum_Lmax)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power law ->", "slope_min =",TabParam_Lum_min(Param_Lum_slope)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power Law ->", "slope_max =",TabParam_Lum_max(Param_Lum_slope)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power law ->", "k_evol_min =",TabParam_Lum_min(Param_Lum_k_evol)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Evolving power Law ->", "k_evol_max =",TabParam_Lum_max(Param_Lum_k_evol)," ]"
CASE(Model_LumSch) ! Schechter function
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "Lmin_min =",TabParam_Lum_min(Param_Lum_Lmin)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lmin))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "Lmin_max =",TabParam_Lum_max(Param_Lum_Lmin)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_Lbreak))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "Lbreak_min =",TabParam_Lum_min(Param_Lum_Lbreak)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_Lbreak))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "Lbreak_max =",TabParam_Lum_max(Param_Lum_Lbreak)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "slope_min =",TabParam_Lum_min(Param_Lum_slope)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_slope))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "slope_max =",TabParam_Lum_max(Param_Lum_slope)," ]"
CALL ReadReal(51, TabParam_Lum_min(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "k_evol_min =",TabParam_Lum_min(Param_Lum_k_evol)," ]"
CALL ReadReal(51, TabParam_Lum_max(Param_Lum_k_evol))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Lum :", "Schechter ->", "k_evol_max =",TabParam_Lum_max(Param_Lum_k_evol)," ]"
END SELECT
END IF
CLOSE(51)
! Redshift
OPEN(UNIT=52, FILE=TRIM(param_search_path)//'redshift_param_search.init')
CALL ReadInteger(52, z_explore)
IF(z_explore == 1) THEN
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') "[ Redshift ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
SELECT CASE(Model_z)
CASE(Model_zFix) ! Fixed redshift
CALL ReadReal(52, TabParam_z_min(Param_z_z0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Fix ->", "z0_min =", TabParam_z_min(Param_z_z0)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_z0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Fix ->", "z0_max =", TabParam_z_max(Param_z_z0)," ]"
CASE(Model_zSH)
CALL ReadReal(52, TabParam_z_min(Param_z_zmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "zmax_min =", TabParam_z_min(Param_z_zmax)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_zmax))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "zmax_max =", TabParam_z_max(Param_z_zmax)," ]"
CALL ReadReal(52, TabParam_z_min(Param_z_zm))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "zm_min =", TabParam_z_min(Param_z_zm)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_zm))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "zm_max =", TabParam_z_max(Param_z_zm)," ]"
CALL ReadReal(52, TabParam_z_min(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "a_min =", TabParam_z_min(Param_z_a)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "a_max =", TabParam_z_max(Param_z_a)," ]"
CALL ReadReal(52, TabParam_z_min(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "b_min =", TabParam_z_min(Param_z_b)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Springel-Hernquist ->", "b_max =", TabParam_z_max(Param_z_b)," ]"
CASE(Model_z_evol)
CALL ReadReal(52, TabParam_z_min(Param_z_zeta))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "z evolution (SH) ->", "zeta_min =", TabParam_z_min(Param_z_zeta)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_zeta))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "z evolution (SH) ->", "zeta_max =", TabParam_z_max(Param_z_zeta)," ]"
CASE(Model_zBExp)
CALL ReadReal(52, TabParam_z_min(Param_z_zm))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "zm_min =", TabParam_z_min(Param_z_zm)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_zm))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "zm_max =", TabParam_z_max(Param_z_zm)," ]"
CALL ReadReal(52, TabParam_z_min(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "a_min =", TabParam_z_min(Param_z_a)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_a))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "a_max =", TabParam_z_max(Param_z_a)," ]"
CALL ReadReal(52, TabParam_z_min(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "b_min =", TabParam_z_min(Param_z_b)," ]"
CALL ReadReal(52, TabParam_z_max(Param_z_b))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_z :", "Broken Exponential ->", "b_max =", TabParam_z_max(Param_z_b)," ]"
CASE DEFAULT
IF(SHOW_READ) WRITE(*,'(A)') "[ No parameter search for this redshift model ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
END SELECT
END IF
CLOSE(52)
! Peak energy
OPEN(UNIT=53, FILE=TRIM(param_search_path)//'Ep_param_search.init')
CALL ReadInteger(53, Ep_explore)
IF(Ep_explore == 1) THEN
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') "[ Peak Energy ]"
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
SELECT CASE(Model_Ep)
CASE(Model_EpFix) ! Fixed Ep
CALL ReadReal(53, TabParam_Ep_min(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Fix ->", "Ep0_min =", TabParam_Ep_min(Param_Ep_Ep0)," ]"
CALL ReadReal(53, TabParam_Ep_max(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Fix ->", "Ep0_max =", TabParam_Ep_max(Param_Ep_Ep0)," ]"
CASE(Model_EpLogNormal) ! Lognormal Ep
CALL ReadReal(53, TabParam_Ep_min(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "LogNormal ->", "Ep0_min =", TabParam_Ep_min(Param_Ep_Ep0)," ]"
CALL ReadReal(53, TabParam_Ep_max(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "LogNormal ->", "Ep0_max =", TabParam_Ep_max(Param_Ep_Ep0)," ]"
CALL ReadReal(53, TabParam_Ep_min(Param_Ep_sigmaLog))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "LogNormal ->", "sigmaLog_min =", TabParam_Ep_min(Param_Ep_sigmaLog)," ]"
CALL ReadReal(53, TabParam_Ep_max(Param_Ep_sigmaLog))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "LogNormal ->", "sigmaLog_max =", TabParam_Ep_max(Param_Ep_sigmaLog)," ]"
CASE(Model_EpAmati)
CALL ReadReal(53, TabParam_Ep_min(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", "Ep0_min =", TabParam_Ep_min(Param_Ep_Ep0)," ]"
CALL ReadReal(53, TabParam_Ep_max(Param_Ep_Ep0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", "Ep0_max =", TabParam_Ep_max(Param_Ep_Ep0)," ]"
CALL ReadReal(53, TabParam_Ep_min(Param_Ep_sigmaLog))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", "sigmaLog_min =", TabParam_Ep_min(Param_Ep_sigmaLog)," ]"
CALL ReadReal(53, TabParam_Ep_max(Param_Ep_sigmaLog))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", "sigmaLog_max =", TabParam_Ep_max(Param_Ep_sigmaLog)," ]"
CALL ReadReal(53, TabParam_Ep_min(Param_Ep_L0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", " L0_min =", TabParam_Ep_min(Param_Ep_L0)," ]"
CALL ReadReal(53, TabParam_Ep_max(Param_Ep_L0))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", " L0_max =", TabParam_Ep_max(Param_Ep_L0)," ]"
CALL ReadReal(53, TabParam_Ep_min(Param_Ep_alpha_amati))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", " alpha_min =", TabParam_Ep_min(Param_Ep_alpha_amati)," ]"
CALL ReadReal(53, TabParam_Ep_max(Param_Ep_alpha_amati))
IF(SHOW_READ) WRITE(*,Format_RIF) "[ ","Model_Ep :", "Amati-like ->", " alpha_max =", TabParam_Ep_max(Param_Ep_alpha_amati)," ]"
CASE DEFAULT
STOP "Error : Ep Model unknown (check .init file)"
END SELECT
END IF
CLOSE(53)
CALL Calculate_dof()
IF(SHOW_READ) WRITE(*,'(A)') "[ -------------------------------------------------------------- ]"
IF(SHOW_READ) WRITE(*,'(A,I2,A)') "[ (data to fit - degrees of freedom) : ",dof," ]"
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') " ================== Parameter Search File done =================== "
IF(SHOW_READ) WRITE(*,'(A)') " "
IF(SHOW_READ) WRITE(*,'(A)') " "
END SUBROUTINE ReadParamSearchFile
SUBROUTINE Calculate_dof()
dof = 0
IF(lum_explore == 1) THEN
SELECT CASE(Model_Lum)
CASE(Model_LumFix)
dof = dof - 1
CASE(Model_LumPL)
IF(TabParam_Lum_min(Param_Lum_Lmin) /= TabParam_Lum_max(Param_Lum_Lmin)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_Lmax) /= TabParam_Lum_max(Param_Lum_Lmax)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_slope) /= TabParam_Lum_max(Param_Lum_slope)) dof = dof - 1
CASE(Model_LumBPL_evol)
IF(TabParam_Lum_min(Param_Lum_Lmin) /= TabParam_Lum_max(Param_Lum_Lmin)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_Lmax) /= TabParam_Lum_max(Param_Lum_Lmax)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_Lbreak) /= TabParam_Lum_max(Param_Lum_Lbreak)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_slopeL) /= TabParam_Lum_max(Param_Lum_slopeL)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_slopeH) /= TabParam_Lum_max(Param_Lum_slopeH)) dof = dof - 1
CASE(Model_LumPL_evol)
IF(TabParam_Lum_min(Param_Lum_Lmin) /= TabParam_Lum_max(Param_Lum_Lmin)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_Lmax) /= TabParam_Lum_max(Param_Lum_Lmax)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_slope) /= TabParam_Lum_max(Param_Lum_slope)) dof = dof - 1
IF(TabParam_Lum_min(Param_Lum_k_evol) /= TabParam_Lum_max(Param_Lum_k_evol)) dof = dof - 1
END SELECT
END IF
IF(z_explore == 1) THEN
SELECT CASE(Model_z)
CASE(Model_zFix)
dof = dof - 1
CASE(Model_zSH)
IF(TabParam_z_min(Param_z_zmax) /= TabParam_z_max(Param_z_zmax)) dof = dof - 1
IF(TabParam_z_min(Param_z_zm) /= TabParam_z_max(Param_z_zm)) dof = dof - 1
IF(TabParam_z_min(Param_z_a) /= TabParam_z_max(Param_z_a)) dof = dof - 1
IF(TabParam_z_min(Param_z_b) /= TabParam_z_max(Param_z_b)) dof = dof - 1
END SELECT
END IF
IF(Ep_explore == 1) THEN
SELECT CASE(Model_Ep)
CASE(Model_EpFix)
dof = dof - 1
CASE(Model_EpLogNormal)
IF(TabParam_Ep_min(Param_Ep_Ep0) /= TabParam_Ep_max(Param_Ep_Ep0)) dof = dof - 1
IF(TabParam_Ep_min(Param_Ep_sigmaLog) /= TabParam_Ep_max(Param_Ep_sigmaLog)) dof = dof - 1
CASE(Model_EpAmati)
IF(TabParam_Ep_min(Param_Ep_Ep0) /= TabParam_Ep_max(Param_Ep_Ep0)) dof = dof - 1
IF(TabParam_Ep_min(Param_Ep_sigmaLog) /= TabParam_Ep_max(Param_Ep_sigmaLog)) dof = dof - 1
IF(TabParam_Ep_min(Param_Ep_L0) /= TabParam_Ep_max(Param_Ep_L0)) dof = dof - 1
IF(TabParam_Ep_min(Param_Ep_alpha_amati) /= TabParam_Ep_max(Param_Ep_alpha_amati)) dof = dof - 1
END SELECT
END IF
DO i_Constraint = 1, N_Constraints
IF(Constraint_included(i_Constraint)) THEN
IF(i_Constraint == Constraint_Kommers) dof = dof + N_Komm - 1 ! -1 for the normalization
IF(i_Constraint == Constraint_Preece ) dof = dof + N_Preece - 1
IF(i_Constraint == Constraint_Stern ) dof = dof + N_Stern - 1
IF(i_Constraint == Constraint_HETE2) dof = dof + 1
IF(i_Constraint == Constraint_EpGBM) dof = dof + N_EpGBM - 1
!IF(i_Constraint == Constraint_eBAT6) dof = dof + N_eBAT6 - 1
END IF
END DO
END SUBROUTINE Calculate_dof
SUBROUTINE Set_Fixed_Parameters()
INTEGER :: imin, imax, j
! --- Redshift --- !
IF(Model_z == Model_zFix) THEN
z = TabParam_z(Param_z_z0)
imin = 1
imax = INT(SIZE(Tabprecisez)-1)
IF(z <= 0.d0) WRITE(*,*) "WARNING in MonteCarlo : z <= 0 not allowed, results will be absurd"
DO
j = (imin+imax)/2
IF (z >= Tabprecisez(j)) THEN
imin = j+1
ELSE IF (z < Tabprecisez(j-1)) THEN
imax = j
ELSE
EXIT
END IF
END DO
D_L = TabD_L(j-1) + (TabD_L(j)-TabD_L(j-1)) * (z-Tabprecisez(j-1)) / (Tabprecisez(j)-Tabprecisez(j-1))
END IF
! -- Luminosity [erg/s] -- !
IF(Model_Lum == Model_LumFix) L = TabParam_Lum(Param_Lum_L0)
IF(Model_Lum == Model_LumBPL_evol) t_star = Calc_t_star(TabParam_Lum)
! --- Spectral Model --- !
IF(Model_Spec == Model_SpecBPLFix .OR. Model_Spec == Model_SpecBandFix) THEN
alpha = TabParam_Spec(Param_spec_alpha)
beta = TabParam_Spec(Param_spec_beta)
ktild = Calc_ktild(alpha, beta, Model_Spec)
END IF
IF(verbose == 2) PRINT*, "ktild =", ktild
! --- Peak Energy [keV] --- !
IF(Model_Ep == Model_EpFix) Ep = TabParam_Ep(Param_Ep_Ep0)
END SUBROUTINE Set_Fixed_Parameters
SUBROUTINE Draw_model_parameters()
IF(Lum_Explore == 1) THEN
SELECT CASE(Model_lum)
CASE(Model_LumPL)
IF(TabParam_Lum_max(Param_Lum_Lmin) /= TabParam_Lum_min(Param_Lum_Lmin)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lmin) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lmin))-LOG10(TabParam_Lum_min(Param_Lum_Lmin))) + LOG10(TabParam_Lum_min(Param_Lum_Lmin)))
ELSE
TabParam_Lum(Param_Lum_Lmin) = TabParam_Lum_min(Param_Lum_Lmin)
END IF
IF(TabParam_Lum_max(Param_Lum_Lmax) /= TabParam_Lum_min(Param_Lum_Lmax)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lmax) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lmax))-LOG10(TabParam_Lum_min(Param_Lum_Lmax))) + LOG10(TabParam_Lum_min(Param_Lum_Lmax)))
ELSE
TabParam_Lum(Param_Lum_Lmax) = TabParam_Lum_min(Param_Lum_Lmax)
END IF
IF(TabParam_Lum_max(Param_Lum_slope) /= TabParam_Lum_min(Param_Lum_slope)) THEN
t = uniform()
TabParam_Lum(Param_Lum_slope) = t*(TabParam_Lum_max(Param_Lum_slope)-TabParam_Lum_min(Param_Lum_slope)) + TabParam_Lum_min(Param_Lum_slope)
ELSE
TabParam_Lum(Param_Lum_slope) = TabParam_Lum_min(Param_Lum_slope)
END IF
CASE(Model_LumBPL_evol)
IF(TabParam_Lum_max(Param_Lum_Lmin) /= TabParam_Lum_min(Param_Lum_Lmin)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lmin) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lmin))-LOG10(TabParam_Lum_min(Param_Lum_Lmin))) + LOG10(TabParam_Lum_min(Param_Lum_Lmin)))
ELSE
TabParam_Lum(Param_Lum_Lmin) = TabParam_Lum_min(Param_Lum_Lmin)
END IF
IF(TabParam_Lum_max(Param_Lum_Lmax) /= TabParam_Lum_min(Param_Lum_Lmax)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lmax) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lmax))-LOG10(TabParam_Lum_min(Param_Lum_Lmax))) + LOG10(TabParam_Lum_min(Param_Lum_Lmax)))
ELSE
TabParam_Lum(Param_Lum_Lmax) = TabParam_Lum_min(Param_Lum_Lmax)
END IF
IF(TabParam_Lum_max(Param_Lum_Lbreak) /= TabParam_Lum_min(Param_Lum_Lbreak)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lbreak) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lbreak))-LOG10(TabParam_Lum_min(Param_Lum_Lbreak))) + LOG10(TabParam_Lum_min(Param_Lum_Lbreak)))
ELSE
TabParam_Lum(Param_Lum_Lbreak) = TabParam_Lum_min(Param_Lum_Lbreak)
END IF
IF(TabParam_Lum_max(Param_Lum_slopeL) /= TabParam_Lum_min(Param_Lum_slopeL)) THEN
t = uniform()
TabParam_Lum(Param_Lum_slopeL) = t*(TabParam_Lum_max(Param_Lum_slopeL)-TabParam_Lum_min(Param_Lum_slopeL)) + TabParam_Lum_min(Param_Lum_slopeL)
ELSE
TabParam_Lum(Param_Lum_slopeL) = TabParam_Lum_min(Param_Lum_slopeL)
END IF
IF(TabParam_Lum_max(Param_Lum_slopeH) /= TabParam_Lum_min(Param_Lum_slopeH)) THEN
t = uniform()
TabParam_Lum(Param_Lum_slopeH) = t*(TabParam_Lum_max(Param_Lum_slopeH)-TabParam_Lum_min(Param_Lum_slopeH)) + TabParam_Lum_min(Param_Lum_slopeH)
ELSE
TabParam_Lum(Param_Lum_slopeH) = TabParam_Lum_min(Param_Lum_slopeH)
END IF
CASE(Model_LumPL_evol)
IF(TabParam_Lum_max(Param_Lum_Lmin) /= TabParam_Lum_min(Param_Lum_Lmin)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lmin) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lmin))-LOG10(TabParam_Lum_min(Param_Lum_Lmin))) + LOG10(TabParam_Lum_min(Param_Lum_Lmin)))
ELSE
TabParam_Lum(Param_Lum_Lmin) = TabParam_Lum_min(Param_Lum_Lmin)
END IF
IF(TabParam_Lum_max(Param_Lum_Lmax) /= TabParam_Lum_min(Param_Lum_Lmax)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lmax) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lmax))-LOG10(TabParam_Lum_min(Param_Lum_Lmax))) + LOG10(TabParam_Lum_min(Param_Lum_Lmax)))
ELSE
TabParam_Lum(Param_Lum_Lmax) = TabParam_Lum_min(Param_Lum_Lmax)
END IF
IF(TabParam_Lum_max(Param_Lum_slope) /= TabParam_Lum_min(Param_Lum_slope)) THEN
t = uniform()
TabParam_Lum(Param_Lum_slope) = t*(TabParam_Lum_max(Param_Lum_slope)-TabParam_Lum_min(Param_Lum_slope)) + TabParam_Lum_min(Param_Lum_slope)
ELSE
TabParam_Lum(Param_Lum_slope) = TabParam_Lum_min(Param_Lum_slope)
END IF
IF(TabParam_Lum_max(Param_Lum_k_evol) /= TabParam_Lum_min(Param_Lum_k_evol)) THEN
t = uniform()
TabParam_Lum(Param_Lum_k_evol) = t*(TabParam_Lum_max(Param_Lum_k_evol)-TabParam_Lum_min(Param_Lum_k_evol)) + TabParam_Lum_min(Param_Lum_k_evol)
ELSE
TabParam_Lum(Param_Lum_k_evol) = TabParam_Lum_min(Param_Lum_k_evol)
END IF
CASE(Model_LumSch)
IF(TabParam_Lum_max(Param_Lum_Lmin) /= TabParam_Lum_min(Param_Lum_Lmin)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lmin) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lmin))-LOG10(TabParam_Lum_min(Param_Lum_Lmin))) + LOG10(TabParam_Lum_min(Param_Lum_Lmin)))
ELSE
TabParam_Lum(Param_Lum_Lmin) = TabParam_Lum_min(Param_Lum_Lmin)
END IF
IF(TabParam_Lum_max(Param_Lum_Lbreak) /= TabParam_Lum_min(Param_Lum_Lbreak)) THEN
t = uniform()
TabParam_Lum(Param_Lum_Lbreak) = 10.d0**(t*(LOG10(TabParam_Lum_max(Param_Lum_Lbreak))-LOG10(TabParam_Lum_min(Param_Lum_Lbreak))) + LOG10(TabParam_Lum_min(Param_Lum_Lbreak)))
ELSE
TabParam_Lum(Param_Lum_Lbreak) = TabParam_Lum_min(Param_Lum_Lbreak)
END IF
IF(TabParam_Lum_max(Param_Lum_slope) /= TabParam_Lum_min(Param_Lum_slope)) THEN
t = uniform()
TabParam_Lum(Param_Lum_slope) = t*(TabParam_Lum_max(Param_Lum_slope)-TabParam_Lum_min(Param_Lum_slope)) + TabParam_Lum_min(Param_Lum_slope)
ELSE
TabParam_Lum(Param_Lum_slope) = TabParam_Lum_min(Param_Lum_slope)
END IF
IF(TabParam_Lum_max(Param_Lum_k_evol) /= TabParam_Lum_min(Param_Lum_k_evol)) THEN
t = uniform()
TabParam_Lum(Param_Lum_k_evol) = t*(TabParam_Lum_max(Param_Lum_k_evol)-TabParam_Lum_min(Param_Lum_k_evol)) + TabParam_Lum_min(Param_Lum_k_evol)
ELSE
TabParam_Lum(Param_Lum_k_evol) = TabParam_Lum_min(Param_Lum_k_evol)
END IF
END SELECT
END IF
IF(Ep_explore == 1) THEN
SELECT CASE(Model_Ep)
CASE(Model_EpFix)
IF(TabParam_Ep_max(Param_Ep_Ep0) /= TabParam_Ep_min(Param_Ep_Ep0)) THEN
t = uniform()
TabParam_Ep(Param_Ep_Ep0) = 10.d0**(t*(LOG10(TabParam_Ep_max(Param_Ep_Ep0))-LOG10(TabParam_Ep_min(Param_Ep_Ep0))) + LOG10(TabParam_Ep_min(Param_Ep_Ep0)))
ELSE
TabParam_Ep(Param_Ep_Ep0) = TabParam_Ep_min(Param_Ep_Ep0)
END IF
CASE(Model_EpLogNormal)
IF(TabParam_Ep_max(Param_Ep_Ep0) /= TabParam_Ep_min(Param_Ep_Ep0)) THEN
t = uniform()
TabParam_Ep(Param_Ep_Ep0) = 10.d0**(t*(LOG10(TabParam_Ep_max(Param_Ep_Ep0))-LOG10(TabParam_Ep_min(Param_Ep_Ep0))) + LOG10(TabParam_Ep_min(Param_Ep_Ep0)))
ELSE
TabParam_Ep(Param_Ep_Ep0) = TabParam_Ep_min(Param_Ep_Ep0)
END IF
IF(TabParam_Ep_max(Param_Ep_sigmaLog) /= TabParam_Ep_min(Param_Ep_sigmaLog)) THEN
t = uniform()
TabParam_Ep(Param_Ep_sigmaLog) = t*(TabParam_Ep_max(Param_Ep_sigmaLog)-TabParam_Ep_min(Param_Ep_sigmaLog)) + TabParam_Ep_min(Param_Ep_sigmaLog)
ELSE
TabParam_Ep(Param_Ep_sigmaLog) = TabParam_Ep_min(Param_Ep_sigmaLog)
END IF
CASE(Model_EpAmati)
IF(TabParam_Ep_max(Param_Ep_Ep0) /= TabParam_Ep_min(Param_Ep_Ep0)) THEN
t = uniform()
TabParam_Ep(Param_Ep_Ep0) = 10.d0**(t*(LOG10(TabParam_Ep_max(Param_Ep_Ep0))-LOG10(TabParam_Ep_min(Param_Ep_Ep0))) + LOG10(TabParam_Ep_min(Param_Ep_Ep0)))
ELSE
TabParam_Ep(Param_Ep_Ep0) = TabParam_Ep_min(Param_Ep_Ep0)
END IF
IF(TabParam_Ep_max(Param_Ep_sigmaLog) /= TabParam_Ep_min(Param_Ep_sigmaLog)) THEN
t = uniform()
TabParam_Ep(Param_Ep_sigmaLog) = t*(TabParam_Ep_max(Param_Ep_sigmaLog)-TabParam_Ep_min(Param_Ep_sigmaLog)) + TabParam_Ep_min(Param_Ep_sigmaLog)
ELSE
TabParam_Ep(Param_Ep_sigmaLog) = TabParam_Ep_min(Param_Ep_sigmaLog)
END IF
IF(TabParam_Ep_max(Param_Ep_L0) /= TabParam_Ep_min(Param_Ep_L0)) THEN
t = uniform()
TabParam_Ep(Param_Ep_L0) = 10.d0**(t*(LOG10(TabParam_Ep_max(Param_Ep_L0))-LOG10(TabParam_Ep_min(Param_Ep_L0))) + LOG10(TabParam_Ep_min(Param_Ep_L0)))
ELSE
TabParam_Ep(Param_Ep_L0) = TabParam_Ep_min(Param_Ep_L0)
END IF
IF(TabParam_Ep_max(Param_Ep_alpha_amati) /= TabParam_Ep_min(Param_Ep_alpha_amati)) THEN
t = uniform()
TabParam_Ep(Param_Ep_alpha_amati) = t*(TabParam_Ep_max(Param_Ep_alpha_amati)-TabParam_Ep_min(Param_Ep_alpha_amati)) + TabParam_Ep_min(Param_Ep_alpha_amati)
ELSE
TabParam_Ep(Param_Ep_alpha_amati) = TabParam_Ep_min(Param_Ep_alpha_amati)
END IF
END SELECT
END IF
IF(z_explore == 1) THEN
SELECT CASE(Model_z)
CASE(Model_z_evol)
IF(TabParam_z_max(Param_z_zeta) /= TabParam_z_min(Param_z_zeta)) THEN
t = uniform()
TabParam_z(Param_z_zeta) = t*(TabParam_z_max(Param_z_zeta)-TabParam_z_min(Param_z_zeta)) + TabParam_z_min(Param_z_zeta)
ELSE
TabParam_z(Param_z_zeta) = TabParam_z_min(Param_z_zeta)
END IF
CASE DEFAULT
STOP "Error : no exploration implemented with this redshift distribution (check .init file)"
END SELECT
END IF
END SUBROUTINE Draw_model_parameters
SUBROUTINE Draw_Markov_Jump()
REAL(8) :: temp = 0.d0
INTEGER(4) :: safeguard = 0
IF(Lum_Explore == 1) THEN
SELECT CASE(Model_lum)
CASE(Model_LumPL)
IF(TabParam_Lum_max(Param_Lum_Lmin) /= TabParam_Lum_min(Param_Lum_Lmin)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lmin)), Step_Lum(Param_Lum_Lmin)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lmin in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lmin)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lmin))) THEN
TabParam_Lum(Param_Lum_Lmin) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lmin) = TabParam_Lum_min(Param_Lum_Lmin)
END IF
IF(TabParam_Lum_max(Param_Lum_Lmax) /= TabParam_Lum_min(Param_Lum_Lmax)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lmax)), Step_Lum(Param_Lum_Lmax)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lmax in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lmax)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lmax))) THEN
TabParam_Lum(Param_Lum_Lmax) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lmax) = TabParam_Lum_min(Param_Lum_Lmax)
END IF
IF(TabParam_Lum_max(Param_Lum_slope) /= TabParam_Lum_min(Param_Lum_slope)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Lum(Param_Lum_slope), Step_Lum(Param_Lum_slope))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for slope in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_slope)) .AND. (temp <= TabParam_Lum_max(Param_Lum_slope))) THEN
TabParam_Lum(Param_Lum_slope) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_slope) = TabParam_Lum_min(Param_Lum_slope)
END IF
CASE(Model_LumBPL_evol)
IF(TabParam_Lum_max(Param_Lum_Lmin) /= TabParam_Lum_min(Param_Lum_Lmin)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lmin)), Step_Lum(Param_Lum_Lmin)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lmin in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lmin)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lmin))) THEN
TabParam_Lum(Param_Lum_Lmin) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lmin) = TabParam_Lum_min(Param_Lum_Lmin)
END IF
IF(TabParam_Lum_max(Param_Lum_Lmax) /= TabParam_Lum_min(Param_Lum_Lmax)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lmax)), Step_Lum(Param_Lum_Lmax)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lmax in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lmax)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lmax))) THEN
TabParam_Lum(Param_Lum_Lmax) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lmax) = TabParam_Lum_min(Param_Lum_Lmax)
END IF
IF(TabParam_Lum_max(Param_Lum_Lbreak) /= TabParam_Lum_min(Param_Lum_Lbreak)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lbreak)), Step_Lum(Param_Lum_Lbreak)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lbreak in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lbreak)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lbreak))) THEN
TabParam_Lum(Param_Lum_Lbreak) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lbreak) = TabParam_Lum_min(Param_Lum_Lbreak)
END IF
IF(TabParam_Lum_max(Param_Lum_slopeL) /= TabParam_Lum_min(Param_Lum_slopeL)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Lum(Param_Lum_slopeL), Step_Lum(Param_Lum_slopeL))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for slopeL in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_slopeL)) .AND. (temp <= TabParam_Lum_max(Param_Lum_slopeL))) THEN
TabParam_Lum(Param_Lum_slopeL) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_slopeL) = TabParam_Lum_min(Param_Lum_slopeL)
END IF
IF(TabParam_Lum_max(Param_Lum_slopeH) /= TabParam_Lum_min(Param_Lum_slopeH)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Lum(Param_Lum_slopeH), Step_Lum(Param_Lum_slopeH))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for slopeH in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_slopeH)) .AND. (temp <= TabParam_Lum_max(Param_Lum_slopeH))) THEN
TabParam_Lum(Param_Lum_slopeH) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_slopeH) = TabParam_Lum_min(Param_Lum_slopeH)
END IF
CASE(Model_LumPL_evol)
IF(TabParam_Lum_max(Param_Lum_Lmin) /= TabParam_Lum_min(Param_Lum_Lmin)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lmin)), Step_Lum(Param_Lum_Lmin)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lmin in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lmin)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lmin))) THEN
TabParam_Lum(Param_Lum_Lmin) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lmin) = TabParam_Lum_min(Param_Lum_Lmin)
END IF
IF(TabParam_Lum_max(Param_Lum_Lmax) /= TabParam_Lum_min(Param_Lum_Lmax)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lmax)), Step_Lum(Param_Lum_Lmax)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lmax in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lmax)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lmax))) THEN
TabParam_Lum(Param_Lum_Lmax) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lmax) = TabParam_Lum_min(Param_Lum_Lmax)
END IF
IF(TabParam_Lum_max(Param_Lum_slope) /= TabParam_Lum_min(Param_Lum_slope)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Lum(Param_Lum_slope), Step_Lum(Param_Lum_slope))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for slope in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_slope)) .AND. (temp <= TabParam_Lum_max(Param_Lum_slope))) THEN
TabParam_Lum(Param_Lum_slope) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_slope) = TabParam_Lum_min(Param_Lum_slope)
END IF
IF(TabParam_Lum_max(Param_Lum_k_evol) /= TabParam_Lum_min(Param_Lum_k_evol)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Lum(Param_Lum_k_evol), Step_Lum(Param_Lum_k_evol))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for k_evol in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_k_evol)) .AND. (temp <= TabParam_Lum_max(Param_Lum_k_evol))) THEN
TabParam_Lum(Param_Lum_k_evol) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_k_evol) = TabParam_Lum_min(Param_Lum_k_evol)
END IF
CASE(Model_LumSch)
IF(TabParam_Lum_max(Param_Lum_Lmin) /= TabParam_Lum_min(Param_Lum_Lmin)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lmin)), Step_Lum(Param_Lum_Lmin)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lmin in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lmin)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lmin))) THEN
TabParam_Lum(Param_Lum_Lmin) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lmin) = TabParam_Lum_min(Param_Lum_Lmin)
END IF
IF(TabParam_Lum_max(Param_Lum_Lbreak) /= TabParam_Lum_min(Param_Lum_Lbreak)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Lum(Param_Lum_Lbreak)), Step_Lum(Param_Lum_Lbreak)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Lbreak in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_Lbreak)) .AND. (temp <= TabParam_Lum_max(Param_Lum_Lbreak))) THEN
TabParam_Lum(Param_Lum_Lbreak) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_Lbreak) = TabParam_Lum_min(Param_Lum_Lbreak)
END IF
IF(TabParam_Lum_max(Param_Lum_slope) /= TabParam_Lum_min(Param_Lum_slope)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Lum(Param_Lum_slope), Step_Lum(Param_Lum_slope))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for slope in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_slope)) .AND. (temp <= TabParam_Lum_max(Param_Lum_slope))) THEN
TabParam_Lum(Param_Lum_slope) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_slope) = TabParam_Lum_min(Param_Lum_slope)
END IF
IF(TabParam_Lum_max(Param_Lum_k_evol) /= TabParam_Lum_min(Param_Lum_k_evol)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Lum(Param_Lum_k_evol), Step_Lum(Param_Lum_k_evol))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for k_evol in Draw_Markov_Jump()'
IF( (temp >= TabParam_Lum_min(Param_Lum_k_evol)) .AND. (temp <= TabParam_Lum_max(Param_Lum_k_evol))) THEN
TabParam_Lum(Param_Lum_k_evol) = temp
EXIT
END IF
END DO
ELSE
TabParam_Lum(Param_Lum_k_evol) = TabParam_Lum_min(Param_Lum_k_evol)
END IF
END SELECT
END IF
IF(Ep_explore == 1) THEN
SELECT CASE(Model_Ep)
CASE(Model_EpFix)
IF(TabParam_Ep_max(Param_Ep_Ep0) /= TabParam_Ep_min(Param_Ep_Ep0)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Ep(Param_Ep_Ep0)), Step_Ep(Param_Ep_Ep0)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Ep0 in Draw_Markov_Jump()'
IF( (temp >= TabParam_Ep_min(Param_Ep_Ep0)) .AND. (temp <= TabParam_Ep_max(Param_Ep_Ep0))) THEN
TabParam_Ep(Param_Ep_Ep0) = temp
EXIT
END IF
END DO
ELSE
TabParam_Ep(Param_Ep_Ep0) = TabParam_Ep_min(Param_Ep_Ep0)
END IF
CASE(Model_EpLogNormal)
IF(TabParam_Ep_max(Param_Ep_Ep0) /= TabParam_Ep_min(Param_Ep_Ep0)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Ep(Param_Ep_Ep0)), Step_Ep(Param_Ep_Ep0)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Ep0 in Draw_Markov_Jump()'
IF( (temp >= TabParam_Ep_min(Param_Ep_Ep0)) .AND. (temp <= TabParam_Ep_max(Param_Ep_Ep0))) THEN
TabParam_Ep(Param_Ep_Ep0) = temp
EXIT
END IF
END DO
ELSE
TabParam_Ep(Param_Ep_Ep0) = TabParam_Ep_min(Param_Ep_Ep0)
END IF
IF(TabParam_Ep_max(Param_Ep_sigmaLog) /= TabParam_Ep_min(Param_Ep_sigmaLog)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Ep(Param_Ep_sigmaLog), Step_Ep(Param_Ep_sigmaLog))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for sigmaLog in Draw_Markov_Jump()'
IF( (temp >= TabParam_Ep_min(Param_Ep_sigmaLog)) .AND. (temp <= TabParam_Ep_max(Param_Ep_sigmaLog))) THEN
TabParam_Ep(Param_Ep_sigmaLog) = temp
EXIT
END IF
END DO
ELSE
TabParam_Ep(Param_Ep_sigmaLog) = TabParam_Ep_min(Param_Ep_sigmaLog)
END IF
CASE(Model_EpAmati)
IF(TabParam_Ep_max(Param_Ep_Ep0) /= TabParam_Ep_min(Param_Ep_Ep0)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Ep(Param_Ep_Ep0)), Step_Ep(Param_Ep_Ep0)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for Ep0 in Draw_Markov_Jump()'
IF( (temp >= TabParam_Ep_min(Param_Ep_Ep0)) .AND. (temp <= TabParam_Ep_max(Param_Ep_Ep0))) THEN
TabParam_Ep(Param_Ep_Ep0) = temp
EXIT
END IF
END DO
ELSE
TabParam_Ep(Param_Ep_Ep0) = TabParam_Ep_min(Param_Ep_Ep0)
END IF
IF(TabParam_Ep_max(Param_Ep_sigmaLog) /= TabParam_Ep_min(Param_Ep_sigmaLog)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Ep(Param_Ep_sigmaLog), Step_Ep(Param_Ep_sigmaLog))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for sigmaLog in Draw_Markov_Jump()'
IF( (temp >= TabParam_Ep_min(Param_Ep_sigmaLog)) .AND. (temp <= TabParam_Ep_max(Param_Ep_sigmaLog))) THEN
TabParam_Ep(Param_Ep_sigmaLog) = temp
EXIT
END IF
END DO
ELSE
TabParam_Ep(Param_Ep_sigmaLog) = TabParam_Ep_min(Param_Ep_sigmaLog)
END IF
IF(TabParam_Ep_max(Param_Ep_L0) /= TabParam_Ep_min(Param_Ep_L0)) THEN
safeguard = 0
DO
temp = 10.d0**(gaussian(LOG10(TabParam_Ep(Param_Ep_L0)), Step_Ep(Param_Ep_L0)))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for L0 in Draw_Markov_Jump()'
IF( (temp >= TabParam_Ep_min(Param_Ep_L0)) .AND. (temp <= TabParam_Ep_max(Param_Ep_L0))) THEN
TabParam_Ep(Param_Ep_L0) = temp
EXIT
END IF
END DO
ELSE
TabParam_Ep(Param_Ep_L0) = TabParam_Ep_min(Param_Ep_L0)
END IF
IF(TabParam_Ep_max(Param_Ep_alpha_amati) /= TabParam_Ep_min(Param_Ep_alpha_amati)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_Ep(Param_Ep_alpha_amati), Step_Ep(Param_Ep_alpha_amati))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for alpha_amati in Draw_Markov_Jump()'
IF( (temp >= TabParam_Ep_min(Param_Ep_alpha_amati)) .AND. (temp <= TabParam_Ep_max(Param_Ep_alpha_amati))) THEN
TabParam_Ep(Param_Ep_alpha_amati) = temp
EXIT
END IF
END DO
ELSE
TabParam_Ep(Param_Ep_alpha_amati) = TabParam_Ep_min(Param_Ep_alpha_amati)
END IF
END SELECT
END IF
IF(z_explore == 1) THEN
SELECT CASE(Model_z)
CASE(Model_z_evol)
IF(TabParam_z_max(Param_z_zeta) /= TabParam_z_min(Param_z_zeta)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_z(Param_z_zeta), Step_z(Param_z_zeta))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for zeta in Draw_Markov_Jump()'
IF( (temp >= TabParam_z_min(Param_z_zeta)) .AND. (temp <= TabParam_z_max(Param_z_zeta))) THEN
TabParam_z(Param_z_zeta) = temp
EXIT
END IF
END DO
ELSE
TabParam_z(Param_z_zeta) = TabParam_z_min(Param_z_zeta)
END IF
CASE(Model_zBExp)
IF(TabParam_z_max(Param_z_zm) /= TabParam_z_min(Param_z_zm)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_z(Param_z_zm), Step_z(Param_z_zm))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for zm in Draw_Markov_Jump()'
IF( (temp >= TabParam_z_min(Param_z_zm)) .AND. (temp <= TabParam_z_max(Param_z_zm))) THEN
TabParam_z(Param_z_zm) = temp
EXIT
END IF
END DO
ELSE
TabParam_z(Param_z_zm) = TabParam_z_min(Param_z_zm)
END IF
IF(TabParam_z_max(Param_z_a) /= TabParam_z_min(Param_z_a)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_z(Param_z_a), Step_z(Param_z_a))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for a in Draw_Markov_Jump()'
IF( (temp >= TabParam_z_min(Param_z_a)) .AND. (temp <= TabParam_z_max(Param_z_a))) THEN
TabParam_z(Param_z_a) = temp
EXIT
END IF
END DO
ELSE
TabParam_z(Param_z_a) = TabParam_z_min(Param_z_a)
END IF
IF(TabParam_z_max(Param_z_b) /= TabParam_z_min(Param_z_b)) THEN
safeguard = 0
DO
temp = gaussian(TabParam_z(Param_z_b), Step_z(Param_z_b))
safeguard = safeguard + 1
IF(safeguard > 10000) STOP 'Looping too many times for b in Draw_Markov_Jump()'
IF( (temp >= TabParam_z_min(Param_z_b)) .AND. (temp <= TabParam_z_max(Param_z_b))) THEN
TabParam_z(Param_z_b) = temp
EXIT
END IF
END DO
ELSE
TabParam_z(Param_z_b) = TabParam_z_min(Param_z_b)
END IF
END SELECT
END IF
END SUBROUTINE Draw_Markov_Jump
SUBROUTINE Reset_Markov_Chain()
CALL Reset_MCMC_Step_Size()
CALL Reset_temperature()
IF(rank == master_proc) CALL Draw_model_Parameters() ! Move to random place in parameter space
CALL MPI_BCAST(TabParam_Lum, NParam_Lum, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_z, NParam_z, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_Ep, NParam_Ep, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(TabParam_spec, NParam_spec, MPI_REAL8, master_proc, MPI_COMM_WORLD, code)
CALL MonteCarlo(hist_flag) ! Calculate Chi2
rejected = 0 ! Reset consecutive rejected jumps
accepted_rec = 1 ! By design this jump is accepted
accepted = 0.d0 ! Reset the accepted rate
acceptance_ratio = 0.d0 ! Reset ratio of accepted jumps
steps_since_reset = 0 ! Reset steps count
MCMC_run_nb = MCMC_run_nb + 1
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) "[RESET CHAIN] run : ",MCMC_run_nb," MonteCarlo OK"
!IF(rank == master_proc) WRITE(*,*) "[RESET CHAIN] run : ",MCMC_run_nb," Chi2 : ", Chi2(0), " Lmin, slope : ",TabParam_Lum(Param_Lum_Lmin),TabParam_Lum(Param_Lum_slope)
IF(rank == master_proc) WRITE(*,'(A,I6,A,F8.2,A,F7.4x,F6.4,A,2F6.3)') "[RESET CHAIN] run : ",MCMC_run_nb," Chi2 : ", Chi2(0), " Lmin, slope : ",LOG10(TabParam_Lum(Param_Lum_Lmin)),TabParam_Lum(Param_Lum_slope), " steps : Lmin, slope ", Step_Lum(Param_Lum_Lmin), Step_Lum(Param_Lum_slope)
CALL Write_reprise_MCMC()
END SUBROUTINE Reset_Markov_Chain
SUBROUTINE Update_Markov_Chain()
! If the Markov jump is not accepted, revert to previous state
IF (lum_explore == 1) TabParam_Lum = TabParam_Lum_old
IF (Ep_explore == 1) TabParam_Ep = TabParam_Ep_old
IF (z_explore == 1 ) TabParam_z = TabParam_z_old
Chi2 = Chi2_old
lnL = lnL_old
END SUBROUTINE Update_Markov_Chain
SUBROUTINE Reset_temperature()
tau = 1.d3
END SUBROUTINE Reset_temperature
SUBROUTINE Reset_MCMC_Step_Size()
Step_Lum = 0.d0
Step_Ep = 0.d0
Step_z = 0.d0
Step_Lum(Param_Lum_Lmin) = 0.02d0
Step_Lum(Param_Lum_Lmax) = 0.025d0
Step_Lum(Param_Lum_Lbreak) = 0.025d0
Step_Lum(Param_Lum_slope) = 0.02d0
Step_Lum(Param_Lum_slopeL) = 0.05d0
Step_Lum(Param_Lum_slopeH) = 0.02d0
Step_Lum(Param_Lum_k_evol) = 0.04d0
Step_Ep(Param_Ep_Ep0) = 0.0075d0
Step_Ep(Param_Ep_sigmaLog) = 0.01d0
Step_Ep(Param_Ep_alpha_amati) = 0.01d0
Step_z(Param_z_zeta) = 0.01d0
Step_z(Param_z_zm) = 0.03d0
Step_z(Param_z_a) = 0.03d0
Step_z(Param_z_b) = 0.01d0
END SUBROUTINE Reset_MCMC_Step_Size
SUBROUTINE Update_MCMC_Step_Size(downscale, upscale)
REAL(8), intent(in) :: downscale, upscale
IF (acceptance_ratio > 0.234d0) THEN
Step_Lum = Step_Lum * upscale
Step_Ep = Step_Ep * upscale
Step_z = Step_z * upscale
ELSE IF((acceptance_ratio <= 0.234d0) .AND. (acceptance_ratio > 0.d0)) THEN
Step_Lum = Step_Lum * downscale
Step_Ep = Step_Ep * downscale
Step_z = Step_z * downscale
END IF
END SUBROUTINE Update_MCMC_Step_Size
SUBROUTINE Update_temperature(kappa_tau, tau_lim)
REAL(8), intent(in) :: kappa_tau
REAL(8), intent(in) :: tau_lim
tau = kappa_tau * (tau - tau_lim) + tau_lim
END SUBROUTINE Update_temperature
SUBROUTINE Write_reprise_MCMC()
! Write in reprise
OPEN(UNIT=43, FILE=TRIM(path)//'reprise_MCMC.dat', FORM='unformatted', POSITION='append')
IF(rank == master_proc) WRITE(43) TabSave_ijk_Kiss, TabParam_Lum, TabParam_z, TabParam_Spec, TabParam_Ep, &
& Chi2, lnL, k_Kommers, k_Stern, k_Preece, k_EpGBM, k_eBAT6, dof, accepted_rec, tau, Step_Lum, Step_z, Step_Ep,&
& TabHistLogL_master, TabHistz_master, TabHistLogEp_master, TabHistLogEpobs_master, TabHistLogP_master, &
& TabHistKomm_DRDP, TabHistPreece_Ep_master, TabHistStern_P23_master, TabHistEpGBM_Epobs_master, TabHisteBAT6_z_master
CLOSE(43) ! Close reprise file
END SUBROUTINE Write_reprise_MCMC
SUBROUTINE Update_best_parameters()
INTEGER :: i
OPEN(UNIT=876, FILE=TRIM(path)//'best_chi2.txt')
WRITE(876,'(A)') "# This file contains the information of the best model"
WRITE(876,'(A)') "# "
WRITE(876,'(A,ES12.5)') "# Best Chi2 : ", Chi2_min
WRITE(876,'(A,I3)') "# degrees of freedom : ", dof
WRITE(876,'(A,F6.3)') "# 3 sigma interval : ", delta_chi2_3
WRITE(876,'(A)') "# "
WRITE(876,'(A,I2,A)') "# seeds (KISS i,j,k) for ",nb_procs," cores : "
DO i=0, nb_procs-1
WRITE(876, *) TabSave_ijk_KISS(1,i),TabSave_ijk_KISS(2,i),TabSave_ijk_KISS(3,i)
END DO
WRITE(876,'(A)') "# "
WRITE(876,'(A)') "# Constraints used : "
DO i_Constraint=1, N_Constraints
IF(Constraint_Included(i_Constraint)) WRITE(876,'(a)') "# - "//TRIM(TabConstraint_name(i_Constraint))
END DO
WRITE(876,'(A)') "# "
WRITE(876,'(A)') "# Parameters : "
WRITE(876,'(A)') "# "
WRITE(876,'(A)') "# Luminosity function : (0) Fix (1 arg : L0)"
WRITE(876,'(A)') "# Luminosity function : (1) Power Law (3 args : Lmin, Lmax, slope)"
WRITE(876,'(A)') "# Luminosity function : (2) Evolving BPL (6 args : Lmin, Lmax, Lbreak, slopeL, slopeH, k_evol)"
WRITE(876,'(A)') "# Luminosity function : (3) Evol. Power Law (3 args : Lmin, Lmax, slope, k_evol)"
SELECT CASE(Model_Lum)
CASE(Model_LumFix)
TabBestParam_Lum(Param_Lum_L0) = TabParam_Lum(Param_Lum_L0)
WRITE(876,'(I1)') Model_LumFix
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_L0)
CASE(Model_LumPL)
TabBestParam_Lum(Param_Lum_Lmin) = TabParam_Lum(Param_Lum_Lmin)
TabBestParam_Lum(Param_Lum_Lmax) = TabParam_Lum(Param_Lum_Lmax)
TabBestParam_Lum(Param_Lum_slope) = TabParam_Lum(Param_Lum_slope)
WRITE(876,'(I1)') Model_LumPL
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_Lmin)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_Lmax)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_slope)
CASE(Model_LumBPL_evol)
TabBestParam_Lum(Param_Lum_Lmin) = TabParam_Lum(Param_Lum_Lmin)
TabBestParam_Lum(Param_Lum_Lmax) = TabParam_Lum(Param_Lum_Lmax)
TabBestParam_Lum(Param_Lum_Lbreak) = TabParam_Lum(Param_Lum_Lbreak)
TabBestParam_Lum(Param_Lum_slopeL) = TabParam_Lum(Param_Lum_slopeL)
TabBestParam_Lum(Param_Lum_slopeH) = TabParam_Lum(Param_Lum_slopeH)
TabBestParam_Lum(Param_Lum_k_evol) = TabParam_Lum(Param_Lum_k_evol)
WRITE(876,'(I1)') Model_LumBPL_evol
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_Lmin)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_Lmax)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_Lbreak)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_slopeL)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_slopeH)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_k_evol)
CASE(Model_LumPL_evol)
TabBestParam_Lum(Param_Lum_Lmin) = TabParam_Lum(Param_Lum_Lmin)
TabBestParam_Lum(Param_Lum_Lmax) = TabParam_Lum(Param_Lum_Lmax)
TabBestParam_Lum(Param_Lum_slope) = TabParam_Lum(Param_Lum_slope)
TabBestParam_Lum(Param_Lum_k_evol) = TabParam_Lum(Param_Lum_k_evol)
WRITE(876,'(I1)') Model_LumPL_evol
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_Lmin)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_Lmax)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_slope)
WRITE(876,'(ES12.5)') TabBestParam_Lum(Param_Lum_k_evol)
END SELECT
WRITE(876,'(A)') "# "
WRITE(876,'(A)') "# Peak energy : (0) Fix (1 arg : Ep0)"
WRITE(876,'(A)') "# Peak energy : (1) LogNormal (2 args : Ep0[keV], sigmaLog)"
WRITE(876,'(A)') "# Peak energy : (3) Amati-like (4 args : Ep0[keV], sigmaLog, L0[erg/s], alpha_amati)"
! DONT FORGET TO ADD THIS LATER (the other possible models)
SELECT CASE(Model_Ep)
CASE(Model_EpFix)
TabBestParam_Ep(Param_Ep_Ep0) = TabParam_Ep(Param_Ep_Ep0)
WRITE(876,'(I1)') Model_EpFix
WRITE(876,'(ES12.5)') TabBestParam_Ep(Param_Ep_Ep0)
CASE(Model_EpLogNormal)
TabBestParam_Ep(Param_Ep_Ep0) = TabParam_Ep(Param_Ep_Ep0)
TabBestParam_Ep(Param_Ep_sigmaLog) = TabParam_Ep(Param_Ep_sigmaLog)
WRITE(876,'(I1)') Model_EpLogNormal
WRITE(876,'(ES12.5)') TabBestParam_Ep(Param_Ep_Ep0)
WRITE(876,'(ES12.5)') TabBestParam_Ep(Param_Ep_sigmaLog)
CASE(Model_EpAmati)
TabBestParam_Ep(Param_Ep_Ep0) = TabParam_Ep(Param_Ep_Ep0)
TabBestParam_Ep(Param_Ep_sigmaLog) = TabParam_Ep(Param_Ep_sigmaLog)
TabBestParam_Ep(Param_Ep_L0) = TabParam_Ep(Param_Ep_L0)
TabBestParam_Ep(Param_Ep_alpha_amati) = TabParam_Ep(Param_Ep_alpha_amati)
WRITE(876,'(I1)') Model_EpAmati
WRITE(876,'(ES12.5)') TabBestParam_Ep(Param_Ep_Ep0)
WRITE(876,'(ES12.5)') TabBestParam_Ep(Param_Ep_sigmaLog)
WRITE(876,'(ES12.5)') TabBestParam_Ep(Param_Ep_L0)
WRITE(876,'(ES12.5)') TabBestParam_Ep(Param_Ep_alpha_amati)
END SELECT
WRITE(876,'(A)') "# "
WRITE(876,'(A)') "# Redshift : (0) z evolution (1 arg : zeta)"
SELECT CASE(Model_z)
CASE(Model_z_evol)
TabBestParam_z(Param_z_zeta) = TabParam_z(Param_z_zeta)
WRITE(876,'(I1)') Model_z_evol
WRITE(876,'(ES12.5)') TabBestParam_z(Param_z_zeta)
END SELECT
WRITE(876,'(A)') "# "
WRITE(876,'(A)') "# Normalizations : "
WRITE(876,*) " Number of GRBs : ", Nb_GRB
WRITE(876,*) " Kommers : ", k_Kommers
WRITE(876,*) " Preece : ", k_Preece
WRITE(876,*) " Stern : ", k_Stern
WRITE(876,*) " EpGBM : ", k_EpGBM
WRITE(876,*) " Pseudo collapse rate : ", pseudo_collapse_rate
CLOSE(876)
END SUBROUTINE Update_best_parameters
SUBROUTINE Draw_Redshift(z)
! --- Redshift ---!
REAL(8), INTENT(out) :: z
INTEGER :: imin, imax, j
IF(Model_z /= Model_zFix) THEN
DO
t = uniform_GRB() ! Different RNG for reproductibility
IF((t > 0.d0) .AND. (t < 1.0d0)) EXIT
END DO
imin = 1
imax = izmax
DO
j = (imin+imax)/2
IF (t >= TabFctDistrz(j)) THEN
imin = j+1
ELSE IF (t < TabFctDistrz(j-1)) THEN
imax = j
ELSE
EXIT
END IF
END DO
z = TabPrecisez(j-1) + (TabPrecisez(j) - TabPrecisez(j-1)) * (t-TabFctDistrz(j-1)) / (TabFctDistrz(j)-TabFctDistrz(j-1))
D_L = TabD_L(j-1) + (TabD_L(j) - TabD_L(j-1) ) * (t-TabFctDistrz(j-1)) / (TabFctDistrz(j)-TabFctDistrz(j-1))
END IF
IF (verbose==2) PRINT*, "z =", z
IF (verbose==2) PRINT*, "D_L = ", D_L, "[Mpc]"
IF (ISNAN(z)) NaNtest_prop = .TRUE.
END SUBROUTINE Draw_Redshift
SUBROUTINE Draw_Luminosity(L)
! -- Luminosity [erg/s] -- !
REAL(8), INTENT(out) :: L
INTEGER :: imin, imax, j
SELECT CASE(Model_Lum)
CASE(Model_LumFix)
CASE(Model_LumPL)
t = uniform_GRB()
IF(TabParam_Lum(Param_Lum_slope) == 1.d0) THEN
L = TabParam_Lum(Param_Lum_Lmin) * (TabParam_Lum(Param_Lum_Lmax)/TabParam_Lum(Param_Lum_Lmin))**t
ELSE
L = TabParam_Lum(Param_Lum_Lmin) * &
& ( 1.d0 - t*( 1.d0 - (TabParam_Lum(Param_Lum_Lmax)/TabParam_Lum(Param_Lum_Lmin))**(1.d0-TabParam_Lum(Param_Lum_slope)) )&
& )**(1.d0/ (1.d0-TabParam_Lum(Param_Lum_slope)) )
END IF
CASE(Model_LumBPL_evol)
t = uniform_GRB()
IF(TabParam_Lum(Param_Lum_slopeL) == 1) THEN
IF(TabParam_Lum(Param_Lum_slopeH) == 1) THEN
L = TabParam_Lum(Param_Lum_Lmin)* (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * (TabParam_Lum(Param_Lum_Lmax)/TabParam_Lum(Param_Lum_Lmin))**t
ELSE
IF(t < t_star) THEN
L = TabParam_Lum(Param_Lum_Lmin)* (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * (TabParam_Lum(Param_Lum_Lbreak)/TabParam_Lum(Param_Lum_Lmin))**(t/t_star)
ELSE
L = TabParam_Lum(Param_Lum_Lbreak)* (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * ( 1.d0 - (t-t_star) * (1.d0 -&
& ( TabParam_Lum(Param_Lum_Lmax)/TabParam_Lum(Param_Lum_Lbreak) )**(1.d0-TabParam_Lum(Param_Lum_slopeH)) ) / (1.d0-t_star) )&
& **( 1.d0/(1.d0 - TabParam_Lum(Param_Lum_slopeH)) )
END IF
END IF
ELSE
IF(TabParam_Lum(Param_Lum_slopeH) == 1) THEN
t = uniform_GRB()
IF(t < t_star) THEN
L = TabParam_Lum(Param_Lum_Lmin)* (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * (1.d0 - t/t_star * (1.d0 - (TabParam_Lum(Param_Lum_Lbreak)/TabParam_Lum(Param_Lum_Lmin))&
& **(1.d0 -TabParam_Lum(Param_Lum_slopeL))) )**(1.d0/(1.d0-TabParam_Lum(Param_Lum_slopeL)))
ELSE
L = TabParam_Lum(Param_Lum_Lbreak)* (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * (TabParam_Lum(Param_Lum_Lmax)/TabParam_Lum(Param_Lum_Lbreak))&
& **((t-t_star)/(1.d0-t_star))
END IF
ELSE
t = uniform_GRB()
IF(t < t_star) THEN
L = TabParam_Lum(Param_Lum_Lmin)* (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * (1.d0 - t/t_star * (1.d0 - (TabParam_Lum(Param_Lum_Lbreak)/TabParam_Lum(Param_Lum_Lmin))&
& **(1.d0 -TabParam_Lum(Param_Lum_slopeL))) )**(1.d0/(1.d0-TabParam_Lum(Param_Lum_slopeL)))
ELSE
L = TabParam_Lum(Param_Lum_Lbreak)* (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * ( 1.d0 - (t-t_star) * (1.d0 -&
& ( TabParam_Lum(Param_Lum_Lmax)/TabParam_Lum(Param_Lum_Lbreak) )**(1.d0-TabParam_Lum(Param_Lum_slopeH)) ) / (1.d0-t_star) )&
& **( 1.d0/(1.d0 - TabParam_Lum(Param_Lum_slopeH)) )
END IF
END IF
END IF
CASE(Model_LumPL_evol)
t = uniform_GRB()
IF(TabParam_Lum(Param_Lum_slope) == 1.d0) THEN
L = TabParam_Lum(Param_Lum_Lmin) * (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * (TabParam_Lum(Param_Lum_Lmax)/TabParam_Lum(Param_Lum_Lmin))**t
ELSE
L = TabParam_Lum(Param_Lum_Lmin) * (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * &
& ( 1.d0 - t*( 1.d0 - (TabParam_Lum(Param_Lum_Lmax)/TabParam_Lum(Param_Lum_Lmin))**(1.d0-TabParam_Lum(Param_Lum_slope)) )&
& )**(1.d0/ (1.d0-TabParam_Lum(Param_Lum_slope)) )
END IF
CASE(Model_LumSch)
DO
t = uniform_GRB() ! Different RNG for reproductibility
IF((t > 0.d0) .AND. (t < 1.0d0)) EXIT
END DO
imin = 1
imax = M_L
DO
j = (imin+imax)/2
IF (t >= TabFctDistrLum(j)) THEN
imin = j+1
ELSE IF (t < TabFctDistrLum(j-1)) THEN
imax = j
ELSE
EXIT
END IF
END DO
L = TabLogL_CDF(j-1) + (TabLogL_CDF(j) - TabLogL_CDF(j-1)) * (t-TabFctDistrLum(j-1)) / (TabFctDistrLum(j)-TabFctDistrLum(j-1))
L = (1.d0+z)**TabParam_Lum(Param_Lum_k_evol) * 10.d0**(L)
CASE DEFAULT
STOP "Monte Carlo (2) : ERROR Lum, not implemented yet"
END SELECT
IF (verbose==2) PRINT*, "L =", L, "[erg/s]"
IF (ISNAN(L)) NaNtest_prop = .TRUE.
END SUBROUTINE Draw_Luminosity
SUBROUTINE Draw_alpha_beta(alpha, beta)
! --- Spectral Model --- !
REAL(8), INTENT(out) :: alpha, beta
INTEGER :: imin, imax, j
IF(Model_Spec == Model_SpecBandD) THEN
DO
alpha = gaussian_GRB(1.d0, 0.5d0)
IF (alpha < 2.0d0) EXIT
END DO
DO
t = uniform_GRB()
IF( t <= 0.15625d0) THEN
beta = 2.d0 + SQRT(t/2.5d0)
ELSE
beta = (9.d0 - SQRT(13.5d0*(1.d0-t)) )/2.5d0
END IF
IF (beta > 2.0d0) EXIT
END DO
ELSE IF (Model_Spec == Model_SpecBandGBM) THEN
DO
t = uniform_GRB()
IF((t > 0.d0) .AND. (t < 1.0d0)) EXIT
END DO
imin = 1
imax = N_GBM_alpha
DO
j = (imin+imax)/2
IF (t >= TabFctDistrGBM_alpha(j)) THEN
imin = j+1
ELSE IF (t < TabFctDistrGBM_alpha(j-1)) THEN
imax = j
ELSE
EXIT
END IF
END DO
alpha = TabGBM_alpha(j-1) + (TabGBM_alpha(j) - TabGBM_alpha(j-1)) * (t-TabFctDistrGBM_alpha(j-1)) / (TabFctDistrGBM_alpha(j)-TabFctDistrGBM_alpha(j-1))
alpha = -alpha ! (because convention is opposite in GBM)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in MonteCarlo, in Draw_alpha_beta, alpha OK : ", alpha
DO
t = uniform_GRB()
IF((t > 0.d0) .AND. (t < 1.0d0)) EXIT
END DO
IF((rank == master_proc) .AND. (verbose == 2)) WRITE(*,*) " in MonteCarlo, in Draw_alpha_beta, t for beta OK : ", t
imin = 1
imax = N_GBM_beta
DO
j = (imin+imax)/2
IF (t >= TabFctDistrGBM_beta(j)) THEN
imin = j+1
ELSE IF (t < TabFctDistrGBM_beta(j-1)) THEN
imax = j
ELSE
EXIT
END IF
END DO
beta = TabGBM_beta(j-1) + (TabGBM_beta(j) - TabGBM_beta(j-1)) * (t-TabFctDistrGBM_beta(j-1)) / (TabFctDistrGBM_beta(j)-TabFctDistrGBM_beta(j-1))
beta = -beta ! (because convention is opposite in GBM)
IF((rank == master_proc) .AND. (verbose >= 1)) WRITE(*,*) " in MonteCarlo, in Draw_alpha_beta, beta OK : ", beta
END IF
ktild = Calc_ktild(alpha, beta, Model_Spec)
IF (ISNAN(ktild)) NaNtest_prop = .TRUE.
IF (ISNAN(alpha)) NaNtest_prop = .TRUE.
IF (ISNAN(beta)) NaNtest_prop = .TRUE.
IF(ISNAN(ktild)) WRITE(*,'(A, 3ES12.5)') "param(ktild, alpha, beta-alpha) : ", ktild, alpha, (beta-alpha)
IF(verbose == 2) THEN
PRINT*, 'alpha = ', alpha
PRINT*, 'beta = ', beta
END IF
END SUBROUTINE Draw_alpha_beta
SUBROUTINE Draw_Ep(Ep)
! --- Peak Energy [keV] --- !
REAL(8), INTENT(out) :: Ep
SELECT CASE(Model_Ep)
CASE(Model_EpLogNormal)
DO
Ep = 10**( gaussian_GRB(LOG10(TabParam_Ep(Param_Ep_Ep0)), TabParam_Ep(Param_Ep_sigmaLog)) )
IF(Ep > 0.d0) EXIT
END DO
CASE(Model_EpAmati)
DO
t = gaussian_GRB(0.d0, TabParam_Ep(Param_Ep_sigmaLog))
!IF(rank == master_proc) WRITE(*,*) " in Draw_Ep t : ", t
!IF(rank == master_proc) WRITE(*,*) " in Draw_Ep L : ", L
Ep = TabParam_Ep(Param_Ep_Ep0) * (L/TabParam_Ep(Param_Ep_L0))**TabParam_Ep(Param_Ep_alpha_amati) * &
& 10.d0**( SQRT(1.d0 + TabParam_Ep(Param_Ep_alpha_amati)**2) * t )
IF(Ep > 0.d0) EXIT
END DO
!IF(rank == master_proc) WRITE(*,*) " in Draw_Ep Ep0 : ", TabParam_Ep(Param_Ep_Ep0)
END SELECT
IF (ISNAN(Ep)) NaNtest_prop = .TRUE.
IF(verbose==2) PRINT*, "Ep : ", Ep, "[keV]"
END SUBROUTINE Draw_Ep
SUBROUTINE InitBoundaries()
! Creates the limits for the histograms
! Fills TabEmin and TabEmax with the values for each instrument
! Creates the detection threshold for each sample
! --- Histogram limits --- !
! ------------------------ !
! --- Luminosity [erg/s] --- !
TabHistlim_inf(Prop_LogL) = 46.d0
TabHistlim_sup(Prop_LogL) = 56.d0
! --- Redshift --- !
TabHistlim_inf(Prop_z) = 0.d0
TabHistlim_sup(Prop_z) = z_maximum
! --- Peak energy [keV] --- !
TabHistlim_inf(Prop_Ep) = 1.d-1
TabHistlim_sup(Prop_Ep) = 1.d4
! --- Peak flux [ph/cm^2/s] --- !
TabHistlim_inf(Prop_LogP) = -4.d0
TabHistlim_sup(Prop_LogP) = 4.d0
! --- Spec alpha --- !
TabHistlim_inf(Prop_alpha) = -1.d0
TabHistlim_sup(Prop_alpha) = 1.9d0
! --- Spec beta --- !
TabHistlim_inf(Prop_beta) = 2.d0
TabHistlim_sup(Prop_beta) = 22.d0
! --- Filling TabEmin and TabEmax --- !
! ----------------------------------- !
! BATSE
TabEmin(Instrument_BATSE) = 50.d0
TabEmax(Instrument_BATSE) = 300.d0
! SWIFT
TabEmin(Instrument_BAT ) = 15.d0
TabEmax(Instrument_BAT ) = 150.d0
! FREGATE
TabEmin(Instrument_FREGATE) = 30.d0
TabEmax(Instrument_FREGATE) = 400.d0
! WXM
TabEmin(Instrument_WXM) = 2.d0
TabEmax(Instrument_WXM) = 10.d0
! ECLAIRs
TabEmin(Instrument_ECLAIRs) = 4.d0
TabEmax(Instrument_ECLAIRs) = 120.d0
! --- Detection Threshold [ph/cm2/s] --- !
! -------------------------------------- !
Threshold(Sample_Intrinsic) = 0.d0
Threshold(Sample_Kommers) = 0.d0 ! 50-300 keV
Threshold(Sample_Preece) = 5.d0 ! 50-300 keV
Threshold(Sample_Stern) = 0.066825d0 ! 50-300 keV
Threshold(Sample_SWIFTweak) = 0.01d0 ! 15-150 keV
Threshold(Sample_SWIFT) = 0.2d0 ! 15-150 keV
Threshold(Sample_SWIFTbright) = 1.d0 ! 15-150 keV
Threshold(Sample_HETE2) = 1.d0 ! 2-10 keV or 30-400 keV
Threshold(Sample_eBAT6) = 2.6d0 ! 15-150 keV
Threshold(Sample_EpGBM) = 0.9d0 ! 50-300 keV
Threshold(Sample_SVOM) = bkgECLAIRsB1 ! 4-150 keV
END SUBROUTINE InitBoundaries
SUBROUTINE Init_RNG()
INTEGER :: i,j
CHARACTER :: skip
IF(RNG == Kiss_rng) THEN
! This is the parallel implementation
! These seeds were generated to garantee 10**12 draws from each core before overlapping
! 1st core
TabInit_ijk_Kiss(1,0) =123456789
TabInit_ijk_Kiss(2,0) =362436069
TabInit_ijk_Kiss(3,0) =521288629
! 2nd core
TabInit_ijk_Kiss(1,1) =293731605
TabInit_ijk_Kiss(2,1) =-985101706
TabInit_ijk_Kiss(3,1) =909351951
! 3rd core
TabInit_ijk_Kiss(1,2) =-408408811
TabInit_ijk_Kiss(2,2) =1991222469
TabInit_ijk_Kiss(3,2) =1423132033
! 4th core
TabInit_ijk_Kiss(1,3) =-1982964459
TabInit_ijk_Kiss(2,3) =-1145452629
TabInit_ijk_Kiss(3,3) =946873952
! 5th core
TabInit_ijk_Kiss(1,4) =-134968043
TabInit_ijk_Kiss(2,4) =27302573
TabInit_ijk_Kiss(3,4) =1817789790
! 6th core
TabInit_ijk_Kiss(1,5) =840613141
TabInit_ijk_Kiss(2,5) =-1675529275
TabInit_ijk_Kiss(3,5) =1643740297
! 7th core
TabInit_ijk_Kiss(1,6) =943779093
TabInit_ijk_Kiss(2,6) =1835649319
TabInit_ijk_Kiss(3,6) =1356939134
! 8th core
TabInit_ijk_Kiss(1,7) =174529813
TabInit_ijk_Kiss(2,7) =1388453552
TabInit_ijk_Kiss(3,7) =814083514
!!$ ! TEMPPPP
!!$ ! 1st core
!!$ TabInit_ijk_Kiss(1,0) =491832654
!!$ TabInit_ijk_Kiss(2,0) =918875735
!!$ TabInit_ijk_Kiss(3,0) =-98911476
!!$ ! 2nd core
!!$ TabInit_ijk_Kiss(1,1) =356972844
!!$ TabInit_ijk_Kiss(2,1) =-95462569
!!$ TabInit_ijk_Kiss(3,1) =847552878
!!$ ! 3rd core
!!$ TabInit_ijk_Kiss(1,2) =-36149117
!!$ TabInit_ijk_Kiss(2,2) =266254988
!!$ TabInit_ijk_Kiss(3,2) =589704982
!!$ ! 4th core
!!$ TabInit_ijk_Kiss(1,3) =-013698126
!!$ TabInit_ijk_Kiss(2,3) =-128796635
!!$ TabInit_ijk_Kiss(3,3) =462139459
IF(reprise .EQV. .TRUE.) THEN
OPEN(UNIT=74, FILE=TRIM(path)//'save_KISS.dat')
READ(74,*) skip ! skip line
DO i=0, nb_procs-1
READ(74, *) TabInit_ijk_Kiss(1,i), TabInit_ijk_Kiss(2,i), TabInit_ijk_Kiss(3,i)
END DO
CLOSE(74)
END IF
! Set the different seeds
iKiss = TabInit_ijk_Kiss(1,rank)
jKiss = TabInit_ijk_Kiss(2,rank)
kKiss = TabInit_ijk_Kiss(3,rank)
ELSE IF (RNG == MT19937) THEN
TabInit_seed_MT(0) = 85105
TabInit_seed_MT(1) = 12345
TabInit_seed_MT(2) = 71123
TabInit_seed_MT(3) = 2153
TabInit_seed_MT(4) = 2862
TabInit_seed_MT(5) = 35836
TabInit_seed_MT(6) = 58214
TabInit_seed_MT(7) = 457622
! Set the different seeds
MT_seed = TabInit_seed_MT(rank)
CALL sgrnd(MT_seed)
END IF
END SUBROUTINE Init_RNG
SUBROUTINE Reset_GRB_seeds()
! Subroutine to reset the seeds for the GRB property drawings to ensure a smooth chi2 surface
iKiss_GRB = TabInit_ijk_Kiss(1,rank)
jKiss_GRB = TabInit_ijk_Kiss(2,rank)
kKiss_GRB = TabInit_ijk_Kiss(3,rank)
END SUBROUTINE Reset_GRB_seeds
SUBROUTINE TestKiss()
INTEGER :: i
REAL(8) :: x
DO i=1, 1000000000
x = uniform()
IF (MODULO(i,100000000)==0) WRITE(*,'(4(A,I12))') "i=",i," Kiss : i=",iKiss," j=",jKiss," k=",kKiss
END DO
END SUBROUTINE TestKiss
SUBROUTINE Save_KISS()
INTEGER :: i
TabSave_ijk_KISS = 0
TabSave_ijk_KISS(1,rank) = iKiss
TabSave_ijk_KISS(2,rank) = jKiss
TabSave_ijk_KISS(3,rank) = kKiss
CALL MPI_REDUCE(TabSave_ijk_KISS(1,:), TabSave_ijk_KISS(1,:), nb_procs, MPI_INT, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
CALL MPI_REDUCE(TabSave_ijk_KISS(2,:), TabSave_ijk_KISS(2,:), nb_procs, MPI_INT, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
CALL MPI_REDUCE(TabSave_ijk_KISS(3,:), TabSave_ijk_KISS(3,:), nb_procs, MPI_INT, MPI_SUM, master_proc, MPI_COMM_WORLD, code)
IF(rank == master_proc) THEN
OPEN(UNIT=325, FILE=TRIM(path)//"save_KISS.dat")
WRITE(325, '(A,I2,A)') '# Last saved KISS seeds i,j,k for ',nb_procs,' cores : '
DO i=0, nb_procs-1
WRITE(325, *) TabSave_ijk_KISS(1,i),TabSave_ijk_KISS(2,i),TabSave_ijk_KISS(3,i)
END DO
CLOSE(325)
END IF
END SUBROUTINE Save_KISS
! -------------------------- !
! ----- Functions used ----- !
! -------------------------- !
FUNCTION Calc_DeltaChi2(p,nu)
! Frederic provided this, might need to ask him to understand it better
REAL(8), INTENT(in) :: p,nu
REAL(8) :: Calc_DeltaChi2
REAL(8) :: xmin,x,xmax,ymin,ymax,y
INTEGER :: i
xmin = 1.d0
ymin = GammaQ((nu/2.d0),(xmin/2.d0))-1.d0+p
xmax = 1000.d0
ymax = GammaQ((nu/2.d0),(xmax/2.d0))-1.d0+p
DO i=1, 100
x = (xmin+xmax)/2.d0
y = GammaQ((nu/2.d0),(x/2.d0))-1.d0+p
IF (y*ymax>0.d0) THEN
xmax = x
ymax = y
ELSE
xmin = x
ymin = y
END IF
END DO
Calc_DeltaChi2 = x
END FUNCTION Calc_DeltaChi2
! Uniform variable on [0,1]
FUNCTION uniform()
REAL(8) :: uniform
INTEGER :: j
INTEGER, PARAMETER :: Maxi=2147483647
IF(RNG == Kiss_rng) THEN
j=Kiss()
uniform=(REAL(j,8)+REAL(Maxi,8)+1.d0)/(2.d0*REAL(Maxi,8)+1.d0)
ELSE IF( RNG == MT19937) THEN
uniform = grnd() ! This is the MT19937 RNG
ELSE
CALL RANDOM_NUMBER(uniform)
END IF
END FUNCTION uniform
! Uniform variable on [0,1]
FUNCTION uniform_GRB()
! Different RNG for GRB sampling
REAL(8) :: uniform_GRB
INTEGER :: j
INTEGER, PARAMETER :: Maxi=2147483647
j=Kiss_GRB()
uniform_GRB=(REAL(j,8)+REAL(Maxi,8)+1.d0)/(2.d0*REAL(Maxi,8)+1.d0)
END FUNCTION uniform_GRB
FUNCTION Kiss()
INTEGER :: Kiss
iKiss=69069*iKiss+32606797
jKiss=Melange(Melange(jKiss,17),-15)
kKiss=Melange(IAND(Melange(kKiss,18),2147483647),-13)
Kiss=iKiss+jKiss+kKiss
END FUNCTION Kiss
FUNCTION Kiss_GRB()
INTEGER :: Kiss_GRB
iKiss_GRB=69069*iKiss_GRB+32606797
jKiss_GRB=Melange(Melange(jKiss_GRB,17),-15)
kKiss_GRB=Melange(IAND(Melange(kKiss_GRB,18),2147483647),-13)
Kiss_GRB=iKiss_GRB+jKiss_GRB+kKiss_GRB
END FUNCTION Kiss_GRB
FUNCTION Melange(k,n)
INTEGER, INTENT(In) :: k,n
INTEGER :: Melange
Melange=IEOR(k,ISHFT(k,n))
END FUNCTION Melange
REAL(8) FUNCTION gaussian(mu, sigma)
! Random draw with a gaussian distribution
REAL(8), INTENT(in) :: mu, sigma
REAL(8) :: t, theta
DO
t = uniform()
IF(t>0) EXIT
END DO
theta = uniform()
theta = theta * 2*Pi
gaussian = mu + SQRT(2.d0) * sigma * ( COS(theta) * SQRT(-LOG(t)) )
! sigma * ( COS(theta) * SQRT(-LOG(t)) )
! for comparison with Daigne 2006 remove sqrt(2)
END FUNCTION gaussian
REAL(8) FUNCTION gaussian_GRB(mu, sigma)
! Random draw with a gaussian distribution
REAL(8), INTENT(in) :: mu, sigma
REAL(8) :: t, theta
DO
t = uniform_GRB()
IF(t>0) EXIT
END DO
theta = uniform_GRB()
theta = theta * 2*Pi
gaussian_GRB = mu + SQRT(2.d0) * sigma * ( COS(theta) * SQRT(-LOG(t)) )
! sigma * ( COS(theta) * SQRT(-LOG(t)) )
! for comparison with Daigne 2006 remove sqrt(2)
END FUNCTION gaussian_GRB
REAL(8) FUNCTION Rz(z, Model_z, Tabparam_z)
! GRB rate as a function of redshift [GRB/yr/Mpc^3]
! b : slope at low z
! b-a : slope at high z
REAL(8), INTENT(in) :: z
INTEGER, INTENT(in) :: Model_z
REAL(8), DIMENSION(1:10), INTENT(in) :: Tabparam_z
REAL(8) :: a, b, c, d, zm, zeta
SELECT CASE(Model_z)
CASE(Model_zFix)
Rz = 1.d0
CASE(Model_zUniform)
Rz = 1.d0
CASE(Model_zSH)
zm = TabParam_z(Param_z_zm)
a = TabParam_z(Param_z_a)
b = TabParam_z(Param_z_b)
Rz = 0.00132d0 * a * EXP(b*(z-zm)) / ( a-b + b*EXP(a*(z-zm)) )
CASE(Model_zDaigne)
a = TabParam_z(Param_z_a)
b = TabParam_z(Param_z_b)
c = TabParam_z(Param_z_c)
d = TabParam_z(Param_z_d)
Rz = 0.0122d0 * a * EXP(b*z) / ( EXP(c*z) + d )
CASE(Model_z_evol)
a = TabParam_z(Param_z_a)
b = TabParam_z(Param_z_b)
zm = TabParam_z(Param_z_zm)
zeta = TabParam_z(Param_z_zeta)
! normalization comes from IMF Salpeter
Rz = 0.00132d0 * z_evolution(z, zm, zeta) * a * EXP(b*(z-zm)) / ( a-b + b*EXP(a*(z-zm)) )
CASE(Model_zLi)
a = TabParam_z(Param_z_a)
b = TabParam_z(Param_z_b)
c = TabParam_z(Param_z_c)
d = TabParam_z(Param_z_d)
! Normalization from Salpeter IMF
Rz = 0.007422d0 * (a + b*z) / ( 1.d0 + (z/c)**d )
CASE(Model_zBPL)
a = TabParam_z(Param_z_a)
b = TabParam_z(Param_z_b)
zm = TabParam_z(Param_z_zm)
! No normalization (don't need for pdf)
IF(z <= zm) THEN
Rz = (1.d0 + z)**a
ELSE
Rz = (1.d0 + z)**b * (1.d0 + zm)**(a-b)
END IF
CASE(Model_zBExp)
a = TabParam_z(Param_z_a)
b = TabParam_z(Param_z_b)
zm = TabParam_z(Param_z_zm)
! Normalization from fit to SH with Salpeter IMF
IF(z <= zm) THEN
Rz =0.00033313d0 * EXP(a*z)
ELSE
Rz =0.00033313d0 * EXP(b*z) * EXP((a-b)*zm)
END IF
END SELECT
END FUNCTION Rz
REAL(8) FUNCTION z_evolution(z, zm, zeta)
REAL(8), INTENT(in) :: z, zm, zeta
! Function that returns the redshift dependence of the "efficiency" of collapses to form GRBs
!IF(z <= zm) THEN
! z_evolution = 1.d0
!ELSE
!z_evolution = ( (1.d0+z)/(1.d0+zm) )**zeta
z_evolution = EXP(zeta*z)
!END IF
END FUNCTION z_evolution
REAL(8) FUNCTION Calc_Epobs(Ep,z)
REAL(8), INTENT(in) :: Ep, z
! --- Peak Energy (obs) [keV] --- !
Calc_Epobs = Ep / (1.d0 + z)
IF (ISNAN(Epobs)) NaNtest_prop = .TRUE.
IF(verbose==2) PRINT*, "Epobs : ", Calc_Epobs, "[keV]"
END FUNCTION Calc_Epobs
REAL(8) FUNCTION Calc_t_star(TabParam_Lum)
REAL(8), DIMENSION(1:10), INTENT(in) :: TabParam_Lum
REAL(8) :: slopeL, slopeH, Lbreak, Lmin, Lmax
Lmin = TabParam_Lum(Param_Lum_Lmin)
Lmax = TabParam_Lum(Param_Lum_Lmax)
Lbreak = TabParam_Lum(Param_Lum_Lbreak)
slopeL = TabParam_Lum(Param_Lum_slopeL)
slopeH = TabParam_Lum(Param_Lum_slopeH)
IF(slopeL == 1) THEN
IF(slopeH == 1) THEN
STOP "Problem in Calc_t_star : slopeL = 1 and slopeH = 1"
ELSE
Calc_t_star = LOG(Lbreak/Lmin) / ( LOG(Lbreak/Lmin) + (slopeH-1.d0)**(-1) * ( 1.d0 - (Lmax/Lbreak)**(1.d0-slopeH) ) )
END IF
ELSE
IF(slopeH == 1) THEN
Calc_t_star = ( Lbreak**(1.d0-slopeL) - Lmin**(1.d0-slopeL) ) / ( (Lbreak**(1.d0-slopeL) - Lmin**(1.d0-slopeL)) + (1.d0-slopeL)*Lbreak**(1.d0-slopeL)*LOG(Lmax/Lbreak) )
ELSE
Calc_t_star = ( Lbreak**(1.d0-slopeL) - Lmin**(1.d0-slopeL) ) / &
& ( (Lbreak**(1.d0-slopeL) - Lmin**(1.d0-slopeL)) + Lbreak**(slopeH-slopeL) * (1.d0-slopeL)/(1.d0-slopeH) * (Lmax**(1.d0-slopeH) - Lbreak**(1.d0-slopeH)) )
END IF
END IF
END FUNCTION Calc_t_star
REAL(8) FUNCTION Calc_Lum(L, Model_Lum, TabParam_Lum)
! Calc_Lum returns the probability of getting the luminosity L with a given model
! Luminosity in [erg/s]
REAL(8), INTENT(in) :: L
INTEGER, INTENT(in) :: Model_Lum
REAL(8), DIMENSION(1:10), INTENT(in) :: TabParam_Lum
REAL(8) :: slope, Lmin, Lmax
REAL(8) :: slopeL, slopeH, Lbreak, t_star
SELECT CASE(Model_Lum)
CASE(Model_LumFix)
Calc_Lum = 0.d0
CASE(Model_LumPL)
Lmin = TabParam_Lum(Param_Lum_Lmin)
Lmax = TabParam_Lum(Param_Lum_Lmax)
slope = TabParam_Lum(Param_Lum_slope)
IF(L < Lmin .OR. L > Lmax) THEN
Calc_Lum = 0.d0
ELSE
IF(slope == 1.d0) THEN
Calc_Lum = 1.d0/(LOG(Lmax/Lmin)*L)
ELSE
Calc_Lum = L**(-slope) * (slope-1.d0) / ( Lmin**(1.d0-slope) - Lmax**(1.d0-slope) )
END IF
END IF
CASE(Model_LumBPL_evol)
Lmin = TabParam_Lum(Param_Lum_Lmin)
Lmax = TabParam_Lum(Param_Lum_Lmax)
Lbreak = TabParam_Lum(Param_Lum_Lbreak)
slopeL = TabParam_Lum(Param_Lum_slopeL)
slopeH = TabParam_Lum(Param_Lum_slopeH)
IF(L <= Lmin .OR. L >= Lmax) THEN
Calc_Lum = 0.d0
ELSE
IF (slopeL == 1.d0 .AND. slopeH == 1.d0) THEN
Calc_Lum = 1.d0/(LOG(Lmax/Lmin)*L)
ELSE IF (slopeL == 1.d0 .AND. slopeH /= 1.d0) THEN
t_star = LOG(Lbreak/Lmin) / ( LOG(Lbreak/Lmin) + (slopeH-1.d0)**(-1) * ( 1.d0 - (Lmax/Lbreak)**(1.d0-slopeH) ) )
IF (L <= Lbreak) THEN
Calc_Lum = t_star / ( L* LOG(Lbreak/Lmin) )
ELSE IF (L > Lbreak) THEN
Calc_Lum = (1.d0 - t_star) * (slopeH - 1.d0) * L**(-slopeH) / ( Lbreak**(1.d0 - slopeH) - Lmax**(1.d0 - slopeH) )
END IF
ELSE IF (slopeL /= 1.d0 .AND. slopeH == 1.d0) THEN
t_star = ( L**(1.d0-slopeL) - Lmin**(1.d0-slopeL) ) / ( (Lbreak**(1.d0-slopeL) - Lmin**(1.d0-slopeL)) + (1.d0-slopeL)*Lbreak**(1.d0-slopeL)*LOG(Lmax/Lbreak) )
IF (L <= Lbreak) THEN
Calc_Lum = t_star * (slopeH - 1.d0) * L**(-slopeH) / ( Lbreak**(1.d0 - slopeH) - Lmax**(1.d0 - slopeH) )
ELSE IF (L > Lbreak) THEN
Calc_Lum = (1.d0 - t_star) / ( L* LOG(Lbreak/Lmin) )
END IF
ELSE IF (slopeL /= 1.d0 .AND. slopeH /= 1.d0) THEN
t_star = ( L**(1.d0-slopeL) - Lmin**(1.d0-slopeL) ) / &
& ( (Lbreak**(1.d0-slopeL) - Lmin**(1.d0-slopeL)) + Lbreak**(slopeH-slopeL) * (1.d0-slopeL)/(1.d0-slopeH) * (Lmax**(1.d0-slopeH) - Lbreak**(1.d0-slopeH)) )
IF (L <= Lbreak) THEN
Calc_Lum = t_star * (slopeH - 1.d0) * L**(-slopeH) / ( Lbreak**(1.d0 - slopeH) - Lmax**(1.d0 - slopeH) )
ELSE IF (L > Lbreak) THEN
Calc_Lum = (1.d0 - t_star) * (slopeH - 1.d0) * L**(-slopeH) / ( Lbreak**(1.d0 - slopeH) - Lmax**(1.d0 - slopeH) )
END IF
ELSE
STOP "Problem in Calc_Lum"
END IF
END IF
CASE(Model_LumSch)
slope = TabParam_Lum(Param_Lum_slope)
Lbreak = TabParam_Lum(Param_Lum_Lbreak)
Calc_Lum = (L / Lbreak )**(-slope) * EXP(-L/Lbreak)
CASE DEFAULT
STOP "Calc_Lum : error, model not defined."
END SELECT
END FUNCTION Calc_Lum
REAL(8) FUNCTION Calc_ktild(alpha, beta, Model_Spec)
! Calculates the normalization factor for the spectral shape
! Uses the Gamma functions for optimized speed. See stats.f90 for details
REAL(8), INTENT(in) :: alpha, beta
INTEGER, INTENT(in) :: Model_Spec
REAL(8) :: x_c, xBx, Gamma, gln
IF(Model_Spec == Model_SpecBPLFix) THEN
Calc_ktild = (2.d0-alpha) * (beta-2.d0) / (beta-alpha)
ELSE
x_c = (beta - alpha) / (2.d0 - alpha)
CALL GammaSeries(Gamma, 2.d0-alpha, beta-alpha, gln)
xBx = Gamma * EXP(gln) /( (2.d0 - alpha)**(2.d0-alpha) )
IF(verbose == 2) PRINT*, "ktild integral up to x_c = ", xBx
xBx = xBx + x_c**(2.d0-alpha) * EXP(alpha-beta) / (beta - 2.d0)
Calc_ktild = 1.d0/xBx
END IF
END FUNCTION Calc_ktild
SUBROUTINE Calculate_Peakflux_Instrument()
! --- Number of Photons between Emin and Emax [ph/cm^2/s] --- !
DO i_Instrument=1, N_Instruments
IF(Instrument_Included(i_Instrument)) THEN
Peakflux_Instrument(i_Instrument) = Nb_ph(L, z, Ep, D_L, alpha, beta, ktild, TabEmin(i_Instrument), TabEmax(i_Instrument))
IF (verbose==2) THEN
WRITE(*,'(A,A20,ES12.5,A,F3.0,A,F4.0,A)')&
& " Instrument : " , TRIM(TabInstrument_name(i_Instrument)) // " Peakflux =",Peakflux_Instrument(i_Instrument),&
& " [ph/cm2/s between ",TabEmin(i_Instrument)," and ", TabEmax(i_Instrument), " keV]"
END IF
IF (ISNAN(Peakflux_Instrument(i_Instrument))) NaNtest_prop = .TRUE.
END IF
END DO
END SUBROUTINE Calculate_Peakflux_Instrument
SUBROUTINE Calculate_Detection_Probability()
REAL(8) :: cts_ECLAIRs, Prob_det_ij=0.d0
INTEGER :: i,j
! ---------------- Detection Probability [0,1] ---------------- !
DO i_Sample=0, N_Samples
IF(i_Sample >= 1) THEN
IF(Sample_Included(i_Sample)) THEN
SELECT CASE(i_Sample)
CASE(Sample_Kommers)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_BATSE)
! BATSE23 (Kommers et al. 2000, eq (4) ) :
!PRINT*,Peakflux_Instrument(Instrument_BATSE), ERF(-4.801d0 + 29.868d0 *1.d0 )
IF(Peakflux_Instrument(Instrument_BATSE) <= 1.d0) THEN ! Had to add this because above 1.d0, ERF function gets Floating Point Exception : erroneous arithmetic operation.
Prob_det(Sample_Kommers) = 0.5d0 * ( 1.d0 + ERF(-4.801d0 + 29.868d0 * Peakflux_Instrument(Instrument_BATSE) ))
ELSE
Prob_det(Sample_Kommers) = 1.d0
END IF
IF (ISNAN(Prob_det(Sample_Kommers))) NaNtest_prop = .TRUE.
CASE(Sample_Preece)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_BATSE)
IF(Peakflux_Instrument(Instrument_BATSE) >= Threshold(Sample_Preece)) THEN
Prob_det(Sample_Preece) = 1.d0
ELSE
Prob_det(Sample_Preece) = 0.d0
END IF
CASE(Sample_Stern)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_BATSE)
IF(Peakflux_Instrument(Instrument_BATSE) >= Threshold(Sample_Stern)) THEN
Prob_det(Sample_Stern) = 1.d0
ELSE
Prob_det(Sample_Stern) = 0.d0
END IF
CASE(Sample_SWIFTweak)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_BAT )
IF(Peakflux_Instrument(Instrument_BAT ) >= Threshold(Sample_Swiftweak)) THEN
Prob_det(Sample_Swiftweak) = 1.d0
ELSE
Prob_det(Sample_Swiftweak) = 0.d0
END IF
CASE(Sample_SWIFT)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_BAT )
IF(Peakflux_Instrument(Instrument_BAT ) >= Threshold(Sample_Swift)) THEN
Prob_det(Sample_Swift) = 1.d0
ELSE
Prob_det(Sample_Swift) = 0.d0
END IF
CASE(Sample_SWIFTbright)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_BAT )
IF(Peakflux_Instrument(Instrument_BAT ) >= Threshold(Sample_Swiftbright)) THEN
Prob_det(Sample_Swiftbright) = 1.d0
ELSE
Prob_det(Sample_Swiftbright) = 0.d0
END IF
CASE(Sample_HETE2)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_FREGATE)
IF(Peakflux_Instrument(Instrument_WXM) >= Threshold(Sample_HETE2) .OR. Peakflux_Instrument(Instrument_FREGATE) >= Threshold(Sample_HETE2) ) THEN
Prob_det(Sample_HETE2) = 1.d0
ELSE
Prob_det(Sample_HETE2) = 0.d0
END IF
CASE(Sample_eBAT6)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_BAT )
IF(Peakflux_Instrument(Instrument_BAT ) >= Threshold(Sample_eBAT6)) THEN
Prob_det(Sample_eBAT6) = 1.d0
ELSE
Prob_det(Sample_eBAT6) = 0.d0
END IF
CASE(Sample_EpGBM)
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_BATSE)
IF(Peakflux_Instrument(Instrument_BATSE) >= Threshold(Sample_EpGBM)) THEN
Prob_det(Sample_EpGBM) = 1.d0
ELSE
Prob_det(Sample_EpGBM) = 0.d0
END IF
CASE(Sample_SVOM)
cts_ECLAIRs = Nb_cts_ECLAIRs(L, z, Ep, D_L, alpha, beta, ktild, TabEmin(Instrument_ECLAIRs), TabEmax(Instrument_ECLAIRs)) ! on-axis
Peakflux(i_Sample) = Peakflux_Instrument(Instrument_ECLAIRs)
Prob_det(Sample_SVOM) = 0.D0
DO i=-NoffECLAIRs, NoffECLAIRs
DO j=-NoffECLAIRs, NoffECLAIRs
IF(cts_ECLAIRs * TABoffECLAIRs(i,j) >= nsigmasECLAIRs * SQRT(Threshold(Sample_SVOM) / Delta_t_pflx) ) THEN
Prob_det_ij = 1.d0
ELSE
Prob_det_ij = 0.d0
END IF
Prob_det(Sample_SVOM) = Prob_det(Sample_SVOM) + TABomegaECLAIRs(i,j) * Prob_det_ij
END DO
END DO
Prob_det(Sample_SVOM) = Prob_det(Sample_SVOM) / omegaECLAIRs
IF (verbose == 2) PRINT*, "cts ECLAIRS =",cts_ECLAIRs
IF (verbose == 2) PRINT*, "detec limit =", nsigmasECLAIRs * SQRT(Threshold(Sample_SVOM) / Delta_t_pflx)
!IF(cts_ECLAIRs >= nsigmasECLAIRs * SQRT(Threshold(Sample_SVOM) / Delta_t_pflx) ) THEN
! Prob_det(Sample_SVOM) = 1.d0
!ELSE
! Prob_det(Sample_SVOM) = 0.d0
!END IF
CASE DEFAULT
STOP "Error, undefined sample."
END SELECT
IF (ISNAN(Peakflux(i_Sample))) NaNtest_prop = .TRUE.
IF (verbose==2) PRINT*, "Prob_det of ",TRIM(TabSample_name(i_Sample)) ," = ", Prob_det(i_Sample)
END IF
ELSE
Prob_det(i_Sample) = 1.d0
END IF
END DO
END SUBROUTINE Calculate_Detection_Probability
REAL(8) FUNCTION Nb_ph(L, z, Ep, D_L, alpha, beta, ktild, Emin, Emax)
! Returns the Number of photons [ph/cm^2/s] between Emin and Emax
! L [erg/s]
! Ep [keV] (source frame)
! D_L [Mpc]
! Emin,Emax [keV] (observer frame)
REAL(8), INTENT(in) :: L, z, Ep, D_L, alpha, beta, ktild, Emin, Emax
REAL(8) :: xmin,xmax,x1, x2, B1, B2, B, dx, dlogx
INTEGER :: M2,j
xmin = (1.d0+z)*Emin/Ep
xmax = (1.d0+z)*Emax/Ep
dlogx = 1.d-2
M2 = MAX(1, INT(LOG10(xmax/xmin)/dlogx))
IF(verbose == 2) PRINT*, " Number of steps for Nb_ph integration : ", M2
x1 = xmin
B1 = Btild(x1, ktild, Model_Spec, alpha, beta)
B = 0.d0
DO j=1,M2
x2 = 10.d0**(LOG10(xmin)+LOG10(xmax/xmin)*REAL(j,8)/REAL(M2,8))
B2 = Btild(x2, ktild, Model_Spec, alpha, beta)
B = B + 0.5d0*(x2-x1)*(B2+B1)
x1 = x2
B1 = B2
END DO
IF(verbose == 2) PRINT*, " Btild integrated value : ", B
Nb_ph = (1.d0+z) * L /(4.d0*Pi*(Ep*keV)*(D_L*Mpc)**2) * B
END FUNCTION Nb_ph
REAL(8) FUNCTION Nb_cts_ECLAIRs(L, z, Ep, D_L, alpha, beta, ktild, Emin, Emax)
! Returns the Number of photons [ph/cm^2/s] between Emin and Emax
! L [erg/s]
! Ep [keV] (source frame)
! D_L [Mpc]
! Emin,Emax [keV] (observer frame)
REAL(8), INTENT(in) :: L, z, Ep, D_L, alpha, beta, ktild, Emin, Emax
REAL(8) :: xmin,xmax,x1, x2, B1, B2, Aeff1, Aeff2, B, dx, dlogx
INTEGER :: M2,j,i,ieff
xmin = (1.d0+z)*Emin/Ep
xmax = (1.d0+z)*Emax/Ep
dlogx = 1.d-2
M2 = MAX(1, INT(LOG10(xmax/xmin)/dlogx))
IF(verbose == 2) PRINT*, " Number of steps for Nb_ph integration : ", M2
x1 = xmin
B1 = Btild(x1, ktild, Model_Spec, alpha, beta)
i = 1
DO WHILE(TABeffECLAIRsE(i)<= Emin)
ieff = i
i = i + 1
IF(i > NeffECLAIRs) THEN
PRINT*,"Warning in Nb_ph_ECLAIRs: Emin=",Emin," larger than TABeffECLAIRsE(NeffECLAIRs)=",TABeffECLAIRsE(NeffECLAIRs)
EXIT
END IF
END DO
Aeff1 = TABeffECLAIRsA(ieff)
B = 0.d0
DO j=1,M2
x2 = 10.d0**(LOG10(xmin)+LOG10(xmax/xmin)*REAL(j,8)/REAL(M2,8))
B2 = Btild(x2, ktild, Model_Spec, alpha, beta)
i = 1
DO WHILE(TABeffECLAIRsE(i)<= Ep*x2/(1.d0+z) )
ieff = i
i = i + 1
IF(i > NeffECLAIRs) THEN
PRINT*,"Warning in Nb_ph_ECLAIRs: E2=",Ep*x2/(1.d0+z)," larger than TABeffECLAIRsE(NeffECLAIRs)=",TABeffECLAIRsE(NeffECLAIRs)
EXIT
END IF
END DO
Aeff2 = TABeffECLAIRsA(ieff)
B = B + 0.5d0*(x2-x1)*(Aeff2*B2 + Aeff1*B1)
x1 = x2
B1 = B2
Aeff1 = Aeff2
END DO
IF(verbose == 2) PRINT*, " Btild integrated value : ", B
Nb_cts_ECLAIRs = (1.d0+z) * L /(4.d0*Pi*(Ep*keV)*(D_L*Mpc)**2) * B
END FUNCTION Nb_cts_ECLAIRs
REAL(8) FUNCTION F_12(L, z, Ep, D_L, alpha, beta, ktild, Emin, Emax)
! Returns the Energy flux [erg/cm^2/s] between Emin and Emax
! L [erg/s]
! Ep [keV] (source frame)
! D_L [Mpc]
! Emin,Emax [keV] (observer frame)
REAL(8), INTENT(in) :: L, z, Ep, D_L, alpha, beta, ktild, Emin, Emax
REAL(8) :: xmin,xmax,x1, x2, B1, B2, B, dx, dlogx
INTEGER :: M2,j
xmin = (1.d0+z)*Emin/Ep
xmax = (1.d0+z)*Emax/Ep
dlogx = 0.01d0
M2 = MAX(1, INT(LOG10(xmax/xmin)/dlogx))
x1 = xmin
B1 = xBtild(x1, ktild, Model_Spec, alpha, beta)
B = 0.d0
DO j=1,M2
x2 = 10.d0**(LOG10(xmin)+LOG10(xmax/xmin)*REAL(j,8)/REAL(M2,8))
B2 = xBtild(x2, ktild, Model_Spec, alpha, beta)
B = B + 0.5d0*(x2-x1)*(B2+B1)
x1 = x2
B1 = B2
END DO
IF(verbose==2) PRINT*, "B =", B
F_12 = L /(4.d0*Pi*(D_L*Mpc)**2) * B
END FUNCTION F_12
REAL(8) FUNCTION Btild(x, ktild, Model_Spec, alpha, beta) ! No units
! Returns the unitless spectral shape. Used by Nb_ph
REAL(8), INTENT(in) :: x, ktild
INTEGER, INTENT(in) :: Model_Spec
REAL(8) :: alpha, beta, x_c
INTEGER :: j, M
IF(Model_Spec == Model_SpecBPLFix) THEN
IF(x<1.d0) THEN
Btild = ktild * x**(-alpha)
ELSE IF(x>1.d0) THEN
Btild = ktild * x**(-beta)
ELSE
Btild = ktild
PRINT*, "In Btild, E = Ep"
END IF
ELSE IF (Model_Spec == Model_SpecBandFix .OR. Model_Spec == Model_SpecBandK .OR. Model_Spec == Model_SpecBandD .OR. Model_Spec == Model_SpecBandGBM) THEN
x_c = (beta - alpha) / (2.d0 - alpha)
IF(x < x_c) THEN
Btild = ktild * x**(-alpha) * EXP( (alpha - 2.d0) * x )
ELSE IF (x > x_c) THEN
Btild = ktild * x**(-beta ) * EXP(alpha - beta) * x_c**(beta - alpha)
ELSE
Btild = ktild * x_c**(-alpha) * EXP(alpha - beta)
PRINT*, "In Btild, x = x_c"
END IF
END IF
END FUNCTION Btild
! Returns the unitless spectral shape. Used by F_12 (energy flux)
REAL(8) FUNCTION xBtild(x, ktild, Model_Spec, alpha, beta) ! No units
REAL(8), INTENT(in) :: x, ktild
INTEGER, INTENT(in) :: Model_Spec
REAL(8) :: alpha, beta, x_c
INTEGER :: j, M
IF(Model_Spec == Model_SpecBPLFix) THEN
IF(x<1.d0) THEN
xBtild = ktild * x**(1.d0-alpha)
ELSE IF(x>1.d0) THEN
xBtild = ktild * x**(1.d0-beta)
ELSE
xBtild = ktild
PRINT*, "In xBtild, E = Ep"
END IF
ELSE IF (Model_Spec == Model_SpecBandFix .OR. Model_Spec == Model_SpecBandK .OR. Model_Spec == Model_SpecBandD .OR. Model_Spec == Model_SpecBandGBM) THEN
x_c = (beta - alpha) / (2.d0 - alpha)
IF(x < x_c) THEN
xBtild = ktild * x**(1.d0-alpha) * EXP( (alpha - 2.d0) * x )
ELSE IF (x > x_c) THEN
xBtild = ktild * x**(1.d0-beta ) * EXP(alpha - beta) * x_c**(beta - alpha)
ELSE
xBtild = ktild * x_c**(1.d0-alpha) * EXP(alpha - beta)
PRINT*, "In xBtild, x = x_c"
END IF
END IF
END FUNCTION xBtild
! -----------------------
! End of : Functions used
SUBROUTINE Generate_Names()
! Generates TabSample_name, TabConstraint_name
TabSample_name(Sample_Intrinsic) = "intr_sample"
TabSample_name(Sample_Kommers) = "Kommers_sample"
TabSample_name(Sample_Preece) = "Preece_sample"
TabSample_name(Sample_Stern) = "Stern_sample"
TabSample_name(Sample_SWIFTweak) = "SWIFTweak_sample"
TabSample_name(Sample_SWIFT) = "SWIFT_sample"
TabSample_name(Sample_SWIFTbright) = "SWIFTbright_sample"
TabSample_name(Sample_HETE2) = "HETE2_sample"
TabSample_name(Sample_eBAT6) = "eBAT6_sample"
TabSample_name(Sample_EpGBM) = "GBM_sample"
TabSample_name(Sample_SVOM) = "SVOM_sample"
TabInstrument_name(Instrument_BATSE) = "BATSE"
TabInstrument_name(Instrument_BAT ) = "BAT"
TabInstrument_name(Instrument_FREGATE) = "FREGATE"
TabInstrument_name(Instrument_WXM) = "WXM"
TabInstrument_name(Instrument_ECLAIRs) = "ECLAIRs"
TabConstraint_name(Constraint_Kommers) = "Kommers"
TabConstraint_name(Constraint_Preece) = "Preece"
TabConstraint_name(Constraint_Stern) = "Stern"
TabConstraint_name(Constraint_HETE2) = "XRFHETE2"
TabConstraint_name(Constraint_EpGBM) = "EpGBM"
TabConstraint_name(Constraint_eBAT6) = "eBAT6"
END SUBROUTINE Generate_Names
SUBROUTINE Generate_Paths()
INTEGER :: i
DO i=0,N_Samples
LFile(i) = TRIM(path) // "luminosity_" // TRIM(TabSample_name(i))
zFile(i) = TRIM(path) // "redshift_" // TRIM(TabSample_name(i))
EpFile(i) = TRIM(path) // "peakenergy_" // TRIM(TabSample_name(i))
PFile(i) = TRIM(path) // "peakflux_" // TRIM(TabSample_name(i))
SpecFile_a(i) = TRIM(path) // "spec_alpha_" // TRIM(TabSample_name(i))
SpecFile_b(i) = TRIM(path) // "spec_beta_" // TRIM(TabSample_name(i))
zFile_cumul(i) = TRIM(path) // "cumul_redshift_" // TRIM(TabSample_name(i))
LErrorFile(i) = TRIM(path) // "luminosity_err_" // TRIM(TabSample_name(i))
zErrorFile(i) = TRIM(path) // "redshift_err_" // TRIM(TabSample_name(i))
EpErrorFile(i) = TRIM(path) // "peakenergy_err_" // TRIM(TabSample_name(i))
PErrorFile(i) = TRIM(path) // "peakflux_err_" // TRIM(TabSample_name(i))
SpecErrorFile_a(i) = TRIM(path) // "spec_alpha_err_" // TRIM(TabSample_name(i))
SpecErrorFile_b(i) = TRIM(path) // "spec_beta_err_" // TRIM(TabSample_name(i))
END DO
KommFile = TRIM(path) // KommFile
PreeceFile = TRIM(path) // PreeceFile
SternFile = TRIM(path) // SternFile
XRFHETE2File = TRIM(path) // XRFHETE2File
EpGBMFile = TRIM(path) // EpGBMFile
eBAT6File = TRIM(path) // eBAT6File
KommErrorFile = TRIM(path) // KommErrorFile
PreeceErrorFile = TRIM(path) // PreeceErrorFile
SternErrorFile = TRIM(path) // SternErrorFile
XRFHETE2ErrorFile = TRIM(path) // XRFHETE2ErrorFile
EpGBMErrorFile = TRIM(path) // EpGBMErrorFile
eBAT6ErrorFile = TRIM(path) // eBAT6ErrorFile
eBAT6_EpLFile = TRIM(path) // eBAT6_EpLFile
END SUBROUTINE Generate_Paths
SUBROUTINE Prepare_Histogram_Prop(TabHistlim_inf, TabHistlim_sup, n_call)
! Generates the x-axis for luminosity, redshift, Ep, Peak flux histograms
! and (re)sets the values of the histograms to 0
REAL(8), DIMENSION(1:N_prop), INTENT(in) :: TabHistlim_inf, TabHistlim_sup
INTEGER, INTENT(inout) :: n_call
! Assumptions
REAL(8) :: LogLmin,LogLmax
REAL(8) :: zmax
REAL(8) :: LogEpmin,LogEpmax
REAL(8) :: LogPmin,LogPmax
REAL(8) :: alpha_min,alpha_max
REAL(8) :: beta_min,beta_max
! Local
INTEGER :: i
IF (n_call == 0 ) THEN
IF(Lsave(0)) THEN
! Log(L) [erg/s]
LogLmin = TabHistlim_inf(Prop_LogL)
LogLmax = TabHistlim_sup(Prop_LogL)
DO i=0, N_L
TabLogL(i) = LogLmin + (LogLmax-LogLmin) * REAL(i,8)/REAL(N_L,8)
END DO
END IF
IF(zsave(0)) THEN
! Redshift z
zmax = TabHistlim_sup(Prop_z)
DO i=0, N_z
Tabz(i) = zmax * REAL(i,8)/REAL(N_z,8)
END DO
END IF
IF(Epsave(0)) THEN
! Ep [keV]
LogEpmin = LOG10(TabHistlim_inf(Prop_Ep))
LogEpmax = LOG10(TabHistlim_sup(Prop_Ep))
DO i=0, N_Ep
TabLogEp(i) = LogEpmin + (LogEpmax-LogEpmin) * REAL(i,8)/REAL(N_Ep,8)
END DO
END IF
IF(Psave(0)) THEN
! Peak Flux [ph/cm2/s between Emin and Emax]
LogPmin = TabHistlim_inf(Prop_LogP)
LogPmax = TabHistlim_sup(Prop_LogP)
DO i=0, N_P
TabLogP(i) = LogPmin + (LogPmax-LogPmin) * REAL(i,8)/REAL(N_P,8)
END DO
END IF
IF(Specsave(0)) THEN
! alpha and beta
alpha_min = TabHistlim_inf(Prop_alpha)
alpha_max = TabHistlim_sup(Prop_alpha)
DO i=0, N_spec_a
TabSpec_a(i) = alpha_min + (alpha_max-alpha_min) * REAL(i,8)/REAL(N_spec_a,8)
END DO
beta_min = TabHistlim_inf(Prop_beta)
beta_max = TabHistlim_sup(Prop_beta)
DO i=0, N_spec_b
TabSpec_b(i) = beta_min + (beta_max-beta_min) * REAL(i,8)/REAL(N_spec_b,8)
END DO
END IF
!!$ ! redshift for eBAT6
!!$ DO i=0, N_eBAT6
!!$ TabeBAT6_z(i) = 10.d0 * REAL(i,8)/REAL(N_eBAT6,8)
!!$ END DO
! Ep-L plane for eBAT6
DO i=0, N_eBAT6_EpL ! equally spaced in logscale
TabeBAT6_EpL(Indice_Ep, i) = 4.d0 * REAL(i,8)/REAL(N_eBAT6_EpL,8)
TabeBAT6_EpL(Indice_L, i) = 48.d0 + (55.d0-48.d0) * REAL(i,8)/REAL(N_eBAT6_EpL,8)
END DO
TabeBAT6_EpL = 10**TabeBAT6_EpL ! remove log
n_call = n_call + 1
END IF
! --- Reset Histograms --- !
IF(Lsave(0)) THEN
TabHistLogL = 0.d0
TabHistLogL_master = 0.d0
END IF
IF(zsave(0)) THEN
TabHistz = 0.d0
TabHistz_master = 0.d0
END IF
IF(Epsave(0)) THEN
TabHistLogEp = 0.d0
TabHistLogEpobs = 0.d0
TabHistLogEp_master = 0.d0
TabHistLogEpobs_master = 0.d0
END IF
IF(Psave(0)) THEN
TabHistLogP = 0.d0
TabHistLogP_master = 0.d0
END IF
IF(Specsave(0)) THEN
TabHistalpha = 0.d0
TabHistalpha_master = 0.d0
TabHistbeta = 0.d0
TabHistbeta_master = 0.d0
END IF
! Ep-L plane for eBAT6
TabHisteBAT6_EpL = 0.d0
TabHisteBAT6_EpL_master = 0.d0
END SUBROUTINE Prepare_Histogram_Prop
SUBROUTINE Reset_Histogram_Chi2()
IF (Constraint_included(Constraint_Kommers)) THEN
k_Kommers = 0.d0
TabHistKomm_P23 = 0.d0
TabHistKomm_P23_master = 0.d0
END IF
IF (Constraint_included(Constraint_Preece)) THEN
k_Preece = 0.d0
TabHistPreece_Ep = 0.d0
TabHistPreece_Ep_master = 0.d0
END IF
IF (Constraint_included(Constraint_Stern)) THEN
k_Stern = 0.d0
TabHistStern_P23 = 0.d0
TabHistStern_P23_master = 0.d0
END IF
IF (Constraint_included(Constraint_EpGBM)) THEN
k_EpGBM = 0.d0
TabHistEpGBM_Epobs = 0.d0
TabHistEpGBM_Epobs_master = 0.d0
END IF
IF (Constraint_included(Constraint_eBAT6)) THEN
k_eBAT6 = 0.d0
TabHisteBAT6_z = 0.d0
TabHisteBAT6_z_master = 0.d0
END IF
END SUBROUTINE Reset_Histogram_Chi2
SUBROUTINE Reset_Histogram_Samples()
IF (Sample_included(Sample_Kommers)) THEN
k_Kommers = 0.d0
TabHistKomm_P23 = 0.d0
TabHistKomm_P23_master = 0.d0
END IF
IF (Sample_included(Sample_Preece)) THEN
k_Preece = 0.d0
TabHistPreece_Ep = 0.d0
TabHistPreece_Ep_master = 0.d0
END IF
IF (Sample_included(Sample_Stern)) THEN
k_Stern = 0.d0
TabHistStern_P23 = 0.d0
TabHistStern_P23_master = 0.d0
END IF
IF (Sample_included(Sample_EpGBM)) THEN
k_EpGBM = 0.d0
TabHistEpGBM_Epobs = 0.d0
TabHistEpGBM_Epobs_master = 0.d0
END IF
IF (Sample_included(Sample_eBAT6)) THEN
! redshift for eBAT6
TabHisteBAT6_z = 0.d0
TabHisteBAT6_z_master = 0.d0
END IF
END SUBROUTINE Reset_Histogram_Samples
SUBROUTINE Prepare_Luminosity()
! Creates distribution function for luminosity
INTEGER :: i,j
REAL(8) :: x1,y1,x2,y2,integ
REAL(8) :: x_c, xBx, Gamma, gln, Gamma_min
REAL(8) :: logLbreak, logLmin
TabFctDistrLum(0) = 0.d0
IF (Model_Lum == Model_LumSch) THEN
logLmin = LOG10(TabParam_Lum(Param_Lum_Lmin))
logLbreak = LOG10(TabParam_Lum(Param_Lum_Lbreak))
TabLogL_CDF(0) = logLmin
integ = 0.d0
IF(run_mode == one_run) OPEN(UNIT=909, FILE=TRIM(path)//"probLum.dat")
WRITE(909,*) 10**logLmin, Calc_Lum(logLmin, Model_Lum, TabParam_Lum) , TabFctDistrLum(0)
x1 = 10.d0**(TabLogL_CDF(0))
y1 = Calc_Lum(x1, Model_Lum, TabParam_Lum)
DO i=1, M_L
TabLogL_CDF(i) = logLmin + REAL(i,8)/REAL(M_L,8) * (logLbreak-logLmin + 1.5d0) ! to avoid extremely low probability beyond logLbreak + 1.5
x2 = 10.d0**(TabLogL_CDF(i))
y2 = Calc_Lum(x2, Model_Lum, TabParam_Lum)
integ = 0.5d0 * (x2 - x1) * (y1 + y2)
x1 = x2
y1 = y2
!IF (verbose==2) PRINT*, "integ_Lum =", integ
TabFctDistrLum(i) = TabFctDistrLum(i-1) + integ
WRITE(909,*) x2, y2, TabFctDistrLum(i)
END DO
CLOSE(909)
ELSE IF (Model_Lum > Model_LumSch) THEN ! CHECK THIS
IF(rank == master_proc) PRINT*, ' WARNING THIS LUM MODEL HASNT BEEN CHECKED'
DO i=1, N_L
x1 = 10.d0**(TabLogL(i-1))
y1 = Calc_Lum(x1, Model_Lum, TabParam_Lum)
integ = 0.d0
DO j=1, M_L
x2 = 10.d0**(TabLogL(i-1)+(TabLogL(i)-TabLogL(i-1))*REAL(j,8)/REAL(M_L,8))
y2 = Calc_Lum(x2, Model_Lum, TabParam_Lum)
integ = integ + 0.5d0*(x2-x1)*(y2+y1)
x1 = x2
y1 = y2
IF (verbose==2) PRINT*, "integ_Lum =", integ
END DO
TabFctDistrLum(i) = TabFctDistrLum(i-1) + integ
END DO
END IF
IF (verbose==2) PRINT*, 'Final value of F_Lum :', TabFctDistrLum(M_L)
TabFctDistrLum(0:M_L) = TabFctDistrLum(0:M_L) / TabFctDistrLum(M_L)
END SUBROUTINE Prepare_Luminosity
SUBROUTINE Prepare_Redshift()
! Creates distribution function for redshift
INTEGER :: i
REAL(8) :: x1,x2,y1,y2,integ,zmax
SELECT CASE(Model_z)
CASE(Model_zFix)
zmax = 0.d0
CASE(Model_zUniform)
zmax = TabParam_z(Param_z_zmax)
CASE(Model_zSH)
zmax = TabParam_z(Param_z_zmax)
CASE(Model_zDaigne)
zmax = z_maximum
CASE(Model_z_evol)
zmax = TabParam_z(Param_z_zmax)
CASE(Model_zLi)
zmax = z_maximum
CASE(Model_zPesc)
zmax = z_maximum
CASE(Model_zBPL)
zmax = TabParam_z(Param_z_zmax)
CASE(Model_zBExp)
zmax = TabParam_z(Param_z_zmax)
CASE DEFAULT
STOP "Prepare_Redshift : z model not defined"
END SELECT
! indice zmax
IF ( zmax > Tabprecisez(INT(SIZE(Tabprecisez)-1)) ) STOP "Aborting zmax not allowed"
IF (zmax /= 0.d0 ) THEN
IF (Model_z /= Model_zPesc) THEN
izmax = INT(REAL(SIZE(Tabprecisez)-1)*(zmax-Tabprecisez(0))/(Tabprecisez(INT(SIZE(Tabprecisez)-1))-Tabprecisez(0)))
IF ( ABS(Tabprecisez(izmax)-zmax) > 1.d-4 ) THEN
WRITE(*,*) "WARNING Moving zmax from ", zmax, " to ",Tabprecisez(izmax)
END IF
zmax = Tabprecisez(izmax)
TabFctDistrz = 0.d0
IF(run_mode == one_run) OPEN(UNIT=909, FILE=TRIM(path)//"probz.dat")
IF(run_mode == one_run) OPEN(UNIT=908, FILE=TRIM(path)//"FctDistrz.dat")
DO i=1, izmax
x1 = Tabprecisez(i-1)
y1 = Rz(x1, Model_z, Tabparam_z) * TabdVdz(i-1) / (1.d0 + x1)
x2 = Tabprecisez(i)
y2 = Rz(x2, Model_z, Tabparam_z) * TabdVdz( i ) / (1.d0 + x1)
integ = 0.5d0 * (x2 - x1) * (y1 + y2)
TabFctDistrz(i) = TabFctDistrz(i-1) + integ
IF(run_mode == one_run) WRITE(909, '(3ES12.5)') Tabprecisez(i), integ/(Tabprecisez(i)-Tabprecisez(i-1)), TabdVdz(i)/(1.d0 + x1)
IF(run_mode == one_run) WRITE(908, '(2ES12.5)') Tabprecisez(i), TabFctDistrz(i)
END DO
IF(run_mode == one_run) CLOSE(909)
IF(run_mode == one_run) CLOSE(908)
pseudo_collapse_rate = TabFctDistrz(izmax)
!WRITE(*,'(A,ES12.5,A)') ' Pseudo collapse rate :', TabFctDistrz(izmax), ' collapse/yr'
IF (verbose == 1) WRITE(*,*) 'Final value of F_z (Before normalization) :', TabFctDistrz(izmax)
TabFctDistrz(0:izmax) = TabFctDistrz(0:izmax) / TabFctDistrz(izmax)
ELSE
!!$ TabFctDistrz = 0.d0
!!$ OPEN(UNIT=55, FILE='../../catalogs/BAT6_cat/z_cumul_distr_Pesc16.txt')
!!$ READ(55,*) skip ! skip line
!!$ READ(55,*) skip ! skip line
!!$
!!$ DO i=0, N_
!!$ READ(55, *) TabGBM_alpha(i), TabFctDistrGBM_alpha(i)
!!$ END DO
!!$ CLOSE(55)
END IF
ELSE ! if zmax = 0
END IF
END SUBROUTINE Prepare_Redshift
SUBROUTINE Prepare_Spec()
! Creates distribution function for alpha and beta
INTEGER :: i
CHARACTER :: skip
TabFctDistrGBM_alpha = 0.d0
OPEN(UNIT=55, FILE='../../catalogs/GBM_cat/alpha_GBM.txt')
READ(55,*) skip ! skip line
READ(55,*) skip ! skip line
READ(55,*) skip ! skip line
DO i=0, N_GBM_alpha
READ(55, *) TabGBM_alpha(i), TabFctDistrGBM_alpha(i)
END DO
CLOSE(55)
TabFctDistrGBM_beta = 0.d0
OPEN(UNIT=55, FILE='../../catalogs/GBM_cat/beta_GBM.txt')
READ(55,*) skip ! skip line
READ(55,*) skip ! skip line
READ(55,*) skip ! skip line
DO i=0, N_GBM_beta
READ(55, *) TabGBM_beta(i), TabFctDistrGBM_beta(i)
END DO
CLOSE(55)
END SUBROUTINE Prepare_Spec
SUBROUTINE Prepare_Constraints()
INTEGER :: i,j
CHARACTER :: skip
REAL(8) :: Global_GRB_rate
! Kommers (2000) Table 2 : P23 [ph/cm2/s 50-300keV]
OPEN(FILE='../observational_constraints/Kommers.dat', UNIT=600)
READ(600, *) skip ! skips the first line of the file
j = 1
DO i=1, 2*N_Komm
IF (MOD(i,2) /= 0) THEN
READ(600, '(4ES12.5)') TabKomm_P23(j-1), TabHistKomm_P23obs(j), TabKomm_DRobs(j), TabKomm_DRobserr(j)
j = j+1
ELSE IF (i == 2*N_Komm) THEN
READ(600,'(ES12.5)') TabKomm_P23(N_Komm)
ELSE
READ(600, *) skip
END IF
END DO
CLOSE(600)
TabKomm_LogP23 = LOG10(TabKomm_P23) ! Logscale
!PRINT*,'Global GRB rate from Kommers : ', SUM(TabKomm_DRobs)*4.d0*Pi, 'GRB/year'
DO i=1, N_Komm
TabKomm_DRDPobs(i) = TabKomm_DRobs(i) /(TabKomm_P23(i)-TabKomm_P23(i-1))
TabKomm_DRDPobserr(i) = TabKomm_DRobserr(i)/(TabKomm_P23(i)-TabKomm_P23(i-1))
END DO
! Preece (????) : Ep [keV]
OPEN(FILE='../observational_constraints/preece.eb2.dat', UNIT=601)
! READ(601, *) skip ! skips the first line of the file
DO i=1, N_Preece
READ(601, *) skip
READ(601, *) TabPreece_Ep(i-1), TabHistPreece_Epobs(i)
END DO
READ(601, *) TabPreece_Ep(N_Preece)
! TabPreece_Ep(N_Preece) = 6309.57d0
! DO i=1, N_Preece
! WRITE(*,*) " i, TabPreece_Ep(i-1), TabPreece_Ep(i), DN(i)", i, TabPreece_Ep(i-1), TabPreece_Ep(i), TabHistPreece_Epobs(i)
! END DO
! READ(*,*)
CLOSE(601)
TabPreece_LogEp = LOG10(TabPreece_Ep)
TabHistPreece_Epobserr = SQRT(TabHistPreece_Epobs)
TabHistPreece_Epobs = TabHistPreece_Epobs
! LogNLogP Stern
!OPEN(FILE='../observational_constraints/lognlogp.stern.dat', UNIT=602)
OPEN(FILE='../observational_constraints/Stern_lognlogp_rebinned.txt', UNIT=602)
DO i=1, 10 ! skips the first 10 lines of the file
READ(602, *) skip
END DO
DO i=1, N_Stern
READ(602,*) TabStern_P23(i-1), TabHistStern_P23obs(i), TabHistStern_P23obserr(i)
END DO
CLOSE(602)
!This was used in old Stern constraint from Daigne+06
!TabStern_P23(N_Stern) = TabStern_P23(N_Stern-1) + 0.1d0
TabStern_P23(N_Stern) = 50.d0
!TabStern_P23 = 10**(TabStern_P23)/0.75d0 ! divide by 0.75 to convert from counts to flux
TabHistStern_P23obs = 10.d0**(TabHistStern_P23obs)
! Error propagation from log to linear scale (i.e. the average between the plus and minus errors)
TabHistStern_P23obserr = TabHistStern_P23obs * ( (10.d0**(TabHistStern_P23obserr)-1.d0) )!+ (1.d0-10.d0**(-TabHistStern_P23obserr)) )
Global_GRB_rate = 0.d0
DO i=1, N_Stern
Global_GRB_rate = Global_GRB_rate + LOG10(TabStern_P23(i)/ TabStern_P23(i-1)) * TabHistStern_P23obs(i)
END DO
!PRINT*, 'Global GRB rate from Stern+01 : ', Global_GRB_rate, ' GRB/year in 4 pi with pflx in [50-300 keV] above ',TabStern_P23(0),' ph/cm2/s'
!This was used in old Stern constraint from Daigne+06
!TabStern_P23 = 10.d0**(TabStern_P23)
!TabStern_P23 = TabStern_P23 / 0.75d0
! GBM catalog (Gruber 2014) : Ep [keV]
OPEN(FILE='../observational_constraints/Ep_GBM.txt', UNIT=603)
READ(603, *) skip ! skips the first lines of the file
READ(603, *) skip ! skips the first lines of the file
READ(603, *) skip ! skips the first lines of the file
j = 1
DO i=1, 2*N_EpGBM
IF (MOD(i,2) /= 0) THEN
READ(603, *) TabEpGBM_Epobs(j-1), TabHistEpGBM_Epobsobs(j), TabHistEpGBM_Epobsobserr(j)
j = j+1
ELSE IF (i == 2*N_EpGBM) THEN
READ(603,*) TabEpGBM_Epobs(N_EpGBM)
ELSE
READ(603, *) skip
END IF
END DO
TabEpGBM_LogEpobs = LOG10(TabEpGBM_Epobs)
CLOSE(603)
! eBAT6 redshift histogram (from Pescalli+16)
OPEN(FILE='../observational_constraints/eBAT6_constraint.txt', UNIT=605)
READ(605, *) skip ! skips the first lines of the file
READ(605, *) skip ! skips the first lines of the file
READ(605, *) skip ! skips the first lines of the file
j = 1
DO i=1, 2*N_eBAT6
IF (MOD(i,2) /= 0) THEN
READ(605, *) TabeBAT6_z(j-1), TabHisteBAT6_zobs(j), TabHisteBAT6_zobserr(j)
j = j+1
ELSE IF (i == 2*N_eBAT6) THEN
READ(605,*) TabeBAT6_z(N_eBAT6)
ELSE
READ(605, *) skip
END IF
END DO
CLOSE(605)
END SUBROUTINE Prepare_Constraints
SUBROUTINE Fill_Histogram_Prop()
INTEGER :: imin, imax, j
! --- Luminosity [erg/s] --- !
iBinL = INT( ( LOG10(L)-TabHistlim_inf(Prop_LogL) ) / ( TabHistlim_sup(Prop_LogL)-TabHistlim_inf(Prop_LogL) ) * REAL(N_L,8) ) + 1
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinL =", iBinL
! --- Redshift --- !
iBinz = INT( z / TabHistlim_sup(Prop_z) * REAL(N_z,8) ) + 1
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinz =", iBinz
! --- Peak Energy (source frame) [keV] --- !
IF( (Ep < TabHistlim_inf(Prop_Ep)) .OR. (Ep >= TabHistlim_sup(Prop_Ep) )) THEN
iBinEp = -1
ELSE
iBinEp = INT( ( LOG10(Ep)-LOG10(TabHistlim_inf(Prop_Ep)) ) / ( LOG10(TabHistlim_sup(Prop_Ep))-LOG10(TabHistlim_inf(Prop_Ep)) ) * REAL(N_Ep,8) ) + 1
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinEp =", iBinEp
! --- Peak Energy (observer frame) [keV] --- !
IF( (Epobs < TabHistlim_inf(Prop_Ep)) .OR. (Epobs >= TabHistlim_sup(Prop_Ep) )) THEN
iBinEpobs = -1
ELSE
iBinEpobs = INT( ( LOG10(Epobs)-LOG10(TabHistlim_inf(Prop_Ep)) ) / ( LOG10(TabHistlim_sup(Prop_Ep))-LOG10(TabHistlim_inf(Prop_Ep)) ) * REAL(N_Ep,8) ) + 1
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinEpobs =", iBinEpobs
! --- Peak Flux [ph/cm2/s] --- !
DO i_Sample = 1, N_Samples
IF(Sample_Included(i_Sample)) THEN
IF( (LOG10(Peakflux(i_Sample)) < TabHistlim_inf(Prop_LogP)) .OR. (LOG10(Peakflux(i_Sample)) >= TabHistlim_sup(Prop_LogP) )) THEN
iBinPeakflux(i_Sample) = -1
ELSE
iBinPeakflux(i_Sample) = INT( (LOG10(Peakflux(i_Sample))-TabHistlim_inf(Prop_LogP))/( TabHistlim_sup(Prop_LogP)-TabHistlim_inf(Prop_LogP) )*REAL(N_P,8) ) + 1
END IF
IF( (verbose == 1) .AND. (rank == master_proc) )WRITE(*,'(A,A,A,I3)') " iBinPeakflux of ",TRIM(TabSample_name(i_Sample))," = ", iBinPeakflux(i_Sample)
END IF
END DO
! --- Spec alpha --- !
IF( (alpha < TabHistlim_inf(Prop_alpha)) .OR. (alpha >= TabHistlim_sup(Prop_alpha) )) THEN
iBina = -1
ELSE
iBina = INT( ( alpha-TabHistlim_inf(Prop_alpha) ) / ( TabHistlim_sup(Prop_alpha)-TabHistlim_inf(Prop_alpha) ) * REAL(N_spec_a,8) ) + 1
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBina =", iBina
! --- Spec beta --- !
IF( (beta < TabHistlim_inf(Prop_beta)) .OR. (beta >= TabHistlim_sup(Prop_beta) )) THEN
iBinb = -1
ELSE
iBinb = INT( ( beta-TabHistlim_inf(Prop_beta) ) / ( TabHistlim_sup(Prop_beta)-TabHistlim_inf(Prop_beta) ) * REAL(N_spec_b,8) ) + 1
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinb =", iBinb
! ----------- Fill the histograms ------------- !
DO i_Sample = 0, N_Samples
IF(Sample_Included(i_Sample)) THEN
IF((iBinL > 0) &
& .AND. (iBinL <= N_L)) TabHistLogL(i_Sample, iBinL) = TabHistLogL(i_Sample, iBinL) + Prob_det(i_Sample)
IF(iBinz > 0) TabHistz(i_Sample, iBinz) = TabHistz(i_Sample, iBinz) + Prob_det(i_Sample)
IF(iBinEp > 0) TabHistLogEp(i_Sample, iBinEp) = TabHistLogEp(i_Sample, iBinEp) + Prob_det(i_Sample)
IF(iBinEpobs > 0) TabHistLogEpobs(i_Sample, iBinEpobs) = TabHistLogEpobs(i_Sample, iBinEpobs) + Prob_det(i_Sample)
IF(iBina > 0) TabHistalpha(i_Sample, iBina) = TabHistalpha(i_Sample, iBina) + Prob_det(i_Sample)
IF(iBinb > 0) TabHistbeta(i_Sample, iBinb) = TabHistbeta(i_Sample, iBinb) + Prob_det(i_Sample)
IF (i_Sample >= 1) THEN
IF(iBinPeakflux(i_Sample) > 0) TabHistLogP(i_Sample, iBinPeakflux(i_Sample)) = TabHistLogP(i_Sample, iBinPeakflux(i_Sample)) + Prob_det(i_Sample)
END IF
END IF
END DO
END SUBROUTINE Fill_Histogram_Prop
SUBROUTINE Fill_Histogram_Chi2()
INTEGER :: imin, imax, j
! Comparison with Kommers et al. 2000
IF(Constraint_Included(Constraint_Kommers)) THEN
IF ( ( LOG10(Peakflux(Sample_Kommers)) < TabKomm_LogP23(0) ) .OR. ( LOG10(Peakflux(Sample_Kommers)) >= TabKomm_LogP23(N_Komm) ) ) THEN
iBinKomm = -1
ELSE
imin = 1
imax = N_Komm
DO
j = (imin+imax)/2
IF ( LOG10(Peakflux(Sample_Kommers)) >= TabKomm_LogP23(j) ) THEN
imin = j+1
ELSE IF ( LOG10(Peakflux(Sample_Kommers)) < TabKomm_LogP23(j-1) ) THEN
imax = j
ELSE
EXIT
END IF
END DO
iBinKomm = j
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinKomm =", iBinKomm
END IF
! Comparison with Preece
IF(Constraint_Included(Constraint_Preece)) THEN
IF ( ( Epobs < TabPreece_Ep(0) ) .OR. ( Epobs >= TabPreece_Ep(N_Preece) ) ) THEN
iBinPreece = -1
ELSE
imin = 1
imax = N_Preece
DO
j = (imin+imax)/2
IF ( Epobs >= TabPreece_Ep(j) ) THEN
imin = j+1
ELSE IF ( Epobs < TabPreece_Ep(j-1) ) THEN
imax = j
ELSE
EXIT
END IF
END DO
iBinPreece = j
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinPreece =", iBinPreece
END IF
! Comparison with Stern
IF(Constraint_Included(Constraint_Stern)) THEN
IF ( ( Peakflux(Sample_Stern) < TabStern_P23(0) ) .OR. ( Peakflux(Sample_Stern) >= TabStern_P23(N_Stern) ) ) THEN
iBinStern = -1
ELSE
imin = 1
imax = N_Stern
DO
j = (imin+imax)/2
IF ( Peakflux(Sample_Stern) >= TabStern_P23(j) ) THEN
imin = j+1
ELSE IF ( Peakflux(Sample_Stern) < TabStern_P23(j-1) ) THEN
imax = j
ELSE
EXIT
END IF
END DO
iBinStern = j
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinStern =", iBinStern
END IF
! Comparison with XRFHETE2
IF(Constraint_Included(Constraint_HETE2)) THEN
NGRB_HETE2 = NGRB_HETE2 + Prob_det(Sample_HETE2)
softness = F_12(L, z, Ep, D_L, alpha, beta, ktild, TabEmin(Instrument_WXM), 30.d0) /&
& F_12(L, z, Ep, D_L, alpha, beta, ktild, TabEmin(Instrument_FREGATE), TabEmax(Instrument_FREGATE))
IF (ISNAN(softness)) NaNtest_prop = .TRUE.
!TabEmax(Instrument_WXM) remember to replace it
! PRINT*, "softness =", softness
IF( softness > 1.d0) THEN
NGRB_XRFHETE2 = NGRB_XRFHETE2 + Prob_det(Sample_HETE2)
END IF
END IF
! Comparison with GBM Ep distribution from Gruber et al. 2014 catalog
IF(Constraint_Included(Constraint_EpGBM)) THEN
IF( Epobs < TabEpGBM_Epobs(0) .OR. Epobs >= TabEpGBM_Epobs(N_EpGBM) ) THEN
iBinEpGBM = -1
ELSE
imin = 1
imax = N_EpGBM
DO
j = (imin+imax)/2
IF ( Epobs >= TabEpGBM_Epobs(j) ) THEN
imin = j+1
ELSE IF ( Epobs < TabEpGBM_Epobs(j-1) ) THEN
imax = j
ELSE
EXIT
END IF
END DO
iBinEpGBM = j
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinEpGBM =", iBinEpGBM
END IF
! Comparison with eBAT6 redshift distribution from Pescalli et al. 2016
IF(Constraint_Included(Constraint_eBAT6)) THEN
IF( z < TabeBAT6_z(0) .OR. z >= TabeBAT6_z(N_eBAT6) ) THEN
iBineBAT6 = -1
ELSE
iBineBAT6 = INT( z / TabeBAT6_z(N_eBAT6) * REAL(N_eBAT6,8) ) + 1
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBineBAT6 =", iBineBAT6
END IF
! --- Simulated observations for comparison with real observations --- !
! --------------------------- Fill histograms ------------------------ !
IF(Constraint_Included(Constraint_Kommers)) THEN
IF (iBinKomm > 0) TabHistKomm_P23(iBinKomm) = TabHistKomm_P23(iBinKomm) + Prob_det(Sample_Kommers)
END IF
IF(Constraint_Included(Constraint_Stern)) THEN
IF (iBinStern > 0) TabHistStern_P23(iBinStern) = TabHistStern_P23(iBinStern) + Prob_det(Sample_Stern)
END IF
IF(Constraint_Included(Constraint_Preece)) THEN
IF (iBinPreece > 0) TabHistPreece_Ep(iBinPreece) = TabHistPreece_Ep(iBinPreece) + Prob_det(Sample_Preece)
END IF
IF(Constraint_Included(Constraint_EpGBM)) THEN
IF (iBinEpGBM > 0) TabHistEpGBM_Epobs(iBinEpGBM) = TabHistEpGBM_Epobs(iBinEpGBM) + Prob_det(Sample_EpGBM)
END IF
IF(Constraint_Included(Constraint_eBAT6)) THEN
IF (iBineBAT6 > 0) TabHisteBAT6_z(iBineBAT6) = TabHisteBAT6_z(iBineBAT6) + Prob_det(Sample_eBAT6)
END IF
END SUBROUTINE Fill_Histogram_Chi2
SUBROUTINE Fill_Samples()
INTEGER :: imin, imax, j
! Comparison with Kommers et al. 2000
IF(Sample_Included(Sample_Kommers) .AND. .NOT.(Constraint_Included(Constraint_Kommers))) THEN
IF ( ( LOG10(Peakflux(Sample_Kommers)) < TabKomm_LogP23(0) ) .OR. ( LOG10(Peakflux(Sample_Kommers)) >= TabKomm_LogP23(N_Komm) ) ) THEN
iBinKomm = -1
ELSE
imin = 1
imax = N_Komm
DO
j = (imin+imax)/2
IF ( LOG10(Peakflux(Sample_Kommers)) >= TabKomm_LogP23(j) ) THEN
imin = j+1
ELSE IF ( LOG10(Peakflux(Sample_Kommers)) < TabKomm_LogP23(j-1) ) THEN
imax = j
ELSE
EXIT
END IF
END DO
iBinKomm = j
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinKomm =", iBinKomm
END IF
! Comparison with Preece
IF(Sample_Included(Sample_Preece) .AND. .NOT.(Constraint_Included(Constraint_Preece))) THEN
IF ( ( Epobs < TabPreece_Ep(0) ) .OR. ( Epobs >= TabPreece_Ep(N_Preece) ) ) THEN
iBinPreece = -1
ELSE
imin = 1
imax = N_Preece
DO
j = (imin+imax)/2
IF ( Epobs >= TabPreece_Ep(j) ) THEN
imin = j+1
ELSE IF ( Epobs < TabPreece_Ep(j-1) ) THEN
imax = j
ELSE
EXIT
END IF
END DO
iBinPreece = j
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinPreece =", iBinPreece
END IF
! Comparison with Stern
IF(Sample_Included(Sample_Stern) .AND. .NOT.(Constraint_Included(Constraint_Stern))) THEN
IF ( ( Peakflux(Sample_Stern) < TabStern_P23(0) ) .OR. ( Peakflux(Sample_Stern) >= TabStern_P23(N_Stern) ) ) THEN
iBinStern = -1
ELSE
imin = 1
imax = N_Stern
DO
j = (imin+imax)/2
IF ( Peakflux(Sample_Stern) >= TabStern_P23(j) ) THEN
imin = j+1
ELSE IF ( Peakflux(Sample_Stern) < TabStern_P23(j-1) ) THEN
imax = j
ELSE
EXIT
END IF
END DO
iBinStern = j
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinStern =", iBinStern
END IF
! Comparison with XRFHETE2
IF(Sample_Included(Sample_HETE2) .AND. .NOT.(Constraint_Included(Constraint_HETE2))) THEN
NGRB_HETE2 = NGRB_HETE2 + Prob_det(Sample_HETE2)
softness = F_12(L, z, Ep, D_L, alpha, beta, ktild, TabEmin(Instrument_WXM), 30.d0) /&
& F_12(L, z, Ep, D_L, alpha, beta, ktild, TabEmin(Instrument_FREGATE), TabEmax(Instrument_FREGATE))
IF (ISNAN(softness)) NaNtest_prop = .TRUE.
!TabEmax(Instrument_WXM) remember to replace it
! PRINT*, "softness =", softness
IF( softness > 1.d0) THEN
NGRB_XRFHETE2 = NGRB_XRFHETE2 + Prob_det(Sample_HETE2)
END IF
END IF
! Comparison with GBM Ep distribution from Gruber et al. 2014 catalog
IF(Sample_Included(Sample_EpGBM) .AND. .NOT.(Constraint_Included(Constraint_EpGBM))) THEN
IF( Epobs < TabEpGBM_Epobs(0) .OR. Epobs >= TabEpGBM_Epobs(N_EpGBM) ) THEN
iBinEpGBM = -1
ELSE
imin = 1
imax = N_EpGBM
DO
j = (imin+imax)/2
IF ( Epobs >= TabEpGBM_Epobs(j) ) THEN
imin = j+1
ELSE IF ( Epobs < TabEpGBM_Epobs(j-1) ) THEN
imax = j
ELSE
EXIT
END IF
END DO
iBinEpGBM = j
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBinEpGBM =", iBinEpGBM
END IF
! Comparison with z distribution from Pescalli et al. 2016
IF(Sample_Included(Sample_eBAT6) .AND. .NOT.(Constraint_Included(Constraint_eBAT6))) THEN
IF( z < TabeBAT6_z(0) .OR. z >= TabeBAT6_z(N_eBAT6) ) THEN
iBineBAT6 = -1
ELSE
iBineBAT6 = INT( z / TabeBAT6_z(N_eBAT6) * REAL(N_eBAT6,8) ) + 1
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBineBAT6 =", iBineBAT6
END IF
! --- Simulated observations for comparison with real observations --- !
! --------------------------- Fill histograms ------------------------ !
IF(Sample_Included(Sample_Kommers) .AND. .NOT.(Constraint_Included(Constraint_Kommers))) THEN
IF (iBinKomm > 0) TabHistKomm_P23(iBinKomm) = TabHistKomm_P23(iBinKomm) + Prob_det(Sample_Kommers)
END IF
IF(Sample_Included(Sample_Stern) .AND. .NOT.(Constraint_Included(Constraint_Stern))) THEN
IF (iBinStern > 0) TabHistStern_P23(iBinStern) = TabHistStern_P23(iBinStern) + Prob_det(Sample_Stern)
END IF
IF(Sample_Included(Sample_Preece) .AND. .NOT.(Constraint_Included(Constraint_Preece))) THEN
IF (iBinPreece > 0) TabHistPreece_Ep(iBinPreece) = TabHistPreece_Ep(iBinPreece) + Prob_det(Sample_Preece)
END IF
IF(Sample_Included(Sample_EpGBM) .AND. .NOT.(Constraint_Included(Constraint_EpGBM))) THEN
IF (iBinEpGBM > 0) TabHistEpGBM_Epobs(iBinEpGBM) = TabHistEpGBM_Epobs(iBinEpGBM) + Prob_det(Sample_EpGBM)
END IF
IF(Sample_Included(Sample_eBAT6) .AND. .NOT.(Constraint_Included(Constraint_eBAT6))) THEN
IF (iBineBAT6 > 0) TabHisteBAT6_z(iBineBAT6) = TabHisteBAT6_z(iBineBAT6) + Prob_det(Sample_eBAT6)
END IF
CALL Fill_eBAT6()
END SUBROUTINE Fill_Samples
SUBROUTINE Fill_eBAT6()
INTEGER :: imin, imax, j
! Comparison with Ep-L plane for the eBAT6 sample from Pescalli et al. 2016
IF(Sample_Included(Sample_eBAT6)) THEN
IF(hist_flag == 2) THEN
! Ep
IF( Ep < TabeBAT6_EpL(Indice_Ep,0) .OR. Ep >= TabeBAT6_EpL(Indice_Ep,N_eBAT6_EpL) ) THEN
iBineBAT6_Ep = -1
ELSE
iBineBAT6_Ep = INT( ( LOG10(Ep)-LOG10(TabeBAT6_EpL(Indice_Ep,0)) ) / ( LOG10(TabeBAT6_EpL(Indice_Ep,N_eBAT6_EpL))-LOG10(TabeBAT6_EpL(Indice_Ep,0)) ) * REAL(N_eBAT6_EpL,8) ) + 1
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBineBAT6_Ep =", iBineBAT6_Ep
! L
IF( L < TabeBAT6_EpL(Indice_L,0) .OR. L >= TabeBAT6_EpL(Indice_L,N_eBAT6_EpL) ) THEN
iBineBAT6_L = -1
ELSE
iBineBAT6_L = INT( ( LOG10(L)- LOG10(TabeBAT6_EpL(Indice_L,0)) ) / ( LOG10(TabeBAT6_EpL(Indice_L,N_eBAT6_EpL))-LOG10(TabeBAT6_EpL(Indice_L,0)) ) * REAL(N_eBAT6_EpL,8) ) + 1
END IF
IF (verbose == 2) WRITE(*,'(A,I3)') " iBineBAT6_L =", iBineBAT6_L
IF((iBineBAT6_L > 0) .AND. (iBineBAT6_Ep > 0)) TabHisteBAT6_EpL(iBineBAT6_Ep, iBineBAT6_L) = TabHisteBAT6_EpL(iBineBAT6_Ep, iBineBAT6_L) + Prob_det(Sample_eBAT6)
END IF
END IF
END SUBROUTINE Fill_eBAT6
SUBROUTINE Normalize_Model()
! Calculate normalization coefficients
REAL(8) :: x1,x2, x1_forlnL, x2_forlnL
INTEGER :: i
!dof = 0
Chi2 = 0.d0
! Kommers et al. 2000
IF(Sample_Included(Sample_Kommers)) THEN
x1 = 0.d0
x2 = 0.d0
DO i=1, N_Komm
! Simulated rate and rate error
TabHistKomm_DRDP(i) = TabHistKomm_P23_master(i) / ( REAL(Nb_GRB,8) * ( TabKomm_P23(i)-TabKomm_P23(i-1) ) )
TabHistKomm_DRDPerr(i) = SQRT(TabHistKomm_P23_master(i)) / ( REAL(Nb_GRB,8) * ( TabKomm_P23(i)-TabKomm_P23(i-1) ) )
! Note : error is SQRT(N) because of Poisson statistics
x1 = x1 + TabHistKomm_DRDP(i) * TabKomm_DRDPobs(i) / TabKomm_DRDPobserr(i)**2
x2 = x2 + TabHistKomm_DRDP(i)**2 / TabKomm_DRDPobserr(i)**2
END DO
IF(ISNAN(x1)) NaNtest_hist = .TRUE.
IF(ISNAN(x2)) NaNtest_hist = .TRUE.
k_Kommers = x1 / x2
IF (ISNAN(k_Kommers)) NaNtest_hist = .TRUE.
TabHistKomm_DRDP = TabHistKomm_DRDP * k_Kommers ! Normalize
TabHistKomm_DRDPerr = TabHistKomm_DRDPerr * k_Kommers
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Kommers data) : k_Kommers =", k_Kommers/(4.d0*Pi), " yr-1 ]"
END IF
! Preece
IF(Sample_Included(Sample_Preece)) THEN
x1 = 0.d0
x2 = 0.d0
DO i=1, N_Preece
x1 = x1 + TabHistPreece_Ep_master(i) * TabHistPreece_Epobs(i) / (TabHistPreece_Epobserr(i)**2)
x2 = x2 + TabHistPreece_Ep_master(i)**2 / (TabHistPreece_Epobserr(i)**2)
END DO
IF(x2 .NE. 0.d0) THEN
k_Preece = x1 / x2
ELSE
k_Preece = 0.d0
Chi2(Constraint_Preece) = 1.d20
END IF
IF (ISNAN(k_Preece)) NaNtest_hist = .TRUE.
TabHistPreece_Ep_master = TabHistPreece_Ep_master * k_Preece ! Normalize
TabHistPreece_Eperr = TabHistPreece_Eperr * k_Preece
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Preece data) : k_Preece =", k_Preece, " ]"
END IF
! Stern
IF(Sample_Included(Sample_Stern)) THEN
x1 = 0.d0
x2 = 0.d0
x1_forlnL = 0.d0
x2_forlnL = 0.d0
! Save a record of Stern hist from model as dN to use in likelihood
TabHistStern_P23_forlnL = TabHistStern_P23_master
DO i=1, N_Stern
TabHistStern_P23err(i) = SQRT(TabHistStern_P23_master(i)) / ( LOG10(TabStern_P23(i)/TabStern_P23(i-1)) )
TabHistStern_P23_master(i) = TabHistStern_P23_master(i) / ( LOG10(TabStern_P23(i)/TabStern_P23(i-1)) )
IF(TabHistStern_P23obserr(i) > 0.d0) THEN
x1 = x1 + (TabHistStern_P23obs(i) * TabHistStern_P23_master(i)) / (TabHistStern_P23obserr(i)**2)
x2 = x2 + (TabHistStern_P23_master(i) / TabHistStern_P23obserr(i) )**2
END IF
! Transform Stern from dN/(dlogP * useful_time) to dN for use in likelihood
TabHistStern_P23obs_forlnL(i) = TabHistStern_P23obs(i) * ( LOG10(TabStern_P23(i)/TabStern_P23(i-1)) ) * Delta_t_Stern * Omega_div_4Pi
TabHistStern_P23obserr_forlnL(i) = TabHistStern_P23obserr(i) * ( LOG10(TabStern_P23(i)/TabStern_P23(i-1)) ) * Delta_t_Stern * Omega_div_4Pi
IF(TabHistStern_P23obserr_forlnL(i) > 0.d0) THEN
x1_forlnL = x1_forlnL + (TabHistStern_P23obs_forlnL(i) * TabHistStern_P23_forlnL(i)) / (TabHistStern_P23obserr_forlnL(i)**2)
x2_forlnL = x2_forlnL + (TabHistStern_P23_forlnL(i) / TabHistStern_P23obserr_forlnL(i) )**2
END IF
END DO
k_Stern = x1 / x2
k_Stern_forlnL = x1_forlnL / x2_forlnL
!k_Stern = 10.**(x1 / x2)
!IF (run_mode == one_run) THEN
IF (ISNAN(k_Stern)) NaNtest_hist = .TRUE.
IF (ISNAN(k_Stern_forlnL)) NaNtest_hist = .TRUE.
!END IF
IF (ISNAN(k_Stern)) k_Stern = 1.d20
TabHistStern_P23_master = TabHistStern_P23_master * k_Stern
TabHistStern_P23err = TabHistStern_P23err * k_Stern
TabHistStern_P23_forlnL = TabHistStern_P23_forlnL * k_Stern_forlnL
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Stern data) : k_Stern =", k_Stern ,' yr-1 ]'
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Stern data) : Sim duration =", 1.d0/k_Stern ,' yr ]'
! IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Stern data) : eta_0 =", k_Stern*Nb_GRB/pseudo_collapse_rate, " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Stern data) : R_GRB/R_coll =", k_stern*Nb_GRB/collapse_rate_from_SFR , " yr ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Stern data) : n_GRB normalization =", k_stern*Nb_GRB / pseudo_collapse_rate, " GRB/yr ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Stern data) : Pseudo collapse rate =", pseudo_collapse_rate, " collapse/yr ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From BATSE23 (Stern data) : Real GRB rate =", k_stern*Nb_GRB, " GRB/yr ]"
END IF
! XRF HETE2
IF(Sample_Included(Sample_HETE2)) THEN
IF(NGRB_HETE2 > 0.d0) THEN
Frac_XRFHETE2 = NGRB_XRFHETE2 / NGRB_HETE2
ELSE
Frac_XRFHETE2 = 0.d0
Chi2(Constraint_HETE2) = 1.d20
END IF
!IF (run_mode == one_run) THEN
IF (ISNAN(Frac_XRFHETE2)) NaNtest_hist = .TRUE.
!END IF
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From HETE2 : Frac_XRFHETE2 =", Frac_XRFHETE2,' ]'
END IF
! GBM Ep catalog (from Gruber et al. 2014)
IF(Sample_Included(Sample_EpGBM)) THEN
x1 = 0.d0
x2 = 0.d0
DO i=1, N_EpGBM
TabHistEpGBM_Epobserr(i) = SQRT(TabHistEpGBM_Epobs_master(i))
! Note : error is SQRT(N) because of Poisson statistics
x1 = x1 + TabHistEpGBM_Epobs_master(i) * TabHistEpGBM_Epobsobs(i) / TabHistEpGBM_Epobsobserr(i)**2
x2 = x2 + TabHistEpGBM_Epobs_master(i)**2 / TabHistEpGBM_Epobsobserr(i)**2
END DO
!PRINT*, " x1, x2 = ",x1,x2
IF(x2 > 0.d0) THEN
k_EpGBM = x1 / x2
ELSE
!PRINT*, "GBM sample is empty..."
k_EpGBM = 0.d0
END IF
IF (ISNAN(k_EpGBM)) NaNtest_hist = .TRUE.
TabHistEpGBM_Epobs_master = TabHistEpGBM_Epobs_master * k_EpGBM ! Normalize
TabHistEpGBM_Epobserr = TabHistEpGBM_Epobserr * k_EpGBM
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From GBM (Gruber data) : normalization =", k_EpGBM, " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From GBM (Gruber data) : GBM efficiency =", k_EpGBM/(k_Stern*Delta_t_EpGBM), " ]"
END IF
! eBAT6 redshift distribution (from Pescalli et al. 2016)
IF(Sample_Included(Sample_eBAT6)) THEN
x1 = 0.d0
x2 = 0.d0
DO i=1, N_eBAT6
! Note : error is SQRT(N) because of Poisson statistics
x1 = x1 + TabHisteBAT6_z_master(i) * TabHisteBAT6_zobs(i)
x2 = x2 + TabHisteBAT6_z_master(i)**2
END DO
!PRINT*, " x1, x2 = ",x1,x2
IF(x2 > 0.d0) THEN
k_eBAT6 = x1 / x2
ELSE
k_eBAT6 = 0.d0
END IF
IF (ISNAN(k_eBAT6)) NaNtest_hist = .TRUE.
TabHisteBAT6_zerr = SQRT(TabHisteBAT6_z_master)
TabHisteBAT6_z_master = TabHisteBAT6_z_master * k_eBAT6 ! Normalize
TabHisteBAT6_zerr = TabHisteBAT6_zerr * k_eBAT6
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From eBAT6 (Pescalli data) : normalization =", k_eBAT6, " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ From eBAT6 (Pescalli data) : eBAT6 efficiency =", k_eBAT6/(k_Stern*Delta_t_eBAT6), " ]"
END IF
IF(run_mode == one_run) WRITE(*,'(A)') "[ ------------------------------------------------------------------------------------------------- ]"
!IF (run_mode == one_run) THEN
IF (ISNAN(k_Stern)) NaNtest_hist = .TRUE.
!END IF
IF (NaNtest_hist) THEN
WRITE(*,*) "[ k_Kommers k_Stern k_Preece Frac_XRFHETE2 k_EpGBM k_eBAT6 ]"
WRITE(*,*) "[ ", k_Kommers, k_Stern, k_Preece, Frac_XRFHETE2, k_EpGBM, k_eBAT6, " ]"
WRITE(*,*) "[ TabHistKomm ]"
WRITE(*,*) TabHistKomm_DRDP
WRITE(*,*) "[ TabHistStern ]"
WRITE(*,*) TabHistStern_P23
WRITE(*,*) "[ TabHistPreece ]"
WRITE(*,*) TabHistPreece_Ep
WRITE(*,*) "[ TabHistEpGBM ]"
WRITE(*,*) TabHistEpGBM_Epobs
WRITE(*,*) "[ TabHisteBAT6 ]"
WRITE(*,*) TabHisteBAT6_z
END IF
END SUBROUTINE Normalize_Model
SUBROUTINE Calculate_Chi2()
INTEGER :: i
IF(Constraint_Included(Constraint_Kommers)) THEN
DO i=1, N_Komm
Chi2(Constraint_Kommers) = Chi2(Constraint_Kommers) + ( (TabHistKomm_DRDP(i) - TabKomm_DRDPobs(i)) / TabKomm_DRDPobserr(i) )**2
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ Chi2_Kommers = ", Chi2(Constraint_Kommers), " ]"
END IF
IF(Constraint_Included(Constraint_Preece)) THEN
DO i=1, N_Preece
IF(TabHistPreece_Epobserr(i) > 0.d0) THEN
Chi2(Constraint_Preece) = Chi2(Constraint_Preece) + ( (TabHistPreece_Ep_master(i) - TabHistPreece_Epobs(i)) / TabHistPreece_Epobserr(i) )**2
! WRITE(*,*) "i, DN-DNobs, err, Chi2 :", i, (TabHistPreece_Ep(i) - TabHistPreece_Epobs(i)), TabHistPreece_Epobserr(i), Chi2(Constraint_Preece)
END IF
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ Chi2_Preece = ", Chi2(Constraint_Preece), " ]"
END IF
IF(Constraint_Included(Constraint_Stern)) THEN
DO i=1, N_Stern
IF(TabHistStern_P23obserr(i) > 0.d0) THEN
Chi2(Constraint_Stern) = Chi2(Constraint_Stern) + ( (TabHistStern_P23_master(i)-TabHistStern_P23obs(i)) / TabHistStern_P23obserr(i) )**2
END IF
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ Chi2_Stern = ", Chi2(Constraint_Stern), " ]"
END IF
IF(Constraint_Included(Constraint_HETE2)) THEN
Chi2(Constraint_HETE2) = ( (Frac_XRFHETE2 - Frac_XRFHETE2obs) / sigma_XRFHETE2obs )**2
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ Chi2_XRFHETE2 = ", Chi2(Constraint_HETE2), " ]"
END IF
IF(Constraint_Included(Constraint_EpGBM)) THEN
DO i=1, N_EpGBM
IF(TabHistEpGBM_Epobsobserr(i) > 0.d0) THEN
Chi2(Constraint_EpGBM) = Chi2(Constraint_EpGBM) + ( (TabHistEpGBM_Epobs_master(i) - TabHistEpGBM_Epobsobs(i)) / TabHistEpGBM_Epobsobserr(i) )**2
END IF
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ Chi2_EpGBM = ", Chi2(Constraint_EpGBM), " ]"
END IF
IF(Constraint_Included(Constraint_eBAT6)) THEN
DO i=1, N_eBAT6
IF(TabHisteBAT6_zobserr(i) > 0.d0) THEN
Chi2(Constraint_eBAT6) = Chi2(Constraint_eBAT6) + ( (TabHisteBAT6_z_master(i) - TabHisteBAT6_zobs(i)) / TabHisteBAT6_zobserr(i) )**2
END IF
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.2,A)') "[ (ignoring empty bins) Chi2_eBAT6 = ", Chi2(Constraint_eBAT6), " ]"
END IF
Chi2(0) = SUM(Chi2)
END SUBROUTINE Calculate_Chi2
SUBROUTINE Calculate_unnormalized_Likelihood()
INTEGER :: i
lnL = 0.d0
IF(Constraint_Included(Constraint_Kommers)) THEN
DO i=1, N_Komm
lnL(Constraint_Kommers) = lnL(Constraint_Kommers) + (TabKomm_DRDPobs(i)+epsilon) * LOG(TabHistKomm_DRDP(i)+epsilon)&
& - (TabHistKomm_DRDP(i)+epsilon)
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ lnL_Kommers = ", lnL(Constraint_Kommers), " ]"
END IF
IF(Constraint_Included(Constraint_Preece)) THEN
DO i=1, N_Preece
lnL(Constraint_Preece) = lnL(Constraint_Preece) + (TabHistPreece_Epobs(i)+epsilon) * LOG(TabHistPreece_Ep_master(i)+epsilon) - (TabHistPreece_Ep_master(i)+epsilon)
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ lnL_Preece = ", lnL(Constraint_Preece), " ]"
END IF
IF(Constraint_Included(Constraint_Stern)) THEN
lnL_max_test = 0.d0
lnL_empty_test = 0.d0
DO i=1, N_Stern
lnL(Constraint_Stern) = lnL(Constraint_Stern) + (TabHistStern_P23obs_forlnL(i)+epsilon) * LOG((TabHistStern_P23_forlnL(i)+epsilon)) &
& - (TabHistStern_P23_forlnL(i)+epsilon)
lnL_max_test(Constraint_Stern) = lnL_max_test(Constraint_Stern) + (TabHistStern_P23obs_forlnL(i)+epsilon) * LOG((TabHistStern_P23obs_forlnL(i)+epsilon)) &
& - (TabHistStern_P23obs_forlnL(i)+epsilon)
lnL_empty_test(Constraint_Stern) = lnL_empty_test(Constraint_Stern) + (TabHistStern_P23obs_forlnL(i)+epsilon) * LOG((epsilon)) &
& - (epsilon)
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ lnL_Stern = ", lnL(Constraint_Stern), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ max lnL_Stern = ", lnL_max_test(Constraint_Stern), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ empty lnL_Stern = ", lnL_empty_test(Constraint_Stern), " ]"
END IF
IF(Constraint_Included(Constraint_HETE2)) THEN ! Not modified from Chi2, this has no meaning !!
lnL(Constraint_HETE2) = ( (Frac_XRFHETE2 - Frac_XRFHETE2obs) / sigma_XRFHETE2obs )**2
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ no meaning !!!!! lnL_XRFHETE2 = ", lnL(Constraint_HETE2), " ]"
END IF
IF(Constraint_Included(Constraint_EpGBM)) THEN
DO i=1, N_EpGBM
lnL(Constraint_EpGBM) = lnL(Constraint_EpGBM) + (TabHistEpGBM_Epobsobs(i)+epsilon) * LOG((TabHistEpGBM_Epobs_master(i)+epsilon))&
& - (TabHistEpGBM_Epobs_master(i)+epsilon)
lnL_max_test(Constraint_EpGBM) = lnL_max_test(Constraint_EpGBM) + (TabHistEpGBM_Epobsobs(i)+epsilon) * LOG((TabHistEpGBM_Epobsobs(i)+epsilon))&
& - (TabHistEpGBM_Epobsobs(i)+epsilon)
lnL_empty_test(Constraint_EpGBM) = lnL_empty_test(Constraint_EpGBM) + (TabHistEpGBM_Epobsobs(i)+epsilon) * LOG(epsilon)&
& - (epsilon)
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ lnL_EpGBM = ", lnL(Constraint_EpGBM), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ max lnL_EpGBM = ", lnL_max_test(Constraint_EpGBM), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ empty lnL_EpGBM = ", lnL_empty_test(Constraint_EpGBM), " ]"
END IF
IF(Constraint_Included(Constraint_eBAT6)) THEN
lnL_weight(Constraint_eBAT6) = 10.d0
DO i=1, N_eBAT6
lnL(Constraint_eBAT6) = lnL(Constraint_eBAT6) + (TabHisteBAT6_zobs(i)+epsilon) * LOG((TabHisteBAT6_z_master(i)+epsilon))&
& - (TabHisteBAT6_z_master(i)+epsilon)
lnL_max_test(Constraint_eBAT6) = lnL_max_test(Constraint_eBAT6) + (TabHisteBAT6_zobs(i)+epsilon) * LOG((TabHisteBAT6_zobs(i)+epsilon))&
& - (TabHisteBAT6_zobs(i)+epsilon)
lnL_empty_test(Constraint_eBAT6) = lnL_empty_test(Constraint_eBAT6) + (TabHisteBAT6_zobs(i)+epsilon) * LOG(epsilon)&
& - (epsilon)
END DO
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ lnL_eBAT6 = ", lnL(Constraint_eBAT6) * lnL_weight(Constraint_eBAT6), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ max lnL_eBAT6 = ", lnL_max_test(Constraint_eBAT6) * lnL_weight(Constraint_eBAT6), " ]"
IF(run_mode == one_run) WRITE(*,'(A,ES12.5,A)') "[ empty lnL_eBAT6 = ", lnL_empty_test(Constraint_eBAT6) * lnL_weight(Constraint_eBAT6), " ]"
END IF
lnL(0) = SUM(lnL*lnL_weight)
lnL_max_test(0) = SUM(lnL_max_test*lnL_weight)
lnL_empty_test(0) = SUM(lnL_empty_test*lnL_weight)
END SUBROUTINE Calculate_unnormalized_Likelihood
SUBROUTINE Save_Histograms()
INTEGER :: i, i_Sample
REAL(8) :: xtemp ! TEMPPPPPP
! --- Luminosity --- !
DO i_Sample = 0, N_Samples
IF(Sample_Included(i_Sample))THEN
IF (Lsave(i_Sample)) THEN
OPEN( UNIT=100, FILE=TRIM(LFile(i_Sample))//".dat" )
DO i=1, N_L
! Turn histogram into Lmin * p(L)
IF (Model_Lum == Model_LumFix) THEN
TabHistLogL_master(i_Sample, i) = TabParam_Lum(Param_Lum_L0) * TabHistLogL_master(i_Sample,i) / ( REAL(Nb_GRB,8) * ( 10**(TabLogL(i)) - 10**(TabLogL(i-1)) ) )
ELSE
TabHistLogL_master(i_Sample, i) = TabParam_Lum(Param_Lum_Lmin) * TabHistLogL_master(i_Sample,i) / ( REAL(Nb_GRB,8) * ( 10**(TabLogL(i)) - 10**(TabLogL(i-1)) ) )
END IF
! 1 2
! [Log(L)] [Lmin*p(L)]
WRITE(100, '(2ES12.5)') TabLogL(i-1), TabHistLogL_master(i_Sample, i)
WRITE(100, '(2ES12.5)') TabLogL(i), TabHistLogL_master(i_Sample, i)
END DO
CLOSE(100)
END IF
END IF
END DO
! ----- Redshift ----- !
DO i_Sample = 0, N_Samples
IF(Sample_Included(i_Sample))THEN
IF (zsave(i_Sample)) THEN
OPEN( UNIT=110, FILE=TRIM(zFile(i_Sample))//".dat" )
OPEN( UNIT=111, FILE=TRIM(zFile_cumul(i_Sample))//".dat" )
xtemp = 0.d0
WRITE(111, '(2ES12.5)') Tabz(0), xtemp
DO i=1, N_z
xtemp = xtemp + TabHistz_master(i_Sample, i)
WRITE(111, '(2ES12.5)') Tabz(i), xtemp
! Normalize
TabHistz_master(i_Sample, i) = TabHistz_master(i_Sample, i) / ( REAL(Nb_GRB,8) * (Tabz(i) - Tabz(i-1)) )
! 1 2
! [z] [z pdf]
WRITE(110, '(2ES12.5)') Tabz(i-1), TabHistz_master(i_Sample, i)
WRITE(110, '(2ES12.5)') Tabz(i), TabHistz_master(i_Sample, i)
END DO
CLOSE(111)
CLOSE(110)
END IF
END IF
END DO
! ----- Peak Energy ----- !
DO i_Sample = 0, N_Samples
IF(Sample_Included(i_Sample))THEN
IF (Epsave(i_Sample)) THEN
OPEN( UNIT=120, FILE=TRIM(EpFile(i_Sample))//".dat" )
DO i=1, N_Ep
! Normalize
TabHistLogEp_master(i_Sample, i) = TabHistLogEp_master(i_Sample, i) / ( REAL(Nb_GRB,8) * (TabLogEp(i) - TabLogEp(i-1)) )
TabHistLogEpobs_master(i_Sample, i) = TabHistLogEpobs_master(i_Sample, i) / ( REAL(Nb_GRB,8) * (TabLogEp(i) - TabLogEp(i-1)) )
! 1 2 3
! [Ep] [Ep source pdf] [Ep obs pdf]
WRITE(120, '(3ES12.5)') TabLogEp(i-1), TabHistLogEp_master(i_Sample, i), TabHistLogEpobs_master(i_Sample, i)
WRITE(120, '(3ES12.5)') TabLogEp(i), TabHistLogEp_master(i_Sample, i), TabHistLogEpobs_master(i_Sample, i)
END DO
CLOSE(120)
END IF
END IF
END DO
! ----- Peak Flux ----- !
DO i_Sample = 1, N_Samples
IF (Psave(i_Sample)) THEN
IF(Sample_Included(i_Sample)) THEN
OPEN( UNIT=120, FILE=TRIM(PFile(i_Sample))//".dat" )
DO i=1, N_P
! Normalize
TabHistLogP_master(i_Sample, i) = TabHistLogP_master(i_Sample, i) / ( REAL(Nb_GRB,8) * (10**TabLogP(i) - 10**TabLogP(i-1)) )
! 1 2
! [P] [P pdf]
WRITE(120, '(2ES12.5)') TabLogP(i-1), TabHistLogP_master(i_Sample, i)
WRITE(120, '(2ES12.5)') TabLogP(i), TabHistLogP_master(i_Sample, i)
END DO
CLOSE(120)
END IF
END IF
END DO
! --- Spec alpha --- !
DO i_Sample = 0, N_Samples
IF(Sample_Included(i_Sample))THEN
IF (Specsave(i_Sample)) THEN
OPEN(UNIT=130, FILE=TRIM(SpecFile_a(i_Sample))//".dat" )
WRITE(130, '(2ES12.5)') TabSpec_a(0), 0.d0
DO i=1, N_spec_a
TabHistalpha_master(i_Sample, i) = TabHistalpha_master(i_Sample,i) / ( REAL(Nb_GRB,8) * ( TabSpec_a(i) - TabSpec_a(i-1) ) )
! 1 2
! [alpha] [alpha pdf]
WRITE(130, '(2ES12.5)') TabSpec_a(i-1), TabHistalpha_master(i_Sample, i)
WRITE(130, '(2ES12.5)') TabSpec_a(i), TabHistalpha_master(i_Sample, i)
END DO
CLOSE(130)
END IF
END IF
END DO
! --- Spec beta --- !
DO i_Sample = 0, N_Samples
IF(Sample_Included(i_Sample))THEN
IF (Specsave(i_Sample)) THEN
OPEN(UNIT=140, FILE=TRIM(SpecFile_b(i_Sample))//".dat" )
WRITE(140, '(2ES12.5)') TabSpec_b(0), 0.d0
DO i=1, N_spec_b
TabHistbeta_master(i_Sample, i) = TabHistbeta_master(i_Sample,i) / ( REAL(Nb_GRB,8) * ( TabSpec_b(i) - TabSpec_b(i-1) ) )
! 1 2
! [beta] [beta pdf]
WRITE(140, '(2ES12.5)') TabSpec_b(i-1), TabHistbeta_master(i_Sample, i)
WRITE(140, '(2ES12.5)') TabSpec_b(i), TabHistbeta_master(i_Sample, i)
END DO
CLOSE(140)
END IF
END IF
END DO
END SUBROUTINE Save_Histograms
SUBROUTINE Save_eBAT6()
CHARACTER(len=10) :: eBAT6_EpL_format = '( ES12.5)'
INTEGER :: i
WRITE(eBAT6_EpL_format(2:3), '(I2)') N_eBAT6_EpL + 2
IF(Sample_Included(Sample_eBAT6)) THEN
! redshift
!!$ DO i=2, N_eBAT6 ! start from 2 because ignore first bin
!!$ TabHisteBAT6_z_master(i) = TabHisteBAT6_z_master(i) + TabHisteBAT6_z_master(i-1)
!!$ END DO
!!$ OPEN( UNIT=309, FILE=TRIM(eBAT6File)//".dat" )
!!$
!!$ DO i=1, N_eBAT6
!!$ ! 1 2
!!$ ! [z] [number]
!!$ WRITE(309, '(2ES12.5)') TabeBAT6_z(i-1), TabHisteBAT6_z_master(i)
!!$ WRITE(309, '(2ES12.5)') TabeBAT6_z(i), TabHisteBAT6_z_master(i)
!!$ END DO
!!$ CLOSE(309)
! Ep-L plane
OPEN( UNIT=310, FILE=TRIM(eBAT6_EpLFile)//".dat" )
DO i=1, N_eBAT6_EpL
! 1 2 3
! [med_bin Ep] [med_bin L] [1D histogram(all_Ep, one_L)]
!WRITE(310, eBAT6_EpL_format) TabeBAT6_EpL(Indice_Ep, i),TabeBAT6_EpL(Indice_L, i), TabHisteBAT6_EpL_master(:,i)
WRITE(310, eBAT6_EpL_format) 0.5d0*(TabeBAT6_EpL(Indice_Ep, i) + TabeBAT6_EpL(Indice_Ep, i-1) ), 0.5d0*(TabeBAT6_EpL(Indice_L, i) + TabeBAT6_EpL(Indice_L, i-1)), TabHisteBAT6_EpL_master(:,i)
END DO
CLOSE(310)
END IF
END SUBROUTINE Save_eBAT6
SUBROUTINE Save_Constraints()
INTEGER :: i
! ---- P23 Kommers et al. 2000 ---- !
IF (Constraint_save(Constraint_Kommers)) THEN
OPEN(UNIT=200, FILE=TRIM(KommFile)//".dat")
OPEN(UNIT=2000, FILE=TRIM(KommErrorFile)//".dat")
DO i=1, N_Komm
! 1 2 3
! [Log(P23)] [DRDP hist BATSE23 model] [DRDP Kommers hist]
WRITE(200, '(3ES12.5)') TabKomm_LogP23(i-1), TabHistKomm_DRDP(i), TabKomm_DRDPobs(i)
WRITE(200, '(3ES12.5)') TabKomm_LogP23(i), TabHistKomm_DRDP(i), TabKomm_DRDPobs(i)
! 1 2 3 4 5
! [Log(P23)] [DRDP hist Kommers model] [Kommers model err] [DRDP hist Kommers obs] [DRDP hist Kommers obs err]
WRITE(2000, '(5ES12.5)') (TabKomm_LogP23(i-1)+TabKomm_LogP23(i))/2.d0,&
& TabHistKomm_DRDP(i), TabHistKomm_DRDPerr(i), TabKomm_DRDPobs(i), TabKomm_DRDPobserr(i)
END DO
CLOSE(200)
CLOSE(2000)
END IF
IF (Constraint_save(Constraint_Preece)) THEN
OPEN(UNIT=201, FILE=TRIM(PreeceFile)//".dat")
OPEN(UNIT=2001, FILE=TRIM(PreeceErrorFile)//".dat")
DO i=1, N_Preece
! 1 2 3
! [Log(Ep)] [Ep Hist model] [Ep Preece hist]
WRITE(201, '(3ES12.5)') TabPreece_LogEp(i-1), TabHistPreece_Ep_master(i), TabHistPreece_Epobs(i)
WRITE(201, '(3ES12.5)') TabPreece_LogEp(i), TabHistPreece_Ep_master(i), TabHistPreece_Epobs(i)
! 1 2 3 4 5
! [Log(Ep)] [Ep hist model] [Ep hist model err] [Ep Preece hist obs] [Ep Preece hist obs err]
WRITE(2001, '(5ES12.5)') (TabPreece_LogEp(i-1)+TabPreece_LogEp(i))/2.d0,&
& TabHistPreece_Ep_master(i), TabHistPreece_Eperr(i), TabHistPreece_Epobs(i), TabHistPreece_Epobserr(i)
END DO
CLOSE(201)
CLOSE(2001)
END IF
IF (Constraint_save(Constraint_Stern)) THEN
OPEN(UNIT=202, FILE=TRIM(SternFile)//".dat")
OPEN(UNIT=2002, FILE=TRIM(SternErrorFile)//".dat")
DO i=1, N_Stern
! 1 2 3
! [P23] [P23 Hist model] [P23 Stern hist]
WRITE(202, '(3ES12.5)') TabStern_P23(i-1), TabHistStern_P23_master(i), TabHistStern_P23obs(i)
WRITE(202, '(3ES12.5)') TabStern_P23(i), TabHistStern_P23_master(i), TabHistStern_P23obs(i)
! 1 2 3 4 5
! [P23] [P23 hist model] [P23 hist model err] [P23 Stern hist obs] [P23 Stern hist obs err]
WRITE(2002, '(5ES12.4)') SQRT(TabStern_P23(i-1)*TabStern_P23(i)),&
& TabHistStern_P23_master(i), TabHistStern_P23err(i), TabHistStern_P23obs(i), TabHistStern_P23obserr(i)
END DO
CLOSE(202)
CLOSE(2002)
END IF
IF (Constraint_save(Constraint_EpGBM)) THEN
OPEN(UNIT=203, FILE=TRIM(EpGBMFile)//".dat")
OPEN(UNIT=2003, FILE=TRIM(EpGBMErrorFile)//".dat")
DO i=1, N_EpGBM
! 1 2 3
! [Log(Ep)] [EpGBM model hist] [EpGBM obs hist]
WRITE(203, '(3ES12.5)') TabEpGBM_Epobs(i-1), TabHistEpGBM_Epobs_master(i), TabHistEpGBM_Epobsobs(i)
WRITE(203, '(3ES12.5)') TabEpGBM_Epobs(i), TabHistEpGBM_Epobs_master(i), TabHistEpGBM_Epobsobs(i)
! 1 2 3 4 5
! [Log(Ep)] [Ep hist model] [Ep hist model err] [Ep EpGBM hist obs] [Ep EpGBM hist obs err]
WRITE(2003, '(5ES12.5)') (TabEpGBM_Epobs(i-1)+TabEpGBM_Epobs(i))/2.d0,&
& TabHistEpGBM_Epobs_master(i), TabHistEpGBM_Epobserr(i), TabHistEpGBM_Epobsobs(i), TabHistEpGBM_Epobsobserr(i)
END DO
CLOSE(203)
CLOSE(2003)
END IF
IF (Constraint_save(Constraint_eBAT6)) THEN
OPEN(UNIT=204, FILE=TRIM(eBAT6File)//".dat")
OPEN(UNIT=2004, FILE=TRIM(eBAT6ErrorFile)//".dat")
DO i=1, N_eBAT6
! 1 2 3
! [z] [eBAT6 model hist] [eBAT6 obs hist]
WRITE(204, '(3ES12.5)') TabeBAT6_z(i-1), TabHisteBAT6_z_master(i), TabHisteBAT6_zobs(i)
WRITE(204, '(3ES12.5)') TabeBAT6_z(i), TabHisteBAT6_z_master(i), TabHisteBAT6_zobs(i)
! 1 2 3 4 5
! [z] [z hist model] [z hist model err] [z eBAT6 hist obs] [z eBAT6 hist obs err]
WRITE(2004, '(5ES12.5)') (TabeBAT6_z(i-1)+TabeBAT6_z(i))/2.d0,&
& TabHisteBAT6_z_master(i), TabHisteBAT6_zerr(i), TabHisteBAT6_zobs(i), TabHisteBAT6_zobserr(i)
END DO
CLOSE(204)
CLOSE(2004)
END IF
END SUBROUTINE Save_Constraints
SUBROUTINE Post_process_Constraints()
INTEGER :: i
CHARACTER(len=10) :: Kommers_format = '( ES12.5)'
CHARACTER(len=10) :: Stern_format = '( ES12.5)'
CHARACTER(len=10) :: Preece_format = '( ES12.5)'
CHARACTER(len=10) :: EpGBM_format = '( ES12.5)'
CHARACTER(len=11) :: eBAT6_format = '( ES12.5)'
IF (Constraint_save(Constraint_Stern)) THEN
WRITE(Stern_format(2:3), '(I2)') N_Stern + N_Constraints + 1
OPEN(UNIT=201, FILE=TRIM(SternFile)//"_post_proc.dat", POSITION="append")
WRITE(201, Stern_format) Chi2, TabHistStern_P23_master
CLOSE(201)
END IF
IF (Constraint_save(Constraint_Preece)) THEN
WRITE(Preece_format(2:3), '(I2)') N_Preece + N_Constraints + 1
OPEN(UNIT=202, FILE=TRIM(PreeceFile)//"_post_proc.dat", POSITION="append")
WRITE(202, Preece_format) Chi2, TabHistPreece_Ep_master
CLOSE(202)
END IF
IF (Constraint_save(Constraint_EpGBM)) THEN
WRITE(EpGBM_format(2:3), '(I2)') N_EpGBM + N_Constraints + 1
OPEN(UNIT=203, FILE=TRIM(EpGBMFile)//"_post_proc.dat", POSITION="append")
WRITE(203, EpGBM_format) Chi2, TabHistEpGBM_Epobs_master
CLOSE(203)
END IF
IF (Constraint_save(Constraint_eBAT6)) THEN
WRITE(eBAT6_format(2:4), '(I3)') N_eBAT6 + N_Constraints + 1
! make the distribution cumulative
DO i=2, N_eBAT6 ! start from 2 because ignore first bin
TabHisteBAT6_z_master(i) = TabHisteBAT6_z_master(i) + TabHisteBAT6_z_master(i-1)
END DO
OPEN(UNIT=204, FILE=TRIM(eBAT6File)//"_post_proc.dat", POSITION="append")
WRITE(204, eBAT6_format) Chi2, TabHisteBAT6_z_master
CLOSE(204)
END IF
END SUBROUTINE Post_process_Constraints
SUBROUTINE Reset_eBAT6_output_files()
OPEN(UNIT=267, FILE=TRIM(path)//'eBAT6_KS_data_'//str_rank//'.dat')
WRITE(267,'(A,I2)')"# This is the eBAT6 sample redshift distribution of processor ", rank
ClOSE(267)
END SUBROUTINE Reset_eBAT6_output_files
SUBROUTINE WRITE_INFO()
OPEN(UNIT=83, FILE=TRIM(path)//'info.txt')
WRITE(83, '(A)') "# This file gathers the information about the run"
WRITE(83, '(A)') "Directory : "//TRIM(path)
WRITE(83, '(A,xI2)') "Number of cores :", nb_procs
IF(RNG == Kiss_rng) THEN
WRITE(83, '(A)') "RNG : KISS"
ELSE IF (RNG == MT19937) THEN
WRITE(83, '(A)') "RNG : MT19937"
ELSE
WRITE(83 ,'(A)') "RNG : ERROR"
END IF
IF(run_mode == one_run) THEN
WRITE(83, '(A)') "Run mode : one run"
ELSE IF(run_mode == param_search) THEN
WRITE(83, '(A)') "Run mode : parameter search"
ELSE IF(run_mode == MCMC) THEN
WRITE(83, '(A)') "Run mode : MCMC"
ELSE
WRITE(83,'(A)') "Run mode : ERROR"
END IF
WRITE(83, '(A,xES12.5)') 'Number of GRBs :', REAL(Nb_GRB,8)
WRITE(83, '(A)') 'Parameters explored :'
IF(lum_explore == 1) WRITE(83, '(A)') " - Luminosity : "
IF(z_explore == 1) WRITE(83, '(A)') " - Redshift : "
IF(Ep_explore == 1) WRITE(83, '(A)') " - Ep : "
IF(spec_explore == 1) WRITE(83, '(A)') " - Spectrum : "
WRITE(83, '(A)') 'Constraints used :'
DO i_Constraint=1, N_Constraints
IF(Constraint_Included(i_Constraint)) WRITE(83,'(A)') " - "//TRIM(TabConstraint_name(i_Constraint))//" : "
END DO
WRITE(83, '(A,xF6.3)') 'dof : ', REAL(dof,8)
WRITE(83, '(A,xF6.3)') '1_sigma : ', delta_chi2_1
WRITE(83, '(A,xF6.3)') '2_sigma : ', delta_chi2_2
WRITE(83, '(A,xF6.3)') '3_sigma : ', delta_chi2_3
CLOSE(83)
END SUBROUTINE WRITE_INFO
INTEGER(4) FUNCTION Calc_starting_i()
IF (reprise .EQV. .TRUE.) THEN
IF (Nb_lines >= N_MCMC_iter) THEN
starting_i = MOD(Nb_lines , N_MCMC_iter)
ELSE
starting_i = Nb_lines
END IF
ELSE
starting_i = 1
END IF
Calc_starting_i = starting_i
END FUNCTION Calc_starting_i
SUBROUTINE Reprise_mode()
IF (reprise .EQV. .TRUE.) THEN
IF(run_mode == MCMC) THEN
! Lecture du fichier
OPEN(UNIT=43, FILE=TRIM(path)//'reprise_MCMC.dat', FORM='unformatted')
Nb_lines = 0
DO
READ(43, err=996,end=997) TabSave_ijk_Kiss, TabParam_Lum, TabParam_z, TabParam_Spec, TabParam_Ep, &
& Chi2, lnL, k_Kommers, k_Stern, k_Preece, k_EpGBM, k_eBAT6, dof, accepted_rec, tau, Step_Lum, Step_z, Step_Ep,&
& TabHistLogL_master, TabHistz_master, TabHistLogEp_master, TabHistLogEpobs_master, TabHistLogP_master, &
& TabHistKomm_DRDP, TabHistPreece_Ep_master, TabHistStern_P23_master, TabHistEpGBM_Epobs_master, TabHisteBAT6_z_master
Nb_lines = Nb_lines + 1
! WRITE(*,*) "[ reprise #", Nb_lines," : reduced Chi2 = ", Chi2(0)/REAL(dof,8)," ]"
END DO
997 IF(rank == master_proc) WRITE(*,*) "[ Number of lines read in reprise_MCMC.dat : ",Nb_lines," ]"
996 IF(rank == master_proc) WRITE(*,*) "[ [Error] Number of lines read in reprise_MCMC.dat : ",Nb_lines," ]"
CLOSE(43)
ELSE IF(run_mode == param_search) THEN
OPEN(UNIT=43, FILE=TRIM(path)//'reprise.dat', FORM='unformatted')
! Lecture du fichier
Nb_lines = 0
DO
READ(43, err=998,end=999) TabSave_ijk_Kiss, TabParam_Lum, TabParam_z, TabParam_Spec, TabParam_Ep, &
& Chi2, k_Kommers, k_Stern, k_Preece, k_EpGBM, Frac_XRFHETE2,dof, chi2_min, Nb_good_models, Nb_models
Nb_lines = Nb_lines + 1
! WRITE(*,*) "[ reprise #", Nb_lines," : reduced Chi2 = ", Chi2(0)/REAL(dof,8)," ]"
END DO
999 IF(rank == master_proc) WRITE(*,*) "[ Number of lines read in reprise.dat : ",Nb_lines," ]"
998 IF(rank == master_proc) WRITE(*,*) "[ [Error] Number of lines read in reprise.dat : ",Nb_lines," ]"
CLOSE(43)
END IF
END IF
END SUBROUTINE Reprise_mode
SUBROUTINE Define_Nb_lines
! This part is to find the number of lines in the file
IF(rank == master_proc) THEN
OPEN(UNIT=43, FILE=TRIM(path)//'reprise.dat', FORM='unformatted')
Nb_lines = 0
DO
READ(43,err=998,end=999) TabSave_ijk_Kiss, TabParam_Lum, TabParam_z, TabParam_Spec, TabParam_Ep, &
& Chi2, k_Kommers, k_Stern, k_Preece, k_EpGBM, Frac_XRFHETE2, dof, Chi2_min, Nb_good_models, Nb_models
Nb_lines = Nb_lines + 1
END DO
998 IF(rank == master_proc) WRITE(*,*) "[ [Error] Number of lines read in reprise.dat : ",Nb_lines," ]"
999 IF(rank == master_proc) WRITE(*,*) "[ Number of lines read in reprise.dat : ",Nb_lines," ]"
CLOSE(43)
Nb_good_models_to_pp = Nb_good_models
END IF
CALL MPI_BCAST(Nb_lines, 1, MPI_INTEGER, master_proc, MPI_COMM_WORLD, code)
CALL MPI_BCAST(Nb_good_models_to_pp, 1, MPI_INTEGER, master_proc, MPI_COMM_WORLD, code)
END SUBROUTINE Define_Nb_lines
REAL(8) FUNCTION Calc_kappa_tau(tau_0, epsilon_tau)
REAL(8), intent(in) :: tau_0
REAL(8), intent(in) :: epsilon_tau
Calc_kappa_tau = ( epsilon / (tau_0 - 1.d0) )**(0.05d0)
! Calculated so that after 20 updates, tau = 1 + epsilon
END FUNCTION Calc_kappa_tau
SUBROUTINE InitECLAIRs(nsigmasECLAIRs)
REAL(8), intent(in) :: nsigmasECLAIRs
REAL(8) :: x,y, E1obsECLAIRs, E2obsECLAIRs
INTEGER :: i
WRITE(*,'(A)')
WRITE(*,'(A)') "================================================"
WRITE(*,'(A)') "== =="
WRITE(*,'(A)') "== Init ECLAIRs instrument =="
WRITE(*,'(A)') "== =="
WRITE(*,'(A)') "================================================"
WRITE(*,'(A)')
E1obsECLAIRs = TabEmin(Instrument_ECLAIRs)
E2obsECLAIRs = TabEmax(Instrument_ECLAIRs)
WRITE(*,'(2(A,1ES12.5),A)') "ECLAIRs: use energy channel : ",E1obsECLAIRs," to ",E2obsECLAIRs," keV"
WRITE(*,'(1(A,1ES12.5),A)') "ECLAIRs: use detection level at ",nsigmasECLAIRs," sigmas"
WRITE(*,'(A)')
ExtEclairs=". . . "
IF (nsigmasECLAIRs<10.D0) THEN
WRITE(ExtEclairs(2:5), '(1I4.4)') INT(nsigmasECLAIRS*1000.D0) ! 5.5 -> 5500
ELSE
WRITE(ExtEclairs(2:5), '(1I4.4)') INT(nsigmasECLAIRS*100.D0) ! 10. -> 1000
END IF
WRITE(ExtEclairs(7:10), '(1I4.4)') INT(E1obsECLAIRs*10.D0) ! 4 -> 0040 ; 250 -> 2500
WRITE(ExtEclairs(12:15),'(1I4.4)') INT(E2obsECLAIRs*10.D0) ! 4 -> 0040 ; 250 -> 2500
WRITE(*,'(A,A)') "ECLAIRs: extension = ",ExtECLAIRs
WRITE(*,'(A)')
! Effective area
OPEN(UNIT=100,FILE=TRIM(PathSVOM) // "rf_eff.txt")
NeffECLAIRS = 0
DO
READ(100,*,err=999,end=999) x,y
NeffECLAIRs = NeffECLAIRs+1
TABeffECLAIRsE(NeffECLAIRs) = x
TABeffECLAIRsA(NeffECLAIRs) = y
END DO
999 CLOSE(100)
WRITE(*,'(A,I4.4,A)') "ECLAIRs: effective area --> ",NeffECLAIRs," values"
WRITE(*,'(2(A,1ES12.5),A)') " from ",TABeffECLAIRsE(1)," keV -- ",TABeffECLAIRsA(1)," cm2"
WRITE(*,'(2(A,1ES12.5),A)') " to ",TABeffECLAIRsE(NeffECLAIRs)," keV -- ",TABeffECLAIRsA(NeffECLAIRs)," cm2"
! Background
OPEN(UNIT=100,FILE=TRIM(PathSVOM) // "rf_bkg.txt")
NbkgECLAIRS = 0
DO
READ(100,*,err=888,end=888) x,y
NbkgECLAIRS = NbkgECLAIRS+1
TABbkgECLAIRsE(NbkgECLAIRs) = x
TABbkgECLAIRsB(NbkgECLAIRs) = y
END DO
888 CLOSE(100)
WRITE(*,'(A,I4.4,A)') "ECLAIRs: background --> ",NbkgECLAIRs," values"
WRITE(*,'(2(A,1ES12.5),A)') " from ",TABbkgECLAIRsE(1)," keV -- ",TABbkgECLAIRsB(1)," cts/s/keV"
WRITE(*,'(2(A,1ES12.5),A)') " to ",TABbkgECLAIRsE(NbkgECLAIRs)," keV -- ",TABbkgECLAIRsB(NbkgECLAIRs)," cts/s/keV"
IF (NbkgECLAIRs/=NeffECLAIRs) STOP "Error: different numbers of values for efficiency and background"
DO i=1, NeffECLAIRs
IF (TABbkgECLAIRsE(i)/=TABeffECLAIRsE(i)) STOP "Error: different values of energy for efficieny and background"
END DO
DO i=1, NeffECLAIRs
IF (TABeffECLAIRsE(i)<=E1obsECLAIRs) istartECLAIRs=i
IF (TABeffECLAIRsE(i)<=E2obsECLAIRs) iendECLAIRs=i
END DO
WRITE(*,'(2(A,1I4.4))') "ECLAIRS: energy grid --> ",istartECLAIRs," to ",iendECLAIRs
bkgECLAIRsB1 = 0.D0
DO i=istartECLAIRs+1, iendECLAIRs !2, NbkgECLAIRs
bkgECLAIRsB1 = bkgECLAIRsB1 + 0.5D0*(TABbkgECLAIRsE(i)-TABbkgECLAIRsE(i-1))*(TABbkgECLAIRsB(i-1)+TABbkgECLAIRsB(i))
END DO
WRITE(*,'(A,1ES12.5,A)') "ECLAIRs: background --> ",bkgECLAIRsB1," cts/s"
! offaxis correction
OPEN(UNIT=100,FILE=TRIM(PathSVOM) // "rf_offaxis.txt")
DO i=-NoffECLAIRs,NoffECLAIRs
READ(100,*,err=777) TABoffECLAIRs(i,-NoffECLAIRs:NoffECLAIRs)
! WRITE(*,*) i,"OK"
END DO
CLOSE(100)
WRITE(*,'(2(A,1ES12.5))') "ECLAIRs: offaxis correction from ",MINVAL(TABoffECLAIRs)," to ",MAXVAL(TABoffECLAIRs)
! solid angle associated to each "pixel"
OPEN(UNIT=100,FILE=TRIM(PathSVOM) // "rf_omega.txt")
DO i=-NoffECLAIRs,NoffECLAIRs
READ(100,*,err=777) TABomegaECLAIRs(i,-NoffECLAIRs:NoffECLAIRs)
! WRITE(*,*) i,"OK"
END DO
CLOSE(100)
WRITE(*,'(2(A,1ES12.5),A)') "ECLAIRs: omega(pixel) = ",MINVAL(TABomegaECLAIRs)," to ",MAXVAL(TABomegaECLAIRs)," sr"
omegaECLAIRs=SUM(TabomegaECLAIRs)
WRITE(*,'(A,1ES12.5,A)') "ECLAIRs: omega(total) = ",omegaECLAIRs," sr"
RETURN
777 STOP "Error when reading rf_offaxis.txt"
END SUBROUTINE InitECLAIRs
END PROGRAM Core
| JPalmerio/GRB_population_code | Src_para/GRB_population_MC_ubuntu.f90 | FORTRAN | gpl-3.0 | 283,929 |
/****************************************************************************
** Resource object code
**
** Created by: The Resource Compiler for Qt version 5.5.0
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
static const unsigned char qt_resource_data[] = {
// E:/new/Mainwindow/mainwindow/mainwindow/varList/background/e_06_1.png
0x0,0x0,0x5,0x3d,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x3d,0x0,0x0,0x0,0x21,0x8,0x6,0x0,0x0,0x0,0x6a,0x76,0xa3,0x9,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,
0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,
0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,
0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,
0x62,0x4b,0x47,0x44,0x0,0x0,0x0,0x0,0x0,0x0,0xf9,0x43,0xbb,0x7f,0x0,0x0,
0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x12,0x0,0x0,0xb,0x12,0x1,0xd2,
0xdd,0x7e,0xfc,0x0,0x0,0x4,0xa1,0x49,0x44,0x41,0x54,0x58,0xc3,0xed,0x99,0x5f,
0x48,0x5b,0x57,0x1c,0xc7,0x3f,0xc6,0x60,0x59,0x52,0x66,0x4b,0x25,0x1a,0x7d,0x50,
0x2c,0xed,0x40,0x34,0xe8,0x83,0x69,0x4a,0x4c,0x43,0x8b,0x24,0x73,0x94,0xf9,0x92,
0xd4,0x4e,0x50,0x28,0xab,0xf,0x82,0xa5,0xac,0x84,0x91,0x97,0x6e,0x1d,0x54,0x12,
0x46,0xa0,0x82,0xf,0xa5,0x6a,0xa6,0x28,0x4c,0xd3,0x8a,0x5,0xb,0xdd,0x4b,0x6c,
0x88,0xce,0xb4,0x93,0x95,0x2b,0x79,0xb8,0x30,0x1f,0xa4,0xed,0x40,0x30,0xbb,0x12,
0x97,0x9a,0x8,0x25,0x6e,0x7b,0xd0,0xdc,0x25,0x9d,0xed,0x83,0xd1,0xc6,0xba,0x7e,
0xe1,0xc0,0xf9,0xfb,0xbb,0xbf,0xcf,0xb9,0xf7,0x77,0xee,0xbd,0xe7,0xe4,0x91,0x26,
0x8f,0xc7,0x73,0x3,0x30,0x1,0xa7,0x81,0x8f,0x78,0xff,0xb5,0xe,0x3c,0x6,0x66,
0x1c,0xe,0xc7,0x8d,0x54,0x65,0xde,0x16,0x6c,0x25,0xf0,0x23,0x70,0x2a,0xd7,0x5e,
0xee,0xa1,0x7e,0x1,0x5a,0x1d,0xe,0xc7,0xa2,0x72,0xab,0x62,0xc,0xa8,0xd7,0x68,
0x34,0x9c,0x31,0x99,0x28,0x2d,0x2d,0x45,0xa9,0x54,0x66,0x61,0x7f,0x7f,0x28,0x99,
0x4c,0xb2,0xb4,0xb4,0xc4,0xf4,0xcc,0xc,0x91,0x48,0xe4,0xd4,0x16,0xa7,0x3e,0xcf,
0xe3,0xf1,0x7c,0x3,0x7c,0x57,0x5c,0x5c,0x4c,0xcb,0x85,0xb,0x7,0x2,0x76,0x3b,
0x78,0xdf,0xdd,0xbb,0x2c,0x2f,0x2f,0x3,0x7c,0xab,0x60,0x33,0x86,0x69,0x30,0x1a,
0xf,0x24,0x30,0x80,0x52,0xa9,0xa4,0xc1,0x68,0x4c,0x15,0x4d,0xa,0xc0,0x8,0x50,
0x56,0x56,0x96,0x6b,0xdf,0xf6,0x54,0x69,0x7c,0x26,0x5,0x5b,0xab,0xf4,0x41,0xbd,
0xcb,0x29,0xa5,0xf1,0x1d,0x52,0xe4,0xda,0x99,0x5c,0xe8,0x3,0xf4,0x4e,0x14,0x8f,
0xc7,0xf1,0x7a,0xbd,0x59,0x3b,0x12,0xe,0x87,0xb9,0x72,0xe5,0xca,0xfb,0x3,0xed,
0x9f,0x9a,0xe2,0x8b,0xd6,0x56,0xe2,0xf1,0x38,0xe1,0x70,0x18,0x45,0x7e,0xfe,0x5b,
0xd3,0xbd,0xf1,0xf1,0x77,0x2,0xb7,0x67,0xd0,0x1a,0x8d,0x86,0x81,0xfe,0x7e,0x0,
0xee,0xdc,0xb9,0x83,0x4e,0xa7,0xe3,0xaf,0x8d,0xd,0x39,0x9d,0x3d,0x7b,0x96,0x79,
0x41,0xc8,0xa8,0xb3,0xdb,0x6c,0xf2,0xf8,0x48,0x24,0x42,0x38,0x1c,0xe6,0xb7,0x85,
0x5,0xa4,0x95,0x15,0xc2,0xe1,0xb0,0x9c,0xde,0x36,0x89,0xd9,0x4c,0xdc,0xae,0x2c,
0xd9,0x6a,0xb5,0x5a,0x6,0x4f,0x57,0x24,0x12,0x21,0x10,0x8,0xa0,0xd3,0xe9,0xde,
0x38,0x36,0x38,0x3d,0x4d,0x4b,0x4b,0x8b,0x5c,0xf6,0xf9,0x7c,0x72,0x7e,0x5e,0x10,
0xb6,0xcd,0xbb,0xdc,0xee,0xac,0xfc,0xcd,0x1a,0xda,0xeb,0xf5,0x52,0x5f,0x5f,0x8f,
0x4e,0xa7,0x63,0x71,0x71,0x91,0x5b,0xb7,0x6e,0xc9,0x6d,0xd2,0xca,0xa,0x27,0x4f,
0x9e,0xdc,0x36,0x56,0xcf,0x9f,0x3f,0x8f,0xd5,0x6a,0xc5,0x6e,0xb3,0x61,0xdf,0xd8,
0xe0,0xde,0xf8,0x38,0xd3,0xc1,0x20,0xbd,0xbd,0xbd,0x0,0x28,0xf2,0xf3,0x33,0xfa,
0xa7,0x4f,0x5c,0xd1,0xb1,0x63,0xb9,0x85,0xfe,0xb8,0xb0,0x90,0xda,0xba,0x3a,0x7c,
0x3e,0x1f,0x9f,0x35,0x35,0xd1,0xd1,0xd1,0x1,0xc0,0xda,0xda,0x1a,0xd,0x26,0x13,
0x3f,0x3d,0x7c,0x48,0xec,0xe5,0x4b,0xae,0x5f,0xbf,0xce,0xf,0x5e,0x2f,0x87,0xf,
0x1f,0x6,0xa0,0xa4,0xa4,0x24,0xdb,0x4b,0xe7,0xe,0xda,0x6e,0xb3,0xf1,0x89,0x20,
0xf0,0xd5,0xb5,0x6b,0x98,0xcf,0x9c,0x41,0xa7,0xd3,0x11,0x8f,0xc7,0xb9,0xdc,0xd1,
0x41,0x7f,0x5f,0x1f,0x56,0xab,0x15,0x80,0xdf,0x5f,0xbc,0x60,0x74,0x74,0x14,0xb7,
0xdb,0x8d,0x5a,0xad,0xce,0x19,0x70,0x6,0xf4,0x1f,0x92,0xb4,0x63,0x23,0xda,0xd2,
0x52,0xc6,0xc6,0xc6,0x0,0xf8,0xf5,0xe9,0x53,0xba,0xbb,0xbb,0xa9,0xab,0xab,0xe3,
0xf3,0xe6,0x66,0xbe,0xbc,0x7c,0x19,0xb7,0xdb,0x4d,0x5b,0x7b,0x3b,0xb7,0x6f,0xdf,
0xe6,0xd3,0xa6,0x26,0x9c,0x4e,0x27,0x7a,0xbd,0x3e,0xc3,0x46,0x2c,0x16,0xa3,0xe0,
0xd0,0xa1,0xc,0x3f,0xa2,0xab,0xab,0x72,0x3e,0xbd,0x3e,0xb1,0xbe,0x4e,0x2c,0x16,
0xdb,0xb1,0xcf,0xbb,0xf2,0x71,0x22,0x49,0x12,0xa2,0x28,0x32,0x37,0x37,0x87,0x5e,
0xaf,0xc7,0x6c,0x36,0xd3,0xd9,0xd9,0x9,0xc0,0xe0,0xe0,0xa0,0xdc,0xaf,0xb3,0xb3,
0x13,0xa7,0xd3,0xc9,0xd5,0xab,0x57,0x99,0x9c,0x9c,0xcc,0xb0,0x11,0xa,0x85,0xa8,
0xaa,0xaa,0xda,0xd,0x77,0xde,0xd,0x74,0x28,0x14,0xa2,0xa7,0xa7,0x87,0xea,0xea,
0x6a,0x2,0x81,0x0,0xb1,0x58,0x8c,0x47,0x8f,0x1e,0xc9,0xed,0xa2,0x28,0x32,0x39,
0x39,0x89,0x28,0x8a,0xc,0xc,0xc,0x30,0x35,0x35,0x45,0x63,0x63,0x63,0x86,0x8d,
0x85,0x85,0x85,0x77,0x16,0xe7,0xbb,0x2,0x2d,0x8a,0x22,0x66,0xb3,0x19,0x95,0x4a,
0x45,0x45,0x45,0x5,0xc3,0xc3,0xc3,0x1c,0x3f,0x7e,0x5c,0x6e,0x57,0xab,0xd5,0xb8,
0x5c,0x2e,0xaa,0xaa,0xaa,0x90,0x24,0x9,0xbf,0xdf,0x8f,0x4a,0xa5,0x92,0xdb,0x25,
0x49,0x62,0x76,0x76,0x96,0xca,0xca,0xca,0xc,0xbb,0x1a,0x8d,0x66,0xff,0x42,0xcf,
0xcd,0xcd,0x71,0xe2,0xc4,0x9,0x0,0xfc,0x7e,0x3f,0x66,0xb3,0x99,0xf2,0xf2,0x72,
0xb9,0x3d,0x95,0x17,0x45,0x91,0xae,0xae,0x2e,0x5c,0x2e,0x17,0x89,0x44,0x42,0x6e,
0xf,0x85,0x42,0x34,0x37,0x37,0x53,0x54,0x54,0x94,0x61,0xf7,0xf5,0xf2,0xbe,0x81,
0x4e,0xdd,0xa5,0xea,0xea,0x6a,0x12,0x89,0x4,0x43,0x43,0x43,0x72,0x3c,0xa7,0xab,
0xbd,0xbd,0x1d,0x41,0x10,0x38,0x77,0xee,0x1c,0x35,0x35,0x35,0x3c,0x7b,0xf6,0xc,
0x80,0x44,0x22,0x81,0xcb,0xe5,0xe2,0xe2,0xc5,0x8b,0x72,0xdf,0xe7,0xcf,0x9f,0xff,
0x67,0x7c,0x71,0x71,0xb1,0x9c,0xd2,0xd7,0x89,0x9d,0x28,0xeb,0x57,0x56,0x28,0x14,
0xc2,0x68,0x34,0xca,0x8f,0xeb,0xc4,0xc4,0x44,0x46,0xc,0xa7,0x64,0xb7,0xdb,0xe5,
0x3e,0x7d,0x7d,0x7d,0x72,0xfd,0xfd,0xfb,0xf7,0xd1,0x6a,0xb5,0x18,0xc,0x6,0xdc,
0x6e,0x37,0xab,0xab,0xab,0x4,0x83,0x41,0x2e,0x5d,0xba,0x94,0x71,0x9d,0xad,0xad,
0x1e,0x0,0x9c,0x4e,0x67,0x6e,0xa1,0x4b,0x4a,0x4a,0xe8,0xea,0xea,0xda,0x76,0x32,
0x8e,0x1c,0x39,0xc2,0x83,0x7,0xf,0x80,0x37,0x3f,0xaa,0x5a,0xad,0x96,0x9b,0x37,
0x6f,0xa2,0x52,0xa9,0xd0,0xeb,0xf5,0xac,0xad,0xad,0x61,0xb1,0x58,0x30,0x18,0xc,
0xc0,0x66,0x5c,0xf7,0xbf,0xf6,0x89,0x6b,0xb1,0x58,0xb2,0x5a,0xf4,0xf2,0x3c,0x1e,
0xcf,0xdf,0x0,0x6d,0x6d,0x6d,0xd9,0xf2,0xef,0x7b,0x8d,0x8c,0x8c,0x0,0x1f,0x36,
0x11,0xfe,0x3f,0x52,0xb0,0x79,0xf4,0x41,0x32,0x99,0xcc,0xb5,0x2f,0x7b,0xaa,0x34,
0xbe,0x75,0x5,0x30,0x3,0x9b,0xff,0xbe,0x7,0x59,0x69,0x7c,0x3f,0xcb,0xd0,0x82,
0x20,0x1c,0xd8,0xbb,0x9d,0x4c,0x26,0x11,0xfe,0xdd,0x84,0x98,0x49,0x1d,0xe0,0x3d,
0x6,0xc,0x47,0x8f,0x1e,0xa5,0xb6,0xb6,0x16,0x8d,0x46,0x43,0x41,0x41,0x41,0xae,
0x7d,0xcd,0x5a,0xaf,0x5e,0xbd,0x22,0x12,0x89,0x30,0x3f,0x3f,0x4f,0x34,0x1a,0x5,
0x78,0xe2,0x70,0x38,0x4e,0xa7,0xde,0xd3,0xad,0xc0,0x48,0x34,0x1a,0x35,0x6,0x2,
0x81,0x5c,0xfb,0xba,0x57,0x9a,0x5,0xda,0x60,0xeb,0xa8,0x36,0x25,0x8f,0xc7,0xf3,
0x35,0x9b,0x67,0x5b,0x26,0xa0,0x30,0xd7,0x5e,0xee,0x82,0xfe,0x64,0x33,0x7c,0x67,
0x1c,0xe,0xc7,0xf7,0xa9,0xca,0x7f,0x0,0xcb,0x75,0xcb,0x3d,0xfe,0x6,0x8,0x5f,
0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
// E:/new/Mainwindow/mainwindow/mainwindow/varList/background/delete_03.png
0x0,0x0,0x5,0x76,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x3d,0x0,0x0,0x0,0x21,0x8,0x6,0x0,0x0,0x0,0x6a,0x76,0xa3,0x9,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,
0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,
0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,
0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,
0x62,0x4b,0x47,0x44,0x0,0x0,0x0,0x0,0x0,0x0,0xf9,0x43,0xbb,0x7f,0x0,0x0,
0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x12,0x0,0x0,0xb,0x12,0x1,0xd2,
0xdd,0x7e,0xfc,0x0,0x0,0x4,0xda,0x49,0x44,0x41,0x54,0x58,0xc3,0xe5,0x99,0x59,
0x6c,0x54,0x55,0x18,0xc7,0x7f,0xf7,0xde,0xd9,0x3a,0x1d,0xe8,0x64,0x3a,0xd3,0x16,
0x4,0xcb,0x5a,0x10,0x5b,0xa0,0xb1,0x50,0x6a,0xdb,0xc4,0xa0,0xb8,0xd1,0x10,0x1e,
0x88,0x25,0x8d,0xe2,0x93,0x1b,0xa1,0x9a,0x48,0x62,0xfa,0x84,0xe8,0x83,0x69,0x48,
0x7c,0x30,0x4d,0x34,0x71,0x4b,0x8,0xc4,0x88,0x31,0xda,0x87,0xe2,0x92,0x3e,0x68,
0x32,0x85,0x2,0xd1,0x4c,0xa0,0x6c,0xd2,0xc0,0x50,0x5b,0x4b,0xa5,0x65,0x9c,0xe,
0x73,0x67,0x9f,0x7b,0x7d,0xb8,0xb3,0x74,0x28,0x34,0xe0,0x5,0x67,0x28,0xff,0xb7,
0x7b,0xce,0x99,0xef,0x7c,0xbf,0xef,0x9c,0xef,0x2c,0x73,0x4,0xa6,0xa8,0xb6,0xcb,
0xb7,0x17,0x68,0x6,0x1a,0x80,0x22,0xee,0x7f,0x85,0x81,0x7e,0xc0,0xed,0x69,0x77,
0xec,0x4d,0x17,0xa,0x29,0xd8,0x25,0xc0,0x57,0x40,0x7d,0xbe,0xbd,0xbc,0x87,0x3a,
0xe,0xb4,0x79,0xda,0x1d,0x97,0xc,0xa9,0x82,0xaf,0x81,0x75,0x2b,0x5d,0x12,0x6f,
0x35,0x58,0x58,0x53,0x21,0x61,0x36,0x8,0xf9,0x76,0x52,0xb7,0xa2,0x9,0x95,0x93,
0x63,0x49,0x3e,0xea,0x8f,0x70,0x7e,0x3c,0x59,0x9f,0xe2,0x5c,0x2f,0xd4,0x76,0xf9,
0xf6,0x0,0xef,0xad,0x2a,0x93,0xf8,0x6c,0x6b,0x31,0x96,0x59,0x0,0x7b,0xa3,0x22,
0x9,0x95,0x57,0xba,0x65,0xce,0x5e,0x4d,0x2,0xbc,0x2b,0xa2,0xe5,0x30,0xbb,0xea,
0x2d,0xb3,0x12,0x18,0xc0,0x62,0x10,0xd8,0x55,0x6f,0x49,0x7f,0x36,0x8b,0x40,0x23,
0xc0,0xda,0x79,0x52,0xbe,0x7d,0xbb,0xa7,0xaa,0x9d,0x9f,0xce,0x64,0xd,0xba,0x8,
0x98,0x15,0x39,0x3c,0x93,0x4c,0xd9,0x31,0x35,0x8b,0xf9,0x76,0x26,0x1f,0x7a,0x20,
0xa1,0xd,0x7a,0xd,0xc,0x5d,0x4b,0x12,0x8a,0xa9,0x0,0xb8,0xe6,0x68,0x31,0x3c,
0xe6,0x8d,0x67,0xea,0x37,0x2c,0x36,0xe2,0xb4,0x65,0x63,0xfb,0xd8,0xc7,0x93,0xfc,
0xbe,0xb3,0x24,0xf3,0x7d,0xee,0x4a,0x22,0xc7,0x5e,0x65,0xa9,0x84,0xd5,0x94,0x4d,
0xb5,0x4f,0x8f,0x84,0x99,0x6b,0x16,0xd8,0x5e,0x67,0xe1,0x6e,0x49,0x37,0xf4,0x17,
0xc7,0x23,0xf8,0x23,0x2a,0xff,0x44,0x54,0x5a,0x6b,0x4c,0x2c,0x75,0x4a,0x1c,0x1a,
0x88,0xd1,0x5a,0x63,0xe2,0xd0,0x40,0x8c,0xa5,0x4e,0x9,0x39,0xaa,0xd2,0xef,0x8d,
0xdf,0xd4,0xf1,0x17,0xbf,0x97,0xd9,0xbc,0x48,0x73,0xe3,0xf0,0xe5,0x4,0xdf,0xb5,
0xda,0xa8,0x2c,0x95,0x32,0x1,0xe9,0xfe,0x43,0xb,0xe0,0x96,0xd5,0xe6,0x9c,0x60,
0xe4,0x15,0x1a,0xe0,0x8d,0x6,0xb,0x17,0x27,0x92,0x99,0xef,0xc5,0x76,0x91,0x96,
0x1a,0x33,0x27,0x86,0xb5,0x51,0xc,0xc5,0xd4,0xf4,0x1e,0x79,0x53,0xbd,0xff,0x7c,
0x31,0xe7,0xae,0x24,0xf0,0xfa,0x95,0xc,0x70,0x28,0xa6,0xb2,0xfb,0xc7,0x10,0x3b,
0xd7,0x99,0x9,0x46,0x55,0x3a,0x7a,0x64,0x3a,0x5b,0x8a,0xef,0xa,0x78,0xc1,0xe4,
0xf4,0xc9,0xbf,0x12,0x6c,0xae,0x32,0x66,0x80,0x3b,0x7a,0x64,0xb6,0xae,0x30,0xd2,
0x52,0x63,0x66,0x7b,0x9d,0x5,0xbb,0x45,0xa0,0xa3,0x47,0xce,0xa4,0xd2,0xac,0x80,
0x3e,0xfa,0x67,0x82,0x35,0xf,0x19,0x38,0x77,0x25,0xc1,0xb6,0x83,0xd7,0xa9,0x2e,
0x97,0x78,0xb5,0x31,0x7b,0xe7,0xe9,0x78,0xca,0x4a,0x75,0xb9,0xc4,0x6b,0xdf,0x6,
0xa7,0xad,0x3,0x77,0xaa,0xbb,0x32,0xbd,0xf5,0x6a,0x22,0xa8,0x70,0x64,0x2c,0x49,
0x67,0xa9,0x44,0xf3,0xe7,0x1,0x1a,0x2b,0x24,0x46,0x26,0x15,0xf6,0xfc,0x20,0x4f,
0x6b,0xdb,0x5a,0x63,0xe2,0x83,0x5f,0xc2,0x1c,0x68,0x9b,0x93,0x1f,0xe8,0x9e,0x81,
0x28,0x5e,0xbf,0x82,0xfb,0x52,0x9c,0x91,0x49,0x5,0x80,0xd1,0x80,0x82,0xd7,0xaf,
0xe4,0xd4,0x55,0xb9,0x66,0x3e,0xed,0x59,0x4d,0x2,0xab,0xec,0x22,0x67,0x46,0x13,
0xfc,0xbc,0x43,0x83,0x19,0xbf,0xae,0xd9,0xfb,0xa4,0x3f,0x42,0x75,0xb9,0x44,0xf3,
0x12,0x6d,0xea,0x3f,0x32,0xcf,0x40,0x4b,0x8d,0x59,0x57,0x90,0x33,0xd0,0xe3,0x13,
0x13,0x77,0xfc,0xe3,0x40,0x50,0x24,0x9e,0x14,0x91,0x43,0x9,0xc2,0x51,0x6d,0x81,
0x91,0x43,0x2a,0xf1,0xa4,0x40,0x20,0x28,0x67,0xea,0x26,0x3,0x2a,0xe1,0xa8,0x98,
0xea,0xc3,0x78,0x43,0x5f,0x46,0xe4,0xc0,0x35,0x76,0x54,0x8b,0x7c,0xe8,0x4e,0xd2,
0xf5,0x9c,0x36,0x75,0x9d,0x1a,0x23,0x66,0xc1,0x80,0x4d,0x8c,0xe1,0x34,0xca,0x29,
0x3f,0xf5,0xe0,0x1a,0x73,0xa1,0xff,0x8b,0x36,0x2d,0x57,0xf0,0x8c,0x89,0xac,0x5f,
0xa0,0x30,0xe4,0xd7,0xa0,0x2b,0xed,0x2a,0xa3,0x41,0x29,0xa7,0xee,0x76,0xb4,0x76,
0xbe,0xc2,0x60,0x9f,0x44,0xf7,0x19,0x89,0xb,0xbe,0xec,0xa,0x7d,0xca,0x27,0x30,
0x1c,0x14,0xf1,0x8c,0x65,0x97,0x9f,0xa6,0x85,0xa,0x8f,0x2f,0xba,0x3d,0xbb,0x37,
0x53,0x41,0xe4,0x74,0x5a,0x75,0xa5,0x2a,0x65,0xc5,0x2a,0xab,0xca,0xb2,0x40,0x81,
0x53,0x12,0x2b,0x1d,0x6a,0x4e,0xf0,0x9c,0xc5,0xfa,0xfa,0x29,0x88,0xd5,0xbb,0x77,
0x50,0xa4,0xfb,0x8c,0xc4,0x6f,0xd7,0x4,0x56,0x96,0xa9,0xc,0xf9,0x5,0xce,0x5e,
0x15,0xa9,0x72,0xa9,0xcc,0x35,0x41,0xb9,0x4d,0x25,0x14,0x17,0x38,0x31,0xa2,0x95,
0x39,0xac,0xfa,0xb6,0x2d,0xdd,0xd0,0xc3,0x41,0xa8,0x72,0x65,0x9d,0x18,0xf2,0xb,
0xcc,0xb7,0xe5,0x3a,0xb5,0xd0,0xae,0xd2,0xb6,0xfa,0xd6,0x87,0x13,0x39,0x26,0x70,
0xc1,0x27,0xd0,0xd9,0xa4,0xb5,0xd9,0x7f,0x56,0xa2,0xee,0x86,0xb4,0x58,0xe1,0x52,
0x38,0xef,0x13,0x38,0xe8,0xd1,0x7f,0x5,0xd6,0x35,0xbd,0x47,0x26,0xa7,0x9f,0x8e,
0x2e,0xfa,0x4,0x56,0x97,0xe7,0x42,0x17,0x19,0x61,0x41,0xc9,0xad,0x47,0x67,0xeb,
0xa3,0xd9,0x80,0xec,0x73,0x1b,0xd8,0xb6,0x4c,0x99,0xd6,0xbe,0xc8,0x8,0x6f,0x37,
0x24,0x79,0xb3,0xd7,0x40,0xb9,0x4d,0x65,0xd3,0xf2,0x3c,0xe5,0xf4,0xaf,0x97,0x44,
0xb6,0x2c,0x53,0xd8,0xe7,0x36,0x30,0x1c,0x84,0x27,0x1f,0x56,0xe9,0x1e,0x12,0xd9,
0xb8,0x24,0x41,0xef,0xa0,0xc8,0x70,0x50,0x6b,0x77,0xf4,0xb2,0x48,0xdf,0xb0,0x36,
0xa9,0x9c,0x33,0xec,0x36,0xbe,0x90,0xc0,0x5c,0x93,0xca,0x33,0x55,0x49,0x7a,0x7,
0xb5,0xf6,0xa7,0x7c,0x2,0xb5,0x15,0x5a,0xbd,0xc3,0xaa,0xd2,0xf9,0x44,0x82,0x9,
0x59,0xdf,0x51,0x54,0x17,0xb4,0xcd,0x4,0x4d,0x8b,0x14,0x2a,0xed,0xda,0xa8,0x58,
0x4d,0xb0,0xdb,0xa4,0x62,0x35,0x81,0x67,0x4c,0xb,0x48,0x7a,0xea,0xd7,0x56,0x68,
0x23,0xf3,0xf4,0xd2,0x5c,0x1b,0x1b,0xe7,0x65,0x47,0xd4,0x61,0x55,0x79,0xbd,0x5e,
0x1b,0xf5,0xbf,0x83,0x2,0xa3,0x41,0x81,0x6d,0xcb,0x14,0x9a,0xa6,0xac,0xd4,0xb,
0x4a,0xd4,0x19,0x67,0xcd,0xed,0x48,0xa8,0xed,0xf2,0xa9,0x0,0x3f,0xbd,0x10,0xd7,
0x65,0xe8,0x7e,0xd0,0xb3,0xdf,0x68,0xfb,0x74,0x41,0xac,0xde,0xff,0xb7,0x1e,0x58,
0xe8,0x30,0x40,0x34,0xa9,0xd3,0x52,0x81,0x6b,0xa,0x5f,0x58,0x4,0xdc,0x0,0xa7,
0xc7,0x67,0xf7,0xbf,0xa1,0x53,0xf8,0xfa,0x32,0xd0,0x5f,0xe,0x48,0x44,0xf4,0x5d,
0x53,0xb,0x56,0x91,0x84,0xc6,0x97,0x92,0x3b,0xfd,0x80,0xd7,0xf,0x6c,0x58,0x6c,
0x57,0x79,0xb9,0x5a,0xa1,0xda,0xa5,0x60,0x33,0xe6,0xdb,0x55,0xfd,0xa,0xc6,0xe1,
0xf4,0xb8,0xc8,0xfe,0xd3,0x22,0x5e,0xed,0x42,0x74,0xcc,0xd3,0xee,0x68,0x48,0xef,
0xd3,0x6d,0xc0,0x1,0xaf,0x5f,0x68,0xdc,0xdb,0x27,0x1,0xb3,0xf2,0xb5,0xe3,0x8,
0xf0,0x12,0xa4,0x9e,0x6a,0xd3,0xaa,0xed,0xf2,0xbd,0x83,0xf6,0xb6,0xd5,0xc,0x94,
0xdc,0xb9,0xdd,0x82,0xd3,0x24,0x5a,0xfa,0xba,0x3d,0xed,0x8e,0x7d,0xe9,0xc2,0x7f,
0x1,0xea,0xda,0xc3,0x45,0xfc,0xc6,0x51,0x9d,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,
0x44,0xae,0x42,0x60,0x82,
// E:/new/Mainwindow/mainwindow/mainwindow/varList/background/delete_02.png
0x0,0x0,0x5,0x7a,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x3d,0x0,0x0,0x0,0x21,0x8,0x6,0x0,0x0,0x0,0x6a,0x76,0xa3,0x9,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,
0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,
0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,
0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,
0x62,0x4b,0x47,0x44,0x0,0x0,0x0,0x0,0x0,0x0,0xf9,0x43,0xbb,0x7f,0x0,0x0,
0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x12,0x0,0x0,0xb,0x12,0x1,0xd2,
0xdd,0x7e,0xfc,0x0,0x0,0x4,0xde,0x49,0x44,0x41,0x54,0x58,0xc3,0xe5,0x99,0x5d,
0x6c,0x53,0x65,0x18,0xc7,0x7f,0xe7,0x9c,0x7e,0x8c,0xae,0xb0,0xb1,0x75,0x2d,0x6c,
0xe0,0xf8,0x1c,0x88,0x1b,0x8e,0x38,0x3e,0x66,0x57,0x63,0x50,0x34,0xca,0x42,0xb8,
0x20,0x8c,0x2c,0xc8,0xa5,0x1f,0x5c,0x78,0x21,0xd,0xd9,0x15,0xa2,0x17,0x66,0x21,
0xf5,0xca,0x44,0x13,0xa3,0x17,0x6,0x62,0x84,0x18,0xdd,0xc5,0xd4,0x98,0x5d,0xcc,
0x58,0x60,0x40,0x34,0x45,0x8,0xa0,0x2c,0x30,0xe6,0x66,0xd9,0xca,0x68,0xbb,0xd2,
0x8f,0xad,0x3b,0x3d,0xc7,0x8b,0xd3,0x4f,0xc6,0x16,0xb0,0xcc,0xd6,0xf9,0xbf,0x7b,
0x3f,0xce,0x7b,0x9e,0xdf,0xf3,0x3c,0xef,0xf3,0xbe,0xed,0x11,0xc8,0x92,0xcb,0xe5,
0x3a,0xa,0x38,0x80,0x66,0x60,0x1,0xff,0x7d,0xc5,0x80,0x3e,0xc0,0xed,0x74,0x3a,
0x8f,0xa6,0x3a,0x85,0x24,0xec,0x2a,0xe0,0x4b,0x60,0x6b,0xa1,0xad,0x9c,0x43,0x9d,
0x7,0xda,0x9d,0x4e,0xe7,0x4d,0x5d,0xb2,0xe3,0x2b,0x60,0xb3,0xd5,0x6a,0xe5,0x39,
0x87,0x83,0xea,0xea,0x6a,0x74,0x3a,0x5d,0x1e,0xeb,0x17,0x87,0x64,0x59,0xc6,0xeb,
0xf5,0xf2,0xb3,0xdb,0x8d,0xcf,0xe7,0xdb,0x9a,0xe4,0xdc,0x22,0xb8,0x5c,0xae,0x23,
0xc0,0x7b,0x36,0x9b,0x8d,0xb6,0xbd,0x7b,0xe7,0x5,0xec,0x83,0xe0,0x4f,0x9e,0x3a,
0xc5,0xe8,0xe8,0x28,0xc0,0xbb,0x22,0xda,0x1e,0xa6,0xc5,0x6e,0x9f,0x97,0xc0,0x0,
0x3a,0x9d,0x8e,0x16,0xbb,0x3d,0xd5,0x74,0x88,0x80,0x1d,0xa0,0xa6,0xa6,0xa6,0xd0,
0xb6,0xcd,0xa9,0xb2,0xf8,0x1c,0x22,0xc9,0x2a,0x3d,0x5f,0xa3,0x9c,0x52,0x16,0x9f,
0x51,0x2c,0xb4,0x31,0x85,0xd0,0xff,0x12,0x3a,0xef,0x9c,0x1e,0xbc,0x9b,0x20,0x1a,
0x57,0x1,0xa8,0x5a,0xa8,0xf9,0xf0,0xdc,0xc0,0x54,0x7a,0x7c,0xdb,0x4a,0x3d,0x16,
0x73,0xc6,0xb7,0xcf,0x7c,0x3c,0xce,0xaf,0x7,0xcb,0xd2,0xed,0x6b,0xb7,0xe5,0x9c,
0xf5,0x6a,0x2b,0x25,0x4c,0x6,0x21,0xdd,0xfe,0xf4,0x4c,0x8c,0x45,0x46,0x81,0x7d,
0x4d,0x25,0xc5,0x3,0xfd,0xf9,0xf9,0x9,0x82,0x13,0x2a,0x81,0x9,0x95,0xb6,0x6,
0x3,0xab,0x2d,0x12,0x27,0x2f,0xc7,0x69,0x6b,0x30,0x70,0xf2,0x72,0x9c,0xd5,0x16,
0x89,0xc8,0xa4,0x4a,0xdf,0xc0,0xd4,0x3,0xd,0xdf,0xff,0x6d,0x84,0x9d,0x2b,0x34,
0x33,0xbe,0xbb,0x25,0xf3,0x4d,0x9b,0x99,0xda,0x4a,0x29,0xed,0x90,0xae,0x3f,0x34,
0x7,0xee,0xda,0x68,0xcc,0x71,0x46,0x41,0xa1,0x1,0xde,0x6a,0x2e,0xe1,0xc6,0x58,
0x22,0xdd,0x5e,0x59,0x2e,0xd2,0xda,0x60,0xe4,0xc2,0x90,0x16,0xc5,0x68,0x5c,0xe5,
0xaa,0x2f,0x31,0xe3,0xf3,0xef,0xbf,0x5a,0xca,0xb5,0xdb,0x32,0x3,0x41,0x25,0xd,
0x1c,0x8d,0xab,0x1c,0xfa,0x21,0xca,0xc1,0xcd,0x46,0xc2,0x93,0x2a,0x1d,0xdd,0x11,
0x3a,0x5b,0x4b,0x1f,0xb,0x78,0xd1,0xec,0xe9,0xdf,0xfe,0x92,0xd9,0x59,0xa7,0x4f,
0x3,0x77,0x74,0x47,0xd8,0xbd,0x4e,0x4f,0x6b,0x83,0x91,0x7d,0x4d,0x25,0x94,0x97,
0x8,0x74,0x74,0x47,0xd2,0x5b,0x69,0x5e,0x40,0x9f,0xfd,0x53,0xe6,0xe9,0x1a,0x1d,
0xd7,0x6e,0xcb,0xec,0x39,0x71,0x8f,0x7a,0x9b,0xc4,0xeb,0xf6,0xcc,0x6f,0x9e,0x8e,
0x17,0x4d,0xd4,0xdb,0x24,0xde,0xf8,0x3a,0x3c,0xad,0xe,0x3c,0xaa,0x8a,0xe2,0x70,
0x1e,0xb,0x2b,0x9c,0x19,0x49,0xd0,0x59,0x29,0xe1,0xf8,0x2c,0x84,0x7d,0x89,0xc4,
0xf0,0xb8,0xc2,0x91,0xef,0x23,0xd3,0xe6,0xb6,0x35,0x18,0xf8,0xa0,0x37,0xc6,0xf1,
0xf6,0x85,0x85,0x81,0xee,0xbe,0x3c,0xc9,0x40,0x50,0xc1,0x7d,0x73,0x8a,0xe1,0x71,
0x5,0x0,0x6f,0x48,0x61,0x20,0xa8,0xe4,0x8c,0xd5,0x55,0x49,0xb3,0xae,0x63,0x32,
0x8,0x6c,0x28,0x17,0xb9,0xe2,0x95,0xf9,0xf1,0x80,0x6,0x73,0xe7,0x9e,0xb6,0xde,
0x27,0x7d,0x13,0xd4,0xdb,0x24,0x1c,0xab,0xb4,0xd4,0x7f,0x72,0xa9,0x8e,0xd6,0x6,
0x63,0x5e,0x4e,0x4e,0x43,0xdf,0x19,0x1b,0x7b,0xe4,0x87,0x43,0x61,0x91,0xa9,0x84,
0x48,0x24,0x2a,0x13,0x9b,0xd4,0xa,0x4c,0x24,0xaa,0x32,0x95,0x10,0x8,0x85,0x23,
0xe9,0xb1,0xf1,0x90,0x4a,0x6c,0x52,0x4c,0xbe,0x43,0x7f,0xdf,0xbb,0xf4,0x44,0x42,
0x77,0x39,0x50,0x2f,0xf2,0xa1,0x3b,0xc1,0x47,0xaf,0x68,0xa9,0x6b,0xd1,0x18,0x31,
0xa,0x3a,0xcc,0x62,0x1c,0x8b,0x3e,0x92,0xb4,0x33,0x2f,0xde,0x5c,0xe8,0x7f,0xa2,
0x1d,0x6b,0x15,0x3c,0x23,0x22,0x5b,0x96,0x29,0xc,0x6,0x35,0xe8,0xda,0x72,0x15,
0x6f,0x58,0xca,0x19,0x7b,0x18,0x35,0x56,0x2b,0xf4,0x9f,0x96,0xe8,0xba,0x22,0x71,
0xdd,0x9f,0xa9,0xd0,0x97,0xfc,0x2,0x43,0x61,0x11,0xcf,0x48,0xa6,0xfc,0xb4,0x2c,
0x57,0x78,0x76,0xc5,0xc3,0xad,0xfb,0xd8,0xa1,0x1f,0xb7,0x9a,0x2a,0x55,0xac,0xa5,
0x2a,0x1b,0xac,0x19,0xa0,0xd0,0x25,0x89,0xf5,0x15,0x6a,0x8e,0xf3,0x2c,0xa5,0xf9,
0xbd,0xa7,0x28,0xaa,0x77,0x4f,0xbf,0x48,0xd7,0x15,0x89,0x5f,0xee,0xa,0xac,0xb7,
0xaa,0xc,0x6,0x5,0xae,0xfa,0x44,0xea,0xaa,0x54,0x16,0x19,0xc0,0x66,0x56,0x89,
0x4e,0x9,0x5c,0x18,0xd6,0xfa,0x2a,0x4c,0xf9,0x1d,0x5b,0x79,0x43,0xf,0x85,0xa1,
0xae,0x2a,0x63,0xc4,0x60,0x50,0xa0,0xda,0x9c,0x6b,0xd4,0xf2,0x72,0x95,0xf6,0x8d,
0x33,0x5f,0x4e,0x22,0x71,0x81,0xeb,0x7e,0x81,0xce,0x16,0x6d,0xce,0x17,0x57,0x25,
0x9a,0xee,0xdb,0x16,0xeb,0xaa,0x14,0x7e,0xf7,0xb,0x9c,0xf0,0xcc,0x5e,0x14,0x1f,
0x46,0x79,0xa5,0xf7,0xf0,0xf8,0xf4,0xdb,0xd1,0xd,0xbf,0xc0,0x46,0x5b,0x2e,0xf4,
0x2,0x3d,0x2c,0x2b,0x9b,0x39,0x3a,0xbb,0x9f,0xca,0x38,0xe4,0x98,0x5b,0xc7,0x9e,
0x35,0xca,0xb4,0xf9,0xb,0xf4,0xf0,0x4e,0x73,0x82,0xb7,0x7b,0x74,0xd8,0xcc,0x2a,
0x3b,0xd6,0x16,0x68,0x4f,0xff,0x74,0x53,0x64,0xd7,0x1a,0x85,0x63,0x6e,0x1d,0x43,
0x61,0x78,0xe1,0x9,0x95,0xae,0x41,0x91,0xed,0xab,0x64,0x7a,0xfa,0x45,0x86,0xc2,
0xda,0xbc,0xb3,0xb7,0x44,0x4e,0xf,0x69,0x49,0x65,0x99,0xe5,0xb4,0xf1,0x47,0x5,
0x16,0x19,0x54,0x5e,0xae,0x4b,0xd0,0xd3,0xaf,0xcd,0xbf,0xe4,0x17,0xd8,0xb4,0x44,
0x1b,0xaf,0x30,0xa9,0x74,0x3e,0x2f,0x33,0x16,0xc9,0xef,0x2a,0x9a,0x17,0xb4,0xd9,
0x0,0x2d,0x2b,0x14,0x6a,0xcb,0xb5,0xa8,0x98,0xc,0x70,0xc8,0xa0,0x62,0x32,0x80,
0x67,0x44,0x73,0x48,0x2a,0xf5,0x37,0x2d,0xd1,0x22,0xf3,0xd2,0xea,0xdc,0x35,0xb6,
0x2f,0xcd,0x44,0xb4,0xc2,0xa4,0xf2,0xe6,0x56,0x2d,0xea,0xa3,0x61,0x1,0x6f,0x58,
0x60,0xcf,0x1a,0x85,0x96,0xac,0x4a,0xbd,0xac,0x4c,0x9d,0x35,0x6b,0xe6,0x1c,0x3a,
0x95,0x96,0xd9,0x7b,0x3a,0x65,0xd0,0x61,0x47,0xe6,0xaa,0x58,0x57,0xa5,0xe6,0xcc,
0xc9,0x56,0xf6,0xbc,0x6c,0xed,0xdf,0x34,0x73,0xd,0xc8,0x57,0x45,0x51,0xbd,0xff,
0x6d,0xfd,0x6f,0xa1,0x63,0xa0,0xfd,0x37,0x3c,0x9f,0x95,0xc5,0x17,0x13,0x1,0x37,
0x80,0xcf,0xe7,0x2b,0xb4,0x5d,0x73,0xaa,0x2c,0xbe,0xd3,0x69,0x68,0x8f,0xc7,0x33,
0x6f,0xa3,0x2d,0xcb,0x32,0x1e,0x8f,0x27,0xd5,0x74,0xa7,0x3e,0xe0,0xf5,0x1,0xdb,
0x16,0x2f,0x5e,0x4c,0x63,0x63,0x23,0x56,0xab,0x15,0x83,0xc1,0x50,0x68,0x5b,0xf3,
0x56,0x3c,0x1e,0xc7,0xe7,0xf3,0x71,0xf1,0xe2,0x45,0x2,0x81,0x0,0xc0,0x39,0xa7,
0xd3,0xd9,0x9c,0x3a,0xb2,0xda,0x81,0xe3,0x81,0x40,0xc0,0xde,0xdb,0xdb,0x5b,0x68,
0x5b,0xe7,0x4a,0x67,0x80,0xd7,0x20,0xf9,0xa9,0x36,0x25,0x97,0xcb,0x75,0x18,0xed,
0xdb,0x96,0x3,0x28,0x7b,0xf4,0x75,0x8b,0x4e,0xe3,0x68,0xdb,0xd7,0xed,0x74,0x3a,
0x8f,0xa5,0x3a,0xff,0x6,0xdb,0xbd,0xd3,0xac,0xb6,0xc0,0x9e,0x1,0x0,0x0,0x0,
0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
// E:/new/Mainwindow/mainwindow/mainwindow/varList/background/e_06_3.png
0x0,0x0,0x5,0x51,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x3d,0x0,0x0,0x0,0x21,0x8,0x6,0x0,0x0,0x0,0x6a,0x76,0xa3,0x9,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,
0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,
0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,
0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,
0x62,0x4b,0x47,0x44,0x0,0x0,0x0,0x0,0x0,0x0,0xf9,0x43,0xbb,0x7f,0x0,0x0,
0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x12,0x0,0x0,0xb,0x12,0x1,0xd2,
0xdd,0x7e,0xfc,0x0,0x0,0x4,0xb5,0x49,0x44,0x41,0x54,0x58,0xc3,0xed,0x99,0x5d,
0x6c,0x14,0x55,0x14,0xc7,0x7f,0x77,0x66,0x3f,0xbb,0x45,0xca,0xd2,0x85,0x16,0x2c,
0x82,0x68,0x4b,0x95,0x52,0x36,0x56,0xa,0xd2,0x26,0x50,0x88,0x41,0xb2,0xf,0xf0,
0x62,0x2,0x29,0x31,0x11,0x35,0x86,0xd0,0xf8,0x60,0x40,0xe2,0x3,0x50,0x63,0x4c,
0x43,0xd4,0x44,0x9b,0x20,0x9,0xd1,0x4,0x25,0xa4,0x1a,0x13,0x8c,0x36,0x4,0x42,
0xa2,0xf,0x2d,0x14,0x84,0x66,0x15,0xb0,0x98,0x62,0xe5,0x4b,0x3e,0x64,0xcb,0x66,
0xdb,0x6e,0xbb,0xdf,0x73,0x7d,0xd8,0xdd,0x4e,0x17,0xa,0x86,0x4e,0xcb,0xd6,0xca,
0xff,0x69,0xee,0x9d,0x99,0x73,0xcf,0xef,0x9e,0x73,0xe6,0xde,0xcc,0x15,0xc,0x91,
0xbb,0xd1,0xbf,0x13,0xa8,0x6,0x96,0x0,0x76,0xfe,0xfb,0xa,0x1,0x6d,0x40,0x8b,
0xb7,0xce,0xb9,0x33,0xdd,0x29,0x52,0xb0,0x4f,0x2,0x7,0x80,0xca,0x6c,0x7b,0x39,
0x86,0x3a,0x9,0xac,0xf7,0xd6,0x39,0xff,0x34,0xa5,0x3a,0x9a,0x80,0xe7,0xe7,0xb9,
0x54,0xde,0x5a,0x62,0xa3,0xbc,0x40,0xc5,0x6a,0x12,0xd9,0x76,0xd2,0xb0,0x22,0x71,
0xc9,0xaf,0x37,0x13,0x7c,0xd2,0x16,0xe6,0x77,0x5f,0xa2,0x32,0xc5,0xb9,0x48,0xb8,
0x1b,0xfd,0xdb,0x81,0xfa,0x67,0xa6,0xa9,0xec,0x5d,0xe3,0xc0,0x36,0x1,0x60,0xef,
0x54,0x38,0x2e,0x79,0xfd,0xbb,0x7e,0x3a,0x6e,0x25,0x0,0x76,0x28,0x24,0x6b,0x98,
0xcd,0x95,0xb6,0x9,0x9,0xc,0x60,0x33,0x9,0x36,0x57,0xda,0xd2,0xcd,0x6a,0x5,
0x58,0xa,0xb0,0xb0,0x50,0xcd,0xb6,0x6f,0x63,0x2a,0xf7,0x8c,0x74,0x25,0x27,0xa1,
0xed,0xc0,0x84,0xa8,0xe1,0xfb,0xc9,0xa2,0xc7,0xd4,0xaa,0x64,0xdb,0x99,0x6c,0xe8,
0x11,0xf4,0x48,0x34,0x10,0x95,0x34,0x9d,0xe,0x1b,0x76,0xe4,0xfc,0x8d,0x38,0xdb,
0xf,0xf5,0x3f,0x14,0x68,0x93,0x51,0x3,0x3,0x51,0xc9,0xf1,0x2b,0x71,0x8e,0x5f,
0x9,0xd2,0xe0,0x71,0x70,0xf9,0x76,0x82,0xda,0x83,0xf7,0x77,0xbe,0xbe,0xda,0x86,
0xa7,0xcc,0xfa,0x50,0x0,0xc7,0x4,0x3a,0x3f,0x57,0xa1,0xc1,0xe3,0x60,0x5b,0x73,
0x3f,0xfb,0x4f,0x85,0x79,0x63,0xa9,0x9d,0xf6,0x4d,0x93,0x7,0xef,0x6f,0x38,0xd0,
0xc7,0xbb,0xcb,0xed,0x94,0x16,0xe,0x3f,0x54,0x77,0x50,0xc3,0xd7,0xa7,0xd1,0xd5,
0x9d,0x20,0x10,0x96,0x9c,0xbf,0x11,0x1f,0xbc,0xf7,0xc4,0x54,0xf5,0x9e,0x93,0x68,
0x64,0xe2,0xc,0x43,0x3,0xe4,0x58,0x4,0xd,0x1e,0xc7,0xb0,0x40,0x1d,0x1,0xed,
0x9e,0xc0,0x0,0x27,0x2e,0xc6,0xd8,0xd1,0xa2,0x97,0xc7,0xb1,0x21,0x80,0xfb,0xd7,
0x3a,0x86,0xbd,0xfe,0xac,0xcd,0x58,0x39,0x19,0x86,0x6e,0x3a,0x1d,0xa6,0x7c,0xa6,
0x89,0xd2,0x42,0x13,0x97,0x6f,0x27,0xf8,0xfc,0xa4,0xee,0x50,0x20,0x2c,0x99,0x6e,
0x13,0xc3,0xd6,0x6a,0xcd,0x53,0x66,0x96,0x15,0x5b,0xf0,0x94,0x59,0xf1,0x94,0x59,
0x69,0x3e,0x1b,0xe1,0xe7,0xab,0x71,0xde,0x5b,0x9d,0x84,0x7b,0x6e,0x77,0x4f,0xc6,
0xf3,0x43,0x27,0x2e,0xcf,0x66,0x6c,0x79,0x35,0xc,0x9d,0x6b,0x15,0xd4,0x1e,0xec,
0xa7,0xbe,0xda,0x46,0x4d,0x89,0x85,0x75,0xee,0x64,0xca,0x5,0x23,0x92,0x37,0xf,
0xd,0xf0,0xd1,0x4a,0x3b,0xc1,0x88,0x64,0xf7,0xa9,0x8,0xf5,0x35,0x76,0x72,0xad,
0x49,0x87,0x5d,0x93,0xb2,0xb7,0x70,0x18,0x86,0xf6,0x94,0x59,0x99,0x9b,0xaf,0xf2,
0xc1,0x4f,0x21,0x16,0xcf,0x31,0x53,0x5a,0x68,0x62,0x20,0x2a,0xd9,0xd6,0xdc,0xcf,
0x96,0x45,0x56,0x96,0x15,0x5b,0x0,0xb8,0xde,0xab,0xf1,0x43,0x47,0x94,0x6d,0x2b,
0x73,0xc8,0xb1,0x64,0x77,0x23,0x34,0x8,0xed,0xeb,0xee,0x1e,0xb1,0x91,0x7c,0x33,
0x7c,0xfc,0x22,0xc8,0x70,0x4,0xef,0xdf,0x82,0x3d,0xa7,0x55,0xe6,0x39,0x25,0x2b,
0x66,0x87,0xd9,0x72,0x30,0xcc,0xd6,0xea,0x38,0x6b,0x4b,0x60,0xbf,0x57,0xe5,0xd5,
0xaf,0x63,0x6c,0x2c,0xd7,0x58,0x38,0x43,0xcb,0xb0,0xd1,0x1b,0x54,0x30,0x4b,0x81,
0xaf,0x3b,0x94,0xea,0x31,0xe3,0xf,0xa4,0x53,0xdc,0x94,0xe1,0x5f,0x28,0x62,0xa2,
0x37,0x18,0xc1,0xd7,0xdd,0xf7,0x80,0x9e,0x9a,0x81,0x51,0xda,0x9c,0xf8,0x7,0x4,
0x9d,0x3e,0xc1,0x2f,0xd7,0x15,0x5e,0x3b,0x62,0xa2,0xa2,0x40,0x52,0xeb,0x4e,0x0,
0xf0,0xe3,0xd,0x3d,0xaa,0xb5,0xee,0x4,0x1b,0xcb,0x35,0x3e,0x3c,0xa5,0x72,0xf4,
0x42,0xe6,0xd0,0xde,0x9b,0xa,0x73,0x9d,0x72,0x34,0xdc,0xf9,0x57,0x8d,0xa,0x74,
0xfb,0x35,0xc1,0x97,0x67,0x54,0x4a,0x5c,0x1a,0x9f,0x2e,0x8f,0x13,0x8c,0xc2,0xf1,
0x4b,0xba,0xe9,0x4e,0x9f,0xe0,0xe8,0x5,0x85,0x4e,0x9f,0xe0,0xdb,0xf3,0xa,0x7b,
0x57,0xc7,0xa8,0x9a,0x9d,0x19,0xe9,0xab,0x41,0x70,0x39,0x1e,0x74,0xe4,0x2c,0x42,
0x77,0xf9,0x5,0x15,0x5,0x12,0xbb,0x19,0x8a,0xf2,0x24,0x87,0xaf,0x28,0xcc,0x9a,
0xa2,0x47,0x2d,0xc7,0x2,0xfb,0x3a,0x54,0x8a,0x5d,0x92,0x9e,0x28,0xb4,0x5e,0x52,
0xb0,0x9b,0xf5,0xf7,0xfd,0x3,0x82,0xb,0x7d,0x82,0x59,0x79,0x99,0x91,0xce,0x1f,
0xa3,0x49,0x18,0x15,0xe8,0xdf,0xfc,0x82,0xd9,0x29,0xc8,0xd6,0x4b,0xa,0xb,0x9c,
0x92,0xc7,0x27,0xeb,0x0,0xe9,0xeb,0x4e,0x9f,0x60,0x5d,0xa9,0xc6,0xbe,0xe,0x95,
0x50,0x4c,0x7f,0xbf,0xfd,0x9a,0xa0,0x62,0xaa,0xc4,0x99,0x93,0x9,0x7d,0x67,0x7b,
0xb4,0x64,0xf8,0xeb,0x9d,0x8e,0x52,0x89,0x4b,0x23,0x14,0x83,0xef,0xff,0x50,0x78,
0xe7,0x85,0xc4,0x5d,0xcf,0xad,0x9a,0xa5,0xd1,0x71,0x4b,0x61,0xcd,0xb3,0x9,0xe,
0x75,0x29,0x5c,0xd,0x8,0x8a,0x5d,0x92,0x50,0x2c,0x99,0x5,0x9b,0xca,0xf5,0x77,
0xfe,0xea,0xb9,0xfb,0xeb,0xbe,0xea,0x1b,0x73,0x46,0xdb,0x5d,0x90,0x45,0xe8,0xf6,
0x6b,0x82,0xa7,0x27,0xc9,0xc1,0x74,0x6d,0x7c,0x29,0x3e,0x58,0xc3,0x5d,0x7e,0xdd,
0xf9,0xd5,0x25,0x1a,0x76,0x73,0x32,0x72,0xef,0xaf,0xd0,0xb7,0x9a,0x47,0x3a,0x55,
0xa6,0x58,0x24,0xee,0x99,0x1a,0x7b,0x4e,0xaa,0xf4,0x46,0x5,0x67,0xfc,0x82,0x9a,
0xc2,0xcc,0x28,0x1f,0x7e,0x59,0x4f,0x8d,0x5d,0x2d,0xc6,0xdc,0x36,0xc,0xed,0x72,
0xc0,0xba,0x52,0xed,0xae,0x7e,0xef,0x4d,0x85,0xc7,0x2c,0x92,0x86,0xaa,0x64,0x4,
0xef,0x95,0xaa,0xd3,0x1c,0x92,0xba,0xa,0xd,0xbb,0x19,0x16,0x4c,0x97,0xf4,0xc7,
0x24,0x55,0x45,0xe0,0x9e,0x99,0xb4,0x99,0xef,0x80,0xb7,0xdd,0x99,0x99,0x53,0x55,
0xa4,0x91,0xef,0x18,0x79,0xea,0xb,0x77,0xa3,0x5f,0xde,0x39,0x93,0x13,0x55,0xe9,
0x12,0x79,0xf4,0x13,0xe1,0xff,0x22,0x85,0xe4,0xd1,0x7,0x91,0x84,0x41,0x4b,0xe3,
0x5c,0x43,0xf8,0x42,0xa,0xd0,0x2,0x70,0xce,0x37,0xb1,0xff,0x86,0xe,0xe1,0x6b,
0x1d,0x84,0xfe,0xe2,0xac,0x4a,0x38,0x3e,0x62,0x9b,0xe3,0x5a,0xe1,0x78,0x92,0x2f,
0xa5,0x96,0xf4,0x1,0x5e,0x1b,0xb0,0x78,0x4e,0x9e,0xe4,0x95,0xf9,0x1a,0xf3,0x5d,
0x1a,0xb9,0xe6,0x11,0x8f,0x31,0x6e,0x14,0x8c,0xc1,0x39,0x9f,0xc2,0xbe,0x73,0xa,
0x17,0x3,0x2,0xe0,0x84,0xb7,0xce,0xb9,0x24,0xbd,0x4e,0xaf,0x7,0xbe,0xba,0x18,
0x10,0x4b,0x77,0xb6,0xaa,0xc0,0x84,0x3c,0xed,0x38,0x6,0x6c,0x80,0xd4,0x51,0x6d,
0x5a,0xee,0x46,0xff,0x56,0x92,0x67,0x5b,0xd5,0xc0,0xe4,0x7,0xb7,0x3b,0xee,0xd4,
0x43,0xb2,0x7c,0x5b,0xbc,0x75,0xce,0x5d,0xe9,0xce,0x7f,0x0,0xa6,0x46,0xa7,0x83,
0xce,0xc4,0x8f,0x74,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
// E:/new/Mainwindow/mainwindow/mainwindow/varList/background/delete_01.png
0x0,0x0,0x5,0x72,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x3d,0x0,0x0,0x0,0x21,0x8,0x6,0x0,0x0,0x0,0x6a,0x76,0xa3,0x9,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,
0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,
0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,
0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,
0x62,0x4b,0x47,0x44,0x0,0x0,0x0,0x0,0x0,0x0,0xf9,0x43,0xbb,0x7f,0x0,0x0,
0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x12,0x0,0x0,0xb,0x12,0x1,0xd2,
0xdd,0x7e,0xfc,0x0,0x0,0x4,0xd6,0x49,0x44,0x41,0x54,0x58,0xc3,0xe5,0x99,0x5d,
0x4c,0x53,0x67,0x18,0xc7,0x7f,0x60,0xe3,0xb2,0x92,0x1,0x6a,0x53,0x3e,0x7a,0x81,
0x1,0x6e,0x2c,0x86,0xd0,0xc,0xea,0x14,0x90,0x68,0x88,0x77,0x96,0xa8,0x7c,0x44,
0x8,0x9,0x6,0xba,0x68,0x2,0x17,0x36,0xcd,0x76,0x76,0xb3,0xb9,0x90,0x8,0xd9,
0x4e,0xe4,0xc2,0xb,0xc9,0x8e,0x5e,0x11,0x16,0x70,0xc6,0x84,0x9a,0x78,0x61,0x50,
0x52,0x18,0x75,0x8b,0x17,0x85,0x92,0xd0,0xac,0x69,0x4a,0xea,0x22,0x96,0x8e,0xc0,
0x80,0x96,0x26,0xd,0x6e,0xbb,0x68,0x7b,0xd2,0xe,0x35,0x4a,0xd1,0x22,0xfe,0xae,
0xce,0xf3,0xbc,0xef,0x79,0xce,0xf3,0x7f,0xbf,0xdb,0x37,0x8d,0x38,0x44,0x51,0xbc,
0x2,0x54,0x3,0x47,0x81,0x4f,0xf9,0xf0,0x9,0x1,0x8f,0x81,0x9,0xb3,0xd9,0x7c,
0x25,0xe6,0x4c,0x8b,0x8a,0x2d,0x4,0x7e,0x6,0x8e,0xa4,0x3a,0xcb,0x77,0xc8,0xef,
0x40,0xb3,0xd9,0x6c,0xf6,0x28,0xa2,0x8e,0x21,0xa0,0x42,0xad,0x56,0x73,0xbc,0xba,
0x9a,0xfc,0xfc,0x7c,0x14,0xa,0x45,0x12,0xf1,0x77,0x6,0x1b,0x1b,0x1b,0xcc,0xcf,
0xcf,0x33,0x3e,0x31,0x81,0xdf,0xef,0x3f,0x12,0xd5,0xa9,0x4f,0x13,0x45,0xf1,0x5b,
0xe0,0xfb,0x9c,0x9c,0x1c,0x9a,0x1a,0x1b,0x77,0x85,0xd8,0x97,0x89,0x1f,0xbe,0x7d,
0x9b,0x85,0x85,0x5,0x80,0xef,0xd2,0x89,0xcc,0x61,0xaa,0x2a,0x2b,0x77,0xa5,0x60,
0x0,0x85,0x42,0x41,0x55,0x65,0x65,0xcc,0xac,0x4e,0x7,0x2a,0x1,0x34,0x1a,0x4d,
0xaa,0x73,0x7b,0xa7,0xc4,0xe9,0xab,0x4e,0x27,0xba,0x4a,0xef,0xd6,0x5e,0x8e,0x11,
0xa7,0xef,0x93,0xf4,0x54,0x27,0x93,0xa,0x3e,0x4a,0xd1,0x49,0x8f,0x69,0x8f,0xc7,
0x43,0x20,0x10,0x0,0x20,0x37,0x37,0x17,0x0,0xeb,0xf8,0xb8,0x5c,0x5e,0x73,0xfc,
0x38,0x6a,0xb5,0x5a,0xb6,0xd3,0xf7,0xec,0xe1,0x9f,0x17,0x2f,0x64,0xdb,0xe1,0x70,
0x24,0xc4,0x2b,0x2a,0x2a,0x22,0x23,0x23,0x43,0xb6,0xaf,0x5d,0xbb,0x46,0x56,0x56,
0x16,0xed,0xed,0xed,0xdb,0x26,0x3a,0xe9,0x9e,0xee,0xeb,0xeb,0xa3,0xa7,0xb7,0x97,
0xcb,0x26,0x13,0xd6,0xf1,0x71,0x7c,0x3e,0x1f,0xfd,0xfd,0xfd,0x0,0xf4,0xf7,0xf7,
0xe3,0xf3,0xf9,0xf0,0x78,0x3c,0xdc,0xba,0x75,0xeb,0xa5,0xef,0x97,0xe9,0x74,0x48,
0x92,0x84,0x24,0x49,0x94,0xe9,0x74,0xb1,0x6d,0x45,0x6e,0x90,0x9f,0x24,0x89,0x1f,
0x45,0x91,0x60,0x30,0xb8,0x6d,0xa2,0xb7,0x65,0xf5,0xfa,0x46,0x10,0xf8,0xc3,0xe5,
0x92,0x6d,0xed,0xa1,0x43,0x34,0xd4,0xd7,0x33,0x6e,0xb5,0x2,0x10,0x8,0x4,0x98,
0x9a,0x9a,0x7a,0xe5,0xfb,0xd7,0xaf,0x5f,0xc7,0xe1,0x70,0x30,0xeb,0x74,0x52,0x58,
0x58,0x8,0x40,0x30,0x18,0xa4,0xb1,0xa9,0x89,0xee,0xee,0x6e,0x56,0x57,0x56,0xe8,
0x30,0x1a,0xb9,0x29,0x49,0x9,0xa3,0x60,0xab,0xec,0x98,0x39,0xfd,0xe4,0xc9,0x13,
0x9a,0xcf,0x9f,0x97,0x5,0x77,0x18,0x8d,0x7c,0x69,0x34,0xd2,0x50,0x5f,0x4f,0x7b,
0x7b,0x3b,0xaa,0x3,0x7,0xe8,0x30,0x1a,0xb7,0xa5,0xc7,0x77,0x8c,0xe8,0xd1,0x87,
0xf,0xa9,0xa8,0xa8,0xc0,0xe1,0x70,0xf0,0x79,0x79,0x39,0x15,0xe5,0xe5,0x98,0x4c,
0x26,0xb9,0xbc,0xb7,0xb7,0x97,0x8a,0xf2,0x72,0xc,0x75,0x75,0x9b,0xd6,0x81,0xb7,
0x65,0x47,0x6c,0xce,0x7e,0xbf,0x9f,0xe1,0xe1,0x61,0x6e,0x4a,0x12,0x9f,0x65,0x66,
0xd2,0xd4,0xd4,0xc4,0xdc,0xdc,0x1c,0x5d,0x5d,0x5d,0x9b,0xea,0x5e,0xbc,0x78,0x91,
0xcb,0x26,0x13,0xf,0x47,0x47,0x53,0x23,0xfa,0x97,0x3b,0x77,0x98,0x75,0x3a,0x19,
0x1d,0x1d,0x65,0x6e,0x6e,0xe,0x80,0x3f,0x9f,0x3e,0x65,0xd6,0xe9,0x4c,0x28,0x2b,
0x29,0x29,0x79,0x6d,0x9c,0x8c,0x8c,0xc,0x4e,0x9c,0x38,0xc1,0xf4,0xf4,0x34,0xbe,
0xe7,0xcf,0x1,0xf0,0xf9,0x7c,0x0,0xf4,0x44,0x7b,0xb8,0xb6,0xb6,0x16,0x80,0xd2,
0xd2,0x52,0x1a,0xea,0xeb,0x93,0x6a,0x64,0x59,0xf4,0x5f,0x8b,0x8b,0x6f,0xfd,0xf2,
0xea,0xea,0x2a,0xe1,0x70,0x98,0x40,0x30,0xc8,0x7a,0x28,0x4,0x40,0x20,0x18,0x24,
0x1c,0xe,0x27,0x94,0xfd,0xbd,0xb2,0xc2,0x7a,0x28,0x24,0x7f,0xe3,0xff,0xdf,0x5a,
0xf,0x85,0x30,0x99,0x4c,0x7c,0x2d,0x8,0xdc,0xbd,0x7b,0x17,0x80,0xbc,0xfc,0x7c,
0x0,0x94,0x4a,0x25,0x59,0xd9,0xd9,0xb2,0xbd,0x95,0x3c,0x5f,0x29,0x7a,0x2b,0x18,
0xc,0x6,0x6c,0x36,0x1b,0x35,0x35,0x35,0xb8,0xdd,0x6e,0x0,0x8a,0x8b,0x8b,0xf1,
0x7a,0xbd,0x9,0x65,0x6f,0x82,0x5e,0xaf,0x67,0x72,0x72,0x92,0xc1,0xc1,0x41,0x66,
0x66,0x66,0x64,0xbf,0xd5,0x6a,0xc5,0xe5,0x72,0x61,0xb3,0xd9,0x64,0xdf,0xa9,0x53,
0xa7,0x38,0x79,0xf2,0x64,0x6a,0x44,0x6f,0x37,0x75,0x75,0x75,0xe4,0xe5,0xe5,0xa1,
0xd3,0xe9,0x64,0xdf,0xd2,0xd2,0x12,0x3a,0x9d,0x2e,0xa1,0xf1,0xe2,0xf,0x3b,0x5b,
0x61,0x47,0xac,0xde,0x16,0x8b,0x85,0xc1,0xc1,0x41,0x46,0x46,0x46,0x28,0x2d,0x2d,
0xc5,0xed,0x76,0x63,0xb7,0xdb,0xd1,0x6a,0xb5,0xec,0xdf,0xbf,0x1f,0x8d,0x46,0x43,
0x20,0x10,0xc0,0x6a,0xb5,0xa2,0xd5,0x6a,0x51,0xa9,0x54,0xa9,0x15,0xed,0x72,0xb9,
0xd0,0x6a,0xb5,0xb2,0xed,0x76,0xbb,0x29,0x28,0x28,0x48,0xa8,0x73,0xf0,0xe0,0x41,
0x2e,0x5d,0xba,0xf4,0xca,0x18,0x6b,0x6b,0x6b,0xcc,0xcc,0xcc,0x70,0xef,0xde,0x3d,
0x0,0x7a,0x7a,0x7a,0xa8,0xaa,0xaa,0x4a,0xa8,0x73,0xf8,0xf0,0x61,0xec,0x76,0x3b,
0x37,0x6e,0xdc,0x48,0xba,0x91,0x93,0x1a,0xde,0x5e,0xaf,0x77,0x93,0x6f,0x76,0x76,
0x16,0xbd,0x5e,0x9f,0xe0,0x53,0x2a,0x95,0x9b,0x1a,0x22,0x9e,0x96,0x96,0x16,0xf9,
0x59,0x10,0x4,0x3a,0x3b,0x3b,0x37,0xd5,0x57,0x2a,0x95,0x5c,0xbd,0x7a,0x95,0xd3,
0xa7,0x4f,0xa3,0xd1,0x68,0x30,0x18,0xc,0xa9,0x11,0x7d,0xff,0xfe,0x7d,0xda,0xda,
0xda,0x10,0x4,0x1,0x97,0xcb,0xc5,0xb9,0x73,0xe7,0xe8,0xeb,0xeb,0x63,0x6c,0x6c,
0xc,0x8b,0xc5,0x82,0x2b,0x7a,0x34,0x7d,0xf4,0xe8,0x11,0xf,0x1e,0x3c,0x0,0x90,
0x8f,0x99,0x2f,0x63,0x71,0x71,0x91,0xec,0xec,0x6c,0xce,0x9c,0x39,0x83,0xc5,0x62,
0x1,0x22,0xb,0xd9,0xb1,0x63,0xc7,0x0,0x50,0xa9,0x54,0xc,0xd,0xd,0x25,0x9c,
0xcf,0xdf,0xbb,0xe8,0xcc,0xcc,0x4c,0x6a,0x6b,0x6b,0x29,0x2e,0x2e,0x6,0x22,0xfb,
0xad,0x14,0x3d,0x1f,0xdb,0x6c,0x36,0xda,0xda,0xda,0xe4,0xa1,0x1f,0x4b,0xfc,0xec,
0xd9,0xb3,0x9,0x31,0x2e,0x5c,0xb8,0x20,0x3f,0xab,0x54,0x2a,0x4,0x41,0x0,0xe0,
0xd9,0xb3,0x67,0x78,0xbd,0x5e,0x3a,0x3b,0x3b,0xe5,0x3d,0x1a,0xa0,0xa0,0xa0,0xe0,
0xb5,0xa3,0xe6,0x4d,0x48,0x13,0x45,0xf1,0x5f,0x80,0xd6,0xd6,0xd6,0xa4,0x2,0x7d,
0x8,0xc,0xc,0xc,0x0,0x3b,0x64,0xf5,0x7e,0xdf,0x7c,0xb4,0xa2,0x43,0x10,0xf9,
0x6f,0x78,0x37,0x13,0xa7,0x2f,0x94,0xe,0x4c,0x40,0xe4,0x97,0xce,0x6e,0x26,0x4e,
0xdf,0xaf,0xb2,0x68,0xbb,0xdd,0xbe,0x6b,0x7b,0x7b,0x63,0x63,0x3,0xbb,0xdd,0x1e,
0x33,0x27,0x62,0x17,0x78,0x8f,0x81,0x2f,0xf6,0xed,0xdb,0x47,0x59,0x59,0x19,0x6a,
0xb5,0x9a,0xbd,0x7b,0xf7,0xa6,0x3a,0xd7,0xa4,0x9,0x87,0xc3,0xf8,0xfd,0x7e,0xa6,
0xa6,0xa6,0x58,0x5e,0x5e,0x6,0xf8,0xcd,0x6c,0x36,0x1f,0x8d,0xed,0xd3,0xcd,0xc0,
0xc0,0xf2,0xf2,0x72,0xe5,0xd8,0xd8,0x58,0xaa,0x73,0x7d,0x57,0x4c,0x2,0xad,0x10,
0xbd,0xaa,0x8d,0x21,0x8a,0xe2,0x57,0x44,0xee,0xb6,0xaa,0x81,0xac,0x54,0x67,0xb9,
0xd,0xac,0x10,0x99,0xbe,0x13,0x66,0xb3,0xf9,0x87,0x98,0xf3,0x3f,0xa4,0x8e,0xd5,
0xf9,0xb,0xd2,0x44,0x4c,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,
0x82,
// E:/new/Mainwindow/mainwindow/mainwindow/varList/background/e_06_2.png
0x0,0x0,0x5,0x5e,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x3d,0x0,0x0,0x0,0x21,0x8,0x6,0x0,0x0,0x0,0x6a,0x76,0xa3,0x9,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,
0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,
0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,
0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,
0x62,0x4b,0x47,0x44,0x0,0x0,0x0,0x0,0x0,0x0,0xf9,0x43,0xbb,0x7f,0x0,0x0,
0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x12,0x0,0x0,0xb,0x12,0x1,0xd2,
0xdd,0x7e,0xfc,0x0,0x0,0x4,0xc2,0x49,0x44,0x41,0x54,0x58,0xc3,0xed,0x99,0x5f,
0x6c,0x53,0x55,0x1c,0xc7,0x3f,0xf7,0xf6,0xdf,0xba,0x82,0xb0,0xb1,0x76,0x6c,0x13,
0x9c,0x22,0x9b,0x8b,0x19,0x5b,0xe3,0xe4,0x5f,0x57,0x3,0x3,0xd,0x2e,0x7d,0x90,
0x17,0xc,0x64,0xbc,0x88,0x31,0x86,0xc4,0x27,0xb,0x12,0x1f,0x80,0x19,0x63,0x16,
0x52,0x7d,0xd0,0x4,0x49,0x8c,0xf,0x28,0x21,0x40,0x4c,0x48,0x94,0x10,0x8,0x9,
0x4b,0x2c,0xff,0x26,0x2c,0x5d,0x30,0x8e,0x64,0x38,0xe5,0x8f,0xc,0xd6,0x8e,0xee,
0x5f,0xb7,0xfe,0xbb,0xbd,0xc7,0x87,0xb6,0x6b,0xcb,0x36,0x3,0xeb,0x46,0x61,0xf2,
0x7d,0xba,0xe7,0xdc,0x7b,0xce,0xfd,0x7e,0xce,0xef,0xf7,0x3b,0xb7,0xe9,0x91,0x48,
0x93,0xcb,0xe5,0xda,0xb,0xd8,0x81,0x55,0x80,0x91,0xa7,0x5f,0x41,0xe0,0x22,0xe0,
0x76,0x3a,0x9d,0x7b,0x93,0x9d,0x52,0x2,0xf6,0x25,0xe0,0x30,0xb0,0x22,0xd7,0x2e,
0x67,0x50,0x6d,0xc0,0x16,0xa7,0xd3,0xf9,0x97,0x36,0xd1,0x71,0x4,0x78,0xdd,0x62,
0xb1,0xf0,0x86,0xdd,0x4e,0x69,0x69,0x29,0x5a,0xad,0x36,0x8b,0xf9,0x9f,0xc,0x29,
0x8a,0x42,0x4f,0x4f,0xf,0xbf,0xba,0xdd,0x78,0xbd,0xde,0x15,0x9,0xce,0xe5,0x92,
0xcb,0xe5,0xda,0xd,0x34,0x17,0x17,0x17,0xf3,0xee,0xa6,0x4d,0xb3,0x2,0x76,0x22,
0xf8,0xa3,0xc7,0x8e,0xd1,0xdb,0xdb,0xb,0xb0,0x47,0x26,0x5e,0xc3,0xd4,0xdb,0x6c,
0xb3,0x12,0x18,0x40,0xab,0xd5,0x52,0x6f,0xb3,0x25,0x9b,0x76,0x19,0xb0,0x1,0x94,
0x95,0x95,0xe5,0xda,0xdb,0x8c,0x2a,0x8d,0xcf,0x2e,0x93,0xd8,0xa5,0x67,0x6b,0x94,
0x93,0x4a,0xe3,0x33,0xc8,0xb9,0x36,0x93,0xb,0x3d,0x83,0x9e,0x8a,0x46,0x23,0x82,
0x23,0x57,0x42,0x59,0x1b,0xb9,0x76,0x57,0x61,0xf7,0xc9,0x91,0xc7,0x2,0x9d,0x75,
0x21,0x8f,0x46,0x4,0x17,0x6e,0x29,0x5c,0xb8,0x15,0xa0,0xc5,0x61,0xe2,0xe6,0xfd,
0x18,0x4d,0xc7,0xff,0xdb,0x7c,0xb3,0x3d,0xf,0x47,0xb5,0xe1,0xb1,0x0,0xce,0x8,
0x74,0xd1,0x1c,0x99,0x16,0x87,0x89,0x5d,0x27,0x46,0x38,0x74,0x39,0xc4,0x7,0x36,
0x23,0xed,0xdb,0xe7,0x8d,0xdd,0xdf,0x7a,0x78,0x98,0x4f,0xd7,0x1a,0xa9,0x2a,0x99,
0xf8,0x55,0x7d,0x1,0x15,0xdf,0xb0,0x4a,0x77,0x5f,0x8c,0x81,0x90,0xe0,0xda,0x5d,
0x65,0xec,0xde,0xb,0xb,0x34,0x93,0x2e,0x62,0x36,0xb,0x37,0x2d,0x5b,0x76,0xbe,
0x5e,0xa2,0xc5,0x61,0x9a,0x10,0xa8,0x73,0x40,0x9d,0x14,0x18,0xe0,0xd2,0xdf,0x51,
0xf6,0xb8,0x53,0xe5,0x71,0x3e,0xd,0xf0,0xd0,0x46,0xd3,0x84,0xd7,0xdf,0x5e,0xcc,
0xae,0x9c,0xb2,0x86,0x3e,0x72,0x25,0x44,0x4d,0x99,0x96,0xaa,0x12,0x2d,0x37,0xef,
0xc7,0xf8,0xbe,0x2d,0x65,0x68,0x20,0x24,0x28,0xce,0x93,0x26,0xac,0xd5,0x86,0x97,
0x75,0xac,0xa9,0xd0,0xe3,0xa8,0x36,0xe0,0xa8,0x36,0x70,0xe2,0xf7,0x30,0xbf,0xdd,
0x56,0xf8,0xac,0x31,0xe,0xf7,0xda,0xfe,0xc1,0x8c,0xe7,0xd3,0x17,0x6e,0x7e,0x9e,
0x94,0x5b,0xe8,0x39,0x6,0x89,0xa6,0xe3,0x23,0x34,0xdb,0xf3,0x68,0xa8,0xd4,0xb3,
0xd9,0x1a,0x4f,0xb9,0x40,0x58,0xf0,0xe1,0xc9,0x51,0xbe,0x5c,0x6f,0x24,0x10,0x16,
0xec,0xbf,0x1c,0xa6,0xb9,0xc1,0xc8,0x1c,0x43,0xdc,0xb0,0x79,0x6e,0xee,0x3e,0x1c,
0x59,0x43,0x3b,0xaa,0xd,0x2c,0x29,0xd2,0xf0,0x45,0x6b,0x90,0x95,0x2f,0xea,0xa8,
0x2a,0xd1,0x32,0x1a,0x11,0xec,0x3a,0x31,0xc2,0x8e,0xe5,0x6,0xd6,0x54,0xe8,0x1,
0xe8,0x19,0x52,0xf9,0xa5,0x33,0xc2,0xae,0xf5,0xf9,0xe4,0xeb,0xb3,0x8b,0xd4,0xb4,
0x41,0xfb,0xfa,0xfa,0xa6,0x3c,0x49,0x91,0xe,0xbe,0x7a,0xb,0x44,0x28,0x8c,0xa7,
0x57,0xe2,0xc0,0x15,0xd,0xaf,0x14,0xa,0xd6,0x95,0x87,0xd8,0x71,0x3c,0xc4,0x4e,
0xbb,0xc2,0xc6,0x4a,0x38,0xe4,0xd1,0xf0,0xde,0xd1,0x28,0xdb,0x6a,0x54,0x6a,0x4b,
0xd5,0x8c,0x39,0x86,0x2,0x32,0x3a,0x21,0xe1,0xeb,0xb,0x26,0x7a,0x74,0xf8,0x7,
0x92,0x29,0xae,0xcd,0xf0,0x17,0xc,0x6b,0x19,0xa,0x84,0xf1,0xf5,0xd,0x4f,0xc9,
0xef,0xb4,0xe4,0x98,0x7f,0x54,0xa2,0xcb,0x27,0xd1,0xd1,0x23,0xf3,0xfe,0x69,0x2d,
0x75,0xb,0x5,0x4d,0xd6,0x18,0x0,0x67,0xef,0xa6,0xa2,0xda,0x64,0x8d,0xb1,0xad,
0x46,0xc5,0x75,0x59,0xc3,0x99,0xeb,0x99,0xaf,0xf6,0xdc,0x93,0x59,0x52,0x28,0xa6,
0xc3,0xce,0xe3,0x81,0x6e,0xbf,0x23,0xf1,0xc3,0x55,0xd,0x95,0x66,0x95,0xaf,0xd7,
0x2a,0x4,0x22,0x70,0xe1,0x46,0x6a,0xea,0x2e,0x9f,0xc4,0x99,0xeb,0x32,0x5d,0x3e,
0x89,0x9f,0xae,0xc9,0x7c,0xd7,0x18,0xa5,0xbe,0x3c,0x33,0xd2,0xb7,0x3,0x60,0x36,
0x3d,0xea,0x9b,0x73,0x8,0xdd,0xed,0x97,0xa8,0x5b,0x28,0x30,0xea,0x60,0xd1,0x7c,
0xc1,0xa9,0x5b,0x32,0x8b,0xb,0x52,0x51,0xcb,0xd7,0xc3,0xc1,0x4e,0xd,0x15,0x66,
0xc1,0x60,0x4,0xce,0xdd,0x90,0x31,0xea,0x52,0xe3,0xfd,0xa3,0x12,0xd7,0x87,0x25,
0x16,0xcf,0xcf,0x8c,0x74,0xd1,0xc,0x2d,0xc2,0xb4,0x40,0xff,0xe1,0x97,0x28,0x4f,
0x40,0x9e,0xbb,0x21,0xb3,0xac,0x50,0xf0,0xfc,0xbc,0x14,0x40,0xf2,0xba,0xcb,0x27,
0xb1,0xb9,0x4a,0xe5,0x60,0xa7,0x86,0x60,0x34,0x35,0xbe,0xfd,0x8e,0x44,0xdd,0x2,
0x41,0x61,0x7e,0x26,0xf4,0x83,0xed,0xe9,0x52,0xd6,0xbb,0x77,0x32,0x4a,0x95,0x66,
0x95,0x60,0x14,0x7e,0xfe,0x53,0xe6,0x93,0xd5,0xb1,0x71,0xcf,0x6d,0x58,0xac,0xd2,
0xe9,0x95,0x79,0xe7,0xd5,0x18,0x27,0xbb,0x65,0x6e,0xf,0x48,0x54,0x98,0x5,0xc1,
0x68,0x3c,0xb,0xb6,0xd7,0xa4,0xc6,0xfc,0x33,0x38,0x7e,0x77,0xdf,0x70,0x4c,0x97,
0xd1,0xb6,0x2e,0xcc,0x21,0x74,0xfb,0x1d,0x89,0xa5,0x73,0xc5,0x58,0xba,0x7e,0xf3,
0xb6,0x32,0x56,0xc3,0xdd,0xfe,0x94,0xf9,0xc6,0x4a,0x15,0xa3,0x2e,0x1e,0xb9,0xcf,
0xd7,0xa5,0x7e,0x6a,0x9e,0xee,0xd2,0x50,0xa0,0x17,0x58,0xcb,0x54,0xe,0xb4,0x69,
0x18,0x8a,0x48,0x5c,0xf5,0x4b,0x34,0x94,0x64,0x46,0xf9,0xd4,0xa6,0x54,0x6a,0xec,
0x73,0x67,0x67,0x3b,0x6b,0x68,0xb3,0x9,0x36,0x57,0xa9,0xe3,0xfa,0x3d,0xf7,0x64,
0x9e,0xd3,0xb,0x5a,0xea,0xe3,0x11,0x9c,0x2c,0x55,0x2d,0x26,0xc1,0x47,0x75,0x2a,
0x46,0x1d,0x2c,0x2b,0x16,0x8c,0x44,0x5,0xf5,0x8b,0xc0,0x5a,0x16,0x9f,0xb3,0xc8,
0x4,0x1f,0x5b,0x33,0x33,0xa7,0x7e,0x91,0x4a,0x91,0x69,0xea,0xa9,0x9f,0x35,0xf4,
0x83,0xdf,0x5b,0x80,0xa,0xb3,0x60,0xa7,0x59,0x79,0xa8,0xf1,0xab,0xd3,0x76,0xf1,
0xd5,0xe5,0xe3,0xe7,0x2a,0xcc,0x17,0xbc,0xb9,0x54,0x4c,0x3a,0x66,0x2a,0x7a,0xf6,
0x27,0xc2,0xff,0x45,0x32,0xf1,0xa3,0xf,0x14,0xe5,0xe1,0xd2,0xf1,0x69,0x55,0x1a,
0x5f,0x50,0x6,0xdc,0x0,0x5e,0xaf,0x37,0xd7,0xbe,0x66,0x54,0x69,0x7c,0xe7,0xc6,
0xa0,0x3d,0x1e,0xcf,0xac,0x8d,0xb6,0xa2,0x28,0x78,0x3c,0x9e,0x64,0xd3,0x9d,0x3c,
0xc0,0xbb,0x8,0xac,0x2c,0x28,0x28,0xa0,0xb6,0xb6,0x16,0x8b,0xc5,0x82,0x5e,0xaf,
0xcf,0xb5,0xd7,0xac,0x15,0x89,0x44,0xf0,0x7a,0xbd,0x74,0x74,0x74,0xd0,0xdf,0xdf,
0xf,0x70,0xc9,0xe9,0x74,0xae,0x4a,0x7e,0xb2,0xb6,0x0,0x3f,0xf6,0xf7,0xf7,0xdb,
0x5a,0x5b,0x5b,0x73,0xed,0x75,0xa6,0x74,0x1e,0xd8,0xa,0x89,0xa3,0xda,0xa4,0x5c,
0x2e,0xd7,0x4e,0xe2,0x67,0x5b,0x76,0x60,0xde,0xa3,0xcf,0xfb,0xc4,0x69,0x90,0x78,
0xf9,0xba,0x9d,0x4e,0xe7,0xbe,0x64,0xe7,0xbf,0x42,0xaa,0xb7,0x47,0xdd,0xd5,0x25,
0xe3,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
};
static const unsigned char qt_resource_name[] = {
// varList
0x0,0x7,
0xc,0x87,0x30,0x44,
0x0,0x76,
0x0,0x61,0x0,0x72,0x0,0x4c,0x0,0x69,0x0,0x73,0x0,0x74,
// background
0x0,0xa,
0x1,0xe4,0x67,0x4,
0x0,0x62,
0x0,0x61,0x0,0x63,0x0,0x6b,0x0,0x67,0x0,0x72,0x0,0x6f,0x0,0x75,0x0,0x6e,0x0,0x64,
// e_06_1.png
0x0,0xa,
0xc,0x31,0x33,0x27,
0x0,0x65,
0x0,0x5f,0x0,0x30,0x0,0x36,0x0,0x5f,0x0,0x31,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// delete_03.png
0x0,0xd,
0x7,0xb3,0xc3,0x87,
0x0,0x64,
0x0,0x65,0x0,0x6c,0x0,0x65,0x0,0x74,0x0,0x65,0x0,0x5f,0x0,0x30,0x0,0x33,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// delete_02.png
0x0,0xd,
0x7,0xb0,0xc3,0x87,
0x0,0x64,
0x0,0x65,0x0,0x6c,0x0,0x65,0x0,0x74,0x0,0x65,0x0,0x5f,0x0,0x30,0x0,0x32,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// e_06_3.png
0x0,0xa,
0xc,0x2b,0x33,0x27,
0x0,0x65,
0x0,0x5f,0x0,0x30,0x0,0x36,0x0,0x5f,0x0,0x33,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// delete_01.png
0x0,0xd,
0x7,0xb9,0xc3,0x87,
0x0,0x64,
0x0,0x65,0x0,0x6c,0x0,0x65,0x0,0x74,0x0,0x65,0x0,0x5f,0x0,0x30,0x0,0x31,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// e_06_2.png
0x0,0xa,
0xc,0x28,0x33,0x27,
0x0,0x65,
0x0,0x5f,0x0,0x30,0x0,0x36,0x0,0x5f,0x0,0x32,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
};
static const unsigned char qt_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
// :/varList
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2,
// :/varList/background
0x0,0x0,0x0,0x14,0x0,0x2,0x0,0x0,0x0,0x6,0x0,0x0,0x0,0x3,
// :/varList/background/delete_02.png
0x0,0x0,0x0,0x68,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xa,0xbb,
// :/varList/background/delete_03.png
0x0,0x0,0x0,0x48,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x5,0x41,
// :/varList/background/delete_01.png
0x0,0x0,0x0,0xa2,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x15,0x8e,
// :/varList/background/e_06_2.png
0x0,0x0,0x0,0xc2,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x1b,0x4,
// :/varList/background/e_06_3.png
0x0,0x0,0x0,0x88,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x10,0x39,
// :/varList/background/e_06_1.png
0x0,0x0,0x0,0x2e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
};
#ifdef QT_NAMESPACE
# define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name
# define QT_RCC_MANGLE_NAMESPACE0(x) x
# define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b
# define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b)
# define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \
QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE))
#else
# define QT_RCC_PREPEND_NAMESPACE(name) name
# define QT_RCC_MANGLE_NAMESPACE(name) name
#endif
#ifdef QT_NAMESPACE
namespace QT_NAMESPACE {
#endif
bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *);
bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *);
#ifdef QT_NAMESPACE
}
#endif
int QT_RCC_MANGLE_NAMESPACE(qInitResources_varlistbackground)();
int QT_RCC_MANGLE_NAMESPACE(qInitResources_varlistbackground)()
{
QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData)
(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_varlistbackground)();
int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_varlistbackground)()
{
QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData)
(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
namespace {
struct initializer {
initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_varlistbackground)(); }
~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_varlistbackground)(); }
} dummy;
}
| billhhh/whLBS | Framework/Mainwindow/mainwindow/mainwindow/GeneratedFiles/qrc_varlistbackground.cpp | C++ | gpl-3.0 | 46,694 |
<?php
class plenitude extends usuario{
public function get_url($array=true){
if($array)
return explode('/', $_SERVER['REQUEST_URI']);
else
return $_SERVER['REQUEST_URI'];
}
public function run(){
$url = self::get_url();
$todo = self::processa($url);
}
function processa($url){
switch(strtolower($url[1])){
case "javascript":
self::compress('js');
break;
case "css":
$tipo = "css";
$content = $url[2];
include_once "compressor_1.php";
break;
case "central":
$path = PASTA_PAGINAS.'/cfg/'.$url[2];
if(file_exists($path)){
header ("content-type: text/xml");
include_once $path;
}else{
}
break;
case "pagina":
$path = PASTA_PAGINAS.'/php/'.$url[2].'.php';
if(file_exists($path)){
header ("content-type: text/html");
include_once $path;
}else{
}
break;
case "req":
$fp = fopen('/debug.txt','w+');
fwrite($fp,$_POST." -> ".date('h:i:s'));
fclose($fp);
$path = PASTA_AJAX.'/'.$url[2].'.php';
if(file_exists($path)){
include_once $path;
}else{
echo "nop: ".$path;
}
break;
case "sair":
unset($_SESSION);
session_destroy();
default:
if(parent::check_online() == true){
parent::reload_info();
include_once "default.php";
}else{
include_once "login.php";
}
}
}
function desenhar_icones($max_coluna){
$icone = self::get_icones();
$total_de_icones = count($icone);
$altura = 0;
$cnt_coluna = 0;
$esquerda = 0;
for($i=0;$i<=$total_de_icones-1;$i++){
if($cnt_coluna == $max_coluna){
$esquerda += 70;
$cnt_coluna = 0;
$altura = 0;
}
echo"<div id=\"icone_".$i."\" class=\"icone\" style=\"left:".$esquerda."px; top:".$altura."px;\">
<div class=\"icone_imagem\">
<img src=\"media/icone/".$icone[$i]['img']."\" width=\"40\" height=\"60\" alt=\"".$icone[$i]['titulo']."\" />
</div>
<div class=\"icone_texto\">
<a href=\"pagina/".$icone[$i]['link']."\">".utf8_encode($icone[$i]['titulo'])."</a>
</div>
</div>";
$altura += 90;
$cnt_coluna++;
}
}
function get_icones(){
if(parent::getAutParam('id_tipo') == 1 || parent::getAutParam('id_tipo') == 3)
$query = "SELECT * FROM icone INNER JOIN iconextipo AS crz ON crz.id_icone = icone.idicone WHERE crz.id_tipo = 0 OR crz.id_tipo = ".parent::getAutParam('id_tipo');
else
$query = "SELECT * FROM icone INNER JOIN iconextipo AS crz ON crz.id_icone = icone.idicone WHERE crz.id_tipo = 0 OR crz.id_tipo = ".parent::getAutParam('id_tipo')." AND crz.depto = ".parent::getUserParam('Departamento');
$db = $GLOBALS['db'];
$db->abre(1);
$res = $db->query($query, 1);
$db->fecha(1);
return $res;
}
}
| dansoah/plenitude-alfa | _sistema/php/plenitude.class.php | PHP | gpl-3.0 | 2,756 |
# Mila
Repository to host lecture slides and code examples of master course "Modeling in Landscape Archaeology"
What is covered in the course aka what will you find here?
- [an intro to R](html/00_Intro_R.html)
- [a first look at the data we are using](html/01_Inspect_data_and_ask_questions.html)
- [handling spatial data](html/02_Spatial_Data.html)
- [intro to point pattern](html/03_PointPattern.html)
- [raster analyses](html/04_Raster_analysis.html)
- [a very short intro to interpolation](html/05_Interpolation.html)
- [an application of viewsheds and least-cost paths](html/06_Viewshed_ShortestPath.html)
- [and something more or less different regarding least-cost paths](html/06_Distance_analyses.html)
For more detailed information about "Modeling in Landscape Archaeology" you can also have a look at the github repository of the book from Oliver Nakoinz and me:
- [http://dakni.github.io/mhbil/](http://dakni.github.io/mhbil/)
- or directly [https://github.com/dakni/mhbil](https://github.com/dakni/mhbil)
In order to make sense of the code that you find there: read the book ;)
- [Worldcat link](http://www.worldcat.org/oclc/933567741)
- [online fulltext for FU students via Primo FU](https://primo.fu-berlin.de/FUB:FUB_ALMA_DS51960803280002883)
- [at Springer](http://www.springer.com/de/book/9783319295367)
<p align="center">
<img src="https://images.springer.com/sgw/books/medium/9783319295367.jpg" width="150"/>
</p>
| dakni/mila | README.md | Markdown | gpl-3.0 | 1,449 |
/*
Copyright (c) 2010-2011 Gluster, Inc. <http://www.gluster.com>
This file is part of GlusterFS.
GlusterFS 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.
GlusterFS 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/>.
*/
#ifndef _CONFIG_H
#define _CONFIG_H
#include "config.h"
#endif
#include "rpcsvc.h"
#include "list.h"
#include "dict.h"
#include "xdr-rpc.h"
int
auth_unix_request_init (rpcsvc_request_t *req, void *priv)
{
if (!req)
return -1;
memset (req->verf.authdata, 0, RPCSVC_MAX_AUTH_BYTES);
req->verf.datalen = 0;
req->verf.flavour = AUTH_NULL;
return 0;
}
int auth_unix_authenticate (rpcsvc_request_t *req, void *priv)
{
int ret = RPCSVC_AUTH_REJECT;
struct authunix_parms aup;
char machname[MAX_MACHINE_NAME];
if (!req)
return ret;
ret = xdr_to_auth_unix_cred (req->cred.authdata, req->cred.datalen,
&aup, machname, req->auxgids);
if (ret == -1) {
gf_log ("", GF_LOG_WARNING, "failed to decode unix credentials");
ret = RPCSVC_AUTH_REJECT;
goto err;
}
req->uid = aup.aup_uid;
req->gid = aup.aup_gid;
req->auxgidcount = aup.aup_len;
gf_log (GF_RPCSVC, GF_LOG_TRACE, "Auth Info: machine name: %s, uid: %d"
", gid: %d", machname, req->uid, req->gid);
ret = RPCSVC_AUTH_ACCEPT;
err:
return ret;
}
rpcsvc_auth_ops_t auth_unix_ops = {
.transport_init = NULL,
.request_init = auth_unix_request_init,
.authenticate = auth_unix_authenticate
};
rpcsvc_auth_t rpcsvc_auth_unix = {
.authname = "AUTH_UNIX",
.authnum = AUTH_UNIX,
.authops = &auth_unix_ops,
.authprivate = NULL
};
rpcsvc_auth_t *
rpcsvc_auth_unix_init (rpcsvc_t *svc, dict_t *options)
{
return &rpcsvc_auth_unix;
}
| vbellur/glusterfs-udp | rpc/rpc-lib/src/auth-unix.c | C | gpl-3.0 | 2,548 |
/*
* Strategy implementation
* .setup function: Set up triggers, which listen to specific
* incoming or outgoing packets, and bind
* triggers to these events.
* .teardown function: Unbind triggers.
*
*/
#include "old_ooo_tcp_fragment.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "globals.h"
#include "socket.h"
#include "protocol.h"
#include "logging.h"
#include "helper.h"
//#include "ttl_probing.h"
static void send_junk_data(
const char *src_ip, unsigned short src_port,
const char *dst_ip, unsigned short dst_port,
unsigned int seq_num, unsigned int ack_num,
unsigned int len)
{
struct send_tcp_vars vars;
//log_debug("size of vars: %ld", sizeof vars);
memset(&vars, 0, sizeof vars);
strncpy(vars.src_ip, src_ip, 16);
strncpy(vars.dst_ip, dst_ip, 16);
vars.src_port = src_port;
vars.dst_port = dst_port;
vars.flags = TCP_ACK;
vars.seq_num = seq_num;
vars.ack_num = ack_num;
//vars.wrong_tcp_checksum = 1;
/*
u_char bytes[20] = {0x13,0x12,0xf9,0x89,0x5c,0xdd,0xa6,0x15,0x12,0x83,0x3e,0x93,0x11,0x22,0x33,0x44,0x55,0x66,0x01,0x01};
memcpy(vars.tcp_opt, bytes, 20);
vars.tcp_opt_len = 20;
*/
vars.payload_len = len;
int i;
for (i = 0; i < len; i++) {
vars.payload[i] = '.';
}
//dump_send_tcp_vars(&vars);
send_tcp(&vars);
}
static void send_data(
const char *src_ip, unsigned short src_port,
const char *dst_ip, unsigned short dst_port,
unsigned int seq_num, unsigned int ack_num,
unsigned char *payload, unsigned int payload_len)
{
struct send_tcp_vars vars;
//log_debug("size of vars: %ld", sizeof vars);
memset(&vars, 0, sizeof vars);
strncpy(vars.src_ip, src_ip, 16);
strncpy(vars.dst_ip, dst_ip, 16);
vars.src_port = src_port;
vars.dst_port = dst_port;
vars.flags = TCP_ACK;
vars.seq_num = seq_num;
vars.ack_num = ack_num;
//vars.wrong_tcp_checksum = 1;
/*
u_char bytes[20] = {0x13,0x12,0xf9,0x89,0x5c,0xdd,0xa6,0x15,0x12,0x83,0x3e,0x93,0x11,0x22,0x33,0x44,0x55,0x66,0x01,0x01};
memcpy(vars.tcp_opt, bytes, 20);
vars.tcp_opt_len = 20;
*/
vars.payload_len = payload_len;
memcpy(vars.payload, payload, payload_len);
//dump_send_tcp_vars(&vars);
send_tcp(&vars);
}
int x29_setup()
{
char cmd[256];
sprintf(cmd, "iptables -A INPUT -p tcp -m multiport --sport 53,80 --tcp-flags SYN,ACK SYN,ACK -j NFQUEUE --queue-num %d", NF_QUEUE_NUM);
system(cmd);
return 0;
}
int x29_teardown()
{
char cmd[256];
sprintf(cmd, "iptables -D INPUT -p tcp -m multiport --sport 53,80 --tcp-flags SYN,ACK SYN,ACK -j NFQUEUE --queue-num %d", NF_QUEUE_NUM);
system(cmd);
return 0;
}
int x29_process_syn(struct mypacket *packet)
{
return 0;
}
int x29_process_synack(struct mypacket *packet)
{
return 0;
}
int x29_process_request(struct mypacket *packet)
{
char sip[16], dip[16];
unsigned short sport, dport;
struct in_addr s_in_addr = {packet->iphdr->saddr};
struct in_addr d_in_addr = {packet->iphdr->daddr};
strncpy(sip, inet_ntoa(s_in_addr), 16);
strncpy(dip, inet_ntoa(d_in_addr), 16);
sport = ntohs(packet->tcphdr->th_sport);
dport = ntohs(packet->tcphdr->th_dport);
int segoff = 20;
// For reassembly of overlapping TCP segments,
// if a subsequent left-equal segment arrives,
// GFW prefers it (TCP5). Khattak etal.
send_data(sip, sport, dip, dport, htonl(ntohl(packet->tcphdr->th_seq)+segoff), packet->tcphdr->th_ack, packet->payload+segoff, packet->payload_len-segoff);
send_junk_data(sip, sport, dip, dport, htonl(ntohl(packet->tcphdr->th_seq)+segoff), packet->tcphdr->th_ack, packet->payload_len-segoff);
send_data(sip, sport, dip, dport, packet->tcphdr->th_seq, packet->tcphdr->th_ack, packet->payload, segoff);
return -1;
}
| seclab-ucr/INTANG | src/strategies/old_ooo_tcp_fragment.c | C | gpl-3.0 | 4,020 |
<?php
/*
* Copyright (c) 2011-2021 Lp Digital
*
* This file is part of BackBee Standalone.
*
* BackBee 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 BackBee Standalone. If not, see <https://www.gnu.org/licenses/>.
*/
namespace BackBee\Security\Acl\Domain;
use Symfony\Component\Security\Acl\Model\DomainObjectInterface;
/**
* This methods should be implemented by objects to be stored in ACLs.
*
* @category BackBee
*
* @copyright Lp digital system
* @author c.rouillon <charles.rouillon@lp-digital.fr>
*/
interface ObjectIdentifiableInterface extends DomainObjectInterface
{
/**
* Checks for an explicit objects equality.
*
* @param ObjectIdentifiableInterface $identity
* @return Boolean
*/
public function equals(ObjectIdentifiableInterface $identity);
/**
* Returns the unique identifier for this object.
*
* @return string
*/
public function getIdentifier();
/**
* Returns a type for the domain object. Typically, this is the PHP class name.
*
* @return string cannot return null
*/
public function getType();
}
| backbee/backbee-php | Security/Acl/Domain/ObjectIdentifiableInterface.php | PHP | gpl-3.0 | 1,643 |
# coding: utf-8
# license: GPLv3
from enemies import *
from hero import *
def annoying_input_int(message =''):
answer = None
while answer == None:
try:
answer = int(input(message))
except ValueError:
print('Вы ввели недопустимые символы')
return answer
def game_tournament(hero, dragon_list):
for dragon in dragon_list:
print('Вышел', dragon._color, 'дракон!')
while dragon.is_alive() and hero.is_alive():
print('Вопрос:', dragon.question())
answer = annoying_input_int('Ответ:')
if dragon.check_answer(answer):
hero.attack(dragon)
print('Верно! \n** дракон кричит от боли **')
else:
dragon.attack(hero)
print('Ошибка! \n** вам нанесён удар... **')
if dragon.is_alive():
break
print('Дракон', dragon._color, 'повержен!\n')
if hero.is_alive():
print('Поздравляем! Вы победили!')
print('Ваш накопленный опыт:', hero._experience)
else:
print('К сожалению, Вы проиграли...')
def start_game():
try:
print('Добро пожаловать в арифметико-ролевую игру с драконами!')
print('Представьтесь, пожалуйста: ', end = '')
hero = Hero(input())
dragon_number = 3
dragon_list = generate_dragon_list(dragon_number)
assert(len(dragon_list) == 3)
print('У Вас на пути', dragon_number, 'драконов!')
game_tournament(hero, dragon_list)
except EOFError:
print('Поток ввода закончился. Извините, принимать ответы более невозможно.')
| mipt-cs-on-python3/arithmetic_dragons | tournament.py | Python | gpl-3.0 | 1,950 |
// Copyright (c) 2012-2013 Andre Martins
// All Rights Reserved.
//
// This file is part of TurboParser 2.1.
//
// TurboParser 2.1 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 3 of the License, or
// (at your option) any later version.
//
// TurboParser 2.1 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 TurboParser 2.1. If not, see <http://www.gnu.org/licenses/>.
#include "DependencyDecoder.h"
#include "DependencyPart.h"
#include "DependencyPipe.h"
#include "FactorTree.h"
#include "FactorHeadAutomaton.h"
#include "FactorGrandparentHeadAutomaton.h"
#include "FactorTrigramHeadAutomaton.h"
#include "FactorSequence.h"
#include "AlgUtils.h"
#include <iostream>
#include <Eigen/Dense>
#include "logval.h"
// Define a matrix of doubles using Eigen.
typedef LogVal<double> LogValD;
namespace Eigen {
typedef Eigen::Matrix<LogValD, Dynamic, Dynamic> MatrixXlogd;
}
using namespace std;
void DependencyDecoder::DecodeCostAugmented(Instance *instance, Parts *parts,
const vector<double> &scores,
const vector<double> &gold_output,
vector<double> *predicted_output,
double *cost,
double *loss) {
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
int offset_arcs, num_arcs;
if (pipe_->GetDependencyOptions()->labeled()) {
dependency_parts->GetOffsetLabeledArc(&offset_arcs, &num_arcs);
} else {
dependency_parts->GetOffsetArc(&offset_arcs, &num_arcs);
}
// p = 0.5-z0, q = 0.5'*z0, loss = p'*z + q
double q = 0.0;
vector<double> p(num_arcs, 0.0);
vector<double> scores_cost = scores;
for (int r = 0; r < num_arcs; ++r) {
p[r] = 0.5 - gold_output[offset_arcs + r];
scores_cost[offset_arcs + r] += p[r];
q += 0.5*gold_output[offset_arcs + r];
}
Decode(instance, parts, scores_cost, predicted_output);
*cost = q;
for (int r = 0; r < num_arcs; ++r) {
*cost += p[r] * (*predicted_output)[offset_arcs + r];
}
*loss = *cost;
for (int r = 0; r < parts->size(); ++r) {
*loss += scores[r] * ((*predicted_output)[r] - gold_output[r]);
}
}
void DependencyDecoder::DecodeMarginals(Instance *instance, Parts *parts,
const vector<double> &scores,
const vector<double> &gold_output,
vector<double> *predicted_output,
double *entropy,
double *loss) {
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
// Right now, only allow marginal inference for arc-factored models.
CHECK(dependency_parts->IsArcFactored());
// Create copy of the scores.
vector<double> copied_scores(scores);
vector<double> total_scores;
vector<double> label_marginals;
int offset_arcs, num_arcs;
dependency_parts->GetOffsetArc(&offset_arcs, &num_arcs);
int offset_labeled_arcs, num_labeled_arcs;
dependency_parts->GetOffsetLabeledArc(&offset_labeled_arcs,
&num_labeled_arcs);
// If labeled parsing, decode the labels and update the scores.
if (pipe_->GetDependencyOptions()->labeled()) {
DecodeLabelMarginals(instance, parts, copied_scores, &total_scores,
&label_marginals);
for (int r = 0; r < total_scores.size(); ++r) {
copied_scores[offset_arcs + r] += total_scores[r];
}
}
predicted_output->clear();
predicted_output->resize(parts->size(), 0.0);
double log_partition_function;
DecodeMatrixTree(instance, parts, copied_scores, predicted_output,
&log_partition_function, entropy);
// If labeled parsing, write the components of the predicted output that
// correspond to the labeled parts.
if (pipe_->GetDependencyOptions()->labeled()) {
for (int r = 0; r < num_labeled_arcs; ++r) {
DependencyPartLabeledArc *labeled_arc =
static_cast<DependencyPartLabeledArc*>(
(*parts)[offset_labeled_arcs + r]);
int index_arc = dependency_parts->FindArc(labeled_arc->head(),
labeled_arc->modifier());
CHECK_GE(index_arc, 0);
(*predicted_output)[offset_labeled_arcs + r] =
label_marginals[r] * (*predicted_output)[index_arc];
}
// Recompute the entropy.
*entropy = log_partition_function;
for (int r = 0; r < num_labeled_arcs; ++r) {
*entropy -= (*predicted_output)[offset_labeled_arcs + r] *
scores[offset_labeled_arcs + r];
}
if (*entropy < 0.0) {
//LOG(INFO) << "Entropy truncated to zero (" << *entropy << ")";
*entropy = 0.0;
}
}
*loss = *entropy;
for (int r = 0; r < parts->size(); ++r) {
*loss += scores[r] * ((*predicted_output)[r] - gold_output[r]);
}
if (*loss < 0.0) {
//LOG(INFO) << "Loss truncated to zero (" << *loss << ")";
*loss = 0.0;
}
}
// Decode the best label for each candidate arc. The output vector
// best_labeled_parts, indexed by the unlabeled arcs, contains the indices
// of the best labeled part for each arc.
void DependencyDecoder::DecodeLabels(Instance *instance, Parts *parts,
const vector<double> &scores,
vector<int> *best_labeled_parts) {
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
int offset, num_arcs;
dependency_parts->GetOffsetArc(&offset, &num_arcs);
best_labeled_parts->resize(num_arcs);
for (int r = 0; r < num_arcs; ++r) {
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*parts)[offset + r]);
const vector<int> &index_labeled_parts =
dependency_parts->FindLabeledArcs(arc->head(), arc->modifier());
// Find the best label for each candidate arc.
int best_label = -1;
double best_score;
for (int k = 0; k < index_labeled_parts.size(); ++k) {
if (best_label < 0 ||
scores[index_labeled_parts[k]] > best_score) {
best_label = index_labeled_parts[k];
best_score = scores[best_label];
}
}
(*best_labeled_parts)[r] = best_label;
}
}
// Decode the label marginals for each candidate arc. The output vector
// total_scores contains the sum of exp-scores (over the labels) for each arc;
// label_marginals contains those marginals ignoring the tree constraint.
void DependencyDecoder::DecodeLabelMarginals(Instance *instance, Parts *parts,
const vector<double> &scores,
vector<double> *total_scores,
vector<double> *label_marginals) {
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
int offset, num_arcs;
int offset_labeled, num_labeled_arcs;
dependency_parts->GetOffsetArc(&offset, &num_arcs);
dependency_parts->GetOffsetLabeledArc(&offset_labeled, &num_labeled_arcs);
total_scores->clear();
total_scores->resize(num_arcs, 0.0);
label_marginals->clear();
label_marginals->resize(num_labeled_arcs, 0.0);
for (int r = 0; r < num_arcs; ++r) {
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*parts)[offset + r]);
const vector<int> &index_labeled_parts =
dependency_parts->FindLabeledArcs(arc->head(), arc->modifier());
// Find the best label for each candidate arc.
LogValD total_score = LogValD::Zero();
for (int k = 0; k < index_labeled_parts.size(); ++k) {
total_score += LogValD(scores[index_labeled_parts[k]], false);
}
(*total_scores)[r] = total_score.logabs();
double sum = 0.0;
for (int k = 0; k < index_labeled_parts.size(); ++k) {
LogValD marginal =
LogValD(scores[index_labeled_parts[k]], false) / total_score;
(*label_marginals)[index_labeled_parts[k] - offset_labeled] =
marginal.as_float();
sum += marginal.as_float();
}
if (!NEARLY_EQ_TOL(sum, 1.0, 1e-9)) {
LOG(INFO) << "Label marginals don't sum to one: sum = " << sum;
}
}
}
void DependencyDecoder::Decode(Instance *instance, Parts *parts,
const vector<double> &scores,
vector<double> *predicted_output) {
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
// Create copy of the scores.
vector<double> copied_scores(scores);
vector<int> best_labeled_parts;
int offset_arcs, num_arcs;
dependency_parts->GetOffsetArc(&offset_arcs, &num_arcs);
// If labeled parsing, decode the labels and update the scores.
if (pipe_->GetDependencyOptions()->labeled()) {
DecodeLabels(instance, parts, copied_scores, &best_labeled_parts);
for (int r = 0; r < best_labeled_parts.size(); ++r) {
copied_scores[offset_arcs + r] += copied_scores[best_labeled_parts[r]];
}
}
predicted_output->clear();
predicted_output->resize(parts->size(), 0.0);
if (dependency_parts->IsArcFactored() ||
dependency_parts->IsLabeledArcFactored()) {
double value;
DecodeBasic(instance, parts, copied_scores, predicted_output, &value);
} else {
#ifdef USE_CPLEX
DecodeCPLEX(instance, parts, copied_scores, false, true, predicted_output);
#else
DecodeFactorGraph(instance, parts, copied_scores, false, true,
predicted_output);
#endif
// At test time, run Chu-Liu-Edmonds on top of the outcome of AD3
// as a rounding heuristic to make sure we get a valid tree.
// TODO: maybe change the interface to AD3 to let us implement
// a primal rounding heuristic - in this case just getting the output
// coming from the TREE factor should work well enough.
if (pipe_->GetDependencyOptions()->test()) {
for (int r = 0; r < num_arcs; ++r) {
copied_scores[offset_arcs + r] = (*predicted_output)[offset_arcs + r];
}
double value;
DecodeBasic(instance, parts, copied_scores, predicted_output, &value);
}
}
// If labeled parsing, write the components of the predicted output that
// correspond to the labeled parts.
if (pipe_->GetDependencyOptions()->labeled()) {
for (int r = 0; r < num_arcs; ++r) {
(*predicted_output)[best_labeled_parts[r]] =
(*predicted_output)[offset_arcs + r];
}
}
}
void DependencyDecoder::DecodePruner(Instance *instance, Parts *parts,
const vector<double> &scores,
vector<double> *predicted_output) {
int sentence_length =
static_cast<DependencyInstanceNumeric*>(instance)->size();
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
double posterior_threshold =
pipe_->GetDependencyOptions()->GetPrunerPosteriorThreshold();
int max_heads = pipe_->GetDependencyOptions()->GetPrunerMaxHeads();
if (max_heads < 0) max_heads = sentence_length;
predicted_output->clear();
predicted_output->resize(parts->size(), 0.0);
CHECK(dependency_parts->IsArcFactored());
double entropy;
double log_partition_function;
vector<double> posteriors;
DecodeMatrixTree(instance, parts, scores, &posteriors,
&log_partition_function, &entropy);
int num_used_parts = 0;
for (int m = 1; m < sentence_length; ++m) {
vector<pair<double,int> > scores_heads;
for (int h = 0; h < sentence_length; ++h) {
int r = dependency_parts->FindArc(h, m);
if (r < 0) continue;
scores_heads.push_back(pair<double,int>(-posteriors[r], r));
}
if (scores_heads.size() == 0) continue;
stable_sort(scores_heads.begin(), scores_heads.end());
double max_posterior = -scores_heads[0].first;
for (int k = 0; k < max_heads && k < scores_heads.size(); ++k) {
int r = scores_heads[k].second;
// Note: better to put k == 0 because things could have gone
// wrong with the marginal decoder and all parents could
// end up with zero probability.
if (k == 0 ||
-scores_heads[k].first >= posterior_threshold * max_posterior) {
++num_used_parts;
(*predicted_output)[r] = 1.0;
} else {
break;
}
}
}
VLOG(2) << "Pruning reduced to "
<< static_cast<double>(num_used_parts) /
static_cast<double>(sentence_length)
<< " candidate heads per word.";
}
void DependencyDecoder::DecodePrunerNaive(Instance *instance, Parts *parts,
const vector<double> &scores,
vector<double> *predicted_output) {
int sentence_length =
static_cast<DependencyInstanceNumeric*>(instance)->size();
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
int max_heads = pipe_->GetDependencyOptions()->GetPrunerMaxHeads();
predicted_output->clear();
predicted_output->resize(parts->size(), 0.0);
CHECK(dependency_parts->IsArcFactored());
// Get max_heads heads per modifier.
for (int m = 1; m < sentence_length; ++m) {
vector<pair<double,int> > scores_heads;
for (int h = 0; h < sentence_length; ++h) {
int r = dependency_parts->FindArc(h, m);
if (r < 0) continue;
scores_heads.push_back(pair<double,int>(-scores[r], r));
}
stable_sort(scores_heads.begin(), scores_heads.end());
for (int k = 0; k < max_heads && k < scores_heads.size(); ++k) {
int r = scores_heads[k].second;
(*predicted_output)[r] = 1.0;
}
}
}
// Decoder for the basic model; it finds a maximum weighted arborescence
// using Edmonds' algorithm (which runs in O(n^2)).
void DependencyDecoder::DecodeBasic(Instance *instance, Parts *parts,
const vector<double> &scores,
vector<double> *predicted_output,
double *value) {
int sentence_length =
static_cast<DependencyInstanceNumeric*>(instance)->size();
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
int offset_arcs, num_arcs;
dependency_parts->GetOffsetArc(&offset_arcs, &num_arcs);
vector<DependencyPartArc*> arcs(num_arcs);
vector<double> scores_arcs(num_arcs);
for (int r = 0; r < num_arcs; ++r) {
arcs[r] = static_cast<DependencyPartArc*>((*parts)[offset_arcs + r]);
scores_arcs[r] = scores[offset_arcs + r];
}
vector<int> heads;
vector<bool> disabled_nodes(sentence_length, false);
// LPK: Get the Instance inorder to get the disable list
DependencyInstanceNumeric *dependency_instance = static_cast<DependencyInstanceNumeric*>(instance);
for (int m = 1; m < sentence_length; ++m){
int sel = dependency_instance->GetSelect(m);
if (sel == 0){
disabled_nodes[m] = true;
}
}
RunChuLiuEdmondsWithDisabledNode(&disabled_nodes, sentence_length, arcs, scores_arcs, &heads, value);
predicted_output->resize(parts->size());
for (int r = 0; r < num_arcs; ++r) {
(*predicted_output)[offset_arcs + r] = 0.0;
}
for (int m = 1; m < sentence_length; ++m) {
int h = heads[m];
int r = dependency_parts->FindArc(h, m);
if (r < 0) {
//LOG(INFO) << "No arc " << h << " -> " << m;
} else {
(*predicted_output)[offset_arcs + r] = 1.0;
}
}
}
// Decoder for the basic model; it finds a maximum weighted arborescence
// using Edmonds' algorithm (which runs in O(n^2)).
void DependencyDecoder::RunChuLiuEdmondsIteration(
vector<bool> *disabled,
vector<vector<int> > *candidate_heads,
vector<vector<double> > *candidate_scores,
vector<int> *heads,
double *value) {
// Original number of nodes (including the root).
int length = disabled->size();
// Pick the best incoming arc for each node.
heads->resize(length);
vector<double> best_scores(length);
for (int m = 1; m < length; ++m) {
if ((*disabled)[m]) continue;
int best = -1;
for (int k = 0; k < (*candidate_heads)[m].size(); ++k) {
if (best < 0 ||
(*candidate_scores)[m][k] > (*candidate_scores)[m][best]) {
best = k;
}
}
if (best < 0) {
// No spanning tree exists. Assign the parent of this node
// to the root, and give it a minus infinity score.
(*heads)[m] = 0;
best_scores[m] = -std::numeric_limits<double>::infinity();
} else {
(*heads)[m] = (*candidate_heads)[m][best]; //best;
best_scores[m] = (*candidate_scores)[m][best]; //best;
}
}
// Look for cycles. Return after the first cycle is found.
vector<int> cycle;
vector<int> visited(length, 0);
for (int m = 1; m < length; ++m) {
if ((*disabled)[m]) continue;
// Examine all the ancestors of m until the root or a cycle is found.
int h = m;
while (h != 0) {
// If already visited, break and check if it is part of a cycle.
// If visited[h] < m, the node was visited earlier and seen not
// to be part of a cycle.
if (visited[h]) break;
visited[h] = m;
h = (*heads)[h];
}
// Found a cycle to which h belongs.
// Obtain the full cycle.
if (visited[h] == m) {
m = h;
do {
cycle.push_back(m);
m = (*heads)[m];
} while (m != h);
break;
}
}
// If there are no cycles, then this is a well formed tree.
if (cycle.empty()) {
*value = 0.0;
for (int m = 1; m < length; ++m) {
*value += best_scores[m];
}
return;
}
// Build a cycle membership vector for constant-time querying and compute the
// score of the cycle.
// Nominate a representative node for the cycle and disable all the others.
double cycle_score = 0.0;
vector<bool> in_cycle(length, false);
int representative = cycle[0];
for (int k = 0; k < cycle.size(); ++k) {
int m = cycle[k];
in_cycle[m] = true;
cycle_score += best_scores[m];
if (m != representative) (*disabled)[m] = true;
}
// Contract the cycle.
// 1) Update the score of each child to the maximum score achieved by a parent
// node in the cycle.
vector<int> best_heads_cycle(length);
for (int m = 1; m < length; ++m) {
if ((*disabled)[m] || m == representative) continue;
double best_score;
// If the list of candidate parents of m is shorter than the length of
// the cycle, use that. Otherwise, loop through the cycle.
int best = -1;
for (int k = 0; k < (*candidate_heads)[m].size(); ++k) {
if (!in_cycle[(*candidate_heads)[m][k]]) continue;
if (best < 0 || (*candidate_scores)[m][k] > best_score) {
best = k;
best_score = (*candidate_scores)[m][best];
}
}
if (best < 0) continue;
best_heads_cycle[m] = (*candidate_heads)[m][best];
// Reconstruct the list of candidate heads for this m.
int l = 0;
for (int k = 0; k < (*candidate_heads)[m].size(); ++k) {
int h = (*candidate_heads)[m][k];
double score = (*candidate_scores)[m][k];
if (!in_cycle[h]) {
(*candidate_heads)[m][l] = h;
(*candidate_scores)[m][l] = score;
++l;
}
}
// If h is in the cycle and is not the representative node,
// it will be dropped from the list of candidate heads.
(*candidate_heads)[m][l] = representative;
(*candidate_scores)[m][l] = best_score;
(*candidate_heads)[m].resize(l+1);
(*candidate_scores)[m].resize(l+1);
}
// 2) Update the score of each candidate parent of the cycle supernode.
vector<int> best_modifiers_cycle(length, -1);
vector<int> candidate_heads_representative;
vector<double> candidate_scores_representative;
vector<double> best_scores_cycle(length);
// Loop through the cycle.
for (int k = 0; k < cycle.size(); ++k) {
int m = cycle[k];
for (int l = 0; l < (*candidate_heads)[m].size(); ++l) {
// Get heads out of the cycle.
int h = (*candidate_heads)[m][l];
if (in_cycle[h]) continue;
double score = (*candidate_scores)[m][l] - best_scores[m];
if (best_modifiers_cycle[h] < 0 || score > best_scores_cycle[h]) {
best_modifiers_cycle[h] = m;
best_scores_cycle[h] = score;
}
}
}
for (int h = 0; h < length; ++h) {
if (best_modifiers_cycle[h] < 0) continue;
double best_score = best_scores_cycle[h] + cycle_score;
candidate_heads_representative.push_back(h);
candidate_scores_representative.push_back(best_score);
}
// Reconstruct the list of candidate heads for the representative node.
(*candidate_heads)[representative] = candidate_heads_representative;
(*candidate_scores)[representative] = candidate_scores_representative;
// Save the current head of the representative node (it will be overwritten).
int head_representative = (*heads)[representative];
// Call itself recursively.
RunChuLiuEdmondsIteration(disabled,
candidate_heads,
candidate_scores,
heads,
value);
// Uncontract the cycle.
int h = (*heads)[representative];
(*heads)[representative] = head_representative;
(*heads)[best_modifiers_cycle[h]] = h;
for (int m = 1; m < length; ++m) {
if ((*disabled)[m]) continue;
if ((*heads)[m] == representative) {
// Get the right parent from within the cycle.
(*heads)[m] = best_heads_cycle[m];
}
}
for (int k = 0; k < cycle.size(); ++k) {
int m = cycle[k];
(*disabled)[m] = false;
}
}
void DependencyDecoder::RunChuLiuEdmonds(int sentence_length,
const vector<DependencyPartArc*> &arcs,
const vector<double> &scores,
vector<int> *heads,
double *value) {
vector<vector<int> > candidate_heads(sentence_length);
vector<vector<double> > candidate_scores(sentence_length);
vector<bool> disabled(sentence_length, false);
for (int r = 0; r < arcs.size(); ++r) {
int h = arcs[r]->head();
int m = arcs[r]->modifier();
candidate_heads[m].push_back(h);
candidate_scores[m].push_back(scores[r]);
}
heads->assign(sentence_length, -1);
RunChuLiuEdmondsIteration(&disabled, &candidate_heads,
&candidate_scores, heads, value);
}
// LPK: This is used for decoding with a hard contrains that some nodes
// should not be included in the tree.
void DependencyDecoder::RunChuLiuEdmondsWithDisabledNode(vector<bool> *disabled_nodes,
int sentence_length,
const vector<DependencyPartArc*> &arcs,
const vector<double> &scores,
vector<int> *heads,
double *value) {
// LPK: How many nodes we disabled.
int disabled_number = 0;
for(int i = 0; i < sentence_length; ++i){
if((*disabled_nodes)[i]){
disabled_number++;
}
}
if(disabled_number == sentence_length){
value = 0;
for(int i = 0; i < sentence_length; i++){
(*heads)[i] = -1;
}
return;
}
vector<int> mapping_nodes(sentence_length);
int map_index = 0;
for(int i = 0; i < sentence_length; i++){
if((*disabled_nodes)[i]){
// disabled nodes will not be mapped
mapping_nodes[i] = -1;
}else{
mapping_nodes[i] = map_index;
map_index++;
}
}
vector<int> mapping_nodes_back(sentence_length - disabled_number);
int map_back_i = 0;
for(int i = 0; i < sentence_length; i++){
if(mapping_nodes[i] == map_back_i){
mapping_nodes_back[map_back_i] = i;
map_back_i++;
}
}
vector<int> heads_for_decode(sentence_length - disabled_number, -1);
vector<vector<int> > candidate_heads(sentence_length - disabled_number);
vector<vector<double> > candidate_scores(sentence_length - disabled_number);
vector<bool> disabled(sentence_length - disabled_number, false);
for (int r = 0; r < arcs.size(); ++r) {
int h = arcs[r]->head();
int m = arcs[r]->modifier();
// If the head or the modifier is disable, we should send it to the CLE algorithm.
if((*disabled_nodes)[h] || (*disabled_nodes)[m]){
continue;
}
candidate_heads[mapping_nodes[m]].push_back(mapping_nodes[h]);
candidate_scores[mapping_nodes[m]].push_back(scores[r]);
}
RunChuLiuEdmondsIteration(&disabled, &candidate_heads,
&candidate_scores, &heads_for_decode, value);
heads->assign(sentence_length, -1);
// map the heads back to original ones
for (int i = 0; i < (sentence_length - disabled_number); ++i){
if(heads_for_decode[i] < 0){
// here we don't have the nodes to map back
(*heads)[mapping_nodes_back[i]] = -1;
}
else{
(*heads)[mapping_nodes_back[i]] = mapping_nodes_back[heads_for_decode[i]];
}
}
//VLOG(2) << "Finished decoding with disabled";
}
// Marginal decoder for the basic model; it invokes the matrix-tree theorem.
void DependencyDecoder::DecodeMatrixTree(Instance *instance, Parts *parts,
const vector<double> &scores,
vector<double> *predicted_output,
double *log_partition_function,
double *entropy) {
int sentence_length =
static_cast<DependencyInstanceNumeric*>(instance)->size();
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
// Matrix for storing the potentials.
Eigen::MatrixXlogd potentials(sentence_length, sentence_length);
// Kirchhoff matrix.
Eigen::MatrixXlogd kirchhoff(sentence_length-1, sentence_length-1);
// Compute an offset to improve numerical stability. This is a constant that
// is subtracted from all scores.
int offset_arcs, num_arcs;
dependency_parts->GetOffsetArc(&offset_arcs, &num_arcs);
double constant = 0.0;
for (int r = 0; r < num_arcs; ++r) {
constant += scores[offset_arcs + r];
}
constant /= static_cast<double>(num_arcs);
// Set the potentials.
for (int h = 0; h < sentence_length; ++h) {
for (int m = 0; m < sentence_length; ++m) {
potentials(m, h) = LogValD::Zero();
int r = dependency_parts->FindArc(h, m);
if (r >= 0) {
potentials(m, h) = LogValD(scores[r] - constant, false);
}
}
}
// Set the Kirchhoff matrix.
for (int h = 0; h < sentence_length - 1; ++h) {
for (int m = 0; m < sentence_length - 1; ++m) {
kirchhoff(h, m) = -potentials(m+1, h+1);
}
}
for (int m = 1; m < sentence_length; ++m) {
LogValD sum = LogValD::Zero();
for (int h = 0; h < sentence_length; ++h) {
sum += potentials(m, h);
}
kirchhoff(m-1, m-1) = sum;
}
// Inverse of the Kirchoff matrix.
Eigen::FullPivLU<Eigen::MatrixXlogd> lu(kirchhoff);
Eigen::MatrixXlogd inverted_kirchhoff = lu.inverse();
*log_partition_function = lu.determinant().logabs() +
constant * (sentence_length - 1);
Eigen::MatrixXlogd marginals(sentence_length, sentence_length);
for (int h = 0; h < sentence_length; ++h) {
marginals(0, h) = LogValD::Zero();
}
for (int m = 1; m < sentence_length; ++m) {
marginals(m, 0) = potentials(m, 0) * inverted_kirchhoff(m-1, m-1);
for (int h = 1; h < sentence_length; ++h) {
marginals(m, h) = potentials(m, h) *
(inverted_kirchhoff(m-1, m-1) - inverted_kirchhoff(m-1, h-1));
}
}
// Compute the entropy.
predicted_output->resize(parts->size());
*entropy = *log_partition_function;
for (int r = 0; r < num_arcs; ++r) {
int h = static_cast<DependencyPartArc*>((*parts)[offset_arcs + r])->head();
int m = static_cast<DependencyPartArc*>((*parts)[offset_arcs + r])->modifier();
if (marginals(m, h).signbit()) {
if (!NEARLY_ZERO_TOL(marginals(m, h).as_float(), 1e-6)) {
LOG(INFO) << "Marginals truncated to zero (" << marginals(m, h).as_float() << ")";
}
CHECK(!std::isnan(marginals(m, h).as_float()));
} else if (marginals(m, h).logabs() > 0) {
if (!NEARLY_ZERO_TOL(marginals(m, h).as_float() - 1.0, 1e-6)) {
LOG(INFO) << "Marginals truncated to one (" << marginals(m, h).as_float() << ")";
}
}
(*predicted_output)[offset_arcs + r] = marginals(m, h).as_float();
*entropy -= (*predicted_output)[offset_arcs + r] * scores[offset_arcs + r];
}
if (*entropy < 0.0) {
if (!NEARLY_ZERO_TOL(*entropy, 1e-6)) {
//LOG(INFO) << "Entropy truncated to zero (" << *entropy << ")";
}
*entropy = 0.0;
}
}
// Decode building a factor graph and calling the AD3 algorithm.
void DependencyDecoder::DecodeFactorGraph(Instance *instance, Parts *parts,
const vector<double> &scores,
bool single_root,
bool relax,
vector<double> *predicted_output) {
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
DependencyInstanceNumeric* sentence =
static_cast<DependencyInstanceNumeric*>(instance);
CHECK(!single_root);
CHECK(relax);
// Get the offsets for the different parts.
int offset_arcs, num_arcs;
dependency_parts->GetOffsetArc(&offset_arcs, &num_arcs);
int offset_labeled_arcs, num_labeled_arcs;
dependency_parts->GetOffsetLabeledArc(&offset_labeled_arcs,
&num_labeled_arcs);
int offset_siblings, num_siblings;
dependency_parts->GetOffsetSibl(&offset_siblings, &num_siblings);
int offset_next_siblings, num_next_siblings;
dependency_parts->GetOffsetNextSibl(&offset_next_siblings,
&num_next_siblings);
int offset_grandparents, num_grandparents;
dependency_parts->GetOffsetGrandpar(&offset_grandparents, &num_grandparents);
int offset_grandsiblings, num_grandsiblings;
dependency_parts->GetOffsetGrandSibl(&offset_grandsiblings, &num_grandsiblings);
int offset_trisiblings, num_trisiblings;
dependency_parts->GetOffsetTriSibl(&offset_trisiblings, &num_trisiblings);
int offset_nonprojective, num_nonprojective;
dependency_parts->GetOffsetNonproj(&offset_nonprojective, &num_nonprojective);
int offset_path, num_path;
dependency_parts->GetOffsetPath(&offset_path, &num_path);
int offset_bigrams, num_bigrams;
dependency_parts->GetOffsetHeadBigr(&offset_bigrams, &num_bigrams);
// Define what parts are used.
bool use_arbitrary_sibling_parts = (num_siblings > 0);
bool use_next_sibling_parts = (num_next_siblings > 0);
bool use_grandparent_parts = (num_grandparents > 0);
bool use_grandsibling_parts = (num_grandsiblings > 0);
bool use_trisibling_parts = (num_trisiblings > 0);
bool use_nonprojective_arc_parts = (num_nonprojective > 0);
bool use_path_parts = (num_path > 0);
bool use_head_bigram_parts = (num_bigrams > 0);
VLOG(2) << "Print the used things:\t" << "use_arbitrary_sibling_parts\t" << use_arbitrary_sibling_parts <<"\n"
<< "use_next_sibling_parts\t" << use_next_sibling_parts <<"\n"
<< "use_grandparent_parts\t" << use_grandparent_parts <<"\n"
<< "use_grandsibling_parts\t" << use_grandsibling_parts <<"\n"
<< "use_trisibling_parts\t" << use_trisibling_parts <<"\n"
<< "use_nonprojective_arc_parts\t" << use_nonprojective_arc_parts <<"\n"
<< "use_path_parts\t" << use_path_parts <<"\n"
<< "use_head_bigram_parts\t" << use_head_bigram_parts <<"\n";
// Define optional configurations of the factor graph.
bool use_tree_factor = true;
bool use_head_automata = true;
bool use_trigram_head_automata = true;
bool use_grandparent_head_automata = true;
bool use_head_bigram_sequence_factor = true;
// Evidence vector that allows to assign evidence to each variable.
bool add_evidence = false;
vector<int> evidence;
// If non-projective arc parts or path parts are being used, then we will
// use flows instead of a tree factor.
// Currently, if flows are used, no large factors (such as head automata
// or head bigrams) will be used. That is because adding evidence to those
// large factors is not yet implemented.
if (use_nonprojective_arc_parts || use_path_parts) {
use_tree_factor = false;
use_head_automata = false;
use_trigram_head_automata = false;
use_grandparent_head_automata = false;
use_head_bigram_sequence_factor = false;
add_evidence = true;
}
bool use_flows = !use_tree_factor;
// Define zero/infinity potentials (not used if add_evidence = true).
double log_potential_zero = -50;
double log_potential_infinity = -log_potential_zero;
// Variables of the factor graph.
vector<AD3::BinaryVariable*> variables;
// Indices that allow to identify the part corresponding to each variable.
vector<int> part_indices_;
vector<int> additional_part_indices;
vector<int> factor_part_indices_;
// Create factor graph.
AD3::FactorGraph *factor_graph = new AD3::FactorGraph;
int verbosity = 1;
if (VLOG_IS_ON(2)) {
verbosity = 2;
}
factor_graph->SetVerbosity(verbosity);
// Compute the transitivity closure of the dependency graph to get the set of
// possible directed paths.
// In practice, this is always pretty dense, so there is not a big payoff.
vector<vector<bool> > graph_paths;
bool prune_paths = true;
if (use_flows) {
if (prune_paths) {
graph_paths.assign(sentence->size(),
vector<bool>(sentence->size(), false));
for (int r = 0; r < num_arcs; ++r) {
DependencyPartArc *arc = static_cast<DependencyPartArc*>(
(*dependency_parts)[offset_arcs + r]);
int h = arc->head();
int m = arc->modifier();
graph_paths[h][m] = true;
}
timeval start, end;
gettimeofday(&start, NULL);
ComputeTransitiveClosure(&graph_paths);
for (int i = 0; i < sentence->size(); ++i) {
graph_paths[i][i] = true;
}
gettimeofday(&end, NULL);
double elapsed_time_paths = diff_ms(end,start);
int num_possible_paths = 0;
for (int i = 0; i < sentence->size(); ++i) {
for (int j = 0; j < sentence->size(); ++j) {
if (i == j || graph_paths[i][j]) ++num_possible_paths;
}
}
VLOG(2) << num_arcs << " possible arcs and "
<< num_possible_paths << " possible paths in "
<< sentence->size() * sentence->size()
<< " (took " << elapsed_time_paths << " ms.)";
}
}
// Build arc variables.
int sentence_length =
static_cast<DependencyInstanceNumeric*>(instance)->size();
vector<bool> disabled_nodes(sentence_length, false);
DependencyInstanceNumeric *dependency_instance = static_cast<DependencyInstanceNumeric*>(instance);
for (int m = 1; m < sentence_length; ++m){
int sel = dependency_instance->GetSelect(m);
if (sel == 0){
disabled_nodes[m] = true;
}
}
for (int r = 0; r < num_arcs; ++r) {
AD3::BinaryVariable* variable = factor_graph->CreateBinaryVariable();
variable->SetLogPotential(scores[offset_arcs + r]);
variables.push_back(variable);
part_indices_.push_back(offset_arcs + r);
// For the disabled arcs, they should have evidence 0, means they should always be 0.
// DependencyPartArc *arc = static_cast<DependencyPartArc*>(
// (*dependency_parts)[offset_arcs + r]);
// int h = arc->head();
// int m = arc->modifier();
// if(disabled_nodes[h] || disabled_nodes[m]){
evidence.push_back(-1);
// VLOG(0) << "score_disabled " << h << " " << m << " " << scores[offset_arcs + r];
// }else{
// evidence.push_back(-1);
// VLOG(0) << "score_active " << h << " " << m << " " << scores[offset_arcs + r];
// }
}
//////////////////////////////////////////////////////////////////////
// Build tree factor.
//////////////////////////////////////////////////////////////////////
if (use_tree_factor) {
// Build tree factor.
vector<AD3::BinaryVariable*> local_variables(num_arcs);
vector<DependencyPartArc*> arcs(num_arcs);
for (int r = 0; r < num_arcs; ++r) {
local_variables[r] = variables[r];
arcs[r] = static_cast<DependencyPartArc*>((*parts)[offset_arcs + r]);
}
AD3::FactorTree *factor = new AD3::FactorTree;
// LPK: To initialize the tree factor, we should tell the factor the
// dependency instance, so that they now what to forbid in the tree.
// This is not the optimal solution in codes though...
DependencyInstanceNumeric *dependency_instance = static_cast<DependencyInstanceNumeric*>(instance);
factor->Initialize(sentence->size(), arcs, this, dependency_instance);
factor_graph->DeclareFactor(factor, local_variables, true);
factor_part_indices_.push_back(-1);
} else {
// Build the "single parent" factors.
for (int m = 1; m < sentence->size(); ++m) {
vector<AD3::BinaryVariable*> local_variables;
for (int h = 0; h < sentence->size(); ++h) {
int r = dependency_parts->FindArc(h, m);
if (r < 0) continue;
local_variables.push_back(variables[r]);
}
factor_graph->CreateFactorXOR(local_variables);
factor_part_indices_.push_back(-1);
}
}
// LPK: Start of Difficult factors...
int offset_path_variables = -1;
if (use_flows) {
// Create flow variables.
int offset_flow_variables = variables.size();
for (int r = 0; r < num_arcs; ++r) {
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*dependency_parts)[offset_arcs + r]);
int h = arc->head();
int m = arc->modifier();
for (int k = 0; k < sentence->size(); ++k) {
// Create flow variable denoting that arc (h,m) carries flow to k.
AD3::BinaryVariable* variable = factor_graph->CreateBinaryVariable();
// No arc carries flow to the root or to its head.
int evidence_value = -1;
if (k == 0 || k == h) {
if (add_evidence) {
evidence_value = 0;
} else {
variable->SetLogPotential(log_potential_zero);
}
} else if (prune_paths && add_evidence && !graph_paths[m][k]) {
evidence_value = 0;
}
variables.push_back(variable);
part_indices_.push_back(-1); // Auxiliary variable; no part for it.
evidence.push_back(evidence_value);
}
}
// Create path variables.
offset_path_variables = variables.size();
for (int d = 0; d < sentence->size(); ++d) {
for (int a = 0; a < sentence->size(); ++a) {
// Create path variable denoting that there is path from a to d.
AD3::BinaryVariable* variable = factor_graph->CreateBinaryVariable();
// Each word descends from the root and from itself.
int evidence_value = -1;
if (a == 0 || a == d) {
if (add_evidence) {
evidence_value = 1;
} else {
variable->SetLogPotential(log_potential_infinity);
}
} else if (prune_paths && add_evidence && !graph_paths[a][d]) {
evidence_value = 0;
}
variables.push_back(variable);
// For now, consider this as an auxiliary variable. Later there can be
// a path part for it, in which case the index below will be updated.
part_indices_.push_back(-1);
evidence.push_back(evidence_value);
}
}
// Create a "path builder" factor. The following constraints will be
// imposed:
// sum_{i=0}^{n} f_{ijk} = p_{jk} for each j,k with j \ne 0.
// The case j=k is already addressed in the "single parent" factors.
//int offset_path_builder_factors = factors.size();
vector<vector<vector<AD3::BinaryVariable*> > > local_variables_path_builder(
sentence->size(), vector<vector<AD3::BinaryVariable*> >(sentence->size()));
for (int r = 0; r < num_arcs; ++r) {
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*dependency_parts)[offset_arcs + r]);
int m = arc->modifier();
for (int k = 0; k < sentence->size(); ++k) {
int index = offset_flow_variables + k + r*sentence->size();
local_variables_path_builder[m][k].push_back(variables[index]);
}
}
for (int d = 0; d < sentence->size(); ++d) {
for (int a = 1; a < sentence->size(); ++a) {
int index = offset_path_variables + a + d*sentence->size();
local_variables_path_builder[a][d].push_back(variables[index]);
factor_graph->CreateFactorXOROUT(local_variables_path_builder[a][d]);
factor_part_indices_.push_back(-1);
}
}
// Create the "flow delta" factor. The following constraints will be
// imposed:
// sum_{j=0}^{n} f_{ijk} = p_{ik} for each i,k s.t. i \ne k.
// TODO: remove the comment below, because that's not really done?
// Remark: the f_{ijj} variables are replaced by the arc variables z_{ij}.
//int offset_flow_delta_factors = factors.size();
vector<vector<vector<AD3::BinaryVariable*> > > local_variables_flow_delta(
sentence->size(), vector<vector<AD3::BinaryVariable*> >(sentence->size()));
for (int r = 0; r < num_arcs; ++r) {
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*dependency_parts)[offset_arcs + r]);
int h = arc->head();
for (int k = 0; k < sentence->size(); ++k) {
if (h == k) continue;
int index = offset_flow_variables + k + r*sentence->size();
local_variables_flow_delta[h][k].push_back(variables[index]);
}
}
for (int d = 0; d < sentence->size(); ++d) {
for (int a = 1; a < sentence->size(); ++a) {
if (a == d) continue;
int index = offset_path_variables + a + d*sentence->size();
if (local_variables_flow_delta[a][d].size() == 0) {
// Useless to create a XOR-OUT factor with no inputs and one output.
// That is equivalent to impose that the output is zero.
if (add_evidence) {
evidence[index] = 0;
} else {
variables[index]->SetLogPotential(log_potential_zero);
// TODO: keep track of the original log-potential.
}
continue;
}
local_variables_flow_delta[a][d].push_back(variables[index]);
factor_graph->CreateFactorXOROUT(local_variables_flow_delta[a][d]);
factor_part_indices_.push_back(-1);
}
}
// Create the "flow implies arc" factor. The following constraints will be
// imposed:
// f_{ijk} <= a_{ij}; equivalently f_{ijk} "implies" a_{ij} for each i,j,k.
//offset_flow_support_factors = factors.size();
for (int r = 0; r < num_arcs; ++r) {
for (int k = 0; k < sentence->size(); ++k) {
vector<AD3::BinaryVariable*> local_variables;
// The LHS of the implication relation.
int index = offset_flow_variables + k + r*sentence->size();
local_variables.push_back(variables[index]);
// The RHS of the implication relation.
local_variables.push_back(variables[r]);
factor_graph->CreateFactorIMPLY(local_variables);
factor_part_indices_.push_back(-1);
}
}
}
//////////////////////////////////////////////////////////////////////
// Build sibling factors.
//////////////////////////////////////////////////////////////////////
if (use_arbitrary_sibling_parts) {
// LPK: Not used in the standard model
for (int r = 0; r < num_siblings; ++r) {
DependencyPartSibl *part = static_cast<DependencyPartSibl*>(
(*dependency_parts)[offset_siblings + r]);
int r1 = dependency_parts->FindArc(part->head(), part->modifier());
int r2 = dependency_parts->FindArc(part->head(), part->sibling());
CHECK_GE(r1, 0);
CHECK_GE(r2, 0);
vector<AD3::BinaryVariable*> local_variables;
local_variables.push_back(variables[r1 - offset_arcs]);
local_variables.push_back(variables[r2 - offset_arcs]);
factor_graph->CreateFactorPAIR(local_variables,
scores[offset_siblings + r]);
// TODO: set these global indices at the end after all variables/factors
// are created.
//factor->SetGlobalIndex(...);
additional_part_indices.push_back(offset_siblings + r);
factor_part_indices_.push_back(offset_siblings + r);
}
}
//////////////////////////////////////////////////////////////////////
// Build grandparent factors.
//////////////////////////////////////////////////////////////////////
if (!use_grandparent_head_automata || !use_next_sibling_parts) {
// Not used in the standard model
for (int r = 0; r < num_grandparents; ++r) {
DependencyPartGrandpar *part = static_cast<DependencyPartGrandpar*>(
(*dependency_parts)[offset_grandparents + r]);
int r1 = dependency_parts->FindArc(part->grandparent(), part->head());
int r2 = dependency_parts->FindArc(part->head(), part->modifier());
CHECK_GE(r1, 0);
CHECK_GE(r2, 0);
vector<AD3::BinaryVariable*> local_variables;
local_variables.push_back(variables[r1 - offset_arcs]);
local_variables.push_back(variables[r2 - offset_arcs]);
factor_graph->CreateFactorPAIR(local_variables,
scores[offset_grandparents + r]);
// TODO: set these global indices at the end after all variables/factors are created.
//factor->SetGlobalIndex(...);
additional_part_indices.push_back(offset_grandparents + r);
factor_part_indices_.push_back(offset_grandparents + r);
}
}
//////////////////////////////////////////////////////////////////////
// Build grandsibling and tri-sibling factors without automata.
//////////////////////////////////////////////////////////////////////
if (!use_grandparent_head_automata) {
// TODO(afm): Implement grand-siblings without automata.
CHECK_EQ(num_grandsiblings, 0);
}
if (!use_trigram_head_automata) {
// TODO(afm): Implement tri-siblings without automata.
CHECK_EQ(num_trisiblings, 0);
}
//////////////////////////////////////////////////////////////////////
// Build trisibling factors with automata.
//////////////////////////////////////////////////////////////////////
if (use_trigram_head_automata && num_trisiblings > 0) {
// Get all the trisiblings, indices, etc.
// LPK: Not used in standard model
VLOG(2) << "use_trigram_head_automata\n";
vector<vector<DependencyPartTriSibl*> > left_trisiblings(sentence->size());
vector<vector<DependencyPartTriSibl*> > right_trisiblings(sentence->size());
vector<vector<double> > left_scores(sentence->size());
vector<vector<double> > right_scores(sentence->size());
vector<vector<int> > left_indices(sentence->size());
vector<vector<int> > right_indices(sentence->size());
for (int r = 0; r < num_trisiblings; ++r) {
DependencyPartTriSibl *trisibling =
static_cast<DependencyPartTriSibl*>(
(*parts)[offset_trisiblings + r]);
if (trisibling->head() > trisibling->other_sibling()) {
// Left trisibling.
left_trisiblings[trisibling->head()].push_back(trisibling);
left_scores[trisibling->head()].push_back(
scores[offset_trisiblings + r]);
// Save the part index to get the posterior later.
left_indices[trisibling->head()].push_back(offset_trisiblings + r);
} else {
// Right trisibling.
right_trisiblings[trisibling->head()].push_back(trisibling);
right_scores[trisibling->head()].push_back(
scores[offset_trisiblings + r]);
// Save the part index to get the posterior later.
right_indices[trisibling->head()].push_back(offset_trisiblings + r);
}
}
// Now, go through each head and create left and right automata.
for (int h = 0; h < sentence->size(); ++h) {
// Build left head automaton.
vector<AD3::BinaryVariable*> local_variables;
vector<DependencyPartArc*> arcs;
for (int m = h-1; m >= 1; --m) {
int r = dependency_parts->FindArc(h, m);
if (r < 0) continue;
int index = r - offset_arcs;
local_variables.push_back(variables[index]);
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*parts)[offset_arcs + r]);
arcs.push_back(arc);
}
//if (arcs.size() == 0) continue; // Do not create an empty factor.
AD3::FactorTrigramHeadAutomaton *left_factor =
new AD3::FactorTrigramHeadAutomaton;
left_factor->Initialize(arcs, left_trisiblings[h]);
left_factor->SetAdditionalLogPotentials(left_scores[h]);
factor_graph->DeclareFactor(left_factor, local_variables, true);
factor_part_indices_.push_back(-1);
additional_part_indices.insert(additional_part_indices.end(),
left_indices[h].begin(),
left_indices[h].end());
// Build right head automaton.
local_variables.clear();
arcs.clear();
for (int m = h+1; m < sentence->size(); ++m) {
int r = dependency_parts->FindArc(h, m);
if (r < 0) continue;
int index = r - offset_arcs;
local_variables.push_back(variables[index]);
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*parts)[offset_arcs + r]);
arcs.push_back(arc);
}
//if (arcs.size() == 0) continue; // Do not create an empty factor.
AD3::FactorTrigramHeadAutomaton *right_factor =
new AD3::FactorTrigramHeadAutomaton;
right_factor->Initialize(arcs, right_trisiblings[h]);
right_factor->SetAdditionalLogPotentials(right_scores[h]);
factor_graph->DeclareFactor(right_factor, local_variables, true);
factor_part_indices_.push_back(-1);
additional_part_indices.insert(additional_part_indices.end(),
right_indices[h].begin(),
right_indices[h].end());
}
}
//////////////////////////////////////////////////////////////////////
// Build next sibling factors.
//////////////////////////////////////////////////////////////////////
if (use_head_automata || use_grandparent_head_automata) {
//VLOG(0) << "FLAG3";
// LPK: IMPORTANT PART USED IN STANDARD MODEL
// Get all the grandparents, indices, etc.
vector<vector<DependencyPartGrandpar*> > left_grandparents(sentence->size());
vector<vector<DependencyPartGrandpar*> > right_grandparents(sentence->size());
vector<vector<double> > left_grandparent_scores(sentence->size());
vector<vector<double> > right_grandparent_scores(sentence->size());
vector<vector<int> > left_grandparent_indices(sentence->size());
vector<vector<int> > right_grandparent_indices(sentence->size());
if (use_grandparent_head_automata &&
use_grandparent_parts &&
use_next_sibling_parts) {
for (int r = 0; r < num_grandparents; ++r) {
DependencyPartGrandpar *part = static_cast<DependencyPartGrandpar*>(
(*dependency_parts)[offset_grandparents + r]);
//if (disabled_nodes[part->head()] || disabled_nodes[part->modifier()]) continue;
if (part->head() > part->modifier()) {
// Left sibling.
left_grandparents[part->head()].push_back(part);
left_grandparent_scores[part->head()].push_back(
scores[offset_grandparents + r]);
// Save the part index to get the posterior later.
left_grandparent_indices[part->head()].push_back(
offset_grandparents + r);
} else {
// Right sibling.
right_grandparents[part->head()].push_back(part);
right_grandparent_scores[part->head()].push_back(
scores[offset_grandparents + r]);
// Save the part index to get the posterior later.
right_grandparent_indices[part->head()].push_back(
offset_grandparents + r);
}
}
}
// Get all the grandsiblings, indices, etc.
vector<vector<DependencyPartGrandSibl*> > left_grandsiblings(sentence->size());
vector<vector<DependencyPartGrandSibl*> > right_grandsiblings(sentence->size());
vector<vector<double> > left_grandsibling_scores(sentence->size());
vector<vector<double> > right_grandsibling_scores(sentence->size());
vector<vector<int> > left_grandsibling_indices(sentence->size());
vector<vector<int> > right_grandsibling_indices(sentence->size());
if (use_grandparent_head_automata &&
use_grandsibling_parts) {
for (int r = 0; r < num_grandsiblings; ++r) {
DependencyPartGrandSibl *part = static_cast<DependencyPartGrandSibl*>(
(*dependency_parts)[offset_grandsiblings + r]);
if (part->head() > part->sibling()) {
// Left sibling.
left_grandsiblings[part->head()].push_back(part);
left_grandsibling_scores[part->head()].push_back(
scores[offset_grandsiblings + r]);
// Save the part index to get the posterior later.
left_grandsibling_indices[part->head()].push_back(
offset_grandsiblings + r);
} else {
// Right sibling.
right_grandsiblings[part->head()].push_back(part);
right_grandsibling_scores[part->head()].push_back(
scores[offset_grandsiblings + r]);
// Save the part index to get the posterior later.
right_grandsibling_indices[part->head()].push_back(
offset_grandsiblings + r);
}
}
}
// Get all the next siblings, indices, etc.
vector<vector<DependencyPartNextSibl*> > left_siblings(sentence->size());
vector<vector<DependencyPartNextSibl*> > right_siblings(sentence->size());
vector<vector<double> > left_scores(sentence->size());
vector<vector<double> > right_scores(sentence->size());
vector<vector<int> > left_indices(sentence->size());
vector<vector<int> > right_indices(sentence->size());
for (int r = 0; r < num_next_siblings; ++r) {
DependencyPartNextSibl *sibling =
static_cast<DependencyPartNextSibl*>(
(*parts)[offset_next_siblings + r]);
if (sibling->head() > sibling->next_sibling()) {
// Left sibling.
left_siblings[sibling->head()].push_back(sibling);
left_scores[sibling->head()].push_back(
scores[offset_next_siblings + r]);
// Save the part index to get the posterior later.
left_indices[sibling->head()].push_back(offset_next_siblings + r);
} else {
// Right sibling.
right_siblings[sibling->head()].push_back(sibling);
right_scores[sibling->head()].push_back(
scores[offset_next_siblings + r]);
// Save the part index to get the posterior later.
right_indices[sibling->head()].push_back(offset_next_siblings + r);
}
}
// Now, go through each head and create left and right automata.
for (int h = 0; h < sentence->size(); ++h) {
//VLOG(0) << "FLAG4";
// if (disabled_nodes[h]) continue;
// Get the incoming arcs, in case we are using grandparents
// or grandsiblings.
vector<AD3::BinaryVariable*> local_variables_grandparents;
vector<DependencyPartArc*> incoming_arcs;
if (use_grandparent_head_automata &&
((use_grandparent_parts && use_next_sibling_parts) ||
(use_grandsibling_parts))) {
// LPK : only if the head word - h is not disabled, can we build the incoming
// arcs for it.
if (!disabled_nodes[h]){
for (int g = 0; g < sentence->size(); ++g) {
int r = dependency_parts->FindArc(g, h);
if (r < 0) continue;
int index = r - offset_arcs;
local_variables_grandparents.push_back(variables[index]);
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*parts)[offset_arcs + r]);
incoming_arcs.push_back(arc);
}
}
}
// Build left head automaton.
vector<AD3::BinaryVariable*> local_variables = local_variables_grandparents;
vector<DependencyPartArc*> arcs;
for (int m = h-1; m >= 1; --m) {
int r = dependency_parts->FindArc(h, m);
if (r < 0) continue;
int index = r - offset_arcs;
local_variables.push_back(variables[index]);
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*parts)[offset_arcs + r]);
arcs.push_back(arc);
}
//if (arcs.size() == 0) continue; // Do not create an empty factor.
if (use_grandparent_head_automata &&
((use_grandparent_parts && use_next_sibling_parts) ||
(use_grandsibling_parts)) &&
incoming_arcs.size() > 0) {
// LPK: Since there is a incoming_arcs > 0 constrains there
// it seems we can simply prevent the automaton from construction
// by banning all the incomimg arcs
AD3::FactorGrandparentHeadAutomaton *factor =
new AD3::FactorGrandparentHeadAutomaton;
if (use_grandsibling_parts) {
factor->Initialize(incoming_arcs, arcs,
left_grandparents[h],
left_siblings[h],
left_grandsiblings[h]);
} else {
// LPK: This is the thing used in the standard model. (the left automata part.)
// (the right part can be seen later in the code.)
factor->Initialize(incoming_arcs, arcs,
left_grandparents[h],
left_siblings[h]);
}
vector<double> additional_log_potentials = left_grandparent_scores[h];
additional_log_potentials.insert(additional_log_potentials.end(),
left_scores[h].begin(),
left_scores[h].end());
if (use_grandsibling_parts) {
additional_log_potentials.insert(additional_log_potentials.end(),
left_grandsibling_scores[h].begin(),
left_grandsibling_scores[h].end());
}
factor->SetAdditionalLogPotentials(additional_log_potentials);
factor_graph->DeclareFactor(factor, local_variables, true);
factor_part_indices_.push_back(-1);
additional_part_indices.insert(additional_part_indices.end(),
left_grandparent_indices[h].begin(),
left_grandparent_indices[h].end());
additional_part_indices.insert(additional_part_indices.end(),
left_indices[h].begin(),
left_indices[h].end());
if (use_grandsibling_parts) {
additional_part_indices.insert(additional_part_indices.end(),
left_grandsibling_indices[h].begin(),
left_grandsibling_indices[h].end());
}
} else {
AD3::FactorHeadAutomaton *factor = new AD3::FactorHeadAutomaton;
factor->Initialize(arcs, left_siblings[h]);
factor->SetAdditionalLogPotentials(left_scores[h]);
factor_graph->DeclareFactor(factor, local_variables, true);
factor_part_indices_.push_back(-1);
additional_part_indices.insert(additional_part_indices.end(),
left_indices[h].begin(),
left_indices[h].end());
}
// Build right head automaton.
local_variables.clear();
local_variables = local_variables_grandparents;
arcs.clear();
for (int m = h+1; m < sentence->size(); ++m) {
int r = dependency_parts->FindArc(h, m);
if (r < 0) continue;
int index = r - offset_arcs;
local_variables.push_back(variables[index]);
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*parts)[offset_arcs + r]);
arcs.push_back(arc);
}
//if (arcs.size() == 0) continue; // Do not create an empty factor.
if (use_grandparent_head_automata &&
((use_grandparent_parts && use_next_sibling_parts) ||
(use_grandsibling_parts)) &&
incoming_arcs.size() > 0) {
AD3::FactorGrandparentHeadAutomaton *factor =
new AD3::FactorGrandparentHeadAutomaton;
if (use_grandsibling_parts) {
factor->Initialize(incoming_arcs, arcs,
right_grandparents[h],
right_siblings[h],
right_grandsiblings[h]);
} else {
factor->Initialize(incoming_arcs, arcs,
right_grandparents[h],
right_siblings[h]);
}
vector<double> additional_log_potentials = right_grandparent_scores[h];
additional_log_potentials.insert(additional_log_potentials.end(),
right_scores[h].begin(),
right_scores[h].end());
if (use_grandsibling_parts) {
additional_log_potentials.insert(additional_log_potentials.end(),
right_grandsibling_scores[h].begin(),
right_grandsibling_scores[h].end());
}
factor->SetAdditionalLogPotentials(additional_log_potentials);
factor_graph->DeclareFactor(factor, local_variables, true);
factor_part_indices_.push_back(-1);
additional_part_indices.insert(additional_part_indices.end(),
right_grandparent_indices[h].begin(),
right_grandparent_indices[h].end());
additional_part_indices.insert(additional_part_indices.end(),
right_indices[h].begin(),
right_indices[h].end());
if (use_grandsibling_parts) {
additional_part_indices.insert(additional_part_indices.end(),
right_grandsibling_indices[h].begin(),
right_grandsibling_indices[h].end());
}
} else {
AD3::FactorHeadAutomaton *factor = new AD3::FactorHeadAutomaton;
factor->Initialize(arcs, right_siblings[h]);
factor->SetAdditionalLogPotentials(right_scores[h]);
factor_graph->DeclareFactor(factor, local_variables, true);
factor_part_indices_.push_back(-1);
additional_part_indices.insert(additional_part_indices.end(),
right_indices[h].begin(),
right_indices[h].end());
}
}
} else {
//VLOG(0) << "FLAG5";
// Create OMEGA variables.
int offset_omega_variables = variables.size();
for (int r = 0; r < num_arcs; ++r) {
for (int s = 0; s < sentence->size(); ++s) {
// Create omega variable denoting that...
AD3::BinaryVariable* variable = factor_graph->CreateBinaryVariable();
variables.push_back(variable);
part_indices_.push_back(-1);
evidence.push_back(-1);
}
}
// Create RHO variables.
int offset_rho_variables = variables.size();
for (int m = 0; m < sentence->size(); ++m) {
for (int s = 0; s < sentence->size(); ++s) {
// Create rho variable denoting that...
AD3::BinaryVariable* variable = factor_graph->CreateBinaryVariable();
variables.push_back(variable);
part_indices_.push_back(-1);
evidence.push_back(-1);
}
}
// Create NEXT SIBL variables.
int offset_next_sibling_variables = variables.size();
for (int r = 0; r < num_next_siblings; ++r) {
AD3::BinaryVariable* variable = factor_graph->CreateBinaryVariable();
variable->SetLogPotential(scores[offset_next_siblings + r]);
variables.push_back(variable);
part_indices_.push_back(offset_next_siblings + r);
evidence.push_back(-1);
}
// Create the "omega normalizer" factor. The following constraints will be
// imposed:
// sum_{k >= ch >= par} omega_{par,ch,k} = 1, for all par, k.
// REMARK: omega_{par,ch,<q>} = z_{par,ch}.
//Hence in those cases must substitute omega by z accordingly
// Create arrays of the variables that partipate in each factor.
// Each array is in local_variables_rho[par][k].
vector<vector<vector<AD3::BinaryVariable*> > >
local_variables_omega_normalizer(sentence->size(),
vector<vector<AD3::BinaryVariable*> >(sentence->size()));
// Add the rho variables to the arrays.
for (int h = 0; h < sentence->size(); ++h) {
for (int k = 0; k < sentence->size(); ++k) {
int index = offset_rho_variables + h*sentence->size() + k;
local_variables_omega_normalizer[h][k].push_back(variables[index]);
}
}
// Add the omega variables to the arrays.
for (int r = 0; r < num_arcs; ++r) {
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*dependency_parts)[r]);
int h = arc->head();
int m = arc->modifier();
if (h < m) {
for (int k = m; k < sentence->size(); ++k) {
int index;
if (k == m) {
index = r;
} else {
index = offset_omega_variables + r*sentence->size() + k;
}
local_variables_omega_normalizer[h][k].push_back(variables[index]);
}
} else {
for (int k = m; k >= 0; k--) {
int index;
if (k == m) {
index = r;
} else {
index = offset_omega_variables + r*sentence->size() + k;
}
local_variables_omega_normalizer[h][k].push_back(variables[index]);
}
}
}
// Create the factors.
for (int h = 0; h < sentence->size(); ++h) {
for (int k = 0; k < sentence->size(); ++k) {
factor_graph->CreateFactorXOR(local_variables_omega_normalizer[h][k]);
factor_part_indices_.push_back(-1);
}
}
// Create the "omega propagate" and "rho propagate" factors. The following
// constraints will be imposed:
// omega_{par,ch1,ch2} + z_{par,ch1,ch2} = omega_{par,ch1,ch2-1}.
// Create arrays of the variables that partipate in each factor.
// Each array is in local_variables[r][k].
vector<vector<vector<AD3::BinaryVariable*> > > local_variables_omega_propagate(
num_arcs, vector<vector<AD3::BinaryVariable*> >(sentence->size()));
vector<vector<vector<bool> > > negated_omega_propagate(
num_arcs, vector<vector<bool> >(sentence->size()));
// Do this first for par != ch1 (omega propagate factors):
for (int r = 0; r < num_arcs; ++r) {
DependencyPartArc *arc =
static_cast<DependencyPartArc*>((*dependency_parts)[r + offset_arcs]);
int h = arc->head();
int m = arc->modifier();
if (h < m) {
for (int k = m + 1; k < sentence->size(); ++k) {
int index;
// Omega.
if (k == m) {
index = r;
} else {
index = offset_omega_variables + r*sentence->size() + k;
}
local_variables_omega_propagate[r][k].push_back(variables[index]);
negated_omega_propagate[r][k].push_back(false); // negated = false.
// Previous omega.
if (k - 1 == m) {
index = r;
} else {
index = offset_omega_variables + r*sentence->size() + k - 1;
}
local_variables_omega_propagate[r][k].push_back(variables[index]);
negated_omega_propagate[r][k].push_back(true); // negated = true.
}
} else {
for (int k = m - 1; k >= 0; k--) {
int index;
// Omega.
if (k == m) {
index = r;
} else {
index = offset_omega_variables + r*sentence->size() + k;
}
local_variables_omega_propagate[r][k].push_back(variables[index]);
negated_omega_propagate[r][k].push_back(false); // negated = false.
// Previous omega.
if (k + 1 == m) {
index = r;
} else {
index = offset_omega_variables + r*sentence->size() + k + 1;
}
local_variables_omega_propagate[r][k].push_back(variables[index]);
negated_omega_propagate[r][k].push_back(true); // negated = true.
}
}
}
// Create arrays of the variables that partipate in each factor.
// Each array is in local_variables[par][k].
vector<vector<vector<AD3::BinaryVariable*> > > local_variables_rho_propagate(
sentence->size(), vector<vector<AD3::BinaryVariable*> >(sentence->size()));
vector<vector<vector<bool> > > negated_rho_propagate(
sentence->size(), vector<vector<bool> >(sentence->size()));
// Now for par == ch1 (rho propagate factors):
for (int h = 0; h < sentence->size(); ++h) {
for (int k = 0; k < sentence->size(); ++k) {
if (h == k) continue;
if (h < k) {
int index;
// Rho.
index = offset_rho_variables + h*sentence->size() + k;
local_variables_rho_propagate[h][k].push_back(variables[index]);
negated_rho_propagate[h][k].push_back(false); // negated = false.
// Previous rho.
index = offset_rho_variables + h*sentence->size() + k - 1;
local_variables_rho_propagate[h][k].push_back(variables[index]);
negated_rho_propagate[h][k].push_back(true); // negated = true.
} else {
int index;
// Rho.
index = offset_rho_variables + h*sentence->size() + k;
local_variables_rho_propagate[h][k].push_back(variables[index]);
negated_rho_propagate[h][k].push_back(false); // negated = false.
// Previous rho.
index = offset_rho_variables + h*sentence->size() + k + 1;
local_variables_rho_propagate[h][k].push_back(variables[index]);
negated_rho_propagate[h][k].push_back(true); // negated = true.
}
}
}
// Now add the prev sibl variables to these factors.
for (int r = 0; r < num_next_siblings; ++r) {
DependencyPartNextSibl *part = static_cast<DependencyPartNextSibl*>(
(*dependency_parts)[offset_next_siblings + r]);
int h = part->head();
int m = part->modifier();
int s = part->next_sibling();
// Last child (left or right).
if (s == sentence->size() || s == -1) continue;
if (h == m) {
// First child variable.
int index = offset_next_sibling_variables + r;
local_variables_rho_propagate[h][s].push_back(variables[index]);
negated_rho_propagate[h][s].push_back(false); // negated = false.
} else {
// Next sibling variable.
int r1 = dependency_parts->FindArc(h, m);
int index = offset_next_sibling_variables + r;
local_variables_omega_propagate[r1 - offset_arcs][s].push_back(
variables[index]);
// negated = false.
negated_omega_propagate[r1 - offset_arcs][s].push_back(false);
}
}
// Create the actual factors.
for (int r = 0; r < num_arcs; ++r) {
for (int k = 0; k < sentence->size(); ++k) {
if (local_variables_omega_propagate[r][k].size() == 0) continue;
CHECK_GE(local_variables_omega_propagate[r][k].size(), 2);
CHECK_LE(local_variables_omega_propagate[r][k].size(), 3);
factor_graph->CreateFactorXOR(local_variables_omega_propagate[r][k],
negated_omega_propagate[r][k]);
factor_part_indices_.push_back(-1);
}
}
for (int h = 0; h < sentence->size(); ++h) {
for (int k = 0; k < sentence->size(); ++k) {
if (local_variables_rho_propagate[h][k].size() == 0) continue;
CHECK_GE(local_variables_rho_propagate[h][k].size(), 2);
CHECK_LE(local_variables_rho_propagate[h][k].size(), 3);
factor_graph->CreateFactorXOR(local_variables_rho_propagate[h][k],
negated_rho_propagate[h][k]);
factor_part_indices_.push_back(-1);
}
}
// Create the "next sibling consistency" factors. The following constraints
// will be imposed:
// sum_{ch1} z_{par,ch1,ch2} = z_{par,ch2}.
// Create arrays of the variables that participate in each factor.
// Each array is in local_variables[r].
vector<vector<AD3::BinaryVariable*> > local_variables_consistency(
num_arcs);
for (int r = 0; r < num_next_siblings; ++r) {
DependencyPartNextSibl *part = static_cast<DependencyPartNextSibl*>(
(*dependency_parts)[offset_next_siblings + r]);
int h = part->head();
int s = part->next_sibling();
// Last child (left or right).
if (s == sentence->size() || s == -1) continue;
// Next sibling variable (negated = false).
int r2 = dependency_parts->FindArc(h, s);
int index = offset_next_sibling_variables + r;
local_variables_consistency[r2 - offset_arcs].push_back(variables[index]);
}
for (int r = 0; r < num_arcs; ++r) {
// Arc variable (negated = true).
local_variables_consistency[r].push_back(variables[r]);
}
// Create the actual factors.
for (int r = 0; r < num_arcs; ++r) {
if (local_variables_consistency[r].size() == 0) continue;
factor_graph->CreateFactorXOROUT(local_variables_consistency[r]);
factor_part_indices_.push_back(-1);
}
// Take care of the leftmost/rightmost children.
// Create "equality" factors for handling special cases, making sure that
// certain variables are equivalent.
for (int r = 0; r < num_next_siblings; ++r) {
DependencyPartNextSibl *part = static_cast<DependencyPartNextSibl*>(
(*dependency_parts)[offset_next_siblings + r]);
int h = part->head();
int m = part->modifier();
int s = part->next_sibling();
// Do something for LAST CHILD:
// * omega[r*length + (length-1)] if r points to the right
// * omega[r*length + 0] if r points to the left
// * rho[par*length + (length-1)] if r points to the right
// * rho[par*length + 0] if r points to the left.
if (s == sentence->size()) {
// Rightmost child.
if (h == m) {
// No child on right side.
// Impose the constraint:
// z[r] == rho[par*length + (length-1)];
vector<AD3::BinaryVariable*> local_variables(2);
int index = offset_next_sibling_variables + r;
local_variables[0] = variables[index];
index = offset_rho_variables + h * sentence->size() +
(sentence->size() - 1);
local_variables[1] = variables[index];
// Create the factor.
factor_graph->CreateFactorXOROUT(local_variables);
factor_part_indices_.push_back(-1);
} else {
// Impose the constraint:
// z[r] == omega[r1*length + (length-1)];
int r1 = dependency_parts->FindArc(h, m);
CHECK_GE(r1, 0);
vector<AD3::BinaryVariable*> local_variables(2);
int index = offset_next_sibling_variables + r;
local_variables[0] = variables[index];
if (sentence->size() - 1 == m) {
index = r1 - offset_arcs;
} else {
index = offset_omega_variables +
(r1 - offset_arcs) * sentence->size() + (sentence->size() - 1);
}
local_variables[1] = variables[index];
// Create the factor.
factor_graph->CreateFactorXOROUT(local_variables);
factor_part_indices_.push_back(-1);
}
} else if (s == -1) {
// Leftmost child.
if (h == m) {
// No child on left side.
// Impose the constraint:
// z[r] == rho[par*length + 0];
vector<AD3::BinaryVariable*> local_variables(2);
int index = offset_next_sibling_variables + r;
local_variables[0] = variables[index];
index = offset_rho_variables + h * sentence->size() + 0;
local_variables[1] = variables[index];
// Create the factor.
factor_graph->CreateFactorXOROUT(local_variables);
factor_part_indices_.push_back(-1);
} else {
// Impose the constraint:
// z[r] == omega[r1*length + 0];
int r1 = dependency_parts->FindArc(h, m);
CHECK_GE(r1, 0);
vector<AD3::BinaryVariable*> local_variables(2);
int index = offset_next_sibling_variables + r;
local_variables[0] = variables[index];
if (0 == m) {
CHECK(false);
index = r1 - offset_arcs;
} else {
index = offset_omega_variables +
(r1 - offset_arcs) * sentence->size() + 0;
}
local_variables[1] = variables[index];
// Create the factor.
factor_graph->CreateFactorXOROUT(local_variables);
factor_part_indices_.push_back(-1);
}
}
}
}
//////////////////////////////////////////////////////////////////////
// Handle the non-projective parts.
//////////////////////////////////////////////////////////////////////
// Create NONPROJARCEXTRA variables.
// These indicate that a span is nonprojective, being or not being a arc
// there.
int offset_nonproj_extra_variables = variables.size();
for (int r = 0; r < num_nonprojective; ++r) {
// NONPROJARCEXTRA variable.
AD3::BinaryVariable* variable = factor_graph->CreateBinaryVariable();
variables.push_back(variable);
part_indices_.push_back(-1);
DependencyPartNonproj *part = static_cast<DependencyPartNonproj*>(
(*dependency_parts)[offset_nonprojective + r]);
int evidence_value = -1;
if (part->head() == 0) {
// NONPROJARCEXTRA is necessarily 0.
if (add_evidence) {
evidence_value = 0;
} else {
variable->SetLogPotential(log_potential_zero);
}
}
evidence.push_back(evidence_value);
}
// Create NONPROJARC variables.
// These are the conjunction of the ARC variables with the NONPROJARCEXTRA
// variables.
int offset_nonproj_variables = variables.size();
for (int r = 0; r < num_nonprojective; ++r) {
// NONPROJARC variable.
AD3::BinaryVariable* variable = factor_graph->CreateBinaryVariable();
variable->SetLogPotential(scores[offset_nonprojective + r]);
variables.push_back(variable);
part_indices_.push_back(offset_nonprojective + r);
evidence.push_back(-1);
}
// Create NONPROJARCEXTRA factors.
for (int r = 0; r < num_nonprojective; ++r) {
//LOG(0) << "FLAG6";
DependencyPartNonproj *part = static_cast<DependencyPartNonproj*>(
(*dependency_parts)[offset_nonprojective + r]);
// No factor necessary in this case, as NONPROJARCEXTRA is necessarily 0.
if (part->head() == 0) continue;
vector<AD3::BinaryVariable*> local_variables;
vector<bool> negated;
int left, right;
if (part->head() <= part->modifier()) {
left = part->head();
right = part->modifier();
} else {
left = part->modifier();
right = part->head();
}
CHECK_GE(offset_path_variables, 0);
for (int k = left; k <= right; ++k) {
// Add negated path variable.
int index = offset_path_variables + part->head() + k * sentence->size();
local_variables.push_back(variables[index]);
negated.push_back(true);
}
// Add NONPROJARCEXTRA variable.
int index = offset_nonproj_extra_variables + r;
local_variables.push_back(variables[index]);
negated.push_back(false);
// Create the NONPROJARCEXTRA factor.
factor_graph->CreateFactorOROUT(local_variables, negated);
factor_part_indices_.push_back(-1);
}
// Create NONPROJARC factors.
for (int r = 0; r < num_nonprojective; ++r) {
//VLOG(0) << "FLAG7";
DependencyPartNonproj *part = static_cast<DependencyPartNonproj*>(
(*dependency_parts)[offset_nonprojective + r]);
vector<AD3::BinaryVariable*> local_variables;
int r1 = dependency_parts->FindArc(part->head(), part->modifier());
// Add the arc variable (negated).
int index = r1 - offset_arcs;
local_variables.push_back(variables[index]);
// Add the NONPROJARCEXTRA variable (negated).
index = offset_nonproj_extra_variables + r;
local_variables.push_back(variables[index]);
// Add the NONPROJARC variable (negated).
index = offset_nonproj_variables + r;
local_variables.push_back(variables[index]);
// Create the NONPROJARCEXTRA factor.
factor_graph->CreateFactorANDOUT(local_variables);
factor_part_indices_.push_back(-1);
}
//////////////////////////////////////////////////////////////////////
// Handle the directed path parts.
//////////////////////////////////////////////////////////////////////
if (num_path > 0) CHECK_GE(offset_path_variables, 0);
for (int r = 0; r < num_path; ++r) {
//VLOG(0) << "FLAG8";
DependencyPartPath *part = static_cast<DependencyPartPath*>(
(*dependency_parts)[offset_path + r]);
int a = part->ancestor();
int d = part->descendant();
int index = offset_path_variables + a + d*sentence->size();
AD3::BinaryVariable *variable = variables[index];
part_indices_[index] = offset_path + r;
// TODO: solve this problem.
// varPath->m_logPotentialOrig = scores[offset + r];
// Only update the log potential if it was not set to zero or infinity
// earlier.
if (variable->GetLogPotential() == 0.0) {
variable->SetLogPotential(scores[offset_path + r]);
}
}
//////////////////////////////////////////////////////////////////////
// Handle the head bigram parts.
//////////////////////////////////////////////////////////////////////
if (use_head_bigram_sequence_factor && use_head_bigram_parts) {
//VLOG(0) << "FLAG9";
// Populate local variables and compute the number of states for each
// position in the sequence (i.e. each word).
vector<AD3::BinaryVariable*> local_variables;
vector<int> num_states(sentence->size() - 1, 0);
vector<vector<int> > index_heads(sentence->size() - 1,
vector<int>(sentence->size(), -1));
for (int m = 1; m < sentence->size(); ++m) {
for (int h = 0; h < sentence->size(); ++h) {
int r = dependency_parts->FindArc(h, m);
if (r < 0) continue;
local_variables.push_back(variables[r - offset_arcs]);
index_heads[m - 1][h] = num_states[m - 1];
++num_states[m - 1];
}
}
vector<vector<vector<int> > > index_edges(sentence->size());
int index = 0;
for (int i = 0; i < sentence->size(); ++i) {
// If i == 0, the previous state is the start symbol.
int num_previous_states = (i > 0)? num_states[i - 1] : 1;
// One state to account for the final symbol.
int num_current_states = (i < sentence->size() - 1)? num_states[i] : 1;
index_edges[i].resize(num_previous_states);
for (int j = 0; j < num_previous_states; ++j) {
index_edges[i][j].resize(num_current_states);
for (int k = 0; k < num_current_states; ++k) {
index_edges[i][j][k] = index;
++index;
}
}
}
vector<double> additional_log_potentials(index, 0.0);
vector<int> head_bigram_indices(index, -1);
for (int r = 0; r < num_bigrams; ++r) {
DependencyPartHeadBigram *part = static_cast<DependencyPartHeadBigram*>
((*dependency_parts)[offset_bigrams + r]);
int m = part->modifier();
CHECK_GE(m, 1);
CHECK_LT(m, sentence->size() + 1);
int previous_state = (m == 1)?
0 : index_heads[m - 2][part->previous_head()];
int current_state = (m == sentence->size())? 0 : index_heads[m - 1][part->head()];
CHECK_GE(previous_state, 0);
if (m > 1) CHECK_LT(previous_state, num_states[m - 2]);
CHECK_GE(current_state, 0);
if (m < sentence->size()) CHECK_LT(current_state, num_states[m - 1]);
int index = index_edges[m - 1][previous_state][current_state];
CHECK_GE(index, 0);
CHECK_LT(index, additional_log_potentials.size());
additional_log_potentials[index] = scores[offset_bigrams + r];
head_bigram_indices[index] = offset_bigrams + r;
}
AD3::FactorSequence *factor = new AD3::FactorSequence;
factor->Initialize(num_states);
factor->SetAdditionalLogPotentials(additional_log_potentials);
factor_graph->DeclareFactor(factor, local_variables, true);
factor_part_indices_.push_back(-1);
additional_part_indices.insert(additional_part_indices.end(),
head_bigram_indices.begin(),
head_bigram_indices.end());
} else {
for (int r = 0; r < num_bigrams; ++r) {
//VLOG(0) << "FLAG10";
DependencyPartHeadBigram *part = static_cast<DependencyPartHeadBigram*>
((*dependency_parts)[offset_bigrams + r]);
int r1 = dependency_parts->FindArc(part->head(), part->modifier());
int r2 = dependency_parts->FindArc(part->previous_head(),
part->modifier() - 1);
CHECK_GE(r1, 0);
CHECK_GE(r2, 0);
vector<AD3::BinaryVariable*> local_variables;
local_variables.push_back(variables[r1 - offset_arcs]);
local_variables.push_back(variables[r2 - offset_arcs]);
factor_graph->CreateFactorPAIR(local_variables,
scores[offset_bigrams + r]);
// TODO: set these global indices at the end after all variables/factors are created.
//factor->SetGlobalIndex(...);
additional_part_indices.push_back(offset_bigrams + r);
factor_part_indices_.push_back(offset_bigrams + r);
}
}
//////////////////////////////////////////////////////////////////////////////
// LPK: end of difficult factors
CHECK_EQ(variables.size(), part_indices_.size());
CHECK_EQ(factor_graph->GetNumFactors(), factor_part_indices_.size());
// Compute additional_part_indices_.
int offset = factor_graph->GetNumVariables();
for (int i = 0; i < factor_graph->GetNumFactors(); ++i) {
offset += factor_graph->GetFactor(i)->GetAdditionalLogPotentials().size();
}
CHECK_EQ(additional_part_indices.size(),
offset - factor_graph->GetNumVariables());
// Concatenate part_indices and additional_part_indices.
part_indices_.insert(part_indices_.end(),
additional_part_indices.begin(),
additional_part_indices.end());
evidence.resize(part_indices_.size(), -1);
VLOG(2) << "Number of factors: " << factor_graph->GetNumFactors();
VLOG(2) << "Number of variables: " << factor_graph->GetNumVariables();
vector<int> recomputed_indices(part_indices_.size(), -1);
bool solved = false;
if (add_evidence) {
VLOG(2) << "Adding evidence...";
timeval start, end;
gettimeofday(&start, NULL);
int status = factor_graph->AddEvidence(&evidence, &recomputed_indices);
gettimeofday(&end, NULL);
double elapsed_time = diff_ms(end,start);
VLOG(2) << "Graph simplification took " << elapsed_time << "ms.";
CHECK_NE(status, AD3::STATUS_INFEASIBLE);
if (status == AD3::STATUS_OPTIMAL_INTEGER) solved = true;
VLOG(2) << "Number of factors: " << factor_graph->GetNumFactors();
VLOG(2) << "Number of variables: " << factor_graph->GetNumVariables();
}
//#define PRINT_GRAPH
#ifdef PRINT_GRAPH
//static int num_inst = 0;
ofstream stream;
stream.open("tmp.fg", ofstream::out | ofstream::app);
//stream.open("tmp.fg", ofstream::out);
CHECK(stream.good());
factor_graph->Print(stream);
stream << endl;
//++num_inst;
//if (num_inst == 14) CHECK(false);
stream.flush();
stream.clear();
stream.close();
#endif
vector<double> posteriors;
vector<double> additional_posteriors;
double value_ref;
double *value = &value_ref;
factor_graph->SetMaxIterationsAD3(500);
//factor_graph->SetMaxIterationsAD3(200);
factor_graph->SetEtaAD3(0.05);
factor_graph->AdaptEtaAD3(true);
factor_graph->SetResidualThresholdAD3(1e-3);
//factor_graph->SetResidualThresholdAD3(1e-6);
// Run AD3.
timeval start, end;
gettimeofday(&start, NULL);
if (!solved) {
factor_graph->SolveLPMAPWithAD3(&posteriors, &additional_posteriors, value);
}
gettimeofday(&end, NULL);
double elapsed_time = diff_ms(end,start);
VLOG(2) << "Elapsed time (AD3) = " << elapsed_time
<< " (" << sentence->size() << ") ";
delete factor_graph;
*value = 0.0;
predicted_output->assign(parts->size(), 0.0);
for (int i = 0; i < part_indices_.size(); ++i) {
int r = part_indices_[i];
if (r < 0) continue;
if (add_evidence) {
if (recomputed_indices[i] < 0) {
CHECK_GE(evidence[i], 0) << i;
(*predicted_output)[r] = evidence[i];
} else {
if (recomputed_indices[i] < posteriors.size()) {
(*predicted_output)[r] = posteriors[recomputed_indices[i]];
} else {
int j = recomputed_indices[i] - posteriors.size();
(*predicted_output)[r] = additional_posteriors[j];
}
}
} else {
if (i < posteriors.size()) {
(*predicted_output)[r] = posteriors[i];
} else {
int j = i - posteriors.size();
(*predicted_output)[r] = additional_posteriors[j];
}
}
*value += (*predicted_output)[r] * scores[r];
}
VLOG(2) << "Solution value (AD3) = " << *value;
}
#ifdef USE_CPLEX
#include <limits.h>
#define ILOUSESTL
#include <ilcplex/ilocplex.h>
ILOSTLBEGIN
void DependencyDecoder::DecodeCPLEX(Instance *instance, Parts *parts,
const vector<double> &scores,
bool single_root,
bool relax,
vector<double> *predicted_output) {
DependencyParts *dependency_parts = static_cast<DependencyParts*>(parts);
DependencyInstanceNumeric* sentence =
static_cast<DependencyInstanceNumeric*>(instance);
int offset_arcs, num_arcs;
dependency_parts->GetOffsetArc(&offset_arcs, &num_arcs);
int offset_labeled_arcs, num_labeled_arcs;
dependency_parts->GetOffsetArc(&offset_arcs, &num_arcs);
int offset_siblings, num_siblings;
dependency_parts->GetOffsetSibl(&offset_siblings, &num_siblings);
int offset_next_siblings, num_next_siblings;
dependency_parts->GetOffsetNextSibl(&offset_next_siblings, &num_next_siblings);
int offset_grandparents, num_grandparents;
dependency_parts->GetOffsetGrandpar(&offset_grandparents, &num_grandparents);
int offset_nonprojective, num_nonprojective;
dependency_parts->GetOffsetNonproj(&offset_nonprojective, &num_nonprojective);
int offset_path, num_path;
dependency_parts->GetOffsetPath(&offset_path, &num_path);
int offset_bigrams, num_bigrams;
dependency_parts->GetOffsetHeadBigr(&offset_bigrams, &num_bigrams);
bool use_arbitrary_sibling_parts = (num_siblings > 0);
bool use_next_sibling_parts = (num_next_siblings > 0);
bool use_grandparent_parts = (num_grandparents > 0);
bool use_nonprojective_arc_parts = (num_nonprojective > 0);
bool use_path_parts = (num_path > 0);
bool use_head_bigram_parts = (num_bigrams > 0);
// If true, use multi-commodities; otherwise, use single commodities.
bool use_multicommodity_flows = true;
int i, j, r;
try
{
timeval start, end;
gettimeofday(&start, NULL);
IloEnv env;
IloModel mod(env);
IloCplex cplex(mod);
///////////////////////////////////////////////////////////////////
// Variable definition
///////////////////////////////////////////////////////////////////
IloNumVar::Type varType = relax? ILOFLOAT : ILOBOOL;
IloNumVarArray z(env, parts->size(), 0.0, 1.0, varType);
IloNumVarArray flow;
if (use_multicommodity_flows)
flow = IloNumVarArray(env, num_arcs * sentence->size(), 0.0, 1.0, ILOFLOAT);
else
flow = IloNumVarArray(env, num_arcs, 0.0, sentence->size() - 1, ILOFLOAT);
///////////////////////////////////////////////////////////////////
// Objective
///////////////////////////////////////////////////////////////////
IloExpr exprObj(env);
for (r = 0; r < parts->size(); r++)
{
// Skip labeled arcs.
if ((*parts)[r]->type() == DEPENDENCYPART_LABELEDARC) continue;
// Add score to the objective.
exprObj += -scores[r] * z[r];
}
IloObjective obj(env, exprObj, IloObjective::Minimize);
mod.add(obj);
exprObj.end();
///////////////////////////////////////////////////////////////////
// Constraints
///////////////////////////////////////////////////////////////////
// The root has no parent
// sum_i (z_i0) = 0
IloExpr expr(env);
for (i = 0; i < sentence->size(); i++)
{
r = dependency_parts->FindArc(i, 0);
if (r < 0)
continue;
expr += z[r];
}
mod.add(expr == 0.0);
expr.end();
// afm 10/31/09
if (single_root)
{
// The root has exactly one child
// sum_i (z_0i) = 1
IloExpr expr(env);
for (i = 0; i < sentence->size(); i++)
{
r = dependency_parts->FindArc(0, i);
if (r < 0)
continue;
expr += z[r];
}
mod.add(expr == 1.0);
expr.end();
}
for (int j = 1; j < sentence->size(); j++)
{
// One parent per word (other than the root)
// sum_i (z_ij) = 1 for all j
expr = IloExpr(env);
for (i = 0; i < sentence->size(); i++)
{
r = dependency_parts->FindArc(i, j);
if (r < 0)
continue;
expr += z[r];
}
mod.add(expr == 1.0);
expr.end();
}
if (use_multicommodity_flows) // Multi-commodity flows
{
int k;
// Root sends one unit of commodity to each node
// sum_i (f_i0k) - sum_i (f_0ik) = -1, for each k which is not zero
for (k = 1; k < sentence->size(); k++)
{
expr = IloExpr(env);
for (int j = 0; j < sentence->size(); j++)
{
r = dependency_parts->FindArc(0, j);
if (r < 0)
continue;
expr += flow[r*sentence->size() + k];
r = dependency_parts->FindArc(j, 0);
if (r < 0)
continue;
expr -= flow[r*sentence->size() + k];
}
mod.add(expr == 1.0);
expr.end();
}
// Any node consume its own commodity and no other:
// sum_i (f_ijk) - sum_i (f_jik) = 1(j==k), for each j,k which are not zero
for (k = 1; k < sentence->size(); k++)
{
for (j = 1; j < sentence->size(); j++)
{
expr = IloExpr(env);
for (i = 0; i < sentence->size(); i++)
{
r = dependency_parts->FindArc(i, j);
if (r < 0)
continue;
expr += flow[r*sentence->size() + k];
}
for (i = 0; i < sentence->size(); i++)
{
r = dependency_parts->FindArc(j, i);
if (r < 0)
continue;
expr -= flow[r*sentence->size() + k];
}
if (j == k)
mod.add(expr == 1.0);
else
mod.add(expr == 0.0);
expr.end();
}
}
// Disabled arcs do not carry any flow
// f_ijk <= z_ij for each i, j, and k
for (r = 0; r < num_arcs; r++)
{
for (k = 0; k < sentence->size(); k++)
{
mod.add(flow[r*sentence->size() + k] <= z[r]);
}
}
}
else // Single commodity flows
{
// Root sends flow n
// sum_j (f_0j) = n
expr = IloExpr(env);
for (j = 0; j < sentence->size(); j++)
{
r = dependency_parts->FindArc(0, j);
if (r < 0)
continue;
expr += flow[r];
}
mod.add(expr == sentence->size() - 1);
expr.end();
// Incoming minus outgoing flow is 1 (except for the root)
// sum_i (f_ij) - sum_i (f_ji) = 1 for each j
for (j = 1; j < sentence->size(); j++)
{
expr = IloExpr(env);
for (i = 0; i < sentence->size(); i++)
{
r = dependency_parts->FindArc(i, j);
if (r < 0)
continue;
expr += flow[r];
}
for (i = 0; i < sentence->size(); i++)
{
r = dependency_parts->FindArc(j, i);
if (r < 0)
continue;
expr -= flow[r];
}
mod.add(expr == 1.0);
expr.end();
}
// Flow on disabled arcs is zero
// f_ij <= n*z_ij for each i and j
for (i = 0; i < sentence->size(); i++)
{
for (j = 0; j < sentence->size(); j++)
{
r = dependency_parts->FindArc(i, j);
if (r < 0)
continue;
mod.add(flow[r] <= (sentence->size()-1) * z[r]);
}
}
}
///////////////////////////////////////////////////////////////
// Add global constraints (if any)
///////////////////////////////////////////////////////////////
if (use_arbitrary_sibling_parts)
{
// z_ijk <= z_ij for each i,j,k
// z_ijk <= z_ik for each i,j,k
// z_ijk >= z_ij + z_ik - 1 for each i,j,k
for (int r = 0; r < num_siblings; ++r)
{
DependencyPartSibl *part = static_cast<DependencyPartSibl*>(
(*dependency_parts)[offset_siblings + r]);
int h = part->head();
int m = part->modifier();
int s = part->sibling();
int r1 = dependency_parts->FindArc(h, m);
int r2 = dependency_parts->FindArc(h, s);
CHECK_GE(r1, 0);
CHECK_GE(r2, 0);
mod.add(z[offset_siblings + r] - z[r1] <= 0.0);
mod.add(z[offset_siblings + r] - z[r2] <= 0.0);
mod.add(z[offset_siblings + r] - z[r1] - z[r2] >= -1.0);
}
}
if (use_next_sibling_parts)
{
IloNumVarArray omega(env, num_arcs * sentence->size(),
0.0, 1.0, ILOFLOAT);
IloNumVarArray rho(env, sentence->size() * sentence->size(),
0.0, 1.0, ILOFLOAT); // This stores omega(par,par,k)
//////////////////////////////////////////////////
// omega_{par,ch,ch} = z_{par,ch}
//////////////////////////////////////////////////
for (int r = 0; r < num_arcs; r++)
{
DependencyPartArc *arc = static_cast<DependencyPartArc*>(
(*dependency_parts)[offset_arcs + r]);
int par = arc->head();
int ch = arc->modifier();
if (par == ch) // This should never happen
continue;
mod.add(omega[r*sentence->size() + ch] - z[r] == 0.0);
}
//////////////////////////////////////////////////
// sum_{k >= ch >= par} omega_{par,ch,k} = 1, for all k
//////////////////////////////////////////////////
vector<IloExpr> vExpr(sentence->size() * sentence->size());
for (int ind = 0; ind < vExpr.size(); ind++)
vExpr[ind] = IloExpr(env);
for (int par = 0; par < sentence->size(); par++)
{
for (int k = 0; k < sentence->size(); k++)
{
vExpr[par*sentence->size() + k] += rho[par*sentence->size() + k];
}
}
for (int r = 0; r < num_arcs; r++)
{
DependencyPartArc *arc = static_cast<DependencyPartArc*>(
(*dependency_parts)[offset_arcs + r]);
int par = arc->head();
int ch = arc->modifier();
if (par == ch) // This should never happen
continue;
if (par < ch)
{
for (int k = ch; k < sentence->size(); k++)
{
vExpr[par*sentence->size() + k] += omega[r*sentence->size() + k];
}
}
else
{
for (int k = ch; k >= 0; k--)
{
vExpr[par*sentence->size() + k] += omega[r*sentence->size() + k];
}
}
}
for (int ind = 0; ind < vExpr.size(); ind++)
{
mod.add(vExpr[ind] == 1.0);
vExpr[ind].end();
}
//////////////////////////////////////////////////
// omega_{par,ch1,ch2} + z_{par,ch1,ch2} = omega_{par,ch1,ch2-1}
//////////////////////////////////////////////////
// Do this first for par != ch1:
vExpr.clear();
vExpr.resize(num_arcs * sentence->size());
for (int ind = 0; ind < vExpr.size(); ind++)
vExpr[ind] = IloExpr(env);
for (int r = 0; r < num_arcs; r++)
{
DependencyPartArc *arc = static_cast<DependencyPartArc*>(
(*dependency_parts)[offset_arcs + r]);
int par = arc->head();
int ch = arc->modifier();
if (par == ch) // This should never happen
continue;
if (par < ch)
{
for (int k = ch + 1; k < sentence->size(); k++)
{
vExpr[r*sentence->size() + k] += omega[r*sentence->size() + k] - omega[r*sentence->size() + k - 1];
}
}
else
{
for (int k = ch - 1; k >= 0; k--)
{
vExpr[r*sentence->size() + k] += omega[r*sentence->size() + k] - omega[r*sentence->size() + k + 1];
}
}
}
// Now for par == ch1:
vector<IloExpr> vExpr2(sentence->size() * sentence->size());
for (int ind = 0; ind < vExpr2.size(); ind++)
vExpr2[ind] = IloExpr(env);
for (int par = 0; par < sentence->size(); par++)
{
for (int k = 0; k < sentence->size(); k++)
{
if (par == k)
continue;
if (par < k)
{
vExpr2[par*sentence->size() + k] += rho[par*sentence->size() + k] - rho[par*sentence->size() + k - 1];
}
else // if (par > k)
{
vExpr2[par*sentence->size() + k] += rho[par*sentence->size() + k] - rho[par*sentence->size() + k + 1];
}
}
}
for (int r = 0; r < num_next_siblings; ++r)
{
DependencyPartNextSibl *part = static_cast<DependencyPartNextSibl*>(
(*dependency_parts)[offset_next_siblings + r]);
int h = part->head();
int m = part->modifier();
int s = part->next_sibling();
if (s == sentence->size() || s == -1) // Last child (left or right)
continue;
if (h == m) // First child
vExpr2[h*sentence->size() + s] += z[offset_next_siblings + r];
else
{
int r1 = dependency_parts->FindArc(h, m);
int r2 = dependency_parts->FindArc(h, s);
vExpr[r1*sentence->size() + s] += z[offset_next_siblings + r];
}
}
for (int ind = 0; ind < vExpr.size(); ind++)
{
mod.add(vExpr[ind] == 0.0);
vExpr[ind].end();
}
for (int ind = 0; ind < vExpr2.size(); ind++)
{
mod.add(vExpr2[ind] == 0.0);
vExpr2[ind].end();
}
//////////////////////////////////////////////////
// sum_{ch1} z_{par,ch1,ch2} = z_{par,ch2}
//////////////////////////////////////////////////
vExpr.clear();
vExpr.resize(num_arcs);
for (int ind = 0; ind < vExpr.size(); ind++)
vExpr[ind] = IloExpr(env);
for (int r = 0; r < num_next_siblings; ++r)
{
DependencyPartNextSibl *part = static_cast<DependencyPartNextSibl*>(
(*dependency_parts)[offset_next_siblings + r]);
int h = part->head();
int m = part->modifier();
int s = part->next_sibling();
if (s == sentence->size() || s == -1) // Last child (left/right)
continue;
int r1 = dependency_parts->FindArc(h, m);
int r2 = dependency_parts->FindArc(h, s);
vExpr[r2] += z[offset_next_siblings + r];
}
for (int ind = 0; ind < vExpr.size(); ind++)
{
mod.add(vExpr[ind] == z[ind]);
vExpr[ind].end();
}
// Take care of the leftmost/rightmost children:
for (int r = 0; r < num_next_siblings; ++r)
{
DependencyPartNextSibl *part = static_cast<DependencyPartNextSibl*>(
(*dependency_parts)[offset_next_siblings + r]);
int h = part->head();
int m = part->modifier();
int s = part->next_sibling();
// Do something for LAST CHILD:
// * omega[r*sentence->size() + (sentence->size()-1)] if r points to the right
// * omega[r*sentence->size() + 0] if r points to the left
// * rho[par*sentence->size() + (sentence->size()-1)] if r points to the right
// * rho[par*sentence->size() + 0] if r points to the left
if (s == sentence->size()) // Rightmost child
{
if (h == m) // No child on right side
{
mod.add(z[offset_next_siblings + r] == rho[h*sentence->size() + (sentence->size()-1)]);
}
else
{
int r1 = dependency_parts->FindArc(h, m);
mod.add(z[offset_next_siblings + r] == omega[r1*sentence->size() + (sentence->size()-1)]);
}
}
else if (s == -1) // Leftmost child
{
if (h == m) // No child on left side
{
mod.add(z[offset_next_siblings + r] == rho[h*sentence->size() + 0]);
}
else
{
int r1 = dependency_parts->FindArc(h, m);
mod.add(z[offset_next_siblings + r] == omega[r1*sentence->size() + 0]);
}
}
}
}
if (use_grandparent_parts)
{
// z_ijk <= z_ij for each i,j,k
// z_ijk <= z_ik for each i,j,k
// z_ijk >= z_ij + z_ik - 1 for each i,j,k
for (int r = 0; r < num_grandparents; ++r)
{
DependencyPartGrandpar *part = static_cast<DependencyPartGrandpar*>(
(*dependency_parts)[offset_grandparents + r]);
int g = part->grandparent();
int h = part->head();
int m = part->modifier();
int r1 = dependency_parts->FindArc(g, h);
int r2 = dependency_parts->FindArc(h, m);
CHECK_GE(r1, 0);
CHECK_GE(r2, 0);
mod.add(z[offset_grandparents + r] - z[r1] <= 0.0);
mod.add(z[offset_grandparents + r] - z[r2] <= 0.0);
mod.add(z[offset_grandparents + r] - z[r1] - z[r2] >= -1.0);
}
}
if (use_nonprojective_arc_parts)
{
int j, k;
// Define auxiliary variables (indicates a path between i and j)
IloNumVarArray psi(env, sentence->size()*sentence->size(),
0.0, 1.0, ILOFLOAT);
vector<IloExpr> vExpr(sentence->size()*sentence->size());
for (int ind = 0; ind < vExpr.size(); ind++)
vExpr[ind] = IloExpr(env);
for (int r = 0; r < num_arcs; r++)
{
DependencyPartArc *arc = static_cast<DependencyPartArc*>(
(*dependency_parts)[offset_arcs + r]);
j = arc->modifier();
if (j == 0)
continue;
for (k = 0; k < sentence->size(); k++)
{
vExpr[j + sentence->size()*k] += flow[r*sentence->size() + k];
}
}
for (k = 0; k < sentence->size(); k++)
{
// psi_0k = 1, for each k = 1,...,n
// psi_jk = sum(i) f_ijk, for each j,k = 1,...,n
mod.add(psi[0 + sentence->size()*k] == 1);
for (j = 1; j < sentence->size(); j++)
{
//mod.add(psi[j + sentence->size()*k] == vExpr[j + sentence->size()*k]);
mod.add(psi[j + sentence->size()*k] <= vExpr[j + sentence->size()*k]);
mod.add(psi[j + sentence->size()*k] >= vExpr[j + sentence->size()*k]);
}
}
for (int ind = 0; ind < vExpr.size(); ind++)
{
vExpr[ind].end();
}
vExpr.clear();
// znp_ij <= z_ij for each i,j
// znp_ij >= z_ij - psi_ik for each i,j, and k in (i,j)
// znp_ij <= -sum(k in (i,j)) psi_ik + |j-i| - 1, for each i,j
for (int r = 0; r < num_nonprojective; ++r)
{
DependencyPartNonproj *part = static_cast<DependencyPartNonproj*>(
(*dependency_parts)[offset_nonprojective + r]);
int par = part->head();
int ch = part->modifier();
int r1 = dependency_parts->FindArc(par, ch); // Typically r1 == r - r0
if (r1 < 0) // Should not happen
{
mod.add(z[offset_nonprojective + r] <= 0.0);
continue;
}
else
mod.add(z[offset_nonprojective + r] - z[r1] <= 0.0);
int i0, j0;
if (par < ch)
{
i0 = par;
j0 = ch;
}
else if (par > ch)
{
i0 = ch;
j0 = par;
}
else
continue; // If ch==par, znp_ij = z_ij = 0 necessarily
expr = IloExpr(env);
for (int k = i0+1; k < j0; k++)
{
mod.add(z[offset_nonprojective + r] - z[r1] + psi[par + sentence->size()*k] >= 0.0);
expr += psi[par + sentence->size()*k];
}
expr += z[offset_nonprojective + r];
mod.add(expr <= j0 - i0 - 1);
expr.end();
}
}
if (use_path_parts)
{
int j, k;
// Define auxiliary variables (indicates a path between i and j)
IloNumVarArray psi(env, sentence->size()*sentence->size(),
0.0, 1.0, ILOFLOAT);
vector<IloExpr> vExpr(sentence->size()*sentence->size());
for (int ind = 0; ind < vExpr.size(); ind++)
vExpr[ind] = IloExpr(env);
for (int r = 0; r < num_arcs; r++)
{
DependencyPartArc *arc = static_cast<DependencyPartArc*>(
(*dependency_parts)[offset_arcs + r]);
j = arc->modifier();
if (j == 0)
continue;
for (k = 0; k < sentence->size(); k++)
{
vExpr[j + sentence->size()*k] += flow[r*sentence->size() + k];
}
}
for (k = 0; k < sentence->size(); k++)
{
// psi_0k = 1, for each k = 1,...,n
// psi_jk = sum(i) f_ijk, for each j,k = 1,...,n
mod.add(psi[0 + sentence->size()*k] == 1);
for (j = 1; j < sentence->size(); j++)
{
mod.add(psi[j + sentence->size()*k] == vExpr[j + sentence->size()*k]);
}
}
for (int ind = 0; ind < vExpr.size(); ind++)
{
vExpr[ind].end();
}
vExpr.clear();
// zpath_ij = psi_ij for each i,j
for (int r = 0; r < num_path; ++r)
{
DependencyPartPath *part = static_cast<DependencyPartPath*>(
(*dependency_parts)[offset_path + r]);
int ancest = part->ancestor();
int descend = part->descendant();
mod.add(z[offset_path + r] == psi[ancest + sentence->size()*descend]);
}
}
if (use_head_bigram_parts)
{
// z_{prevpar,par,ch} <= z_{par,ch} for each prevpar,par,ch
// z_{prevpar,par,ch} <= z_{prevpar,ch-1} for each prevpar,par,ch
// z_{prevpar,par,ch} >= z_{par,ch} + z_{prevpar,ch-1} - 1 for each prevpar,par,ch
for (int r = 0; r < num_bigrams; ++r)
{
DependencyPartHeadBigram *part = static_cast<DependencyPartHeadBigram*>(
(*dependency_parts)[offset_bigrams + r]);
int prevpar = part->previous_head();
int par = part->head();
int ch = part->modifier();
assert(ch-1 >= 0);
int r1 = dependency_parts->FindArc(prevpar, ch-1);
int r2 = dependency_parts->FindArc(par, ch);
assert(r1 >= 0 && r2 >= 0);
mod.add(z[offset_bigrams + r] - z[r1] <= 0.0);
mod.add(z[offset_bigrams + r] - z[r2] <= 0.0);
mod.add(z[offset_bigrams + r] - z[r1] - z[r2] >= -1.0);
}
}
///////////////////////////////////////////////////////////////////
// Solve
///////////////////////////////////////////////////////////////////
double tilim = pipe_->GetDependencyOptions()->train()? 60.0 : 300.0; // Time limit: 60 seconds training, 300 sec. testing
cplex.setParam (IloCplex::TiLim, tilim); // Time limit: 60 seconds
bool hasSolution = false;
if (cplex.solve())
{
hasSolution = true;
cplex.out() << "Solution status = " << cplex.getStatus() << endl;
cplex.out() << "Solution value = " << cplex.getObjValue() << endl;
gettimeofday(&end, NULL);
double elapsed_time = diff_ms(end,start);
cout << "Elapsed time (CPLEX) = " << elapsed_time << " (" << sentence->size() << ") " << endl;
}
else
{
cout << "Could not solve the LP!" << endl;
if (cplex.getCplexStatus() == IloCplex::AbortTimeLim)
{
cout << "Time out!" << endl;
cplex.out() << "Solution status = " << cplex.getStatus() << endl;
if (!relax)
cplex.out() << "Solution best value = " << cplex.getBestObjValue() << endl;
}
if (pipe_->GetDependencyOptions()->test())
{
if (cplex.isPrimalFeasible())
hasSolution = true;
else
{
cout << "Trying to solve the LP in primal form..." << endl;
cplex.setParam(IloCplex::RootAlg, IloCplex::Primal);
if (cplex.solve())
{
hasSolution = true;
cplex.out() << "Solution status = " << cplex.getStatus() << endl;
cplex.out() << "Solution value = " << cplex.getObjValue() << endl;
}
else
{
cout << "Could not solve the LP in primal form!" << endl;
if (cplex.isPrimalFeasible())
{
hasSolution = true;
cout << "However, a feasible solution was found." << endl;
}
}
cplex.setParam(IloCplex::RootAlg, IloCplex::AutoAlg);
}
}
}
if (hasSolution)
{
IloNumArray zOpt(env,parts->size());
cplex.getValues(z, zOpt);
for (r = 0; r < parts->size(); r++) {
// Skip labeled parts.
if ((*parts)[r]->type() == DEPENDENCYPART_LABELEDARC) continue;
(*predicted_output)[r] = zOpt[r];
}
///////
for (int j = 0; j < sentence->size(); j++)
{
double sum = 0.0;
for (int i = 0; i < sentence->size(); i++)
{
r = dependency_parts->FindArc(i,j);
if (r < 0)
continue;
sum += (*predicted_output)[r];
if (relax)
{
double val = (*predicted_output)[r];
if (val*(1-val) > 0.001)
{
cout << "Fractional value!" << endl;
}
}
}
if (j == 0)
assert(NEARLY_EQ_TOL(sum, 0.0, 1e-9));
else
assert(NEARLY_EQ_TOL(sum, 1.0, 1e-9));
}
}
env.end();
}
catch (IloException& ex)
{
cout << "Error: " << ex << endl;
cerr << "Error: " << ex << endl;
}
catch (...)
{
cout << "Unspecified error" << endl;
cerr << "Unspecified error" << endl;
}
}
#endif
| lifu-tu/TE_TweeboParser | TBParser/src/parser/DependencyDecoder.cpp | C++ | gpl-3.0 | 115,505 |
/* Copyright (C) 2007-2012 Vincent Ollivier
*
* Purple Haze 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.
*
* Purple Haze 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/>.
*/
#ifndef ZOBRIST_H
#define ZOBRIST_H
#include <iostream>
#include <random>
#include "common.h"
typedef uint64_t Hash;
class Zobrist
{
private:
Hash gen_hash();
Hash pieces_positions[2][7][BOARD_SIZE];
Hash side_to_move;
Hash castle_rights[4];
Hash en_passants[BOARD_SIZE];
std::mt19937_64 generator;
public:
Zobrist();
void change_side(Hash& h) {
h ^= side_to_move;
};
void update_piece(Hash& h, Color c, PieceType t, Square s) {
h ^= pieces_positions[c][t][s];
};
void update_castle_right(Hash& h, Color c, PieceType t) {
h ^= castle_rights[2 * c + t - QUEEN];
};
void update_en_passant(Hash& h, Square s) {
h ^= en_passants[s];
};
friend std::ostream& operator<<(std::ostream& out, const Zobrist& zobrist);
};
#endif /* !ZOBRIST_H */
| vinc/purplehaze | src/zobrist.h | C | gpl-3.0 | 1,619 |
@Echo off & SetLocal EnableDelayedExpansion & Mode con:cols=100 lines=10 & Color 0B
Title Build XISO
Set "SourceDirectory=Extras Disc"
Set "OutputISOName=Xbox Softmodding Tool Extras Disc.iso"
Echo About to create an Xbox ISO.
Echo:
Echo Source Directory
Echo %SourceDirectory%
Echo:
Echo Output ISO Name.
Echo %OutputISOName%
Timeout /t 3 >NUL
Call "Build Disc Save.bat"
"Other\Tools\XDVDFS Tools\bin\windows\xdvdfs_maker.exe" "%SourceDirectory%" "%OutputISOName%"
RD /Q /S "%SourceDirectory%\softmod files\Softmod Files" | Rocky5/2016-Softmodding-Tool | Build XISO.bat | Batchfile | gpl-3.0 | 545 |
# -*- coding: utf-8 -*-
__all__ = [
"test_config_db",
"test_grid",
"test_shell",
"test_svn",
]
if __name__ == "__main__" :
import doctest
for i in __all__ :
print ("%%-%ds: %%s" % (max(map(len, __all__)) + 1)) % (
i,
doctest.testmod(__import__(i, None, None, [i, ], ), ),
)
| spikeekips/source-over-ssh | src/tests/__init__.py | Python | gpl-3.0 | 344 |
/*
* Copyright 2011 Kai Rohr
*
*
* This file is part of mIDas.
*
* mIDas 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.
*
* mIDas 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 mIDas. If not, see <http://www.gnu.org/licenses/>.
*/
package pfaeff;
import havocx42.BlockUID;
import havocx42.TranslationRecord;
import havocx42.TranslationRecordFactory;
import havocx42.World;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.logging.*;
import java.util.Map;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import region.RegionFile;
public class IDChanger {
public static Logger logger = Logger.getLogger(IDChanger.class.getName());
public static int changedPlaced = 0;
public static int changedChest = 0;
public static int changedPlayer = 0;
public static Map<BlockUID, Integer> convertedBlockCount = new HashMap<BlockUID, Integer>();
public static Map<BlockUID, Integer> convertedItemCount = new HashMap<BlockUID, Integer>();
private static boolean isValidSaveGame(File f) {
logger.log(Level.INFO, "Checking save game: " + f.getName());
ArrayList<RegionFile> rf;
try {
rf = NBTFileIO.getRegionFiles(f);
} catch (IOException e) {
logger.log(Level.WARNING, "Unable to load save file", e);
return false;
}
return ((rf != null) && (rf.size() > 0));
}
private static HashMap<BlockUID, BlockUID> readPatchFile(File f) {
// new version use a hashmap to record what blocks to transmute
// to what.
final HashMap<BlockUID, BlockUID> translations = new HashMap<BlockUID, BlockUID>();
if (!f.exists()) {
logger.log(Level.SEVERE, "No such patch file: " + f.getName());
System.exit(1);
}
try {
FileInputStream fstream = new FileInputStream(f);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
TranslationRecord tr;
while ((strLine = br.readLine()) != null) {
try {
tr = TranslationRecordFactory.createTranslationRecord(strLine);
if (tr != null) {
translations.put(tr.source, tr.target);
} else {
logger.info("Patch contains an invalid line, no big deal: " + strLine);
}
} catch (NumberFormatException e2) {
// JOptionPane.showMessageDialog(this,
// "That's not how you format translations \""+strLine+System.getProperty("line.separator")+"example:"+System.getProperty("line.separator")+"1 stone -> 3 dirt",
// "Error", JOptionPane.ERROR_MESSAGE);
logger.info("Patch contains an invalid line, no big deal" + strLine);
continue;
}
}
br.close();
in.close();
fstream.close();
} catch (Exception filewriting) {
logger.log(Level.SEVERE, "Unable to open patch file", filewriting);
System.exit(1);
}
return translations;
}
public static void main(String[] args) throws IOException {
OptionSet options = null;
OptionParser parser = new OptionParser() {
{
acceptsAll(asList("?", "help"), "Show the help");
acceptsAll(asList("p", "patch-file"), "Patch file to use")
.withRequiredArg()
.ofType(File.class);
acceptsAll(asList("i", "input-save-game"), "Save game to read as input")
.withRequiredArg()
.ofType(File.class);
acceptsAll(asList("no-convert-blocks"), "Disable block ID conversion");
acceptsAll(asList("no-convert-items"), "Disable item ID conversion");
acceptsAll(asList("no-convert-buildcraft-pipes"),"Disable BuildCraft pipe ID conversion");
acceptsAll(asList("no-convert-player-inventories"), "Disable player inventory ID conversion");
acceptsAll(asList("convert-project-table"), "Enable conversion of RedPower2 Project Table to bau5 Project Bench");
acceptsAll(asList("dump-tile-entities"), "Enable dumping tile entity NBT data for debugging purposes");
acceptsAll(asList("count-block-stats"), "Enable counting the types of blocks converted");
acceptsAll(asList("count-item-stats"), "Enable counting the types of items converted");
acceptsAll(asList("convert-charging-bench-gregtech"), "Enable conversion of IC2 Charging Bench to GregTech Charge-O-Mat");
acceptsAll(asList("warn-unconverted-block-id-after"), "Log block IDs without mappings, after vanilla maximum")
.withRequiredArg()
.ofType(Integer.class);
acceptsAll(asList("warn-unconverted-item-id-after"), "Log item IDs without mappings, after vanilla maximum")
.withRequiredArg()
.ofType(Integer.class);
}
};
try {
options = parser.parse(args);
} catch (joptsimple.OptionException ex) {
logger.log(Level.SEVERE, ex.getLocalizedMessage());
return;
}
if (!options.has("patch-file") || !options.has("input-save-game")) {
parser.printHelpOn(System.out);
System.exit(1);
}
HashMap<BlockUID, BlockUID> translations = readPatchFile((File) options.valueOf("patch-file"));
logger.log(Level.INFO, "loaded "+translations.size()+" translations");
File saveGame = (File) options.valueOf("input-save-game");
if (!isValidSaveGame(saveGame)) {
logger.log(Level.SEVERE, "Invalid save game: "+ saveGame.getName());
return;
}
// change block ids
final World world;
try {
world = new World(saveGame);
logger.log(Level.INFO, "Converting...");
world.convert(translations, options);
} catch (IOException e1) {
logger.log(Level.WARNING, "Unable to open world, are you sure you have selected a save?");
}
}
private static List<String> asList(String... params) {
return Arrays.asList(params);
}
}
| agaricusb/midas-silver | src/main/java/pfaeff/IDChanger.java | Java | gpl-3.0 | 7,330 |
#!/usr/bin/python
# MinerLite - A client side miner controller.
# This will launch cgminer with a few delay seconds and
# retrieve the local data and post it into somewhere!
#
# Author: Yanxiang Wu
# Release Under GPL 3
# Used code from cgminer python API example
import socket
import json
import sys
import subprocess
import time
import os
path = "/home/ltcminer/mining/cgminer/cgminer"
log_file = "/home/ltcminer/mining/minerlite.log"
def linesplit(socket):
buffer = socket.recv(4096)
done = False
while not done:
more = socket.recv(4096)
if not more:
done = True
else:
buffer = buffer+more
if buffer:
return buffer
def retrieve_cgminer_info(command, parameter):
"""retrieve status of devices from cgminer
"""
api_ip = '127.0.0.1'
api_port = 4028
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((api_ip,int(api_port)))
if not parameter:
s.send(json.dumps({"command":command,"parameter":parameter}))
else:
s.send(json.dumps({"command":command}))
response = linesplit(s)
response = response.replace('\x00','')
return_val = response
response = json.loads(response)
# print response
s.close()
return return_val
def run_cgminer(path):
subprocess.Popen([path, "--api-listen"])
print "Starting cgminer in 2 seconds"
time.sleep(2)
print "Running cgminer ..."
run_cgminer(path)
time.sleep(15)
with open(log_file, 'a') as logfile:
try:
logfile.write( retrieve_cgminer_info("devs", None) )
except socket.error:
pass | cecilulysess/MinerLite | main.py | Python | gpl-3.0 | 1,792 |
<?php
include './FoodBusiness.php';
include './DietBusiness.php';
include './DietPlanBusiness.php';
include './DietPersonBussiness.php';
//
//$dietBusiness = new DietBusiness();
//$temp = $dietBusiness->getDiet(1);
////var_dump($temp);
//echo (json_encode($temp));
////exit;
if (isset($_POST['option'])) {
$option = $_POST['option'];
switch ($option) {
case 1://insert a diet
// get value
$nameDiet = $_POST['txtName'];
$descriptionDiet = $_POST['txtDescription'];
// $dietDayDietPlan = $_POST['txtDay'];
// $dietHourDietPlan = $_POST['txtHour'];
$temp = $_POST['quantityFood'];
// $idFoodDietPlan = $_POST['selFood'];
$idPersonDietPerson = $_POST['idPerson'];
$dietBusiness = new DietBusiness();
$dietPlanBusiness = new DietPlanBusiness();
$dietPersonBusiness = new DietPersonBusiness();
// obtengo las id de las tablas
$idDiet = $dietBusiness->getMaxId();
$idDietPerson = $dietPersonBusiness->getMaxId();
$idDietPlan = $dietPlanBusiness->getMaxId();
$diet = new Diet($idDiet, $nameDiet, $descriptionDiet);
if ($dietBusiness->insertDiet($diet)) {
$dietPerson = new DietPerson($idDietPerson, $idPersonDietPerson, $idDiet);
$dietPersonBusiness->insertDietPerson($dietPerson); //assign a diet to person
$dietPlan = new DietPlan($idDietPlan, $idFoodDietPlan, $idDiet, $dietDayDietPlan, $dietHourDietPlan);
// $dietPlanBusiness->insertDietPlan($dietPlan); // insert food a dietplan
for ($i = 0; $i < $temp; $i++) { // insert food a dietplan
$idFoodDietPlan = $_POST['food' . $i];
$idDietPlan = $dietPlanBusiness->getMaxId();
$dietPlan = new DietPlan($idDietPlan, $idFoodDietPlan, $idDiet, $_POST['day' . $i], $_POST['hour' . $i]);
$dietPlanBusiness->insertDietPlan($dietPlan);
}
}
break;
case 2: // get all the food
$foodBusiness = new FoodBusiness();
$array = $foodBusiness->getAllFood();
$temp = "";
foreach ($array as $current) {
$temp = $temp . $current->getIdFood() . ",";
$temp = $temp . $current->getNameFood() . " " . $current->getNutritionalValueFood() . ";";
}//Fin del foreach
if (strlen($temp) > 0) {
$temp = substr($temp, 0, strlen($temp) - 1);
}
echo $temp;
break;
case 3; // get the person diet and show
$idPersonDietPerson = $_POST['idPerson'];
$dietBusiness = new DietBusiness();
$temp = $dietBusiness->getDiet($idPersonDietPerson);
// if (strlen($temp) > 0) {
// $temp = substr($temp, 0, strlen($temp) - 1);
// }
echo (json_encode($temp));
// echo $temp;
break;
case 4; // delete a diet
$idDiet = (int) $_POST['txtID'];
$dietBusiness = new DietBusiness();
echo $dietBusiness->deleteDiet($idDiet);
break;
}
} | yunenrr/Caoba | business/DietAction.php | PHP | gpl-3.0 | 3,287 |
#!/usr/bin/python
import re
import sys
import os
import getopt
import vcf
def main():
params = parseArgs()
vfh = vcf.Reader(open(params.vcf, 'r'))
#grab contig sizes
contigs = dict()
for c,s in vfh.contigs.items():
contigs[s.id] = s.length
regions = list()
this_chrom = None
start = int()
stop = int()
count = 0
for rec in vfh:
if not this_chrom:
this_chrom = rec.CHROM
start = 1
stop = 1
count = 0
#If we entered new chromosome, submit old break
elif this_chrom != rec.CHROM:
t = tuple([this_chrom, start, contigs[this_chrom]])
regions.append(t)
this_chrom = rec.CHROM
start = 1
stop = 1
count = 0
#if this SNP is parsimony-informative
if rec.is_snp and not rec.is_monomorphic:
#Check if parsimony-informative
if is_PIS(rec):
count+=1
#if this is the final PIS, submit region to list
if count == params.force:
stop = rec.POS
t = tuple([this_chrom, start, stop])
regions.append(t)
start = stop + 1
count = 0
t = tuple([this_chrom, start, contigs[this_chrom]])
regions.append(t)
print("Writing regions to out.regions...")
write_regions("out.regions", regions)
#Function to write list of regions tuples, in GATK format
def write_regions(f, r):
with open(f, 'w') as fh:
try:
for reg in r:
ol = str(reg[0]) + ":" + str(reg[1]) + "-" + str(reg[2]) + "\n"
fh.write(ol)
except IOError as e:
print("Could not read file %s: %s"%(f,e))
sys.exit(1)
except Exception as e:
print("Unexpected error reading file %s: %s"%(f,e))
sys.exit(1)
finally:
fh.close()
#Function to check pyVCF record for if parsimony informative or not
def is_PIS(r):
ref=0
alt=0
for call in r.samples:
if call.gt_type:
if call.gt_type == 0:
ref += 1
elif call.gt_type == 1:
alt += 1
elif call.gt_type == 2:
alt += 1
ref += 1
if ref >= 2 and alt >= 2:
return(True)
if ref <= 2 and alt <= 2:
return(False)
#Object to parse command-line arguments
class parseArgs():
def __init__(self):
#Define options
try:
options, remainder = getopt.getopt(sys.argv[1:], 'v:f:h', \
["vcf=" "help", "force="])
except getopt.GetoptError as err:
print(err)
self.display_help("\nExiting because getopt returned non-zero exit status.")
#Default values for params
#Input params
self.vcf=None
self.force=100000
#First pass to see if help menu was called
for o, a in options:
if o in ("-h", "-help", "--help"):
self.display_help("Exiting because help menu was called.")
#Second pass to set all args.
for opt, arg_raw in options:
arg = arg_raw.replace(" ","")
arg = arg.strip()
opt = opt.replace("-","")
#print(opt,arg)
if opt in ('v', 'vcf'):
self.vcf = arg
elif opt in ('f','force'):
self.force=int(arg)
elif opt in ('h', 'help'):
pass
else:
assert False, "Unhandled option %r"%opt
#Check manditory options are set
if not self.vcf:
self.display_help("Must provide VCF file <-v,--vcf>")
def display_help(self, message=None):
if message is not None:
print()
print (message)
print ("\nfindBreaksVCF.py\n")
print ("Contact:Tyler K. Chafin, University of Arkansas,tkchafin@uark.edu")
print ("\nUsage: ", sys.argv[0], "-v <input.vcf> -f <100000>\n")
print ("Description: Breaks chromosomes into chunks of X parsimony-informative sites, for running MDL")
print("""
Arguments:
-v,--vcf : VCF file for parsing
-f,--force : Number of PIS to force a break
-h,--help : Displays help menu
""")
print()
sys.exit()
#Call main function
if __name__ == '__main__':
main()
| tkchafin/scripts | findBreaksVCF.py | Python | gpl-3.0 | 3,606 |
from aospy import Run
am2_control = Run(
name='am2_control',
description=(
'Preindustrial control simulation.'
),
data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/'
'SM2.1U_Control-1860_lm2_aie_rerun6.YIM/pp'),
data_in_dur=5,
data_in_start_date='0001-01-01',
data_in_end_date='0080-12-31',
default_date_range=('0021-01-01', '0080-12-31'),
idealized=False
)
am2_tropics = Run(
name='am2_tropics',
description=(
'Anthropogenic sulfate aerosol forcing only in the'
' Northern Hemisphere tropics (EQ to 30N)'
),
data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/'
'SM2.1U_Control-1860_lm2_aie2_tropical_rerun6.YIM/pp'),
data_in_dur=5,
data_in_start_date='0001-01-01',
data_in_end_date='0080-12-31',
default_date_range=('0021-01-01', '0080-12-31'),
idealized=False
)
am2_extratropics = Run(
name='am2_extratropics',
description=(
'Anthropogenic sulfate aerosol forcing only in the'
' Northern Hemisphere extratropics (30N to Pole)'
),
data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/'
'SM2.1U_Control-1860_lm2_aie2_extropical_rerun6.YIM/pp'),
data_in_dur=5,
data_in_start_date='0001-01-01',
data_in_end_date='0080-12-31',
default_date_range=('0021-01-01', '0080-12-31'),
idealized=False
)
am2_tropics_and_extratropics = Run(
name='am2_tropics+extratropics',
description=(
'Anthropogenic sulfate aerosol forcing everywhere'
),
data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/'
'SM2.1U_Control-1860_lm2_aie2_rerun6.YIM/pp'),
data_in_dur=5,
data_in_start_date='0001-01-01',
data_in_end_date='0080-12-31',
default_date_range=('0021-01-01', '0080-12-31'),
idealized=False
)
# REYOI Runs - First year is 1982; we throw that out as spinup;
# start analysis in 1983.
am2_HadISST_control = Run(
name='am2_HadISST_control',
description=(
'1981-2000 HadISST climatological annual cycle of SSTs and sea '
'ice repeated annually, with PD atmospheric composition.'
),
data_in_direc=('/archive/yim/siena_201203/m45_am2p14_1990/'
'gfdl.ncrc2-intel-prod/pp'),
data_in_dur=16,
data_in_start_date='1983-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
am2_reyoi_control = Run(
name='am2_reyoi_control',
tags=['reyoi', 'cont'],
description='PI atmos and Reynolds OI climatological SSTs',
data_in_direc=('/archive/Spencer.Hill/am2/am2clim_reyoi/'
'gfdl.ncrc2-default-prod/pp'),
data_in_dur=1,
data_in_start_date='1982-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
am2_reyoi_extratropics_full = Run(
name='am2_reyoi_extratropics_full',
description=(
'Full SST anomaly pattern applied to REYOI fixed SST climatology.'),
data_in_direc=('/archive/Spencer.Clark/am2/'
'am2clim_reyoi_extratropics_full/'
'gfdl.ncrc2-default-prod/pp'),
data_in_dur=17,
data_in_start_date='1982-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
am2_reyoi_extratropics_sp = Run(
name='am2_reyoi_extratropics_sp',
description=(
'Spatial Pattern SST anomaly pattern applied to'
' REYOI fixed SST climatology.'),
data_in_direc=('/archive/Spencer.Clark/am2/'
'am2clim_reyoi_extratropics_sp/gfdl.ncrc2-default-prod/pp'),
data_in_dur=17,
data_in_start_date='1982-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
am2_reyoi_tropics_sp_SI = Run(
name='am2_reyoi_tropics_sp_SI',
description=(
'Spatial Pattern SST anomaly pattern applied to REYOI fixed SST'
' climatology.'),
data_in_direc=('/archive/Spencer.Clark/am2/'
'am2clim_reyoi_tropics_sp_SI/gfdl.ncrc2-default-prod/pp'),
data_in_dur=17,
data_in_start_date='1982-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
am2_reyoi_tropics_full = Run(
name='am2_reyoi_tropics_full',
description=(
'Full SST anomaly pattern applied to REYOI fixed SST climatology.'),
data_in_direc=('/archive/Spencer.Clark/am2/'
'am2clim_reyoi_tropics_full/gfdl.ncrc2-default-prod/pp'),
data_in_dur=17,
data_in_start_date='1982-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
am2_reyoi_extratropics_sp_SI = Run(
name='am2_reyoi_extratropics_sp_SI',
description=(
'Spatial Pattern SST anomaly pattern applied to REYOI fixed'
' SST climatology. Fixed sea-ice.'),
data_in_direc=('/archive/Spencer.Clark/am2/'
'am2clim_reyoi_extratropics_sp_SI/'
'gfdl.ncrc2-default-prod/pp'),
data_in_dur=17,
data_in_start_date='1982-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
am2_reyoi_extratropics_u = Run(
name='am2_reyoi_extratropics_u',
description=(
'Uniform SST anomaly pattern applied to REYOI fixed SST climatology.'),
data_in_direc=('/archive/Spencer.Clark/am2/'
'am2clim_reyoi_extratropics_u/gfdl.ncrc2-default-prod/pp'),
data_in_dur=17,
data_in_start_date='1982-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
am2_reyoi_tropics_u = Run(
name='am2_reyoi_tropics_u',
description=(
'Uniform SST anomaly pattern applied to REYOI fixed SST climatology.'),
data_in_direc=('/archive/Spencer.Clark/am2/'
'am2clim_reyoi_tropics_u/gfdl.ncrc2-default-prod/pp'),
data_in_dur=17,
data_in_start_date='1982-01-01',
data_in_end_date='1998-12-31',
default_date_range=('1983-01-01', '1998-12-31'),
idealized=False
)
| spencerkclark/aospy-obj-lib | aospy_user/runs/cases.py | Python | gpl-3.0 | 6,191 |
# GetExtendedList
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **int** | ID of the list |
**name** | **string** | Name of the list |
**totalBlacklisted** | **int** | Number of blacklisted contacts in the list |
**totalSubscribers** | **int** | Number of contacts in the list |
**folderId** | **int** | ID of the folder |
**createdAt** | [**\DateTime**] | Creation UTC date-time of the list (YYYY-MM-DDTHH:mm:ss.SSSZ) |
**campaignStats** | [**\SendinBlue\Client\Model\GetExtendedListCampaignStats[]**](GetExtendedListCampaignStats.md) | | [optional]
**dynamicList** | **bool** | Status telling if the list is dynamic or not (true=dynamic, false=not dynamic) | [optional]
[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)
| LoicLEMEUT/sendinblue | lib/api-v3-sdk/docs/Model/GetExtendedList.md | Markdown | gpl-3.0 | 937 |
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WolfScript API PlayerCreate</title>
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link href="../../../../../../assets/css/docs.css" rel="stylesheet" />
<link href="../../../../../../assets/css/github.css" rel="stylesheet" />
<link href="../../../../../../assets/fonts/foundation-icons.css" rel="stylesheet" />
<script src="../../../../../../assets/js/vendor/modernizr.js"></script>
</head>
<body>
<body class="antialiased hide-extras">
<div class="inner-wrap">
<nav class="top-bar docs-bar hide-for-small" data-topbar>
<ul class="title-area">
<li class="name">
<h1><a href="/web/index.html"><i class="fi-paw"></i> WolfScript.io</a></h1>
</li>
</ul>
<section class="top-bar-section">
<ul class="right">
<li class="divider"></li>
<li class='divider'></li>
<li><a href='../../../../../../index.html' class=''>Docs</a></li>
<li class='divider'></li>
<li><a href='../../../../../../wolfbuk/io/wolfscript/0.html' class=''>WolfBuk API</a></li>
<li class='divider'></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/0.html' class=''>WolfCanary API</a></li>
<li class='divider'></li>
<li><a href='../../../../../../wolfnode/globals.html' class=''>WolfNode</a></li>
<li class="divider"></li>
<li><a href='http://github.com/miningwolf/wolfscript ' class=''> <i class="fi-social-github"></i> Github</a></li>
<li class="divider"></li>
<li class="has-form">
<a href="../../../../../../GettingStarted.html " class="small button">Getting Started</a>
</li>
</ul>
</section>
</nav>
<ul class="breadcrumbs">
<li><a href='../../../../../../index.html'>Docs </a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/0.html'>wolfcanary</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/0.html'>io.wolfscript</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/0.html'>commandsys</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/0.html'>commands</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/0.html'>playermod</a></li>
<li class='current'><a href='#'>PlayerCreate</a></li>
</ul>
<div class="row">
<div class="large-3 medium-4 columns">
<div class="hide-for-small">
<div class="sidebar">
<nav>
<ul class="side-nav accordion" data-accordion>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/0.html' class=''>wolfcanary API</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/api/0.html' class=''>api</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/backbone/0.html' class=''>backbone</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/bansystem/0.html' class=''>bansystem</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/channels/0.html' class=''>channels</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/chat/0.html' class=''>chat</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/0.html' class=''>commandsys</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/groupmod/0.html' class=''>commandsys.commands.groupmod</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/player/0.html' class=''>commandsys.commands.player</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/0.html' class=''>commandsys.commands.playermod</a></li>
<li class='active'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerCreate.html'>PlayerCreate</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerGroupAdd.html'>PlayerGroupAdd</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerGroupCheck.html'>PlayerGroupCheck</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerGroupList.html'>PlayerGroupList</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerGroupRemove.html'>PlayerGroupRemove</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerGroupSet.html'>PlayerGroupSet</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerPermissionAdd.html'>PlayerPermissionAdd</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerPermissionCheck.html'>PlayerPermissionCheck</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerPermissionList.html'>PlayerPermissionList</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerPermissionRemove.html'>PlayerPermissionRemove</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerPrefix.html'>PlayerPrefix</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerRemove.html'>PlayerRemove</a></li>
<li><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayermodBase.html'>PlayermodBase</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/system/0.html' class=''>commandsys.commands.system</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/system/bans/0.html' class=''>commandsys.commands.system.bans</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/system/informational/0.html' class=''>commandsys.commands.system.informational</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/system/kits/0.html' class=''>commandsys.commands.system.kits</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/system/operator/0.html' class=''>commandsys.commands.system.operator</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/system/reservelist/0.html' class=''>commandsys.commands.system.reservelist</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/system/whitelist/0.html' class=''>commandsys.commands.system.whitelist</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/vanilla/0.html' class=''>commandsys.commands.vanilla</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/warp/0.html' class=''>commandsys.commands.warp</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/commandsys/commands/world/0.html' class=''>commandsys.commands.world</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/config/0.html' class=''>config</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/converter/0.html' class=''>converter</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/database/0.html' class=''>database</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/event/0.html' class=''>event</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/exceptions/0.html' class=''>exceptions</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/help/0.html' class=''>help</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/kit/0.html' class=''>kit</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/logger/0.html' class=''>logger</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/metrics/0.html' class=''>metrics</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/motd/0.html' class=''>motd</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/permissionsystem/0.html' class=''>permissionsystem</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/plugin/0.html' class=''>plugin</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/serialize/0.html' class=''>serialize</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/tasks/0.html' class=''>tasks</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/user/0.html' class=''>user</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/util/0.html' class=''>util</a></li>
<li class='divider'></li>
<li class='heading'><a href='../../../../../../wolfcanary/io/wolfscript/warp/0.html' class=''>warp</a></li>
<li class='divider'></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="large-9 medium-8 columns">
<section class="doc-content">
<h2 id="playercreate-__class__">PlayerCreate <strong>class</strong></h2>
<blockquote>
<p>io.wolfscript.commandsys.commands.playermod.PlayerCreate
Extends <a href="PlayermodBase.html"><code>PlayermodBase</code></a></p>
</blockquote>
<hr>
<h3 id="class-overview">Class Overview</h3>
<p>Command to add a player (for permissions, groups, etc.) to the database</p>
<table>
<thead>
<tr>
<th>Method</th>
<th style="text-align:left">Type </th>
</tr>
</thead>
<tbody>
<tr>
<td> function <strong>execute</strong>(caller) <br> <em>execute method</em></td>
<td style="text-align:left"><code>void</code></td>
</tr>
<tr>
<td></td>
<td style="text-align:left"></td>
</tr>
<tr>
<td><strong>Inherited items from <a href="PlayermodBase.html"><code>PlayermodBase</code></a></strong></td>
<td style="text-align:left"></td>
</tr>
<tr>
<td> function <strong>execute</strong>(caller) <br> <em>execute method</em></td>
<td style="text-align:left"><code>void</code></td>
</tr>
</tbody>
</table>
<hr>
<h3 id="public-methods-for-playercreate-playercreate-md-">Public Methods for <a href="PlayerCreate.html"><code>PlayerCreate</code></a></h3>
<h5 id="-a-id-execute-a-public-function-__execute__-caller-"><a id='execute'></a>public function <strong>execute</strong>(caller)</h5>
<p><em>execute method</em></p>
<table>
<thead>
<tr>
<th>Argument</th>
<th>Type</th>
<th>Description </th>
</tr>
</thead>
<tbody>
<tr>
<td>caller</td>
<td><a href="../../../chat/MessageReceiver.html"><code>MessageReceiver</code></a></td>
<td>caller argument</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Returns</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>void</code></td>
<td></td>
</tr>
</tbody>
</table>
<hr>
<h3 id="public-methods-for-playermodbase-playermodbase-md-">Public Methods for <a href="PlayermodBase.html"><code>PlayermodBase</code></a></h3>
<h5 id="-a-id-execute-a-public-function-__execute__-caller-"><a id='execute'></a>public function <strong>execute</strong>(caller)</h5>
<p><em>execute method</em></p>
<table>
<thead>
<tr>
<th>Argument</th>
<th>Type</th>
<th>Description </th>
</tr>
</thead>
<tbody>
<tr>
<td>caller</td>
<td><a href="../../../chat/MessageReceiver.html"><code>MessageReceiver</code></a></td>
<td>caller argument</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Returns</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>void</code></td>
<td></td>
</tr>
</tbody>
</table>
<hr>
<hr>
<h5 id="this-file-was-system-generated-using-custom-scripts-copyright-c-2015-mining-wolf-">This file was system generated using custom scripts copyright (c) 2015 Mining Wolf.</h5>
</section>
</div>
</div>
</div>
<script src="../../../../../../assets/js/vendor/jquery.js"></script>
<script src="../../../../../../assets/js/vendor/fastclick.js"></script>
<script src="../../../../../../assets/js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html> | miningwolf/docs | html/wolfcanary/io/wolfscript/commandsys/commands/playermod/PlayerCreate.html | HTML | gpl-3.0 | 13,378 |
package org.reflaction.ii;
import java.lang.reflect.*;
interface Person {
void walk();
void sayHello(String name);
}
class MyInvokationHandler implements InvocationHandler {
/*
proxy:代表动态代理对象
method:代表正在执行的方法
args:代表调用目标方法时传入的实参。
*/
public Object invoke(Object proxy, Method method, Object[] args) {
System.out.println("----正在执行的方法:" + method);
if (args != null) {
System.out.println("下面是执行该方法时传入的实参为:");
for (Object val : args) {
System.out.println(val);
}
} else {
System.out.println("调用该方法没有实参!");
}
return null;
}
}
public class ProxyTest {
public static void main(String[] args)
throws Exception {
// 创建一个InvocationHandler对象
InvocationHandler handler = new MyInvokationHandler();
// 使用指定的InvocationHandler来生成一个动态代理对象
Person p = (Person) Proxy.newProxyInstance(Person.class.getClassLoader()
, new Class[]{Person.class}, handler);
// 调用动态代理对象的walk()和sayHello()方法
p.walk();
p.sayHello("xxx");
}
}
| hannahwangww/mujava | ii/ProxyTest.java | Java | gpl-3.0 | 1,383 |
//==================================================================================
//
// L2SOLVE.HPP
//
//==================================================================================
#ifndef AGILE_IRGN_L2SOLVE_HPP
#define AGILE_IRGN_L2SOLVE_HPP
#include "agile/calc/irgn.hpp"
namespace agile
{
using agile::GPUMatrix;
using agile::GPUVector;
template <typename TType, typename TType2>
class L2Solve : public IRGN<TType, TType2>
{
public:
//! \brief Default constructor.
//!
//! The default constructor creates an empty L2Solve Class.
L2Solve()
: IRGN<TType,TType2>()
{
}
//! \brief Constructor.
//!
//! The Constructor creates an L2Solve.
L2Solve(GPUMatrix<TType>* coil, unsigned int num_coils, IRGN_Params param)
: IRGN<TType,TType2>(coil, num_coils, param)
{
Init();
}
//! \brief Constructor.
//!
//! The Constructor creates an initialized L2Solve.
L2Solve(GPUMatrix<TType>* coil, unsigned int num_coils)
: IRGN<TType,TType2>(coil, num_coils)
{
Init();
}
//! \brief Destructor.
virtual ~L2Solve()
{
delete[] cb_mat_;
cb_mat_ = 0;
delete[] Mc_mat_;
Mc_mat_ = 0;
delete[] eta4_mat_;
eta4_mat_ = 0;
delete[] dc_old_mat_;
dc_old_mat_ = 0;
}
void Solve(const GPUMatrix<TType>* u, const GPUMatrix<TType>* c,
const GPUMatrix<TType>* rhs, const GPUMatrix<TType>* u0,
unsigned maxits, typename TType::value_type alpha, typename TType::value_type beta,
GPUMatrix<TType>* du, GPUMatrix<TType>* dc);
private:
void Init();
GPUMatrix<TType> ub_mat_;
GPUMatrix<TType> Mu_mat_;
GPUMatrix<TType> eta3_mat_;
GPUMatrix<TType> du_old_mat_;
GPUMatrix<TType> safe_;
GPUMatrix<TType>* cb_mat_;
GPUMatrix<TType>* Mc_mat_;
GPUMatrix<TType>* eta4_mat_;
GPUMatrix<TType>* dc_old_mat_;
typename agile::to_real_type<TType>::type norm_;
typename agile::to_real_type<TType>::type one_;
typename agile::to_real_type<TType>::type two_;
};
}
#endif //AGILE_IRGN_L2SOLVE_HPP
| IMTtugraz/AGILE | include/agile/calc/l2solve.hpp | C++ | gpl-3.0 | 2,342 |
#!/bin/bash
# --------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ---------------------------------------------------------------------
#**********************
# functions
#**********************
initializeVariables()
{
MAKE_TAG=true
CREATE_DIENA_DISTRIBUTION_ZIP=false
STANDARD_QT_USED=false
PRODUCT_PATH="build/linux/release/product"
QT_PATH="/usr/local/Trolltech/Qt-4.7.0"
PLUGINS_PATH="$QT_PATH/plugins"
GUI_TRANSLATIONS_DIRECTORY_PATH="../Qt-sankore3.1/translations"
QT_LIBRARY_DEST_PATH="$PRODUCT_PATH/qtlib"
QT_LIBRARY_SOURCE_PATH="$QT_PATH/lib"
ARCHITECTURE=`uname -m`
if [ "$ARCHITECTURE" == "x86_64" ]; then
ARCHITECTURE="amd64"
fi
if [ "$ARCHITECTURE" == "i686" ]; then
ARCHITECTURE="i386"
fi
NOTIFY_CMD=`which notify-send`
QMAKE_PATH="$QT_PATH/bin/qmake"
LRELEASES="$QT_PATH/bin/lrelease"
ZIP_PATH=`which zip`
}
notifyError(){
if [ -e "$NOTIFY_CMD" ]; then
$NOTIFY_CMD -t 0 -i "/usr/share/icons/oxygen/64x64/status/dialog-error.png" "$1"
else
printf "\033[31merror:\033[0m $1\n"
fi
exit 1
}
notifyProgress(){
if [ -e "$NOTIFY_CMD" ]; then
$NOTIFY_CMD "$1" "$2"
else
printf "\033[32m--> Achieved task:\033[0m $1:\n\t$2\n"
fi
}
alertIfPreviousVersionInstalled(){
APT_CACHE=`which apt-cache`
if [ ! -e "$APT_CACHE" ]; then
notifyError "apt-cache command not found"
else
SEARCH_RESULT=`$APT_CACHE search myLiveNotes`
if [ `echo $SEARCH_RESULT | grep -c myLiveNotes` -ge 1 ]; then
notifyError "Found a previous version of myLiveNotes. Remove it to avoid to put it as dependency"
fi
fi
}
checkDir(){
if [ ! -d "$1" ]; then
notifyError "Directory not found : $1"
fi
}
checkExecutable(){
if [ ! -e "$1" ]; then
notifyError "$1 command not found"
fi
}
copyQtLibrary(){
if ls "$QT_LIBRARY_SOURCE_PATH/$1.so" &> /dev/null; then
cp $QT_LIBRARY_SOURCE_PATH/$1.so.? "$QT_LIBRARY_DEST_PATH/"
cp $QT_LIBRARY_SOURCE_PATH/$1.so.?.?.? "$QT_LIBRARY_DEST_PATH/"
else
notifyError "$1 library not found in path: $QT_LIBRARY_SOURCE_PATH"
fi
}
buildWithStandardQt(){
STANDARD_QT=`which qmake-qt4`
if [ $? == "0" ]; then
QT_VERSION=`$STANDARD_QT --version | grep -i "Using Qt version" | sed -e "s/Using Qt version \(.*\) in.*/\1/"`
if [ `echo $QT_VERSION | sed -e "s/\.//g"` -gt 480 ]; then
notifyProgress "Standard QT" "A recent enough qmake has been found. Using this one instead of custom one"
STANDARD_QT_USED=true
QMAKE_PATH=$STANDARD_QT
LRELEASES=`which lrelease`
if [ "`arch`" == "i686" ]; then
QT_PATH="/usr/lib/i386-linux-gnu"
else
QT_PATH="/usr/lib/`arch`-linux-gnu"
fi
PLUGINS_PATH="$QT_PATH/qt4/plugins"
fi
fi
}
#**********************
# script
#**********************
initializeVariables
buildWithStandardQt
for var in "$@"
do
if [ $var == "notag" ]; then
MAKE_TAG=false;
fi
if [ $var == "diena" ]; then
CREATE_DIENA_DISTRIBUTION_ZIP=true;
fi
done
alertIfPreviousVersionInstalled
#check of directories and executables
checkDir $QT_PATH
checkDir $PLUGINS_PATH
checkDir $GUI_TRANSLATIONS_DIRECTORY_PATH
checkExecutable $QMAKE_PATH
checkExecutable $LRELEASES
checkExecutable $ZIP_PATH
# cleaning the build directory
rm -rf "build/linux/release"
rm -rf install
notifyProgress "QT" "Internalization"
$LRELEASES Sankore_3.1.pro
cd $GUI_TRANSLATIONS_DIRECTORY_PATH
$LRELEASES translations.pro
cd -
notifyProgress "myLiveNotes" "Building myLiveNotes"
if [ "$ARCHITECTURE" == "amd64" ]; then
$QMAKE_PATH Sankore_3.1.pro -spec linux-g++-64
else
$QMAKE_PATH Sankore_3.1.pro -spec linux-g++
fi
make -j 4 release-install
if [ ! -e "$PRODUCT_PATH/myLiveNotes" ]; then
notifyError "myLiveNotes build failed"
fi
notifyProgress "Git Hub" "Make a tag of the delivered version"
VERSION=`cat build/linux/release/version`
if [ ! -f build/linux/release/version ]; then
notifyError "version not found"
else
LAST_COMMITED_VERSION="`git describe $(git rev-list --tags --max-count=1)`"
if [ "v$VERSION" != "$LAST_COMMITED_VERSION" ]; then
if [ $MAKE_TAG == true ]; then
git tag -a "v${VERSION}" -m "Generating setup for v$VERSION"
git push origin --tags
fi
fi
fi
cp resources/linux/run.sh $PRODUCT_PATH
chmod a+x $PRODUCT_PATH/run.sh
cp -R resources/linux/qtlinux/* $PRODUCT_PATH/
notifyProgress "QT" "Coping plugins and library ..."
cp -R $PLUGINS_PATH $PRODUCT_PATH/
# copying customization
cp -R resources/customizations $PRODUCT_PATH/
# copying startup hints
cp -R resources/startupHints $PRODUCT_PATH/
if [ $STANDARD_QT_USED == false ]; then
#copying custom qt library
mkdir -p $QT_LIBRARY_DEST_PATH
copyQtLibrary libQtDBus
copyQtLibrary libQtScript
copyQtLibrary libQtSvg
copyQtLibrary libQtXmlPatterns
copyQtLibrary libQtNetwork
copyQtLibrary libQtXml
copyQtLibrary libQtGui
copyQtLibrary libQtCore
copyQtLibrary libphonon
copyQtLibrary libQtWebKit
fi
notifyProgress "QT" "Internalization"
if [ ! -e $PRODUCT_PATH/i18n ]; then
mkdir $PRODUCT_PATH/i18n
fi
#copying qt gui translation
cp $GUI_TRANSLATIONS_DIRECTORY_PATH/qt_??.qm $PRODUCT_PATH/i18n/
rm -rf install/linux
mkdir -p install/linux
#Removing .svn directories ...
cd $PRODUCT_PATH
find . -name .svn -exec rm -rf {} \; 2> /dev/null
cd -
notifyProgress "Building myLiveNotes" "Finished to build Sankore building the package"
BASE_WORKING_DIR="packageBuildDir"
#creating package directory
mkdir $BASE_WORKING_DIR
mkdir "$BASE_WORKING_DIR/DEBIAN"
mkdir -p "$BASE_WORKING_DIR/usr/share/applications"
mkdir -p "$BASE_WORKING_DIR/usr/local"
cat > "$BASE_WORKING_DIR/DEBIAN/prerm" << EOF
#!/bin/bash
# --------------------------------------------------------------------
# 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/>.
# ---------------------------------------------------------------------
xdg-desktop-menu uninstall /usr/share/applications/myLiveNotes.desktop
exit 0
#DEBHELPER#
EOF
cat > "$BASE_WORKING_DIR/DEBIAN/postint" << EOF
#!/bin/bash
# --------------------------------------------------------------------
# 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/>.
# ---------------------------------------------------------------------
xdg-desktop-menu install --novendor /usr/share/applications/myLiveNotes.desktop
exit 0
#DEBHELPER#
EOF
SANKORE_DIRECTORY_NAME="myLiveNotes-$VERSION"
SANKORE_PACKAGE_DIRECTORY="$BASE_WORKING_DIR/usr/local/$SANKORE_DIRECTORY_NAME"
#move sankore build directory to packages directory
cp -R $PRODUCT_PATH $SANKORE_PACKAGE_DIRECTORY
cat > $BASE_WORKING_DIR/usr/local/$SANKORE_DIRECTORY_NAME/run.sh << EOF
#!/bin/bash
# --------------------------------------------------------------------
# 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/>.
# ---------------------------------------------------------------------
env LD_LIBRARY_PATH=/usr/local/$SANKORE_DIRECTORY_NAME/qtlib:$LD_LIBRARY_PATH /usr/local/$SANKORE_DIRECTORY_NAME/myLiveNotes
EOF
CHANGE_LOG_FILE="$BASE_WORKING_DIR/DEBIAN/changelog-sankore-$VERSION.txt"
CONTROL_FILE="$BASE_WORKING_DIR/DEBIAN/control"
CHANGE_LOG_TEXT="changelog.txt"
echo "myLiveNotes ($VERSION) $ARCHITECTURE; urgency=low" > "$CHANGE_LOG_FILE"
echo >> "$CHANGE_LOG_FILE"
cat $CHANGE_LOG_TEXT >> "$CHANGE_LOG_FILE"
echo >> "$CHANGE_LOG_FILE"
echo "-- Claudio Valerio <claudio@myLiveNotes.org> `date`" >> "$CHANGE_LOG_FILE"
echo "Package: myLiveNotes" > "$CONTROL_FILE"
echo "Version: $VERSION" >> "$CONTROL_FILE"
echo "Section: education" >> "$CONTROL_FILE"
echo "Priority: optional" >> "$CONTROL_FILE"
echo "Architecture: $ARCHITECTURE" >> "$CONTROL_FILE"
echo "Essential: no" >> "$CONTROL_FILE"
echo "Installed-Size: `du -s $SANKORE_PACKAGE_DIRECTORY | awk '{ print $1 }'`" >> "$CONTROL_FILE"
echo "Maintainer: myLiveNotes Developers team <dev@myLiveNotes.com>" >> "$CONTROL_FILE"
echo "Homepage: http://dev.myLiveNotes.org" >> "$CONTROL_FILE"
echo -n "Depends: " >> "$CONTROL_FILE"
unset tab
declare -a tab
let count=0
for l in `objdump -p $SANKORE_PACKAGE_DIRECTORY/myLiveNotes | grep NEEDED | awk '{ print $2 }'`; do
for lib in `dpkg -S $l | awk -F":" '{ print $1 }'`; do
#echo $lib
presence=`echo ${tab[*]} | grep -c "$lib"`;
if [ "$presence" == "0" ]; then
tab[$count]=$lib;
((count++));
fi;
done;
done;
for ((i=0;i<${#tab[@]};i++)); do
if [ $i -ne "0" ]; then
echo -n ", " >> "$CONTROL_FILE"
fi
echo -n "${tab[$i]} (>= "`dpkg -p ${tab[$i]} | grep "Version: " | awk '{ print $2 }'`") " >> "$CONTROL_FILE"
done
echo "" >> "$CONTROL_FILE"
echo "Description: This a interactive white board that uses a free standard format." >> "$CONTROL_FILE"
find $BASE_WORKING_DIR/usr/ -exec md5sum {} > $BASE_WORKING_DIR/DEBIAN/md5sums 2>/dev/null \;
SANKORE_SHORTCUT="$BASE_WORKING_DIR/usr/share/applications/myLiveNotes.desktop"
echo "[Desktop Entry]" > $SANKORE_SHORTCUT
echo "Version=$VERSION" >> $SANKORE_SHORTCUT
echo "Encoding=UTF-8" >> $SANKORE_SHORTCUT
echo "Name=myLiveNotes ($VERSION)" >> $SANKORE_SHORTCUT
echo "GenericName=myLiveNotes" >> $SANKORE_SHORTCUT
echo "Comment=Logiciel de création de présentations pour tableau numérique interactif (TNI)" >> $SANKORE_SHORTCUT
echo "Exec=/usr/local/$SANKORE_DIRECTORY_NAME/run.sh" >> $SANKORE_SHORTCUT
echo "Icon=/usr/local/$SANKORE_DIRECTORY_NAME/sankore.png" >> $SANKORE_SHORTCUT
echo "StartupNotify=true" >> $SANKORE_SHORTCUT
echo "Terminal=false" >> $SANKORE_SHORTCUT
echo "Type=Application" >> $SANKORE_SHORTCUT
echo "Categories=Education" >> $SANKORE_SHORTCUT
echo "Name[fr_FR]=myLiveNotes ($VERSION)" >> $SANKORE_SHORTCUT
cp "resources/images/uniboard.png" "$SANKORE_PACKAGE_DIRECTORY/sankore.png"
chmod 755 "$BASE_WORKING_DIR/DEBIAN"
chmod 755 "$BASE_WORKING_DIR/DEBIAN/prerm"
chmod 755 "$BASE_WORKING_DIR/DEBIAN/postint"
mkdir -p "install/linux"
DEBIAN_PACKAGE_NAME="myLiveNotes_${VERSION}_$ARCHITECTURE.deb"
chown -R root:root $BASE_WORKING_DIR
dpkg -b "$BASE_WORKING_DIR" "install/linux/$DEBIAN_PACKAGE_NAME"
notifyProgress "myLiveNotes" "Package built"
#clean up mess
rm -rf $BASE_WORKING_DIR
if [ $CREATE_DIENA_DISTRIBUTION_ZIP == true ]; then
ZIP_NAME="myLiveNotes_`lsb_release -is`_`lsb_release -rs`_${VERSION}_${ARCHITECTURE}.zip"
cd install/linux
$ZIP_PATH -1 --junk-paths ${ZIP_NAME} ${DEBIAN_PACKAGE_NAME} ../../ReleaseNotes.pdf ../../JournalDesModifications.pdf ../../LICENSE.txt
cd -
notifyProgress "myLiveNotes" "Build Diena zip file for distribution"
fi
| myLiveNotes/myLiveNotes | buildDebianPackage.sh | Shell | gpl-3.0 | 13,092 |
#ifndef Func_meanPositive_H
#define Func_meanPositive_H
#include "RealPos.h"
#include "RlTypedFunction.h"
#include <string>
namespace RevLanguage {
/**
* The RevLanguage wrapper of the arithmetic meanPositive function.
*
* The RevLanguage wrapper of the meanPositive function connects
* the variables/parameters of the function and creates the internal MeanFunction object.
*
* @copybrief RevBayesCore::MeanFunction
* @see RevBayesCore::MeanFunction for the internal object
*/
class Func_meanPositive : public TypedFunction<RealPos> {
public:
Func_meanPositive( void );
// Basic utility functions
Func_meanPositive* clone(void) const; //!< Clone the object
static const std::string& getClassType(void); //!< Get Rev type
static const TypeSpec& getClassTypeSpec(void); //!< Get class type spec
std::string getFunctionName(void) const; //!< Get the primary name of the function in Rev
const TypeSpec& getTypeSpec(void) const; //!< Get the type spec of the instance
// Function functions you have to override
RevBayesCore::TypedFunction<double>* createFunction(void) const; //!< Create internal function object
const ArgumentRules& getArgumentRules(void) const; //!< Get argument rules
};
}
#endif
| revbayes/revbayes | src/revlanguage/functions/math/Func_meanPositive.h | C | gpl-3.0 | 1,808 |
/***************************************************************************
begin : Thu Apr 24 15:54:58 CEST 2003
copyright : (C) 2003 by Giuseppe Lipari
email : lipari@sssup.it
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <deque>
#include <sstream>
#include <entity.hpp>
#include <simul.hpp>
namespace MetaSim {
using namespace std;
Simulation *Simulation::instance_ = 0;
class NoMoreEventsInQueue {};
Simulation::Simulation() : dbg(), numRuns(0),
actRuns(0),
globTime (0),
end (false)
{
}
Simulation& Simulation::getInstance()
{
if (instance_ == 0) instance_ = new Simulation();
return *instance_;
}
const Tick Simulation::getTime()
{
return globTime;
}
void Simulation::setTime(Tick t)
{
globTime = t;
}
// this function performs one single simulation step
// It returns the tick after the simulation step has been completed
const Tick Simulation::sim_step()
{
Event *temp;
Tick mytime;
DBGENTER(_SIMUL_DBG_LEV);
temp = Event::getFirst(); // takes the first event in the queue ...
if (temp == NULL) throw NoMoreEventsInQueue();
temp->drop(); // ... and extract it!
mytime = temp->getTime(); // stores the current time
DBGPRINT_3("Executing event action at time [", mytime, "]: ");
#ifdef __DEBUG__
temp->print();
print();
#endif
setTime(mytime);
temp->action(); // do what it is supposed to do...
if (temp->isDisposable()) // if it has to be deleted...
delete temp; // delete it!
return mytime;
}
// this event returns the time of the first event in the queue
// (i.e. the next event to be processed) or throws and exception
// if there is no more events in the queue
const Tick Simulation::getNextEventTime()
{
Event *temp = Event::getFirst();
if (temp == NULL) throw NoMoreEventsInQueue();
else return Event::getFirst()->getTime();
}
// this function will run until a specified time,
// without cleaning any variable.
// it can be used for debugging reasons.
// it returns the final tick
// it stops before executing the first event after stop
const Tick Simulation::run_to(const Tick &stop)
{
try {
while (getNextEventTime() <= stop) {
globTime = sim_step();
}
} catch (NoMoreEventsInQueue &e) {
cerr << "No more events in queue: simulation time = "
<< globTime << endl;
}
if (globTime < stop) globTime = stop;
return globTime;
}
void Simulation::initRuns(int nRuns)
{
BaseStat::init(nRuns);
globTime = 0;
end = false;
}
void Simulation::initSingleRun()
{
globTime = 0;
// Run Initialization:
// Before each run, call the newRun() of every entity
// and setup statistics
Entity::callNewRun();
BaseStat::newRun();
}
void Simulation::endSingleRun()
{
Entity::callEndRun();
BaseStat::endRun();
clearEventQueue();
}
// Main function:
// This is the simulation engine
void Simulation::run(Tick endTick, int nRuns)
{
DBGENTER(_SIMUL_DBG_LEV);
bool initializeRuns = true;
bool terminateSim = true;
if (nRuns < -1) {
cout << "Initialize stats" << endl;
initializeRuns = true;
terminateSim = false;
numRuns = 1;
nRuns = -nRuns;
}
else if (nRuns == -1) {
cout << "Will not initialize stats" << endl;
initializeRuns = false;
terminateSim = false;
numRuns = 1;
}
else if (nRuns == 0) {
cout << "Last Sim in the batch" << endl;
initializeRuns = false;
terminateSim = true;
numRuns = 1;
}
else if (nRuns == 1) {
cout << "One single run" << endl;
initializeRuns = true;
terminateSim = true;
numRuns = 1;
}
else numRuns = nRuns;
if (numRuns == 2) {
cout << "Warning: Simulation cannot be "
"initialized with 2 runs" << endl;
cout << " Executing 3 runs!" << endl;
numRuns = 3;
}
if (initializeRuns) initRuns(numRuns);
// Ok, now starts the main cycle of the simulation.
// remember that actRuns is the actual run number
// while numRuns is the maximum number of runs.
actRuns = 0;
while (actRuns < numRuns) {
cout << "\n Run #" << actRuns << endl;
initSingleRun();
// MAIN CYCLE!!
try {
while (globTime < endTick) {
globTime = sim_step();
}
} catch (NoMoreEventsInQueue &e) {
cerr << "No more events in queue: simulation time ="
<< globTime << endl;
}
endSingleRun();
actRuns++; // next run....
}
end = true;
if (terminateSim) endSim(); // the simulation is over!!
}
void Simulation::clearEventQueue()
{
Event *temp;
while ((temp = Event::getFirst()) != NULL) {
temp->drop();
if (temp->isDisposable()) // if it has to be deleted...
delete temp;
}
globTime = 0;
}
// only for debug
void Simulation::print()
{
DBGPRINT_3("Actual time = [",globTime,"]");
DBGPRINT("---------- Begin Event Queue ----------");
Event::printQueue();
DBGPRINT("---------- End Event Queue ------------");
}
// wrappers for debug entry/exit
void Simulation::dbgEnter(string lev, string header)
{
stringstream ss;
ss << "t = [" << globTime << "] --> " + header;
//string h = "t = [" + string(globTime) + "] --> " + header;
//dbg.enter(lev, h);
dbg.enter(lev, ss.str());
}
void Simulation::dbgExit()
{
dbg.exit();
}
void Simulation::endSim()
{
// Collect statistics
BaseStat::endSim();
}
}
extern "C" {
void libmetasim_is_present() {
return;
}
}
| balsini/RTSIM | METASIM/src/simul.cpp | C++ | gpl-3.0 | 7,324 |
/*
* Created on 9 Dec 2015 ( Time 11:08:58 )
* Generated by Telosys Tools Generator ( version 2.1.1 )
*/
package com.abm.mainet.common.master.mapper;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.stereotype.Component;
import com.abm.mainet.common.domain.LocationMasEntity;
import com.abm.mainet.common.domain.Organisation;
import com.abm.mainet.common.master.dto.DepartmentDTO;
import com.abm.mainet.common.utility.AbstractServiceMapper;
/**
* Mapping between entity beans and display beans.
*/
@Component
public class DepartmentServiceMapper extends AbstractServiceMapper {
/**
* ModelMapper : bean to bean mapping library.
*/
private ModelMapper modelMapper;
/**
* Constructor.
*/
public DepartmentServiceMapper() {
modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
}
/**
* Mapping from 'DepartmentEntity' to 'Department'
* @param departmentEntity
*/
public DepartmentDTO mapDepartmentEntityToDepartment(LocationMasEntity departmentEntity) {
if(departmentEntity == null) {
return null;
}
//--- Generic mapping
DepartmentDTO department = map(departmentEntity, DepartmentDTO.class);
//--- Link mapping ( link to TbOrganisation )
if(departmentEntity.getOrganisation() != null) {
department.setOrgid(departmentEntity.getOrganisation().getOrgid());
}
return department;
}
/**
* Mapping from 'Department' to 'DepartmentEntity'
* @param department
* @param departmentEntity
*/
public void mapDepartmentToDepartmentEntity(DepartmentDTO department, LocationMasEntity departmentEntity) {
if(department == null) {
return;
}
//--- Generic mapping
map(department, departmentEntity);
//--- Link mapping ( link : department )
if( hasLinkToTbOrganisation(department) ) {
Organisation organisation=new Organisation();
organisation.setOrgid(department.getOrgid());
departmentEntity.setOrganisation(organisation);
} else {
departmentEntity.setOrganisation(null);
}
}
/**
* Verify that TbOrganisation id is valid.
* @param TbOrganisation TbOrganisation
* @return boolean
*/
private boolean hasLinkToTbOrganisation(DepartmentDTO department) {
if(department.getOrgid() != null) {
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected ModelMapper getModelMapper() {
return modelMapper;
}
protected void setModelMapper(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
}
} | abmindiarepomanager/ABMOpenMainet | Mainet1.0/MainetServiceParent/MainetServiceCommon/src/main/java/com/abm/mainet/common/master/mapper/DepartmentServiceMapper.java | Java | gpl-3.0 | 2,563 |
require 'octokit'
require 'git'
require 'net/http'
require 'uri'
module HS
module Command extend self
include HS::CommandHelpers
def generate_action_proc(command)
require "hs/commands/#{command.name}"
Proc.new do |global_opts, opts, args|
init(global_opts, opts, args)
send(command.name)
end
end
def init(global_opts, opts, args)
@global_opts = global_opts
@opts = opts
@args = args
@hs = HS::CodeReviewClient.new(HS::Authentication.api_secret)
if File.exists?(File.expand_path(File.join("~", ".netrc")))
::Octokit.netrc = true
end
@gh = ::Octokit.new
end
def require_message(initial_value='')
@opts[:message] ||= prompt_message(initial_value)
end
def prompt_message(initial_value)
input = editor_input(initial_value)
.split("\n").reject { |l| l.start_with? "#" }.join("\n")
if input.empty?
$stderr.puts "Empty message. Aborting."
exit(1)
else
input
end
end
def github_url_data(url)
uri = URI(url)
if uri.host =~ /github/
_, username, repo = uri.path.split('/')
{:url => uri.to_s, :username => username, :repo => repo}
else
# XXX: This should raise an exception instead, methinks
$stderr.puts "Remotes must be github.com"
exit(1)
end
end
def remote_data(git, remote)
github_url_data(git.remote(remote).url.chomp('.git'))
end
end
class CommandError < StandardError; end
end
| recursecenter/hs-cli | lib/hs/command.rb | Ruby | gpl-3.0 | 1,558 |
Partial Class FrmIniciarConsultaContrato
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.UcVistaDetalleProcesoCompra1.ESTADO = 17
Me.UcVistaDetalleProcesoCompra1.EVAL_FEC_REC = False
Me.UcVistaDetalleProcesoCompra1.EVAL_FEC_RET = False
Me.UcVistaDetalleProcesoCompra1.IDESTABLECIMIENTO = Session("IdEstablecimiento")
'me.UcVistaDetalleProcesoCompra1._IDPROCESO
Me.UcVistaDetalleProcesoCompra1.PaginaRedirect = "frmConsultarContratos.aspx"
Me.UcVistaDetalleProcesoCompra1.Consultar()
End Sub
End Class
| wilxsv/fork-sinab | WebSites/Abastecimientos/UACI/FrmIniciarConsultaContrato.aspx.vb | Visual Basic | gpl-3.0 | 653 |
<?php
/** ---------------------------------------------------------------------
* themes/default/Front/front_page_html : Front page of site
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2013 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* @package CollectiveAccess
* @subpackage Core
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3
*
* ----------------------------------------------------------------------
*/
$va_access_values = $this->getVar("access_values");
$qr_res = $this->getVar('featured_set_items_as_search_result');
$o_config = $this->getVar("config");
$vs_caption_template = $o_config->get("front_page_set_item_caption_template");
if(!$vs_caption_template){
$vs_caption_template = "<l>^ca_objects.preferred_labels.name</l>";
}
if($qr_res && $qr_res->numHits()){
?>
<div class="jcarousel-wrapper">
<!-- Carousel -->
<div class="jcarousel">
<ul>
<?php
while($qr_res->nextHit()){
if($vs_media = $qr_res->getWithTemplate('<l>^ca_object_representations.media.large</l>', array("checkAccess" => $va_access_values))){
print "<li><div class='frontSlide'>".$vs_media;
print "<div class='frontSlideCaption'>";
print $qr_res->getWithTemplate("<l><i>^ca_objects.preferred_labels.name</i></l>");
if($qr_res->get("ca_objects.creation_date")){
print ", ";
if(strtolower($qr_res->get("ca_objects.creation_date")) == "unknown"){
print "Date ".$qr_res->get("ca_objects.creation_date");
}else{
print $qr_res->get("ca_objects.creation_date");
}
}
$va_entities = $qr_res->get("ca_entities", array("returnWithStructure" => true, "restrictToRelationshipTypes" => array("creator"), "checkAccess" => $va_access_values));
if(sizeof($va_entities)){
$t_entity = new ca_entities();
print "<br/>";
$i = 0;
foreach($va_entities as $va_entity){
$t_entity->load($va_entity["entity_id"]);
print caDetailLink($this->request, $t_entity->getLabelForDisplay(), "", "ca_entities", $t_entity->get("entity_id"));
$vs_nationality = trim($t_entity->get("nationality", array("delimiter" => "; ", "convertCodesToDisplayText" => true)));
$vs_dob = $t_entity->get("dob_dod");
if(strtolower($vs_dob) == "unknown"){
$vs_dob = "";
}
if($vs_nationality || $vs_dob){
print " (".$vs_nationality;
if($vs_nationality && $vs_dob){
print ", ";
}
print $vs_dob.")";
}
$i++;
if($i < sizeof($va_entities)){
print ", ";
}
}
}
print "</div>";
print "</div></li>";
$vb_item_output = true;
}
}
?>
</ul>
</div><!-- end jcarousel -->
<?php
if($vb_item_output){
?>
<!-- Prev/next controls -->
<a href="#" class="jcarousel-control-prev"><i class="fa fa-angle-left"></i></a>
<a href="#" class="jcarousel-control-next"><i class="fa fa-angle-right"></i></a>
<!-- Pagination -->
<p class="jcarousel-pagination">
<!-- Pagination items will be generated in here -->
</p>
<?php
}
?>
</div><!-- end jcarousel-wrapper -->
<script type='text/javascript'>
jQuery(document).ready(function() {
/*
Carousel initialization
*/
$('.jcarousel')
.jcarousel({
// Options go here
});
/*
Prev control initialization
*/
$('.jcarousel-control-prev')
.on('jcarouselcontrol:active', function() {
$(this).removeClass('inactive');
})
.on('jcarouselcontrol:inactive', function() {
$(this).addClass('inactive');
})
.jcarouselControl({
// Options go here
target: '-=1'
});
/*
Next control initialization
*/
$('.jcarousel-control-next')
.on('jcarouselcontrol:active', function() {
$(this).removeClass('inactive');
})
.on('jcarouselcontrol:inactive', function() {
$(this).addClass('inactive');
})
.jcarouselControl({
// Options go here
target: '+=1'
});
/*
Pagination initialization
*/
$('.jcarousel-pagination')
.on('jcarouselpagination:active', 'a', function() {
$(this).addClass('active');
})
.on('jcarouselpagination:inactive', 'a', function() {
$(this).removeClass('active');
})
.jcarouselPagination({
// Options go here
});
});
</script>
<?php
}
?> | libis/pa_cct | themes/steelcase/views/Front/featured_set_slideshow_html.php | PHP | gpl-3.0 | 5,383 |
<?php
/**
* @version $Revision: $:
* @author $Author: $:
* @date $Date: $:
*/
namespace ManiaLivePlugins\NadeoLive\XmlRpcScript;
use ManiaLive\DedicatedApi\Callback\Event as ServerEvent;
class Plugin extends \ManiaLive\PluginHandler\Plugin
{
public function onInit()
{
}
public function onLoad()
{
$this->enableDedicatedEvents(ServerEvent::ON_MODE_SCRIPT_CALLBACK);
}
public function onModeScriptCallback($param1, $param2)
{
$this->param = $param2;
switch ($param1)
{
case 'LibXmlRpc_BeginMatch':
$this->dispatch(Event::ON_BEGIN_MATCH, $param2);
break;
case 'LibXmlRpc_OnShoot':
$this->dispatch(Event::ON_SHOOT, $param2);
break;
case 'LibXmlRpc_OnHit':
$this->dispatch(Event::ON_HIT, $param2);
break;
case 'LibXmlRpc_OnNearMiss':
$this->dispatch(Event::ON_NEAR_MISS, $param2);
break;
case 'LibXmlRpc_OnCapture':
$this->dispatch(Event::ON_CAPTURE, $param2);
break;
case 'BeginMatch':
$this->dispatch(Event::ON_ELITE_MATCH_START, json_decode($param2));
break;
case 'BeginTurn':
$this->dispatch(Event::ON_ELITE_BEGIN_TURN, json_decode($param2));
break;
case 'OnShoot':
$this->dispatch(Event::ON_ELITE_SHOOT, json_decode($param2));
break;
case 'OnHit':
$this->dispatch(Event::ON_ELITE_HIT, json_decode($param2));
break;
case 'OnCapture':
$this->dispatch(Event::ON_ELITE_CAPTURE, json_decode($param2));
break;
case 'OnArmorEmpty':
$this->dispatch(Event::ON_ELITE_ARMOR_EMPTY, json_decode($param2));
break;
case 'OnNearMiss':
$this->dispatch(Event::ON_ELITE_NEAR_MISS, json_decode($param2));
break;
case 'EndTurn':
$this->dispatch(Event::ON_ELITE_END_TURN, json_decode($param2));
}
}
protected function dispatch($event, $param)
{
\ManiaLive\Event\Dispatcher::dispatch(new Event($event, $param));
}
} | maniaplanet/manialive-plugins | NadeoLive/XmlRpcScript/Plugin.php | PHP | gpl-3.0 | 1,888 |
<?php
use Illuminate\Database\Seeder;
use App\Vehiculo;
use App\Fabricante;
use Faker\Factory AS Faker;
class VehiculoSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create('es_ES');
$cantidad = Fabricante::all()->count();
for ($i=0; $i < 45; $i++)
{
Vehiculo::create(
[
'serie' => $faker->word(),
'color' => $faker->safeColorName(),
'año' => $faker->date($format = 'Y-m-d', $max = 'now'),
'potencia' => $faker->randomNumber(3),
'cilindraje' => $faker->randomNumber(4),
'peso' => $faker->randomFloat(4),
'id_fabricante' => $faker->numberBetween(1, $cantidad)
]
);
}
}
}
| JoseLoarca/laravel | database/seeds/VehiculoSeeder.php | PHP | gpl-3.0 | 901 |
package org.springframework.roo.multiselect.web;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import org.springframework.roo.multiselect.domain.Pet;
/**
* = PetsItemJsonController
*
* TODO Auto-generated class documentation
*
*/
@RooController(entity = Pet.class, type = ControllerType.ITEM)
@RooJSON
public class PetsItemJsonController {
}
| DISID/disid-proofs | spring-roo-datatables-multiselect/src/main/java/org/springframework/roo/multiselect/web/PetsItemJsonController.java | Java | gpl-3.0 | 561 |
<?php
/**
* TbButtonColumn class file.
* @author Christoffer Niska <ChristofferNiska@gmail.com>
* @copyright Copyright © Christoffer Niska 2011-
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @package bootstrap.widgets
* @since 0.9.8
*/
Yii::import('zii.widgets.grid.CButtonColumn');
/**
* Bootstrap button column widget.
* Used to set buttons to use Glyphicons instead of the defaults images.
*/
class TbButtonColumn extends CButtonColumn
{
/**
* @var string the view button icon (defaults to 'eye-open').
*/
public $viewButtonIcon = 'eye-open';
/**
* @var string the update button icon (defaults to 'pencil').
*/
public $updateButtonIcon = 'pencil';
/**
* @var string the delete button icon (defaults to 'trash').
*/
public $deleteButtonIcon = 'trash';
/**
* Initializes the default buttons (view, update and delete).
*/
protected function initDefaultButtons()
{
parent::initDefaultButtons();
if ($this->viewButtonIcon !== false && !isset($this->buttons['view']['icon']))
$this->buttons['view']['icon'] = $this->viewButtonIcon;
if ($this->updateButtonIcon !== false && !isset($this->buttons['update']['icon']))
$this->buttons['update']['icon'] = $this->updateButtonIcon;
if ($this->deleteButtonIcon !== false && !isset($this->buttons['delete']['icon']))
$this->buttons['delete']['icon'] = $this->deleteButtonIcon;
}
/**
* Renders a link button.
* @param string $id the ID of the button
* @param array $button the button configuration which may contain 'label', 'url', 'imageUrl' and 'options' elements.
* @param integer $row the row number (zero-based)
* @param mixed $data the data object associated with the row
*/
protected function renderButton($id, $button, $row, $data)
{
if (isset($button['visible']) && !$this->evaluateExpression($button['visible'], array('row'=>$row, 'data'=>$data)))
return;
$label = isset($button['label']) ? $button['label'] : $id;
$url = isset($button['url']) ? $this->evaluateExpression($button['url'], array('data'=>$data, 'row'=>$row)) : '#';
$options = isset($button['options']) ? $button['options'] : array();
if (!isset($options['title']))
$options['title'] = $label;
if (!isset($options['rel']))
$options['rel'] = 'tooltip';
if (isset($button['icon']))
{
if (strpos($button['icon'], 'icon') === false)
$button['icon'] = 'icon-'.implode(' icon-', explode(' ', $button['icon']));
echo CHtml::link('<i class="'.$button['icon'].'"></i>', $url, $options);
}
else if (isset($button['imageUrl']) && is_string($button['imageUrl']))
echo CHtml::link(CHtml::image($button['imageUrl'], $label), $url, $options);
else
echo CHtml::link($label, $url, $options);
}
}
| kevinnewesil/Grades2Show | protected/extensions/bootstrap/widgets/TbButtonColumn.php | PHP | gpl-3.0 | 2,813 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#Copyright (C) 2013 Jonathan Delvaux <dumpformat@djoproject.net>
#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/>.
import unittest
from dumpformat import dumpManager
#TODO test
#try to save .test.xml does not work, why ?
class mltriesTest(unittest.TestCase):
def setUp(self):
self.d = dumpManager()
def test_init(self):
self.d.save("./test.xml")
def test_
def test_load(self):
pass
#TODO
#save then load and compare
if __name__ == '__main__':
unittest.main() | djo938/dumpFormat | dumpformat/test/test.py | Python | gpl-3.0 | 1,155 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.