code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#ifdef PARSER_H #define PARSER_H int parse(char *content, long fsize, int argsc, char *args[]); #endif
mishavetl/slang
src/slang/parser.h
C
gpl-3.0
105
#mapSvg{background-color: #ffffff;} .l0r0 { stroke: #000000; stroke-width: 0.26; stroke-opacity: 1.0; stroke-dasharray: ; fill: #f7fbff; fill-opacity: 1.0; } .l0r1 { stroke: #000000; stroke-width: 0.26; stroke-opacity: 1.0; stroke-dasharray: ; fill: #d7e6f4; fill-opacity: 1.0; } .l0r2 { stroke: #000000; stroke-width: 0.26; stroke-opacity: 1.0; stroke-dasharray: ; fill: #afd1e7; fill-opacity: 1.0; } .l0r3 { stroke: #000000; stroke-width: 0.26; stroke-opacity: 1.0; stroke-dasharray: ; fill: #72b2d7; fill-opacity: 1.0; } .l0r4 { stroke: #000000; stroke-width: 0.26; stroke-opacity: 1.0; stroke-dasharray: ; fill: #3d8dc3; fill-opacity: 1.0; } .l0r5 { stroke: #000000; stroke-width: 0.26; stroke-opacity: 1.0; stroke-dasharray: ; fill: #1562a9; fill-opacity: 1.0; } .l0r6 { stroke: #000000; stroke-width: 0.26; stroke-opacity: 1.0; stroke-dasharray: ; fill: #08306b; fill-opacity: 1.0; }
leoouma/leoouma.github.io
d3-map/css/color.css
CSS
gpl-3.0
890
// port.js class SingleData { constructor (port, order, type, value) { this.port = port this.order = order this.type = type this.value = value } } export let inputVariables = [] export let countVariables = [] // Add a new port export function Add (countInputPort) { countInputPort++ inputVariables[countInputPort] = [] countVariables[countInputPort] = 0 $('div#inputPortList').append( `<div class="list-group-item list-group-item-action" data-toggle="modal" data-target="#addNewModal${countInputPort}" id="inputPort${countInputPort}"> Port ${countInputPort}</div>` ) $(`#inputPort${countInputPort}`).click(function () { portDetail(countInputPort) }) return true } // Show Details of Port export function portDetail (countInputPort) { let container = '' let order = countVariables[countInputPort] // Show exist variables for (let variable of inputVariables[countInputPort]) { container += `<li class="list-group-item list-group-item-action"> <p class="mb-1 float-left text-primary">${variable.order + 1}&nbsp;&nbsp;&nbsp;&nbsp;</p> <p class="mb-1 float-left variable-type"><label class="variable-type" order="${variable.order}"> ${variable.type}</label>&nbsp;&nbsp;&nbsp;&nbsp;</p> <p class="mb-1 float-left"> <input type="text" class="form-control variable-value" order="${variable.order}" value="${variable.value}"> </p> </li>` } // Show variables list $('div#modalArea').html( `<div class="modal fade" id="addNewModal${countInputPort}" tabindex="-1" role="dialog" aria-labelledby="addNewModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="addNewModalLabel">Port ${countInputPort}</h5> <button class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-row" id="globalDt"> <select class="form-control col-md-7 mx-sm-3 mb-3" id="dt"> <option value="Numeric">Numeric</option> <option value="Character">Character</option> <option value="Enumeration">Enumeration</option> <option value="Boolean">Boolean</option> <option value="Set">Set</option> <option value="Sequence">Sequence</option> <option value="String">String</option> <option value="Composite">Composite</option> <option value="Product">Product</option> <option value="Map">Map</option> <option value="Union">Union</option> <option value="Class">Class</option> </select> <button class="btn btn-outline-primary col-md-4 mb-3" id="addVariable">Add</button> </div> <!-- list of data types --> <div> <ul class="list-group" id="variables"> ${container} </ul> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" id="savePort">Save changes</button> <button class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div>` ) // Add a new variables $('button#addVariable').click(function () { let selectedValue = $('select#dt').val() console.log(order) $('ul#variables').append( `<li class="list-group-item list-group-item-action"> <p class="mb-1 float-left text-primary">${order + 1}&nbsp;&nbsp;&nbsp;&nbsp;</p> <p class="mb-1 float-left variable-type"><label class="variable-type" order=${order}> ${selectedValue}</label>&nbsp;&nbsp;&nbsp;&nbsp;</p> <p class="mb-1 float-left"> <input type="text" class="form-control variable-value" order="${order}" placeholder="${selectedValue}"> </p> </li>` ) order++ }) // Save port $('button#savePort').click(function () { let i for (i = 0; i < order; i++) { let type = $(`label.variable-type[order$="${i}"]`).text() let value = $(`input.variable-value[order$="${i}"]`).val() // console.log(type + '\n' + value) inputVariables[countInputPort][i] = new SingleData(countInputPort, i, type, value) console.log(`saved: port: ${countInputPort} order: ${i} type: ${type} value: ${value}`) } countVariables[countInputPort] = i console.log('total: ' + countVariables[countInputPort]) }) } export function Update (id, value) { let editId = 'div#' + id $(editId).text(value) }
cy92830/DataTypeGUI
src/scripts/port1.js
JavaScript
gpl-3.0
4,832
<?PHP require_once("website.php"); $adminModuleUtils->checkAdminModule(MODULE_FORM); $mlText = $languageUtils->getMlText(__FILE__); $warnings = array(); $formSubmitted = LibEnv::getEnvHttpPOST("formSubmitted"); if ($formSubmitted) { $formId = LibEnv::getEnvHttpPOST("formId"); $name = LibEnv::getEnvHttpPOST("name"); $description = LibEnv::getEnvHttpPOST("description"); $name = LibString::cleanString($name); $description = LibString::cleanString($description); // The name is required if (!$name) { array_push($warnings, $mlText[6]); } // Check that the name is not already used if ($form = $formUtils->selectByName($name)) { $wFormId = $form->getId(); if ($wFormId != $formId) { array_push($warnings, $mlText[7]); } } if (count($warnings) == 0) { // Duplicate the form $formUtils->duplicate($formId, $name); $str = LibHtml::urlRedirect("$gFormUrl/admin.php"); printMessage($str); exit; } } else { $formId = LibEnv::getEnvHttpGET("formId"); $name = ''; $description = ''; if ($form = $formUtils->selectById($formId)) { $randomNumber = LibUtils::generateUniqueId(); $name = $form->getName() . FORM_DUPLICATA . '_' . $randomNumber; $description = $form->getDescription(); } } $strWarning = ''; if (count($warnings) > 0) { foreach ($warnings as $warning) { $strWarning .= "<br>$warning"; } } $panelUtils->setHeader($mlText[0], "$gFormUrl/admin.php"); $panelUtils->addLine($panelUtils->addCell($strWarning, "wb")); $help = $popupUtils->getHelpPopup($mlText[3], 300, 300); $panelUtils->setHelp($help); $panelUtils->openForm($PHP_SELF); $panelUtils->addLine($panelUtils->addCell($mlText[4], "nbr"), "<input type='text' name='name' value='$name' size='30' maxlength='50'>"); $panelUtils->addLine(); $panelUtils->addLine($panelUtils->addCell($mlText[5], "nbr"), "<input type='text' name='description' value='$description' size='30' maxlength='255'>"); $panelUtils->addLine(); $panelUtils->addLine('', $panelUtils->getOk()); $panelUtils->addHiddenField('formSubmitted', 1); $panelUtils->addHiddenField('formId', $formId); $panelUtils->closeForm(); $str = $panelUtils->render(); printAdminPage($str); ?>
stephaneeybert/learnintouch
modules/form/duplicate.php
PHP
gpl-3.0
2,253
// DXQuake3 Source // Copyright (c) 2003 Richard Geary ([email protected]) // // // Useful Utilities for DQ // #include "stdafx.h" //'a'-'A' = 97 - 65 = 32 #define DQLowerCase( in ) ( ( (in)>='a' && (in)<='z' ) ? (in)-32 : (in) ) //Copy pSrc to pDest up to null terminating char or MaxLength //Return value is length of copied string, excluding null-terminator int DQstrcpy(char *pDest, const char *pSrc, int MaxLength) { int pos = 0; if( !pDest || !pSrc || MaxLength<0 ) { //Used by c_Exception, so we can't throw a c_Exception type throw 1; } while(*pSrc!='\0' && pos<MaxLength-1) { *pDest = *pSrc; ++pos; ++pSrc; ++pDest; } *pDest = '\0'; return pos; } //Returns length of pSrc excluding null terminting character, up to MaxLength int DQstrlen(const char *pSrc, int MaxLength) { const char *pos = pSrc; int len = 0; while(*pos!='\0' && len<MaxLength) { ++len; ++pos; } return len; } //Compares pStr1 to pStr2 up to Null terminator or Maxlength. Returns 0 if identital, else -1 (c.f. C strcmp) int DQstrcmp(const char *pStr1, const char *pStr2, int MaxLength) { int pos = 1; DebugCriticalAssert( pStr1 && pStr2 ); while(*pStr1==*pStr2) { if(*pStr1=='\0' || pos>=MaxLength) return 0; //strings identical ++pStr1; ++pStr2; ++pos; } if(*pStr1=='\0' || *pStr2=='\0') return 0; //strings different return -1; } //Compares (case insensitive) pStr1 to pStr2 up to Null terminator or Maxlength. Returns 0 if identital, else -1 (c.f. C strcmp) int DQstrcmpi(const char *pStr1, const char *pStr2, int MaxLength) { int pos = 0; DebugCriticalAssert( pStr1 && pStr2 ); char c1, c2; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); while(c1==c2) { if(pos>=MaxLength) return -1; if(c1=='\0') return 0; //strings identical ++pStr1; ++pStr2; ++pos; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); } //strings different return -1; } //Skips space, tab, new lines, // and /* */ //Returns position (in bytes) relative to pSrc int DQSkipWhitespace(const char *pSrc, int MaxLength) { BOOL bComment = FALSE; //Possible Comment ( // ) int pos=0; DebugCriticalAssert( pSrc ); while(pos<MaxLength && (*pSrc==' ' || *pSrc=='\t' || *pSrc=='/' || *pSrc=='*' || *pSrc==10 || *pSrc==13)) { if(*pSrc=='*') { //if we have /* if(bComment) { //Skip until */ bComment = TRUE; while(bComment) { if(pos>=MaxLength) return MaxLength; if(*pSrc=='*') { if((pos+1<MaxLength) && *(pSrc+1)=='/') { bComment = FALSE; ++pSrc; ++pos; } } ++pSrc; ++pos; } } else break; // we have * on its own, which is not whitespace } if(*pSrc=='/') { if(bComment == TRUE) { //Skip to end of line while(*pSrc!=10 && *pSrc!=0 && pos<MaxLength) { ++pSrc; ++pos; } bComment = FALSE; } else bComment = TRUE; } else { if(bComment == TRUE) { //Previous / was a valid character return pos-1; } } ++pSrc; ++pos; } // if(*pSrc==10 || *pSrc==13 || *pSrc==0 || pos==MaxLength) return MaxLength; //end of the string //else return pos; } //Returns the position of the next space, tab, end of line, comment, or MaxLength int DQSkipWord(const char *pSrc, int MaxLength) { BOOL bComment = FALSE; int pos=0; DebugCriticalAssert( pSrc ); while(pos<MaxLength && *pSrc!=' ' && *pSrc!='\t' && *pSrc!=10 && *pSrc!=13 && *pSrc!=0) { if(*pSrc=='*' && bComment==TRUE) { return pos-1; } if(*pSrc=='/') { if(bComment == TRUE) { // return pos of start of // return pos-1; } else bComment = TRUE; } else { bComment = FALSE; //wasn't a comment line } ++pSrc; ++pos; } return pos; } //Strips an extention off a path void DQStripExtention(char *pPath, int MaxLength) { int pos = 0; while(pos<MaxLength && *pPath!='\0') { ++pos; ++pPath; } //Move back to . while(pos>0 && *pPath!='.') { --pos; --pPath; } //Truncate pPath if(*pPath=='.') *pPath='\0'; return; } //Strips a filename off a path void DQStripFilename(char *pPath, int MaxLength) { BOOL bHasFilename = FALSE; //path has a filename in it int pos = 0; while(pos<MaxLength && *pPath!='\0') { if(*pPath=='.') bHasFilename = TRUE; ++pos; ++pPath; } if(!bHasFilename) { //path has no filename already //Remove any / at the end of pPath --pPath; if(*pPath=='\\' || *pPath=='/') *pPath='\0'; return; } /* Move back to / or \ */ while(pos>0 && *pPath!='/' && *pPath!='\\') { --pos; --pPath; } //Truncate pPath *pPath='\0'; return; } //Returns position of next line (relative to pSrc) int DQNextLine(const char *pSrc, int MaxLength) { int pos=0; DebugCriticalAssert( pSrc ); while(pos<MaxLength && *pSrc!=10 && *pSrc!=13 && *pSrc!=0) { ++pSrc; ++pos; } if(*pSrc==0) return pos; return pos+1; } //Case insensitive Compare pSrc1 to pSrc2 until next whitespace or MaxLength, not including comments (cba) //Return 0 if identical, else -1 int DQWordstrcmpi(const char *pStr1, const char *pStr2, int MaxLength) { DebugCriticalAssert( pStr1 && pStr2 ); int pos = 0; char c1, c2; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); while(c1==c2) { if(c1=='\0' || c1==' ' || c1=='\t' || pos>MaxLength) return 0; //strings identical ++pStr1; ++pStr2; ++pos; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); } if(c1=='\0' && ( c2==' ' || c2=='\t' || c2==10 || c2==13) ) return 0; if(c2=='\0' && ( c1==' ' || c1=='\t' || c1==10 || c1==13) ) return 0; //strings different return -1; } //Compares (case insensitive) pStrShort to pStrLong up to FIRST Null terminator or Maxlength. //Returns 0 if pStrLong is identical to pStrShort so far, else -1 //eg. pStrShort = "blah", pStrLong = "blahman", return 0 //eg. pStrShort = "blahman", pStrLong = "blah", return -1 int DQPartialstrcmpi(const char *pStrShort, const char *pStrLong, int MaxLength) { int pos = 0; DebugCriticalAssert( pStrShort && pStrLong ); char c1, c2; c1 = DQLowerCase( *pStrShort ); c2 = DQLowerCase( *pStrLong ); while(c1==c2) { if(pos>=MaxLength) return 0; if(c1=='\0') return 0; ++pStrShort; ++pStrLong; ++pos; c1 = DQLowerCase( *pStrShort ); c2 = DQLowerCase( *pStrLong ); } if(*pStrShort=='\0') return 0; //strings different return -1; } //Copies pSrc to pDest until whitespace or MaxLength //Returns length of word, excluding null terminator int DQWordstrcpy(char *pDest, const char *pSrc, int MaxLength) { int pos = 0; DebugCriticalAssert( pSrc && pDest && MaxLength>=0 ); while(*pSrc!='\0' && *pSrc!=' ' && *pSrc!='\t' && *pSrc!=10 && *pSrc!=13 && pos<MaxLength-1) { *pDest = *pSrc; ++pos; ++pSrc; ++pDest; } *pDest = '\0'; return pos; } //Appends pSrcAppend to pDest, up to pSrcAppend[MaxLength] or Null-terminator //Returns length of pSrcAppend int DQstrcat(char *pDest, const char *pSrcAppend, int MaxLength) { int pos = 0, SrcLength = 0; while(*pDest!='\0') { if(pos>=MaxLength) { return MaxLength; } ++pDest; ++pos; } while(*pSrcAppend!='\0') { if(pos>=MaxLength-1) { return MaxLength; } *pDest = *pSrcAppend; ++pDest; ++pSrcAppend; ++pos; ++SrcLength; } *pDest = '\0'; return SrcLength; } void DQStripPath(char *pFullPath, int MaxLength) { int pos = 0; char *pPath = pFullPath; while(pos<MaxLength && *pPath!='\0') { ++pos; ++pPath; } while(pos>0 && *pPath!='/' && *pPath!='\\') { --pPath; --pos; } if(pos==0) return; ++pPath; ++pos; while(pos<MaxLength && *pPath!='\0') { *pFullPath = *pPath; ++pPath; ++pFullPath; ++pos; } *pFullPath='\0'; } //Copy pSrc to pDest until *pSrc==marker or '\0' or MaxLength reached //returns num chars copied +1, or the pos of the null-terminator int DQCopyUntil(char *pDest, const char *pSrc, char marker, int MaxLength) { int pos = 0; while(pos<MaxLength-1 && *pSrc!=marker && *pSrc!='\0') { *pDest=*pSrc; ++pDest; ++pSrc; ++pos; } *pDest = '\0'; if(*pSrc=='\0') return pos; return pos+1; //return the char after marker } //remove "'s void DQStripQuotes(char *pString, int MaxLength) { int i; if(*pString=='"') { for(i=0;i<MaxLength && *(pString+1)!='"';++i,++pString) *pString = *(pString+1); *pString='\0'; } } //Truncate pStr1 when it varies (case insensitive) from pCompareString void DQstrTruncate(char *pStr1, const char *pCompareString, int MaxLength) { int pos = 0; DebugCriticalAssert( pStr1 && pCompareString ); char c1,c2; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pCompareString ); while(c1==c2) { if(pos>=MaxLength) return; if(c1=='\0') return; ++pStr1; ++pCompareString; ++pos; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pCompareString ); } //Truncate *pStr1 = '\0'; } void DQWCharToChar(WCHAR *pSrc, int SrcLength, char *pDest, int DestLength) { WideCharToMultiByte( CP_ACP, NULL, pSrc, SrcLength, pDest, DestLength, NULL, NULL ); } //same as strcmpi, but insensitive to \ and / int DQFilenamestrcmpi(const char *pStr1, const char *pStr2, int MaxLength) { int pos = 0; DebugCriticalAssert( pStr1 && pStr2 ); char c1, c2; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); if(c1=='\\') c1='/'; if(c2=='\\') c2='/'; while(c1==c2) { if(pos>=MaxLength) return -1; if(c1=='\0') return 0; //strings identical ++pStr1; ++pStr2; ++pos; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); if(c1=='\\') c1='/'; if(c2=='\\') c2='/'; } //strings different return -1; } void DQStripGfxExtention(char *pSrc, int MaxLength) { int len; if(!pSrc || MaxLength<4) return; len = DQstrlen( pSrc, MAX_QPATH ); if(len>4) { if( (DQstrcmpi(&pSrc[len-4], ".tga", MAX_QPATH)==0) || (DQstrcmpi(&pSrc[len-4], ".jpg", MAX_QPATH)==0) ) { pSrc[len-4] = '\0'; } } }
coltongit/dxquake3
code/utils.cpp
C++
gpl-3.0
10,161
package net.mosstest.tests; import net.mosstest.scripting.NodePosition; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.fail; public class NodePositionTest { public static final int CHUNK_DIMENSION = 16; public static final int[] coords = {0, 1, -1, 16, -16, 67, -66, 269, -267, 65601, -65601, Integer.MAX_VALUE, Integer.MIN_VALUE}; @Test public void testHashCode() { for (int i = 0; i < coords.length; i++) { for (int j = 0; j < coords.length; j++) { for (int k = 0; k < coords.length; k++) { for (byte x = 0; x < CHUNK_DIMENSION; x += 8) { for (byte y = 0; y < CHUNK_DIMENSION; y += 8) { for (byte z = 0; z < CHUNK_DIMENSION; z += 8) { NodePosition pos1 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, z); NodePosition pos2 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, z); Assert.assertEquals( "Mismatched hashCodes for value-identical NodePosition objects", pos1.hashCode(), pos2.hashCode()); } } } } } } } @Test public void testByteArrayReadWrite() { for (int i = 0; i < coords.length; i++) { for (int j = 0; i < coords.length; i++) { for (int k = 0; i < coords.length; i++) { for (byte x = 0; x < CHUNK_DIMENSION; x+=8) { for (byte y = 0; y < CHUNK_DIMENSION; y+=8) { for (byte z = 0; z < CHUNK_DIMENSION; z+=4) { NodePosition pos1 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, z); byte[] bytes = pos1.toBytes(); NodePosition pos2; try { pos2 = new NodePosition(bytes); Assert.assertTrue( "NodePosition nmarshaled from byte[] fails equals() check with original NodePosition.", pos1.equals(pos2)); } catch (IOException e) { fail("IOException caught in unmarshaling NodePosition from byte[]"); } } } } } } } } @Test public void testEqualsObject() { for (int i = 0; i < coords.length; i++) { for (int j = 0; j < coords.length; j++) { for (int k = 0; k < coords.length; k++) { for (byte x = 0; x < CHUNK_DIMENSION; x+=8) { for (byte y = 0; y < CHUNK_DIMENSION; y+=8) { for (byte z = 0; z < CHUNK_DIMENSION; z+=4) { NodePosition pos1 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, z); NodePosition pos2 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, z); Assert.assertTrue( "Value-equal objects fail equals() check", pos1.equals(pos2)); Assert.assertTrue( "Value-equal objects fail equals() check", pos2.equals(pos1)); NodePosition pos3 = new NodePosition( 0, coords[i] + 1, coords[j], coords[k], x, y, z); NodePosition pos4 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, z); Assert.assertFalse( "Value-unequal objects erroneously pass equals() check for x", pos3.equals(pos4)); Assert.assertFalse( "Value-unequal objects erroneously pass equals() check for x", pos4.equals(pos3)); NodePosition pos5 = new NodePosition(0, coords[i], coords[j] + 1, coords[k], x, y, z); NodePosition pos6 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, z); Assert.assertFalse( "Value-unequal objects erroneously pass equals() check for y", pos5.equals(pos6)); Assert.assertFalse( "Value-unequal objects erroneously pass equals() check for y", pos6.equals(pos5)); NodePosition pos7 = new NodePosition(0, coords[i], coords[j], coords[k] + 1, x, y, z); NodePosition pos8 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, z); Assert.assertFalse( "Value-unequal objects erroneously pass equals() check for z", pos7.equals(pos8)); Assert.assertFalse( "Value-unequal objects erroneously pass equals() check for z", pos8.equals(pos7)); } } } } } } } @Test public void testToBytes() { for (int i = 0; i < coords.length; i++) { for (int j = 0; j < coords.length; j++) { for (int k = 0; k < coords.length; k++) { for (byte x = 0; x < CHUNK_DIMENSION; x+=4) { for (byte y = 0; y < CHUNK_DIMENSION; y+=8) { NodePosition pos1 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, (byte)0); NodePosition pos2 = new NodePosition(0, coords[i], coords[j], coords[k], x, y, (byte)0); org.junit.Assert.assertArrayEquals( pos1.toBytes(), pos2.toBytes()); } } } } } } }
mosstest/mosstest
tests/net/mosstest/tests/NodePositionTest.java
Java
gpl-3.0
7,454
/* * G. Rilling, last modification: 3.2007 * [email protected] * * code based on a student project by T. Boustane and G. Quellec, 11.03.2004 * supervised by P. Chainais (ISIMA - LIMOS - Universite Blaise Pascal - Clermont II * email : [email protected]). */ /************************************************************************/ /* */ /* GET INPUT DATA */ /* */ /************************************************************************/ input_t get_input(int nlhs,int nrhs,const mxArray *prhs[]) { input_t input; int n,i; double *x,*y,*y_temp,*third,fourth; input.stop_params.threshold = DEFAULT_THRESHOLD; input.stop_params.tolerance = DEFAULT_TOLERANCE; input.allocated_x=0; #ifdef _ALT_MEXERRMSGTXT_ input.error_flag=0; #endif input.max_imfs=0; input.is_circular=false; /* argument checking*/ if (nrhs>5) mexErrMsgTxt("Too many arguments"); if (nrhs<2) mexErrMsgTxt("Not enough arguments"); if (nlhs>2) mexErrMsgTxt("Too many output arguments"); if (!mxIsEmpty(prhs[0])) if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) || (mxGetNumberOfDimensions(prhs[0]) > 2)) mexErrMsgTxt("X must be either empty or a double precision real vector."); if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]) || (mxGetNumberOfDimensions(prhs[1]) > 2)) mexErrMsgTxt("Y must be a double precision real vector."); /* input reading: x and y */ n=GREATER(mxGetN(prhs[1]),mxGetM(prhs[1])); /* length of vector x */ if (mxIsEmpty(prhs[0])) { input.allocated_x = 1; x = (double *)malloc(n*sizeof(double)); for(i=0;i<n;i++) x[i] = i; } else x=mxGetPr(prhs[0]); y_temp=mxGetPr(prhs[1]); /* Third argument, circularity */ if (nrhs>=3) { if(!mxIsEmpty(prhs[2])) { if (!mxIsLogical(prhs[2]) || mxGetNumberOfElements(prhs[2])!=1){ mexErrMsgTxt("CIRCULARITY must be boolean element"); } else { input.is_circular = (bool)mxGetScalar(prhs[2]); } } } /* fourth argument */ if (nrhs>=4) { if(!mxIsEmpty(prhs[3])) { if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsDouble(prhs[3]) || (mxGetN(prhs[3])!=1 && mxGetM(prhs[3])!=1)) mexErrMsgTxt("STOP must be a real vector of 1 or 2 elements"); i = GREATER(mxGetN(prhs[3]),mxGetM(prhs[3])); if (i>2) mexErrMsgTxt("STOP must be a vector of 1 or 2 elements"); third=mxGetPr(prhs[3]); switch (i) { case 1 : { if (nrhs==4 && *third==(int)*third && *third > 0) {/* third argument is max_imfs */ input.max_imfs=(int)*third; } else {/* third argument is input.stop_params.threshold */ input.stop_params.threshold=*third; } } break; case 2 : { input.stop_params.threshold=third[0]; input.stop_params.tolerance=third[1]; } } /* input checking */ if (input.stop_params.threshold <= 0){ mexErrMsgTxt("threshold must be a positive number"); } if (input.stop_params.threshold >= 1){ mexWarnMsgTxt("threshold should be lower than 1"); } if (input.stop_params.tolerance < 0 || input.stop_params.tolerance >= 1){ mexErrMsgTxt("tolerance must be a real number in [O,1]"); } } } /* fifth argument */ if (nrhs==5) { if (!mxIsEmpty(prhs[4])) { /* if empty -> do nothing */ if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4]) || !mxIsDouble(prhs[4]) || mxGetN(prhs[4])!=1 || mxGetM(prhs[4])!=1) mexErrMsgTxt("NB_IMFS must be a positive integer"); fourth=*mxGetPr(prhs[4]); if ((unsigned int)fourth != fourth) mexErrMsgTxt("NB_IMFS must be a positive integer"); input.max_imfs=(int)fourth; } } /* more input checking */ if (!input.allocated_x && (SMALLER(mxGetN(prhs[0]),mxGetM(prhs[0]))!=1 || SMALLER(mxGetN(prhs[1]),mxGetM(prhs[1]))!=1)) mexErrMsgTxt("X and Y must be vectors"); if (GREATER(mxGetN(prhs[1]),mxGetM(prhs[1]))!=n) mexErrMsgTxt("X and Y must have the same length"); i=1; while (i<n && x[i]>x[i-1]) i++; if (i<n) mexErrMsgTxt("Values in X must be non decreasing"); /* copy vector y to avoid erasing input data */ y=(double *)malloc(n*sizeof(double)); for (i=0;i<n;i++){ y[i]=y_temp[i]; } input.n=n; input.x=x; input.y=y; return input; } /************************************************************************/ /* */ /* INITIALIZATION OF THE LIST */ /* */ /************************************************************************/ imf_list_t init_imf_list(int n) { imf_list_t list; list.first=NULL; list.last=NULL; list.n=n; list.m=0; return list; } /************************************************************************/ /* */ /* ADD AN IMF TO THE LIST */ /* */ /************************************************************************/ void add_imf(imf_list_t *list,double *p,int nb_it) { double *v=(double *)malloc(list->n*sizeof(double)); int i; imf_t *mode=(imf_t *)malloc(sizeof(imf_t)); for (i=0;i<list->n;i++) v[i]=p[i]; mode->pointer=v; mode->nb_iterations=nb_it; mode->next=NULL; if (!list->first) { list->first=mode; } else { (list->last)->next=mode; } list->last=mode; list->m++; } /************************************************************************/ /* */ /* FREE MEMORY ALLOCATED FOR THE LIST */ /* */ /************************************************************************/ void free_imf_list(imf_list_t list) { imf_t *current=list.first, *previous; while (current) { previous=current; current=current->next; free(previous->pointer); free(previous); } } /************************************************************************/ /* */ /* OUTPUT INTO MATLAB ARRAY */ /* */ /************************************************************************/ void write_output(imf_list_t list,mxArray *plhs[]) { double *out1,*out2; imf_t *current; int i=0,j,m=list.m,n=list.n; plhs[0]=mxCreateDoubleMatrix(m,n,mxREAL); out1=mxGetPr(plhs[0]); plhs[1]=mxCreateDoubleMatrix(1,m-1,mxREAL); out2=mxGetPr(plhs[1]); for (current=list.first;current;current=current->next) { for (j=0;j<n;j++){ *(out1+j*m+i)=current->pointer[j]; } if (i<m-1) *(out2+i)=current->nb_iterations; i++; } }
pintomollo/asset
MEX/io.c
C
gpl-3.0
7,428
function createDownloadLink(data,filename,componentId){ let a = document.createElement('a'); a.href = 'data:' + data; a.download = filename; a.innerHTML = 'Export'; a.class = 'btn' let container = document.getElementById(componentId); container.appendChild(a); } function closest(array, num) { let i = 0; let minDiff = 1000; let ans; for (i in array) { let m = Math.abs(num - array[i]); if (m < minDiff) { minDiff = m; ans = array[i]; } } return ans; } export {createDownloadLink, closest}
alvcarmona/efficiencycalculatorweb
effcalculator/frontend/assets/js/utils.js
JavaScript
gpl-3.0
678
/* To Do: Fix Reverse Driving Make only one side fire (right) */ /* Copyright (c) 2014, 2015 Qualcomm Technologies Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Qualcomm Technologies Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.*; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.hardware.*; //red turns left //blue turns right /* To Do; Double gears on shooter Rotate Block and Top Part of Beacon Pusher 90 degrees. The servo end position is currently level with the end of the robot instead of sideways */ import java.text.SimpleDateFormat; import java.util.Date; import static android.os.SystemClock.sleep; /** * Registers OpCode and Initializes Variables */ @com.qualcomm.robotcore.eventloop.opmode.Autonomous(name = "Autonomous α", group = "FTC772") public class Autonomous extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); private DcMotor frontLeft, frontRight, intake, dispenserLeft, dispenserRight, liftLeft, liftRight, midtake; private Servo dispenser, beaconAngleLeft, beaconAngleRight, forkliftLeft, forkliftRight; private boolean drivingForward = true; //private boolean init = false; //private final double DISPENSER_POWER = 1; private double BEACON_LEFT_IN; private double BEACON_RIGHT_IN; private final int INITIAL_FORWARD = 1000; private final int RAMP_UP = 1000; private final int TURN_ONE = 300; private final int FORWARD_TWO = 500; private final int TURN_TWO = 300; private final int FORWARD_THREE = 300; private final int COLOR_CORRECTION = 50; private final int FORWARD_FOUR = 400; private final int TURN_THREE = 500; private final int FORWARD_FIVE = 500; private final boolean isRed = true; private boolean didColorCorrection = false; private boolean wasChangingAngle = false; private ColorSensor colorSensor; private TouchSensor leftTouchSensor, rightTouchSensor; // @Override // public void init() { // /* // Initialize DcMotors // */ // frontLeft = hardwareMap.dcMotor.get("frontLeft"); // frontRight = hardwareMap.dcMotor.get("frontRight"); // // //intake = hardwareMap.dcMotor.get("intake"); // dispenserLeft = hardwareMap.dcMotor.get("dispenserLeft"); // dispenserRight = hardwareMap.dcMotor.get("dispenserRight"); // // /* // Initialize Servos // */ // dispenserAngle = hardwareMap.servo.get("dispenserAngle"); // beaconAngle = hardwareMap.servo.get("beaconAngle"); // // // /* // Initialize Sensors // */ // colorSensor = hardwareMap.colorSensor.get("colorSensor"); // leftTouchSensor = hardwareMap.touchSensor.get("leftTouchSensor"); // rightTouchSensor = hardwareMap.touchSensor.get("rightTouchSensor"); // // //Display completion message // telemetry.addData("Status", "Initialized"); // } /* * Code to run when the op mode is first enabled goes here * @see com.qualcomm.robotcore.eventloop.opmode.OpMode#start() @Override public void init_loop() { }*/ /* * This method will be called ONCE when start is pressed * @see com.qualcomm.robotcore.eventloop.opmode.OpMode#loop() */ /* public void start() { /* Initialize all motors/servos to position */ //runtime.reset(); //dispenserAngle.setPosition(DEFAULT_ANGLE); // } /* * This method will be called repeatedly in a loop * @see com.qualcomm.robotcore.eventloop.opmode.OpMode#loop() */ @Override public void runOpMode() throws InterruptedException { frontLeft = hardwareMap.dcMotor.get("frontLeft"); frontRight = hardwareMap.dcMotor.get("frontRight"); intake = hardwareMap.dcMotor.get("intake"); midtake = hardwareMap.dcMotor.get("midtake"); dispenserLeft = hardwareMap.dcMotor.get("dispenserLeft"); dispenserRight = hardwareMap.dcMotor.get("dispenserRight"); dispenserLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); dispenserRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); liftLeft = hardwareMap.dcMotor.get("liftLeft"); liftRight = hardwareMap.dcMotor.get("liftRight"); liftLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); liftLeft.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); liftRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); liftRight.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); /* Initialize Servos */ dispenser = hardwareMap.servo.get("dispenser"); beaconAngleLeft = hardwareMap.servo.get("beaconAngleLeft"); beaconAngleRight = hardwareMap.servo.get("beaconAngleRight"); forkliftLeft = hardwareMap.servo.get("forkliftLeft"); forkliftRight = hardwareMap.servo.get("forkliftRight"); /* Initialize Sensors */ //colorSensor = hardwareMap.colorSensor.get("colorSensor"); //leftTouchSensor = hardwareMap.touchSensor.get("leftTouchSensor"); //rightTouchSensor = hardwareMap.touchSensor.get("rightTouchSensor"); //Display completion message telemetry.addData("Status", "Initialized"); /* Steps to Autonomous: Fire starting balls Drive to beacon 1 Press beacon 1 Drive to beacon 2 Press beacon 2 Drive to center and park while knocking ball off */ frontLeft.setPower(1); frontRight.setPower(-1); sleep(INITIAL_FORWARD); frontLeft.setPower(0); frontRight.setPower(0); dispenserLeft.setPower(1); dispenserRight.setPower(1); sleep(RAMP_UP); intake.setPower(1); midtake.setPower(1); dispenser.setPosition(0); sleep(500); dispenser.setPosition(.45); sleep(150); dispenser.setPosition(0); sleep(500); dispenser.setPosition(.45); intake.setPower(0); midtake.setPower(0); dispenserRight.setPower(0); dispenserLeft.setPower(0); if (isRed) { frontLeft.setPower(1); frontRight.setPower(1); sleep(TURN_ONE); frontRight.setPower(-1); } else { frontLeft.setPower(-1); frontRight.setPower(-1); sleep(TURN_ONE); frontLeft.setPower(1); } sleep(FORWARD_TWO); if (!isRed) { frontLeft.setPower(-1); sleep(TURN_TWO); frontLeft.setPower(1); } else { frontRight.setPower(1); sleep(TURN_TWO); frontRight.setPower(-1); } sleep(FORWARD_THREE); frontLeft.setPower(0); frontRight.setPower(0); if (!isRed) { if (colorSensor.red()<colorSensor.blue()) { beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN)); } else { frontLeft.setPower(1); frontRight.setPower(-1); sleep(COLOR_CORRECTION); didColorCorrection = true; frontLeft.setPower(0); frontRight.setPower(0); beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN)); } } else { if (colorSensor.red()>colorSensor.blue()) { beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN)); } else { frontLeft.setPower(1); frontRight.setPower(-1); sleep(COLOR_CORRECTION); didColorCorrection = true; frontLeft.setPower(0); frontRight.setPower(0); beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN)); } } frontLeft.setPower(1); frontRight.setPower(-1); if (didColorCorrection) { sleep(FORWARD_FOUR-COLOR_CORRECTION); } else { sleep(FORWARD_FOUR); } frontLeft.setPower(0); frontRight.setPower(0); if (!isRed) { if (colorSensor.red()<colorSensor.blue()) { beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN)); } else { frontLeft.setPower(1); frontRight.setPower(-1); sleep(COLOR_CORRECTION); frontLeft.setPower(0); frontRight.setPower(0); beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN)); } } else { if (colorSensor.red()>colorSensor.blue()) { beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN)); } else { frontLeft.setPower(1); frontRight.setPower(-1); sleep(COLOR_CORRECTION); frontLeft.setPower(0); frontRight.setPower(0); beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN)); } } frontLeft.setPower(1); frontRight.setPower(1); sleep(TURN_THREE); frontRight.setPower(-1); sleep(FORWARD_FIVE); telemetry.addData("Status", "Run Time: " + runtime.toString()); /* This section is the short version of the autonomous for in case the other part doesn't work. It drives straight forward and knocks the cap ball off in the center. */ sleep(10000); frontLeft.setPower(1); frontRight.setPower(-1); sleep(4000); frontRight.setPower(0); frontLeft.setPower(0); sleep(10000); } }
NeonRD1/FTC772
ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Autonomous.java
Java
gpl-3.0
11,732
/*root_check.c */ #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/input.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/statfs.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <dirent.h> #include "common.h" #include "cutils/properties.h" #include "cutils/android_reboot.h" #include "install.h" #include "minui/minui.h" #include "minzip/DirUtil.h" #include "minzip/SysUtil.h" #include "roots.h" #include "ui.h" #include "screen_ui.h" #include "device.h" #include "minzip/Zip.h" #include "root_check.h" extern "C" { #include "cr32.h" #include "md5.h" } #define FILENAME_MAX 200 unsigned int key=15; bool checkResult = true; static const char *SYSTEM_ROOT = "/system/"; static char* file_to_check[]={ "supersu.apk", "superroot.apk", "superuser.apk", "busybox.apk"}; static char* file_to_pass[]={ "recovery-from-boot.p", "install-recovery.sh", "recovery_rootcheck", "build.prop", "S_ANDRO_SFL.ini", "recovery.sig" }; static const char *IMAGE_LOAD_PATH ="/tmp/rootcheck/"; static const char *TEMP_FILE_IN_RAM="/tmp/system_dencrypt"; static const char *TEMP_IMAGE_IN_RAM="/tmp/image_dencrypt"; static const char *CRC_COUNT_TMP="/tmp/crc_count"; static const char *FILE_COUNT_TMP="/tmp/file_count"; static const char *DYW_DOUB_TMP="/tmp/doub_check"; static const char *FILE_NEW_TMP="/tmp/list_new_file"; struct last_check_file{ int n_newfile; int n_lostfile; int n_modifyfile; int n_rootfile; int file_number_to_check; int expect_file_number; unsigned int file_count_check; unsigned int crc_count_check; }; static struct last_check_file*check_file_result; int root_to_check[MAX_ROOT_TO_CHECK]={0}; extern RecoveryUI* ui; img_name_t img_array[PART_MAX] = { #ifdef MTK_ROOT_PRELOADER_CHECK {"/dev/preloader", "preloader"}, #endif {"/dev/uboot", "uboot"}, {"/dev/bootimg", "bootimg"}, {"/dev/recovery", "recoveryimg"}, {"/dev/logo", "logo"}, }; img_name_t img_array_gpt[PART_MAX] = { #ifdef MTK_ROOT_PRELOADER_CHECK {"/dev/preloader", "preloader"}, #endif {"/dev/block/platform/mtk-msdc.0/by-name/lk", "uboot"}, {"/dev/block/platform/mtk-msdc.0/by-name/boot", "bootimg"}, {"/dev/block/platform/mtk-msdc.0/by-name/recovery", "recoveryimg"}, {"/dev/block/platform/mtk-msdc.0/by-name/logo", "logo"}, }; img_checksum_t computed_checksum[PART_MAX]; img_checksum_t expected_checksum[PART_MAX]; int check_map[MAX_FILES_IN_SYSTEM/INT_BY_BIT+1]; int check_modify[MAX_FILES_IN_SYSTEM/INT_BY_BIT+1]; static bool is_support_gpt_c(void) { int fd = open("/dev/block/platform/mtk-msdc.0/by-name/para", O_RDONLY); if (fd == -1) { return false; } else { close(fd); return true; } } static void set_bit(int x) { check_map[x>>SHIFT]|= 1<<(x&MASK); } static void clear_bit(int x) { check_map[x>>SHIFT]&= ~(1<<(x&MASK)); } static int test_bit(int x) { return check_map[x>>SHIFT]&(1<<(x&MASK)); } static void set_bit_m(int x) { check_modify[x>>SHIFT]|= 1<<(x&MASK); } static void clear_bit_m(int x) { check_modify[x>>SHIFT]&= ~(1<<(x&MASK)); } static int test_bit_m(int x) { return check_modify[x>>SHIFT]&(1<<(x&MASK)); } static int file_crc_check( const char* path, unsigned int* nCS, unsigned char *nMd5) { char buf[4*1024]; FILE *fp = 0; int rRead_count = 0; int i = 0; *nCS = 0; #ifdef MTK_ROOT_ADVANCE_CHECK MD5_CTX md5; MD5Init(&md5); memset(nMd5, 0, MD5_LENGTH); #endif struct stat st; memset(&st,0,sizeof(st)); if ( path == NULL ){ LOGE("file_crc_check-> %s is null", path); return -1; } if(lstat(path,&st)<0) { LOGE("\n %s does not exist,lsta fail", path); return 1; } if(S_ISLNK(st.st_mode)) { printf("%s is a link file,just pass\n", path); return 0; } fp = fopen(path, "r"); if( fp == NULL ) { LOGE("\nfile_crc_check->path:%s ,fp is null", path); LOGE("\nfopen fail reason is %s",strerror(errno)); return -1; } while(!feof(fp)) { memset(buf, 0x0, sizeof(buf)); rRead_count = fread(buf, 1, sizeof(buf), fp); if( rRead_count <=0 ) break; #ifdef MTK_ROOT_NORMAL_CHECK *nCS += crc32(*nCS, buf, rRead_count); #endif #ifdef MTK_ROOT_ADVANCE_CHECK MD5Update(&md5,(unsigned char*)buf, rRead_count); #endif } #ifdef MTK_ROOT_ADVANCE_CHECK MD5Final(&md5, nMd5); #endif fclose(fp); return 0; } static int clear_selinux_file(char* path) { int found=0; int ret=0; FILE *fp_info; FILE *fp_new; char buf[512]; char p_name[256]; unsigned char p_md[MD5_LENGTH*2]; char *p_cmp_name; unsigned int p_size; int p_number; struct stat statbuf; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if(fgets(buf, sizeof(buf), fp_info) != NULL) { while(fgets(buf, sizeof(buf), fp_info)) { if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { //TODO:path[0] will be '\0' sometimes, and it should be '/' path[0] = '/'; if(strstr(p_name,path)!=NULL) { p_cmp_name=strstr(p_name,path); if(strcmp(p_cmp_name,path)==0) { found=1; clear_bit(p_number); } } } } if(found==0) { LOGE("found a new file,filename is %s",path); check_file_result->n_newfile+=1; if(access(FILE_NEW_TMP,0)==-1) { int fd_new=creat(FILE_NEW_TMP,0755); } fp_new=fopen(FILE_NEW_TMP, "a"); if(fp_new) { fprintf(fp_new,"%s\n",path); } else { LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno)); return CHECK_ADD_NEW_FILE; } checkResult=false; fclose(fp_info); fclose(fp_new); return CHECK_ADD_NEW_FILE; } } } else { LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); return CHECK_PASS; } static int clear_selinux_dir(char const* path) { int ret=0; FILE *fp_info; FILE *fp_new; char buf[512]; char p_name[256]; unsigned char p_md[MD5_LENGTH*2]; char *p_cmp_name; unsigned int p_size; int p_number; struct stat statbuf; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if(fgets(buf, sizeof(buf), fp_info) != NULL) { while(fgets(buf, sizeof(buf), fp_info)) { if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { //TODO:path[0] will be '\0' sometimes, and it should be '/' //path[0] = '/'; if(strstr(p_name,path)!=NULL) { p_cmp_name=strstr(p_name,path); LOGE("%s file is selinux protected,just pass\n",p_cmp_name); clear_bit(p_number); } else { //LOGE("not found %s in orignal file,please check!",path); continue; } } } } } else { LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); return CHECK_PASS; } static int check_reall_file(char* path, int nCS, char* nMd5) { int found=0; int ret=0; FILE *fp_info; FILE *fp_new; char buf[512]; char p_name[256]; unsigned char p_md[MD5_LENGTH*2]; char *p_cmp_name; unsigned int p_size; int p_number; struct stat statbuf; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if(fgets(buf, sizeof(buf), fp_info) != NULL) { //while(fgets(buf, sizeof(buf), fp_info)&&!found) while(fgets(buf, sizeof(buf), fp_info)) { memset(p_md, '0', sizeof(p_md)); if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { //TODO: can not get correct p_name from sscanf(), so use below instead char *p1 = strchr(buf, '\t'); char *p2 = strchr(p1+1, '\t'); if(p1&&p2) memcpy(p_name, p1+1, p2-p1-1); //TODO:path[0] will be '\0' sometimes, and it should be '/' path[0] = '/'; if(strstr(p_name,path)!=NULL) { p_cmp_name=strstr(p_name,path); if(strcmp(p_cmp_name,path)==0) { found=1; int rettmp = 0; clear_bit(p_number); #ifdef MTK_ROOT_NORMAL_CHECK if(p_size==nCS) { //printf("%s crc check pass\n",path); } else { printf("expected crc is %u\n",p_size); printf("computed crc is %u\n",nCS); printf("%s is modifyed\n",path); //fclose(fp_info); rettmp = CHECK_FILE_NOT_MATCH; } #endif #ifdef MTK_ROOT_ADVANCE_CHECK if(p_md[1]=='\0') p_md[1]='0'; hextoi_md5(p_md); if(memcmp(nMd5, p_md, MD5_LENGTH)==0) { //printf("%s md5 check pass\n",path); } else { #if 1 int i; for(i=0;i<16;i++) { printf("%02x",nMd5[i]); } for(i=0;i<16;i++) { printf("%02x", p_md[i]); } #endif LOGE("<<ERROR>>\n"); //check_file_result->n_modifyfile+=1; LOGE("Error:%s has been modified md5",path); ret=stat(path,&statbuf); if(ret != 0) { LOGE("Error:%s is not exist\n",path); } time_t modify=statbuf.st_mtime; ui->Print("on %s\n", ctime(&modify)); //fclose(fp_info); //return CHECK_FILE_NOT_MATCH; rettmp = CHECK_FILE_NOT_MATCH; } #endif if(rettmp){ check_file_result->n_modifyfile+=1; clear_bit_m(p_number); fclose(fp_info); return rettmp; } } } } } if(found==0) { LOGE("found a new file,filename is %s",path); check_file_result->n_newfile+=1; if(access(FILE_NEW_TMP,0)==-1) { int fd_new=creat(FILE_NEW_TMP,0755); } fp_new=fopen(FILE_NEW_TMP, "a"); if(fp_new) { fprintf(fp_new,"%s\n",path); } else { LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno)); return CHECK_ADD_NEW_FILE; } checkResult=false; fclose(fp_info); fclose(fp_new); return CHECK_ADD_NEW_FILE; } } } else { LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); return CHECK_PASS; } static bool dir_check( char const*dir) { struct dirent *dp; DIR *d_fd; unsigned int nCS = 0; unsigned char nMd5[MD5_LENGTH]; char newdir[FILENAME_MAX]; int find_pass=0; if ((d_fd = opendir(dir)) == NULL) { if(strcmp(dir,"/system/")==0) { LOGE("open system dir fail,please check!\n"); return false; } else { LOGE("%s is selinux protected,this dir just pass!\n",dir); if(clear_selinux_dir(dir) != 0) { LOGE("clear selinux dir fail\n"); } return false; } } while ((dp = readdir(d_fd)) != NULL) { find_pass = 0; if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0) continue; if (dp->d_type == DT_DIR){ memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir); strcat(newdir, dp->d_name); strcat(newdir, "/"); if(dir_check(newdir) == false){ //closedir(d_fd); continue; //return false; } }else{ int idx = 0; int idy = 0; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir); strcat(newdir, dp->d_name); for(; idx < sizeof(file_to_check)/sizeof(char*); idx++){ if(strcmp(dp->d_name, file_to_check[idx]) == 0){ root_to_check[idx]=1; ui->Print("Dir_check---found a root File: %s\n",dp->d_name); } } for(; idy < sizeof(file_to_pass)/sizeof(char*); idy++){ if(strcmp(dp->d_name, file_to_pass[idy]) == 0){ printf("Dir_check---found a file to pass: %s\n",dp->d_name); find_pass=1; break; } } if(find_pass==0) { ui->Print("scanning **** %s ****\n",dp->d_name); if(0 == file_crc_check(newdir, &nCS, nMd5)){ if (check_reall_file(newdir, nCS, (char*)nMd5)!=0) { LOGE("Error:%s check fail\n",newdir); checkResult = false; } check_file_result->file_number_to_check++; }else if(1 == file_crc_check(newdir, &nCS, nMd5)) { LOGE("%s could be selinux protected\n",newdir); //closedir(d_fd) if (clear_selinux_file(newdir)!=0) { LOGE("Error:%s is a selinux file,clear bit fail\n",newdir); checkResult = false; } check_file_result->file_number_to_check++; continue; } else { LOGE("check %s error\n",newdir); closedir(d_fd); return false; } } } } closedir(d_fd); return true; } static int load_zip_file() { const char *FILE_COUNT_ZIP="file_count"; const char *CRC_COUNT_ZIP="crc_count"; const char *DOUBLE_DYW_CHECK="doub_check"; const char *ZIP_FILE_ROOT="/system/data/recovery_rootcheck"; //const char *ZIP_FILE_ROOT_TEMP="/system/recovery_rootcheck"; ZipArchive zip; //struct stat statbuf; int ret; int err=1; MemMapping map; if (sysMapFile(ZIP_FILE_ROOT, &map) != 0) { LOGE("failed to map file %s\n", ZIP_FILE_ROOT); return INSTALL_CORRUPT; } //ret=stat(ZIP_FILE_ROOT_TEMP,&statbuf); printf("load zip file from %s\n",ZIP_FILE_ROOT); err = mzOpenZipArchive(map.addr, map.length, &zip); if (err != 0) { LOGE("Can't open %s\n(%s)\n", ZIP_FILE_ROOT, err != -1 ? strerror(err) : "bad"); sysReleaseMap(&map); return CHECK_NO_KEY; } const ZipEntry* file_count = mzFindZipEntry(&zip,FILE_COUNT_ZIP); if (file_count== NULL) { mzCloseZipArchive(&zip); sysReleaseMap(&map); return CHECK_NO_KEY; } unlink(FILE_COUNT_TMP); int fd_file = creat(FILE_COUNT_TMP, 0755); if (fd_file< 0) { mzCloseZipArchive(&zip); LOGE("Can't make %s:%s\n", FILE_COUNT_TMP, strerror(errno)); sysReleaseMap(&map); return CHECK_NO_KEY; } bool ok_file= mzExtractZipEntryToFile(&zip, file_count, fd_file); close(fd_file); if (!ok_file) { LOGE("Can't copy %s\n", FILE_COUNT_ZIP); sysReleaseMap(&map); return CHECK_NO_KEY; } else { printf("%s is ok\n", FILE_COUNT_TMP); } const ZipEntry* crc_count = mzFindZipEntry(&zip,CRC_COUNT_ZIP); if (crc_count== NULL) { mzCloseZipArchive(&zip); sysReleaseMap(&map); return CHECK_NO_KEY; } unlink(CRC_COUNT_TMP); int fd_crc = creat(CRC_COUNT_TMP, 0755); if (fd_crc< 0) { mzCloseZipArchive(&zip); LOGE("Can't make %s\n", CRC_COUNT_TMP); sysReleaseMap(&map); return CHECK_NO_KEY; } bool ok_crc = mzExtractZipEntryToFile(&zip, crc_count, fd_crc); close(fd_crc); if (!ok_crc) { LOGE("Can't copy %s\n", CRC_COUNT_ZIP); sysReleaseMap(&map); return CHECK_NO_KEY; } else { printf("%s is ok\n", CRC_COUNT_TMP); } const ZipEntry* dcheck_crc = mzFindZipEntry(&zip,DOUBLE_DYW_CHECK); if (dcheck_crc== NULL) { mzCloseZipArchive(&zip); sysReleaseMap(&map); return CHECK_NO_KEY; } unlink(DYW_DOUB_TMP); int fd_d = creat(DYW_DOUB_TMP, 0755); if (fd_d< 0) { mzCloseZipArchive(&zip); LOGE("Can't make %s\n", DYW_DOUB_TMP); sysReleaseMap(&map); return CHECK_NO_KEY; } bool ok_d = mzExtractZipEntryToFile(&zip, dcheck_crc, fd_d); close(fd_d); if (!ok_d) { LOGE("Can't copy %s\n", DOUBLE_DYW_CHECK); sysReleaseMap(&map); return CHECK_NO_KEY; } else { printf("%s is ok\n", DYW_DOUB_TMP); } mzCloseZipArchive(&zip); sysReleaseMap(&map); return 0; } static char* decrypt_str(char *source,unsigned int key) { char buf[FILENAME_MAX]={0}; memset(buf, 0, FILENAME_MAX); int i; int j=0; int len=strlen(source); if(len%2 != 0) { printf("Error,sourcr encrypt filename length is odd"); return NULL; } int len2=len/2; for(i=0;i<len2;i++) { char c1=source[j]; char c2=source[j+1]; j=j+2; c1=c1-65; c2=c2-65; char b2=c2*16+c1; char b1=b2^key; buf[i]=b1; } buf[len2]='\0'; memset(source,0,len); strcpy(source,buf); return source; } static int load_image_encrypt_file() { FILE *fp_info; FILE *fp_tmp; char buf[512]; char p_name[512]; char p_img_size[128]; char *p_cmp_name=NULL; char p_crc[256]; char p_md5[256]; int p_number; int p_file_number; fp_info = fopen(CRC_COUNT_TMP, "r"); fp_tmp = fopen(TEMP_IMAGE_IN_RAM,"w+"); if(fp_tmp) { if(fp_info) { while (fgets(buf, sizeof(buf), fp_info)) { memset(p_md5, 0, sizeof(p_md5)); if (sscanf(buf,"%s %s %s %s",p_name,p_img_size,p_crc,p_md5) == 4) { char *p_pname=decrypt_str(p_name,key); char *p_pcrc=decrypt_str(p_crc,key); char *p_pmd5=decrypt_str(p_md5,key); char *p_pimgsize=decrypt_str(p_img_size,key); unsigned long crc; crc = strtoul(p_pcrc, (char **)NULL, 10); unsigned long img_size = strtoul(p_pimgsize, (char **)NULL, 10); //printf("p_pname %s,p_img_size %d,rcrc %u, p_pmd5 %s\n",p_pname,img_size,rcrc, p_pmd5); fprintf(fp_tmp,"%s\t%lu\t%lu\t%s\n",p_pname,img_size, crc, p_pmd5); } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return -1; } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); fclose(fp_tmp); return 0; } static int load_system_encrypt_file() { FILE *fp_info; FILE *fp_tmp; char buf[512]; char p_name[512]; char *p_cmp_name=NULL; char p_crc[256]; char p_md5[256]; int p_number; int p_file_number; fp_info = fopen(FILE_COUNT_TMP, "r"); fp_tmp = fopen(TEMP_FILE_IN_RAM,"w+"); if(fp_tmp) { if(fp_info) { if (fgets(buf, sizeof(buf), fp_info) != NULL) { if (sscanf(buf, "%d %s %d", &p_number,p_name,&p_file_number) == 3) { fprintf(fp_tmp,"%d\t%s\t%d\n",p_number,p_name,p_file_number); } while (fgets(buf, sizeof(buf), fp_info)) { memset(p_md5, 0, sizeof(p_md5)); if (sscanf(buf, "%d %s %s %s", &p_number,p_name,p_crc,p_md5) == 4) { char *p_pname=decrypt_str(p_name,key); char *p_pcrc=decrypt_str(p_crc,key); char *p_pmd5=decrypt_str(p_md5,key); unsigned long crc; crc = strtoul(p_pcrc, (char **)NULL, 10); //printf("p_pname:%s, crc32:%s %lu %d %d %d\n", p_pname, p_pcrc, crc, sizeof(long), sizeof(long long), sizeof(unsigned int)); fprintf(fp_tmp,"%d\t%s\t%lu\t%s\n",p_number,p_pname,crc, p_pmd5); } } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return -1; } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); fclose(fp_tmp); return 0; } static bool image_crc_check( char const*dir) { struct dirent *dp; DIR *d_fd; unsigned int nCS = 0; unsigned char nMd5[MD5_LENGTH]; if ((d_fd = opendir(dir)) == NULL) { LOGE("dir_check-<<<< %s not dir\n",dir); return false; } while ((dp = readdir(d_fd)) != NULL) { if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0) continue; if (dp->d_type == DT_DIR){ char newdir[FILENAME_MAX]={0}; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir); strcat(newdir, dp->d_name); strcat(newdir, "/"); if(dir_check(newdir) == false){ closedir(d_fd); return false; } }else{ char newdir[FILENAME_MAX]; int idx = 0; int idy = 0; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir); strcat(newdir, dp->d_name); if(0 == file_crc_check(newdir, &nCS, nMd5)){ #ifdef MTK_ROOT_PRELOADER_CHECK if(strstr(newdir,"preloader")!=NULL) { computed_checksum[PRELOADER].crc32=nCS; memcpy(computed_checksum[PRELOADER].md5, nMd5, MD5_LENGTH); } #endif if(strstr(newdir,"bootimg")!=NULL) { computed_checksum[BOOTIMG].crc32=nCS; memcpy(computed_checksum[BOOTIMG].md5, nMd5, MD5_LENGTH); } if(strstr(newdir,"uboot")!=NULL) { computed_checksum[UBOOT].crc32=nCS; memcpy(computed_checksum[UBOOT].md5, nMd5, MD5_LENGTH); } if(strstr(newdir,"recovery")!=NULL) { computed_checksum[RECOVERYIMG].crc32=nCS; memcpy(computed_checksum[RECOVERYIMG].md5, nMd5, MD5_LENGTH); } if(strstr(newdir,"logo")!=NULL) { computed_checksum[LOGO].crc32=nCS; memcpy(computed_checksum[LOGO].md5, nMd5, MD5_LENGTH); } }else{ printf("%s function fail\n",__func__); closedir(d_fd); return false; } } } closedir(d_fd); return true; } static int list_root_file() { int idx=0; for(;idx<MAX_ROOT_TO_CHECK;idx++) { if(root_to_check[idx]==1) { check_file_result->n_rootfile+=1; ui->Print("found a root file,%s\n",file_to_check[idx]); } } return 0; } static int list_lost_file(int number) { FILE *fp_info; char buf[512]; char p_name[256]; char p_md[256]; int found=0; char *p_cmp_name=NULL; unsigned int p_size; int p_number; int idy=0; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if (fgets(buf, sizeof(buf), fp_info) != NULL) { while (fgets(buf, sizeof(buf), fp_info)) { if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { if(p_number==number) { p_cmp_name=strstr(p_name,"/system"); for(; idy < sizeof(file_to_pass)/sizeof(char*); idy++) { if(strstr(p_cmp_name, file_to_pass[idy]) != NULL) { printf("list lost file---found a file to pass: %s\n",p_cmp_name); //checkResult=true; //break; return 0; } } if(p_cmp_name != NULL) { check_file_result->n_lostfile+=1; ui->Print("Error:%s is lost\n",p_cmp_name); checkResult=false; } else { check_file_result->n_lostfile+=1; ui->Print("Error:%s is lost\n",p_name); checkResult=false; } found=1; break; } } } if(!found) { LOGE("Error:not found a lost file\n"); fclose(fp_info); return -1; } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return -1; } fclose(fp_info); return 0; } static int image_copy( const char* path,int loop,const char* tem_name) { unsigned int nCS=0; char *temp_file; char buf[1024]; int rRead_count = 0; int idx = 0; int sum=0; if (path == NULL ){ LOGE("image_copy-> %s is null", path); return -1; } if (ensure_path_mounted(IMAGE_LOAD_PATH) != 0) { LOGE("Can't mount %s\n", IMAGE_LOAD_PATH); return -1; } if (mkdir(IMAGE_LOAD_PATH, 0700) != 0) { if (errno != EEXIST) { LOGE("Can't mkdir %s (%s)\n", IMAGE_LOAD_PATH, strerror(errno)); return -1; } } struct stat st; if (stat(IMAGE_LOAD_PATH, &st) != 0) { LOGE("failed to stat %s (%s)\n", IMAGE_LOAD_PATH, strerror(errno)); return -1; } if (!S_ISDIR(st.st_mode)) { LOGE("%s isn't a directory\n", IMAGE_LOAD_PATH); return -1; } if ((st.st_mode & 0777) != 0700) { LOGE("%s has perms %o\n", IMAGE_LOAD_PATH, st.st_mode); return -1; } if (st.st_uid != 0) { LOGE("%s owned by %lu; not root\n", IMAGE_LOAD_PATH, st.st_uid); return -1; } char copy_path[FILENAME_MAX]; memset(copy_path, 0, FILENAME_MAX); strcpy(copy_path, IMAGE_LOAD_PATH); strcat(copy_path, "/temp_"); strcat(copy_path, tem_name); char* buffer = (char*)malloc(1024); if (buffer == NULL) { LOGE("Failed to allocate buffer\n"); return -1; } size_t read; FILE* fin = fopen(path, "rb"); if (fin == NULL) { LOGE("Failed to open %s (%s)\n", path, strerror(errno)); return -1; } FILE* fout = fopen(copy_path, "wb"); if (fout == NULL) { LOGE("Failed to open %s (%s)\n", copy_path, strerror(errno)); return -1; } while ((read = fread(buffer, 1, 1024, fin)) > 0) { sum+=read; if(sum<loop) { if (fwrite(buffer, 1, read, fout) != read) { LOGE("Short write of %s (%s)\n", copy_path, strerror(errno)); return -1; } } else { int read_end=read+loop-sum; if (fwrite(buffer, 1, read_end, fout) != read_end) { LOGE("Short write of %s (%s)\n", copy_path, strerror(errno)); return -1; } break; } } free(buffer); if (fclose(fout) != 0) { LOGE("Failed to close %s (%s)\n", copy_path, strerror(errno)); return -1; } if (fclose(fin) != 0) { LOGE("Failed to close %s (%s)\n", path, strerror(errno)); return -1; } return 0; } static int list_new_file() { FILE *fp_new; struct stat statbuf; char buf[256]; if(access(FILE_NEW_TMP,0)==-1) { printf("%s is not exist\n",FILE_NEW_TMP); return 0; } fp_new= fopen(FILE_NEW_TMP, "r"); if(fp_new) { while (fgets(buf, sizeof(buf), fp_new)) { ui->Print("Error:%s is new ",buf); int ret=stat(buf,&statbuf); /* if(ret != 0) { LOGE("Error:%s is not exist\n",buf); } */ time_t modify=statbuf.st_mtime; ui->Print("it is created on %s\n", ctime(&modify)); } } else { LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno)); return -1; } fclose(fp_new); return 0; } static bool remove_check_file(const char *file_name) { int ret = 0; ret = unlink(file_name); if (ret == 0) return true; if (ret < 0 && errno == ENOENT) return true; return false; } static bool remove_check_dir(const char *dir_name) { struct dirent *dp; DIR *d_fd; if ((d_fd = opendir(dir_name)) == NULL) { LOGE("dir_check-<<<< %s not dir\n",dir_name); return false; } while ((dp = readdir(d_fd)) != NULL) { if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0) continue; if (dp->d_type == DT_DIR){ char newdir[FILENAME_MAX]={0}; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir_name); strcat(newdir, dp->d_name); strcat(newdir, "/"); if(remove_check_dir(newdir) == false){ closedir(d_fd); return false; } }else{ char newdir[FILENAME_MAX]; int idx = 0; int idy = 0; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir_name); strcat(newdir, dp->d_name); const char* to_remove_file; to_remove_file=newdir; if(!remove_check_file(to_remove_file)) { LOGE("Error:unlink %s fail\n",to_remove_file); } } } return true; } static int get_image_info() { FILE *fp_info; char buf[512]; char p_name[32]; unsigned int p_size; unsigned int p_c; unsigned char p_crc[MD5_LENGTH*2]; memset(expected_checksum, 0, sizeof(expected_checksum)); fp_info = fopen(TEMP_IMAGE_IN_RAM, "r"); if(fp_info) { while (fgets(buf, sizeof(buf), fp_info)) { memset(p_crc, 0, sizeof(p_crc)); //Z_DEBUG("%d %s\n", __LINE__, buf); if (sscanf(buf, "%s %d %u %s", p_name, &p_size, &p_c, p_crc) == 4) { //Z_DEBUG("%d %s\n", __LINE__, p_crc); hextoi_md5(p_crc); #ifdef MTK_ROOT_PRELOADER_CHECK if (!strcmp(p_name, "preloader.bin")) { expected_checksum[PRELOADER].size = p_size; expected_checksum[PRELOADER].crc32 = p_c; memcpy(expected_checksum[PRELOADER].md5, p_crc, MD5_LENGTH); } #endif if (!strcmp(p_name, "lk.bin")) { expected_checksum[UBOOT].size = p_size; expected_checksum[UBOOT].crc32 = p_c; memcpy(expected_checksum[UBOOT].md5, p_crc, MD5_LENGTH); } if (!strcmp(p_name, "boot.img")) { expected_checksum[BOOTIMG].size = p_size; expected_checksum[BOOTIMG].crc32 = p_c; memcpy(expected_checksum[BOOTIMG].md5, p_crc, MD5_LENGTH); } if (!strcmp(p_name, "recovery.img")) { expected_checksum[RECOVERYIMG].size = p_size; expected_checksum[RECOVERYIMG].crc32 = p_c; memcpy(expected_checksum[RECOVERYIMG].md5, p_crc, MD5_LENGTH); } if (!strcmp(p_name, "logo.bin")) { expected_checksum[LOGO].size = p_size; expected_checksum[LOGO].crc32 = p_c; memcpy(expected_checksum[LOGO].md5, p_crc, MD5_LENGTH); } } } } else { printf("%s function fail,open error reason is %s\n",__func__,strerror(errno)); return -1; } fclose(fp_info); return 0; } static int check_file_number_insystem(int file_number) { FILE *fp_info; char buf[512]; char p_name[128]; int p_number; int p_pnumber; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if (fgets(buf, sizeof(buf), fp_info) != NULL) { if (sscanf(buf, "%d %s %d", &p_pnumber,p_name, &p_number)== 3) { printf("p_name:%s,p_number : %d\n",p_name,p_number); if (!strcmp(p_name, "file_number_in_system_dayu")) { check_file_result->expect_file_number=p_number; //printf("func is %s,line is %d,p_number is %d,file_number is %d,n_modfyfile is %d,check_file_result->n_newfile is %d\n",__func__,__LINE__,p_number,file_number,check_file_result->n_modifyfile,check_file_result->n_newfile); #if 0 if((p_number==file_number)&&(check_file_result->n_lostfile==0)&&(check_file_result->n_newfile==0)) { ui->Print("\nSystem Dir File Number Check Pass"); fclose(fp_info); return 0; } else { printf("%s %d p_number:%d file_number:%d check_file_result->n_lostfile:%d check_file_result->n_newfile:%d\n", __func__, __LINE__, p_number, file_number, check_file_result->n_lostfile, check_file_result->n_newfile); ui->Print("\nSystem Dir File Number Check Fail\n"); fclose(fp_info); return CHECK_SYSTEM_FILE_NUM_ERR; } #endif } } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return 1; } fclose(fp_info); return 0; } static void delete_unneed_file() { if(!remove_check_file(TEMP_FILE_IN_RAM)) { LOGE("unlink temp system crc file error\n"); } if(!remove_check_file(TEMP_IMAGE_IN_RAM)) { LOGE("unlink temp image crc file error\n"); } if(!remove_check_file(FILE_NEW_TMP)) { LOGE("unlink temp new file error\n"); } if(!remove_check_file(FILE_COUNT_TMP)) { LOGE("unlink temp new file error\n"); } if(!remove_check_file(DYW_DOUB_TMP)) { LOGE("unlink temp new file error\n"); } if(!remove_check_dir(IMAGE_LOAD_PATH)) { LOGE("unlink temp image dir error\n"); } } static int list_modify_file(int number) { FILE *fp_info; struct stat statbuf; char buf[512]; char p_name[256]; char p_md[256]; int found=0; char *p_cmp_name=NULL; unsigned int p_size; int p_number; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if (fgets(buf, sizeof(buf), fp_info) != NULL) { while (fgets(buf, sizeof(buf), fp_info)) { if (sscanf(buf,"%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { if(p_number==number) { p_cmp_name=strstr(p_name,"/system"); if(p_cmp_name != NULL) { ui->Print("Error:%s has been modified",p_cmp_name); int ret=stat(p_cmp_name,&statbuf); if(ret != 0) { LOGE("Error:%s is not exist\n",p_cmp_name); } time_t modify=statbuf.st_mtime; ui->Print("on %s\n", ctime(&modify)); } else { ui->Print("Error:%s is modifyed\n",p_name); } found=1; break; } } } if(!found) { LOGE("Error:not found a lost file\n"); fclose(fp_info); return -1; } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return -1; } fclose(fp_info); return 0; } static int encrypt_file_doub_check() { char buf[512]; FILE *fp_info; unsigned int file_count_crc; unsigned int crc_count_crc; unsigned int nCS = 0; unsigned char nMd5[MD5_LENGTH]; fp_info = fopen(DYW_DOUB_TMP, "r"); if(fp_info) { if(fgets(buf, sizeof(buf), fp_info) != NULL) { if (sscanf(buf,"%u %u", &file_count_crc,&crc_count_crc) == 2) { check_file_result->file_count_check=file_count_crc; check_file_result->crc_count_check=crc_count_crc; } else { ui->Print("double check file is error\n"); return CHECK_NO_KEY; } } else { ui->Print("double check file is null\n"); return CHECK_NO_KEY; } } else { LOGE("open %s error,error reason is %s\n",DYW_DOUB_TMP,strerror(errno)); return CHECK_NO_KEY; } if(0 == file_crc_check(FILE_COUNT_TMP, &nCS, nMd5)) { if(nCS!=check_file_result->file_count_check) { ui->Print("file count double check fail\n"); return CHECK_NO_KEY; } } if(0 == file_crc_check(CRC_COUNT_TMP, &nCS, nMd5)) { if(nCS != check_file_result->crc_count_check) { ui->Print("crc count double check fail\n"); return CHECK_NO_KEY; } } return 0; } int root_check(){ ui->SetBackground(RecoveryUI::ERASING); ui->SetProgressType(RecoveryUI::INDETERMINATE); ui->Print("Now check begins, please wait.....\n"); int per,cper; #ifdef MTK_ROOT_NORMAL_CHECK printf("use normal check\n"); #endif #ifdef MTK_ROOT_ADVANCE_CHECK printf("use advance check\n"); #endif check_file_result=(struct last_check_file*)malloc(sizeof(last_check_file)); if(ensure_path_mounted(SYSTEM_ROOT) != 0) { ui->Print("--mount System fail \n"); } memset(check_file_result,0,sizeof(last_check_file)); memset(check_map,0xff,sizeof(check_map)); memset(check_modify,0xff,sizeof(check_modify)); if(load_zip_file()) { ui->Print("load source zip file fail\n"); return CHECK_NO_KEY; } if(load_system_encrypt_file()) { ui->Print("load system encrypt file fail\n"); return CHECK_NO_KEY; } if(load_image_encrypt_file()) { ui->Print("load partition encrypt file fail\n"); return CHECK_NO_KEY; } if(encrypt_file_doub_check()) { ui->Print("encrypt file double check fail\n"); return CHECK_NO_KEY; } if(false == dir_check(SYSTEM_ROOT)) { checkResult = false; } check_file_result->file_number_to_check+=1; ui->Print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); if (check_file_number_insystem(check_file_result->file_number_to_check)!=0) { checkResult=false; } if(list_new_file()) { LOGE("list new file error\n"); } if(list_root_file()) { LOGE("list root file error\n"); } for(cper=0;cper<check_file_result->file_number_to_check-1;cper++) { if(test_bit(cper)) { //checkResult=false; list_lost_file(cper); } } for(cper=0;cper<check_file_result->file_number_to_check-1;cper++) { if(!test_bit_m(cper)) { checkResult=false; list_modify_file(cper); } } if(check_file_result->n_newfile) { ui->Print("Error:found %d new files\n",check_file_result->n_newfile); } if(check_file_result->n_lostfile) { ui->Print("Error:found %d lost files\n",check_file_result->n_lostfile); } if(check_file_result->n_modifyfile) { ui->Print("Error:found %d modified files\n",check_file_result->n_modifyfile); } if(check_file_result->n_rootfile) { ui->Print("Error:found %d root files\n",check_file_result->n_rootfile); } if(ensure_path_unmounted(SYSTEM_ROOT) != 0) { LOGE("root_check function--unmount System fail \n"); } if(get_image_info()) { checkResult=false; } int i = 0; if(!is_support_gpt_c()) { printf("this is not gpt version"); for(i=0;i<PART_MAX;i++) { if(0 == image_copy(img_array[i].img_devname,expected_checksum[i].size,img_array[i].img_printname)) { printf("copy %s done\n", img_array[i].img_printname); } else { printf("copy %s error\n", img_array[i].img_printname); checkResult = false; } } } else { printf("this is gpt version"); for(i=0;i<PART_MAX;i++) { if(0 == image_copy(img_array_gpt[i].img_devname,expected_checksum[i].size,img_array_gpt[i].img_printname)) { printf("copy %s done\n", img_array_gpt[i].img_printname); } else { printf("copy %s error\n", img_array_gpt[i].img_printname); checkResult = false; } } } if(false == image_crc_check(IMAGE_LOAD_PATH)) { checkResult = false; return CHECK_IMAGE_ERR; } for(i=0;i<PART_MAX;i++) { #ifdef MTK_ROOT_NORMAL_CHECK if((expected_checksum[i].crc32==computed_checksum[i].crc32)&&(computed_checksum[i].crc32 != 0)) { printf("\n%s NORMAL check Pass", img_array[i].img_printname); } else { if(i==1) { checkResult=false; ui->Print("Error:%s NORMAL check Fail\n",img_array[i].img_printname); printf("except check sum is %u,compute checksum is %u\n",expected_checksum[i].crc32,computed_checksum[i].crc32); } } #endif #ifdef MTK_ROOT_ADVANCE_CHECK if(memcmp(expected_checksum[i].md5, computed_checksum[i].md5, MD5_LENGTH)==0) { printf("\n%s ADVANCE check Pass", img_array[i].img_printname); } else { if(i==1) { checkResult=false; ui->Print("Error:%s ADVANCE check Fail\n", img_array[i].img_printname); #if 1 char *nMd5 = (char*)expected_checksum[i].md5; char *p_md = (char*)computed_checksum[i].md5; int i; printf("e:"); for(i=0;i<16;i++) { printf("%02x",nMd5[i]); } printf("\n"); printf("c:"); for(i=0;i<16;i++) { printf("%02x", p_md[i]); } printf("\n"); #endif } } #endif } int m_root_check=0; for(;m_root_check<MAX_ROOT_TO_CHECK;m_root_check++) { root_to_check[m_root_check]=0; } delete_unneed_file(); free(check_file_result); if(checkResult) { return CHECK_PASS; } else { checkResult=true; return CHECK_FAIL; } }
MTK6580/walkie-talkie
ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/bootable/recovery/root_check.cpp
C++
gpl-3.0
49,261
/* * @file TestXMLNode.java * @brief XMLNode unit tests * * @author Akiya Jouraku (Java conversion) * @author Michael Hucka <[email protected]> * * $Id: TestXMLNode.java 11442 2010-07-09 02:23:35Z mhucka $ * $HeadURL: https://sbml.svn.sourceforge.net/svnroot/sbml/trunk/libsbml/src/bindings/java/test/org/sbml/libsbml/test/xml/TestXMLNode.java $ * * ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ====== * * DO NOT EDIT THIS FILE. * * This file was generated automatically by converting the file located at * src/xml/test/TestXMLNode.c * using the conversion program dev/utilities/translateTests/translateTests.pl. * Any changes made here will be lost the next time the file is regenerated. * * ----------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright 2005-2010 California Institute of Technology. * Copyright 2002-2005 California Institute of Technology and * Japan Science and Technology Corporation. * * 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. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html * ----------------------------------------------------------------------------- */ package org.sbml.libsbml.test.xml; import org.sbml.libsbml.*; import java.io.File; import java.lang.AssertionError; public class TestXMLNode { static void assertTrue(boolean condition) throws AssertionError { if (condition == true) { return; } throw new AssertionError(); } static void assertEquals(Object a, Object b) throws AssertionError { if ( (a == null) && (b == null) ) { return; } else if ( (a == null) || (b == null) ) { throw new AssertionError(); } else if (a.equals(b)) { return; } throw new AssertionError(); } static void assertNotEquals(Object a, Object b) throws AssertionError { if ( (a == null) && (b == null) ) { throw new AssertionError(); } else if ( (a == null) || (b == null) ) { return; } else if (a.equals(b)) { throw new AssertionError(); } } static void assertEquals(boolean a, boolean b) throws AssertionError { if ( a == b ) { return; } throw new AssertionError(); } static void assertNotEquals(boolean a, boolean b) throws AssertionError { if ( a != b ) { return; } throw new AssertionError(); } static void assertEquals(int a, int b) throws AssertionError { if ( a == b ) { return; } throw new AssertionError(); } static void assertNotEquals(int a, int b) throws AssertionError { if ( a != b ) { return; } throw new AssertionError(); } public void test_XMLNode_attribute_add_remove() { XMLTriple triple = new XMLTriple("test","",""); XMLAttributes attr = new XMLAttributes(); XMLNode node = new XMLNode(triple,attr); XMLTriple xt1 = new XMLTriple("name1", "http://name1.org/", "p1"); XMLTriple xt2 = new XMLTriple("name2", "http://name2.org/", "p2"); XMLTriple xt3 = new XMLTriple("name3", "http://name3.org/", "p3"); XMLTriple xt1a = new XMLTriple("name1", "http://name1a.org/", "p1a"); XMLTriple xt2a = new XMLTriple("name2", "http://name2a.org/", "p2a"); node.addAttr( "name1", "val1", "http://name1.org/", "p1"); node.addAttr(xt2, "val2"); assertTrue( node.getAttributesLength() == 2 ); assertTrue( node.isAttributesEmpty() == false ); assertTrue( !node.getAttrName(0).equals( "name1") == false ); assertTrue( !node.getAttrValue(0).equals( "val1" ) == false ); assertTrue( !node.getAttrURI(0).equals( "http://name1.org/") == false ); assertTrue( !node.getAttrPrefix(0).equals( "p1" ) == false ); assertTrue( !node.getAttrName(1).equals( "name2") == false ); assertTrue( !node.getAttrValue(1).equals( "val2" ) == false ); assertTrue( !node.getAttrURI(1).equals( "http://name2.org/") == false ); assertTrue( !node.getAttrPrefix(1).equals( "p2" ) == false ); assertTrue( node.getAttrValue( "name1").equals("") == true ); assertTrue( node.getAttrValue( "name2").equals("") == true ); assertTrue( !node.getAttrValue( "name1", "http://name1.org/").equals( "val1" ) == false ); assertTrue( !node.getAttrValue( "name2", "http://name2.org/").equals( "val2" ) == false ); assertTrue( !node.getAttrValue(xt1).equals( "val1" ) == false ); assertTrue( !node.getAttrValue(xt2).equals( "val2" ) == false ); assertTrue( node.hasAttr(-1) == false ); assertTrue( node.hasAttr(2) == false ); assertTrue( node.hasAttr(0) == true ); assertTrue( node.hasAttr( "name1", "http://name1.org/") == true ); assertTrue( node.hasAttr( "name2", "http://name2.org/") == true ); assertTrue( node.hasAttr( "name3", "http://name3.org/") == false ); assertTrue( node.hasAttr(xt1) == true ); assertTrue( node.hasAttr(xt2) == true ); assertTrue( node.hasAttr(xt3) == false ); node.addAttr( "noprefix", "val3"); assertTrue( node.getAttributesLength() == 3 ); assertTrue( node.isAttributesEmpty() == false ); assertTrue( !node.getAttrName(2).equals( "noprefix") == false ); assertTrue( !node.getAttrValue(2).equals( "val3" ) == false ); assertTrue( node.getAttrURI(2).equals("") == true ); assertTrue( node.getAttrPrefix(2).equals("") == true ); assertTrue( !node.getAttrValue( "noprefix").equals( "val3" ) == false ); assertTrue( !node.getAttrValue( "noprefix", "").equals( "val3" ) == false ); assertTrue( node.hasAttr( "noprefix" ) == true ); assertTrue( node.hasAttr( "noprefix", "") == true ); node.addAttr(xt1, "mval1"); node.addAttr( "name2", "mval2", "http://name2.org/", "p2"); assertTrue( node.getAttributesLength() == 3 ); assertTrue( node.isAttributesEmpty() == false ); assertTrue( !node.getAttrName(0).equals( "name1") == false ); assertTrue( !node.getAttrValue(0).equals( "mval1") == false ); assertTrue( !node.getAttrURI(0).equals( "http://name1.org/") == false ); assertTrue( !node.getAttrPrefix(0).equals( "p1" ) == false ); assertTrue( !node.getAttrName(1).equals( "name2" ) == false ); assertTrue( !node.getAttrValue(1).equals( "mval2" ) == false ); assertTrue( !node.getAttrURI(1).equals( "http://name2.org/") == false ); assertTrue( !node.getAttrPrefix(1).equals( "p2" ) == false ); assertTrue( node.hasAttr(xt1) == true ); assertTrue( node.hasAttr( "name1", "http://name1.org/") == true ); node.addAttr( "noprefix", "mval3"); assertTrue( node.getAttributesLength() == 3 ); assertTrue( node.isAttributesEmpty() == false ); assertTrue( !node.getAttrName(2).equals( "noprefix") == false ); assertTrue( !node.getAttrValue(2).equals( "mval3" ) == false ); assertTrue( node.getAttrURI(2).equals("") == true ); assertTrue( node.getAttrPrefix(2).equals("") == true ); assertTrue( node.hasAttr( "noprefix") == true ); assertTrue( node.hasAttr( "noprefix", "") == true ); node.addAttr(xt1a, "val1a"); node.addAttr(xt2a, "val2a"); assertTrue( node.getAttributesLength() == 5 ); assertTrue( !node.getAttrName(3).equals( "name1") == false ); assertTrue( !node.getAttrValue(3).equals( "val1a") == false ); assertTrue( !node.getAttrURI(3).equals( "http://name1a.org/") == false ); assertTrue( !node.getAttrPrefix(3).equals( "p1a") == false ); assertTrue( !node.getAttrName(4).equals( "name2") == false ); assertTrue( !node.getAttrValue(4).equals( "val2a") == false ); assertTrue( !node.getAttrURI(4).equals( "http://name2a.org/") == false ); assertTrue( !node.getAttrPrefix(4).equals( "p2a") == false ); assertTrue( !node.getAttrValue( "name1", "http://name1a.org/").equals( "val1a" ) == false ); assertTrue( !node.getAttrValue( "name2", "http://name2a.org/").equals( "val2a" ) == false ); assertTrue( !node.getAttrValue(xt1a).equals( "val1a" ) == false ); assertTrue( !node.getAttrValue(xt2a).equals( "val2a" ) == false ); node.removeAttr(xt1a); node.removeAttr(xt2a); assertTrue( node.getAttributesLength() == 3 ); node.removeAttr( "name1", "http://name1.org/"); assertTrue( node.getAttributesLength() == 2 ); assertTrue( node.isAttributesEmpty() == false ); assertTrue( !node.getAttrName(0).equals( "name2") == false ); assertTrue( !node.getAttrValue(0).equals( "mval2") == false ); assertTrue( !node.getAttrURI(0).equals( "http://name2.org/") == false ); assertTrue( !node.getAttrPrefix(0).equals( "p2") == false ); assertTrue( !node.getAttrName(1).equals( "noprefix") == false ); assertTrue( !node.getAttrValue(1).equals( "mval3") == false ); assertTrue( node.getAttrURI(1).equals("") == true ); assertTrue( node.getAttrPrefix(1).equals("") == true ); assertTrue( node.hasAttr( "name1", "http://name1.org/") == false ); node.removeAttr(xt2); assertTrue( node.getAttributesLength() == 1 ); assertTrue( node.isAttributesEmpty() == false ); assertTrue( !node.getAttrName(0).equals( "noprefix") == false ); assertTrue( !node.getAttrValue(0).equals( "mval3") == false ); assertTrue( node.getAttrURI(0).equals("") == true ); assertTrue( node.getAttrPrefix(0).equals("") == true ); assertTrue( node.hasAttr(xt2) == false ); assertTrue( node.hasAttr( "name2", "http://name2.org/") == false ); node.removeAttr( "noprefix"); assertTrue( node.getAttributesLength() == 0 ); assertTrue( node.isAttributesEmpty() == true ); assertTrue( node.hasAttr( "noprefix" ) == false ); assertTrue( node.hasAttr( "noprefix", "") == false ); node = null; xt1 = null; xt2 = null; xt3 = null; xt1a = null; xt2a = null; triple = null; attr = null; } public void test_XMLNode_attribute_set_clear() { XMLTriple triple = new XMLTriple("test","",""); XMLAttributes attr = new XMLAttributes(); XMLNode node = new XMLNode(triple,attr); XMLAttributes nattr = new XMLAttributes(); XMLTriple xt1 = new XMLTriple("name1", "http://name1.org/", "p1"); XMLTriple xt2 = new XMLTriple("name2", "http://name2.org/", "p2"); XMLTriple xt3 = new XMLTriple("name3", "http://name3.org/", "p3"); XMLTriple xt4 = new XMLTriple("name4", "http://name4.org/", "p4"); XMLTriple xt5 = new XMLTriple("name5", "http://name5.org/", "p5"); nattr.add(xt1, "val1"); nattr.add(xt2, "val2"); nattr.add(xt3, "val3"); nattr.add(xt4, "val4"); nattr.add(xt5, "val5"); node.setAttributes(nattr); assertTrue( node.getAttributesLength() == 5 ); assertTrue( node.isAttributesEmpty() == false ); assertTrue( !node.getAttrName(0).equals( "name1") == false ); assertTrue( !node.getAttrValue(0).equals( "val1" ) == false ); assertTrue( !node.getAttrURI(0).equals( "http://name1.org/") == false ); assertTrue( !node.getAttrPrefix(0).equals( "p1" ) == false ); assertTrue( !node.getAttrName(1).equals( "name2") == false ); assertTrue( !node.getAttrValue(1).equals( "val2" ) == false ); assertTrue( !node.getAttrURI(1).equals( "http://name2.org/") == false ); assertTrue( !node.getAttrPrefix(1).equals( "p2" ) == false ); assertTrue( !node.getAttrName(2).equals( "name3") == false ); assertTrue( !node.getAttrValue(2).equals( "val3" ) == false ); assertTrue( !node.getAttrURI(2).equals( "http://name3.org/") == false ); assertTrue( !node.getAttrPrefix(2).equals( "p3" ) == false ); assertTrue( !node.getAttrName(3).equals( "name4") == false ); assertTrue( !node.getAttrValue(3).equals( "val4" ) == false ); assertTrue( !node.getAttrURI(3).equals( "http://name4.org/") == false ); assertTrue( !node.getAttrPrefix(3).equals( "p4" ) == false ); assertTrue( !node.getAttrName(4).equals( "name5") == false ); assertTrue( !node.getAttrValue(4).equals( "val5" ) == false ); assertTrue( !node.getAttrURI(4).equals( "http://name5.org/") == false ); assertTrue( !node.getAttrPrefix(4).equals( "p5" ) == false ); XMLTriple ntriple = new XMLTriple("test2","http://test2.org/","p2"); node.setTriple(ntriple); assertTrue( !node.getName().equals( "test2") == false ); assertTrue( !node.getURI().equals( "http://test2.org/") == false ); assertTrue( !node.getPrefix().equals( "p2") == false ); node.clearAttributes(); assertTrue( node.getAttributesLength() == 0 ); assertTrue( node.isAttributesEmpty() != false ); triple = null; ntriple = null; node = null; attr = null; nattr = null; xt1 = null; xt2 = null; xt3 = null; xt4 = null; xt5 = null; } public void test_XMLNode_convert() { String xmlstr = "<annotation>\n" + " <test xmlns=\"http://test.org/\" id=\"test\">test</test>\n" + "</annotation>"; XMLNode node; XMLNode child, gchild; XMLAttributes attr; XMLNamespaces ns; node = XMLNode.convertStringToXMLNode(xmlstr,null); child = node.getChild(0); gchild = child.getChild(0); attr = child.getAttributes(); ns = child.getNamespaces(); assertTrue( !node.getName().equals( "annotation") == false ); assertTrue( !child.getName().equals("test" ) == false ); assertTrue( !gchild.getCharacters().equals("test" ) == false ); assertTrue( !attr.getName(0).equals( "id" ) == false ); assertTrue( !attr.getValue(0).equals( "test" ) == false ); assertTrue( !ns.getURI(0).equals( "http://test.org/" ) == false ); assertTrue( ns.getPrefix(0).equals("") == true ); String toxmlstring = node.toXMLString(); assertTrue( !toxmlstring.equals(xmlstr) == false ); node = null; } public void test_XMLNode_convert_dummyroot() { String xmlstr_nodummy1 = "<notes>\n" + " <p>test</p>\n" + "</notes>"; String xmlstr_nodummy2 = "<html>\n" + " <p>test</p>\n" + "</html>"; String xmlstr_nodummy3 = "<body>\n" + " <p>test</p>\n" + "</body>"; String xmlstr_nodummy4 = "<p>test</p>"; String xmlstr_nodummy5 = "<test1>\n" + " <test2>test</test2>\n" + "</test1>"; String xmlstr_dummy1 = "<p>test1</p><p>test2</p>"; String xmlstr_dummy2 = "<test1>test1</test1><test2>test2</test2>"; XMLNode rootnode; XMLNode child, gchild; XMLAttributes attr; XMLNamespaces ns; String toxmlstring; rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy1,null); assertTrue( rootnode.getNumChildren() == 1 ); child = rootnode.getChild(0); gchild = child.getChild(0); assertTrue( !rootnode.getName().equals( "notes") == false ); assertTrue( !child.getName().equals("p" ) == false ); assertTrue( !gchild.getCharacters().equals("test" ) == false ); toxmlstring = rootnode.toXMLString(); assertTrue( !toxmlstring.equals(xmlstr_nodummy1) == false ); rootnode = null; rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy2,null); assertTrue( rootnode.getNumChildren() == 1 ); child = rootnode.getChild(0); gchild = child.getChild(0); assertTrue( !rootnode.getName().equals( "html") == false ); assertTrue( !child.getName().equals("p" ) == false ); assertTrue( !gchild.getCharacters().equals("test" ) == false ); toxmlstring = rootnode.toXMLString(); assertTrue( !toxmlstring.equals(xmlstr_nodummy2) == false ); rootnode = null; rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy3,null); assertTrue( rootnode.getNumChildren() == 1 ); child = rootnode.getChild(0); gchild = child.getChild(0); assertTrue( !rootnode.getName().equals( "body") == false ); assertTrue( !child.getName().equals("p" ) == false ); assertTrue( !gchild.getCharacters().equals("test" ) == false ); toxmlstring = rootnode.toXMLString(); assertTrue( !toxmlstring.equals(xmlstr_nodummy3) == false ); rootnode = null; rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy4,null); assertTrue( rootnode.getNumChildren() == 1 ); child = rootnode.getChild(0); assertTrue( !rootnode.getName().equals( "p") == false ); assertTrue( !child.getCharacters().equals("test" ) == false ); toxmlstring = rootnode.toXMLString(); assertTrue( !toxmlstring.equals(xmlstr_nodummy4) == false ); rootnode = null; rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy5,null); assertTrue( rootnode.getNumChildren() == 1 ); child = rootnode.getChild(0); gchild = child.getChild(0); assertTrue( !rootnode.getName().equals( "test1") == false ); assertTrue( !child.getName().equals("test2" ) == false ); assertTrue( !gchild.getCharacters().equals("test" ) == false ); toxmlstring = rootnode.toXMLString(); assertTrue( !toxmlstring.equals(xmlstr_nodummy5) == false ); rootnode = null; rootnode = XMLNode.convertStringToXMLNode(xmlstr_dummy1,null); assertTrue( rootnode.isEOF() == true ); assertTrue( rootnode.getNumChildren() == 2 ); child = rootnode.getChild(0); gchild = child.getChild(0); assertTrue( !child.getName().equals( "p") == false ); assertTrue( !gchild.getCharacters().equals("test1" ) == false ); child = rootnode.getChild(1); gchild = child.getChild(0); assertTrue( !child.getName().equals( "p") == false ); assertTrue( !gchild.getCharacters().equals("test2" ) == false ); toxmlstring = rootnode.toXMLString(); assertTrue( !toxmlstring.equals(xmlstr_dummy1) == false ); rootnode = null; rootnode = XMLNode.convertStringToXMLNode(xmlstr_dummy2,null); assertTrue( rootnode.isEOF() == true ); assertTrue( rootnode.getNumChildren() == 2 ); child = rootnode.getChild(0); gchild = child.getChild(0); assertTrue( !child.getName().equals( "test1") == false ); assertTrue( !gchild.getCharacters().equals("test1" ) == false ); child = rootnode.getChild(1); gchild = child.getChild(0); assertTrue( !child.getName().equals( "test2") == false ); assertTrue( !gchild.getCharacters().equals("test2" ) == false ); toxmlstring = rootnode.toXMLString(); assertTrue( !toxmlstring.equals(xmlstr_dummy2) == false ); rootnode = null; } public void test_XMLNode_create() { XMLNode node = new XMLNode(); assertTrue( node != null ); assertTrue( node.getNumChildren() == 0 ); node = null; node = new XMLNode(); assertTrue( node != null ); XMLNode node2 = new XMLNode(); assertTrue( node2 != null ); node.addChild(node2); assertTrue( node.getNumChildren() == 1 ); XMLNode node3 = new XMLNode(); assertTrue( node3 != null ); node.addChild(node3); assertTrue( node.getNumChildren() == 2 ); node = null; node2 = null; node3 = null; } public void test_XMLNode_createElement() { XMLTriple triple; XMLAttributes attr; XMLNamespaces ns; XMLNode snode, enode, tnode; XMLAttributes cattr; String name = "test"; String uri = "http://test.org/"; String prefix = "p"; String text = "text node"; triple = new XMLTriple(name,uri,prefix); ns = new XMLNamespaces(); attr = new XMLAttributes(); ns.add(uri,prefix); attr.add("id", "value",uri,prefix); snode = new XMLNode(triple,attr,ns); assertTrue( snode != null ); assertTrue( snode.getNumChildren() == 0 ); assertTrue( !snode.getName().equals(name) == false ); assertTrue( !snode.getPrefix().equals(prefix) == false ); assertTrue( !snode.getURI().equals(uri) == false ); assertTrue( snode.isElement() == true ); assertTrue( snode.isStart() == true ); assertTrue( snode.isEnd() == false ); assertTrue( snode.isText() == false ); snode.setEnd(); assertTrue( snode.isEnd() == true ); snode.unsetEnd(); assertTrue( snode.isEnd() == false ); cattr = snode.getAttributes(); assertTrue( cattr != null ); assertTrue( !cattr.getName(0).equals( "id" ) == false ); assertTrue( !cattr.getValue(0).equals( "value") == false ); assertTrue( !cattr.getPrefix(0).equals(prefix) == false ); assertTrue( !cattr.getURI(0).equals(uri) == false ); triple = null; attr = null; ns = null; snode = null; attr = new XMLAttributes(); attr.add("id", "value"); triple = new XMLTriple(name, "", ""); snode = new XMLNode(triple,attr); assertTrue( snode != null ); assertTrue( snode.getNumChildren() == 0 ); assertTrue( !snode.getName().equals( "test") == false ); assertTrue( snode.getPrefix().equals("") == true ); assertTrue( snode.getURI().equals("") == true ); assertTrue( snode.isElement() == true ); assertTrue( snode.isStart() == true ); assertTrue( snode.isEnd() == false ); assertTrue( snode.isText() == false ); cattr = snode.getAttributes(); assertTrue( cattr != null ); assertTrue( !cattr.getName(0).equals( "id" ) == false ); assertTrue( !cattr.getValue(0).equals( "value") == false ); assertTrue( cattr.getPrefix(0).equals("") == true ); assertTrue( cattr.getURI(0).equals("") == true ); enode = new XMLNode(triple); assertTrue( enode != null ); assertTrue( enode.getNumChildren() == 0 ); assertTrue( !enode.getName().equals( "test") == false ); assertTrue( enode.getPrefix().equals("") == true ); assertTrue( enode.getURI().equals("") == true ); assertTrue( enode.isElement() == true ); assertTrue( enode.isStart() == false ); assertTrue( enode.isEnd() == true ); assertTrue( enode.isText() == false ); tnode = new XMLNode(text); assertTrue( tnode != null ); assertTrue( !tnode.getCharacters().equals(text) == false ); assertTrue( tnode.getNumChildren() == 0 ); assertTrue( tnode.getName().equals("") == true ); assertTrue( tnode.getPrefix().equals("") == true ); assertTrue( tnode.getURI().equals("") == true ); assertTrue( tnode.isElement() == false ); assertTrue( tnode.isStart() == false ); assertTrue( tnode.isEnd() == false ); assertTrue( tnode.isText() == true ); triple = null; attr = null; snode = null; enode = null; tnode = null; } public void test_XMLNode_createFromToken() { XMLToken token; XMLTriple triple; XMLNode node; triple = new XMLTriple("attr", "uri", "prefix"); token = new XMLToken(triple); node = new XMLNode(token); assertTrue( node != null ); assertTrue( node.getNumChildren() == 0 ); assertTrue( !node.getName().equals( "attr") == false ); assertTrue( !node.getPrefix().equals( "prefix") == false ); assertTrue( !node.getURI().equals( "uri") == false ); assertTrue( node.getChild(1) != null ); token = null; triple = null; node = null; } public void test_XMLNode_getters() { XMLToken token; XMLNode node; XMLTriple triple; XMLAttributes attr; XMLNamespaces NS; NS = new XMLNamespaces(); NS.add( "http://test1.org/", "test1"); token = new XMLToken("This is a test"); node = new XMLNode(token); assertTrue( node != null ); assertTrue( node.getNumChildren() == 0 ); assertTrue( !node.getCharacters().equals( "This is a test") == false ); assertTrue( node.getChild(1) != null ); attr = new XMLAttributes(); assertTrue( attr != null ); attr.add( "attr2", "value"); triple = new XMLTriple("attr", "uri", "prefix"); token = new XMLToken(triple,attr); assertTrue( token != null ); node = new XMLNode(token); assertTrue( !node.getName().equals( "attr") == false ); assertTrue( !node.getURI().equals( "uri") == false ); assertTrue( !node.getPrefix().equals( "prefix") == false ); XMLAttributes returnattr = node.getAttributes(); assertTrue( !returnattr.getName(0).equals( "attr2") == false ); assertTrue( !returnattr.getValue(0).equals( "value") == false ); token = new XMLToken(triple,attr,NS); node = new XMLNode(token); XMLNamespaces returnNS = node.getNamespaces(); assertTrue( returnNS.getLength() == 1 ); assertTrue( returnNS.isEmpty() == false ); triple = null; token = null; node = null; } public void test_XMLNode_insert() { XMLAttributes attr = new XMLAttributes(); XMLTriple trp_p = new XMLTriple("parent","",""); XMLTriple trp_c1 = new XMLTriple("child1","",""); XMLTriple trp_c2 = new XMLTriple("child2","",""); XMLTriple trp_c3 = new XMLTriple("child3","",""); XMLTriple trp_c4 = new XMLTriple("child4","",""); XMLTriple trp_c5 = new XMLTriple("child5","",""); XMLNode p = new XMLNode(trp_p,attr); XMLNode c1 = new XMLNode(trp_c1,attr); XMLNode c2 = new XMLNode(trp_c2,attr); XMLNode c3 = new XMLNode(trp_c3,attr); XMLNode c4 = new XMLNode(trp_c4,attr); XMLNode c5 = new XMLNode(trp_c5,attr); p.addChild(c2); p.addChild(c4); p.insertChild(0,c1); p.insertChild(2,c3); p.insertChild(4,c5); assertTrue( p.getNumChildren() == 5 ); assertTrue( !p.getChild(0).getName().equals( "child1") == false ); assertTrue( !p.getChild(1).getName().equals( "child2") == false ); assertTrue( !p.getChild(2).getName().equals( "child3") == false ); assertTrue( !p.getChild(3).getName().equals( "child4") == false ); assertTrue( !p.getChild(4).getName().equals( "child5") == false ); p.removeChildren(); p.insertChild(0,c1); p.insertChild(0,c2); p.insertChild(0,c3); p.insertChild(0,c4); p.insertChild(0,c5); assertTrue( p.getNumChildren() == 5 ); assertTrue( !p.getChild(0).getName().equals( "child5") == false ); assertTrue( !p.getChild(1).getName().equals( "child4") == false ); assertTrue( !p.getChild(2).getName().equals( "child3") == false ); assertTrue( !p.getChild(3).getName().equals( "child2") == false ); assertTrue( !p.getChild(4).getName().equals( "child1") == false ); p.removeChildren(); p.insertChild(1,c1); p.insertChild(2,c2); p.insertChild(3,c3); p.insertChild(4,c4); p.insertChild(5,c5); assertTrue( p.getNumChildren() == 5 ); assertTrue( !p.getChild(0).getName().equals( "child1") == false ); assertTrue( !p.getChild(1).getName().equals( "child2") == false ); assertTrue( !p.getChild(2).getName().equals( "child3") == false ); assertTrue( !p.getChild(3).getName().equals( "child4") == false ); assertTrue( !p.getChild(4).getName().equals( "child5") == false ); p.removeChildren(); XMLNode tmp; tmp = p.insertChild(0,c1); assertTrue( !tmp.getName().equals("child1") == false ); tmp = p.insertChild(0,c2); assertTrue( !tmp.getName().equals("child2") == false ); tmp = p.insertChild(0,c3); assertTrue( !tmp.getName().equals("child3") == false ); tmp = p.insertChild(0,c4); assertTrue( !tmp.getName().equals("child4") == false ); tmp = p.insertChild(0,c5); assertTrue( !tmp.getName().equals("child5") == false ); p.removeChildren(); tmp = p.insertChild(1,c1); assertTrue( !tmp.getName().equals("child1") == false ); tmp = p.insertChild(2,c2); assertTrue( !tmp.getName().equals("child2") == false ); tmp = p.insertChild(3,c3); assertTrue( !tmp.getName().equals("child3") == false ); tmp = p.insertChild(4,c4); assertTrue( !tmp.getName().equals("child4") == false ); tmp = p.insertChild(5,c5); assertTrue( !tmp.getName().equals("child5") == false ); p = null; c1 = null; c2 = null; c3 = null; c4 = null; c5 = null; attr = null; trp_p = null; trp_c1 = null; trp_c2 = null; trp_c3 = null; trp_c4 = null; trp_c5 = null; } public void test_XMLNode_namespace_add() { XMLTriple triple = new XMLTriple("test","",""); XMLAttributes attr = new XMLAttributes(); XMLNode node = new XMLNode(triple,attr); assertTrue( node.getNamespacesLength() == 0 ); assertTrue( node.isNamespacesEmpty() == true ); node.addNamespace( "http://test1.org/", "test1"); assertTrue( node.getNamespacesLength() == 1 ); assertTrue( node.isNamespacesEmpty() == false ); node.addNamespace( "http://test2.org/", "test2"); assertTrue( node.getNamespacesLength() == 2 ); assertTrue( node.isNamespacesEmpty() == false ); node.addNamespace( "http://test1.org/", "test1a"); assertTrue( node.getNamespacesLength() == 3 ); assertTrue( node.isNamespacesEmpty() == false ); node.addNamespace( "http://test1.org/", "test1a"); assertTrue( node.getNamespacesLength() == 3 ); assertTrue( node.isNamespacesEmpty() == false ); assertTrue( ! (node.getNamespaceIndex( "http://test1.org/") == -1) ); node = null; triple = null; attr = null; } public void test_XMLNode_namespace_get() { XMLTriple triple = new XMLTriple("test","",""); XMLAttributes attr = new XMLAttributes(); XMLNode node = new XMLNode(triple,attr); node.addNamespace( "http://test1.org/", "test1"); node.addNamespace( "http://test2.org/", "test2"); node.addNamespace( "http://test3.org/", "test3"); node.addNamespace( "http://test4.org/", "test4"); node.addNamespace( "http://test5.org/", "test5"); node.addNamespace( "http://test6.org/", "test6"); node.addNamespace( "http://test7.org/", "test7"); node.addNamespace( "http://test8.org/", "test8"); node.addNamespace( "http://test9.org/", "test9"); assertTrue( node.getNamespacesLength() == 9 ); assertTrue( node.getNamespaceIndex( "http://test1.org/") == 0 ); assertTrue( !node.getNamespacePrefix(1).equals( "test2") == false ); assertTrue( !node.getNamespacePrefix( "http://test1.org/").equals( "test1") == false ); assertTrue( !node.getNamespaceURI(1).equals( "http://test2.org/") == false ); assertTrue( !node.getNamespaceURI( "test2").equals( "http://test2.org/") == false ); assertTrue( node.getNamespaceIndex( "http://test1.org/") == 0 ); assertTrue( node.getNamespaceIndex( "http://test2.org/") == 1 ); assertTrue( node.getNamespaceIndex( "http://test5.org/") == 4 ); assertTrue( node.getNamespaceIndex( "http://test9.org/") == 8 ); assertTrue( node.getNamespaceIndex( "http://testX.org/") == -1 ); assertTrue( node.hasNamespaceURI( "http://test1.org/") != false ); assertTrue( node.hasNamespaceURI( "http://test2.org/") != false ); assertTrue( node.hasNamespaceURI( "http://test5.org/") != false ); assertTrue( node.hasNamespaceURI( "http://test9.org/") != false ); assertTrue( node.hasNamespaceURI( "http://testX.org/") == false ); assertTrue( node.getNamespaceIndexByPrefix( "test1") == 0 ); assertTrue( node.getNamespaceIndexByPrefix( "test5") == 4 ); assertTrue( node.getNamespaceIndexByPrefix( "test9") == 8 ); assertTrue( node.getNamespaceIndexByPrefix( "testX") == -1 ); assertTrue( node.hasNamespacePrefix( "test1") != false ); assertTrue( node.hasNamespacePrefix( "test5") != false ); assertTrue( node.hasNamespacePrefix( "test9") != false ); assertTrue( node.hasNamespacePrefix( "testX") == false ); assertTrue( node.hasNamespaceNS( "http://test1.org/", "test1") != false ); assertTrue( node.hasNamespaceNS( "http://test5.org/", "test5") != false ); assertTrue( node.hasNamespaceNS( "http://test9.org/", "test9") != false ); assertTrue( node.hasNamespaceNS( "http://testX.org/", "testX") == false ); node = null; triple = null; attr = null; } public void test_XMLNode_namespace_remove() { XMLTriple triple = new XMLTriple("test","",""); XMLAttributes attr = new XMLAttributes(); XMLNode node = new XMLNode(triple,attr); node.addNamespace( "http://test1.org/", "test1"); node.addNamespace( "http://test2.org/", "test2"); node.addNamespace( "http://test3.org/", "test3"); node.addNamespace( "http://test4.org/", "test4"); node.addNamespace( "http://test5.org/", "test5"); assertTrue( node.getNamespacesLength() == 5 ); node.removeNamespace(4); assertTrue( node.getNamespacesLength() == 4 ); node.removeNamespace(3); assertTrue( node.getNamespacesLength() == 3 ); node.removeNamespace(2); assertTrue( node.getNamespacesLength() == 2 ); node.removeNamespace(1); assertTrue( node.getNamespacesLength() == 1 ); node.removeNamespace(0); assertTrue( node.getNamespacesLength() == 0 ); node.addNamespace( "http://test1.org/", "test1"); node.addNamespace( "http://test2.org/", "test2"); node.addNamespace( "http://test3.org/", "test3"); node.addNamespace( "http://test4.org/", "test4"); node.addNamespace( "http://test5.org/", "test5"); assertTrue( node.getNamespacesLength() == 5 ); node.removeNamespace(0); assertTrue( node.getNamespacesLength() == 4 ); node.removeNamespace(0); assertTrue( node.getNamespacesLength() == 3 ); node.removeNamespace(0); assertTrue( node.getNamespacesLength() == 2 ); node.removeNamespace(0); assertTrue( node.getNamespacesLength() == 1 ); node.removeNamespace(0); assertTrue( node.getNamespacesLength() == 0 ); node = null; triple = null; attr = null; } public void test_XMLNode_namespace_remove_by_prefix() { XMLTriple triple = new XMLTriple("test","",""); XMLAttributes attr = new XMLAttributes(); XMLNode node = new XMLNode(triple,attr); node.addNamespace( "http://test1.org/", "test1"); node.addNamespace( "http://test2.org/", "test2"); node.addNamespace( "http://test3.org/", "test3"); node.addNamespace( "http://test4.org/", "test4"); node.addNamespace( "http://test5.org/", "test5"); assertTrue( node.getNamespacesLength() == 5 ); node.removeNamespace( "test1"); assertTrue( node.getNamespacesLength() == 4 ); node.removeNamespace( "test2"); assertTrue( node.getNamespacesLength() == 3 ); node.removeNamespace( "test3"); assertTrue( node.getNamespacesLength() == 2 ); node.removeNamespace( "test4"); assertTrue( node.getNamespacesLength() == 1 ); node.removeNamespace( "test5"); assertTrue( node.getNamespacesLength() == 0 ); node.addNamespace( "http://test1.org/", "test1"); node.addNamespace( "http://test2.org/", "test2"); node.addNamespace( "http://test3.org/", "test3"); node.addNamespace( "http://test4.org/", "test4"); node.addNamespace( "http://test5.org/", "test5"); assertTrue( node.getNamespacesLength() == 5 ); node.removeNamespace( "test5"); assertTrue( node.getNamespacesLength() == 4 ); node.removeNamespace( "test4"); assertTrue( node.getNamespacesLength() == 3 ); node.removeNamespace( "test3"); assertTrue( node.getNamespacesLength() == 2 ); node.removeNamespace( "test2"); assertTrue( node.getNamespacesLength() == 1 ); node.removeNamespace( "test1"); assertTrue( node.getNamespacesLength() == 0 ); node.addNamespace( "http://test1.org/", "test1"); node.addNamespace( "http://test2.org/", "test2"); node.addNamespace( "http://test3.org/", "test3"); node.addNamespace( "http://test4.org/", "test4"); node.addNamespace( "http://test5.org/", "test5"); assertTrue( node.getNamespacesLength() == 5 ); node.removeNamespace( "test3"); assertTrue( node.getNamespacesLength() == 4 ); node.removeNamespace( "test1"); assertTrue( node.getNamespacesLength() == 3 ); node.removeNamespace( "test4"); assertTrue( node.getNamespacesLength() == 2 ); node.removeNamespace( "test5"); assertTrue( node.getNamespacesLength() == 1 ); node.removeNamespace( "test2"); assertTrue( node.getNamespacesLength() == 0 ); node = null; triple = null; attr = null; } public void test_XMLNode_namespace_set_clear() { XMLTriple triple = new XMLTriple("test","",""); XMLAttributes attr = new XMLAttributes(); XMLNode node = new XMLNode(triple,attr); XMLNamespaces ns = new XMLNamespaces(); assertTrue( node.getNamespacesLength() == 0 ); assertTrue( node.isNamespacesEmpty() == true ); ns.add( "http://test1.org/", "test1"); ns.add( "http://test2.org/", "test2"); ns.add( "http://test3.org/", "test3"); ns.add( "http://test4.org/", "test4"); ns.add( "http://test5.org/", "test5"); node.setNamespaces(ns); assertTrue( node.getNamespacesLength() == 5 ); assertTrue( node.isNamespacesEmpty() == false ); assertTrue( !node.getNamespacePrefix(0).equals( "test1") == false ); assertTrue( !node.getNamespacePrefix(1).equals( "test2") == false ); assertTrue( !node.getNamespacePrefix(2).equals( "test3") == false ); assertTrue( !node.getNamespacePrefix(3).equals( "test4") == false ); assertTrue( !node.getNamespacePrefix(4).equals( "test5") == false ); assertTrue( !node.getNamespaceURI(0).equals( "http://test1.org/") == false ); assertTrue( !node.getNamespaceURI(1).equals( "http://test2.org/") == false ); assertTrue( !node.getNamespaceURI(2).equals( "http://test3.org/") == false ); assertTrue( !node.getNamespaceURI(3).equals( "http://test4.org/") == false ); assertTrue( !node.getNamespaceURI(4).equals( "http://test5.org/") == false ); node.clearNamespaces(); assertTrue( node.getNamespacesLength() == 0 ); assertTrue( node.isAttributesEmpty() != false ); ns = null; node = null; triple = null; attr = null; } public void test_XMLNode_remove() { XMLAttributes attr = new XMLAttributes(); XMLTriple trp_p = new XMLTriple("parent","",""); XMLTriple trp_c1 = new XMLTriple("child1","",""); XMLTriple trp_c2 = new XMLTriple("child2","",""); XMLTriple trp_c3 = new XMLTriple("child3","",""); XMLTriple trp_c4 = new XMLTriple("child4","",""); XMLTriple trp_c5 = new XMLTriple("child5","",""); XMLNode p = new XMLNode(trp_p,attr); XMLNode c1 = new XMLNode(trp_c1,attr); XMLNode c2 = new XMLNode(trp_c2,attr); XMLNode c3 = new XMLNode(trp_c3,attr); XMLNode c4 = new XMLNode(trp_c4,attr); XMLNode c5 = new XMLNode(trp_c5,attr); XMLNode r; p.addChild(c1); p.addChild(c2); p.addChild(c3); p.addChild(c4); p.addChild(c5); r = p.removeChild(5); assertTrue( r == null ); r = p.removeChild(1); assertTrue( p.getNumChildren() == 4 ); assertTrue( !r.getName().equals("child2") == false ); r = null; r = p.removeChild(3); assertTrue( p.getNumChildren() == 3 ); assertTrue( !r.getName().equals("child5") == false ); r = null; r = p.removeChild(0); assertTrue( p.getNumChildren() == 2 ); assertTrue( !r.getName().equals("child1") == false ); r = null; r = p.removeChild(1); assertTrue( p.getNumChildren() == 1 ); assertTrue( !r.getName().equals("child4") == false ); r = null; r = p.removeChild(0); assertTrue( p.getNumChildren() == 0 ); assertTrue( !r.getName().equals("child3") == false ); r = null; p.addChild(c1); p.addChild(c2); p.addChild(c3); p.addChild(c4); p.addChild(c5); r = p.removeChild(4); assertTrue( p.getNumChildren() == 4 ); assertTrue( !r.getName().equals("child5") == false ); r = null; r = p.removeChild(3); assertTrue( p.getNumChildren() == 3 ); assertTrue( !r.getName().equals("child4") == false ); r = null; r = p.removeChild(2); assertTrue( p.getNumChildren() == 2 ); assertTrue( !r.getName().equals("child3") == false ); r = null; r = p.removeChild(1); assertTrue( p.getNumChildren() == 1 ); assertTrue( !r.getName().equals("child2") == false ); r = null; r = p.removeChild(0); assertTrue( p.getNumChildren() == 0 ); assertTrue( !r.getName().equals("child1") == false ); r = null; p.addChild(c1); p.addChild(c2); p.addChild(c3); p.addChild(c4); p.addChild(c5); r = p.removeChild(0); assertTrue( p.getNumChildren() == 4 ); assertTrue( !r.getName().equals("child1") == false ); r = null; r = p.removeChild(0); assertTrue( p.getNumChildren() == 3 ); assertTrue( !r.getName().equals("child2") == false ); r = null; r = p.removeChild(0); assertTrue( p.getNumChildren() == 2 ); assertTrue( !r.getName().equals("child3") == false ); r = null; r = p.removeChild(0); assertTrue( p.getNumChildren() == 1 ); assertTrue( !r.getName().equals("child4") == false ); r = null; r = p.removeChild(0); assertTrue( p.getNumChildren() == 0 ); assertTrue( !r.getName().equals("child5") == false ); r = null; p.addChild(c1); p.addChild(c2); p.addChild(c3); p.addChild(c4); p.addChild(c5); r = p.removeChild(0); assertTrue( !r.getName().equals("child1") == false ); p.insertChild(0,r); assertTrue( p.getNumChildren() == 5 ); assertTrue( !p.getChild(0).getName().equals("child1") == false ); r = null; r = p.removeChild(1); assertTrue( !r.getName().equals("child2") == false ); p.insertChild(1,r); assertTrue( p.getNumChildren() == 5 ); assertTrue( !p.getChild(1).getName().equals("child2") == false ); r = null; r = p.removeChild(2); assertTrue( !r.getName().equals("child3") == false ); p.insertChild(2,r); assertTrue( p.getNumChildren() == 5 ); assertTrue( !p.getChild(2).getName().equals("child3") == false ); r = null; r = p.removeChild(3); assertTrue( !r.getName().equals("child4") == false ); p.insertChild(3,r); assertTrue( p.getNumChildren() == 5 ); assertTrue( !p.getChild(3).getName().equals("child4") == false ); r = null; r = p.removeChild(4); assertTrue( !r.getName().equals("child5") == false ); p.insertChild(4,r); assertTrue( p.getNumChildren() == 5 ); assertTrue( !p.getChild(4).getName().equals("child5") == false ); r = null; p = null; c1 = null; c2 = null; c3 = null; c4 = null; c5 = null; attr = null; trp_p = null; trp_c1 = null; trp_c2 = null; trp_c3 = null; trp_c4 = null; trp_c5 = null; } /** * Loads the SWIG-generated libSBML Java module when this class is * loaded, or reports a sensible diagnostic message about why it failed. */ static { String varname; String shlibname; if (System.getProperty("mrj.version") != null) { varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. shlibname = "libsbmlj.jnilib and/or libsbml.dylib"; } else { varname = "LD_LIBRARY_PATH"; // We're not on a Mac. shlibname = "libsbmlj.so and/or libsbml.so"; } try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (SecurityException e) { e.printStackTrace(); System.err.println("Could not load the libSBML library files due to a"+ " security exception.\n"); System.exit(1); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); System.err.println("Error: could not link with the libSBML library files."+ " It is likely\nyour " + varname + " environment variable does not include the directories\n"+ "containing the " + shlibname + " library files.\n"); System.exit(1); } catch (ClassNotFoundException e) { e.printStackTrace(); System.err.println("Error: unable to load the file libsbmlj.jar."+ " It is likely\nyour -classpath option and CLASSPATH" + " environment variable\n"+ "do not include the path to libsbmlj.jar.\n"); System.exit(1); } } }
alexholehouse/SBMLIntegrator
libsbml-5.0.0/src/bindings/java/test/org/sbml/libsbml/test/xml/TestXMLNode.java
Java
gpl-3.0
44,048
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Sonic Visualiser An audio file viewer and annotation editor. Centre for Digital Music, Queen Mary, University of London. This file copyright 2008 QMUL. 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. See the file COPYING included with this distribution for more information. */ #ifndef _MODEL_DATA_TABLE_MODEL_H_ #define _MODEL_DATA_TABLE_MODEL_H_ #include <QAbstractItemModel> #include <vector> #include "PraalineCore/Base/BaseTypes.h" class TabularModel; class UndoableCommand; class ModelDataTableModel : public QAbstractItemModel { Q_OBJECT public: ModelDataTableModel(TabularModel *m); virtual ~ModelDataTableModel(); QVariant data(const QModelIndex &index, int role) const; bool setData(const QModelIndex &index, const QVariant &value, int role); bool insertRow(int row, const QModelIndex &parent = QModelIndex()); bool removeRow(int row, const QModelIndex &parent = QModelIndex()); Qt::ItemFlags flags(const QModelIndex &index) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; QModelIndex parent(const QModelIndex &index) const; int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QModelIndex getModelIndexForFrame(sv_frame_t frame) const; sv_frame_t getFrameForModelIndex(const QModelIndex &) const; void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); QModelIndex findText(QString text) const; void setCurrentRow(int row); int getCurrentRow() const; signals: void frameSelected(int); void addCommand(UndoableCommand *); void currentChanged(const QModelIndex &); void modelRemoved(); protected slots: void modelChanged(); void modelChangedWithin(sv_frame_t, sv_frame_t); void modelAboutToBeDeleted(); protected: TabularModel *m_model; int m_sortColumn; Qt::SortOrder m_sortOrdering; int m_currentRow; typedef std::vector<int> RowList; mutable RowList m_sort; mutable RowList m_rsort; int getSorted(int row) const; int getUnsorted(int row) const; void resort() const; void resortNumeric() const; void resortAlphabetical() const; void clearSort(); }; #endif
praaline/Praaline
svcore/data/model/ModelDataTableModel.h
C
gpl-3.0
2,739
all: pipestat pipemulti pipeatom pipepoll pipepage ppage pmulti tolower ptolower add2 add3 padd2 ffread ffwrite ffrw xsiget xsique xsisem xsishm addr zroshm pipeselect msgid shmlst shmlst: shmlst.o apue.o gcc -Wall -g $^ -o $@ -lpthread shmlst.o: shmlst.c ../apue.h gcc -Wall -g -c $< -o $@ msgid: msgid.o apue.o gcc -Wall -g $^ -o $@ -lpthread msgid.o: msgid.c ../apue.h gcc -Wall -g -c $< -o $@ pipeselect: pipeselect.o apue.o gcc -Wall -g $^ -o $@ -lpthread pipeselect.o: pipeselect.c ../apue.h gcc -Wall -g -c $< -o $@ zroshm: zroshm.o apue.o gcc -Wall -g $^ -o $@ -lpthread zroshm.o: zroshm.c ../apue.h gcc -Wall -g -c $< -o $@ -D_BSD_SOURCE addr: addr.o apue.o gcc -Wall -g $^ -o $@ -lpthread addr.o: addr.c ../apue.h gcc -Wall -g -c $< -o $@ xsishm: xsishm.o apue.o gcc -Wall -g $^ -o $@ -lpthread xsishm.o: xsishm.c ../apue.h gcc -Wall -g -c $< -o $@ xsisem: xsisem.o apue.o gcc -Wall -g $^ -o $@ -lpthread xsisem.o: xsisem.c ../apue.h gcc -Wall -g -c $< -o $@ xsique: xsique.o apue.o gcc -Wall -g $^ -o $@ -lpthread xsique.o: xsique.c ../apue.h gcc -Wall -g -c $< -o $@ xsiget: xsiget.o apue.o gcc -Wall -g $^ -o $@ -lpthread xsiget.o: xsiget.c ../apue.h gcc -Wall -g -c $< -o $@ ffrw: ffrw.o apue.o gcc -Wall -g $^ -o $@ -lpthread ffrw.o: ffrw.c ../apue.h gcc -Wall -g -c $< -o $@ ffwrite: ffwrite.o apue.o gcc -Wall -g $^ -o $@ -lpthread ffwrite.o: ffwrite.c ../apue.h gcc -Wall -g -c $< -o $@ ffread: ffread.o apue.o gcc -Wall -g $^ -o $@ -lpthread ffread.o: ffread.c ../apue.h gcc -Wall -g -c $< -o $@ padd2: padd2.o apue.o gcc -Wall -g $^ -o $@ -lpthread padd2.o: padd2.c ../apue.h gcc -Wall -g -c $< -o $@ add3: add3.o apue.o gcc -Wall -g $^ -o $@ -lpthread add3.o: add3.c ../apue.h gcc -Wall -g -c $< -o $@ -DSETVBUF add2: add2.o apue.o gcc -Wall -g $^ -o $@ -lpthread add2.o: add2.c ../apue.h gcc -Wall -g -c $< -o $@ ptolower: ptolower.o apue.o gcc -Wall -g $^ -o $@ -lpthread ptolower.o: ptolower.c ../apue.h gcc -Wall -g -c $< -o $@ tolower: tolower.o apue.o gcc -Wall -g $^ -o $@ -lpthread tolower.o: tolower.c ../apue.h gcc -Wall -g -c $< -o $@ pmulti: pmulti.o apue.o gcc -Wall -g $^ -o $@ -lpthread pmulti.o: pmulti.c ../apue.h gcc -Wall -g -c $< -o $@ ppage: ppage.o apue.o gcc -Wall -g $^ -o $@ -lpthread ppage.o: ppage.c ../apue.h gcc -Wall -g -c $< -o $@ pipepage: pipepage.o apue.o gcc -Wall -g $^ -o $@ -lpthread pipepage.o: pipepage.c ../apue.h gcc -Wall -g -c $< -o $@ pipepoll: pipepoll.o apue.o gcc -Wall -g $^ -o $@ -lpthread pipepoll.o: pipepoll.c ../apue.h gcc -Wall -g -c $< -o $@ pipeatom: pipeatom.o apue.o gcc -Wall -g $^ -o $@ -lpthread pipeatom.o: pipeatom.c ../apue.h gcc -Wall -g -c $< -o $@ pipemulti: pipemulti.o apue.o gcc -Wall -g $^ -o $@ -lpthread pipemulti.o: pipemulti.c ../apue.h gcc -Wall -g -c $< -o $@ pipestat: pipestat.o apue.o gcc -Wall -g $^ -o $@ -lpthread pipestat.o: pipestat.c ../apue.h gcc -Wall -g -c $< -o $@ log.o: ../log.c ../log.h gcc -Wall -g -c $< -o $@ apue.o: ../apue.c ../apue.h gcc -Wall -g -c $< -o $@ -D__USE_BSD -DUSE_PTHREAD clean: @echo "start clean..." -rm -f *.o core.* *.log *~ *.swp pipestat pipemulti pipeatom pipepoll pipepage ppage pmulti tolower ptolower add2 add3 padd2 ffread ffwrite ffrw xsiget xsique xsisem xsishm addr zroshm msgid shmlst @echo "end clean" .PHONY: clean
goodpaperman/apue
15.chapter/Makefile
Makefile
gpl-3.0
3,397
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: HtmlElement.php 24399 2011-08-26 08:20:07Z padraic $ */ /** * @see Zend_View_Helper_Abstract */ require_once 'Zend/View/Helper/Abstract.php'; /** * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_View_Helper_HtmlElement extends Zend_View_Helper_Abstract { /** * EOL character */ const EOL = "\n"; /** * The tag closing bracket * * @var string */ protected $_closingBracket = null; /** * Get the tag closing bracket * * @return string */ public function getClosingBracket() { if (!$this->_closingBracket) { if ($this->_isXhtml()) { $this->_closingBracket = ' />'; } else { $this->_closingBracket = '>'; } } return $this->_closingBracket; } /** * Is doctype XHTML? * * @return boolean */ protected function _isXhtml() { $doctype = $this->view->doctype(); return $doctype->isXhtml(); } /** * Is doctype strict? * * @return boolean */ protected function _isStrictDoctype() { $doctype = $this->view->doctype(); return $doctype->isStrict(); } /** * Converts an associative array to a string of tag attributes. * * @access public * * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * * @return string The XHTML for the attributes. */ protected function _htmlAttribs($attribs) { $xhtml = ''; foreach ((array)$attribs as $key => $val) { $key = $this->view->escape($key); if (('on' == substr($key, 0, 2)) || ('constraints' == $key)) { // Don't escape event attributes; _do_ substitute double quotes with singles if (!is_scalar($val)) { // non-scalar data should be cast to JSON first require_once 'Zend/Json.php'; $val = Zend_Json::encode($val); } // Escape single quotes inside event attribute values. // This will create html, where the attribute value has // single quotes around it, and escaped single quotes or // non-escaped double quotes inside of it $val = str_replace('\'', '&#39;', $val); } else { if (is_array($val)) { $val = implode(' ', $val); } $val = $this->view->escape($val); } if ('id' == $key) { $val = $this->_normalizeId($val); } if (strpos($val, '"') !== false) { $xhtml .= " $key='$val'"; } else { $xhtml .= " $key=\"$val\""; } } return $xhtml; } /** * Normalize an ID * * @param string $value * @return string */ protected function _normalizeId($value) { if (strstr($value, '[')) { if ('[]' == substr($value, -2)) { $value = substr($value, 0, strlen($value) - 2); } $value = trim($value, ']'); $value = str_replace('][', '-', $value); $value = str_replace('[', '-', $value); } return $value; } }
jvianney/SwiftHR
Zend/View/Helper/HtmlElement.php
PHP
gpl-3.0
4,330
<?php namespace Neos\Neos\TYPO3CR\Transformations; /* * This file is part of the Neos.Neos package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Doctrine\Common\Persistence\ObjectManager; use Neos\Flow\Annotations as Flow; use Neos\Flow\Persistence\PersistenceManagerInterface; use Neos\Flow\ResourceManagement\ResourceManager; use Neos\Media\Domain\Model\ImageInterface; use Neos\Media\Domain\Model\ImageVariant; use Neos\Media\Domain\Repository\AssetRepository; use Neos\Media\TypeConverter\ProcessingInstructionsConverter; use Neos\ContentRepository\Domain\Model\NodeData; use Neos\ContentRepository\Migration\Transformations\AbstractTransformation; /** * Convert serialized (old resource management) ImageVariants to new ImageVariants. */ class ImageVariantTransformation extends AbstractTransformation { /** * @Flow\Inject * @var AssetRepository */ protected $assetRepository; /** * @Flow\Inject * @var ResourceManager */ protected $resourceManager; /** * @Flow\Inject * @var ProcessingInstructionsConverter */ protected $processingInstructionsConverter; /** * @Flow\Inject * @var PersistenceManagerInterface */ protected $persistenceManager; /** * Doctrine's Entity Manager. Note that "ObjectManager" is the name of the related interface. * * @Flow\Inject * @var ObjectManager */ protected $entityManager; /** * @param NodeData $node * @return boolean */ public function isTransformable(NodeData $node) { return true; } /** * Change the property on the given node. * * @param NodeData $node * @return void */ public function execute(NodeData $node) { foreach ($node->getNodeType()->getProperties() as $propertyName => $propertyConfiguration) { if (isset($propertyConfiguration['type']) && ($propertyConfiguration['type'] === ImageInterface::class || preg_match('/array\<.*\>/', $propertyConfiguration['type']))) { if (!isset($nodeProperties)) { $nodeRecordQuery = $this->entityManager->getConnection()->prepare('SELECT properties FROM typo3_typo3cr_domain_model_nodedata WHERE persistence_object_identifier=?'); $nodeRecordQuery->execute([$this->persistenceManager->getIdentifierByObject($node)]); $nodeRecord = $nodeRecordQuery->fetch(\PDO::FETCH_ASSOC); $nodeProperties = unserialize($nodeRecord['properties']); } if (!isset($nodeProperties[$propertyName]) || empty($nodeProperties[$propertyName])) { continue; } if ($propertyConfiguration['type'] === ImageInterface::class) { $adjustments = array(); $oldVariantConfiguration = $nodeProperties[$propertyName]; if (is_array($oldVariantConfiguration)) { foreach ($oldVariantConfiguration as $variantPropertyName => $property) { switch (substr($variantPropertyName, 3)) { case 'originalImage': /** * @var $originalAsset Image */ $originalAsset = $this->assetRepository->findByIdentifier($this->persistenceManager->getIdentifierByObject($property)); break; case 'processingInstructions': $adjustments = $this->processingInstructionsConverter->convertFrom($property, 'array'); break; } } $nodeProperties[$propertyName] = null; if (isset($originalAsset)) { $stream = $originalAsset->getResource()->getStream(); if ($stream === false) { continue; } fclose($stream); $newImageVariant = new ImageVariant($originalAsset); foreach ($adjustments as $adjustment) { $newImageVariant->addAdjustment($adjustment); } $originalAsset->addVariant($newImageVariant); $this->assetRepository->update($originalAsset); $nodeProperties[$propertyName] = $this->persistenceManager->getIdentifierByObject($newImageVariant); } } } elseif (preg_match('/array\<.*\>/', $propertyConfiguration['type'])) { if (is_array($nodeProperties[$propertyName])) { $convertedValue = []; foreach ($nodeProperties[$propertyName] as $entryValue) { if (!is_object($entryValue)) { continue; } $stream = $entryValue->getResource()->getStream(); if ($stream === false) { continue; } fclose($stream); $existingObjectIdentifier = null; try { $existingObjectIdentifier = $this->persistenceManager->getIdentifierByObject($entryValue); if ($existingObjectIdentifier !== null) { $convertedValue[] = $existingObjectIdentifier; } } catch (\Exception $exception) { } } $nodeProperties[$propertyName] = $convertedValue; } } } } if (isset($nodeProperties)) { $nodeUpdateQuery = $this->entityManager->getConnection()->prepare('UPDATE typo3_typo3cr_domain_model_nodedata SET properties=? WHERE persistence_object_identifier=?'); $nodeUpdateQuery->execute([serialize($nodeProperties), $this->persistenceManager->getIdentifierByObject($node)]); } } }
hhoechtl/neos-development-collection
Neos.Neos/Classes/TYPO3CR/Transformations/ImageVariantTransformation.php
PHP
gpl-3.0
6,680
/********************************************************************** * Copyright (c) 2011 by the President and Fellows of Harvard College * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. * * Contact information * * Office for Information Systems * Harvard University Library * Harvard University * Cambridge, MA 02138 * (617)495-3724 * [email protected] **********************************************************************/ package edu.harvard.hul.ois.ots.schemas.AES; import java.io.StringReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; public class LayerTest extends junit.framework.TestCase { /** Sample string for testing */ private final static String layerSample = "<layer composition=\"123456\" order=\"1\" role=\"PROTECTIVE_LAYER\">\n" + " <thickness unit=\"MILLIMETRES\">1</thickness>\n" + "</layer>"; public void testRead () throws Exception { // set up a parser XMLInputFactory xmlif = XMLInputFactory.newInstance(); XMLStreamReader xmlr = xmlif.createXMLStreamReader(new StringReader(layerSample)); xmlr.nextTag(); Layer la = new Layer (xmlr); assertEquals ("123456", la.getComposition()); assertEquals ("PROTECTIVE_LAYER", la.getRole ()); assertEquals ((Integer) 1, la.getOrder ()); Measurement th = la.getThickness(); assertEquals ("MILLIMETRES", th.getUnit()); assertEquals ((Double) 1.0, th.toValue()); } }
opf-labs/ots-schema
test/edu/harvard/hul/ois/ots/schemas/AES/LayerTest.java
Java
gpl-3.0
2,208
/* * Copyright (C) 2013 The OmniROM Project * * 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/>. * */ package com.android.systemui.tuner; import android.content.Context; import android.content.res.TypedArray; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.android.systemui.R; public class SeekBarPreference extends Preference implements OnSeekBarChangeListener { public static int maximum = 100; public static int interval = 5; private TextView monitorBox; private SeekBar bar; int currentValue = 100; private OnPreferenceChangeListener changer; public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected View onCreateView(ViewGroup parent) { View layout = View.inflate(getContext(), R.layout.qs_slider_preference, null); monitorBox = (TextView) layout.findViewById(R.id.monitor_box); bar = (SeekBar) layout.findViewById(R.id.seek_bar); bar.setProgress(currentValue); monitorBox.setText(String.valueOf(currentValue) + "%"); bar.setOnSeekBarChangeListener(this); return layout; } public void setInitValue(int progress) { currentValue = progress; } @Override protected Object onGetDefaultValue(TypedArray a, int index) { // TODO Auto-generated method stub return super.onGetDefaultValue(a, index); } @Override public void setOnPreferenceChangeListener( OnPreferenceChangeListener onPreferenceChangeListener) { changer = onPreferenceChangeListener; super.setOnPreferenceChangeListener(onPreferenceChangeListener); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progress = Math.round(((float) progress) / interval) * interval; currentValue = progress; monitorBox.setText(String.valueOf(progress) + "%"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { changer.onPreferenceChange(this, Integer.toString(currentValue)); } }
OmniEvo/android_frameworks_base
packages/SystemUI/src/com/android/systemui/tuner/SeekBarPreference.java
Java
gpl-3.0
3,019
 using System; using System.Web; using System.Web.Routing; using System.Drawing; using System.Drawing.Imaging; using Meridian59.Files.BGF; namespace Meridian59.BgfService { /// <summary> /// /// </summary> public class FileRouteHandler : IRouteHandler { public FileRouteHandler() { } public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new FileHttpHandler(); } } /// <summary> /// Provides contents from BGF file. This includes meta data /// like offsets and hotspots as well as frame images as PNG or BMP. /// </summary> public class FileHttpHandler : IHttpHandler { /// <summary> /// Handles the HTTP request /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { HttpResponse response = context.Response; // -------------------------------------------------------------------------------------------- // 1) PARSE URL PARAMETERS // -------------------------------------------------------------------------------------------- // read parameters from url-path (see Global.asax): RouteValueDictionary parms = context.Request.RequestContext.RouteData.Values; string parmFile = parms.ContainsKey("file") ? (string)parms["file"] : null; string parmReq = parms.ContainsKey("req") ? (string)parms["req"] : null; string parm1 = parms.ContainsKey("parm1") ? (string)parms["parm1"] : null; string parm2 = parms.ContainsKey("parm2") ? (string)parms["parm2"] : null; string parm3 = parms.ContainsKey("parm3") ? (string)parms["parm3"] : null; BgfCache.Entry entry; // no filename or request type if (String.IsNullOrEmpty(parmFile) || !BgfCache.GetBGF(parmFile, out entry) || String.IsNullOrEmpty(parmReq)) { context.Response.StatusCode = 404; return; } // set cache behaviour context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.VaryByParams["*"] = false; context.Response.Cache.SetLastModified(entry.LastModified); // -------------------------------------------------------------------------------------------- // FRAME IMAGE // -------------------------------------------------------------------------------------------- if (parmReq == "frame") { ushort index; byte palette = 0; Byte.TryParse(parm3, out palette); // try to parse index and palette and validate range if (!UInt16.TryParse(parm2, out index) || index >= entry.Bgf.Frames.Count) { context.Response.StatusCode = 404; return; } // create BMP (256 col) or PNG (32-bit) or return raw pixels (8bit indices) if (parm1 == "bmp") { response.ContentType = "image/bmp"; response.AddHeader( "Content-Disposition", "inline; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".bmp"); Bitmap bmp = entry.Bgf.Frames[index].GetBitmap(palette); bmp.Save(context.Response.OutputStream, ImageFormat.Bmp); bmp.Dispose(); } else if (parm1 == "png") { response.ContentType = "image/png"; response.AddHeader( "Content-Disposition", "inline; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".png"); Bitmap bmp = entry.Bgf.Frames[index].GetBitmapA8R8G8B8(palette); bmp.Save(context.Response.OutputStream, ImageFormat.Png); bmp.Dispose(); } else if (parm1 == "bin") { response.ContentType = "application/octet-stream"; response.AddHeader( "Content-Disposition", "attachment; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".bin"); byte[] pixels = entry.Bgf.Frames[index].PixelData; context.Response.OutputStream.Write(pixels, 0, pixels.Length); } else context.Response.StatusCode = 404; } // -------------------------------------------------------------------------------------------- // JSON META DATA // -------------------------------------------------------------------------------------------- else if (parmReq == "meta") { // set response type response.ContentType = "application/json"; response.ContentEncoding = new System.Text.UTF8Encoding(false); response.AddHeader("Content-Disposition", "inline; filename=" + entry.Bgf.Filename + ".json"); // unix timestamp long stamp = (entry.LastModified.Ticks - 621355968000000000) / 10000000; ///////////////////////////////////////////////////////////// response.Write("{\"file\":\""); response.Write(entry.Bgf.Filename); response.Write("\",\"size\":"); response.Write(entry.Size.ToString()); response.Write(",\"modified\":"); response.Write(stamp.ToString()); response.Write(",\"shrink\":"); response.Write(entry.Bgf.ShrinkFactor.ToString()); response.Write(",\"frames\":["); for (int i = 0; i < entry.Bgf.Frames.Count; i++) { BgfBitmap frame = entry.Bgf.Frames[i]; if (i > 0) response.Write(','); response.Write("{\"w\":"); response.Write(frame.Width.ToString()); response.Write(",\"h\":"); response.Write(frame.Height.ToString()); response.Write(",\"x\":"); response.Write(frame.XOffset.ToString()); response.Write(",\"y\":"); response.Write(frame.YOffset.ToString()); response.Write(",\"hs\":["); for (int j = 0; j < frame.HotSpots.Count; j++) { BgfBitmapHotspot hs = frame.HotSpots[j]; if (j > 0) response.Write(','); response.Write("{\"i\":"); response.Write(hs.Index.ToString()); response.Write(",\"x\":"); response.Write(hs.X.ToString()); response.Write(",\"y\":"); response.Write(hs.Y.ToString()); response.Write('}'); } response.Write("]}"); } response.Write("],\"groups\":["); for (int i = 0; i < entry.Bgf.FrameSets.Count; i++) { BgfFrameSet group = entry.Bgf.FrameSets[i]; if (i > 0) response.Write(','); response.Write('['); for (int j = 0; j < group.FrameIndices.Count; j++) { if (j > 0) response.Write(','); response.Write(group.FrameIndices[j].ToString()); } response.Write(']'); } response.Write("]}"); } // -------------------------------------------------------------------------------------------- // INVALID // -------------------------------------------------------------------------------------------- else { context.Response.StatusCode = 404; return; } } public bool IsReusable { get { return true; } } } }
MorbusM59/meridian59-dotnet
Meridian59.BgfService/App_Code/FileHttpHandler.cs
C#
gpl-3.0
8,579
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Family of SNOOKS, William and HODGETTS, Hester</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li class = "CurrentSection"><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="RelationshipDetail"> <h2>Family of SNOOKS, William and HODGETTS, Hester<sup><small></small></sup></h2> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Husband</td> <td class="ColumnValue"> <a href="../../../ppl/a/2/d15f5fee313374669e11df1962a.html">SNOOKS, William<span class="grampsid"> [I4380]</span></a> </td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Wife</td> <td class="ColumnValue"> <a href="../../../ppl/8/a/d15f5fee2ed557a17281a3a3ca8.html">HODGETTS, Hester<span class="grampsid"> [I4379]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">&nbsp;</td> <td class="ColumnValue"> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> <a href="../../../evt/5/b/d15f60c46163c843224b21ed4b5.html" title="Marriage"> Marriage <span class="grampsid"> [E22216]</span> </a> </td> <td class="ColumnDate">1867-12-27</td> <td class="ColumnPlace"> <a href="../../../plc/e/f/d15f5fee7cd783d870fa29fbdfe.html" title=""> </a> </td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> <a href="../../../evt/4/b/d15f60c4621475319e058d15b4.html" title="Family (Primary)"> Family (Primary) <span class="grampsid"> [E22217]</span> </a> </td> <td class="ColumnDate">&nbsp;</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> <a href="#sref1a">1a</a> </td> </tr> </tbody> </table> </td> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">Attributes</td> <td class="ColumnValue"> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">FF63BEFC4A5E114BB5AA49A422CA6FD59C8D</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </td> </tr> </tr> </table> </div> <div class="subsection" id="attributes"> <h4>Attributes</h4> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">FF63BEFC4A5E114BB5AA49A422CA6FD59C8D</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/6/9/d15f5fe2fcb2b608ef162497496.html" title="Frank Lee: GEDCOM File : NathanielHODGETTS.ged" name ="sref1"> Frank Lee: GEDCOM File : NathanielHODGETTS.ged <span class="grampsid"> [S0218]</span> </a> <ol> <li id="sref1a"> <ul> <li> Confidence: Low </li> </ul> </li> </ol> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:47<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/fam/1/2/d15f5fee30647fb184389abaf21.html
HTML
gpl-3.0
6,516
<?php require('../core.php'); $act=explode('/',$_REQUEST['action']); $db=$app->conn[0]; $tbl='tbl_grupo'; switch($act[0]){ case 'create': if($app->acl(103)){ $record = json_decode(html_entity_decode(file_get_contents('php://input'),ENT_COMPAT,'utf-8'),true); if($db->AutoExecute($tbl,$record,'INSERT')){ $json['success']=true; }else{ $json['success']=false; $json['msg']=$db->ErrorMsg(); } }else{ $json['success']=false; $json['msg']='Falta de permisos para realizar esta accion'; } break; case 'read': $json=array(); $json['success']=true; $json['data']=array(); $sql="SELECT * FROM {$tbl}"; $rs=$db->Execute($sql); while (!$rs->EOF) { $json['data'][]=$rs->fields; $rs->MoveNext(); } break; case 'update': if($app->acl(103)){ $record = json_decode(html_entity_decode(file_get_contents('php://input'),ENT_COMPAT,'utf-8'),true); if($db->AutoExecute($tbl,$record,'UPDATE',"id={$act[1]}")){ $json['success']=true; }else{ $json['success']=false; $json['msg']=$db->ErrorMsg(); } }else{ $json['success']=false; $json['msg']='Falta de permisos para realizar esta accion'; } break; case 'destroy': if($app->acl(103)){ $rw=$db->GetRow("SELECT * FROM {$tbl} WHERE id={$act[1]}"); $rs=$db->Execute("DELETE FROM {$tbl} WHERE id={$act[1]}"); $json['success']=true; }else{ $json['success']=false; $json['msg']='Falta de permisos para realizar esta accion'; } break; } echo json_encode($json); ?>
openvinci/openvinci
data/group.php
PHP
gpl-3.0
1,942
/* * Copyright (C) 2015 Max Planck Institute for Psycholinguistics * * 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/>. */ function init_cmdi() { $("a.toggle").click(function () { $(this).parent().parent().toggleClass('collapsed'); $(this).parent().parent().toggleClass('expanded'); }); } function expand_highlighted_cmdi() { $(".searchword").parents('.IMDI_group.cmdi').removeClass('collapsed'); $(".searchword").parents('.IMDI_group.cmdi').addClass('expanded'); } $(document).ready(init_cmdi);
TheLanguageArchive/ASV
metadata-browser-hybrid/src/main/java/nl/mpi/metadatabrowser/services/cmdi/impl/res/cmdi2html.js
JavaScript
gpl-3.0
1,134
package com.example.channelmanager; /** * Created by Administrator on 2017/2/7. * 频道列表 */ public class ProjectChannelBean { private String topicid; // 设置该标签是否可编辑,如果出现在我的频道中,且值为1,则可在右上角显示删除按钮 private int editStatus; private String cid; private String tname; private String ename; // 标签类型,显示是我的频道还是更多频道 private int tabType; private String tid; private String column; public ProjectChannelBean(){} public ProjectChannelBean(String tname, String tid){ this.tname = tname; this.tid = tid; } public ProjectChannelBean(String tname, String column, String tid){ this.tname = tname; this.column = column; this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public int getTabType() { return tabType; } public void setTabType(int tabType) { this.tabType = tabType; } public int getEditStatus() { return editStatus; } public void setEditStatus(int editStatus) { this.editStatus = editStatus; } public String getTopicid() { return topicid; } public void setTopicid(String topicid) { this.topicid = topicid; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getTid() { return tid; } public void setTid(String tid) { this.tid = tid; } public String getColumn() { return column; } public void setColumn(String column) { this.column = column; } }
liaozhoubei/NetEasyNews
channelmanager/src/main/java/com/example/channelmanager/ProjectChannelBean.java
Java
gpl-3.0
1,956
/** Template Controllers @module Templates */ /** The execute contract template @class [template] elements_executeContract @constructor */ Template['elements_executeContract'].onCreated(function(){ var template = this; // Set Defaults TemplateVar.set('sending', false); // show execute part if its a custom contract if(CustomContracts.findOne({address: template.data.address})) TemplateVar.set('executionVisible', true); // check address for code web3.eth.getCode(template.data.address, function(e, code) { if(!e && code.length > 2) { TemplateVar.set(template, 'hasCode', true); } }); }); Template['elements_executeContract'].helpers({ /** Reruns when the data context changes @method (reactiveContext) */ 'reactiveContext': function() { var contractInstance = web3.eth.contract(this.jsonInterface).at(this.address); var contractFunctions = []; var contractConstants = []; _.each(this.jsonInterface, function(func, i){ func = _.clone(func); // Walk throught the jsonInterface and extract functions and constants if(func.type == 'function') { func.contractInstance = contractInstance; func.inputs = _.map(func.inputs, Helpers.createTemplateDataFromInput); if(func.constant){ // if it's a constant contractConstants.push(func); } else { //if its a variable contractFunctions.push(func); } } }); TemplateVar.set('contractConstants', contractConstants); TemplateVar.set('contractFunctions', contractFunctions); } }); Template['elements_executeContract'].events({ /** Select a contract function @event 'change .select-contract-function */ 'change .select-contract-function': function(e, template){ TemplateVar.set('executeData', null); // change the inputs and data field TemplateVar.set('selectedFunction', _.find(TemplateVar.get('contractFunctions'), function(contract){ return contract.name === e.currentTarget.value; })); Tracker.afterFlush(function(){ $('.abi-input').trigger('change'); }); }, /** Click the show hide button @event click .toggle-visibility */ 'click .toggle-visibility': function(){ TemplateVar.set('executionVisible', !TemplateVar.get('executionVisible')); } }); /** The contract constants template @class [template] elements_executeContract_constant @constructor */ /** Formats the values for display @method formatOutput */ var formatOutput = function(val) { if(_.isArray(val)) return _.map(val, formatOutput); else { // stringify boolean if(_.isBoolean(val)) val = val ? 'YES' : 'NO'; // convert bignumber objects val = (_.isObject(val) && val.toString) ? val.toString(10) : val; return val; } }; Template['elements_executeContract_constant'].onCreated(function(){ var template = this; // initialize our input data prior to the first call TemplateVar.set('inputs', _.map(template.data.inputs, function(input) { return Helpers.addInputValue([input], input, {})[0]; })); // call the contract functions when data changes and on new blocks this.autorun(function() { // make reactive to the latest block EthBlocks.latest; // get args for the constant function var args = TemplateVar.get('inputs') || []; // add callback args.push(function(e, r) { if(!e) { var outputs = []; // single return value if(template.data.outputs.length === 1) { template.data.outputs[0].value = r; outputs.push(template.data.outputs[0]); // multiple return values } else { outputs = _.map(template.data.outputs, function(output, i) { output.value = r[i]; return output; }); } TemplateVar.set(template, 'outputs', outputs); } }); template.data.contractInstance[template.data.name].apply(null, args); }); }); Template['elements_executeContract_constant'].helpers({ /** Formats the value if its a big number or array @method (value) */ 'value': function() { return _.isArray(this.value) ? formatOutput(this.value) : [formatOutput(this.value)]; }, /** Figures out extra data @method (extra) */ 'extra': function() { var data = formatOutput(this); // 1000000000 if (data > 1400000000 && data < 1800000000 && Math.floor(data/1000) != data/1000) { return '(' + moment(data*1000).fromNow() + ')'; } if (data == 'YES') { return '<span class="icon icon-check"></span>'; } else if (data == 'NO') { return '<span class="icon icon-ban"></span>' } return; } }); Template['elements_executeContract_constant'].events({ /** React on user input on the constant functions @event change .abi-input, input .abi-input */ 'change .abi-input, input .abi-input': function(e, template) { var inputs = Helpers.addInputValue(template.data.inputs, this, e.currentTarget); TemplateVar.set('inputs', inputs); } }); /** The contract function template @class [template] elements_executeContract_function @constructor */ Template['elements_executeContract_function'].onCreated(function(){ var template = this; // change the amount when the currency unit is changed template.autorun(function(c){ var unit = EthTools.getUnit(); if(!c.firstRun) { TemplateVar.set('amount', EthTools.toWei(template.find('input[name="amount"]').value.replace(',','.'), unit)); } }); }); Template['elements_executeContract_function'].onRendered(function(){ // Run all inputs through formatter to catch bools this.$('.abi-input').trigger('change'); }); Template['elements_executeContract_function'].helpers({ 'reactiveDataContext': function(){ if(this.inputs.length === 0) TemplateVar.set('executeData', this.contractInstance[this.name].getData()); } }); Template['elements_executeContract_function'].events({ /** Set the amount while typing @event keyup input[name="amount"], change input[name="amount"], input input[name="amount"] */ 'keyup input[name="amount"], change input[name="amount"], input input[name="amount"]': function(e, template){ var wei = EthTools.toWei(e.currentTarget.value.replace(',','.')); TemplateVar.set('amount', wei || '0'); }, /** React on user input on the execute functions @event change .abi-input, input .abi-input */ 'change .abi-input, input .abi-input': function(e, template) { var inputs = Helpers.addInputValue(template.data.inputs, this, e.currentTarget); TemplateVar.set('executeData', template.data.contractInstance[template.data.name].getData.apply(null, inputs)); }, /** Executes a transaction on contract @event click .execute */ 'click .execute': function(e, template){ var to = template.data.contractInstance.address, gasPrice = 50000000000, estimatedGas = undefined, /* (typeof mist == 'undefined')not working */ amount = TemplateVar.get('amount') || 0, selectedAccount = Helpers.getAccountByAddress(TemplateVar.getFrom('.execute-contract select[name="dapp-select-account"]', 'value')), data = TemplateVar.get('executeData'); var latestTransaction = Transactions.findOne({}, {sort: {timestamp: -1}}); if (latestTransaction && latestTransaction.gasPrice) gasPrice = latestTransaction.gasPrice; if(selectedAccount) { console.log('Providing gas: ', estimatedGas ,' + 100000'); if(selectedAccount.balance === '0') return GlobalNotification.warning({ content: 'i18n:wallet.send.error.emptyWallet', duration: 2 }); // The function to send the transaction var sendTransaction = function(estimatedGas){ TemplateVar.set('sending', true); // CONTRACT TX if(contracts['ct_'+ selectedAccount._id]) { // Load the accounts owned by user and sort by balance var accounts = EthAccounts.find({name: {$exists: true}}, {sort: {name: 1}}).fetch(); accounts.sort(Helpers.sortByBalance); // Looks for them among the wallet account owner var fromAccount = _.find(accounts, function(acc){ return (selectedAccount.owners.indexOf(acc.address)>=0); }) contracts['ct_'+ selectedAccount._id].execute.sendTransaction(to || '', amount || '', data || '', { from: fromAccount.address, gasPrice: gasPrice, gas: estimatedGas }, function(error, txHash){ TemplateVar.set(template, 'sending', false); console.log(error, txHash); if(!error) { console.log('SEND from contract', amount); addTransactionAfterSend(txHash, amount, selectedAccount.address, to, gasPrice, estimatedGas, data); FlowRouter.go('dashboard'); } else { // EthElements.Modal.hide(); GlobalNotification.error({ content: error.message, duration: 8 }); } }); // SIMPLE TX } else { web3.eth.sendTransaction({ from: selectedAccount.address, to: to, data: data, value: amount, gasPrice: gasPrice, gas: estimatedGas }, function(error, txHash){ TemplateVar.set(template, 'sending', false); console.log(error, txHash); if(!error) { console.log('SEND simple'); addTransactionAfterSend(txHash, amount, selectedAccount.address, to, gasPrice, estimatedGas, data); // FlowRouter.go('dashboard'); GlobalNotification.success({ content: 'i18n:wallet.send.transactionSent', duration: 2 }); } else { // EthElements.Modal.hide(); GlobalNotification.error({ content: error.message, duration: 8 }); } }); } }; sendTransaction(estimatedGas); } } });
EarthDollar/ed-meteor-dapp-wallet
app/client/templates/elements/executeContract.js
JavaScript
gpl-3.0
11,818
/* * Leaktrack, a Memory Leack Tracker. * Copyright (C) 2002-2008 Aymerick Jehanne <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * GPL v2: http://www.gnu.org/licenses/gpl.txt * * Contact: [email protected] * Home: http://libwbxml.aymerick.com */ /** * @file lt_log.h * @ingroup leaktrack * * @brief Log Functions * * @note Code adapted from Kannel project (http://www.kannel.org/) */ #ifndef LEAKTRACK_LOG_H #define LEAKTRACK_LOG_H /** * @brief Open the log file * @param filename The logfile name */ LT_DECLARE(void) lt_log_open_file(char *filename); /** * @brief Logging function * @param e If different from 0, try to resolve a system error * @param fmt The log text (in printf style) */ LT_DECLARE_NONSTD(void) lt_log(int e, const char *fmt, ...); /** * @brief Close the log file */ LT_DECLARE(void) lt_log_close_file(void); #endif
Muzikatoshi/omega
vendor/github.com/libwbxml/libwbxml/win32/leaktrack/lt_log.h
C
gpl-3.0
1,570
/* * Copyright (C) 2016 Douglas Wurtele * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wurtele.ArmyTracker.models.enumerations; /** * * @author Douglas Wurtele */ public enum AbsenceStatusType { SUBMITTED, APPROVED, DISAPPROVED; }
dougwurtele/Army-Tracker
src/main/java/org/wurtele/ArmyTracker/models/enumerations/AbsenceStatusType.java
Java
gpl-3.0
857
package org.zarroboogs.weibo.widget.galleryview; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.FloatMath; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.OnScaleGestureListener; import android.view.VelocityTracker; import android.view.ViewConfiguration; public abstract class VersionedGestureDetector { static final String LOG_TAG = "VersionedGestureDetector"; OnGestureListener mListener; public static VersionedGestureDetector newInstance(Context context, OnGestureListener listener) { final int sdkVersion = Build.VERSION.SDK_INT; VersionedGestureDetector detector = null; if (sdkVersion < Build.VERSION_CODES.ECLAIR) { detector = new CupcakeDetector(context); } else if (sdkVersion < Build.VERSION_CODES.FROYO) { detector = new EclairDetector(context); } else { detector = new FroyoDetector(context); } detector.mListener = listener; return detector; } public abstract boolean onTouchEvent(MotionEvent ev); public abstract boolean isScaling(); public static interface OnGestureListener { public void onDrag(float dx, float dy); public void onFling(float startX, float startY, float velocityX, float velocityY); public void onScale(float scaleFactor, float focusX, float focusY); } private static class CupcakeDetector extends VersionedGestureDetector { float mLastTouchX; float mLastTouchY; final float mTouchSlop; final float mMinimumVelocity; public CupcakeDetector(Context context) { final ViewConfiguration configuration = ViewConfiguration.get(context); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mTouchSlop = configuration.getScaledTouchSlop(); } private VelocityTracker mVelocityTracker; private boolean mIsDragging; float getActiveX(MotionEvent ev) { return ev.getX(); } float getActiveY(MotionEvent ev) { return ev.getY(); } public boolean isScaling() { return false; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); mLastTouchX = getActiveX(ev); mLastTouchY = getActiveY(ev); mIsDragging = false; break; } case MotionEvent.ACTION_MOVE: { final float x = getActiveX(ev); final float y = getActiveY(ev); final float dx = x - mLastTouchX, dy = y - mLastTouchY; if (!mIsDragging) { // Use Pythagoras to see if drag length is larger than // touch slop mIsDragging = FloatMath.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop; } if (mIsDragging) { mListener.onDrag(dx, dy); mLastTouchX = x; mLastTouchY = y; if (null != mVelocityTracker) { mVelocityTracker.addMovement(ev); } } break; } case MotionEvent.ACTION_CANCEL: { // Recycle Velocity Tracker if (null != mVelocityTracker) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; } case MotionEvent.ACTION_UP: { if (mIsDragging) { if (null != mVelocityTracker) { mLastTouchX = getActiveX(ev); mLastTouchY = getActiveY(ev); // Compute velocity within the last 1000ms mVelocityTracker.addMovement(ev); mVelocityTracker.computeCurrentVelocity(1000); final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker.getYVelocity(); // If the velocity is greater than minVelocity, call // listener if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) { mListener.onFling(mLastTouchX, mLastTouchY, -vX, -vY); } } } // Recycle Velocity Tracker if (null != mVelocityTracker) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; } } return true; } } @TargetApi(5) private static class EclairDetector extends CupcakeDetector { private static final int INVALID_POINTER_ID = -1; private int mActivePointerId = INVALID_POINTER_ID; private int mActivePointerIndex = 0; public EclairDetector(Context context) { super(context); } @Override float getActiveX(MotionEvent ev) { try { return ev.getX(mActivePointerIndex); } catch (Exception e) { return ev.getX(); } } @Override float getActiveY(MotionEvent ev) { try { return ev.getY(mActivePointerIndex); } catch (Exception e) { return ev.getY(); } } @Override public boolean onTouchEvent(MotionEvent ev) { final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mActivePointerId = ev.getPointerId(0); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mActivePointerId = INVALID_POINTER_ID; break; case MotionEvent.ACTION_POINTER_UP: final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = ev.getPointerId(newPointerIndex); mLastTouchX = ev.getX(newPointerIndex); mLastTouchY = ev.getY(newPointerIndex); } break; } mActivePointerIndex = ev.findPointerIndex(mActivePointerId != INVALID_POINTER_ID ? mActivePointerId : 0); return super.onTouchEvent(ev); } } @TargetApi(8) private static class FroyoDetector extends EclairDetector { private final ScaleGestureDetector mDetector; // Needs to be an inner class so that we don't hit // VerifyError's on API 4. private final OnScaleGestureListener mScaleListener = new OnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { mListener.onScale(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY()); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { // NO-OP } }; public FroyoDetector(Context context) { super(context); mDetector = new ScaleGestureDetector(context, mScaleListener); } @Override public boolean isScaling() { return mDetector.isInProgress(); } @Override public boolean onTouchEvent(MotionEvent ev) { mDetector.onTouchEvent(ev); return super.onTouchEvent(ev); } } }
MehmetNuri/Beebo
app/src/main/java/org/zarroboogs/weibo/widget/galleryview/VersionedGestureDetector.java
Java
gpl-3.0
8,826
/*************************************************************************** * Copyright (C) 2011-2017 Alexander V. Popov. * * This file is part of Molecular Dynamics Trajectory * Reader & Analyzer (MDTRA) source code. * * MDTRA source code 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. * * MDTRA source code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***************************************************************************/ // Purpose: // Implementation of MDTRA_ResultDialog #include "mdtra_main.h" #include "mdtra_mainWindow.h" #include "mdtra_project.h" #include "mdtra_utils.h" #include "mdtra_resultDialog.h" #include "mdtra_resultDataSourceDialog.h" #include "mdtra_multiResultDataSourceDialog.h" #include <QtGui/QMessageBox> #include <QtGui/QPushButton> static const char *szScaleUnitNames[MDTRA_YSU_MAX] = { "Angstroms", "Nanometers", "Degrees", "Radians", "Kcal/A", "Micronewtons", "Square Angstroms", "Square Nanometers", }; static unsigned int uiScaleUnitMap[MDTRA_YSU_MAX] = { (1 << MDTRA_DT_RMSD) | (1 << MDTRA_DT_RMSD_SEL) | (1 << MDTRA_DT_RMSF) | (1 << MDTRA_DT_RMSF_SEL) | (1 << MDTRA_DT_RADIUS_OF_GYRATION) | (1 << MDTRA_DT_DISTANCE), (1 << MDTRA_DT_RMSD) | (1 << MDTRA_DT_RMSD_SEL) | (1 << MDTRA_DT_RMSF) | (1 << MDTRA_DT_RMSF_SEL) | (1 << MDTRA_DT_RADIUS_OF_GYRATION) | (1 << MDTRA_DT_DISTANCE), (1 << MDTRA_DT_ANGLE) | (1 << MDTRA_DT_ANGLE2) | (1 << MDTRA_DT_TORSION) | (1 << MDTRA_DT_TORSION_UNSIGNED) | (1 << MDTRA_DT_DIHEDRAL) | (1 << MDTRA_DT_DIHEDRAL_ABS) | (1 << MDTRA_DT_PLANEANGLE), (1 << MDTRA_DT_ANGLE) | (1 << MDTRA_DT_ANGLE2) | (1 << MDTRA_DT_TORSION) | (1 << MDTRA_DT_TORSION_UNSIGNED) | (1 << MDTRA_DT_DIHEDRAL) | (1 << MDTRA_DT_DIHEDRAL_ABS) | (1 << MDTRA_DT_PLANEANGLE), (1 << MDTRA_DT_FORCE) | (1 << MDTRA_DT_RESULTANT_FORCE), (1 << MDTRA_DT_FORCE) | (1 << MDTRA_DT_RESULTANT_FORCE), (1 << MDTRA_DT_SAS) | (1 << MDTRA_DT_SAS_SEL) | (1 << MDTRA_DT_OCCA) | (1 << MDTRA_DT_OCCA_SEL), (1 << MDTRA_DT_SAS) | (1 << MDTRA_DT_SAS_SEL) | (1 << MDTRA_DT_OCCA) | (1 << MDTRA_DT_OCCA_SEL), }; MDTRA_ResultDialog :: MDTRA_ResultDialog( int index, QWidget *parent ) : QDialog( parent ) { m_pMainWindow = qobject_cast<MDTRA_MainWindow*>(parent); assert(m_pMainWindow != NULL); setupUi( this ); setFixedSize( width(), height() ); setWindowIcon( QIcon(":/png/16x16/result.png") ); if (index < 0) { setWindowTitle( tr("Add Result Collector") ); } else { setWindowTitle( tr("Edit Result Collector") ); } m_iResultIndex = index; MDTRA_DataType currentDT = MDTRA_DT_RMSD; MDTRA_YScaleUnits currentSU = MDTRA_YSU_ANGSTROMS; MDTRA_Layout currentL = UTIL_GetDataSourceDefaultLayout(currentDT); if (index < 0) { QString resultTitle = tr("Result %1").arg(m_pMainWindow->getResultCounter()); lineEdit->setText(resultTitle); } else { MDTRA_Result *pResult = m_pMainWindow->getProject()->fetchResultByIndex( index ); if (pResult) { lineEdit->setText( pResult->name ); currentDT = pResult->type; currentSU = pResult->units; currentL = pResult->layout; dsScaleUnitsCombo->setEnabled( currentDT != MDTRA_DT_USER ); for (int i = 0; i < pResult->sourceList.count(); i++) { m_dsRefList << pResult->sourceList.at(i); MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( pResult->sourceList.at(i).dataSourceIndex ); QListWidgetItem *pItem = new QListWidgetItem( QObject::tr("DATA SOURCE %1: %2\nScale = %3 Bias = %4") .arg(pDS->index) .arg(pDS->name) .arg(pResult->sourceList.at(i).yscale) .arg(pResult->sourceList.at(i).bias), dsList ); pItem->setIcon( QIcon(":/png/16x16/source.png") ); } } } for (int i = 0; i < MDTRA_DT_MAX; i++) { dsTypeCombo->addItem( UTIL_GetDataSourceShortTypeName(i) ); if (UTIL_GetDataSourceTypeId(i) == currentDT) dsTypeCombo->setCurrentIndex(i); } for (int i = 0, j = 0; i < MDTRA_YSU_MAX; i++) { if (uiScaleUnitMap[i] & (1 << (int)currentDT)) { dsScaleUnitsCombo->addItem( szScaleUnitNames[i], i ); if (i == (int)currentSU) dsScaleUnitsCombo->setCurrentIndex(j); j++; } } switch (currentL) { default: case MDTRA_LAYOUT_TIME: rbTime->setChecked( true ); break; case MDTRA_LAYOUT_RESIDUE: rbRes->setChecked( true ); break; } rbLabel->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); rbTime->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); rbRes->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); connect(dsTypeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(exec_on_update_layout_and_scale_units())); connect(lineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(exec_on_check_resultInput())); connect(buttonBox, SIGNAL(accepted()), this, SLOT(exec_on_accept())); connect(dsAdd, SIGNAL(clicked()), this, SLOT(exec_on_add_result_data_source())); connect(dsAddMulti, SIGNAL(clicked()), this, SLOT(exec_on_add_multiple_result_data_sources())); connect(dsEdit, SIGNAL(clicked()), this, SLOT(exec_on_edit_result_data_source())); connect(dsList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(exec_on_edit_result_data_source())); connect(dsRemove, SIGNAL(clicked()), this, SLOT(exec_on_remove_result_data_source())); connect(dsUp, SIGNAL(clicked()), this, SLOT(exec_on_up_result_data_source())); connect(dsDown, SIGNAL(clicked()), this, SLOT(exec_on_down_result_data_source())); exec_on_check_resultInput(); } void MDTRA_ResultDialog :: exec_on_update_layout_and_scale_units( void ) { MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); int currentDTi = (int)currentDT; int currentSU = dsScaleUnitsCombo->itemData(dsScaleUnitsCombo->currentIndex()).toUInt(); MDTRA_Layout currentL = UTIL_GetDataSourceDefaultLayout(currentDT); rbLabel->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); rbTime->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); rbRes->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); switch (currentL) { default: case MDTRA_LAYOUT_TIME: rbTime->setChecked( true ); break; case MDTRA_LAYOUT_RESIDUE: rbRes->setChecked( true ); break; } dsScaleUnitsCombo->clear(); for (int i = 0, j = 0; i < MDTRA_YSU_MAX; i++) { if (uiScaleUnitMap[i] & (1 << currentDTi)) { dsScaleUnitsCombo->addItem( szScaleUnitNames[i], i ); if (i == currentSU) dsScaleUnitsCombo->setCurrentIndex(j); j++; } } dsScaleUnitsCombo->setEnabled( currentDT != MDTRA_DT_USER ); } void MDTRA_ResultDialog :: exec_on_check_resultInput( void ) { dsTypeCombo->setEnabled( dsList->count() == 0 ); dsUp->setEnabled( dsList->count() > 1 ); dsDown->setEnabled( dsList->count() > 1 ); buttonBox->button( QDialogButtonBox::Ok )->setEnabled( (lineEdit->text().length() > 0) && (dsList->count() > 0)); } void MDTRA_ResultDialog :: exec_on_accept( void ) { if (m_iResultIndex < 0) { if (!m_pMainWindow->getProject()->checkUniqueResultName( lineEdit->text() )) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("Result \"%1\" already registered.\nPlease enter another result title.").arg(lineEdit->text())); return; } } MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); MDTRA_YScaleUnits currentSU = (MDTRA_YScaleUnits)dsScaleUnitsCombo->itemData(dsScaleUnitsCombo->currentIndex()).toUInt(); MDTRA_Layout currentL; if (rbRes->isChecked()) currentL = MDTRA_LAYOUT_RESIDUE; else currentL = MDTRA_LAYOUT_TIME; if (m_iResultIndex < 0) { m_pMainWindow->getProject()->registerResult( lineEdit->text(), currentDT, currentSU, currentL, m_dsRefList, true ); } else { m_pMainWindow->getProject()->modifyResult( m_iResultIndex, lineEdit->text(), currentDT, currentSU, currentL, m_dsRefList ); } accept(); } void MDTRA_ResultDialog :: exec_on_add_result_data_source( void ) { MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); MDTRA_ResultDataSourceDialog dialog( currentDT, NULL, m_pMainWindow, this ); if (!dialog.GetAvailableDataSourceCount()) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("No data sources of type \"%1\" are registered!").arg(UTIL_GetDataSourceShortTypeName(dsTypeCombo->currentIndex()))); return; } QString sCheckUserData(""); bool bCheckUserData = false; if (m_dsRefList.count() > 0) { MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( m_dsRefList.at(0).dataSourceIndex ); sCheckUserData = pDS->userdata; bCheckUserData = true; } if (dialog.exec()) { MDTRA_DSRef newdsref; dialog.GetResultDataSource( &newdsref ); MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( newdsref.dataSourceIndex ); if ( bCheckUserData && (sCheckUserData != pDS->userdata) ) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("Cannot add user-defined Data Source of type \"%1\"!\nThe Result Collector already has user-defined Data Source of type \"%2\".").arg(pDS->userdata).arg(sCheckUserData)); return; } m_dsRefList << newdsref; QListWidgetItem *pItem = new QListWidgetItem( QObject::tr("DATA SOURCE %1: %2\nScale = %3 Bias = %4") .arg(pDS->index) .arg(pDS->name) .arg(newdsref.yscale) .arg(newdsref.bias), dsList ); pItem->setIcon( QIcon(":/png/16x16/source.png") ); exec_on_check_resultInput(); } } void MDTRA_ResultDialog :: exec_on_edit_result_data_source( void ) { MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); QListWidgetItem *pItem = dsList->currentItem(); MDTRA_DSRef *pCurrentRef = const_cast<MDTRA_DSRef*>(&m_dsRefList.at(dsList->currentRow())); MDTRA_ResultDataSourceDialog dialog( currentDT, pCurrentRef, m_pMainWindow, this ); if (dialog.exec()) { dialog.GetResultDataSource( pCurrentRef ); MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( pCurrentRef->dataSourceIndex ); pItem->setText( QObject::tr("DATA SOURCE %1: %2\nScale = %3 Bias = %4") .arg(pDS->index) .arg(pDS->name) .arg(pCurrentRef->yscale) .arg(pCurrentRef->bias)); } } void MDTRA_ResultDialog :: exec_on_remove_result_data_source( void ) { if (dsList->selectedItems().count() <= 0) return; if (QMessageBox::No == QMessageBox::warning( this, tr("Confirm"), tr("Do you want to remove selected result data source from the list?"), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape )) { return; } int itemIndex = dsList->currentRow(); m_dsRefList.removeAt( itemIndex ); QListWidgetItem *pItem = dsList->currentItem(); dsList->removeItemWidget( pItem ); delete pItem; exec_on_check_resultInput(); } void MDTRA_ResultDialog :: exec_on_up_result_data_source( void ) { if (dsList->selectedItems().count() <= 0) return; int itemIndex = dsList->currentRow(); if (itemIndex <= 0) return; m_dsRefList.swap( itemIndex, itemIndex-1 ); QListWidgetItem *currentItem = dsList->takeItem( itemIndex ); dsList->insertItem( itemIndex - 1, currentItem ); dsList->setCurrentItem( currentItem ); } void MDTRA_ResultDialog :: exec_on_down_result_data_source( void ) { if (dsList->selectedItems().count() <= 0) return; int itemIndex = dsList->currentRow(); if (itemIndex >= dsList->count()-1) return; m_dsRefList.swap( itemIndex, itemIndex+1 ); QListWidgetItem *currentItem = dsList->takeItem( itemIndex ); dsList->insertItem( itemIndex + 1, currentItem ); dsList->setCurrentItem( currentItem ); } void MDTRA_ResultDialog :: exec_on_add_multiple_result_data_sources( void ) { MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); MDTRA_MultiResultDataSourceDialog dialog( currentDT, m_pMainWindow, this ); if (!dialog.GetAvailableDataSourceCount()) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("No data sources of type \"%1\" are registered!").arg(UTIL_GetDataSourceShortTypeName(dsTypeCombo->currentIndex()))); return; } QString sCheckUserData(""); bool bCheckUserData = false; if (m_dsRefList.count() > 0) { MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( m_dsRefList.at(0).dataSourceIndex ); sCheckUserData = pDS->userdata; bCheckUserData = true; } if (dialog.exec()) { for (int i = 0; i < dialog.GetAvailableDataSourceCount(); i++) { MDTRA_DSRef newdsref; if (!dialog.GetResultDataSource( i, &newdsref )) continue; MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( newdsref.dataSourceIndex ); if ( bCheckUserData && (sCheckUserData != pDS->userdata) ) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("Cannot add user-defined Data Source of type \"%1\"!\nThe Result Collector already has user-defined Data Source of type \"%2\".").arg(pDS->userdata).arg(sCheckUserData)); continue; } m_dsRefList << newdsref; QListWidgetItem *pItem = new QListWidgetItem( QObject::tr("DATA SOURCE %1: %2\nScale = %3 Bias = %4") .arg(pDS->index) .arg(pDS->name) .arg(newdsref.yscale) .arg(newdsref.bias), dsList ); pItem->setIcon( QIcon(":/png/16x16/source.png") ); if ( !bCheckUserData ) { sCheckUserData = pDS->userdata; bCheckUserData = true; } } exec_on_check_resultInput(); } }
MrXaeroX/MDTRA
src/mdtra_resultDialog.cpp
C++
gpl-3.0
14,044
/** * Track the trackers * Copyright (C) 2014 Sebastian Schelter, Felix Neutatz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.ssc.trackthetrackers.analysis.statistics object Dataset { def numPaylevelDomains = 42889800 def domainsByCompany = Map( //addthis.com 1136762 -> "AddThis", //amazon.com 2150098 -> "Amazon", //images-amazon.com 18691888 -> "Amazon", //casalemedia.com 6971664 -> "CasaleMedia", //facebook.net 13237946 -> "Facebook", //fbcdn.net 13481035 -> "Facebook", //facebook.com 13237914 -> "Facebook", //google.com 15964788 -> "Google", //doubleclick.net 11142763 -> "Google", //googlesyndication.com 15967902 -> "Google", //youtube.com 42467638 -> "Google", //google-analytics.com 15964105 -> "Google", //googleadservices.com 15965227 -> "Google", //feedburner.com 13536774 -> "Google", //recaptcha.net 31564322 -> "Google", //photobucket.com 29569518 -> "PhotoBucket", //statcounter.com 35757837 -> "StatCounter", //twitter.com 39224483 -> "Twitter", //twimg.com 39210295 -> "Twitter", //yahooapis.com 42207014 -> "Yahoo", //yahoo.com 42206842 -> "Yahoo", //yahoo.net 42206882 -> "Yahoo", //yimg.com 42318764 -> "Yahoo", //tumblr.com 39095913 -> "Yahoo", //flickr.com 14050903 -> "Yahoo", //geocities.com 15358455 -> "Yahoo" ) }
HungUnicorn/trackthetrackers
analysis/src/main/scala/io/ssc/trackthetrackers/analysis/statistics/Dataset.scala
Scala
gpl-3.0
2,093
;; ;; CTC test for NEZ80 (Darkstar) MultiF-Board ;; CTCBASE EQU $E8 CTCCHAN0 EQU CTCBASE+0 ; Channel 1 - Free CTCCHAN1 EQU CTCBASE+1 ; Channel 2 - Free CTCCHAN2 EQU CTCBASE+2 ; Channel 3 - UART 1 Interrupt CTCCHAN3 EQU CTCBASE+3 ; Channel 4 - UART 0 Interrupt LF EQU 0AH CR EQU 0DH BS EQU 08H ;Back space (required for sector display) BELL EQU 07H TAB EQU 09H ;TAB ACROSS (8 SPACES FOR SD-BOARD) ESC EQU 1BH CLEAR EQU 1CH ;SD Systems Video Board, Clear to EOL. (Use 80 spaces if EOL not available ;on other video cards) RDCON EQU 1 ;For CP/M I/O WRCON EQU 2 PRINT EQU 9 CONST EQU 11 ;CONSOLE STAT BDOS EQU 5 FALSE EQU 0 TRUE EQU -1 QUIT EQU 0 ORG $100 INITIALIZE: ; initialize CTC Chan 0 as timer and test interrupts DI IM 2 LD A,$10 ; Vector table base MSB ($1000) LD I,A LD A,00000011b OUT (CTCCHAN0),A LD A,10100111b ; Command word OUT (CTCCHAN0),A LD A,$FF ; 4M / 256 / 256 = 122 ticks per sec. OUT (CTCCHAN0),A LD A,$00 ; CTC handler locations in int. vector OUT (CTCCHAN0),A LD DE,MSINIT ; Wait for start CALL PSTRING CALL ZCI EI ; let things run ENDLOOP: JP ENDLOOP CALL ZCSTS CP $01 JR NZ,ENDLOOP DI JP QUIT IHANDLCH0: LD DE,MSICH0 JR DONEINT IHANDLCH1: LD DE,MSICH1 JR DONEINT IHANDLCH2: LD DE,MSICH2 JR DONEINT IHANDLCH3: LD DE,MSICH3 JR DONEINT DONEINT: CALL PSTRING EI RETI ZCSTS: PUSH BC PUSH DE PUSH HL LD C,CONST CALL BDOS ;Returns with 1 in [A] if character at keyboard POP HL POP DE POP BC CP 1 RET ; ZCO: ;Write character that is in [C] PUSH AF PUSH BC PUSH DE PUSH HL LD E,C LD C,WRCON CALL BDOS POP HL POP DE POP BC POP AF RET ZCI: ;Return keyboard character in [A] PUSH BC PUSH DE PUSH HL LD C,RDCON CALL BDOS POP HL POP DE POP BC RET ; ; ; ;Print a string in [DE] up to '$' PSTRING: LD C,PRINT JP BDOS ;PRINT MESSAGE, ; ;------------------------------------------------------------------------------- MSINIT DB 'CTC initalized, a key to go...',CR,LF,'$' MSICH0 DB 'Channel 0 interrupt!',CR,LF,'$' MSICH1 DB 'Channel 1 interrupt!',CR,LF,'$' MSICH2 DB 'Channel 2 interrupt!',CR,LF,'$' MSICH3 DB 'Channel 3 interrupt!',CR,LF,'$' ; ;------------------------------------------------------------------------------- ORG $1000 INTVEC: THNDLCH0: DW IHANDLCH0 THNDLCH1: DW IHANDLCH1 THNDLCH2: DW IHANDLCH2 THNDLCH3: DW IHANDLCH3 TVECFILL: DS 247 TVECEND: DB 0 ;------------------------------------------------------------------------------- END
pbetti/ZDS
hw-devel/MultiF-Board/CTC/ctc.asm
Assembly
gpl-3.0
2,484
# dict_exp_result_types _namespace: [SMRUCC.genomics.Data.Regtransbase.MySQL](./index.md)_ -- DROP TABLE IF EXISTS `dict_exp_result_types`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `dict_exp_result_types` ( `exp_result_type_guid` int(11) NOT NULL DEFAULT '0', `name` varchar(100) DEFAULT NULL, PRIMARY KEY (`exp_result_type_guid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; --
amethyst-asuka/GCModeller
manual/sdk_api/docs/SMRUCC.genomics.Data.Regtransbase.MySQL/dict_exp_result_types.md
Markdown
gpl-3.0
529
#Region "Microsoft.VisualBasic::9562de1d3b30395990f3c41fe48394df, ..\GCModeller\engine\GCModeller\EngineSystem\Services\DataAcquisition\DataAdapters\Proteome.vb" ' Author: ' ' asuka ([email protected]) ' xieguigang ([email protected]) ' xie ([email protected]) ' ' Copyright (c) 2016 GPL3 Licensed ' ' ' GNU GENERAL PUBLIC LICENSE (GPL3) ' ' 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/>. #End Region Imports SMRUCC.genomics.GCModeller.ModellingEngine.EngineSystem.Services.DataAcquisition.DataSerializer Imports SMRUCC.genomics.GCModeller.ModellingEngine.EngineSystem.Services.DataAcquisition.Services Namespace EngineSystem.Services.DataAcquisition.DataAdapters Public Class Proteome : Inherits EngineSystem.Services.DataAcquisition.DataAdapter(Of EngineSystem.ObjectModels.SubSystem.ProteinAssembly) Implements IDataAdapter Public Overrides ReadOnly Property TableName As String Get Return "proteome" End Get End Property Sub New(System As EngineSystem.ObjectModels.SubSystem.ProteinAssembly) Call MyBase.New(System) End Sub Public Overrides Function DataSource() As DataSource() Dim LQuery = From Protein In MyBase.System.Proteins Let value = Protein.DataSource Select value ' Return LQuery.ToArray End Function Public Overrides Function DefHandles() As HandleF() Return (From item In MyBase.System.Proteins Select item.SerialsHandle).ToArray End Function End Class End Namespace
amethyst-asuka/GCModeller
src/GCModeller/engine/GCModeller/EngineSystem/Services/DataAcquisition/DataAdapters/Proteome.vb
Visual Basic
gpl-3.0
2,283
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- **************************************************************** --> <!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * --> <!-- * i.e. only iterate & print data where possible. Thanks, Jez. * --> <!-- **************************************************************** --> <html> <head> <!-- Generated by groovydoc (2.3.3) on Tue Jul 01 09:50:55 CEST 2014 --> <title>ComponentResult (Gradle API 2.0)</title> <meta name="date" content="2014-07-01"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon"> <link href="../../../../../groovy.ico" type="image/x-icon" rel="icon"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <body class="center"> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ComponentResult (Gradle API 2.0)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <div> <ul class="navList"> <li><a href="../../../../../index.html?org/gradle/api/artifacts/result/ComponentResult" target="_top">Frames</a></li> <li><a href="ComponentResult.html" target="_top">No Frames</a></li> </ul> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> Nested&nbsp;&nbsp;&nbsp;Field&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li><a href="#method_summary">Method</a></li>&nbsp;&nbsp;&nbsp; </ul> <ul class="subNavList"> <li>&nbsp;|&nbsp;Detail:&nbsp;</li> Field&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li><a href="#method_detail">Method</a></li>&nbsp;&nbsp;&nbsp; </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">Package: <strong>org.gradle.api.artifacts.result</strong></div> <h2 title="[Java] Interface ComponentResult" class="title">[Java] Interface ComponentResult</h2> </div> <div class="contentContainer"> <ul class="inheritance"> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <p> The result of resolving a component. <DL><DT><B>Since:</B></DT><DD>2.0</DD></DL></p> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== NESTED CLASS SUMMARY =========== --> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <!-- =========== FIELD SUMMARY =========== --> <!-- =========== PROPERTY SUMMARY =========== --> <!-- =========== ELEMENT SUMMARY =========== --> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"><!-- --></a> <h3>Methods Summary</h3> <ul class="blockList"> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Methods Summary table"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Type</th> <th class="colLast" scope="col">Name and description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href='../../../../../org/gradle/api/artifacts/component/ComponentIdentifier.html'>ComponentIdentifier</a></strong></code></td> <td class="colLast"><code><strong><a href="#getId()">getId</a></strong>()</code><br>Returns the ID of the requested component.</td> </tr> </table> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- =========== METHOD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getId()"><!-- --></a> <ul class="blockListLast"> <li class="blockList"> <h4>public&nbsp;<a href='../../../../../org/gradle/api/artifacts/component/ComponentIdentifier.html'>ComponentIdentifier</a> <strong>getId</strong>()</h4> <p> Returns the ID of the requested component. </p> </li> </ul> </li> </ul> </li> </ul> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <div> <ul class="navList"> <li><a href="../../../../../index.html?org/gradle/api/artifacts/result/ComponentResult" target="_top">Frames</a></li> <li><a href="ComponentResult.html" target="_top">No Frames</a></li> </ul> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> Nested&nbsp;&nbsp;&nbsp;Field&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li><a href="#method_summary">Method</a></li>&nbsp;&nbsp;&nbsp; </ul> <ul class="subNavList"> <li>&nbsp;|&nbsp;Detail:&nbsp;</li> Field&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li><a href="#method_detail">Method</a></li>&nbsp;&nbsp;&nbsp; </ul> </div> <p>Gradle API 2.0</p> <a name="skip-navbar_bottom"> <!-- --> </a> </div> </div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
VolitionEos/DungFactory
.gradlew/wrapper/dists/gradle-2.0-all/7rd4e4rcg4riqi0j6j508m2lbk/gradle-2.0/docs/groovydoc/org/gradle/api/artifacts/result/ComponentResult.html
HTML
gpl-3.0
7,713
package DataHash; use strict; use warnings; use DirHandle; use List::Util qw(max); use List::MoreUtils qw{uniq}; use Exporter; our (@ISA, @EXPORT_OK); @ISA =qw(Exporter); @EXPORT_OK = qw(get_data_hash dump_column_to_files); =pod =head1 get_data_hash get_data_hash hashes all of the data.number.language files in the output directory and returns all of the information from the data files hashed. The results are checked for consistency via ... =cut sub get_data_hash { my $output_dir = shift; my $hash; my $d = DirHandle->new($output_dir); if (defined $d) { while (defined(my $file = $d->read)) { next unless ($file =~ /^data\.([\w+-]+)\.(\d+)$/); my $language = $1; my $number = $2; if (open(my $fh, "<", join('/', $output_dir, $file))) { while (<$fh>) { if ($. == 2) { chomp; $_ =~ s/\s+//g; $hash->{$language}->{$number}->{result} = $_; } elsif ($. == 3) { my ($user, $system, $elapsed) = ($_ =~ /^([\d.:]+)user\s+([\d.:]+)system\s+([\d.:]+)elapsed/); $hash->{$language}->{$number}->{user} = $user; $hash->{$language}->{$number}->{system} = $system; $hash->{$language}->{$number}->{elapsed} = $elapsed; } } close $fh; } else { print "Can not open $file, $!\n"; } } undef $d; } check_results($hash); return $hash; } =pod =head1 check_results check results takes the hash constructed in get_data_hash and checks that all of the results are consistent. =cut sub check_results { my $hash = shift; # find the language with the highest number of solutions my @lang_nums; foreach my $language (keys %$hash) { push @lang_nums, {$language => scalar keys %{$hash->{$language}}}; } my $max_pair = max @lang_nums; # check the unique number of results per problem - # if it is > 1 then we have found an anomaly my $first = (keys %$max_pair)[0]; foreach my $number (sort {$a <=> $b} keys %{$hash->{$first}}) { my @results; foreach my $language (sort keys %$hash) { my $result = $hash->{$language}->{$number}->{result}; push @results, $result if defined $result; } my $uniq = uniq @results; if ($uniq > 1) { print "----------------------------\n"; print "RESULTS ERROR for number $number\n"; foreach my $language (keys %$hash) { print $language,"\t'",$hash->{$language}->{$number}->{result},"'\n"; } } } } =pod =head1 dump_column_to_files dump_column_to_files constructs a hash via get_data_hash and dumps a slice of this hash into a file. invoked via : dump_column_to_files($output_dir, "times", "user"); and : dump_column_to_files($output_dir, "output", "result"); =cut sub dump_column_to_files { my $output_dir = shift; my $suffix = shift; my $field = shift; my $hash = get_data_hash($output_dir); foreach my $language (sort keys %$hash) { my $file = join('.', $language, $suffix); if (open(my $fh, ">", join('/', $output_dir, $file))) { foreach my $number (sort {$a <=> $b} keys %{$hash->{$language}}) { my $hlnf = $hash->{$language}->{$number}->{$field}; print $fh (defined $hlnf) ? $hlnf : '*',"\n"; } } else { print "Can not open $file, $!\n" } } } 1;
bobblestiltskin/project_euler
scripts/DataHash.pm
Perl
gpl-3.0
3,344
/* * IIIFProducer * Copyright (C) 2017 Leipzig University Library <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package de.ubleipzig.iiifproducer.template; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.fasterxml.jackson.core.JsonProcessingException; import java.io.File; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; public class SerializerExceptionTest { @Mock private TemplateStructure mockStructure; @BeforeEach public void setUp() { initMocks(this); when(mockStructure.getStructureLabel()).thenReturn("a structure"); } @Test public void testError() { when(mockStructure.getStructureLabel()).thenAnswer(inv -> { sneakyJsonException(); return "a structure"; }); final Optional<String> json = ManifestSerializer.serialize(mockStructure); assertFalse(json.isPresent()); } @Test void testIOException() { final String json = "{}"; final File outfile = new File("/an-invalid-path"); assertEquals(false, ManifestSerializer.writeToFile(json, outfile)); } @SuppressWarnings("unchecked") private static <T extends Throwable> void sneakyThrow(final Throwable e) throws T { throw (T) e; } private static void sneakyJsonException() { sneakyThrow(new JsonProcessingException("expected") { }); } }
ubleipzig/iiif-producer
templates/src/test/java/de/ubleipzig/iiifproducer/template/SerializerExceptionTest.java
Java
gpl-3.0
2,279
package com.github.ypid.complexalarm; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import android.content.Context; import android.content.res.AssetManager; import android.util.Log; import com.evgenii.jsevaluator.JsEvaluator; import com.evgenii.jsevaluator.JsFunctionCallFormatter; import com.evgenii.jsevaluator.interfaces.JsCallback; /* * Simple wrapper for the API documented here: * https://github.com/ypid/opening_hours.js#library-api */ public class OpeningHours { private JsEvaluator mJsEvaluator; final private String nominatiomTestJSONString = "{\"place_id\":\"44651229\",\"licence\":\"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\"osm_type\":\"way\",\"osm_id\":\"36248375\",\"lat\":\"49.5400039\",\"lon\":\"9.7937133\",\"display_name\":\"K 2847, Lauda-K\u00f6nigshofen, Main-Tauber-Kreis, Regierungsbezirk Stuttgart, Baden-W\u00fcrttemberg, Germany, European Union\",\"address\":{\"road\":\"K 2847\",\"city\":\"Lauda-K\u00f6nigshofen\",\"county\":\"Main-Tauber-Kreis\",\"state_district\":\"Regierungsbezirk Stuttgart\",\"state\":\"Baden-W\u00fcrttemberg\",\"country\":\"Germany\",\"country_code\":\"de\",\"continent\":\"European Union\"}}"; private Scanner scanner; private String globalResult; private String getFileContent(String fileName, Context context) throws IOException { final AssetManager am = context.getAssets(); final InputStream inputStream = am.open(fileName); scanner = new Scanner(inputStream, "UTF-8"); return scanner.useDelimiter("\\A").next(); } private String loadJs(String fileName, Context context) { try { return getFileContent(fileName, context); } catch (final IOException e) { e.printStackTrace(); } return null; } protected OpeningHours(Context context) { Log.d("OpeningHours", "Loading up opening_hours.js"); mJsEvaluator = new JsEvaluator(context); String librarySrouce = loadJs("javascript-libs/suncalc/suncalc.min.js", context); mJsEvaluator.evaluate(librarySrouce); librarySrouce = loadJs( "javascript-libs/opening_hours/opening_hours.min.js", context); mJsEvaluator.evaluate(librarySrouce); } protected String evalOpeningHours(String value, String nominatiomJSON, byte oh_mode) { String ohConstructorCall = "new opening_hours('" + value + "', JSON.parse('" + nominatiomJSON + "'), " + oh_mode + ")"; Log.d("OpeningHours constructor", ohConstructorCall); final String code = "var oh, warnings, crashed = true;" + "try {" + " oh = " + ohConstructorCall + ";" + " warnings = oh.getWarnings();" + " crashed = false;" + "} catch(err) {" + " crashed = err;" + "}" + "oh.getNextChange().toString();" + // "crashed.toString();" + ""; mJsEvaluator.evaluate(code, new JsCallback() { @Override public void onResult(final String resultValue) { Log.d("OpeningHours", String.format("Result: %s", resultValue)); } }); return "test"; } protected String getDate() { globalResult = null; mJsEvaluator.evaluate("new Date().toString()", new JsCallback() { @Override public void onResult(final String resultValue) { Log.d("Date", String.format("Result: %s", resultValue)); // Block until event occurs. globalResult = resultValue; Log.d("Date", String.format("globalResult: %s", globalResult)); } }); for (int i = 0; i < 100; i++) { Log.d("Date", String.format("%d, %s", i, globalResult)); try { Log.d("Date", "sleep"); Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block Log.d("Date", "Catch"); e.printStackTrace(); } if (globalResult != null) { break; } } return globalResult; } protected String returnDate() { return globalResult; } protected String evalOpeningHours(String value, String nominatiomJSON) { return evalOpeningHours(value, nominatiomJSON, (byte) 0); } protected String evalOpeningHours(String value) { // evalOpeningHours(value, "{}"); return evalOpeningHours(value, nominatiomTestJSONString); // FIXME // testing // only } }
ypid/ComplexAlarm
src/com/github/ypid/complexalarm/OpeningHours.java
Java
gpl-3.0
4,883
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Surname - CARTY</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li class = "CurrentSection"><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="SurnameDetail"> <h3>CARTY</h3> <p id="description"> This page contains an index of all the individuals in the database with the surname of CARTY. Selecting the person&#8217;s name will take you to that person&#8217;s individual page. </p> <table class="infolist primobjlist surname"> <thead> <tr> <th class="ColumnName">Given Name</th> <th class="ColumnDate">Birth</th> <th class="ColumnDate">Death</th> <th class="ColumnPartner">Partner</th> <th class="ColumnParents">Parents</th> </tr> </thead> <tbody> <tr> <td class="ColumnName"> <a href="../../../ppl/a/7/d15f5fcded238cdd56331c5547a.html">P. C.<span class="grampsid"> [I1565]</span></a> </td> <td class="ColumnBirth">&nbsp;</td> <td class="ColumnDeath">&nbsp;</td> <td class="ColumnPartner"> <a href="../../../ppl/0/b/d15f5fcde9579098d591c1c59b0.html">CUTCLIFFE, Mildred Lucille<span class="grampsid"> [I1564]</span></a> </td> <td class="ColumnParents">&nbsp;</td> </tr> </tbody> </table> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:06<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/srn/e/d/c072ac2090ff5b9841e27a50479f47de.html
HTML
gpl-3.0
3,141
{% extends "base.html" %} {% block header %} 成功新增记录! {% endblock %} {% block body %} {% endblock %}
ytao/py_rz
app/templates/success.html
HTML
gpl-3.0
114
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # file: $Id$ # auth: metagriffin <[email protected]> # date: 2012/04/20 # copy: (C) Copyright 2012-EOT metagriffin -- see LICENSE.txt #------------------------------------------------------------------------------ # This software 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 software is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # 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 .tracker import * from .merger import * #------------------------------------------------------------------------------ # end of $Id$ #------------------------------------------------------------------------------
metagriffin/pysyncml
pysyncml/change/__init__.py
Python
gpl-3.0
1,255
/* classes: h_files */ #ifndef SCM_HASHTAB_H #define SCM_HASHTAB_H /* Copyright (C) 1995,1996,1999,2000,2001, 2003, 2004, 2006, 2008, 2009, 2011 Free Software Foundation, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "libguile/__scm.h" #define SCM_HASHTABLE_P(x) (SCM_HAS_TYP7 (x, scm_tc7_hashtable)) #define SCM_VALIDATE_HASHTABLE(pos, arg) \ SCM_MAKE_VALIDATE_MSG (pos, arg, HASHTABLE_P, "hash-table") #define SCM_HASHTABLE_VECTOR(h) SCM_CELL_OBJECT_1 (h) #define SCM_SET_HASHTABLE_VECTOR(x, v) SCM_SET_CELL_OBJECT_1 ((x), (v)) #define SCM_HASHTABLE(x) ((scm_t_hashtable *) SCM_CELL_WORD_2 (x)) #define SCM_HASHTABLE_N_ITEMS(x) (SCM_HASHTABLE (x)->n_items) #define SCM_SET_HASHTABLE_N_ITEMS(x, n) (SCM_HASHTABLE (x)->n_items = n) #define SCM_HASHTABLE_INCREMENT(x) (SCM_HASHTABLE_N_ITEMS(x)++) #define SCM_HASHTABLE_DECREMENT(x) (SCM_HASHTABLE_N_ITEMS(x)--) #define SCM_HASHTABLE_UPPER(x) (SCM_HASHTABLE (x)->upper) #define SCM_HASHTABLE_LOWER(x) (SCM_HASHTABLE (x)->lower) #define SCM_HASHTABLE_N_BUCKETS(h) \ SCM_SIMPLE_VECTOR_LENGTH (SCM_HASHTABLE_VECTOR (h)) #define SCM_HASHTABLE_BUCKET(h, i) \ SCM_SIMPLE_VECTOR_REF (SCM_HASHTABLE_VECTOR (h), i) #define SCM_SET_HASHTABLE_BUCKET(h, i, x) \ SCM_SIMPLE_VECTOR_SET (SCM_HASHTABLE_VECTOR (h), i, x) /* Function that computes a hash of OBJ modulo MAX. */ typedef unsigned long (*scm_t_hash_fn) (SCM obj, unsigned long max, void *closure); /* Function that returns the value associated with OBJ in ALIST according to some equality predicate. */ typedef SCM (*scm_t_assoc_fn) (SCM obj, SCM alist, void *closure); /* Function to fold over the entries of a hash table. */ typedef SCM (*scm_t_hash_fold_fn) (void *closure, SCM key, SCM value, SCM result); /* Function to iterate over the handles (key-value pairs) of a hash table. */ typedef SCM (*scm_t_hash_handle_fn) (void *closure, SCM handle); typedef struct scm_t_hashtable { unsigned long n_items; /* number of items in table */ unsigned long lower; /* when to shrink */ unsigned long upper; /* when to grow */ int size_index; /* index into hashtable_size */ int min_size_index; /* minimum size_index */ scm_t_hash_fn hash_fn; /* for rehashing after a GC. */ } scm_t_hashtable; SCM_API SCM scm_vector_to_hash_table (SCM vector); SCM_API SCM scm_c_make_hash_table (unsigned long k); SCM_API SCM scm_make_hash_table (SCM n); SCM_API SCM scm_hash_table_p (SCM h); SCM_INTERNAL void scm_i_rehash (SCM table, scm_t_hash_fn hash_fn, void *closure, const char *func_name); SCM_API SCM scm_hash_fn_get_handle (SCM table, SCM obj, scm_t_hash_fn hash_fn, scm_t_assoc_fn assoc_fn, void *closure); SCM_API SCM scm_hash_fn_create_handle_x (SCM table, SCM obj, SCM init, scm_t_hash_fn hash_fn, scm_t_assoc_fn assoc_fn, void *closure); SCM_API SCM scm_hash_fn_ref (SCM table, SCM obj, SCM dflt, scm_t_hash_fn hash_fn, scm_t_assoc_fn assoc_fn, void *closure); SCM_API SCM scm_hash_fn_set_x (SCM table, SCM obj, SCM val, scm_t_hash_fn hash_fn, scm_t_assoc_fn assoc_fn, void *closure); SCM_API SCM scm_hash_fn_remove_x (SCM table, SCM obj, scm_t_hash_fn hash_fn, scm_t_assoc_fn assoc_fn, void *closure); SCM_API SCM scm_internal_hash_fold (scm_t_hash_fold_fn fn, void *closure, SCM init, SCM table); SCM_API void scm_internal_hash_for_each_handle (scm_t_hash_handle_fn fn, void *closure, SCM table); SCM_API SCM scm_hash_clear_x (SCM table); SCM_API SCM scm_hashq_get_handle (SCM table, SCM obj); SCM_API SCM scm_hashq_create_handle_x (SCM table, SCM obj, SCM init); SCM_API SCM scm_hashq_ref (SCM table, SCM obj, SCM dflt); SCM_API SCM scm_hashq_set_x (SCM table, SCM obj, SCM val); SCM_API SCM scm_hashq_remove_x (SCM table, SCM obj); SCM_API SCM scm_hashv_get_handle (SCM table, SCM obj); SCM_API SCM scm_hashv_create_handle_x (SCM table, SCM obj, SCM init); SCM_API SCM scm_hashv_ref (SCM table, SCM obj, SCM dflt); SCM_API SCM scm_hashv_set_x (SCM table, SCM obj, SCM val); SCM_API SCM scm_hashv_remove_x (SCM table, SCM obj); SCM_API SCM scm_hash_get_handle (SCM table, SCM obj); SCM_API SCM scm_hash_create_handle_x (SCM table, SCM obj, SCM init); SCM_API SCM scm_hash_ref (SCM table, SCM obj, SCM dflt); SCM_API SCM scm_hash_set_x (SCM table, SCM obj, SCM val); SCM_API SCM scm_hash_remove_x (SCM table, SCM obj); SCM_API SCM scm_hashx_get_handle (SCM hash, SCM assoc, SCM table, SCM obj); SCM_API SCM scm_hashx_create_handle_x (SCM hash, SCM assoc, SCM table, SCM obj, SCM init); SCM_API SCM scm_hashx_ref (SCM hash, SCM assoc, SCM table, SCM obj, SCM dflt); SCM_API SCM scm_hashx_set_x (SCM hash, SCM assoc, SCM table, SCM obj, SCM val); SCM_API SCM scm_hashx_remove_x (SCM hash, SCM assoc, SCM table, SCM obj); SCM_API SCM scm_hash_fold (SCM proc, SCM init, SCM hash); SCM_API SCM scm_hash_for_each (SCM proc, SCM hash); SCM_API SCM scm_hash_for_each_handle (SCM proc, SCM hash); SCM_API SCM scm_hash_map_to_list (SCM proc, SCM hash); SCM_INTERNAL void scm_i_hashtable_print (SCM exp, SCM port, scm_print_state *pstate); SCM_INTERNAL void scm_init_hashtab (void); #endif /* SCM_HASHTAB_H */ /* Local Variables: c-file-style: "gnu" End: */
skangas/guile
libguile/hashtab.h
C
gpl-3.0
5,980
/** * Copyright (c) 2000-2004 Liferay, LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dotmarketing.portlets.mailinglists.action; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import com.dotcms.repackage.portlet.javax.portlet.PortletConfig; import com.dotcms.repackage.portlet.javax.portlet.RenderRequest; import com.dotcms.repackage.portlet.javax.portlet.RenderResponse; import com.dotcms.repackage.portlet.javax.portlet.WindowState; import javax.servlet.jsp.PageContext; import com.dotcms.repackage.commons_beanutils.org.apache.commons.beanutils.BeanUtils; import com.dotcms.repackage.struts.org.apache.struts.action.ActionForm; import com.dotcms.repackage.struts.org.apache.struts.action.ActionForward; import com.dotcms.repackage.struts.org.apache.struts.action.ActionMapping; import com.dotmarketing.business.Role; import com.dotmarketing.portlets.mailinglists.factories.MailingListFactory; import com.dotmarketing.portlets.mailinglists.model.MailingList; import com.dotmarketing.portlets.userfilter.factories.UserFilterFactory; import com.dotmarketing.util.Config; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.model.User; import com.liferay.portal.struts.PortletAction; import com.liferay.portal.util.Constants; /** * <a href="ViewQuestionsAction.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * @version $Revision: 1.4 $ * */ public class ViewMailingListsAction extends PortletAction { public ActionForward render( ActionMapping mapping, ActionForm form, PortletConfig config, RenderRequest req, RenderResponse res) throws Exception { Logger.debug(this, "Running ViewMailingListsAction"); try { //get the user, order, direction User user = com.liferay.portal.util.PortalUtil.getUser(req); String orderBy = req.getParameter("orderby"); String direction = req.getParameter("direction"); String condition = req.getParameter("query"); //get their lists List list = null; List roles = com.dotmarketing.business.APILocator.getRoleAPI().loadRolesForUser(user.getUserId()); boolean isMarketingAdmin = false; Iterator rolesIt = roles.iterator(); while (rolesIt.hasNext()) { Role role = (Role) rolesIt.next(); if (UtilMethods.isSet(role.getRoleKey()) && role.getRoleKey().equals(Config.getStringProperty("MAILINGLISTS_ADMIN_ROLE"))) { isMarketingAdmin = true; break; } } if (isMarketingAdmin) { if (UtilMethods.isSet(orderBy) && UtilMethods.isSet(direction)) { //list = MailingListFactory.getAllMailingLists(orderBy, direction); list = MailingListFactory.getAllMailingLists(); list.addAll(UserFilterFactory.getAllUserFilter()); if (orderBy.equals("title")) { if (direction.equals(" asc")) Collections.sort(list, new ComparatorTitleAsc()); else Collections.sort(list, new ComparatorTitleDesc()); } } else if(UtilMethods.isSet(condition)) { list = MailingListFactory.getAllMailingListsCondition(condition); list.addAll(UserFilterFactory.getUserFilterByTitle(condition)); Collections.sort(list, new ComparatorTitleAsc()); } else { list = MailingListFactory.getAllMailingLists(); list.addAll(UserFilterFactory.getAllUserFilter()); Collections.sort(list, new ComparatorTitleAsc()); } } else { if (UtilMethods.isSet(orderBy) && UtilMethods.isSet(direction)) { //list = MailingListFactory.getMailingListsByUser(user, orderBy, direction); list = MailingListFactory.getMailingListsByUser(user); list.add(MailingListFactory.getUnsubscribersMailingList()); list.addAll(UserFilterFactory.getAllUserFilterByUser(user)); if (orderBy.equals("title")) { if (direction.equals(" asc")) Collections.sort(list, new ComparatorTitleAsc()); else Collections.sort(list, new ComparatorTitleDesc()); } } else if(UtilMethods.isSet(condition)) { list = MailingListFactory.getMailingListsByUserCondition(user, condition); list.add(MailingListFactory.getUnsubscribersMailingList()); list.addAll(UserFilterFactory.getUserFilterByTitleAndUser(condition, user)); Collections.sort(list, new ComparatorTitleAsc()); } else { list = MailingListFactory.getMailingListsByUser(user); list.add(MailingListFactory.getUnsubscribersMailingList()); list.addAll(UserFilterFactory.getAllUserFilterByUser(user)); Collections.sort(list, new ComparatorTitleAsc()); } } if (req.getWindowState().equals(WindowState.NORMAL)) { // if (list != null) // list = orderMailingListByDescDate(list); req.setAttribute(WebKeys.MAILING_LIST_VIEW_PORTLET, list); return mapping.findForward("portlet.ext.mailinglists.view"); } else { req.setAttribute(WebKeys.MAILING_LIST_VIEW, list); return mapping.findForward("portlet.ext.mailinglists.view_mailinglists"); } } catch (Exception e) { req.setAttribute(PageContext.EXCEPTION, e); return mapping.findForward(Constants.COMMON_ERROR); } } private List<MailingList> orderMailingListByDescDate(List<MailingList> list) { List<MailingList> result = new ArrayList<MailingList>(list.size()); int i; boolean added; MailingList mailingList2; for (MailingList mailingList1: list) { if (result.size() == 0) { result.add(mailingList1); } else { added = false; for (i = 0; i < result.size(); ++i) { mailingList2 = result.get(i); if (mailingList2.getIDate().before(mailingList1.getIDate())) { result.add(i, mailingList1); added = true; break; } } if (!added) result.add(mailingList1); } } return result; } private class ComparatorTitleAsc implements Comparator { public int compare(Object o1, Object o2) { String title1, title2; try { if (o1 instanceof MailingList) title1 = BeanUtils.getProperty(o1, "title"); else title1 = BeanUtils.getProperty(o1, "userFilterTitle"); } catch (Exception e) { title1 = ""; } try { if (o2 instanceof MailingList) title2 = BeanUtils.getProperty(o2, "title"); else title2 = BeanUtils.getProperty(o2, "userFilterTitle"); } catch (Exception e) { title2 = ""; } return title1.compareToIgnoreCase(title2); } } private class ComparatorTitleDesc implements Comparator { public int compare(Object o1, Object o2) { String title1, title2; try { if (o1 instanceof MailingList) title1 = BeanUtils.getProperty(o1, "title"); else title1 = BeanUtils.getProperty(o1, "userFilterTitle"); } catch (Exception e) { title1 = ""; } try { if (o2 instanceof MailingList) title2 = BeanUtils.getProperty(o2, "title"); else title2 = BeanUtils.getProperty(o2, "userFilterTitle"); } catch (Exception e) { title2 = ""; } return title2.compareToIgnoreCase(title1); } } }
austindlawless/dotCMS
src/com/dotmarketing/portlets/mailinglists/action/ViewMailingListsAction.java
Java
gpl-3.0
8,207
/***************************************************************************** * Written by Chris Dunlap <[email protected]>. * Copyright (C) 2007-2021 Lawrence Livermore National Security, LLC. * Copyright (C) 2001-2007 The Regents of the University of California. * UCRL-CODE-2002-009. * * This file is part of ConMan: The Console Manager. * For details, see <https://dun.github.io/conman/>. * * ConMan 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. * * ConMan 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 ConMan. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ /* FIXME: * This code does not fully handle the following cases: * - when the watched directory does not yet exist * - when the watched directory is later deleted * In the event of the watched directory not yet existing, this code should * watch the parent directory for its subsequent creation; if the parent * does not yet exist, it should watch the parent's parent, etc., up to the * root. This might be best accomplished by initially registering all of * parent directories up to the root for the directory being watched. * In the event of the watched directory being deleted (event IN_IGNORED), * once the existing watch has been removed, this should degenerate into the * case above where the watched directory does not yet exist. * * Currently, inotify works as expected as long as the parent directory being * watched persists for the lifetime of the daemon. But once that * directory's inode is removed, the daemon falls back to using timers to * periodically resurrect downed objects. */ #if HAVE_CONFIG_H # include <config.h> #endif /* HAVE_CONFIG_H */ /***************************************************************************** * Stubbed Routines for building without <sys/inotify.h>. * * These routines preserve type-checking while allowing any decent compiler * to optimize the case of simply returning a constant integer such that * no function call overhead is incurred. *****************************************************************************/ #if ! HAVE_SYS_INOTIFY_H #include "inevent.h" int inevent_add (const char *filename, inevent_cb_f cb_fnc, void *cb_arg) { return (-1); } int inevent_remove (const char *filename) { return (-1); } int inevent_get_fd (void) { return (-1); } int inevent_process (void) { return (-1); } /***************************************************************************** * Routines for building with <sys/inotify.h> (Linux 2.6.13+). *****************************************************************************/ #else /* HAVE_SYS_INOTIFY_H */ #include <assert.h> #include <errno.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/inotify.h> #include <unistd.h> #include "inevent.h" #include "list.h" #include "log.h" #include "util-file.h" /***************************************************************************** * Constants *****************************************************************************/ /* Number of bytes for the average inotify event (w/ 16 bytes for name). */ #define INEVENT_SIZE ((sizeof (struct inotify_event)) + 16) /* Number of average inotify events to process per read invocation. */ #define INEVENT_NUM 128 /* Number of bytes to allocate for the inotify event buffer. */ #define INEVENT_BUF_LEN ((INEVENT_SIZE) * (INEVENT_NUM)) /***************************************************************************** * Internal Data Types *****************************************************************************/ struct inevent { char *pathname; /* pathname being watched */ char *dirname; /* directory component of pathname */ char *filename; /* filename component of pathname */ inevent_cb_f cb_fnc; /* callback function */ void *cb_arg; /* callback function arg */ int wd; /* inotify watch descriptor */ }; typedef struct inevent inevent_t; /***************************************************************************** * Private Function Prototypes *****************************************************************************/ static int _inevent_init (void); static void _inevent_fini (void); static inevent_t * _inevent_create (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg); static void _inevent_destroy (inevent_t *inevent_ptr); static int _list_find_by_path (const inevent_t *inevent_ptr, const char *pathname); static int _list_find_by_wd (const inevent_t *inevent_ptr, const int *wd_ptr); static int _list_find_by_event (const inevent_t *inevent_ptr, const struct inotify_event *event_ptr); /***************************************************************************** * Internal Data Variables *****************************************************************************/ static int inevent_fd = -1; /* inotify file descriptor */ static List inevent_list = NULL; /* list of inevent structs */ /***************************************************************************** * Public Functions *****************************************************************************/ int inevent_add (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg) { /* Adds an inotify event for [pathname], causing [cb_fnc] to be invoked with * [cb_arg] whenever the specified file is created. * Returns 0 on success, or -1 on error. */ inevent_t *inevent_ptr; if (pathname == NULL) { log_msg (LOG_ERR, "inotify event pathname not specified"); return (-1); } if (cb_fnc == NULL) { log_msg (LOG_ERR, "inotify event callback not specified"); return (-1); } if (pathname[0] != '/') { log_msg (LOG_ERR, "inotify event path \"%s\" is not absolute", pathname); return (-1); } if (inevent_fd == -1) { if (_inevent_init () < 0) { log_msg (LOG_ERR, "unable to initialize inotify: %s", strerror (errno)); return (-1); } } if (list_find_first (inevent_list, (ListFindF) _list_find_by_path, (void *) pathname)) { log_msg (LOG_ERR, "inotify event path \"%s\" already specified", pathname); return (-1); } inevent_ptr = _inevent_create (pathname, cb_fnc, cb_arg); if (inevent_ptr == NULL) { return (-1); } list_append (inevent_list, inevent_ptr); return (0); } int inevent_remove (const char *pathname) { /* Removes the inotify event (if present) for [pathname]. * Returns 0 on success, or -1 on error. */ ListIterator li = NULL; inevent_t *inevent_ptr; int wd_cnt; if (pathname == NULL) { return (0); } if (inevent_list == NULL) { return (0); } li = list_iterator_create (inevent_list); inevent_ptr = list_find (li, (ListFindF) _list_find_by_path, (void *) pathname); if (inevent_ptr == NULL) { log_msg (LOG_ERR, "inotify event path \"%s\" not registered", pathname); list_iterator_destroy (li); return (0); } (void) list_remove (li); list_iterator_reset (li); wd_cnt = 0; while (list_find (li, (ListFindF) _list_find_by_wd, &(inevent_ptr->wd))) { wd_cnt++; } list_iterator_destroy (li); /* If no other inevents were found with a matching wd, then this inevent * is the only one associated with this watch descriptor. As such, the * watch associated with this watch descriptor can be removed since no * other objects are relying on it. * Note that multiple files may share the same watch descriptor since it * is the file's directory that is watched. */ if ((inevent_ptr->wd >= 0) && (wd_cnt == 0)) { (void) inotify_rm_watch (inevent_fd, inevent_ptr->wd); DPRINTF((10, "Removed inotify watch wd=%d for directory \"%s\".\n", inevent_ptr->wd, inevent_ptr->dirname)); } _inevent_destroy (inevent_ptr); if (list_is_empty (inevent_list)) { _inevent_fini (); } return (0); } int inevent_get_fd (void) { /* Returns the file descriptor associated with the inotify event queue, * or -1 on error. */ return (inevent_fd); } int inevent_process (void) { /* Processes the callback functions for all available events in the inotify * event queue. * Returns the number of events processed on success, or -1 on error. */ char buf [INEVENT_BUF_LEN]; int len; int n = 0; if (inevent_fd == -1) { return (-1); } retry_read: len = read (inevent_fd, buf, sizeof (buf)); if (len < 0) { if (errno == EINTR) { goto retry_read; } log_msg (LOG_ERR, "unable to read inotify fd: %s", strerror (errno)); return (-1); } else if (len == 0) { log_msg (LOG_ERR, "inotify read buffer is too small"); return (-1); } else { unsigned int i = 0; uint32_t event_mask = IN_CREATE | IN_MOVED_TO; while (i < (unsigned int) len) { struct inotify_event *event_ptr; inevent_t *inevent_ptr; event_ptr = (struct inotify_event *) &buf[i]; DPRINTF((15, "Received inotify event wd=%d mask=0x%x len=%u name=\"%s\".\n", event_ptr->wd, event_ptr->mask, event_ptr->len, (event_ptr->len > 0 ? event_ptr->name : ""))); if (event_ptr->mask & IN_IGNORED) { (void) list_delete_all (inevent_list, (ListFindF) _list_find_by_wd, &(event_ptr->wd)); } else if ((event_ptr->mask & event_mask) && (event_ptr->len > 0)) { inevent_ptr = list_find_first (inevent_list, (ListFindF) _list_find_by_event, event_ptr); if ((inevent_ptr != NULL) && (inevent_ptr->cb_fnc != NULL)) { inevent_ptr->cb_fnc (inevent_ptr->cb_arg); } } i += sizeof (struct inotify_event) + event_ptr->len; n++; } } return (n); } /***************************************************************************** * Private Functions *****************************************************************************/ static int _inevent_init (void) { /* Initializes the inotify event subsystem. * Returns 0 on success, or -1 on error (with errno set). */ assert (inevent_fd == -1); assert (inevent_list == NULL); if (inevent_fd == -1) { inevent_fd = inotify_init (); if (inevent_fd == -1) { goto err; } set_fd_closed_on_exec (inevent_fd); set_fd_nonblocking (inevent_fd); } if (inevent_list == NULL) { inevent_list = list_create ((ListDelF) _inevent_destroy); if (inevent_list == NULL) { goto err; } } DPRINTF((5, "Initialized inotify event subsystem.\n")); return (inevent_fd); err: _inevent_fini (); return (-1); } static void _inevent_fini (void) { /* Shuts down the inotify event subsystem. */ assert (inevent_fd >= 0); assert (inevent_list != NULL); if (inevent_fd >= 0) { (void) close (inevent_fd); inevent_fd = -1; } if (inevent_list != NULL) { list_destroy (inevent_list); inevent_list = NULL; } DPRINTF((5, "Shut down inotify event subsystem.\n")); return; } static inevent_t * _inevent_create (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg) { /* Creates an inotify event object for [cb_fnc] to be invoked with [cb_arg] * whenever the file specified by [pathname] is created. * Returns a pointer to the new object on success, or NULL on error * (with errno set). */ inevent_t *inevent_ptr = NULL; char *p; uint32_t event_mask = IN_CREATE | IN_MOVED_TO; assert (pathname != NULL); assert (pathname[0] == '/'); assert (cb_fnc != NULL); inevent_ptr = malloc (sizeof (*inevent_ptr)); if (inevent_ptr == NULL) { goto err; } memset (inevent_ptr, 0, sizeof (*inevent_ptr)); inevent_ptr->wd = -1; inevent_ptr->pathname = strdup (pathname); if (inevent_ptr->pathname == NULL) { goto err; } inevent_ptr->dirname = strdup (pathname); if (inevent_ptr->dirname == NULL) { goto err; } p = strrchr (inevent_ptr->dirname, '/'); inevent_ptr->filename = strdup (p + 1); if (inevent_ptr->filename == NULL) { goto err; } if (p == inevent_ptr->dirname) { /* dirname is root directory ("/") */ *++p = '\0'; } else { *p = '\0'; } inevent_ptr->cb_fnc = cb_fnc; inevent_ptr->cb_arg = cb_arg; inevent_ptr->wd = inotify_add_watch (inevent_fd, inevent_ptr->dirname, event_mask); if (inevent_ptr->wd == -1) { goto err; } DPRINTF((10, "Added inotify watch wd=%d for \"%s\".\n", inevent_ptr->wd, inevent_ptr->pathname)); return (inevent_ptr); err: _inevent_destroy (inevent_ptr); return (NULL); } static void _inevent_destroy (inevent_t *inevent_ptr) { /* Destroys the inotify event object referenced by [inevent_ptr]. */ assert (inevent_ptr != NULL); if (inevent_ptr == NULL) { return; } DPRINTF((10, "Removed inotify watch wd=%d for \"%s\".\n", inevent_ptr->wd, inevent_ptr->pathname)); if (inevent_ptr->pathname != NULL) { free (inevent_ptr->pathname); } if (inevent_ptr->dirname != NULL) { free (inevent_ptr->dirname); } if (inevent_ptr->filename != NULL) { free (inevent_ptr->filename); } free (inevent_ptr); return; } static int _list_find_by_path (const inevent_t *inevent_ptr, const char *pathname) { /* List function helper to match items in a list of inevent_t pointers using * the pathname [pathname] as the key. * Returns non-zero if the key is found; o/w, returns zero. */ assert (inevent_ptr != NULL); assert (pathname != NULL); return (strcmp (inevent_ptr->pathname, pathname) == 0); } static int _list_find_by_wd (const inevent_t *inevent_ptr, const int *wd_ptr) { /* List function helper to match items in a list of inevent_t pointers using * a pointer to an inotify watch descriptor [wd_ptr] as the key. * Returns non-zero if the key is found; o/w, returns zero. */ assert (inevent_ptr != NULL); assert (wd_ptr != NULL); return (inevent_ptr->wd == *wd_ptr); } static int _list_find_by_event (const inevent_t *inevent_ptr, const struct inotify_event *event_ptr) { /* List function helper to match items in a list of inevent_t pointers using * a pointer to an inotify_event struct [event_ptr] as the key. * Returns non-zero if the key is found; o/w, returns zero. */ assert (inevent_ptr != NULL); assert (inevent_ptr->filename != NULL); assert (event_ptr != NULL); assert (event_ptr->len > 0); assert (event_ptr->name != NULL); return ((inevent_ptr->wd == event_ptr->wd) && (strcmp (inevent_ptr->filename, event_ptr->name) == 0)); } #endif /* HAVE_SYS_INOTIFY_H */
dun/conman
inevent.c
C
gpl-3.0
16,114
/* * Copyright (c) 2017 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * 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.obiba.mica.core.service; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import javax.inject.Inject; import javax.validation.constraints.NotNull; import net.minidev.json.JSONArray; import org.obiba.mica.core.domain.SchemaFormContentAware; import org.obiba.mica.file.FileStoreService; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.google.common.collect.Sets; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Option; import com.jayway.jsonpath.PathNotFoundException; import com.jayway.jsonpath.internal.JsonReader; import static com.jayway.jsonpath.Configuration.defaultConfiguration; @Service public class SchemaFormContentFileService { @Inject private FileStoreService fileStoreService; public void save(@NotNull SchemaFormContentAware newEntity, SchemaFormContentAware oldEntity, String entityPath) { Assert.notNull(newEntity, "New content cannot be null"); Object json = defaultConfiguration().jsonProvider().parse(newEntity.getContent()); DocumentContext newContext = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(json); Map<String, JSONArray> newPaths = getPathFilesMap(newContext, json); if (newPaths == null) return; // content does not have any file field if (oldEntity != null) { Object oldJson = defaultConfiguration().jsonProvider().parse(oldEntity.getContent()); DocumentContext oldContext = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(oldJson); Map<String, JSONArray> oldPaths = getPathFilesMap(oldContext, oldJson); if (oldPaths != null) { saveAndDelete(oldPaths, newPaths, entityPath); } else { // schema and definition now have files newPaths.values().forEach(v -> saveFiles(v, entityPath)); } } else { newPaths.values().forEach(v -> saveFiles(v, entityPath)); } cleanup(newPaths, newContext); newEntity.setContent(newContext.jsonString()); } public void deleteFiles(SchemaFormContentAware entity) { Object json = defaultConfiguration().jsonProvider().parse(entity.getContent()); DocumentContext context = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(json); DocumentContext reader = new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json); try { ((JSONArray)context.read("$..obibaFiles")).stream() .map(p -> (JSONArray) reader.read(p.toString())) .flatMap(Collection::stream) .forEach(file -> fileStoreService.delete(((LinkedHashMap)file).get("id").toString())); } catch(PathNotFoundException e) { } } /** * Removes the fields with empty obibaFiles from content. * * @param newPaths * @param newContext */ private void cleanup(Map<String, JSONArray> newPaths, DocumentContext newContext) { newPaths.keySet().forEach(p -> { if (newPaths.get(p).isEmpty()) { newContext.delete(p.replace("['obibaFiles']", "")); } }); } private void saveAndDelete(Map<String, JSONArray> oldPaths, Map<String, JSONArray> newPaths, String entityPath) { newPaths.keySet().forEach(p -> { if (oldPaths.containsKey(p)) { saveAndDeleteFiles(oldPaths.get(p), newPaths.get(p), entityPath); } else { saveFiles(newPaths.get(p), entityPath); } }); } private Map<String, JSONArray> getPathFilesMap(DocumentContext context, Object json) { DocumentContext reader = new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json); JSONArray paths = null; try { paths = context.read("$..obibaFiles"); } catch(PathNotFoundException e) { return null; } return paths.stream().collect(Collectors.toMap(Object::toString, p -> (JSONArray) reader.read(p.toString()))); } private Iterable<Object> saveAndDeleteFiles(JSONArray oldFiles, JSONArray newFiles, String entityPath) { cleanFileJsonArrays(oldFiles, newFiles); Iterable<Object> toDelete = Sets.difference(Sets.newHashSet(oldFiles), Sets.newHashSet(newFiles)); Iterable<Object> toSave = Sets.difference(Sets.newHashSet(newFiles), Sets.newHashSet(oldFiles)); toDelete.forEach(file -> fileStoreService.delete(((LinkedHashMap)file).get("id").toString())); saveFiles(toSave, entityPath); return toDelete; } private void cleanFileJsonArrays(JSONArray... arrays) { if (arrays != null) { Arrays.stream(arrays).forEach(s -> s.forEach(a -> { if (a instanceof LinkedHashMap) { LinkedHashMap<String, String> jsonMap = (LinkedHashMap<String, String>) a; jsonMap.keySet().stream().filter(k -> k.contains("$")).collect(Collectors.toList()).forEach(jsonMap::remove); } })); } } private void saveFiles(Iterable files, String entityPath) { if(files != null) files.forEach(file -> { LinkedHashMap map = (LinkedHashMap)file; map.put("path", entityPath); fileStoreService.save(map.get("id").toString()); }); } }
Rima-B/mica2
mica-core/src/main/java/org/obiba/mica/core/service/SchemaFormContentFileService.java
Java
gpl-3.0
5,584
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer 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 cancer. If not, see <http://www.gnu.org/licenses/>. use libc::c_void; #[repr(C)] pub struct GList { pub data: *mut c_void, pub next: *mut GList, pub prev: *mut GList, } extern "C" { pub fn g_list_free(ptr: *mut GList); pub fn g_object_unref(ptr: *mut c_void); pub fn g_object_ref(ptr: *mut c_void) -> *mut c_void; }
meh/cancer
src/ffi/glib.rs
Rust
gpl-3.0
1,012
body, td, pre { font-family: Arial,Helvetica,sans-serif; font-size: 13px; }
kohascanbit/tabakaleraubik
koha-tmpl/intranet-tmpl/prog/en/css/tinymce.css
CSS
gpl-3.0
86
{% extends "base.html" %} {% block content_title %}Cursos{% endblock %} {% block box_title %}Detalhes Curso: <span class="label label-info">{{ object.pk }}</span>{% endblock %} {% block box_body %} <div class="page-header"> <a class="btn btn-large btn-default" title="Lista" href="{% url 'curso_home' %}"><i class="fa fa-list fa-1x"></i></a> <a class="btn btn-large btn-warning" title="Editar" href="{% url 'curso_atualizar' object.pk %}"><i class="fa fa-edit fa-1x"></i></a> <a class="btn btn-large btn-info" title="Imprimir" href="{% url 'imprime_curso' object.pk %}" ><i class="fa fa-print fa-1x"></i> </a> <a class="btn btn-large btn-danger" title="Excluir" href="{% url 'curso_deletar' object.pk %}"><i class="fa fa-remove fa-1x"></i></a> </div> <div class="row"> <div class="col-md-4"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"> Descrição</h3> <span class="pull-right clickable"></span> </div> <div class="panel-body"> {{ object.descricao }} </div> </div> </div> <div class="col-md-4"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"> Quantidade de Vagas</h3> <span class="pull-right clickable"></span> </div> <div class="panel-body"> {{ object.quant_vaga }} </div> </div> </div> <div class="col-md-4"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"> Carga Horária</h3> <span class="pull-right clickable"></span> </div> <div class="panel-body"> {{ object.carga_horaria }} </div> </div> </div> </div> <div class="row"> <div class="col-md-3"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"> Semestre</h3> <span class="pull-right clickable"></span> </div> <div class="panel-body"> {{ object.semestre }} </div> </div> </div> <div class="col-md-3"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"> Turno</h3> <span class="pull-right clickable"></span> </div> <div class="panel-body"> {{ object.turno }} </div> </div> </div> <div class="col-md-3"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"> Pré-Requisito</h3> <span class="pull-right clickable"></span> </div> <div class="panel-body"> {{ object.get_pre_requisito_display }} </div> </div> </div> <div class="col-md-3"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"> Ativo</h3> <span class="pull-right clickable"></span> </div> <div class="panel-body"> {{ object.get_ativo_display }} </div> </div> </div> </div> <div class="row"> <div class="col-md-2"> <div class="panel panel-info"> <div class="panel-heading clickable"> <h3 class="panel-title"> Quem Cadastrou</h3> <span class="pull-right "></span> </div> <div class="panel-body"> {% if object.quem_criou %} {{ object.quem_criou }} {% else %} Não Informado! {% endif %} </div> </div> </div> <div class="col-md-2"> <div class="panel panel-info"> <div class="panel-heading clickable"> <h3 class="panel-title"> Data Cadastro</h3> <span class="pull-right "></span> </div> <div class="panel-body"> {{ object.data_criacao|date:"d/m/Y"|default:"--/--/---" }} </div> </div> </div> <div class="col-md-2"> <div class="panel panel-info"> <div class="panel-heading clickable"> <h3 class="panel-title"> Hora Cadastro</h3> <span class="pull-right "></span> </div> <div class="panel-body"> {{ object.hora_criacao|time:"h:i:s"|default:"--:--" }} </div> </div> </div> <div class="col-md-2"> <div class="panel panel-info"> <div class="panel-heading clickable"> <h3 class="panel-title"> Quem Alterou</h3> <span class="pull-right "></span> </div> <div class="panel-body"> {% if object.quem_alterou %} {{ object.quem_alterou }} {% else %} Não Informado! {% endif %} </div> </div> </div> <div class="col-md-2"> <div class="panel panel-info"> <div class="panel-heading clickable"> <h3 class="panel-title"> Data Alteração</h3> <span class="pull-right "></span> </div> <div class="panel-body"> {{ object.data_alteracao|date:"d/m/Y" }} </div> </div> </div> <div class="col-md-2"> <div class="panel panel-info"> <div class="panel-heading clickable"> <h3 class="panel-title"> Hora Alteração</h3> <span class="pull-right "></span> </div> <div class="panel-body"> {{ object.hora_alteracao|time:"h:i:s" }} </div> </div> </div> </div> {% endblock %}
dparaujo/projeto
app_academico/curso/templates/curso/detalhe.html
HTML
gpl-3.0
7,191
Bitrix 17.0.9 Business Demo = e475d0cd490d83505c54e6cec1c3d6ed
gohdan/DFC
known_files/hashes/bitrix/modules/bizproc/install/activities/bitrix/webhookactivity/lang/en/webhookactivity.php
PHP
gpl-3.0
63
<?php /* Smarty version Smarty-3.1.19, created on 2017-09-23 12:35:41 compiled from "/var/www/html/admin240x2hjae/themes/default/template/page_header_toolbar.tpl" */ ?> <?php /*%%SmartyHeaderCode:61757368659c68d5d8d2e84-70988510%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( 'd65aaeae6f3a1059b7e9527adddd1e40bec16718' => array ( 0 => '/var/www/html/admin240x2hjae/themes/default/template/page_header_toolbar.tpl', 1 => 1506184509, 2 => 'file', ), ), 'nocache_hash' => '61757368659c68d5d8d2e84-70988510', 'function' => array ( ), 'variables' => array ( 'title' => 0, 'page_header_toolbar_title' => 0, 'page_header_toolbar_btn' => 0, 'current_tab_level' => 0, 'breadcrumbs2' => 0, 'toolbar_btn' => 0, 'k' => 0, 'table' => 0, 'btn' => 0, 'help_link' => 0, 'tab_modules_open' => 0, 'tab_modules_list' => 0, 'tabs' => 0, 'level_1' => 0, 'level_2' => 0, 'level_3' => 0, 'level_4' => 0, ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.19', 'unifunc' => 'content_59c68d5dac6da8_00389838', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_59c68d5dac6da8_00389838')) {function content_59c68d5dac6da8_00389838($_smarty_tpl) {?> <?php if (!isset($_smarty_tpl->tpl_vars['title']->value)&&isset($_smarty_tpl->tpl_vars['page_header_toolbar_title']->value)) {?> <?php $_smarty_tpl->tpl_vars['title'] = new Smarty_variable($_smarty_tpl->tpl_vars['page_header_toolbar_title']->value, null, 0);?> <?php }?> <?php if (isset($_smarty_tpl->tpl_vars['page_header_toolbar_btn']->value)) {?> <?php $_smarty_tpl->tpl_vars['toolbar_btn'] = new Smarty_variable($_smarty_tpl->tpl_vars['page_header_toolbar_btn']->value, null, 0);?> <?php }?> <div class="bootstrap"> <div class="page-head <?php if (isset($_smarty_tpl->tpl_vars['current_tab_level']->value)&&$_smarty_tpl->tpl_vars['current_tab_level']->value==3) {?>with-tabs<?php }?>"> <h2 class="page-title"> <?php if (is_array($_smarty_tpl->tpl_vars['title']->value)) {?><?php echo preg_replace('!<[^>]*?>!', ' ', end($_smarty_tpl->tpl_vars['title']->value));?> <?php } else { ?><?php echo preg_replace('!<[^>]*?>!', ' ', $_smarty_tpl->tpl_vars['title']->value);?> <?php }?> </h2> <ul class="breadcrumb page-breadcrumb"> <?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']!='') {?> <li class="breadcrumb-container"> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']);?> </li> <?php }?> <?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']!=''&&$_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']!=$_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']) {?> <li class="breadcrumb-current"> <?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']!='') {?><a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']);?> "><?php }?> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']);?> <?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']!='') {?></a><?php }?> </li> <?php }?> </ul> <div class="page-bar toolbarBox"> <div class="btn-toolbar"> <a href="#" class="toolbar_btn dropdown-toolbar navbar-toggle" data-toggle="collapse" data-target="#toolbar-nav"><i class="process-icon-dropdown"></i> <div><?php echo smartyTranslate(array('s'=>'Menu'),$_smarty_tpl);?> </div> </a> <ul id="toolbar-nav" class="nav nav-pills pull-right collapse navbar-collapse"> <?php $_smarty_tpl->tpl_vars['btn'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['btn']->_loop = false; $_smarty_tpl->tpl_vars['k'] = new Smarty_Variable; $_from = $_smarty_tpl->tpl_vars['toolbar_btn']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['btn']->key => $_smarty_tpl->tpl_vars['btn']->value) { $_smarty_tpl->tpl_vars['btn']->_loop = true; $_smarty_tpl->tpl_vars['k']->value = $_smarty_tpl->tpl_vars['btn']->key; ?> <?php if ($_smarty_tpl->tpl_vars['k']->value!='back'&&$_smarty_tpl->tpl_vars['k']->value!='modules-list') {?> <li> <a id="page-header-desc-<?php echo $_smarty_tpl->tpl_vars['table']->value;?> -<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['imgclass'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['imgclass']);?> <?php } else { ?><?php echo $_smarty_tpl->tpl_vars['k']->value;?> <?php }?>" class="toolbar_btn <?php if (isset($_smarty_tpl->tpl_vars['btn']->value['target'])&&$_smarty_tpl->tpl_vars['btn']->value['target']) {?> _blank<?php }?> pointer"<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['href'])) {?> href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['href']);?> "<?php }?> title="<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['help'])) {?><?php echo $_smarty_tpl->tpl_vars['btn']->value['help'];?> <?php } else { ?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['desc']);?> <?php }?>"<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['js'])&&$_smarty_tpl->tpl_vars['btn']->value['js']) {?> onclick="<?php echo $_smarty_tpl->tpl_vars['btn']->value['js'];?> "<?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['modal_target'])&&$_smarty_tpl->tpl_vars['btn']->value['modal_target']) {?> data-target="<?php echo $_smarty_tpl->tpl_vars['btn']->value['modal_target'];?> " data-toggle="modal"<?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['help'])) {?> data-toggle="tooltip" data-placement="bottom"<?php }?>> <i class="<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['icon'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['icon']);?> <?php } else { ?>process-icon-<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['imgclass'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['imgclass']);?> <?php } else { ?><?php echo $_smarty_tpl->tpl_vars['k']->value;?> <?php }?><?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['class'])) {?> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['class']);?> <?php }?>"></i> <div<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['force_desc'])&&$_smarty_tpl->tpl_vars['btn']->value['force_desc']==true) {?> class="locked"<?php }?>><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['desc']);?> </div> </a> </li> <?php }?> <?php } ?> <?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list'])) {?> <li> <a id="page-header-desc-<?php echo $_smarty_tpl->tpl_vars['table']->value;?> -<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'];?> <?php } else { ?>modules-list<?php }?>" class="toolbar_btn<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['class'])) {?> <?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['class'];?> <?php }?><?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['target'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['target']) {?> _blank<?php }?>" <?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['href'])) {?>href="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['href'];?> "<?php }?> title="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['desc'];?> "<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js']) {?> onclick="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js'];?> "<?php }?>> <i class="<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['icon'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['icon'];?> <?php } else { ?>process-icon-<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'];?> <?php } else { ?>modules-list<?php }?><?php }?>"></i> <div<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['force_desc'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['force_desc']==true) {?> class="locked"<?php }?>><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['desc'];?> </div> </a> </li> <?php }?> <?php if (isset($_smarty_tpl->tpl_vars['help_link']->value)) {?> <li> <a class="toolbar_btn btn-help" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['help_link']->value);?> " title="<?php echo smartyTranslate(array('s'=>'Help'),$_smarty_tpl);?> "> <i class="process-icon-help"></i> <div><?php echo smartyTranslate(array('s'=>'Help'),$_smarty_tpl);?> </div> </a> </li> <?php }?> </ul> <?php if ((isset($_smarty_tpl->tpl_vars['tab_modules_open']->value)&&$_smarty_tpl->tpl_vars['tab_modules_open']->value)||isset($_smarty_tpl->tpl_vars['tab_modules_list']->value)) {?> <script type="text/javascript"> //<![CDATA[ var modules_list_loaded = false; <?php if (isset($_smarty_tpl->tpl_vars['tab_modules_open']->value)&&$_smarty_tpl->tpl_vars['tab_modules_open']->value) {?> $(function () { $('#modules_list_container').modal('show'); openModulesList(); }); <?php }?> <?php if (isset($_smarty_tpl->tpl_vars['tab_modules_list']->value)) {?> $('.process-icon-modules-list').parent('a').unbind().bind('click', function (event) { event.preventDefault(); $('#modules_list_container').modal('show'); openModulesList(); }); <?php }?> //]]> </script> <?php }?> </div> </div> <?php if (isset($_smarty_tpl->tpl_vars['current_tab_level']->value)&&$_smarty_tpl->tpl_vars['current_tab_level']->value==3) {?> <div class="page-head-tabs"> <?php $_smarty_tpl->tpl_vars['level_1'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_1']->_loop = false; $_from = $_smarty_tpl->tpl_vars['tabs']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['level_1']->key => $_smarty_tpl->tpl_vars['level_1']->value) { $_smarty_tpl->tpl_vars['level_1']->_loop = true; ?> <?php $_smarty_tpl->tpl_vars['level_2'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_2']->_loop = false; $_from = $_smarty_tpl->tpl_vars['level_1']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['level_2']->key => $_smarty_tpl->tpl_vars['level_2']->value) { $_smarty_tpl->tpl_vars['level_2']->_loop = true; ?> <?php $_smarty_tpl->tpl_vars['level_3'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_3']->_loop = false; $_from = $_smarty_tpl->tpl_vars['level_2']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['level_3']->key => $_smarty_tpl->tpl_vars['level_3']->value) { $_smarty_tpl->tpl_vars['level_3']->_loop = true; ?> <?php if ($_smarty_tpl->tpl_vars['level_3']->value['current']) {?> <?php $_smarty_tpl->tpl_vars['level_4'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_4']->_loop = false; $_from = $_smarty_tpl->tpl_vars['level_3']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['level_4']->key => $_smarty_tpl->tpl_vars['level_4']->value) { $_smarty_tpl->tpl_vars['level_4']->_loop = true; ?> <a href="<?php echo $_smarty_tpl->tpl_vars['level_4']->value['href'];?> " <?php if ($_smarty_tpl->tpl_vars['level_4']->value['current']) {?>class="current"<?php }?>><?php echo $_smarty_tpl->tpl_vars['level_4']->value['name'];?> </a> <?php } ?> <?php }?> <?php } ?> <?php } ?> <?php } ?> </div> <?php }?> </div> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h'=>'displayDashboardTop'),$_smarty_tpl);?> </div> <?php }} ?>
rjpalermo1/paymentsandbox_ps
src/app/cache/dev/smarty/compile/d6/5a/ae/d65aaeae6f3a1059b7e9527adddd1e40bec16718.file.page_header_toolbar.tpl.php
PHP
gpl-3.0
14,335
///////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2018- Equinor ASA // // ResInsight 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. // // ResInsight 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 at <http://www.gnu.org/licenses/gpl.html> // for more details. // ///////////////////////////////////////////////////////////////////////////////// #pragma once #include "RiaDefines.h" #include <QString> //================================================================================================== /// //================================================================================================== class RicWellPathFractureReportItem { public: RicWellPathFractureReportItem( const QString& wellPathNameForExport, const QString& fractureName, const QString& fractureTemplateName, double measuredDepth ); void setData( double trans, size_t connCount, double area ); void setWidthAndConductivity( double width, double conductivity ); void setHeightAndHalfLength( double height, double halfLength ); void setAreaWeightedPermeability( double permeability ); void setUnitSystem( RiaDefines::EclipseUnitSystem unitSystem ); void setPressureDepletionParameters( bool performPressureDepletionScaling, const QString& timeStepString, const QString& wbhpString, double userWBHP, double actualWBHP, double minPressureDrop, double maxPressureDrop ); QString wellPathNameForExport() const; QString fractureName() const; QString fractureTemplateName() const; RiaDefines::EclipseUnitSystem unitSystem() const; double transmissibility() const; size_t connectionCount() const; double fcd() const; double area() const; double kfwf() const; double kf() const; double wf() const; double xf() const; double h() const; double km() const; double kmxf() const; bool performPressureDepletionScaling() const; QString pressureDepletionTimeStepString() const; QString pressureDepletionWBHPString() const; double pressureDepletionUserWBHP() const; double pressureDepletionActualWBHP() const; double pressureDepletionMinPressureDrop() const; double pressureDepletionMaxPressureDrop() const; bool operator<( const RicWellPathFractureReportItem& other ) const; private: RiaDefines::EclipseUnitSystem m_unitSystem; QString m_wellPathNameForExport; QString m_wellPathFracture; QString m_wellPathFractureTemplate; double m_mesuredDepth; double m_transmissibility; size_t m_connectionCount; double m_area; double m_kfwf; double m_kf; double m_wf; double m_xf; double m_h; double m_km; bool m_performPressureDepletionScaling; QString m_pressureDepletionTimeStepString; QString m_pressureDepletionWBHPString; double m_pressureDepletionUserWBHP; double m_pressureDepletionActualWBHP; double m_pressureDepletionMinPressureDrop; double m_pressureDepletionMaxPressureDrop; };
OPM/ResInsight
ApplicationLibCode/Commands/CompletionExportCommands/RicWellPathFractureReportItem.h
C
gpl-3.0
3,886
/** * * This file is part of Tulip (www.tulip-software.org) * * Authors: David Auber and the Tulip development Team * from LaBRI, University of Bordeaux * * Tulip 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. * * Tulip is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * */ #include <stdio.h> #include <string> #include <iostream> #include <cppunit/TestCase.h> #include <tulip/TulipPluginHeaders.h> using namespace std; class Test2 : public tlp::BooleanAlgorithm { public: PLUGININFORMATION("Test2","Jezequel","03/11/2004","0","1.0", "") Test2(tlp::PluginContext* context) : tlp::BooleanAlgorithm(context) {} ~Test2() {} bool run() { return true; } }; PLUGIN(Test2)
jukkes/TulipProject
unit_test/library/tulip/testPlugin2.cpp
C++
gpl-3.0
1,069
/* Copyright 2019 Equinor ASA. This file is part of the Open Porous Media project (OPM). OPM 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. OPM is distributed in the hope that it will be useful, 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 OPM. If not, see <http://www.gnu.org/licenses/>. */ #include <opm/parser/eclipse/EclipseState/Schedule/TimeMap.hpp> #include <opm/parser/eclipse/EclipseState/Schedule/RFTConfig.hpp> namespace Opm { RFTConfig::RFTConfig(const TimeMap& time_map) : tm(time_map) { } bool RFTConfig::rft(const std::string& well_name, std::size_t report_step) const { if (report_step >= this->tm.size()) throw std::invalid_argument("Invalid "); const auto well_iter = this->well_open.find(well_name); if (well_iter != this->well_open.end()) { // A general "Output RFT when the well is opened" has been configured with WRFT if (this->well_open_rft_time.first && this->well_open_rft_time.second <= report_step) { if (well_iter->second == report_step) return true; } // A FOPN setting has been configured with the WRFTPLT keyword if (this->well_open_rft_name.count(well_name) > 0) { if (well_iter->second == report_step) return true; } } if (this->rft_config.count(well_name) == 0) return false; auto rft_pair = this->rft_config.at(well_name)[report_step]; if (rft_pair.first == RFTConnections::YES) return (rft_pair.second == report_step); if (rft_pair.first == RFTConnections::NO) return false; if (rft_pair.first == RFTConnections::REPT) return true; if (rft_pair.first == RFTConnections::TIMESTEP) return true; return false; } bool RFTConfig::plt(const std::string& well_name, std::size_t report_step) const { if (report_step >= this->tm.size()) throw std::invalid_argument("Invalid "); if (this->plt_config.count(well_name) == 0) return false; auto plt_pair = this->plt_config.at(well_name)[report_step]; if (plt_pair.first == PLTConnections::YES) return (plt_pair.second == report_step); if (plt_pair.first == PLTConnections::NO) return false; if (plt_pair.first == PLTConnections::REPT) return true; if (plt_pair.first == PLTConnections::TIMESTEP) return true; return false; } void RFTConfig::updateRFT(const std::string& well_name, std::size_t report_step, RFTConnections::RFTEnum value) { if (value == RFTConnections::FOPN) this->setWellOpenRFT(well_name); else { if (this->rft_config.count(well_name) == 0) { auto state = DynamicState<std::pair<RFTConnections::RFTEnum, std::size_t>>(this->tm, std::make_pair(RFTConnections::NO, 0)); this->rft_config.emplace( well_name, state ); } this->rft_config.at(well_name).update(report_step, std::make_pair(value, report_step)); } } void RFTConfig::updatePLT(const std::string& well_name, std::size_t report_step, PLTConnections::PLTEnum value) { if (this->plt_config.count(well_name) == 0) { auto state = DynamicState<std::pair<PLTConnections::PLTEnum, std::size_t>>(this->tm, std::make_pair(PLTConnections::NO, 0)); this->plt_config.emplace( well_name, state ); } this->plt_config.at(well_name).update(report_step, std::make_pair(value, report_step)); } bool RFTConfig::getWellOpenRFT(const std::string& well_name, std::size_t report_step) const { if (this->well_open_rft_name.count(well_name) > 0) return true; return (this->well_open_rft_time.first && this->well_open_rft_time.second <= report_step); } void RFTConfig::setWellOpenRFT(std::size_t report_step) { this->well_open_rft_time = std::make_pair(true, report_step); } void RFTConfig::setWellOpenRFT(const std::string& well_name) { this->well_open_rft_name.insert( well_name ); } void RFTConfig::addWellOpen(const std::string& well_name, std::size_t report_step) { if (this->well_open.count(well_name) == 0) this->well_open[well_name] = report_step; } std::size_t RFTConfig::firstRFTOutput() const { std::size_t first_rft = this->tm.size(); if (this->well_open_rft_time.first) { // The WRFT keyword has been used to request RFT output at well open for all wells. std::size_t rft_time = this->well_open_rft_time.second; for (const auto& rft_pair : this->well_open) { if (rft_pair.second >= rft_time) first_rft = std::min(first_rft, rft_pair.second); } } else { // Go through the individual wells and look for first open settings for (const auto& rft_pair : this->well_open) first_rft = std::min(first_rft, rft_pair.second); } for (const auto& rft_pair : this->plt_config) { const auto& dynamic_state = rft_pair.second; auto pred = [] (const std::pair<PLTConnections::PLTEnum, std::size_t>& ) { return false; }; int this_first_rft = dynamic_state.find_if(pred); if (this_first_rft >= 0) first_rft = std::min(first_rft, static_cast<std::size_t>(this_first_rft)); } return first_rft; } bool RFTConfig::active(std::size_t report_step) const { for (const auto& rft_pair : this->rft_config) { if (this->rft(rft_pair.first, report_step)) return true; } for (const auto& plt_pair : this->plt_config) { if (this->rft(plt_pair.first, report_step)) return true; } return false; } }
andlaus/opm-common
src/opm/parser/eclipse/EclipseState/Schedule/RFTConfig.cpp
C++
gpl-3.0
5,913
"""Test class for Custom Sync UI :Requirement: Sync :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: Repositories :TestType: Functional :CaseImportance: High :Upstream: No """ from fauxfactory import gen_string from nailgun import entities from robottelo import manifests from robottelo.api.utils import enable_rhrepo_and_fetchid from robottelo.constants import ( DISTRO_RHEL6, DISTRO_RHEL7, DOCKER_REGISTRY_HUB, DOCKER_UPSTREAM_NAME, FAKE_1_YUM_REPO, FEDORA27_OSTREE_REPO, REPOS, REPOSET, REPO_TYPE, PRDS, ) from robottelo.decorators import ( fixture, run_in_one_thread, skip_if_not_set, tier2, upgrade, skip_if_bug_open, ) from robottelo.decorators.host import skip_if_os from robottelo.products import ( RepositoryCollection, RHELCloudFormsTools, SatelliteCapsuleRepository, ) @fixture(scope='module') def module_org(): return entities.Organization().create() @fixture(scope='module') def module_custom_product(module_org): return entities.Product(organization=module_org).create() @fixture(scope='module') def module_org_with_manifest(): org = entities.Organization().create() manifests.upload_manifest_locked(org.id) return org @tier2 def test_positive_sync_custom_repo(session, module_custom_product): """Create Content Custom Sync with minimal input parameters :id: 00fb0b04-0293-42c2-92fa-930c75acee89 :expectedresults: Sync procedure is successful :CaseImportance: Critical """ repo = entities.Repository( url=FAKE_1_YUM_REPO, product=module_custom_product).create() with session: results = session.sync_status.synchronize([ (module_custom_product.name, repo.name)]) assert len(results) == 1 assert results[0] == 'Syncing Complete.' @run_in_one_thread @skip_if_not_set('fake_manifest') @tier2 @upgrade def test_positive_sync_rh_repos(session, module_org_with_manifest): """Create Content RedHat Sync with two repos. :id: e30f6509-0b65-4bcc-a522-b4f3089d3911 :expectedresults: Sync procedure for RedHat Repos is successful :CaseLevel: Integration """ repos = ( SatelliteCapsuleRepository(cdn=True), RHELCloudFormsTools(cdn=True) ) distros = [DISTRO_RHEL7, DISTRO_RHEL6] repo_collections = [ RepositoryCollection(distro=distro, repositories=[repo]) for distro, repo in zip(distros, repos) ] for repo_collection in repo_collections: repo_collection.setup(module_org_with_manifest.id, synchronize=False) repo_paths = [ ( repo.repo_data['product'], repo.repo_data.get('releasever'), repo.repo_data.get('arch'), repo.repo_data['name'], ) for repo in repos ] with session: session.organization.select(org_name=module_org_with_manifest.name) results = session.sync_status.synchronize(repo_paths) assert len(results) == len(repo_paths) assert all([result == 'Syncing Complete.' for result in results]) @skip_if_bug_open('bugzilla', 1625783) @skip_if_os('RHEL6') @tier2 @upgrade def test_positive_sync_custom_ostree_repo(session, module_custom_product): """Create custom ostree repository and sync it. :id: e4119b9b-0356-4661-a3ec-e5807224f7d2 :expectedresults: ostree repo should be synced successfully :CaseLevel: Integration """ repo = entities.Repository( content_type='ostree', url=FEDORA27_OSTREE_REPO, product=module_custom_product, unprotected=False, ).create() with session: results = session.sync_status.synchronize([ (module_custom_product.name, repo.name)]) assert len(results) == 1 assert results[0] == 'Syncing Complete.' @run_in_one_thread @skip_if_bug_open('bugzilla', 1625783) @skip_if_os('RHEL6') @skip_if_not_set('fake_manifest') @tier2 @upgrade def test_positive_sync_rh_ostree_repo(session, module_org_with_manifest): """Sync CDN based ostree repository. :id: 4d28fff0-5fda-4eee-aa0c-c5af02c31de5 :Steps: 1. Import a valid manifest 2. Enable the OStree repo and sync it :expectedresults: ostree repo should be synced successfully from CDN :CaseLevel: Integration """ enable_rhrepo_and_fetchid( basearch=None, org_id=module_org_with_manifest.id, product=PRDS['rhah'], repo=REPOS['rhaht']['name'], reposet=REPOSET['rhaht'], releasever=None, ) with session: session.organization.select(org_name=module_org_with_manifest.name) results = session.sync_status.synchronize([ (PRDS['rhah'], REPOS['rhaht']['name'])]) assert len(results) == 1 assert results[0] == 'Syncing Complete.' @tier2 @upgrade def test_positive_sync_docker_via_sync_status(session, module_org): """Create custom docker repo and sync it via the sync status page. :id: 00b700f4-7e52-48ed-98b2-e49b3be102f2 :expectedresults: Sync procedure for specific docker repository is successful :CaseLevel: Integration """ product = entities.Product(organization=module_org).create() repo_name = gen_string('alphanumeric') with session: session.repository.create( product.name, {'name': repo_name, 'repo_type': REPO_TYPE['docker'], 'repo_content.upstream_url': DOCKER_REGISTRY_HUB, 'repo_content.upstream_repo_name': DOCKER_UPSTREAM_NAME} ) assert session.repository.search(product.name, repo_name)[0]['Name'] == repo_name result = session.sync_status.synchronize([(product.name, repo_name)]) assert result[0] == 'Syncing Complete.'
omaciel/robottelo
tests/foreman/ui/test_sync.py
Python
gpl-3.0
5,811
<?php $L['Alerts_Title'] = 'Allarmi personalizzati'; $L['Alerts_Description'] = 'Allarmi personalizzati da ${0}'; $L['Alerts_header'] = 'Allarmi personalizzati da ${0}'; $L['Alerts_Configure_header'] = 'Configura download automatico'; $L['Update_Alerts_label'] = 'Scarica allarmi personalizzati'; $L['Refresh_label'] = 'Download configurazioni allarmi'; $L['last_update_label'] = 'Ultimo aggiornamento'; $L['Type_label'] = 'Allarme'; $L['Instance_label'] = 'Parametro'; $L['Threshold_label'] = 'Soglia'; $L['AlertsAutoUpdates_enabled_label'] = 'Abilita download automatico degli allarmi personalizzati (raccomandato)'; $L['AlertsAutoUpdates_disabled_label'] = 'Disabilita download automatico degli allarmi personalizzati'; $L['df_label'] = 'Spazio disco libero'; $L['load_label'] = 'Carico CPU'; $L['ping_droprate_label'] = 'Tasso di pacchetti persi'; $L['ping_label'] = 'Latenza ping'; $L['swap_label'] = 'Swap libero'; $L['Partition_label'] = 'Partizione'; $L['Host_label'] = 'Host'; $L['Intro_label'] = 'Ogni server ha una lista predefinita di allarmi di default. Solo alcuni possono essere personalizzati. <br/> Questa pagina mostra solo gli allarmi personalizzati su <a href="${0}">${0}</a>.'; $L['Download_label'] = 'Di default, le modifiche agli allarmi fatte su <a href="${0}">${0}</a> sono applicate ogni notte. <br/> Il tasto "Scarica allarmi personalizzati" scarica la configurazione subito.'; $L['max_fail_label'] = 'Critica sopra'; $L['min_fail_label'] = 'Critica sotto'; $L['max_warn_label'] = 'Media sopra'; $L['min_warn_label'] = 'Media sotto';
NethServer/nethserver-lang
locale/it/server-manager/NethServer_Module_Alerts.php
PHP
gpl-3.0
1,563
// dependencies define(['mvc/ui/ui-tabs', 'mvc/ui/ui-misc', 'mvc/ui/ui-portlet', 'utils/utils', 'plugin/models/chart', 'plugin/models/group', 'plugin/views/group', 'plugin/views/settings', 'plugin/views/types'], function(Tabs, Ui, Portlet, Utils, Chart, Group, GroupView, SettingsView, TypesView) { /** * The charts editor holds the tabs for selecting chart types, chart configuration * and data group selections. */ return Backbone.View.extend({ // initialize initialize: function(app, options){ // link this var self = this; // link application this.app = app; // get current chart object this.chart = this.app.chart; // message element this.message = new Ui.Message(); // create portlet this.portlet = new Portlet.View({ icon : 'fa-bar-chart-o', title: 'Editor', operations : { 'save' : new Ui.ButtonIcon({ icon : 'fa-save', tooltip : 'Draw Chart', title : 'Draw', onclick : function() { self._saveChart(); } }), 'back' : new Ui.ButtonIcon({ icon : 'fa-caret-left', tooltip : 'Return to Viewer', title : 'Cancel', onclick : function() { // show viewer/viewport self.app.go('viewer'); // reset chart self.app.storage.load(); } }) } }); // // grid with chart types // this.types = new TypesView(app, { onchange : function(chart_type) { // get chart definition var chart_definition = self.app.types.get(chart_type); if (!chart_definition) { console.debug('FAILED - Editor::onchange() - Chart type not supported.'); } // parse chart definition self.chart.definition = chart_definition; // reset type relevant chart content self.chart.settings.clear(); // update chart type self.chart.set({type: chart_type}); // set modified flag self.chart.set('modified', true); // log console.debug('Editor::onchange() - Switched chart type.'); }, ondblclick : function(chart_id) { self._saveChart(); } }); // // tabs // this.tabs = new Tabs.View({ title_new : 'Add Data', onnew : function() { var group = self._addGroupModel(); self.tabs.show(group.id); } }); // // main/default tab // // construct elements this.title = new Ui.Input({ placeholder: 'Chart title', onchange: function() { self.chart.set('title', self.title.value()); } }); // append element var $main = $('<div/>'); $main.append(Utils.wrap((new Ui.Label({ title : 'Provide a chart title:'})).$el)); $main.append(Utils.wrap(this.title.$el)); $main.append(Utils.wrap(this.types.$el)); // add tab this.tabs.add({ id : 'main', title : 'Start', $el : $main }); // // main settings tab // // create settings view this.settings = new SettingsView(this.app); // add tab this.tabs.add({ id : 'settings', title : 'Configuration', $el : this.settings.$el }); // append tabs this.portlet.append(this.message.$el); this.portlet.append(this.tabs.$el); // elements this.setElement(this.portlet.$el); // hide back button on startup this.tabs.hideOperation('back'); // chart events var self = this; this.chart.on('change:title', function(chart) { self._refreshTitle(); }); this.chart.on('change:type', function(chart) { self.types.value(chart.get('type')); }); this.chart.on('reset', function(chart) { self._resetChart(); }); this.app.chart.on('redraw', function(chart) { self.portlet.showOperation('back'); }); // groups events this.app.chart.groups.on('add', function(group) { self._addGroup(group); }); this.app.chart.groups.on('remove', function(group) { self._removeGroup(group); }); this.app.chart.groups.on('reset', function(group) { self._removeAllGroups(); }); this.app.chart.groups.on('change:key', function(group) { self._refreshGroupKey(); }); // reset this._resetChart(); }, // hide show: function() { this.$el.show(); }, // hide hide: function() { this.$el.hide(); }, // refresh title _refreshTitle: function() { var title = this.chart.get('title'); this.portlet.title(title); this.title.value(title); }, // refresh group _refreshGroupKey: function() { var self = this; var counter = 0; this.chart.groups.each(function(group) { var title = group.get('key', ''); if (title == '') { title = 'Data label'; } self.tabs.title(group.id, ++counter + ': ' + title); }); }, // add group model _addGroupModel: function() { var group = new Group({ id : Utils.uuid() }); this.chart.groups.add(group); return group; }, // add group tab _addGroup: function(group) { // link this var self = this; // create view var group_view = new GroupView(this.app, {group: group}); // add new tab this.tabs.add({ id : group.id, $el : group_view.$el, ondel : function() { self.chart.groups.remove(group.id); } }); // update titles this._refreshGroupKey(); // reset this.chart.set('modified', true); }, // remove group _removeGroup: function(group) { this.tabs.del(group.id); // update titles this._refreshGroupKey(); // reset this.chart.set('modified', true); }, // remove group _removeAllGroups: function(group) { this.tabs.delRemovable(); }, // reset _resetChart: function() { // reset chart details this.chart.set('id', Utils.uuid()); this.chart.set('type', 'nvd3_bar'); this.chart.set('dataset_id', this.app.options.config.dataset_id); this.chart.set('title', 'New Chart'); // reset back button this.portlet.hideOperation('back'); }, // create chart _saveChart: function() { // update chart data this.chart.set({ type : this.types.value(), title : this.title.value(), date : Utils.time() }); // make sure that at least one data group is available if (this.chart.groups.length == 0) { this.message.update({message: 'Please select data columns before drawing the chart.'}); var group = this._addGroupModel(); this.tabs.show(group.id); return; } // make sure that all necessary columns are assigned var self = this; var valid = true; var chart_def = this.chart.definition; this.chart.groups.each(function(group) { if (!valid) { return; } for (var key in chart_def.columns) { if (group.attributes[key] == 'null') { self.message.update({status: 'danger', message: 'This chart type requires column types not found in your tabular file.'}); self.tabs.show(group.id); valid = false; return; } } }); // validate if columns have been selected if (!valid) { return; } // show viewport this.app.go('viewer'); // wait until chart is ready var self = this; this.app.deferred.execute(function() { // save self.app.storage.save(); // trigger redraw self.chart.trigger('redraw'); }); } }); });
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/config/plugins/visualizations/charts/static/views/editor.js
JavaScript
gpl-3.0
9,412
{% extends "jblux/base.html" %} {% block title %}New Character{% endblock %} {% block content %} <form method="post" action="{% url jblux_django.jblux.views.new_character %}"> {% csrf_token %} {% include "jblux/base_form.html" %} <p><input type="submit" value="Create Character" /></p> </form> {% endblock %}
jcnix/JBlux
jblux_django/templates/jblux/character_edit.html
HTML
gpl-3.0
324
/** * This file is part of RT2D, a 2D OpenGL framework. * * - Copyright 2017 Rik Teerling <[email protected]> * - Initial commit */ #include "canvas.h" Canvas::Canvas() : Entity() { this->init(16); } Canvas::Canvas(int pixelsize) : Entity() { this->init(pixelsize); } Canvas::~Canvas() { } void Canvas::update(float deltaTime) { } void Canvas::init(int pixelsize) { this->position = Point2(SWIDTH/2, SHEIGHT/2); this->scale = Point2(pixelsize, pixelsize); // width, height, bitdepth, filter, wrap PixelBuffer tmp = PixelBuffer(SWIDTH/pixelsize, SHEIGHT/pixelsize, 4, 0, 0); this->addDynamicSprite(&tmp); // get the pixels from the texture and make the framebuffer point to it this->_framebuffer = this->sprite()->texture()->pixels(); this->_width = SWIDTH / pixelsize; this->_height = SHEIGHT / pixelsize; backgroundcolor = RGBAColor(0, 0, 0, 0); this->fill(backgroundcolor); } void Canvas::setPixel(int x, int y, RGBAColor color) { this->_framebuffer->setPixel(x, y, color); } RGBAColor Canvas::getPixel(int x, int y) { return this->_framebuffer->getPixel(x, y); } void Canvas::clearPixel(int x, int y) { this->_framebuffer->setPixel(x, y, backgroundcolor); } void Canvas::fill(RGBAColor color) { // fill framebuffer with color for (long y=0; y<_framebuffer->height; y++) { for (long x=0; x<_framebuffer->width; x++) { this->setPixel(x, y, color); } } } void Canvas::drawSprite(const PixelSprite& spr) { size_t s = spr.pixels.size(); for (size_t i = 0; i < s; i++) { this->setPixel(spr.pixels[i].position.x + spr.position.x, spr.pixels[i].position.y + spr.position.y, spr.pixels[i].color); } } void Canvas::clearSprite(const PixelSprite& spr) { size_t s = spr.pixels.size(); for (size_t i = 0; i < s; i++) { this->clearPixel(spr.pixels[i].position.x + spr.position.x, spr.pixels[i].position.y + spr.position.y); } } void Canvas::drawLine(Vector2f from, Vector2f to, RGBAColor color) { float x0 = from.x; float y0 = from.y; float x1 = to.x; float y1 = to.y; bool steep = false; if (std::abs(x0-x1) < std::abs(y0-y1)) { std::swap(x0, y0); std::swap(x1, y1); steep = true; } if (x0 > x1) { std::swap(x0, x1); std::swap(y0, y1); } int dx = x1-x0; int dy = y1-y0; int derror2 = std::abs(dy)*2; int error2 = 0; int y = y0; for (int x = x0; x <= x1; x++) { if (steep) { this->setPixel(y, x, color); } else { this->setPixel(x, y, color); } error2 += derror2; if (error2 > dx) { y += (y1 > y0 ? 1 : -1); error2 -= dx*2; } } }
rktrlng/rt2d
rt2d/canvas.cpp
C++
gpl-3.0
2,543
#!/usr/bin/env python from keyring import get_password from boto.iam.connection import IAMConnection import lib.LoadBotoConfig as BotoConfig from sys import exit envs = ['dev', 'qa', 'staging', 'demo', 'prod'] for env in envs: id = BotoConfig.config.get(env, 'aws_access_key_id') key = get_password(BotoConfig.config.get(env, 'keyring'), id) conn = IAMConnection(aws_access_key_id=id, aws_secret_access_key=key) print(conn.get_signin_url())
johnkastler/aws
get_account_urls.py
Python
gpl-3.0
456
<?php namespace App\Services\Geografico\ObterOsc; use App\Services\BaseService; use App\Dao\Geografico\GeolocalizacaoDao; class Service extends BaseService{ public function executar(){ $conteudoRequisicao = $this->requisicao->getConteudo(); $modelo = new Model($conteudoRequisicao); if($modelo->obterCodigoResposta() === 200){ $requisicao = $modelo->obterRequisicao(); $geolocalizacaoOsc = (new GeolocalizacaoDao())->obterGeolocalizacaoOsc($requisicao->id_osc); if($geolocalizacaoOsc){ $this->resposta->prepararResposta($geolocalizacaoOsc, 200); }else{ $this->resposta->prepararResposta(null, 204); } }else{ $this->resposta->prepararResposta($modelo->obterMensagemResposta(), $modelo->obterCodigoResposta()); } } }
Plataformas-Cidadania/portalosc
app/Services/Geografico/ObterOsc/Service.php
PHP
gpl-3.0
795
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Guillaume Saupin <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at the mozilla.org home page #ifndef EIGEN_SKYLINEMATRIX_H #define EIGEN_SKYLINEMATRIX_H #include "SkylineStorage.h" #include "SkylineMatrixBase.h" namespace Eigen { /** \ingroup Skyline_Module * * \class SkylineMatrix * * \brief The main skyline matrix class * * This class implements a skyline matrix using the very uncommon storage * scheme. * * \param _Scalar the scalar type, i.e. the type of the coefficients * \param _Options Union of bit flags controlling the storage scheme. Currently the only possibility * is RowMajor. The default is 0 which means column-major. * * */ namespace internal { template<typename _Scalar, int _Options> struct traits<SkylineMatrix<_Scalar, _Options> > { typedef _Scalar Scalar; typedef Sparse StorageKind; enum { RowsAtCompileTime = Dynamic, ColsAtCompileTime = Dynamic, MaxRowsAtCompileTime = Dynamic, MaxColsAtCompileTime = Dynamic, Flags = SkylineBit | _Options, CoeffReadCost = NumTraits<Scalar>::ReadCost, }; }; } template<typename _Scalar, int _Options> class SkylineMatrix : public SkylineMatrixBase<SkylineMatrix<_Scalar, _Options> > { public: EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE(SkylineMatrix) EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(SkylineMatrix, +=) EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(SkylineMatrix, -=) using Base::IsRowMajor; protected: typedef SkylineMatrix<Scalar, (Flags&~RowMajorBit) | (IsRowMajor ? RowMajorBit : 0) > TransposedSkylineMatrix; Index m_outerSize; Index m_innerSize; public: Index* m_colStartIndex; Index* m_rowStartIndex; SkylineStorage<Scalar> m_data; public: inline Index rows() const { return IsRowMajor ? m_outerSize : m_innerSize; } inline Index cols() const { return IsRowMajor ? m_innerSize : m_outerSize; } inline Index innerSize() const { return m_innerSize; } inline Index outerSize() const { return m_outerSize; } inline Index upperNonZeros() const { return m_data.upperSize(); } inline Index lowerNonZeros() const { return m_data.lowerSize(); } inline Index upperNonZeros(Index j) const { return m_colStartIndex[j + 1] - m_colStartIndex[j]; } inline Index lowerNonZeros(Index j) const { return m_rowStartIndex[j + 1] - m_rowStartIndex[j]; } inline const Scalar* _diagPtr() const { return &m_data.diag(0); } inline Scalar* _diagPtr() { return &m_data.diag(0); } inline const Scalar* _upperPtr() const { return &m_data.upper(0); } inline Scalar* _upperPtr() { return &m_data.upper(0); } inline const Scalar* _lowerPtr() const { return &m_data.lower(0); } inline Scalar* _lowerPtr() { return &m_data.lower(0); } inline const Index* _upperProfilePtr() const { return &m_data.upperProfile(0); } inline Index* _upperProfilePtr() { return &m_data.upperProfile(0); } inline const Index* _lowerProfilePtr() const { return &m_data.lowerProfile(0); } inline Index* _lowerProfilePtr() { return &m_data.lowerProfile(0); } inline Scalar coeff(Index row, Index col) const { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); if (outer == inner) return this->m_data.diag(outer); if (IsRowMajor) { if (inner > outer) //upper matrix { const Index minOuterIndex = inner - m_data.upperProfile(inner); if (outer >= minOuterIndex) return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); else return Scalar(0); } if (inner < outer) //lower matrix { const Index minInnerIndex = outer - m_data.lowerProfile(outer); if (inner >= minInnerIndex) return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); else return Scalar(0); } return m_data.upper(m_colStartIndex[inner] + outer - inner); } else { if (outer > inner) //upper matrix { const Index maxOuterIndex = inner + m_data.upperProfile(inner); if (outer <= maxOuterIndex) return this->m_data.upper(m_colStartIndex[inner] + (outer - inner)); else return Scalar(0); } if (outer < inner) //lower matrix { const Index maxInnerIndex = outer + m_data.lowerProfile(outer); if (inner <= maxInnerIndex) return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer)); else return Scalar(0); } } } inline Scalar& coeffRef(Index row, Index col) { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); if (outer == inner) return this->m_data.diag(outer); if (IsRowMajor) { if (col > row) //upper matrix { const Index minOuterIndex = inner - m_data.upperProfile(inner); eigen_assert(outer >= minOuterIndex && "you try to acces a coeff that do not exist in the storage"); return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); } if (col < row) //lower matrix { const Index minInnerIndex = outer - m_data.lowerProfile(outer); eigen_assert(inner >= minInnerIndex && "you try to acces a coeff that do not exist in the storage"); return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); } } else { if (outer > inner) //upper matrix { const Index maxOuterIndex = inner + m_data.upperProfile(inner); eigen_assert(outer <= maxOuterIndex && "you try to acces a coeff that do not exist in the storage"); return this->m_data.upper(m_colStartIndex[inner] + (outer - inner)); } if (outer < inner) //lower matrix { const Index maxInnerIndex = outer + m_data.lowerProfile(outer); eigen_assert(inner <= maxInnerIndex && "you try to acces a coeff that do not exist in the storage"); return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer)); } } } inline Scalar coeffDiag(Index idx) const { eigen_assert(idx < outerSize()); eigen_assert(idx < innerSize()); return this->m_data.diag(idx); } inline Scalar coeffLower(Index row, Index col) const { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); eigen_assert(inner != outer); if (IsRowMajor) { const Index minInnerIndex = outer - m_data.lowerProfile(outer); if (inner >= minInnerIndex) return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); else return Scalar(0); } else { const Index maxInnerIndex = outer + m_data.lowerProfile(outer); if (inner <= maxInnerIndex) return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer)); else return Scalar(0); } } inline Scalar coeffUpper(Index row, Index col) const { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); eigen_assert(inner != outer); if (IsRowMajor) { const Index minOuterIndex = inner - m_data.upperProfile(inner); if (outer >= minOuterIndex) return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); else return Scalar(0); } else { const Index maxOuterIndex = inner + m_data.upperProfile(inner); if (outer <= maxOuterIndex) return this->m_data.upper(m_colStartIndex[inner] + (outer - inner)); else return Scalar(0); } } inline Scalar& coeffRefDiag(Index idx) { eigen_assert(idx < outerSize()); eigen_assert(idx < innerSize()); return this->m_data.diag(idx); } inline Scalar& coeffRefLower(Index row, Index col) { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); eigen_assert(inner != outer); if (IsRowMajor) { const Index minInnerIndex = outer - m_data.lowerProfile(outer); eigen_assert(inner >= minInnerIndex && "you try to acces a coeff that do not exist in the storage"); return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); } else { const Index maxInnerIndex = outer + m_data.lowerProfile(outer); eigen_assert(inner <= maxInnerIndex && "you try to acces a coeff that do not exist in the storage"); return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer)); } } inline bool coeffExistLower(Index row, Index col) { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); eigen_assert(inner != outer); if (IsRowMajor) { const Index minInnerIndex = outer - m_data.lowerProfile(outer); return inner >= minInnerIndex; } else { const Index maxInnerIndex = outer + m_data.lowerProfile(outer); return inner <= maxInnerIndex; } } inline Scalar& coeffRefUpper(Index row, Index col) { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); eigen_assert(inner != outer); if (IsRowMajor) { const Index minOuterIndex = inner - m_data.upperProfile(inner); eigen_assert(outer >= minOuterIndex && "you try to acces a coeff that do not exist in the storage"); return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); } else { const Index maxOuterIndex = inner + m_data.upperProfile(inner); eigen_assert(outer <= maxOuterIndex && "you try to acces a coeff that do not exist in the storage"); return this->m_data.upper(m_colStartIndex[inner] + (outer - inner)); } } inline bool coeffExistUpper(Index row, Index col) { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); eigen_assert(inner != outer); if (IsRowMajor) { const Index minOuterIndex = inner - m_data.upperProfile(inner); return outer >= minOuterIndex; } else { const Index maxOuterIndex = inner + m_data.upperProfile(inner); return outer <= maxOuterIndex; } } protected: public: class InnerUpperIterator; class InnerLowerIterator; class OuterUpperIterator; class OuterLowerIterator; /** Removes all non zeros */ inline void setZero() { m_data.clear(); memset(m_colStartIndex, 0, (m_outerSize + 1) * sizeof (Index)); memset(m_rowStartIndex, 0, (m_outerSize + 1) * sizeof (Index)); } /** \returns the number of non zero coefficients */ inline Index nonZeros() const { return m_data.diagSize() + m_data.upperSize() + m_data.lowerSize(); } /** Preallocates \a reserveSize non zeros */ inline void reserve(Index reserveSize, Index reserveUpperSize, Index reserveLowerSize) { m_data.reserve(reserveSize, reserveUpperSize, reserveLowerSize); } /** \returns a reference to a novel non zero coefficient with coordinates \a row x \a col. * * \warning This function can be extremely slow if the non zero coefficients * are not inserted in a coherent order. * * After an insertion session, you should call the finalize() function. */ EIGEN_DONT_INLINE Scalar & insert(Index row, Index col) { const Index outer = IsRowMajor ? row : col; const Index inner = IsRowMajor ? col : row; eigen_assert(outer < outerSize()); eigen_assert(inner < innerSize()); if (outer == inner) return m_data.diag(col); if (IsRowMajor) { if (outer < inner) //upper matrix { Index minOuterIndex = 0; minOuterIndex = inner - m_data.upperProfile(inner); if (outer < minOuterIndex) //The value does not yet exist { const Index previousProfile = m_data.upperProfile(inner); m_data.upperProfile(inner) = inner - outer; const Index bandIncrement = m_data.upperProfile(inner) - previousProfile; //shift data stored after this new one const Index stop = m_colStartIndex[cols()]; const Index start = m_colStartIndex[inner]; for (Index innerIdx = stop; innerIdx >= start; innerIdx--) { m_data.upper(innerIdx + bandIncrement) = m_data.upper(innerIdx); } for (Index innerIdx = cols(); innerIdx > inner; innerIdx--) { m_colStartIndex[innerIdx] += bandIncrement; } //zeros new data memset(this->_upperPtr() + start, 0, (bandIncrement - 1) * sizeof (Scalar)); return m_data.upper(m_colStartIndex[inner]); } else { return m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); } } if (outer > inner) //lower matrix { const Index minInnerIndex = outer - m_data.lowerProfile(outer); if (inner < minInnerIndex) //The value does not yet exist { const Index previousProfile = m_data.lowerProfile(outer); m_data.lowerProfile(outer) = outer - inner; const Index bandIncrement = m_data.lowerProfile(outer) - previousProfile; //shift data stored after this new one const Index stop = m_rowStartIndex[rows()]; const Index start = m_rowStartIndex[outer]; for (Index innerIdx = stop; innerIdx >= start; innerIdx--) { m_data.lower(innerIdx + bandIncrement) = m_data.lower(innerIdx); } for (Index innerIdx = rows(); innerIdx > outer; innerIdx--) { m_rowStartIndex[innerIdx] += bandIncrement; } //zeros new data memset(this->_lowerPtr() + start, 0, (bandIncrement - 1) * sizeof (Scalar)); return m_data.lower(m_rowStartIndex[outer]); } else { return m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); } } } else { if (outer > inner) //upper matrix { const Index maxOuterIndex = inner + m_data.upperProfile(inner); if (outer > maxOuterIndex) //The value does not yet exist { const Index previousProfile = m_data.upperProfile(inner); m_data.upperProfile(inner) = outer - inner; const Index bandIncrement = m_data.upperProfile(inner) - previousProfile; //shift data stored after this new one const Index stop = m_rowStartIndex[rows()]; const Index start = m_rowStartIndex[inner + 1]; for (Index innerIdx = stop; innerIdx >= start; innerIdx--) { m_data.upper(innerIdx + bandIncrement) = m_data.upper(innerIdx); } for (Index innerIdx = inner + 1; innerIdx < outerSize() + 1; innerIdx++) { m_rowStartIndex[innerIdx] += bandIncrement; } memset(this->_upperPtr() + m_rowStartIndex[inner] + previousProfile + 1, 0, (bandIncrement - 1) * sizeof (Scalar)); return m_data.upper(m_rowStartIndex[inner] + m_data.upperProfile(inner)); } else { return m_data.upper(m_rowStartIndex[inner] + (outer - inner)); } } if (outer < inner) //lower matrix { const Index maxInnerIndex = outer + m_data.lowerProfile(outer); if (inner > maxInnerIndex) //The value does not yet exist { const Index previousProfile = m_data.lowerProfile(outer); m_data.lowerProfile(outer) = inner - outer; const Index bandIncrement = m_data.lowerProfile(outer) - previousProfile; //shift data stored after this new one const Index stop = m_colStartIndex[cols()]; const Index start = m_colStartIndex[outer + 1]; for (Index innerIdx = stop; innerIdx >= start; innerIdx--) { m_data.lower(innerIdx + bandIncrement) = m_data.lower(innerIdx); } for (Index innerIdx = outer + 1; innerIdx < outerSize() + 1; innerIdx++) { m_colStartIndex[innerIdx] += bandIncrement; } memset(this->_lowerPtr() + m_colStartIndex[outer] + previousProfile + 1, 0, (bandIncrement - 1) * sizeof (Scalar)); return m_data.lower(m_colStartIndex[outer] + m_data.lowerProfile(outer)); } else { return m_data.lower(m_colStartIndex[outer] + (inner - outer)); } } } } /** Must be called after inserting a set of non zero entries. */ inline void finalize() { if (IsRowMajor) { if (rows() > cols()) m_data.resize(cols(), cols(), rows(), m_colStartIndex[cols()] + 1, m_rowStartIndex[rows()] + 1); else m_data.resize(rows(), cols(), rows(), m_colStartIndex[cols()] + 1, m_rowStartIndex[rows()] + 1); // eigen_assert(rows() == cols() && "memory reorganisatrion only works with suare matrix"); // // Scalar* newArray = new Scalar[m_colStartIndex[cols()] + 1 + m_rowStartIndex[rows()] + 1]; // Index dataIdx = 0; // for (Index row = 0; row < rows(); row++) { // // const Index nbLowerElts = m_rowStartIndex[row + 1] - m_rowStartIndex[row]; // // std::cout << "nbLowerElts" << nbLowerElts << std::endl; // memcpy(newArray + dataIdx, m_data.m_lower + m_rowStartIndex[row], nbLowerElts * sizeof (Scalar)); // m_rowStartIndex[row] = dataIdx; // dataIdx += nbLowerElts; // // const Index nbUpperElts = m_colStartIndex[row + 1] - m_colStartIndex[row]; // memcpy(newArray + dataIdx, m_data.m_upper + m_colStartIndex[row], nbUpperElts * sizeof (Scalar)); // m_colStartIndex[row] = dataIdx; // dataIdx += nbUpperElts; // // // } // //todo : don't access m_data profile directly : add an accessor from SkylineMatrix // m_rowStartIndex[rows()] = m_rowStartIndex[rows()-1] + m_data.lowerProfile(rows()-1); // m_colStartIndex[cols()] = m_colStartIndex[cols()-1] + m_data.upperProfile(cols()-1); // // delete[] m_data.m_lower; // delete[] m_data.m_upper; // // m_data.m_lower = newArray; // m_data.m_upper = newArray; } else { if (rows() > cols()) m_data.resize(cols(), rows(), cols(), m_rowStartIndex[cols()] + 1, m_colStartIndex[cols()] + 1); else m_data.resize(rows(), rows(), cols(), m_rowStartIndex[rows()] + 1, m_colStartIndex[rows()] + 1); } } inline void squeeze() { finalize(); m_data.squeeze(); } void prune(Scalar reference, RealScalar epsilon = dummy_precision<RealScalar > ()) { //TODO } /** Resizes the matrix to a \a rows x \a cols matrix and initializes it to zero * \sa resizeNonZeros(Index), reserve(), setZero() */ void resize(size_t rows, size_t cols) { const Index diagSize = rows > cols ? cols : rows; m_innerSize = IsRowMajor ? cols : rows; eigen_assert(rows == cols && "Skyline matrix must be square matrix"); if (diagSize % 2) { // diagSize is odd const Index k = (diagSize - 1) / 2; m_data.resize(diagSize, IsRowMajor ? cols : rows, IsRowMajor ? rows : cols, 2 * k * k + k + 1, 2 * k * k + k + 1); } else // diagSize is even { const Index k = diagSize / 2; m_data.resize(diagSize, IsRowMajor ? cols : rows, IsRowMajor ? rows : cols, 2 * k * k - k + 1, 2 * k * k - k + 1); } if (m_colStartIndex && m_rowStartIndex) { delete[] m_colStartIndex; delete[] m_rowStartIndex; } m_colStartIndex = new Index [cols + 1]; m_rowStartIndex = new Index [rows + 1]; m_outerSize = diagSize; m_data.reset(); m_data.clear(); m_outerSize = diagSize; memset(m_colStartIndex, 0, (cols + 1) * sizeof (Index)); memset(m_rowStartIndex, 0, (rows + 1) * sizeof (Index)); } void resizeNonZeros(Index size) { m_data.resize(size); } inline SkylineMatrix() : m_outerSize(-1), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) { resize(0, 0); } inline SkylineMatrix(size_t rows, size_t cols) : m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) { resize(rows, cols); } template<typename OtherDerived> inline SkylineMatrix(const SkylineMatrixBase<OtherDerived>& other) : m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) { *this = other.derived(); } inline SkylineMatrix(const SkylineMatrix & other) : Base(), m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) { *this = other.derived(); } inline void swap(SkylineMatrix & other) { //EIGEN_DBG_SKYLINE(std::cout << "SkylineMatrix:: swap\n"); std::swap(m_colStartIndex, other.m_colStartIndex); std::swap(m_rowStartIndex, other.m_rowStartIndex); std::swap(m_innerSize, other.m_innerSize); std::swap(m_outerSize, other.m_outerSize); m_data.swap(other.m_data); } inline SkylineMatrix & operator=(const SkylineMatrix & other) { std::cout << "SkylineMatrix& operator=(const SkylineMatrix& other)\n"; if (other.isRValue()) { swap(other.const_cast_derived()); } else { resize(other.rows(), other.cols()); memcpy(m_colStartIndex, other.m_colStartIndex, (m_outerSize + 1) * sizeof (Index)); memcpy(m_rowStartIndex, other.m_rowStartIndex, (m_outerSize + 1) * sizeof (Index)); m_data = other.m_data; } return *this; } template<typename OtherDerived> inline SkylineMatrix & operator=(const SkylineMatrixBase<OtherDerived>& other) { const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit); if (needToTranspose) { // TODO // return *this; } else { // there is no special optimization return SkylineMatrixBase<SkylineMatrix>::operator=(other.derived()); } } friend std::ostream & operator <<(std::ostream & s, const SkylineMatrix & m) { EIGEN_DBG_SKYLINE( std::cout << "upper elements : " << std::endl; for (Index i = 0; i < m.m_data.upperSize(); i++) std::cout << m.m_data.upper(i) << "\t"; std::cout << std::endl; std::cout << "upper profile : " << std::endl; for (Index i = 0; i < m.m_data.upperProfileSize(); i++) std::cout << m.m_data.upperProfile(i) << "\t"; std::cout << std::endl; std::cout << "lower startIdx : " << std::endl; for (Index i = 0; i < m.m_data.upperProfileSize(); i++) std::cout << (IsRowMajor ? m.m_colStartIndex[i] : m.m_rowStartIndex[i]) << "\t"; std::cout << std::endl; std::cout << "lower elements : " << std::endl; for (Index i = 0; i < m.m_data.lowerSize(); i++) std::cout << m.m_data.lower(i) << "\t"; std::cout << std::endl; std::cout << "lower profile : " << std::endl; for (Index i = 0; i < m.m_data.lowerProfileSize(); i++) std::cout << m.m_data.lowerProfile(i) << "\t"; std::cout << std::endl; std::cout << "lower startIdx : " << std::endl; for (Index i = 0; i < m.m_data.lowerProfileSize(); i++) std::cout << (IsRowMajor ? m.m_rowStartIndex[i] : m.m_colStartIndex[i]) << "\t"; std::cout << std::endl; ); for (Index rowIdx = 0; rowIdx < m.rows(); rowIdx++) { for (Index colIdx = 0; colIdx < m.cols(); colIdx++) { s << m.coeff(rowIdx, colIdx) << "\t"; } s << std::endl; } return s; } /** Destructor */ inline ~SkylineMatrix() { delete[] m_colStartIndex; delete[] m_rowStartIndex; } /** Overloaded for performance */ Scalar sum() const; }; template<typename Scalar, int _Options> class SkylineMatrix<Scalar, _Options>::InnerUpperIterator { public: InnerUpperIterator(const SkylineMatrix& mat, Index outer) : m_matrix(mat), m_outer(outer), m_id(_Options == RowMajor ? mat.m_colStartIndex[outer] : mat.m_rowStartIndex[outer] + 1), m_start(m_id), m_end(_Options == RowMajor ? mat.m_colStartIndex[outer + 1] : mat.m_rowStartIndex[outer + 1] + 1) { } inline InnerUpperIterator & operator++() { m_id++; return *this; } inline InnerUpperIterator & operator+=(Index shift) { m_id += shift; return *this; } inline Scalar value() const { return m_matrix.m_data.upper(m_id); } inline Scalar* valuePtr() { return const_cast<Scalar*> (&(m_matrix.m_data.upper(m_id))); } inline Scalar& valueRef() { return const_cast<Scalar&> (m_matrix.m_data.upper(m_id)); } inline Index index() const { return IsRowMajor ? m_outer - m_matrix.m_data.upperProfile(m_outer) + (m_id - m_start) : m_outer + (m_id - m_start) + 1; } inline Index row() const { return IsRowMajor ? index() : m_outer; } inline Index col() const { return IsRowMajor ? m_outer : index(); } inline size_t size() const { return m_matrix.m_data.upperProfile(m_outer); } inline operator bool() const { return (m_id < m_end) && (m_id >= m_start); } protected: const SkylineMatrix& m_matrix; const Index m_outer; Index m_id; const Index m_start; const Index m_end; }; template<typename Scalar, int _Options> class SkylineMatrix<Scalar, _Options>::InnerLowerIterator { public: InnerLowerIterator(const SkylineMatrix& mat, Index outer) : m_matrix(mat), m_outer(outer), m_id(_Options == RowMajor ? mat.m_rowStartIndex[outer] : mat.m_colStartIndex[outer] + 1), m_start(m_id), m_end(_Options == RowMajor ? mat.m_rowStartIndex[outer + 1] : mat.m_colStartIndex[outer + 1] + 1) { } inline InnerLowerIterator & operator++() { m_id++; return *this; } inline InnerLowerIterator & operator+=(Index shift) { m_id += shift; return *this; } inline Scalar value() const { return m_matrix.m_data.lower(m_id); } inline Scalar* valuePtr() { return const_cast<Scalar*> (&(m_matrix.m_data.lower(m_id))); } inline Scalar& valueRef() { return const_cast<Scalar&> (m_matrix.m_data.lower(m_id)); } inline Index index() const { return IsRowMajor ? m_outer - m_matrix.m_data.lowerProfile(m_outer) + (m_id - m_start) : m_outer + (m_id - m_start) + 1; ; } inline Index row() const { return IsRowMajor ? m_outer : index(); } inline Index col() const { return IsRowMajor ? index() : m_outer; } inline size_t size() const { return m_matrix.m_data.lowerProfile(m_outer); } inline operator bool() const { return (m_id < m_end) && (m_id >= m_start); } protected: const SkylineMatrix& m_matrix; const Index m_outer; Index m_id; const Index m_start; const Index m_end; }; } // end namespace Eigen #endif // EIGEN_SkylineMatrix_H
cnr-isti-vclab/vcglib
eigenlib/unsupported/Eigen/src/Skyline/SkylineMatrix.h
C
gpl-3.0
31,062
//cmdtypist: the main of cmdtypist /* Program title: CMDTYPIST Author: Chiatiah Calson License: GPL 3 or later versions Date and Time: 5 July 2017 @ 10:40PM Program Size: 2.8MB */ #include<math.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<ctype.h> #include <unistd.h> //cmdtypist.c: Implementing the main #include"functions_for_cmd_typist.h"//function prototypes and global variables. #include"display.h"//display fixing #include"utils.h"//useful functions #include"files.h"//file manipulations #include"config.h"//configuration #include"terminal.h"//manipulating the terminal char argv[5][18]; int main(int argc, char **argv)//argc=command line counter, argv=pointer to pointer to character(command line arguments) { redirect(); lmt_pg_size(); name_display(); read_message_conf();//welcome message for first time users. int lesson_choice=1;//global variable to hold the number corresponding to the chosen lesson. //char commands[][10]={"0ls","1edituser","2myown","3--help","4man","5mkuser","6mkrand","7mkstd", "8select","9chblk","10sound","11--off","12--on","13cch","14reset","15timeset","16atv","17raw"}; char commands[][10]={"ls","edituser","myown","--help","man","mkuser","mkrand","mkstd", "select","chblk","sound","--off","--on","cch","reset","timeset","atv","raw"}; if(argc<1||argc>3) { fprintf(stderr, "%s\n", "Invalid number of arguments to cmdtypist"); exit(EXIT_FAILURE); } switch(argc)//switching command depending on the number of command line arguments. { case 1: if(read_myown_config()!=0) { lesson_list();//list all lessons present. select_lesson(argc,&lesson_choice); } main_play(argc,&lesson_choice); break; case 2: if(strcmp(argv[1],commands[2])==0) { write_myown_config(0); main_play(argc,&lesson_choice); } else if(strcmp(argv[1],commands[13])==0) { write_myown_config(1); lesson_list(); select_lesson(argc,&lesson_choice); system("clear"); main_play(argc,&lesson_choice); } else if(strcmp(argv[1],commands[3])==0) { FILE *fp; if((fp=fopen("help.md","r"))==NULL) { fprintf(stderr, "%s\n", "Fatal Error, Some files are missing"); exit(EXIT_FAILURE); } while((ch=getc(fp))!=EOF) printf("%c", ch); puts(""); if(fclose(fp)) { fprintf(stderr, "%s\n", "Fatal Error, Unable to close some files\n"); exit(EXIT_FAILURE); } } else if(strcmp(argv[1],commands[4])==0) { FILE *fp; if((fp=fopen("Readme.txt","r"))==NULL) { fprintf(stderr, "%s\n", "Fatal Error, Some files are missing"); exit(EXIT_FAILURE); } while((ch=getc(fp))!=EOF) printf("%c", ch); } else if(strcmp(argv[1],commands[6])==0) write_conf_mode(0); else if(strcmp(argv[1],commands[7])==0) write_conf_mode(1); else if(strcmp(argv[1],commands[14])==0) { printf("%s","Will reset to default; continue? [y/n]:"); if(get_only_char()=='n') exit(EXIT_SUCCESS); reset_default_config(argv[2],argc); printf("%s\n","Settings reset to default"); exit(EXIT_SUCCESS); } else if(strcmp(argv[1],commands[16])==0) { adapt_to_ver(); exit(EXIT_SUCCESS); } else if(strcmp(argv[1],commands[0])==0) { lesson_list(); select_lesson(argc,&lesson_choice); main_play(argc,&lesson_choice); } else fprintf(stderr, "%s\n", "Ensure the second argument is corrrectly spelled"); break; case 3: if(strcmp(argv[1],commands[5])==0) { test_new_user(argv[2]); lesson_list(); select_lesson(argc,&lesson_choice); main_play(argc,&lesson_choice); } else if(strcmp(argv[1],commands[14])==0&&strcmp(argv[2],commands[17])==0) { reset_default_config(argv[2],argc); exit(EXIT_SUCCESS); } else if(strcmp(argv[1],commands[8])==0) { if(read_myown_config()==1) lesson_choice = range_verifier(is_integral(argv[2],argc)); else { lesson_choice=1; fprintf(stderr, "%s\n\n", "You have been redirected here because you are typing in \"myown\""); } main_play(argc,&lesson_choice); } /* else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--on")==0)//modifying system sound { sound_config_write(1); exit(EXIT_SUCCESS); } else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--off")==0) { sound_config_write(0); exit(EXIT_SUCCESS); }*/ else if((strcmp(argv[1],commands[10])==0))//modifying system sound { if(strcmp(argv[2],commands[12])==0) { sound_config_write(1); exit(EXIT_SUCCESS); } else if(strcmp(argv[2],commands[11])==0) { sound_config_write(0); exit(EXIT_SUCCESS); } else { fprintf(stderr, "%s\n", "Check argument 3 for errors, can be \"--on or --off\""); exit(EXIT_SUCCESS); } } else if(strcmp(argv[1],commands[9])==0) { write_conf_block_read(is_integral(argv[2],argc)); exit(EXIT_SUCCESS); } break; /*case 4://later update if((strcmp(argv[1],"timeset")==0))//testing if user wants to play for specific amount of time. { if(strcmp(argv[2],"--on")==0) { time_set=1; main_play(); } else { fprintf(stderr, "%s\n", "Argument 3 invalid or not recognized"); exit(EXIT_SUCCESS); } }*/ default: fprintf(stderr, "%s\n", "Argument is invalid, use \"help\" to find out more"); break; } return 0; } void select_lesson(int argc_cmd, int* user_choice) { char firstarg[81];// if(argc_cmd>0&&argc_cmd<4)//checking on the command line argument. { char ch;// printf("%s", "Enter command >>"); while(scanf("%s",firstarg)!=1||(scanf("%d",&*user_choice))!=1||*user_choice<1||*user_choice>15||strncmp(firstarg,"select",6)!=0)//Ensuring that "select" { //is entered accurately and the selected value is within the correct range. if((strncmp(firstarg,"se",2)==0||strcmp(firstarg,"sel")==0||strcmp(firstarg,"sele")==0||strcmp(firstarg,"selec")==0)&&strcmp(firstarg,"select")!=0) //Making suggestion to help user prevent errors. fprintf(stderr, "\n%s\n%s", "Did you mean \"select usernumber\"","Enter command >>"); else if(ch!=1&&strcmp(firstarg,"select")==0) printf("%s%s", "Lesson number cannot contain symbols or alphas\n","Enter command >>"); else if((*user_choice<1||*user_choice>20)&&strcmp(firstarg,"select")==0) fprintf(stderr, "%s %d\n", "No lesson entry for ",*user_choice); else printf("%s\nEnter command >>", "Command not found"); while(ch=getchar()!='\n');//disposing off wrong input string. } } else { fprintf(stderr, "%s\n", "Invalid number of arguments, consult \"cmdtypist --help\" for more"); exit(EXIT_FAILURE); } /* if(argc_cmd==3) if(strncmp(argv[2],"select",6)!=0||lesson_choice<1||lesson_choice>20) { fprintf(stderr, "%s\n", "Command not found\n"); if(strncmp(argv[2],"se",2)) fprintf(stderr, "%s\n", "Did you mean \"select\""); else if(lesson_choice<1||lesson_choice>20) fprintf(stderr, "%s %d\n", "No lesson entry for ",lesson_choice); //else if(ch!=1) printf("%s", "Lesson number cannot contain symbols or alpha letters.\n"); exit(EXIT_FAILURE); }*/ printf("\n"); } void urs_or_cchl(void) { if(read_myown_config()==0) { strcpy(file_to_read,"my_own.txt"); mode=1; } else if(read_myown_config()==1) strcpy(file_to_read,"noslaclessons.txt"); else { fprintf(stderr, "%s\n", "Fatal Error, lesson file corrupted or does not exist"); exit(EXIT_FAILURE); } } void lesson_position(long *read_this_length,long *point_to,int *my_choice)//setting up the pointer in a position of the file to start reading. { FILE *lesson_point; urs_or_cchl(); if((lesson_point=fopen(file_to_read,"r+"))==NULL) { fprintf(stderr, "%s\n", "Fatal Error, Some files are missing"); exit(EXIT_FAILURE); } if(read_myown_config()==0) { rewind(lesson_point);//return to beginning *read_this_length=read_file_size(lesson_point); *point_to=0; } else switch(*my_choice) { case 1: *point_to=0; if(read_myown_config()==1) *read_this_length=25510; break; case 2: *point_to=25512L; *read_this_length=21660; break; case 3: *point_to=39326L; *read_this_length=397417; break; case 4: *point_to=444591L; *read_this_length=11142; break; case 5: *point_to=455733L; *read_this_length=98588; break; case 6: *point_to=554321L; *read_this_length=19564; break; case 7: *point_to=573885L; *read_this_length=79999; break; case 8: *point_to=653884L; *read_this_length=327523; break; case 9: *point_to=981407L; *read_this_length=208614; break; case 10: *point_to=1190021L; *read_this_length=400980; break; case 11: *point_to=1591001L; *read_this_length=625353; break; case 12: *point_to=2216354L; *read_this_length=1132581; break; default: *point_to=0; } if(fclose(lesson_point)) { fprintf(stderr, "%s\n", "Unable to close lesson file"); exit(EXIT_FAILURE); } } void main_play(int argc_cmd,int *lesson_choice) { //lmt_pg_size(); char terminate=0; long length_to_read;//holds information on how long the text to be read is. long move_lesson_to; lesson_position(&length_to_read,&move_lesson_to,lesson_choice); unsigned short block_count=0; user_test();//test if a user already exists or not. long num_of_chars_typed=0; block_length=read_conf_block_read(); mode=read_conf_mode(); urs_or_cchl();//selects file to read from remove_ext_ascii();//removes any non ascii 7 bits characters from lesson file. unsigned int start_time,elapsed_time=0;//elapsed_time: time used during the typing session measured from start time. unsigned short number_of_lines_count=1;//used to count the total number of lines to print. const unsigned short chars_to_read=77;//total number of characters to read for each line. unsigned int i=0;//counter variable for loop counting. char linetype[150];//char array to hold the total number of characters to to read from file per line. //lesson_list(); //fseek(noslac_lessonsp,25531L,SEEK_SET);//places the pointer to the position of the file to read. int wrong_letters=0;//sums up the total number of wrong characters entered during program run. srand((unsigned)time(NULL));//randomizing seed FILE *noslac_lessonsp;//lesson pointer if((noslac_lessonsp=fopen(file_to_read,"r"))==NULL) { fprintf(stderr, "%s\n", "Fatal Error, Some files are missing"); exit(EXIT_FAILURE); } fseek(noslac_lessonsp,move_lesson_to,SEEK_SET); while(block_count <= (int)(length_to_read/((chars_to_read+1) * block_length)))//testing inorder to read the entire lesson chosen. { num_of_chars_typed=0; char time_checker=0;//changes back to zero after every block typing /*goes =reads a certain number of characters in the file using a loop determined by the random generator and places the pointer at the end of it's reading. thereby making the lesson each time to be random*/ if(mode==0) { int u=0;//counter while(u<=rand()%(length_to_read-((chars_to_read+1)*block_length))&&(ch=getc(noslac_lessonsp))!=EOF)//program feels new u++; do fseek(noslac_lessonsp,-2L,SEEK_CUR); while((ch=getc(noslac_lessonsp))!=' ');//moving backwards from where it is placed //to start reading from where there is a space or has found an uppercase letter. } number_of_lines_count=1; while(number_of_lines_count<=block_length)//testing for number of lines to read. { i=0; char endl = guess(14, 33);//endl holds the char to end a line in place of usual '\n' char startl = guess(14, 33); //guess generates a random char while(i <= chars_to_read)//test on i to get 77 characters. the screen size is exactly 77 characters. { linetype[i] = getc(noslac_lessonsp);//getting characters and placing in the linetype array. if(linetype[0] == ' ')//prevent a the start of a line from ever being a space character linetype[0] = startl; //replace with random char if(linetype[chars_to_read] == ' ')//ensuring a line does not end with a space character. linetype[chars_to_read] = '-';//replacing space character at the end of a line with a - if(i > 1) if(linetype[i-1] == ' ' && linetype[i] == ' ')//preventing two consecutive space characters since text read is random. i -= 2; //checking and eliminating newlines to prevent brakes. if(linetype[i]=='\n'){ linetype[i] = endl; linetype[++i] = ' '; } if(linetype[i]==EOF)//making sure a line does not contain any end of file character by any chance { fprintf(stderr, "%s\n", "Closed unexpectedly, <possibly a corrupt cmdtypist file OR you haven't placed any text in myown.txt>"); exit(EXIT_FAILURE); } i++; } linetype[i]='\0';//Adding string terminator and subtracting the number of spaces removed. if((number_of_lines_count % (block_length)) == 0 && number_of_lines_count != 0) printf(""LAST_LINE_BLUE""); else printf(""RESET""); puts(linetype);//using puts inorder to print the a line and move to the next for the user to follow number_of_lines_count++; i=0;//setting i to 0 to begin new counting. unsigned short error_store[3000], j=0;//error_store: array of ints to note the index of a wrong character. while(i <= chars_to_read+1)//adding 1 for the extra enter key after the 77 letters are entered. { int u=0;//loop counter if((ch=getche())!='\n'&&ch!=EOF)//using getche to prevent printing of enter key. { putchar(ch); if(time_checker==0)//Making sure time is initialized only once { time_checker=1; wrong_letters=0;//setting errors to 0 to start next typing session start_time=(unsigned)time(NULL);//to start timing. } } if(ch==EOF) { fprintf(stderr, "%s\n", "Closed unexpectedly, <an unexpected character keyed in>"); exit(EXIT_FAILURE); } if(ch == 27 || ch == '\t')/*testing for ESC character or a tab to exit program. iscntrl ensures a control character is entered to exit the program*/ { terminate=1; letter_clear(1); puts("\n"); break; } if((ch==127 || ch == 8)&& i == 0)//not using '\b' since most terminals are 'cooked' (keys like backspace are handled by terminal driver) //checking for both delete and backspace. letter_clear(adapt_to_ver_read()); else if((ch == 127 || ch == 8) && i > 0)//testing for delete of backspace { i--;//decremting the number of characters entered when backspaced is pressed. letter_clear(adapt_to_ver_read()); j=wrong_letters; while(j>u)//counting from u to j, to find if there is a wrong character stored in the error_store array of ints. { //printf("j=%d and u=%d\n", j,u); if(error_store[j]==i)//checking through the array for errased wrong charactes initially entered. { //also ensuring before any decrement, wrong_letters>0 wrong_letters--;//decrementing the number of wrong letters. /*if(wrong_letters<0) { printf("finally got a case %d\n",wrong_letters); wrong_letters=0; }*/ error_store[j]=-99;//-99 is a value which will never be reached. //this is to mark the erased index as no longer wrong. break;//Ensuring that immediately there is a match, the while loop is escaped for speed. } j--; } } else if(i==78&&ch!='\n') letter_clear(1); else if(ch!=linetype[i]) { if(ch!='\n')//testing for ENTER to prevent its printing by printf which will cause a newline. { num_of_chars_typed++; letter_clear(1);//clearing the wrong character //printf("\a"RED"%c"RESET"",ch );//to print again with color RED. \a is used to include a beep for wrong charater printf("%s%c",(sound_config_read())==1? "\a"RED"":""RED"",ch);//\a is used to include a beep for wrong character entries wrong_letters++; error_store[wrong_letters]=i;//recording the index of a wrong letter u=0; j++; //Incrementing the backspace counter. i++; //incrementing the number of wrong characters entered. } } else { if(ch!='\n')//Preventing printing of newline which causes an escape from current typing position in the console. { letter_clear(1); num_of_chars_typed++; printf(""GREEN"%c"RESET"", ch);//changing color of correct character to green. i++; } } if(ch=='\n'&&i==78) break;//escaping loop when the user keys in an Enter. } printf("%s","\n" ); //Prints two spaces to ensure the two console spaces left are used, so next printing goes to next line. Game console is 80 and 78 is being used. if(terminate==1||argc_cmd==4) break; } elapsed_time = (unsigned)time(NULL) - start_time;/*getting the final time and subtracting from the initial to get the elapsed time*/ block_count++; //printf("lines=%d block = %d\n",number_of_lines_count,block_length ); if(terminate==1)//exiting on tabs and other systme keys { char user_name[81]; if(elapsed_time <= 10) { fprintf(stderr, "%s\n", "Speed not recorded"); printf(""RESET"\n"); exit(EXIT_SUCCESS); } get_user_name(user_name); printf(""GREEN" "); printf("%s", user_name); if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters. wrong_letters=0; write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed); session_style(elapsed_time,wrong_letters,num_of_chars_typed); exit(EXIT_SUCCESS);//display current typing speed and error } if(((number_of_lines_count-1)%block_length)==0) { char user_name[81]; if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters. wrong_letters=0; printf(""GREEN" "); get_user_name(user_name);//reading user name from file to display in session printf("%s", user_name); session_style(elapsed_time,wrong_letters,num_of_chars_typed);//printing session speed details write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed);//writing user speed to speed file } } } /*Wrong letters algorithm: if a user is at the first position of the line and presses backspace, then, that backspace is simply cleared and i not incremented the array error_store[] keeps track of the index(the i position of the wrong character) and increments a counter variable j, which which be used as A stop point in a for loop when this stored inex is searched. When ever backspace keyed in(i!=0), i is first decremented and a search is done through out the loop to see if the decremented i was stored in error store, if so, then the user is erasing a wrong character, so the wrong_letters is decremented.*/ /*solving the case where wrong_letters shows a messy value changing it's type to int and making sure it's always greater than 0 */
Noslac/cmd_typist
cmd_typist.c
C
gpl-3.0
19,200
package com.dank.festivalapp.lib; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DataBaseHelper extends SQLiteOpenHelper{ //The Android's default system path of your application database. private static final String DATABASE_NAME = "FestivalApp.db"; private static final int DATABASE_VERSION = 1; private static DataBaseHelper mInstance = null; private DataBaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public static DataBaseHelper getInstance(Context ctx) { /** * use the application context as suggested by CommonsWare. * this will ensure that you dont accidentally leak an Activitys * context (see this article for more information: * http://developer.android.com/resources/articles/avoiding-memory-leaks.html) */ if (mInstance == null) { mInstance = new DataBaseHelper(ctx); } return mInstance; } public boolean isTableExists(SQLiteDatabase db, String tableName) { Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+ tableName +"'", null); if(cursor != null) { if(cursor.getCount() > 0) { cursor.close(); return true; } cursor.close(); } return false; } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(DataBaseHelper.class.getName(), "TODO "); } }
dankl/festivalapp-lib
src/com/dank/festivalapp/lib/DataBaseHelper.java
Java
gpl-3.0
1,650
/* WebROaR - Ruby Application Server - http://webroar.in/ * Copyright (C) 2009 Goonj LLC * * This file is part of WebROaR. * * WebROaR 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. * * WebROaR 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 WebROaR. If not, see <http://www.gnu.org/licenses/>. */ #ifndef WR_ACCESS_LOG_H_ #define WR_ACCESS_LOG_H_ #define WR_ACCESS_LOG_FILE "/var/log/webroar/access.log" #define WR_REQ_USER_AGENT "HTTP_USER_AGENT" #define WR_REQ_REFERER "HTTP_REFERER" #include <wr_request.h> int wr_access_log(wr_req_t*); #endif /*WR_ACCESS_LOG_H_*/
webroar/webroar
src/head/wr_access_log.h
C
gpl-3.0
1,056
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2019-2020 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package install import ( "bytes" "fmt" "os/exec" "strconv" "strings" "time" "github.com/snapcore/snapd/gadget" "github.com/snapcore/snapd/gadget/quantity" "github.com/snapcore/snapd/logger" "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/strutil" ) var ( ensureNodesExist = ensureNodesExistImpl ) var createdPartitionGUID = []string{ "0FC63DAF-8483-4772-8E79-3D69D8477DE4", // Linux filesystem data "0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", // Linux swap partition } // creationSupported returns whether we support and expect to create partitions // of the given type, it also means we are ready to remove them for re-installation // or retried installation if they are appropriately marked with createdPartitionAttr. func creationSupported(ptype string) bool { return strutil.ListContains(createdPartitionGUID, strings.ToUpper(ptype)) } // createMissingPartitions creates the partitions listed in the laid out volume // pv that are missing from the existing device layout, returning a list of // structures that have been created. func createMissingPartitions(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume) ([]gadget.OnDiskStructure, error) { buf, created := buildPartitionList(dl, pv) if len(created) == 0 { return created, nil } logger.Debugf("create partitions on %s: %s", dl.Device, buf.String()) // Write the partition table. By default sfdisk will try to re-read the // partition table with the BLKRRPART ioctl but will fail because the // kernel side rescan removes and adds partitions and we have partitions // mounted (so it fails on removal). Use --no-reread to skip this attempt. cmd := exec.Command("sfdisk", "--append", "--no-reread", dl.Device) cmd.Stdin = buf if output, err := cmd.CombinedOutput(); err != nil { return created, osutil.OutputErr(output, err) } // Re-read the partition table if err := reloadPartitionTable(dl.Device); err != nil { return nil, err } // Make sure the devices for the partitions we created are available if err := ensureNodesExist(created, 5*time.Second); err != nil { return nil, fmt.Errorf("partition not available: %v", err) } return created, nil } // buildPartitionList builds a list of partitions based on the current // device contents and gadget structure list, in sfdisk dump format, and // returns a partitioning description suitable for sfdisk input and a // list of the partitions to be created. func buildPartitionList(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume) (sfdiskInput *bytes.Buffer, toBeCreated []gadget.OnDiskStructure) { sectorSize := dl.SectorSize // Keep track what partitions we already have on disk seen := map[quantity.Offset]bool{} for _, s := range dl.Structure { start := s.StartOffset / quantity.Offset(sectorSize) seen[start] = true } // Check if the last partition has a system-data role canExpandData := false if n := len(pv.LaidOutStructure); n > 0 { last := pv.LaidOutStructure[n-1] if last.VolumeStructure.Role == gadget.SystemData { canExpandData = true } } // The partition index pIndex := 0 // Write new partition data in named-fields format buf := &bytes.Buffer{} for _, p := range pv.LaidOutStructure { if !p.IsPartition() { continue } pIndex++ s := p.VolumeStructure // Skip partitions that are already in the volume start := p.StartOffset / quantity.Offset(sectorSize) if seen[start] { continue } // Only allow the creation of partitions with known GUIDs // TODO:UC20: also provide a mechanism for MBR (RPi) ptype := partitionType(dl.Schema, p.Type) if dl.Schema == "gpt" && !creationSupported(ptype) { logger.Noticef("cannot create partition with unsupported type %s", ptype) continue } // Check if the data partition should be expanded size := s.Size if s.Role == gadget.SystemData && canExpandData && quantity.Size(p.StartOffset)+s.Size < dl.Size { size = dl.Size - quantity.Size(p.StartOffset) } // Can we use the index here? Get the largest existing partition number and // build from there could be safer if the disk partitions are not consecutive // (can this actually happen in our images?) node := deviceName(dl.Device, pIndex) fmt.Fprintf(buf, "%s : start=%12d, size=%12d, type=%s, name=%q\n", node, p.StartOffset/quantity.Offset(sectorSize), size/sectorSize, ptype, s.Name) toBeCreated = append(toBeCreated, gadget.OnDiskStructure{ LaidOutStructure: p, Node: node, Size: size, }) } return buf, toBeCreated } func partitionType(label, ptype string) string { t := strings.Split(ptype, ",") if len(t) < 1 { return "" } if len(t) == 1 { return t[0] } if label == "gpt" { return t[1] } return t[0] } func deviceName(name string, index int) string { if len(name) > 0 { last := name[len(name)-1] if last >= '0' && last <= '9' { return fmt.Sprintf("%sp%d", name, index) } } return fmt.Sprintf("%s%d", name, index) } // removeCreatedPartitions removes partitions added during a previous install. func removeCreatedPartitions(lv *gadget.LaidOutVolume, dl *gadget.OnDiskVolume) error { indexes := make([]string, 0, len(dl.Structure)) for i, s := range dl.Structure { if wasCreatedDuringInstall(lv, s) { logger.Noticef("partition %s was created during previous install", s.Node) indexes = append(indexes, strconv.Itoa(i+1)) } } if len(indexes) == 0 { return nil } // Delete disk partitions logger.Debugf("delete disk partitions %v", indexes) cmd := exec.Command("sfdisk", append([]string{"--no-reread", "--delete", dl.Device}, indexes...)...) if output, err := cmd.CombinedOutput(); err != nil { return osutil.OutputErr(output, err) } // Reload the partition table if err := reloadPartitionTable(dl.Device); err != nil { return err } // Re-read the partition table from the device to update our partition list if err := gadget.UpdatePartitionList(dl); err != nil { return err } // Ensure all created partitions were removed if remaining := createdDuringInstall(lv, dl); len(remaining) > 0 { return fmt.Errorf("cannot remove partitions: %s", strings.Join(remaining, ", ")) } return nil } // ensureNodeExists makes sure the device nodes for all device structures are // available and notified to udev, within a specified amount of time. func ensureNodesExistImpl(dss []gadget.OnDiskStructure, timeout time.Duration) error { t0 := time.Now() for _, ds := range dss { found := false for time.Since(t0) < timeout { if osutil.FileExists(ds.Node) { found = true break } time.Sleep(100 * time.Millisecond) } if found { if err := udevTrigger(ds.Node); err != nil { return err } } else { return fmt.Errorf("device %s not available", ds.Node) } } return nil } // reloadPartitionTable instructs the kernel to re-read the partition // table of a given block device. func reloadPartitionTable(device string) error { // Re-read the partition table using the BLKPG ioctl, which doesn't // remove existing partitions, only appends new partitions with the right // size and offset. As long as we provide consistent partitioning from // userspace we're safe. output, err := exec.Command("partx", "-u", device).CombinedOutput() if err != nil { return osutil.OutputErr(output, err) } return nil } // udevTrigger triggers udev for the specified device and waits until // all events in the udev queue are handled. func udevTrigger(device string) error { if output, err := exec.Command("udevadm", "trigger", "--settle", device).CombinedOutput(); err != nil { return osutil.OutputErr(output, err) } return nil } // wasCreatedDuringInstall returns if the OnDiskStructure was created during // install by referencing the gadget volume. A structure is only considered to // be created during install if it is a role that is created during install and // the start offsets match. We specifically don't look at anything on the // structure such as filesystem information since this may be incomplete due to // a failed installation, or due to the partial layout that is created by some // ARM tools (i.e. ptool and fastboot) when flashing images to internal MMC. func wasCreatedDuringInstall(lv *gadget.LaidOutVolume, s gadget.OnDiskStructure) bool { // for a structure to have been created during install, it must be one of // the system-boot, system-data, or system-save roles from the gadget, and // as such the on disk structure must exist in the exact same location as // the role from the gadget, so only return true if the provided structure // has the exact same StartOffset as one of those roles for _, gs := range lv.LaidOutStructure { // TODO: how to handle ubuntu-save here? maybe a higher level function // should decide whether to delete it or not? switch gs.Role { case gadget.SystemSave, gadget.SystemData, gadget.SystemBoot: // then it was created during install or is to be created during // install, see if the offset matches the provided on disk structure // has if s.StartOffset == gs.StartOffset { return true } } } return false } // createdDuringInstall returns a list of partitions created during the // install process. func createdDuringInstall(lv *gadget.LaidOutVolume, layout *gadget.OnDiskVolume) (created []string) { created = make([]string, 0, len(layout.Structure)) for _, s := range layout.Structure { if wasCreatedDuringInstall(lv, s) { created = append(created, s.Node) } } return created }
chipaca/snappy
gadget/install/partition.go
GO
gpl-3.0
10,175
-- -- PostgreSQL database dump -- SET statement_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; -- -- Name: casts; Type: SCHEMA; Schema: -; Owner: - -- CREATE SCHEMA casts; SET search_path = casts, pg_catalog; -- -- Name: _date_to_bigint(date); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _date_to_bigint(date) RETURNS bigint LANGUAGE sql IMMUTABLE STRICT AS $_$ SELECT casts._date_to_integer($1)::bigint $_$; -- -- Name: _date_to_integer(date); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _date_to_integer(date) RETURNS integer LANGUAGE sql IMMUTABLE STRICT AS $_$ SELECT EXTRACT(YEAR FROM $1)::integer * 10000 + EXTRACT(MONTH FROM $1)::integer * 100 + EXTRACT(DAY FROM $1)::integer $_$; -- -- Name: _interval_to_bigint(interval); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _interval_to_bigint(interval) RETURNS bigint LANGUAGE sql IMMUTABLE STRICT AS $_$ SELECT EXTRACT(YEAR FROM $1)::bigint * 10000000000 + EXTRACT(MONTH FROM $1)::bigint * 100000000 + EXTRACT(DAY FROM $1)::bigint * 1000000 + EXTRACT(HOUR FROM $1)::bigint * 10000 + EXTRACT(MINUTE FROM $1)::bigint * 100 + EXTRACT(SECONDS FROM $1)::bigint $_$; -- -- Name: _text_to_bigint(text); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _text_to_bigint(text) RETURNS bigint LANGUAGE plperlu IMMUTABLE STRICT COST 1 AS $_X$ return $1 if ($_[0] =~ m/^(\d+)(\.\d+)?$/); return undef; $_X$; -- -- Name: _text_to_date(text); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _text_to_date(text) RETURNS date LANGUAGE plperlu IMMUTABLE STRICT COST 1 AS $_X$ $_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format return $& if( $_[0] =~ m/^(\d{4}-\d{1,2}-\d{1,2})/ ); return undef; $_X$; -- -- Name: _text_to_numeric(text); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _text_to_numeric(text) RETURNS numeric LANGUAGE plperlu IMMUTABLE STRICT COST 1 AS $_X$ return $1.$2 if( $_[0] =~ m/^(\d+)(\.\d+)?$/); return undef; $_X$; -- -- Name: _text_to_time(text); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _text_to_time(text) RETURNS time without time zone LANGUAGE plperlu IMMUTABLE STRICT COST 1 AS $_X$ return $& if( $_[0] =~ s/^(\d{1,2}:\d{1,2})(:\d{1,2}(\.\d+)?)?$/$1$2/ ); return undef; $_X$; -- -- Name: _text_to_timestamp(text); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _text_to_timestamp(text) RETURNS timestamp without time zone LANGUAGE plperlu IMMUTABLE STRICT COST 1 AS $_X$ $_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format return $_[0] if( $_[0] =~ s/^(\d{4}-\d{2}-\d{2})( \d{1,2}:\d{2}:\d{2})?(\.\d+)?([\+\-\d\:.]+)?/$1$2$3$4/ ); return undef; $_X$; -- -- Name: _text_to_timestamptz(text); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _text_to_timestamptz(text) RETURNS timestamp with time zone LANGUAGE plperlu IMMUTABLE STRICT COST 1 AS $_X$ $_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format return $_[0] if( $_[0] =~ s/^(\d{4}-\d{2}-\d{2})( \d{1,2}:\d{2}:\d{2})?(\.\d+)?([\+\-\d\:.]+)?/$1$2$3$4/ ); return undef; $_X$; -- -- Name: _time_to_integer(time without time zone); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _time_to_integer(time without time zone) RETURNS integer LANGUAGE sql IMMUTABLE STRICT AS $_$ SELECT EXTRACT(HOUR FROM $1)::integer * 10000 + EXTRACT(MINUTE FROM $1)::integer * 100 + EXTRACT(SECONDS FROM $1)::integer $_$; -- -- Name: _time_to_integer(time with time zone); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _time_to_integer(time with time zone) RETURNS integer LANGUAGE sql IMMUTABLE STRICT AS $_$ SELECT EXTRACT(HOUR FROM $1)::integer * 10000 + EXTRACT(MINUTE FROM $1)::integer * 100 + EXTRACT(SECONDS FROM $1)::integer $_$; -- -- Name: _unknown_to_bigint(unknown); Type: FUNCTION; Schema: casts; Owner: - -- CREATE OR REPLACE FUNCTION _unknown_to_bigint(unknown) RETURNS bigint LANGUAGE plperlu AS $_X$ return $1 if ($_[0] =~ m/^(\d+)(\.\d+)?$/); return undef; $_X$; SET search_path = pg_catalog; -- -- Name: CAST (date AS integer); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (date AS integer) WITH FUNCTION casts._date_to_integer(date) AS IMPLICIT; -- -- Name: CAST (date AS bigint); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (date AS bigint) WITH FUNCTION casts._date_to_bigint(date) AS IMPLICIT; -- -- Name: CAST (interval AS bigint); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (interval AS bigint) WITH FUNCTION casts._interval_to_bigint(interval) AS IMPLICIT; -- -- Name: CAST (text AS date); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (text AS date) WITH FUNCTION casts._text_to_date(text) AS IMPLICIT; -- -- Name: CAST (text AS bigint); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (text AS bigint) WITH FUNCTION casts._text_to_bigint(text) AS IMPLICIT; -- -- Name: CAST (text AS numeric); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (text AS numeric) WITH FUNCTION casts._text_to_numeric(text) AS IMPLICIT; -- -- Name: CAST (text AS time without time zone); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (text AS time without time zone) WITH FUNCTION casts._text_to_time(text) AS IMPLICIT; -- -- Name: CAST (text AS timestamp without time zone); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (text AS timestamp without time zone) WITH FUNCTION casts._text_to_timestamp(text) AS IMPLICIT; -- -- Name: CAST (text AS timestamp with time zone); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (text AS timestamp with time zone) WITH FUNCTION casts._text_to_timestamptz(text) AS IMPLICIT; -- -- Name: CAST (time without time zone AS integer); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (time without time zone AS integer) WITH FUNCTION casts._time_to_integer(time without time zone) AS IMPLICIT; -- -- Name: CAST (time with time zone AS integer); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (time with time zone AS integer) WITH FUNCTION casts._time_to_integer(time with time zone) AS IMPLICIT; -- -- Name: CAST (unknown AS bigint); Type: CAST; Schema: pg_catalog; Owner: - -- CREATE CAST (unknown AS bigint) WITH FUNCTION casts._unknown_to_bigint(unknown) AS IMPLICIT; -- -- PostgreSQL database dump complete --
amgroup/woocommerce-pg
sql/db.schema.casts.pg.sql
SQL
gpl-3.0
6,751
# Thème Wordpress du site tela-botanica.org Ce thème utilise le bundler [Webpack](https://webpack.github.io) et l'outil de gestion de dépendances [Composer](https://getcomposer.org). ## Pour débuter Installer [Node](https://nodejs.org) Installer les dépendences du projet npm install composer install Définir les constantes suivantes dans `wp-config.php`: ```php /** * Remplir ces valeurs avec les clés d'API du compte Algolia */ define('ALGOLIA_APPLICATION_ID',); define('ALGOLIA_SEARCH_API_KEY',); define('ALGOLIA_ADMIN_API_KEY',); define('ALGOLIA_PREFIX',); // (correspondant à l'environnement en cours, par exemple `prod_`) ``` ### Pendant le développement npm start Cette commande : - surveille les fichiers du thème - recompile automatiquement à chaque modification ### Compiler le thème npm run build Cette commande : - compile `assets/styles/main.scss` dans `dist/bundle.css` - compile `assets/scripts/main.js` dans `dist/bundle.js` - inclut en inline les images SVG utilisées dans les feuilles de style ### Déployer le thème avec git Depuis le serveur : git pull composer install
telabotanica/wp-theme-telabotanica
README.md
Markdown
gpl-3.0
1,142
// ---------------------------------------------------------------------- // File: VersionedHashRevisionTracker.cc // Author: Georgios Bitzes - CERN // ---------------------------------------------------------------------- /************************************************************************ * quarkdb - a redis-like highly available key-value store * * Copyright (C) 2019 CERN/Switzerland * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>.* ************************************************************************/ #include "VersionedHashRevisionTracker.hh" #include "utils/Macros.hh" #include "Formatter.hh" namespace quarkdb { //------------------------------------------------------------------------------ // Indicate which revision we're referring to. When called multiple times // for the same object, the given value MUST be the same. //------------------------------------------------------------------------------ void VersionedHashRevision::setRevisionNumber(uint64_t rev) { if(currentRevision != 0) { qdb_assert(currentRevision == rev); } else { currentRevision = rev; } } //------------------------------------------------------------------------------ // Add to update batch - empty value indicates deletion //------------------------------------------------------------------------------ void VersionedHashRevision::addUpdate(std::string_view field, std::string_view value) { updateBatch.emplace_back(field, value); } //------------------------------------------------------------------------------ // Serialize contents //------------------------------------------------------------------------------ std::string VersionedHashRevision::serialize() const { return Formatter::vhashRevision(currentRevision, updateBatch).val; } //------------------------------------------------------------------------------ // Get revision for a specific key //------------------------------------------------------------------------------ VersionedHashRevision& VersionedHashRevisionTracker::forKey(std::string_view key) { return contents[std::string(key)]; } //------------------------------------------------------------------------------ // Iterate through contents //------------------------------------------------------------------------------ std::map<std::string, VersionedHashRevision>::iterator VersionedHashRevisionTracker::begin() { return contents.begin(); } std::map<std::string, VersionedHashRevision>::iterator VersionedHashRevisionTracker::end() { return contents.end(); } }
gbitzes/quarkdb
src/storage/VersionedHashRevisionTracker.cc
C++
gpl-3.0
3,494
Provisioning a new site ======================= ## Required packages: * nginx * Python 3 * Git * pip * virtualenv e.g.,, on Ubuntu: sudo apt-get install nginx git python3 python3-pip sudo pip3 install virtualenv ## Nginx Virtual Host config * see nginx.template.conf * replace SITENAME with, e.g., staging.my-domain.com ## Systemd service * see gunicorn-systemd.template.service * replace SITENAME with, e.g., staging.my-domain.com ## Folder structure: Assume we have a user account at /home/username /home/username └── sites └── SITENAME ├── database ├── source ├── static └── virtualenv
kdchaires/superlists-tdd-python
superlists/deploy_tools/provisioning_notes.md
Markdown
gpl-3.0
683
package ems.server.protocol; import ems.server.domain.Device; import ems.server.domain.EventSeverity; import ems.server.domain.EventType; import ems.server.utils.EventHelper; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * EventAwareResponseHandler * Created by thebaz on 9/15/14. */ public class EventAwareResponseHandler implements ResponseHandler { private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); private final Device device; public EventAwareResponseHandler(Device device) { this.device = device; format.setTimeZone(TimeZone.getTimeZone("UTC")); } @Override public void onTimeout(String variable) { EventHelper.getInstance().addEvent(device, EventType.EVENT_NETWORK, EventSeverity.EVENT_WARN); } @Override public void onSuccess(String variable) { //do nothing } @Override public void onError(String variable, int errorCode, String errorDescription) { EventSeverity eventSeverity = EventSeverity.EVENT_ERROR; EventType eventType = EventType.EVENT_PROTOCOL; String description = "Event of type: \'" + eventType + "\' at: " + format.format(new Date(System.currentTimeMillis())) + " with severity: \'" + eventSeverity + "\' for device: " + device.getName() + ". Error code:" + errorCode + ", Error description: " + errorDescription; EventHelper.getInstance().addEvent(device, eventType, eventSeverity, description); } }
thebaz73/ems-server
src/main/java/ems/server/protocol/EventAwareResponseHandler.java
Java
gpl-3.0
1,600
<?php /* COPYRIGHT 2008 - see www.milliondollarscript.com for a list of authors This file is part of the Million Dollar Script. Million Dollar Script 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. Million Dollar Script 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 the Million Dollar Script. If not, see <http://www.gnu.org/licenses/>. */ require_once ('category.inc.php'); require_once ('lists.inc.php'); require_once ('dynamic_forms.php'); global $ad_tag_to_field_id; global $ad_tag_to_search; global $CACHE_ENABLED; if ($CACHE_ENABLED=='YES') { $dir = dirname(__FILE__); $dir = preg_split ('%[/\\\]%', $dir); $blank = array_pop($dir); $dir = implode('/', $dir); include ("$dir/cache/form1_cache.inc.php"); $ad_tag_to_search = $tag_to_search; $ad_tag_to_field_id = $tag_to_field_id; } else { $ad_tag_to_search = tag_to_search_init(1); $ad_tag_to_field_id = ad_tag_to_field_id_init(); } ##################################### function ad_tag_to_field_id_init () { global $CACHE_ENABLED; if ($CACHE_ENABLED=='YES') { global $ad_tag_to_field_id; return $ad_tag_to_field_id; } global $label; $sql = "SELECT *, t2.field_label AS NAME FROM `form_fields` as t1, form_field_translations as t2 where t1.field_id = t2.field_id AND t2.lang='".$_SESSION['MDS_LANG']."' AND form_id=1 ORDER BY list_sort_order "; $result = mysql_query($sql) or die (mysql_error()); # do a query for each field while ($fields = mysql_fetch_array($result, MYSQL_ASSOC)) { //$form_data = $row[] $tag_to_field_id[$fields['template_tag']]['field_id'] = $fields['field_id']; $tag_to_field_id[$fields['template_tag']]['field_type'] = $fields['field_type']; $tag_to_field_id[$fields['template_tag']]['field_label'] = $fields['NAME']; } $tag_to_field_id["ORDER_ID"]['field_id'] = 'order_id'; $tag_to_field_id["ORDER_ID"]['field_label'] = 'Order ID'; //$tag_to_field_id["ORDER_ID"]['field_label'] = $label["employer_resume_list_date"]; $tag_to_field_id["BID"]['field_id'] = 'banner_id'; $tag_to_field_id["BID"]['field_label'] = 'Grid ID'; $tag_to_field_id["USER_ID"]['field_id'] = 'user_id'; $tag_to_field_id["USER_ID"]['field_label'] = 'User ID'; $tag_to_field_id["AD_ID"]['field_id'] = 'ad_id'; $tag_to_field_id["AD_ID"]['field_label'] = 'Ad ID'; $tag_to_field_id["DATE"]['field_id'] = 'ad_date'; $tag_to_field_id["DATE"]['field_label'] = 'Date'; return $tag_to_field_id; } ###################################################################### function load_ad_values ($ad_id) { $prams = array(); $sql = "SELECT * FROM `ads` WHERE ad_id='$ad_id' "; $result = mysql_query($sql) or die ($sql. mysql_error()); if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $prams['ad_id'] = $ad_id; $prams['user_id'] = $row['user_id']; $prams['order_id'] = $row['order_id']; $prams['banner_id'] = $row['banner_id']; $sql = "SELECT * FROM form_fields WHERE form_id=1 AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' "; $result = mysql_query($sql) or die(mysql_error()); while ($fields = mysql_fetch_array($result, MYSQL_ASSOC)) { $prams[$fields['field_id']] = $row[$fields['field_id']]; if ($fields['field_type']=='DATE') { $day = $_REQUEST[$row['field_id']."d"]; $month = $_REQUEST[$row['field_id']."m"]; $year = $_REQUEST[$row['field_id']."y"]; $prams[$fields['field_id']] = "$year-$month-$day"; } elseif (($fields['field_type']=='MSELECT') || ($row['field_type']=='CHECK')) { if (is_array($_REQUEST[$row['field_id']])) { $prams[$fields['field_id']] = implode (",", $_REQUEST[$fields['field_id']]); } else { $prams[$fields['field_id']] = $_REQUEST[$fields['field_id']]; } } } return $prams; } else { return false; } } ######################################################### function assign_ad_template($prams) { global $label; $str = $label['mouseover_ad_template']; $sql = "SELECT * FROM form_fields WHERE form_id='1' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' "; //echo $sql; $result = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { if ($row['field_type']=='IMAGE') { if ((file_exists(UPLOAD_PATH.'images/'.$prams[$row['field_id']]))&&($prams[$row['field_id']])) { $str = str_replace('%'.$row['template_tag'].'%', '<img alt="" src="'. UPLOAD_HTTP_PATH."images/".$prams[$row['field_id']].'" >', $str); } else { //$str = str_replace('%'.$row['template_tag'].'%', '<IMG SRC="'.UPLOAD_HTTP_PATH.'images/no-image.gif" WIDTH="150" HEIGHT="150" BORDER="0" ALT="">', $str); $str = str_replace('%'.$row['template_tag'].'%', '', $str); } } else { $str = str_replace('%'.$row['template_tag'].'%', get_template_value($row['template_tag'],1), $str); } $str = str_replace('$'.$row['template_tag'].'$', get_template_field_label($row['template_tag'],1), $str); } return $str; } ######################################################### function display_ad_form ($form_id, $mode, $prams) { global $label; global $error; global $BID; if ($prams == '' ) { $prams['mode'] = $_REQUEST['mode']; $prams['ad_id']= $_REQUEST['ad_id']; $prams['banner_id'] = $BID; $prams['user_id'] = $_REQUEST['user_id']; $sql = "SELECT * FROM form_fields WHERE form_id='$form_id' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' "; //echo $sql; $result = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { //$prams[$row[field_id]] = $_REQUEST[$row[field_id]]; if ($row['field_type']=='DATE') { $day = $_REQUEST[$row['field_id']."d"]; $month = $_REQUEST[$row['field_id']."m"]; $year = $_REQUEST[$row['field_id']."y"]; $prams[$row['field_id']] = "$year-$month-$day"; } elseif (($row['field_type']=='MSELECT') || ($row['field_type']=='CHECK')) { if (is_array($_REQUEST[$row['field_id']])) { $prams[$row['field_id']] = implode (",", $_REQUEST[$row['field_id']]); } else { $prams[$row['field_id']] = $_REQUEST[$row['field_id']]; } } else { $prams[$row['field_id']] = stripslashes ($_REQUEST[$row['field_id']]); } } } if (!defined('SCW_INCLUDE')) { ?> <script type='text/JavaScript' src='<?php echo BASE_HTTP_PATH."scw/scw_js.php?lang=".$_SESSION['MDS_LANG']; ?>'></script> <?php define ('SCW_INCLUDE', 'Y'); } ?> <form method="POST" action="<?php htmlentities($_SERVER['PHP_SELF']); ?>" name="form1" onsubmit=" form1.savebutton.disabled=true;" enctype="multipart/form-data"> <input type="hidden" name="mode" size="" value="<?php echo $mode; ?>"> <input type="hidden" name="ad_id" size="" value="<?php echo $prams['ad_id']; ?>"> <input type="hidden" name="user_id" size="" value="<?php echo $prams['user_id']; ?>"> <input type="hidden" name="order_id" size="" value="<?php echo $prams['order_id']; ?>"> <input type="hidden" name="banner_id" size="" value="<?php echo $prams['banner_id']; ?>"> <table cellSpacing="1" cellPadding="5" class="ad_data" id="ad" > <?php if (($error != '' ) && ($mode!='EDIT')) { ?> <tr> <td bgcolor="#F2F2F2" colspan="2"><?php echo "<span class='error_msg_label'>".$label['ad_save_error']."</span><br> <b>".$error."</b>"; ?></td> </tr> <?php } ?> <tr bgColor="#ffffff"> <td bgColor="#eaeaea"> <?php if ($mode == "EDIT") { echo "[Ad Form]"; } // section 1 display_form ($form_id, $mode, $prams, 1); ?> </tr> <tr><td colspan="2" bgcolor="#ffffff"> <input type="hidden" name="save" id="save101" value=""> <?php if ($mode=='edit') { ?> <input class="form_submit_button" TYPE="SUBMIT" class='big_button' name="savebutton" value="<?php echo $label['ad_save_button'];?>" onClick="save101.value='1';"> <?php } ?> </td></tr> </table> </form> <?php } ########################################################################### function list_ads ($admin=false, $order, $offset, $list_mode='ALL', $user_id='') { ## Globals global $label; global $tag_to_field_id; $tag_to_field_id = ad_tag_to_field_id_init(); ########################################### # Load in the form data, including column names # (dont forget LANGUAGE TOO) global $ad_tag_to_field_id; $records_per_page = 40; global $label; // languages array $order_str = $order; if ($order == '') { $order = " `order_id` "; } else { $order = " `$order` "; } global $action; // process search result if ($_REQUEST['action'] == 'search') { $q_string = generate_q_string(1); $where_sql = generate_search_sql(1); } // DATE_FORMAT(`adate`, '%d-%b-%Y') AS formatted_date $order = $_REQUEST['order_by']; if ($_REQUEST['ord']=='asc') { $ord = 'ASC'; } elseif ($_REQUEST['ord']=='desc') { $ord = 'DESC'; } else { $ord = 'DESC'; // sort descending by default } if ($order == '') { $order = " `ad_date` "; } else { $order = " `$order` "; } global $BID; if ($list_mode == 'USER' ) { if (!is_numeric($user_id)) { $user_id = $_SESSION['MDS_ID']; } $sql = "Select * FROM `ads` as t1, `orders` as t2 WHERE t1.ad_id=t2.ad_id AND t1.order_id > 0 AND t1.banner_id='".$BID."' AND t1.user_id='".$user_id."' AND (t2.status = 'completed' OR t2.status = 'expired') $where_sql ORDER BY $order $ord "; } elseif ($list_mode =='TOPLIST') { // $sql = "SELECT *, DATE_FORMAT(MAX(order_date), '%Y-%c-%d') as max_date, sum(quantity) AS pixels FROM orders, ads where ads.order_id=orders.order_id AND status='completed' and orders.banner_id='$BID' GROUP BY orders.user_id, orders.banner_id order by pixels desc "; } else { $sql = "Select * FROM `ads` as t1, `orders` AS t2 WHERE t1.ad_id=t2.ad_id AND t1.banner_id='$BID' and t1.order_id > 0 $where_sql ORDER BY $order $ord "; } //echo "[".$sql."]"; $result = mysql_query($sql) or die (mysql_error()); ############ # get the count $count = mysql_num_rows($result); if ($count > $records_per_page) { mysql_data_seek($result, $offset); } if ($count > 0 ) { if ($pages == 1) { } elseif ($list_mode!='USER') { $pages = ceil($count / $records_per_page); $cur_page = $_REQUEST['offset'] / $records_per_page; $cur_page++; echo "<center>"; //echo "Page $cur_page of $pages - "; $label["navigation_page"] = str_replace ("%CUR_PAGE%", $cur_page, $label["navigation_page"]); $label["navigation_page"] = str_replace ("%PAGES%", $pages, $label["navigation_page"]); echo "<span > ".$label["navigation_page"]."</span> "; $nav = nav_pages_struct($result, $q_string, $count, $records_per_page); $LINKS = 10; render_nav_pages($nav, $LINKS, $q_string, $show_emp, $cat); echo "</center>"; } $dir = dirname(__FILE__); $dir = preg_split ('%[/\\\]%', $dir); $blank = array_pop($dir); $dir = implode('/', $dir); include ($dir.'/mouseover_box.htm'); // edit this file to change the style of the mouseover box! echo '<script language="JAVASCRIPT">'; include ('mouseover_js.inc.php'); echo '</script>'; ?> <table border='0' bgcolor='#d9d9d9' cellspacing="1" cellpadding="5" id="adslist" > <tr bgcolor="#EAEAEA"> <?php if ($admin == true ) { echo '<td class="list_header_cell">&nbsp;</td>'; } if ($list_mode == 'USER' ) { echo '<td class="list_header_cell">&nbsp;</td>'; } echo_list_head_data(1, $admin); if (($list_mode == 'USER' ) || ($admin)) { echo '<td class="list_header_cell">'.$label['ads_inc_pixels_col'].'</td>'; echo '<td class="list_header_cell">'.$label['ads_inc_expires_col'].'</td>'; echo '<td class="list_header_cell" >'.$label['ad_list_status'].'</td>'; } ?> </tr> <?php $i=0; global $prams; while (($prams = mysql_fetch_array($result, MYSQL_ASSOC)) && ($i < $records_per_page)) { $i++; ?> <tr bgcolor="ffffff" onmouseover="old_bg=this.getAttribute('bgcolor');this.setAttribute('bgcolor', '#FBFDDB', 0);" onmouseout="this.setAttribute('bgcolor', old_bg, 0);"> <?php if ($admin == true ) { echo '<td class="list_data_cell" >'; ?> <!--<input style="font-size: 8pt" type="button" value="Delete" onClick="if (!confirmLink(this, 'Delete, are you sure?')) {return false;} window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=delete&ad_id=<?php echo $prams['ad_id']; ?>'"><br>!--> <input type="button" style="font-size: 8pt" value="Edit" onClick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=edit&ad_id=<?php echo $prams['ad_id']; ?>'"> <?php echo '</td>'; } if ($list_mode == 'USER' ) { echo '<td class="list_data_cell">'; ?> <!--<input style="font-size: 8pt" type="button" value="Delete" onClick="if (!confirmLink(this, 'Delete, are you sure?')) {return false;} window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=delete&ad_id=<?php echo $prams['ad_id']; ?>'"><br>--> <input type="button" style="font-size: 8pt" value="Edit" onClick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?ad_id=<?php echo $prams['ad_id']; ?>'"> <?php echo '</td>'; } echo_ad_list_data($admin); if (($list_mode == 'USER' ) || ($admin)) { ///////////////// echo '<td class="list_data_cell"><img src="get_order_image.php?BID='.$BID.'&aid='.$prams['ad_id'].'"></td>'; ////////////////// echo '<td>'; if ($prams['days_expire'] > 0) { if ($prams['published']!='Y') { $time_start = strtotime(gmdate('r')); } else { $time_start = strtotime($prams['date_published']." GMT"); } $elapsed_time = strtotime(gmdate('r')) - $time_start; $elapsed_days = floor ($elapsed_time / 60 / 60 / 24); $exp_time = ($prams['days_expire'] * 24 * 60 * 60); $exp_time_to_go = $exp_time - $elapsed_time; $exp_days_to_go = floor ($exp_time_to_go / 60 / 60 / 24); $to_go = elapsedtime($exp_time_to_go); $elapsed = elapsedtime($elapsed_time); if ($prams['status']=='expired') { $days = "<a href='orders.php'>".$label['ads_inc_expied_stat']."</a>"; } elseif ($prams['date_published']=='') { $days = $label['ads_inc_nyp_stat']; } else { $days = str_replace ('%ELAPSED%', $elapsed, $label['ads_inc_elapsed_stat']); $days = str_replace ('%TO_GO%', $to_go, $days); //$days = "$elapsed elapsed<br> $to_go to go "; } //$days = $elapsed_time; //print_r($prams); } else { $days = $label['ads_inc_nev_stat']; } echo $days; echo '</td>'; ///////////////// if ($prams['published']=='Y') { $pub =$label['ads_inc_pub_stat']; } else { $pub = $label['ads_inc_npub_stat']; } if ($prams['approved']=='Y') { $app = $label['ads_inc_app_stat'].', '; } else { $app = $label['ads_inc_napp_stat'].', '; } //$label['ad_list_st_'.$prams['status']]." echo '<td class="list_data_cell">'.$app.$pub."</td>"; } ?> </tr> <?php //$prams[file_photo] = ''; // $new_name=''; } echo "</table>"; } else { echo "<center><font size='2' face='Arial'><b>".$label["ads_not_found"].".</b></font></center>"; } return $count; } ######################################################## function delete_ads_files ($ad_id) { $sql = "select * from form_fields where form_id=1 "; $result = mysql_query ($sql) or die (mysql_error()); while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) { $field_id = $row['field_id']; $field_type = $row['field_type']; if (($field_type == "FILE")) { deleteFile("ads", "ad_id", $ad_id, $field_id); } if (($field_type == "IMAGE")){ deleteImage("ads", "ad_id", $ad_id, $field_id); } } } #################### function delete_ad ($ad_id) { delete_ads_files ($ad_id); $sql = "delete FROM `ads` WHERE `ad_id`='".$ad_id."' "; $result = mysql_query($sql) or die (mysql_error().$sql); } ################################ function search_category_tree_for_ads() { if (func_num_args() > 0 ) { $cat_id = func_get_arg(0); } else { $cat_id = $_REQUEST[cat]; } $sql = "select search_set from categories where category_id='$cat_id' "; $result2 = mysql_query ($sql) or die (mysql_error()); $row = mysql_fetch_array($result2); $search_set = $row[search_set]; $sql = "select * from form_fields where field_type='CATEGORY' AND form_id='1'"; $result = mysql_query ($sql) or die (mysql_error()); $i=0; if (mysql_num_rows($result) >0) { while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) { if ($i>0) { $where_cat .= " OR "; } $where_cat .= " `$row[field_id]` IN ($search_set) "; $i++; } } if ($where_cat=='') { return " AND 1=2 "; } if ($search_set=='') { return ""; } return " AND ($where_cat) "; } #################### function search_category_for_ads() { if (func_num_args() > 0 ) { $cat_id = func_get_arg(0); } else { $cat_id = $_REQUEST[cat]; } $sql = "select * from form_fields where field_type='CATEGORY' AND form_id='1'"; $result = mysql_query ($sql) or die (mysql_error()); $i=0; if (mysql_num_rows($result) >0) { while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) { if ($i>0) { $where_cat .= " OR "; } $where_cat .= " `$row[field_id]`='$cat_id' "; $i++; } } if ($where_cat=='') { return " AND 1=2 "; } return " AND ($where_cat) "; //$sql ="Select * from posts_table where $where_cat "; //echo $sql."<br/>"; //$result2 = mysql_query ($sql) or die (mysql_error()); } ################## function generate_ad_id () { $query ="SELECT max(`ad_id`) FROM `ads`"; $result = mysql_query($query) or die(mysql_error()); $row = mysql_fetch_row($result); $row[0]++; return $row[0]; } ################# function temp_ad_exists($sid) { $query ="SELECT ad_id FROM `ads` where user_id='$sid' "; $result = mysql_query($query) or die(mysql_error()); // $row = mysql_fetch_row($result); return mysql_num_rows($result); } ################################################################ function insert_ad_data() { if (func_num_args() > 0) { $admin = func_get_arg(0); // admin mode. } $user_id = $_SESSION['MDS_ID']; if ($user_id=='') { $user_id = addslashes(session_id()); } $order_id = $_REQUEST['order_id']; $ad_date = (gmdate("Y-m-d H:i:s")); $banner_id = $_REQUEST['banner_id']; if ($_REQUEST['ad_id'] == '') { $ad_id = generate_ad_id (); $now = (gmdate("Y-m-d H:i:s")); $sql = "REPLACE INTO `ads` (`ad_id`, `order_id`, `user_id`, `ad_date`, `banner_id` ".get_sql_insert_fields(1).") VALUES ('$ad_id', '$order_id', '$user_id', '$ad_date', '$banner_id' ".get_sql_insert_values(1, "ads", "ad_id", $_REQUEST['ad_id'], $user_id).") "; } else { $ad_id = $_REQUEST['ad_id']; if (!$admin) { // make sure that the logged in user is the owner of this ad. if (!is_numeric($_REQUEST['user_id'])) { // temp order (user_id = session_id()) if ($_REQUEST['user_id']!=session_id()) return false; } else { // user is logged in $sql = "select user_id from `ads` WHERE ad_id='".$_REQUEST['ad_id']."'"; $result = mysql_query ($sql) or die(mysql_error()); $row = @mysql_fetch_array($result); if ($_SESSION['MDS_ID']!==$row['user_id']) { return false; // not the owner, hacking attempt! } } } $now = (gmdate("Y-m-d H:i:s")); $sql = "UPDATE `ads` SET `ad_date`='$now' ".get_sql_update_values (1, "ads", "ad_id", $_REQUEST['ad_id'], $user_id)." WHERE ad_id='".$ad_id."'"; } //echo "<hr><b>Insert:</b> $sql<hr>"; //print_r ($_FILES); mysql_query ($sql) or die("[$sql]".mysql_error()); //build_ad_count(0); return $ad_id; } ############################################################### function validate_ad_data($form_id) { return validate_form_data(1); return $error; } ################################################################ function update_blocks_with_ad($ad_id, $user_id) { global $prams; $prams = load_ad_values($ad_id); if ($prams['order_id']>0) { $sql = "UPDATE blocks SET alt_text='".addslashes(get_template_value('ALT_TEXT', 1))."', url='".addslashes(get_template_value('URL', 1))."' WHERE order_id='".$prams['order_id']."' AND user_id='".$user_id."' "; mysql_query($sql) or die(mysql_error()); mds_log("Updated blocks with ad URL, ALT_TEXT", $sql); } } ?>
LauraHilliger/hufemap
include/ads.inc.php
PHP
gpl-3.0
21,673
// binary_frame.go /* Binary Frame Tool. Version: 0.1.1. Date of Creation: 2018-01-28. Author: McArcher. This is a simple Tool which draws a binary Frame around the Content. A Frame consists of logical Ones (1) and has a Spacer of Zeroes (0). So, --- XXX XXX --- Becomes something with a binary Frame with a Spacer: ------- 1111111 1000001 10XXX01 10XXX01 1000001 1111111 ------- This Technique is a great Thing to enclose Dimensions of the "X" into the File. It may be useful for Transmission of Signals in Space or other Places with a great Chances for Signal Corruption. Even when damaged, a Frame or Remains of a Frame may help a lot in the Process of Data Recovery. This Frame may be used as a Transport Package when there is no Package of the Transmission Protocol, and may be used in a universal Range. To comply with this-day Computers, the Algorithm makes Sizes compatible with 8-Bit Bytes, but it is also able to use any Size you want. */ //============================================================================== package main import ( "flag" "fmt" "io/ioutil" "log" "math" "os" "strconv" ) //============================================================================== type bit bool type row_of_bits []bit type field_of_bits []row_of_bits //============================================================================== const bits_in_byte = 8 const FILLED = true const EMPTY = false const ACTION_NONE = 0 const ACTION_ENCODE_F1 = 1 const ACTION_ENCODE_F2 = 2 const ACTION_DECODE_F1 = 3 const ACTION_DECODE_F2 = 4 const ERROR_1 = 1 //============================================================================== var cla_file_in *string var cla_file_out *string var cla_action_type *string var cla_x *string var cla_y *string var action_type uint8 var file_input_path string var file_output_path string var file_input_content []byte var file_output_content []byte var file_input_x uint64 var file_input_y uint64 var file_input_size uint64 // Number of Bytes. var input_field_size uint64 // Number of Bits. var output_field_size uint64 // Number of Bits. var file_input_cols uint64 var file_input_rows uint64 var file_output_cols uint64 var file_output_rows uint64 var field field_of_bits var field_framed field_of_bits //============================================================================== func main() { var err error var err_code uint8 var ok bool // Command Line Arguments. read_cla() // Read Input File. file_input_content, err = ioutil.ReadFile(file_input_path) check_error(err) file_input_size = uint64(len(file_input_content)) input_field_size = file_input_size * bits_in_byte // Check X & Y. if file_input_x <= 0 { fmt.Println("Bad X Size.") os.Exit(ERROR_1) } file_input_cols = file_input_x if (input_field_size % file_input_x) != 0 { fmt.Println("Bad X Size.") os.Exit(ERROR_1) } file_input_rows = input_field_size / file_input_x // Do Action. if action_type == ACTION_ENCODE_F1 { fmt.Println("Encoding (F1) \"" + file_input_path + "\"...") // // Output Size. file_output_cols = file_input_cols + 4 file_output_rows = file_input_rows + 4 output_field_size = file_output_cols * file_output_rows // Report. fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows, ".") /// fmt.Println("Output Data (WxH):", file_output_cols, "x", file_output_rows, ".") /// // Bytes -> Field. field, ok = bytes_to_field(input_field_size, file_input_cols, file_input_rows, file_input_content) check_ok(ok) // Field -> Frame. field_framed, err_code = pack_data_f1(input_field_size, file_input_cols, file_input_rows, field) check_err_code(err_code) // Frame -> Bytes. file_output_content, ok = field_to_bytes(output_field_size, file_output_cols, file_output_rows, field_framed) check_ok(ok) // Bytes -> File. fmt.Println("Writing \"" + file_output_path + "\"...") // err = ioutil.WriteFile(file_output_path, file_output_content, 0644) check_error(err) } if action_type == ACTION_ENCODE_F2 { fmt.Println("Encoding (F2) \"" + file_input_path + "\"...") // // Output Size. file_output_cols = file_input_cols + 8 file_output_rows = file_input_rows + 8 output_field_size = file_output_cols * file_output_rows // Report. fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows, ".") /// fmt.Println("Output Data (WxH):", file_output_cols, "x", file_output_rows, ".") /// // Bytes -> Field. field, ok = bytes_to_field(input_field_size, file_input_cols, file_input_rows, file_input_content) check_ok(ok) // Field -> Frame. field_framed, err_code = pack_data_f2(input_field_size, file_input_cols, file_input_rows, field) check_err_code(err_code) // Frame -> Bytes. file_output_content, ok = field_to_bytes(output_field_size, file_output_cols, file_output_rows, field_framed) check_ok(ok) // Bytes -> File. fmt.Println("Writing \"" + file_output_path + "\"...") // err = ioutil.WriteFile(file_output_path, file_output_content, 0644) check_error(err) } if action_type == ACTION_DECODE_F1 { fmt.Println("Decoding (F1) \"" + file_input_path + "\"...") // // Output Size. file_output_cols = file_input_cols - 4 file_output_rows = file_input_rows - 4 output_field_size = file_output_cols * file_output_rows // Report. fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows, ".") /// fmt.Println("Output Data (WxH):", file_output_cols, "x", file_output_rows, ".") /// // Bytes -> Frame. field_framed, ok = bytes_to_field(input_field_size, file_input_cols, file_input_rows, file_input_content) check_ok(ok) // Frame -> Field. field, ok = get_data_f1(input_field_size, file_input_cols, file_input_rows, field_framed) check_ok(ok) // Field -> Bytes. file_output_content, ok = field_to_bytes(output_field_size, file_output_cols, file_output_rows, field) check_ok(ok) // Bytes -> File. fmt.Println("Writing \"" + file_output_path + "\"...") // err = ioutil.WriteFile(file_output_path, file_output_content, 0644) check_error(err) } if action_type == ACTION_DECODE_F2 { fmt.Println("Decoding (F2) \"" + file_input_path + "\"...") // // Output Size. file_output_cols = file_input_cols - 8 file_output_rows = file_input_rows - 8 output_field_size = file_output_cols * file_output_rows // Report. fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows, ".") /// fmt.Println("Output Data (WxH):", file_output_cols, "x", file_output_rows, ".") /// // Bytes -> Frame. field_framed, ok = bytes_to_field(input_field_size, file_input_cols, file_input_rows, file_input_content) check_ok(ok) // Frame -> Field. field, ok = get_data_f2(input_field_size, file_input_cols, file_input_rows, field_framed) check_ok(ok) // Field -> Bytes. file_output_content, ok = field_to_bytes(output_field_size, file_output_cols, file_output_rows, field) check_ok(ok) // Bytes -> File. fmt.Println("Writing \"" + file_output_path + "\"...") // err = ioutil.WriteFile(file_output_path, file_output_content, 0644) check_error(err) } if action_type == ACTION_NONE { fmt.Println("Idle...") // } } //============================================================================== // Packs useful Data into Message and surrounds it with a Frame I. func pack_data_f1( data_bits_count uint64, data_columns_count uint64, data_rows_count uint64, data field_of_bits) (field_of_bits, uint8) { const DS = 4 const DO = DS / 2 const data_columns_count_limit = math.MaxUint64 - DS const data_rows_count_limit = math.MaxUint64 - DS const ERROR_ALL_CLEAR = 0 // No Error. const ERROR_BAD_SIZE = 1 // (Colums * Rows) ≠ (Bit Count). const ERROR_COLUMNS_ERROR = 2 // Too many Columns in Data. const ERROR_ROWS_ERROR = 3 // Too many Rows in Data. var data_bits_count_required uint64 var result field_of_bits // Cursors in Result. var i uint64 // Current Row #. var i_max uint64 // var i_min uint64 // var j uint64 // Current Column #. var j_max uint64 // var j_min uint64 // // Cursors in Data. var y uint64 // Current Row #. var x uint64 // Current Column #. var result_columns_count uint64 var result_rows_count uint64 var data_first_column_index uint64 var data_first_row_index uint64 //var data_last_column_index uint64 //var data_last_row_index uint64 var result_first_column_index uint64 var result_first_row_index uint64 var result_last_column_index uint64 var result_last_row_index uint64 // Check Input Data. data_bits_count_required = data_columns_count * data_rows_count if data_bits_count != data_bits_count_required { return nil, ERROR_BAD_SIZE } if data_columns_count > data_columns_count_limit { return nil, ERROR_COLUMNS_ERROR } if data_rows_count > data_rows_count_limit { return nil, ERROR_ROWS_ERROR } // Indices & Sizes. result_columns_count = data_columns_count + DS result_rows_count = data_rows_count + DS data_first_column_index = 0 data_first_row_index = 0 //data_last_column_index = data_columns_count - 1 //data_last_row_index = data_rows_count - 1 result_first_column_index = 0 result_first_row_index = 0 result_last_column_index = result_columns_count - 1 result_last_row_index = result_rows_count - 1 // Create an empty Field. result = make(field_of_bits, result_rows_count) for i = result_first_row_index; i <= result_last_row_index; i++ { result[i] = make(row_of_bits, result_columns_count) for j = result_first_column_index; j <= result_last_column_index; j++ { result[i][j] = EMPTY } } // Draw the Frame I. for j = result_first_column_index; j <= result_last_column_index; j++ { result[result_first_row_index][j] = FILLED result[result_last_row_index][j] = FILLED } for i = result_first_row_index; i <= result_last_row_index; i++ { result[i][result_first_column_index] = FILLED result[i][result_last_column_index] = FILLED } // Draw Frame's Spacer. i_min = result_first_row_index + 1 i_max = result_last_row_index - 1 j_min = result_first_column_index + 1 j_max = result_last_column_index - 1 for j = j_min; j <= j_max; j++ { result[i_min][j] = EMPTY result[i_max][j] = EMPTY } for i = i_min; i <= i_max; i++ { result[i][j_min] = EMPTY result[i][j_max] = EMPTY } // Draw Data. i_min = result_first_row_index + DO i_max = result_last_row_index - DO j_min = result_first_column_index + DO j_max = result_last_column_index - DO y = data_first_row_index for i = i_min; i <= i_max; i++ { x = data_first_column_index for j = j_min; j <= j_max; j++ { result[i][j] = data[y][x] x++ } y++ } return result, ERROR_ALL_CLEAR } //============================================================================== // Packs useful Data into Message and surrounds it with a Frame II. func pack_data_f2( data_bits_count uint64, data_columns_count uint64, data_rows_count uint64, data field_of_bits) (field_of_bits, uint8) { const DS = 8 const DO = DS / 2 const data_columns_count_limit = math.MaxUint64 - DS const data_rows_count_limit = math.MaxUint64 - DS const ERROR_ALL_CLEAR = 0 // No Error. const ERROR_BAD_SIZE = 1 // (Colums * Rows) ≠ (Bit Count). const ERROR_COLUMNS_ERROR = 2 // Too many Columns in Data. const ERROR_ROWS_ERROR = 3 // Too many Rows in Data. var data_bits_count_required uint64 var result field_of_bits // Cursors in Result. var i uint64 // Current Row #. var i_max uint64 // var i_min uint64 // var j uint64 // Current Column #. var j_max uint64 // var j_min uint64 // // Cursors in Data. var y uint64 // Current Row #. var x uint64 // Current Column #. var result_columns_count uint64 var result_rows_count uint64 var data_first_column_index uint64 var data_first_row_index uint64 //var data_last_column_index uint64 //var data_last_row_index uint64 var result_first_column_index uint64 var result_first_row_index uint64 var result_last_column_index uint64 var result_last_row_index uint64 // Check Input Data. data_bits_count_required = data_columns_count * data_rows_count if data_bits_count != data_bits_count_required { return nil, ERROR_BAD_SIZE } if data_columns_count > data_columns_count_limit { return nil, ERROR_COLUMNS_ERROR } if data_rows_count > data_rows_count_limit { return nil, ERROR_ROWS_ERROR } // Indices & Sizes. result_columns_count = data_columns_count + DS result_rows_count = data_rows_count + DS data_first_column_index = 0 data_first_row_index = 0 //data_last_column_index = data_columns_count - 1 //data_last_row_index = data_rows_count - 1 result_first_column_index = 0 result_first_row_index = 0 result_last_column_index = result_columns_count - 1 result_last_row_index = result_rows_count - 1 // Create an empty Field. result = make(field_of_bits, result_rows_count) for i = result_first_row_index; i <= result_last_row_index; i++ { result[i] = make(row_of_bits, result_columns_count) for j = result_first_column_index; j <= result_last_column_index; j++ { result[i][j] = EMPTY } } // Draw the Frame I. for j = result_first_column_index; j <= result_last_column_index; j++ { result[result_first_row_index][j] = FILLED result[result_last_row_index][j] = FILLED } for i = result_first_row_index; i <= result_last_row_index; i++ { result[i][result_first_column_index] = FILLED result[i][result_last_column_index] = FILLED } // Draw Frame's Spacer. i_min = result_first_row_index + 1 i_max = result_last_row_index - 1 j_min = result_first_column_index + 1 j_max = result_last_column_index - 1 for j = j_min; j <= j_max; j++ { result[i_min][j] = EMPTY result[i_max][j] = EMPTY } for i = i_min; i <= i_max; i++ { result[i][j_min] = EMPTY result[i][j_max] = EMPTY } // Draw the Frame II. i_min = result_first_row_index + 2 i_max = result_last_row_index - 2 j_min = result_first_column_index + 2 j_max = result_last_column_index - 2 for j = j_min; j <= j_max; j++ { result[i_min][j] = FILLED result[i_max][j] = FILLED } for i = i_min; i <= i_max; i++ { result[i][j_min] = FILLED result[i][j_max] = FILLED } // Draw Frame's Spacer. i_min = result_first_row_index + 3 i_max = result_last_row_index - 3 j_min = result_first_column_index + 3 j_max = result_last_column_index - 3 for j = j_min; j <= j_max; j++ { result[i_min][j] = EMPTY result[i_max][j] = EMPTY } for i = i_min; i <= i_max; i++ { result[i][j_min] = EMPTY result[i][j_max] = EMPTY } // Draw Data. i_min = result_first_row_index + DO i_max = result_last_row_index - DO j_min = result_first_column_index + DO j_max = result_last_column_index - DO y = data_first_row_index for i = i_min; i <= i_max; i++ { x = data_first_column_index for j = j_min; j <= j_max; j++ { result[i][j] = data[y][x] x++ } y++ } return result, ERROR_ALL_CLEAR } //============================================================================== // Checks Integrity of a Frame I of the Message. func check_frame_f1( message_bits_count uint64, message_columns_count uint64, message_rows_count uint64, message field_of_bits) bool { const message_columns_count_limit = math.MaxUint64 const message_rows_count_limit = math.MaxUint64 const message_rows_count_min = 4 + 1 // Rows in empty Message. const message_columns_count_min = 4 + 1 // Columns in empty Message. const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var data_bits_count_required uint64 // Cursors in Message. var i uint64 // Current Row #. var i_max uint64 // var i_min uint64 // var j uint64 // Current Column #. var j_max uint64 // var j_min uint64 // // Check Input Data. data_bits_count_required = message_columns_count * message_rows_count if message_bits_count != data_bits_count_required { return ERROR } if message_columns_count > message_columns_count_limit { return ERROR } if message_rows_count > message_rows_count_limit { return ERROR } // Check Minimum Sizes. if message_rows_count < message_rows_count_min { return ERROR } if message_columns_count < message_columns_count_min { return ERROR } // Check Dimensions of Array. if uint64(len(message)) != message_rows_count { return ERROR } i_min = 0 i_max = message_rows_count - 1 for i = i_min; i <= i_max; i++ { if uint64(len(message[i])) != message_columns_count { return ERROR } } // Check Frame I. j_min = 0 j_max = message_columns_count - 1 for j = j_min; j <= j_max; j++ { if message[i_min][j] != FILLED { return ERROR } if message[i_max][j] != FILLED { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != FILLED { return ERROR } if message[i][j_max] != FILLED { return ERROR } } // Check Frame's Spacer. i_min = 1 i_max = message_rows_count - 2 j_min = 1 j_max = message_columns_count - 2 for j = j_min; j <= j_max; j++ { if message[i_min][j] != EMPTY { return ERROR } if message[i_max][j] != EMPTY { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != EMPTY { return ERROR } if message[i][j_max] != EMPTY { return ERROR } } return ERROR_ALL_CLEAR } //============================================================================== // Checks Integrity of a Frame II of the Message. func check_frame_f2( message_bits_count uint64, message_columns_count uint64, message_rows_count uint64, message field_of_bits) bool { const message_columns_count_limit = math.MaxUint64 const message_rows_count_limit = math.MaxUint64 const message_rows_count_min = 8 + 1 // Rows in empty Message. const message_columns_count_min = 8 + 1 // Columns in empty Message. const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var data_bits_count_required uint64 // Cursors in Message. var i uint64 // Current Row #. var i_max uint64 // var i_min uint64 // var j uint64 // Current Column #. var j_max uint64 // var j_min uint64 // // Check Input Data. data_bits_count_required = message_columns_count * message_rows_count if message_bits_count != data_bits_count_required { return ERROR } if message_columns_count > message_columns_count_limit { return ERROR } if message_rows_count > message_rows_count_limit { return ERROR } // Check Minimum Sizes. if message_rows_count < message_rows_count_min { return ERROR } if message_columns_count < message_columns_count_min { return ERROR } // Check Dimensions of Array. if uint64(len(message)) != message_rows_count { return ERROR } i_min = 0 i_max = message_rows_count - 1 for i = i_min; i <= i_max; i++ { if uint64(len(message[i])) != message_columns_count { return ERROR } } // Check Frame I. j_min = 0 j_max = message_columns_count - 1 for j = j_min; j <= j_max; j++ { if message[i_min][j] != FILLED { return ERROR } if message[i_max][j] != FILLED { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != FILLED { return ERROR } if message[i][j_max] != FILLED { return ERROR } } // Check Frame's Spacer. i_min = 1 i_max = message_rows_count - 2 j_min = 1 j_max = message_columns_count - 2 for j = j_min; j <= j_max; j++ { if message[i_min][j] != EMPTY { return ERROR } if message[i_max][j] != EMPTY { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != EMPTY { return ERROR } if message[i][j_max] != EMPTY { return ERROR } } // Check Frame II. i_min = 2 i_max = message_rows_count - 3 j_min = 2 j_max = message_columns_count - 3 for j = j_min; j <= j_max; j++ { if message[i_min][j] != FILLED { return ERROR } if message[i_max][j] != FILLED { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != FILLED { return ERROR } if message[i][j_max] != FILLED { return ERROR } } // Check Frame's Spacer. i_min = 3 i_max = message_rows_count - 4 j_min = 3 j_max = message_columns_count - 4 for j = j_min; j <= j_max; j++ { if message[i_min][j] != EMPTY { return ERROR } if message[i_max][j] != EMPTY { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != EMPTY { return ERROR } if message[i][j_max] != EMPTY { return ERROR } } return ERROR_ALL_CLEAR } //============================================================================== // Gets Data from Message with Frame I. func get_data_f1( message_bits_count uint64, message_columns_count uint64, message_rows_count uint64, message field_of_bits) (field_of_bits, bool) { const DS = 4 const DO = DS / 2 const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var data field_of_bits var data_rows_count uint64 var data_columns_count uint64 var cf bool // Result of Frame Check. // Cursors in Message. var i uint64 // Current Row #. var i_min uint64 // var j uint64 // Current Column #. var j_min uint64 // // Cursors in Data. var y uint64 // Current Row #. var x uint64 // Current Column #. // Check Frame. cf = check_frame_f1(message_bits_count, message_columns_count, message_rows_count, message) if cf == ERROR { return nil, ERROR } // Prepare Data. data_rows_count = message_rows_count - DS data_columns_count = message_columns_count - DS // data = make(field_of_bits, data_rows_count) for y = 0; y < data_rows_count; y++ { data[y] = make(row_of_bits, data_columns_count) for x = 0; x < data_columns_count; x++ { data[y][x] = EMPTY } } // Get Data. i_min = DO j_min = DO i = i_min for y = 0; y < data_rows_count; y++ { j = j_min for x = 0; x < data_columns_count; x++ { data[y][x] = message[i][j] j++ } i++ } return data, ERROR_ALL_CLEAR } //============================================================================== // Gets Data from Message with Frame II. func get_data_f2( message_bits_count uint64, message_columns_count uint64, message_rows_count uint64, message field_of_bits) (field_of_bits, bool) { const DS = 8 const DO = DS / 2 const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var data field_of_bits var data_rows_count uint64 var data_columns_count uint64 var cf bool // Result of Frame Check. // Cursors in Message. var i uint64 // Current Row #. var i_min uint64 // var j uint64 // Current Column #. var j_min uint64 // // Cursors in Data. var y uint64 // Current Row #. var x uint64 // Current Column #. // Check Frame. cf = check_frame_f2(message_bits_count, message_columns_count, message_rows_count, message) if cf == ERROR { return nil, ERROR } // Prepare Data. data_rows_count = message_rows_count - DS data_columns_count = message_columns_count - DS // data = make(field_of_bits, data_rows_count) for y = 0; y < data_rows_count; y++ { data[y] = make(row_of_bits, data_columns_count) for x = 0; x < data_columns_count; x++ { data[y][x] = EMPTY } } // Get Data. i_min = DO j_min = DO i = i_min for y = 0; y < data_rows_count; y++ { j = j_min for x = 0; x < data_columns_count; x++ { data[y][x] = message[i][j] j++ } i++ } return data, ERROR_ALL_CLEAR } //============================================================================== // Converts Field into Array of Bytes. func field_to_bytes( field_bits_count uint64, field_columns_count uint64, field_rows_count uint64, field field_of_bits) ([]byte, bool) { const field_columns_count_limit = math.MaxUint64 const field_rows_count_limit = math.MaxUint64 const ERROR_ALL_CLEAR = true // No Error. const ERROR = false const MSG_1 = "Warning ! The Size of the Output Data can not be stored " + "using 8-Bit Bytes ! The Size is not a Multiple of 8 !" var i uint64 var j uint64 // Cursors in Field. var y uint64 var x uint64 var array []byte var current_bit bit var current_byte byte var bytes_count uint64 var field_bits_count_required uint64 var field_column_first uint64 var field_column_last uint64 field_column_first = 0 field_column_last = field_columns_count - 1 // Check Input Data. field_bits_count_required = field_columns_count * field_rows_count if field_bits_count != field_bits_count_required { log.Println("1") return nil, ERROR } if field_columns_count > field_columns_count_limit { log.Println("2") return nil, ERROR } if field_rows_count > field_rows_count_limit { log.Println("3") return nil, ERROR } // Can be converted to Bytes ? if (field_bits_count % bits_in_byte) != 0 { fmt.Println(MSG_1) return nil, ERROR } bytes_count = field_bits_count / bits_in_byte array = make([]byte, bytes_count) x = 0 y = 0 for i = 0; i < bytes_count; i++ { current_byte = 0 // Read 8 Bits. for j = 0; j < bits_in_byte; j++ { current_bit = field[y][x] // Save Bit in Byte. if current_bit == FILLED { current_byte = current_byte | (128 >> j) } // Next Element in Field. if x == field_column_last { y++ x = field_column_first } else { x++ } } // Save to Array. array[i] = current_byte } return array, ERROR_ALL_CLEAR } //============================================================================== // Converts Array of Bytes into Field. func bytes_to_field( field_bits_count uint64, field_columns_count uint64, field_rows_count uint64, array []byte) (field_of_bits, bool) { const field_columns_count_limit = math.MaxUint64 const field_rows_count_limit = math.MaxUint64 const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var i uint64 var j uint64 // Cursors in Field. var y uint64 var x uint64 var field field_of_bits var current_bit bit var current_byte byte var current_byte_tmp byte var bytes_count uint64 var field_bits_count_required uint64 var field_column_first uint64 var field_column_last uint64 field_column_first = 0 field_column_last = field_columns_count - 1 // Check Input Data. field_bits_count_required = field_columns_count * field_rows_count if field_bits_count != field_bits_count_required { return nil, ERROR } if field_columns_count > field_columns_count_limit { return nil, ERROR } if field_rows_count > field_rows_count_limit { return nil, ERROR } // Can be converted to Bytes ? if (field_bits_count % bits_in_byte) != 0 { return nil, ERROR } bytes_count = uint64(len(array)) if bytes_count*bits_in_byte != field_bits_count { return nil, ERROR } // Create an empty Field. field = make(field_of_bits, field_rows_count) for y = 0; y < field_rows_count; y++ { field[y] = make(row_of_bits, field_columns_count) for x = 0; x < field_columns_count; x++ { field[y][x] = EMPTY } } x = 0 y = 0 for i = 0; i < bytes_count; i++ { current_byte = array[i] // Read 8 Bits. for j = 0; j < bits_in_byte; j++ { current_byte_tmp = (current_byte >> (7 - j)) & 1 if current_byte_tmp == 1 { current_bit = FILLED } else { current_bit = EMPTY } // Save Bit in Field. field[y][x] = current_bit // Next Element in Field. if x == field_column_last { y++ x = field_column_first } else { x++ } } } return field, ERROR_ALL_CLEAR } //============================================================================== // Read Command Line Arguments (Keys, Flags, Switches). func read_cla() { var err error // Set Rules. cla_file_in = flag.String("fi", "input", "File Input.") cla_file_out = flag.String("fo", "output", "File Output.") cla_action_type = flag.String("a", "", "Action Type.") cla_x = flag.String("x", "0", "Columns.") cla_y = flag.String("y", "0", "Rows.") // Read C.L.A. flag.Parse() // Files. file_input_path = *cla_file_in file_output_path = *cla_file_out // Action Type. if *cla_action_type == "e1" { action_type = ACTION_ENCODE_F1 } else if *cla_action_type == "e2" { action_type = ACTION_ENCODE_F2 } else if *cla_action_type == "d1" { action_type = ACTION_DECODE_F1 } else if *cla_action_type == "d2" { action_type = ACTION_DECODE_F2 } else { action_type = ACTION_NONE } // X, Y. file_input_x, err = strconv.ParseUint(*cla_x, 10, 64) check_error(err) file_input_y, err = strconv.ParseUint(*cla_y, 10, 64) check_error(err) } //============================================================================== func check_error(err error) { if err != nil { log.Println(err) os.Exit(ERROR_1) } } //============================================================================== func check_ok(ok bool) { if !ok { log.Println("Error.") os.Exit(ERROR_1) } else { //fmt.Println("OK.") } } //============================================================================== func check_err_code(err_code uint8) { if err_code == 0 { //fmt.Println("OK.") } else { log.Println("Error.") os.Exit(ERROR_1) } } //==============================================================================
legacy-vault/tests
go/binary_frame/2/binary_frame.go
GO
gpl-3.0
29,039
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 20 13:37:16 2017 Author: Peiyong Jiang : [email protected] Function: 旋转使得变换。 """ import matplotlib.pyplot as plt import tensorflow as tf import numpy as np plt.close('all') emitX=12 alphaX=-10. betaX=13. gammaX=(1.+alphaX**2)/betaX sigmaX=np.array([[betaX,-alphaX],[-alphaX,gammaX]])*emitX; numPart=np.int32(1e5); X=np.random.multivariate_normal([0.,0.],sigmaX,numPart).T plt.figure(1) plt.plot(X[0,:],X[1,:],'.') ## w=tf.Variable(tf.random_normal([1,1])) w1=tf.cos(w) w2=tf.sin(w) P_Row_1=tf.concat([w1,-w2],0) P_Row_2=tf.concat([w2,w1],0) P=tf.concat([P_Row_1,P_Row_2],1) xI=tf.placeholder(tf.float32,[2,None]) xO=tf.matmul(P,xI) xxp=tf.reduce_mean(xO[0]*xO[1]) lossAlpha=xxp**2 rateLearn=1e-4 optTotal=tf.train.AdamOptimizer(rateLearn) trainAlpha=optTotal.minimize(lossAlpha) sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=True)) sess.run(tf.global_variables_initializer()) sizeBatch=64 for _ in xrange(8000): startBatch=np.random.randint(0,high=numPart-sizeBatch-1) xFeed=X[:,startBatch:startBatch+sizeBatch:] sess.run(trainAlpha,feed_dict={xI:xFeed}) #print(sess.run(LambdaR)) #print('---------------------------') print(sess.run(lossAlpha,feed_dict={xI:X}),_) print('_______________________________________________') zReal=sess.run(xO,feed_dict={xI:X}) plt.figure(2) plt.plot(zReal[0,:],zReal[1,:],'r.') plt.axis('equal') plt.figure(10) plt.hold plt.plot(zReal[0,:],zReal[1,:],'r.') plt.plot(X[0,:],X[1,:],'b.') #plt.plot(zReal[0,:],zReal[1,:],'r.') plt.axis('equal') plt.figure(11) plt.hold #plt.plot(zReal[0,:],zReal[1,:],'r.') plt.plot(X[0,:],X[1,:],'b.') plt.plot(zReal[0,:],zReal[1,:],'r.') plt.axis('equal') zRealCov=np.cov(zReal) emitXReal=np.sqrt(np.linalg.det(zRealCov)) print(emitXReal)
iABC2XYZ/abc
DM_Twiss/TwissTrain9.py
Python
gpl-3.0
1,927
<?php theme()->render("2column-right", [ ["Header", "top"], ["Post", "content"], ["Comments", "content"], ["SidebarRight", "right"], ["Footer", "bottom"] ]);
erikkubica/netlime-starter-theme-v2
single.php
PHP
gpl-3.0
177
/* This file is part of Arkhados. Arkhados 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. Arkhados 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 Arkhados. If not, see <http://www.gnu.org/licenses/>. */ package arkhados.spell.buffs.info; import arkhados.controls.CRotation; import arkhados.controls.CTrackLocation; import arkhados.effects.BuffEffect; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; public class MineralArmorInfo extends BuffInfo { { setIconPath("Interface/Images/SpellIcons/MineralArmor.png"); } @Override public BuffEffect createBuffEffect(BuffInfoParameters params) { MineralArmorEffect effect = new MineralArmorEffect(params.duration); effect.addToCharacter(params); return effect; } } class MineralArmorEffect extends BuffEffect { private Node centralNode = null; public MineralArmorEffect(float timeLeft) { super(timeLeft); } public void addToCharacter(BuffInfoParameters params) { Node character = (Node) params.buffControl.getSpatial(); Spatial crystals1 = assets.loadModel("Models/crystals.j3o"); Spatial crystals2 = assets.loadModel("Models/crystals.j3o"); Spatial crystals3 = assets.loadModel("Models/crystals.j3o"); Spatial crystals4 = assets.loadModel("Models/crystals.j3o"); centralNode = new Node("mineral-armor-node"); centralNode.attachChild(crystals1); centralNode.attachChild(crystals2); centralNode.attachChild(crystals3); centralNode.attachChild(crystals4); crystals1.setLocalTranslation(-7.5f, 0f, 0f); crystals2.setLocalTranslation(7.5f, 0f, 0f); crystals3.setLocalTranslation(0f, 0f, -7.5f); crystals4.setLocalTranslation(0f, 0f, 7.5f); Node world = character.getParent(); world.attachChild(centralNode); centralNode.addControl( new CTrackLocation(character, new Vector3f(0f, 10f, 0f))); centralNode.addControl(new CRotation(0f, 2f, 0f)); } @Override public void destroy() { super.destroy(); centralNode.removeFromParent(); } }
TripleSnail/Arkhados
src/arkhados/spell/buffs/info/MineralArmorInfo.java
Java
gpl-3.0
2,655
jQuery(document).ready(function(){ if( $('.cd-stretchy-nav').length > 0 ) { var stretchyNavs = $('.cd-stretchy-nav'); stretchyNavs.each(function(){ var stretchyNav = $(this), stretchyNavTrigger = stretchyNav.find('.cd-nav-trigger'); stretchyNavTrigger.on('click', function(event){ event.preventDefault(); stretchyNav.toggleClass('nav-is-visible'); }); }); $(document).on('click', function(event){ ( !$(event.target).is('.cd-nav-trigger') && !$(event.target).is('.cd-nav-trigger span') ) && stretchyNavs.removeClass('nav-is-visible'); }); }; ///toggle en contenido $(".toggle-view li").on('click', function(e){ e.currentTarget.classList.toggle("active"); }); });
GobiernoFacil/agentes-v2
public/js/main.js
JavaScript
gpl-3.0
716
use strict; use warnings; package RPG::ResultSet::Election; use base 'DBIx::Class::ResultSet'; use Carp; sub schedule { my $self = shift; my $town = shift || croak "Town not supplied"; my $days = shift || croak "Number of days not supplied"; croak "Already have an election scheduled\n" if $town->current_election; my $mayor = $town->mayor; croak "No mayor in this town" unless $mayor; croak "Invalid day\n" if $days < 3; my $schema = $self->result_source->schema; my $today = $schema->resultset('Day')->find_today; my $day = $today->day_number + $days; my $election = $self->create( { town_id => $town->id, scheduled_day => $day, status => 'Open', } ); $schema->resultset('Election_Candidate')->create( { character_id => $mayor->id, election_id => $election->id, }, ); $schema->resultset('Town_History')->create( { town_id => $town->id, day_id => $today->id, message => $mayor->name . " has called an election for day $day. " . ucfirst $mayor->pronoun('subjective') . " invites prospective candidates to register to run.", } ); $schema->resultset('Global_News')->create( { day_id => $today->id, message => "The town of " . $town->town_name . " has scheduled an election for day $day.", }, ); return $election; } 1;
Mutant/CrownOfConquest
lib/RPG/ResultSet/Election.pm
Perl
gpl-3.0
1,522
![GeneralAssemb.ly](../../img/icons/FEWD_Logo.png) #FEWD - Review, Process, and Debugging ###Lesson 11 - Mar 14, 2016 "What was the hardest part of learning to code? It’s learning to not let errors and complicated functions get you down. Everyone makes mistakes and it’s the process of debugging them that teaches you how to be a better coder." - <a href="http://imagirlwhocodes.com/post/140868820390/amanda-xu-a-swerve-in-another-direction">Amanda Xu</a> --- ##Agenda * Surveys, please! * Exit Ticket Review * Debugging * Assignment 5 review: from pseudocode to implementation --- ##Exit Tickets * What is a good way to memorize the most used functions in Jquery/javascript? Answer: Once you encounter a jQuery function, you'll find that many of them are named pretty transparently after what they do (`.html` and `.css` for example). But as you're starting out, you may still need to look up the documentation or StackOverflow to jog your memory -- that's ok! * How in the hell do I get good at this? Answer: Persistence, practice, and patience with yourself! --- ## Resources for practicing * <a href="http://tympanus.net/codrops/">Codrops tutorials and playground</a> * <a href="https://www.smashingmagazine.com/2008/09/jquery-examples-and-best-practices/">Continue to learn about best practices</a> * <a href="https://www.codecademy.com/learn/jquery">Code Academy jQuery course</a> * <a href="http://jqexercise.droppages.com/">jQuery drills</a> - these range in difficulty and don't offer much to help you learn, but it's great for practicing! --- ##Debugging <img src="http://www.wired.com/images_blogs/wiredscience/2013/12/moth-660x548.jpg" style="height: 80%"> The very first "bug", <a href="http://www.wired.com/2013/12/googles-doodle-honors-grace-hopper-and-entomology/">discovered by Grace Hopper</a>. --- ##Debugging tips * The console is your friend: * The first thing you should always do if your code starts doing things contrary to your expectations is open up your console. A lot of times console will just tell you what went wrong! * Use `console.log` whenever you need to check if something is working: write out variable values to check that they are updating correctly, log out messages to verify your event handlers are firing correctly, etc. [You can even log out jQuery elements!] * When a part of your code doesn't work, take a step back and ask yourself these questions: * What did I expect to happen? * What happened instead? * Where in the place in my code where this functionality is being implemented? * Instead of attempting to throw more code at an already buggy codebase, simplify. --- ##Debug-a-long * Fixing errors with the <a href="starter/debugging-relaxr">Relaxr blog exercise</a>. * Fixing errors with the <a href="starter/debugging-compare-that">Compare That exercise</a>. --- ## Assignment 5 : pseudocode to implementation Pseudocoding the CitiPix app: * Need to set up a click listener + handler for the submit button. * When the submit button is clicked, need to get the input value. * Verify (using `console.log`) that you are getting the value before you continue to the next parts. * Once you have the input value, our program needs to **DECIDE** if we should add a class to the body based on what was typed. *Because each of these should work approximately the same way, if we figure out one case, we can carry over the technique to the other cases.* * If the user typed "New York" or "New York City" or "NYC", we should see the nyc.jpg background * If the user typed "San Francisco" or "SF" or "Bay Area", we should see the sf background * If the user typed "Los Angeles" or "LA" or "LAX", we should see the la.jpg background * If the user typed "Austin" or "ATX", we should see the austin.jpg background * If the user typed "Sydney" or "SYD", we should see the sydney.jpg background --- ## More Practice: Number Guesser We will build a number guesser game where the computer generates a random number from 1-10, and the user enters numbers into the input field until the number they enter is a match. When the user's guess is incorrect, the program will tell user if they need to guess higher or lower. <a href="http://codepen.io/emmacunningham/pen/pyNJJy?editors=1010">Starter code</a> * Write pseudocode for the logic flow of your program * Convert the pseudocode to real JavaScript code, working on things piece-by-piece --- ##Homework * Work on the HTML + CSS for your Final Project * Surveys if you haven't yet filled yours out --- ##Exit Tickets - Lesson #11, Topic: Review & Debugging ###Please fill out the <a href="https://docs.google.com/forms/d/1Iw2zghHfGgeM1p1G16F6kLi7KViv28tG3HVNnoM3PAc/viewform">exit ticket</a> before you leave
emmacunningham/ga_sample_lesson
fewd_slides/Week_06_Review_Refactor/11_review_debugging/slides.md
Markdown
gpl-3.0
4,773
#include "precomp.h" #include "stdinc.h" #include "io_sfen.h" #include "commandpacket.h" namespace godwhale { const CommandPacket::CharSeparator CommandPacket::ms_separator(" ", ""); CommandPacket::CommandPacket(CommandType type) : m_type(type), m_positionId(-1), m_position(false) { } CommandPacket::CommandPacket(CommandPacket const & other) : m_positionId(-1), m_position(false) { } CommandPacket::CommandPacket(CommandPacket && other) : m_positionId(-1), m_position(false) { } /** * @brief ƒRƒ}ƒ“ƒh‚ÌŽÀs—Dæ‡ˆÊ‚ðŽæ“¾‚µ‚Ü‚·B * * ’l‚ª‘å‚«‚¢•û‚ªA—Dæ‡ˆÊ‚͍‚‚¢‚Å‚·B */ int CommandPacket::getPriority() const { switch (m_type) { // I—¹Œn‚̃Rƒ}ƒ“ƒh‚Í‚·‚®‚ÉŽÀs case COMMAND_QUIT: case COMMAND_STOP: return 100; // ’ʏí‚̃Rƒ}ƒ“ƒh‚Í‚»‚̂܂܂̏‡‚Å case COMMAND_LOGIN: case COMMAND_SETPOSITION: case COMMAND_MAKEROOTMOVE: case COMMAND_SETPV: case COMMAND_SETMOVELIST: case COMMAND_VERIFY: return 50; // ƒGƒ‰[‚Ý‚½‚¢‚È‚à‚Ì case COMMAND_NONE: return 0; } unreachable(); return -1; } /** * @brief str‚ªtarget‚ªŽ¦‚·ƒg[ƒNƒ“‚Å‚ ‚é‚©’²‚ׂ܂·B */ bool CommandPacket::isToken(std::string const & str, std::string const & target) { return (str.compare(target) == 0); } /** * @brief RSI(remote shogi interface)‚ðƒp[ƒX‚µAƒRƒ}ƒ“ƒh‚É’¼‚µ‚Ü‚·B */ shared_ptr<CommandPacket> CommandPacket::parse(std::string const & rsi) { if (rsi.empty()) { throw new std::invalid_argument("rsi"); } Tokenizer tokens(rsi, ms_separator); std::string token = *tokens.begin(); if (isToken(token, "login")) { return parse_Login(rsi, tokens); } else if (isToken(token, "setposition")) { return parse_SetPosition(rsi, tokens); } else if (isToken(token, "makerootmove")) { return parse_MakeRootMove(rsi, tokens); } else if (isToken(token, "setmovelist")) { return parse_SetMoveList(rsi, tokens); } else if (isToken(token, "stop")) { return parse_Stop(rsi, tokens); } else if (isToken(token, "quit")) { return parse_Quit(rsi, tokens); } return shared_ptr<CommandPacket>(); } /** * @brief ƒRƒ}ƒ“ƒh‚ðRSI(remote shogi interface)‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI() const { assert(m_type != COMMAND_NONE); switch (m_type) { case COMMAND_LOGIN: return toRSI_Login(); case COMMAND_SETPOSITION: return toRSI_SetPosition(); case COMMAND_MAKEROOTMOVE: return toRSI_MakeRootMove(); case COMMAND_SETMOVELIST: return toRSI_SetMoveList(); case COMMAND_STOP: return toRSI_Stop(); case COMMAND_QUIT: return toRSI_Quit(); } unreachable(); return std::string(); } #pragma region Login /** * @brief loginƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B * * login <address> <port> <login_id> <nthreads> */ shared_ptr<CommandPacket> CommandPacket::parse_Login(std::string const & rsi, Tokenizer & tokens) { shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_LOGIN)); Tokenizer::iterator begin = ++tokens.begin(); result->m_serverAddress = *begin++; result->m_serverPort = *begin++; result->m_loginId = *begin++; return result; } /** * @brief loginƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_Login() const { return (F("login %1% %2% %3%") % m_serverAddress % m_serverPort % m_loginId) .str(); } #pragma endregion #pragma region SetPosition /** * @brief setpositionƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B * * setposition <position_id> [sfen <sfen> | startpos] moves <move1> ... <moven> * <sfen> = <board_sfen> <turn_sfen> <hand_sfen> <nmoves> */ shared_ptr<CommandPacket> CommandPacket::parse_SetPosition(std::string const & rsi, Tokenizer & tokens) { shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_SETPOSITION)); Tokenizer::iterator begin = ++tokens.begin(); result->m_positionId = lexical_cast<int>(*begin++); std::string token = *begin++; if (token == "sfen") { std::string sfen; sfen += *begin++ + " "; // board sfen += *begin++ + " "; // turn sfen += *begin++ + " "; // hand sfen += *begin++; // nmoves result->m_position = sfenToPosition(sfen); } else if (token == "startpos") { result->m_position = Position(); } // moves‚͂Ȃ¢‚±‚Æ‚ª‚ ‚è‚Ü‚·B if (begin == tokens.end()) { return result; } if (*begin++ != "moves") { throw new ParseException(F("%1%: Žw‚µŽè‚ª³‚µ‚­‚ ‚è‚Ü‚¹‚ñB") % rsi); } for (; begin != tokens.end(); ++begin) { Move move = sfenToMove(result->m_position, *begin); if (!result->m_position.makeMove(move)) { LOG_ERROR() << result->m_position; LOG_ERROR() << *begin << ": Žw‚µŽè‚ª³‚µ‚­‚ ‚è‚Ü‚¹‚ñB"; throw new ParseException(F("%1%: Žw‚µŽè‚ª³‚µ‚­‚ ‚è‚Ü‚¹‚ñB") % *begin); } } return result; } /** * @brief setpositionƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_SetPosition() const { Position position = m_position; std::vector<Move> moves = position.getMoveList(); // ‹Ç–Ê‚ð‚·‚×‚Ä–ß‚µ‚Ü‚·B while (!position.getMoveList().empty()) { position.unmakeMove(); } std::string posStr; if (position.isInitial()) { posStr = " startpos"; } else { posStr = " sfen "; posStr += positionToSfen(position); } std::string movesStr; if (!moves.empty()) { movesStr += " moves"; BOOST_FOREACH(Move move, moves) { movesStr += " "; movesStr += moveToSfen(move); } } return (F("setposition %1%%2%%3%") % m_positionId % posStr % movesStr) .str(); } #pragma endregion #pragma region MakeRootMove /** * @brief makerootmoveƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B * * makerootmove <position_id> <old_position_id> <move> */ shared_ptr<CommandPacket> CommandPacket::parse_MakeRootMove(std::string const & rsi, Tokenizer & tokens) { shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_MAKEROOTMOVE)); Tokenizer::iterator begin = ++tokens.begin(); // Å‰‚̃g[ƒNƒ“‚Í”ò‚΂µ‚Ü‚·B result->m_positionId = lexical_cast<int>(*begin++); result->m_oldPositionId = lexical_cast<int>(*begin++); // —^‚¦‚ç‚ꂽpositionId‚Ȃǂ©‚ç‹Ç–Ê‚ðŒŸõ‚µ‚Ü‚·B Position position; result->m_move = sfenToMove(position, *begin++); return result; } /** * @brief makerootmoveƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_MakeRootMove() const { return (F("makerootmove %1% %2% %3%") % m_positionId % m_oldPositionId % moveToSfen(m_move)) .str(); } #pragma endregion #pragma region SetMoveList /** * @brief setmovelistƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B * * setmovelist <position_id> <itd> <pld> <move1> ... <moven> */ shared_ptr<CommandPacket> CommandPacket::parse_SetMoveList(std::string const & rsi, Tokenizer & tokens) { shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_SETMOVELIST)); Tokenizer::iterator begin = ++tokens.begin(); // Å‰‚̃g[ƒNƒ“‚Í”ò‚΂µ‚Ü‚·B result->m_positionId = lexical_cast<int>(*begin++); result->m_iterationDepth = lexical_cast<int>(*begin++); result->m_plyDepth = lexical_cast<int>(*begin++); // —^‚¦‚ç‚ꂽpositionId‚Ȃǂ©‚ç‹Ç–Ê‚ðŒŸõ‚µ‚Ü‚·B Position position; Tokenizer::iterator end = tokens.end(); for (; begin != end; ++begin) { Move move = sfenToMove(position, *begin); if (move.isEmpty()) { throw ParseException(F("%1%: ³‚µ‚¢Žw‚µŽè‚ł͂ ‚è‚Ü‚¹‚ñB") % *begin); } result->m_moveList.push_back(move); } return result; } /** * @brief setmovelistƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_SetMoveList() const { std::string movesStr; BOOST_FOREACH(Move move, m_moveList) { movesStr += " "; movesStr += moveToSfen(move); } return (F("setmovelist %1% %2% %3% %4%") % m_positionId %m_iterationDepth % m_plyDepth % movesStr) .str(); } #pragma endregion #pragma region Stop /** * @brief stopƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B */ shared_ptr<CommandPacket> CommandPacket::parse_Stop(std::string const & rsi, Tokenizer & tokens) { return shared_ptr<CommandPacket>(new CommandPacket(COMMAND_STOP)); } /** * @brief stopƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_Stop() const { return "stop"; } #pragma endregion #pragma region Quit /** * @brief quitƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B */ shared_ptr<CommandPacket> CommandPacket::parse_Quit(std::string const & rsi, Tokenizer & tokens) { return shared_ptr<CommandPacket>(new CommandPacket(COMMAND_QUIT)); } /** * @brief quitƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_Quit() const { return "quit"; } #pragma endregion } // namespace godwhale
ebifrier/godwhale
src/commandpacket.cpp
C++
gpl-3.0
9,268
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using KSP; namespace panelfar { public static class PANELFARMeshSimplification { //Take the raw part geometry and simplify it so that further simplification of the entire vessel is faster public static PANELFARPartLocalMesh PreProcessLocalMesh(PANELFARPartLocalMesh mesh) { //Array of vertices; indexing must not change Vector3[] verts = new Vector3[mesh.vertexes.Length]; mesh.vertexes.CopyTo(verts, 0); //Array of triangles; each triangle points to an index in verts MeshIndexTriangle[] indexTris = new MeshIndexTriangle[mesh.triangles.Length]; mesh.triangles.CopyTo(indexTris, 0); //Array of a list of triangles that contain a given vertex; indexing is same as verts, each index in list points to an index in indexTris List<int>[] trisAttachedToVerts = GetTrisAttachedToVerts(verts, indexTris); //Array of quadrics associated with a particular vertex; indexing is same as verts Quadric[] vertQuadrics = CalculateVertQuadrics(verts, indexTris); //A list of possible vertex pairs that can be contracted into a single point MinHeap<MeshPairContraction> pairContractions = GeneratePairContractions(indexTris, verts, vertQuadrics); int faces = (int)Math.Floor(indexTris.Length * 0.5); faces = DecimateVertices(faces, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics); //This will be used to update the old array (which has many empty elements) to a new vertex array and allow the indexTris to be updated as well Dictionary<int, int> beforeIndexAfterIndex = new Dictionary<int, int>(); int currentIndex = 0; List<Vector3> newVerts = new List<Vector3>(); for (int i = 0; i < verts.Length; i++) { Vector3 v = verts[i]; if (trisAttachedToVerts[i] != null) { beforeIndexAfterIndex.Add(i, currentIndex); currentIndex++; newVerts.Add(v); } } MeshIndexTriangle[] newIndexTris = new MeshIndexTriangle[faces]; currentIndex = 0; foreach(MeshIndexTriangle tri in indexTris) { if(tri != null) { MeshIndexTriangle newTri = new MeshIndexTriangle(beforeIndexAfterIndex[tri.v0], beforeIndexAfterIndex[tri.v1], beforeIndexAfterIndex[tri.v2]); newIndexTris[currentIndex] = newTri; currentIndex++; } } mesh.vertexes = newVerts.ToArray(); mesh.triangles = newIndexTris; return mesh; } public static int DecimateVertices(int targetFaces, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics) { int validFaces = indexTris.Length; int counter = 1; StringBuilder debug = new StringBuilder(); debug.AppendLine("Target Faces: " + targetFaces); try { while (validFaces > targetFaces) { debug.AppendLine("Iteration: " + counter + " Faces: " + validFaces); //Get the pair contraction with the least error associated with it MeshPairContraction pair = pairContractions.ExtractDominating(); debug.AppendLine("Contraction between vertices at indicies: " + pair.v0 + " and " + pair.v1); debug.AppendLine("Tris attached to v0: " + trisAttachedToVerts[pair.v0].Count + " Tris attached to v1: " + trisAttachedToVerts[pair.v1].Count); //Get faces that will be deleted / changed by contraction ComputeContraction(ref pair, indexTris, trisAttachedToVerts); //Act on faces, delete extra vertex, change all references to second vertex validFaces -= ApplyContraction(ref pair, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics); counter++; } for(int i = 0; i < indexTris.Length; i++) { MeshIndexTriangle tri = indexTris[i]; if (tri == null) continue; if (trisAttachedToVerts[tri.v0] == null) { debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v0); } if (trisAttachedToVerts[tri.v1] == null) { debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v1); } if (trisAttachedToVerts[tri.v2] == null) { debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v2); } } debug.AppendLine("Final: Faces: " + validFaces); } catch (Exception e) { debug.AppendLine("Error: " + e.Message); debug.AppendLine("Stack trace"); debug.AppendLine(e.StackTrace); } Debug.Log(debug.ToString()); return validFaces; } public static int ApplyContraction(ref MeshPairContraction pair, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics) { int removedFaces = pair.deletedFaces.Count; //Move v0, clear v1 verts[pair.v0] = pair.contractedPosition; verts[pair.v1] = Vector3.zero; foreach (int triIndex in trisAttachedToVerts[pair.v1]) if (!pair.deletedFaces.Contains(triIndex) && !trisAttachedToVerts[pair.v0].Contains(triIndex)) trisAttachedToVerts[pair.v0].Add(triIndex); //Clear out all the tris attached to a non-existent vertex trisAttachedToVerts[pair.v1] = null; //Accumulate quadrics, clear unused one vertQuadrics[pair.v0] += vertQuadrics[pair.v1]; vertQuadrics[pair.v1] = new Quadric(); //Adjust deformed triangles foreach (int changedTri in pair.deformedFaces) { MeshIndexTriangle tri = indexTris[changedTri]; if (tri.v0.Equals(pair.v1)) tri.v0 = pair.v0; else if (tri.v1.Equals(pair.v1)) tri.v1 = pair.v0; else tri.v2 = pair.v0; indexTris[changedTri] = tri; } //Clear deleted triangles foreach(int deletedTri in pair.deletedFaces) { indexTris[deletedTri] = null; } List<MeshPairContraction> pairList = pairContractions.ToList(); for (int i = 0; i < pairContractions.Count; i++) { MeshPairContraction otherPair = pairList[i]; if (otherPair.v0.Equals(pair.v1)) { otherPair.v0 = pair.v0; } else if (otherPair.v1.Equals(pair.v1)) { otherPair.v1 = pair.v0; } pairList[i] = otherPair; } int count = pairList.Count; for (int i = 0; i < count; i++ ) { MeshPairContraction iItem = pairList[i]; for(int j = i + 1; j < count; j++) { if (pairList[j].Equals(iItem)) { pairList.RemoveAt(j); //Remove duplicate element count--; //Reduce length to iterate over j--; //Make sure not to skip over a duplicate } } if(iItem.v1 == iItem.v0) { pairList.RemoveAt(i); //Remove degenerate edge count--; //Reduce length to iterate over i--; //Make sure not to skip over a duplicate continue; } CalculateTargetPositionForPairContraction(ref iItem, verts, vertQuadrics); pairList[i] = iItem; } pairContractions = new MinHeap<MeshPairContraction>(pairList); return removedFaces; } public static void ComputeContraction(ref MeshPairContraction pair, MeshIndexTriangle[] indexTris, List<int>[] trisAttachedToVerts) { //This contains a list of all tris that will be changed by this contraction; boolean indicates whether they will be removed or not Dictionary<int, bool> trisToChange = new Dictionary<int, bool>(); pair.deformedFaces.Clear(); pair.deletedFaces.Clear(); //Iterate through every triangle attached to vertex 0 of this pair and add them to the dict foreach(int triIndex in trisAttachedToVerts[pair.v0]) { if(indexTris[triIndex] != null) trisToChange.Add(triIndex, false); } //Iterate through tris attached to vert 1... foreach (int triIndex in trisAttachedToVerts[pair.v1]) { if (indexTris[triIndex] == null) continue; //if the tri is already there, it will become degenerate during this contraction and should be removed if (trisToChange.ContainsKey(triIndex)) trisToChange[triIndex] = true; //else, add it and it will simply be deformed else trisToChange.Add(triIndex, false); } //Now, divide them into the appropriate lists foreach(KeyValuePair<int, bool> triIndex in trisToChange) { if (triIndex.Value) pair.deletedFaces.Add(triIndex.Key); else pair.deformedFaces.Add(triIndex.Key); } } public static MinHeap<MeshPairContraction> GeneratePairContractions(MeshIndexTriangle[] indexTris, Vector3[] verts, Quadric[] vertQuadrics) { List<MeshPairContraction> pairContractions = new List<MeshPairContraction>(); foreach(MeshIndexTriangle tri in indexTris) { MeshPairContraction e0 = new MeshPairContraction(tri.v0, tri.v1), e1 = new MeshPairContraction(tri.v1, tri.v2), e2 = new MeshPairContraction(tri.v2, tri.v0); if (!pairContractions.Contains(e0)) pairContractions.Add(e0); if (!pairContractions.Contains(e1)) pairContractions.Add(e1); if (!pairContractions.Contains(e2)) pairContractions.Add(e2); } //Calculate point that each pair contraction will contract to if it is to be done CalculateTargetPositionForAllPairContractions(ref pairContractions, verts, vertQuadrics); MinHeap<MeshPairContraction> heap = new MinHeap<MeshPairContraction>(pairContractions); return heap; } public static void CalculateTargetPositionForAllPairContractions(ref List<MeshPairContraction> pairContractions, Vector3[] verts, Quadric[] vertQuadrics) { for (int i = 0; i < pairContractions.Count; i++) { MeshPairContraction pair = pairContractions[i]; CalculateTargetPositionForPairContraction(ref pair, verts, vertQuadrics); pairContractions[i] = pair; } } public static void CalculateTargetPositionForPairContraction(ref MeshPairContraction pair, Vector3[] verts, Quadric[] vertQuadrics) { Vector3 v0 = verts[pair.v0], v1 = verts[pair.v1]; Quadric Q0 = vertQuadrics[pair.v0], Q1 = vertQuadrics[pair.v1]; Quadric Q = Q0 + Q1; if (Q.Optimize(ref pair.contractedPosition, 1e-12)) pair.error = Q.Evaluate(pair.contractedPosition); else { double ei = Q.Evaluate(v0), ej = Q.Evaluate(v1); if (ei < ej) { pair.error = ei; pair.contractedPosition = v0; } else { pair.error = ej; pair.contractedPosition = v1; } } } //This returns an array that contains (in each element) a list of indexes that specify which MeshIndexTriangles (in indexTris) are connected to which Vector3s (in verts) public static List<int>[] GetTrisAttachedToVerts(Vector3[] verts, MeshIndexTriangle[] indexTris) { List<int>[] trisAttachedToVerts = new List<int>[verts.Length]; for (int i = 0; i < trisAttachedToVerts.Length; i++) { trisAttachedToVerts[i] = new List<int>(); } for (int i = 0; i < indexTris.Length; i++) { MeshIndexTriangle tri = indexTris[i]; trisAttachedToVerts[tri.v0].Add(i); trisAttachedToVerts[tri.v1].Add(i); trisAttachedToVerts[tri.v2].Add(i); } return trisAttachedToVerts; } //Returns an array of quadrics for evaluating the error of each possible contraction public static Quadric[] CalculateVertQuadrics(Vector3[] verts, MeshIndexTriangle[] indexTris) { Quadric[] vertQuadrics = new Quadric[verts.Length]; for (int i = 0; i < vertQuadrics.Length; i++ ) vertQuadrics[i] = new Quadric(); foreach (MeshIndexTriangle tri in indexTris) { Vector3 v0, v1, v2; v0 = verts[tri.v0]; v1 = verts[tri.v1]; v2 = verts[tri.v2]; double area = PANELFARTriangleUtils.triangle_area(v0, v1, v2); Vector4 p; if (area > 0) p = PANELFARTriangleUtils.triangle_plane(v0, v1, v2); else { p = PANELFARTriangleUtils.triangle_plane(v2, v1, v0); area = -area; } Quadric Q = new Quadric(p.x, p.y, p.z, p.w, area); // Area-weight quadric and add it into the three quadrics for the corners Q *= Q.area; vertQuadrics[tri.v0] += Q; vertQuadrics[tri.v1] += Q; vertQuadrics[tri.v2] += Q; } return vertQuadrics; } } }
ferram4/PANELFAR
PANELFAR/PANELFARMeshSimplification.cs
C#
gpl-3.0
15,504
# CMake generated Testfile for # Source directory: /home/aviral/GNU-Niyantran/gr36/gr-blocks/include/blocks # Build directory: /home/aviral/GNU-Niyantran/build/gr36/gr-blocks/include/blocks # # This file includes the relevent testing commands required for # testing this directory and lists subdirectories to be tested as well.
aviralchandra/Sandhi
build/gr36/gr-blocks/include/blocks/CTestTestfile.cmake
CMake
gpl-3.0
331
import threading import asyncio async def hello(): print('Hello world! (%s)' % threading.currentThread()) await asyncio.sleep(1) print('Hello again! (%s)' % threading.currentThread()) loop = asyncio.get_event_loop() tasks = [hello(), hello()] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
IIIIIIIIll/sdy_notes_liaoxf
LiaoXueFeng/as_IO/async_await.py
Python
gpl-3.0
325
#include <iostream> #include <string> class Shape { public : virtual void draw (void) = 0; static Shape *Create (std::string type); }; class circle : public Shape { public : void draw(void){ std::cout << "circle" << std::endl; } }; class square : public Shape { public : void draw(void){ std::cout << "square" << std::endl; } }; Shape * Shape::Create (std::string type){ if(type == "circle"){ std::cout << "creating circle" << std::endl; return new circle(); } if(type == "square") { std::cout << "creating circle" << std::endl; return new square(); } return NULL; }; int main (){ Shape *cir = Shape::Create("circle"); if ( cir != NULL ) cir->draw(); return 0; }
selvagit/experiments
computing/cpp/factory_method.cpp
C++
gpl-3.0
709
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[5]; atomic_int atom_1_r1_1; atomic_int atom_1_r13_0; void *t0(void *arg){ label_1:; atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); int v3_r3 = v2_r1 ^ v2_r1; int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst); int v7_r6 = v6_r4 ^ v6_r4; int v8_r6 = v7_r6 + 1; atomic_store_explicit(&vars[3], v8_r6, memory_order_seq_cst); int v10_r8 = atomic_load_explicit(&vars[3], memory_order_seq_cst); int v11_cmpeq = (v10_r8 == v10_r8); if (v11_cmpeq) goto lbl_LC00; else goto lbl_LC00; lbl_LC00:; atomic_store_explicit(&vars[4], 1, memory_order_seq_cst); int v13_r11 = atomic_load_explicit(&vars[4], memory_order_seq_cst); int v14_r12 = v13_r11 ^ v13_r11; int v17_r13 = atomic_load_explicit(&vars[0+v14_r12], memory_order_seq_cst); int v21 = (v2_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v21, memory_order_seq_cst); int v22 = (v17_r13 == 0); atomic_store_explicit(&atom_1_r13_0, v22, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[3], 0); atomic_init(&vars[2], 0); atomic_init(&vars[0], 0); atomic_init(&vars[4], 0); atomic_init(&vars[1], 0); atomic_init(&atom_1_r1_1, 0); atomic_init(&atom_1_r13_0, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v18 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v19 = atomic_load_explicit(&atom_1_r13_0, memory_order_seq_cst); int v20_conj = v18 & v19; if (v20_conj == 1) assert(0); return 0; }
nidhugg/nidhugg
tests/litmus/C-tests/MP+PPO073.c
C
gpl-3.0
1,993
{% extends "allauth/account/base.html" %} {% load i18n %} {% block head_title %}{% trans "Set Password" %}{% endblock %} {% block content %} <h1>{% trans "Set Password" %}</h1> <form method="POST" action="{% url 'account_set_password' %}" class="password_set"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="action" value="{% trans 'Set Password' %}"/> </form> {% endblock %}
manterd/myPhyloDB
templates/allauth/account/password_set.html
HTML
gpl-3.0
429
#include "CAN.h" #include "led.h" #include "delay.h" #include "usart.h" ////////////////////////////////////////////////////////////////////////////////// //±¾³ÌÐòÖ»¹©Ñ§Ï°Ê¹Óã¬Î´¾­×÷ÕßÐí¿É£¬²»µÃÓÃÓÚÆäËüÈκÎÓÃ; //ALIENTEKÕ½½¢STM32¿ª·¢°å //CANÇý¶¯ ´úÂë //ÕýµãÔ­×Ó@ALIENTEK //¼¼ÊõÂÛ̳:www.openedv.com //ÐÞ¸ÄÈÕÆÚ:2012/9/11 //°æ±¾£ºV1.0 //°æÈ¨ËùÓУ¬µÁ°æ±Ø¾¿¡£ //Copyright(C) ¹ãÖÝÊÐÐÇÒíµç×ӿƼ¼ÓÐÏÞ¹«Ë¾ 2009-2019 //All rights reserved ////////////////////////////////////////////////////////////////////////////////// //CAN³õʼ»¯ //tsjw:ÖØÐÂͬ²½ÌøÔ¾Ê±¼äµ¥Ôª.·¶Î§:1~3; CAN_SJW_1tq CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq //tbs2:ʱ¼ä¶Î2µÄʱ¼äµ¥Ôª.·¶Î§:1~8; //tbs1:ʱ¼ä¶Î1µÄʱ¼äµ¥Ôª.·¶Î§:1~16; CAN_BS1_1tq ~CAN_BS1_16tq //brp :²¨ÌØÂÊ·ÖÆµÆ÷.·¶Î§:1~1024;(ʵ¼ÊÒª¼Ó1,Ò²¾ÍÊÇ1~1024) tq=(brp)*tpclk1 //×¢ÒâÒÔÉϲÎÊýÈκÎÒ»¸ö¶¼²»ÄÜÉèΪ0,·ñÔò»áÂÒ. //²¨ÌØÂÊ=Fpclk1/((tsjw+tbs1+tbs2)*brp); //mode:0,ÆÕͨģʽ;1,»Ø»·Ä£Ê½; //Fpclk1µÄʱÖÓÔÚ³õʼ»¯µÄʱºòÉèÖÃΪ36M,Èç¹ûÉèÖÃCAN_Normal_Init(1,8,7,5,1); //Ôò²¨ÌØÂÊΪ:36M/((1+8+7)*5)=450Kbps //·µ»ØÖµ:0,³õʼ»¯OK; // ÆäËû,³õʼ»¯Ê§°Ü; u8 CAN_Mode_Init(u8 tsjw,u8 tbs2,u8 tbs1,u16 brp,u8 mode) { GPIO_InitTypeDef GPIO_InitStructure; CAN_InitTypeDef CAN_InitStructure; CAN_FilterInitTypeDef CAN_FilterInitStructure; #if CAN_RX0_INT_ENABLE NVIC_InitTypeDef NVIC_InitStructure; #endif RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//ʹÄÜPORTAʱÖÓ RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN2, ENABLE);//ʹÄÜCAN2ʱÖÓ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //¸´ÓÃÍÆÍì GPIO_Init(GPIOB, &GPIO_InitStructure); //³õʼ»¯IO GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//ÉÏÀ­ÊäÈë GPIO_Init(GPIOB, &GPIO_InitStructure);//³õʼ»¯IO //CANµ¥ÔªÉèÖà CAN_InitStructure.CAN_TTCM=DISABLE; //·Çʱ¼ä´¥·¢Í¨ÐÅģʽ // CAN_InitStructure.CAN_ABOM=DISABLE; //Èí¼þ×Ô¶¯ÀëÏß¹ÜÀí // CAN_InitStructure.CAN_AWUM=DISABLE; //˯Ãßģʽͨ¹ýÈí¼þ»½ÐÑ(Çå³ýCAN->MCRµÄSLEEPλ)// CAN_InitStructure.CAN_NART=ENABLE; //½ûÖ¹±¨ÎÄ×Ô¶¯´«ËÍ // CAN_InitStructure.CAN_RFLM=DISABLE; //±¨ÎIJ»Ëø¶¨,еĸ²¸Ç¾ÉµÄ // CAN_InitStructure.CAN_TXFP=DISABLE; //ÓÅÏȼ¶Óɱ¨Îıêʶ·û¾ö¶¨ // CAN_InitStructure.CAN_Mode= mode; //ģʽÉèÖ㺠mode:0,ÆÕͨģʽ;1,»Ø»·Ä£Ê½; // //ÉèÖò¨ÌØÂÊ CAN_InitStructure.CAN_SJW=tsjw; //ÖØÐÂͬ²½ÌøÔ¾¿í¶È(Tsjw)Ϊtsjw+1¸öʱ¼äµ¥Î» CAN_SJW_1tq CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq CAN_InitStructure.CAN_BS1=tbs1; //Tbs1=tbs1+1¸öʱ¼äµ¥Î»CAN_BS1_1tq ~CAN_BS1_16tq CAN_InitStructure.CAN_BS2=tbs2;//Tbs2=tbs2+1¸öʱ¼äµ¥Î»CAN_BS2_1tq ~ CAN_BS2_8tq CAN_InitStructure.CAN_Prescaler=brp; //·ÖƵϵÊý(Fdiv)Ϊbrp+1 // CAN_Init(CAN2, &CAN_InitStructure); // ³õʼ»¯CAN1 CAN_FilterInitStructure.CAN_FilterNumber=0; //¹ýÂËÆ÷0 CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask; CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit; //32λ CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000;////32λID CAN_FilterInitStructure.CAN_FilterIdLow=0x0000; CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000;//32λMASK CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000; CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0;//¹ýÂËÆ÷0¹ØÁªµ½FIFO0 CAN_FilterInitStructure.CAN_FilterActivation=ENABLE; //¼¤»î¹ýÂËÆ÷0 CAN_FilterInit(&CAN_FilterInitStructure);//Â˲¨Æ÷³õʼ»¯ return 0; } //can·¢ËÍÒ»×éÊý¾Ý(¹Ì¶¨¸ñʽ:IDΪ0X12,±ê×¼Ö¡,Êý¾ÝÖ¡) //len:Êý¾Ý³¤¶È(×î´óΪ8) //msg:Êý¾ÝÖ¸Õë,×î´óΪ8¸ö×Ö½Ú. //·µ»ØÖµ:0,³É¹¦; // ÆäËû,ʧ°Ü; u8 Can_Send_Msg(u8* msg,u8 len) { u8 mbox; u16 i=0; CanTxMsg TxMessage; TxMessage.StdId=0x12; // ±ê×¼±êʶ·ûΪ0 TxMessage.ExtId=0x12; // ÉèÖÃÀ©Õ¹±êʾ·û£¨29룩 TxMessage.IDE=0; // ʹÓÃÀ©Õ¹±êʶ·û TxMessage.RTR=0; // ÏûÏ¢ÀàÐÍΪÊý¾ÝÖ¡£¬Ò»Ö¡8λ TxMessage.DLC=len; // ·¢ËÍÁ½Ö¡ÐÅÏ¢ for(i=0;i<len;i++) TxMessage.Data[i]=msg[i]; // µÚÒ»Ö¡ÐÅÏ¢ mbox= CAN_Transmit(CAN2, &TxMessage); i=0; while((CAN_TransmitStatus(CAN2, mbox)==CAN_TxStatus_Failed)&&(i<0XFFF))i++; //µÈ´ý·¢ËͽáÊø if(i>=0XFFF)return 1; return 0; } //can¿Ú½ÓÊÕÊý¾Ý²éѯ //buf:Êý¾Ý»º´æÇø; //·µ»ØÖµ:0,ÎÞÊý¾Ý±»ÊÕµ½; // ÆäËû,½ÓÊÕµÄÊý¾Ý³¤¶È; u8 Can_Receive_Msg(u8 *buf) { u32 i; CanRxMsg RxMessage; if( CAN_MessagePending(CAN2,CAN_FIFO0)==0)return 0; //ûÓнÓÊÕµ½Êý¾Ý,Ö±½ÓÍ˳ö CAN_Receive(CAN2, CAN_FIFO0, &RxMessage);//¶ÁÈ¡Êý¾Ý for(i=0;i<8;i++) buf[i]=RxMessage.Data[i]; return RxMessage.DLC; }
chempin/stm32f107-
10.CAN/OV/can.c
C
gpl-3.0
4,689
/* Author: Juan Rada-Vilela, Ph.D. Copyright (C) 2010-2014 FuzzyLite Limited All rights reserved This file is part of fuzzylite. fuzzylite 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. fuzzylite 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 fuzzylite. If not, see <http://www.gnu.org/licenses/>. fuzzylite™ is a trademark of FuzzyLite Limited. */ #include "../../fl/defuzzifier/IntegralDefuzzifier.h" namespace fl { int IntegralDefuzzifier::_defaultResolution = 200; void IntegralDefuzzifier::setDefaultResolution(int defaultResolution) { _defaultResolution = defaultResolution; } int IntegralDefuzzifier::defaultResolution() { return _defaultResolution; } IntegralDefuzzifier::IntegralDefuzzifier(int resolution) : Defuzzifier(), _resolution(resolution) { } IntegralDefuzzifier::~IntegralDefuzzifier() { } void IntegralDefuzzifier::setResolution(int resolution) { this->_resolution = resolution; } int IntegralDefuzzifier::getResolution() const { return this->_resolution; } }
senabhishek/fuzzyliteAndSwift
FuzzyLiteTemplate/fuzzylite/src/defuzzifier/IntegralDefuzzifier.cpp
C++
gpl-3.0
1,554
/* Liquid War 6 is a unique multiplayer wargame. Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Christian Mauduit <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Liquid War 6 homepage : http://www.gnu.org/software/liquidwar6/ Contact author : [email protected] */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include <CUnit/CUnit.h> #include "mat.h" int main (int argc, const char *argv[]) { int ret = 0; lw6sys_context_t *sys_context = NULL; int mode = 0; LW6SYS_MAIN_BEGIN (sys_context); lw6sys_log_clear (sys_context, NULL); mode = lw6sys_arg_test_mode (sys_context, argc, argv); if (CU_initialize_registry () == CUE_SUCCESS) { if (lw6mat_test_register (sys_context, mode)) { ret = lw6mat_test_run (sys_context, mode); } CU_cleanup_registry (); } LW6SYS_TEST_OUTPUT; LW6SYS_MAIN_END (sys_context); return (!ret); }
lijiaqigreat/liquidwar-web
reference/src/lib/mat/mat-testmain.c
C
gpl-3.0
1,546
""" Tests are performed against csr1000v-universalk9.03.15.00.S.155-2.S-std. """ import unittest from iosxe.iosxe import IOSXE from iosxe.exceptions import AuthError node = '172.16.92.134' username = 'cisco' password = 'cisco' port = 55443 class TestIOSXE(unittest.TestCase): def setUp(self): self.xe = IOSXE(node=node, username=username, password=password, disable_warnings=True) def test_iosxe_is_a_IOSXE(self): self.assertIsInstance(self.xe, IOSXE) def test_invalid_user_pass_returns_auth_error(self): self.assertRaises(AuthError, IOSXE, node=node, username='stuff', password='things', disable_warnings=True) def test_url_base(self): self.assertEqual(self.xe.url_base, 'https://{0}:{1}/api/v1'.format(node, port)) def test_token_uri(self): self.assertEqual(self.xe.token_uri, '/auth/token-services') def test_save_config_success(self): resp = self.xe.save_config() self.assertEqual(204, resp.status_code)
bobthebutcher/iosxe
tests/test_iosxe.py
Python
gpl-3.0
1,026
//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. #ifndef APIQUERYRESULT_HPP #define APIQUERYRESULT_HPP #include "definitions.hpp" #include <QString> #include <QList> #include <QHash> #include "queryresult.hpp" namespace Huggle { //! Key/value node for data from API queries //! \todo Currently value is provided even for nodes that shouldn't have it class HUGGLE_EX_CORE ApiQueryResultNode { public: ApiQueryResultNode(); ~ApiQueryResultNode(); /*! * \brief GetAttribute Return the specified attribute if it exists, otherwise return the default * \param name Name of attribute * \param default_val Value to return if the attribute is not found * \return Value of attribute or default value */ QString GetAttribute(const QString &name, const QString &default_val = ""); //! Name of attribute QString Name; //! Value of attribute QString Value; //! Hashtable of attribtues QHash<QString, QString> Attributes; QList<ApiQueryResultNode*> ChildNodes; }; //! Api queries have their own result class so that we can use it to parse them //! this is a universal result class that uses same format for all known //! formats we are going to use, including XML or JSON, so that it shouldn't //! matter which one we use, we always get this structure as output class HUGGLE_EX_CORE ApiQueryResult : public QueryResult { public: ApiQueryResult(); //! Frees the results from memory ~ApiQueryResult() override; /*! * \brief Process Process the data into Nodes and handle any warnings / errors */ void Process(); /*! * \brief GetNode Get the first node with the specified name * IMPORTANT: do not delete this node, it's a pointer to item in a list which get deleted in destructor of class * \param node_name Name of node * \return The specified node or a null pointer if none found */ ApiQueryResultNode *GetNode(const QString& node_name); /*! * \brief GetNodes Get all nodes with the specified name * IMPORTANT: do not delete these nodes, they point to items in a list which get deleted in destructor of class * \param node_name Name of node * \return QList of pointers to found nodes */ QList<ApiQueryResultNode*> GetNodes(const QString& node_name); QString GetNodeValue(const QString &node_name, const QString &default_value = ""); /*! * \brief HasWarnings Return if the API has returned any warnings * \return True if there are warnings, false otherwise */ bool HasWarnings(); //! List of result nodes unsorted with no hierarchy QList<ApiQueryResultNode*> Nodes; ApiQueryResultNode *Root; //! Warning from API query QString Warning; //! If any error was encountered during the query bool HasErrors = false; }; } #endif // APIQUERYRESULT_HPP
huggle/huggle3-qt-lx
src/huggle_core/apiqueryresult.hpp
C++
gpl-3.0
3,741
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = versionTransform; var _path2 = require('path'); var _path3 = _interopRequireDefault(_path2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var packagePath = _path3.default.resolve(process.cwd(), './package.json'); var _require = require(packagePath); var version = _require.version; function versionTransform() { return { visitor: { Identifier: function Identifier(path) { if (path.node.name === 'VERSION') { path.replaceWithSourceString('"' + version + '"'); } } } }; };
cassiane/KnowledgePlatform
Implementacao/nodejs-tcc/node_modules/babel-plugin-version-transform/lib/index.js
JavaScript
gpl-3.0
675
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Basic Table</h2> <p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p> <table class="table"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>Doe</td> <td>[email protected]</td> </tr> <tr> <td>Mary</td> <td>Moe</td> <td>[email protected]</td> </tr> <tr> <td>July</td> <td>Dooley</td> <td>[email protected]</td> </tr> </tbody> </table> </div> </body> </html>
hfarazm/Bootstrap-3-Tutorials-Hfarazm.com
Tutorial 1 - Getting started with Bootstrap 3/bootstrap-example.html
HTML
gpl-3.0
1,147
from __future__ import absolute_import from pywb.framework.wbrequestresponse import WbResponse, WbRequest from pywb.framework.archivalrouter import ArchivalRouter from six.moves.urllib.parse import urlsplit import base64 import socket import ssl from io import BytesIO from pywb.rewrite.url_rewriter import SchemeOnlyUrlRewriter, UrlRewriter from pywb.rewrite.rewrite_content import RewriteContent from pywb.utils.wbexception import BadRequestException from pywb.utils.bufferedreaders import BufferedReader from pywb.utils.loaders import to_native_str from pywb.framework.proxy_resolvers import ProxyAuthResolver, CookieResolver, IPCacheResolver from tempfile import SpooledTemporaryFile #================================================================= class ProxyArchivalRouter(ArchivalRouter): """ A router which combines both archival and proxy modes support First, request is treated as a proxy request using ProxyRouter Second, if not handled by the router, it is treated as a regular archival mode request. """ def __init__(self, routes, **kwargs): super(ProxyArchivalRouter, self).__init__(routes, **kwargs) self.proxy = ProxyRouter(routes, **kwargs) def __call__(self, env): response = self.proxy(env) if response: return response response = super(ProxyArchivalRouter, self).__call__(env) if response: return response #================================================================= class ProxyRouter(object): """ A router which supports http proxy mode requests Handles requests of the form: GET http://example.com The router returns latest capture by default. However, if Memento protocol support is enabled, the memento Accept-Datetime header can be used to select specific capture. See: http://www.mementoweb.org/guide/rfc/#Pattern1.3 for more details. """ BLOCK_SIZE = 4096 DEF_MAGIC_NAME = 'pywb.proxy' BUFF_RESPONSE_MEM_SIZE = 1024*1024 CERT_DL_PEM = '/pywb-ca.pem' CERT_DL_P12 = '/pywb-ca.p12' CA_ROOT_FILE = './ca/pywb-ca.pem' CA_ROOT_NAME = 'pywb https proxy replay CA' CA_CERTS_DIR = './ca/certs/' EXTRA_HEADERS = {'cache-control': 'no-cache', 'connection': 'close', 'p3p': 'CP="NOI ADM DEV COM NAV OUR STP"'} def __init__(self, routes, **kwargs): self.error_view = kwargs.get('error_view') proxy_options = kwargs.get('config', {}) if proxy_options: proxy_options = proxy_options.get('proxy_options', {}) self.magic_name = proxy_options.get('magic_name') if not self.magic_name: self.magic_name = self.DEF_MAGIC_NAME proxy_options['magic_name'] = self.magic_name self.extra_headers = proxy_options.get('extra_headers') if not self.extra_headers: self.extra_headers = self.EXTRA_HEADERS proxy_options['extra_headers'] = self.extra_headers res_type = proxy_options.get('cookie_resolver', True) if res_type == 'auth' or not res_type: self.resolver = ProxyAuthResolver(routes, proxy_options) elif res_type == 'ip': self.resolver = IPCacheResolver(routes, proxy_options) #elif res_type == True or res_type == 'cookie': # self.resolver = CookieResolver(routes, proxy_options) else: self.resolver = CookieResolver(routes, proxy_options) self.use_banner = proxy_options.get('use_banner', True) self.use_wombat = proxy_options.get('use_client_rewrite', True) self.proxy_cert_dl_view = proxy_options.get('proxy_cert_download_view') if not proxy_options.get('enable_https_proxy'): self.ca = None return try: from certauth.certauth import CertificateAuthority except ImportError: #pragma: no cover print('HTTPS proxy is not available as the "certauth" module ' + 'is not installed') print('Please install via "pip install certauth" ' + 'to enable HTTPS support') self.ca = None return # HTTPS Only Options ca_file = proxy_options.get('root_ca_file', self.CA_ROOT_FILE) # attempt to create the root_ca_file if doesn't exist # (generally recommended to create this seperately) ca_name = proxy_options.get('root_ca_name', self.CA_ROOT_NAME) certs_dir = proxy_options.get('certs_dir', self.CA_CERTS_DIR) self.ca = CertificateAuthority(ca_file=ca_file, certs_dir=certs_dir, ca_name=ca_name) self.use_wildcard = proxy_options.get('use_wildcard_certs', True) def __call__(self, env): is_https = (env['REQUEST_METHOD'] == 'CONNECT') ArchivalRouter.ensure_rel_uri_set(env) # for non-https requests, check non-proxy urls if not is_https: url = env['REL_REQUEST_URI'] if not url.startswith(('http://', 'https://')): return None env['pywb.proxy_scheme'] = 'http' route = None coll = None matcher = None response = None ts = None # check resolver, for pre connect resolve if self.resolver.pre_connect: route, coll, matcher, ts, response = self.resolver.resolve(env) if response: return response # do connect, then get updated url if is_https: response = self.handle_connect(env) if response: return response url = env['REL_REQUEST_URI'] else: parts = urlsplit(env['REL_REQUEST_URI']) hostport = parts.netloc.split(':', 1) env['pywb.proxy_host'] = hostport[0] env['pywb.proxy_port'] = hostport[1] if len(hostport) == 2 else '' env['pywb.proxy_req_uri'] = parts.path if parts.query: env['pywb.proxy_req_uri'] += '?' + parts.query env['pywb.proxy_query'] = parts.query if self.resolver.supports_switching: env['pywb_proxy_magic'] = self.magic_name # route (static) and other resources to archival replay if env['pywb.proxy_host'] == self.magic_name: env['REL_REQUEST_URI'] = env['pywb.proxy_req_uri'] # special case for proxy install response = self.handle_cert_install(env) if response: return response return None # check resolver, post connect if not self.resolver.pre_connect: route, coll, matcher, ts, response = self.resolver.resolve(env) if response: return response rel_prefix = '' custom_prefix = env.get('HTTP_PYWB_REWRITE_PREFIX', '') if custom_prefix: host_prefix = custom_prefix urlrewriter_class = UrlRewriter abs_prefix = True # always rewrite to absolute here rewrite_opts = dict(no_match_rel=True) else: host_prefix = env['pywb.proxy_scheme'] + '://' + self.magic_name urlrewriter_class = SchemeOnlyUrlRewriter abs_prefix = False rewrite_opts = {} # special case for proxy calendar if (env['pywb.proxy_host'] == 'query.' + self.magic_name): url = env['pywb.proxy_req_uri'][1:] rel_prefix = '/' if ts is not None: url = ts + '/' + url wbrequest = route.request_class(env, request_uri=url, wb_url_str=url, coll=coll, host_prefix=host_prefix, rel_prefix=rel_prefix, wburl_class=route.handler.get_wburl_type(), urlrewriter_class=urlrewriter_class, use_abs_prefix=abs_prefix, rewrite_opts=rewrite_opts, is_proxy=True) if matcher: route.apply_filters(wbrequest, matcher) # full rewrite and banner if self.use_wombat and self.use_banner: wbrequest.wb_url.mod = '' elif self.use_banner: # banner only, no rewrite wbrequest.wb_url.mod = 'bn_' else: # unaltered, no rewrite or banner wbrequest.wb_url.mod = 'uo_' response = route.handler(wbrequest) if not response: return None # add extra headers for replay responses if wbrequest.wb_url and wbrequest.wb_url.is_replay(): response.status_headers.replace_headers(self.extra_headers) # check for content-length res = response.status_headers.get_header('content-length') try: if int(res) > 0: return response except: pass # need to either chunk or buffer to get content-length if env.get('SERVER_PROTOCOL') == 'HTTP/1.1': response.status_headers.remove_header('content-length') response.status_headers.headers.append(('Transfer-Encoding', 'chunked')) response.body = self._chunk_encode(response.body) else: response.body = self._buffer_response(response.status_headers, response.body) return response @staticmethod def _chunk_encode(orig_iter): for chunk in orig_iter: if not len(chunk): continue chunk_len = b'%X\r\n' % len(chunk) yield chunk_len yield chunk yield b'\r\n' yield b'0\r\n\r\n' @staticmethod def _buffer_response(status_headers, iterator): out = SpooledTemporaryFile(ProxyRouter.BUFF_RESPONSE_MEM_SIZE) size = 0 for buff in iterator: size += len(buff) out.write(buff) content_length_str = str(size) # remove existing content length status_headers.replace_header('Content-Length', content_length_str) out.seek(0) return RewriteContent.stream_to_gen(out) def get_request_socket(self, env): if not self.ca: return None sock = None if env.get('uwsgi.version'): # pragma: no cover try: import uwsgi fd = uwsgi.connection_fd() conn = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) try: sock = socket.socket(_sock=conn) except: sock = conn except Exception as e: pass elif env.get('gunicorn.socket'): # pragma: no cover sock = env['gunicorn.socket'] if not sock: # attempt to find socket from wsgi.input input_ = env.get('wsgi.input') if input_: if hasattr(input_, '_sock'): # pragma: no cover raw = input_._sock sock = socket.socket(_sock=raw) # pragma: no cover elif hasattr(input_, 'raw'): sock = input_.raw._sock return sock def handle_connect(self, env): sock = self.get_request_socket(env) if not sock: return WbResponse.text_response('HTTPS Proxy Not Supported', '405 HTTPS Proxy Not Supported') sock.send(b'HTTP/1.0 200 Connection Established\r\n') sock.send(b'Proxy-Connection: close\r\n') sock.send(b'Server: pywb proxy\r\n') sock.send(b'\r\n') hostname, port = env['REL_REQUEST_URI'].split(':') if not self.use_wildcard: certfile = self.ca.cert_for_host(hostname) else: certfile = self.ca.get_wildcard_cert(hostname) try: ssl_sock = ssl.wrap_socket(sock, server_side=True, certfile=certfile, #ciphers="ALL", suppress_ragged_eofs=False, ssl_version=ssl.PROTOCOL_SSLv23 ) env['pywb.proxy_ssl_sock'] = ssl_sock buffreader = BufferedReader(ssl_sock, block_size=self.BLOCK_SIZE) statusline = to_native_str(buffreader.readline().rstrip()) except Exception as se: raise BadRequestException(se.message) statusparts = statusline.split(' ') if len(statusparts) < 3: raise BadRequestException('Invalid Proxy Request: ' + statusline) env['REQUEST_METHOD'] = statusparts[0] env['REL_REQUEST_URI'] = ('https://' + env['REL_REQUEST_URI'].replace(':443', '') + statusparts[1]) env['SERVER_PROTOCOL'] = statusparts[2].strip() env['pywb.proxy_scheme'] = 'https' env['pywb.proxy_host'] = hostname env['pywb.proxy_port'] = port env['pywb.proxy_req_uri'] = statusparts[1] queryparts = env['REL_REQUEST_URI'].split('?', 1) env['PATH_INFO'] = queryparts[0] env['QUERY_STRING'] = queryparts[1] if len(queryparts) > 1 else '' env['pywb.proxy_query'] = env['QUERY_STRING'] while True: line = to_native_str(buffreader.readline()) if line: line = line.rstrip() if not line: break parts = line.split(':', 1) if len(parts) < 2: continue name = parts[0].strip() value = parts[1].strip() name = name.replace('-', '_').upper() if name not in ('CONTENT_LENGTH', 'CONTENT_TYPE'): name = 'HTTP_' + name env[name] = value env['wsgi.input'] = buffreader #remain = buffreader.rem_length() #if remain > 0: #remainder = buffreader.read() #env['wsgi.input'] = BufferedReader(BytesIO(remainder)) #remainder = buffreader.read(self.BLOCK_SIZE) #env['wsgi.input'] = BufferedReader(ssl_sock, # block_size=self.BLOCK_SIZE, # starting_data=remainder) def handle_cert_install(self, env): if env['pywb.proxy_req_uri'] in ('/', '/index.html', '/index.html'): available = (self.ca is not None) if self.proxy_cert_dl_view: return (self.proxy_cert_dl_view. render_response(available=available, pem_path=self.CERT_DL_PEM, p12_path=self.CERT_DL_P12)) elif env['pywb.proxy_req_uri'] == self.CERT_DL_PEM: if not self.ca: return None buff = b'' with open(self.ca.ca_file, 'rb') as fh: buff = fh.read() content_type = 'application/x-x509-ca-cert' headers = [('Content-Length', str(len(buff)))] return WbResponse.bin_stream([buff], content_type=content_type, headers=headers) elif env['pywb.proxy_req_uri'] == self.CERT_DL_P12: if not self.ca: return None buff = self.ca.get_root_PKCS12() content_type = 'application/x-pkcs12' headers = [('Content-Length', str(len(buff)))] return WbResponse.bin_stream([buff], content_type=content_type, headers=headers)
pombredanne/pywb
pywb/framework/proxy.py
Python
gpl-3.0
16,139
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image', 'eo', { alertUrl: 'Bonvolu tajpi la retadreson de la bildo', alt: 'Anstataŭiga Teksto', border: 'Bordero', btnUpload: 'Sendu al Servilo', button2Img: 'Ĉu vi volas transformi la selektitan bildbutonon en simplan bildon?', hSpace: 'Horizontala Spaco', img2Button: 'Ĉu vi volas transformi la selektitan bildon en bildbutonon?', infoTab: 'Informoj pri Bildo', linkTab: 'Ligilo', lockRatio: 'Konservi Proporcion', menu: 'Atributoj de Bildo', resetSize: 'Origina Grando', title: 'Atributoj de Bildo', titleButton: 'Bildbutonaj Atributoj', upload: 'Alŝuti', urlMissing: 'La fontretadreso de la bildo mankas.', vSpace: 'Vertikala Spaco', validateBorder: 'La bordero devas esti entjera nombro.', validateHSpace: 'La horizontala spaco devas esti entjera nombro.', validateVSpace: 'La vertikala spaco devas esti entjera nombro.' });
tsmaryka/hitc
public/javascripts/ckeditor/plugins/image/lang/eo.js
JavaScript
gpl-3.0
1,029
/** * Copyright (c) 2010-11 The AEminium Project (see AUTHORS file) * * This file is part of Plaid Programming Language. * * Plaid Programming Language 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. * * Plaid Programming Language 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 Plaid Programming Language. If not, see <http://www.gnu.org/licenses/>. */ package aeminium.runtime.tools.benchmark; public class RTBench { private static Benchmark[] benchmarks = { new TaskCreationBenchmark(), new IndependentTaskGraph(), new LinearTaskGraph(), new FixedParallelMaxDependencies(), new ChildTaskBenchmark(), new FibonacciBenchmark() }; public static void usage() { System.out.println(); System.out.println("java aeminium.runtime.tools.benchmark.RTBench COMMAND"); System.out.println(""); System.out.println("COMMANDS:"); System.out.println(" list - List available benchmarks."); System.out.println(" run BENCHMARK - Run specified benchmark."); System.out.println(); } public static void main(String[] args) { if ( args.length == 0 ) { usage(); return; } if ( args[0].equals("list") ) { for( Benchmark benchmark : benchmarks ) { System.out.println(benchmark.getName()); } } else if ( args[0].equals("run") && args.length == 2 ) { Benchmark benchmark = null; for ( Benchmark b : benchmarks ) { if ( b.getName().equals(args[1])) { benchmark = b; } } if ( benchmark != null ) { Reporter reporter = new StringBuilderReporter(); reporter.startBenchmark(benchmark.getName()); benchmark.run(reporter); reporter.stopBenchmark(benchmark.getName()); reporter.flush(); } else { usage(); } } else { usage(); } } protected static void reportVMStats(Reporter reporter) { reporter.reportLn(String.format("Memory (TOTAL/MAX/FREE) (%d,%d,%d)", Runtime.getRuntime().totalMemory(), Runtime.getRuntime().maxMemory(), Runtime.getRuntime().freeMemory())); } }
AEminium/AeminiumRuntime
src/aeminium/runtime/tools/benchmark/RTBench.java
Java
gpl-3.0
2,591
<h1><?php the_issuu_message('Document'); ?></h1> <form action="" method="post" id="document-upload"> <input type="hidden" name="name" value="<?= $doc->name; ?>"> <table class="form-table"> <tbody> <tr> <th><label for="title"><?php the_issuu_message('Title'); ?></label></th> <td><input type="text" name="title" id="title" class="regular-text code" value="<?= $doc->title; ?>"></td> </tr> <tr> <th><label for="description"><?php the_issuu_message('Description'); ?></label></th> <td> <textarea name="description" id="description" cols="45" rows="6"><?= $doc->description; ?></textarea> </td> </tr> <tr> <th><label for="tags">Tags</label></th> <td> <textarea name="tags" id="tags" cols="45" rows="6"><?= $tags; ?></textarea> <p class="description"> <?php the_issuu_message('Use commas to separate tags. Do not use spaces.'); ?> </p> </td> </tr> <tr> <th><label><?php the_issuu_message('Publish date'); ?></label></th> <td> <input type="text" name="pub[day]" id="dia" placeholder="<?php the_issuu_message('Day'); ?>" class="small-text" maxlength="2" value="<?= date('d', strtotime($doc->publishDate)); ?>"> / <input type="text" name="pub[month]" id="mes" placeholder="<?php the_issuu_message('Month'); ?>" class="small-text" maxlength="2" value="<?= date('m', strtotime($doc->publishDate)); ?>"> / <input type="text" name="pub[year]" id="ano" placeholder="<?php the_issuu_message('Year'); ?>" class="small-text" maxlength="4" value="<?= date('Y', strtotime($doc->publishDate)); ?>"> <p class="description"> <?php the_issuu_message('Date of publication of the document.<br><strong>NOTE:</strong> If you do not enter a value, the current date will be used'); ?> </p> </td> </tr> <tr> <th><label for="commentsAllowed"><?php the_issuu_message('Allow comments'); ?></label></th> <td> <input type="checkbox" name="commentsAllowed" id="commentsAllowed" value="true" <?= ($doc->commentsAllowed == true)? 'checked' : ''; ?>> </td> </tr> <tr> <th><label for="downloadable"><?php the_issuu_message('Allow file download'); ?></label></th> <td> <input type="checkbox" name="downloadable" id="downloadable" value="true" <?= ($doc->downloadable == true)? 'checked' : ''; ?>> </td> </tr> <tr> <th><label><?php the_issuu_message('Access'); ?></label></th> <td> <?php if ($doc->access == 'private') : ?> <p><strong><?php the_issuu_message('Private'); ?></strong></p> <p class="description"> <?php the_issuu_message('To publish this document <a href="http://issuu.com/home/publications" target="_blank">click here</a>'); ?> </p> <?php else: ?> <p><strong><?php the_issuu_message('Public'); ?></strong></p> <?php endif; ?> </td> </tr> <tr> <th> <input type="submit" class="button-primary" value="<?php the_issuu_message('Update'); ?>"> <h3> <a href="admin.php?page=issuu-document-admin" style="text-decoration: none;"> <?php the_issuu_message('Back'); ?> </a> </h3> </th> </tr> </tbody> </table> </form>
wp-plugins/issuu-panel
menu/documento/forms/update.php
PHP
gpl-3.0
3,277
#include "component.h" #include "entity.h" namespace entity { Component::Component(Entity* parent) : QObject(parent) { if (parent != NULL) { parent->addComponent(this); } } } uint qHash(entity::HashableComponent* key, uint seed) { return key == 0 ? 0 : key->hash(seed); }
alaineman/PowerGrid
src/EntityFramework/entity/component.cpp
C++
gpl-3.0
312
/* Copyright (C) 2005-2012 by George Williams */ /* * 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. * The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "fontforgeui.h" #include "groups.h" #include <unistd.h> #include <ustring.h> #include <utype.h> #include <gkeysym.h> #include <math.h> /******************************************************************************/ /******************************** Group Widget ********************************/ /******************************************************************************/ #define COLOR_CHOOSE (-10) static GTextInfo std_colors[] = { { (unichar_t *) N_("Select by Color"), NULL, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' }, { (unichar_t *) N_("Color|Choose..."), NULL, 0, 0, (void *) COLOR_CHOOSE, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' }, { (unichar_t *) N_("Color|Default"), &def_image, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' }, { NULL, &white_image, 0, 0, (void *) 0xffffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &red_image, 0, 0, (void *) 0xff0000, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &green_image, 0, 0, (void *) 0x00ff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &blue_image, 0, 0, (void *) 0x0000ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &yellow_image, 0, 0, (void *) 0xffff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &cyan_image, 0, 0, (void *) 0x00ffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, { NULL, &magenta_image, 0, 0, (void *) 0xff00ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, GTEXTINFO_EMPTY }; struct groupdlg { unsigned int oked: 1; unsigned int done: 1; unsigned int select_many: 1; /* define groups can only select one group at a time, select/restrict */ /* to groups can select multiple things */ unsigned int select_kids_too: 1; /* When we select a parent group do we want to select all the kids? */ Group *root; Group *oldsel; int open_cnt, lines_page, off_top, off_left, page_width, bmargin; int maxl; GWindow gw,v; GGadget *vsb, *hsb, *cancel, *ok, *compact; GGadget *newsub, *delete, *line1, *gpnamelab, *gpname, *glyphslab, *glyphs; GGadget *idlab, *idname, *iduni, *set, *select, *unique, *colour, *line2; int fh, as; GFont *font; FontView *fv; void (*select_callback)(struct groupdlg *); GTimer *showchange; }; extern int _GScrollBar_Width; static Group *GroupFindLPos(Group *group,int lpos,int *depth) { int i; forever { if ( group->lpos==lpos ) return( group ); if ( !group->open ) return( NULL ); for ( i=0; i<group->kid_cnt-1; ++i ) { if ( lpos<group->kids[i+1]->lpos ) break; } group = group->kids[i]; ++*depth; } } static int GroupPosInParent(Group *group) { Group *parent = group->parent; int i; if ( parent==NULL ) return( 0 ); for ( i=0; i<parent->kid_cnt; ++i ) if ( parent->kids[i]==group ) return( i ); return( -1 ); } static Group *GroupNext(Group *group,int *depth) { if ( group->open && group->kids ) { ++*depth; return( group->kids[0] ); } forever { int pos; if ( group->parent==NULL ) return( NULL ); pos = GroupPosInParent(group); if ( pos+1<group->parent->kid_cnt ) return( group->parent->kids[pos+1] ); group = group->parent; --*depth; } } static Group *GroupPrev(struct groupdlg *grp, Group *group,int *depth) { int pos; while ( group->parent!=NULL && group==group->parent->kids[0] ) { group = group->parent; --*depth; } if ( group->parent==NULL ) return( NULL ); pos = GroupPosInParent(group); group = group->parent->kids[pos-1]; while ( group->open ) { group = group->kids[group->kid_cnt-1]; ++*depth; } return( group ); } static int _GroupSBSizes(struct groupdlg *grp, Group *group, int lpos, int depth) { int i, len; group->lpos = lpos++; len = 5+8*depth+ grp->as + 5 + GDrawGetText8Width(grp->v,group->name,-1); if ( group->glyphs!=NULL ) len += 5 + GDrawGetText8Width(grp->v,group->glyphs,-1); if ( len > grp->maxl ) grp->maxl = len; if ( group->open ) { for ( i=0; i< group->kid_cnt; ++i ) lpos = _GroupSBSizes(grp,group->kids[i],lpos,depth+1); } return( lpos ); } static int GroupSBSizes(struct groupdlg *grp) { int lpos; grp->maxl = 0; GDrawSetFont(grp->v,grp->font); lpos = _GroupSBSizes(grp,grp->root,0,0); grp->maxl += 5; /* margin */ GScrollBarSetBounds(grp->vsb,0,lpos,grp->lines_page); GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width); grp->open_cnt = lpos; return( lpos ); } static void GroupSelectKids(Group *group,int sel) { int i; group->selected = sel; for ( i=0; i<group->kid_cnt; ++i ) GroupSelectKids(group->kids[i],sel); } static void GroupDeselectAllBut(Group *root,Group *group) { int i; if ( root!=group ) root->selected = false; for ( i=0; i<root->kid_cnt; ++i ) GroupDeselectAllBut(root->kids[i],group); } static Group *_GroupCurrentlySelected(Group *group) { int i; Group *sel; if ( group->selected ) return( group ); for ( i=0; i<group->kid_cnt; ++i ) { sel = _GroupCurrentlySelected(group->kids[i]); if ( sel!=NULL ) return( sel ); } return( NULL ); } static Group *GroupCurrentlySelected(struct groupdlg *grp) { if ( grp->select_many ) return( NULL ); return( _GroupCurrentlySelected(grp->root)); } static void GroupWExpose(struct groupdlg *grp,GWindow pixmap,GRect *rect) { int depth, y, len; Group *group; GRect r; Color fg; GDrawFillRect(pixmap,rect,GDrawGetDefaultBackground(NULL)); GDrawSetLineWidth(pixmap,0); r.height = r.width = grp->as; y = (rect->y/grp->fh) * grp->fh + grp->as; depth=0; group = GroupFindLPos(grp->root,rect->y/grp->fh+grp->off_top,&depth); GDrawSetFont(pixmap,grp->font); while ( group!=NULL ) { r.y = y-grp->as+1; r.x = 5+8*depth - grp->off_left; fg = group->selected ? 0xff0000 : 0x000000; if ( group->glyphs==NULL ) { GDrawDrawRect(pixmap,&r,fg); GDrawDrawLine(pixmap,r.x+2,r.y+grp->as/2,r.x+grp->as-2,r.y+grp->as/2, fg); if ( !group->open ) GDrawDrawLine(pixmap,r.x+grp->as/2,r.y+2,r.x+grp->as/2,r.y+grp->as-2, fg); } len = GDrawDrawText8(pixmap,r.x+r.width+5,y,group->name,-1,fg); if ( group->glyphs ) GDrawDrawText8(pixmap,r.x+r.width+5+len+5,y,group->glyphs,-1,fg); group = GroupNext(group,&depth); y += grp->fh; if ( y-grp->fh>rect->y+rect->height ) break; } } static void GroupWMouse(struct groupdlg *grp,GEvent *event) { int x; int depth=0; Group *group; group = GroupFindLPos(grp->root,event->u.mouse.y/grp->fh+grp->off_top,&depth); if ( group==NULL ) return; x = 5+8*depth - grp->off_left; if ( event->u.mouse.x<x ) return; if ( event->u.mouse.x<=x+grp->as ) { if ( group->glyphs != NULL ) return; group->open = !group->open; GroupSBSizes(grp); } else { group->selected = !group->selected; if ( grp->select_kids_too ) GroupSelectKids(group,group->selected); else if ( group->selected && !grp->select_many ) GroupDeselectAllBut(grp->root,group); if ( grp->select_callback!=NULL ) (grp->select_callback)(grp); } GDrawRequestExpose(grp->v,NULL,false); } static void GroupScroll(struct groupdlg *grp,struct sbevent *sb) { int newpos = grp->off_top; switch( sb->type ) { case et_sb_top: newpos = 0; break; case et_sb_uppage: newpos -= grp->lines_page; break; case et_sb_up: --newpos; break; case et_sb_down: ++newpos; break; case et_sb_downpage: newpos += grp->lines_page; break; case et_sb_bottom: newpos = grp->open_cnt-grp->lines_page; break; case et_sb_thumb: case et_sb_thumbrelease: newpos = sb->pos; break; } if ( newpos>grp->open_cnt-grp->lines_page ) newpos = grp->open_cnt-grp->lines_page; if ( newpos<0 ) newpos =0; if ( newpos!=grp->off_top ) { int diff = newpos-grp->off_top; grp->off_top = newpos; GScrollBarSetPos(grp->vsb,grp->off_top); GDrawScroll(grp->v,NULL,0,diff*grp->fh); } } static void GroupHScroll(struct groupdlg *grp,struct sbevent *sb) { int newpos = grp->off_left; switch( sb->type ) { case et_sb_top: newpos = 0; break; case et_sb_uppage: newpos -= grp->page_width; break; case et_sb_up: --newpos; break; case et_sb_down: ++newpos; break; case et_sb_downpage: newpos += grp->page_width; break; case et_sb_bottom: newpos = grp->maxl-grp->page_width; break; case et_sb_thumb: case et_sb_thumbrelease: newpos = sb->pos; break; } if ( newpos>grp->maxl-grp->page_width ) newpos = grp->maxl-grp->page_width; if ( newpos<0 ) newpos =0; if ( newpos!=grp->off_left ) { int diff = newpos-grp->off_left; grp->off_left = newpos; GScrollBarSetPos(grp->hsb,grp->off_left); GDrawScroll(grp->v,NULL,-diff,0); } } static void GroupResize(struct groupdlg *grp,GEvent *event) { GRect size, wsize; int lcnt, offy; int sbsize = GDrawPointsToPixels(grp->gw,_GScrollBar_Width); GDrawGetSize(grp->gw,&size); lcnt = (size.height-grp->bmargin)/grp->fh; GGadgetResize(grp->vsb,sbsize,lcnt*grp->fh); GGadgetMove(grp->vsb,size.width-sbsize,0); GGadgetResize(grp->hsb,size.width-sbsize,sbsize); GGadgetMove(grp->hsb,0,lcnt*grp->fh); GDrawResize(grp->v,size.width-sbsize,lcnt*grp->fh); grp->page_width = size.width-sbsize; grp->lines_page = lcnt; GScrollBarSetBounds(grp->vsb,0,grp->open_cnt,grp->lines_page); GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width); GGadgetGetSize(grp->cancel,&wsize); offy = size.height-wsize.height-6 - wsize.y; GGadgetMove(grp->cancel,size.width-wsize.width-30, wsize.y+offy); GGadgetMove(grp->ok , 30-3,wsize.y+offy-3); if ( grp->newsub!=NULL ) { GGadgetGetSize(grp->newsub,&wsize); GGadgetMove(grp->newsub,wsize.x,wsize.y+offy); GGadgetGetSize(grp->delete,&wsize); GGadgetMove(grp->delete,wsize.x,wsize.y+offy); GGadgetGetSize(grp->line1,&wsize); GGadgetMove(grp->line1,wsize.x,wsize.y+offy); GGadgetGetSize(grp->gpnamelab,&wsize); GGadgetMove(grp->gpnamelab,wsize.x,wsize.y+offy); GGadgetGetSize(grp->gpname,&wsize); GGadgetMove(grp->gpname,wsize.x,wsize.y+offy); GGadgetGetSize(grp->glyphslab,&wsize); GGadgetMove(grp->glyphslab,wsize.x,wsize.y+offy); GGadgetGetSize(grp->glyphs,&wsize); GGadgetMove(grp->glyphs,wsize.x,wsize.y+offy); GGadgetGetSize(grp->idlab,&wsize); GGadgetMove(grp->idlab,wsize.x,wsize.y+offy); GGadgetGetSize(grp->idname,&wsize); GGadgetMove(grp->idname,wsize.x,wsize.y+offy); GGadgetGetSize(grp->iduni,&wsize); GGadgetMove(grp->iduni,wsize.x,wsize.y+offy); GGadgetGetSize(grp->set,&wsize); GGadgetMove(grp->set,wsize.x,wsize.y+offy); GGadgetGetSize(grp->select,&wsize); GGadgetMove(grp->select,wsize.x,wsize.y+offy); GGadgetGetSize(grp->unique,&wsize); GGadgetMove(grp->unique,wsize.x,wsize.y+offy); GGadgetGetSize(grp->colour,&wsize); GGadgetMove(grp->colour,wsize.x,wsize.y+offy); GGadgetGetSize(grp->line2,&wsize); GGadgetMove(grp->line2,wsize.x,wsize.y+offy); } else { GGadgetGetSize(grp->compact,&wsize); GGadgetMove(grp->compact,wsize.x,wsize.y+offy); } GDrawRequestExpose(grp->v,NULL,true); GDrawRequestExpose(grp->gw,NULL,true); } static void GroupWChangeCurrent(struct groupdlg *grp,Group *current,Group *next ) { if ( current!=NULL ) current->selected = false; next->selected = true; if ( next->lpos<grp->off_top || next->lpos>=grp->off_top+grp->lines_page ) { if ( next->lpos>=grp->off_top+grp->lines_page ) grp->off_top = next->lpos; else { grp->off_top = next->lpos-grp->lines_page-1; if ( grp->off_top<0 ) grp->off_top = 0; } GScrollBarSetPos(grp->vsb,grp->off_top); GDrawRequestExpose(grp->v,NULL,false); } } static int GroupChar(struct groupdlg *grp,GEvent *event) { int depth = 0; int pos; Group *current = GroupCurrentlySelected(grp); switch (event->u.chr.keysym) { case GK_F1: case GK_Help: help("groups.html"); return( true ); case GK_Return: case GK_KP_Enter: if ( current!=NULL ) { current->open = !current->open; GroupSBSizes(grp); GDrawRequestExpose(grp->v,NULL,false); } return( true ); case GK_Page_Down: case GK_KP_Page_Down: pos = grp->off_top+(grp->lines_page<=1?1:grp->lines_page-1); if ( pos >= grp->open_cnt-grp->lines_page ) pos = grp->open_cnt-grp->lines_page; if ( pos<0 ) pos = 0; grp->off_top = pos; GScrollBarSetPos(grp->vsb,pos); GDrawRequestExpose(grp->v,NULL,false); return( true ); case GK_Down: case GK_KP_Down: if ( current==NULL || (event->u.chr.state&ksm_control)) { if ( grp->off_top<grp->open_cnt-1 ) { ++grp->off_top; GScrollBarSetPos(grp->vsb,grp->off_top); GDrawScroll(grp->v,NULL,0,grp->fh); } } else GroupWChangeCurrent(grp,current,GroupNext(current,&depth)); return( true ); case GK_Up: case GK_KP_Up: if ( current==NULL || (event->u.chr.state&ksm_control)) { if (grp->off_top!=0 ) { --grp->off_top; GScrollBarSetPos(grp->vsb,grp->off_top); GDrawScroll(grp->v,NULL,0,-grp->fh); } } else GroupWChangeCurrent(grp,current,GroupPrev(grp,current,&depth)); return( true ); case GK_Page_Up: case GK_KP_Page_Up: pos = grp->off_top-(grp->lines_page<=1?1:grp->lines_page-1); if ( pos<0 ) pos = 0; grp->off_top = pos; GScrollBarSetPos(grp->vsb,pos); GDrawRequestExpose(grp->v,NULL,false); return( true ); case GK_Left: case GK_KP_Left: if ( !grp->select_many && current!=NULL ) GroupWChangeCurrent(grp,current,current->parent); return( true ); case GK_Right: case GK_KP_Right: if ( !grp->select_many && current != NULL && current->kid_cnt!=0 ) { if ( !current->open ) { current->open = !current->open; GroupSBSizes(grp); } GroupWChangeCurrent(grp,current,current->kids[0]); } return( true ); case GK_Home: case GK_KP_Home: if ( grp->off_top!=0 ) { grp->off_top = 0; GScrollBarSetPos(grp->vsb,0); GDrawRequestExpose(grp->v,NULL,false); } if ( !grp->select_many ) GroupWChangeCurrent(grp,current,grp->root); return( true ); case GK_End: case GK_KP_End: pos = grp->open_cnt-grp->lines_page; if ( pos<0 ) pos = 0; if ( pos!=grp->off_top ) { grp->off_top = pos; GScrollBarSetPos(grp->vsb,pos); GDrawRequestExpose(grp->v,NULL,false); } if ( !grp->select_many ) GroupWChangeCurrent(grp,current,GroupFindLPos(grp->root,grp->open_cnt-1,&depth)); return( true ); } return( false ); } static int grpv_e_h(GWindow gw, GEvent *event) { struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw); if (( event->type==et_mouseup || event->type==et_mousedown ) && (event->u.mouse.button>=4 && event->u.mouse.button<=7) ) { return( GGadgetDispatchEvent(grp->vsb,event)); } switch ( event->type ) { case et_expose: GroupWExpose(grp,gw,&event->u.expose.rect); break; case et_char: return( GroupChar(grp,event)); case et_mouseup: GroupWMouse(grp,event); break; } return( true ); } static void GroupWCreate(struct groupdlg *grp,GRect *pos) { FontRequest rq; int as, ds, ld; GGadgetCreateData gcd[5]; GTextInfo label[4]; int sbsize = GDrawPointsToPixels(NULL,_GScrollBar_Width); GWindowAttrs wattrs; static GFont *font=NULL; if ( font==NULL ) { memset(&rq,'\0',sizeof(rq)); rq.utf8_family_name = SANS_UI_FAMILIES; rq.point_size = 12; rq.weight = 400; font = GDrawInstanciateFont(grp->gw,&rq); font = GResourceFindFont("Groups.Font",font); } grp->font = font; GDrawWindowFontMetrics(grp->gw,grp->font,&as,&ds,&ld); grp->fh = as+ds; grp->as = as; grp->lines_page = (pos->height-grp->bmargin)/grp->fh; grp->page_width = pos->width-sbsize; wattrs.mask = wam_events|wam_cursor/*|wam_bordwidth|wam_bordcol*/; wattrs.event_masks = ~0; wattrs.border_width = 1; wattrs.border_color = 0x000000; wattrs.cursor = ct_pointer; pos->x = 0; pos->y = 0; pos->width -= sbsize; pos->height = grp->lines_page*grp->fh; grp->v = GWidgetCreateSubWindow(grp->gw,pos,grpv_e_h,grp,&wattrs); GDrawSetVisible(grp->v,true); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); gcd[0].gd.pos.x = pos->width; gcd[0].gd.pos.y = 0; gcd[0].gd.pos.width = sbsize; gcd[0].gd.pos.height = pos->height; gcd[0].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels | gg_sb_vert; gcd[0].creator = GScrollBarCreate; gcd[1].gd.pos.x = 0; gcd[1].gd.pos.y = pos->height; gcd[1].gd.pos.height = sbsize; gcd[1].gd.pos.width = pos->width; gcd[1].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels; gcd[1].creator = GScrollBarCreate; GGadgetsCreate(grp->gw,gcd); grp->vsb = gcd[0].ret; grp->hsb = gcd[1].ret; } /******************************************************************************/ /******************************** Group Dialogs *******************************/ /******************************************************************************/ static int FindDuplicateNumberInString(int seek,char *str) { char *start; if ( str==NULL ) return( false ); while ( *str!='\0' ) { while ( *str==' ' ) ++str; start = str; while ( *str!=' ' && *str!='\0' ) ++str; if ( start==str ) break; if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) { char *end; int val = strtol(start+2,&end,16), val2=val; if ( *end=='-' ) { if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' ) end+=2; val2 = strtol(end+1,NULL,16); } if ( seek>=val && seek<=val2 ) return( true ); } } return( false ); } static int FindDuplicateNameInString(char *name,char *str) { char *start; if ( str==NULL ) return( false ); while ( *str!='\0' ) { while ( *str==' ' ) ++str; start = str; while ( *str!=' ' && *str!='\0' ) ++str; if ( start==str ) break; if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) /* Skip it */; else { int ch = *str; *str = '\0'; if ( strcmp(name,start)==0 ) { *str = ch; return( true ); } *str = ch; } } return( false ); } static Group *FindDuplicateNumber(Group *top,int val,Group *cur,char *str) { int i; Group *grp; if ( FindDuplicateNumberInString(val,str)) return( cur ); if ( top==cur ) return( NULL ); if ( FindDuplicateNumberInString(val,top->glyphs)) return( top ); for ( i=0; i<top->kid_cnt; ++i ) if ( (grp = FindDuplicateNumber(top->kids[i],val,cur,NULL))!=NULL ) return( grp ); return( NULL ); } static Group *FindDuplicateName(Group *top,char *name,Group *cur,char *str) { int i; Group *grp; if ( FindDuplicateNameInString(name,str)) return( cur ); if ( top==cur ) return( NULL ); if ( FindDuplicateNameInString(name,top->glyphs)) return( top ); for ( i=0; i<top->kid_cnt; ++i ) if ( (grp = FindDuplicateName(top->kids[i],name,cur,NULL))!=NULL ) return( grp ); return( NULL ); } static int GroupValidateGlyphs(Group *cur,char *g,const unichar_t *gu,int unique) { char *gpt, *start; Group *top, *grp; if ( gu!=NULL ) { for ( ; *gu!='\0'; ++gu ) { if ( *gu<' ' || *gu>=0x7f || *gu=='(' || *gu==')' || *gu=='[' || *gu==']' || *gu=='{' || *gu=='}' || *gu=='<' || *gu=='>' || *gu=='%' || *gu=='/' ) { ff_post_error(_("Glyph names must be valid postscript names"),_("Glyph names must be valid postscript names")); return( false ); } } } if ( unique ) { /* Can't use cur->unique because it hasn't been set yet */ top = cur; while ( top->parent!=NULL && top->parent->unique ) top = top->parent; for ( gpt=g; *gpt!='\0' ; ) { while ( *gpt==' ' ) ++gpt; start = gpt; while ( *gpt!=' ' && *gpt!='\0' ) ++gpt; if ( start==gpt ) break; if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) { char *end; int val = strtol(start+2,&end,16), val2=val; if ( *end=='-' ) { if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' ) end+=2; val2 = strtol(end+1,NULL,16); } if ( val2<val ) { ff_post_error(_("Bad Range"),_("Bad Range, start (%1$04X) is greater than end (%2$04X)"), val, val2 ); return( false ); } for ( ; val<=val2; ++val ) if ( (grp=FindDuplicateNumber(top,val,cur,gpt))!=NULL ) { ff_post_error(_("Duplicate Name"),_("The code point U+%1$04X occurs in groups %2$.30s and %3$.30s"), val, cur->name, grp->name); return( false ); } } else { int ch = *gpt; *gpt = '\0'; if ( (grp=FindDuplicateName(top,start,cur,ch!='\0'?gpt+1:NULL))!=NULL ) { ff_post_error(_("Duplicate Name"),_("The glyph name \"%1$.30s\" occurs in groups %2$.30s and %3$.30s"), start, cur->name, grp->name); *gpt = ch; return( false ); } *gpt = ch; } } } return( true ); } static int GroupSetKidsUnique(Group *group) { int i; group->unique = true; for ( i=0; i<group->kid_cnt; ++i ) if ( !GroupSetKidsUnique(group->kids[i])) return( false ); if ( group->glyphs!=NULL ) { if ( !GroupValidateGlyphs(group,group->glyphs,NULL,true)) return( false ); } return( true ); } static int GroupFinishOld(struct groupdlg *grp) { if ( grp->oldsel!=NULL ) { const unichar_t *gu = _GGadgetGetTitle(grp->glyphs); char *g = cu_copy(gu); int oldunique = grp->oldsel->unique; if ( !GroupValidateGlyphs(grp->oldsel,g,gu,GGadgetIsChecked(grp->unique))) { free(g); return( false ); } free(grp->oldsel->name); grp->oldsel->name = GGadgetGetTitle8(grp->gpname); free(grp->oldsel->glyphs); if ( *g=='\0' ) { grp->oldsel->glyphs = NULL; free(g); } else grp->oldsel->glyphs = g; grp->oldsel->unique = GGadgetIsChecked(grp->unique); if ( grp->oldsel->unique && !oldunique ) { /* The just set the unique bit. We must force it set in all */ /* kids. We really should check for uniqueness too!!!!! */ if ( !GroupSetKidsUnique(grp->oldsel)) return( false ); } } return( true ); } static void GroupSelected(struct groupdlg *grp) { Group *current = GroupCurrentlySelected(grp); if ( !GroupFinishOld(grp)) { if ( current!=NULL ) current->selected=false; if ( grp->oldsel!=NULL ) grp->oldsel->selected = true; return; } grp->oldsel = current; if ( current == NULL ) { GGadgetSetEnabled(grp->newsub,false); GGadgetSetEnabled(grp->delete,false); GGadgetSetEnabled(grp->gpnamelab,false); GGadgetSetEnabled(grp->gpname,false); GGadgetSetEnabled(grp->glyphslab,false); GGadgetSetEnabled(grp->glyphs,false); GGadgetSetEnabled(grp->set,false); GGadgetSetEnabled(grp->select,false); GGadgetSetEnabled(grp->unique,false); GGadgetSetEnabled(grp->colour,false); } else { unichar_t *glyphs = uc_copy(current->glyphs); GGadgetSetTitle8(grp->gpname,current->name); if ( glyphs==NULL ) glyphs = uc_copy(""); GGadgetSetTitle(grp->glyphs,glyphs); free(glyphs); GGadgetSetChecked(grp->unique,current->unique); GGadgetSetEnabled(grp->newsub,current->glyphs==NULL || *current->glyphs=='\0'); GGadgetSetEnabled(grp->delete,current->parent!=NULL); GGadgetSetEnabled(grp->gpnamelab,true); GGadgetSetEnabled(grp->gpname,true); GGadgetSetEnabled(grp->glyphslab,current->kid_cnt==0); GGadgetSetEnabled(grp->glyphs,current->kid_cnt==0); GGadgetSetEnabled(grp->set,current->kid_cnt==0); GGadgetSetEnabled(grp->select,current->kid_cnt==0); GGadgetSetEnabled(grp->unique,current->parent==NULL || !current->parent->unique); GGadgetSetEnabled(grp->colour,current->kid_cnt==0); } } static void GroupShowChange(struct groupdlg *grp) { if ( GroupFinishOld(grp)) GDrawRequestExpose(grp->v,NULL,false); grp->showchange = NULL; } static int Group_GlyphListChanged(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_textchanged ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); const unichar_t *glyphs = _GGadgetGetTitle(g); GGadgetSetEnabled(grp->newsub,*glyphs=='\0'); if ( grp->showchange!=NULL ) GDrawCancelTimer(grp->showchange); grp->showchange = GDrawRequestTimer(grp->gw,500,0,NULL); } return( true ); } static int Group_ToSelection(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); const unichar_t *ret = _GGadgetGetTitle(grp->glyphs); SplineFont *sf = grp->fv->b.sf; FontView *fv = grp->fv; const unichar_t *end; int pos, found=-1; char *nm; GDrawSetVisible(fv->gw,true); GDrawRaise(fv->gw); memset(fv->b.selected,0,fv->b.map->enccount); while ( *ret ) { end = u_strchr(ret,' '); if ( end==NULL ) end = ret+u_strlen(ret); nm = cu_copybetween(ret,end); for ( ret = end; isspace(*ret); ++ret); if ( (nm[0]=='U' || nm[0]=='u') && nm[1]=='+' ) { char *end; int val = strtol(nm+2,&end,16), val2=val; if ( *end=='-' ) { if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' ) end+=2; val2 = strtol(end+1,NULL,16); } for ( ; val<=val2; ++val ) { if (( pos = SFFindSlot(sf,fv->b.map,val,NULL))!=-1 ) { if ( found==-1 ) found = pos; if ( pos!=-1 ) fv->b.selected[pos] = true; } } } else if ( strncasecmp(nm,"color=#",strlen("color=#"))==0 ) { Color col = strtoul(nm+strlen("color=#"),NULL,16); int gid; SplineChar *sc; for ( pos=0; pos<fv->b.map->enccount; ++pos ) if ( (gid=fv->b.map->map[pos])!=-1 && (sc = sf->glyphs[gid])!=NULL && sc->color == col ) fv->b.selected[pos] = true; } else { if (( pos = SFFindSlot(sf,fv->b.map,-1,nm))!=-1 ) { if ( found==-1 ) found = pos; if ( pos!=-1 ) fv->b.selected[pos] = true; } } free(nm); } if ( found!=-1 ) FVScrollToChar(fv,found); GDrawRequestExpose(fv->v,NULL,false); } return( true ); } static int Group_FromSelection(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); SplineFont *sf = grp->fv->b.sf; FontView *fv = grp->fv; unichar_t *vals, *pt; int i, len, max, gid, k; SplineChar *sc, dummy; char buffer[20]; if ( GGadgetIsChecked(grp->idname) ) { for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) { gid = fv->b.map->map[i]; if ( gid!=-1 && sf->glyphs[gid]!=NULL ) sc = sf->glyphs[gid]; else sc = SCBuildDummy(&dummy,sf,fv->b.map,i); len += strlen(sc->name)+1; if ( fv->b.selected[i]>max ) max = fv->b.selected[i]; } pt = vals = galloc((len+1)*sizeof(unichar_t)); *pt = '\0'; for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) { gid = fv->b.map->map[i]; if ( gid!=-1 && sf->glyphs[gid]!=NULL ) sc = sf->glyphs[gid]; else sc = SCBuildDummy(&dummy,sf,fv->b.map,i); uc_strcpy(pt,sc->name); pt += u_strlen(pt); *pt++ = ' '; } if ( pt>vals ) pt[-1]='\0'; } else { vals = NULL; for ( k=0; k<2; ++k ) { int last=-2, start=-2; len = 0; for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) { gid = fv->b.map->map[i]; if ( gid!=-1 && sf->glyphs[gid]!=NULL ) sc = sf->glyphs[gid]; else sc = SCBuildDummy(&dummy,sf,fv->b.map,i); if ( sc->unicodeenc==-1 ) continue; if ( sc->unicodeenc==last+1 ) last = sc->unicodeenc; else { if ( last!=-2 ) { if ( start!=last ) sprintf( buffer, "U+%04X-U+%04X ", start, last ); else sprintf( buffer, "U+%04X ", start ); if ( vals!=NULL ) uc_strcpy(vals+len,buffer); len += strlen(buffer); } start = last = sc->unicodeenc; } } if ( last!=-2 ) { if ( start!=last ) sprintf( buffer, "U+%04X-U+%04X ", start, last ); else sprintf( buffer, "U+%04X ", start ); if ( vals!=NULL ) uc_strcpy(vals+len,buffer); len += strlen(buffer); } if ( !k ) vals = galloc((len+1)*sizeof(unichar_t)); else if ( len!=0 ) vals[len-1] = '\0'; else *vals = '\0'; } } GGadgetSetTitle(grp->glyphs,vals); free(vals); } return( true ); } static int Group_AddColor(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); GTextInfo *ti = GGadgetGetListItemSelected(g); int set=false; Color xcol=0; if ( ti==NULL ) /* Can't happen */; else if ( ti->userdata == (void *) COLOR_CHOOSE ) { struct hslrgb col, font_cols[6]; memset(&col,0,sizeof(col)); col = GWidgetColor(_("Pick a color"),&col,SFFontCols(grp->fv->b.sf,font_cols)); if ( col.rgb ) { xcol = (((int) rint(255.*col.r))<<16 ) | (((int) rint(255.*col.g))<<8 ) | (((int) rint(255.*col.b)) ); set = true; } } else { xcol = (intpt) ti->userdata; set = true; } if ( set ) { char buffer[40]; unichar_t ubuf[40]; sprintf(buffer," color=#%06x", xcol ); uc_strcpy(ubuf,buffer); GTextFieldReplace(grp->glyphs,ubuf); if ( grp->showchange==NULL ) GroupShowChange(grp); } GGadgetSelectOneListItem(g,0); } return( true ); } static int Group_NewSubGroup(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); Group *new_grp; if ( !GroupFinishOld(grp)) return( true ); GDrawRequestExpose(grp->v,NULL,false); if ( grp->oldsel==NULL ) return( true ); if ( grp->oldsel->glyphs!=NULL && grp->oldsel->glyphs!='\0' ) { GGadgetSetEnabled(grp->newsub,false); return( true ); } grp->oldsel->kids = grealloc(grp->oldsel->kids,(++grp->oldsel->kid_cnt)*sizeof(Group *)); grp->oldsel->kids[grp->oldsel->kid_cnt-1] = new_grp = chunkalloc(sizeof(Group)); new_grp->parent = grp->oldsel; new_grp->unique = grp->oldsel->unique; new_grp->name = copy(_("UntitledGroup")); grp->oldsel->selected = false; grp->oldsel->open = true; new_grp->selected = true; GroupSBSizes(grp); GroupSelected(grp); GDrawRequestExpose(grp->v,NULL,false); } return( true ); } static int Group_Delete(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g)); Group *parent; int pos, i; if ( grp->oldsel==NULL || grp->oldsel->parent==NULL ) return( true ); parent = grp->oldsel->parent; pos = GroupPosInParent(grp->oldsel); if ( pos==-1 ) return( true ); for ( i=pos; i<parent->kid_cnt-1; ++i ) parent->kids[i] = parent->kids[i+1]; --parent->kid_cnt; GroupFree(grp->oldsel); grp->oldsel = NULL; GroupSBSizes(grp); GroupSelected(grp); GDrawRequestExpose(grp->v,NULL,false); } return( true ); } static int displaygrp_e_h(GWindow gw, GEvent *event) { struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw); if (( event->type==et_mouseup || event->type==et_mousedown ) && (event->u.mouse.button>=4 && event->u.mouse.button<=7) ) { return( GGadgetDispatchEvent(grp->vsb,event)); } if ( grp==NULL ) return( true ); switch ( event->type ) { case et_expose: break; case et_char: return( GroupChar(grp,event)); break; case et_timer: GroupShowChange(grp); break; case et_resize: if ( event->u.resize.sized ) GroupResize(grp,event); break; case et_controlevent: switch ( event->u.control.subtype ) { case et_scrollbarchange: if ( event->u.control.g == grp->vsb ) GroupScroll(grp,&event->u.control.u.sb); else GroupHScroll(grp,&event->u.control.u.sb); break; case et_buttonactivate: grp->done = true; grp->oked = event->u.control.g == grp->ok; break; } break; case et_close: grp->done = true; break; case et_destroy: if ( grp->newsub!=NULL ) free(grp); return( true ); } if ( grp->done && grp->newsub!=NULL ) { if ( grp->oked ) { if ( !GroupFinishOld(grp)) { grp->done = grp->oked = false; return( true ); } GroupFree(group_root); if ( grp->root->kid_cnt==0 && grp->root->glyphs==NULL ) { group_root = NULL; GroupFree(grp->root); } else group_root = grp->root; SaveGroupList(); } else GroupFree(grp->root); GDrawDestroyWindow(grp->gw); } return( true ); } void DefineGroups(FontView *fv) { struct groupdlg *grp; GRect pos; GWindowAttrs wattrs; GGadgetCreateData gcd[20]; GTextInfo label[19]; int h, k,kk; grp = gcalloc(1,sizeof(*grp)); grp->fv = fv; grp->select_many = grp->select_kids_too = false; grp->select_callback = GroupSelected; if ( group_root==NULL ) { grp->root = chunkalloc(sizeof(Group)); grp->root->name = copy(_("Groups")); } else grp->root = GroupCopy(group_root); memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict; wattrs.event_masks = ~(1<<et_charup); wattrs.is_dlg = true; wattrs.restrict_input_to_me = false; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Define Groups"); pos.x = pos.y = 0; pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200)); pos.height = h = GDrawPointsToPixels(NULL,482); grp->gw = GDrawCreateTopWindow(NULL,&pos,displaygrp_e_h,grp,&wattrs); grp->bmargin = GDrawPointsToPixels(NULL,248)+GDrawPointsToPixels(grp->gw,_GScrollBar_Width); GroupWCreate(grp,&pos); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); k = 0; gcd[k].gd.pos.x = 20; gcd[k].gd.pos.y = GDrawPixelsToPoints(NULL,h-grp->bmargin)+12; gcd[k].gd.flags = gg_visible; label[k].text = (unichar_t *) _("New Sub-Group"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.handle_controlevent = Group_NewSubGroup; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.width = -1; gcd[k].gd.pos.x = GDrawPixelsToPoints(NULL,(pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor))); gcd[k].gd.pos.y = gcd[k-1].gd.pos.y; gcd[k].gd.flags = gg_visible; label[k].text = (unichar_t *) _("_Delete"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k].gd.handle_controlevent = Group_Delete; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k++].creator = GLineCreate; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+8; gcd[k].gd.flags = gg_visible; label[k].text = (unichar_t *) _("Group Name:"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k++].creator = GLabelCreate; gcd[k].gd.pos.x = 80; gcd[k].gd.pos.width = 115; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-3; gcd[k].gd.flags = gg_visible; gcd[k++].creator = GTextFieldCreate; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-2].gd.pos.y+16; gcd[k].gd.flags = gg_visible; label[k].text = (unichar_t *) _("Glyphs:"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k++].creator = GLabelCreate; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+14; gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-10; gcd[k].gd.pos.height = 4*13+4; gcd[k].gd.flags = gg_visible | gg_enabled | gg_textarea_wrap; gcd[k].gd.handle_controlevent = Group_GlyphListChanged; gcd[k++].creator = GTextAreaCreate; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+gcd[k-1].gd.pos.height+5; gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; label[k].text = (unichar_t *) _("Identify by"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired."); gcd[k++].creator = GLabelCreate; gcd[k].gd.pos.x = 90; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-2; label[k].text = (unichar_t *) _("Name"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = (gg_visible | gg_enabled | gg_cb_on | gg_utf8_popup); gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired."); gcd[k++].creator = GRadioCreate; gcd[k].gd.pos.x = 140; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y; label[k].text = (unichar_t *) _("Unicode"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired."); gcd[k++].creator = GRadioCreate; label[k].text = (unichar_t *) _("Set From Font"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+18; gcd[k].gd.popup_msg = (unichar_t *) _("Set this glyph list to be the glyphs selected in the fontview"); gcd[k].gd.flags = gg_visible | gg_utf8_popup; gcd[k].gd.handle_controlevent = Group_FromSelection; gcd[k++].creator = GButtonCreate; label[k].text = (unichar_t *) _("Select In Font"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 110; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y; gcd[k].gd.popup_msg = (unichar_t *) _("Set the fontview's selection to be the glyphs named here"); gcd[k].gd.flags = gg_visible | gg_utf8_popup; gcd[k].gd.handle_controlevent = Group_ToSelection; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26; label[k].text = (unichar_t *) _("No Glyph Duplicates"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible | gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Glyph names (or unicode code points) may occur at most once in this group and any of its sub-groups"); gcd[k++].creator = GCheckBoxCreate; for ( kk=0; kk<3; ++kk ) std_colors[kk].text = (unichar_t *) S_((char *) std_colors[kk].text); std_colors[1].image = GGadgetImageCache("colorwheel.png"); std_colors[0].selected = true; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+15; gcd[k].gd.label = &std_colors[0]; gcd[k].gd.u.list = std_colors; gcd[k].gd.handle_controlevent = Group_AddColor; gcd[k].gd.flags = gg_visible | gg_utf8_popup; gcd[k++].creator = GListButtonCreate; gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+28; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k++].creator = GLineCreate; gcd[k].gd.pos.width = -1; gcd[k].gd.pos.x = 30; gcd[k].gd.pos.y = h-GDrawPointsToPixels(NULL,32); gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels; label[k].text = (unichar_t *) _("_OK"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.width = -1; gcd[k].gd.pos.x = (pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor)); gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+3; gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels; label[k].text = (unichar_t *) _("_Cancel"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k++].creator = GButtonCreate; GGadgetsCreate(grp->gw,gcd); grp->newsub = gcd[0].ret; grp->delete = gcd[1].ret; grp->line1 = gcd[2].ret; grp->gpnamelab = gcd[3].ret; grp->gpname = gcd[4].ret; grp->glyphslab = gcd[5].ret; grp->glyphs = gcd[6].ret; grp->idlab = gcd[7].ret; grp->idname = gcd[8].ret; grp->iduni = gcd[9].ret; grp->set = gcd[10].ret; grp->select = gcd[11].ret; grp->unique = gcd[12].ret; grp->colour = gcd[13].ret; grp->line2 = gcd[14].ret; grp->ok = gcd[15].ret; grp->cancel = gcd[16].ret; GroupSBSizes(grp); GroupResize(grp,NULL); GDrawSetVisible(grp->gw,true); } static void MapEncAddGid(EncMap *map,SplineFont *sf, int compacted, int gid, int uni, char *name) { if ( compacted && gid==-1 ) return; if ( gid!=-1 && map->backmap[gid]==-1 ) map->backmap[gid] = map->enccount; if ( map->enccount>=map->encmax ) map->map = grealloc(map->map,(map->encmax+=100)*sizeof(int)); map->map[map->enccount++] = gid; if ( !compacted ) { Encoding *enc = map->enc; if ( enc->char_cnt>=enc->char_max ) { enc->unicode = grealloc(enc->unicode,(enc->char_max+=256)*sizeof(int)); enc->psnames = grealloc(enc->psnames,enc->char_max*sizeof(char *)); } if ( uni==-1 && name!=NULL ) { if ( gid!=-1 && sf->glyphs[gid]!=NULL ) uni = sf->glyphs[gid]->unicodeenc; else uni = UniFromName(name,ui_none,&custom); } enc->unicode[enc->char_cnt] = uni; enc->psnames[enc->char_cnt++] = copy( name ); } } static void MapAddGroupGlyph(EncMap *map,SplineFont *sf,char *name, int compacted) { int gid; if ( (name[0]=='u' || name[0]=='U') && name[1]=='+' && ishexdigit(name[2])) { char *end; int val = strtol(name+2,&end,16), val2=val; if ( *end=='-' ) { if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' ) end+=2; val2 = strtol(end+1,NULL,16); } for ( ; val<=val2; ++val ) { gid = SFFindExistingSlot(sf,val,NULL); MapEncAddGid(map,sf,compacted,gid,val,NULL); } } else if ( strncasecmp(name,"color=#",strlen("color=#"))==0 ) { Color col = strtoul(name+strlen("color=#"),NULL,16); int gid; SplineChar *sc; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc = sf->glyphs[gid])!=NULL && sc->color == col ) MapEncAddGid(map,sf,compacted,gid,sc->unicodeenc,NULL); } else { gid = SFFindExistingSlot(sf,-1,name); MapEncAddGid(map,sf,compacted,gid,-1,name); } } static int MapAddSelectedGroups(EncMap *map,SplineFont *sf,Group *group, int compacted) { int i, cnt=0; char *start, *pt; int ch; if ( group->glyphs==NULL ) { for ( i=0; i<group->kid_cnt; ++i ) cnt += MapAddSelectedGroups(map,sf,group->kids[i], compacted); } else if ( group->selected ) { for ( pt=group->glyphs; *pt!='\0'; ) { while ( *pt==' ' ) ++pt; start = pt; while ( *pt!=' ' && *pt!='\0' ) ++pt; ch = *pt; *pt='\0'; if ( *start!='\0' ) MapAddGroupGlyph(map,sf,start, compacted); *pt=ch; } ++cnt; } return( cnt ); } static int GroupSelCnt(Group *group, Group **first, Group **second) { int cnt = 0, i; if ( group->glyphs==NULL ) { for ( i=0; i<group->kid_cnt; ++i ) cnt += GroupSelCnt(group->kids[i],first,second); } else if ( group->selected ) { if ( *first==NULL ) *first = group; else if ( *second==NULL ) *second = group; ++cnt; } return( cnt ); } static char *EncNameFromGroups(Group *group) { Group *first = NULL, *second = NULL; int cnt = GroupSelCnt(group,&first,&second); char *prefix = P_("Group","Groups",cnt); char *ret; switch ( cnt ) { case 0: return( copy( _("No Groups")) ); case 1: ret = galloc(strlen(prefix) + strlen(first->name) + 3 ); sprintf( ret, "%s: %s", prefix, first->name); break; case 2: ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 5 ); sprintf( ret, "%s: %s, %s", prefix, first->name, second->name ); break; default: ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 9 ); sprintf( ret, "%s: %s, %s ...", prefix, first->name, second->name ); break; } return( ret ); } static void EncodeToGroups(FontView *fv,Group *group, int compacted) { SplineFont *sf = fv->b.sf; EncMap *map; if ( compacted ) map = EncMapNew(0,sf->glyphcnt,&custom); else { Encoding *enc = gcalloc(1,sizeof(Encoding)); enc->enc_name = EncNameFromGroups(group); enc->is_temporary = true; enc->char_max = 256; enc->unicode = galloc(256*sizeof(int32)); enc->psnames = galloc(256*sizeof(char *)); map = EncMapNew(0,sf->glyphcnt,enc); } if ( MapAddSelectedGroups(map,sf,group,compacted)==0 ) { ff_post_error(_("Nothing Selected"),_("Nothing Selected")); EncMapFree(map); } else if ( map->enccount==0 ) { ff_post_error(_("Nothing Selected"),_("None of the glyphs in the current font match any names or code points in the selected groups")); EncMapFree(map); } else { fv->b.selected = grealloc(fv->b.selected,map->enccount); memset(fv->b.selected,0,map->enccount); EncMapFree(fv->b.map); fv->b.map = map; FVSetTitle((FontViewBase *) fv); FontViewReformatOne((FontViewBase *) fv); } } void DisplayGroups(FontView *fv) { struct groupdlg grp; GRect pos; GWindowAttrs wattrs; GGadgetCreateData gcd[6]; GTextInfo label[5]; int h; memset( &grp,0,sizeof(grp)); grp.fv = fv; grp.select_many = grp.select_kids_too = true; grp.root = group_root; if ( grp.root==NULL ) { grp.root = chunkalloc(sizeof(Group)); grp.root->name = copy(_("Groups")); } memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict; wattrs.event_masks = ~(1<<et_charup); wattrs.is_dlg = true; wattrs.restrict_input_to_me = 1; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Display By Groups"); pos.x = pos.y = 0; pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200)); pos.height = h = GDrawPointsToPixels(NULL,317); grp.gw = GDrawCreateTopWindow(NULL,&pos,displaygrp_e_h,&grp,&wattrs); grp.bmargin = GDrawPointsToPixels(NULL,50)+GDrawPointsToPixels(grp.gw,_GScrollBar_Width); GroupWCreate(&grp,&pos); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); gcd[0].gd.pos.width = -1; gcd[0].gd.pos.x = 30; gcd[0].gd.pos.y = h-GDrawPointsToPixels(NULL,30); gcd[0].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels; label[0].text = (unichar_t *) _("_OK"); label[0].text_is_1byte = true; label[0].text_in_resource = true; gcd[0].gd.label = &label[0]; gcd[0].creator = GButtonCreate; gcd[1].gd.pos.width = -1; gcd[1].gd.pos.x = (pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor)); gcd[1].gd.pos.y = gcd[0].gd.pos.y+3; gcd[1].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels; label[1].text = (unichar_t *) _("_Cancel"); label[1].text_is_1byte = true; label[1].text_in_resource = true; gcd[1].gd.label = &label[1]; gcd[1].creator = GButtonCreate; gcd[2].gd.pos.width = -1; gcd[2].gd.pos.x = 10; gcd[2].gd.pos.y = gcd[0].gd.pos.y-GDrawPointsToPixels(NULL,17); gcd[2].gd.flags = gg_visible | gg_enabled | gg_cb_on | gg_pos_in_pixels; label[2].text = (unichar_t *) _("Compacted"); label[2].text_is_1byte = true; label[2].text_in_resource = true; gcd[2].gd.label = &label[2]; gcd[2].creator = GCheckBoxCreate; GGadgetsCreate(grp.gw,gcd); grp.ok = gcd[0].ret; grp.cancel = gcd[1].ret; grp.compact = gcd[2].ret; GroupSBSizes(&grp); GDrawSetVisible(grp.gw,true); while ( !grp.done ) GDrawProcessOneEvent(NULL); GDrawSetUserData(grp.gw,NULL); if ( grp.oked ) EncodeToGroups(fv,grp.root, GGadgetIsChecked(gcd[2].ret)); if ( grp.root!=group_root ) GroupFree(grp.root); GDrawDestroyWindow(grp.gw); }
rakeshyeka/PDFprocessor
pdf2htmlEX/fontforge-pdf2htmlEX/fontforgeexe/groupsdlg.c
C
gpl-3.0
50,023
import java.util.List; import java.util.LinkedList; import java.util.ArrayList; import java.util.Arrays; import java.io.File; import java.io.BufferedReader; import java.io.FileReader; import java.util.Scanner; import java.io.IOException; import java.io.FileNotFoundException; import java.lang.NumberFormatException; import java.util.Collections; public class FanMapMaker { private static class IntList extends ArrayList<Integer> {} private void printChargesArray(int[] distribution, int size) { int percent; System.out.println("temp2tcharge:"); for(int i = 0; i <= size; i++) { // retlw .248 ;31 PWM=97% percent = (100*i)/60; System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%"); } } private void printChargesArrayStatAll(int[] distribution, int size) { int percent; System.out.println("temp2tcharge_tab:"); for(int i = 0; i <= size; i++) { percent = (100*i)/size; System.out.println("\XORLW\t\t."+i+"\n"+ "\tBTFSC\t\tSTATUS,Z\n"+ "\tMOVLW\t\t."+distribution[percent]+"\t\t; [" + i + "] " + percent + "%\n" ); } System.out.println("\tGOTO\t\ttemp2tcharge_tab_end"); } private void printChargesArrayStatic(int[] distribution, int size) { int percent; String tmpRegName = "TMP0"; String endLabel = "temp2tcharge_tab_end"; System.out.println("temp2tcharge_tab:"); System.out.println("\tMOVLW\t\t.255\n\tMOVF\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\tnext1\n\tGOTO\t\t"+endLabel); for(int i = 1; i <= size; i++) { // retlw .248 ;31 PWM=97% percent = (100*i)/60; //System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%"); System.out.println("next"+i+":\n\tMOVLW\t\t."+ distribution[percent]+"\t\t; [" + i + "] " + percent + "%\n\tDECFSZ\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\t"+ ((i<size) ? "next"+(i+1) : endLabel) + "\n\tGOTO\t\t"+endLabel); } } public static void main(String[] a) { FanMapMaker fmp = new FanMapMaker(); IntList percentToCharge[] = new IntList[101]; int res[] = new int[101]; for(int i = 0; i < percentToCharge.length; i++) percentToCharge[i] = new IntList(); File decFile = new File("allDec.dat"); File incFile = new File("allInc.dat"); BufferedReader decReader = null; BufferedReader incReader = null; Integer tchrg; Integer fanPercx; Float sum; Float fanPerc; try { //decReader = new BufferedReader(new FileReader(decFile)); //incReader = new BufferedReader(new FileReader(incFile)); Scanner decScan = new Scanner(decFile); Scanner incScan = new Scanner(incFile); int cnt = 0; while (decScan.hasNext()) { tchrg = decScan.nextInt(); fanPerc = 0.0f; for(int i = 0; i < 3; i++) { fanPerc += decScan.nextFloat(); } fanPerc /= 3.0f; fanPercx = Math.round(fanPerc); percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat()) //System.out.println(tchrg + " " + fanPercx); } while (incScan.hasNext()) { tchrg = incScan.nextInt(); fanPerc = 0.0f; for(int i = 0; i < 3; i++) { fanPerc += incScan.nextFloat(); } fanPerc /= 3.0f; fanPercx = Math.round(fanPerc); percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat()) //System.out.println(tchrg + " " + fanPercx); } for (int i = 0; i < percentToCharge.length; i++) { Collections.sort(percentToCharge[i]); //System.out.print("" + i + " " + "["); for(Integer e: percentToCharge[i]) { //System.out.print(e + " "); } //System.out.println("]"); } int last = 1; for (int i = percentToCharge.length - 1; i >= 0; i--) { if(percentToCharge[i].size() > 0) { res[i] = percentToCharge[i].get(0); last = res[i]; } else { res[i] = last; } //System.out.println(i + " " + res[i]); } fmp.printChargesArrayStatAll(res, 50); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } finally { /*try { if (decReader != null) { //decReader.close(); } } //catch (IOException e) { //} try { if (incReader != null) { //incReader.close(); } } //catch (IOException e) { //} */ } } }
pworkshop/FanReg
tools/FanMapMaker.java
Java
gpl-3.0
4,595
# -*- coding: utf-8 -*- import os from pygal import * def listeEuler(f, x0, y0, pas, n): x, y, L = x0, y0, [] for k in range(n): L += [(x, y)] x += pas y += pas * f(x, y) return L def euler(f, x0, y0, xf, n): pas = (xf - x0) / n courbe = XY() courbe.title = "Methode d Euler" courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n)) courbe.render_to_file("courbeEulerPython.svg") os.system("pause")
NicovincX2/Python-3.5
Analyse (mathématiques)/Analyse fonctionnelle/Équation différentielle/euler.py
Python
gpl-3.0
468
vti_encoding:SR|utf8-nl vti_timelastmodified:TW|14 Aug 2014 12:39:17 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|Office-PC\\Rafael vti_modifiedby:SR|Office-PC\\Rafael vti_timecreated:TR|01 Nov 2014 09:09:36 -0000 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|14 Aug 2014 12:39:17 -0000 vti_cacheddtm:TX|03 Nov 2015 21:05:11 -0000 vti_filesize:IR|554 vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 12:39:17 -0000 vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:05:11 -0000
Vitronic/kaufreund.de
admin/language/english/openbay/_vti_cnf/amazonus_overview.php
PHP
gpl-3.0
753
## Water Model construction # # Creates and constructs the model with all demands. ## `config` must be defined before loading this file! include("world.jl") include("weather.jl") if get(config, "demandmodel", nothing) == "USGS" include("WaterDemand.jl") else include("Thermoelectric.jl") include("Livestock.jl") include("Agriculture.jl"); include("IrrigationAgriculture.jl"); include("UnivariateAgriculture.jl"); include("IndustrialDemand.jl"); include("UrbanDemand.jl"); include("WaterDemand.jl"); end ## Check if the optimize-surface script has been called storedresult = cached_fallback("extraction/withdrawals", () -> false) if storedresult == false @warn "Missing saved allocation files. Please run optimize-surface.jl" elseif size(storedresult)[1] != numcanals || size(storedresult)[3] != numsteps @warn "Cache file does not match current configuration. Please remove." end println("Creating model...") model = newmodel(); # Add all of the components if get(config, "demandmodel", nothing) != "USGS" thermoelectric = initthermoelectric(model); # exogenous livestock = initlivestock(model); # exogenous irrigationagriculture = initirrigationagriculture(model); # optimization-only univariateagriculture = initunivariateagriculture(model); # optimization-only agriculture = initagriculture(model); # optimization-only industrialdemand = initindustrialdemand(model); # exogenous urbandemand = initurbandemand(model); # exogenous end waterdemand = initwaterdemand(model); # dep. Agriculture, PopulationDemand # Connect up the components if get(config, "demandmodel", nothing) != "USGS" agriculture[:irrcropareas] = irrigationagriculture[:totalareas] agriculture[:irrcropproduction] = irrigationagriculture[:production] agriculture[:irrirrigation] = irrigationagriculture[:totalirrigation] agriculture[:unicropareas] = univariateagriculture[:totalareas2] agriculture[:unicropproduction] = univariateagriculture[:production] agriculture[:uniirrigation] = univariateagriculture[:totalirrigation] waterdemand[:totalirrigation] = agriculture[:allirrigation]; waterdemand[:thermoelectricuse] = thermoelectric[:demand_copy]; waterdemand[:livestockuse] = livestock[:demand_copy]; waterdemand[:urbanuse] = urbandemand[:waterdemand]; waterdemand[:industrialuse] = industrialdemand[:waterdemand]; end
AmericasWater/awash
src/model-waterdemand.jl
Julia
gpl-3.0
2,420
// Copyright © 2014, 2015, Travis Snoozy // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "cuisyntax.hpp" #include <boost/spirit/include/qi_parse.hpp> #include <cstdlib> #include <iostream> #include <iomanip> // Boost modules // Asio // Program Options namespace aha { namespace pawn { namespace testtool { std::ostream& operator<<(std::ostream& os, const aha::pawn::testtool::hex128_t& hex) { std::ios save(NULL); save.copyfmt(os); os << std::hex << std::setfill('0') << std::setw(8) << hex.byte1 << std::setw(8) << hex.byte2 << std::setw(8) << hex.byte3 << std::setw(8) << hex.byte4; os.copyfmt(save); return os; } std::ostream& operator<<(std::ostream& os, const aha::pawn::testtool::node_data_t& data) { std::ios save(NULL); save.copyfmt(os); os << std::setfill(' ') << std::left << std::setw(22) << "Key" << data.key << "\n" << std::setw(22) << "TX IV" << data.txiv << "\n" << std::setw(22) << "RX IV" << data.rxiv << "\n"; std::ios save2(NULL); save2.copyfmt(os); os << std::setw(22) << "Timeslot" << std::hex << std::setfill('0') << std::setw(4) << data.timeslot << "\n"; os.copyfmt(save2); os << std::setw(22) << "Timeslot enable" << data.enable_timeslot << "\n" << std::setw(22) << "TX encryption enable" << data.enable_tx_encryption << "\n" << std::setw(22) << "RX decryption enable" << data.enable_rx_decryption << "\n"; os.copyfmt(save); return os; } enum class option_visitor_result { SUCCESS, DOES_NOT_EXIST, ALREADY_EXISTS, INVALID_COMMAND, UNEXPECTED_DATA }; class option_visitor : public boost::static_visitor<option_visitor_result> { private: boost::spirit::qi::symbols<char, node_data_t> nodes; public: option_visitor_result operator()(const option_display_command_t& cmd) { nodes.for_each([](std::string& key, node_data_t& value){ std::cout << "Node " << key << "\n" << value << std::endl; }); return option_visitor_result::SUCCESS; } option_visitor_result operator()(const option_display_node_command_t& cmd) { node_data_t* node = nodes.find(cmd.node); if(node == NULL) { return option_visitor_result::DOES_NOT_EXIST; } std::cout << "Node " << cmd.node << "\n" << *node << std::endl; return option_visitor_result::SUCCESS; } option_visitor_result operator()(const option_set_node_command_t& cmd) { node_data_t* node = nodes.find(cmd.node); if(node == NULL) { return option_visitor_result::DOES_NOT_EXIST; } switch(cmd.param) { case option_set_node_param::KEY: node->key = boost::get<hex128_t>(cmd.data); break; case option_set_node_param::RXDECRYPT: node->enable_rx_decryption = boost::get<bool>(cmd.data); break; case option_set_node_param::RXIV: node->rxiv = boost::get<hex128_t>(cmd.data); break; case option_set_node_param::TIMESLOT: if(cmd.data.type() == typeid(bool)) { node->enable_timeslot = boost::get<bool>(cmd.data); } else if(cmd.data.type() == typeid(hex128_t)) { node->timeslot = (uint16_t)boost::get<hex128_t>(cmd.data).byte4; } else { return option_visitor_result::UNEXPECTED_DATA; } break; case option_set_node_param::TXENCRYPT: node->enable_tx_encryption = boost::get<bool>(cmd.data); break; case option_set_node_param::TXIV: node->txiv = boost::get<hex128_t>(cmd.data); break; default: return option_visitor_result::INVALID_COMMAND; } return option_visitor_result::SUCCESS; } option_visitor_result operator()(const option_create_node_command_t& cmd) { if(nodes.find(cmd.node) != NULL) { return option_visitor_result::ALREADY_EXISTS; } nodes.at(cmd.node); return option_visitor_result::SUCCESS; } option_visitor_result operator()(const transmit_command_t& cmd) { node_data_t* node = nodes.find(cmd.node); if(node == NULL) { return option_visitor_result::DOES_NOT_EXIST; } // TODO: Write this out to the designated serial port. return option_visitor_result::SUCCESS; } }; }}} using aha::pawn::testtool::option_visitor_result; int main(int argc, char** argv) { std::string input; std::string message; aha::pawn::testtool::command_t* command; std::string::const_iterator begin, end; aha::pawn::testtool::grammar::cui_grammar<std::string::const_iterator> grammar; std::getline(std::cin, input); aha::pawn::testtool::option_visitor option_visitor; while(input != "quit") { command = new aha::pawn::testtool::command_t(); begin = input.begin(); end = input.end(); bool result = boost::spirit::qi::phrase_parse( begin, end, grammar, boost::spirit::ascii::space, (*command)); if(result && begin == end) { switch(boost::apply_visitor(option_visitor, *command)) { case option_visitor_result::SUCCESS: std::cout << "OK."; break; case option_visitor_result::DOES_NOT_EXIST: std::cout << "Node does not exist."; break; case option_visitor_result::ALREADY_EXISTS: std::cout << "Node already exists."; break; case option_visitor_result::INVALID_COMMAND: case option_visitor_result::UNEXPECTED_DATA: std::cout << "An unexpected error occurred."; break; } std::cout << std::endl; } else { std::cout << "Could not parse that." << std::endl; } delete command; std::getline(std::cin, input); } return EXIT_SUCCESS; } // vim: set expandtab ts=4 sts=4 sw=4 fileencoding=utf-8:
Travis-Snoozy/AffordableHomeAutomation
c/pawn-testtool/main.cpp
C++
gpl-3.0
7,041