code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
using System; using System.IO; using Microsoft.Net.Http.Headers; namespace Slickflow.Designer.Controllers.WebApi { public static class MultipartRequestHelper { // Content-Type: multipart/form-data; boundary="----WebKitFormBoundarymx2fSWqWSd0OxQqq" // The spec says 70 characters is a reasonable limit. public static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit) { var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary); if (string.IsNullOrWhiteSpace(boundary.Value)) { throw new InvalidDataException("Missing Content type definition!"); } if (boundary.Length > lengthLimit) { throw new InvalidDataException( $"The length of file {lengthLimit} is too long!"); } return boundary.Value; } public static bool IsMultipartContentType(string contentType) { return !string.IsNullOrEmpty(contentType) && contentType.IndexOf("multipart/", StringComparison.OrdinalIgnoreCase) >= 0; } public static bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition) { // Content-Disposition: form-data; name="key"; return contentDisposition != null && contentDisposition.DispositionType.Equals("form-data") && string.IsNullOrEmpty(contentDisposition.FileName.Value) && string.IsNullOrEmpty(contentDisposition.FileNameStar.Value); } public static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition) { // Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg" return contentDisposition != null && contentDisposition.DispositionType.Equals("form-data") && (!string.IsNullOrEmpty(contentDisposition.FileName.Value) || !string.IsNullOrEmpty(contentDisposition.FileNameStar.Value)); } } }
besley/Slickflow
NETCORE/Slickflow/Source/Slickflow.Designer/Controllers/WebApi/MultipartRequestHelper.cs
C#
lgpl-3.0
2,150
const kevoree = require('kevoree-library'); const modelValidator = require('kevoree-validator'); const monkeyPatch = require('./util/monkey-patch'); // statements list const statements = { addRepo: require('./statements/addRepo'), add: require('./statements/add'), move: require('./statements/move'), attach: require('./statements/attach'), addBinding: require('./statements/addBinding'), delBinding: require('./statements/delBinding'), include: require('./statements/include'), set: require('./statements/set'), network: require('./statements/network'), remove: require('./statements/remove'), detach: require('./statements/detach'), namespace: require('./statements/namespace'), start: require('./statements/start'), stop: require('./statements/stop'), pause: require('./statements/pause'), }; // expressions list const expressions = { typeDef: require('./expressions/typeDef'), typeFQN: require('./expressions/typeFQN'), nameList: require('./expressions/nameList'), instancePath: require('./expressions/instancePath'), wildcard: require('./expressions/wildcard'), string: require('./expressions/string'), string2: require('./expressions/string2'), string3: require('./expressions/string3'), repoString: require('./expressions/repoString'), version: require('./expressions/version'), anything: require('./expressions/anything'), realString: require('./expressions/realString'), realStringNoNewLine: require('./expressions/realStringNoNewLine'), newLine: require('./expressions/newLine'), singleQuoteLine: require('./expressions/singleQuoteLine'), doubleQuoteLine: require('./expressions/doubleQuoteLine'), escaped: require('./expressions/escaped'), ctxVar: require('./expressions/ctxVar'), genCtxVar: require('./expressions/genCtxVar'), tdefVersion: require('./expressions/tdefVersion'), duVersion: require('./expressions/duVersion'), integer: require('./expressions/integer'), latest: require('./expressions/latest'), release: require('./expressions/release'), versionDecl: require('./expressions/versionDecl'), versionLine: require('./expressions/versionLine'), versionLines: require('./expressions/versionLines'), }; const factory = new kevoree.factory.DefaultKevoreeFactory(); const cloner = factory.createModelCloner(); /** * * @param ast * @param ctxModel * @param opts * @param callback * @constructor */ function interpreter(ast, ctxModel, opts) { // output model let model = null; if (ctxModel) { // if we have a context model, clone it and use it has a base model = cloner.clone(ctxModel, false); } else { // otherwise start from a brand new model model = factory.createContainerRoot(); } // this ContainerRoot is the root of the model factory.root(model); opts.warnings = []; opts.identifiers = []; return Promise.resolve() .then(() => { // create commands based on interpreted statements & expressions const commands = []; ast.children.forEach((child0) => { child0.children.forEach((stmt) => { if (typeof (statements[stmt.type]) === 'function') { commands.push(() => { return statements[stmt.type](model, expressions, stmt, opts); }); } else { throw new Error('Unknown statement "' + stmt.type + '"'); } }); }); return commands; }) .then((commands) => { // execute commands sequentially return commands.reduce((prev, next) => { return prev.then(next); }, Promise.resolve()); }) .then(() => { // commands executed successfully => validate output model return new Promise((resolve) => { modelValidator(model); resolve(); }) .then(() => { // model is valid => return return { error: null, model: model, warnings: opts.warnings, }; }) .catch((err) => { // model is not valid // try to find instance position for ModelValidationError ast.children .map((stmt) => { return stmt.children[0]; }) .filter((stmt) => { return stmt.type === 'add'; }) .some((addStmt) => { const instancePos = addStmt.instances[err.path]; if (instancePos) { err.pos = instancePos; return true; } return false; }); return { error: err, model: null, warnings: opts.warnings, }; }) .then((result) => { // whether it is valid or not => monkey patch model monkeyPatch(model); return result; }); }, (err) => { return { error: err, model: null, warnings: opts.warnings, }; }); } module.exports = interpreter;
kevoree/kevoree-js
tools/kevoree-kevscript/lib/interpreter.js
JavaScript
lgpl-3.0
4,996
package org.concord.qm2d.model; /** * @author Charles Xie * */ public class PointSource extends Source { private float sigma = 1; public PointSource(float xcenter, float ycenter, int nx, int ny, float xmin, float xmax, float ymin, float ymax) { super(nx, ny, xmin, xmax, ymin, ymax); setLocation(xcenter, ycenter); } public void setSigma(float sigma) { this.sigma = sigma; } public float getSigma() { return sigma; } public boolean contains(float x, float y) { float size = 0.02f * Math.max(xmax - xmin, ymax - ymin); float a = (x - xcenter) / size; float b = (y - ycenter) / size; return a * a + b * b <= 1; } @Override public String toXml() { String xml = "<point period=\"" + period; xml += "\" amplitude=\"" + amplitude; xml += "\" sigma=\"" + sigma; xml += "\" xcenter=\"" + xcenter; xml += "\" ycenter=\"" + ycenter; xml += "\" px=\"" + px; xml += "\" py=\"" + py; if (!isVisible()) xml += "\" visible=\"false"; if (!isDraggable()) xml += "\" draggable=\"false"; xml += "\"/>\n"; return xml; } @Override public String toString() { return toXml(); } }
charxie/quantumworkbench
src/org/concord/qm2d/model/PointSource.java
Java
lgpl-3.0
1,131
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Copyright © 2014 Tekla Corporation. Tekla is a Trimble Company"> // Copyright (C) 2013 [Jorge Costa, Jorge.Costa@tekla.com] // </copyright> // -------------------------------------------------------------------------------------------------------------------- // This program 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 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 Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SqaleEditor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("jmecsoftware.com")] [assembly: AssemblyProduct("SqaleEditor")] [assembly: AssemblyCopyright("Copyright © 2015 jmecsoftware.com")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("6.0.0.0")] [assembly: AssemblyFileVersion("6.0.0.0")]
jmecsoftware/QualityProfileEditorPlugin
SqaleEditor/Properties/AssemblyInfo.cs
C#
lgpl-3.0
3,594
/* * Metadata functions for the Python object definition of the libvmdk handle * * Copyright (C) 2009-2016, Joachim Metz <joachim.metz@gmail.com> * * Refer to AUTHORS for acknowledgements. * * This software 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 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 Lesser General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ #include <common.h> #include <types.h> #include "pyvmdk_error.h" #include "pyvmdk_extent_descriptor.h" #include "pyvmdk_extent_descriptors.h" #include "pyvmdk_handle.h" #include "pyvmdk_integer.h" #include "pyvmdk_libcerror.h" #include "pyvmdk_libvmdk.h" #include "pyvmdk_python.h" #include "pyvmdk_unused.h" /* Retrieves the disk type * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_disk_type( pyvmdk_handle_t *pyvmdk_handle, PyObject *arguments PYVMDK_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; PyObject *integer_object = NULL; static char *function = "pyvmdk_handle_get_disk_type"; int result = 0; int disk_type = 0; PYVMDK_UNREFERENCED_PARAMETER( arguments ) if( pyvmdk_handle == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid handle.", function ); return( NULL ); } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_disk_type( pyvmdk_handle->handle, &disk_type, &error ); Py_END_ALLOW_THREADS if( result != 1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: unable to retrieve disk type.", function ); libcerror_error_free( &error ); return( NULL ); } #if PY_MAJOR_VERSION >= 3 integer_object = PyLong_FromLong( (long) disk_type ); #else integer_object = PyInt_FromLong( (long) disk_type ); #endif return( integer_object ); } /* Retrieves the media size * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_media_size( pyvmdk_handle_t *pyvmdk_handle, PyObject *arguments PYVMDK_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; PyObject *integer_object = NULL; static char *function = "pyvmdk_handle_get_media_size"; size64_t media_size = 0; int result = 0; PYVMDK_UNREFERENCED_PARAMETER( arguments ) if( pyvmdk_handle == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid handle.", function ); return( NULL ); } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_media_size( pyvmdk_handle->handle, &media_size, &error ); Py_END_ALLOW_THREADS if( result != 1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: failed to retrieve media size.", function ); libcerror_error_free( &error ); return( NULL ); } integer_object = pyvmdk_integer_unsigned_new_from_64bit( (uint64_t) media_size ); return( integer_object ); } /* Retrieves the content identifier * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_content_identifier( pyvmdk_handle_t *pyvmdk_handle, PyObject *arguments PYVMDK_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; PyObject *integer_object = NULL; static char *function = "pyvmdk_handle_get_content_identifier"; uint32_t content_identifier = 0; int result = 0; PYVMDK_UNREFERENCED_PARAMETER( arguments ) if( pyvmdk_handle == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid handle.", function ); return( NULL ); } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_content_identifier( pyvmdk_handle->handle, &content_identifier, &error ); Py_END_ALLOW_THREADS if( result != 1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: unable to retrieve content identifier.", function ); libcerror_error_free( &error ); return( NULL ); } integer_object = pyvmdk_integer_unsigned_new_from_64bit( content_identifier ); return( integer_object ); } /* Retrieves the parent content identifier * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_parent_content_identifier( pyvmdk_handle_t *pyvmdk_handle, PyObject *arguments PYVMDK_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; PyObject *integer_object = NULL; static char *function = "pyvmdk_handle_get_parent_content_identifier"; uint32_t parent_content_identifier = 0; int result = 0; PYVMDK_UNREFERENCED_PARAMETER( arguments ) if( pyvmdk_handle == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid handle.", function ); return( NULL ); } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_parent_content_identifier( pyvmdk_handle->handle, &parent_content_identifier, &error ); Py_END_ALLOW_THREADS if( result != 1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: unable to retrieve parent content identifier.", function ); libcerror_error_free( &error ); return( NULL ); } integer_object = pyvmdk_integer_unsigned_new_from_64bit( parent_content_identifier ); return( integer_object ); } /* Retrieves the parent filename * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_parent_filename( pyvmdk_handle_t *pyvmdk_handle, PyObject *arguments PYVMDK_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; PyObject *string_object = NULL; const char *errors = NULL; uint8_t *parent_filename = NULL; static char *function = "pyvmdk_handle_get_parent_filename"; size_t parent_filename_size = 0; int result = 0; PYVMDK_UNREFERENCED_PARAMETER( arguments ) if( pyvmdk_handle == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid handle.", function ); return( NULL ); } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_utf8_parent_filename_size( pyvmdk_handle->handle, &parent_filename_size, &error ); Py_END_ALLOW_THREADS if( result == -1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: unable to retrieve parent filename size.", function ); libcerror_error_free( &error ); goto on_error; } else if( ( result == 0 ) || ( parent_filename_size == 0 ) ) { Py_IncRef( Py_None ); return( Py_None ); } parent_filename = (uint8_t *) PyMem_Malloc( sizeof( uint8_t ) * parent_filename_size ); if( parent_filename == NULL ) { PyErr_Format( PyExc_IOError, "%s: unable to create parent filename.", function ); goto on_error; } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_utf8_parent_filename( pyvmdk_handle->handle, parent_filename, parent_filename_size, &error ); Py_END_ALLOW_THREADS if( result != 1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: unable to retrieve parent filename.", function ); libcerror_error_free( &error ); goto on_error; } /* Pass the string length to PyUnicode_DecodeUTF8 * otherwise it makes the end of string character is part * of the string */ string_object = PyUnicode_DecodeUTF8( (char *) parent_filename, (Py_ssize_t) parent_filename_size - 1, errors ); PyMem_Free( parent_filename ); return( string_object ); on_error: if( parent_filename != NULL ) { PyMem_Free( parent_filename ); } return( NULL ); } /* Retrieves the number of extents * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_number_of_extents( pyvmdk_handle_t *pyvmdk_handle, PyObject *arguments PYVMDK_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; PyObject *integer_object = NULL; static char *function = "pyvmdk_handle_get_number_of_extents"; int number_of_extents = 0; int result = 0; PYVMDK_UNREFERENCED_PARAMETER( arguments ) if( pyvmdk_handle == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid handle.", function ); return( NULL ); } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_number_of_extents( pyvmdk_handle->handle, &number_of_extents, &error ); Py_END_ALLOW_THREADS if( result != 1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: unable to retrieve number of extents.", function ); libcerror_error_free( &error ); return( NULL ); } #if PY_MAJOR_VERSION >= 3 integer_object = PyLong_FromLong( (long) number_of_extents ); #else integer_object = PyInt_FromLong( (long) number_of_extents ); #endif return( integer_object ); } /* Retrieves a specific extent descriptor by index * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_extent_descriptor_by_index( pyvmdk_handle_t *pyvmdk_handle, int extent_index ) { libcerror_error_t *error = NULL; libvmdk_extent_descriptor_t *extent_descriptor = NULL; PyObject *extent_descriptor_object = NULL; static char *function = "pyvmdk_handle_get_extent_descriptor_by_index"; int result = 0; if( pyvmdk_handle == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid handle.", function ); return( NULL ); } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_extent_descriptor( pyvmdk_handle->handle, extent_index, &extent_descriptor, &error ); Py_END_ALLOW_THREADS if( result != 1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: unable to retrieve extent: %d descriptor.", function, extent_index ); libcerror_error_free( &error ); goto on_error; } extent_descriptor_object = pyvmdk_extent_descriptor_new( extent_descriptor, pyvmdk_handle ); if( extent_descriptor_object == NULL ) { PyErr_Format( PyExc_MemoryError, "%s: unable to create extent descriptor object.", function ); goto on_error; } return( extent_descriptor_object ); on_error: if( extent_descriptor != NULL ) { libvmdk_extent_descriptor_free( &extent_descriptor, NULL ); } return( NULL ); } /* Retrieves a specific extent descriptor * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_extent_descriptor( pyvmdk_handle_t *pyvmdk_handle, PyObject *arguments, PyObject *keywords ) { PyObject *extent_descriptor_object = NULL; static char *keyword_list[] = { "extent_index", NULL }; int extent_index = 0; if( PyArg_ParseTupleAndKeywords( arguments, keywords, "i", keyword_list, &extent_index ) == 0 ) { return( NULL ); } extent_descriptor_object = pyvmdk_handle_get_extent_descriptor_by_index( pyvmdk_handle, extent_index ); return( extent_descriptor_object ); } /* Retrieves an extent descriptors sequence and iterator object for the extent descriptors * Returns a Python object if successful or NULL on error */ PyObject *pyvmdk_handle_get_extent_descriptors( pyvmdk_handle_t *pyvmdk_handle, PyObject *arguments PYVMDK_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; PyObject *extent_descriptors_object = NULL; static char *function = "pyvmdk_handle_get_extent_descriptors"; int number_of_extent_descriptors = 0; int result = 0; PYVMDK_UNREFERENCED_PARAMETER( arguments ) if( pyvmdk_handle == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid handle.", function ); return( NULL ); } Py_BEGIN_ALLOW_THREADS result = libvmdk_handle_get_number_of_extents( pyvmdk_handle->handle, &number_of_extent_descriptors, &error ); Py_END_ALLOW_THREADS if( result != 1 ) { pyvmdk_error_raise( error, PyExc_IOError, "%s: unable to retrieve number of extents.", function ); libcerror_error_free( &error ); return( NULL ); } extent_descriptors_object = pyvmdk_extent_descriptors_new( pyvmdk_handle, &pyvmdk_handle_get_extent_descriptor_by_index, number_of_extent_descriptors ); if( extent_descriptors_object == NULL ) { PyErr_Format( PyExc_MemoryError, "%s: unable to create extent descriptors object.", function ); return( NULL ); } return( extent_descriptors_object ); }
uckelman/libvmdk
pyvmdk/pyvmdk_metadata.c
C
lgpl-3.0
13,299
/* * Copyright (C) 2008 Universidade Federal de Campina Grande * * This file is part of OurGrid. * * OurGrid 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 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.ourgrid.peer.ui.async.gui.actions; import java.awt.Frame; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JDialog; import org.ourgrid.peer.ui.async.gui.AddUserDialog; /** * It represents an Action to add a new peer user. */ public class AddBrokerAction extends AbstractAction { private Frame frame; private JDialog addUserDialog; /** Creates new form AddPeerUserAction */ public AddBrokerAction(Frame frame) { super("Add broker"); this.frame = frame; } /** * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { addUserDialog = new AddUserDialog(frame, true); addUserDialog.setVisible(true); } }
OurGrid/OurGrid
src/main/java/org/ourgrid/peer/ui/async/gui/actions/AddBrokerAction.java
Java
lgpl-3.0
1,576
#include <stdio.h> #include <stdlib.h> #include <assert.h> extern int base64encode(const void* data_buf, size_t dataLength, char* result, size_t resultSize); extern int base64decode(char *in, size_t inLen, unsigned char *out, size_t *outLen); int main(int argc, char *argv[]) { return 0; }
NaMorham/QUT-Tutoring-1-C
Base64/main.c
C
lgpl-3.0
297
package game.handle; import agents.Vacuum; public class VacuumHandle extends AgentHandle { public VacuumHandle(Vacuum agent) { super(agent); } public static VacuumHandle createVacuum() { return new VacuumHandle(new Vacuum()); } @Override public long getTimeRemaining() { return 1; } @Override public void setTimeRemaining(long seconds) { } @Override public boolean isDisqualified() { return agent.isDead(); } @Override public boolean isPlayer() { return false; } }
istvanszoke/softlab4
src/main/game/handle/VacuumHandle.java
Java
lgpl-3.0
572
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Thu Dec 13 08:48:04 PST 2012 --> <TITLE> SegmentNode (JTS Topology Suite version 1.13) </TITLE> <META NAME="keywords" CONTENT="com.vividsolutions.jts.noding.SegmentNode class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="SegmentNode (JTS Topology Suite version 1.13)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> JTS Topology Suite version 1.13</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../com/vividsolutions/jts/noding/SegmentIntersector.html" title="interface in com.vividsolutions.jts.noding"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../com/vividsolutions/jts/noding/SegmentNodeList.html" title="class in com.vividsolutions.jts.noding"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?com/vividsolutions/jts/noding/SegmentNode.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SegmentNode.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> com.vividsolutions.jts.noding</FONT> <BR> Class SegmentNode</H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>com.vividsolutions.jts.noding.SegmentNode</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>java.lang.Comparable</DD> </DL> <HR> <DL> <DT><PRE>public class <B>SegmentNode</B><DT>extends java.lang.Object<DT>implements java.lang.Comparable</DL> </PRE> <P> Represents an intersection point between two <A HREF="../../../../com/vividsolutions/jts/noding/SegmentString.html" title="interface in com.vividsolutions.jts.noding"><CODE>SegmentString</CODE></A>s. <P> <P> <DL> <DT><B>Version:</B></DT> <DD>1.7</DD> </DL> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../com/vividsolutions/jts/geom/Coordinate.html" title="class in com.vividsolutions.jts.geom">Coordinate</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../com/vividsolutions/jts/noding/SegmentNode.html#coord">coord</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../com/vividsolutions/jts/noding/SegmentNode.html#segmentIndex">segmentIndex</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../com/vividsolutions/jts/noding/SegmentNode.html#SegmentNode(com.vividsolutions.jts.noding.NodedSegmentString, com.vividsolutions.jts.geom.Coordinate, int, int)">SegmentNode</A></B>(<A HREF="../../../../com/vividsolutions/jts/noding/NodedSegmentString.html" title="class in com.vividsolutions.jts.noding">NodedSegmentString</A>&nbsp;segString, <A HREF="../../../../com/vividsolutions/jts/geom/Coordinate.html" title="class in com.vividsolutions.jts.geom">Coordinate</A>&nbsp;coord, int&nbsp;segmentIndex, int&nbsp;segmentOctant)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../com/vividsolutions/jts/noding/SegmentNode.html#compareTo(java.lang.Object)">compareTo</A></B>(java.lang.Object&nbsp;obj)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../com/vividsolutions/jts/geom/Coordinate.html" title="class in com.vividsolutions.jts.geom">Coordinate</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../com/vividsolutions/jts/noding/SegmentNode.html#getCoordinate()">getCoordinate</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets the <A HREF="../../../../com/vividsolutions/jts/geom/Coordinate.html" title="class in com.vividsolutions.jts.geom"><CODE>Coordinate</CODE></A> giving the location of this node.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../com/vividsolutions/jts/noding/SegmentNode.html#isEndPoint(int)">isEndPoint</A></B>(int&nbsp;maxSegmentIndex)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../com/vividsolutions/jts/noding/SegmentNode.html#isInterior()">isInterior</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../com/vividsolutions/jts/noding/SegmentNode.html#print(java.io.PrintStream)">print</A></B>(java.io.PrintStream&nbsp;out)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="coord"><!-- --></A><H3> coord</H3> <PRE> public final <A HREF="../../../../com/vividsolutions/jts/geom/Coordinate.html" title="class in com.vividsolutions.jts.geom">Coordinate</A> <B>coord</B></PRE> <DL> <DL> </DL> </DL> <HR> <A NAME="segmentIndex"><!-- --></A><H3> segmentIndex</H3> <PRE> public final int <B>segmentIndex</B></PRE> <DL> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="SegmentNode(com.vividsolutions.jts.noding.NodedSegmentString, com.vividsolutions.jts.geom.Coordinate, int, int)"><!-- --></A><H3> SegmentNode</H3> <PRE> public <B>SegmentNode</B>(<A HREF="../../../../com/vividsolutions/jts/noding/NodedSegmentString.html" title="class in com.vividsolutions.jts.noding">NodedSegmentString</A>&nbsp;segString, <A HREF="../../../../com/vividsolutions/jts/geom/Coordinate.html" title="class in com.vividsolutions.jts.geom">Coordinate</A>&nbsp;coord, int&nbsp;segmentIndex, int&nbsp;segmentOctant)</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getCoordinate()"><!-- --></A><H3> getCoordinate</H3> <PRE> public <A HREF="../../../../com/vividsolutions/jts/geom/Coordinate.html" title="class in com.vividsolutions.jts.geom">Coordinate</A> <B>getCoordinate</B>()</PRE> <DL> <DD>Gets the <A HREF="../../../../com/vividsolutions/jts/geom/Coordinate.html" title="class in com.vividsolutions.jts.geom"><CODE>Coordinate</CODE></A> giving the location of this node. <P> <DD><DL> </DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>the coordinate of the node</DL> </DD> </DL> <HR> <A NAME="isInterior()"><!-- --></A><H3> isInterior</H3> <PRE> public boolean <B>isInterior</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="isEndPoint(int)"><!-- --></A><H3> isEndPoint</H3> <PRE> public boolean <B>isEndPoint</B>(int&nbsp;maxSegmentIndex)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="compareTo(java.lang.Object)"><!-- --></A><H3> compareTo</H3> <PRE> public int <B>compareTo</B>(java.lang.Object&nbsp;obj)</PRE> <DL> <DD><DL> <DT><B>Specified by:</B><DD><CODE>compareTo</CODE> in interface <CODE>java.lang.Comparable</CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>-1 this SegmentNode is located before the argument location; 0 this SegmentNode is at the argument location; 1 this SegmentNode is located after the argument location</DL> </DD> </DL> <HR> <A NAME="print(java.io.PrintStream)"><!-- --></A><H3> print</H3> <PRE> public void <B>print</B>(java.io.PrintStream&nbsp;out)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> JTS Topology Suite version 1.13</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../com/vividsolutions/jts/noding/SegmentIntersector.html" title="interface in com.vividsolutions.jts.noding"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../com/vividsolutions/jts/noding/SegmentNodeList.html" title="class in com.vividsolutions.jts.noding"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?com/vividsolutions/jts/noding/SegmentNode.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SegmentNode.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
ace-design/island
external/jts-1.13/com/vividsolutions/jts/noding/SegmentNode.html
HTML
lgpl-3.0
16,482
var assert = require('assert'); var path = false; var path2 = false; // Normal switch var test = "B"; switch (test) { case "A": assert(false); break; case "B": path = true; break; default: assert(false); } assert(path) // Strict equality in switch test path = false; var test2 = 0; switch (test2) { case "0": assert(false); break; default: path = true; } assert(path); // Empty switch switch (test) {} // Switch without default var test3 = "A" path = false; switch (test3) { case "A": path = true; break; case "B": assert(false); break; } assert(path); // value not handled var test4 = "Z"; switch (test4) { case "A": assert(false); break; } // Switch with default only path = false; switch (test) { default: path = true; } assert(path) // Break in default path = false; switch (test) { default: path = true; break; } assert(path) // Case whihout break; var test5 = "A"; path = false; switch (test5) { case "A": case "B": path = true; break; } assert(path) // Default placed first var test6 = "B"; path = false; switch (test6) { default: assert(false); case "A": assert(false); break; case "B": path = true; break; } assert(path); // More complex expression as test var test7 = 21 path = false; switch (test7) { case (function () { return 42; })(): assert(false); break; case (function () { return 21; })(): path = true; break default: assert(false); } assert(path); // Bonus var test8 = "C" path = false; path2 = false; switch (test8) { case "A": assert(false); default: path = true; case "B": path2 = true; } assert(path && path2); var test9 = "B"; path = false; path2 = false; switch (test9) { case "A": assert(false); case "B": path = true; default: path2 = true; } assert(path && path2); var test10 = "B"; path = false; switch (test10) { default: assert(false); case "A": assert(false); case "B": path = true; } assert(path); var test11 = "B"; path = false; switch (test11) { default: assert(false); case "A": assert(false); case "B": path = true; break; } assert(path); var i = 3; var a = []; while(i){ switch(i--){ case 3: a.push(3); break; case 2: a.push(2); break; case 1: a.push(1); break; } } assert(a.length === 3); assert(a[0] === 3); assert(a[1] === 2); assert(a[2] === 1);
PaulBernier/castl
test/switch.js
JavaScript
lgpl-3.0
2,489
set(CCOS_CMAKECONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/CMakeConfig) ################################################################################ # Setup default installation targets for a project ################################################################################ macro(CcOSSetInstall ProjectName ) install( TARGETS ${ProjectName} EXPORT "${ProjectName}Config" RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib/static PUBLIC_HEADER DESTINATION include/${ProjectName} ) endmacro() ################################################################################ # Add Xml Configurations to cmake install ################################################################################ macro (CcOSSetInstallConfig ProjectName ) install( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/config/ DESTINATION config/${ProjectName} PATTERN "*.xml" ) endmacro() ################################################################################ # Set Cmake Version Info to Project ################################################################################ macro (CcSetOSVersion ProjectName ) set_target_properties( ${ProjectName} PROPERTIES VERSION ${CCOS_VERSION_CMAKE} SOVERSION ${CCOS_VERSION_CMAKE}) endmacro() ################################################################################ # Setup Include Directorys for importing CcOS ################################################################################ macro( CcOSTargetIncludeDirs ProjectName ) foreach(DIR ${ARGN}) list(APPEND DIRS ${DIR} ) target_include_directories(${ProjectName} PUBLIC $<BUILD_INTERFACE:${DIR}> ) endforeach() target_include_directories( ${ProjectName} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}> $<INSTALL_INTERFACE:$<INSTALL_PREFIX>/include/${ProjectName}> ) endmacro() ################################################################################ # Generate RC-File for MSVC Builds, output is a Version.h File in current dir # usage: CcOSGenerateRcFileToCurrentDir( ProjectName [SourceFiles] ) ################################################################################ macro( CcOSGenerateRcFileToCurrentDir ProjectName ) set(PROJECT_NAME "${ProjectName}") configure_file( ${CCOS_CMAKECONFIG_DIR}/InputFiles/ProjectVersion.rc.in ${CMAKE_CURRENT_BINARY_DIR}/${ProjectName}_Version.rc.tmp @ONLY) CcMoveFile(${CMAKE_CURRENT_BINARY_DIR}/${ProjectName}_Version.rc.tmp ${CMAKE_CURRENT_BINARY_DIR}/${ProjectName}_Version.rc) if(${ARGC} GREATER 1) if(NOT DEFINED GCC) list(APPEND ${ARGV1} "${CMAKE_CURRENT_BINARY_DIR}/${ProjectName}_Version.rc") endif() endif(${ARGC} GREATER 1) endmacro() ################################################################################ # Rename Endings of Project output file to CcOS default. # CURRENTLY NOT IN USE!! ################################################################################ macro( CcOSProjectNaming ProjectName ) set_target_properties(${ProjectName} PROPERTIES OUTPUT_NAME "${ProjectName}" ) # Debug becomes and d at the end. set_target_properties(${ProjectName} PROPERTIES OUTPUT_NAME_DEBUG "${ProjectName}d" ) endmacro() ################################################################################ # Set Version info for library. # If Linux, set SOVERSION too. ################################################################################ macro( CcOSLibVersion ProjectName ) set_target_properties(${ProjectName} PROPERTIES VERSION ${CCOS_VERSION_CMAKE}) if(LINUX) set_target_properties(${ProjectName} PROPERTIES SOVERSION ${CCOS_VERSION_CMAKE} ) endif(LINUX) endmacro() ################################################################################ # Post config Steps afert CcAddLibrary: # Usage CcOSLibSettings( ProjectName [bSetupInstall] [bSetupVersion] [sSetFiltersByFolders]) ################################################################################ macro( CcOSLibSettings ProjectName ) if(${ARGC} GREATER 1) if(${ARGV1} STREQUAL "TRUE") CcOSSetInstall(${ProjectName}) endif(${ARGV1} STREQUAL "TRUE") endif(${ARGC} GREATER 1) if(${ARGC} GREATER 2) if(${ARGV2} STREQUAL "TRUE") CcOSLibVersion(${ProjectName}) endif(${ARGV2} STREQUAL "TRUE") endif(${ARGC} GREATER 2) if(${ARGC} GREATER 3) set(FILES ${ARGN}) list(REMOVE_AT FILES 0) list(REMOVE_AT FILES 0) list(REMOVE_AT FILES 0) CcSetFiltersByFolders(${FILES}) endif(${ARGC} GREATER 3) endmacro() ################################################################################ # Post config Steps afert add_executable: # Usage CcOSExeSettings( ProjectName [sSetFiltersByFolders]) ################################################################################ macro( CcOSExeSettings ProjectName ) if(${ARGC} GREATER 1) set(FILES ${ARGN}) CcSetFiltersByFolders(${FILES}) endif(${ARGC} GREATER 1) endmacro()
AndyD87/CcOS
CMakeConfig/ProjectMacros.cmake
CMake
lgpl-3.0
5,236
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import org.sonar.api.utils.text.JsonWriter; import org.sonar.server.platform.db.migration.DatabaseMigrationState; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.RUNNING; public class DbMigrationJsonWriter { static final String FIELD_STATE = "state"; static final String FIELD_MESSAGE = "message"; static final String FIELD_STARTED_AT = "startedAt"; static final String STATUS_NO_MIGRATION = "NO_MIGRATION"; static final String STATUS_NOT_SUPPORTED = "NOT_SUPPORTED"; static final String STATUS_MIGRATION_RUNNING = "MIGRATION_RUNNING"; static final String STATUS_MIGRATION_FAILED = "MIGRATION_FAILED"; static final String STATUS_MIGRATION_SUCCEEDED = "MIGRATION_SUCCEEDED"; static final String STATUS_MIGRATION_REQUIRED = "MIGRATION_REQUIRED"; static final String NO_CONNECTION_TO_DB = "Cannot connect to Database."; static final String UNSUPPORTED_DATABASE_MIGRATION_STATUS = "Unsupported DatabaseMigration status"; static final String MESSAGE_NO_MIGRATION_ON_EMBEDDED_DATABASE = "Upgrade is not supported on embedded database."; static final String MESSAGE_MIGRATION_REQUIRED = "Database migration is required. DB migration can be started using WS /api/system/migrate_db."; static final String MESSAGE_STATUS_NONE = "Database is up-to-date, no migration needed."; static final String MESSAGE_STATUS_RUNNING = "Database migration is running."; static final String MESSAGE_STATUS_SUCCEEDED = "Migration succeeded."; static final String MESSAGE_STATUS_FAILED = "Migration failed: %s.<br/> Please check logs."; private DbMigrationJsonWriter() { // static methods only } static void write(JsonWriter json, DatabaseMigrationState databaseMigrationState) { json.beginObject() .prop(FIELD_STATE, statusToJson(databaseMigrationState.getStatus())) .prop(FIELD_MESSAGE, buildMessage(databaseMigrationState)) .propDateTime(FIELD_STARTED_AT, databaseMigrationState.getStartedAt()) .endObject(); } static void writeNotSupportedResponse(JsonWriter json) { json.beginObject() .prop(FIELD_STATE, STATUS_NOT_SUPPORTED) .prop(FIELD_MESSAGE, MESSAGE_NO_MIGRATION_ON_EMBEDDED_DATABASE) .endObject(); } static void writeJustStartedResponse(JsonWriter json, DatabaseMigrationState databaseMigrationState) { json.beginObject() .prop(FIELD_STATE, statusToJson(RUNNING)) .prop(FIELD_MESSAGE, MESSAGE_STATUS_RUNNING) .propDateTime(FIELD_STARTED_AT, databaseMigrationState.getStartedAt()) .endObject(); } static void writeMigrationRequiredResponse(JsonWriter json) { json.beginObject() .prop(FIELD_STATE, STATUS_MIGRATION_REQUIRED) .prop(FIELD_MESSAGE, MESSAGE_MIGRATION_REQUIRED) .endObject(); } private static String statusToJson(DatabaseMigrationState.Status status) { switch (status) { case NONE: return STATUS_NO_MIGRATION; case RUNNING: return STATUS_MIGRATION_RUNNING; case FAILED: return STATUS_MIGRATION_FAILED; case SUCCEEDED: return STATUS_MIGRATION_SUCCEEDED; default: throw new IllegalArgumentException( "Unsupported DatabaseMigration.Status " + status + " can not be converted to JSON value"); } } private static String buildMessage(DatabaseMigrationState databaseMigrationState) { switch (databaseMigrationState.getStatus()) { case NONE: return MESSAGE_STATUS_NONE; case RUNNING: return MESSAGE_STATUS_RUNNING; case SUCCEEDED: return MESSAGE_STATUS_SUCCEEDED; case FAILED: return String.format(MESSAGE_STATUS_FAILED, failureMessage(databaseMigrationState)); default: return UNSUPPORTED_DATABASE_MIGRATION_STATUS; } } private static String failureMessage(DatabaseMigrationState databaseMigrationState) { Throwable failureError = databaseMigrationState.getError(); if (failureError == null) { return "No failure error"; } return failureError.getMessage(); } static String statusDescription() { return "State values are:" + "<ul>" + "<li>NO_MIGRATION: DB is up to date with current version of SonarQube.</li>" + "<li>NOT_SUPPORTED: Migration is not supported on embedded databases.</li>" + "<li>MIGRATION_RUNNING: DB migration is under go.</li>" + "<li>MIGRATION_SUCCEEDED: DB migration has run and has been successful.</li>" + "<li>MIGRATION_FAILED: DB migration has run and failed. SonarQube must be restarted in order to retry a " + "DB migration (optionally after DB has been restored from backup).</li>" + "<li>MIGRATION_REQUIRED: DB migration is required.</li>" + "</ul>"; } }
Godin/sonar
server/sonar-server/src/main/java/org/sonar/server/platform/ws/DbMigrationJsonWriter.java
Java
lgpl-3.0
5,619
import pytest from forte.solvers import solver_factory, HF def test_df_rhf(): """Test DF-RHF on HF.""" ref_energy = -100.04775218911111 # define a molecule xyz = """ H 0.0 0.0 0.0 F 0.0 0.0 1.0 """ # create a molecular model input = solver_factory(molecule=xyz, basis='cc-pVTZ', int_type='df') # specify the electronic state state = input.state(charge=0, multiplicity=1, sym='a1') # create a HF object and run hf = HF(input, state=state) hf.run() assert hf.value('hf energy') == pytest.approx(ref_energy, 1.0e-10) def test_df_rhf_select_aux(): """Test DF-RHF on HF.""" ref_energy = -100.04775602524956 # define a molecule xyz = """ H 0.0 0.0 0.0 F 0.0 0.0 1.0 """ # create a molecular model input = solver_factory(molecule=xyz, int_type='df', basis='cc-pVTZ', scf_aux_basis='cc-pVQZ-JKFIT') # specify the electronic state state = input.state(charge=0, multiplicity=1, sym='a1') # create a HF object and run hf = HF(input, state=state) hf.run() assert hf.value('hf energy') == pytest.approx(ref_energy, 1.0e-10) if __name__ == "__main__": test_df_rhf() test_df_rhf_select_aux()
evangelistalab/forte
tests/pytest/hf/test_df_hf.py
Python
lgpl-3.0
1,224
<?php /** * The MetaModels extension allows the creation of multiple collections of custom items, * each with its own unique set of selectable attributes, with attribute extendability. * The Front-End modules allow you to build powerful listing and filtering of the * data in each collection. * * PHP version 5 * * @package MetaModels * @subpackage Core * @author Christian Schiffler <c.schiffler@cyberspectrum.de> * @copyright The MetaModels team. * @license LGPL. * @filesource */ namespace MetaModels\BackendIntegration; use MetaModels\IMetaModelsServiceContainer; use MetaModels\BackendIntegration\InputScreen\IInputScreen; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use MetaModels\Helper\ToolboxFile; use ContaoCommunityAlliance\Contao\Bindings\Events\Image\ResizeImageEvent; use ContaoCommunityAlliance\Contao\Bindings\ContaoEvents; /** * This class builds the backend module list and is responsible for creating the backend menu array for Contao. */ class BackendModuleBuilder { /** * The service container. * * @var IMetaModelsServiceContainer */ protected $container; /** * The view combinations. * * @var ViewCombinations */ protected $viewCombinations; /** * The contents of the backend menu to be set. * * @var array */ protected $backendMenu = array(); /** * The language strings for the modules. * * @var array */ protected $languageStrings = array(); /** * Create a new instance. * * @param IMetaModelsServiceContainer $container The service container. * * @param ViewCombinations $viewCombinations The view combinations. */ public function __construct(IMetaModelsServiceContainer $container, ViewCombinations $viewCombinations) { $this->container = $container; $this->viewCombinations = $viewCombinations; if (!$this->loadFromCache()) { $this->resolve(); $this->saveToCache(); } } /** * Try to load the combinations from cache. * * @return bool */ protected function loadFromCache() { $key = $this->calculateCacheKey(); if (!$this->container->getCache()->contains($key)) { return false; } // Perform loading now. $data = json_decode($this->container->getCache()->fetch($key), true); if (empty($data)) { return false; } $this->backendMenu = $data['backendMenu']; $this->languageStrings = $data['languageStrings']; return true; } /** * Try to load the combinations from cache. * * @return bool */ protected function saveToCache() { // Pretty print only came available with php 5.4. $flags = 0; if (defined('JSON_PRETTY_PRINT')) { $flags = JSON_PRETTY_PRINT; } return $this->container->getCache()->save( $this->calculateCacheKey(), json_encode( array( 'backendMenu' => $this->backendMenu, 'languageStrings' => $this->languageStrings, ), $flags ) ); } /** * Calculate the cache key to use. * * @return string * * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ protected function calculateCacheKey() { // Determine cache key. $key = sprintf( 'backend_menu_%s_%s_%s', strtolower(TL_MODE), $this->viewCombinations->getUser()->id ?: 'anonymous', $GLOBALS['TL_LANGUAGE'] ); return $key; } /** * Retrieve the event dispatcher. * * @return EventDispatcherInterface */ protected function getEventDispatcher() { return $this->container->getEventDispatcher(); } /** * Build a 16x16 sized representation of the passed icon if it exists or fallback to the default icon otherwise. * * @param string $icon The path to the icon (relative to TL_ROOT). * * @return string The path to the generated icon. */ protected function buildIcon($icon) { // Determine image to use. if ($icon && file_exists(TL_ROOT . '/' . $icon)) { $event = new ResizeImageEvent($icon, 16, 16); $this->getEventDispatcher()->dispatch(ContaoEvents::IMAGE_RESIZE, $event); return $event->getResultImage(); } return 'system/modules/metamodels/assets/images/icons/metamodels.png'; } /** * Handle stand alone integration in the backend. * * @param IInputScreen $inputScreen The input screen containing the information. * * @return void */ private function addModuleToBackendMenu($inputScreen) { $metaModel = $inputScreen->getMetaModel(); $moduleName = 'metamodel_' . $metaModel->getTableName(); $tableCaption = $metaModel->getName(); $icon = $this->buildIcon(ToolboxFile::convertValueToPath($inputScreen->getIcon())); $section = $inputScreen->getBackendSection(); if (!$section) { $section = 'metamodels'; } $this->backendMenu[$section][$moduleName] = array ( 'tables' => array($metaModel->getTableName()), 'icon' => $icon, 'callback' => 'MetaModels\BackendIntegration\Module' ); $caption = array($tableCaption); foreach ($inputScreen->getBackendCaption() as $languageEntry) { if ($languageEntry['langcode'] == 'en') { $caption = array($languageEntry['label'], $languageEntry['description']); } if (!empty($languageEntry['label']) && ($languageEntry['langcode'] == $this->viewCombinations->getUser()->language) ) { $caption = array($languageEntry['label'], $languageEntry['description']); break; } } $this->languageStrings['MOD'][$moduleName] = $caption; } /** * Inject all meta models into their corresponding parent tables. * * @param string[] $parentTables The names of the MetaModels for which input screens are to be added. * * @return void * * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ private function addChildTablesToBackendModules($parentTables) { $localMenu = array_replace_recursive($GLOBALS['BE_MOD'], $this->backendMenu); $lastCount = count($parentTables); // Loop until all tables are injected or until there was no injection during one run. // This is important, as we might have models that are child of another model. while ($parentTables) { foreach ($parentTables as $parentTable => $childTables) { foreach ($localMenu as $groupName => $modules) { foreach ($modules as $moduleName => $moduleConfiguration) { if ( isset($moduleConfiguration['tables']) && in_array($parentTable, $moduleConfiguration['tables']) ) { // First put them into our private list. $this->backendMenu[$groupName][$moduleName]['tables'] = array_merge( $localMenu[$groupName][$moduleName]['tables'], $childTables ); // And now buffer them in the backend menu copy to be able to resolve. $localMenu[$groupName][$moduleName]['tables'] = array_merge( $localMenu[$groupName][$moduleName]['tables'], $this->backendMenu[$groupName][$moduleName]['tables'] ); unset($parentTables[$parentTable]); break; } } } } // If the dependencies can not be resolved any further, we give up here. if (count($parentTables) == $lastCount) { break; } $lastCount = count($parentTables); } } /** * Retrieve the table names from a list of input screens. * * @param string[] $metaModelNames The names of the MetaModels for which input screens are to be added. * * @return string[] */ private function getTableNamesFromInputScreens($metaModelNames) { $parentTables = array(); foreach ($metaModelNames as $metaModelName) { $parentTable = $this->viewCombinations->getParentOf($metaModelName); $parentTables[$parentTable][] = $metaModelName; } return $parentTables; } /** * Inject MetaModels in the backend menu. * * @return void */ private function resolve() { foreach ($this->viewCombinations->getStandaloneInputScreens() as $inputScreen) { $this->addModuleToBackendMenu($inputScreen); } $parentTables = $this->getTableNamesFromInputScreens( $this->viewCombinations->getParentedInputScreenNames() ); $this->addChildTablesToBackendModules($parentTables); } /** * Set the local data into the GLOBALS config. * * @return void * * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ public function export() { // Do not replace the array. See #684. foreach ($this->backendMenu as $section => $entries) { if (!isset($GLOBALS['BE_MOD'][$section])) { $GLOBALS['BE_MOD'][$section] = array(); } $GLOBALS['BE_MOD'][$section] = array_merge_recursive($entries, $GLOBALS['BE_MOD'][$section]); } $GLOBALS['TL_LANG'] = array_merge_recursive($this->languageStrings, $GLOBALS['TL_LANG']); } }
designs2/core
src/MetaModels/BackendIntegration/BackendModuleBuilder.php
PHP
lgpl-3.0
10,334
<?php /** * This file is part of PhpCocktail. PhpCocktail 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. * PhpCocktail 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 PhpCocktail. * If not, see <http://www.gnu.org/licenses/>. * @copyright Copyright 2013 t */ namespace Cocktail; /** * I am used to produce nicer output by eg. indenting blocks properly or compacting. Set * @author t * @package Cocktail\Beautify * @version 1.01 */ class Beautify { /** * @var int content returned as-is. Being the fasted, this is recommended for production */ const MODE_NONE = 0; /** * @var int somewhat compacts the output, however, may be necessary for readability, othervise deprecated. Breaks * text inside <pre> as well. */ const MODE_COMPACT = 1; /** * @var int adjust indenting to the specified level, remove unnecessary newlines */ const MODE_BEAUTIFUL = 2; /** * @var int as MODE_BEAUTIFUL but ensures there is a newline at the beginning and at the end of the content. Usually * this mode ensure maximum readability */ const MODE_BEAUTIFUL_NEWLINES = 128; /** * @var int as in constants, will be fetched from config .Beautify.mode if is null and getMode() is called */ protected static $_mode = null; /** * I return current mode. If null, set it from conf * @return int */ static public function getMode() { if (is_null(self::$_mode)) { self::$_mode = \Camarera::conf('Beautify.mode'); } return self::$_mode; } /** * I set global mode * @param int $mode * @throws \InvalidArgumentException */ static public function setMode($mode) { if (!in_array($mode, array(0, 1, 2, 128, 129, 130), true)) { throw new \InvalidArgumentException(); }; static::$_mode = $mode; } /** * I am a shortcut to beauty() * @param mixed $content * @param int $tabCount * @param int $mode * @see beauty() */ static function b($content, $tabCount=0, $mode=null) { return static::beauty($content, $tabCount, $mode); } /** * I beautify content. Note content will be casted to string unless $mode is MODE_NONE * @param mixed $content anything that can be echo'ed (string, number, object with __toString() method) * @param int $tabCount adjust main tabbing to this level * @param int $mode mode to use, null to use global setting * @return string the processed string */ static function beauty($content, $tabCount=0, $mode=null) { if (is_null($mode)) { $mode = static::$_mode; } if ($mode == self::MODE_NONE) { return $content; } $content = \Util::toString($content); switch ($mode) { case self::MODE_BEAUTIFUL_NEWLINES: case self::MODE_BEAUTIFUL: $ensureNewlines = $mode == self::MODE_BEAUTIFUL_NEWLINES; // remove base indent level, first find out how many tabs to remove if (preg_match('/^\t+/', $content, $matches)) { $inTabCount = strlen($matches[0]); for ($offset=0; $offset=strpos($content, "\n", $offset+1); ) { // continue on empty line if (!isset($content[$offset+1])) { break; } elseif ($content[$offset+1]=="\n") { continue; } for ($i=$offset; ($i==$offset) || (($i<strlen($content)) && ($content[$i]== "\t")); $i++); $inTabCount = min($inTabCount, $i - $offset-1); } $content = str_replace("\n" . str_repeat("\t", $inTabCount), "\n", $content); $content = substr($content, $inTabCount); } // get rid of double newlines $content = preg_replace('/\n(\s)*\n/', "\n", $content); // now do the indenting, it is attached to ensure newlines // ensure beginning newline if necessary if ($ensureNewlines && (substr($content, 0) != "\n")) { $content = "\n" . $content; } // do actual indenting if ($tabCount) { $content = str_replace("\n", "\n" . str_repeat("\t", $tabCount), $content); if (substr($content, -($tabCount+1)) == "\n" . str_repeat("\t", $tabCount)) { $content = substr($content, 0, -$tabCount); } } // ensure ending newline if necessary if ($ensureNewlines && (substr($content, -1) != "\n")) { $content.= "\n"; }; break; case self::MODE_COMPACT: $content = str_replace("\t", " ", $content); while (strpos($content, " ") !== false) { $content = str_replace(" ", " ", $content); } $content = str_replace("\n ", "\n", $content); while (strpos($content, "\n\n") !== false) { $content = str_replace("\n\n", "\n", $content); } break; case self::MODE_NONE: default: break; } return $content; } /** * I strip of head comment of php file * @param $content * @param string $mode * @return mixed */ static function stripHeadComment($content, $mode='php') { if (preg_match('/^(<\?(php)?\s*\/\*\*.+?\*\/)(.+)$/s', $content, $matches)) { return ltrim($matches[3]); } return $content; } }
phpcocktail/cocktail
src/Cocktail/Beautify/Beautify.class.php
PHP
lgpl-3.0
5,342
package eu.europa.echa.iuclid6.namespaces.endpoint_study_record_repeateddosetoxicityother._2; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.PicklistField; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.PicklistFieldWithSmallTextRemarks; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.RepeatableEntryType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="Qualifier" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="Guideline" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="VersionRemarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="Deviation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "qualifier", "guideline", "versionRemarks", "deviation" }) public class GuidelineEntry extends RepeatableEntryType { @XmlElement(name = "Qualifier", required = true) protected PicklistField qualifier; @XmlElement(name = "Guideline", required = true) protected PicklistField guideline; @XmlElement(name = "VersionRemarks", required = true) protected String versionRemarks; @XmlElement(name = "Deviation", required = true) protected PicklistFieldWithSmallTextRemarks deviation; /** * Gets the value of the qualifier property. * * @return * possible object is * {@link PicklistField } * */ public PicklistField getQualifier() { return qualifier; } /** * Sets the value of the qualifier property. * * @param value * allowed object is * {@link PicklistField } * */ public void setQualifier(PicklistField value) { this.qualifier = value; } /** * Gets the value of the guideline property. * * @return * possible object is * {@link PicklistField } * */ public PicklistField getGuideline() { return guideline; } /** * Sets the value of the guideline property. * * @param value * allowed object is * {@link PicklistField } * */ public void setGuideline(PicklistField value) { this.guideline = value; } /** * Gets the value of the versionRemarks property. * * @return * possible object is * {@link String } * */ public String getVersionRemarks() { return versionRemarks; } /** * Sets the value of the versionRemarks property. * * @param value * allowed object is * {@link String } * */ public void setVersionRemarks(String value) { this.versionRemarks = value; } /** * Gets the value of the deviation property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getDeviation() { return deviation; } /** * Sets the value of the deviation property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setDeviation(PicklistFieldWithSmallTextRemarks value) { this.deviation = value; } }
ideaconsult/i5
iuclid_6_2-io/src/main/java/eu/europa/echa/iuclid6/namespaces/endpoint_study_record_repeateddosetoxicityother/_2/GuidelineEntry.java
Java
lgpl-3.0
4,194
using System; namespace SharpPcap.WinpkFilter { /// <summary> /// Used to set the adapter flags. /// </summary> [Flags] public enum AdapterModes : uint { /// <summary> /// No flags. /// </summary> None = 0x00000000, /// <summary> /// Receive packets sent by MSTCP to network interface. /// The original packet is dropped. /// </summary> SentTunnel = 0x00000001, /// <summary> /// Receive packets sent from network interface to MSTCP. /// The original packet is dropped. /// </summary> RecvTunnel = 0x00000002, /// <summary> /// Receive packets sent from and to MSTCP and network interface. /// The original packet is dropped. /// </summary> Tunnel = SentTunnel | RecvTunnel, /// <summary> /// Receive packets sent by MSTCP to network interface. /// The original packet is still delivered to the network. /// </summary> SentListen = 0x00000004, /// <summary> /// Receive packets sent from network interface to MSTCP /// The original packet is still delivered to the network. /// </summary> RecvListen = 0x00000008, /// <summary> /// Receive packets sent from and to MSTCP and network interface. /// The original packet is dropped. /// </summary> Listen = SentListen | RecvListen, /// <summary> /// In promiscuous mode TCP/IP stack receives all. /// </summary> FilterDirect = 0x00000010, /// <summary> /// Passes loopback packet for processing. /// </summary> LoopbackFilter = 0x00000020, /// <summary> /// Silently drop loopback packets. /// </summary> LoopbackBlock = 0x00000040 } }
chmorgan/sharppcap
SharpPcap/WinpkFilter/AdapterModes.cs
C#
lgpl-3.0
1,892
#include <QtGui/QApplication> #include <QTextCodec> #include "keyboard.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextCodec::setCodecForTr( QTextCodec::codecForName("GB2312") ); //ÔÚÒÆÖ²Ê±¿ÉÄܳöÏÖ±àÂëÎÊÌâ keyboard w; w.show(); return a.exec(); }
newdebug/NewDebug
Qt/KuInput/main.cpp
C++
lgpl-3.0
294
/* QEPushButton.cpp * * This file is part of the EPICS QT Framework, initially developed at the * Australian Synchrotron. * * Copyright (c) 2009-2021 Australian Synchrotron * * The EPICS QT Framework 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. * * The EPICS QT Framework is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the EPICS QT Framework. If not, see <http://www.gnu.org/licenses/>. * * Author: * Andrew Rhyder * Contact details: * andrew.rhyder@synchrotron.org.au */ /* This class is a CA aware push button widget based on the Qt push button widget. It is tighly integrated with the base class QEWidget. Refer to QEWidget.cpp for details */ #include <QEPushButton.h> #include <QProcess> #include <QMessageBox> #include <QMainWindow> #include <QIcon> /* Constructor with no initialisation */ QEPushButton::QEPushButton( QWidget *parent ) : QPushButton( parent ), QEGenericButton( this ) { QEGenericButton::setup(); setup(); } /* Constructor with known variable */ QEPushButton::QEPushButton( const QString &variableNameIn, QWidget *parent ) : QPushButton( parent ), QEGenericButton( this ) { setVariableName( variableNameIn, 0 ); QEGenericButton::setup(); setup(); activate(); } /* Setup common to all constructors */ void QEPushButton::setup() { // Create second single variable methods object for the alt readback PV. // altReadback = new QESingleVariableMethods (this, VAR_READBACK); // Identify the type of button setText( "QEPushButton" ); // For each variable name property manager, set up an index to identify it when it signals and // set up a connection to recieve variable name property changes. // The variable name property manager class only delivers an updated variable name after the user has stopped typing connectNewVariableNameProperty( SLOT ( useNewVariableNameProperty( QString, QString, unsigned int ) ) ); altReadback->connectNewVariableNameProperty( SLOT ( useNewVariableNameProperty( QString, QString, unsigned int ) ) ); } /* Destructor function */ QEPushButton::~QEPushButton() { if( altReadback ) delete altReadback; } // Setup default updateOption. // QEGenericButton::updateOptions QEPushButton::getDefaultUpdateOption() { return QEGenericButton::UPDATE_TEXT; } /* Set variable name substitutions. Must set all - as each variable name proprty manager needs it's own copy. */ void QEPushButton::setVariableNameSubstitutionsProperty( const QString& substitutions ) { QESingleVariableMethods::setVariableNameSubstitutionsProperty (substitutions); altReadback->setVariableNameSubstitutionsProperty( substitutions ); } /* Set/get alternative readback PV name. */ void QEPushButton::setAltReadbackProperty( const QString& variableName ) { altReadback->setVariableNameProperty( variableName ); } QString QEPushButton::getAltReadbackProperty() const { return altReadback->getVariableNameProperty(); } /* Set/get alternative readback PV attay index. */ void QEPushButton::setAltReadbackArrayIndex( const int arrayIndex ) { altReadback->setArrayIndex( arrayIndex ); } int QEPushButton::getAltReadbackArrayIndex () const { return altReadback->getArrayIndex(); } // Slot to receiver a 'process completed' signal from the application launcher void QEPushButton::programCompletedSlot() { emit programCompleted(); } //============================================================================== // Drag drop // All in QEGenericButton //============================================================================== // Copy / Paste // Mostly in QEGenericButton QVariant QEPushButton::copyData() { return QVariant( getButtonText() ); } // end
qtepics/qeframework
qeframeworkSup/project/widgets/QEButton/QEPushButton.cpp
C++
lgpl-3.0
4,248
/* This file is part of Poti Poti is free software: you can redistribute it and/or modify it under the terms of the GNU Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Poti 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 Public License for more details. You should have received a copy of the GNU Public License along with Poti. If not, see <http://www.gnu.org/licenses/>. */ #include <poti.h> struct test { bool poti_basic_events; bool poti_legacy_header; bool poti_with_comments; bool poti_with_alias; bool poti_relative_timestamps; }; /* * This program tests all combinations by which poti can be initialize. */ int main (int argc, char **argv) { int tn; if (argc != 2){ return 1; }else{ tn = atoi(argv[1]); } struct test *tests = malloc(sizeof(struct test)); int ntests = 1; int a, b, c, d; for (a = 0; a < 2; a++){ for (b = 0; b < 2; b++){ for (c = 0; c < 2; c++){ for (d = 0; d < 2; d++){ tests[ntests-1].poti_basic_events = a; tests[ntests-1].poti_legacy_header = b; tests[ntests-1].poti_with_comments = false; tests[ntests-1].poti_with_alias = c; tests[ntests-1].poti_relative_timestamps = d; ntests++; tests = realloc(tests, ntests * sizeof(struct test)); } } } } if (tn < ntests){ printf ("# Running test %d out of %d tests.\n", tn, ntests); poti_init_custom (NULL, tests[tn].poti_basic_events, tests[tn].poti_legacy_header, tests[tn].poti_with_comments, tests[tn].poti_with_alias, tests[tn].poti_relative_timestamps); }else{ //Unsupported test printf ("# Unsupported test %d.\n", tn); return 2; } printf("# This trace has been created with the following init configuration:\n"); printf("# With basic events: %s\n", tests[tn].poti_basic_events ? "true" : "false"); printf("# With legacy header: %s\n", tests[tn].poti_legacy_header ? "true" : "false"); printf("# With comments: %s\n", tests[tn].poti_with_comments ? "true" : "false"); printf("# With aliases: %s\n", tests[tn].poti_with_alias ? "true" : "false"); printf("# With relative timestamps: %s\n", tests[tn].poti_relative_timestamps ? "true" : "false"); poti_header(); poti_DContainerType ("0", "PROCESS"); poti_DStateType ("PROCESS", "VAR"); poti_ECreateContainer (123, "PROCESS", "0", "p1"); poti_ESetState (123.1, "p1", "VAR", "Inicio"); poti_EPushState (123.2, "p1", "VAR", "Meio"); poti_EPopState (123.3, "p1", "VAR"); poti_close(); free(tests); return 0; }
schnorr/poti
examples/header.c
C
lgpl-3.0
2,782
/* * Copyright 2000-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package benchmark.bcel.verifier.exc; /** * Instances of this class are thrown by BCEL's class file verifier "JustIce" * when the verification of a method is requested that does not exist. * * @version $Id: InvalidMethodException.java 371539 2006-01-23 14:08:00Z tcurdt $ * @author Enver Haase */ public class InvalidMethodException extends RuntimeException{ /** Constructs an InvalidMethodException with the specified detail message. */ public InvalidMethodException(String message){ super(message); } }
Xyene/JBL
src/test/java/benchmark/bcel/verifier/exc/InvalidMethodException.java
Java
lgpl-3.0
1,153
<?php namespace Swoole; use Swoole; class Response { public $http_protocol = 'HTTP/1.1'; public $http_status = 200; public $head; public $cookie; public $body; static $HTTP_HEADERS = array( 100 => "100 Continue", 101 => "101 Switching Protocols", 200 => "200 OK", 201 => "201 Created", 204 => "204 No Content", 206 => "206 Partial Content", 300 => "300 Multiple Choices", 301 => "301 Moved Permanently", 302 => "302 Found", 303 => "303 See Other", 304 => "304 Not Modified", 307 => "307 Temporary Redirect", 400 => "400 Bad Request", 401 => "401 Unauthorized", 403 => "403 Forbidden", 404 => "404 Not Found", 405 => "405 Method Not Allowed", 406 => "406 Not Acceptable", 408 => "408 Request Timeout", 410 => "410 Gone", 413 => "413 Request Entity Too Large", 414 => "414 Request URI Too Long", 415 => "415 Unsupported Media Type", 416 => "416 Requested Range Not Satisfiable", 417 => "417 Expectation Failed", 500 => "500 Internal Server Error", 501 => "501 Method Not Implemented", 503 => "503 Service Unavailable", 506 => "506 Variant Also Negotiates"); function send_http_status($code) { $this->head[0] = $this->http_protocol.' '.self::$HTTP_HEADERS[$code]; $this->http_status = $code; } function send_head($key,$value) { $this->head[$key] = $value; } /** * ����cookie * @param $name * @param null $value * @param null $expire * @param string $path * @param null $domain * @param null $secure * @param null $httponly */ function setcookie($name, $value = null, $expire = null, $path = '/', $domain = null, $secure = null, $httponly = null) { if($value==null) $value='deleted'; $cookie = "$name=$value; expires=Tue, ".date("D, d-M-Y H:i:s T",$expire)."; path=$path"; if($domain) $cookie.="; domain=$domain"; if($httponly) $cookie.='; httponly'; $this->cookie[] = $cookie; } /** * ����head��Ϣ * @param $header */ function addHeader(array $header) { $this->head = array_merge($this->head, $header); } function getHeader($fastcgi = false) { $out = ''; if ($fastcgi) { $out .= 'Status: '.$this->http_status.' '.self::$HTTP_HEADERS[$this->http_status]."\r\n"; } else { //Protocol if (isset($this->head[0])) { $out .= $this->head[0]."\r\n"; unset($this->head[0]); } else { $out = "HTTP/1.1 200 OK\r\n"; } } //fill header if (!isset($this->head['Server'])) { $this->head['Server'] = Swoole\Protocol\WebServer::SOFTWARE; } if (!isset($this->head['Content-Type'])) { $this->head['Content-Type'] = 'text/html; charset='.\Swoole::$charset; } if (!isset($this->head['Content-Length'])) { $this->head['Content-Length'] = strlen($this->body); } //Headers foreach($this->head as $k=>$v) { $out .= $k.': '.$v."\r\n"; } //Cookies if (!empty($this->cookie) and is_array($this->cookie)) { foreach($this->cookie as $v) { $out .= "Set-Cookie: $v\r\n"; } } //End $out .= "\r\n"; return $out; } function noCache() { $this->head['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'; $this->head['Pragma'] = 'no-cache'; } }
chenqingji/qing-sw
libs/Swoole/Response.php
PHP
lgpl-3.0
3,914
Rebuilding database. This may take a few minutes.
nicolasbrailo/potzify
templates/rebuild_db.html
HTML
lgpl-3.0
52
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_65) on Thu Nov 26 15:41:17 PST 2015 --> <title>MLIRL</title> <meta name="date" content="2015-11-26"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="MLIRL"; } } catch(err) { } //--> var methods = {"i0":9,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html" target="_top">Frames</a></li> <li><a href="MLIRL.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">burlap.behavior.singleagent.learnfromdemo.mlirl</div> <h2 title="Class MLIRL" class="title">Class MLIRL</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>burlap.behavior.singleagent.learnfromdemo.mlirl.MLIRL</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">MLIRL</span> extends java.lang.Object</pre> <div class="block">An implementation of Maximum-likelihood Inverse Reinforcement Learning [1]. This class takes as input (from an <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl"><code>MLIRLRequest</code></a> object) a set of expert trajectories through a domain and a <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/support/DifferentiableRF.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl.support"><code>DifferentiableRF</code></a> model, and learns the parameters of the reward function model that maximizes the likelihood of the trajectories. The reward function parameter spaces is searched using gradient ascent. Since the policy gradient it uses is non-linear, it's possible that it may get stuck in local optimas. Computing the policy gradient is done by iteratively replanning after each gradient ascent step with a <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/support/QGradientPlanner.html" title="interface in burlap.behavior.singleagent.learnfromdemo.mlirl.support"><code>QGradientPlanner</code></a> instance provided in the <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl"><code>MLIRLRequest</code></a> object. <p/> The gradient ascent will stop either after a fixed number of steps or until the change in likelihood is smaller than some threshold. If the max number of steps is set to -1, then it will continue until the change in likelihood is smaller than the threshold. <p/> 1. Babes, Monica, et al. "Apprenticeship learning about multiple intentions." Proceedings of the 28th International Conference on Machine Learning (ICML-11). 2011.</div> <dl> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>James MacGlashan.</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#debugCode">debugCode</a></span></code> <div class="block">The debug code used for printing information to the terminal.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#learningRate">learningRate</a></span></code> <div class="block">The gradient ascent learning rate</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#maxLikelihoodChange">maxLikelihoodChange</a></span></code> <div class="block">The likelihood change threshold to stop gradient ascent.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#maxSteps">maxSteps</a></span></code> <div class="block">The maximum number of steps of gradient ascent.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl">MLIRLRequest</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#request">request</a></span></code> <div class="block">The MLRIL request defining the IRL problem.</div> </td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#MLIRL-burlap.behavior.singleagent.learnfromdemo.mlirl.MLIRLRequest-double-double-int-">MLIRL</a></span>(<a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl">MLIRLRequest</a>&nbsp;request, double&nbsp;learningRate, double&nbsp;maxLikelihoodChange, int&nbsp;maxSteps)</code> <div class="block">Initializes.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>protected static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#addToVector-double:A-double:A-">addToVector</a></span>(double[]&nbsp;sumVector, double[]&nbsp;deltaVector)</code> <div class="block">Performs a vector addition and stores the results in sumVector</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#getDebugCode--">getDebugCode</a></span>()</code> <div class="block">Returns the debug code used for printing to the terminal</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#logLikelihood--">logLikelihood</a></span>()</code> <div class="block">Computes and returns the log-likelihood of all expert trajectories under the current reward function parameters.</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>double[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#logLikelihoodGradient--">logLikelihoodGradient</a></span>()</code> <div class="block">Computes and returns the gradient of the log-likelihood of all trajectories</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#logLikelihoodOfTrajectory-burlap.behavior.singleagent.EpisodeAnalysis-double-">logLikelihoodOfTrajectory</a></span>(<a href="../../../../../burlap/behavior/singleagent/EpisodeAnalysis.html" title="class in burlap.behavior.singleagent">EpisodeAnalysis</a>&nbsp;ea, double&nbsp;weight)</code> <div class="block">Computes and returns the log-likelihood of the given trajectory under the current reward function parameters and weights it by the given weight.</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>double[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#logPolicyGrad-burlap.oomdp.core.states.State-burlap.oomdp.singleagent.GroundedAction-">logPolicyGrad</a></span>(<a href="../../../../../burlap/oomdp/core/states/State.html" title="interface in burlap.oomdp.core.states">State</a>&nbsp;s, <a href="../../../../../burlap/oomdp/singleagent/GroundedAction.html" title="class in burlap.oomdp.singleagent">GroundedAction</a>&nbsp;ga)</code> <div class="block">Computes and returns the gradient of the Boltzmann policy for the given state and action.</div> </td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#performIRL--">performIRL</a></span>()</code> <div class="block">Runs gradient ascent.</div> </td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#setDebugCode-int-">setDebugCode</a></span>(int&nbsp;debugCode)</code> <div class="block">Sets the debug code used for printing to the terminal</div> </td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#setRequest-burlap.behavior.singleagent.learnfromdemo.mlirl.MLIRLRequest-">setRequest</a></span>(<a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl">MLIRLRequest</a>&nbsp;request)</code> <div class="block">Sets the <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl"><code>MLIRLRequest</code></a> object defining the IRL problem.</div> </td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#toggleDebugPrinting-boolean-">toggleDebugPrinting</a></span>(boolean&nbsp;printDebug)</code> <div class="block">Sets whether information during learning is printed to the terminal.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="request"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>request</h4> <pre>protected&nbsp;<a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl">MLIRLRequest</a> request</pre> <div class="block">The MLRIL request defining the IRL problem.</div> </li> </ul> <a name="learningRate"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>learningRate</h4> <pre>protected&nbsp;double learningRate</pre> <div class="block">The gradient ascent learning rate</div> </li> </ul> <a name="maxLikelihoodChange"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>maxLikelihoodChange</h4> <pre>protected&nbsp;double maxLikelihoodChange</pre> <div class="block">The likelihood change threshold to stop gradient ascent.</div> </li> </ul> <a name="maxSteps"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>maxSteps</h4> <pre>protected&nbsp;int maxSteps</pre> <div class="block">The maximum number of steps of gradient ascent. when set to -1, there is no limit and termination will be based on the <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html#maxLikelihoodChange"><code>maxLikelihoodChange</code></a> alone.</div> </li> </ul> <a name="debugCode"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>debugCode</h4> <pre>protected&nbsp;int debugCode</pre> <div class="block">The debug code used for printing information to the terminal.</div> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="MLIRL-burlap.behavior.singleagent.learnfromdemo.mlirl.MLIRLRequest-double-double-int-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>MLIRL</h4> <pre>public&nbsp;MLIRL(<a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl">MLIRLRequest</a>&nbsp;request, double&nbsp;learningRate, double&nbsp;maxLikelihoodChange, int&nbsp;maxSteps)</pre> <div class="block">Initializes.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>request</code> - the problem request definition</dd> <dd><code>learningRate</code> - the gradient ascent learning rate</dd> <dd><code>maxLikelihoodChange</code> - the likelihood change threshold that must be reached to terminate gradient ascent</dd> <dd><code>maxSteps</code> - the maximum number of gradient ascent steps allowed before termination is forced. Set to -1 to rely only on likelihood threshold.</dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="setRequest-burlap.behavior.singleagent.learnfromdemo.mlirl.MLIRLRequest-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setRequest</h4> <pre>public&nbsp;void&nbsp;setRequest(<a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl">MLIRLRequest</a>&nbsp;request)</pre> <div class="block">Sets the <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl"><code>MLIRLRequest</code></a> object defining the IRL problem.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>request</code> - the <a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl"><code>MLIRLRequest</code></a> object defining the IRL problem.</dd> </dl> </li> </ul> <a name="toggleDebugPrinting-boolean-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toggleDebugPrinting</h4> <pre>public&nbsp;void&nbsp;toggleDebugPrinting(boolean&nbsp;printDebug)</pre> <div class="block">Sets whether information during learning is printed to the terminal. Will automatically toggle the debug printing for the underlying valueFunction as well.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>printDebug</code> - if true, information is printed to the terminal; if false then it is silent.</dd> </dl> </li> </ul> <a name="getDebugCode--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDebugCode</h4> <pre>public&nbsp;int&nbsp;getDebugCode()</pre> <div class="block">Returns the debug code used for printing to the terminal</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the debug code used for printing to the terminal.</dd> </dl> </li> </ul> <a name="setDebugCode-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDebugCode</h4> <pre>public&nbsp;void&nbsp;setDebugCode(int&nbsp;debugCode)</pre> <div class="block">Sets the debug code used for printing to the terminal</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>debugCode</code> - the debug code used for printing to the terminal</dd> </dl> </li> </ul> <a name="performIRL--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>performIRL</h4> <pre>public&nbsp;void&nbsp;performIRL()</pre> <div class="block">Runs gradient ascent.</div> </li> </ul> <a name="logLikelihood--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>logLikelihood</h4> <pre>public&nbsp;double&nbsp;logLikelihood()</pre> <div class="block">Computes and returns the log-likelihood of all expert trajectories under the current reward function parameters.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the log-likelihood of all expert trajectories under the current reward function parameters.</dd> </dl> </li> </ul> <a name="logLikelihoodOfTrajectory-burlap.behavior.singleagent.EpisodeAnalysis-double-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>logLikelihoodOfTrajectory</h4> <pre>public&nbsp;double&nbsp;logLikelihoodOfTrajectory(<a href="../../../../../burlap/behavior/singleagent/EpisodeAnalysis.html" title="class in burlap.behavior.singleagent">EpisodeAnalysis</a>&nbsp;ea, double&nbsp;weight)</pre> <div class="block">Computes and returns the log-likelihood of the given trajectory under the current reward function parameters and weights it by the given weight.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>ea</code> - the trajectory</dd> <dd><code>weight</code> - the weight to assign the trajectory</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the log-likelihood of the given trajectory under the current reward function parameters and weights it by the given weight.</dd> </dl> </li> </ul> <a name="logLikelihoodGradient--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>logLikelihoodGradient</h4> <pre>public&nbsp;double[]&nbsp;logLikelihoodGradient()</pre> <div class="block">Computes and returns the gradient of the log-likelihood of all trajectories</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the gradient of the log-likelihood of all trajectories</dd> </dl> </li> </ul> <a name="logPolicyGrad-burlap.oomdp.core.states.State-burlap.oomdp.singleagent.GroundedAction-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>logPolicyGrad</h4> <pre>public&nbsp;double[]&nbsp;logPolicyGrad(<a href="../../../../../burlap/oomdp/core/states/State.html" title="interface in burlap.oomdp.core.states">State</a>&nbsp;s, <a href="../../../../../burlap/oomdp/singleagent/GroundedAction.html" title="class in burlap.oomdp.singleagent">GroundedAction</a>&nbsp;ga)</pre> <div class="block">Computes and returns the gradient of the Boltzmann policy for the given state and action.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>s</code> - the state in which the policy is queried</dd> <dd><code>ga</code> - the action for which the policy is queried.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>s the gradient of the Boltzmann policy for the given state and action.</dd> </dl> </li> </ul> <a name="addToVector-double:A-double:A-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>addToVector</h4> <pre>protected static&nbsp;void&nbsp;addToVector(double[]&nbsp;sumVector, double[]&nbsp;deltaVector)</pre> <div class="block">Performs a vector addition and stores the results in sumVector</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>sumVector</code> - the input vector to which the values in deltaVector will be added.</dd> <dd><code>deltaVector</code> - the vector values to add to sumVector.</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <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="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRLRequest.html" title="class in burlap.behavior.singleagent.learnfromdemo.mlirl"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html" target="_top">Frames</a></li> <li><a href="MLIRL.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
gauravpuri/MDP_Repp
doc/burlap/behavior/singleagent/learnfromdemo/mlirl/MLIRL.html
HTML
lgpl-3.0
27,140
import time import sys def sizeof_fmt(num, unit='B'): # source: http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size for uprexif in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "{:3.2f} {}{}".format(num, uprexif, unit) num /= 1024.0 return "{:3.2f} Yi{}".format(num, unit) output = sys.stderr progress_format = '{n} [{b}] {p:3.1f}% ({d}/{a}) {s}' class FileTransferProgressBar(object): # inspired by clint.textui.progress.Bar def __init__(self, filesize, name='', width=32, empty_char=' ', filled_char='#', hide=None, speed_update=0.2, bar_update=0.05, progress_format=progress_format): self.name, self.filesize, self.width, self.ec, self.fc = name, filesize, width, empty_char, filled_char self.speed_update, self.bar_update, self.progress_format = speed_update, bar_update, progress_format if hide is None: try: self.hide = not output.isatty() except AttributeError: self.hide = True else: self.hide = hide self.last_progress = 0 self.last_time = time.time() self.last_speed_update = self.last_time self.start_time = self.last_time self.last_speed_progress = 0 self.last_speed = 0 self.max_bar_size = 0 def show(self, progress): if time.time() - self.last_time > self.bar_update: self.last_time = time.time() self.last_progress = progress if self.last_time - self.last_speed_update > self.speed_update: self.last_speed = (self.last_speed_progress - progress) / float(self.last_speed_update - self.last_time) self.last_speed_update = self.last_time self.last_speed_progress = progress status = self.width * progress // self.filesize percent = float(progress * 100) / self.filesize bar = self.progress_format.format(n=self.name, b=self.fc * status + self.ec * (self.width - status), p=percent, d=sizeof_fmt(progress), a=sizeof_fmt(self.filesize), s=sizeof_fmt(self.last_speed) + '/s') max_bar = self.max_bar_size self.max_bar_size = max(len(bar), self.max_bar_size) bar = bar + (' ' * (max_bar - len(bar))) + '\r' # workaround for ghosts output.write(bar) output.flush() def done(self): speed = self.filesize / float(time.time() - self.start_time) bar = self.progress_format.format(n=self.name, b=self.fc * self.width, p=100, d=sizeof_fmt(self.filesize), a=sizeof_fmt(self.filesize), s=sizeof_fmt(speed) + '/s') max_bar = self.max_bar_size self.max_bar_size = max(len(bar), self.max_bar_size) bar = bar + (' ' * (max_bar - len(bar))) + '\r' output.write(bar) output.write('\n') output.flush()
JuniorJPDJ/pyChomikBox
ChomikBox/utils/FileTransferProgressBar.py
Python
lgpl-3.0
3,099
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_18) on Tue Nov 02 05:44:46 MDT 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class cs236.lab1.Tokenizer </TITLE> <META NAME="date" CONTENT="2010-11-02"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class cs236.lab1.Tokenizer"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../cs236/lab1/Tokenizer.html" title="class in cs236.lab1"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?cs236/lab1//class-useTokenizer.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Tokenizer.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>cs236.lab1.Tokenizer</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../cs236/lab1/Tokenizer.html" title="class in cs236.lab1">Tokenizer</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#cs236.lab2"><B>cs236.lab2</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="cs236.lab2"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../cs236/lab1/Tokenizer.html" title="class in cs236.lab1">Tokenizer</A> in <A HREF="../../../cs236/lab2/package-summary.html">cs236.lab2</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../cs236/lab2/package-summary.html">cs236.lab2</A> with parameters of type <A HREF="../../../cs236/lab1/Tokenizer.html" title="class in cs236.lab1">Tokenizer</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../cs236/lab2/TokenizerServer.html#TokenizerServer(cs236.lab1.Tokenizer)">TokenizerServer</A></B>(<A HREF="../../../cs236/lab1/Tokenizer.html" title="class in cs236.lab1">Tokenizer</A>&nbsp;tTokenizer)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a new instance with a Tokenizer to run.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../cs236/lab1/Tokenizer.html" title="class in cs236.lab1"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?cs236/lab1//class-useTokenizer.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Tokenizer.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
beatgammit/cs236-labs
dist/javadoc/cs236/lab1/class-use/Tokenizer.html
HTML
lgpl-3.0
7,324
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ActiveUp.Net.WhoIs.Compact")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("abc")] [assembly: AssemblyProduct("ActiveUp.Net.WhoIs.Compact")] [assembly: AssemblyCopyright("Copyright © abc 2007")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fbae32e7-71fa-41f7-88b9-952ca0e9462b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("5.0.3454.364")]
DavidS/MailSystem.NET
Class Library/ActiveUp.Net.WhoIs.Compact/Properties/AssemblyInfo.cs
C#
lgpl-3.0
1,392
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "deleteresourcepolicyrequest.h" #include "deleteresourcepolicyrequest_p.h" #include "deleteresourcepolicyresponse.h" #include "lexmodelsv2request_p.h" namespace QtAws { namespace LexModelsV2 { /*! * \class QtAws::LexModelsV2::DeleteResourcePolicyRequest * \brief The DeleteResourcePolicyRequest class provides an interface for LexModelsV2 DeleteResourcePolicy requests. * * \inmodule QtAwsLexModelsV2 * * * \sa LexModelsV2Client::deleteResourcePolicy */ /*! * Constructs a copy of \a other. */ DeleteResourcePolicyRequest::DeleteResourcePolicyRequest(const DeleteResourcePolicyRequest &other) : LexModelsV2Request(new DeleteResourcePolicyRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a DeleteResourcePolicyRequest object. */ DeleteResourcePolicyRequest::DeleteResourcePolicyRequest() : LexModelsV2Request(new DeleteResourcePolicyRequestPrivate(LexModelsV2Request::DeleteResourcePolicyAction, this)) { } /*! * \reimp */ bool DeleteResourcePolicyRequest::isValid() const { return false; } /*! * Returns a DeleteResourcePolicyResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * DeleteResourcePolicyRequest::response(QNetworkReply * const reply) const { return new DeleteResourcePolicyResponse(*this, reply); } /*! * \class QtAws::LexModelsV2::DeleteResourcePolicyRequestPrivate * \brief The DeleteResourcePolicyRequestPrivate class provides private implementation for DeleteResourcePolicyRequest. * \internal * * \inmodule QtAwsLexModelsV2 */ /*! * Constructs a DeleteResourcePolicyRequestPrivate object for LexModelsV2 \a action, * with public implementation \a q. */ DeleteResourcePolicyRequestPrivate::DeleteResourcePolicyRequestPrivate( const LexModelsV2Request::Action action, DeleteResourcePolicyRequest * const q) : LexModelsV2RequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the DeleteResourcePolicyRequest * class' copy constructor. */ DeleteResourcePolicyRequestPrivate::DeleteResourcePolicyRequestPrivate( const DeleteResourcePolicyRequestPrivate &other, DeleteResourcePolicyRequest * const q) : LexModelsV2RequestPrivate(other, q) { } } // namespace LexModelsV2 } // namespace QtAws
pcolby/libqtaws
src/lexmodelsv2/deleteresourcepolicyrequest.cpp
C++
lgpl-3.0
3,102
# <center>**C++ Web Template Library Project**</center> **Software Requirements Specification** **Author**: Pedro Henrique **Contact**: ph.geekstuff@gmail.com **Document Name**: srs.md (Markdown) **Document Version**: 0.1b (for Coimbra Engineering Institute) **Updated at**: May 10, 2016 **GitHub**: https://github.com/phgeekstuff/wtl.git ### 1. History | Date | Responsible | Description | |---|---|---| | May 7, 2016 | Pedro Henrique | First Specification. | | May 10, 2016 | Pedro Henrique | Specifying **FR0005**.| | May 11, 2016 | Pedro Henrique | .| ### 2. Overview The goal of the project is to build and maintain a high-level abstraction for C/C++ developers to take advantage of all modern standards of web, such as: HTTP, HTML, CSS, JavaScript, SOAP and RESTFul web services, and so on. Also, the idea is to provide tools for easy migration of legacy code and apps to web/connected environment. ### 3. Introduction The goal of this document is to keep track of all requirements related to C++ Web Template Library Project. ### 4. User Types 1. Developer 2. IT Analyst 3. UI/UX Designer ### 5. Functional Requirements [**MUST**] **FR0001:** C++ Code Main Namespace All code written in C++ related to C++ Web Template Library must be in _"wtl"_ namespace. [**MUST**] **FR0002:** HTML Integration HTML tags of _wtl_ must start with "wtl:" prefix. It helps to avoid any problem with other technologies. [**MUST**] **FR0003:** HTML Templates All _wtl_ tags must start with "wtl:" prefix. It to helps avoid any problem with other technologies. [**SHOULD**] **FR0004** STL code style is Preferred All types should be named or aliases following STL code common convention. [**MUST**] **FR0005:** C++ Base Headers Basic headers must be provide as following: | Header Name | Description | |-------------|-------------| |<center>&lt;wtl&gt;</center> | Main types of _wtl_.| |<center>&lt;wtlhttp&gt;</center>| Basic abstraction for HTTP. |<center>&lt;wtlhtml&gt;</center> | Basic abstraction for HTML.| |<center>&lt;wtlxml&gt;</center> | Basic abstraction for XML.| |<center>&lt;wtljson&gt;</center> | Basic abstraction for JSON.| |<center>&lt;wtlio&gt;</center> | Basic IO types which work over HTTP.| |<center>&lt;wtlservice&gt;</center> | Basic types for Web Services.| |<center>&lt;wtl&gt;</center> | .| ### 6. Non-Functional Requirements [**MUST**] **NFR1000:** Legacy Code Compliance It must be compatible to ANSI C (at least C99) and C++98 languages. Supporting legacy code. [**MUST**] **NFR1001:** Modern Code Compliance It must be compatible to C11 and Modern C++ (at least C++11) languages. Supporting modern code. [**MUST**] **NFR1003:** Complete standard code It must support standard C/C++ code, and run in any platform that supports C/C++ standard code. [**MUST**] **NFR1004:** Runtime Deployment It must not require a specific framework despite web server and http handler modules (i.e. different to .net framework or jre). [**MUST**] **NFR1005** Ansi C Compliance It must be coded in a way that can be integrated transparently to Ansi C Standard Library. [**MUST**] **NFR1006** STL Compliance It must be coded in a way that can be integrated transparently to STL (Standard Template Library) [**MUST**] **NFR1007** Generic Programming is Preferred Generic Programming must be considered the main mindset behind wtl, considering C++ common sense. [**SHOULD**] **NFR1008** Object Oriented Programming is the second choice Considering C++ common sense, Object Oriented Programming should be the second choice for coding. [**SHOULD**] **NFR1009** All common paradigms should be supported Considering C++ common sense, Object Oriented Programming should be the second choice for coding. ### 7. Glossary * <em>**css**</em>: Cascade Stylesheet * <em>**html**</em>: Hypertext Markup Language * <em>**http**</em>: Hypertext Transfer Protocol * <em>**json**</em>: JavaScript Object Notation * <em>**rest**</em>: Representational State Transfer * <em>**soap**</em>: Simple Access Object Protocol * <em>**stl**</em>: C++ Standard Template Library * <em>**wtl**</em>: C++ Web Template Library ### 8. References * [Markdown Markup Language](https://guides.github.com/features/mastering-markdown) * [ISO C++](https://isocpp.org) * [Stroustrup C++](http://www.stroustrup.com/C++.html) * [ISO C Official Web Site](http://www.open-std.org/jtc1/sc22/wg14/)
phgeekstuff/wtl
doc/srs.md
Markdown
lgpl-3.0
4,423
<?php /** * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0 * @copyright Aimeos (aimeos.org), 2019-2022 * @package Controller * @subpackage Jobs */ namespace Aimeos\Controller\Jobs\Stock\Import\Csv; /** * Stock import controller factory for CSV files. * * @package Controller * @subpackage Jobs */ class Factory extends \Aimeos\Controller\Jobs\Common\Factory\Base implements \Aimeos\Controller\Jobs\Common\Factory\Iface { /** * Creates a new controller specified by the given name. * * @param \Aimeos\MShop\Context\Item\Iface $context Context object required by controllers * @param \Aimeos\Bootstrap $aimeos \Aimeos\Bootstrap object * @param string|null $name Name of the controller or "Standard" if null * @return \Aimeos\Controller\Jobs\Iface New controller object */ public static function create( \Aimeos\MShop\Context\Item\Iface $context, \Aimeos\Bootstrap $aimeos, string $name = null ) : \Aimeos\Controller\Jobs\Iface { /** controller/jobs/stock/import/csv/name * Class name of the used stock suggestions scheduler controller implementation * * Each default job controller can be replace by an alternative imlementation. * To use this implementation, you have to set the last part of the class * name as configuration value so the controller factory knows which class it * has to instantiate. * * For example, if the name of the default class is * * \Aimeos\Controller\Jobs\Stock\Import\Csv\Standard * * and you want to replace it with your own version named * * \Aimeos\Controller\Jobs\Stock\Import\Csv\Mycsv * * then you have to set the this configuration option: * * controller/jobs/stock/import/csv/name = Mycsv * * The value is the last part of your own class name and it's case sensitive, * so take care that the configuration value is exactly named like the last * part of the class name. * * The allowed characters of the class name are A-Z, a-z and 0-9. No other * characters are possible! You should always start the last part of the class * name with an upper case character and continue only with lower case characters * or numbers. Avoid chamel case names like "MyCsv"! * * @param string Last part of the class name * @since 2019.04 * @category Developer */ if( $name === null ) { $name = $context->config()->get( 'controller/jobs/stock/import/csv/name', 'Standard' ); } if( ctype_alnum( $name ) === false ) { $classname = is_string( $name ) ? '\\Aimeos\\Controller\\Jobs\\Stock\\Import\\Csv\\' . $name : '<not a string>'; throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid characters in class name "%1$s"', $classname ) ); } $iface = '\\Aimeos\\Controller\\Jobs\\Iface'; $classname = '\\Aimeos\\Controller\\Jobs\\Stock\\Import\\Csv\\' . $name; $controller = self::createController( $context, $aimeos, $classname, $iface ); /** controller/jobs/stock/import/csv/decorators/excludes * Excludes decorators added by the "common" option from the stock import CSV job controller * * Decorators extend the functionality of a class by adding new aspects * (e.g. log what is currently done), executing the methods of the underlying * class only in certain conditions (e.g. only for logged in users) or * modify what is returned to the caller. * * This option allows you to remove a decorator added via * "controller/jobs/common/decorators/default" before they are wrapped * around the job controller. * * controller/jobs/stock/import/csv/decorators/excludes = array( 'decorator1' ) * * This would remove the decorator named "decorator1" from the list of * common decorators ("\Aimeos\Controller\Jobs\Common\Decorator\*") added via * "controller/jobs/common/decorators/default" to the job controller. * * @param array List of decorator names * @since 2019.04 * @category Developer * @see controller/jobs/common/decorators/default * @see controller/jobs/stock/import/csv/decorators/global * @see controller/jobs/stock/import/csv/decorators/local */ /** controller/jobs/stock/import/csv/decorators/global * Adds a list of globally available decorators only to the stock import CSV job controller * * Decorators extend the functionality of a class by adding new aspects * (e.g. log what is currently done), executing the methods of the underlying * class only in certain conditions (e.g. only for logged in users) or * modify what is returned to the caller. * * This option allows you to wrap global decorators * ("\Aimeos\Controller\Jobs\Common\Decorator\*") around the job controller. * * controller/jobs/stock/import/csv/decorators/global = array( 'decorator1' ) * * This would add the decorator named "decorator1" defined by * "\Aimeos\Controller\Jobs\Common\Decorator\Decorator1" only to the job controller. * * @param array List of decorator names * @since 2019.04 * @category Developer * @see controller/jobs/common/decorators/default * @see controller/jobs/stock/import/csv/decorators/excludes * @see controller/jobs/stock/import/csv/decorators/local */ /** controller/jobs/stock/import/csv/decorators/local * Adds a list of local decorators only to the stock import CSV job controller * * Decorators extend the functionality of a class by adding new aspects * (e.g. log what is currently done), executing the methods of the underlying * class only in certain conditions (e.g. only for logged in users) or * modify what is returned to the caller. * * This option allows you to wrap local decorators * ("\Aimeos\Controller\Jobs\Stock\Import\Csv\Decorator\*") around the job * controller. * * controller/jobs/stock/import/csv/decorators/local = array( 'decorator2' ) * * This would add the decorator named "decorator2" defined by * "\Aimeos\Controller\Jobs\Stock\Import\Csv\Decorator\Decorator2" * only to the job controller. * * @param array List of decorator names * @since 2019.04 * @category Developer * @see controller/jobs/common/decorators/default * @see controller/jobs/stock/import/csv/decorators/excludes * @see controller/jobs/stock/import/csv/decorators/global */ return self::addControllerDecorators( $context, $aimeos, $controller, 'stock/import/csv' ); } }
aimeos/ai-controller-jobs
src/Controller/Jobs/Stock/Import/Csv/Factory.php
PHP
lgpl-3.0
6,395
// Copyright (C) 2011 Yann Grandmaitre // // This file is part of scribelog // // This program 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 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <cstdlib> #include <iostream> #include <ctime> #include <chrono> #include <future> #include <zlib.h> #include "fork.hh" #include "log.hh" Log::Log(const ConfigParser::t_MapConfig& config) : config_(config), fd_(-1) { } Log::~Log() { } bool Log::write(const char* data, ssize_t size) { if (fd_ == -1) { if (!open()) return false; } auto it_delay = config_.find("delay"); if (it_delay != config_.end()) { //check delay auto now = std::chrono::high_resolution_clock::now(); if (now - begin_ >= std::chrono::seconds( std::atoi(it_delay->second.c_str()))) { close(fd_); // Compress the file in a fork process Fork f; if (f.is_child ()) compress(filename_); if (!open()) return false; } } ::write(fd_, data, size); return true; } void Log::compress(const std::string& filename) { std::clog << "debut" << std::endl; int fd = ::open(filename.c_str(), O_RDONLY, 0666); // FIXME get the compression level in config file gzFile gz = gzopen((filename + ".gz").c_str(), "wb5"); if (gz == 0) { std::clog << "Couldn't create the .gz file: " << filename << ".gz" << std::endl; } else { char buffer[64 * 1024]; int32_t size = ::read(fd, buffer, sizeof(buffer)); while (size > 0) { if(gzwrite(gz, buffer, size) == 0) { std::clog << "gzwrite error" << std::endl; } size = ::read(fd, buffer, sizeof(buffer)); } gzclose(gz); ::close(fd); } exit(0); } bool Log::open() { begin_ = std::chrono::high_resolution_clock::now(); const auto it = config_.find("file"); if (it == config_.end()) { std::clog << "no file found in config" << std::endl; return false; } // Get date may be see std::put_time and std::localtime auto ts = ::time(0); struct ::tm local_tm; ::localtime_r(&ts, &local_tm); char buffer[128]; auto size = strftime(buffer, sizeof (buffer), "%Y%m%d-%T", &local_tm); std::string date(buffer, size); // FIXME use stringstream filename_ = date + "-" + it->second; int fd = ::open(filename_.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); if (fd == -1) { std::clog << "could'n open the file: " << it->second << std::endl; return false; } fd_ = fd; return true; }
ikir/scribelog
src/log.cc
C++
lgpl-3.0
3,309
/**************************************************** Statistics Online Computational Resource (SOCR) http://www.StatisticsResource.org All SOCR programs, materials, tools and resources are developed by and freely disseminated to the entire community. Users may revise, extend, redistribute, modify under the terms of the Lesser GNU General Public License as published by the Open Source Initiative http://opensource.org/licenses/. All efforts should be made to develop and distribute factually correct, useful, portable and extensible resource all available in all digital formats for free over the Internet. SOCR resources are distributed in the hope that they will be useful, but without any warranty; without any explicit, implicit or implied warranty for merchantability or fitness for a particular purpose. See the GNU Lesser General Public License for more details see http://opensource.org/licenses/lgpl-license.php. http://www.SOCR.ucla.edu http://wiki.stat.ucla.edu/socr It s Online, Therefore, It Exists! ****************************************************/ package edu.ucla.stat.SOCR.analyses.result; import java.util.HashMap; public class TwoPairedSignTestResult extends Result { public TwoPairedSignTestResult(HashMap texture) { super(texture); } public TwoPairedSignTestResult(HashMap texture, HashMap graph) { super(texture, graph); } }
SOCR/HTML5_WebSite
SOCR2.8/src/edu/ucla/stat/SOCR/analyses/result/TwoPairedSignTestResult.java
Java
lgpl-3.0
1,402
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2015 Pelican Mapping * http://osgearth.org * * osgEarth is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <osgEarthAnnotation/AnnotationNode> #include <osgEarthAnnotation/AnnotationSettings> #include <osgEarthAnnotation/AnnotationUtils> #include <osgEarthSymbology/ModelSymbol> #include <osgEarth/DepthOffset> #include <osgEarth/MapNode> #include <osgEarth/NodeUtils> #include <osgEarth/TerrainEngineNode> using namespace osgEarth; using namespace osgEarth::Annotation; //------------------------------------------------------------------- namespace osgEarth { namespace Annotation { struct AutoClampCallback : public TerrainCallback { AutoClampCallback( AnnotationNode* annotation): _annotation( annotation ) { } void onTileAdded( const TileKey& key, osg::Node* tile, TerrainCallbackContext& context ) { _annotation->reclamp( key, tile, context.getTerrain() ); } AnnotationNode* _annotation; }; } } //------------------------------------------------------------------- Style AnnotationNode::s_emptyStyle; //------------------------------------------------------------------- AnnotationNode::AnnotationNode(MapNode* mapNode) : _mapNode ( mapNode ), _dynamic ( false ), _autoclamp ( false ), _depthAdj ( false ), _activeDs ( 0L ) { //Note: Cannot call setMapNode() here because it's a virtual function. // Each subclass will be separately responsible at ctor time. // always blend. this->getOrCreateStateSet()->setMode( GL_BLEND, osg::StateAttribute::ON ); // always draw after the terrain. this->getOrCreateStateSet()->setRenderBinDetails( 1, "DepthSortedBin" ); } AnnotationNode::AnnotationNode(MapNode* mapNode, const Config& conf) : _mapNode ( mapNode ), _dynamic ( false ), _autoclamp ( false ), _depthAdj ( false ), _activeDs ( 0L ) { this->setName( conf.value("name") ); if ( conf.hasValue("lighting") ) { bool lighting = conf.value<bool>("lighting", false); setLightingIfNotSet( lighting ); } if ( conf.hasValue("backface_culling") ) { bool culling = conf.value<bool>("backface_culling", false); getOrCreateStateSet()->setMode( GL_CULL_FACE, (culling?1:0) | osg::StateAttribute::OVERRIDE ); } if ( conf.hasValue("blending") ) { bool blending = conf.value<bool>("blending", false); getOrCreateStateSet()->setMode( GL_BLEND, (blending?1:0) | osg::StateAttribute::OVERRIDE ); } else { // blend by default. this->getOrCreateStateSet()->setMode( GL_BLEND, osg::StateAttribute::ON ); } // always draw after the terrain. this->getOrCreateStateSet()->setRenderBinDetails( 1, "DepthSortedBin" ); } AnnotationNode::~AnnotationNode() { setMapNode( 0L ); } void AnnotationNode::setLightingIfNotSet( bool lighting ) { osg::StateSet* ss = this->getOrCreateStateSet(); if ( ss->getMode(GL_LIGHTING) == osg::StateAttribute::INHERIT ) { this->getOrCreateStateSet()->setMode( GL_LIGHTING, (lighting ? 1 : 0) | osg::StateAttribute::OVERRIDE ); } } void AnnotationNode::setMapNode( MapNode* mapNode ) { if ( getMapNode() != mapNode ) { // relocate the auto-clamping callback, if there is one: osg::ref_ptr<MapNode> oldMapNode = _mapNode.get(); if ( oldMapNode.valid() ) { if ( _autoClampCallback ) { oldMapNode->getTerrain()->removeTerrainCallback( _autoClampCallback.get() ); if ( mapNode ) mapNode->getTerrain()->addTerrainCallback( _autoClampCallback.get() ); } } _mapNode = mapNode; applyStyle( this->getStyle() ); } } void AnnotationNode::setAnnotationData( AnnotationData* data ) { _annoData = data; } AnnotationData* AnnotationNode::getOrCreateAnnotationData() { if ( !_annoData.valid() ) { setAnnotationData( new AnnotationData() ); } return _annoData.get(); } void AnnotationNode::setDynamic( bool value ) { _dynamic = value; } void AnnotationNode::setCPUAutoClamping( bool value ) { if ( getMapNode() ) { if ( !_autoclamp && value ) { setDynamic( true ); if ( AnnotationSettings::getContinuousClamping() ) { _autoClampCallback = new AutoClampCallback( this ); getMapNode()->getTerrain()->addTerrainCallback( _autoClampCallback.get() ); } } else if ( _autoclamp && !value && _autoClampCallback.valid()) { getMapNode()->getTerrain()->removeTerrainCallback( _autoClampCallback ); _autoClampCallback = 0; } _autoclamp = value; if ( _autoclamp && AnnotationSettings::getApplyDepthOffsetToClampedLines() ) { if ( !_depthAdj ) { // verify that the geometry if polygon-less: bool wantDepthAdjustment = false; PrimitiveSetTypeCounter counter; this->accept(counter); if ( counter._polygon == 0 && (counter._line > 0 || counter._point > 0) ) { wantDepthAdjustment = true; } setDepthAdjustment( wantDepthAdjustment ); } else { // update depth adjustment calculation //getOrCreateStateSet()->addUniform( DepthOffsetUtils::createMinOffsetUniform(this) ); } } } } void AnnotationNode::setDepthAdjustment( bool enable ) { if ( enable ) { _doAdapter.setGraph(this); _doAdapter.recalculate(); } else { _doAdapter.setGraph(0L); } _depthAdj = enable; } bool AnnotationNode::makeAbsolute( GeoPoint& mapPoint, osg::Node* patch ) const { // in terrain-clamping mode, force it to HAT=0: if ( _altitude.valid() && ( _altitude->clamping() == AltitudeSymbol::CLAMP_TO_TERRAIN || _altitude->clamping() == AltitudeSymbol::CLAMP_RELATIVE_TO_TERRAIN) ) { mapPoint.altitudeMode() = ALTMODE_RELATIVE; //If we're clamping to the terrain if (_altitude->clamping() == AltitudeSymbol::CLAMP_TO_TERRAIN) { mapPoint.z() = 0.0; } } // if the point's already absolute and we're not clamping it, nop. if ( mapPoint.altitudeMode() == ALTMODE_ABSOLUTE ) { return true; } // calculate the absolute Z of the map point. if ( getMapNode() ) { // find the terrain height at the map point: double hamsl; if (getMapNode()->getTerrain()->getHeight(patch, mapPoint.getSRS(), mapPoint.x(), mapPoint.y(), &hamsl, 0L)) { // apply any scale/offset in the symbology: if ( _altitude.valid() ) { if ( _altitude->verticalScale().isSet() ) hamsl *= _altitude->verticalScale()->eval(); if ( _altitude->verticalOffset().isSet() ) hamsl += _altitude->verticalOffset()->eval(); } mapPoint.z() += hamsl; } mapPoint.altitudeMode() = ALTMODE_ABSOLUTE; return true; } return false; } void AnnotationNode::installDecoration( const std::string& name, Decoration* ds ) { if ( _activeDs ) { clearDecoration(); } if ( ds == 0L ) { _dsMap.erase( name ); } else { _dsMap[name] = ds->copyOrClone(); } } void AnnotationNode::uninstallDecoration( const std::string& name ) { clearDecoration(); _dsMap.erase( name ); } const std::string& AnnotationNode::getDecoration() const { return _activeDsName; } void AnnotationNode::setDecoration( const std::string& name ) { // already active? if ( _activeDs && _activeDsName == name ) return; // is a different one active? if so kill it if ( _activeDs ) clearDecoration(); // try to find and enable the new one DecorationMap::iterator i = _dsMap.find(name); if ( i != _dsMap.end() ) { Decoration* ds = i->second.get(); if ( ds ) { if ( this->accept(ds, true) ) { _activeDs = ds; _activeDsName = name; } } } } void AnnotationNode::clearDecoration() { if ( _activeDs ) { this->accept(_activeDs, false); _activeDs = 0L; _activeDsName = ""; } } bool AnnotationNode::hasDecoration( const std::string& name ) const { return _dsMap.find(name) != _dsMap.end(); } osg::Group* AnnotationNode::getChildAttachPoint() { osg::Transform* t = osgEarth::findTopMostNodeOfType<osg::Transform>(this); return t ? (osg::Group*)t : (osg::Group*)this; } bool AnnotationNode::supportsAutoClamping( const Style& style ) const { return !style.has<ExtrusionSymbol>() && !style.has<ModelSymbol>() && !style.has<MarkerSymbol>() && // backwards-compability style.has<AltitudeSymbol>() && (style.get<AltitudeSymbol>()->clamping() == AltitudeSymbol::CLAMP_TO_TERRAIN || style.get<AltitudeSymbol>()->clamping() == AltitudeSymbol::CLAMP_RELATIVE_TO_TERRAIN) && style.get<AltitudeSymbol>()->technique() != AltitudeSymbol::TECHNIQUE_GPU; } void AnnotationNode::configureForAltitudeMode( const AltitudeMode& mode ) { bool cpuClamp = false; if ( _altitude.valid() ) { bool clamp = _altitude->clamping() == _altitude->CLAMP_TO_TERRAIN || _altitude->clamping() == _altitude->CLAMP_RELATIVE_TO_TERRAIN; bool gpuClamp = clamp && _altitude->technique() == _altitude->TECHNIQUE_GPU; cpuClamp = (mode == ALTMODE_RELATIVE || clamp) && !gpuClamp; if ( clamp && mode == ALTMODE_ABSOLUTE ) { // note: altitude mode conflicts with style. } } setCPUAutoClamping( cpuClamp ); } void AnnotationNode::applyStyle( const Style& style) { if ( supportsAutoClamping(style) ) { _altitude = style.get<AltitudeSymbol>(); setCPUAutoClamping( true ); } applyRenderSymbology(style); } void AnnotationNode::applyRenderSymbology(const Style& style) { const RenderSymbol* render = style.get<RenderSymbol>(); if ( render ) { if ( render->depthTest().isSet() ) { getOrCreateStateSet()->setMode( GL_DEPTH_TEST, (render->depthTest() == true? osg::StateAttribute::ON : osg::StateAttribute::OFF) | osg::StateAttribute::OVERRIDE ); } if ( render->lighting().isSet() ) { getOrCreateStateSet()->setMode( GL_LIGHTING, (render->lighting() == true? osg::StateAttribute::ON : osg::StateAttribute::OFF) | osg::StateAttribute::OVERRIDE ); } if ( render->depthOffset().isSet() ) { _doAdapter.setDepthOffsetOptions( *render->depthOffset() ); setDepthAdjustment( true ); } if ( render->backfaceCulling().isSet() ) { getOrCreateStateSet()->setMode( GL_CULL_FACE, (render->backfaceCulling() == true? osg::StateAttribute::ON : osg::StateAttribute::OFF) | osg::StateAttribute::OVERRIDE ); } #ifndef OSG_GLES2_AVAILABLE if ( render->clipPlane().isSet() ) { GLenum mode = GL_CLIP_PLANE0 + render->clipPlane().value(); getOrCreateStateSet()->setMode(mode, 1); } #endif if ( render->order().isSet() || render->renderBin().isSet() ) { osg::StateSet* ss = getOrCreateStateSet(); int binNumber = render->order().isSet() ? (int)render->order()->eval() : ss->getBinNumber(); std::string binName = render->renderBin().isSet() ? render->renderBin().get() : ss->useRenderBinDetails() ? ss->getBinName() : "RenderBin"; ss->setRenderBinDetails(binNumber, binName); } if ( render->minAlpha().isSet() ) { DiscardAlphaFragments().install( getOrCreateStateSet(), render->minAlpha().value() ); } if ( render->transparent() == true ) { osg::StateSet* ss = getOrCreateStateSet(); ss->setRenderingHint( ss->TRANSPARENT_BIN ); } } }
omega-hub/osgearth
src/osgEarthAnnotation/AnnotationNode.cpp
C++
lgpl-3.0
13,525
#!/usr/bin/perl # Makes the test run with tracing enabled by default, can be overridden # with --notrace unshift(@ARGV, "--trace"); if (!$::Driver) { use FindBin; exec("$FindBin::Bin/bootstrap.pl", @ARGV, $0); die; } # DESCRIPTION: Verilator: Verilog Test driver/expect definition # # Copyright 2019 by Todd Strader. This program is free software; you can # redistribute it and/or modify it under the terms of either the GNU # Lesser General Public License Version 3 or the Perl Artistic License # Version 2.0. scenarios( vlt => 1, xsim => 1, ); $Self->{sim_time} = $Self->{benchmark} * 100 if $Self->{benchmark}; # Always compile the secret file with Verilator no matter what simulator # we are testing with my $cmd = ["t/t_prot_lib_secret.pl", "--vlt"]; my $secret_prefix = "t_prot_lib_secret"; my $secret_dir = "$Self->{obj_dir}/../../obj_vlt/$secret_prefix"; while (1) { run(logfile => "$Self->{obj_dir}/secret_compile.log", cmd => $cmd); last if $Self->{errors}; compile( verilator_flags2 => ["$secret_dir/secret.sv", "-LDFLAGS", "'-L../$secret_prefix -lsecret -static'"], xsim_flags2 => ["$secret_dir/secret.sv"], ); execute( check_finished => 1, xsim_run_flags2 => ["--sv_lib", "$secret_dir/libsecret", "--dpi_absolute"], ); if ($Self->{vlt} && $Self->{trace}) { # We can see the ports of the secret module file_grep("$Self->{obj_dir}/simx.vcd", qr/accum_in/); # but we can't see what's inside file_grep_not("$Self->{obj_dir}/simx.vcd", qr/secret_/); } ok(1); last; } 1;
toddstrader/verilator-dev
test_regress/t/t_prot_lib.pl
Perl
lgpl-3.0
1,735
<?php class UrlComponent extends Component { protected $url_original; protected $url_trim; protected $url_array; protected $url_section_count; protected $levels; function initialize(Controller $controller) { $here = $controller->request->here; $request_url = ($controller->request->url) ? $controller->request->url : ''; $this->levels = explode('/', trim($request_url, '/')); $this->url_original = rtrim($here, '/'); $this->url_trim = trim($here, '/'); $this->url_array = explode('/', $this->url_trim); $this->url_section_count = count($this->url_array); } public function getLevels() { return $this->levels; } public function here($p_compare = null) { if (!isset($p_compare)) { return $this->url_original; } $temp1 = strtolower($this->url_original); $temp2 = strtolower(rtrim($p_compare, '/')); return ($temp1 == $temp2); } public function slug($p_compare = null, $p_partial = false) { $result = str_replace('/', '-', $this->url_trim); $result = (empty($result)) ? 'home' : $result; if (empty($p_compare)) { return $result; } else { if (!$p_partial) { return (strtolower($result) == strtolower($p_compare)); } else { return (strpos(strtolower($result), strtolower($p_compare)) !== false); } } } public function local_slug($p_compare = null, $p_partial = false) { $levels = implode('-', $this->getLevels()); $result = str_replace('/', '-', $levels); $result = (empty($result)) ? 'home' : $result; if (empty($p_compare)) { return $result; } else { if (!$p_partial) { return (strtolower($result) == strtolower($p_compare)); } else { return (strpos(strtolower($result), strtolower($p_compare)) !== false); } } } public function url($p_url) { return Router::url($p_url, true); } private function generateRandom() { return chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . mt_rand(1000, 9999); } public function nocache($p_url) { return Router::url($p_url . '?nc=' . $this->generateRandom(), true); } public function version($p_url, $p_version = null) { if (!empty($p_version)) { return (strtolower($p_version) == 'time') ? Router::url($p_url . '?v=' . date('YmdHms'), true) : Router::url($p_url . '?v=' . $p_version, true); } else { return Router::url($p_url . '?v=' . $this->generateRandom(), true); } } public function add() { $url = $this->url_original . '/' . implode('/', func_get_args()); $result = Router::url($url, true); return $result; } public function count($p_quant = null) { if ($p_quant === null) { return $this->url_section_count; } else { return $this->url_section_count == $p_quant; } } public function has($p_section, $p_match_all = false) { $url = $this->here(); $url = strtolower($url); $tmp_array = explode('/', $url); if (is_string($p_section)) { $locate = strtolower($p_section); return in_array($locate, $tmp_array); } if (is_array($p_section)) { if (!$p_match_all) { foreach ($p_section as $key => $section) { $locate = strtolower($section); if (in_array($locate, $tmp_array)) { return true; } } return false; } else { $matchs = array(); foreach ($p_section as $key => $section) { $locate = strtolower($section); if (in_array($locate, $tmp_array)) { if (!in_array($locate, $matchs)) { $matchs[] = $locate; } } } return count($matchs) >= count($p_section); } } return false; } public function local_level($p_level, $p_compare = null) { $levels = $this->getLevels(); $use_level = $p_level; if (empty($use_level)) { $use_level = 1; } if (strtolower($use_level) === 'first') { $use_level = 1; } if (strtolower($use_level) === 'last') { $use_level = count($levels); } if (!empty($levels[$use_level-1])) { $result = $levels[$use_level-1]; return ($p_compare === null) ? $result : (strcasecmp($result, $p_compare) === 0); } return ($p_compare === null) ? '' : ($p_compare === ''); } public function level($p_level, $p_compare = null) { $url = $this->here(); $url = trim($url, '/'); $tmp_array = explode('/', $url); $use_level = $p_level; if (empty($use_level)) { $use_level = 1; } if (strtolower($use_level) === 'first') { $use_level = 1; } if (strtolower($use_level) === 'last') { $use_level = count($tmp_array); } if (!empty($tmp_array[$use_level-1])) { $result = $tmp_array[$use_level-1]; return ($p_compare === null) ? $result : (strcasecmp($result, $p_compare) === 0); } return ($p_compare === null) ? '' : ($p_compare === ''); } public function firstLevel($p_compare = null) { $result = $this->level(1, $p_compare); return $result; } public function lastLevel($p_compare = null) { $result = $this->level('last', $p_compare); return $result; } public function auto_javascript($p_prefix = '', $p_max_level = 3) { App::uses('Folder', 'Utility'); $url = $this->here(); $url = strtolower($url); $url = trim($url, '/'); $tmp_array = explode('/', $url); $tmp_count = count($tmp_array); while($tmp_count > $p_max_level) { unset($tmp_array[count($tmp_array)-1]); $tmp_count = count($tmp_array); } $url = implode('/', $tmp_array); $url = str_replace('/', '-', $url); $url = str_replace('_', '-', $url); $base = trim($p_prefix, '/'); $filename = WWW_ROOT . $base . DS . 'js' . DS . $url . '.js'; $usefile = $this->url('/' . $base . '/' . 'js' . '/' . $url . '.js'); if (file_exists($filename)) { return $this->Html->script($this->url($usefile), array('inline' => false)); } return false; } }
DevUtils/devutils-cakephp-plugin
Controller/Component/UrlComponent.php
PHP
lgpl-3.0
5,782
#include <Wt/WWidget> #include <Wt/WText> #include <Wt/WSignal> #include <Wt/WImage> #include <Wt/WHBoxLayout> #include <boost/algorithm/string.hpp> #include "logger.h" #include "contactentry.h" void ContactEntry::ensureProperTextLength(std::string& text) { if(text.size() > 17) { text.resize(15); text.append("..."); } } ContactEntry::ContactEntry(unsigned int uin, std::string name) : mUin(uin) { ensureProperTextLength(name); setStyleClass("ContactEntry"); Wt::WHBoxLayout *layout = new Wt::WHBoxLayout(); Wt::WContainerWidget* imageHolder = new Wt::WContainerWidget(); imageHolder->resize(20,"100%"); layout->addWidget(imageHolder); Wt::WImage *image = new Wt::WImage("images/na.png"); imageHolder->addWidget(image); mpShowText = new Wt::WText(); if(name.empty()) { mpShowText->setText(boost::lexical_cast<std::string>(uin)); } else { mpShowText->setText(Wt::WString::fromUTF8(name)); } layout->addWidget(mpShowText,1); setLayout(layout); } bool ContactEntry::matchesFilter(std::string filter) const { std::string name = mpShowText->text().toUTF8(); auto result = boost::algorithm::ifind_first(name,filter); if (!result.empty()) return true; std::string uin = (boost::lexical_cast<std::string>(mUin)); result = boost::algorithm::ifind_first(uin,filter); return !result.empty(); }
ntszar/axg
Ui/contactentry.cpp
C++
lgpl-3.0
1,433
#pragma once #include <QtWidgets/QDialog> #include <QtGui/QFont> #include <QtCore/QString> #include <QtCore/QStringList> namespace Ui { class EditHeadlineDialog; } class EditHeadlineDialog : public QDialog { Q_OBJECT public: explicit EditHeadlineDialog(QWidget *parent = nullptr); ~EditHeadlineDialog(); void set_style_name(const QString& name); void set_style_font(const QFont& font); void set_style_stylesheet(const QString& stylesheet); void set_style_triggers(const QStringList& triggers); QString get_style_name() const; QString get_style_stylesheet() const; QStringList get_style_triggers() const; private slots: // void slot_update_font(const QFont& font); // void slot_update_font_size(int index); void slot_apply_stylesheet(); void slot_update_ok(); private: Ui::EditHeadlineDialog *ui{nullptr}; };
b0bh00d/Newsroom
editheadlinedialog.h
C
lgpl-3.0
1,021
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "describeeffectivepatchesforpatchbaselinerequest.h" #include "describeeffectivepatchesforpatchbaselinerequest_p.h" #include "describeeffectivepatchesforpatchbaselineresponse.h" #include "ssmrequest_p.h" namespace QtAws { namespace SSM { /*! * \class QtAws::SSM::DescribeEffectivePatchesForPatchBaselineRequest * \brief The DescribeEffectivePatchesForPatchBaselineRequest class provides an interface for SSM DescribeEffectivePatchesForPatchBaseline requests. * * \inmodule QtAwsSSM * * <fullname>AWS Systems Manager</fullname> * * AWS Systems Manager is a collection of capabilities that helps you automate management tasks such as collecting system * inventory, applying operating system (OS) patches, automating the creation of Amazon Machine Images (AMIs), and * configuring operating systems (OSs) and applications at scale. Systems Manager lets you remotely and securely manage the * configuration of your managed instances. A <i>managed instance</i> is any Amazon Elastic Compute Cloud instance (EC2 * instance), or any on-premises server or virtual machine (VM) in your hybrid environment that has been configured for * Systems * * Manager> * * This reference is intended to be used with the <a * href="https://docs.aws.amazon.com/systems-manager/latest/userguide/">AWS Systems Manager User * * Guide</a>> * * To get started, verify prerequisites and configure managed instances. For more information, see <a * href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up.html">Setting up AWS * Systems Manager</a> in the <i>AWS Systems Manager User * * Guide</i>> <p class="title"> <b>Related resources</b> * * </p <ul> <li> * * For information about how to use a Query API, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/making-api-requests.html">Making API requests</a>. * * </p </li> <li> * * For information about other API actions you can perform on EC2 instances, see the <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/">Amazon EC2 API * * Reference</a>> </li> <li> * * For information about AWS AppConfig, a capability of Systems Manager, see the <a * href="https://docs.aws.amazon.com/appconfig/latest/userguide/">AWS AppConfig User Guide</a> and the <a * href="https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/">AWS AppConfig API * * Reference</a>> </li> <li> * * For information about AWS Incident Manager, a capability of Systems Manager, see the <a * href="https://docs.aws.amazon.com/incident-manager/latest/userguide/">AWS Incident Manager User Guide</a> and the <a * href="https://docs.aws.amazon.com/incident-manager/latest/APIReference/">AWS Incident Manager API * * \sa SsmClient::describeEffectivePatchesForPatchBaseline */ /*! * Constructs a copy of \a other. */ DescribeEffectivePatchesForPatchBaselineRequest::DescribeEffectivePatchesForPatchBaselineRequest(const DescribeEffectivePatchesForPatchBaselineRequest &other) : SsmRequest(new DescribeEffectivePatchesForPatchBaselineRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a DescribeEffectivePatchesForPatchBaselineRequest object. */ DescribeEffectivePatchesForPatchBaselineRequest::DescribeEffectivePatchesForPatchBaselineRequest() : SsmRequest(new DescribeEffectivePatchesForPatchBaselineRequestPrivate(SsmRequest::DescribeEffectivePatchesForPatchBaselineAction, this)) { } /*! * \reimp */ bool DescribeEffectivePatchesForPatchBaselineRequest::isValid() const { return false; } /*! * Returns a DescribeEffectivePatchesForPatchBaselineResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * DescribeEffectivePatchesForPatchBaselineRequest::response(QNetworkReply * const reply) const { return new DescribeEffectivePatchesForPatchBaselineResponse(*this, reply); } /*! * \class QtAws::SSM::DescribeEffectivePatchesForPatchBaselineRequestPrivate * \brief The DescribeEffectivePatchesForPatchBaselineRequestPrivate class provides private implementation for DescribeEffectivePatchesForPatchBaselineRequest. * \internal * * \inmodule QtAwsSSM */ /*! * Constructs a DescribeEffectivePatchesForPatchBaselineRequestPrivate object for Ssm \a action, * with public implementation \a q. */ DescribeEffectivePatchesForPatchBaselineRequestPrivate::DescribeEffectivePatchesForPatchBaselineRequestPrivate( const SsmRequest::Action action, DescribeEffectivePatchesForPatchBaselineRequest * const q) : SsmRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the DescribeEffectivePatchesForPatchBaselineRequest * class' copy constructor. */ DescribeEffectivePatchesForPatchBaselineRequestPrivate::DescribeEffectivePatchesForPatchBaselineRequestPrivate( const DescribeEffectivePatchesForPatchBaselineRequestPrivate &other, DescribeEffectivePatchesForPatchBaselineRequest * const q) : SsmRequestPrivate(other, q) { } } // namespace SSM } // namespace QtAws
pcolby/libqtaws
src/ssm/describeeffectivepatchesforpatchbaselinerequest.cpp
C++
lgpl-3.0
5,892
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_CREATEWEBACLREQUEST_P_H #define QTAWS_CREATEWEBACLREQUEST_P_H #include "wafrequest_p.h" #include "createwebaclrequest.h" namespace QtAws { namespace WAF { class CreateWebACLRequest; class CreateWebACLRequestPrivate : public WafRequestPrivate { public: CreateWebACLRequestPrivate(const WafRequest::Action action, CreateWebACLRequest * const q); CreateWebACLRequestPrivate(const CreateWebACLRequestPrivate &other, CreateWebACLRequest * const q); private: Q_DECLARE_PUBLIC(CreateWebACLRequest) }; } // namespace WAF } // namespace QtAws #endif
pcolby/libqtaws
src/waf/createwebaclrequest_p.h
C
lgpl-3.0
1,378
package nl.siegmann.epublib.html.htmlcleaner; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.htmlcleaner.CleanerProperties; import org.htmlcleaner.CommentNode; import org.htmlcleaner.ContentNode; import org.htmlcleaner.EndTagToken; import org.htmlcleaner.TagNode; public class XmlSerializer { protected CleanerProperties props; public XmlSerializer(CleanerProperties props) { this.props = props; } public void writeXml(TagNode tagNode, XMLStreamWriter writer) throws XMLStreamException { // if ( !props.isOmitXmlDeclaration() ) { // String declaration = "<?xml version=\"1.0\""; // if (charset != null) { // declaration += " encoding=\"" + charset + "\""; // } // declaration += "?>"; // writer.write(declaration + "\n"); // } // if ( !props.isOmitDoctypeDeclaration() ) { // DoctypeToken doctypeToken = tagNode.getDocType(); // if ( doctypeToken != null ) { // doctypeToken.serialize(this, writer); // } // } // serialize(tagNode, writer); writer.flush(); } protected void serializeOpenTag(TagNode tagNode, XMLStreamWriter writer) throws XMLStreamException { String tagName = tagNode.getName(); writer.writeStartElement(tagName); Map tagAtttributes = tagNode.getAttributes(); for(Iterator it = tagAtttributes.entrySet().iterator();it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String attName = (String) entry.getKey(); String attValue = (String) entry.getValue(); if ( !props.isNamespacesAware() && ("xmlns".equals(attName) || attName.startsWith("xmlns:")) ) { continue; } writer.writeAttribute(attName, attValue); } } protected void serializeEmptyTag(TagNode tagNode, XMLStreamWriter writer) throws XMLStreamException { String tagName = tagNode.getName(); writer.writeEmptyElement(tagName); Map tagAtttributes = tagNode.getAttributes(); for(Iterator it = tagAtttributes.entrySet().iterator();it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String attName = (String) entry.getKey(); String attValue = (String) entry.getValue(); if ( !props.isNamespacesAware() && ("xmlns".equals(attName) || attName.startsWith("xmlns:")) ) { continue; } writer.writeAttribute(attName, attValue); } } protected void serializeEndTag(TagNode tagNode, XMLStreamWriter writer) throws XMLStreamException { writer.writeEndElement(); } protected void serialize(TagNode tagNode, XMLStreamWriter writer) throws XMLStreamException { if(tagNode.getChildren().isEmpty()) { serializeEmptyTag(tagNode, writer); } else { serializeOpenTag(tagNode, writer); List tagChildren = tagNode.getChildren(); for(Iterator childrenIt = tagChildren.iterator(); childrenIt.hasNext(); ) { Object item = childrenIt.next(); if (item != null) { serializeToken(item, writer); } } serializeEndTag(tagNode, writer); } } private void serializeToken(Object item, XMLStreamWriter writer) throws XMLStreamException { if ( item instanceof ContentNode ) { writer.writeCharacters(((ContentNode) item).getContent().toString()); } else if(item instanceof CommentNode) { writer.writeComment(((CommentNode) item).getContent().toString()); } else if(item instanceof EndTagToken) { // writer.writeEndElement(); } else if(item instanceof TagNode) { serialize((TagNode) item, writer); } } }
narrative-technologies/epublib
epublib-tools/src/main/java/nl/siegmann/epublib/html/htmlcleaner/XmlSerializer.java
Java
lgpl-3.0
3,933
package net.timmytech.learnmod; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import net.timmytech.learnmod.proxy.IProxy; import net.timmytech.learnmod.reference.Reference; @Mod(modid= Reference.MOD_ID, name=Reference.MOD_NAME, version=Reference.VERSION) public class learnmod { @Mod.Instance(Reference.MOD_ID) public static learnmod instance; @SidedProxy(clientSide = "net.timmytech.learnmod.proxy.ClientProxy", serverSide = "net.timmytech.learnmod.proxy.ServerProxy") public static IProxy proxy; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { } @Mod.EventHandler public void init(FMLInitializationEvent event) { } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { } }
timmyforchelsea/LearningModding
src/main/java/net/timmytech/learnmod/learnmod.java
Java
lgpl-3.0
997
/// <reference path="../references.d.ts" /> /// <reference path="./gameManager.service.ts" /> /// <reference path="../kdarts.ts" /> var kdarts; (function (kdarts) { var game; (function (game) { var X01SidenavController = (function () { function X01SidenavController($state, $mdSidenav, $mdDialog) { this.$state = $state; this.$mdSidenav = $mdSidenav; this.$mdDialog = $mdDialog; } X01SidenavController.prototype.closeMenu = function () { this.$mdSidenav('left').close() .then(function () { }); }; X01SidenavController.prototype.cancelGame = function () { var _this = this; var confirm = this.$mdDialog.confirm() .title('Cancel Game') .content('Are you sure you want to cancel the game?') .ok('Yes') .cancel('Cancel'); this.$mdDialog.show(confirm).then(function () { _this.closeMenu(); _this.$state.go('home'); }, function () { _this.closeMenu(); }); }; X01SidenavController.$inject = ['$state', '$mdSidenav', '$mdDialog']; return X01SidenavController; })(); angular.module('kdarts.game').controller('X01SidenavController', X01SidenavController); })(game = kdarts.game || (kdarts.game = {})); })(kdarts || (kdarts = {})); //# sourceMappingURL=x01sidenav.controller.js.map
tiborbotos/kdarts
archive/public/kdarts2/scripts/game/x01sidenav.controller.js
JavaScript
lgpl-3.0
1,622
h1, h2, h3, h4, h5, h6 { color : Navy; } .varname { background-color: #FFB; font-weight: bold; } .classname { color: #A00; } .function, .methodname { color: #0A0; } .navheader, .navfooter { background-color: #EEF; } .programlisting { border: 2px solid gray; border-style: groove; padding: 2px; background-color: #e7e7ef; } .screen { border: 2px solid gray; border-style: groove; padding: 5px; }
mischat/rdfapi-php
doc/manual.css
CSS
lgpl-3.0
453
/* * * SchemaCrawler * http://www.schemacrawler.com * Copyright (c) 2000-2015, Sualeh Fatehi. * * 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 2.1 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., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * */ package schemacrawler.crawl; import static java.util.Objects.requireNonNull; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import sf.util.Utility; /** * A wrapper around a JDBC resultset obtained from a database metadata * call. This allows type-safe methods to obtain boolean, integer and * string data, while abstracting away the quirks of the JDBC metadata * API. * * @author Sualeh Fatehi */ final class MetadataResultSet implements AutoCloseable { private static final Logger LOGGER = Logger.getLogger(MetadataResultSet.class .getName()); private static final int FETCHSIZE = 20; private final ResultSet results; private final List<String> resultSetColumns; private Set<String> readColumns; MetadataResultSet(final ResultSet resultSet) throws SQLException { results = requireNonNull(resultSet, "Cannot use null results"); try { results.setFetchSize(FETCHSIZE); } catch (final NullPointerException | SQLException e) { LOGGER.log(Level.WARNING, "Could not set fetch size", e); } final List<String> resultSetColumns = new ArrayList<>(); try { final ResultSetMetaData rsMetaData = resultSet.getMetaData(); for (int i = 0; i < rsMetaData.getColumnCount(); i++) { String columnName; columnName = rsMetaData.getColumnLabel(i + 1); if (Utility.isBlank(columnName)) { columnName = rsMetaData.getColumnName(i + 1); } resultSetColumns.add(columnName.toUpperCase()); } } catch (final SQLException e) { LOGGER.log(Level.WARNING, "Could not get columns list"); } this.resultSetColumns = Collections.unmodifiableList(resultSetColumns); readColumns = new HashSet<>(); } /** * Releases this <code>ResultSet</code> object's database and JDBC * resources immediately instead of waiting for this to happen when it * is automatically closed. * * @throws SQLException * On an exception */ @Override public void close() throws SQLException { results.close(); } /** * Gets unread (and therefore unmapped) columns from the database * metadata resultset, and makes them available as addiiotnal * attributes. * * @return Map of additional attributes to the database object */ Map<String, Object> getAttributes() { final Map<String, Object> attributes = new HashMap<>(); for (final String columnName: resultSetColumns) { if (!readColumns.contains(columnName)) { try { final Object value = results.getObject(columnName); attributes.put(columnName, value); } catch (final SQLException | ArrayIndexOutOfBoundsException e) { /* * MySQL connector is broken and can cause * ArrayIndexOutOfBoundsExceptions for no good reason (tested * with connector 5.1.26 and server version 5.0.95). Ignoring * the exception, we can still get some useful data out of the * database. */ LOGGER.log(Level.WARNING, "Could not read value for column " + columnName, e); } } } return attributes; } BigInteger getBigInteger(final String columnName) { String stringBigInteger = getString(columnName); if (Utility.isBlank(stringBigInteger)) { return null; } stringBigInteger = stringBigInteger.replaceAll("[, ]", stringBigInteger); BigInteger value; try { value = new BigInteger(stringBigInteger); } catch (final Exception e) { LOGGER.log(Level.WARNING, "Could not get big integer value", e); return null; } return value; } /** * Checks if the value of a column from the result set evaluates to * true. * * @param columnName * Column name to check * @return Whether the string evaluates to true */ boolean getBoolean(final String columnName) { boolean value = false; if (useColumn(columnName)) { try { final Object booleanValue = results.getObject(columnName); final String stringBooleanValue; if (results.wasNull() || booleanValue == null) { LOGGER.log(Level.FINE, String .format("NULL value for column %s, so evaluating to 'false'", columnName)); stringBooleanValue = null; } else { stringBooleanValue = String.valueOf(booleanValue).trim(); } if (!Utility.isBlank(stringBooleanValue)) { try { final int booleanInt = Integer.parseInt(stringBooleanValue); value = booleanInt != 0; } catch (final NumberFormatException e) { value = stringBooleanValue.equalsIgnoreCase("YES") || Boolean.valueOf(stringBooleanValue).booleanValue(); } } } catch (final SQLException e) { LOGGER.log(Level.WARNING, "Could not read boolean value for column " + columnName, e); } } return value; } /** * Reads the value of a column from the result set as an enum. * * @param columnName * Column name * @param defaultValue * Default enum value to return * @return Enum value of the column, or the default if not available */ <E extends Enum<E>> E getEnum(final String columnName, final E defaultValue) { final String value = getString(columnName); E enumValue; if (value == null || defaultValue == null) { enumValue = defaultValue; } else { try { enumValue = (E) Enum.valueOf(defaultValue.getClass(), value.toLowerCase(Locale.ENGLISH)); } catch (final Exception e) { enumValue = defaultValue; } } return enumValue; } /** * Reads the value of a column from the result set as an integer. If * the value was null, returns the default. * * @param columnName * Column name * @param defaultValue * Default value * @return Integer value of the column, or the default if not * available */ int getInt(final String columnName, final int defaultValue) { int value = defaultValue; if (useColumn(columnName)) { try { value = results.getInt(columnName); if (results.wasNull()) { LOGGER.log(Level.FINE, String .format("NULL int value for column %s, so using default %d", columnName, defaultValue)); value = defaultValue; } } catch (final SQLException e) { LOGGER.log(Level.WARNING, "Could not read integer value for column " + columnName, e); } } return value; } /** * Reads the value of a column from the result set as a long. If the * value was null, returns the default. * * @param columnName * Column name * @param defaultValue * Default value * @return Long value of the column, or the default if not available */ long getLong(final String columnName, final long defaultValue) { long value = defaultValue; if (useColumn(columnName)) { try { value = results.getLong(columnName); if (results.wasNull()) { LOGGER.log(Level.FINE, String .format("NULL long value for column %s, so using default %d", columnName, defaultValue)); value = defaultValue; } } catch (final SQLException e) { LOGGER.log(Level.WARNING, "Could not read long value for column " + columnName, e); } } return value; } /** * Reads the value of a column from the result set as a short. If the * value was null, returns the default. * * @param columnName * Column name * @param defaultValue * Default value * @return Short value of the column, or the default if not available */ short getShort(final String columnName, final short defaultValue) { short value = defaultValue; if (useColumn(columnName)) { try { value = results.getShort(columnName); if (results.wasNull()) { LOGGER.log(Level.FINE, String .format("NULL short value for column %s, so using default %d", columnName, defaultValue)); value = defaultValue; } } catch (final SQLException e) { LOGGER.log(Level.WARNING, "Could not read short value for column " + columnName, e); } } return value; } /** * Reads the value of a column from the result set as a string. * * @param columnName * Column name * @return String value of the column, or null if not available */ String getString(final String columnName) { String value = null; if (useColumn(columnName)) { try { value = results.getString(columnName); if (results.wasNull()) { LOGGER.log(Level.FINE, String .format("NULL value for column %s, so using null string", columnName)); value = null; } if (value != null) { value = value.trim(); } } catch (final SQLException e) { LOGGER.log(Level.WARNING, "Could not read string value for column " + columnName, e); } } return value; } /** * Moves the cursor down one row from its current position. A * <code>ResultSet</code> cursor is initially positioned before the * first row; the first call to the method <code>next</code> makes the * first row the current row; the second call makes the second row the * current row, and so on. * * @return <code>true</code> if the new current row is valid; * <code>false</code> if there are no more rows * @throws SQLException * On a database access error */ boolean next() throws SQLException { readColumns = new HashSet<>(); return results.next(); } private boolean useColumn(final String columnName) { final boolean useColumn = columnName != null && resultSetColumns.contains(columnName); if (useColumn) { readColumns.add(columnName); } return useColumn; } }
ceharris/SchemaCrawler
schemacrawler-api/src/main/java/schemacrawler/crawl/MetadataResultSet.java
Java
lgpl-3.0
11,937
Status -------------------------------------------------------------------------------- This is a pre-release repository. It's not yet fully ready for use in real applications, but can be already used for familiarization. Information -------------------------------------------------------------------------------- RDRS is an open-source realtime digital radio physics and simulation library. It can be used for modelling behavior of the digital radio link in realtime and modelling the effects of radio transmission on the data. Target Use -------------------------------------------------------------------------------- RDRS requires a 64-bit OS for a full support for high-speed long-range radio communication and enough free space on hard drive for storing the sent data. If long-range radio support is not required, the 32-bit version will suffice. The following platforms are supported: - Windows (32-bit and 64-bit) - Linux (32-bit and 64-bit)
FoxWorks/RDRS
README.md
Markdown
lgpl-3.0
957
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_CREATESECURITYCONFIGURATIONREQUEST_P_H #define QTAWS_CREATESECURITYCONFIGURATIONREQUEST_P_H #include "emrrequest_p.h" #include "createsecurityconfigurationrequest.h" namespace QtAws { namespace EMR { class CreateSecurityConfigurationRequest; class CreateSecurityConfigurationRequestPrivate : public EmrRequestPrivate { public: CreateSecurityConfigurationRequestPrivate(const EmrRequest::Action action, CreateSecurityConfigurationRequest * const q); CreateSecurityConfigurationRequestPrivate(const CreateSecurityConfigurationRequestPrivate &other, CreateSecurityConfigurationRequest * const q); private: Q_DECLARE_PUBLIC(CreateSecurityConfigurationRequest) }; } // namespace EMR } // namespace QtAws #endif
pcolby/libqtaws
src/emr/createsecurityconfigurationrequest_p.h
C
lgpl-3.0
1,543
/** * Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite 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.0 of the License, or * (at your option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package com.examples.with.different.packagename.testcarver; public class InnerConstructor extends InnerConstructorSuper{ public InnerConstructor(){ super(true); } public InnerConstructor(Object obj){ super(true); } }
sefaakca/EvoSuite-Sefa
master/src/test/java/com/examples/with/different/packagename/testcarver/InnerConstructor.java
Java
lgpl-3.0
1,009
/** * Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite 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.0 of the License, or * (at your option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.seeding; import org.evosuite.EvoSuite; import org.evosuite.Properties; import org.evosuite.SystemTestBase; import org.evosuite.ga.metaheuristics.GeneticAlgorithm; import org.evosuite.testsuite.TestSuiteChromosome; import org.junit.Assert; import org.junit.Test; import com.examples.with.different.packagename.seeding.NumericDynamicDoubleSeeding; import com.examples.with.different.packagename.seeding.NumericDynamicFloatSeeding; import com.examples.with.different.packagename.seeding.NumericDynamicIntSeeding; import com.examples.with.different.packagename.seeding.NumericDynamicLongSeeding; /** * @author jmr * */ public class NumericDynamicSeedingSystemTest extends SystemTestBase { public static final double defaultDynamicPool = Properties.DYNAMIC_POOL; // DOUBLES @Test public void testDynamicSeedingDouble() { EvoSuite evosuite = new EvoSuite(); String targetClass = NumericDynamicDoubleSeeding.class.getCanonicalName(); Properties.TARGET_CLASS = targetClass; Properties.CLIENT_ON_THREAD = true; Properties.DYNAMIC_SEEDING = true; //Properties.ALGORITHM = Properties.Algorithm.ONEPLUSONEEA; Properties.DYNAMIC_POOL = 0.8d; // Probability of picking value from constants pool ConstantPoolManager.getInstance().reset(); String[] command = new String[] { "-generateSuite", "-class", targetClass, "-Dprint_to_system=true" }; Object result = evosuite.parseCommandLine(command); GeneticAlgorithm<?> ga = getGAFromResult(result); TestSuiteChromosome best = (TestSuiteChromosome) ga.getBestIndividual(); System.out.println("EvolvedTestSuite:\n" + best); System.out.println("ConstantPool:\n" + ConstantPoolManager.getInstance().getDynamicConstantPool().toString()); Assert.assertEquals("Non-optimal coverage: ", 1d, best.getCoverage(), 0.001); } // FLOATS @Test public void testDynamicSeedingFloat() { EvoSuite evosuite = new EvoSuite(); String targetClass = NumericDynamicFloatSeeding.class.getCanonicalName(); Properties.TARGET_CLASS = targetClass; Properties.CLIENT_ON_THREAD = true; Properties.DYNAMIC_SEEDING = true; //Properties.ALGORITHM = Properties.Algorithm.ONEPLUSONEEA; Properties.DYNAMIC_POOL = 0.8f; // Probability of picking value from constants pool ConstantPoolManager.getInstance().reset(); String[] command = new String[] { "-generateSuite", "-class", targetClass, "-Dprint_to_system=true" }; Object result = evosuite.parseCommandLine(command); GeneticAlgorithm<?> ga = getGAFromResult(result); TestSuiteChromosome best = (TestSuiteChromosome) ga.getBestIndividual(); System.out.println("EvolvedTestSuite:\n" + best); System.out.println("ConstantPool:\n" + ConstantPoolManager.getInstance().getDynamicConstantPool().toString()); Assert.assertEquals("Non-optimal coverage: ", 1d, best.getCoverage(), 0.001); } // LONGS @Test public void testDynamicSeedingLong() { EvoSuite evosuite = new EvoSuite(); String targetClass = NumericDynamicLongSeeding.class.getCanonicalName(); Properties.TARGET_CLASS = targetClass; Properties.CLIENT_ON_THREAD = true; Properties.DYNAMIC_SEEDING = true; //Properties.ALGORITHM = Properties.Algorithm.ONEPLUSONEEA; Properties.DYNAMIC_POOL = 0.8; // Probability of picking value from constants pool ConstantPoolManager.getInstance().reset(); String[] command = new String[] { "-generateSuite", "-class", targetClass, "-Dprint_to_system=true" }; Object result = evosuite.parseCommandLine(command); GeneticAlgorithm<?> ga = getGAFromResult(result); TestSuiteChromosome best = (TestSuiteChromosome) ga.getBestIndividual(); System.out.println("EvolvedTestSuite:\n" + best); System.out.println("ConstantPool:\n" + ConstantPoolManager.getInstance().getDynamicConstantPool().toString()); Assert.assertEquals("Non-optimal coverage: ", 1d, best.getCoverage(), 0.001); } // INTS @Test public void testDynamicSeedingInt() { EvoSuite evosuite = new EvoSuite(); String targetClass = NumericDynamicIntSeeding.class.getCanonicalName(); Properties.TARGET_CLASS = targetClass; Properties.CLIENT_ON_THREAD = true; Properties.DYNAMIC_SEEDING = true; //Properties.ALGORITHM = Properties.Algorithm.ONEPLUSONEEA; Properties.DYNAMIC_POOL = 0.8; // Probability of picking value from constants pool ConstantPoolManager.getInstance().reset(); String[] command = new String[] { "-generateSuite", "-class", targetClass, "-Dprint_to_system=true" }; Object result = evosuite.parseCommandLine(command); GeneticAlgorithm<?> ga = getGAFromResult(result); TestSuiteChromosome best = (TestSuiteChromosome) ga.getBestIndividual(); System.out.println("EvolvedTestSuite:\n" + best); System.out.println("ConstantPool:\n" + ConstantPoolManager.getInstance().getDynamicConstantPool().toString()); Assert.assertEquals("Non-optimal coverage: ", 1d, best.getCoverage(), 0.001); } }
sefaakca/EvoSuite-Sefa
master/src/test/java/org/evosuite/seeding/NumericDynamicSeedingSystemTest.java
Java
lgpl-3.0
5,701
/** * Copyright (c) 2014, Ruediger Moeller. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 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 * * Date: 03.01.14 * Time: 21:19 * To change this template use File | Settings | File Templates. */ package org.nustaq.fastcast.config; /** * Created with IntelliJ IDEA. * User: moelrue * Date: 8/5/13 * Time: 5:18 PM * To change this template use File | Settings | File Templates. */ public class SubscriberConf { int topicId; /////////////////////////////////////////////////////////////////////////////// // // buffers // /////////////////////////////////////////////////////////////////////////////// // in case of gaps, buffer that many received packets (=datagram in fastcast context). // KEPT PER SENDER PER TOPIC !. So value of 10 with 10 senders on 2 topics = 20000 = 160MB with 8kb packets // increase for high volume receivers causing retransmissions (the larger, the fewer retransmissions will be there) int receiveBufferPackets = 5000; /////////////////////////////////////////////////////////////////////////////// // // timings // /////////////////////////////////////////////////////////////////////////////// // time interval until a receiver sends a retransmission request after a gap long maxDelayRetransMS = 1; // time until a retransrequest is sent again if sender does not fulfill long maxDelayNextRetransMS = 5; // time until a sender is lost+deallocated if it stops sending heartbeats // on overload i had crashes from false overload induced timeouts and receive of packets after buffer dealloc // pls report once you observe crashes ! long senderHBTimeout = 10000; /////////////////////////////////////////////////////////////////////////////// // // receiver misc // /////////////////////////////////////////////////////////////////////////////// // accept packet loss. don't send retransmissions. Note that this only works for messages < datagramsize (see transport conf) boolean unreliable = false; public SubscriberConf() { } public SubscriberConf(int topicId) { this.topicId = topicId; } public int getTopicId() { return topicId; } public SubscriberConf topicId(int topicId) { this.topicId = topicId; return this; } public int getReceiveBufferPackets() { return receiveBufferPackets; } public SubscriberConf receiveBufferPackets(int receiveBufferPackets) { this.receiveBufferPackets = receiveBufferPackets; return this; } public long getMaxDelayRetransMS() { return maxDelayRetransMS; } public SubscriberConf maxDelayRetransMS(long maxDelyRetransMS) { this.maxDelayRetransMS = maxDelyRetransMS; return this; } public long getMaxDelayNextRetransMS() { return maxDelayNextRetransMS; } public SubscriberConf maxDelayNextRetransMS(long maxDelayNextRetransMS) { this.maxDelayNextRetransMS = maxDelayNextRetransMS; return this; } public long getSenderHBTimeout() { return senderHBTimeout; } public SubscriberConf setSenderHBTimeout(long senderHBTimeout) { this.senderHBTimeout = senderHBTimeout; return this; } public boolean isUnreliable() { return unreliable; } public SubscriberConf unreliable(boolean unreliable) { this.unreliable = unreliable; return this; } }
RuedigerMoeller/fast-cast
src/main/java/org/nustaq/fastcast/config/SubscriberConf.java
Java
lgpl-3.0
4,223
from ctypes import* import math lib = cdll.LoadLibrary("Z:\\Documents\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMIComponent\\bin\\Debug\\SWMMComponent.dll") print(lib) print("\n") finp = b"Z:\\Documents\\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMINoGlobalsPythonTest\\test.inp" frpt = b"Z:\\Documents\\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMINoGlobalsPythonTest\\test.rpt" fout = b"Z:\\Documents\\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMINoGlobalsPythonTest\\test.out" project = lib.swmm_open(finp , frpt , fout) print(project) print("\n") newHour = 0 oldHour = 0 theDay = 0 theHour = 0 elapsedTime = c_double() if(lib.swmm_getErrorCode(project) == 0): lib.swmm_start(project, 1) if(lib.swmm_getErrorCode(project) == 0): print("Simulating day: 0 Hour: 0") print("\n") while True: lib.swmm_step(project, byref(elapsedTime)) newHour = elapsedTime.value * 24 if(newHour > oldHour): theDay = int(elapsedTime.value) temp = math.floor(elapsedTime.value) temp = (elapsedTime.value - temp) * 24.0 theHour = int(temp) #print("\b\b\b\b\b\b\b\b\b\b\b\b\b\b") #print("\n") print "Hour " , str(theHour) , " Day " , str(theDay) , ' \r', #print("\n") oldHour = newHour if(elapsedTime.value <= 0 or not lib.swmm_getErrorCode(project) == 0): break lib.swmm_end(project) lib.swmm_report(project) lib.swmm_close(project)
cbuahin/SWMMOpenMIComponent
Source/SWMMOpenMINoGlobalsPythonTest/SWMMOpenMINoGlobalsPythonTest.py
Python
lgpl-3.0
1,641
/** * Squidy Interaction 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. * * Squidy Interaction 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 Squidy Interaction Library. If not, see * <http://www.gnu.org/licenses/>. * * 2009 Human-Computer Interaction Group, University of Konstanz. * <http://hci.uni-konstanz.de> * * Please contact info@squidy-lib.de or visit our website * <http://www.squidy-lib.de> for further information. */ package org.squidy.nodes.tracking; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.ServerSocket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Vector; import java.io.IOException; import javax.imageio.ImageIO; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.squidy.manager.ProcessException; import org.squidy.manager.controls.ComboBox; import org.squidy.manager.controls.TextField; import org.squidy.manager.data.DataConstant; import org.squidy.manager.data.IDataContainer; import org.squidy.manager.data.Processor; import org.squidy.manager.data.Property; import org.squidy.manager.data.Throughput; import org.squidy.manager.data.domainprovider.impl.EndianDomainProvider; import org.squidy.manager.data.impl.DataObject; import org.squidy.manager.data.impl.DataPosition2D; import org.squidy.manager.model.AbstractNode; import org.squidy.manager.util.DataUtility; import org.squidy.nodes.ir.ConfigManagable; import org.squidy.nodes.tracking.config.ConfigNotifier; import java.net.Socket; import com.illposed.osc.Endian; import com.illposed.osc.OSCBundle; import com.illposed.osc.OSCListener; import com.illposed.osc.OSCMessage; import com.illposed.osc.OSCPortIn; import com.illposed.osc.OSCPortOut; public class CameraConfigComm /*extends Thread*/ implements ImageCallback { private static final Log LOG = LogFactory.getLog(CameraConfigComm.class); private String addressOutgoing = "127.0.0.1"; private int portOutgoing = 4444; public int getPortOutgoing() { return portOutgoing; } public void setPortOutgoing(int portOutgoing) { if( portOutgoing != this.portOutgoing){ this.portOutgoing = portOutgoing; if( oscPortOut != null){ oscPortOut.close(); try { oscPortOut = new OSCPortOut(InetAddress.getByName(addressOutgoing), portOutgoing); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private int portIncoming = 4445; public int getPortIncoming() { return portIncoming; } public void setPortIncoming(int portIncoming) { if( portIncoming != this.portIncoming){ this.portIncoming = portIncoming; if( oscPortIn != null){ oscPortIn.stopListening(); oscPortIn.close(); try { oscPortIn = new OSCPortIn(portIncoming, endian); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } startConfigListener(); } } } private int id = 0; private boolean isFirstImageRequest = true; private OSCPortOut oscPortOut; private OSCPortIn oscPortIn; private ServerSocket imageServer; private Socket imageClient; private DatagramSocket imageClientUDP; private boolean initDone = false; private Endian endian; private CameraCallback configUpdate; private DataInputStream is; private String line; private int MAX_LEN = 100000; private byte[] imgBuffer; private int imgLoadDelay = 250; private ImageListener il; private boolean connectedToImageClient = false; private boolean streamImage = false; private ImageListener imageListener = null; private boolean isStopped = true; private int imageServerPort = 7777; public int getImageServerPort() { return imageServerPort; } public void setImageServerPort(int imageServerPort) { if(imageServerPort != this.imageServerPort){ this.imageServerPort = imageServerPort; try { if(imageServer != null) { imageServer.close(); imageServer = new ServerSocket(imageServerPort); if( imageListener != null){ imageListener = new ImageListener(imageServer, this); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public boolean isStopped() { return isStopped; } public void setStopped(boolean isStopped) { this.isStopped = isStopped; } public CameraConfigComm(String addressOut, int portOut, int portIn, int imageServerPort, Endian endian, CameraCallback cb) { this.imageServerPort = imageServerPort; portOutgoing = portOut; portIncoming = portIn; addressOutgoing = addressOut; this.endian = endian; configUpdate = cb; } public void updateImage(BufferedImage img) { configUpdate.imageUpdate(img); } /* * public void streamImage(){ new Thread() { * * @Override public void run() { super.run(); * * * * * } }.start(); } */ /* @Override public void run() { imageListener.setStopped(false); while (!isInterrupted() && !isStopped) { try { Thread.sleep(imgLoadDelay); OSCBundle bundle = new OSCBundle(); OSCMessage param = new OSCMessage("/config/param"); param.addArgument(id); param.addArgument(1); param.addArgument("set"); param.addArgument("stream_image"); param.addArgument("bool"); param.addArgument("true"); bundle.addPacket(param); try { oscPortOut.send(bundle); } catch (IOException e) { interrupt(); imageListener.setStopped(true); //throw new ProcessException(e.getMessage(), e); } if (!imageListener.isAlive()) imageListener.start(); } catch (InterruptedException e) { interrupt(); // System.out.println( "Unterbrechung in sleep()" ); } } imageListener.setStopped(true); } */ public void closeConnections() { if(oscPortOut != null) oscPortOut.close(); if(oscPortIn != null) { oscPortIn.stopListening(); oscPortIn.close(); } //if(imageClientUDP != null) { //imageClientUDP.close(); } try { if(imageServer != null) { imageServer.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } initDone = false; } public void initConnection() throws UnknownHostException { try { //if(oscPortOut == null ) { oscPortOut = new OSCPortOut(InetAddress.getByName(addressOutgoing), portOutgoing); } //if(oscPortIn == null ) { oscPortIn = new OSCPortIn(portIncoming, endian); startConfigListener(); } //imageClientUDP = new DatagramSocket(7778); try { //if( imageServer == null && !imageServer.isBound()){ imageServer = new ServerSocket(imageServerPort); //} } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } initDone = true; } catch (SocketException e) { throw new ProcessException(e.getMessage(), e); } } public void waitForImage() { try { /* * byte[] imgArrUDP = new byte[MAX_LEN]; DatagramPacket p = new * DatagramPacket(imgArrUDP, MAX_LEN); imageClientUDP.receive(p); * byte[] imgArr = new byte[p.getLength()]; * System.arraycopy(imgArrUDP, 0, imgArr, 0, p.getLength()); */ if (!connectedToImageClient) { imageClient = imageServer.accept(); connectedToImageClient = true; } is = new DataInputStream(imageClient.getInputStream()); int i1 = is.read(); int i2 = is.read(); int i3 = is.read(); int i4 = is.read(); String s1 = Integer.toHexString(i1); String s2 = Integer.toHexString(i2); String s3 = Integer.toHexString(i3); String s4 = Integer.toHexString(i4); String sHex = s4 + s3 + s2 + s1; int imgLen = Integer.parseInt(sHex, 16); byte[] imgArr = new byte[imgLen]; byte[] imgTemp = new byte[imgLen]; int numBytesRead = is.read(imgTemp, 0, imgLen); System.arraycopy(imgTemp, 0, imgArr, 0, numBytesRead); while (numBytesRead < imgLen) { int bytesRead = is.read(imgTemp, 0, imgLen); System.arraycopy(imgTemp, 0, imgArr, numBytesRead - 1, bytesRead); numBytesRead += bytesRead; } // byte [] imgArr = new byte[v.size()]; // byte[] imgArr = (byte[])al.toArray(); BufferedImage image = ImageIO .read(new ByteArrayInputStream(imgArr)); File outputFile = new File("image.jpg"); ImageIO.write(image, "JPG", outputFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void startConfigListener() { oscPortIn.addListener("/config/param", new OSCListener() { public void acceptMessages(Date time, OSCMessage[] messages) { for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); int ackID = -1; int numArgs = arguments.length; ackID = Integer.parseInt(arguments[0].toString()); int numParams = Integer.parseInt(arguments[1].toString()); for( int i = 2; i < numArgs; i+=4) { String command = arguments[i].toString(); String name = arguments[i + 1].toString(); String type = arguments[i + 2].toString(); String value = arguments[i+3].toString(); configUpdate.configUpdate(name, type, value); } } } }); oscPortIn.startListening(); } public void sendMultipleParameters(String name, String type, String [] values, int numParams) { if (!initDone) { try { initConnection(); } catch (UnknownHostException e1) { if (LOG.isErrorEnabled()) { LOG.error(e1.getMessage(), e1); } System.out.println("Could not connect to Camera on " + addressOutgoing + " : " + portOutgoing); return; } } OSCBundle bundle = new OSCBundle(); OSCMessage param = new OSCMessage("/config/param"); param.addArgument(id); param.addArgument(numParams); param.addArgument("set"); for( int i = 0; i < numParams; i++ ){ param.addArgument(name); param.addArgument(type); param.addArgument(values[i]); } bundle.addPacket(param); // int len = bundle.getByteArray().length; try { oscPortOut.send(bundle); } catch (IOException e) { throw new ProcessException(e.getMessage(), e); } } public void sendParameter(String name, String type, String value) { if (!initDone) { try { initConnection(); } catch (UnknownHostException e1) { if (LOG.isErrorEnabled()) { LOG.error(e1.getMessage(), e1); } System.out.println("Could not connect to Camera on " + addressOutgoing + " : " + portOutgoing); return; } } OSCBundle bundle = new OSCBundle(); OSCMessage param = new OSCMessage("/config/param"); param.addArgument(id); param.addArgument(1); param.addArgument("set"); param.addArgument(name); param.addArgument(type); param.addArgument(value); bundle.addPacket(param); int len = bundle.getByteArray().length; if (name.equals("stream_image") && value.equals("true")) { //init imageServer if (imageServer == null) { try { imageServer = new ServerSocket(imageServerPort); } catch (IOException e) { e.printStackTrace(); imageServer = null; } } if (imageListener == null) { imageListener = new ImageListener(imageServer, this); imageListener.start(); } } //send try { oscPortOut.send(bundle); } catch (IOException e) { throw new ProcessException(e.getMessage(), e); } /* if (name.equals("stream_image") && value.equals("true")) { try { imageServer.close(); imageServer = new ServerSocket(imageServerPort); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } imageListener = new ImageListener(imageServer, this); if (!this.isAlive()) this.start(); else this.resume(); } else if (name.equals("stream_image") && value.equals("false")) { try { imageServer.close(); imageServer = new ServerSocket(imageServerPort); if (this.isAlive()) this.suspend(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { oscPortOut.send(bundle); } catch (IOException e) { throw new ProcessException(e.getMessage(), e); } } */ id++; } /* * public void requestImage() { if( !initDone ) { try { initConnection(); } * catch (UnknownHostException e1) { if (LOG.isErrorEnabled()) { * LOG.error(e1.getMessage(), e1); } * System.out.println("Could not connect to Camera on " + addressOutgoing + * " : " + portOutgoing); return; } } OSCBundle bundle = new OSCBundle(); * OSCMessage param = new OSCMessage("/config/param"); * param.addArgument(id); param.addArgument("get"); * param.addArgument("image"); bundle.addPacket(param); int len = * bundle.getByteArray().length; try { oscPortOut.send(bundle); } catch * (IOException e) { throw new ProcessException(e.getMessage(), e); } id++; * } */ }
raedle/Squidy
squidy-nodes/src/main/java/org/squidy/nodes/tracking/CameraConfigComm.java
Java
lgpl-3.0
14,362
// Created file "Lib\src\mfuuid\mfinternal_i" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_IMFByteStreamReservation, 0x1a37165b, 0x2079, 0x402c, 0x9e, 0x2c, 0xeb, 0xcd, 0xed, 0xe8, 0xc1, 0x2f);
Frankie-PellesC/fSDK
Lib/src/mfuuid/mfinternal_i00000055.c
C
lgpl-3.0
467
package com.sirma.itt.seip.eai.content.tool.params; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.mockito.Mockito; import com.sirma.itt.seip.eai.content.tool.exception.EAIRuntimeException; import javafx.application.Application.Parameters; public class ParametersProviderTest { @Test public void testGetAndSetParameters() { Parameters parameters = Mockito.mock(Parameters.class); Map<String, String> paramsNamed = new HashMap<>(); paramsNamed.put(ParametersProvider.PARAM_API_URL, "http://0.0.0.0:11999"); paramsNamed.put(ParametersProvider.PARAM_AUTHORIZATION, "header"); paramsNamed.put(ParametersProvider.PARAM_CONTENT_URI, "emf:uri"); Mockito.when(parameters.getNamed()).thenReturn(paramsNamed); ParametersProvider.setParameters(parameters); assertNotNull(ParametersProvider.get(ParametersProvider.PARAM_API_URL)); } @Test(expected = EAIRuntimeException.class) public void testGetAndSetParametersWithMissingParams() { Parameters parameters = Mockito.mock(Parameters.class); Map<String, String> paramsNamed = new HashMap<>(); paramsNamed.put(ParametersProvider.PARAM_AUTHORIZATION, "header"); paramsNamed.put(ParametersProvider.PARAM_CONTENT_URI, "emf:uri"); Mockito.when(parameters.getNamed()).thenReturn(paramsNamed); ParametersProvider.setParameters(parameters); } }
SirmaITT/conservation-space-1.7.0
docker/sirma-platform/eai/eai-domain-tools/eai-content-tool/src/test/java/com/sirma/itt/seip/eai/content/tool/params/ParametersProviderTest.java
Java
lgpl-3.0
1,396
package bpellint.core.validators.xml; import org.pmw.tinylog.Logger; import api.ValidationException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.nio.file.Path; public class XMLValidator { private static DocumentBuilderFactory dbf = DocumentBuilderFactory .newInstance(); public void validate(Path path) throws ValidationException { try { DocumentBuilder db = dbf.newDocumentBuilder(); db.parse(path.toFile()); Logger.debug("File " + path + " is a valid XML file"); } catch (Exception e) { throw new ValidationException("The file " + path + " is not well formed", e); } } }
uniba-dsg/BPELlint
src/main/java/bpellint/core/validators/xml/XMLValidator.java
Java
lgpl-3.0
735
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program 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. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\event\player; use pocketmine\event\Event; use pocketmine\network\SourceInterface; use pocketmine\Player; /** * Allows the creation of players overriding the base Player class */ class PlayerCreationEvent extends Event { public static $handlerList = null; /** @var SourceInterface */ private $interface; /** @var mixed */ private $clientId; /** @var string */ private $address; /** @var int */ private $port; /** @var Player::class */ private $baseClass; /** @var Player::class */ private $playerClass; /** * @param SourceInterface $interface * @param Player ::class $baseClass * @param Player ::class $playerClass * @param mixed $clientId * @param string $address * @param int $port */ public function __construct(SourceInterface $interface, $baseClass, $playerClass, $clientId, $address, $port){ $this->interface = $interface; $this->clientId = $clientId; $this->address = $address; $this->port = $port; if(!is_a($baseClass, Player::class, true)){ throw new \RuntimeException("Base class $baseClass must extend " . Player::class); } $this->baseClass = $baseClass; if(!is_a($playerClass, Player::class, true)){ throw new \RuntimeException("Class $playerClass must extend " . Player::class); } $this->playerClass = $playerClass; } /** * @return SourceInterface */ public function getInterface(){ return $this->interface; } /** * @return string */ public function getAddress(){ return $this->address; } /** * @return int */ public function getPort(){ return $this->port; } /** * @return mixed */ public function getClientId(){ return $this->clientId; } /** * @return Player::class */ public function getBaseClass(){ return $this->baseClass; } /** * @param Player ::class $class */ public function setBaseClass($class){ if(!is_a($class, $this->baseClass, true)){ throw new \RuntimeException("Base class $class must extend " . $this->baseClass); } $this->baseClass = $class; } /** * @return Player::class */ public function getPlayerClass(){ return $this->playerClass; } /** * @param Player ::class $class */ public function setPlayerClass($class){ if(!is_a($class, $this->baseClass, true)){ throw new \RuntimeException("Class $class must extend " . $this->baseClass); } $this->playerClass = $class; } }
LeverylTeam/Leveryl
src/pocketmine/event/player/PlayerCreationEvent.php
PHP
lgpl-3.0
3,131
/* * This file is part of MyPet * * Copyright © 2011-2019 Keyle * MyPet is licensed under the GNU Lesser General Public License. * * MyPet 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. * * MyPet 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.Keyle.MyPet.skilltreecreator; import de.Keyle.MyPet.api.Util; import org.nanohttpd.protocols.http.IHTTPSession; import org.nanohttpd.protocols.http.NanoHTTPD; import org.nanohttpd.protocols.http.response.Response; import org.nanohttpd.protocols.http.response.Status; import org.nanohttpd.protocols.websockets.CloseCode; import org.nanohttpd.protocols.websockets.NanoWSD; import org.nanohttpd.protocols.websockets.WebSocket; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class WebServer extends NanoWSD { static Map<String, String> MIME_TYPES = new HashMap<>(); static Response NOT_FOUND = Response.newFixedLengthResponse(Status.NOT_FOUND, "text/plain", "Not Found"); ApiHandler apiHandler; List<WebsocketHandler> websocketHandlers = new ArrayList<>(); public WebServer(File skilltreeDir) throws IOException { super(64712); apiHandler = new ApiHandler(skilltreeDir); setTempFileManagerFactory(new FileManager()); start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); } @Override protected WebSocket openWebSocket(IHTTPSession ihttpSession) { if (ihttpSession.getUri().equals("/websocket")) { WebsocketHandler websocketHandler = new WebsocketHandler(ihttpSession) { @Override protected void onClose(CloseCode code, String reason, boolean initiatedByRemote) { websocketHandlers.remove(this); super.onClose(code, reason, initiatedByRemote); } }; websocketHandlers.add(websocketHandler); return websocketHandler; } return null; } public void sendToWebsockets(String message) { for (WebsocketHandler handler : websocketHandlers) { try { handler.send(message); } catch (IOException e) { e.printStackTrace(); } } } @Override @SuppressWarnings("deprecation") public Response serve(IHTTPSession session) { String uri = session.getUri(); if (uri.equals("/")) { uri = "/index.html"; } System.out.println(session.getMethod().name() + ": " + uri); if (uri.startsWith("/api/")) { return apiHandler.handle(session); } else { return serveFile(uri); } } @Override public void stop() { sendToWebsockets("{\"action\": \"SERVER_STOP\", \"message\": \"Server stopped\"}"); for (WebsocketHandler handler : websocketHandlers) { try { handler.close(CloseCode.GoingAway, "Server stopped", false); } catch (IOException ignored) { } } super.stop(); } public Response serveFile(String uri) { try { return newResourceResponse("gui" + uri); } catch (FileNotFoundException ignored) { try { return newResourceResponse("gui/index.html"); } catch (FileNotFoundException e) { e.printStackTrace(); } } return NOT_FOUND; } public static String getMimeType(String fileName) { String extension = Util.getFileExtension(fileName); if (MIME_TYPES.containsKey(extension)) { return MIME_TYPES.get(extension); } return "text/plain"; } public static Response newFixedJsonResponse(String jsonString) { return Response.newFixedLengthResponse(Status.OK, "application/json", jsonString); } public static Response newFixedFileResponse(File file, String mime) throws FileNotFoundException { Response res = Response.newFixedLengthResponse(Status.OK, mime, new FileInputStream(file), (long) ((int) file.length())); res.addHeader("Accept-Ranges", "bytes"); return res; } public static Response newResourceResponse(String file) throws FileNotFoundException { String mime = getMimeType(file); Response res; try { res = Response.newChunkedResponse(Status.OK, mime, ClassLoader.getSystemResource(file).openStream()); } catch (Exception e) { throw new FileNotFoundException(e.getMessage()); } res.addHeader("Accept-Ranges", "bytes"); return res; } static { MIME_TYPES.put("png", "image/png"); MIME_TYPES.put("svg", "image/svg+xml"); MIME_TYPES.put("js", "application/javascript"); MIME_TYPES.put("json", "application/json"); MIME_TYPES.put("html", "text/html"); MIME_TYPES.put("ico", "image/x-icon"); MIME_TYPES.put("css", "text/css"); } }
xXKeyleXx/MyPet
modules/GUI/src/main/java/de/Keyle/MyPet/skilltreecreator/WebServer.java
Java
lgpl-3.0
5,650
var gui={}; (function() { try { var open = require("open"); var fs = require("fs"); } catch(e) { var open = function(path) { window.open("file://"+path); } } var state = document.getElementById("state"), statemsg = document.getElementById("statemsg"), progress = document.getElementById("progress"), pickdir = document.getElementById("pickdir"), table = document.getElementById("collisions_table").tBodies[0]; pickdir.addEventListener("click", function(){ var fc = document.createElement("input"); fc.type = "file"; fc.value = ""; fc.nwdirectory = true; fc.multiple = true; state.classList.remove("hidden"); fc.onchange = function() { analyze_dir(fc.value); } fc.click(); }, true); gui.update_progress = function(rate) { progress.value = rate; }; gui.set_statemsg = function (msg) { statemsg.innerHTML = msg; }; gui.analyze_authorized = function (auth) { pickdir.disabled = auth; }; function readableSize (size) { if (size > 1e9) return ((size/1e8|0)/10) + " Gb"; else if (size > 1e6) return ((size/1e5|0)/10) + " Mb"; else if (size > 1e3) return ((size/1e2|0)/10) + " Kb"; else return size+" bytes"; } function insert_collision (idx, files, dist) { var row = table.insertRow(idx); row.dataset["dist"] = dist; for (var i=0; i<2; i++) { var cell = row.insertCell(i); var pathElem = document.createTextNode(files[i].dirname+"/"); var fileNameElem = document.createElement("b"); var sizeElem = document.createElement("i"); var deleteBtn = document.createElement("button"); cell.dataset["filepath"] = files[i].filepath; fileNameElem.addEventListener("click",function(e) { var path = e.target.parentElement.dataset["filepath"]; open(path); }, true); fileNameElem.textContent = files[i].stats.name; deleteBtn.textContent = "delete"; deleteBtn.addEventListener("click",function(e) { var path = e.target.parentElement.dataset["filepath"]; if (confirm("Delete "+path+"?")) { fs.unlink(path, function (err) { if (err) { alert("Unable to delete "+path); } else { var row = e.target.parentElement.parentElement; row.parentElement.removeChild(row); } }); } }, true); sizeElem.textContent = readableSize(files[i].stats.size); cell.appendChild(pathElem); cell.appendChild(fileNameElem); cell.appendChild(sizeElem); cell.appendChild(deleteBtn); } cell = row.insertCell(2); cell.textContent = dist; }; gui.display_collision = function (files, dist) { for (var idx=0; idx < table.rows.length; idx++) { //May not be necessary to do a dichotomy if (table.rows[idx].dataset["dist"] >= dist) break; } insert_collision(idx, files, dist); }; gui.init_display_collisions = function() { table.parentElement.classList.remove("hidden"); table.innerHTML = ""; }; gui.all_collisions_displayed = function (ndoublets) { gui.set_statemsg(ndoublets + " collisions found"); gui.update_progress(1); }; })();
lovasoa/doublons-js
src/gui.js
JavaScript
lgpl-3.0
3,002
/** * This file is part of FoxBukkitChat. * * FoxBukkitChat 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. * * FoxBukkitChat 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 FoxBukkitChat. If not, see <http://www.gnu.org/licenses/>. */ package com.foxelbox.foxbukkit.chat.json; public enum MessageType { TEXT, BLANK, KICK, PLAYERSTATE, INJECT, }
FoxelBox/FoxBukkitChat
src/main/java/com/foxelbox/foxbukkit/chat/json/MessageType.java
Java
lgpl-3.0
877
/* * codeare Copyright (C) 2007-2010 Kaveh Vahedipour * Forschungszentrum Juelich, Germany * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "Algos.hpp" #include "EstimateSensitivitiesRadialVIBE.hpp" #include "DFT.hpp" #include "NFFT.hpp" #include "Creators.hpp" static const float NYUGA_RAD = PI*111.246117975f/180.0f; using namespace RRStrategy; codeare::error_code EstimateSensitivitiesRadialVIBE::Init () { try { _kmax_r = GetAttr<float>("kmax_r"); } catch (const TinyXMLQueryException&) {} try { _margin_top = GetAttr<float>("margin_top"); } catch (const TinyXMLQueryException&) {} try { _margin_bottom = GetAttr<float>("margin_bottom"); } catch (const TinyXMLQueryException&) {} _image_space_dims = GetList<size_t>("image_space_dims"); Matrix<cxfl> sensitivities; Add ("sensitivities", sensitivities); return codeare::OK; } codeare::error_code EstimateSensitivitiesRadialVIBE::Prepare () { Matrix<float> kspace, weights, sos; Add<float>("kspace", kspace); Add<float>("weights", weights); Add<float>("sos", sos); return codeare::OK; } inline void EstimateSensitivitiesRadialVIBE::FormGARadialKSpace ( const size_t& nk, const size_t& nv) const { Matrix<float>& kspace = Get<float>("kspace"); Matrix<float>& weights = Get<float>("weights"); kspace = zeros<float>(2,nk,nv); kspace(R(0),R(),R(0)) = linspace<float>(-_kmax_r , _kmax_r, nk); cxfl rot = std::polar<float>(1.0f,NYUGA_RAD); for (size_t j = 1; j < nv; ++j) for (size_t i = 0; i < nk; ++i) { cxfl tmp = rot * cxfl(kspace(0,i,j-1),kspace(1,i,j-1)); kspace(0,i,j) = std::real(tmp); kspace(1,i,j) = std::imag(tmp); } kspace = resize(kspace,2,nv*nk); weights = ones<float>(nv*nk,1); } codeare::error_code EstimateSensitivitiesRadialVIBE::Process () { // Matrices Matrix<cxfl>& meas = Get<cxfl>("meas"); meas = squeeze(1.0e8*meas); Matrix<cxfl>& sensitivities = Get<cxfl>("sensitivities"); Matrix<float>& kspace = Get<float>("kspace"); Matrix<float>& weights = Get<float>("weights"); Matrix<float>& sos = Get<float>("sos"); std::cout << " Incoming: " << size(meas) << std::endl; size_t nk = size(meas,0), nv = size(meas,1), nz = size(meas,2), nc = size(meas,3); // Permute for slice FFT [2 0 1 3] & FFT Vector<size_t> perm(4); perm[0]=2; perm[1]=0; perm[2]=1; perm[3]=3; meas = permute(meas,perm); std::cout << " Permuted for slice FFT: " << size(meas) << std::endl; // Slice FFT std::cout << " Performing slice FFT ..." << std::endl; meas = ifft(meas,0,true); // Removing top and bottom slices meas = meas(CR(_margin_top,nz-1-_margin_bottom),CR(),CR(),CR()); nz = size(meas,0); _image_space_dims[2] = nz; std::cout << " Slice direction reduced: " << size(meas) << std::endl; // Permute for global coil nufft [1 2 0 3] perm[0]=1; perm[1]=2; perm[2]=0; perm[3]=3; meas = permute(meas, perm); std::cout << " Permuted for channel NuFFTs: " << size(meas) << std::endl; meas = resize(meas,nv*nk,nz,nc); std::cout << " Collapsed samples and views dimensions: " << size(meas) << std::endl; // Sort for channel NuFFT: samples, slices, std::cout << " Building GA stack of star k-space trajectory ..." << std::endl; FormGARadialKSpace(nk, nv); // FT operator std::cout << " Building NuFFT operator(s) ..." << std::endl; Vector<size_t> sens_dims = _image_space_dims; sens_dims.push_back(nc); sensitivities = Matrix<cxfl>(sens_dims); Matrix<float> density_comp = zeros<float>(nk,1); Params p; p["nk"] = nv*nk; p["imsz"] = _image_space_dims; p["3rd_dim_cart"] = true; p["m"] = (size_t)1; p["alpha"] = 1.0f; p["epsilon"]=7.e-4f; p["maxit"]=(size_t)1; NFFT<cxfl> ft(p); ft.KSpace(kspace); ft.Weights(weights); std::cout << ft << std::endl; // Channel NuFFTs std::cout << " NuFFTing ..." << std::endl; for (size_t i = 0; i < nc; ++i) sensitivities (R(),R(),R(),R(i)) = ft ->* meas(CR(),CR(),CR(i)); sos = sum(abs(sensitivities),3)+1.e-9; for (size_t i = 0; i < nc; ++i) sensitivities (R(),R(),R(),R(i)) /= sos; meas = resize(meas,nk,nv,nz,nc); kspace = resize(kspace,size(kspace,0),nk,nv); return codeare::OK; } codeare::error_code EstimateSensitivitiesRadialVIBE::Finalise () { return codeare::OK; } // the class factories extern "C" DLLEXPORT ReconStrategy* create () { return new EstimateSensitivitiesRadialVIBE; } extern "C" DLLEXPORT void destroy (ReconStrategy* p) { delete p; }
kvahed/codeare
src/modules/EstimateSensitivitiesRadialVIBE.cpp
C++
lgpl-3.0
5,178
<?php namespace App\Models; use T4\Orm\Model; /** * Class Songs * @package App\Models * * @property string $song * @property string $link * @property \App\Models\Albums $album */ class Songs extends Model { public static $schema = [ 'table' => 'songs', 'columns' => [ 'song' => ['type' => 'string'], 'link' => ['type' => 'text'], ], 'relations' => [ 'album' => [ 'type' => self::BELONGS_TO, 'model' => Albums::class, ], ], ]; }
Mike0712/phpT4
protected/Models/Songs.php
PHP
lgpl-3.0
570
/* * Copyright (C) 1998, 2009 John Pritchard and the Alto Project Group. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package alto.sec; import alto.lang.HttpRequest; import alto.sec.x509.X500Name; import alto.sec.x509.X509Certificate; import alto.sys.IO; import alto.sys.Reference; import alto.sys.Thread; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.security.Key; import java.security.KeyException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.KeyStoreSpi; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.Provider; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.Date; import java.util.Enumeration; /** * Infinite store for certificate entries exclusively. * * @author jdp * @since 1.6 */ public final class TrustStoreSpi extends KeyStoreSpi { public final static TrustStoreSpi Instance = new TrustStoreSpi(); private TrustStoreSpi(){ super(); } public Certificate[] engineGetCertificateChain(java.lang.String alias){ Certificate cert = this.engineGetCertificate(alias); if (null == cert) return null; else return new Certificate[]{cert}; } public Certificate engineGetCertificate(java.lang.String alias){ // IO.Context request = Thread.Context(); // if (null != request){ // Reference reference_subject = TrustStore.SubjectFor(request,alias); // String subject_dn = reference_subject.readString(); // if (null != subject_dn){ // Reference reference_cert = TrustStore.CertificateFor(request,subject_dn); // return reference_cert.readBary(); // } // else return null; // } // else // throw new alto.sys.Error.Bug(); } public Certificate engineGetCertificateForSubject(java.lang.String subject_dn){ // IO.Context request = Thread.Context(); // if (null != request){ // Reference reference_cert = TrustStore.CertificateFor(request,subject_dn); // return reference_cert.getReadParsedX509Certificate(); // } // else throw new alto.sys.Error.Bug(); } public Date engineGetCreationDate(java.lang.String alias){ // IO.Context request = Thread.Context(); // if (null != request){ // Reference reference_subject = TrustStore.SubjectFor(request,alias); // /* // * [TODO] Check DFS protocol // */ // long last = reference_subject.getStorage().lastModified(); // if (0L < last) // return new Date(last); // else return null; // } // else // throw new alto.sys.Error.Bug(); } public void engineSetCertificateEntry(java.lang.String alias, Certificate cert) throws KeyStoreException { // /* // * Currently it's up to the network layer (s.POST) to ensure // * that this op is sane wrt identities and ownership. // */ // if (null != cert && null != alias && cert instanceof X509Certificate){ // X509Certificate x509cert = (X509Certificate)cert; // /* // * [TODO] Check alias for stale DN // */ // Principal subject = x509cert.getSubjectDN(); // if (null != subject){ // IO.Context request = Thread.Context(); // if (null != request){ // Reference reference_subject = TrustStore.SubjectFor(request,alias); // Reference reference_alias = TrustStore.AliasFor(request,subject); // Reference reference_cert = TrustStore.CertificateFor(request,subject); // try { // reference_cert.setWriteParsedX509Certificate(x509cert); // reference_subject.setWriteParsedString(subject.getName()); // reference_alias.setWriteParsedString(alias); // return; // } // catch (java.io.IOException exc){ // throw new KeyStoreException(exc); // } // } // else // throw new alto.sys.Error.Bug(); // } // else // throw new KeyStoreException(); // } // else // throw new KeyStoreException(); } public void engineDeleteEntry(String alias) throws KeyStoreException { } public boolean engineContainsAlias(java.lang.String alias){ // if (null != alias){ // IO.Context request = Thread.Context(); // if (null != request){ // Reference reference = TrustStore.SubjectFor(request,alias); // try { // return (null != reference.readString()); // } // catch (java.io.IOException exc){ // throw new alto.sys.Error.State(exc); // } // } // else throw new alto.sys.Error.Bug(); // } // else // throw new alto.sys.Error.Argument(); } public java.lang.String engineGetCertificateAlias(Certificate cert){ // if (null != cert && cert instanceof X509Certificate){ // X509Certificate x509cert = (X509Certificate)cert; // Principal subject = x509cert.getSubjectDN(); // if (null != subject){ // IO.Context request = Thread.Context(); // if (null != request){ // Reference reference = TrustStore.AliasFor(request,subject); // try { // return reference.readString(); // } // catch (java.io.IOException exc){ // throw new alto.sys.Error.State(exc); // } // } // else throw new alto.sys.Error.Bug(); // } // else // throw new alto.sys.Error.State(); // } // else // throw new alto.sys.Error.Argument(); } public Key engineGetKey(java.lang.String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { throw new java.lang.UnsupportedOperationException(); } public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException { throw new java.lang.UnsupportedOperationException(); } public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { throw new java.lang.UnsupportedOperationException(); } public Enumeration<java.lang.String> engineAliases(){ throw new java.lang.UnsupportedOperationException(); } public int engineSize(){ throw new java.lang.UnsupportedOperationException(); } public boolean engineIsKeyEntry(java.lang.String alias){ return false; } public boolean engineIsCertificateEntry(java.lang.String alias){ return this.engineContainsAlias(alias); } public void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { throw new java.lang.UnsupportedOperationException(); } public void engineStore(KeyStore.LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, CertificateException { throw new java.lang.UnsupportedOperationException(); } public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { throw new java.lang.UnsupportedOperationException(); } public void engineLoad(KeyStore.LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, CertificateException { return;//@see TrustStore#TrustStore() initialization } }
nypgit/alto
src/alto/sec/TrustStoreSpi.java
Java
lgpl-3.0
9,316
namespace SampleHistoryTesting { using System; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Collections.Generic; using Ecng.Xaml; using Ecng.Common; using Ecng.Collections; using Ookii.Dialogs.Wpf; using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.Commissions; using StockSharp.Algo.Storages; using StockSharp.Algo.Testing; using StockSharp.Algo.Indicators; using StockSharp.BusinessEntities; using StockSharp.Logging; using StockSharp.Messages; using StockSharp.Xaml.Charting; using StockSharp.Localization; public partial class MainWindow { // вспомогательный класс для настроек тестирования internal sealed class EmulationInfo { public bool UseMarketDepth { get; set; } public TimeSpan? UseCandleTimeFrame { get; set; } public Color CurveColor { get; set; } public string StrategyName { get; set; } public bool UseOrderLog { get; set; } } private readonly List<HistoryEmulationConnector> _connectors = new List<HistoryEmulationConnector>(); private readonly BufferedChart _bufferedChart; private DateTime _startEmulationTime; private ChartCandleElement _candlesElem; private ChartTradeElement _tradesElem; private ChartIndicatorElement _shortElem; private SimpleMovingAverage _shortMa; private ChartIndicatorElement _longElem; private SimpleMovingAverage _longMa; private ChartArea _area; public MainWindow() { InitializeComponent(); _bufferedChart = new BufferedChart(Chart); HistoryPath.Text = @"..\..\..\HistoryData\".ToFullPath(); From.Value = new DateTime(2012, 10, 1); To.Value = new DateTime(2012, 10, 25); } private void FindPathClick(object sender, RoutedEventArgs e) { var dlg = new VistaFolderBrowserDialog(); if (!HistoryPath.Text.IsEmpty()) dlg.SelectedPath = HistoryPath.Text; if (dlg.ShowDialog(this) == true) { HistoryPath.Text = dlg.SelectedPath; } } private void StartBtnClick(object sender, RoutedEventArgs e) { InitChart(); if (HistoryPath.Text.IsEmpty() || !Directory.Exists(HistoryPath.Text)) { MessageBox.Show(this, LocalizedStrings.Str3014); return; } if (_connectors.Any(t => t.State != EmulationStates.Stopped)) { MessageBox.Show(this, LocalizedStrings.Str3015); return; } var secIdParts = SecId.Text.Split('@'); if (secIdParts.Length != 2) { MessageBox.Show(this, LocalizedStrings.Str3016); return; } var timeFrame = TimeSpan.FromMinutes(5); // создаем настройки для тестирования var settings = new[] { Tuple.Create( TicksCheckBox, TicksTestingProcess, TicksParameterGrid, // тест только на тиках new EmulationInfo {CurveColor = Colors.DarkGreen, StrategyName = LocalizedStrings.Str3017}), Tuple.Create( TicksAndDepthsCheckBox, TicksAndDepthsTestingProcess, TicksAndDepthsParameterGrid, // тест на тиках + стаканы new EmulationInfo {UseMarketDepth = true, CurveColor = Colors.Red, StrategyName = LocalizedStrings.Str3018}), Tuple.Create( CandlesCheckBox, CandlesTestingProcess, CandlesParameterGrid, // тест на свечах new EmulationInfo {UseCandleTimeFrame = timeFrame, CurveColor = Colors.DarkBlue, StrategyName = LocalizedStrings.Str3019}), Tuple.Create( CandlesAndDepthsCheckBox, CandlesAndDepthsTestingProcess, CandlesAndDepthsParameterGrid, // тест на свечах + стаканы new EmulationInfo {UseMarketDepth = true, UseCandleTimeFrame = timeFrame, CurveColor = Colors.Cyan, StrategyName = LocalizedStrings.Str3020}), Tuple.Create( OrderLogCheckBox, OrderLogTestingProcess, OrderLogParameterGrid, // тест на логе заявок new EmulationInfo {UseOrderLog = true, CurveColor = Colors.CornflowerBlue, StrategyName = LocalizedStrings.Str3021}) }; // хранилище, через которое будет производиться доступ к тиковой и котировочной базе var storageRegistry = new StorageRegistry { // изменяем путь, используемый по умолчанию DefaultDrive = new LocalMarketDataDrive(HistoryPath.Text) }; var startTime = (DateTime)From.Value; var stopTime = (DateTime)To.Value; // ОЛ необходимо загружать с 18.45 пред дня, чтобы стаканы строились правильно if (OrderLogCheckBox.IsChecked == true) startTime = startTime.Subtract(TimeSpan.FromDays(1)).AddHours(18).AddMinutes(45).AddTicks(1); // задаем шаг ProgressBar var progressStep = ((stopTime - startTime).Ticks / 100).To<TimeSpan>(); // в реальности период может быть другим, и это зависит от объема данных, // хранящихся по пути HistoryPath, TicksTestingProcess.Maximum = TicksAndDepthsTestingProcess.Maximum = CandlesTestingProcess.Maximum = 100; TicksTestingProcess.Value = TicksAndDepthsTestingProcess.Value = CandlesTestingProcess.Value = 0; var logManager = new LogManager(); var fileLogListener = new FileLogListener("sample.log"); logManager.Listeners.Add(fileLogListener); //logManager.Listeners.Add(new DebugLogListener()); // чтобы смотреть логи в отладчике - работает медленно. var generateDepths = GenDepthsCheckBox.IsChecked == true; var maxDepth = MaxDepth.Text.To<int>(); var maxVolume = MaxVolume.Text.To<int>(); var secCode = secIdParts[0]; var board = ExchangeBoard.GetOrCreateBoard(secIdParts[1]); foreach (var set in settings) { if (set.Item1.IsChecked == false) continue; var progressBar = set.Item2; var statistic = set.Item3; var emulationInfo = set.Item4; // создаем тестовый инструмент, на котором будет производится тестирование var security = new Security { Id = SecId.Text, // по идентификатору инструмента будет искаться папка с историческими маркет данными Code = secCode, Board = board, }; var level1Info = new Level1ChangeMessage { SecurityId = security.ToSecurityId(), ServerTime = startTime, } .TryAdd(Level1Fields.PriceStep, 10m) .TryAdd(Level1Fields.StepPrice, 6m) .TryAdd(Level1Fields.MinPrice, 10m) .TryAdd(Level1Fields.MaxPrice, 1000000m) .TryAdd(Level1Fields.MarginBuy, 10000m) .TryAdd(Level1Fields.MarginSell, 10000m); // тестовый портфель var portfolio = new Portfolio { Name = "test account", BeginValue = 1000000, }; // создаем подключение для эмуляции // инициализируем настройки (инструмент в истории обновляется раз в секунду) var connector = new HistoryEmulationConnector( new[] { security }, new[] { portfolio }) { StorageRegistry = storageRegistry, MarketEmulator = { Settings = { // использовать свечи UseCandlesTimeFrame = emulationInfo.UseCandleTimeFrame, // сведение сделки в эмуляторе если цена коснулась нашей лимитной заявки. // Если выключено - требуется "прохождение цены сквозь уровень" // (более "суровый" режим тестирования.) MatchOnTouch = false, } }, //UseExternalCandleSource = true, CreateDepthFromOrdersLog = emulationInfo.UseOrderLog, CreateTradesFromOrdersLog = emulationInfo.UseOrderLog, }; connector.MarketDataAdapter.SessionHolder.MarketTimeChangedInterval = timeFrame; ((ILogSource)connector).LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info; logManager.Sources.Add(connector); connector.NewSecurities += securities => { //подписываемся на получение данных после получения инструмента if (securities.All(s => s != security)) return; // отправляем данные Level1 для инструмента connector.MarketDataAdapter.SendOutMessage(level1Info); // тест подразумевает наличие стаканов if (emulationInfo.UseMarketDepth) { connector.RegisterMarketDepth(security); if ( // если выбрана генерация стаканов вместо реальных стаканов generateDepths || // для свечей генерируем стаканы всегда emulationInfo.UseCandleTimeFrame != TimeSpan.Zero ) { // если история по стаканам отсутствует, но стаканы необходимы для стратегии, // то их можно сгенерировать на основании цен последних сделок или свечек. connector.RegisterMarketDepth(new TrendMarketDepthGenerator(connector.GetSecurityId(security)) { Interval = TimeSpan.FromSeconds(1), // стакан для инструмента в истории обновляется раз в секунду MaxAsksDepth = maxDepth, MaxBidsDepth = maxDepth, UseTradeVolume = true, MaxVolume = maxVolume, MinSpreadStepCount = 2, // минимальный генерируемый спред - 2 минимальных шага цены MaxSpreadStepCount = 5, // не генерировать спрэд между лучшим бид и аск больше чем 5 минимальных шагов цены - нужно чтобы при генерации из свечей не получалось слишком широкого спреда. MaxPriceStepCount = 3 // максимальное количество шагов между ценами, }); } } else if (emulationInfo.UseOrderLog) { connector.RegisterOrderLog(security); } }; // соединяемся с трейдером и запускаем экспорт, // чтобы инициализировать переданными инструментами и портфелями необходимые свойства EmulationTrader connector.Connect(); connector.StartExport(); var candleManager = new CandleManager(connector); var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame); _shortMa = new SimpleMovingAverage { Length = 10 }; _shortElem = new ChartIndicatorElement { Color = Colors.Coral, ShowAxisMarker = false, FullTitle = _shortMa.ToString() }; _bufferedChart.AddElement(_area, _shortElem); _longMa = new SimpleMovingAverage { Length = 80 }; _longElem = new ChartIndicatorElement { ShowAxisMarker = false, FullTitle = _longMa.ToString() }; _bufferedChart.AddElement(_area, _longElem); // создаем торговую стратегию, скользящие средние на 80 5-минуток и 10 5-минуток var strategy = new SmaStrategy(_bufferedChart, _candlesElem, _tradesElem, _shortMa, _shortElem, _longMa, _longElem, series) { Volume = 1, Portfolio = portfolio, Security = security, Connector = connector, LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info, // по-умолчанию интервал равен 1 минут, // что для истории в диапазон от нескольких месяцев излишне UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>() }; // комиссия в 1 копейку за сделку connector.MarketEmulator.SendInMessage(new CommissionRuleMessage { Rule = new CommissionPerTradeRule { Value = 0.01m } }); logManager.Sources.Add(strategy); // копируем параметры на визуальную панель statistic.Parameters.Clear(); statistic.Parameters.AddRange(strategy.StatisticManager.Parameters); var pnlCurve = Curve.CreateCurve("P&L " + emulationInfo.StrategyName, emulationInfo.CurveColor, EquityCurveChartStyles.Area); var unrealizedPnLCurve = Curve.CreateCurve(LocalizedStrings.PnLUnreal + emulationInfo.StrategyName, Colors.Black); var commissionCurve = Curve.CreateCurve(LocalizedStrings.Str159 + " " + emulationInfo.StrategyName, Colors.Red, EquityCurveChartStyles.DashedLine); var posItems = PositionCurve.CreateCurve(emulationInfo.StrategyName, emulationInfo.CurveColor); strategy.PnLChanged += () => { var pnl = new EquityData { Time = strategy.CurrentTime, Value = strategy.PnL - strategy.Commission ?? 0 }; var unrealizedPnL = new EquityData { Time = strategy.CurrentTime, Value = strategy.PnLManager.UnrealizedPnL }; var commission = new EquityData { Time = strategy.CurrentTime, Value = strategy.Commission ?? 0 }; pnlCurve.Add(pnl); unrealizedPnLCurve.Add(unrealizedPnL); commissionCurve.Add(commission); }; strategy.PositionChanged += () => posItems.Add(new EquityData { Time = strategy.CurrentTime, Value = strategy.Position }); var nextTime = startTime + progressStep; // и подписываемся на событие изменения времени, чтобы обновить ProgressBar connector.MarketTimeChanged += d => { if (connector.CurrentTime < nextTime && connector.CurrentTime < stopTime) return; var steps = (connector.CurrentTime - startTime).Ticks / progressStep.Ticks + 1; nextTime = startTime + (steps * progressStep.Ticks).To<TimeSpan>(); this.GuiAsync(() => progressBar.Value = steps); }; connector.StateChanged += () => { if (connector.State == EmulationStates.Stopped) { candleManager.Stop(series); strategy.Stop(); logManager.Dispose(); _connectors.Clear(); SetIsEnabled(false); this.GuiAsync(() => { if (connector.IsFinished) { progressBar.Value = progressBar.Maximum; MessageBox.Show(LocalizedStrings.Str3024 + (DateTime.Now - _startEmulationTime)); } else MessageBox.Show(LocalizedStrings.cancelled); }); } else if (connector.State == EmulationStates.Started) { SetIsEnabled(true); // запускаем стратегию когда эмулятор запустился strategy.Start(); candleManager.Start(series); } }; if (ShowDepth.IsChecked == true) { MarketDepth.UpdateFormat(security); connector.NewMessage += (message, dir) => { var quoteMsg = message as QuoteChangeMessage; if (quoteMsg != null) MarketDepth.UpdateDepth(quoteMsg); }; } _connectors.Add(connector); } _startEmulationTime = DateTime.Now; // запускаем эмуляцию foreach (var connector in _connectors) { // указываем даты начала и конца тестирования connector.Start(startTime, stopTime); } TabControl.Items.Cast<TabItem>().First(i => i.Visibility == Visibility.Visible).IsSelected = true; } private void CheckBoxClick(object sender, RoutedEventArgs e) { var isEnabled = TicksCheckBox.IsChecked == true || TicksAndDepthsCheckBox.IsChecked == true || CandlesCheckBox.IsChecked == true || CandlesAndDepthsCheckBox.IsChecked == true || OrderLogCheckBox.IsChecked == true; StartBtn.IsEnabled = isEnabled; TabControl.Visibility = isEnabled ? Visibility.Visible : Visibility.Collapsed; } private void StopBtnClick(object sender, RoutedEventArgs e) { foreach (var connector in _connectors) { connector.Stop(); } } private void InitChart() { _bufferedChart.ClearAreas(); Curve.Clear(); PositionCurve.Clear(); _area = new ChartArea(); _bufferedChart.AddArea(_area); _candlesElem = new ChartCandleElement { ShowAxisMarker = false }; _bufferedChart.AddElement(_area, _candlesElem); _tradesElem = new ChartTradeElement { FullTitle = "Сделки" }; _bufferedChart.AddElement(_area, _tradesElem); } private void SetIsEnabled(bool started) { this.GuiAsync(() => { StopBtn.IsEnabled = started; StartBtn.IsEnabled = !started; TicksCheckBox.IsEnabled = TicksAndDepthsCheckBox.IsEnabled = CandlesCheckBox.IsEnabled = CandlesAndDepthsCheckBox.IsEnabled = OrderLogCheckBox.IsEnabled = !started; _bufferedChart.IsAutoRange = started; }); } } }
Enterprize-1701/robot
Samples/Testing/SampleHistoryTesting/MainWindow.xaml.cs
C#
lgpl-3.0
17,350
#ifndef UITEXTCURSOR_H #define UITEXTCURSOR_H #include "Bang/BangDefines.h" #include "Bang/ComponentMacros.h" #include "Bang/LineRenderer.h" #include "Bang/String.h" #include "Bang/Time.h" namespace Bang { class UITextCursor : public LineRenderer { COMPONENT(UITextCursor) public: UITextCursor(); virtual ~UITextCursor() override; virtual void OnUpdate() override; void ResetTickTime(); void SetStroke(float cursorWidth); void SetTickTime(Time cursorTickTime); float GetStroke() const; Time GetTickTime() const; private: Time m_cursorTime; Time m_cursorTickTime; }; } #endif // UITEXTCURSOR_H
Bang3DEngine/Bang
include/Bang/UITextCursor.h
C
lgpl-3.0
647
/* * File: DistanceToBall2.h * Author: chung * * Created on January 14, 2016, 2:02 AM */ #ifndef DISTANCETOBALL2_H #define DISTANCETOBALL2_H #include "Function.h" #include <cmath> /** * \class DistanceToBall2 * \brief Distance from the unit ball of R^n * \version version 0.1 * \ingroup Functions * \date Created on January 14, 2016, 2:02 AM * \author Pantelis Sopasakis * * This class extends Function and implements the squared distance to the closed ball * of norm-2 in \f$\mathbb{R}^n\f$ of radius \f$\rho\f$, centered at \f$c\in\mathbb{R}^n\f$ * which is defined by * * \f[ * B_2(\rho, c) = \{x\in\mathbb{R}^n: \|x-c\|_2 \leq \rho\}, * \f] * * that is, this is the function * * \f[ * f(x) = \frac{w}{2}d(x, B_2(\rho, c))^2 = \frac{w}{2}\|x-\mathrm{proj}(x, B_2(\rho, c))\|^2, * \f] * * where \f$w>0\f$ is a positive scalar and * \f[ * \mathrm{proj}(x, B_2) = \mathrm{argmin}\limits_{\|y-c\|\leq \rho}\|y-x\| * \f] * is the projection of \f$x\f$ on \f$B_2(\rho, c)\f$. This is computed as * * \f[ * \mathrm{proj}(x, B_2) = \begin{cases} * x, &\text{ if } \|x-c\|\leq \rho\\ * c+\frac{\rho}{\|x-c\|}(x-c), &\text{ otherwise} * \end{cases} * \f] * * Essentially, the squared distance to ball-2 is given by * * \f[ * f(x) = \begin{cases} * 0, &\text{ if } \|x-c\|\leq \rho,\\ * \frac{w}{2}(\|x-c\|-\rho)^2,&\text{ otherwise} * \end{cases} * \f] * * * The gradient of \f$f\f$ is given by * * \f[ * \begin{align} * \nabla f (x) &= \frac{w}{2}(x-\mathrm{proj}(x, B_2(\rho, c)))\\ * &= \begin{cases} * 0, & \text{if } \|x-c\|\leq \rho,\\ * \left(1-\frac{\rho}{\|x-c\|}\right)(x-c), &\text{otherwise} * \end{cases} * \end{align} * \f] * */ class DistanceToBall2 : public Function { public: using Function::call; /** * Constructs the indicator of the closed norm-2 unit ball centered at the * origin, i.e., the function * * \f[ * f(x) = \frac{1}{2}d(x, B_2), * \f] * * where * * \f[ * B_2 = \{x\in\mathbb{R}^n: \|x\|_2\leq 1\}. * \f] */ DistanceToBall2(); /** * Constructs the indicator of the closed norm-2 unit ball centered at the * origin scaled by a given scalar. The function has the form * * \f[ * f(x) = \frac{w}{2}d(x, B_2), * \f] * * where * * \f[ * B_2 = \{x\in\mathbb{R}^n: \|x\|_2\leq 1\}. * \f] * * @param w scaling parameter */ explicit DistanceToBall2(double w); /** * Constructs the indicator of the closed norm-2 ball centered at the * origin with radius \f$\rho\f$ scaled by a given scalar. The function has the form * * \f[ * f(x) = \frac{w}{2}d(x, B_2(\rho)), * \f] * * where * * \f[ * B_2(\rho) = \{x\in\mathbb{R}^n: \|x\|_2\leq \rho\}. * \f] * * @param w scaling factor * @param rho radius of the ball */ DistanceToBall2(double w, double rho); /** * Constructs the indicator of the closed norm-2 ball centered at the * a point \f$c\in\mathbb{R}^n\f$ with radius \f$\rho\f$ scaled by a * given scalar. The function has the form * * \f[ * f(x) = \frac{w}{2}d(x, B_2(\rho, c)), * \f] * * where * * \f[ * B_2(\rho,c) = \{x\in\mathbb{R}^n: \|x-c\|_2\leq \rho\}. * \f] * * * @param w scaling factor * @param rho radius of the ball * @param center center of the ball */ DistanceToBall2(double w, double rho, Matrix &center); /** * Default destructor. */ virtual ~DistanceToBall2(); virtual int call(Matrix& x, double& f, Matrix& grad); virtual int call(Matrix& x, double& f); virtual FunctionOntologicalClass category(); private: /** * ball radius */ double m_rho; /** * scaling factor (the function is scaled by w/2) */ double m_w; /** * center of the ball (vector). * Default is the origin (in which case this pointer is \c NULL). */ Matrix * m_center; }; #endif /* DISTANCETOBALL2_H */
lostella/libForBES
source/DistanceToBall2.h
C
lgpl-3.0
4,280
#include <esdm-internal.h> #include "dummy/dummy.h" #ifdef ESDM_HAS_S3 # include "s3/s3.h" # pragma message("Building ESDM with support for S3 backend.") #endif #ifdef ESDM_HAS_POSIX # include "posix/posix.h" # pragma message("Building ESDM with support for generic POSIX backend.") #endif #ifdef ESDM_HAS_IME # include "ime/ime.h" # pragma message("Building ESDM with IME support.") #endif #ifdef ESDM_HAS_KDSA # include "kdsa/esdm-kdsa.h" # pragma message("Building ESDM with Kove XPD KDSA support.") #endif #ifdef ESDM_HAS_MOTR # include "Motr/client.h" # pragma message("Building ESDM with Motr support.") #endif #ifdef ESDM_HAS_WOS # include "WOS/wos.h" # pragma message("Building ESDM with WOS support.") #endif #ifdef ESDM_HAS_PMEM # include "pmem/esdm-pmem.h" # pragma message("Building ESDM with PMEM support.") #endif esdm_backend_t * esdmI_init_backend(char const * name, esdm_config_backend_t * b){ if (strncmp(b->type, "DUMMY", 5) == 0) { return dummy_backend_init(b); } #ifdef ESDM_HAS_POSIX else if (strncmp(b->type, "POSIX", 5) == 0) { return posix_backend_init(b); } #endif #ifdef ESDM_HAS_IME else if (strncasecmp(b->type, "IME", 3) == 0) { return ime_backend_init(b); } #endif #ifdef ESDM_HAS_KDSA else if (strncasecmp(b->type, "KDSA", 4) == 0) { return kdsa_backend_init(b); } #endif #ifdef ESDM_HAS_MOTR else if (strncasecmp(b->type, "MOTR", 6) == 0) { return motr_backend_init(b); } #endif #ifdef ESDM_HAS_WOS else if (strncmp(b->type, "WOS", 3) == 0) { return wos_backend_init(b); } #endif #ifdef ESDM_HAS_PMEM else if (strncmp(b->type, "PMEM", 4) == 0) { return pmem_backend_init(b); } #endif #ifdef ESDM_HAS_S3 else if (strncmp(b->type, "S3", 2) == 0){ return s3_backend_init(b); } #endif return NULL; }
ESiWACE/esdm
src/backends-data/init.c
C
lgpl-3.0
1,819
package schemacrawler.tools.executable; import schemacrawler.schemacrawler.SchemaCrawlerException; import schemacrawler.schemacrawler.SchemaCrawlerOptions; import schemacrawler.tools.options.OutputOptions; public interface CommandProvider { Executable configureNewExecutable(SchemaCrawlerOptions schemaCrawlerOptions, OutputOptions outputOptions) throws SchemaCrawlerException; String getCommand(); String getHelpResource(); }
ceharris/SchemaCrawler
schemacrawler-tools/src/main/java/schemacrawler/tools/executable/CommandProvider.java
Java
lgpl-3.0
480
import pytest import importlib from mpi4py import MPI from spectralDNS import config, get_solver, solve from TGMHD import initialize, regression_test, pi comm = MPI.COMM_WORLD if comm.Get_size() >= 4: params = ('uniform_slab', 'nonuniform_slab', 'uniform_pencil', 'nonuniform_pencil') else: params = ('uniform', 'nonuniform') @pytest.fixture(params=params) def sol(request): """Check for uniform and non-uniform cube""" pars = request.param.split('_') mesh = pars[0] mpi = 'slab' if len(pars) == 2: mpi = pars[1] _args = ['--decomposition', mpi] if mesh == 'uniform': _args += ['--M', '4', '4', '4', '--L', '2*pi', '2*pi', '2*pi'] else: _args += ['--M', '6', '5', '4', '--L', '6*pi', '4*pi', '2*pi'] _args += ['MHD'] return _args def test_MHD(sol): config.update( { 'nu': 0.000625, # Viscosity 'dt': 0.01, # Time step 'T': 0.1, # End time 'eta': 0.01, 'L': [2*pi, 4*pi, 6*pi], 'M': [4, 5, 6], 'convection': 'Divergence' } ) solver = get_solver(regression_test=regression_test, parse_args=sol) context = solver.get_context() initialize(**context) solve(solver, context) config.params.dealias = '3/2-rule' initialize(**context) solve(solver, context) config.params.dealias = '2/3-rule' config.params.optimization = 'cython' importlib.reload(solver) initialize(**context) solve(solver, context) config.params.write_result = 1 config.params.checkpoint = 1 config.dt = 0.01 config.params.t = 0.0 config.params.tstep = 0 config.T = 0.04 solver.regression_test = lambda c: None solve(solver, context)
spectralDNS/spectralDNS
tests/test_MHD.py
Python
lgpl-3.0
1,847
// Copyright © 2011 - Present RealDimensions Software, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace chocolatey.infrastructure.app.domain { using System; using System.Xml.Serialization; using Microsoft.Win32; [Serializable] [XmlType("key")] public class RegistryApplicationKey : IEquatable<RegistryApplicationKey> { public RegistryView RegistryView { get; set; } public string KeyPath { get; set; } [XmlAttribute(AttributeName = "installerType")] public InstallerType InstallerType { get; set; } public string DefaultValue { get; set; } [XmlAttribute(AttributeName = "displayName")] public string DisplayName { get; set; } public string InstallLocation { get; set; } public string UninstallString { get; set; } public bool HasQuietUninstall { get; set; } // informational public string Publisher { get; set; } public string InstallDate { get; set; } public string InstallSource { get; set; } public string Language { get; set; } //uint // version stuff [XmlAttribute(AttributeName = "displayVersion")] public string DisplayVersion { get; set; } public string Version { get; set; } //uint public string VersionMajor { get; set; } //uint public string VersionMinor { get; set; } //uint public string VersionRevision { get; set; } //uint public string VersionBuild { get; set; } //uint // install information public bool SystemComponent { get; set; } public bool WindowsInstaller { get; set; } public bool NoRemove { get; set; } public bool NoModify { get; set; } public bool NoRepair { get; set; } public string ReleaseType { get; set; } //hotfix, securityupdate, update rollup, servicepack public string ParentKeyName { get; set; } /// <summary> /// Is an application listed in ARP (Programs and Features)? /// </summary> /// <returns>true if the key should be listed as a program</returns> /// <remarks> /// http://community.spiceworks.com/how_to/show/2238-how-add-remove-programs-works /// </remarks> public bool is_in_programs_and_features() { return !string.IsNullOrWhiteSpace(DisplayName) && !string.IsNullOrWhiteSpace(UninstallString) && InstallerType != InstallerType.HotfixOrSecurityUpdate && InstallerType != InstallerType.ServicePack && string.IsNullOrWhiteSpace(ParentKeyName) && !NoRemove && !SystemComponent ; } public override string ToString() { return "{0}|{1}|{2}|{3}|{4}".format_with( DisplayName, DisplayVersion, InstallerType, UninstallString, KeyPath ); } public override int GetHashCode() { return DisplayName.GetHashCode() & DisplayVersion.GetHashCode() & UninstallString.GetHashCode() & KeyPath.GetHashCode(); } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; return Equals(obj as RegistryApplicationKey); } bool IEquatable<RegistryApplicationKey>.Equals(RegistryApplicationKey other) { if (ReferenceEquals(other, null)) return false; return DisplayName.is_equal_to(other.DisplayName) && DisplayVersion.is_equal_to(other.DisplayVersion) && UninstallString.is_equal_to(other.UninstallString) && KeyPath.is_equal_to(other.KeyPath) ; } } }
peterstevens130561/sonarlint-vs
its/choco-master_3a5f2b6843/src/chocolatey/infrastructure.app/domain/RegistryApplicationKey.cs
C#
lgpl-3.0
4,450
/* Copyright radare2 2014-2020 - Author: pancake, vane11ope */ #include <r_core.h> /* few remaining static functions */ static bool __init_panels_menu(RCore *core); static bool __init_panels(RCore *core, RPanels *panels); static void __init_menu_screen_settings_layout(void *_core, const char *parent); static void __init_new_panels_root(RCore *core); static void __init_menu_color_settings_layout(void *core, const char *parent); static void __init_menu_disasm_asm_settings_layout(void *_core, const char *parent); static void __set_dcb(RCore *core, RPanel *p); static void __set_pcb(RPanel *p); static void __panels_refresh(RCore *core); #define MENU_Y 1 #define PANEL_NUM_LIMIT 9 #define PANEL_TITLE_SYMBOLS "Symbols" #define PANEL_TITLE_STACK "Stack" #define PANEL_TITLE_XREFS_HERE "Xrefs Here" #define PANEL_TITLE_XREFS "Xrefs" #define PANEL_TITLE_REGISTERS "Registers" #define PANEL_TITLE_DISASSEMBLY "Disassembly" #define PANEL_TITLE_DISASMSUMMARY "Disassemble Summary" #define PANEL_TITLE_ALL_DECOMPILER "Show All Decompiler Output" #define PANEL_TITLE_DECOMPILER "Decompiler" #define PANEL_TITLE_DECOMPILER_O "Decompiler With Offsets" #define PANEL_TITLE_GRAPH "Graph" #define PANEL_TITLE_TINY_GRAPH "Tiny Graph" #define PANEL_TITLE_FUNCTIONS "Functions" #define PANEL_TITLE_FUNCTIONCALLS "Function Calls" #define PANEL_TITLE_BREAKPOINTS "Breakpoints" #define PANEL_TITLE_STRINGS_DATA "Strings in data sections" #define PANEL_TITLE_STRINGS_BIN "Strings in the whole bin" #define PANEL_TITLE_SECTIONS "Sections" #define PANEL_TITLE_SEGMENTS "Segments" #define PANEL_TITLE_COMMENTS "Comments" #define PANEL_CMD_SYMBOLS "isq" #define PANEL_CMD_XREFS_HERE "ax." #define PANEL_CMD_XREFS "ax" #define PANEL_CMD_STACK "px" #define PANEL_CMD_REGISTERS "dr" #define PANEL_CMD_DISASSEMBLY "pd" #define PANEL_CMD_DISASMSUMMARY "pdsf" #define PANEL_CMD_DECOMPILER "pdc" #define PANEL_CMD_DECOMPILER_O "pddo" #define PANEL_CMD_FUNCTION "afl" #define PANEL_CMD_GRAPH "agf" #define PANEL_CMD_TINYGRAPH "agft" #define PANEL_CMD_HEXDUMP "xc" #define PANEL_CMD_CONSOLE "$console" #define PANEL_CONFIG_MENU_MAX 64 #define PANEL_CONFIG_PAGE 10 #define PANEL_CONFIG_SIDEPANEL_W 60 #define PANEL_CONFIG_RESIZE_W 4 #define PANEL_CONFIG_RESIZE_H 4 #define COUNT(x) (sizeof((x)) / sizeof((*x)) - 1) // TODO: kill mutable globals static bool firstRun = true; static bool fromVisual = false; static char *menus_Colors[128]; typedef enum { LEFT, RIGHT, UP, DOWN } Direction; static const char *panels_dynamic [] = { "Disassembly", "Stack", "Registers", NULL }; static const char *panels_static [] = { "Disassembly", "Functions", "Symbols", NULL }; static const char *menus[] = { "File", "Settings", "Edit", "View", "Tools", "Search", "Emulate", "Debug", "Analyze", "Help", NULL }; static const char *menus_File[] = { "New", "Open", "ReOpen", "Close", "Save Layout", "Load Layout", "Clear Saved Layouts", "Quit", NULL }; static const char *menus_Settings[] = { "Colors", "Decompiler", "Disassembly", "Screen", NULL }; static const char *menus_ReOpen[] = { "In RW", "In Debugger", NULL }; static const char *menus_loadLayout[] = { "Saved", "Default", NULL }; static const char *menus_Edit[] = { "Copy", "Paste", "Clipboard", "Write String", "Write Hex", "Write Value", "Assemble", "Fill", "io.cache", NULL }; static const char *menus_iocache[] = { "On", "Off", NULL }; static const char *menus_View[] = { "Console", "Hexdump", "Disassembly", "Disassemble Summary", "Decompiler", "Decompiler With Offsets", "Graph", "Tiny Graph", "Functions", "Function Calls", "Sections", "Segments", PANEL_TITLE_STRINGS_DATA, PANEL_TITLE_STRINGS_BIN, "Symbols", "Imports", "Info", "Database", "Breakpoints", "Comments", "Classes", "Entropy", "Entropy Fire", "Stack", "Xrefs Here", "Methods", "Var READ address", "Var WRITE address", "Summary", "Relocs", "Headers", "File Hashes", PANEL_TITLE_ALL_DECOMPILER, NULL }; static const char *menus_Tools[] = { "Calculator", "R2 Shell", "System Shell", NULL }; static const char *menus_Search[] = { "String (Whole Bin)", "String (Data Sections)", "ROP", "Code", "Hexpairs", NULL }; static const char *menus_Emulate[] = { "Step From", "Step To", "Step Range", NULL }; static const char *menus_Debug[] = { "Registers", "RegisterRefs", "DRX", "Breakpoints", "Watchpoints", "Maps", "Modules", "Backtrace", "Locals", "Continue", "Step", "Step Over", "Reload", NULL }; static const char *menus_Analyze[] = { "Function", "Symbols", "Program", "BasicBlocks", "Calls", "References", NULL }; static const char *menus_settings_disassembly[] = { "asm", "hex.section", "io.cache", "hex.pairs", "emu.str", NULL }; static const char *menus_settings_disassembly_asm[] = { "asm.bytes", "asm.section", "asm.cmt.right", "asm.emu", "asm.var.summary", "asm.pseudo", "asm.flags.inbytes", "asm.arch", "asm.bits", "asm.cpu", NULL }; static const char *menus_settings_screen[] = { "scr.bgfill", "scr.color", "scr.utf8", "scr.utf8.curvy", "scr.wheel", NULL }; static const char *menus_Help[] = { "Toggle Help", "License", "Version", "Fortune", "2048", NULL }; static const char *entropy_rotate[] = { "", "2", "b", "c", "d", "e", "F", "i", "j", "m", "p", "s", "z", "0", NULL }; static char *hexdump_rotate[] = { "xc", "pxa", "pxr", "prx", "pxb", "pxh", "pxw", "pxq", "pxd", "pxr", NULL }; static const char *register_rotate[] = { "", "=", "r", "??", "C", "i", "o", NULL }; static const char *function_rotate[] = { "l", "i", "x", NULL }; static const char *cache_white_list_cmds[] = { "pdc", "pddo", "agf", "Help", NULL }; static const char *help_msg_panels[] = { "|", "split current panel vertically", "-", "split current panel horizontally", ":", "run r2 command in prompt", ";", "add/remove comment", "_", "show hud", "\\", "show user-friendly hud", "?", "show this help", "!", "swap into visual mode", ".", "seek to PC or entrypoint", "*", "show decompiler in the current panel", "\"", "create a panel from the list and replace the current one", "/", "highlight the keyword", "(", "toggle snow", "&", "toggle cache", "[1-9]", "follow jmp/call identified by shortcut (like ;[1])", "' '", "(space) toggle graph / panels", "tab", "go to the next panel", "Enter", "maximize current panel in zoom mode", "a", "toggle auto update for decompiler", "b", "browse symbols, flags, configurations, classes, ...", "c", "toggle cursor", "C", "toggle color", "d", "define in the current address. Same as Vd", "D", "show disassembly in the current panel", "e", "change title and command of current panel", "f", "set/add filter keywords", "F", "remove all the filters", "g", "go/seek to given offset", "G", "go/seek to highlight", "i", "insert hex", "hjkl", "move around (left-down-up-right)", "HJKL", "move around (left-down-up-right) by page", "m", "select the menu panel", "M", "open new custom frame", "n/N", "seek next/prev function/flag/hit (scr.nkey)", "p/P", "rotate panel layout", "q", "quit, or close a tab", "Q", "close all the tabs and quit", "r", "toggle callhints/jmphints/leahints", "R", "randomize color palette (ecr)", "s/S", "step in / step over", "t/T", "tab prompt / close a tab", "u/U", "undo / redo seek", "w", "shuffle panels around in window mode", "V", "go to the graph mode", "xX", "show xrefs/refs of current function from/to data/code", "z", "swap current panel with the first one", NULL }; static const char *help_msg_panels_window[] = { ":", "run r2 command in prompt", ";", "add/remove comment", "\"", "create a panel from the list and replace the current one", "?", "show this help", "|", "split the current panel vertically", "-", "split the current panel horizontally", "tab", "go to the next panel", "Enter", "maximize current panel in zoom mode", "d", "define in the current address. Same as Vd", "b", "browse symbols, flags, configurations, classes, ...", "hjkl", "move around (left-down-up-right)", "HJKL", "resize panels vertically/horizontally", "Q/q/w", "quit window mode", "p/P", "rotate panel layout", "t/T", "rotate related commands in a panel", "X", "close current panel", NULL }; static const char *help_msg_panels_zoom[] = { "?", "show this help", ":", "run r2 command in prompt", ";", "add/remove comment", "\"", "create a panel from the list and replace the current one", "' '", "(space) toggle graph / panels", "tab", "go to the next panel", "b", "browse symbols, flags, configurations, classes, ...", "d", "define in the current address. Same as Vd", "c", "toggle cursor", "C", "toggle color", "hjkl", "move around (left-down-up-right)", "p/P", "seek to next or previous scr.nkey", "s/S", "step in / step over", "t/T", "rotate related commands in a panel", "xX", "show xrefs/refs of current function from/to data/code", "q/Q/Enter","quit zoom mode", NULL }; static RPanel *__get_panel(RPanels *panels, int i) { return (panels && i < PANEL_NUM_LIMIT)? panels->panel[i]: NULL; } static void __update_edge_x(RCore *core, int x) { RPanels *panels = core->panels; int i, j; int tmp_x = 0; for (i = 0; i < panels->n_panels; i++) { RPanel *p0 = __get_panel (panels, i); if (p0->view->pos.x - 2 <= panels->mouse_orig_x && panels->mouse_orig_x <= p0->view->pos.x + 2) { tmp_x = p0->view->pos.x; p0->view->pos.x += x; p0->view->pos.w -= x; for (j = 0; j < panels->n_panels; j++) { RPanel *p1 = __get_panel (panels, j); if (p1->view->pos.x + p1->view->pos.w - 1 == tmp_x) { p1->view->pos.w += x; } } } } } static void __update_edge_y(RCore *core, int y) { RPanels *panels = core->panels; size_t i, j; int tmp_y = 0; for (i = 0; i < panels->n_panels; i++) { RPanel *p0 = __get_panel (panels, i); if (p0->view->pos.y - 2 <= panels->mouse_orig_y && panels->mouse_orig_y <= p0->view->pos.y + 2) { tmp_y = p0->view->pos.y; p0->view->pos.y += y; p0->view->pos.h -= y; for (j = 0; j < panels->n_panels; j++) { RPanel *p1 = __get_panel (panels, j); if (p1->view->pos.y + p1->view->pos.h - 1 == tmp_y) { p1->view->pos.h += y; } } } } } static bool __check_if_mouse_x_illegal(RCore *core, int x) { RPanels *panels = core->panels; RConsCanvas *can = panels->can; const int edge_x = 1; if (x <= edge_x || can->w - edge_x <= x) { return true; } return false; } static bool __check_if_mouse_y_illegal(RCore *core, int y) { RPanels *panels = core->panels; RConsCanvas *can = panels->can; const int edge_y = 0; if (y <= edge_y || can->h - edge_y <= y) { return true; } return false; } static bool __check_if_mouse_x_on_edge(RCore *core, int x, int y) { RPanels *panels = core->panels; const int edge_x = r_config_get_i (core->config, "scr.panelborder")? 3: 1; int i = 0; for (; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); if (x > panel->view->pos.x - (edge_x - 1) && x <= panel->view->pos.x + edge_x) { panels->mouse_on_edge_x = true; panels->mouse_orig_x = x; return true; } } return false; } static bool __check_if_mouse_y_on_edge(RCore *core, int x, int y) { RPanels *panels = core->panels; const int edge_y = r_config_get_i (core->config, "scr.panelborder")? 3: 1; int i = 0; for (; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); if (x > panel->view->pos.x && x <= panel->view->pos.x + panel->view->pos.w + edge_y) { if (y > 2 && y >= panel->view->pos.y && y <= panel->view->pos.y + edge_y) { panels->mouse_on_edge_y = true; panels->mouse_orig_y = y; return true; } } } return false; } static RPanel *__get_cur_panel(RPanels *panels) { return __get_panel (panels, panels->curnode); } static bool __check_if_cur_panel(RCore *core, RPanel *panel) { return __get_cur_panel (core->panels) == panel; } static bool __check_if_addr(const char *c, int len) { if (len < 2) { return false; } int i = 0; for (; i < len; i++) { if (R_STR_ISNOTEMPTY (c + i) && R_STR_ISNOTEMPTY (c+ i + 1) && c[i] == '0' && c[i + 1] == 'x') { return true; } } return false; } static void __check_edge(RCore *core) { RPanels *panels = core->panels; int i; for (i = 0; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); if (panel->view->pos.x + panel->view->pos.w == core->panels->can->w) { panel->view->edge |= (1 << PANEL_EDGE_RIGHT); } else { panel->view->edge &= (1 << PANEL_EDGE_BOTTOM); } if (panel->view->pos.y + panel->view->pos.h == core->panels->can->h) { panel->view->edge |= (1 << PANEL_EDGE_BOTTOM); } else { panel->view->edge &= (1 << PANEL_EDGE_RIGHT); } } } static void __shrink_panels_forward(RCore *core, int target) { RPanels *panels = core->panels; int i = target; for (; i < panels->n_panels - 1; i++) { panels->panel[i] = panels->panel[i + 1]; } } static void __shrink_panels_backward(RCore *core, int target) { RPanels *panels = core->panels; int i = target; for (; i > 0; i--) { panels->panel[i] = panels->panel[i - 1]; } } static void __cache_white_list(RCore *core, RPanel *panel) { int i = 0; for (; i < COUNT (cache_white_list_cmds); i++) { if (!strcmp (panel->model->cmd, cache_white_list_cmds[i])) { panel->model->cache = true; return; } } panel->model->cache = false; } static char *__search_db(RCore *core, const char *title) { RPanels *panels = core->panels; if (!panels->db) { return NULL; } char *out = sdb_get (panels->db, title, 0); if (out) { return out; } return NULL; } static int __show_status(RCore *core, const char *msg) { r_cons_gotoxy (0, 0); r_cons_printf (R_CONS_CLEAR_LINE"%s[Status] %s"Color_RESET, core->cons->context->pal.graph_box2, msg); r_cons_flush (); return r_cons_readchar (); } static bool __show_status_yesno(RCore *core, int def, const char *msg) { r_cons_gotoxy (0, 0); r_cons_flush (); return r_cons_yesno (def, R_CONS_CLEAR_LINE"%s[Status] %s"Color_RESET, core->cons->context->pal.graph_box2, msg); } static char *__show_status_input(RCore *core, const char *msg) { char *n_msg = r_str_newf (R_CONS_CLEAR_LINE"%s[Status] %s"Color_RESET, core->cons->context->pal.graph_box2, msg); r_cons_gotoxy (0, 0); r_cons_flush (); char *out = r_cons_input (n_msg); free (n_msg); return out; } static bool __check_panel_type(RPanel *panel, const char *type) { if (!panel->model->cmd || !type) { return false; } char *tmp = r_str_new (panel->model->cmd); int n = r_str_split (tmp, ' '); if (!n) { free (tmp); return false; } const char *base = r_str_word_get0 (tmp, 0); if (R_STR_ISEMPTY (base)) { free (tmp); return false; } int len = strlen (type); if (!strcmp (type, PANEL_CMD_DISASSEMBLY)) { if (!strncmp (tmp, type, len) && strcmp (panel->model->cmd, PANEL_CMD_DECOMPILER) && strcmp (panel->model->cmd, PANEL_CMD_DECOMPILER_O) && strcmp (panel->model->cmd, PANEL_CMD_DISASMSUMMARY)) { free (tmp); return true; } free (tmp); return false; } if (!strcmp (type, PANEL_CMD_STACK)) { if (!strcmp (tmp, PANEL_CMD_STACK)) { free (tmp); return true; } free (tmp); return false; } if (!strcmp (type, PANEL_CMD_HEXDUMP)) { int i = 0; for (; i < COUNT (hexdump_rotate); i++) { if (!strcmp (tmp, hexdump_rotate[i])) { free (tmp); return true; } } free (tmp); return false; } free (tmp); return !strncmp (panel->model->cmd, type, len); } static bool __check_root_state(RCore *core, RPanelsRootState state) { return core->panels_root->root_state == state; } static bool search_db_check_panel_type (RCore *core, RPanel *panel, const char *ch) { char *str = __search_db (core, ch); bool ret = str && __check_panel_type (panel, str); free (str); return ret; } //TODO: Refactroing static bool __is_abnormal_cursor_type(RCore *core, RPanel *panel) { if (__check_panel_type (panel, PANEL_CMD_SYMBOLS) || __check_panel_type (panel, PANEL_CMD_FUNCTION)) { return true; } if (search_db_check_panel_type (core, panel, PANEL_TITLE_DISASMSUMMARY)) { return true; } if (search_db_check_panel_type (core, panel, PANEL_TITLE_STRINGS_DATA)) { return true; } if (search_db_check_panel_type (core, panel, PANEL_TITLE_STRINGS_BIN)) { return true; } if (search_db_check_panel_type (core, panel, PANEL_TITLE_BREAKPOINTS)) { return true; } if (search_db_check_panel_type (core, panel, PANEL_TITLE_SECTIONS)) { return true; } if (search_db_check_panel_type (core, panel, PANEL_TITLE_SEGMENTS)) { return true; } if (search_db_check_panel_type (core, panel, PANEL_TITLE_COMMENTS)) { return true; } return false; } static bool __is_normal_cursor_type(RPanel *panel) { return (__check_panel_type (panel, PANEL_CMD_STACK) || __check_panel_type (panel, PANEL_CMD_REGISTERS) || __check_panel_type (panel, PANEL_CMD_DISASSEMBLY) || __check_panel_type (panel, PANEL_CMD_HEXDUMP)); } static void __set_cmd_str_cache(RCore *core, RPanel *p, char *s) { free (p->model->cmdStrCache); p->model->cmdStrCache = s; __set_dcb (core, p); __set_pcb (p); } static void __set_decompiler_cache(RCore *core, char *s) { RAnalFunction *func = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL); if (func) { if (core->panels_root->cur_pdc_cache) { sdb_ptr_set (core->panels_root->cur_pdc_cache, r_num_as_string (NULL, func->addr, false), r_str_new (s), 0); } else { Sdb *sdb = sdb_new0 (); const char *pdc_now = r_config_get (core->config, "cmd.pdc"); sdb_ptr_set (sdb, r_num_as_string (NULL, func->addr, false), r_str_new (s), 0); core->panels_root->cur_pdc_cache = sdb; if (!sdb_exists (core->panels_root->pdc_caches, pdc_now)) { sdb_ptr_set (core->panels_root->pdc_caches, r_str_new (pdc_now), sdb, 0); } } } } static void __set_read_only(RCore *core, RPanel *p, char *s) { free (p->model->readOnly); p->model->readOnly = r_str_new (s); __set_dcb (core, p); __set_pcb (p); } static void __set_pos(RPanelPos *pos, int x, int y) { pos->x = x; pos->y = y; } static void __set_size(RPanelPos *pos, int w, int h) { pos->w = w; pos->h = h; } static void __set_geometry(RPanelPos *pos, int x, int y, int w, int h) { __set_pos (pos, x, y); __set_size (pos, w, h); } static void __set_panel_addr(RCore *core, RPanel *panel, ut64 addr) { panel->model->addr = addr; } static int __get_panel_idx_in_pos(RCore *core, int x, int y) { RPanels *panels = core->panels; int i = -1; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); if (x >= p->view->pos.x && x < p->view->pos.x + p->view->pos.w) { if (y >= p->view->pos.y && y < p->view->pos.y + p->view->pos.h) { break; } } } return i; } static void __handlePrompt(RCore *core, RPanels *panels) { r_core_visual_prompt_input (core); int i; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); if (__check_panel_type (p, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, p, core->offset); break; } } } static void __menu_panel_print(RConsCanvas *can, RPanel *panel, int x, int y, int w, int h) { (void) r_cons_canvas_gotoxy (can, panel->view->pos.x + 2, panel->view->pos.y + 2); char *text = r_str_ansi_crop (panel->model->title, x, y, w, h); if (text) { r_cons_canvas_write (can, text); free (text); } else { r_cons_canvas_write (can, panel->model->title); } } static void __update_help_contents(RCore *core, RPanel *panel) { char *read_only = panel->model->readOnly; char *text = NULL; int sx = panel->view->sx; int sy = R_MAX (panel->view->sy, 0); int x = panel->view->pos.x; int y = panel->view->pos.y; int w = panel->view->pos.w; int h = panel->view->pos.h; RPanels *panels = core->panels; RConsCanvas *can = panels->can; (void) r_cons_canvas_gotoxy (can, x + 2, y + 2); if (sx < 0) { char *white = (char*)r_str_pad (' ', 128); int idx = R_MIN (-sx, strlen (white) - 1); white[idx] = 0; text = r_str_ansi_crop (read_only, 0, sy, w + sx - 3, h - 2 + sy); char *newText = r_str_prefix_all (text, white); if (newText) { free (text); text = newText; } } else { text = r_str_ansi_crop (read_only, sx, sy, w + sx - 3, h - 2 + sy); } if (text) { r_cons_canvas_write (can, text); free (text); } } static void __update_help_title(RCore *core, RPanel *panel) { RConsCanvas *can = core->panels->can; RStrBuf *title = r_strbuf_new (NULL); RStrBuf *cache_title = r_strbuf_new (NULL); if (__check_if_cur_panel (core, panel)) { r_strbuf_setf (title, "%s[X] %s"Color_RESET, core->cons->context->pal.graph_box2, panel->model->title); r_strbuf_setf (cache_title, "%s[Cache] N/A"Color_RESET, core->cons->context->pal.graph_box2); } else { r_strbuf_setf (title, "[X] %s ", panel->model->title); r_strbuf_setf (cache_title, "[Cache] N/A"); } if (r_cons_canvas_gotoxy (can, panel->view->pos.x + 1, panel->view->pos.y + 1)) { r_cons_canvas_write (can, r_strbuf_get (title)); } if (r_cons_canvas_gotoxy (can, panel->view->pos.x + panel->view->pos.w - r_str_ansi_len (r_strbuf_get (cache_title)) - 2, panel->view->pos.y + 1)) { r_cons_canvas_write (can, r_strbuf_get (cache_title)); } r_strbuf_free (cache_title); r_strbuf_free (title); } static void __update_panel_contents(RCore *core, RPanel *panel, const char *cmdstr) { bool b = __is_abnormal_cursor_type (core, panel) && core->print->cur_enabled; int sx = b ? -2 :panel->view->sx; int sy = R_MAX (panel->view->sy, 0); int x = panel->view->pos.x; int y = panel->view->pos.y; if (x >= core->panels->can->w) { return; } if (y >= core->panels->can->h) { return; } int w = panel->view->pos.w; int h = panel->view->pos.h; int graph_pad = __check_panel_type (panel, PANEL_CMD_GRAPH) ? 1 : 0; char *text = NULL; RPanels *panels = core->panels; RConsCanvas *can = panels->can; (void) r_cons_canvas_gotoxy (can, x + 2, y + 2); if (sx < 0) { char *white = (char*)r_str_pad (' ', 128); int idx = R_MIN (-sx, strlen (white) - 1); white[idx] = 0; text = r_str_ansi_crop (cmdstr, 0, sy + graph_pad, w + sx - 3, h - 2 + sy); char *newText = r_str_prefix_all (text, white); if (newText) { free (text); text = newText; } } else { text = r_str_ansi_crop (cmdstr, sx, sy + graph_pad, w + sx - 3, h - 2 + sy); } if (text) { r_cons_canvas_write (can, text); free (text); } if (b) { int sub = panel->view->curpos - panel->view->sy; (void) r_cons_canvas_gotoxy (can, panel->view->pos.x + 2, panel->view->pos.y + 2 + sub); r_cons_canvas_write (can, "*"); } } static char *__apply_filter_cmd(RCore *core, RPanel *panel) { char *out = r_str_ndup (panel->model->cmd, strlen (panel->model->cmd) + 1024); if (!panel->model->filter) { return out; } int i; for (i = 0; i < panel->model->n_filter; i++) { char *filter = panel->model->filter[i]; if (strlen (filter) > 1024) { (void)__show_status (core, "filter is too big."); return out; } strcat (out, "~"); strcat (out, filter); } return out; } static void __update_panel_title(RCore *core, RPanel *panel) { RConsCanvas *can = core->panels->can; RStrBuf *title = r_strbuf_new (NULL); RStrBuf *cache_title = r_strbuf_new (NULL); char *cmd_title = __apply_filter_cmd (core, panel); if (__check_if_cur_panel (core, panel)) { if (!strcmp (panel->model->title, cmd_title)) { r_strbuf_setf (title, "%s[X] %s"Color_RESET, core->cons->context->pal.graph_box2, panel->model->title); } else { r_strbuf_setf (title, "%s[X] %s (%s)"Color_RESET, core->cons->context->pal.graph_box2, panel->model->title, cmd_title); } r_strbuf_setf (cache_title, "%s[Cache] %s"Color_RESET, core->cons->context->pal.graph_box2, panel->model->cache ? "On" : "Off"); } else { if (!strcmp (panel->model->title, cmd_title)) { r_strbuf_setf (title, "[X] %s ", panel->model->title); } else { r_strbuf_setf (title, "[X] %s (%s) ", panel->model->title, cmd_title); } r_strbuf_setf (cache_title, "[Cache] %s", panel->model->cache ? "On" : "Off"); } r_strbuf_slice (title, 0, panel->view->pos.w); r_strbuf_slice (cache_title, 0, panel->view->pos.w); if (r_cons_canvas_gotoxy (can, panel->view->pos.x + 1, panel->view->pos.y + 1)) { r_cons_canvas_write (can, r_strbuf_get (title)); } if (r_cons_canvas_gotoxy (can, panel->view->pos.x + panel->view->pos.w - r_str_ansi_len (r_strbuf_get (cache_title)) - 2, panel->view->pos.y + 1)) { r_cons_canvas_write (can, r_strbuf_get (cache_title)); } r_strbuf_free (title); r_strbuf_free (cache_title); free (cmd_title); } //TODO: make this a task static void __update_pdc_contents(RCore *core, RPanel *panel, char *cmdstr) { RPanels *panels = core->panels; RConsCanvas *can = panels->can; int sx = panel->view->sx; int sy = R_MAX (panel->view->sy, 0); int x = panel->view->pos.x; int y = panel->view->pos.y; int w = panel->view->pos.w; int h = panel->view->pos.h; char *text = NULL; (void) r_cons_canvas_gotoxy (can, x + 2, y + 2); if (sx < 0) { char *white = (char*)r_str_pad (' ', 128); int idx = R_MIN (-sx, strlen (white) - 1); white[idx] = 0; text = r_str_ansi_crop (cmdstr, 0, sy, w + sx - 3, h - 2 + sy); char *newText = r_str_prefix_all (text, white); if (newText) { free (text); text = newText; } } else { text = r_str_ansi_crop (cmdstr, sx, sy, w + sx - 3, h - 2 + sy); } if (text) { r_cons_canvas_write (can, text); free (text); } } static char *__find_cmd_str_cache(RCore *core, RPanel* panel) { if (panel->model->cache && panel->model->cmdStrCache) { return panel->model->cmdStrCache; } return NULL; } static char *__handle_cmd_str_cache(RCore *core, RPanel *panel, bool force_cache) { char *cmd = __apply_filter_cmd (core, panel); bool b = core->print->cur_enabled && __get_cur_panel (core->panels) != panel; if (b) { core->print->cur_enabled = false; } char *out = (*cmd == '.') ? r_core_cmd_str_pipe (core, cmd) : r_core_cmd_str (core, cmd); if (force_cache) { panel->model->cache = true; } if (R_STR_ISNOTEMPTY (out)) { __set_cmd_str_cache (core, panel, out); } else { R_FREE (out); } free (cmd); if (b) { core->print->cur_enabled = true; } return out; } static void __panel_all_clear(RPanels *panels) { if (!panels) { return; } int i; RPanel *panel = NULL; for (i = 0; i < panels->n_panels; i++) { panel = __get_panel (panels, i); r_cons_canvas_fill (panels->can, panel->view->pos.x, panel->view->pos.y, panel->view->pos.w, panel->view->pos.h, ' '); } r_cons_canvas_print (panels->can); r_cons_flush (); } static void __layout_default(RPanels *panels) { RPanel *p0 = __get_panel (panels, 0); int h, w = r_cons_get_size (&h); if (panels->n_panels <= 1) { __set_geometry (&p0->view->pos, 0, 1, w, h - 1); return; } int ph = (h - 1) / (panels->n_panels - 1); int colpos = w - panels->columnWidth; __set_geometry (&p0->view->pos, 0, 1, colpos + 1, h - 1); int pos_x = p0->view->pos.x + p0->view->pos.w - 1; int i, total_h = 0; for (i = 1; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); int tmp_w = R_MAX (w - colpos, 0); int tmp_h = 0; if (i + 1 == panels->n_panels) { tmp_h = h - total_h; } else { tmp_h = ph; } __set_geometry (&p->view->pos, pos_x, 2 + (ph * (i - 1)) - 1, tmp_w, tmp_h + 1); total_h += 2 + (ph * (i - 1)) - 1 + tmp_h + 1; } } static void __panels_layout(RPanels *panels) { panels->can->sx = 0; panels->can->sy = 0; __layout_default (panels); } static void __layout_equal_hor(RPanels *panels) { int h, w = r_cons_get_size (&h); int pw = w / panels->n_panels; int i, cw = 0; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); __set_geometry(&p->view->pos, cw, 1, pw, h - 1); cw += pw - 1; if (i == panels->n_panels - 2) { pw = w - cw; } } } static void __adjust_side_panels(RCore *core) { int i, h; (void)r_cons_get_size (&h); RPanels *panels = core->panels; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); if (p->view->pos.x == 0) { if (p->view->pos.w >= PANEL_CONFIG_SIDEPANEL_W) { p->view->pos.x += PANEL_CONFIG_SIDEPANEL_W - 1; p->view->pos.w -= PANEL_CONFIG_SIDEPANEL_W - 1; } } } } static void __update_help(RCore *core, RPanels *ps) { const char *help = "Help"; int i; for (i = 0; i < ps->n_panels; i++) { RPanel *p = __get_panel (ps, i); if (!strncmp (p->model->cmd, help, strlen (help))) { RStrBuf *rsb = r_strbuf_new (NULL); const char *title; const char **msg; switch (ps->mode) { case PANEL_MODE_WINDOW: title = "Panels Window Mode"; msg = help_msg_panels_window; break; case PANEL_MODE_ZOOM: title = "Panels Zoom Mode"; msg = help_msg_panels_zoom; break; default: title = "Panels Mode"; msg = help_msg_panels; break; } // panel's title does not change, keep it short and simple p->model->title = r_str_dup (p->model->title, help); p->model->cmd = r_str_dup (p->model->cmd, help); r_core_visual_append_help (rsb, title, msg); if (!rsb) { break; } char *drained = r_strbuf_drain (rsb); __set_read_only (core, p, drained); free (drained); p->view->refresh = true; } } } static void __set_cursor(RCore *core, bool cur) { RPanel *p = __get_cur_panel (core->panels); RPrint *print = core->print; print->cur_enabled = cur; if (__is_abnormal_cursor_type (core, p)) { return; } if (cur) { print->cur = p->view->curpos; } else { p->view->curpos = print->cur; } print->col = print->cur_enabled ? 1: 0; } static void __set_mode(RCore *core, RPanelsMode mode) { RPanels *panels = core->panels; __set_cursor (core, false); panels->mode = mode; __update_help (core, panels); } static void __set_curnode(RCore *core, int idx) { RPanels *panels = core->panels; if (idx >= panels->n_panels) { idx = 0; } if (idx < 0) { idx = panels->n_panels - 1; } panels->curnode = idx; RPanel *cur = __get_cur_panel (panels); cur->view->curpos = cur->view->sy; } static bool __check_panel_num(RCore *core) { RPanels *panels = core->panels; if (panels->n_panels + 1 > PANEL_NUM_LIMIT) { const char *msg = "panel limit exceeded."; (void)__show_status (core, msg); return false; } return true; } static void __set_rcb(RPanels *ps, RPanel *p) { SdbKv *kv; SdbListIter *sdb_iter; SdbList *sdb_list = sdb_foreach_list (ps->rotate_db, false); ls_foreach (sdb_list, sdb_iter, kv) { char *key = sdbkv_key (kv); if (!__check_panel_type (p, key)) { continue; } p->model->rotateCb = (RPanelRotateCallback)sdb_ptr_get (ps->rotate_db, key, 0); break; } ls_free (sdb_list); } static void __init_panel_param(RCore *core, RPanel *p, const char *title, const char *cmd) { RPanelModel *m = p->model; RPanelView *v = p->view; m->type = PANEL_TYPE_DEFAULT; m->rotate = 0; v->curpos = 0; __set_panel_addr (core, p, core->offset); m->rotateCb = NULL; __set_cmd_str_cache (core, p, NULL); __set_read_only (core, p, NULL); m->funcName = NULL; v->refresh = true; v->edge = 0; if (title) { m->title = r_str_dup (m->title, title); if (cmd) { m->cmd = r_str_dup (m->cmd, cmd); } else { m->cmd = r_str_dup (m->cmd, ""); } } else if (cmd) { m->title = r_str_dup (m->title, cmd); m->cmd = r_str_dup (m->cmd, cmd); } else { m->title = r_str_dup (m->title, ""); m->cmd = r_str_dup (m->cmd, ""); } __set_pcb (p); if (R_STR_ISNOTEMPTY (m->cmd)) { __set_dcb (core, p); __set_rcb (core->panels, p); if (__check_panel_type (p, PANEL_CMD_STACK)) { const char *sp = r_reg_get_name (core->anal->reg, R_REG_NAME_SP); const ut64 stackbase = r_reg_getv (core->anal->reg, sp); m->baseAddr = stackbase; __set_panel_addr (core, p, stackbase - r_config_get_i (core->config, "stack.delta")); } } core->panels->n_panels++; __cache_white_list (core, p); return; } static void __insert_panel(RCore *core, int n, const char *name, const char *cmd) { RPanels *panels = core->panels; if (panels->n_panels + 1 > PANEL_NUM_LIMIT) { return; } RPanel **panel = panels->panel; int i; RPanel *last = panel[panels->n_panels]; for (i = panels->n_panels - 1; i >= n; i--) { panel[i + 1] = panel[i]; } panel[n] = last; __init_panel_param (core, panel[n], name, cmd); } static int __add_cmd_panel(void *user) { RCore *core = (RCore *)user; RPanels *panels = core->panels; if (!__check_panel_num (core)) { return 0; } RPanelsMenu *menu = core->panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; char *cmd = __search_db (core, child->name); if (!cmd) { return 0; } int h; (void)r_cons_get_size (&h); __adjust_side_panels (core); __insert_panel (core, 0, child->name, cmd); RPanel *p0 = __get_panel (panels, 0); __set_geometry (&p0->view->pos, 0, 1, PANEL_CONFIG_SIDEPANEL_W, h - 1); __set_curnode (core, 0); __set_mode (core, PANEL_MODE_DEFAULT); free (cmd); return 0; } static void __add_help_panel(RCore *core) { //TODO: all these things done below are very hacky and refactoring needed RPanels *ps = core->panels; int h; const char *help = "Help"; (void)r_cons_get_size (&h); __adjust_side_panels (core); __insert_panel (core, 0, help, help); RPanel *p0 = __get_panel (ps, 0); __set_geometry (&p0->view->pos, 0, 1, PANEL_CONFIG_SIDEPANEL_W, h - 1); __set_curnode (core, 0); } static char *__load_cmdf(RCore *core, RPanel *p, char *input, char *str) { char *ret = NULL; char *res = __show_status_input (core, input); if (res) { p->model->cmd = r_str_newf (str, res); ret = r_core_cmd_str (core, p->model->cmd); free (res); } return ret; } static int __add_cmdf_panel(RCore *core, char *input, char *str) { RPanels *panels = core->panels; if (!__check_panel_num (core)) { return 0; } int h; (void)r_cons_get_size (&h); RPanelsMenu *menu = core->panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; __adjust_side_panels (core); __insert_panel (core, 0, child->name, ""); RPanel *p0 = __get_panel (panels, 0); __set_geometry (&p0->view->pos, 0, 1, PANEL_CONFIG_SIDEPANEL_W, h - 1); __set_cmd_str_cache (core, p0, __load_cmdf (core, p0, input, str)); __set_curnode (core, 0); __set_mode (core, PANEL_MODE_DEFAULT); return 0; } static void __fix_layout_w(RCore *core) { RPanels *panels = core->panels; RList *list = r_list_new (); int i = 0; for (; i < panels->n_panels - 1; i++) { RPanel *p = __get_panel (panels, i); int64_t t = p->view->pos.x + p->view->pos.w; r_list_append (list, (void *)(t)); } RListIter *iter; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); int tx = p->view->pos.x; if (!tx) { continue; } int min = INT8_MAX; int target_num = INT8_MAX; bool found = false; void *num = NULL; r_list_foreach (list, iter, num) { if ((int64_t)num - 1 == tx) { found = true; break; } int sub = (int64_t)num - tx; if (min > R_ABS (sub)) { min = R_ABS (sub); target_num = (int64_t)num; } } if (!found) { int t = p->view->pos.x - target_num + 1; p->view->pos.x = target_num - 1; p->view->pos.w += t; } } } static void __fix_layout_h(RCore *core) { RPanels *panels = core->panels; RList *list = r_list_new (); int h; (void)r_cons_get_size (&h); int i = 0; for (; i < panels->n_panels - 1; i++) { RPanel *p = __get_panel (panels, i); int64_t t = p->view->pos.y + p->view->pos.h; r_list_append (list, (void *)(t)); } RListIter *iter; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); int ty = p->view->pos.y; int th = p->view->pos.h; if (ty == 1 || th == (h - 1)) { continue; } int min = INT8_MAX; int target_num = INT8_MAX; bool found = false; void *num = NULL; r_list_foreach (list, iter, num) { if ((int64_t)num - 1 == ty) { found = true; break; } int sub = (int64_t)num - ty; if (min > R_ABS (sub)) { min = R_ABS (sub); target_num = (int64_t)num; } } if (!found) { int t = p->view->pos.y - target_num + 1; p->view->pos.y = target_num - 1; p->view->pos.h += t; } } r_list_free (list); } static void __fix_layout(RCore *core) { __fix_layout_w (core); __fix_layout_h (core); } static void show_cursor(RCore *core) { const bool keyCursor = r_config_get_i (core->config, "scr.cursor"); if (keyCursor) { r_cons_gotoxy (core->cons->cpos.x, core->cons->cpos.y); r_cons_show_cursor (1); r_cons_flush (); } } static void __set_refresh_all(RCore *core, bool clearCache, bool force_refresh) { RPanels *panels = core->panels; int i; for (i = 0; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); if (!force_refresh && __check_panel_type (panel, PANEL_CMD_CONSOLE)) { continue; } panel->view->refresh = true; if (clearCache) { __set_cmd_str_cache (core, panel, NULL); } } } static void __split_panel_vertical(RCore *core, RPanel *p, const char *name, const char *cmd) { RPanels *panels = core->panels; if (!__check_panel_num (core)) { return; } __insert_panel (core, panels->curnode + 1, name, cmd); RPanel *next = __get_panel (panels, panels->curnode + 1); int owidth = p->view->pos.w; p->view->pos.w = owidth / 2 + 1; __set_geometry (&next->view->pos, p->view->pos.x + p->view->pos.w - 1, p->view->pos.y, owidth - p->view->pos.w + 1, p->view->pos.h); __fix_layout (core); __set_refresh_all (core, false, true); } static void __split_panel_horizontal(RCore *core, RPanel *p, const char *name, const char *cmd) { RPanels *panels = core->panels; if (!__check_panel_num (core)) { return; } __insert_panel (core, panels->curnode + 1, name, cmd); RPanel *next = __get_panel (panels, panels->curnode + 1); int oheight = p->view->pos.h; p->view->curpos = 0; p->view->pos.h = oheight / 2 + 1; __set_geometry (&next->view->pos, p->view->pos.x, p->view->pos.y + p->view->pos.h - 1, p->view->pos.w, oheight - p->view->pos.h + 1); __fix_layout (core); __set_refresh_all (core, false, true); } static void __panels_check_stackbase(RCore *core) { if (!core || !core->panels) { return; } int i; const char *sp = r_reg_get_name (core->anal->reg, R_REG_NAME_SP); if (!sp) { return; } const ut64 stackbase = r_reg_getv (core->anal->reg, sp); RPanels *panels = core->panels; for (i = 1; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); if (panel->model->cmd && __check_panel_type (panel, PANEL_CMD_STACK) && panel->model->baseAddr != stackbase) { panel->model->baseAddr = stackbase; __set_panel_addr (core, panel, stackbase - r_config_get_i (core->config, "stack.delta") + core->print->cur); } } } static void __del_panel(RCore *core, int pi) { int i; RPanels *panels = core->panels; RPanel *tmp = __get_panel (panels, pi); if (!tmp) { return; } for (i = pi; i < (panels->n_panels - 1); i++) { panels->panel[i] = panels->panel[i + 1]; } panels->panel[panels->n_panels - 1] = tmp; panels->n_panels--; __set_curnode (core, panels->curnode); } static void __del_invalid_panels(RCore *core) { RPanels *panels = core->panels; int i; for (i = 1; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); if (panel->view->pos.w < 2) { __del_panel (core, i); __del_invalid_panels (core); break; } if (panel->view->pos.h < 2) { __del_panel (core, i); __del_invalid_panels (core); break; } } } static void __panels_layout_refresh(RCore *core) { __del_invalid_panels (core); __check_edge (core); __panels_check_stackbase (core); __panels_refresh (core); } static void __reset_scroll_pos(RPanel *p) { p->view->sx = 0; p->view->sy = 0; } static void __activate_cursor(RCore *core) { RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); bool normal = __is_normal_cursor_type (cur); bool abnormal = __is_abnormal_cursor_type (core, cur); if (normal || abnormal) { if (normal && cur->model->cache) { if (__show_status_yesno (core, 1, "You need to turn off cache to use cursor. Turn off now?(Y/n)")) { cur->model->cache = false; __set_cmd_str_cache (core, cur, NULL); (void)__show_status (core, "Cache is off and cursor is on"); __set_cursor (core, !core->print->cur_enabled); cur->view->refresh = true; __reset_scroll_pos (cur); } else { (void)__show_status (core, "You can always toggle cache by \'&\' key"); } return; } __set_cursor (core, !core->print->cur_enabled); cur->view->refresh = true; } else { (void)__show_status (core, "Cursor is not available for the current panel."); } } ut64 __parse_string_on_cursor(RCore *core, RPanel *panel, int idx) { if (!panel->model->cmdStrCache) { return UT64_MAX; } RStrBuf *buf = r_strbuf_new (NULL); char *s = panel->model->cmdStrCache; int l = 0; while (R_STR_ISNOTEMPTY (s) && l != idx) { if (*s == '\n') { l++; } s++; } while (R_STR_ISNOTEMPTY (s) && R_STR_ISNOTEMPTY (s + 1)) { if (*s == '0' && *(s + 1) == 'x') { r_strbuf_append_n (buf, s, 2); while (*s != ' ') { r_strbuf_append_n (buf, s, 1); s++; } ut64 ret = r_num_math (core->num, r_strbuf_get (buf)); r_strbuf_free (buf); return ret; } s++; } r_strbuf_free (buf); return UT64_MAX; } static void __fix_cursor_up(RCore *core) { RPrint *print = core->print; if (print->cur >= 0) { return; } int sz = r_core_visual_prevopsz (core, core->offset + print->cur); if (sz < 1) { sz = 1; } r_core_seek_delta (core, -sz); print->cur += sz; if (print->ocur != -1) { print->ocur += sz; } } static void __cursor_left(RCore *core) { RPanel *cur = __get_cur_panel (core->panels); RPrint *print = core->print; if (__check_panel_type (cur, PANEL_CMD_REGISTERS) || __check_panel_type (cur, PANEL_CMD_STACK)) { if (print->cur > 0) { print->cur--; cur->model->addr--; } } else if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { print->cur--; __fix_cursor_up (core); } else { print->cur--; } } static void __fix_cursor_down(RCore *core) { RPrint *print = core->print; bool cur_is_visible = core->offset + print->cur + 32 < print->screen_bounds; if (!cur_is_visible) { int i = 0; //XXX: ugly hack for (i = 0; i < 2; i++) { RAsmOp op; int sz = r_asm_disassemble (core->rasm, &op, core->block, 32); if (sz < 1) { sz = 1; } r_core_seek_delta (core, sz); print->cur = R_MAX (print->cur - sz, 0); if (print->ocur != -1) { print->ocur = R_MAX (print->ocur - sz, 0); } } } } static void __cursor_right(RCore *core) { RPanel *cur = __get_cur_panel (core->panels); RPrint *print = core->print; if (__check_panel_type (cur, PANEL_CMD_STACK) && print->cur >= 15) { return; } if (__check_panel_type (cur, PANEL_CMD_REGISTERS) || __check_panel_type (cur, PANEL_CMD_STACK)) { print->cur++; cur->model->addr++; } else if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { print->cur++; __fix_cursor_down (core); } else { print->cur++; } } static void __cursor_up(RCore *core) { RPrint *print = core->print; ut64 addr, oaddr = core->offset + print->cur; if (r_core_prevop_addr (core, oaddr, 1, &addr)) { const int delta = oaddr - addr; print->cur -= delta; } else { print->cur -= 4; } __fix_cursor_up (core); } static void __cursor_down(RCore *core) { RPrint *print = core->print; RAnalOp *aop = r_core_anal_op (core, core->offset + print->cur, R_ANAL_OP_MASK_BASIC); if (aop) { print->cur += aop->size; r_anal_op_free (aop); } else { print->cur += 4; } __fix_cursor_down (core); } static void __save_panel_pos(RPanel* panel) { __set_geometry (&panel->view->prevPos, panel->view->pos.x, panel->view->pos.y, panel->view->pos.w, panel->view->pos.h); } static void __restore_panel_pos(RPanel* panel) { __set_geometry (&panel->view->pos, panel->view->prevPos.x, panel->view->prevPos.y, panel->view->prevPos.w, panel->view->prevPos.h); } static void __maximize_panel_size(RPanels *panels) { RPanel *cur = __get_cur_panel (panels); __set_geometry (&cur->view->pos, 0, 1, panels->can->w, panels->can->h - 1); cur->view->refresh = true; } static void __dismantle_panel(RPanels *ps, RPanel *p) { RPanel *justLeftPanel = NULL, *justRightPanel = NULL, *justUpPanel = NULL, *justDownPanel = NULL; RPanel *tmpPanel = NULL; bool leftUpValid = false, leftDownValid = false, rightUpValid = false, rightDownValid = false, upLeftValid = false, upRightValid = false, downLeftValid = false, downRightValid = false; int left[PANEL_NUM_LIMIT], right[PANEL_NUM_LIMIT], up[PANEL_NUM_LIMIT], down[PANEL_NUM_LIMIT]; memset (left, -1, sizeof (left)); memset (right, -1, sizeof (right)); memset (up, -1, sizeof (up)); memset (down, -1, sizeof (down)); int i, ox, oy, ow, oh; ox = p->view->pos.x; oy = p->view->pos.y; ow = p->view->pos.w; oh = p->view->pos.h; for (i = 0; i < ps->n_panels; i++) { tmpPanel = __get_panel (ps, i); if (tmpPanel->view->pos.x + tmpPanel->view->pos.w - 1 == ox) { left[i] = 1; if (oy == tmpPanel->view->pos.y) { leftUpValid = true; if (oh == tmpPanel->view->pos.h) { justLeftPanel = tmpPanel; break; } } if (oy + oh == tmpPanel->view->pos.y + tmpPanel->view->pos.h) { leftDownValid = true; } } if (tmpPanel->view->pos.x == ox + ow - 1) { right[i] = 1; if (oy == tmpPanel->view->pos.y) { rightUpValid = true; if (oh == tmpPanel->view->pos.h) { rightDownValid = true; justRightPanel = tmpPanel; } } if (oy + oh == tmpPanel->view->pos.y + tmpPanel->view->pos.h) { rightDownValid = true; } } if (tmpPanel->view->pos.y + tmpPanel->view->pos.h - 1 == oy) { up[i] = 1; if (ox == tmpPanel->view->pos.x) { upLeftValid = true; if (ow == tmpPanel->view->pos.w) { upRightValid = true; justUpPanel = tmpPanel; } } if (ox + ow == tmpPanel->view->pos.x + tmpPanel->view->pos.w) { upRightValid = true; } } if (tmpPanel->view->pos.y == oy + oh - 1) { down[i] = 1; if (ox == tmpPanel->view->pos.x) { downLeftValid = true; if (ow == tmpPanel->view->pos.w) { downRightValid = true; justDownPanel = tmpPanel; } } if (ox + ow == tmpPanel->view->pos.x + tmpPanel->view->pos.w) { downRightValid = true; } } } if (justLeftPanel) { justLeftPanel->view->pos.w += ox + ow - (justLeftPanel->view->pos.x + justLeftPanel->view->pos.w); } else if (justRightPanel) { justRightPanel->view->pos.w = justRightPanel->view->pos.x + justRightPanel->view->pos.w - ox; justRightPanel->view->pos.x = ox; } else if (justUpPanel) { justUpPanel->view->pos.h += oy + oh - (justUpPanel->view->pos.y + justUpPanel->view->pos.h); } else if (justDownPanel) { justDownPanel->view->pos.h = oh + justDownPanel->view->pos.y + justDownPanel->view->pos.h - (oy + oh); justDownPanel->view->pos.y = oy; } else if (leftUpValid && leftDownValid) { for (i = 0; i < ps->n_panels; i++) { if (left[i] != -1) { tmpPanel = __get_panel (ps, i); tmpPanel->view->pos.w += ox + ow - (tmpPanel->view->pos.x + tmpPanel->view->pos.w); } } } else if (rightUpValid && rightDownValid) { for (i = 0; i < ps->n_panels; i++) { if (right[i] != -1) { tmpPanel = __get_panel (ps, i); tmpPanel->view->pos.w = tmpPanel->view->pos.x + tmpPanel->view->pos.w - ox; tmpPanel->view->pos.x = ox; } } } else if (upLeftValid && upRightValid) { for (i = 0; i < ps->n_panels; i++) { if (up[i] != -1) { tmpPanel = __get_panel (ps, i); tmpPanel->view->pos.h += oy + oh - (tmpPanel->view->pos.y + tmpPanel->view->pos.h); } } } else if (downLeftValid && downRightValid) { for (i = 0; i < ps->n_panels; i++) { if (down[i] != -1) { tmpPanel = __get_panel (ps, i); tmpPanel->view->pos.h = oh + tmpPanel->view->pos.y + tmpPanel->view->pos.h - (oy + oh); tmpPanel->view->pos.y = oy; } } } } static void __dismantle_del_panel(RCore *core, RPanel *p, int pi) { RPanels *panels = core->panels; if (panels->n_panels <= 1) { return; } __dismantle_panel (panels, p); __del_panel (core, pi); } static void __toggle_help(RCore *core) { RPanels *ps = core->panels; int i; for (i = 0; i < ps->n_panels; i++) { RPanel *p = __get_panel (ps, i); if (r_str_endswith (p->model->cmd, "Help")) { __dismantle_del_panel (core, p, i); if (ps->mode == PANEL_MODE_MENU) { __set_mode (core, PANEL_MODE_DEFAULT); } return; } } __add_help_panel (core); if (ps->mode == PANEL_MODE_MENU) { __set_mode (core, PANEL_MODE_DEFAULT); } __update_help (core, ps); } static void __reset_snow(RPanels *panels) { RPanel *cur = __get_cur_panel (panels); r_list_free (panels->snows); panels->snows = NULL; cur->view->refresh = true; } static void __toggle_zoom_mode(RCore *core) { RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); if (panels->mode != PANEL_MODE_ZOOM) { panels->prevMode = panels->mode; __set_mode (core, PANEL_MODE_ZOOM); __save_panel_pos (cur); __maximize_panel_size (panels); } else { __set_mode (core, panels->prevMode); panels->prevMode = PANEL_MODE_DEFAULT; __restore_panel_pos (cur); if (panels->fun == PANEL_FUN_SNOW || panels->fun == PANEL_FUN_SAKURA) { __reset_snow (panels); } } } static void __set_root_state(RCore *core, RPanelsRootState state) { core->panels_root->root_state = state; } static void __handle_tab_next(RCore *core) { if (core->panels_root->n_panels > 1) { core->panels_root->cur_panels++; core->panels_root->cur_panels %= core->panels_root->n_panels; __set_root_state (core, ROTATE); } } static void __handle_print_rotate(RCore *core) { if (r_config_get_i (core->config, "asm.pseudo")) { r_config_toggle (core->config, "asm.pseudo"); r_config_toggle (core->config, "asm.esil"); } else if (r_config_get_i (core->config, "asm.esil")) { r_config_toggle (core->config, "asm.esil"); } else { r_config_toggle (core->config, "asm.pseudo"); } } static void __handle_tab_prev(RCore *core) { if (core->panels_root->n_panels > 1) { core->panels_root->cur_panels--; if (core->panels_root->cur_panels < 0) { core->panels_root->cur_panels = core->panels_root->n_panels - 1; } __set_root_state (core, ROTATE); } } static void __handle_tab_name(RCore *core) { core->panels->name = __show_status_input (core, "tab name: "); } static void __handle_tab_new(RCore *core) { if (core->panels_root->n_panels >= PANEL_NUM_LIMIT) { return; } __init_new_panels_root (core); } static void __init_sdb(RCore *core) { Sdb *db = core->panels->db; sdb_set (db, "Symbols", "isq", 0); sdb_set (db, "Stack" , "px 256@r:SP", 0); sdb_set (db, "Locals", "afvd", 0); sdb_set (db, "Registers", "dr", 0); sdb_set (db, "RegisterRefs", "drr", 0); sdb_set (db, "Disassembly", "pd", 0); sdb_set (db, "Disassemble Summary", "pdsf", 0); sdb_set (db, "Decompiler", "pdc", 0); sdb_set (db, "Decompiler With Offsets", "pdco", 0); sdb_set (db, "Graph", "agf", 0); sdb_set (db, "Tiny Graph", "agft", 0); sdb_set (db, "Info", "i", 0); sdb_set (db, "Database", "k ***", 0); sdb_set (db, "Console", "$console", 0); sdb_set (db, "Hexdump", "xc $r*16", 0); sdb_set (db, "Xrefs", "ax", 0); sdb_set (db, "Xrefs Here", "ax.", 0); sdb_set (db, "Functions", "afl", 0); sdb_set (db, "Function Calls", "aflm", 0); sdb_set (db, "Comments", "CC", 0); sdb_set (db, "Entropy", "p=e 100", 0); sdb_set (db, "Entropy Fire", "p==e 100", 0); sdb_set (db, "DRX", "drx", 0); sdb_set (db, "Sections", "iSq", 0); sdb_set (db, "Segments", "iSSq", 0); sdb_set (db, PANEL_TITLE_STRINGS_DATA, "izq", 0); sdb_set (db, PANEL_TITLE_STRINGS_BIN, "izzq", 0); sdb_set (db, "Maps", "dm", 0); sdb_set (db, "Modules", "dmm", 0); sdb_set (db, "Backtrace", "dbt", 0); sdb_set (db, "Breakpoints", "db", 0); sdb_set (db, "Imports", "iiq", 0); sdb_set (db, "Clipboard", "yx", 0); sdb_set (db, "New", "o", 0); sdb_set (db, "Var READ address", "afvR", 0); sdb_set (db, "Var WRITE address", "afvW", 0); sdb_set (db, "Summary", "pdsf", 0); sdb_set (db, "Classes", "icq", 0); sdb_set (db, "Methods", "ic", 0); sdb_set (db, "Relocs", "ir", 0); sdb_set (db, "Headers", "iH", 0); sdb_set (db, "File Hashes", "it", 0); } static void __free_panel_model(RPanel *panel) { free (panel->model->title); free (panel->model->cmd); free (panel->model->cmdStrCache); free (panel->model->readOnly); free (panel->model); } static void __replace_cmd(RCore *core, const char *title, const char *cmd) { RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); __free_panel_model (cur); cur->model = R_NEW0 (RPanelModel); cur->model->title = r_str_dup (cur->model->title, title); cur->model->cmd = r_str_dup (cur->model->cmd, cmd); __set_cmd_str_cache (core, cur, NULL); __set_panel_addr (core, cur, core->offset); cur->model->type = PANEL_TYPE_DEFAULT; __set_dcb (core, cur); __set_pcb (cur); __set_rcb (panels, cur); __cache_white_list (core, cur); __set_refresh_all (core, false, true); } static void __create_panel(RCore *core, RPanel *panel, const RPanelLayout dir, R_NULLABLE const char* title, const char *cmd) { if (!__check_panel_num (core)) { return; } switch (dir) { case PANEL_LAYOUT_VERTICAL: __split_panel_vertical (core, panel, title, cmd); break; case PANEL_LAYOUT_HORIZONTAL: __split_panel_horizontal (core, panel, title, cmd); break; case PANEL_LAYOUT_NONE: __replace_cmd (core, title, cmd); break; } } static void __create_panel_db(void *user, RPanel *panel, const RPanelLayout dir, R_NULLABLE const char *title) { RCore *core = (RCore *)user; char *cmd = sdb_get (core->panels->db, title, 0); if (!cmd) { return; } __create_panel (core, panel, dir, title, cmd); } static void __create_panel_input(void *user, RPanel *panel, const RPanelLayout dir, R_NULLABLE const char *title) { RCore *core = (RCore *)user; char *cmd = __show_status_input (core, "Command: "); if (cmd) { __create_panel (core, panel, dir, cmd, cmd); } } static void __replace_current_panel_input(void *user, RPanel *panel, const RPanelLayout dir, R_NULLABLE const char *title) { RCore *core = (RCore *)user; char *cmd = __show_status_input (core, "New command: "); if (R_STR_ISNOTEMPTY (cmd)) { __replace_cmd (core, cmd, cmd); } free (cmd); } static char *__search_strings(RCore *core, bool whole) { const char *title = whole ? PANEL_TITLE_STRINGS_BIN : PANEL_TITLE_STRINGS_DATA; const char *str = __show_status_input (core, "Search Strings: "); char *db_val = __search_db (core, title); char *ret = r_str_newf ("%s~%s", db_val, str); free (db_val); return ret; } static void __search_strings_data_create(void *user, RPanel *panel, const RPanelLayout dir, R_NULLABLE const char *title) { RCore *core = (RCore *)user; __create_panel (core, panel, dir, title, __search_strings (core, false)); } static void __search_strings_bin_create(void *user, RPanel *panel, const RPanelLayout dir, R_NULLABLE const char *title) { RCore *core = (RCore *)user; __create_panel (core, panel, dir, title, __search_strings (core, true)); } static RPanels *__get_panels(RPanelsRoot *panels_root, int i) { if (!panels_root || (i >= PANEL_NUM_LIMIT)) { return NULL; } return panels_root->panels[i]; } static void __update_disassembly_or_open (RCore *core) { RPanels *panels = core->panels; int i; bool create_new = true; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); if (__check_panel_type (p, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, p, core->offset); create_new = false; } } if (create_new) { RPanel *panel = __get_panel (panels, 0); int x0 = panel->view->pos.x; int y0 = panel->view->pos.y; int w0 = panel->view->pos.w; int h0 = panel->view->pos.h; int threshold_w = x0 + panel->view->pos.w; int x1 = x0 + w0 / 2 - 1; int w1 = threshold_w - x1; __insert_panel (core, 0, PANEL_TITLE_DISASSEMBLY, PANEL_CMD_DISASSEMBLY); RPanel *p0 = __get_panel (panels, 0); __set_geometry (&p0->view->pos, x0, y0, w0 / 2, h0); RPanel *p1 = __get_panel (panels, 1); __set_geometry (&p1->view->pos, x1, y0, w1, h0); __set_cursor (core, false); __set_curnode (core, 0); } } static int __continue_cb(void *user) { RCore *core = (RCore *)user; r_core_cmd (core, "dc", 0); r_cons_flush (); return 0; } static void __continue_modal_cb(void *user, R_UNUSED RPanel *panel, R_UNUSED const RPanelLayout dir, R_UNUSED R_NULLABLE const char *title) { __continue_cb (user); __update_disassembly_or_open ((RCore *)user); } static void __panel_single_step_in(RCore *core) { if (r_config_get_i (core->config, "cfg.debug")) { r_core_cmd (core, "ds", 0); r_core_cmd (core, ".dr*", 0); } else { r_core_cmd (core, "aes", 0); r_core_cmd (core, ".ar*", 0); } } static int __step_cb(void *user) { RCore *core = (RCore *)user; __panel_single_step_in (core); __update_disassembly_or_open (core); return 0; } static void __panel_single_step_over(RCore *core) { bool io_cache = r_config_get_i (core->config, "io.cache"); r_config_set_i (core->config, "io.cache", false); if (r_config_get_i (core->config, "cfg.debug")) { r_core_cmd (core, "dso", 0); r_core_cmd (core, ".dr*", 0); } else { r_core_cmd (core, "aeso", 0); r_core_cmd (core, ".ar*", 0); } r_config_set_i (core->config, "io.cache", io_cache); } static int __step_over_cb(void *user) { RCore *core = (RCore *)user; __panel_single_step_over (core); __update_disassembly_or_open (core); return 0; } static void __step_modal_cb(void *user, R_UNUSED RPanel *panel, R_UNUSED const RPanelLayout dir, R_UNUSED R_NULLABLE const char *title) { __step_cb (user); } static void __panel_prompt(const char *prompt, char *buf, int len) { r_line_set_prompt (prompt); *buf = 0; r_cons_fgets (buf, len, 0, NULL); } static int __break_points_cb(void *user) { RCore *core = (RCore *)user; char buf[128]; const char *prompt = "addr: "; core->cons->line->prompt_type = R_LINE_PROMPT_OFFSET; r_line_set_hist_callback (core->cons->line, &r_line_hist_offset_up, &r_line_hist_offset_down); __panel_prompt (prompt, buf, sizeof (buf)); r_line_set_hist_callback (core->cons->line, &r_line_hist_cmd_up, &r_line_hist_cmd_down); core->cons->line->prompt_type = R_LINE_PROMPT_DEFAULT; ut64 addr = r_num_math (core->num, buf); r_core_cmdf (core, "dbs 0x%08"PFMT64x, addr); return 0; } static void __put_breakpoints_cb(void *user, R_UNUSED RPanel *panel, R_UNUSED const RPanelLayout dir, R_UNUSED R_NULLABLE const char *title) { __break_points_cb (user); } static void __step_over_modal_cb(void *user, R_UNUSED RPanel *panel, R_UNUSED const RPanelLayout dir, R_UNUSED R_NULLABLE const char *title) { __step_over_cb (user); } static int __show_all_decompiler_cb(void *user) { RCore *core = (RCore *)user; RAnalFunction *func = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL); if (!func) { return 0; } RPanelsRoot *root = core->panels_root; const char *pdc_now = r_config_get (core->config, "cmd.pdc"); char *opts = r_core_cmd_str (core, "e cmd.pdc=?"); RList *optl = r_str_split_list (opts, "\n", 0); RListIter *iter; char *opt; int i = 0; __handle_tab_new (core); RPanels *panels = __get_panels (root, root->n_panels - 1); r_list_foreach (optl, iter, opt) { if (R_STR_ISEMPTY (opt)) { continue; } r_config_set (core->config, "cmd.pdc", opt); RPanel *panel = __get_panel (panels, i++); panels->n_panels = i; panel->model->title = r_str_new (opt); __set_read_only (core, panel, r_core_cmd_str (core, opt)); } __layout_equal_hor (panels); r_list_free (optl); free (opts); r_config_set (core->config, "cmd.pdc", pdc_now); root->cur_panels = root->n_panels - 1; __set_root_state (core, ROTATE); return 0; } static void __delegate_show_all_decompiler_cb(void *user, RPanel *panel, const RPanelLayout dir, R_NULLABLE const char *title) { (void)__show_all_decompiler_cb ((RCore *)user); } static void __init_modal_db(RCore *core) { Sdb *db = core->panels->modal_db; SdbKv *kv; SdbListIter *sdb_iter; SdbList *sdb_list = sdb_foreach_list (core->panels->db, true); ls_foreach (sdb_list, sdb_iter, kv) { const char *key = sdbkv_key (kv); sdb_ptr_set (db, r_str_new (key), &__create_panel_db, 0); } sdb_ptr_set (db, "Search strings in data sections", &__search_strings_data_create, 0); sdb_ptr_set (db, "Search strings in the whole bin", &__search_strings_bin_create, 0); sdb_ptr_set (db, "Create New", &__create_panel_input, 0); sdb_ptr_set (db, "Change Command of Current Panel", &__replace_current_panel_input, 0); sdb_ptr_set (db, PANEL_TITLE_ALL_DECOMPILER, &__delegate_show_all_decompiler_cb, 0); if (r_config_get_i (core->config, "cfg.debug")) { sdb_ptr_set (db, "Put Breakpoints", &__put_breakpoints_cb, 0); sdb_ptr_set (db, "Continue", &__continue_modal_cb, 0); sdb_ptr_set (db, "Step", &__step_modal_cb, 0); sdb_ptr_set (db, "Step Over", &__step_over_modal_cb, 0); } } static void __renew_filter(RPanel *panel, int n) { panel->model->n_filter = 0; char **filter = calloc (sizeof (char *), n); if (!filter) { panel->model->filter = NULL; return; } panel->model->filter = filter; } static void __reset_filter(RCore *core, RPanel *panel) { free (panel->model->filter); panel->model->filter = NULL; __renew_filter (panel, PANEL_NUM_LIMIT); __set_cmd_str_cache (core, panel, NULL); panel->view->refresh = true; __reset_scroll_pos (panel); } static void __rotate_panel_cmds(RCore *core, const char **cmds, const int cmdslen, const char *prefix, bool rev) { if (!cmdslen) { return; } RPanel *p = __get_cur_panel (core->panels); __reset_filter (core, p); if (rev) { if (!p->model->rotate) { p->model->rotate = cmdslen - 1; } else { p->model->rotate--; } } else { p->model->rotate++; } char tmp[64], *between; int i = p->model->rotate % cmdslen; snprintf (tmp, sizeof (tmp), "%s%s", prefix, cmds[i]); between = r_str_between (p->model->cmd, prefix, " "); if (between) { char replace[64]; snprintf (replace, sizeof (replace), "%s%s", prefix, between); p->model->cmd = r_str_replace (p->model->cmd, replace, tmp, 1); } else { p->model->cmd = r_str_dup (p->model->cmd, tmp); } __set_cmd_str_cache (core, p, NULL); p->view->refresh = true; } static void __rotate_entropy_v_cb(void *user, bool rev) { RCore *core = (RCore *)user; __rotate_panel_cmds (core, entropy_rotate, COUNT (entropy_rotate), "p=", rev); } static void __rotate_entropy_h_cb(void *user, bool rev) { RCore *core = (RCore *)user; __rotate_panel_cmds (core, entropy_rotate, COUNT (entropy_rotate), "p==", rev); } static void __rotate_asmemu(RCore *core, RPanel *p) { const bool isEmuStr = r_config_get_i (core->config, "emu.str"); const bool isEmu = r_config_get_i (core->config, "asm.emu"); if (isEmu) { if (isEmuStr) { r_config_set (core->config, "emu.str", "false"); } else { r_config_set (core->config, "asm.emu", "false"); } } else { r_config_set (core->config, "emu.str", "true"); } p->view->refresh = true; } static void __rotate_hexdump_cb(void *user, bool rev) { RCore *core = (RCore *)user; RPanel *p = __get_cur_panel (core->panels); if (rev) { p->model->rotate--; } else { p->model->rotate++; } r_core_visual_applyHexMode (core, p->model->rotate); __rotate_asmemu (core, p); } static void __rotate_register_cb(void *user, bool rev) { RCore *core = (RCore *)user; __rotate_panel_cmds (core, register_rotate, COUNT (register_rotate), "dr", rev); } static void __rotate_function_cb(void *user, bool rev) { RCore *core = (RCore *)user; __rotate_panel_cmds (core, function_rotate, COUNT (function_rotate), "af", rev); } static void __rotate_disasm_cb(void *user, bool rev) { RCore *core = (RCore *)user; RPanel *p = __get_cur_panel (core->panels); //TODO: need to come up with a better solution but okay for now if (!strcmp (p->model->cmd, PANEL_CMD_DECOMPILER) || !strcmp (p->model->cmd, PANEL_CMD_DECOMPILER_O)) { return; } if (rev) { if (!p->model->rotate) { p->model->rotate = 4; } else { p->model->rotate--; } } else { p->model->rotate++; } r_core_visual_applyDisMode (core, p->model->rotate); __rotate_asmemu (core, p); } static void __init_rotate_db(RCore *core) { Sdb *db = core->panels->rotate_db; sdb_ptr_set (db, "pd", &__rotate_disasm_cb, 0); sdb_ptr_set (db, "p==", &__rotate_entropy_h_cb, 0); sdb_ptr_set (db, "p=", &__rotate_entropy_v_cb, 0); sdb_ptr_set (db, "px", &__rotate_hexdump_cb, 0); sdb_ptr_set (db, "dr", &__rotate_register_cb, 0); sdb_ptr_set (db, "af", &__rotate_function_cb, 0); sdb_ptr_set (db, PANEL_CMD_HEXDUMP, &__rotate_hexdump_cb, 0); } static void __init_all_dbs(RCore *core) { __init_sdb (core); __init_modal_db (core); __init_rotate_db (core); } static RConsCanvas *__create_new_canvas(RCore *core, int w, int h) { RConsCanvas *can = r_cons_canvas_new (w, h); if (!can) { eprintf ("Cannot create RCons.canvas context\n"); return false; } r_cons_canvas_fill (can, 0, 0, w, h, ' '); can->linemode = r_config_get_i (core->config, "graph.linemode"); can->color = r_config_get_i (core->config, "scr.color"); return can; } static void __free_menu_item(RPanelsMenuItem *item) { if (!item) { return; } size_t i; free (item->name); free (item->p->model); free (item->p->view); free (item->p); for (i = 0; i < item->n_sub; i++) { __free_menu_item (item->sub[i]); } free (item->sub); free (item); } static void __mht_free_kv(HtPPKv *kv) { free (kv->key); __free_menu_item ((RPanelsMenuItem *)kv->value); } static bool __init(RCore *core, RPanels *panels, int w, int h) { panels->panel = NULL; panels->n_panels = 0; panels->columnWidth = 80; if (r_config_get_i (core->config, "cfg.debug")) { panels->layout = PANEL_LAYOUT_DEFAULT_DYNAMIC; } else { panels->layout = PANEL_LAYOUT_DEFAULT_STATIC; } panels->autoUpdate = false; panels->mouse_on_edge_x = false; panels->mouse_on_edge_y = false; panels->mouse_orig_x = 0; panels->mouse_orig_y = 0; panels->can = __create_new_canvas (core, w, h); panels->db = sdb_new0 (); panels->rotate_db = sdb_new0 (); panels->modal_db = sdb_new0 (); panels->mht = ht_pp_new (NULL, (HtPPKvFreeFunc)__mht_free_kv, (HtPPCalcSizeV)strlen); panels->fun = PANEL_FUN_NOFUN; panels->prevMode = PANEL_MODE_DEFAULT; panels->name = NULL; if (w < 140) { panels->columnWidth = w / 3; } return true; } static RPanels *__panels_new(RCore *core) { RPanels *panels = R_NEW0 (RPanels); if (!panels) { return NULL; } int h, w = r_cons_get_size (&h); firstRun = true; if (!__init (core, panels, w, h)) { free (panels); return NULL; } return panels; } static void __handle_tab_new_with_cur_panel (RCore *core) { RPanels *panels = core->panels; if (panels->n_panels <= 1) { return; } RPanelsRoot *root = core->panels_root; if (root->n_panels + 1 >= PANEL_NUM_LIMIT) { return; } RPanel *cur = __get_cur_panel (panels); RPanels *new_panels = __panels_new (core); if (!new_panels) { return; } root->panels[root->n_panels] = new_panels; RPanels *prev = core->panels; core->panels = new_panels; if (!__init_panels_menu (core) || !__init_panels (core, new_panels)) { core->panels = prev; return; } __set_mode (core, PANEL_MODE_DEFAULT); __init_all_dbs (core); RPanel *new_panel = __get_panel (new_panels, 0); __init_panel_param (core, new_panel, cur->model->title, cur->model->cmd); new_panel->model->cache = cur->model->cache; new_panel->model->funcName = r_str_new (cur->model->funcName); __set_cmd_str_cache (core, new_panel, r_str_new (cur->model->cmdStrCache)); __maximize_panel_size (new_panels); core->panels = prev; __dismantle_del_panel (core, cur, panels->curnode); root->cur_panels = root->n_panels; root->n_panels++; __set_root_state (core, ROTATE); } static void __handle_tab_key(RCore *core, bool shift) { __set_cursor (core, false); RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); r_cons_switchbuf (false); cur->view->refresh = true; if (!shift) { if (panels->mode == PANEL_MODE_MENU) { __set_curnode (core, 0); __set_mode (core, PANEL_MODE_DEFAULT); } else if (panels->mode == PANEL_MODE_ZOOM) { __set_curnode (core, ++panels->curnode); } else { __set_curnode (core, ++panels->curnode); } } else { if (panels->mode == PANEL_MODE_MENU) { __set_curnode (core, panels->n_panels - 1); __set_mode (core, PANEL_MODE_DEFAULT); } else if (panels->mode == PANEL_MODE_ZOOM) { __set_curnode (core, --panels->curnode); } else { __set_curnode (core, --panels->curnode); } } cur = __get_cur_panel (panels); cur->view->refresh = true; if (panels->fun == PANEL_FUN_SNOW || panels->fun == PANEL_FUN_SAKURA) { __reset_snow (panels); } } static bool __handle_zoom_mode(RCore *core, const int key) { RPanels *panels = core->panels; r_cons_switchbuf (false); switch (key) { case 'Q': case 'q': case 0x0d: __toggle_zoom_mode (core); break; case 'c': case 'C': case ';': case ' ': case '_': case '/': case '"': case 'A': case 'r': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'u': case 'U': case 'b': case 'd': case 'n': case 'N': case 'g': case 'h': case 'j': case 'k': case 'J': case 'K': case 'l': case '.': case 'R': case 'p': case 'P': case 's': case 'S': case 't': case 'T': case 'x': case 'X': case ':': case '[': case ']': return false; case 9: __restore_panel_pos (panels->panel[panels->curnode]); __handle_tab_key (core, false); __save_panel_pos (panels->panel[panels->curnode]); __maximize_panel_size (panels); break; case 'Z': __restore_panel_pos (panels->panel[panels->curnode]); __handle_tab_key (core, true); __save_panel_pos (panels->panel[panels->curnode]); __maximize_panel_size (panels); break; case '?': __toggle_zoom_mode (core); __toggle_help (core); __toggle_zoom_mode (core); break; } return true; } static void __set_refresh_by_type(RCore *core, const char *cmd, bool clearCache) { RPanels *panels = core->panels; int i; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); if (!__check_panel_type (p, cmd)) { continue; } p->view->refresh = true; if (clearCache) { __set_cmd_str_cache (core, p, NULL); } } } static char *filter_arg(char *a) { r_name_filter_print (a); char *r = r_str_escape (a); free (a); return r; } static void __handleComment(RCore *core) { RPanel *p = __get_cur_panel (core->panels); if (!__check_panel_type (p, PANEL_CMD_DISASSEMBLY)) { return; } char buf[4095]; char *cmd = NULL; r_line_set_prompt ("[Comment]> "); if (r_cons_fgets (buf, sizeof (buf), 0, NULL) > 0) { ut64 addr, orig; addr = orig = core->offset; if (core->print->cur_enabled) { addr += core->print->cur; r_core_seek (core, addr, false); r_core_cmdf (core, "s 0x%"PFMT64x, addr); } if (!strcmp (buf, "-")) { cmd = strdup ("CC-"); } else { char *arg = filter_arg (strdup (buf)); switch (buf[0]) { case '-': cmd = r_str_newf ("\"CC-%s\"", arg); break; case '!': strcpy (buf, "\"CC!"); break; default: cmd = r_str_newf ("\"CC %s\"", arg); break; } free (arg); } if (cmd) { r_core_cmd (core, cmd, 1); } if (core->print->cur_enabled) { r_core_seek (core, orig, true); } free (cmd); } __set_refresh_by_type (core, p->model->cmd, true); } static bool __move_to_direction(RCore *core, Direction direction) { RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); int cur_x0 = cur->view->pos.x, cur_x1 = cur->view->pos.x + cur->view->pos.w - 1, cur_y0 = cur->view->pos.y, cur_y1 = cur->view->pos.y + cur->view->pos.h - 1; int temp_x0, temp_x1, temp_y0, temp_y1; int i; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); temp_x0 = p->view->pos.x; temp_x1 = p->view->pos.x + p->view->pos.w - 1; temp_y0 = p->view->pos.y; temp_y1 = p->view->pos.y + p->view->pos.h - 1; switch (direction) { case LEFT: if (temp_x1 == cur_x0) { if (temp_y1 <= cur_y0 || cur_y1 <= temp_y0) { continue; } __set_curnode (core, i); return true; } break; case RIGHT: if (temp_x0 == cur_x1) { if (temp_y1 <= cur_y0 || cur_y1 <= temp_y0) { continue; } __set_curnode (core, i); return true; } break; case UP: if (temp_y1 == cur_y0) { if (temp_x1 <= cur_x0 || cur_x1 <= temp_x0) { continue; } __set_curnode (core, i); return true; } break; case DOWN: if (temp_y0 == cur_y1) { if (temp_x1 <= cur_x0 || cur_x1 <= temp_x0) { continue; } __set_curnode (core, i); return true; } break; default: break; } } return false; } static void __direction_default_cb(void *user, int direction) { RCore *core = (RCore *)user; RPanel *cur = __get_cur_panel (core->panels); cur->view->refresh = true; switch ((Direction)direction) { case LEFT: if (cur->view->sx > 0) { cur->view->sx--; } break; case RIGHT: cur->view->sx++; break; case UP: if (cur->view->sy > 0) { cur->view->sy--; } break; case DOWN: cur->view->sy++; break; } } static void __direction_disassembly_cb(void *user, int direction) { RCore *core = (RCore *)user; RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); int cols = core->print->cols; cur->view->refresh = true; switch ((Direction)direction) { case LEFT: if (core->print->cur_enabled) { __cursor_left (core); r_core_block_read (core); __set_panel_addr (core, cur, core->offset); } else if (panels->mode == PANEL_MODE_ZOOM) { cur->model->addr--; } else if (cur->view->sx > 0) { cur->view->sx--; } break; case RIGHT: if (core->print->cur_enabled) { __cursor_right (core); r_core_block_read (core); __set_panel_addr (core, cur, core->offset); } else if (panels->mode == PANEL_MODE_ZOOM) { cur->model->addr++; } else { cur->view->sx++; } break; case UP: core->offset = cur->model->addr; if (core->print->cur_enabled) { __cursor_up (core); r_core_block_read (core); __set_panel_addr (core, cur, core->offset); } else { r_core_visual_disasm_up (core, &cols); r_core_seek_delta (core, -cols); __set_panel_addr (core, cur, core->offset); } break; case DOWN: core->offset = cur->model->addr; if (core->print->cur_enabled) { __cursor_down (core); r_core_block_read (core); __set_panel_addr (core, cur, core->offset); } else { RAsmOp op; r_core_visual_disasm_down (core, &op, &cols); r_core_seek (core, core->offset + cols, true); __set_panel_addr (core, cur, core->offset); } break; } } static void __direction_graph_cb(void *user, int direction) { RCore *core = (RCore *)user; RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); cur->view->refresh = true; const int speed = r_config_get_i (core->config, "graph.scroll") * 2; switch ((Direction)direction) { case LEFT: if (cur->view->sx > 0) { cur->view->sx -= speed; } break; case RIGHT: cur->view->sx += speed; break; case UP: if (cur->view->sy > 0) { cur->view->sy -= speed; } break; case DOWN: cur->view->sy += speed; break; } } static void __direction_register_cb(void *user, int direction) { RCore *core = (RCore *)user; RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); int cols = core->dbg->regcols; cols = cols > 0 ? cols : 3; cur->view->refresh = true; switch ((Direction)direction) { case LEFT: if (core->print->cur_enabled) { __cursor_left (core); } else if (cur->view->sx > 0) { cur->view->sx--; cur->view->refresh = true; } break; case RIGHT: if (core->print->cur_enabled) { __cursor_right (core); } else { cur->view->sx++; cur->view->refresh = true; } break; case UP: if (core->print->cur_enabled) { int tmp = core->print->cur; tmp -= cols; if (tmp >= 0) { core->print->cur = tmp; } } break; case DOWN: if (core->print->cur_enabled) { core->print->cur += cols; } break; } } static void __direction_stack_cb(void *user, int direction) { RCore *core = (RCore *)user; RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); int cols = r_config_get_i (core->config, "hex.cols"); if (cols < 1) { cols = 16; } cur->view->refresh = true; switch ((Direction)direction) { case LEFT: if (core->print->cur_enabled) { __cursor_left (core); } else if (cur->view->sx > 0) { cur->view->sx--; cur->view->refresh = true; } break; case RIGHT: if (core->print->cur_enabled) { __cursor_right (core); } else { cur->view->sx++; cur->view->refresh = true; } break; case UP: r_config_set_i (core->config, "stack.delta", r_config_get_i (core->config, "stack.delta") + cols); cur->model->addr -= cols; break; case DOWN: r_config_set_i (core->config, "stack.delta", r_config_get_i (core->config, "stack.delta") - cols); cur->model->addr += cols; break; } } static void __direction_hexdump_cb(void *user, int direction) { RCore *core = (RCore *)user; RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); int cols = r_config_get_i (core->config, "hex.cols"); if (cols < 1) { cols = 16; } cur->view->refresh = true; switch ((Direction)direction) { case LEFT: if (!core->print->cur) { cur->model->addr -= cols; core->print->cur += cols - 1; } else if (core->print->cur_enabled) { __cursor_left (core); } else { cur->model->addr--; } break; case RIGHT: if (core->print->cur / cols + 1 > cur->view->pos.h - 5 && core->print->cur % cols == cols - 1) { cur->model->addr += cols; core->print->cur -= cols - 1; } else if (core->print->cur_enabled) { __cursor_right (core); } else { cur->model->addr++; } break; case UP: if (!cur->model->cache) { if (core->print->cur_enabled) { if (!(core->print->cur / cols)) { cur->model->addr -= cols; } else { core->print->cur -= cols; } } else { if (cur->model->addr <= cols) { __set_panel_addr (core, cur, 0); } else { cur->model->addr -= cols; } } } else if (cur->view->sy > 0) { cur->view->sy--; } break; case DOWN: if (!cur->model->cache) { if (core->print->cur_enabled) { if (core->print->cur / cols + 1 > cur->view->pos.h - 5) { cur->model->addr += cols; } else { core->print->cur += cols; } } else { cur->model->addr += cols; } } else { cur->view->sy++; } break; } } static void __direction_panels_cursor_cb(void *user, int direction) { RCore *core = (RCore *)user; RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); cur->view->refresh = true; const int THRESHOLD = cur->view->pos.h / 3; int sub; switch ((Direction)direction) { case LEFT: if (!core->print->cur_enabled) { break; } if (cur->view->sx > 0) { cur->view->sx -= r_config_get_i (core->config, "graph.scroll"); } break; case RIGHT: if (core->print->cur_enabled) { break; } cur->view->sx += r_config_get_i (core->config, "graph.scroll"); break; case UP: if (core->print->cur_enabled) { if (cur->view->curpos > 0) { cur->view->curpos--; } if (cur->view->sy > 0) { sub = cur->view->curpos - cur->view->sy; if (sub < 0) { cur->view->sy--; } } } else { if (cur->view->sy > 0) { cur->view->curpos -= 1; cur->view->sy -= 1; } } break; case DOWN: core->offset = cur->model->addr; if (core->print->cur_enabled) { cur->view->curpos++; sub = cur->view->curpos - cur->view->sy; if (sub > THRESHOLD) { cur->view->sy++; } } else { cur->view->curpos += 1; cur->view->sy += 1; } break; } } static void __toggle_window_mode(RCore *core) { RPanels *panels = core->panels; if (panels->mode != PANEL_MODE_WINDOW) { panels->prevMode = panels->mode; __set_mode (core, PANEL_MODE_WINDOW); } else { __set_mode (core, panels->prevMode); panels->prevMode = PANEL_MODE_DEFAULT; } } static void __resize_panel_left(RPanels *panels) { RPanel *cur = __get_cur_panel (panels); int i, cx0, cx1, cy0, cy1, tx0, tx1, ty0, ty1, cur1 = 0, cur2 = 0, cur3 = 0, cur4 = 0; cx0 = cur->view->pos.x; cx1 = cur->view->pos.x + cur->view->pos.w - 1; cy0 = cur->view->pos.y; cy1 = cur->view->pos.y + cur->view->pos.h - 1; RPanel **targets1 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets2 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets3 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets4 = malloc (sizeof (RPanel *) * panels->n_panels); if (!targets1 || !targets2 || !targets3 || !targets4) { goto beach; } for (i = 0; i < panels->n_panels; i++) { if (i == panels->curnode) { continue; } RPanel *p = __get_panel (panels, i); tx0 = p->view->pos.x; tx1 = p->view->pos.x + p->view->pos.w - 1; ty0 = p->view->pos.y; ty1 = p->view->pos.y + p->view->pos.h - 1; if (ty0 == cy0 && ty1 == cy1 && tx1 == cx0 && tx1 - PANEL_CONFIG_RESIZE_W > tx0) { p->view->pos.w -= PANEL_CONFIG_RESIZE_W; cur->view->pos.x -= PANEL_CONFIG_RESIZE_W; cur->view->pos.w += PANEL_CONFIG_RESIZE_W; p->view->refresh = true; cur->view->refresh = true; goto beach; } bool y_included = (ty1 >= cy0 && cy1 >= ty1) || (ty0 >= cy0 && cy1 >= ty0); if (tx1 == cx0 && y_included) { if (tx1 - PANEL_CONFIG_RESIZE_W > tx0) { targets1[cur1++] = p; } } if (tx0 == cx1 && y_included) { if (tx0 - PANEL_CONFIG_RESIZE_W > cx0) { targets3[cur3++] = p; } } if (tx0 == cx0) { if (tx0 - PANEL_CONFIG_RESIZE_W > 0) { targets2[cur2++] = p; } } if (tx1 == cx1) { if (tx1 + PANEL_CONFIG_RESIZE_W < panels->can->w) { targets4[cur4++] = p; } } } if (cur1 > 0) { for (i = 0; i < cur1; i++) { targets1[i]->view->pos.w -= PANEL_CONFIG_RESIZE_W; targets1[i]->view->refresh = true; } for (i = 0; i < cur2; i++) { targets2[i]->view->pos.x -= PANEL_CONFIG_RESIZE_W; targets2[i]->view->pos.w += PANEL_CONFIG_RESIZE_W; targets2[i]->view->refresh = true; } cur->view->pos.x -= PANEL_CONFIG_RESIZE_W; cur->view->pos.w += PANEL_CONFIG_RESIZE_W; cur->view->refresh = true; } else if (cur3 > 0) { for (i = 0; i < cur3; i++) { targets3[i]->view->pos.w += PANEL_CONFIG_RESIZE_W; targets3[i]->view->pos.x -= PANEL_CONFIG_RESIZE_W; targets3[i]->view->refresh = true; } for (i = 0; i < cur4; i++) { targets4[i]->view->pos.w -= PANEL_CONFIG_RESIZE_W; targets4[i]->view->refresh = true; } cur->view->pos.w -= PANEL_CONFIG_RESIZE_W; cur->view->refresh = true; } beach: free (targets1); free (targets2); free (targets3); free (targets4); } static void __resize_panel_right(RPanels *panels) { RPanel *cur = __get_cur_panel (panels); int i, tx0, tx1, ty0, ty1, cur1 = 0, cur2 = 0, cur3 = 0, cur4 = 0; int cx0 = cur->view->pos.x; int cx1 = cur->view->pos.x + cur->view->pos.w - 1; int cy0 = cur->view->pos.y; int cy1 = cur->view->pos.y + cur->view->pos.h - 1; RPanel **targets1 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets2 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets3 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets4 = malloc (sizeof (RPanel *) * panels->n_panels); if (!targets1 || !targets2 || !targets3 || !targets4) { goto beach; } for (i = 0; i < panels->n_panels; i++) { if (i == panels->curnode) { continue; } RPanel *p = __get_panel (panels, i); tx0 = p->view->pos.x; tx1 = p->view->pos.x + p->view->pos.w - 1; ty0 = p->view->pos.y; ty1 = p->view->pos.y + p->view->pos.h - 1; if (ty0 == cy0 && ty1 == cy1 && tx0 == cx1 && tx0 + PANEL_CONFIG_RESIZE_W < tx1) { p->view->pos.x += PANEL_CONFIG_RESIZE_W; p->view->pos.w -= PANEL_CONFIG_RESIZE_W; cur->view->pos.w += PANEL_CONFIG_RESIZE_W; p->view->refresh = true; cur->view->refresh = true; goto beach; } bool y_included = (ty1 >= cy0 && cy1 >= ty1) || (ty0 >= cy0 && cy1 >= ty0); if (tx1 == cx0 && y_included) { if (tx1 + PANEL_CONFIG_RESIZE_W < cx1) { targets1[cur1++] = p; } } if (tx0 == cx1 && y_included) { if (tx0 + PANEL_CONFIG_RESIZE_W < tx1) { targets3[cur3++] = p; } } if (tx0 == cx0) { if (tx0 + PANEL_CONFIG_RESIZE_W < tx1) { targets2[cur2++] = p; } } if (tx1 == cx1) { if (tx1 + PANEL_CONFIG_RESIZE_W < panels->can->w) { targets4[cur4++] = p; } } } if (cur3 > 0) { for (i = 0; i < cur3; i++) { targets3[i]->view->pos.x += PANEL_CONFIG_RESIZE_W; targets3[i]->view->pos.w -= PANEL_CONFIG_RESIZE_W; targets3[i]->view->refresh = true; } for (i = 0; i < cur4; i++) { targets4[i]->view->pos.w += PANEL_CONFIG_RESIZE_W; targets4[i]->view->refresh = true; } cur->view->pos.w += PANEL_CONFIG_RESIZE_W; cur->view->refresh = true; } else if (cur1 > 0) { for (i = 0; i < cur1; i++) { targets1[i]->view->pos.w += PANEL_CONFIG_RESIZE_W; targets1[i]->view->refresh = true; } for (i = 0; i < cur2; i++) { targets2[i]->view->pos.x += PANEL_CONFIG_RESIZE_W; targets2[i]->view->pos.w -= PANEL_CONFIG_RESIZE_W; targets2[i]->view->refresh = true; } cur->view->pos.x += PANEL_CONFIG_RESIZE_W; cur->view->pos.w -= PANEL_CONFIG_RESIZE_W; cur->view->refresh = true; } beach: free (targets1); free (targets2); free (targets3); free (targets4); } static void __resize_panel_up(RPanels *panels) { RPanel *cur = __get_cur_panel (panels); int i, tx0, tx1, ty0, ty1, cur1 = 0, cur2 = 0, cur3 = 0, cur4 = 0; int cx0 = cur->view->pos.x; int cx1 = cur->view->pos.x + cur->view->pos.w - 1; int cy0 = cur->view->pos.y; int cy1 = cur->view->pos.y + cur->view->pos.h - 1; RPanel **targets1 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets2 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets3 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets4 = malloc (sizeof (RPanel *) * panels->n_panels); if (!targets1 || !targets2 || !targets3 || !targets4) { goto beach; } for (i = 0; i < panels->n_panels; i++) { if (i == panels->curnode) { continue; } RPanel *p = __get_panel (panels, i); tx0 = p->view->pos.x; tx1 = p->view->pos.x + p->view->pos.w - 1; ty0 = p->view->pos.y; ty1 = p->view->pos.y + p->view->pos.h - 1; if (tx0 == cx0 && tx1 == cx1 && ty1 == cy0 && ty1 - PANEL_CONFIG_RESIZE_H > ty0) { p->view->pos.h -= PANEL_CONFIG_RESIZE_H; cur->view->pos.y -= PANEL_CONFIG_RESIZE_H; cur->view->pos.h += PANEL_CONFIG_RESIZE_H; p->view->refresh = true; cur->view->refresh = true; goto beach; } bool x_included = (tx1 >= cx0 && cx1 >= tx1) || (tx0 >= cx0 && cx1 >= tx0); if (ty1 == cy0 && x_included) { if (ty1 - PANEL_CONFIG_RESIZE_H > ty0) { targets1[cur1++] = p; } } if (ty0 == cy1 && x_included) { if (ty0 - PANEL_CONFIG_RESIZE_H > cy0) { targets3[cur3++] = p; } } if (ty0 == cy0) { if (ty0 - PANEL_CONFIG_RESIZE_H > 0) { targets2[cur2++] = p; } } if (ty1 == cy1) { if (ty1 - PANEL_CONFIG_RESIZE_H > ty0) { targets4[cur4++] = p; } } } if (cur1 > 0) { for (i = 0; i < cur1; i++) { targets1[i]->view->pos.h -= PANEL_CONFIG_RESIZE_H; targets1[i]->view->refresh = true; } for (i = 0; i < cur2; i++) { targets2[i]->view->pos.y -= PANEL_CONFIG_RESIZE_H; targets2[i]->view->pos.h += PANEL_CONFIG_RESIZE_H; targets2[i]->view->refresh = true; } cur->view->pos.y -= PANEL_CONFIG_RESIZE_H; cur->view->pos.h += PANEL_CONFIG_RESIZE_H; cur->view->refresh = true; } else if (cur3 > 0) { for (i = 0; i < cur3; i++) { targets3[i]->view->pos.h += PANEL_CONFIG_RESIZE_H; targets3[i]->view->pos.y -= PANEL_CONFIG_RESIZE_H; targets3[i]->view->refresh = true; } for (i = 0; i < cur4; i++) { targets4[i]->view->pos.h -= PANEL_CONFIG_RESIZE_H; targets4[i]->view->refresh = true; } cur->view->pos.h -= PANEL_CONFIG_RESIZE_H; cur->view->refresh = true; } beach: free (targets1); free (targets2); free (targets3); free (targets4); } static void __resize_panel_down(RPanels *panels) { RPanel *cur = __get_cur_panel (panels); int i, tx0, tx1, ty0, ty1, cur1 = 0, cur2 = 0, cur3 = 0, cur4 = 0; int cx0 = cur->view->pos.x; int cx1 = cur->view->pos.x + cur->view->pos.w - 1; int cy0 = cur->view->pos.y; int cy1 = cur->view->pos.y + cur->view->pos.h - 1; RPanel **targets1 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets2 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets3 = malloc (sizeof (RPanel *) * panels->n_panels); RPanel **targets4 = malloc (sizeof (RPanel *) * panels->n_panels); if (!targets1 || !targets2 || !targets3 || !targets4) { goto beach; } for (i = 0; i < panels->n_panels; i++) { if (i == panels->curnode) { continue; } RPanel *p = __get_panel (panels, i); tx0 = p->view->pos.x; tx1 = p->view->pos.x + p->view->pos.w - 1; ty0 = p->view->pos.y; ty1 = p->view->pos.y + p->view->pos.h - 1; if (tx0 == cx0 && tx1 == cx1 && ty0 == cy1 && ty0 + PANEL_CONFIG_RESIZE_H < ty1) { p->view->pos.y += PANEL_CONFIG_RESIZE_H; p->view->pos.h -= PANEL_CONFIG_RESIZE_H; cur->view->pos.h += PANEL_CONFIG_RESIZE_H; p->view->refresh = true; cur->view->refresh = true; goto beach; } bool x_included = (tx1 >= cx0 && cx1 >= tx1) || (tx0 >= cx0 && cx1 >= tx0); if (ty1 == cy0 && x_included) { if (ty1 + PANEL_CONFIG_RESIZE_H < cy1) { targets1[cur1++] = p; } } if (ty0 == cy1 && x_included) { if (ty0 + PANEL_CONFIG_RESIZE_H < ty1) { targets3[cur3++] = p; } } if (ty0 == cy0) { if (ty0 + PANEL_CONFIG_RESIZE_H < ty1) { targets2[cur2++] = p; } } if (ty1 == cy1) { if (ty1 + PANEL_CONFIG_RESIZE_H < panels->can->h) { targets4[cur4++] = p; } } } if (cur3 > 0) { for (i = 0; i < cur3; i++) { targets3[i]->view->pos.h -= PANEL_CONFIG_RESIZE_H; targets3[i]->view->pos.y += PANEL_CONFIG_RESIZE_H; targets3[i]->view->refresh = true; } for (i = 0; i < cur4; i++) { targets4[i]->view->pos.h += PANEL_CONFIG_RESIZE_H; targets4[i]->view->refresh = true; } cur->view->pos.h += PANEL_CONFIG_RESIZE_H; cur->view->refresh = true; } else if (cur1 > 0) { for (i = 0; i < cur1; i++) { targets1[i]->view->pos.h += PANEL_CONFIG_RESIZE_H; targets1[i]->view->refresh = true; } for (i = 0; i < cur2; i++) { targets2[i]->view->pos.y += PANEL_CONFIG_RESIZE_H; targets2[i]->view->pos.h -= PANEL_CONFIG_RESIZE_H; targets2[i]->view->refresh = true; } cur->view->pos.y += PANEL_CONFIG_RESIZE_H; cur->view->pos.h -= PANEL_CONFIG_RESIZE_H; cur->view->refresh = true; } beach: free (targets1); free (targets2); free (targets3); free (targets4); } static bool __handle_window_mode(RCore *core, const int key) { RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); r_cons_switchbuf (false); switch (key) { case 'Q': case 'q': case 'w': __toggle_window_mode (core); break; case 0x0d: __toggle_zoom_mode (core); break; case 9: // tab __handle_tab_key (core, false); break; case 'Z': // shift-tab __handle_tab_key (core, true); break; case 'e': { char *cmd = __show_status_input (core, "New command: "); if (R_STR_ISNOTEMPTY (cmd)) { __replace_cmd (core, cmd, cmd); } free (cmd); } break; case 'h': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.x--; } else { (void)__move_to_direction (core, LEFT); if (panels->fun == PANEL_FUN_SNOW || panels->fun == PANEL_FUN_SAKURA) { __reset_snow (panels); } } break; case 'j': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y++; } else { (void)__move_to_direction (core, DOWN); if (panels->fun == PANEL_FUN_SNOW || panels->fun == PANEL_FUN_SAKURA) { __reset_snow (panels); } } break; case 'k': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y--; } else { (void)__move_to_direction (core, UP); if (panels->fun == PANEL_FUN_SNOW || panels->fun == PANEL_FUN_SAKURA) { __reset_snow (panels); } } break; case 'l': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.x++; } else { (void)__move_to_direction (core, RIGHT); if (panels->fun == PANEL_FUN_SNOW || panels->fun == PANEL_FUN_SAKURA) { __reset_snow (panels); } } break; case 'H': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.x += 5; } else { r_cons_switchbuf (false); __resize_panel_left (panels); } break; case 'L': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.x += 5; } else { r_cons_switchbuf (false); __resize_panel_right (panels); } break; case 'J': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y += 5; } else { r_cons_switchbuf (false); __resize_panel_down (panels); } break; case 'K': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y -= 5; } else { r_cons_switchbuf (false); __resize_panel_up (panels); } break; case 'n': __create_panel_input (core, cur, PANEL_LAYOUT_VERTICAL, NULL); break; case 'N': __create_panel_input (core, cur, PANEL_LAYOUT_HORIZONTAL, NULL); break; case 'X': __dismantle_del_panel (core, cur, panels->curnode); break; case '"': case ':': case ';': case '/': case 'd': case 'b': case 'p': case 'P': case 't': case 'T': case '?': case '|': case '-': return false; } return true; } static void __jmp_to_cursor_addr(RCore *core, RPanel *panel) { ut64 addr = __parse_string_on_cursor (core, panel, panel->view->curpos); if (addr == UT64_MAX) { return; } core->offset = addr; __update_disassembly_or_open (core); } static void __set_breakpoints_on_cursor(RCore *core, RPanel *panel) { if (!r_config_get_i (core->config, "cfg.debug")) { return; } if (__check_panel_type (panel, PANEL_CMD_DISASSEMBLY)) { r_core_cmdf (core, "dbs 0x%08"PFMT64x, core->offset + core->print->cur); panel->view->refresh = true; } } static void __insert_value(RCore *core) { if (!r_config_get_i (core->config, "io.cache")) { if (__show_status_yesno (core, 1, "Insert is not available because io.cache is off. Turn on now?(Y/n)")) { r_config_set_i (core->config, "io.cache", 1); (void)__show_status (core, "io.cache is on and insert is available now."); } else { (void)__show_status (core, "You can always turn on io.cache in Menu->Edit->io.cache"); return; } } RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); char buf[128]; if (__check_panel_type (cur, PANEL_CMD_STACK)) { const char *prompt = "insert hex: "; __panel_prompt (prompt, buf, sizeof (buf)); r_core_cmdf (core, "wx %s @ 0x%08" PFMT64x, buf, cur->model->addr); cur->view->refresh = true; } else if (__check_panel_type (cur, PANEL_CMD_REGISTERS)) { const char *creg = core->dbg->creg; if (creg) { const char *prompt = "new-reg-value> "; __panel_prompt (prompt, buf, sizeof (buf)); r_core_cmdf (core, "dr %s = %s", creg, buf); cur->view->refresh = true; } } else if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { const char *prompt = "insert hex: "; __panel_prompt (prompt, buf, sizeof (buf)); r_core_cmdf (core, "wx %s @ 0x%08" PFMT64x, buf, core->offset + core->print->cur); cur->view->refresh = true; } else if (__check_panel_type (cur, PANEL_CMD_HEXDUMP)) { const char *prompt = "insert hex: "; __panel_prompt (prompt, buf, sizeof (buf)); r_core_cmdf (core, "wx %s @ 0x%08" PFMT64x, buf, cur->model->addr + core->print->cur); cur->view->refresh = true; } } static void __cursor_del_breakpoints(RCore *core, RPanel *panel) { RListIter *iter; RBreakpointItem *b; int i = 0; r_list_foreach (core->dbg->bp->bps, iter, b) { if (panel->view->curpos == i++) { r_bp_del (core->dbg->bp, b->addr); } } } static void __set_addr_by_type(RCore *core, const char *cmd, ut64 addr) { RPanels *panels = core->panels; int i; for (i = 0; i < panels->n_panels; i++) { RPanel *p = __get_panel (panels, i); if (!__check_panel_type (p, cmd)) { continue; } __set_panel_addr (core, p, addr); } } static void __handle_refs(RCore *core, RPanel *panel, ut64 tmp) { if (tmp != UT64_MAX) { core->offset = tmp; } int key = __show_status(core, "xrefs:x refs:X "); switch (key) { case 'x': (void)r_core_visual_refs (core, true, false); break; case 'X': (void)r_core_visual_refs (core, false, false); break; default: break; } if (__check_panel_type (panel, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, panel, core->offset); } else { __set_addr_by_type (core, PANEL_CMD_DISASSEMBLY, core->offset); } } static bool __handle_cursor_mode(RCore *core, const int key) { RPanel *cur = __get_cur_panel (core->panels); RPrint *print = core->print; char *db_val; switch (key) { case ':': case ';': case 'd': case 'h': case 'j': case 'k': case 'J': case 'K': case 'l': case 'm': case 'Z': case '"': case 9: return false; case 'g': cur->view->curpos = 0; __reset_scroll_pos (cur); cur->view->refresh = true; break; case ']': if (__check_panel_type (cur, PANEL_CMD_HEXDUMP)) { r_config_set_i (core->config, "hex.cols", r_config_get_i (core->config, "hex.cols") + 1); } else { int cmtcol = r_config_get_i (core->config, "asm.cmt.col"); r_config_set_i (core->config, "asm.cmt.col", cmtcol + 2); } cur->view->refresh = true; break; case '[': if (__check_panel_type (cur, PANEL_CMD_HEXDUMP)) { r_config_set_i (core->config, "hex.cols", r_config_get_i (core->config, "hex.cols") - 1); } else { int cmtcol = r_config_get_i (core->config, "asm.cmt.col"); if (cmtcol > 2) { r_config_set_i (core->config, "asm.cmt.col", cmtcol - 2); } } cur->view->refresh = true; break; case 'Q': case 'q': case 'c': __set_cursor (core, !print->cur_enabled); cur->view->refresh = true; break; case 'w': __toggle_window_mode (core); __set_cursor (core, false); cur->view->refresh = true; break; case 'i': __insert_value (core); break; case '*': if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { r_core_cmdf (core, "dr PC=0x%08"PFMT64x, core->offset + print->cur); __set_panel_addr (core, cur, core->offset + print->cur); } break; case '-': db_val = __search_db (core, "Breakpoints"); if (__check_panel_type (cur, db_val)) { __cursor_del_breakpoints(core, cur); free (db_val); break; } free (db_val); return false; case 'x': __handle_refs (core, cur, __parse_string_on_cursor (core, cur, cur->view->curpos)); break; case 0x0d: __jmp_to_cursor_addr (core, cur); break; case 'b': __set_breakpoints_on_cursor (core, cur); break; case 'H': cur->view->curpos = cur->view->sy; cur->view->refresh = true; break; } return true; } static bool __drag_and_resize(RCore *core) { RPanels *panels = core->panels; if (panels->mouse_on_edge_x || panels->mouse_on_edge_y) { int x, y; if (r_cons_get_click (&x, &y)) { if (panels->mouse_on_edge_x) { __update_edge_x (core, x - panels->mouse_orig_x); } if (panels->mouse_on_edge_y) { __update_edge_y (core, y - panels->mouse_orig_y); } } panels->mouse_on_edge_x = false; panels->mouse_on_edge_y = false; return true; } return false; } static char *__get_word_from_canvas(RCore *core, RPanels *panels, int x, int y) { RStrBuf rsb; r_strbuf_init (&rsb); char *cs = r_cons_canvas_to_string (panels->can); r_strbuf_setf (&rsb, " %s", cs); char *R = r_str_ansi_crop (r_strbuf_get (&rsb), 0, y - 1, x + 1024, y); r_str_ansi_filter (R, NULL, NULL, -1); char *r = r_str_ansi_crop (r_strbuf_get (&rsb), x - 1, y - 1, x + 1024, y); r_str_ansi_filter (r, NULL, NULL, -1); char *pos = strstr (R, r); if (!pos) { pos = R; } #define TOkENs ":=*+-/()[,] " const char *sp = r_str_rsep (R, pos, TOkENs); if (sp) { sp++; } else { sp = pos; } char *sp2 = (char *)r_str_sep (sp, TOkENs); if (sp2) { *sp2 = 0; } char *res = strdup (sp); free (r); free (R); free (cs); r_strbuf_fini (&rsb); return res; } static char *__get_word_from_canvas_for_menu(RCore *core, RPanels *panels, int x, int y) { char *cs = r_cons_canvas_to_string (panels->can); char *R = r_str_ansi_crop (cs, 0, y - 1, x + 1024, y); r_str_ansi_filter (R, NULL, NULL, -1); char *r = r_str_ansi_crop (cs, x - 1, y - 1, x + 1024, y); r_str_ansi_filter (r, NULL, NULL, -1); char *pos = strstr (R, r); char *tmp = pos; const char *padding = " "; if (!pos) { pos = R; } int i = 0; while (pos > R && strncmp (padding, pos, strlen (padding))) { pos--; i++; } while (R_STR_ISNOTEMPTY (tmp) && strncmp (padding, tmp, strlen (padding))) { tmp++; i++; } char *ret = r_str_newlen (pos += strlen (padding), i - strlen (padding)); if (!ret) { ret = strdup (pos); } free (r); free (R); free (cs); return ret; } static void __handle_tab_nth(RCore *core, int ch) { ch -= '0' + 1; if (ch < 0) { return; } if (ch != core->panels_root->cur_panels && ch < core->panels_root->n_panels) { core->panels_root->cur_panels = ch; __set_root_state (core, ROTATE); } } static void __clear_panels_menuRec(RPanelsMenuItem *pmi) { size_t i = 0; for (i = 0; i < pmi->n_sub; i++) { RPanelsMenuItem *sub = pmi->sub[i]; if (sub) { sub->selectedIndex = 0; __clear_panels_menuRec (sub); } } } static void __clear_panels_menu(RCore *core) { RPanels *p = core->panels; RPanelsMenu *pm = p->panels_menu; __clear_panels_menuRec (pm->root); pm->root->selectedIndex = 0; pm->history[0] = pm->root; pm->depth = 1; pm->n_refresh = 0; } static bool __handle_mouse_on_top(RCore *core, int x, int y) { RPanels *panels = core->panels; char *word = __get_word_from_canvas (core, panels, x, y); int i; for (i = 0; i < COUNT (menus); i++) { if (!strcmp (word, menus[i])) { __set_mode (core, PANEL_MODE_MENU); __clear_panels_menu (core); RPanelsMenu *menu = panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; parent->selectedIndex = i; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; (void)(child->cb (core)); free (word); return true; } } if (!strcmp (word, "Tab")) { __handle_tab_new (core); free (word); return true; } if (word[0] == '[' && word[1] && word[2] == ']') { return true; } if (atoi (word)) { __handle_tab_nth (core, word[0]); return true; } return false; } static void __del_menu(RCore *core) { RPanels *panels = core->panels; RPanelsMenu *menu = panels->panels_menu; int i; menu->depth--; for (i = 1; i < menu->depth; i++) { menu->history[i]->p->view->refresh = true; menu->refreshPanels[i - 1] = menu->history[i]->p; } menu->n_refresh = menu->depth - 1; } static RStrBuf *__draw_menu(RCore *core, RPanelsMenuItem *item) { RStrBuf *buf = r_strbuf_new (NULL); if (!buf) { return NULL; } size_t i; for (i = 0; i < item->n_sub; i++) { if (i == item->selectedIndex) { r_strbuf_appendf (buf, "%s> %s"Color_RESET, core->cons->context->pal.graph_box2, item->sub[i]->name); } else { r_strbuf_appendf (buf, " %s", item->sub[i]->name); } r_strbuf_append (buf, " \n"); } return buf; } static void __update_menu_contents(RCore *core, RPanelsMenu *menu, RPanelsMenuItem *parent) { RPanel *p = parent->p; RStrBuf *buf = __draw_menu (core, parent); if (!buf) { return; } free (p->model->title); p->model->title = r_strbuf_drain (buf); int new_w = r_str_bounds (p->model->title, &p->view->pos.h); p->view->pos.w = new_w; p->view->pos.h += 4; p->model->type = PANEL_TYPE_MENU; p->view->refresh = true; menu->refreshPanels[menu->n_refresh - 1] = p; } static void __handle_mouse_on_menu(RCore *core, int x, int y) { RPanels *panels = core->panels; char *word = __get_word_from_canvas_for_menu (core, panels, x, y); RPanelsMenu *menu = panels->panels_menu; int i, d = menu->depth - 1; while (d) { RPanelsMenuItem *parent = menu->history[d--]; for (i = 0; i < parent->n_sub; i++) { if (!strcmp (word, parent->sub[i]->name)) { parent->selectedIndex = i; (void)(parent->sub[parent->selectedIndex]->cb (core)); __update_menu_contents (core, menu, parent); free (word); return; } } __del_menu (core); } __clear_panels_menu (core); __set_mode (core, PANEL_MODE_DEFAULT); __get_cur_panel (panels)->view->refresh = true; free (word); } static void __toggle_cache(RCore *core, RPanel *p) { p->model->cache = !p->model->cache; __set_cmd_str_cache (core, p, NULL); p->view->refresh = true; } static bool __draw_modal(RCore *core, RModal *modal, int range_end, int start, const char *name) { if (start < modal->offset) { return true; } if (start >= range_end) { return false; } if (start == modal->idx) { r_strbuf_appendf (modal->data, "> %s%s"Color_RESET, core->cons->context->pal.graph_box2, name); } else { r_strbuf_appendf (modal->data, " %s", name); } r_strbuf_append (modal->data, " \n"); return true; } static void __update_modal(RCore *core, Sdb *menu_db, RModal *modal) { RPanels *panels = core->panels; RConsCanvas *can = panels->can; modal->data = r_strbuf_new (NULL); int count = sdb_count (menu_db); if (modal->idx >= count) { modal->idx = 0; modal->offset = 0; } else if (modal->idx >= modal->offset + modal->pos.h) { if (modal->offset + modal->pos.h >= count) { modal->offset = 0; modal->idx = 0; } else { modal->offset += 1; } } else if (modal->idx < 0) { modal->offset = R_MAX (count - modal->pos.h, 0); modal->idx = count - 1; } else if (modal->idx < modal->offset) { modal->offset -= 1; } SdbList *l = sdb_foreach_list (menu_db, true); SdbKv *kv; SdbListIter *iter; int i = 0; int max_h = R_MIN (modal->offset + modal->pos.h, count); ls_foreach (l, iter, kv) { if (__draw_modal (core, modal, max_h, i, sdbkv_key (kv))) { i++; } } r_cons_gotoxy (0, 0); r_cons_canvas_fill (can, modal->pos.x, modal->pos.y, modal->pos.w + 2, modal->pos.h + 2, ' '); (void)r_cons_canvas_gotoxy (can, modal->pos.x + 2, modal->pos.y + 1); r_cons_canvas_write (can, r_strbuf_get (modal->data)); r_strbuf_free (modal->data); r_cons_canvas_box (can, modal->pos.x, modal->pos.y, modal->pos.w + 2, modal->pos.h + 2, core->cons->context->pal.graph_box2); r_cons_canvas_print (can); r_cons_flush (); show_cursor (core); } static void __exec_modal(RCore *core, RPanel *panel, RModal *modal, Sdb *menu_db, RPanelLayout dir) { SdbList *l = sdb_foreach_list (menu_db, true); SdbKv *kv; SdbListIter *iter; int i = 0; ls_foreach (l, iter, kv) { if (i++ == modal->idx) { RPanelAlmightyCallback cb = sdb_ptr_get (menu_db, sdbkv_key (kv), 0); cb (core, panel, dir, sdbkv_key (kv)); break; } } } static void __delete_modal(RCore *core, RModal *modal, Sdb *menu_db) { SdbList *l = sdb_foreach_list (menu_db, true); SdbKv *kv; SdbListIter *iter; int i = 0; ls_foreach (l, iter, kv) { if (i++ == modal->idx) { sdb_remove (menu_db, sdbkv_key (kv), 0); } } } static RModal *__init_modal(void) { RModal *modal = R_NEW0 (RModal); if (modal) { __set_pos (&modal->pos, 0, 0); modal->idx = 0; modal->offset = 0; } return modal; } static void __free_modal(RModal **modal) { free (*modal); *modal = NULL; } static void __create_modal(RCore *core, RPanel *panel, Sdb *menu_db) { __set_cursor (core, false); const int w = 40; const int h = 20; const int x = (core->panels->can->w - w) / 2; const int y = (core->panels->can->h - h) / 2; RModal *modal = __init_modal (); __set_geometry (&modal->pos, x, y, w, h); int okey, key, cx, cy; char *word = NULL; __update_modal (core, menu_db, modal); while (modal) { okey = r_cons_readchar (); key = r_cons_arrow_to_hjkl (okey); word = NULL; if (key == INT8_MAX - 1) { if (r_cons_get_click (&cx, &cy)) { if ((cx < x || x + w < cx) || ((cy < y || y + h < cy))) { key = 'q'; } else { word = __get_word_from_canvas_for_menu (core, core->panels, cx, cy); if (word) { void *cb = sdb_ptr_get (menu_db, word, 0); if (cb) { ((RPanelAlmightyCallback)cb) (core, panel, PANEL_LAYOUT_NONE, word); __free_modal (&modal); free (word); break; } free (word); } } } } switch (key) { case 'e': { __free_modal (&modal); char *cmd = __show_status_input (core, "New command: "); if (R_STR_ISNOTEMPTY (cmd)) { __replace_cmd (core, cmd, cmd); } free (cmd); } break; case 'j': modal->idx++; __update_modal (core, menu_db, modal); break; case 'k': modal->idx--; __update_modal (core, menu_db, modal); break; case 'v': __exec_modal (core, panel, modal, menu_db, PANEL_LAYOUT_VERTICAL); __free_modal (&modal); break; case 'h': __exec_modal (core, panel, modal, menu_db, PANEL_LAYOUT_HORIZONTAL); __free_modal (&modal); break; case 0x0d: __exec_modal (core, panel, modal, menu_db, PANEL_LAYOUT_NONE); __free_modal (&modal); break; case '-': __delete_modal (core, modal, menu_db); __update_modal (core, menu_db, modal); break; case 'q': case '"': __free_modal (&modal); break; } } } static bool __handle_mouse_on_X(RCore *core, int x, int y) { RPanels *panels = core->panels; const int idx = __get_panel_idx_in_pos (core, x, y); char *word = __get_word_from_canvas (core, panels, x, y); if (idx == -1) { return false; } RPanel *ppos = __get_panel(panels, idx); const int TITLE_Y = ppos->view->pos.y + 2; if (y == TITLE_Y && strcmp (word, " X ")) { int fx = ppos->view->pos.x; int fX = fx + ppos->view->pos.w; __set_curnode (core, idx); __set_refresh_all (core, true, true); if (x > (fX - 13) && x < fX) { __toggle_cache (core, __get_cur_panel (panels)); } else if (x > fx && x < (fx + 5)) { __dismantle_del_panel (core, ppos, idx); } else { __create_modal (core, __get_panel (panels, 0), panels->modal_db); __set_mode (core, PANEL_MODE_DEFAULT); } free (word); return true; } free (word); return false; } static void __seek_all(RCore *core, ut64 addr) { RPanels *panels = core->panels; int i; for (i = 0; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); panel->model->addr = addr; } } static bool __handle_mouse_on_panel(RCore *core, RPanel *panel, int x, int y, int *key) { RPanels *panels = core->panels; int h; (void)r_cons_get_size (&h); const int idx = __get_panel_idx_in_pos (core, x, y); char *word = __get_word_from_canvas (core, panels, x, y); if (idx == -1) { return false; } __set_curnode (core, idx); __set_refresh_all (core, true, true); RPanel *ppos = __get_panel(panels, idx); if (word) { const ut64 addr = r_num_math (core->num, word); if (__check_panel_type (panel, PANEL_CMD_FUNCTION) && __check_if_addr (word, strlen (word))) { r_core_seek (core, addr, true); __set_addr_by_type (core, PANEL_CMD_DISASSEMBLY, addr); } r_flag_set (core->flags, "panel.addr", addr, 1); r_config_set (core->config, "scr.highlight", word); { ut64 addr = r_num_math (core->num, word); if (addr > 0) { // TODO implement proper panel offset sync // __set_panel_addr (core, cur, addr); __seek_all (core, addr); } } free (word); } if (x >= ppos->view->pos.x && x < ppos->view->pos.x + 4) { *key = 'c'; return false; } return true; } static bool __handle_mouse(RCore *core, RPanel *panel, int *key) { RPanels *panels = core->panels; if (__drag_and_resize (core)) { return true; } if (key && !*key) { int x, y; if (!r_cons_get_click (&x, &y)) { return false; } if (y == MENU_Y && __handle_mouse_on_top (core, x, y)) { return true; } if (panels->mode == PANEL_MODE_MENU) { __handle_mouse_on_menu (core, x, y); return true; } if (__handle_mouse_on_X (core, x, y)) { return true; } if (__check_if_mouse_x_illegal (core, x) || __check_if_mouse_y_illegal (core, y)) { panels->mouse_on_edge_x = false; panels->mouse_on_edge_y = false; return true; } panels->mouse_on_edge_x = __check_if_mouse_x_on_edge (core, x, y); panels->mouse_on_edge_y = __check_if_mouse_y_on_edge (core, x, y); if (panels->mouse_on_edge_x || panels->mouse_on_edge_y) { return true; } if (__handle_mouse_on_panel (core, panel, x, y, key)) { return true; } int h, w = r_cons_get_size (&h); if (y == h) { RPanel *p = __get_cur_panel (panels); __split_panel_horizontal (core, p, p->model->title, p->model->cmd); } else if (x == w) { RPanel *p = __get_cur_panel (panels); __split_panel_vertical (core, p, p->model->title, p->model->cmd); } } if (key && *key == INT8_MAX) { *key = '"'; return false; } return false; } static void __add_visual_mark(RCore *core) { char *msg = r_str_newf (R_CONS_CLEAR_LINE"Set shortcut key for 0x%"PFMT64x": ", core->offset); int ch = __show_status (core, msg); free (msg); r_core_visual_mark (core, ch); } static void __handle_visual_mark(RCore *core) { RPanel *cur = __get_cur_panel (core->panels); if (!__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { return; } int act = __show_status (core, "Visual Mark s:set -:remove \':use: "); switch (act) { case 's': __add_visual_mark (core); break; case '-': r_cons_gotoxy (0, 0); if (r_core_visual_mark_dump (core)) { r_cons_printf (R_CONS_CLEAR_LINE"Remove a shortcut key from the list\n"); r_cons_flush (); int ch = r_cons_readchar (); r_core_visual_mark_del (core, ch); } break; case '\'': r_cons_gotoxy (0, 0); if (r_core_visual_mark_dump (core)) { r_cons_flush (); int ch = r_cons_readchar (); r_core_visual_mark_seek (core, ch); __set_panel_addr (core, cur, core->offset); } } } static void __move_panel_to_left(RCore *core, RPanel *panel, int src) { RPanels *panels = core->panels; __shrink_panels_backward (core, src); panels->panel[0] = panel; int h, w = r_cons_get_size (&h); int p_w = w - panels->columnWidth; p_w /= 2; int new_w = w - p_w; __set_geometry (&panel->view->pos, 0, 1, p_w + 1, h - 1); int i = 1; for (; i < panels->n_panels; i++) { RPanel *tmp = __get_panel (panels, i); int t_x = ((double)tmp->view->pos.x / (double)w) * (double)new_w + p_w; int t_w = ((double)tmp->view->pos.w / (double)w) * (double)new_w + 1; __set_geometry (&tmp->view->pos, t_x, tmp->view->pos.y, t_w, tmp->view->pos.h); } __fix_layout (core); __set_curnode (core, 0); } static void __move_panel_to_right(RCore *core, RPanel *panel, int src) { RPanels *panels = core->panels; __shrink_panels_forward (core, src); panels->panel[panels->n_panels - 1] = panel; int h, w = r_cons_get_size (&h); int p_w = w - panels->columnWidth; p_w /= 2; int p_x = w - p_w; __set_geometry (&panel->view->pos, p_x - 1, 1, p_w + 1, h - 1); int new_w = w - p_w; int i = 0; for (; i < panels->n_panels - 1; i++) { RPanel *tmp = __get_panel (panels, i); int t_x = ((double)tmp->view->pos.x / (double)w) * (double)new_w; int t_w = ((double)tmp->view->pos.w / (double)w) * (double)new_w + 1; __set_geometry (&tmp->view->pos, t_x, tmp->view->pos.y, t_w, tmp->view->pos.h); } __fix_layout (core); __set_curnode (core, panels->n_panels - 1); } static void __move_panel_to_up(RCore *core, RPanel *panel, int src) { RPanels *panels = core->panels; __shrink_panels_backward (core, src); panels->panel[0] = panel; int h, w = r_cons_get_size (&h); int p_h = h / 2; int new_h = h - p_h; __set_geometry (&panel->view->pos, 0, 1, w, p_h - 1); int i = 1; for (; i < panels->n_panels; i++) { RPanel *tmp = __get_panel (panels, i); int t_y = ((double)tmp->view->pos.y / (double)h) * (double)new_h + p_h; int t_h = ((double)tmp->view->pos.h / (double)h) * (double)new_h + 1; __set_geometry (&tmp->view->pos, tmp->view->pos.x, t_y, tmp->view->pos.w, t_h); } __fix_layout (core); __set_curnode (core, 0); } static void __move_panel_to_down(RCore *core, RPanel *panel, int src) { RPanels *panels = core->panels; __shrink_panels_forward (core, src); panels->panel[panels->n_panels - 1] = panel; int h, w = r_cons_get_size (&h); int p_h = h / 2; int new_h = h - p_h; __set_geometry (&panel->view->pos, 0, new_h, w, p_h); size_t i = 0; for (; i < panels->n_panels - 1; i++) { RPanel *tmp = __get_panel (panels, i); const size_t t_y = (tmp->view->pos.y * new_h / h) + 1; const size_t t_h = (tmp->view->edge & (1 << PANEL_EDGE_BOTTOM)) ? new_h - t_y : (tmp->view->pos.h * new_h / h) ; __set_geometry (&tmp->view->pos, tmp->view->pos.x, t_y, tmp->view->pos.w, t_h); } __fix_layout (core); __set_curnode (core, panels->n_panels - 1); } static void __move_panel_to_dir(RCore *core, RPanel *panel, int src) { RPanels *panels = core->panels; __dismantle_panel (panels, panel); int key = __show_status (core, "Move the current panel to direction (h/j/k/l): "); key = r_cons_arrow_to_hjkl (key); __set_refresh_all (core, false, true); switch (key) { case 'h': __move_panel_to_left (core, panel, src); break; case 'l': __move_panel_to_right (core, panel, src); break; case 'k': __move_panel_to_up (core, panel, src); break; case 'j': __move_panel_to_down (core, panel, src); break; default: break; } } static void __set_dcb(RCore *core, RPanel *p) { if (__is_abnormal_cursor_type (core, p)) { p->model->cache = true; p->model->directionCb = __direction_panels_cursor_cb; return; } if ((p->model->cache && p->model->cmdStrCache) || p->model->readOnly) { p->model->directionCb = __direction_default_cb; return; } if (!p->model->cmd) { return; } if (__check_panel_type (p, PANEL_CMD_GRAPH)) { p->model->directionCb = __direction_graph_cb; return; } if (__check_panel_type (p, PANEL_CMD_STACK)) { p->model->directionCb = __direction_stack_cb; } else if (__check_panel_type (p, PANEL_CMD_DISASSEMBLY)) { p->model->directionCb = __direction_disassembly_cb; } else if (__check_panel_type (p, PANEL_CMD_REGISTERS)) { p->model->directionCb = __direction_register_cb; } else if (__check_panel_type (p, PANEL_CMD_HEXDUMP)) { p->model->directionCb = __direction_hexdump_cb; } else { p->model->directionCb = __direction_default_cb; } } static void __swap_panels(RPanels *panels, int p0, int p1) { RPanel *panel0 = __get_panel (panels, p0); RPanel *panel1 = __get_panel (panels, p1); RPanelModel *tmp = panel0->model; panel0->model = panel1->model; panel1->model = tmp; } static bool __check_func(RCore *core) { RAnalFunction *fun = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL); if (!fun) { r_cons_message ("Not in a function. Type 'df' to define it here"); return false; } if (r_list_empty (fun->bbs)) { r_cons_message ("No basic blocks in this function. You may want to use 'afb+'."); return false; } return true; } static void __call_visual_graph(RCore *core) { if (__check_func (core)) { RPanels *panels = core->panels; r_cons_canvas_free (panels->can); panels->can = NULL; int ocolor = r_config_get_i (core->config, "scr.color"); r_core_visual_graph (core, NULL, NULL, true); r_config_set_i (core->config, "scr.color", ocolor); int h, w = r_cons_get_size (&h); panels->can = __create_new_canvas (core, w, h); } } static bool __check_func_diff(RCore *core, RPanel *p) { RAnalFunction *func = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL); if (!func) { if (R_STR_ISEMPTY (p->model->funcName)) { return false; } p->model->funcName = NULL; return true; } if (!p->model->funcName || strcmp (p->model->funcName, func->name)) { p->model->funcName = r_str_dup (p->model->funcName, func->name); return true; } return false; } static void __print_default_cb(void *user, void *p) { RCore *core = (RCore *)user; RPanel *panel = (RPanel *)p; bool update = core->panels->autoUpdate && __check_func_diff (core, panel); char *cmdstr = __find_cmd_str_cache (core, panel); if (update || !cmdstr) { cmdstr = __handle_cmd_str_cache (core, panel, false); if (panel->model->cache && panel->model->cmdStrCache) { __reset_scroll_pos (panel); } } __update_panel_contents (core, panel, cmdstr); } static void __print_decompiler_cb(void *user, void *p) { //TODO: Refactoring //TODO: Also, __check_func_diff should use addr not name RCore *core = (RCore *)user; RPanel *panel = (RPanel *)p; bool update = core->panels->autoUpdate && __check_func_diff (core, panel); char *cmdstr = NULL; if (!update) { cmdstr = __find_cmd_str_cache (core, panel); if (cmdstr) { __update_pdc_contents (core, panel, cmdstr); } return; } RAnalFunction *func = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL); if (func && core->panels_root->cur_pdc_cache) { cmdstr = r_str_new ((char *)sdb_ptr_get (core->panels_root->cur_pdc_cache, r_num_as_string (NULL, func->addr, false), 0)); if (cmdstr) { __set_cmd_str_cache (core, panel, cmdstr); __reset_scroll_pos (panel); __update_pdc_contents (core, panel, cmdstr); return; } } cmdstr = __handle_cmd_str_cache (core, panel, false); if (cmdstr) { __reset_scroll_pos (panel); __set_decompiler_cache (core, cmdstr); __update_pdc_contents (core, panel, cmdstr); } } static void __print_disasmsummary_cb (void *user, void *p) { RCore *core = (RCore *)user; RPanel *panel = (RPanel *)p; bool update = core->panels->autoUpdate && __check_func_diff (core, panel); char *cmdstr = __find_cmd_str_cache (core, panel); if (update || !cmdstr) { cmdstr = __handle_cmd_str_cache (core, panel, true); if (panel->model->cache && panel->model->cmdStrCache) { __reset_scroll_pos (panel); } } __update_panel_contents (core, panel, cmdstr); } static void __print_disassembly_cb(void *user, void *p) { RCore *core = (RCore *)user; RPanel *panel = (RPanel *)p; core->print->screen_bounds = 1LL; char *cmdstr = __find_cmd_str_cache (core, panel); if (cmdstr) { __update_panel_contents (core, panel, cmdstr); return; } char *ocmd = panel->model->cmd; panel->model->cmd = r_str_newf ("%s %d", panel->model->cmd, panel->view->pos.h - 3); ut64 o_offset = core->offset; core->offset = panel->model->addr; r_core_seek (core, panel->model->addr, true); if (r_config_get_i (core->config, "cfg.debug")) { r_core_cmd (core, ".dr*", 0); } cmdstr = __handle_cmd_str_cache (core, panel, false); core->offset = o_offset; free (panel->model->cmd); panel->model->cmd = ocmd; __update_panel_contents (core, panel, cmdstr); } static void __do_panels_refresh(RCore *core) { if (core->panels) { __panel_all_clear (core->panels); __panels_layout_refresh (core); } } static void __do_panels_resize(RCore *core) { RPanels *panels = core->panels; int i; int h, w = r_cons_get_size (&h); for (i = 0; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); if ((panel->view->edge & (1 << PANEL_EDGE_BOTTOM)) && (panel->view->pos.y + panel->view->pos.h < h)) { panel->view->pos.h = h - panel->view->pos.y; } if ((panel->view->edge & (1 << PANEL_EDGE_RIGHT)) && (panel->view->pos.x + panel->view->pos.w < w)) { panel->view->pos.w = w - panel->view->pos.x; } } __do_panels_refresh (core); } static void __do_panels_refreshOneShot(RCore *core) { r_core_task_enqueue_oneshot (&core->tasks, (RCoreTaskOneShot) __do_panels_resize, core); } static void __print_graph_cb(void *user, void *p) { RCore *core = (RCore *)user; RPanel *panel = (RPanel *)p; bool update = core->panels->autoUpdate && __check_func_diff (core, panel); char *cmdstr = __find_cmd_str_cache (core, panel); if (update || !cmdstr) { cmdstr = __handle_cmd_str_cache (core, panel, false); } core->cons->event_resize = NULL; core->cons->event_data = core; core->cons->event_resize = (RConsEvent) __do_panels_refreshOneShot; __update_panel_contents (core, panel, cmdstr); } static void __print_stack_cb(void *user, void *p) { RCore *core = (RCore *)user; RPanel *panel = (RPanel *)p; const int delta = r_config_get_i (core->config, "stack.delta"); const int bits = r_config_get_i (core->config, "asm.bits"); const char sign = (delta < 0)? '+': '-'; const int absdelta = R_ABS (delta); char *cmd = r_str_newf ("%s%s ", PANEL_CMD_STACK, bits == 32 ? "w" : "q"); int n = r_str_split (panel->model->cmd, ' '); int i; for (i = 0; i < n; i++) { const char *s = r_str_word_get0 (panel->model->cmd, i); if (!i) { continue; } cmd = r_str_append (cmd, s); } panel->model->cmd = cmd; const char *cmdstr = r_core_cmd_str (core, r_str_newf ("%s%c%d", cmd, sign, absdelta)); __update_panel_contents (core, panel, cmdstr); } static void __print_hexdump_cb(void *user, void *p) { RCore *core = (RCore *)user; RPanel *panel = (RPanel *)p; char *cmdstr = __find_cmd_str_cache (core, panel); if (!cmdstr) { ut64 o_offset = core->offset; if (!panel->model->cache) { core->offset = panel->model->addr; r_core_seek (core, core->offset, true); r_core_block_read (core); } char *base = hexdump_rotate[R_ABS(panel->model->rotate) % COUNT (hexdump_rotate)]; char *cmd = r_str_newf ("%s ", base); int n = r_str_split (panel->model->cmd, ' '); int i; for (i = 0; i < n; i++) { const char *s = r_str_word_get0 (panel->model->cmd, i); if (!i) { continue; } cmd = r_str_append (cmd, s); } panel->model->cmd = cmd; cmdstr = __handle_cmd_str_cache (core, panel, false); core->offset = o_offset; } __update_panel_contents (core, panel, cmdstr); } static void __hudstuff(RCore *core) { RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); r_core_visual_hudstuff (core); if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, cur, core->offset); } else { int i; for (i = 0; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); if (__check_panel_type (panel, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, panel, core->offset); break; } } } } static void __print_snow(RPanels *panels) { if (!panels->snows) { panels->snows = r_list_newf (free); } RPanel *cur = __get_cur_panel (panels); int i, amount = r_num_rand (4); if (amount > 0) { for (i = 0; i < amount; i++) { RPanelsSnow *snow = R_NEW (RPanelsSnow); snow->x = r_num_rand (cur->view->pos.w) + cur->view->pos.x; snow->y = cur->view->pos.y; r_list_append (panels->snows, snow); } } RListIter *iter, *iter2; RPanelsSnow *snow; r_list_foreach_safe (panels->snows, iter, iter2, snow) { int pos = r_num_rand (3) - 1; snow->x += pos; snow->y++; if (snow->x >= cur->view->pos.w + cur->view->pos.x || snow->x <= cur->view->pos.x + 1) { r_list_delete (panels->snows, iter); continue; } if (snow->y >= cur->view->pos.h + cur->view->pos.y - 1) { r_list_delete (panels->snows, iter); continue; } if (r_cons_canvas_gotoxy (panels->can, snow->x, snow->y)) { if (panels->fun == PANEL_FUN_SAKURA) { r_cons_canvas_write (panels->can, Color_BMAGENTA","Color_RESET); } else { r_cons_canvas_write (panels->can, "*"); } } } } static void __set_pcb(RPanel *p) { if (!p->model->cmd) { return; } if (__check_panel_type (p, PANEL_CMD_DISASSEMBLY)) { p->model->print_cb = __print_disassembly_cb; return; } if (__check_panel_type (p, PANEL_CMD_STACK)) { p->model->print_cb = __print_stack_cb; return; } if (__check_panel_type (p, PANEL_CMD_HEXDUMP)) { p->model->print_cb = __print_hexdump_cb; return; } if (__check_panel_type (p, PANEL_CMD_DECOMPILER)) { p->model->print_cb = __print_decompiler_cb; return; } if (__check_panel_type (p, PANEL_CMD_GRAPH)) { p->model->print_cb = __print_graph_cb; return; } if (__check_panel_type (p, PANEL_CMD_TINYGRAPH)) { p->model->print_cb = __print_graph_cb; return; } if (__check_panel_type (p, PANEL_CMD_DISASMSUMMARY)) { p->model->print_cb = __print_disasmsummary_cb; return; } p->model->print_cb = __print_default_cb; } static int __file_history_up(RLine *line) { RCore *core = line->user; RList *files = r_id_storage_list (core->io->files); int num_files = r_list_length (files); if (line->file_hist_index >= num_files || line->file_hist_index < 0) { return false; } line->file_hist_index++; RIODesc *desc = r_list_get_n (files, num_files - line->file_hist_index); if (desc) { strncpy (line->buffer.data, desc->name, R_LINE_BUFSIZE - 1); line->buffer.index = line->buffer.length = strlen (line->buffer.data); } r_list_free (files); return true; } static int __file_history_down(RLine *line) { RCore *core = line->user; RList *files = r_id_storage_list (core->io->files); int num_files = r_list_length (files); if (line->file_hist_index <= 0 || line->file_hist_index > num_files) { return false; } line->file_hist_index--; if (line->file_hist_index <= 0) { line->buffer.data[0] = '\0'; line->buffer.index = line->buffer.length = 0; return false; } RIODesc *desc = r_list_get_n (files, num_files - line->file_hist_index); if (desc) { strncpy (line->buffer.data, desc->name, R_LINE_BUFSIZE - 1); line->buffer.index = line->buffer.length = strlen (line->buffer.data); } r_list_free (files); return true; } static int __open_file_cb(void *user) { RCore *core = (RCore *)user; core->cons->line->prompt_type = R_LINE_PROMPT_FILE; r_line_set_hist_callback (core->cons->line, &__file_history_up, &__file_history_down); __add_cmdf_panel (core, "open file: ", "o %s"); core->cons->line->prompt_type = R_LINE_PROMPT_DEFAULT; r_line_set_hist_callback (core->cons->line, &r_line_hist_cmd_up, &r_line_hist_cmd_down); return 0; } static int __rw_cb(void *user) { RCore *core = (RCore *)user; r_core_cmd (core, "oo+", 0); return 0; } static int __debugger_cb(void *user) { RCore *core = (RCore *)user; r_core_cmd (core, "oo", 0); return 0; } static int __settings_decompiler_cb(void *user) { RCore *core = (RCore *)user; RPanelsRoot *root = core->panels_root; RPanelsMenu *menu = core->panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; const char *pdc_next = child->name; const char *pdc_now = r_config_get (core->config, "cmd.pdc"); if (!strcmp (pdc_next, pdc_now)) { return 0; } root->cur_pdc_cache = sdb_ptr_get (root->pdc_caches, pdc_next, 0); if (!root->cur_pdc_cache) { Sdb *sdb = sdb_new0 (); if (sdb) { sdb_ptr_set (root->pdc_caches, pdc_next, sdb, 0); root->cur_pdc_cache = sdb; } } r_config_set (core->config, "cmd.pdc", pdc_next); int j = 0; for (j = 0; j < core->panels->n_panels; j++) { RPanel *panel = __get_panel (core->panels, j); if (!strncmp (panel->model->cmd, "pdc", 3)) { char *cmdstr = r_core_cmd_strf (core, "pdc@0x%08"PFMT64x, panel->model->addr); __update_panel_contents (core, panel, cmdstr); __reset_scroll_pos (panel); free (cmdstr); } } __set_refresh_all (core, true, false); __set_mode (core, PANEL_MODE_DEFAULT); return 0; } static void __create_default_panels(RCore *core) { RPanels *panels = core->panels; panels->n_panels = 0; __set_curnode (core, 0); const char **panels_list = panels_static; if (panels->layout == PANEL_LAYOUT_DEFAULT_DYNAMIC) { panels_list = panels_dynamic; } int i = 0; while (panels_list[i]) { RPanel *p = __get_panel (panels, panels->n_panels); if (!p) { return; } const char *s = panels_list[i++]; char *db_val = __search_db (core, s); __init_panel_param (core, p, s, db_val); free (db_val); } } static int __load_layout_saved_cb(void *user) { RCore *core = (RCore *)user; RPanelsMenu *menu = core->panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; if (!r_core_panels_load (core, child->name)) { __create_default_panels (core); __panels_layout (core->panels); } __set_curnode (core, 0); core->panels->panels_menu->depth = 1; __set_mode (core, PANEL_MODE_DEFAULT); return 0; } static int __load_layout_default_cb(void *user) { RCore *core = (RCore *)user; __init_panels (core, core->panels); __create_default_panels (core); __panels_layout (core->panels); core->panels->panels_menu->depth = 1; __set_mode (core, PANEL_MODE_DEFAULT); return 0; } static int __close_file_cb(void *user) { RCore *core = (RCore *)user; r_core_cmd0 (core, "o-*"); return 0; } static int __save_layout_cb(void *user) { RCore *core = (RCore *)user; r_core_panels_save (core, NULL); __set_mode (core, PANEL_MODE_DEFAULT); __clear_panels_menu (core); __get_cur_panel (core->panels)->view->refresh = true; return 0; } static void __update_menu(RCore *core, const char *parent, R_NULLABLE RPanelMenuUpdateCallback cb) { RPanels *panels = core->panels; void *addr = ht_pp_find (panels->mht, parent, NULL); RPanelsMenuItem *p_item = (RPanelsMenuItem *)addr; int i; for (i = 0; i < p_item->n_sub; i++) { RPanelsMenuItem *sub = p_item->sub[i]; ht_pp_delete (core->panels->mht, sdb_fmt ("%s.%s", parent, sub->name)); } p_item->sub = NULL; p_item->n_sub = 0; if (cb) { cb (core, parent); } RPanelsMenu *menu = panels->panels_menu; __update_menu_contents (core, menu, p_item); } static char *__get_panels_config_dir_path(void) { return r_str_home (R_JOIN_2_PATHS (R2_HOME_DATADIR, ".r2panels")); } static void __add_menu(RCore *core, const char *parent, const char *name, RPanelsMenuCallback cb) { RPanels *panels = core->panels; RPanelsMenuItem *p_item, *item = R_NEW0 (RPanelsMenuItem); if (!item) { return; } if (parent) { void *addr = ht_pp_find (panels->mht, parent, NULL); p_item = (RPanelsMenuItem *)addr; ht_pp_insert (panels->mht, sdb_fmt ("%s.%s", parent, name), item); } else { p_item = panels->panels_menu->root; ht_pp_insert (panels->mht, sdb_fmt ("%s", name), item); } item->n_sub = 0; item->selectedIndex = 0; item->name = name ? r_str_new (name) : NULL; item->sub = NULL; item->cb = cb; item->p = R_NEW0 (RPanel); if (item->p) { item->p->model = R_NEW0 (RPanelModel); item->p->view = R_NEW0 (RPanelView); if (item->p->model && item->p->view) { p_item->n_sub++; RPanelsMenuItem **sub = realloc (p_item->sub, sizeof (RPanelsMenuItem *) * p_item->n_sub); if (sub) { p_item->sub = sub; p_item->sub[p_item->n_sub - 1] = item; item = NULL; } } } __free_menu_item (item); } static void __init_menu_saved_layout (void *_core, const char *parent) { char *dir_path = __get_panels_config_dir_path (); RList *dir = r_sys_dir (dir_path); if (!dir) { free (dir_path); return; } RCore *core = (RCore *)_core; RListIter *it; char *entry; r_list_foreach (dir, it, entry) { if (strcmp (entry, ".") && strcmp (entry, "..")) { __add_menu (core, parent, entry, __load_layout_saved_cb); } } r_list_free (dir); free (dir_path); } static int __clear_layout_cb(void *user) { RCore *core = (RCore *)user; if (!__show_status_yesno (core, 0, "Clear all the saved layouts?(y/n): ")) { return 0; } char *dir_path = __get_panels_config_dir_path (); RList *dir = r_sys_dir ((const char *)dir_path); if (!dir) { free (dir_path); return 0; } RListIter *it; char *entry; r_list_foreach (dir, it, entry) { char *tmp = r_str_newf ("%s%s%s", dir_path, R_SYS_DIR, entry); r_file_rm (tmp); free (tmp); } r_file_rm (dir_path); r_list_free (dir); free (dir_path); __update_menu (core, "File.Load Layout.Saved", __init_menu_saved_layout); return 0; } static int __copy_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "How many bytes? ", "\"y %s\""); return 0; } static int __paste_cb(void *user) { RCore *core = (RCore *)user; r_core_cmd0 (core, "yy"); return 0; } static int __write_str_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "insert string: ", "\"w %s\""); return 0; } static int __write_hex_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "insert hexpairs: ", "\"wx %s\""); return 0; } static int __assemble_cb(void *user) { RCore *core = (RCore *)user; r_core_visual_asm (core, core->offset); return 0; } static int __fill_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "Fill with: ", "wow %s"); return 0; } static int __settings_colors_cb(void *user) { RCore *core = (RCore *)user; RPanelsMenu *menu = core->panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; r_str_ansi_filter (child->name, NULL, NULL, -1); r_core_cmdf (core, "eco %s", child->name); int i; for (i = 1; i < menu->depth; i++) { RPanel *p = menu->history[i]->p; p->view->refresh = true; menu->refreshPanels[i - 1] = p; } __update_menu(core, "Settings.Colors", __init_menu_color_settings_layout); return 0; } static int __config_value_cb(void *user) { RCore *core = (RCore *)user; RPanelsMenu *menu = core->panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; RStrBuf *tmp = r_strbuf_new (child->name); (void)r_str_split (r_strbuf_get(tmp), ':'); const char *v = __show_status_input (core, "New value: "); r_config_set (core->config, r_strbuf_get (tmp), v); r_strbuf_free (tmp); free (parent->p->model->title); parent->p->model->title = r_strbuf_drain (__draw_menu (core, parent)); size_t i; for (i = 1; i < menu->depth; i++) { RPanel *p = menu->history[i]->p; p->view->refresh = true; menu->refreshPanels[i - 1] = p; } if (!strcmp (parent->name, "asm")) { __update_menu (core, "Settings.Disassembly.asm", __init_menu_disasm_asm_settings_layout); } if (!strcmp (parent->name, "Screen")) { __update_menu (core, "Settings.Screen", __init_menu_screen_settings_layout); } return 0; } static int __config_toggle_cb(void *user) { RCore *core = (RCore *)user; RPanelsMenu *menu = core->panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; RStrBuf *tmp = r_strbuf_new (child->name); (void)r_str_split (r_strbuf_get (tmp), ':'); r_config_toggle (core->config, r_strbuf_get (tmp)); r_strbuf_free (tmp); free (parent->p->model->title); parent->p->model->title = r_strbuf_drain (__draw_menu (core, parent)); size_t i; for (i = 1; i < menu->depth; i++) { RPanel *p = menu->history[i]->p; p->view->refresh = true; menu->refreshPanels[i - 1] = p; } if (!strcmp (parent->name, "asm")) { __update_menu (core, "Settings.Disassembly.asm", __init_menu_disasm_asm_settings_layout); } if (!strcmp (parent->name, "Screen")) { __update_menu (core, "Settings.Screen", __init_menu_screen_settings_layout); } return 0; } static void __init_menu_screen_settings_layout(void *_core, const char *parent) { RCore *core = (RCore *)_core; RStrBuf *rsb = r_strbuf_new (NULL); int i = 0; while (menus_settings_screen[i]) { const char *menu = menus_settings_screen[i]; r_strbuf_set (rsb, menu); r_strbuf_append (rsb, ": "); r_strbuf_append (rsb, r_config_get (core->config, menu)); if (!strcmp (menus_settings_screen[i], "scr.color")) { __add_menu (core, parent, r_strbuf_get (rsb), __config_value_cb); } else { __add_menu (core, parent, r_strbuf_get (rsb), __config_toggle_cb); } i++; } r_strbuf_free (rsb); } static int __calculator_cb(void *user) { RCore *core = (RCore *)user; for (;;) { char *s = __show_status_input (core, "> "); if (!s || !*s) { free (s); break; } r_core_cmdf (core, "? %s", s); r_cons_flush (); free (s); } return 0; } static int __r2_shell_cb(void *user) { RCore *core = (RCore *)user; core->vmode = false; r_core_visual_prompt_input (core); core->vmode = true; return 0; } static int __system_shell_cb(void *user) { r_cons_set_raw (0); r_cons_flush (); r_sys_cmd ("$SHELL"); return 0; } static int __string_whole_bin_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "search strings in the whole binary: ", "izzq~%s"); return 0; } static int __string_data_sec_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "search string in data sections: ", "izq~%s"); return 0; } static int __rop_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "rop grep: ", "\"/R %s\""); return 0; } static int __code_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "search code: ", "\"/c %s\""); return 0; } static int __hexpairs_cb(void *user) { RCore *core = (RCore *)user; __add_cmdf_panel (core, "search hexpairs: ", "\"/x %s\""); return 0; } static void __esil_init(RCore *core) { r_core_cmd (core, "aeim", 0); r_core_cmd (core, "aeip", 0); } static void __esil_step_to(RCore *core, ut64 end) { r_core_cmdf (core, "aesu 0x%08"PFMT64x, end); } static int __esil_init_cb(void *user) { RCore *core = (RCore *)user; __esil_init (core); return 0; } static int __esil_step_to_cb(void *user) { RCore *core = (RCore *)user; char *end = __show_status_input (core, "target addr: "); __esil_step_to (core, r_num_math (core->num, end)); return 0; } static int __esil_step_range_cb(void *user) { RStrBuf *rsb = r_strbuf_new (NULL); RCore *core = (RCore *)user; r_strbuf_append (rsb, "start addr: "); char *s = __show_status_input (core, r_strbuf_get (rsb)); r_strbuf_append (rsb, s); r_strbuf_append (rsb, " end addr: "); char *d = __show_status_input (core, r_strbuf_get (rsb)); r_strbuf_free (rsb); ut64 s_a = r_num_math (core->num, s); ut64 d_a = r_num_math (core->num, d); if (s_a >= d_a) { return 0; } ut64 tmp = core->offset; core->offset = s_a; __esil_init (core); __esil_step_to (core, d_a); core->offset = tmp; return 0; } static int __io_cache_on_cb(void *user) { RCore *core = (RCore *)user; r_config_set_i (core->config, "io.cache", 1); (void)__show_status (core, "io.cache is on"); __set_mode (core, PANEL_MODE_DEFAULT); return 0; } static int __io_cache_off_cb(void *user) { RCore *core = (RCore *)user; r_config_set_i (core->config, "io.cache", 0); (void)__show_status (core, "io.cache is off"); __set_mode (core, PANEL_MODE_DEFAULT); return 0; } static int __reload_cb(void *user) { RCore *core = (RCore *)user; r_core_file_reopen_debug (core, ""); __update_disassembly_or_open (core); return 0; } static int __function_cb(void *user) { RCore *core = (RCore *)user; r_core_cmdf (core, "af"); return 0; } static int __symbols_cb(void *user) { RCore *core = (RCore *)user; r_core_cmdf (core, "aa"); return 0; } static int __program_cb(void *user) { RCore *core = (RCore *)user; r_core_cmdf (core, "aaa"); return 0; } static int __basic_blocks_cb(void *user) { RCore *core = (RCore *)user; r_core_cmdf (core, "aab"); return 0; } static int __calls_cb(void *user) { RCore *core = (RCore *)user; r_core_cmdf (core, "aac"); return 0; } static int __watch_points_cb(void *user) { RCore *core = (RCore *)user; char addrBuf[128], rw[128]; const char *addrPrompt = "addr: ", *rwPrompt = "<r/w/rw>: "; __panel_prompt (addrPrompt, addrBuf, sizeof (addrBuf)); __panel_prompt (rwPrompt, rw, sizeof (rw)); ut64 addr = r_num_math (core->num, addrBuf); r_core_cmdf (core, "dbw 0x%08"PFMT64x" %s", addr, rw); return 0; } static int __references_cb(void *user) { RCore *core = (RCore *)user; r_core_cmdf (core, "aar"); return 0; } static int __fortune_cb(void *user) { RCore *core = (RCore *)user; char *s = r_core_cmd_str (core, "fo"); r_cons_message (s); free (s); return 0; } static int __game_cb(void *user) { RCore *core = (RCore *)user; r_cons_2048 (core->panels->can->color); return 0; } static int __help_cb(void *user) { RCore *core = (RCore *)user; __toggle_help (core); return 0; } static int __license_cb(void *user) { r_cons_message ("Copyright 2006-2020 - pancake - LGPL"); return 0; } static int __version_cb(void *user) { RCore *core = (RCore *)user; char *s = r_core_cmd_str (core, "?V"); r_cons_message (s); free (s); return 0; } static int __writeValueCb(void *user) { RCore *core = (RCore *)user; char *res = __show_status_input (core, "insert number: "); if (res) { r_core_cmdf (core, "\"wv %s\"", res); free (res); } return 0; } static int __quit_cb(void *user) { __set_root_state ((RCore *)user, QUIT); return 0; } static int __open_menu_cb (void *user) { RCore* core = (RCore *)user; RPanelsMenu *menu = core->panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; if (menu->depth < 2) { __set_pos (&child->p->view->pos, menu->root->selectedIndex * 6, 1); } else { RPanelsMenuItem *p = menu->history[menu->depth - 2]; RPanelsMenuItem *parent2 = p->sub[p->selectedIndex]; __set_pos (&child->p->view->pos, parent2->p->view->pos.x + parent2->p->view->pos.w - 1, menu->depth == 2 ? parent2->p->view->pos.y + parent2->selectedIndex : parent2->p->view->pos.y); } RStrBuf *buf = __draw_menu (core, child); if (!buf) { return 0; } free (child->p->model->title); child->p->model->title = r_strbuf_drain (buf); child->p->view->pos.w = r_str_bounds (child->p->model->title, &child->p->view->pos.h); child->p->view->pos.h += 4; child->p->model->type = PANEL_TYPE_MENU; child->p->view->refresh = true; menu->refreshPanels[menu->n_refresh++] = child->p; menu->history[menu->depth++] = child; return 0; } static int cmpstr(const void *_a, const void *_b) { char *a = (char *)_a, *b = (char *)_b; return strcmp (a, b); } static RList *__sorted_list(RCore *core, const char *menu[], int count) { RList *list = r_list_newf (NULL); int i; for (i = 0; i < count; i++) { if (menu[i]) { (void)r_list_append (list, (void *)menu[i]); } } r_list_sort (list, cmpstr); return list; } static void __init_menu_color_settings_layout (void *_core, const char *parent) { RCore *core = (RCore *)_core; const char *color = core->cons->context->pal.graph_box2; char *now = r_core_cmd_str (core, "eco."); r_str_split (now, '\n'); parent = "Settings.Colors"; RList *list = __sorted_list (core, (const char **)menus_Colors, COUNT (menus_Colors)); char *pos; RListIter* iter; RStrBuf *buf = r_strbuf_new (NULL); r_list_foreach (list, iter, pos) { if (pos && !strcmp (now, pos)) { r_strbuf_setf (buf, "%s%s", color, pos); __add_menu (core, parent, r_strbuf_get (buf), __settings_colors_cb); continue; } __add_menu (core, parent, pos, __settings_colors_cb); } free (now); r_list_free (list); r_strbuf_free (buf); } static void __init_menu_disasm_settings_layout (void *_core, const char *parent) { RCore *core = (RCore *)_core; int i = 0; RList *list = __sorted_list (core, menus_settings_disassembly, COUNT (menus_settings_disassembly)); char *pos; RListIter* iter; RStrBuf *rsb = r_strbuf_new (NULL); r_list_foreach (list, iter, pos) { if (!strcmp (pos, "asm")) { __add_menu (core, parent, pos, __open_menu_cb); __init_menu_disasm_asm_settings_layout (core, "Settings.Disassembly.asm"); } else { r_strbuf_set (rsb, pos); r_strbuf_append (rsb, ": "); r_strbuf_append (rsb, r_config_get (core->config, pos)); __add_menu (core, parent, r_strbuf_get (rsb), __config_toggle_cb); } i++; } r_list_free (list); r_strbuf_free (rsb); } static void __init_menu_disasm_asm_settings_layout(void *_core, const char *parent) { RCore *core = (RCore *)_core; RList *list = __sorted_list (core, menus_settings_disassembly_asm, COUNT (menus_settings_disassembly_asm)); char *pos; RListIter* iter; RStrBuf *rsb = r_strbuf_new (NULL); r_list_foreach (list, iter, pos) { r_strbuf_set (rsb, pos); r_strbuf_append (rsb, ": "); r_strbuf_append (rsb, r_config_get (core->config, pos)); if (!strcmp (pos, "asm.var.summary") || !strcmp (pos, "asm.arch") || !strcmp (pos, "asm.bits") || !strcmp (pos, "asm.cpu")) { __add_menu (core, parent, r_strbuf_get (rsb), __config_value_cb); } else { __add_menu (core, parent, r_strbuf_get (rsb), __config_toggle_cb); } } r_list_free (list); r_strbuf_free (rsb); } static void __load_config_menu(RCore *core) { RList *themes_list = r_core_list_themes (core); RListIter *th_iter; char *th; int i = 0; r_list_foreach (themes_list, th_iter, th) { menus_Colors[i++] = th; } } static bool __init_panels_menu(RCore *core) { RPanels *panels = core->panels; RPanelsMenu *panels_menu = R_NEW0 (RPanelsMenu); if (!panels_menu) { return false; } RPanelsMenuItem *root = R_NEW0 (RPanelsMenuItem); if (!root) { R_FREE (panels_menu); return false; } panels->panels_menu = panels_menu; panels_menu->root = root; root->n_sub = 0; root->name = NULL; root->sub = NULL; __load_config_menu (core); int i = 0; while (menus[i]) { __add_menu (core, NULL, menus[i], __open_menu_cb); i++; } char *parent = "File"; i = 0; while (menus_File[i]) { if (!strcmp (menus_File[i], "Open")) { __add_menu (core, parent, menus_File[i], __open_file_cb); } else if (!strcmp (menus_File[i], "ReOpen")) { __add_menu (core, parent, menus_File[i], __open_menu_cb); } else if (!strcmp (menus_File[i], "Close")) { __add_menu (core, parent, menus_File[i], __close_file_cb); } else if (!strcmp (menus_File[i], "Save Layout")) { __add_menu (core, parent, menus_File[i], __save_layout_cb); } else if (!strcmp (menus_File[i], "Load Layout")) { __add_menu (core, parent, menus_File[i], __open_menu_cb); } else if (!strcmp (menus_File[i], "Clear Saved Layouts")) { __add_menu (core, parent, menus_File[i], __clear_layout_cb); } else if (!strcmp (menus_File[i], "Quit")) { __add_menu (core, parent, menus_File[i], __quit_cb); } else { __add_menu (core, parent, menus_File[i], __add_cmd_panel); } i++; } parent = "Settings"; i = 0; while (menus_Settings[i]) { __add_menu (core, parent, menus_Settings[i++], __open_menu_cb); } parent = "Edit"; i = 0; while (menus_Edit[i]) { if (!strcmp (menus_Edit[i], "Copy")) { __add_menu (core, parent, menus_Edit[i], __copy_cb); } else if (!strcmp (menus_Edit[i], "Paste")) { __add_menu (core, parent, menus_Edit[i], __paste_cb); } else if (!strcmp (menus_Edit[i], "Write String")) { __add_menu (core, parent, menus_Edit[i], __write_str_cb); } else if (!strcmp (menus_Edit[i], "Write Hex")) { __add_menu (core, parent, menus_Edit[i], __write_hex_cb); } else if (!strcmp (menus_Edit[i], "Write Value")) { __add_menu (core, parent, menus_Edit[i], __writeValueCb); } else if (!strcmp (menus_Edit[i], "Assemble")) { __add_menu (core, parent, menus_Edit[i], __assemble_cb); } else if (!strcmp (menus_Edit[i], "Fill")) { __add_menu (core, parent, menus_Edit[i], __fill_cb); } else if (!strcmp (menus_Edit[i], "io.cache")) { __add_menu (core, parent, menus_Edit[i], __open_menu_cb); } else { __add_menu (core, parent, menus_Edit[i], __add_cmd_panel); } i++; } { parent = "View"; i = 0; RList *list = __sorted_list (core, menus_View, COUNT (menus_View)); char *pos; RListIter* iter; r_list_foreach (list, iter, pos) { if (!strcmp (pos, PANEL_TITLE_ALL_DECOMPILER)) { __add_menu (core, parent, pos, __show_all_decompiler_cb); } else { __add_menu (core, parent, pos, __add_cmd_panel); } } } parent = "Tools"; i = 0; while (menus_Tools[i]) { if (!strcmp (menus_Tools[i], "Calculator")) { __add_menu (core, parent, menus_Tools[i], __calculator_cb); } else if (!strcmp (menus_Tools[i], "R2 Shell")) { __add_menu (core, parent, menus_Tools[i], __r2_shell_cb); } else if (!strcmp (menus_Tools[i], "System Shell")) { __add_menu (core, parent, menus_Tools[i], __system_shell_cb); } i++; } parent = "Search"; i = 0; while (menus_Search[i]) { if (!strcmp (menus_Search[i], "String (Whole Bin)")) { __add_menu (core, parent, menus_Search[i], __string_whole_bin_cb); } else if (!strcmp (menus_Search[i], "String (Data Sections)")) { __add_menu (core, parent, menus_Search[i], __string_data_sec_cb); } else if (!strcmp (menus_Search[i], "ROP")) { __add_menu (core, parent, menus_Search[i], __rop_cb); } else if (!strcmp (menus_Search[i], "Code")) { __add_menu (core, parent, menus_Search[i], __code_cb); } else if (!strcmp (menus_Search[i], "Hexpairs")) { __add_menu (core, parent, menus_Search[i], __hexpairs_cb); } i++; } parent = "Emulate"; i = 0; while (menus_Emulate[i]) { if (!strcmp (menus_Emulate[i], "Step From")) { __add_menu (core, parent, menus_Emulate[i], __esil_init_cb); } else if (!strcmp (menus_Emulate[i], "Step To")) { __add_menu (core, parent, menus_Emulate[i], __esil_step_to_cb); } else if (!strcmp (menus_Emulate[i], "Step Range")) { __add_menu (core, parent, menus_Emulate[i], __esil_step_range_cb); } i++; } { parent = "Debug"; i = 0; RList *list = __sorted_list (core, menus_Debug, COUNT (menus_Debug)); char *pos; RListIter* iter; r_list_foreach (list, iter, pos) { if (!strcmp (pos, "Breakpoints")) { __add_menu (core, parent, pos, __break_points_cb); } else if (!strcmp (pos, "Watchpoints")) { __add_menu (core, parent, pos, __watch_points_cb); } else if (!strcmp (pos, "Continue")) { __add_menu (core, parent, pos, __continue_cb); } else if (!strcmp (pos, "Step")) { __add_menu (core, parent, pos, __step_cb); } else if (!strcmp (pos, "Step Over")) { __add_menu (core, parent, pos, __step_over_cb); } else if (!strcmp (pos, "Reload")) { __add_menu (core, parent, pos, __reload_cb); } else { __add_menu (core, parent, pos, __add_cmd_panel); } } } parent = "Analyze"; i = 0; while (menus_Analyze[i]) { if (!strcmp (menus_Analyze[i], "Function")) { __add_menu (core, parent, menus_Analyze[i], __function_cb); } else if (!strcmp (menus_Analyze[i], "Symbols")) { __add_menu (core, parent, menus_Analyze[i], __symbols_cb); } else if (!strcmp (menus_Analyze[i], "Program")) { __add_menu (core, parent, menus_Analyze[i], __program_cb); } else if (!strcmp (menus_Analyze[i], "BasicBlocks")) { __add_menu (core, parent, menus_Analyze[i], __basic_blocks_cb); } else if (!strcmp (menus_Analyze[i], "Calls")) { __add_menu (core, parent, menus_Analyze[i], __calls_cb); } else if (!strcmp (menus_Analyze[i], "References")) { __add_menu (core, parent, menus_Analyze[i], __references_cb); } i++; } parent = "Help"; i = 0; while (menus_Help[i]) { if (!strcmp (menus_Help[i], "License")) { __add_menu (core, parent, menus_Help[i], __license_cb); } else if (!strcmp (menus_Help[i], "Version")) { __add_menu (core, parent, menus_Help[i], __version_cb); } else if (!strcmp (menus_Help[i], "Fortune")) { __add_menu (core, parent, menus_Help[i], __fortune_cb); } else if (!strcmp (menus_Help[i], "2048")) { __add_menu (core, parent, menus_Help[i], __game_cb); } else { __add_menu (core, parent, menus_Help[i], __help_cb); } i++; } parent = "File.ReOpen"; i = 0; while (menus_ReOpen[i]) { if (!strcmp (menus_ReOpen[i], "In RW")) { __add_menu (core, parent, menus_ReOpen[i], __rw_cb); } else if (!strcmp (menus_ReOpen[i], "In Debugger")) { __add_menu (core, parent, menus_ReOpen[i], __debugger_cb); } i++; } parent = "File.Load Layout"; i = 0; while (menus_loadLayout[i]) { if (!strcmp (menus_loadLayout[i], "Saved")) { __add_menu (core, parent, menus_loadLayout[i], __open_menu_cb); } else if (!strcmp (menus_loadLayout[i], "Default")) { __add_menu (core, parent, menus_loadLayout[i], __load_layout_default_cb); } i++; } __init_menu_saved_layout (core, "File.Load Layout.Saved"); __init_menu_color_settings_layout (core, "Settings.Colors"); { parent = "Settings.Decompiler"; char *opts = r_core_cmd_str (core, "e cmd.pdc=?"); RList *optl = r_str_split_list (opts, "\n", 0); RListIter *iter; char *opt; r_list_foreach (optl, iter, opt) { __add_menu (core, parent, strdup (opt), __settings_decompiler_cb); } r_list_free (optl); free (opts); } __init_menu_disasm_settings_layout (core, "Settings.Disassembly"); __init_menu_screen_settings_layout (core, "Settings.Screen"); parent = "Edit.io.cache"; i = 0; while (menus_iocache[i]) { if (!strcmp (menus_iocache[i], "On")) { __add_menu (core, parent, menus_iocache[i], __io_cache_on_cb); } else if (!strcmp (menus_iocache[i], "Off")) { __add_menu (core, parent, menus_iocache[i], __io_cache_off_cb); } i++; } panels_menu->history = calloc (8, sizeof (RPanelsMenuItem *)); __clear_panels_menu (core); panels_menu->refreshPanels = calloc (8, sizeof (RPanel *)); return true; } static bool __init_panels(RCore *core, RPanels *panels) { panels->panel = calloc (sizeof (RPanel *), PANEL_NUM_LIMIT); if (!panels->panel) { return false; } int i; for (i = 0; i < PANEL_NUM_LIMIT; i++) { panels->panel[i] = R_NEW0 (RPanel); panels->panel[i]->model = R_NEW0 (RPanelModel); __renew_filter (panels->panel[i], PANEL_NUM_LIMIT); panels->panel[i]->view = R_NEW0 (RPanelView); if (!panels->panel[i]->model || !panels->panel[i]->view) { return false; } } return true; } static void __refresh_core_offset (RCore *core) { RPanels *panels = core->panels; RPanel *cur = __get_cur_panel (panels); if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { core->offset = cur->model->addr; } } static void demo_begin(RCore *core, RConsCanvas *can) { char *s = r_cons_canvas_to_string (can); if (s) { // TODO drop utf8!! r_str_ansi_filter (s, NULL, NULL, -1); int i, h, w = r_cons_get_size (&h); for (i = 0; i < 40; i+= (1 + (i/30))) { int H = i * ((double)h / 40); char *r = r_str_scale (s, w, H); r_cons_clear00 (); r_cons_gotoxy (0, (h / 2) - (H / 2)); r_cons_strcat (r); r_cons_flush (); free (r); r_sys_usleep (3000); } free (s); } } static void demo_end(RCore *core, RConsCanvas *can) { bool utf8 = r_config_get_i (core->config, "scr.utf8"); r_config_set_i (core->config, "scr.utf8", 0); RPanel *cur = __get_cur_panel (core->panels); cur->view->refresh = true; firstRun= false; __panels_refresh (core); firstRun= true; r_config_set_i (core->config, "scr.utf8", utf8); char *s = r_cons_canvas_to_string (can); if (s) { // TODO drop utf8!! r_str_ansi_filter (s, NULL, NULL, -1); int i, h, w = r_cons_get_size (&h); for (i = h; i > 0; i--) { int H = i; char *r = r_str_scale (s, w, H); r_cons_clear00 (); r_cons_gotoxy (0, (h / 2) - (H / 2)); // center //r_cons_gotoxy (0, h-H); // bottom r_cons_strcat (r); r_cons_flush (); free (r); r_sys_usleep (3000); } r_sys_usleep (100000); free (s); } } static void __default_panel_print(RCore *core, RPanel *panel) { bool o_cur = core->print->cur_enabled; core->print->cur_enabled = o_cur & (__get_cur_panel (core->panels) == panel); if (panel->model->readOnly) { __update_help_contents (core, panel); __update_help_title (core, panel); } else if (panel->model->cmd) { panel->model->print_cb (core, panel); __update_panel_title (core, panel); } core->print->cur_enabled = o_cur; } static void __panel_print(RCore *core, RConsCanvas *can, RPanel *panel, int color) { if (!can || !panel|| !panel->view->refresh) { return; } if (can->w <= panel->view->pos.x || can->h <= panel->view->pos.y) { return; } panel->view->refresh = panel->model->type == PANEL_TYPE_MENU; r_cons_canvas_fill (can, panel->view->pos.x, panel->view->pos.y, panel->view->pos.w, panel->view->pos.h, ' '); if (panel->model->type == PANEL_TYPE_MENU) { __menu_panel_print (can, panel, panel->view->sx, panel->view->sy, panel->view->pos.w, panel->view->pos.h); } else { __default_panel_print (core, panel); } int w, h; w = R_MIN (panel->view->pos.w, can->w - panel->view->pos.x); h = R_MIN (panel->view->pos.h, can->h - panel->view->pos.y); if (color) { r_cons_canvas_box (can, panel->view->pos.x, panel->view->pos.y, w, h, core->cons->context->pal.graph_box2); } else { r_cons_canvas_box (can, panel->view->pos.x, panel->view->pos.y, w, h, core->cons->context->pal.graph_box); } } static void __panels_refresh(RCore *core) { RPanels *panels = core->panels; if (!panels) { return; } RConsCanvas *can = panels->can; if (!can) { return; } r_cons_gotoxy (0, 0); int i, h, w = r_cons_get_size (&h); if (!r_cons_canvas_resize (can, w, h)) { return; } RStrBuf *title = r_strbuf_new (" "); bool utf8 = r_config_get_i (core->config, "scr.utf8"); if (firstRun) { r_config_set_i (core->config, "scr.utf8", 0); } __refresh_core_offset (core); __set_refresh_all (core, false, false); //TODO use getPanel for (i = 0; i < panels->n_panels; i++) { if (i != panels->curnode) { __panel_print (core, can, __get_panel (panels, i), 0); } } if (panels->mode == PANEL_MODE_MENU) { __panel_print (core, can, __get_cur_panel (panels), 0); } else { __panel_print (core, can, __get_cur_panel (panels), 1); } for (i = 0; i < panels->panels_menu->n_refresh; i++) { __panel_print (core, can, panels->panels_menu->refreshPanels[i], 1); } (void) r_cons_canvas_gotoxy (can, -can->sx, -can->sy); r_cons_canvas_fill (can, -can->sx, -can->sy, w, 1, ' '); const char *color = core->cons->context->pal.graph_box2; if (panels->mode == PANEL_MODE_ZOOM) { r_strbuf_appendf (title, "%s Zoom Mode | Press Enter or q to quit"Color_RESET, color); } else if (panels->mode == PANEL_MODE_WINDOW) { r_strbuf_appendf (title, "%s Window Mode | hjkl: move around the panels | q: quit the mode | Enter: Zoom mode"Color_RESET, color); } else { RPanelsMenuItem *parent = panels->panels_menu->root; for (i = 0; i < parent->n_sub; i++) { RPanelsMenuItem *item = parent->sub[i]; if (panels->mode == PANEL_MODE_MENU && i == parent->selectedIndex) { r_strbuf_appendf (title, "%s[%s]"Color_RESET, color, item->name); } else { r_strbuf_appendf (title, " %s ", item->name); } } } if (panels->mode == PANEL_MODE_MENU) { r_cons_canvas_write (can, Color_YELLOW); r_cons_canvas_write (can, r_strbuf_get (title)); r_cons_canvas_write (can, Color_RESET); } else { r_cons_canvas_write (can, Color_RESET); r_cons_canvas_write (can, r_strbuf_get (title)); } r_strbuf_setf (title, "[0x%08"PFMT64x "]", core->offset); i = -can->sx + w - r_strbuf_length (title); (void) r_cons_canvas_gotoxy (can, i, -can->sy); r_cons_canvas_write (can, r_strbuf_get (title)); int tab_pos = i; for (i = core->panels_root->n_panels; i > 0; i--) { RPanels *panels = core->panels_root->panels[i - 1]; char *name = NULL; if (panels) { name = panels->name; } if (i - 1 == core->panels_root->cur_panels) { if (!name) { r_strbuf_setf (title, "%s[%d] "Color_RESET, color, i); } else { r_strbuf_setf (title, "%s[%s] "Color_RESET, color, name); } tab_pos -= r_str_ansi_len (r_strbuf_get (title)); } else { if (!name) { r_strbuf_setf (title, "%d ", i); } else { r_strbuf_setf (title, "%s ", name); } tab_pos -= r_strbuf_length (title); } (void) r_cons_canvas_gotoxy (can, tab_pos, -can->sy); r_cons_canvas_write (can, r_strbuf_get (title)); } r_strbuf_set (title, "Tab "); tab_pos -= r_strbuf_length (title); (void) r_cons_canvas_gotoxy (can, tab_pos, -can->sy); r_cons_canvas_write (can, r_strbuf_get (title)); r_strbuf_free (title); if (panels->fun == PANEL_FUN_SNOW || panels->fun == PANEL_FUN_SAKURA) { __print_snow (panels); } if (firstRun) { if (core->panels_root->n_panels < 2) { if (r_config_get_i (core->config, "scr.demo")) { demo_begin (core, can); } } firstRun = false; r_config_set_i (core->config, "scr.utf8", utf8); RPanel *cur = __get_cur_panel (core->panels); cur->view->refresh = true; __panels_refresh (core); return; } r_cons_canvas_print (can); if (core->scr_gadgets) { r_core_cmd0 (core, "pg"); } show_cursor (core); r_cons_flush (); if (r_cons_singleton ()->fps) { r_cons_print_fps (40); } } static void __panel_breakpoint(RCore *core) { RPanel *cur = __get_cur_panel (core->panels); if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { r_core_cmd (core, "dbs $$", 0); cur->view->refresh = true; } } static void __panel_continue(RCore *core) { r_core_cmd (core, "dc", 0); } static void __handle_menu(RCore *core, const int key) { RPanels *panels = core->panels; RPanelsMenu *menu = panels->panels_menu; RPanelsMenuItem *parent = menu->history[menu->depth - 1]; RPanelsMenuItem *child = parent->sub[parent->selectedIndex]; r_cons_switchbuf (false); switch (key) { case 'h': if (menu->depth <= 2) { menu->n_refresh = 0; if (menu->root->selectedIndex > 0) { menu->root->selectedIndex--; } else { menu->root->selectedIndex = menu->root->n_sub - 1; } if (menu->depth == 2) { menu->depth = 1; (void)(menu->root->sub[menu->root->selectedIndex]->cb (core)); } } else { __del_menu (core); } break; case 'j': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y++; } else { if (menu->depth == 1) { (void)(child->cb (core)); } else { parent->selectedIndex = R_MIN (parent->n_sub - 1, parent->selectedIndex + 1); __update_menu_contents (core, menu, parent); } } break; case 'k': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y--; } else { if (menu->depth < 2) { break; } RPanelsMenuItem *parent = menu->history[menu->depth - 1]; if (parent->selectedIndex > 0) { parent->selectedIndex--; __update_menu_contents (core, menu, parent); } else if (menu->depth == 2) { menu->depth--; } } break; case 'l': { if (menu->depth == 1) { menu->root->selectedIndex++; menu->root->selectedIndex %= menu->root->n_sub; break; } if (parent->sub[parent->selectedIndex]->sub) { (void)(parent->sub[parent->selectedIndex]->cb (core)); } else { menu->n_refresh = 0; menu->root->selectedIndex++; menu->root->selectedIndex %= menu->root->n_sub; menu->depth = 1; (void)(menu->root->sub[menu->root->selectedIndex]->cb (core)); } } break; case 'm': case 'q': case 'Q': case -1: if (panels->panels_menu->depth > 1) { __del_menu (core); } else { menu->n_refresh = 0; __set_mode (core, PANEL_MODE_DEFAULT); __get_cur_panel (panels)->view->refresh = true; } break; case '$': r_core_cmd0 (core, "dr PC=$$"); break; case ' ': case '\r': case '\n': (void)(child->cb (core)); break; case 9: menu->n_refresh = 0; __handle_tab_key (core, false); break; case 'Z': menu->n_refresh = 0; __handle_tab_key (core, true); break; case ':': menu->n_refresh = 0; __handlePrompt (core, panels); break; case '?': menu->n_refresh = 0; __toggle_help (core); break; case '"': menu->n_refresh = 0; __create_modal (core, __get_panel (panels, 0), panels->modal_db); __set_mode (core, PANEL_MODE_DEFAULT); break; } } static bool __handle_console(RCore *core, RPanel *panel, const int key) { if (!__check_panel_type (panel, PANEL_CMD_CONSOLE)) { return false; } r_cons_switchbuf (false); switch (key) { case 'i': { char cmd[128] = {0}; char *prompt = r_str_newf ("[0x%08"PFMT64x"]) ", core->offset); __panel_prompt (prompt, cmd, sizeof (cmd)); if (*cmd) { if (!strcmp (cmd, "clear")) { r_core_cmd0 (core, ":>$console"); } else { r_core_cmdf (core, "?e %s %s>>$console", prompt, cmd); r_core_cmdf (core, "%s >>$console", cmd); } } panel->view->refresh = true; } return true; case 'l': r_core_cmd0 (core, ":>$console"); panel->view->refresh = true; return true; default: // add more things later break; } return false; } static char *__create_panels_config_path(const char *file) { char *dir_path = __get_panels_config_dir_path (); r_sys_mkdirp (dir_path); char *file_path = r_str_newf (R_JOIN_2_PATHS ("%s", "%s"), dir_path, file); R_FREE (dir_path); return file_path; } static char *__get_panels_config_file_from_dir(const char *file) { char *dir_path = __get_panels_config_dir_path (); RList *dir = r_sys_dir (dir_path); if (!dir_path || !dir) { free (dir_path); return NULL; } char *tmp = NULL; RListIter *it; char *entry; r_list_foreach (dir, it, entry) { if (!strcmp (entry, file)) { tmp = entry; break; } } if (!tmp) { r_list_free (dir); free (dir_path); return NULL; } char *ret = r_str_newf (R_JOIN_2_PATHS ("%s", "%s"), dir_path, tmp); r_list_free (dir); free (dir_path); return ret; } R_API void r_core_panels_save(RCore *core, const char *oname) { int i; if (!core->panels) { return; } const char *name = oname; if (R_STR_ISEMPTY (name)) { name = __show_status_input (core, "Name for the layout: "); if (R_STR_ISEMPTY (name)) { (void)__show_status (core, "Name can't be empty!"); return; } } char *config_path = __create_panels_config_path (name); RPanels *panels = core->panels; PJ *pj = pj_new (); for (i = 0; i < panels->n_panels; i++) { RPanel *panel = __get_panel (panels, i); pj_o (pj); pj_ks (pj, "Title", panel->model->title); pj_ks (pj, "Cmd", panel->model->cmd); pj_kn (pj, "x", panel->view->pos.x); pj_kn (pj, "y", panel->view->pos.y); pj_kn (pj, "w", panel->view->pos.w); pj_kn (pj, "h", panel->view->pos.h); pj_end (pj); } FILE *fd = r_sandbox_fopen (config_path, "w"); if (fd) { char *pjs = pj_drain (pj); fprintf (fd, "%s\n", pjs); free (pjs); fclose (fd); __update_menu (core, "File.Load Layout.Saved", __init_menu_saved_layout); (void)__show_status (core, "Panels layout saved!"); } free (config_path); } static char *__parse_panels_config(const char *cfg, int len) { if (R_STR_ISEMPTY (cfg) || len < 2) { return NULL; } char *tmp = r_str_newlen (cfg, len + 1); int i = 0; for (; i < len; i++) { if (tmp[i] == '}') { if (i + 1 < len) { if (tmp[i + 1] == ',') { tmp[i + 1] = '\n'; } continue; } tmp[i + 1] = '\n'; } } return tmp; } R_API bool r_core_panels_load(RCore *core, const char *_name) { if (!core->panels) { return false; } char *config_path = __get_panels_config_file_from_dir (_name); if (!config_path) { char *tmp = r_str_newf ("No saved layout found for the name: %s", _name); (void)__show_status (core, tmp); free (tmp); return false; } char *panels_config = r_file_slurp (config_path, NULL); free (config_path); if (!panels_config) { char *tmp = r_str_newf ("Layout is empty: %s", _name); (void)__show_status (core, tmp); free (tmp); return false; } RPanels *panels = core->panels; __panel_all_clear (panels); panels->n_panels = 0; __set_curnode (core, 0); char *title, *cmd, *x, *y, *w, *h, *p_cfg = panels_config, *tmp_cfg; int i, tmp_count; tmp_cfg = __parse_panels_config (p_cfg, strlen (p_cfg)); tmp_count = r_str_split (tmp_cfg, '\n'); for (i = 0; i < tmp_count; i++) { if (R_STR_ISEMPTY (tmp_cfg)) { break; } title = sdb_json_get_str (tmp_cfg, "Title"); cmd = sdb_json_get_str (tmp_cfg, "Cmd"); (void)r_str_arg_unescape (cmd); x = sdb_json_get_str (tmp_cfg, "x"); y = sdb_json_get_str (tmp_cfg, "y"); w = sdb_json_get_str (tmp_cfg, "w"); h = sdb_json_get_str (tmp_cfg, "h"); RPanel *p = __get_panel (panels, panels->n_panels); __set_geometry (&p->view->pos, atoi (x), atoi (y), atoi (w),atoi (h)); __init_panel_param (core, p, title, cmd); // TODO: fix code duplication with __update_help if (r_str_endswith (cmd, "Help")) { p->model->title = r_str_dup (p->model->title, "Help"); p->model->cmd = r_str_dup (p->model->cmd, "Help"); RStrBuf *rsb = r_strbuf_new (NULL); r_core_visual_append_help (rsb, "Panels Mode", help_msg_panels); if (!rsb) { return false; } __set_read_only (core, p, r_strbuf_drain (rsb)); } tmp_cfg += strlen (tmp_cfg) + 1; } p_cfg += strlen (p_cfg) + 1; free (panels_config); if (!panels->n_panels) { free (tmp_cfg); return false; } __set_refresh_all (core, true, false); return true; } static void __rotate_panels(RCore *core, bool rev) { RPanels *panels = core->panels; RPanel *first = __get_panel (panels, 0); RPanel *last = __get_panel (panels, panels->n_panels - 1); int i; RPanelModel *tmp_model; if (!rev) { tmp_model = first->model; for (i = 0; i < panels->n_panels - 1; i++) { RPanel *p0 = __get_panel (panels, i); RPanel *p1 = __get_panel (panels, i + 1); p0->model = p1->model; } last->model = tmp_model; } else { tmp_model = last->model; for (i = panels->n_panels - 1; i > 0; i--) { RPanel *p0 = __get_panel (panels, i); RPanel *p1 = __get_panel (panels, i - 1); p0->model = p1->model; } first->model = tmp_model; } __set_refresh_all (core, false, true); } static void __undo_seek(RCore *core) { RPanel *cur = __get_cur_panel (core->panels); if (!__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { return; } RIOUndos *undo = r_io_sundo (core->io, core->offset); if (undo) { r_core_visual_seek_animation (core, undo->off); __set_panel_addr (core, cur, core->offset); } } static void __set_filter(RCore *core, RPanel *panel) { if (!panel->model->filter) { return; } char *input = __show_status_input (core, "filter word: "); if (input) { panel->model->filter[panel->model->n_filter++] = input; __set_cmd_str_cache (core, panel, NULL); panel->view->refresh = true; } __reset_scroll_pos (panel); } static void __redo_seek(RCore *core) { RPanel *cur = __get_cur_panel (core->panels); if (!__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { return; } RIOUndos *undo = r_io_sundo_redo (core->io); if (undo) { r_core_visual_seek_animation (core, undo->off); __set_panel_addr (core, cur, core->offset); } } static void __handle_tab(RCore *core) { r_cons_gotoxy (0, 0); if (core->panels_root->n_panels <= 1) { r_cons_printf (R_CONS_CLEAR_LINE"%s[Tab] t:new T:new with current panel -:del =:name"Color_RESET, core->cons->context->pal.graph_box2); } else { const int min = 1; const int max = core->panels_root->n_panels; r_cons_printf (R_CONS_CLEAR_LINE"%s[Tab] [%d..%d]:select; p:prev; n:next; t:new T:new with current panel -:del =:name"Color_RESET, core->cons->context->pal.graph_box2, min, max); } r_cons_flush (); int ch = r_cons_readchar (); if (isdigit (ch)) { __handle_tab_nth (core, ch); return; } switch (ch) { case 'n': __handle_tab_next (core); return; case 'p': __handle_tab_prev (core); return; case '-': __set_root_state (core, DEL); return; case '=': __handle_tab_name (core); return; case 't': __handle_tab_new (core); return; case 'T': __handle_tab_new_with_cur_panel (core); return; } } // copypasta from visual static void prevOpcode(RCore *core) { RPrint *p = core->print; ut64 addr, oaddr = core->offset + core->print->cur; if (r_core_prevop_addr (core, oaddr, 1, &addr)) { const int delta = oaddr - addr; p->cur -= delta; } else { p->cur -= 4; } } static void nextOpcode(RCore *core) { RAnalOp *aop = r_core_anal_op (core, core->offset + core->print->cur, R_ANAL_OP_MASK_BASIC); RPrint *p = core->print; if (aop) { p->cur += aop->size; r_anal_op_free (aop); } else { p->cur += 4; } } static void __panels_process(RCore *core, RPanels *panels) { if (!panels) { return; } int i, okey, key; RPanelsRoot *panels_root = core->panels_root; RPanels *prev; prev = core->panels; core->panels = panels; panels->autoUpdate = true; int h, w = r_cons_get_size (&h); panels->can = __create_new_canvas (core, w, h); __set_refresh_all (core, false, true); r_cons_switchbuf (false); int originCursor = core->print->cur; core->print->cur = 0; core->print->cur_enabled = false; core->print->col = 0; bool originVmode = core->vmode; core->vmode = true; { const char *layout = r_config_get (core->config, "scr.layout"); if (R_STR_ISNOTEMPTY (layout)) { r_core_panels_load (core, layout); } } bool o_interactive = r_cons_is_interactive (); r_cons_set_interactive (true); r_core_visual_showcursor (core, false); r_cons_enable_mouse (false); repeat: r_cons_enable_mouse (r_config_get_i (core->config, "scr.wheel")); core->panels = panels; core->cons->event_resize = NULL; // avoid running old event with new data core->cons->event_data = core; core->cons->event_resize = (RConsEvent) __do_panels_refreshOneShot; __panels_layout_refresh (core); RPanel *cur = __get_cur_panel (panels); if (panels->fun == PANEL_FUN_SNOW || panels->fun == PANEL_FUN_SAKURA) { if (panels->mode == PANEL_MODE_MENU) { panels->fun = PANEL_FUN_NOFUN; __reset_snow (panels); goto repeat; } okey = r_cons_readchar_timeout (300); if (okey == -1) { cur->view->refresh = true; goto repeat; } } else { okey = r_cons_readchar (); } key = r_cons_arrow_to_hjkl (okey); virtualmouse: if (__handle_mouse (core, cur, &key)) { if (panels_root->root_state != DEFAULT) { goto exit; } goto repeat; } r_cons_switchbuf (true); if (panels->mode == PANEL_MODE_MENU) { __handle_menu (core, key); if (__check_root_state (core, QUIT) || __check_root_state (core, ROTATE)) { goto exit; } goto repeat; } if (core->print->cur_enabled) { if (__handle_cursor_mode (core, key)) { goto repeat; } } if (panels->mode == PANEL_MODE_ZOOM) { if (__handle_zoom_mode (core, key)) { goto repeat; } } if (panels->mode == PANEL_MODE_WINDOW) { if (__handle_window_mode (core, key)) { goto repeat; } } if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY) && '0' < key && key <= '9') { ut8 ch = key; r_core_visual_jump (core, ch); __set_panel_addr (core, cur, core->offset); goto repeat; } const char *cmd; RConsCanvas *can = panels->can; if (__handle_console (core, cur, key)) { goto repeat; } switch (key) { case 'u': __undo_seek (core); break; case 'U': __redo_seek (core); break; case 'p': __rotate_panels (core, false); break; case 'P': __rotate_panels (core, true); break; case '.': if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { ut64 addr = r_debug_reg_get (core->dbg, "PC"); if (addr && addr != UT64_MAX) { r_core_seek (core, addr, true); } else { addr = r_num_get (core->num, "entry0"); if (addr && addr != UT64_MAX) { r_core_seek (core, addr, true); } } __set_panel_addr (core, cur, core->offset); } break; case '?': __toggle_help (core); break; case 'b': r_core_visual_browse (core, NULL); break; case ';': __handleComment (core); break; case '$': if (core->print->cur_enabled) { r_core_cmdf (core, "dr PC=$$+%d", core->print->cur); } else { r_core_cmd0 (core, "dr PC=$$"); } break; case 's': __panel_single_step_in (core); if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, cur, core->offset); } break; case 'S': __panel_single_step_over (core); if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, cur, core->offset); } break; case ' ': if (r_config_get_i (core->config, "graph.web")) { r_core_cmd0 (core, "agv $$"); } else { __call_visual_graph (core); } break; case ':': r_core_visual_prompt_input (core); __set_panel_addr (core, cur, core->offset); break; case 'c': __activate_cursor (core); break; case 'C': { int color = r_config_get_i (core->config, "scr.color"); if (++color > 2) { color = 0; } r_config_set_i (core->config, "scr.color", color); can->color = color; __set_refresh_all (core, true, false); } break; case 'r': if (r_config_get_i (core->config, "asm.hint.call")) { r_config_toggle (core->config, "asm.hint.call"); r_config_set_i (core->config, "asm.hint.jmp", true); } else if (r_config_get_i (core->config, "asm.hint.jmp")) { r_config_toggle (core->config, "asm.hint.jmp"); r_config_set_i (core->config, "asm.hint.emu", true); } else if (r_config_get_i (core->config, "asm.hint.emu")) { r_config_toggle (core->config, "asm.hint.emu"); r_config_set_i (core->config, "asm.hint.lea", true); } else if (r_config_get_i (core->config, "asm.hint.lea")) { r_config_toggle (core->config, "asm.hint.lea"); r_config_set_i (core->config, "asm.hint.call", true); } else { r_config_set_i (core->config, "asm.hint.call", true); } break; case 'R': if (r_config_get_i (core->config, "scr.randpal")) { r_core_cmd0 (core, "ecr"); } else { r_core_cmd0 (core, "ecn"); } __do_panels_refresh (core); break; case 'a': panels->autoUpdate = __show_status_yesno (core, 1, "Auto update On? (Y/n)"); break; case 'A': { const int ocur = core->print->cur_enabled; r_core_visual_asm (core, core->offset); core->print->cur_enabled = ocur; } break; case 'd': r_core_visual_define (core, "", 0); break; case 'D': __replace_cmd (core, PANEL_TITLE_DISASSEMBLY, PANEL_CMD_DISASSEMBLY); break; case 'j': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y++; } else { if (core->print->cur_enabled) { nextOpcode (core); } else { r_cons_switchbuf (false); if (cur->model->directionCb) { cur->model->directionCb (core, (int)DOWN); } } } break; case 'k': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y--; } else { if (core->print->cur_enabled) { prevOpcode (core); } else { r_cons_switchbuf (false); if (cur->model->directionCb) { cur->model->directionCb (core, (int)UP); } } } break; case 'K': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y -= 5; } else { if (core->print->cur_enabled) { size_t i; for (i = 0; i < 4; i++) { prevOpcode (core); } } else { r_cons_switchbuf (false); if (cur->model->directionCb) { for (i = 0; i < __get_cur_panel (panels)->view->pos.h / 2 - 6; i++) { cur->model->directionCb (core, (int)UP); } } } } break; case 'J': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.y += 5; } else { if (core->print->cur_enabled) { size_t i; for (i = 0; i < 4; i++) { nextOpcode (core); } } else { r_cons_switchbuf (false); if (cur->model->directionCb) { for (i = 0; i < __get_cur_panel (panels)->view->pos.h / 2 - 6; i++) { cur->model->directionCb (core, (int)DOWN); } } } } break; case 'H': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.x -= 5; } else { r_cons_switchbuf (false); if (cur->model->directionCb) { for (i = 0; i < __get_cur_panel (panels)->view->pos.w / 3; i++) { cur->model->directionCb (core, (int)LEFT); } } } break; case 'L': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.x += 5; } else { r_cons_switchbuf (false); if (cur->model->directionCb) { for (i = 0; i < __get_cur_panel (panels)->view->pos.w / 3; i++) { cur->model->directionCb (core, (int)RIGHT); } } } break; case 'f': __set_filter (core, cur); break; case 'F': __reset_filter (core, cur); break; case '_': __hudstuff (core); break; case '\\': r_core_visual_hud (core); break; case '"': r_cons_switchbuf (false); __create_modal (core, cur, panels->modal_db); if (__check_root_state (core, ROTATE)) { goto exit; } // all panels containing decompiler data should be cached cur->model->cache = strstr (cur->model->title, "Decomp") != NULL; break; case 'O': __handle_print_rotate (core); break; case 'n': if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { r_core_seek_next (core, r_config_get (core->config, "scr.nkey")); __set_panel_addr (core, cur, core->offset); } break; case 'N': if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { r_core_seek_previous (core, r_config_get (core->config, "scr.nkey")); __set_panel_addr (core, cur, core->offset); } break; case 'x': __handle_refs (core, cur, UT64_MAX); break; case 'X': #if 0 // already accessible via xX r_core_visual_refs (core, false, true); cur->model->addr = core->offset; set_refresh_all (panels, false); #endif __dismantle_del_panel (core, cur, panels->curnode); break; case 9: // TAB __handle_tab_key (core, false); break; case 'Z': // SHIFT-TAB __handle_tab_key (core, true); break; case 'M': __handle_visual_mark (core); break; case 'e': { char *cmd = __show_status_input (core, "New command: "); if (R_STR_ISNOTEMPTY (cmd)) { __replace_cmd (core, cmd, cmd); } free (cmd); } break; case 'm': __set_mode (core, PANEL_MODE_MENU); __clear_panels_menu (core); __get_cur_panel (panels)->view->refresh = true; break; case 'g': r_core_visual_showcursor (core, true); r_core_visual_offset (core); r_core_visual_showcursor (core, false); __set_panel_addr (core, cur, core->offset); break; case 'G': { const char *hl = r_config_get (core->config, "scr.highlight"); if (hl) { ut64 addr = r_num_math (core->num, hl); __set_panel_addr (core, cur, addr); // r_io_sundo_push (core->io, addr, false); // doesnt seems to work } } break; case 'h': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.x--; } else { if (core->print->cur_enabled) { core->print->cur--; } else { r_cons_switchbuf (false); if (cur->model->directionCb) { cur->model->directionCb (core, (int)LEFT); } } } break; case 'l': if (r_config_get_i (core->config, "scr.cursor")) { core->cons->cpos.x++; } else { if (core->print->cur_enabled) { core->print->cur++; } else { r_cons_switchbuf (false); if (cur->model->directionCb) { cur->model->directionCb (core, (int)RIGHT); } } } break; case 'V': if (r_config_get_i (core->config, "graph.web")) { r_core_cmd0 (core, "agv $$"); } else { __call_visual_graph (core); } break; case ']': if (__check_panel_type (cur, PANEL_CMD_HEXDUMP)) { r_config_set_i (core->config, "hex.cols", r_config_get_i (core->config, "hex.cols") + 1); } else { int cmtcol = r_config_get_i (core->config, "asm.cmt.col"); r_config_set_i (core->config, "asm.cmt.col", cmtcol + 2); } cur->view->refresh = true; break; case '[': if (__check_panel_type (cur, PANEL_CMD_HEXDUMP)) { r_config_set_i (core->config, "hex.cols", r_config_get_i (core->config, "hex.cols") - 1); } else { int cmtcol = r_config_get_i (core->config, "asm.cmt.col"); if (cmtcol > 2) { r_config_set_i (core->config, "asm.cmt.col", cmtcol - 2); } } cur->view->refresh = true; break; case '/': r_core_cmd0 (core, "?i highlight;e scr.highlight=`yp`"); break; case 'z': if (panels->curnode > 0) { __swap_panels (panels, 0, panels->curnode); __set_curnode (core, 0); } break; case 'i': if (cur->model->rotateCb) { cur->model->rotateCb (core, false); cur->view->refresh = true; } break; case 'I': if (cur->model->rotateCb) { cur->model->rotateCb (core, true); cur->view->refresh = true; } break; case 't': __handle_tab (core); if (panels_root->root_state != DEFAULT) { goto exit; } break; case 'T': if (panels_root->n_panels > 1) { __set_root_state (core, DEL); goto exit; } break; case 'w': __toggle_window_mode (core); break; case 'W': __move_panel_to_dir (core, cur, panels->curnode); break; case 0x0d: // "\\n" if (r_config_get_i (core->config, "scr.cursor")) { key = 0; r_cons_set_click (core->cons->cpos.x, core->cons->cpos.y); goto virtualmouse; } else { __toggle_zoom_mode (core); } break; case '|': { RPanel *p = __get_cur_panel (panels); __split_panel_vertical (core, p, p->model->title, p->model->cmd); break; } case '-': { RPanel *p = __get_cur_panel (panels); __split_panel_horizontal (core, p, p->model->title, p->model->cmd); break; } case '*': if (__check_func (core)) { r_cons_canvas_free (can); panels->can = NULL; __replace_cmd (core, PANEL_TITLE_DECOMPILER, PANEL_CMD_DECOMPILER); int h, w = r_cons_get_size (&h); panels->can = __create_new_canvas (core, w, h); } break; case '(': if (panels->fun != PANEL_FUN_SNOW && panels->fun != PANEL_FUN_SAKURA) { //TODO: Refactoring the FUN if bored af //panels->fun = PANEL_FUN_SNOW; panels->fun = PANEL_FUN_SAKURA; } else { panels->fun = PANEL_FUN_NOFUN; __reset_snow (panels); } break; case ')': __rotate_asmemu (core, __get_cur_panel (panels)); break; case '&': __toggle_cache (core, __get_cur_panel (panels)); break; case R_CONS_KEY_F1: cmd = r_config_get (core->config, "key.f1"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F2: cmd = r_config_get (core->config, "key.f2"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } else { __panel_breakpoint (core); } break; case R_CONS_KEY_F3: cmd = r_config_get (core->config, "key.f3"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F4: cmd = r_config_get (core->config, "key.f4"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F5: cmd = r_config_get (core->config, "key.f5"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F6: cmd = r_config_get (core->config, "key.f6"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F7: cmd = r_config_get (core->config, "key.f7"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } else { __panel_single_step_in (core); if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, cur, core->offset); } } break; case R_CONS_KEY_F8: cmd = r_config_get (core->config, "key.f8"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } else { __panel_single_step_over (core); if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { __set_panel_addr (core, cur, core->offset); } } break; case R_CONS_KEY_F9: cmd = r_config_get (core->config, "key.f9"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } else { if (__check_panel_type (cur, PANEL_CMD_DISASSEMBLY)) { __panel_continue (core); __set_panel_addr (core, cur, core->offset); } } break; case R_CONS_KEY_F10: cmd = r_config_get (core->config, "key.f10"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F11: cmd = r_config_get (core->config, "key.f11"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F12: cmd = r_config_get (core->config, "key.f12"); if (cmd && *cmd) { (void)r_core_cmd0 (core, cmd); } break; case 'Q': __set_root_state (core, QUIT); goto exit; case '!': fromVisual = true; case 'q': case -1: // EOF __set_root_state (core, DEL); if (core->panels_root->n_panels < 2) { if (r_config_get_i (core->config, "scr.demo")) { demo_end (core, can); } } goto exit; #if 0 case 27: // ESC if (r_cons_readchar () == 91) { if (r_cons_readchar () == 90) {} } break; #endif default: // eprintf ("Key %d\n", key); // sleep (1); break; } goto repeat; exit: if (!originVmode) { r_core_visual_showcursor (core, true); } core->cons->event_resize = NULL; core->cons->event_data = NULL; core->print->cur = originCursor; core->print->cur_enabled = false; core->print->col = 0; core->vmode = originVmode; core->panels = prev; r_cons_set_interactive (o_interactive); } static void __del_panels(RCore *core) { RPanelsRoot *panels_root = core->panels_root; if (panels_root->n_panels <= 1) { core->panels_root->root_state = QUIT; return; } int i; for (i = panels_root->cur_panels; i < panels_root->n_panels - 1; i++) { panels_root->panels[i] = panels_root->panels[i + 1]; } panels_root->n_panels--; if (panels_root->cur_panels >= panels_root->n_panels) { panels_root->cur_panels = panels_root->n_panels - 1; } } R_API bool r_core_panels_root(RCore *core, RPanelsRoot *panels_root) { fromVisual = core->vmode; if (!panels_root) { panels_root = R_NEW0 (RPanelsRoot); if (!panels_root) { return false; } core->panels_root = panels_root; panels_root->panels = calloc (sizeof (RPanels *), PANEL_NUM_LIMIT); panels_root->n_panels = 0; panels_root->cur_panels = 0; panels_root->pdc_caches = sdb_new0 (); panels_root->cur_pdc_cache = NULL; __set_root_state (core, DEFAULT); __init_new_panels_root (core); } else { if (!panels_root->n_panels) { panels_root->n_panels = 0; panels_root->cur_panels = 0; __init_new_panels_root (core); } const char *pdc_now = r_config_get (core->config, "cmd.pdc"); if (sdb_exists (panels_root->pdc_caches, pdc_now)) { panels_root->cur_pdc_cache = sdb_ptr_get (panels_root->pdc_caches, r_str_new (pdc_now), 0); } else { Sdb *sdb = sdb_new0(); sdb_ptr_set (panels_root->pdc_caches, r_str_new (pdc_now), sdb, 0); panels_root->cur_pdc_cache = sdb; } } const char *layout = r_config_get (core->config, "scr.layout"); if (!R_STR_ISEMPTY (layout)) { r_core_cmdf (core, "v %s", layout); } RPanels *panels = panels_root->panels[panels_root->cur_panels]; if (panels) { size_t i = 0; for (; i < panels->n_panels; i++) { RPanel *cur = __get_panel (panels, i); if (cur) { cur->model->addr = core->offset; } } } while (panels_root->n_panels) { __set_root_state (core, DEFAULT); __panels_process (core, panels_root->panels[panels_root->cur_panels]); if (__check_root_state (core, DEL)) { __del_panels (core); } if (__check_root_state (core, QUIT)) { break; } } if (fromVisual) { r_core_cmdf (core, "V"); } else { r_cons_enable_mouse (false); } return true; } static void __init_new_panels_root(RCore *core) { RPanelsRoot *panels_root = core->panels_root; RPanels *panels = __panels_new (core); if (!panels) { return; } RPanels *prev = core->panels; core->panels = panels; panels_root->panels[panels_root->n_panels++] = panels; if (!__init_panels_menu (core)) { core->panels = prev; return; } if (!__init_panels (core, panels)) { core->panels = prev; return; } __init_all_dbs (core); __set_mode (core, PANEL_MODE_DEFAULT); __create_default_panels (core); __panels_layout (panels); core->panels = prev; }
unixfreaxjp/radare2
libr/core/panels.c
C
lgpl-3.0
195,125
// // Copyright 2012 Square Inc. // Portions Copyright (c) 2016-present, Facebook, Inc. // // All rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSInteger, SRReadyState) { SR_CONNECTING = 0, SR_OPEN = 1, SR_CLOSING = 2, SR_CLOSED = 3, }; typedef NS_ENUM(NSInteger, SRStatusCode) { // 0–999: Reserved and not used. SRStatusCodeNormal = 1000, SRStatusCodeGoingAway = 1001, SRStatusCodeProtocolError = 1002, SRStatusCodeUnhandledType = 1003, // 1004 reserved. SRStatusNoStatusReceived = 1005, SRStatusCodeAbnormal = 1006, SRStatusCodeInvalidUTF8 = 1007, SRStatusCodePolicyViolated = 1008, SRStatusCodeMessageTooBig = 1009, SRStatusCodeMissingExtension = 1010, SRStatusCodeInternalError = 1011, SRStatusCodeServiceRestart = 1012, SRStatusCodeTryAgainLater = 1013, // 1014: Reserved for future use by the WebSocket standard. SRStatusCodeTLSHandshake = 1015, // 1016–1999: Reserved for future use by the WebSocket standard. // 2000–2999: Reserved for use by WebSocket extensions. // 3000–3999: Available for use by libraries and frameworks. May not be used by applications. Available for registration at the IANA via first-come, first-serve. // 4000–4999: Available for use by applications. }; @class SRWebSocket; @class SRSecurityPolicy; /** Error domain used for errors reported by SRWebSocket. */ extern NSString *const SRWebSocketErrorDomain; /** Key used for HTTP status code if bad response was received from the server. */ extern NSString *const SRHTTPResponseErrorKey; @protocol SRWebSocketDelegate; ///-------------------------------------- #pragma mark - SRWebSocket ///-------------------------------------- /** A `SRWebSocket` object lets you connect, send and receive data to a remote Web Socket. */ @interface SRWebSocket : NSObject <NSStreamDelegate> /** The delegate of the web socket. The web socket delegate is notified on all state changes that happen to the web socket. */ @property (nonatomic, weak) id <SRWebSocketDelegate> delegate; /** A dispatch queue for scheduling the delegate calls. The queue doesn't need be a serial queue. If `nil` and `delegateOperationQueue` is `nil`, the socket uses main queue for performing all delegate method calls. */ @property (nullable, nonatomic, strong) dispatch_queue_t delegateDispatchQueue; /** An operation queue for scheduling the delegate calls. If `nil` and `delegateOperationQueue` is `nil`, the socket uses main queue for performing all delegate method calls. */ @property (nullable, nonatomic, strong) NSOperationQueue *delegateOperationQueue; /** Current ready state of the socket. Default: `SR_CONNECTING`. This property is Key-Value Observable and fully thread-safe. */ @property (atomic, assign, readonly) SRReadyState readyState; /** An instance of `NSURL` that this socket connects to. */ @property (nullable, nonatomic, strong, readonly) NSURL *url; /** All HTTP headers that were received by socket or `nil` if none were received so far. */ @property (nullable, nonatomic, assign, readonly) CFHTTPMessageRef receivedHTTPHeaders; /** Array of `NSHTTPCookie` cookies to apply to the connection. */ @property (nullable, nonatomic, copy) NSArray<NSHTTPCookie *> *requestCookies; /** The negotiated web socket protocol or `nil` if handshake did not yet complete. */ @property (nullable, nonatomic, copy, readonly) NSString *protocol; /** A boolean value indicating whether this socket will allow connection without SSL trust chain evaluation. For DEBUG builds this flag is ignored, and SSL connections are allowed regardless of the certificate trust configuration */ @property (nonatomic, assign, readonly) BOOL allowsUntrustedSSLCertificates; ///-------------------------------------- #pragma mark - Constructors ///-------------------------------------- /** Initializes a web socket with a given `NSURLRequest`. @param request Request to initialize with. */ - (instancetype)initWithURLRequest:(NSURLRequest *)request; /** Initializes a web socket with a given `NSURLRequest`, specifying a transport security policy (e.g. SSL configuration). @param request Request to initialize with. @param securityPolicy Policy object describing transport security behavior. */ - (instancetype)initWithURLRequest:(NSURLRequest *)request securityPolicy:(SRSecurityPolicy *)securityPolicy; /** Initializes a web socket with a given `NSURLRequest` and list of sub-protocols. @param request Request to initialize with. @param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`. */ - (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(nullable NSArray<NSString *> *)protocols; /** Initializes a web socket with a given `NSURLRequest`, list of sub-protocols and whether untrusted SSL certificates are allowed. @param request Request to initialize with. @param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`. @param allowsUntrustedSSLCertificates Boolean value indicating whether untrusted SSL certificates are allowed. Default: `false`. */ - (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(nullable NSArray<NSString *> *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates; /** Initializes a web socket with a given `NSURLRequest`, list of sub-protocols and whether untrusted SSL certificates are allowed. @param request Request to initialize with. @param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`. @param securityPolicy Policy object describing transport security behavior. */ - (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(nullable NSArray<NSString *> *)protocols securityPolicy:(SRSecurityPolicy *)securityPolicy NS_DESIGNATED_INITIALIZER; /** Initializes a web socket with a given `NSURL`. @param url URL to initialize with. */ - (instancetype)initWithURL:(NSURL *)url; /** Initializes a web socket with a given `NSURL` and list of sub-protocols. @param url URL to initialize with. @param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`. */ - (instancetype)initWithURL:(NSURL *)url protocols:(nullable NSArray<NSString *> *)protocols; /** Initializes a web socket with a given `NSURL`, specifying a transport security policy (e.g. SSL configuration). @param url URL to initialize with. @param securityPolicy Policy object describing transport security behavior. */ - (instancetype)initWithURL:(NSURL *)url securityPolicy:(SRSecurityPolicy *)securityPolicy; /** Initializes a web socket with a given `NSURL`, list of sub-protocols and whether untrusted SSL certificates are allowed. @param url URL to initialize with. @param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`. @param allowsUntrustedSSLCertificates Boolean value indicating whether untrusted SSL certificates are allowed. Default: `false`. */ - (instancetype)initWithURL:(NSURL *)url protocols:(nullable NSArray<NSString *> *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates; /** Unavailable initializer. Please use any other initializer. */ - (instancetype)init NS_UNAVAILABLE; /** Unavailable constructor. Please use any other initializer. */ + (instancetype)new NS_UNAVAILABLE; ///-------------------------------------- #pragma mark - Schedule ///-------------------------------------- /** Schedules a received on a given run loop in a given mode. By default, a web socket will schedule itself on `+[NSRunLoop SR_networkRunLoop]` using `NSDefaultRunLoopMode`. @param runLoop The run loop on which to schedule the receiver. @param mode The mode for the run loop. */ - (void)scheduleInRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode NS_SWIFT_NAME(schedule(in:forMode:)); /** Removes the receiver from a given run loop running in a given mode. @param runLoop The run loop on which the receiver was scheduled. @param mode The mode for the run loop. */ - (void)unscheduleFromRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode NS_SWIFT_NAME(unschedule(from:forMode:)); ///-------------------------------------- #pragma mark - Open / Close ///-------------------------------------- /** Opens web socket, which will trigger connection, authentication and start receiving/sending events. An instance of `SRWebSocket` is intended for one-time-use only. This method should be called once and only once. */ - (void)open; /** Closes a web socket using `SRStatusCodeNormal` code and no reason. */ - (void)close; /** Closes a web socket using a given code and reason. @param code Code to close the socket with. @param reason Reason to send to the server or `nil`. */ - (void)closeWithCode:(NSInteger)code reason:(nullable NSString *)reason; ///-------------------------------------- #pragma mark Send ///-------------------------------------- /** Send a UTF-8 string or binary data to the server. @param message UTF-8 String or Data to send. @deprecated Please use `sendString:` or `sendData` instead. */ - (void)send:(nullable id)message __attribute__((deprecated("Please use `sendString:error:` or `sendData:error:` instead."))); /** Send a UTF-8 String to the server. @param string String to send. @param error On input, a pointer to variable for an `NSError` object. If an error occurs, this pointer is set to an `NSError` object containing information about the error. You may specify `nil` to ignore the error information. @return `YES` if the string was scheduled to send, otherwise - `NO`. */ - (BOOL)sendString:(NSString *)string error:(NSError **)error NS_SWIFT_NAME(send(string:)); /** Send binary data to the server. @param data Data to send. @param error On input, a pointer to variable for an `NSError` object. If an error occurs, this pointer is set to an `NSError` object containing information about the error. You may specify `nil` to ignore the error information. @return `YES` if the string was scheduled to send, otherwise - `NO`. */ - (BOOL)sendData:(nullable NSData *)data error:(NSError **)error NS_SWIFT_NAME(send(data:)); /** Send binary data to the server, without making a defensive copy of it first. @param data Data to send. @param error On input, a pointer to variable for an `NSError` object. If an error occurs, this pointer is set to an `NSError` object containing information about the error. You may specify `nil` to ignore the error information. @return `YES` if the string was scheduled to send, otherwise - `NO`. */ - (BOOL)sendDataNoCopy:(nullable NSData *)data error:(NSError **)error NS_SWIFT_NAME(send(dataNoCopy:)); /** Send Ping message to the server with optional data. @param data Instance of `NSData` or `nil`. @param error On input, a pointer to variable for an `NSError` object. If an error occurs, this pointer is set to an `NSError` object containing information about the error. You may specify `nil` to ignore the error information. @return `YES` if the string was scheduled to send, otherwise - `NO`. */ - (BOOL)sendPing:(nullable NSData *)data error:(NSError **)error NS_SWIFT_NAME(sendPing(_:)); @end ///-------------------------------------- #pragma mark - SRWebSocketDelegate ///-------------------------------------- /** The `SRWebSocketDelegate` protocol describes the methods that `SRWebSocket` objects call on their delegates to handle status and messsage events. */ @protocol SRWebSocketDelegate <NSObject> @optional #pragma mark Receive Messages /** Called when any message was received from a web socket. This method is suboptimal and might be deprecated in a future release. @param webSocket An instance of `SRWebSocket` that received a message. @param message Received message. Either a `String` or `NSData`. */ - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message; /** Called when a frame was received from a web socket. @param webSocket An instance of `SRWebSocket` that received a message. @param string Received text in a form of UTF-8 `String`. */ - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string; /** Called when a frame was received from a web socket. @param webSocket An instance of `SRWebSocket` that received a message. @param data Received data in a form of `NSData`. */ - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data; #pragma mark Status & Connection /** Called when a given web socket was open and authenticated. @param webSocket An instance of `SRWebSocket` that was open. */ - (void)webSocketDidOpen:(SRWebSocket *)webSocket; /** Called when a given web socket encountered an error. @param webSocket An instance of `SRWebSocket` that failed with an error. @param error An instance of `NSError`. */ - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error; /** Called when a given web socket was closed. @param webSocket An instance of `SRWebSocket` that was closed. @param code Code reported by the server. @param reason Reason in a form of a String that was reported by the server or `nil`. @param wasClean Boolean value indicating whether a socket was closed in a clean state. */ - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(nullable NSString *)reason wasClean:(BOOL)wasClean; /** Called when a pong data was received in response to ping. @param webSocket An instance of `SRWebSocket` that received a pong frame. @param pongData Payload that was received or `nil` if there was no payload. */ - (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(nullable NSData *)pongData; /** Sent before reporting a text frame to be able to configure if it shuold be convert to a UTF-8 String or passed as `NSData`. If the method is not implemented - it will always convert text frames to String. @param webSocket An instance of `SRWebSocket` that received a text frame. @return `YES` if text frame should be converted to UTF-8 String, otherwise - `NO`. Default: `YES`. */ - (BOOL)webSocketShouldConvertTextFrameToString:(SRWebSocket *)webSocket NS_SWIFT_NAME(webSocketShouldConvertTextFrameToString(_:)); @end NS_ASSUME_NONNULL_END
ios-plugin/uexDemo
3rdParty/src/SocketRocket/SocketRocket/SRWebSocket.h
C
lgpl-3.0
14,815
package repack.org.bouncycastle.cms; import repack.org.bouncycastle.asn1.ASN1EncodableVector; import repack.org.bouncycastle.asn1.ASN1InputStream; import repack.org.bouncycastle.asn1.ASN1Object; import repack.org.bouncycastle.asn1.ASN1Set; import repack.org.bouncycastle.asn1.BEROctetStringGenerator; import repack.org.bouncycastle.asn1.BERSet; import repack.org.bouncycastle.asn1.DEREncodable; import repack.org.bouncycastle.asn1.DERSet; import repack.org.bouncycastle.asn1.DERTaggedObject; import repack.org.bouncycastle.asn1.cms.ContentInfo; import repack.org.bouncycastle.asn1.cms.IssuerAndSerialNumber; import repack.org.bouncycastle.asn1.x509.CertificateList; import repack.org.bouncycastle.asn1.x509.TBSCertificateStructure; import repack.org.bouncycastle.asn1.x509.X509CertificateStructure; import repack.org.bouncycastle.cert.X509AttributeCertificateHolder; import repack.org.bouncycastle.cert.X509CRLHolder; import repack.org.bouncycastle.cert.X509CertificateHolder; import repack.org.bouncycastle.util.Store; import repack.org.bouncycastle.util.io.Streams; import repack.org.bouncycastle.util.io.TeeInputStream; import repack.org.bouncycastle.util.io.TeeOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; import java.security.cert.CRLException; import java.security.cert.CertStore; import java.security.cert.CertStoreException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; class CMSUtils { private static final Runtime RUNTIME = Runtime.getRuntime(); static int getMaximumMemory() { long maxMem = RUNTIME.maxMemory(); if(maxMem > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return (int) maxMem; } static ContentInfo readContentInfo( byte[] input) throws CMSException { // enforce limit checking as from a byte array return readContentInfo(new ASN1InputStream(input)); } static ContentInfo readContentInfo( InputStream input) throws CMSException { // enforce some limit checking return readContentInfo(new ASN1InputStream(input, getMaximumMemory())); } static List getCertificatesFromStore(CertStore certStore) throws CertStoreException, CMSException { List certs = new ArrayList(); try { for(Iterator it = certStore.getCertificates(null).iterator(); it.hasNext(); ) { X509Certificate c = (X509Certificate) it.next(); certs.add(X509CertificateStructure.getInstance( ASN1Object.fromByteArray(c.getEncoded()))); } return certs; } catch(IllegalArgumentException e) { throw new CMSException("error processing certs", e); } catch(IOException e) { throw new CMSException("error processing certs", e); } catch(CertificateEncodingException e) { throw new CMSException("error encoding certs", e); } } static List getCertificatesFromStore(Store certStore) throws CMSException { List certs = new ArrayList(); try { for(Iterator it = certStore.getMatches(null).iterator(); it.hasNext(); ) { X509CertificateHolder c = (X509CertificateHolder) it.next(); certs.add(c.toASN1Structure()); } return certs; } catch(ClassCastException e) { throw new CMSException("error processing certs", e); } } static List getAttributeCertificatesFromStore(Store attrStore) throws CMSException { List certs = new ArrayList(); try { for(Iterator it = attrStore.getMatches(null).iterator(); it.hasNext(); ) { X509AttributeCertificateHolder attrCert = (X509AttributeCertificateHolder) it.next(); certs.add(new DERTaggedObject(false, 2, attrCert.toASN1Structure())); } return certs; } catch(ClassCastException e) { throw new CMSException("error processing certs", e); } } static List getCRLsFromStore(CertStore certStore) throws CertStoreException, CMSException { List crls = new ArrayList(); try { for(Iterator it = certStore.getCRLs(null).iterator(); it.hasNext(); ) { X509CRL c = (X509CRL) it.next(); crls.add(CertificateList.getInstance(ASN1Object.fromByteArray(c.getEncoded()))); } return crls; } catch(IllegalArgumentException e) { throw new CMSException("error processing crls", e); } catch(IOException e) { throw new CMSException("error processing crls", e); } catch(CRLException e) { throw new CMSException("error encoding crls", e); } } static List getCRLsFromStore(Store crlStore) throws CMSException { List certs = new ArrayList(); try { for(Iterator it = crlStore.getMatches(null).iterator(); it.hasNext(); ) { X509CRLHolder c = (X509CRLHolder) it.next(); certs.add(c.toASN1Structure()); } return certs; } catch(ClassCastException e) { throw new CMSException("error processing certs", e); } } static ASN1Set createBerSetFromList(List derObjects) { ASN1EncodableVector v = new ASN1EncodableVector(); for(Iterator it = derObjects.iterator(); it.hasNext(); ) { v.add((DEREncodable) it.next()); } return new BERSet(v); } static ASN1Set createDerSetFromList(List derObjects) { ASN1EncodableVector v = new ASN1EncodableVector(); for(Iterator it = derObjects.iterator(); it.hasNext(); ) { v.add((DEREncodable) it.next()); } return new DERSet(v); } static OutputStream createBEROctetOutputStream(OutputStream s, int tagNo, boolean isExplicit, int bufferSize) throws IOException { BEROctetStringGenerator octGen = new BEROctetStringGenerator(s, tagNo, isExplicit); if(bufferSize != 0) { return octGen.getOctetOutputStream(new byte[bufferSize]); } return octGen.getOctetOutputStream(); } static TBSCertificateStructure getTBSCertificateStructure( X509Certificate cert) { try { return TBSCertificateStructure.getInstance( ASN1Object.fromByteArray(cert.getTBSCertificate())); } catch(Exception e) { throw new IllegalArgumentException( "can't extract TBS structure from this cert"); } } static IssuerAndSerialNumber getIssuerAndSerialNumber(X509Certificate cert) { TBSCertificateStructure tbsCert = getTBSCertificateStructure(cert); return new IssuerAndSerialNumber(tbsCert.getIssuer(), tbsCert.getSerialNumber().getValue()); } private static ContentInfo readContentInfo( ASN1InputStream in) throws CMSException { try { return ContentInfo.getInstance(in.readObject()); } catch(IOException e) { throw new CMSException("IOException reading content.", e); } catch(ClassCastException e) { throw new CMSException("Malformed content.", e); } catch(IllegalArgumentException e) { throw new CMSException("Malformed content.", e); } } public static byte[] streamToByteArray( InputStream in) throws IOException { return Streams.readAll(in); } public static byte[] streamToByteArray( InputStream in, int limit) throws IOException { return Streams.readAllLimited(in, limit); } public static Provider getProvider(String providerName) throws NoSuchProviderException { if(providerName != null) { Provider prov = Security.getProvider(providerName); if(prov != null) { return prov; } throw new NoSuchProviderException("provider " + providerName + " not found."); } return null; } static InputStream attachDigestsToInputStream(Collection digests, InputStream s) { InputStream result = s; Iterator it = digests.iterator(); while(it.hasNext()) { MessageDigest digest = (MessageDigest) it.next(); result = new TeeInputStream(result, new DigOutputStream(digest)); } return result; } static OutputStream attachDigestsToOutputStream(Collection digests, OutputStream s) { OutputStream result = s; Iterator it = digests.iterator(); while(it.hasNext()) { MessageDigest digest = (MessageDigest) it.next(); result = getSafeTeeOutputStream(result, new DigOutputStream(digest)); } return result; } static OutputStream attachSignersToOutputStream(Collection signers, OutputStream s) { OutputStream result = s; Iterator it = signers.iterator(); while(it.hasNext()) { SignerInfoGenerator signerGen = (SignerInfoGenerator) it.next(); result = getSafeTeeOutputStream(result, signerGen.getCalculatingOutputStream()); } return result; } static OutputStream getSafeOutputStream(OutputStream s) { return s == null ? new NullOutputStream() : s; } static OutputStream getSafeTeeOutputStream(OutputStream s1, OutputStream s2) { return s1 == null ? getSafeOutputStream(s2) : s2 == null ? getSafeOutputStream(s1) : new TeeOutputStream( s1, s2); } }
SafetyCulture/DroidText
app/src/main/java/bouncycastle/repack/org/bouncycastle/cms/CMSUtils.java
Java
lgpl-3.0
8,921
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Core3: ForageArea Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Core3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pub-attribs">Public Attributes</a> &#124; <a href="#pro-attribs">Protected Attributes</a> &#124; <a href="#pro-static-attribs">Static Protected Attributes</a> &#124; <a href="class_forage_area-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">ForageArea Class Reference</div> </div> </div><!--header--> <div class="contents"> <p><code>#include &lt;<a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for ForageArea:</div> <div class="dyncontent"> <div class="center"> <img src="class_forage_area.png" usemap="#ForageArea_map" alt=""/> <map id="ForageArea_map" name="ForageArea_map"> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a7bf05b07948a7b5ed497dacc0bf24f7e"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#a7bf05b07948a7b5ed497dacc0bf24f7e">ForageArea</a> (short playerX, short playerY, const String &amp;plt)</td></tr> <tr class="separator:a7bf05b07948a7b5ed497dacc0bf24f7e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a8eca806fd78689ae2f1dfc972589fba1"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#a8eca806fd78689ae2f1dfc972589fba1">checkPermission</a> (short playerX, short playerY, const String &amp;playerPlanet)</td></tr> <tr class="separator:a8eca806fd78689ae2f1dfc972589fba1"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a> Public Attributes</h2></td></tr> <tr class="memitem:a867c75633da0083eaa072af8bd8fad60"><td class="memItemLeft" align="right" valign="top">uint8&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#a867c75633da0083eaa072af8bd8fad60">uses</a></td></tr> <tr class="separator:a867c75633da0083eaa072af8bd8fad60"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-attribs"></a> Protected Attributes</h2></td></tr> <tr class="memitem:a7d14fc12e6e96cceb80129f3357f0be1"><td class="memItemLeft" align="right" valign="top">String&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#a7d14fc12e6e96cceb80129f3357f0be1">planet</a></td></tr> <tr class="separator:a7d14fc12e6e96cceb80129f3357f0be1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a411cea16f8adfabf0d89a5ca4d3d2fd7"><td class="memItemLeft" align="right" valign="top">short&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#a411cea16f8adfabf0d89a5ca4d3d2fd7">xCoord</a></td></tr> <tr class="separator:a411cea16f8adfabf0d89a5ca4d3d2fd7"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:afef2090ad1029ad19f9419989a02e0e8"><td class="memItemLeft" align="right" valign="top">short&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#afef2090ad1029ad19f9419989a02e0e8">yCoord</a></td></tr> <tr class="separator:afef2090ad1029ad19f9419989a02e0e8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac4fcab190d2b5d8964854c2ad38914be"><td class="memItemLeft" align="right" valign="top">Time&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#ac4fcab190d2b5d8964854c2ad38914be">expiration</a></td></tr> <tr class="separator:ac4fcab190d2b5d8964854c2ad38914be"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-static-attribs"></a> Static Protected Attributes</h2></td></tr> <tr class="memitem:a9e9e328a71e39907d7375cc88a971763"><td class="memItemLeft" align="right" valign="top">static const uint8&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#a9e9e328a71e39907d7375cc88a971763">SIZE</a> = 10</td></tr> <tr class="separator:a9e9e328a71e39907d7375cc88a971763"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a29abbcceb878bc2dd948c0fc3288123c"><td class="memItemLeft" align="right" valign="top">static const uint8&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_forage_area.html#a29abbcceb878bc2dd948c0fc3288123c">EXPIRE</a> = 30</td></tr> <tr class="separator:a29abbcceb878bc2dd948c0fc3288123c"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00012">12</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> </div><h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="a7bf05b07948a7b5ed497dacc0bf24f7e"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">ForageArea::ForageArea </td> <td>(</td> <td class="paramtype">short&#160;</td> <td class="paramname"><em>playerX</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">short&#160;</td> <td class="paramname"><em>playerY</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const String &amp;&#160;</td> <td class="paramname"><em>plt</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00027">27</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>References <a class="el" href="_forage_area_8h_source.html#l00021">expiration</a>, <a class="el" href="_forage_area_8h_source.html#l00017">EXPIRE</a>, <a class="el" href="_forage_area_8h_source.html#l00018">planet</a>, <a class="el" href="_forage_area_8h_source.html#l00025">uses</a>, <a class="el" href="_forage_area_8h_source.html#l00019">xCoord</a>, and <a class="el" href="_forage_area_8h_source.html#l00020">yCoord</a>.</p> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="a8eca806fd78689ae2f1dfc972589fba1"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">int ForageArea::checkPermission </td> <td>(</td> <td class="paramtype">short&#160;</td> <td class="paramname"><em>playerX</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">short&#160;</td> <td class="paramname"><em>playerY</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const String &amp;&#160;</td> <td class="paramname"><em>playerPlanet</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00035">35</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>References <a class="el" href="_forage_area_8h_source.html#l00021">expiration</a>, <a class="el" href="_forage_area_8h_source.html#l00018">planet</a>, <a class="el" href="_forage_area_8h_source.html#l00016">SIZE</a>, <a class="el" href="_forage_area_8h_source.html#l00025">uses</a>, <a class="el" href="_forage_area_8h_source.html#l00019">xCoord</a>, and <a class="el" href="_forage_area_8h_source.html#l00020">yCoord</a>.</p> </div> </div> <h2 class="groupheader">Member Data Documentation</h2> <a class="anchor" id="ac4fcab190d2b5d8964854c2ad38914be"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">Time ForageArea::expiration</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00021">21</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>Referenced by <a class="el" href="_forage_area_8h_source.html#l00035">checkPermission()</a>, and <a class="el" href="_forage_area_8h_source.html#l00027">ForageArea()</a>.</p> </div> </div> <a class="anchor" id="a29abbcceb878bc2dd948c0fc3288123c"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">const uint8 ForageArea::EXPIRE = 30</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">static</span><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00017">17</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>Referenced by <a class="el" href="_forage_area_8h_source.html#l00027">ForageArea()</a>.</p> </div> </div> <a class="anchor" id="a7d14fc12e6e96cceb80129f3357f0be1"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">String ForageArea::planet</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00018">18</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>Referenced by <a class="el" href="_forage_area_8h_source.html#l00035">checkPermission()</a>, and <a class="el" href="_forage_area_8h_source.html#l00027">ForageArea()</a>.</p> </div> </div> <a class="anchor" id="a9e9e328a71e39907d7375cc88a971763"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">const uint8 ForageArea::SIZE = 10</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">static</span><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00016">16</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>Referenced by <a class="el" href="_forage_area_8h_source.html#l00035">checkPermission()</a>.</p> </div> </div> <a class="anchor" id="a867c75633da0083eaa072af8bd8fad60"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">uint8 ForageArea::uses</td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00025">25</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>Referenced by <a class="el" href="_forage_area_8h_source.html#l00035">checkPermission()</a>, and <a class="el" href="_forage_area_8h_source.html#l00027">ForageArea()</a>.</p> </div> </div> <a class="anchor" id="a411cea16f8adfabf0d89a5ca4d3d2fd7"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">short ForageArea::xCoord</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00019">19</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>Referenced by <a class="el" href="_forage_area_8h_source.html#l00035">checkPermission()</a>, and <a class="el" href="_forage_area_8h_source.html#l00027">ForageArea()</a>.</p> </div> </div> <a class="anchor" id="afef2090ad1029ad19f9419989a02e0e8"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">short ForageArea::yCoord</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_forage_area_8h_source.html#l00020">20</a> of file <a class="el" href="_forage_area_8h_source.html">ForageArea.h</a>.</p> <p>Referenced by <a class="el" href="_forage_area_8h_source.html#l00035">checkPermission()</a>, and <a class="el" href="_forage_area_8h_source.html#l00027">ForageArea()</a>.</p> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li>/Users/victor/git/Core3Mda/MMOCoreORB/src/server/zone/objects/area/<a class="el" href="_forage_area_8h_source.html">ForageArea.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Oct 15 2013 17:29:27 for Core3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
kidaa/Awakening-Core3
doc/html/class_forage_area.html
HTML
lgpl-3.0
16,461
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import com.google.common.collect.Maps; import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleStatus; import org.sonar.core.qualityprofile.db.ActiveRuleDto; import org.sonar.core.qualityprofile.db.ActiveRuleKey; import org.sonar.core.qualityprofile.db.ActiveRuleParamDto; import org.sonar.core.qualityprofile.db.QualityProfileDto; import org.sonar.core.rule.RuleDto; import org.sonar.core.rule.RuleParamDto; import org.sonar.server.exceptions.BadRequestException; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import java.util.Collection; import java.util.Date; import java.util.Map; class RuleActivatorContext { private final Date initDate = new Date(); private RuleDto rule; private final Map<String, RuleParamDto> ruleParams = Maps.newHashMap(); private QualityProfileDto profile; private ActiveRuleDto activeRule, parentActiveRule; private final Map<String, ActiveRuleParamDto> activeRuleParams = Maps.newHashMap(), parentActiveRuleParams = Maps.newHashMap(); RuleActivatorContext() { } ActiveRuleKey activeRuleKey() { return ActiveRuleKey.of(profile.getKee(), rule.getKey()); } RuleDto rule() { return rule; } RuleActivatorContext setRule(RuleDto rule) { this.rule = rule; return this; } Date getInitDate() { return initDate; } Map<String, RuleParamDto> ruleParamsByKeys() { return ruleParams; } Collection<RuleParamDto> ruleParams() { return ruleParams.values(); } RuleActivatorContext setRuleParams(Collection<RuleParamDto> ruleParams) { this.ruleParams.clear(); for (RuleParamDto ruleParam : ruleParams) { this.ruleParams.put(ruleParam.getName(), ruleParam); } return this; } QualityProfileDto profile() { return profile; } RuleActivatorContext setProfile(QualityProfileDto profile) { this.profile = profile; return this; } @CheckForNull ActiveRuleDto activeRule() { return activeRule; } RuleActivatorContext setActiveRule(@Nullable ActiveRuleDto a) { this.activeRule = a; return this; } @CheckForNull ActiveRuleDto parentActiveRule() { return parentActiveRule; } RuleActivatorContext setParentActiveRule(@Nullable ActiveRuleDto a) { this.parentActiveRule = a; return this; } @CheckForNull String requestParamValue(RuleActivation request, String key) { if (rule.getTemplateId() != null) { return null; } return request.getParameters().get(key); } @CheckForNull String currentParamValue(String key) { ActiveRuleParamDto param = activeRuleParams.get(key); return param != null ? param.getValue() : null; } @CheckForNull String parentParamValue(String key) { ActiveRuleParamDto param = parentActiveRuleParams.get(key); return param != null ? param.getValue() : null; } @CheckForNull String defaultParamValue(String key) { RuleParamDto param = ruleParams.get(key); return param != null ? param.getDefaultValue() : null; } @CheckForNull String currentSeverity() { return activeRule != null ? activeRule.getSeverityString() : null; } @CheckForNull String parentSeverity() { return parentActiveRule != null ? parentActiveRule.getSeverityString() : null; } @CheckForNull String defaultSeverity() { return rule.getSeverityString(); } Map<String, ActiveRuleParamDto> activeRuleParamsAsMap() { return activeRuleParams; } Map<String, String> activeRuleParamsAsStringMap() { Map<String, String> params = Maps.newHashMap(); for (Map.Entry<String, ActiveRuleParamDto> param : activeRuleParams.entrySet()) { params.put(param.getKey(), param.getValue().getValue()); } return params; } RuleActivatorContext setActiveRuleParams(@Nullable Collection<ActiveRuleParamDto> a) { activeRuleParams.clear(); if (a != null) { for (ActiveRuleParamDto ar : a) { this.activeRuleParams.put(ar.getKey(), ar); } } return this; } RuleActivatorContext setParentActiveRuleParams(@Nullable Collection<ActiveRuleParamDto> a) { parentActiveRuleParams.clear(); if (a != null) { for (ActiveRuleParamDto ar : a) { this.parentActiveRuleParams.put(ar.getKey(), ar); } } return this; } /** * True if trying to override an inherited rule but with exactly the same values */ boolean isSameAsParent(ActiveRuleChange change) { if (parentActiveRule == null) { return false; } if (!StringUtils.equals(change.getSeverity(), parentActiveRule.getSeverityString())) { return false; } for (Map.Entry<String, String> entry : change.getParameters().entrySet()) { if (entry.getValue() != null && !entry.getValue().equals(parentParamValue(entry.getKey()))) { return false; } } return true; } boolean isSame(ActiveRuleChange change) { ActiveRule.Inheritance inheritance = change.getInheritance(); if (inheritance != null && !inheritance.name().equals(activeRule.getInheritance())) { return false; } String severity = change.getSeverity(); if (severity != null && !severity.equals(activeRule.getSeverityString())) { return false; } for (Map.Entry<String, String> changeParam : change.getParameters().entrySet()) { ActiveRuleParamDto param = activeRuleParams.get(changeParam.getKey()); if (changeParam.getValue()==null && param != null && param.getValue()!=null) { return false; } if (changeParam.getValue()!=null && (param == null || !StringUtils.equals(changeParam.getValue(), param.getValue()))) { return false; } } return true; } void verifyForActivation() { if (RuleStatus.REMOVED == rule.getStatus()) { throw new BadRequestException("Rule was removed: " + rule.getKey()); } if (rule.isTemplate()) { throw new BadRequestException("Rule template can't be activated on a Quality profile: " + rule.getKey()); } if (rule.getKey().isManual()) { throw new BadRequestException("Manual rule can't be activated on a Quality profile: " + rule.getKey()); } if (!profile.getLanguage().equals(rule.getLanguage())) { throw new BadRequestException(String.format("Rule %s and profile %s have different languages", rule.getKey(), profile.getKey())); } } }
jblievremont/sonarqube
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivatorContext.java
Java
lgpl-3.0
7,290
/* This source file is part of KBEngine For the latest info, see http://www.kbengine.org/ Copyright (c) 2008-2016 KBEngine. KBEngine 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. KBEngine 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 KBEngine. If not, see <http://www.gnu.org/licenses/>. */ #ifndef KBE_ENDPOINT_H #define KBE_ENDPOINT_H #include "common/common.h" #include "common/objectpool.h" #include "helper/debug_helper.h" #include "network/address.h" #include "network/common.h" namespace KBEngine { namespace Network { class Bundle; class EndPoint : public PoolObject { public: typedef KBEShared_ptr< SmartPoolObject< EndPoint > > SmartPoolObjectPtr; static SmartPoolObjectPtr createSmartPoolObj(); static ObjectPool<EndPoint>& ObjPool(); static EndPoint* createPoolObject(); static void reclaimPoolObject(EndPoint* obj); static void destroyObjPool(); void onReclaimObject(); virtual size_t getPoolObjectBytes() { size_t bytes = sizeof(KBESOCKET) + address_.getPoolObjectBytes(); return bytes; } EndPoint(Address address); EndPoint(u_int32_t networkAddr = 0, u_int16_t networkPort = 0); virtual ~EndPoint(); INLINE operator KBESOCKET() const; static void initNetwork(); INLINE bool good() const; void socket(int type); INLINE KBESOCKET socket() const; INLINE void setFileDescriptor(int fd); INLINE int joinMulticastGroup(u_int32_t networkAddr); INLINE int quitMulticastGroup(u_int32_t networkAddr); INLINE int close(); INLINE int setnonblocking(bool nonblocking); INLINE int setbroadcast(bool broadcast); INLINE int setreuseaddr(bool reuseaddr); INLINE int setkeepalive(bool keepalive); INLINE int setnodelay(bool nodelay = true); INLINE int setlinger(uint16 onoff, uint16 linger); INLINE int bind(u_int16_t networkPort = 0, u_int32_t networkAddr = INADDR_ANY); INLINE int listen(int backlog = 5); INLINE int connect(u_int16_t networkPort, u_int32_t networkAddr = INADDR_BROADCAST, bool autosetflags = true); INLINE int connect(bool autosetflags = true); INLINE EndPoint* accept(u_int16_t * networkPort = NULL, u_int32_t * networkAddr = NULL, bool autosetflags = true); INLINE int send(const void * gramData, int gramSize); void send(Bundle * pBundle); void sendto(Bundle * pBundle, u_int16_t networkPort, u_int32_t networkAddr = BROADCAST); INLINE int recv(void * gramData, int gramSize); bool recvAll(void * gramData, int gramSize); INLINE uint32 getRTT(); INLINE int getInterfaceFlags(char * name, int & flags); INLINE int getInterfaceAddress(const char * name, u_int32_t & address); INLINE int getInterfaceNetmask(const char * name, u_int32_t & netmask); bool getInterfaces(std::map< u_int32_t, std::string > &interfaces); int findIndicatedInterface(const char * spec, u_int32_t & address); int findDefaultInterface(char * name, int buffsize); int getInterfaceAddressByName(const char * name, u_int32_t & address); int getInterfaceAddressByMAC(const char * mac, u_int32_t & address); int getDefaultInterfaceAddress(u_int32_t & address); int getBufferSize(int optname) const; bool setBufferSize(int optname, int size); INLINE int getlocaladdress(u_int16_t * networkPort, u_int32_t * networkAddr) const; INLINE int getremoteaddress(u_int16_t * networkPort, u_int32_t * networkAddr) const; Network::Address getLocalAddress() const; Network::Address getRemoteAddress() const; bool getClosedPort(Network::Address & closedPort); INLINE const char * c_str() const; INLINE int getremotehostname(std::string * name) const; INLINE int sendto(void * gramData, int gramSize, u_int16_t networkPort, u_int32_t networkAddr = BROADCAST); INLINE int sendto(void * gramData, int gramSize, struct sockaddr_in & sin); INLINE int recvfrom(void * gramData, int gramSize, u_int16_t * networkPort, u_int32_t * networkAddr); INLINE int recvfrom(void * gramData, int gramSize, struct sockaddr_in & sin); INLINE const Address& addr() const; INLINE void addr(const Address& newAddress); INLINE void addr(u_int16_t newNetworkPort, u_int32_t newNetworkAddress); bool waitSend(); protected: KBESOCKET socket_; Address address_; }; } } #ifdef CODE_INLINE #include "endpoint.inl" #endif #endif // KBE_ENDPOINT_H
Orav/kbengine
kbe/src/lib/network/endpoint.h
C
lgpl-3.0
4,821
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; public interface Scheduler { void schedule(); /** * Stops all processes and waits for them to be down. */ void terminate(); /** * Blocks until all processes are down */ void awaitTermination(); }
lbndev/sonarqube
server/sonar-process-monitor/src/main/java/org/sonar/application/Scheduler.java
Java
lgpl-3.0
1,096
/*************************************************************************** * Copyright (C) 2006 by Dominik Seichter * * domseichter@web.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library 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 Library 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. * * * * In addition, as a special exception, the copyright holders give * * permission to link the code of portions of this program with the * * OpenSSL library under certain conditions as described in each * * individual source file, and distribute linked combinations * * including the two. * * You must obey the GNU General Public License in all respects * * for all of the code used other than OpenSSL. If you modify * * file(s) with this exception, you may extend this exception to your * * version of the file(s), but you are not obligated to do so. If you * * do not wish to do so, delete this exception statement from your * * version. If you delete this exception statement from all source * * files in the program, then also delete it here. * ***************************************************************************/ /* * WARNING: This file was automatically generated by Beautiful Capi! * Do not edit this file! Please edit the source API description. * * Beautiful Capi project: * https://github.com/PetrPPetrov/beautiful-capi * * PoDoFo API description project: * https://github.com/GkmSoft/podofo-capi */ virtual ~PdfAction() {} virtual bool HasScript() const = 0; virtual PoDoFo::EPdfAction GetType() const = 0; virtual void AddToDictionary(PoDoFo::PdfDictionary dictionary) const = 0; virtual PoDoFo::PdfString GetURI() const = 0; virtual void SetURI(PoDoFo::PdfString uri) = 0; virtual PoDoFo::PdfString GetScript() const = 0; virtual void SetScript(PoDoFo::PdfString script) = 0;
GkmSoft/podofo-capi
src/snippets/PoDoFo/PdfAction.h
C
lgpl-3.0
3,148
<?php /* * This file is part of the Blast Project package. * * Copyright (C) 2015-2017 Libre Informatique * * This file is licenced under the GNU LGPL v3. * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ namespace Sil\Bundle\StockBundle\Domain\Repository\InMemory; use Sil\Bundle\StockBundle\Domain\Repository\MovementRepositoryInterface; use Sil\Bundle\StockBundle\Domain\Entity\Movement; /** * @author Glenn Cavarlé <glenn.cavarle@libre-informatique.fr> */ class MovementRepository extends InMemoryRepository implements MovementRepositoryInterface { public function __construct() { parent::__construct(Movement::class); } }
sil-project/StockBundle
src/Domain/Repository/InMemory/MovementRepository.php
PHP
lgpl-3.0
743
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_CANCELCAPACITYRESERVATIONRESPONSE_H #define QTAWS_CANCELCAPACITYRESERVATIONRESPONSE_H #include "ec2response.h" #include "cancelcapacityreservationrequest.h" namespace QtAws { namespace EC2 { class CancelCapacityReservationResponsePrivate; class QTAWSEC2_EXPORT CancelCapacityReservationResponse : public Ec2Response { Q_OBJECT public: CancelCapacityReservationResponse(const CancelCapacityReservationRequest &request, QNetworkReply * const reply, QObject * const parent = 0); virtual const CancelCapacityReservationRequest * request() const Q_DECL_OVERRIDE; protected slots: virtual void parseSuccess(QIODevice &response) Q_DECL_OVERRIDE; private: Q_DECLARE_PRIVATE(CancelCapacityReservationResponse) Q_DISABLE_COPY(CancelCapacityReservationResponse) }; } // namespace EC2 } // namespace QtAws #endif
pcolby/libqtaws
src/ec2/cancelcapacityreservationresponse.h
C
lgpl-3.0
1,582
/** * Copyright © 2014 Instituto Superior Técnico * * This file is part of FenixEdu CMS. * * FenixEdu CMS 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. * * FenixEdu CMS 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 FenixEdu CMS. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.cms.ui; import org.fenixedu.bennu.core.domain.Bennu; import org.fenixedu.bennu.spring.portal.SpringFunctionality; import org.fenixedu.cms.domain.Site; import org.fenixedu.commons.StringNormalizer; import org.fenixedu.commons.i18n.LocalizedString; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; import pt.ist.fenixframework.Atomic; import pt.ist.fenixframework.FenixFramework; import com.google.common.base.Strings; @SpringFunctionality(app = AdminSites.class, title = "application.create-site.title", accessGroup = "#managers") @RequestMapping("/cms/sites/new") public class CreateSite { @RequestMapping(method = RequestMethod.GET) public String create(Model model) { model.addAttribute("templates", Site.getTemplates()); model.addAttribute("folders", Bennu.getInstance().getCmsFolderSet()); return "fenixedu-cms/create"; } @RequestMapping(method = RequestMethod.POST) public RedirectView create(Model model, @RequestParam LocalizedString name, @RequestParam LocalizedString description, @RequestParam String template, @RequestParam(required = false, defaultValue = "false") Boolean published, @RequestParam String folder, @RequestParam(required = false) boolean embedded, RedirectAttributes redirectAttributes) { if (name.isEmpty()) { redirectAttributes.addFlashAttribute("emptyName", true); return new RedirectView("/cms/sites/new", true); } else { if (published == null) { published = false; } createSite(name, description, published, template, folder, embedded); return new RedirectView("/cms/sites/", true); } } @Atomic private void createSite(LocalizedString name, LocalizedString description, boolean published, String template, String folder, boolean embedded) { Site site = new Site(); site.setBennu(Bennu.getInstance()); if (!Strings.isNullOrEmpty(folder)) { site.setFolder(FenixFramework.getDomainObject(folder)); } site.setEmbedded(embedded); site.setDescription(description); site.setName(name); site.setSlug(StringNormalizer.slugify(name.getContent())); site.updateMenuFunctionality(); site.setPublished(published); if (!template.equals("null")) { Site.templateFor(template).makeIt(site); } } }
jcarvalho/fenixedu-cms
src/main/java/org/fenixedu/cms/ui/CreateSite.java
Java
lgpl-3.0
3,540
using ToastNotifications; using ToastNotifications.Core; namespace CustomNotificationsExample.CustomMessage { public static class CustomMessageExtensions { public static void ShowCustomMessage(this Notifier notifier, string title, string message, MessageOptions messageOptions = null) { notifier.Notify(() => new CustomNotification(title, message, messageOptions)); } } }
raflop/ToastNotifications
Src/Examples/CustomNotificationsExample/CustomMessage/CustomMessageExtensions.cs
C#
lgpl-3.0
462
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program 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. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\block; use pocketmine\block\utils\BlockDataSerializer; use pocketmine\block\utils\HorizontalFacingTrait; use pocketmine\block\utils\StairShape; use pocketmine\item\Item; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Facing; use pocketmine\math\Vector3; use pocketmine\player\Player; use pocketmine\world\BlockTransaction; class Stair extends Transparent{ use HorizontalFacingTrait; protected bool $upsideDown = false; protected StairShape $shape; public function __construct(BlockIdentifier $idInfo, string $name, BlockBreakInfo $breakInfo){ $this->shape = StairShape::STRAIGHT(); parent::__construct($idInfo, $name, $breakInfo); } protected function writeStateToMeta() : int{ return BlockDataSerializer::write5MinusHorizontalFacing($this->facing) | ($this->upsideDown ? BlockLegacyMetadata::STAIR_FLAG_UPSIDE_DOWN : 0); } public function readStateFromData(int $id, int $stateMeta) : void{ $this->facing = BlockDataSerializer::read5MinusHorizontalFacing($stateMeta); $this->upsideDown = ($stateMeta & BlockLegacyMetadata::STAIR_FLAG_UPSIDE_DOWN) !== 0; } public function getStateBitmask() : int{ return 0b111; } public function readStateFromWorld() : void{ parent::readStateFromWorld(); $clockwise = Facing::rotateY($this->facing, true); if(($backFacing = $this->getPossibleCornerFacing(false)) !== null){ $this->shape = $backFacing === $clockwise ? StairShape::OUTER_RIGHT() : StairShape::OUTER_LEFT(); }elseif(($frontFacing = $this->getPossibleCornerFacing(true)) !== null){ $this->shape = $frontFacing === $clockwise ? StairShape::INNER_RIGHT() : StairShape::INNER_LEFT(); }else{ $this->shape = StairShape::STRAIGHT(); } } public function isUpsideDown() : bool{ return $this->upsideDown; } /** @return $this */ public function setUpsideDown(bool $upsideDown) : self{ $this->upsideDown = $upsideDown; return $this; } public function getShape() : StairShape{ return $this->shape; } /** @return $this */ public function setShape(StairShape $shape) : self{ $this->shape = $shape; return $this; } protected function recalculateCollisionBoxes() : array{ $topStepFace = $this->upsideDown ? Facing::DOWN : Facing::UP; $bbs = [ AxisAlignedBB::one()->trim($topStepFace, 0.5) ]; $topStep = AxisAlignedBB::one() ->trim(Facing::opposite($topStepFace), 0.5) ->trim(Facing::opposite($this->facing), 0.5); if($this->shape->equals(StairShape::OUTER_LEFT()) || $this->shape->equals(StairShape::OUTER_RIGHT())){ $topStep->trim(Facing::rotateY($this->facing, $this->shape->equals(StairShape::OUTER_LEFT())), 0.5); }elseif($this->shape->equals(StairShape::INNER_LEFT()) || $this->shape->equals(StairShape::INNER_RIGHT())){ //add an extra cube $bbs[] = AxisAlignedBB::one() ->trim(Facing::opposite($topStepFace), 0.5) ->trim($this->facing, 0.5) //avoid overlapping with main step ->trim(Facing::rotateY($this->facing, $this->shape->equals(StairShape::INNER_LEFT())), 0.5); } $bbs[] = $topStep; return $bbs; } private function getPossibleCornerFacing(bool $oppositeFacing) : ?int{ $side = $this->getSide($oppositeFacing ? Facing::opposite($this->facing) : $this->facing); return ( $side instanceof Stair && $side->upsideDown === $this->upsideDown && Facing::axis($side->facing) !== Facing::axis($this->facing) //perpendicular ) ? $side->facing : null; } public function place(BlockTransaction $tx, Item $item, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector, ?Player $player = null) : bool{ if($player !== null){ $this->facing = $player->getHorizontalFacing(); } $this->upsideDown = (($clickVector->y > 0.5 && $face !== Facing::UP) || $face === Facing::DOWN); return parent::place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player); } }
pmmp/PocketMine-MP
src/block/Stair.php
PHP
lgpl-3.0
4,591
// -*- Mode:C++ -*- /************************************************************************\ * * * This file is part of AVANGO. * * * * Copyright 2007 - 2010 Fraunhofer-Gesellschaft zur Foerderung der * * angewandten Forschung (FhG), Munich, Germany. * * * * AVANGO 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, version 3. * * * * AVANGO is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with AVANGO. If not, see <http://www.gnu.org/licenses/>. * * * \************************************************************************/ #include <shade/types/Vec3Accessor.h> shade::types::TypeAccessor::HashValue shade::types::Vec3Accessor::m_hash; shade::types::TypeAccessor::HashType shade::types::Vec3Accessor::hash(void) const { return &m_hash; }
vrsys/avango
attic/avango-shade/core/src/types/Vec3Accessor.cpp
C++
lgpl-3.0
1,738
package com.bluevia.android.directory.parser; import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.util.Log; import com.bluevia.android.commons.parser.ParseException; import com.bluevia.android.commons.parser.xml.XmlParserSerializerUtils; import com.bluevia.android.directory.data.AccessInfo; /** * Xml parser for XmlDirectoryUserAccess entities. * * @author Telefonica I+D * */ class XmlDirectoryAccessInfoParser implements DirectoryEntityParser { private static final String TAG = "XmlDirectoryUserAccessParser"; /** * @see com.bluevia.android.commons.parser.IParser#parse(java.io.InputStream) */ public AccessInfo parse(XmlPullParser parser) throws ParseException { AccessInfo userAccessInfo= new AccessInfo(); int eventType; try { eventType = parser.next(); Log.e(TAG, "Expected event START_TAG: Actual event: " + XmlPullParser.TYPES[eventType]); } catch (XmlPullParserException xppe) { throw new ParseException("Could not read next event.", xppe); } catch (IOException ioe) { throw new ParseException("Could not read next event.", ioe); } while (eventType != XmlPullParser.END_DOCUMENT){ String nameSpace = parser.getName(); switch (eventType){ case XmlPullParser.END_TAG: if (XmlConstants.ACCESSINFO.equals(nameSpace)) { return userAccessInfo; } break; case XmlPullParser.START_TAG: if(nameSpace.equals(XmlConstants.ACCESSINFO_ACCESSTYPE)){ try{ userAccessInfo.setAccessType(XmlParserSerializerUtils.getChildText(parser)); } catch(XmlPullParserException e){ throw new ParseException("Problem with getChild", e); } } if(nameSpace.equals(XmlConstants.ACCESSINFO_APN)){ try{ userAccessInfo.setAPN(XmlParserSerializerUtils.getChildText(parser)); }catch(XmlPullParserException e){ throw new ParseException("Problem with getChild", e); } } if(nameSpace.equals(XmlConstants.ACCESSINFO_ROAMING)){ try{ String roam = XmlParserSerializerUtils.getChildText(parser); if(roam.equals("yes")) userAccessInfo.setRoaming(true); else userAccessInfo.setRoaming(false); }catch(XmlPullParserException e){ throw new ParseException("Problem with getChild", e); } } } try{ eventType = parser.next(); }catch (XmlPullParserException e) { throw new ParseException("Could not read next event.", e); } catch (IOException e) { throw new ParseException("Could not read next event.", e); } } return null; } }
BlueVia/Official-Library-Android
library/src/com/bluevia/android/directory/parser/XmlDirectoryAccessInfoParser.java
Java
lgpl-3.0
3,255
#pragma once #include "../data.h" #include "../type.h" #include "../value.h" #include "stacktrace.h" #include <string> #include <memory> namespace sqf { namespace runtime { struct t_stacktrace : public type::extend<t_stacktrace> { t_stacktrace() : extend() {} static const std::string name() { return "VM-STACKTRACE"; } }; } namespace types { class d_stacktrace : public sqf::runtime::data { public: using data_type = sqf::runtime::t_stacktrace; private: sqf::runtime::diagnostics::stacktrace m_value; protected: bool do_equals(std::shared_ptr<sqf::runtime::data> other, bool invariant) const override { // A stacktrace is never equal to another stacktrace return false; } public: d_stacktrace() = default; d_stacktrace(sqf::runtime::diagnostics::stacktrace stacktrace) : m_value(stacktrace) {} std::string to_string_sqf() const override { return "'" + m_value.to_string() + "'"; } std::string to_string() const override { return m_value.to_string(); } sqf::runtime::type type() const override { return data_type(); } sqf::runtime::diagnostics::stacktrace value() const { return m_value; } void value(sqf::runtime::diagnostics::stacktrace stacktrace) { m_value = stacktrace; } operator sqf::runtime::diagnostics::stacktrace() { return m_value; } }; template<> inline std::shared_ptr<sqf::runtime::data> to_data<sqf::runtime::diagnostics::stacktrace>(sqf::runtime::diagnostics::stacktrace str) { return std::make_shared<d_stacktrace>(str); } } }
X39/sqf-vm
src/runtime/diagnostics/d_stacktrace.h
C
lgpl-3.0
1,563
package pdemanget.javafx.protocol; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import org.apache.commons.io.input.ReaderInputStream; import com.github.sommeri.less4j.LessCompiler; import com.github.sommeri.less4j.core.ThreadUnsafeLessCompiler; /** * merge de https://github.com/SomMeri/less4j * et * https://tomsondev.bestsolution.at/2013/08/07/using-less-in-javafx/ * et * http://stackoverflow.com/questions/24704515/in-javafx-8-can-i-provide-a-stylesheet-from-a-string * * see also * <groupId>org.lesscss</groupId> <artifactId>lesscss-maven-plugin</artifactId> <version>1.3.3</version> */ public class LessLoader { // ... public String loadLess (URL lessFile) { try { // StringBuilder lessContent = new StringBuilder(); // readFileContent(lessFile, lessContent); // // Object rv = ((Invocable)engine).invokeFunction("parseString", lessContent.toString()); // File f = File.createTempFile("less_", ".css"); // f.deleteOnExit(); // // try(FileOutputStream out = new FileOutputStream(f) ) { // out.write(rv.toString().getBytes()); // out.close(); // } // return f.toURI().toURL(); LessCompiler compiler = new ThreadUnsafeLessCompiler(); return compiler.compile(lessFile).getCss(); } catch (Exception e) { throw new RuntimeException(e); } } public void initialize () { // to be done only once. URL.setURLStreamHandlerFactory(new StringURLStreamHandlerFactory()); } private class StringURLConnection extends URLConnection { public StringURLConnection (URL url) { super(url); } @Override public void connect () throws IOException { } @Override public InputStream getInputStream () throws IOException { String file = url.getFile(); long start=System.currentTimeMillis(); String css = loadLess(getClass().getResource(file)); System.out.println("loadLess:"+(System.currentTimeMillis()-start)); StringReader reader = new StringReader(css); return new ReaderInputStream(reader); } } private class StringURLStreamHandlerFactory implements URLStreamHandlerFactory { URLStreamHandler streamHandler = new URLStreamHandler() { @Override protected URLConnection openConnection (URL url) throws IOException { if (url.toString().toLowerCase().endsWith(".less")) { return new StringURLConnection(url); } throw new FileNotFoundException(); } }; @Override public URLStreamHandler createURLStreamHandler (String protocol) { if ("internal".equals(protocol)) { return streamHandler; } return null; } } }
pdemanget/examples
java/javaFx/src/main/java/pdemanget/javafx/protocol/LessLoader.java
Java
lgpl-3.0
2,912
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ SonarQube, open source software quality management tool. ~ Copyright (C) 2008-2014 SonarSource ~ mailto:contact AT sonarsource DOT com ~ ~ SonarQube 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. ~ ~ SonarQube is distributed in the hope that it will be useful, ~ but WITHOUT ANY WARRANTY; without even the implied warranty of ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ~ Lesser General Public License for more details. ~ ~ You should have received a copy of the GNU Lesser General Public License ~ along with this program; if not, write to the Free Software Foundation, ~ Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head profile="http://selenium-ide.openqa.org/profiles/test-case"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>should_display_quality_gates_page</title> </head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr> <td rowspan="1" colspan="3">should_display_quality_gates_page</td> </tr> </thead> <tbody> <tr> <td>open</td> <td>/sonar/quality_gates</td> <td></td> </tr> <tr> <td>waitForElementPresent</td> <td>css=.js-list a</td> <td></td> </tr> <tr> <td>click</td> <td>css=.js-list a</td> <td></td> </tr> <tr> <td>waitForElementPresent</td> <td>css=.js-conditions</td> <td></td> </tr> </tbody> </table> </body> </html>
vamsirajendra/sonarqube
it/it-tests/src/test/resources/qualityGate/QualityGateUiTest/should_display_quality_gates_page.html
HTML
lgpl-3.0
1,844
// Created file "Lib\src\Uuid\propkeys" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(PKEY_NetworkLocation, 0x28636aa6, 0x953d, 0x11d2, 0xb5, 0xd6, 0x00, 0xc0, 0x4f, 0xd9, 0x18, 0xd0);
Frankie-PellesC/fSDK
Lib/src/Uuid/propkeys0000033B.c
C
lgpl-3.0
453
/******************************************************************************* * Copyright (c) 2015 Open Software Solutions GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.html * * Contributors: * Open Software Solutions GmbH ******************************************************************************/ package org.oss.pdfreporter.compilers.jeval.functions; import org.oss.pdfreporter.converters.DecimalConverter; import org.oss.pdfreporter.uses.net.sourceforge.jeval.Evaluator; import org.oss.pdfreporter.uses.net.sourceforge.jeval.function.Function; import org.oss.pdfreporter.uses.net.sourceforge.jeval.function.FunctionConstants; import org.oss.pdfreporter.uses.net.sourceforge.jeval.function.FunctionException; import org.oss.pdfreporter.uses.net.sourceforge.jeval.function.FunctionResult; public class DateStringConverter implements Function { @Override public String getName() { return "dateString"; } @Override public FunctionResult execute(Evaluator evaluator, String arguments) throws FunctionException { String result = null; Long number = null; try { number = DecimalConverter.toDouble(arguments).longValue(); } catch (Exception e) { throw new FunctionException("Invalid argument.", e); } result = "(date)" + number.toString(); return new FunctionResult(result, FunctionConstants.FUNCTION_RESULT_TYPE_STRING); } }
OpenSoftwareSolutions/PDFReporter
pdfreporter-core/src/org/oss/pdfreporter/compilers/jeval/functions/DateStringConverter.java
Java
lgpl-3.0
1,587
<?php /** * Part of Windwalker Packages project. * * @copyright Copyright (C) 2021 __ORGANIZATION__. * @license __LICENSE__ */ declare(strict_types=1); namespace Windwalker\Uri; use Psr\Http\Message\UriFactoryInterface; use Psr\Http\Message\UriInterface; /** * The UriFactory class. */ class UriFactory implements UriFactoryInterface { /** * @inheritDoc */ public function createUri(string $uri = ''): UriInterface { return new Uri($uri); } }
ventoviro/windwalker
packages/uri/src/UriFactory.php
PHP
lgpl-3.0
493
/** * No8 Copyright (C) 2015 no8.io * * 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 no8.application; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import org.junit.Before; import org.junit.Test; public class ApplicationLoopTest { @Before public void before() { Application.resetCurrentApplication(); } @Test public void fakeApplicationRuns() throws InterruptedException, InstantiationException, IllegalAccessException { Launcher launch = new Launcher(FakeApplication.class, Collections.emptyMap()); assertThat(((FakeApplication) launch.application).loops()).isEqualTo(0); // kills the test after a while new Thread(() -> { try { Thread.sleep(110); } catch (Exception e) { e.printStackTrace(); } assertThat(launch.application.loop.isStarted()).isTrue(); launch.application.shutdown(); }).start(); launch.launch(); assertThat(((FakeApplication) launch.application).loops()).isNotEqualTo(0); } }
daniloqueiroz/no8
src/test/java/no8/application/ApplicationLoopTest.java
Java
lgpl-3.0
1,650
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Entities.Basics; using Signum.Entities; using Signum.Utilities; using System.Collections.ObjectModel; using System.Reflection; namespace Signum.Entities.Authorization { [Serializable] public class DefaultDictionary<K, A> { public DefaultDictionary(Func<K, A> defaultAllowed, Dictionary<K, A> overridesDictionary) { this.defaultAllowed = defaultAllowed; this.overrideDictionary = overridesDictionary; } readonly Dictionary<K, A> overrideDictionary; readonly Func<K, A> defaultAllowed; public A GetAllowed(K key) { if (overrideDictionary != null && overrideDictionary.TryGetValue(key, out A result)) return result; return defaultAllowed(key); } public Dictionary<K, A> OverrideDictionary { get { return overrideDictionary; } } public Func<K, A> DefaultAllowed { get { return defaultAllowed; } } } [Serializable] public class ConstantFunction<K, A> { internal A Allowed; public ConstantFunction(A allowed) { this.Allowed = allowed; } public A GetValue(K key) { return this.Allowed; } public override string ToString() { return "Constant {0}".FormatWith(Allowed); } } [Serializable] public class ConstantFunctionButEnums { internal TypeAllowedAndConditions Allowed; public ConstantFunctionButEnums(TypeAllowedAndConditions allowed) { this.Allowed = allowed; } public TypeAllowedAndConditions GetValue(Type type) { if (EnumEntity.Extract(type) != null) return new TypeAllowedAndConditions(TypeAllowed.Read); return Allowed; } public override string ToString() { return "Constant {0}".FormatWith(Allowed); } } [Serializable, InTypeScript(Undefined = false)] public abstract class BaseRulePack<T> : ModelEntity { [NotNullValidator] public Lite<RoleEntity> Role { get; internal set; } [HiddenProperty] public MergeStrategy MergeStrategy { get; set; } [HiddenProperty] public MList<Lite<RoleEntity>> SubRoles { get; set; } = new MList<Lite<RoleEntity>>(); [NotNullValidator] public string Strategy { get { return AuthAdminMessage._0of1.NiceToString().FormatWith( MergeStrategy.NiceToString(), SubRoles.IsNullOrEmpty() ? "∅ -> " + (MergeStrategy == MergeStrategy.Union ? AuthAdminMessage.Nothing : AuthAdminMessage.Everything).NiceToString() : SubRoles.CommaAnd()); } } [NotNullValidator] public MList<T> Rules { get; set; } = new MList<T>(); } [Serializable, InTypeScript(Undefined = false)] public abstract class AllowedRule<R, A> : ModelEntity { A allowedBase; [InTypeScript(Null = false)] public A AllowedBase { get { return allowedBase; } set { allowedBase = value; } } A allowed; [InTypeScript(Null = false)] public A Allowed { get { return allowed; } set { if (Set(ref allowed, value)) { Notify(); } } } protected virtual void Notify() { Notify(() => Overriden); } [InTypeScript(false)] public bool Overriden { get { return !allowed.Equals(allowedBase); } } [InTypeScript(Null = false)] public R Resource { get; set; } public override string ToString() { return "{0} -> {1}".FormatWith(Resource, Allowed) + (Overriden ? "(overriden from {0})".FormatWith(AllowedBase) : ""); } } [Serializable] public class TypeRulePack : BaseRulePack<TypeAllowedRule> { public override string ToString() { return AuthMessage._0RulesFor1.NiceToString().FormatWith(typeof(TypeEntity).NiceName(), Role); } } [Serializable] public class TypeAllowedRule : AllowedRule<TypeEntity, TypeAllowedAndConditions> { public AuthThumbnail? Properties { get; set; } public AuthThumbnail? Operations { get; set; } public AuthThumbnail? Queries { get; set; } public ReadOnlyCollection<TypeConditionSymbol> AvailableConditions { get; set; } } [Serializable] public class TypeAllowedAndConditions : ModelEntity, IEquatable<TypeAllowedAndConditions> { private TypeAllowedAndConditions() { } public TypeAllowedAndConditions(TypeAllowed? fallback, IEnumerable<TypeConditionRuleEmbedded> conditions) { this.fallback = fallback; this.Conditions.AddRange(conditions); } public TypeAllowedAndConditions(TypeAllowed? fallback, params TypeConditionRuleEmbedded[] conditions) { this.fallback = fallback; this.Conditions.AddRange(conditions); } TypeAllowed? fallback; [InTypeScript(Undefined =false)] public TypeAllowed? Fallback { get { return fallback; } private set { fallback = value; } } [InTypeScript(false)] public TypeAllowed FallbackOrNone { get { return this.fallback ?? TypeAllowed.None; } } public MList<TypeConditionRuleEmbedded> Conditions { get; set; } = new MList<TypeConditionRuleEmbedded>(); public bool Equals(TypeAllowedAndConditions other) { return this.fallback.Equals(other.fallback) && this.Conditions.SequenceEqual(other.Conditions); } public override bool Equals(object obj) { var other = obj as TypeAllowedAndConditions; return other != null && Equals(other); } public override int GetHashCode() { return this.fallback.GetHashCode(); } public TypeAllowedBasic Min(bool inUserInterface) { return inUserInterface ? MinUI() : MinDB(); } public TypeAllowedBasic Max(bool inUserInterface) { return inUserInterface ? MaxUI() : MaxDB(); } public TypeAllowed MinCombined() { return TypeAllowedExtensions.Create(MinDB(), MinUI()); } public TypeAllowed MaxCombined() { return TypeAllowedExtensions.Create(MaxDB(), MaxUI()); } public TypeAllowedBasic MinUI() { if (!Conditions.Any()) return FallbackOrNone.GetUI(); return (TypeAllowedBasic)Math.Min((int)fallback.Value.GetUI(), Conditions.Select(a => (int)a.Allowed.GetUI()).Min()); } public TypeAllowedBasic MaxUI() { if (!Conditions.Any()) return FallbackOrNone.GetUI(); return (TypeAllowedBasic)Math.Max((int)fallback.Value.GetUI(), Conditions.Select(a => (int)a.Allowed.GetUI()).Max()); } public TypeAllowedBasic MinDB() { if (!Conditions.Any()) return FallbackOrNone.GetDB(); return (TypeAllowedBasic)Math.Min((int)fallback.Value.GetDB(), Conditions.Select(a => (int)a.Allowed.GetDB()).Min()); } public TypeAllowedBasic MaxDB() { if (!Conditions.Any()) return FallbackOrNone.GetDB(); return (TypeAllowedBasic)Math.Max((int)fallback.Value.GetDB(), Conditions.Select(a => (int)a.Allowed.GetDB()).Max()); } public override string ToString() { if (Conditions.IsEmpty()) return Fallback.ToString(); return "{0} | {1}".FormatWith(Fallback, Conditions.ToString(c => "{0} {1}".FormatWith(c.TypeCondition, c.Allowed), " | ")); } internal bool Exactly(TypeAllowed current) { return Fallback == current && Conditions.IsNullOrEmpty(); } } [Serializable, InTypeScript(Undefined = false)] public class TypeConditionRuleEmbedded : EmbeddedEntity, IEquatable<TypeConditionRuleEmbedded> { private TypeConditionRuleEmbedded() { } public TypeConditionRuleEmbedded(TypeConditionSymbol typeCondition, TypeAllowed allowed) { this.TypeCondition = typeCondition; this.Allowed = allowed; } [InTypeScript(Null = false)] public TypeConditionSymbol TypeCondition { get; set; } public TypeAllowed Allowed { get; set; } public bool Equals(TypeConditionRuleEmbedded other) { return TypeCondition.Equals(other.TypeCondition) && Allowed.Equals(other.Allowed); } } public enum AuthThumbnail { All, Mix, None, } [Serializable] public abstract class AllowedRuleCoerced<R, A> : AllowedRule<R, A> { public A[] CoercedValues { get; internal set; } } [Serializable] public class PropertyRulePack : BaseRulePack<PropertyAllowedRule> { [NotNullValidator] public TypeEntity Type { get; internal set; } public override string ToString() { return AuthMessage._0RulesFor1.NiceToString().FormatWith(typeof(PropertyRouteEntity).NiceName(), Role); } } [Serializable] public class PropertyAllowedRule : AllowedRuleCoerced<PropertyRouteEntity, PropertyAllowed> { } [Serializable] public class QueryRulePack : BaseRulePack<QueryAllowedRule> { [NotNullValidator] public TypeEntity Type { get; internal set; } public override string ToString() { return AuthMessage._0RulesFor1.NiceToString().FormatWith(typeof(QueryEntity).NiceName(), Role); } } [Serializable] public class QueryAllowedRule : AllowedRuleCoerced<QueryEntity, QueryAllowed> { } [Serializable] public class OperationRulePack : BaseRulePack<OperationAllowedRule> { [NotNullValidator] public TypeEntity Type { get; internal set; } public override string ToString() { return AuthMessage._0RulesFor1.NiceToString().FormatWith(typeof(OperationSymbol).NiceName(), Role); } } [Serializable] public class OperationAllowedRule : AllowedRuleCoerced<OperationTypeEmbedded, OperationAllowed> { } [Serializable] public class PermissionRulePack : BaseRulePack<PermissionAllowedRule> { public override string ToString() { return AuthMessage._0RulesFor1.NiceToString().FormatWith(typeof(PermissionSymbol).NiceName(), Role); } } [Serializable] public class PermissionAllowedRule : AllowedRule<PermissionSymbol, bool> { } }
mapacheL/extensions
Signum.Entities.Extensions/Authorization/ServicesData.cs
C#
lgpl-3.0
11,739
/* ztgsyl.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "pnl/pnl_f2c.h" /* Table of constant values */ static doublecomplex c_b1 = {0.,0.}; static int c__2 = 2; static int c_n1 = -1; static int c__5 = 5; static int c__1 = 1; static doublecomplex c_b44 = {-1.,0.}; static doublecomplex c_b45 = {1.,0.}; int ztgsyl_(char *trans, int *ijob, int *m, int * n, doublecomplex *a, int *lda, doublecomplex *b, int *ldb, doublecomplex *c__, int *ldc, doublecomplex *d__, int *ldd, doublecomplex *e, int *lde, doublecomplex *f, int *ldf, double *scale, double *dif, doublecomplex *work, int * lwork, int *iwork, int *info) { /* System generated locals */ int a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, d_dim1, d_offset, e_dim1, e_offset, f_dim1, f_offset, i__1, i__2, i__3, i__4; doublecomplex z__1; /* Builtin functions */ double sqrt(double); /* Local variables */ int i__, j, k, p, q, ie, je, mb, nb, is, js, pq; double dsum; extern int lsame_(char *, char *); int ifunc, linfo; extern int zscal_(int *, doublecomplex *, doublecomplex *, int *), zgemm_(char *, char *, int *, int *, int *, doublecomplex *, doublecomplex *, int *, doublecomplex *, int *, doublecomplex *, doublecomplex *, int *); int lwmin; double scale2, dscale; extern int ztgsy2_(char *, int *, int *, int *, doublecomplex *, int *, doublecomplex *, int *, doublecomplex *, int *, doublecomplex *, int *, doublecomplex *, int *, doublecomplex *, int *, double *, double *, double *, int *); double scaloc; extern int xerbla_(char *, int *); extern int ilaenv_(int *, char *, char *, int *, int *, int *, int *); int iround; int notran; int isolve; extern int zlacpy_(char *, int *, int *, doublecomplex *, int *, doublecomplex *, int *), zlaset_(char *, int *, int *, doublecomplex *, doublecomplex *, doublecomplex *, int *); int lquery; /* -- LAPACK routine (version 3.2) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* January 2007 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* ZTGSYL solves the generalized Sylvester equation: */ /* A * R - L * B = scale * C (1) */ /* D * R - L * E = scale * F */ /* where R and L are unknown m-by-n matrices, (A, D), (B, E) and */ /* (C, F) are given matrix pairs of size m-by-m, n-by-n and m-by-n, */ /* respectively, with complex entries. A, B, D and E are upper */ /* triangular (i.e., (A,D) and (B,E) in generalized Schur form). */ /* The solution (R, L) overwrites (C, F). 0 <= SCALE <= 1 */ /* is an output scaling factor chosen to avoid overflow. */ /* In matrix notation (1) is equivalent to solve Zx = scale*b, where Z */ /* is defined as */ /* Z = [ kron(In, A) -kron(B', Im) ] (2) */ /* [ kron(In, D) -kron(E', Im) ], */ /* Here Ix is the identity matrix of size x and X' is the conjugate */ /* transpose of X. Kron(X, Y) is the Kronecker product between the */ /* matrices X and Y. */ /* If TRANS = 'C', y in the conjugate transposed system Z'*y = scale*b */ /* is solved for, which is equivalent to solve for R and L in */ /* A' * R + D' * L = scale * C (3) */ /* R * B' + L * E' = scale * -F */ /* This case (TRANS = 'C') is used to compute an one-norm-based estimate */ /* of Dif[(A,D), (B,E)], the separation between the matrix pairs (A,D) */ /* and (B,E), using ZLACON. */ /* If IJOB >= 1, ZTGSYL computes a Frobenius norm-based estimate of */ /* Dif[(A,D),(B,E)]. That is, the reciprocal of a lower bound on the */ /* reciprocal of the smallest singular value of Z. */ /* This is a level-3 BLAS algorithm. */ /* Arguments */ /* ========= */ /* TRANS (input) CHARACTER*1 */ /* = 'N': solve the generalized sylvester equation (1). */ /* = 'C': solve the "conjugate transposed" system (3). */ /* IJOB (input) INTEGER */ /* Specifies what kind of functionality to be performed. */ /* =0: solve (1) only. */ /* =1: The functionality of 0 and 3. */ /* =2: The functionality of 0 and 4. */ /* =3: Only an estimate of Dif[(A,D), (B,E)] is computed. */ /* (look ahead strategy is used). */ /* =4: Only an estimate of Dif[(A,D), (B,E)] is computed. */ /* (ZGECON on sub-systems is used). */ /* Not referenced if TRANS = 'C'. */ /* M (input) INTEGER */ /* The order of the matrices A and D, and the row dimension of */ /* the matrices C, F, R and L. */ /* N (input) INTEGER */ /* The order of the matrices B and E, and the column dimension */ /* of the matrices C, F, R and L. */ /* A (input) COMPLEX*16 array, dimension (LDA, M) */ /* The upper triangular matrix A. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= MAX(1, M). */ /* B (input) COMPLEX*16 array, dimension (LDB, N) */ /* The upper triangular matrix B. */ /* LDB (input) INTEGER */ /* The leading dimension of the array B. LDB >= MAX(1, N). */ /* C (input/output) COMPLEX*16 array, dimension (LDC, N) */ /* On entry, C contains the right-hand-side of the first matrix */ /* equation in (1) or (3). */ /* On exit, if IJOB = 0, 1 or 2, C has been overwritten by */ /* the solution R. If IJOB = 3 or 4 and TRANS = 'N', C holds R, */ /* the solution achieved during the computation of the */ /* Dif-estimate. */ /* LDC (input) INTEGER */ /* The leading dimension of the array C. LDC >= MAX(1, M). */ /* D (input) COMPLEX*16 array, dimension (LDD, M) */ /* The upper triangular matrix D. */ /* LDD (input) INTEGER */ /* The leading dimension of the array D. LDD >= MAX(1, M). */ /* E (input) COMPLEX*16 array, dimension (LDE, N) */ /* The upper triangular matrix E. */ /* LDE (input) INTEGER */ /* The leading dimension of the array E. LDE >= MAX(1, N). */ /* F (input/output) COMPLEX*16 array, dimension (LDF, N) */ /* On entry, F contains the right-hand-side of the second matrix */ /* equation in (1) or (3). */ /* On exit, if IJOB = 0, 1 or 2, F has been overwritten by */ /* the solution L. If IJOB = 3 or 4 and TRANS = 'N', F holds L, */ /* the solution achieved during the computation of the */ /* Dif-estimate. */ /* LDF (input) INTEGER */ /* The leading dimension of the array F. LDF >= MAX(1, M). */ /* DIF (output) DOUBLE PRECISION */ /* On exit DIF is the reciprocal of a lower bound of the */ /* reciprocal of the Dif-function, i.e. DIF is an upper bound of */ /* Dif[(A,D), (B,E)] = sigma-MIN(Z), where Z as in (2). */ /* IF IJOB = 0 or TRANS = 'C', DIF is not referenced. */ /* SCALE (output) DOUBLE PRECISION */ /* On exit SCALE is the scaling factor in (1) or (3). */ /* If 0 < SCALE < 1, C and F hold the solutions R and L, resp., */ /* to a slightly perturbed system but the input matrices A, B, */ /* D and E have not been changed. If SCALE = 0, R and L will */ /* hold the solutions to the homogenious system with C = F = 0. */ /* WORK (workspace/output) COMPLEX*16 array, dimension (MAX(1,LWORK)) */ /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* LWORK (input) INTEGER */ /* The dimension of the array WORK. LWORK > = 1. */ /* If IJOB = 1 or 2 and TRANS = 'N', LWORK >= MAX(1,2*M*N). */ /* If LWORK = -1, then a workspace query is assumed; the routine */ /* only calculates the optimal size of the WORK array, returns */ /* this value as the first entry of the WORK array, and no error */ /* message related to LWORK is issued by XERBLA. */ /* IWORK (workspace) INTEGER array, dimension (M+N+2) */ /* INFO (output) INTEGER */ /* =0: successful exit */ /* <0: If INFO = -i, the i-th argument had an illegal value. */ /* >0: (A, D) and (B, E) have common or very close */ /* eigenvalues. */ /* Further Details */ /* =============== */ /* Based on contributions by */ /* Bo Kagstrom and Peter Poromaa, Department of Computing Science, */ /* Umea University, S-901 87 Umea, Sweden. */ /* [1] B. Kagstrom and P. Poromaa, LAPACK-Style Algorithms and Software */ /* for Solving the Generalized Sylvester Equation and Estimating the */ /* Separation between Regular Matrix Pairs, Report UMINF - 93.23, */ /* Department of Computing Science, Umea University, S-901 87 Umea, */ /* Sweden, December 1993, Revised April 1994, Also as LAPACK Working */ /* Note 75. To appear in ACM Trans. on Math. Software, Vol 22, */ /* No 1, 1996. */ /* [2] B. Kagstrom, A Perturbation Analysis of the Generalized Sylvester */ /* Equation (AR - LB, DR - LE ) = (C, F), SIAM J. Matrix Anal. */ /* Appl., 15(4):1045-1060, 1994. */ /* [3] B. Kagstrom and L. Westin, Generalized Schur Methods with */ /* Condition Estimators for Solving the Generalized Sylvester */ /* Equation, IEEE Transactions on Automatic Control, Vol. 34, No. 7, */ /* July 1989, pp 745-751. */ /* ===================================================================== */ /* Replaced various illegal calls to CCOPY by calls to CLASET. */ /* Sven Hammarling, 1/5/02. */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Decode and test input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; d_dim1 = *ldd; d_offset = 1 + d_dim1; d__ -= d_offset; e_dim1 = *lde; e_offset = 1 + e_dim1; e -= e_offset; f_dim1 = *ldf; f_offset = 1 + f_dim1; f -= f_offset; --work; --iwork; /* Function Body */ *info = 0; notran = lsame_(trans, "N"); lquery = *lwork == -1; if (! notran && ! lsame_(trans, "C")) { *info = -1; } else if (notran) { if (*ijob < 0 || *ijob > 4) { *info = -2; } } if (*info == 0) { if (*m <= 0) { *info = -3; } else if (*n <= 0) { *info = -4; } else if (*lda < MAX(1,*m)) { *info = -6; } else if (*ldb < MAX(1,*n)) { *info = -8; } else if (*ldc < MAX(1,*m)) { *info = -10; } else if (*ldd < MAX(1,*m)) { *info = -12; } else if (*lde < MAX(1,*n)) { *info = -14; } else if (*ldf < MAX(1,*m)) { *info = -16; } } if (*info == 0) { if (notran) { if (*ijob == 1 || *ijob == 2) { /* Computing MAX */ i__1 = 1, i__2 = (*m << 1) * *n; lwmin = MAX(i__1,i__2); } else { lwmin = 1; } } else { lwmin = 1; } work[1].r = (double) lwmin, work[1].i = 0.; if (*lwork < lwmin && ! lquery) { *info = -20; } } if (*info != 0) { i__1 = -(*info); xerbla_("ZTGSYL", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*m == 0 || *n == 0) { *scale = 1.; if (notran) { if (*ijob != 0) { *dif = 0.; } } return 0; } /* Determine optimal block sizes MB and NB */ mb = ilaenv_(&c__2, "ZTGSYL", trans, m, n, &c_n1, &c_n1); nb = ilaenv_(&c__5, "ZTGSYL", trans, m, n, &c_n1, &c_n1); isolve = 1; ifunc = 0; if (notran) { if (*ijob >= 3) { ifunc = *ijob - 2; zlaset_("F", m, n, &c_b1, &c_b1, &c__[c_offset], ldc); zlaset_("F", m, n, &c_b1, &c_b1, &f[f_offset], ldf); } else if (*ijob >= 1 && notran) { isolve = 2; } } if (mb <= 1 && nb <= 1 || mb >= *m && nb >= *n) { /* Use unblocked Level 2 solver */ i__1 = isolve; for (iround = 1; iround <= i__1; ++iround) { *scale = 1.; dscale = 0.; dsum = 1.; pq = *m * *n; ztgsy2_(trans, &ifunc, m, n, &a[a_offset], lda, &b[b_offset], ldb, &c__[c_offset], ldc, &d__[d_offset], ldd, &e[e_offset], lde, &f[f_offset], ldf, scale, &dsum, &dscale, info); if (dscale != 0.) { if (*ijob == 1 || *ijob == 3) { *dif = sqrt((double) ((*m << 1) * *n)) / (dscale * sqrt(dsum)); } else { *dif = sqrt((double) pq) / (dscale * sqrt(dsum)); } } if (isolve == 2 && iround == 1) { if (notran) { ifunc = *ijob; } scale2 = *scale; zlacpy_("F", m, n, &c__[c_offset], ldc, &work[1], m); zlacpy_("F", m, n, &f[f_offset], ldf, &work[*m * *n + 1], m); zlaset_("F", m, n, &c_b1, &c_b1, &c__[c_offset], ldc); zlaset_("F", m, n, &c_b1, &c_b1, &f[f_offset], ldf) ; } else if (isolve == 2 && iround == 2) { zlacpy_("F", m, n, &work[1], m, &c__[c_offset], ldc); zlacpy_("F", m, n, &work[*m * *n + 1], m, &f[f_offset], ldf); *scale = scale2; } /* L30: */ } return 0; } /* Determine block structure of A */ p = 0; i__ = 1; L40: if (i__ > *m) { goto L50; } ++p; iwork[p] = i__; i__ += mb; if (i__ >= *m) { goto L50; } goto L40; L50: iwork[p + 1] = *m + 1; if (iwork[p] == iwork[p + 1]) { --p; } /* Determine block structure of B */ q = p + 1; j = 1; L60: if (j > *n) { goto L70; } ++q; iwork[q] = j; j += nb; if (j >= *n) { goto L70; } goto L60; L70: iwork[q + 1] = *n + 1; if (iwork[q] == iwork[q + 1]) { --q; } if (notran) { i__1 = isolve; for (iround = 1; iround <= i__1; ++iround) { /* Solve (I, J) - subsystem */ /* A(I, I) * R(I, J) - L(I, J) * B(J, J) = C(I, J) */ /* D(I, I) * R(I, J) - L(I, J) * E(J, J) = F(I, J) */ /* for I = P, P - 1, ..., 1; J = 1, 2, ..., Q */ pq = 0; *scale = 1.; dscale = 0.; dsum = 1.; i__2 = q; for (j = p + 2; j <= i__2; ++j) { js = iwork[j]; je = iwork[j + 1] - 1; nb = je - js + 1; for (i__ = p; i__ >= 1; --i__) { is = iwork[i__]; ie = iwork[i__ + 1] - 1; mb = ie - is + 1; ztgsy2_(trans, &ifunc, &mb, &nb, &a[is + is * a_dim1], lda, &b[js + js * b_dim1], ldb, &c__[is + js * c_dim1], ldc, &d__[is + is * d_dim1], ldd, &e[js + js * e_dim1], lde, &f[is + js * f_dim1], ldf, & scaloc, &dsum, &dscale, &linfo); if (linfo > 0) { *info = linfo; } pq += mb * nb; if (scaloc != 1.) { i__3 = js - 1; for (k = 1; k <= i__3; ++k) { z__1.r = scaloc, z__1.i = 0.; zscal_(m, &z__1, &c__[k * c_dim1 + 1], &c__1); z__1.r = scaloc, z__1.i = 0.; zscal_(m, &z__1, &f[k * f_dim1 + 1], &c__1); /* L80: */ } i__3 = je; for (k = js; k <= i__3; ++k) { i__4 = is - 1; z__1.r = scaloc, z__1.i = 0.; zscal_(&i__4, &z__1, &c__[k * c_dim1 + 1], &c__1); i__4 = is - 1; z__1.r = scaloc, z__1.i = 0.; zscal_(&i__4, &z__1, &f[k * f_dim1 + 1], &c__1); /* L90: */ } i__3 = je; for (k = js; k <= i__3; ++k) { i__4 = *m - ie; z__1.r = scaloc, z__1.i = 0.; zscal_(&i__4, &z__1, &c__[ie + 1 + k * c_dim1], & c__1); i__4 = *m - ie; z__1.r = scaloc, z__1.i = 0.; zscal_(&i__4, &z__1, &f[ie + 1 + k * f_dim1], & c__1); /* L100: */ } i__3 = *n; for (k = je + 1; k <= i__3; ++k) { z__1.r = scaloc, z__1.i = 0.; zscal_(m, &z__1, &c__[k * c_dim1 + 1], &c__1); z__1.r = scaloc, z__1.i = 0.; zscal_(m, &z__1, &f[k * f_dim1 + 1], &c__1); /* L110: */ } *scale *= scaloc; } /* Substitute R(I,J) and L(I,J) into remaining equation. */ if (i__ > 1) { i__3 = is - 1; zgemm_("N", "N", &i__3, &nb, &mb, &c_b44, &a[is * a_dim1 + 1], lda, &c__[is + js * c_dim1], ldc, &c_b45, &c__[js * c_dim1 + 1], ldc); i__3 = is - 1; zgemm_("N", "N", &i__3, &nb, &mb, &c_b44, &d__[is * d_dim1 + 1], ldd, &c__[is + js * c_dim1], ldc, &c_b45, &f[js * f_dim1 + 1], ldf); } if (j < q) { i__3 = *n - je; zgemm_("N", "N", &mb, &i__3, &nb, &c_b45, &f[is + js * f_dim1], ldf, &b[js + (je + 1) * b_dim1], ldb, &c_b45, &c__[is + (je + 1) * c_dim1], ldc); i__3 = *n - je; zgemm_("N", "N", &mb, &i__3, &nb, &c_b45, &f[is + js * f_dim1], ldf, &e[js + (je + 1) * e_dim1], lde, &c_b45, &f[is + (je + 1) * f_dim1], ldf); } /* L120: */ } /* L130: */ } if (dscale != 0.) { if (*ijob == 1 || *ijob == 3) { *dif = sqrt((double) ((*m << 1) * *n)) / (dscale * sqrt(dsum)); } else { *dif = sqrt((double) pq) / (dscale * sqrt(dsum)); } } if (isolve == 2 && iround == 1) { if (notran) { ifunc = *ijob; } scale2 = *scale; zlacpy_("F", m, n, &c__[c_offset], ldc, &work[1], m); zlacpy_("F", m, n, &f[f_offset], ldf, &work[*m * *n + 1], m); zlaset_("F", m, n, &c_b1, &c_b1, &c__[c_offset], ldc); zlaset_("F", m, n, &c_b1, &c_b1, &f[f_offset], ldf) ; } else if (isolve == 2 && iround == 2) { zlacpy_("F", m, n, &work[1], m, &c__[c_offset], ldc); zlacpy_("F", m, n, &work[*m * *n + 1], m, &f[f_offset], ldf); *scale = scale2; } /* L150: */ } } else { /* Solve transposed (I, J)-subsystem */ /* A(I, I)' * R(I, J) + D(I, I)' * L(I, J) = C(I, J) */ /* R(I, J) * B(J, J) + L(I, J) * E(J, J) = -F(I, J) */ /* for I = 1,2,..., P; J = Q, Q-1,..., 1 */ *scale = 1.; i__1 = p; for (i__ = 1; i__ <= i__1; ++i__) { is = iwork[i__]; ie = iwork[i__ + 1] - 1; mb = ie - is + 1; i__2 = p + 2; for (j = q; j >= i__2; --j) { js = iwork[j]; je = iwork[j + 1] - 1; nb = je - js + 1; ztgsy2_(trans, &ifunc, &mb, &nb, &a[is + is * a_dim1], lda, & b[js + js * b_dim1], ldb, &c__[is + js * c_dim1], ldc, &d__[is + is * d_dim1], ldd, &e[js + js * e_dim1], lde, &f[is + js * f_dim1], ldf, &scaloc, &dsum, & dscale, &linfo); if (linfo > 0) { *info = linfo; } if (scaloc != 1.) { i__3 = js - 1; for (k = 1; k <= i__3; ++k) { z__1.r = scaloc, z__1.i = 0.; zscal_(m, &z__1, &c__[k * c_dim1 + 1], &c__1); z__1.r = scaloc, z__1.i = 0.; zscal_(m, &z__1, &f[k * f_dim1 + 1], &c__1); /* L160: */ } i__3 = je; for (k = js; k <= i__3; ++k) { i__4 = is - 1; z__1.r = scaloc, z__1.i = 0.; zscal_(&i__4, &z__1, &c__[k * c_dim1 + 1], &c__1); i__4 = is - 1; z__1.r = scaloc, z__1.i = 0.; zscal_(&i__4, &z__1, &f[k * f_dim1 + 1], &c__1); /* L170: */ } i__3 = je; for (k = js; k <= i__3; ++k) { i__4 = *m - ie; z__1.r = scaloc, z__1.i = 0.; zscal_(&i__4, &z__1, &c__[ie + 1 + k * c_dim1], &c__1) ; i__4 = *m - ie; z__1.r = scaloc, z__1.i = 0.; zscal_(&i__4, &z__1, &f[ie + 1 + k * f_dim1], &c__1); /* L180: */ } i__3 = *n; for (k = je + 1; k <= i__3; ++k) { z__1.r = scaloc, z__1.i = 0.; zscal_(m, &z__1, &c__[k * c_dim1 + 1], &c__1); z__1.r = scaloc, z__1.i = 0.; zscal_(m, &z__1, &f[k * f_dim1 + 1], &c__1); /* L190: */ } *scale *= scaloc; } /* Substitute R(I,J) and L(I,J) into remaining equation. */ if (j > p + 2) { i__3 = js - 1; zgemm_("N", "C", &mb, &i__3, &nb, &c_b45, &c__[is + js * c_dim1], ldc, &b[js * b_dim1 + 1], ldb, &c_b45, & f[is + f_dim1], ldf); i__3 = js - 1; zgemm_("N", "C", &mb, &i__3, &nb, &c_b45, &f[is + js * f_dim1], ldf, &e[js * e_dim1 + 1], lde, &c_b45, & f[is + f_dim1], ldf); } if (i__ < p) { i__3 = *m - ie; zgemm_("C", "N", &i__3, &nb, &mb, &c_b44, &a[is + (ie + 1) * a_dim1], lda, &c__[is + js * c_dim1], ldc, & c_b45, &c__[ie + 1 + js * c_dim1], ldc); i__3 = *m - ie; zgemm_("C", "N", &i__3, &nb, &mb, &c_b44, &d__[is + (ie + 1) * d_dim1], ldd, &f[is + js * f_dim1], ldf, & c_b45, &c__[ie + 1 + js * c_dim1], ldc); } /* L200: */ } /* L210: */ } } work[1].r = (double) lwmin, work[1].i = 0.; return 0; /* End of ZTGSYL */ } /* ztgsyl_ */
pnlnum/pnl
src/liblapack/ztgsyl.c
C
lgpl-3.0
21,050
<!DOCTYPE html> <html class="um landscape min-width-240px min-width-320px min-width-480px min-width-768px min-width-1024px"> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="target-densitydpi=device-dpi, width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" href="../../../css/fonts/font-awesome.min.css"> <link rel="stylesheet" href="../../../css/ui-box.css"> <link rel="stylesheet" href="../../../css/ui-base.css"> <link rel="stylesheet" href="../../../css/ui-color.css"> <link rel="stylesheet" href="../../../css/appcan.icon.css"> <link rel="stylesheet" href="../../../css/appcan.control.css"> <link rel="stylesheet" href="../../../css/themes/pastie.css"> <link rel="stylesheet" href="../../../css/my.css"> <style type="text/css"> .bc-bg { background-color: #fff; } </style> </head> <body class="um-vp bc-bg" ontouchstart> <div id="dot"> <img src="../../../css/res/common/btn-act.png"/> <div class="menu ub"> <div class="play ub-f1"> 演示 </div><div class="line lineone"></div> <div class="source ub-f1"> 源码 </div><div class="line linetwo"></div> <div class="return ub-f1"> 返回 </div> <div class="triangle-blue"></div> </div> </div> <pre><code data-language="javascript">var commonCallback = function(data) { alert("callback:" + JSON.stringify(data)); } function ScannerSuccessCallBack(opCode, dataType, data) { alert("opCode:" + opCode + " data: " + data); } function ScannerFailedCallBack(data) { alert(data); } window.uexOnload = function() { uexScanner.cbOpen = ScannerSuccessCallBack; uexWidgetOne.cbError = ScannerFailedCallBack; } uexScanner.open() </code></pre> </body> <script src="../../../js/jquery.1.7.2.min.js"></script> <script src="../../../js/jquery.event.ue.js.js"></script> <script src="../../../js/jquery.udraggable.js"></script> <script> var jq = $.noConflict(); </script> <script src="../../../js/rainbow.min.js"></script> <script src="../../../js/javascript.js"></script> <script src="../../../js/appcan.js"></script> <script src="../../../js/appcan.control.js"></script> <script src="../../../js/my.js"></script> </body> <script> appcan.ready(function() { appcan.locStorage.val("single", 1) }); appcan.button(".play", "btn-act", function() { appcan.window.closePopover("source") appcan.locStorage.val("single", 0) // appcan.window.open("play","index.html"); // var titHeight = appcan.locStorage.val("titHeight"); // appcan.window.openPopover("scrawlIndex", "0", "index_content.html", '', 0, titHeight, '', '', '', ''); // appcan.window.publish("changeHeader", "play"); }) </script> </html>
AppCanOpenSource/appcan-native-helper
source/phone/dev4/ui/uexScanner/source_content.html
HTML
lgpl-3.0
3,291
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Input_API; namespace HaptiQ_API { /// <summary> /// LinearBehaviour behaviour defines a set of behaviours where /// an actuator or a set of actuators change the height linearly /// </summary> public class LinearBehaviour : Behaviour { private const int NUMBER_ACTUATORS_DIVIDER = 4; private const double HIGH_POSITION_PERCENTAGE = 0.8; private Tuple<Point, Point> _segment; private int[] singleActuatorsMatrix = new int[] { 2, // 4-HaptiQ 1-line 4}; // 8 -HaptiQ 1-line private int[][] dynamicActuatorsMatrix = new int[][] { new int[]{1, 2}, // 4-HaptiQ 1-line new int[]{2, 4}// 8-HaptiQ 1-line }; /// <summary> /// Constructor of the Linear behaviour. /// Height of the actuators is specified by the ratio value /// </summary> /// <param name="haptiQ"></param> /// <param name="segment"></param> /// <param name="ratio"></param> public LinearBehaviour(HaptiQ haptiQ, Tuple<Point, Point> segment, double ratio) : base(haptiQ) { _segment = segment; TIME = 0; highPosition = HIGH_POSITION_PERCENTAGE * ratio; lowPosition = 0; } /// <summary> /// Plays this behaviour /// </summary> /// <returns></returns> public override Dictionary<int, double> play() { Dictionary<int, double> retval = new Dictionary<int, double>(); TIME++; segmentBehaviour(ref retval); System.Threading.Thread.Sleep(100); return retval; } /// <summary> /// Segment behaviour with pulsation /// </summary> /// <param name="output"></param> private void segmentBehaviour(ref Dictionary<int, double> output) { int sector = getSector(_segment, orientation, actuators.Count, actuators.Count * 2); int matrixIndex = actuators.Count / NUMBER_ACTUATORS_DIVIDER - 1; if (sector % 2 == 0) // Single actuators sector { int activeActs = singleActuatorsMatrix[matrixIndex]; activeActs = RshiftActs(activeActs, (int)(sector / 2), actuators.Count); bitsToActuators(actuators.Count, activeActs, false, false, ref output); setZerosToMinimum(actuators.Count, activeActs, ref output); } else // Double actuators sector { int[] acts = (int[])dynamicActuatorsMatrix[matrixIndex].Clone(); acts[0] = RshiftActs(acts[0], (int)((sector - 1) / 2), actuators.Count); acts[1] = RshiftActs(acts[1], (int)((sector - 1) / 2), actuators.Count); bitsToActuators(actuators.Count, acts[0] | acts[1], false, false, ref output); setZerosToMinimum(actuators.Count, (acts[0] | acts[1]), ref output); } } /// <summary> /// Override equals to allow LinearBehaviour to be compared correctly. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(System.Object obj) { // If parameter is null return false if (obj == null) return false; // If parameter cannot be cast to Point return false LinearBehaviour p = obj as LinearBehaviour; if ((System.Object)p == null) return false; // Return true if the fields match return (p._segment == this._segment && p.orientation == this.orientation && this.highPosition == this.highPosition); } // @see: http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + this._segment.GetHashCode(); hash = hash * 23 + this.orientation.GetHashCode(); hash = hash * 23 + this.highPosition.GetHashCode(); return hash; } } } }
sic2/HaptiQ
HaptiQ/HaptiQ_API/Behaviours/LinearBehaviour.cs
C#
lgpl-3.0
4,469
<?php /** * Smarty PHPunit tests of modifier * * @package PHPunit * @author Rodney Rehm */ /** * class for modifier tests */ class PluginModifierLowerTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->smarty = SmartyTests::$smarty; SmartyTests::init(); } public function testDefault() { $result = "two convicts evade noose, jury hung."; $tpl = $this->smarty->createTemplate('eval:{"Two Convicts Evade Noose, Jury Hung."|lower}'); $this->assertEquals($result, $this->smarty->fetch($tpl)); } public function testDefaultWithoutMbstring() { Smarty::$_MBSTRING = false; $result = "two convicts evade noose, jury hung."; $tpl = $this->smarty->createTemplate('eval:{"Two Convicts Evade Noose, Jury Hung."|lower}'); $this->assertEquals($result, $this->smarty->fetch($tpl)); Smarty::$_MBSTRING = true; } public function testUmlauts() { $result = "two convicts eväde nööse, jury hung."; $tpl = $this->smarty->createTemplate('eval:{"Two Convicts Eväde NöÖse, Jury Hung."|lower}'); $this->assertEquals($result, $this->smarty->fetch($tpl)); } public function testUmlautsWithoutMbstring() { Smarty::$_MBSTRING = false; $result = "two convicts eväde nööse, jury hung."; $tpl = $this->smarty->createTemplate('eval:{"Two Convicts Eväde NöÖse, Jury Hung."|lower}'); $this->assertNotEquals($result, $this->smarty->fetch($tpl)); Smarty::$_MBSTRING = true; } }
chriseling/brainy
test/PluginModifierLowerTest.php
PHP
lgpl-3.0
1,566
/* -*- C -*- * mmap.c -- memory mapping for the sculld char module * * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet * Copyright (C) 2001 O'Reilly & Associates * * The source code in this file can be freely used, adapted, * and redistributed in source or binary form, so long as an * acknowledgment appears in derived source files. The citation * should list that the code comes from the book "Linux Device * Drivers" by Alessandro Rubini and Jonathan Corbet, published * by O'Reilly & Associates. No warranty is attached; * we cannot take responsibility for errors or fitness for use. * * $Id: _mmap.c.in,v 1.13 2004/10/18 18:07:36 corbet Exp $ */ #include <linux/module.h> #include <linux/fs.h> #include <linux/mm.h> /* everything */ #include <linux/errno.h> /* error codes */ #include <asm/pgtable.h> #include "sculld.h" /* local definitions */ /* * open and close: just keep track of how many times the device is * mapped, to avoid releasing it. */ void sculld_vma_open(struct vm_area_struct *vma) { struct sculld_dev *dev = vma->vm_private_data; dev->vmas++; } void sculld_vma_close(struct vm_area_struct *vma) { struct sculld_dev *dev = vma->vm_private_data; dev->vmas--; } /* * The nopage method: the core of the file. It retrieves the * page required from the sculld device and returns it to the * user. The count for the page must be incremented, because * it is automatically decremented at page unmap. * * For this reason, "order" must be zero. Otherwise, only the first * page has its count incremented, and the allocating module must * release it as a whole block. Therefore, it isn't possible to map * pages from a multipage block: when they are unmapped, their count * is individually decreased, and would drop to 0. */ static int sculld_vma_nopage(struct vm_area_struct *vma, struct vm_fault *vmf) { unsigned long offset; struct sculld_dev *ptr, *dev = vma->vm_private_data; struct page *page = NULL; void *pageptr = NULL; /* default to "missing" */ int retval = VM_FAULT_NOPAGE; down(&dev->sem); offset = (unsigned long)(vmf->virtual_address - vma->vm_start) + (vma->vm_pgoff << PAGE_SHIFT); if (offset >= dev->size) goto out; /* out of range */ /* * Now retrieve the sculld device from the list,then the page. * If the device has holes, the process receives a SIGBUS when * accessing the hole. */ offset >>= PAGE_SHIFT; /* offset is a number of pages */ for (ptr = dev; ptr && offset >= dev->qset;) { ptr = ptr->next; offset -= dev->qset; } if (ptr && ptr->data) pageptr = ptr->data[offset]; if (!pageptr) goto out; /* hole or end-of-file */ /* got it, now increment the count */ get_page(page); vmf->page = page; retval = 0; out: up(&dev->sem); return retval; } struct vm_operations_struct sculld_vm_ops = { .open = sculld_vma_open, .close = sculld_vma_close, .fault = sculld_vma_nopage, }; int sculld_mmap(struct file *filp, struct vm_area_struct *vma) { struct inode *inode = filp->f_path.dentry->d_inode; /* refuse to map if order is not 0 */ if (sculld_devices[iminor(inode)].order) return -ENODEV; /* don't do anything here: "nopage" will set up page table entries */ vma->vm_ops = &sculld_vm_ops; vma->vm_flags |= VM_RESERVED; vma->vm_private_data = filp->private_data; sculld_vma_open(vma); return 0; }
xiaoqing-yuanfang/test
ko/ldd3-3.4.108/sculld/mmap.c
C
lgpl-3.0
3,358
/* * Copyright (C) 2005-2011 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.query; import java.util.List; import org.alfresco.api.AlfrescoPublicApi; import org.alfresco.util.Pair; /** * Marker interface for single page of results * * @author janv * @since 4.0 */ @AlfrescoPublicApi public interface PagingResults<R> { /** * Get the page of results. * * @return the results - possibly empty but never <tt>null</tt> */ public List<R> getPage(); /** * True if more items on next page. * <p/> * Note: could also return true if page was cutoff/trimmed for some reason * (eg. due to permission checks of large page of requested max items) * * @return true if more items (eg. on next page)<br/> * - true => at least one more page (or incomplete page - if cutoff)<br/> * - false => last page (or incomplete page - if cutoff) */ public boolean hasMoreItems(); /** * Get the total result count assuming no paging applied. This value will only be available if * the query supports it and the client requested it. By default, it is not requested. * <p/> * Returns result as an approx "range" pair <lower, upper> * <ul> * <li>null (or lower is null): unknown total count (or not requested by the client).</li> * <li>lower = upper : total count should be accurate</li> * <li>lower < upper : total count is an approximation ("about") - somewhere in the given range (inclusive)</li> * <li>upper is null : total count is "more than" lower (upper is unknown)</li> * </ul> * * @return Returns the total results as a range (all results, including the paged results returned) */ public Pair<Integer, Integer> getTotalResultCount(); /** * Get a unique ID associated with these query results. This must be available before and * after execution i.e. it must depend on the type of query and the query parameters * rather than the execution results. Client has the option to pass this back as a hint when * paging. * * @return a unique ID associated with the query execution results */ public String getQueryExecutionId(); }
loftuxab/community-edition-old
projects/core/source/java/org/alfresco/query/PagingResults.java
Java
lgpl-3.0
3,118
ipos ==== ipos
wilmandx/ipos
README.md
Markdown
lgpl-3.0
16
""" Sample a specific geometry or set of geometries. """ import numpy as np import nomad.core.glbl as glbl import nomad.core.trajectory as trajectory import nomad.core.log as log def set_initial_coords(wfn): """Takes initial position and momentum from geometry specified in input""" coords = glbl.properties['init_coords'] ndim = coords.shape[-1] log.print_message('string',[' Initial coordinates taken from input file(s).\n']) for coord in coords: itraj = trajectory.Trajectory(glbl.properties['n_states'], ndim, width=glbl.properties['crd_widths'], mass=glbl.properties['crd_masses'], parent=0, kecoef=glbl.modules['integrals'].kecoef) # set position and momentum itraj.update_x(np.array(coord[0])) itraj.update_p(np.array(coord[1])) # add a single trajectory specified by geometry.dat wfn.add_trajectory(itraj)
mschuurman/FMSpy
nomad/initconds/explicit.py
Python
lgpl-3.0
1,004
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :copyright: Wenjie Lei (lei@princeton.edu), 2016 :license: GNU General Public License, Version 3 (http://www.gnu.org/copyleft/gpl.html) """ from __future__ import (absolute_import, division, print_function) # NOQA from .adjoint_source import calculate_adjsrc_on_stream # NOQA from .adjoint_source import calculate_and_process_adjsrc_on_stream # NOQA from .adjoint_source import calculate_adjsrc_on_trace # NOQA from .adjoint_source import measure_adjoint_on_stream # NOQA
wjlei1990/pytomo3d
pytomo3d/adjoint/__init__.py
Python
lgpl-3.0
573