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
/* GIMP - The GNU Image Manipulation Program * Copyright (C) 1995 Spencer Kimball and Peter Mattis * * GimpImagePropView * Copyright (C) 2005 Michael Natterer <mitch@gimp.org> * Copyright (C) 2006 Sven Neumann <sven@gimp.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <sys/types.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <gegl.h> #include <gtk/gtk.h> #include <glib/gstdio.h> #include "libgimpbase/gimpbase.h" #include "libgimpwidgets/gimpwidgets.h" #include "widgets-types.h" #include "core/gimp.h" #include "core/gimpcontainer.h" #include "core/gimpimage.h" #include "core/gimpimage-colormap.h" #include "core/gimpimage-undo.h" #include "core/gimpundostack.h" #include "core/gimp-utils.h" #include "file/file-procedure.h" #include "file/file-utils.h" #include "plug-in/gimppluginmanager.h" #include "plug-in/gimppluginprocedure.h" #include "gimpimagepropview.h" #include "gimppropwidgets.h" #include "gimp-intl.h" enum { PROP_0, PROP_IMAGE }; static void gimp_image_prop_view_constructed (GObject *object); static void gimp_image_prop_view_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); static void gimp_image_prop_view_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); static GtkWidget * gimp_image_prop_view_add_label (GtkTable *table, gint row, const gchar *text); static void gimp_image_prop_view_undo_event (GimpImage *image, GimpUndoEvent event, GimpUndo *undo, GimpImagePropView *view); static void gimp_image_prop_view_update (GimpImagePropView *view); static void gimp_image_prop_view_file_update (GimpImagePropView *view); G_DEFINE_TYPE (GimpImagePropView, gimp_image_prop_view, GTK_TYPE_TABLE) #define parent_class gimp_image_prop_view_parent_class static void gimp_image_prop_view_class_init (GimpImagePropViewClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->constructed = gimp_image_prop_view_constructed; object_class->set_property = gimp_image_prop_view_set_property; object_class->get_property = gimp_image_prop_view_get_property; g_object_class_install_property (object_class, PROP_IMAGE, g_param_spec_object ("image", NULL, NULL, GIMP_TYPE_IMAGE, GIMP_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); } static void gimp_image_prop_view_init (GimpImagePropView *view) { GtkTable *table = GTK_TABLE (view); gint row = 0; gtk_table_resize (table, 14, 2); gtk_table_set_col_spacings (table, 6); gtk_table_set_row_spacings (table, 3); view->pixel_size_label = gimp_image_prop_view_add_label (table, row++, _("Size in pixels:")); view->print_size_label = gimp_image_prop_view_add_label (table, row++, _("Print size:")); view->resolution_label = gimp_image_prop_view_add_label (table, row++, _("Resolution:")); view->colorspace_label = gimp_image_prop_view_add_label (table, row, _("Color space:")); gtk_table_set_row_spacing (GTK_TABLE (view), row++, 12); view->filename_label = gimp_image_prop_view_add_label (table, row++, _("File Name:")); gtk_label_set_ellipsize (GTK_LABEL (view->filename_label), PANGO_ELLIPSIZE_MIDDLE); view->filesize_label = gimp_image_prop_view_add_label (table, row++, _("File Size:")); view->filetype_label = gimp_image_prop_view_add_label (table, row, _("File Type:")); gtk_table_set_row_spacing (GTK_TABLE (view), row++, 12); view->memsize_label = gimp_image_prop_view_add_label (table, row++, _("Size in memory:")); view->undo_label = gimp_image_prop_view_add_label (table, row++, _("Undo steps:")); view->redo_label = gimp_image_prop_view_add_label (table, row, _("Redo steps:")); gtk_table_set_row_spacing (GTK_TABLE (view), row++, 12); view->pixels_label = gimp_image_prop_view_add_label (table, row++, _("Number of pixels:")); view->layers_label = gimp_image_prop_view_add_label (table, row++, _("Number of layers:")); view->channels_label = gimp_image_prop_view_add_label (table, row++, _("Number of channels:")); view->vectors_label = gimp_image_prop_view_add_label (table, row++, _("Number of paths:")); } static void gimp_image_prop_view_constructed (GObject *object) { GimpImagePropView *view = GIMP_IMAGE_PROP_VIEW (object); if (G_OBJECT_CLASS (parent_class)->constructed) G_OBJECT_CLASS (parent_class)->constructed (object); g_assert (view->image != NULL); g_signal_connect_object (view->image, "name-changed", G_CALLBACK (gimp_image_prop_view_file_update), G_OBJECT (view), G_CONNECT_SWAPPED); g_signal_connect_object (view->image, "size-changed", G_CALLBACK (gimp_image_prop_view_update), G_OBJECT (view), G_CONNECT_SWAPPED); g_signal_connect_object (view->image, "resolution-changed", G_CALLBACK (gimp_image_prop_view_update), G_OBJECT (view), G_CONNECT_SWAPPED); g_signal_connect_object (view->image, "unit-changed", G_CALLBACK (gimp_image_prop_view_update), G_OBJECT (view), G_CONNECT_SWAPPED); g_signal_connect_object (view->image, "mode-changed", G_CALLBACK (gimp_image_prop_view_update), G_OBJECT (view), G_CONNECT_SWAPPED); g_signal_connect_object (view->image, "undo-event", G_CALLBACK (gimp_image_prop_view_undo_event), G_OBJECT (view), 0); gimp_image_prop_view_update (view); gimp_image_prop_view_file_update (view); } static void gimp_image_prop_view_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { GimpImagePropView *view = GIMP_IMAGE_PROP_VIEW (object); switch (property_id) { case PROP_IMAGE: view->image = g_value_get_object (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } static void gimp_image_prop_view_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { GimpImagePropView *view = GIMP_IMAGE_PROP_VIEW (object); switch (property_id) { case PROP_IMAGE: g_value_set_object (value, view->image); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } /* public functions */ GtkWidget * gimp_image_prop_view_new (GimpImage *image) { g_return_val_if_fail (GIMP_IS_IMAGE (image), NULL); return g_object_new (GIMP_TYPE_IMAGE_PROP_VIEW, "image", image, NULL); } /* private functions */ static GtkWidget * gimp_image_prop_view_add_label (GtkTable *table, gint row, const gchar *text) { GtkWidget *label; GtkWidget *desc; desc = g_object_new (GTK_TYPE_LABEL, "label", text, "xalign", 1.0, "yalign", 0.5, NULL); gimp_label_set_attributes (GTK_LABEL (desc), PANGO_ATTR_WEIGHT, PANGO_WEIGHT_BOLD, -1); gtk_table_attach (table, desc, 0, 1, row, row + 1, GTK_FILL, GTK_FILL, 0, 0); gtk_widget_show (desc); label = g_object_new (GTK_TYPE_LABEL, "xalign", 0.0, "yalign", 0.5, "selectable", TRUE, NULL); gtk_table_attach (table, label, 1, 2, row, row + 1, GTK_FILL | GTK_EXPAND, GTK_FILL, 0, 0); gtk_widget_show (label); return label; } static void gimp_image_prop_view_label_set_memsize (GtkWidget *label, GimpObject *object) { gchar *str = g_format_size (gimp_object_get_memsize (object, NULL)); gtk_label_set_text (GTK_LABEL (label), str); g_free (str); } static void gimp_image_prop_view_label_set_filename (GtkWidget *label, GimpImage *image) { const gchar *uri = gimp_image_get_uri (image); if (uri) { gchar *name = file_utils_uri_display_name (uri); gtk_label_set_text (GTK_LABEL (label), name); g_free (name); } else { gtk_label_set_text (GTK_LABEL (label), NULL); gimp_help_set_help_data (gtk_widget_get_parent (label), NULL, NULL); } } static void gimp_image_prop_view_label_set_filesize (GtkWidget *label, GimpImage *image) { gchar *filename = gimp_image_get_filename (image); if (filename) { struct stat buf; if (g_stat (filename, &buf) == 0) { gchar *str = g_format_size (buf.st_size); gtk_label_set_text (GTK_LABEL (label), str); g_free (str); } else { gtk_label_set_text (GTK_LABEL (label), NULL); } g_free (filename); } else { gtk_label_set_text (GTK_LABEL (label), NULL); } } static void gimp_image_prop_view_label_set_filetype (GtkWidget *label, GimpImage *image) { GimpPlugInManager *manager = image->gimp->plug_in_manager; GimpPlugInProcedure *proc; proc = gimp_image_get_save_proc (image); if (! proc) proc = gimp_image_get_load_proc (image); if (! proc) { gchar *filename = gimp_image_get_filename (image); if (filename) { proc = file_procedure_find (manager->load_procs, filename, NULL); g_free (filename); } } gtk_label_set_text (GTK_LABEL (label), proc ? gimp_plug_in_procedure_get_label (proc) : NULL); } static void gimp_image_prop_view_label_set_undo (GtkWidget *label, GimpUndoStack *stack) { gint steps = gimp_undo_stack_get_depth (stack); if (steps > 0) { GimpObject *object = GIMP_OBJECT (stack); gchar *str; gchar buf[256]; str = g_format_size (gimp_object_get_memsize (object, NULL)); g_snprintf (buf, sizeof (buf), "%d (%s)", steps, str); g_free (str); gtk_label_set_text (GTK_LABEL (label), buf); } else { /* no undo (or redo) steps available */ gtk_label_set_text (GTK_LABEL (label), _("None")); } } static void gimp_image_prop_view_undo_event (GimpImage *image, GimpUndoEvent event, GimpUndo *undo, GimpImagePropView *view) { gimp_image_prop_view_update (view); } static void gimp_image_prop_view_update (GimpImagePropView *view) { GimpImage *image = view->image; GimpImageBaseType type; GimpUnit unit; gdouble unit_factor; gint unit_digits; const gchar *desc; gchar format_buf[32]; gchar buf[256]; gdouble xres; gdouble yres; gimp_image_get_resolution (image, &xres, &yres); /* pixel size */ g_snprintf (buf, sizeof (buf), ngettext ("%d × %d pixel", "%d × %d pixels", gimp_image_get_height (image)), gimp_image_get_width (image), gimp_image_get_height (image)); gtk_label_set_text (GTK_LABEL (view->pixel_size_label), buf); /* print size */ unit = gimp_get_default_unit (); unit_digits = gimp_unit_get_digits (unit); g_snprintf (format_buf, sizeof (format_buf), "%%.%df × %%.%df %s", unit_digits + 1, unit_digits + 1, gimp_unit_get_plural (unit)); g_snprintf (buf, sizeof (buf), format_buf, gimp_pixels_to_units (gimp_image_get_width (image), unit, xres), gimp_pixels_to_units (gimp_image_get_height (image), unit, yres)); gtk_label_set_text (GTK_LABEL (view->print_size_label), buf); /* resolution */ unit = gimp_image_get_unit (image); unit_factor = gimp_unit_get_factor (unit); g_snprintf (format_buf, sizeof (format_buf), _("pixels/%s"), gimp_unit_get_abbreviation (unit)); g_snprintf (buf, sizeof (buf), _("%g × %g %s"), xres / unit_factor, yres / unit_factor, unit == GIMP_UNIT_INCH ? _("ppi") : format_buf); gtk_label_set_text (GTK_LABEL (view->resolution_label), buf); /* color type */ type = gimp_image_base_type (image); gimp_enum_get_value (GIMP_TYPE_IMAGE_BASE_TYPE, type, NULL, NULL, &desc, NULL); switch (type) { case GIMP_RGB: case GIMP_GRAY: g_snprintf (buf, sizeof (buf), "%s", desc); break; case GIMP_INDEXED: g_snprintf (buf, sizeof (buf), "%s (%d %s)", desc, gimp_image_get_colormap_size (image), _("colors")); break; } gtk_label_set_text (GTK_LABEL (view->colorspace_label), buf); /* size in memory */ gimp_image_prop_view_label_set_memsize (view->memsize_label, GIMP_OBJECT (image)); /* undo / redo */ gimp_image_prop_view_label_set_undo (view->undo_label, gimp_image_get_undo_stack (image)); gimp_image_prop_view_label_set_undo (view->redo_label, gimp_image_get_redo_stack (image)); /* number of layers */ g_snprintf (buf, sizeof (buf), "%d", gimp_image_get_width (image) * gimp_image_get_height (image)); gtk_label_set_text (GTK_LABEL (view->pixels_label), buf); /* number of layers */ g_snprintf (buf, sizeof (buf), "%d", gimp_image_get_n_layers (image)); gtk_label_set_text (GTK_LABEL (view->layers_label), buf); /* number of channels */ g_snprintf (buf, sizeof (buf), "%d", gimp_image_get_n_channels (image)); gtk_label_set_text (GTK_LABEL (view->channels_label), buf); /* number of vectors */ g_snprintf (buf, sizeof (buf), "%d", gimp_image_get_n_vectors (image)); gtk_label_set_text (GTK_LABEL (view->vectors_label), buf); } static void gimp_image_prop_view_file_update (GimpImagePropView *view) { GimpImage *image = view->image; /* filename */ gimp_image_prop_view_label_set_filename (view->filename_label, image); /* filesize */ gimp_image_prop_view_label_set_filesize (view->filesize_label, image); /* filetype */ gimp_image_prop_view_label_set_filetype (view->filetype_label, image); }
peixuan/GIMP-Mod
app/widgets/gimpimagepropview.c
C
gpl-3.0
16,747
## Catbot Setup Setup scripts for cat-bots (cathook navbots) For more information, visit [Cathook](https://github.com/nullworks/cathook/) After the install script finished successfully, navmesh files have to be moved into your tf2 maps directory. They can be found [here](https://github.com/nullworks/catbot-database). Due to steam recently adding Recaptcha v2, you must provide accounts to the account-generator. More information in [this](https://t.me/sag_bot) Channel. For support, visit us in [this](https://t.me/nullworks) channel. ## Required Dependencies Ubuntu/Debian `sudo apt-get install nodejs firejail net-tools x11-xserver-utils` Fedora/Centos `sudo dnf install nodejs firejail net-tools xorg-x11-server-utils` Arch/Manjaro (High Support) `sudo pacman -Syu nodejs npm firejail net-tools xorg-xhost`
nullifiedcat/catbot-setup
README.md
Markdown
gpl-3.0
821
using System; using System.Text; namespace NzbDrone.Core.Parser.RomanNumerals { /// <summary> /// Represents the numeric system used in ancient Rome, employing combinations of letters from the Latin alphabet to signify values. /// Implementation adapted from: http://www.c-sharpcorner.com/Blogs/14255/converting-to-and-from-roman-numerals.aspx /// </summary> public class RomanNumeral : IComparable, IComparable<RomanNumeral>, IEquatable<RomanNumeral>, IRomanNumeral { #region Fields /// <summary> /// The numeric value of the roman numeral. /// </summary> private readonly int _value; /// <summary> /// Represents the smallest possible value of an <see cref="T:RomanNumeral"/>. This field is constant. /// </summary> public static readonly int MinValue = 1; /// <summary> /// Represents the largest possible value of an <see cref="T:RomanNumeral"/>. This field is constant. /// </summary> public static readonly int MaxValue = 3999; private static readonly string[] Thousands = { "MMM", "MM", "M" }; private static readonly string[] Hundreds = { "CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C" }; private static readonly string[] Tens = { "XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X" }; private static readonly string[] Units = { "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I" }; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="RomanNumeral"/> class. /// </summary> public RomanNumeral() { _value = 1; } /// <summary> /// Initializes a new instance of the <see cref="RomanNumeral"/> class. /// </summary> /// <param name="value">The value.</param> public RomanNumeral(int value) { _value = value; } /// <summary> /// Initializes a new instance of the <see cref="RomanNumeral"/> class. /// </summary> /// <param name="romanNumeral">The roman numeral.</param> public RomanNumeral(string romanNumeral) { int value; if (TryParse(romanNumeral, out value)) { _value = value; } } #endregion #region Methods /// <summary> /// Converts this instance to an integer. /// </summary> /// <returns>A numeric int representation.</returns> public int ToInt() { return _value; } /// <summary> /// Converts this instance to a long. /// </summary> /// <returns>A numeric long representation.</returns> public long ToLong() { return _value; } /// <summary> /// Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded. /// </summary> /// <param name="text">A string containing a number to convert. </param> /// <param name="value">When this method returns, contains the 32-bit signed integer value equivalent of the number contained in <paramref name="text"/>, /// if the conversion succeeded, or zero if the conversion failed. The conversion fails if the <paramref name="text"/> parameter is null or /// <see cref="F:System.String.Empty"/>, is not of the correct format, or represents a number less than <see cref="F:System.Int32.MinValue"/> or greater than <see cref="F:System.Int32.MaxValue"/>. This parameter is passed uninitialized. </param><filterpriority>1</filterpriority> /// <returns> /// true if <paramref name="text"/> was converted successfully; otherwise, false. /// </returns> public static bool TryParse(string text, out int value) { value = 0; if (string.IsNullOrEmpty(text)) return false; text = text.ToUpper(); int len = 0; for (int i = 0; i < 3; i++) { if (text.StartsWith(Thousands[i])) { value += 1000 * (3 - i); len = Thousands[i].Length; break; } } if (len > 0) { text = text.Substring(len); len = 0; } for (int i = 0; i < 9; i++) { if (text.StartsWith(Hundreds[i])) { value += 100 * (9 - i); len = Hundreds[i].Length; break; } } if (len > 0) { text = text.Substring(len); len = 0; } for (int i = 0; i < 9; i++) { if (text.StartsWith(Tens[i])) { value += 10 * (9 - i); len = Tens[i].Length; break; } } if (len > 0) { text = text.Substring(len); len = 0; } for (int i = 0; i < 9; i++) { if (text.StartsWith(Units[i])) { value += 9 - i; len = Units[i].Length; break; } } if (text.Length > len) { value = 0; return false; } return true; } /// <summary> /// Converts a number into a roman numeral. /// </summary> /// <param name="number">The number.</param> /// <returns></returns> private static string ToRomanNumeral(int number) { RangeGuard(number); int thousands, hundreds, tens, units; thousands = number / 1000; number %= 1000; hundreds = number / 100; number %= 100; tens = number / 10; units = number % 10; var sb = new StringBuilder(); if (thousands > 0) sb.Append(Thousands[3 - thousands]); if (hundreds > 0) sb.Append(Hundreds[9 - hundreds]); if (tens > 0) sb.Append(Tens[9 - tens]); if (units > 0) sb.Append(Units[9 - units]); return sb.ToString(); } /// <summary> /// Returns the Roman numeral that was passed in as either an Arabic numeral /// or a Roman numeral. /// </summary> /// <returns>A <see cref="System.String" /> representing a Roman Numeral</returns> public string ToRomanNumeral() { return ToString(); } /// <summary> /// Determines whether a given number is within the valid range of values for a roman numeral. /// </summary> /// <param name="number">The number to validate.</param> /// <exception cref="ArgumentOutOfRangeException"> /// $Roman numerals can not be larger than {MaxValue}. /// or /// $Roman numerals can not be smaller than {MinValue}. /// </exception> private static void RangeGuard(int number) { if (number > MaxValue) throw new ArgumentOutOfRangeException(nameof(number), number, $"Roman numerals can not be larger than {MaxValue}."); if (number < MinValue) throw new ArgumentOutOfRangeException(nameof(number), number, $"Roman numerals can not be smaller than {MinValue}."); } #endregion #region Operators /// <summary> /// Implements the operator *. /// </summary> /// <param name="firstNumeral">The first numeral.</param> /// <param name="secondNumeral">The second numeral.</param> /// <returns> /// The result of the operator. /// </returns> public static RomanNumeral operator *(RomanNumeral firstNumeral, RomanNumeral secondNumeral) { return new RomanNumeral(firstNumeral._value * secondNumeral._value); } /// <summary> /// Implements the operator /. /// </summary> /// <param name="numerator">The numerator.</param> /// <param name="denominator">The denominator.</param> /// <returns> /// The result of the operator. /// </returns> public static RomanNumeral operator /(RomanNumeral numerator, RomanNumeral denominator) { return new RomanNumeral(numerator._value / denominator._value); } /// <summary> /// Implements the operator +. /// </summary> /// <param name="firstNumeral">The first numeral.</param> /// <param name="secondNumeral">The second numeral.</param> /// <returns> /// The result of the operator. /// </returns> public static RomanNumeral operator +(RomanNumeral firstNumeral, RomanNumeral secondNumeral) { return new RomanNumeral(firstNumeral._value + secondNumeral._value); } /// <summary> /// Implements the operator -. /// </summary> /// <param name="firstNumeral">The first numeral.</param> /// <param name="secondNumeral">The second numeral.</param> /// <returns> /// The result of the operator. /// </returns> public static RomanNumeral operator -(RomanNumeral firstNumeral, RomanNumeral secondNumeral) { return new RomanNumeral(firstNumeral._value - secondNumeral._value); } #endregion #region Interface Implementations /// <summary> /// </summary> /// <param name="obj">The object.</param> /// <returns></returns> public int CompareTo(object obj) { if (obj is sbyte || obj is byte || obj is short || obj is ushort || obj is int || obj is uint || obj is long || obj is ulong || obj is float || obj is double || obj is decimal) { var value = (int)obj; return _value.CompareTo(value); } else if (obj is string) { int value; var numeral = obj as string; if (TryParse(numeral, out value)) { return _value.CompareTo(value); } } return 0; } /// <summary> /// Compares to. /// </summary> /// <param name="other">The other.</param> /// <returns></returns> public int CompareTo(RomanNumeral other) { return _value.CompareTo(other._value); } /// <summary> /// Equalses the specified other. /// </summary> /// <param name="other">The other.</param> /// <returns></returns> public bool Equals(RomanNumeral other) { return _value == other._value; } /// <summary> /// Returns the Roman Numeral which was passed to this Instance /// during creation. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents a Roman Numeral. /// </returns> public override string ToString() { return ToRomanNumeral(_value); } #endregion } }
jamesmacwhite/Radarr
src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs
C#
gpl-3.0
11,820
#include <vigir_footstep_planner/threading/expand_state_job.h> #include <vigir_footstep_planner/robot_model/robot_model.h> #include <vigir_footstep_planner/world_model/world_model.h> namespace vigir_footstep_planning { namespace threading { ExpandStateJob::ExpandStateJob(const Footstep& footstep, const PlanningState& state, StateSpace& state_space) : footstep(footstep) , state(state) , state_space(state_space) , cost(0) , risk(0) , new_state(NULL) , successful(false) { } ExpandStateJob::~ExpandStateJob() { } void ExpandStateJob::run() { new_state = NULL; successful = false; /// TODO: backward search case if (state.getPredState() == nullptr) return; next.reset(new PlanningState(footstep.performMeOnThisState(state))); State& next_state = next->getState(); if (*(state.getPredState()) == *next) return; // check reachability due to discretization const State& left_foot = state.getLeg() == LEFT ? state.getState() : state.getPredState()->getState(); const State& right_foot = state.getLeg() == RIGHT ? state.getState() : state.getPredState()->getState(); if (!RobotModel::isReachable(left_foot, right_foot, next_state)) return; // lookup costs double cost_d, risk_d; if (!state_space.getStepCost(state.getState(), state.getPredState()->getState(), next->getState(), cost_d, risk_d)) return; cost_d += footstep.getStepCost(); next_state.setCost(cost_d); next_state.setRisk(risk_d); cost = static_cast<int>(cvMmScale * cost_d); risk = static_cast<int>(cvMmScale * risk_d); // collision check if (!WorldModel::isAccessible(next->getState(), state.getState())) return; //new_state = state_space.createHashEntryIfNotExists(*next); successful = true; } } }
TRECVT/vigir_footstep_planning_core
vigir_footstep_planner/src/threading/expand_state_job.cpp
C++
gpl-3.0
1,751
### # Copyright 2016 - 2022 Green River Data Analysis, LLC # # License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md ### module HmisCsvTwentyTwentyTwo::Loader class EnrollmentCoc < GrdaWarehouse::Hud::Base include LoaderConcern include ::HMIS::Structure::EnrollmentCoc # Because GrdaWarehouse::Hud::* defines the table name, we can't use table_name_prefix :( self.table_name = 'hmis_csv_2022_enrollment_cocs' end end
greenriver/hmis-warehouse
drivers/hmis_csv_twenty_twenty_two/app/models/hmis_csv_twenty_twenty_two/loader/enrollment_coc.rb
Ruby
gpl-3.0
472
#include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/wait.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <signal.h> #include <semaphore.h> #include "socket_pool.h" #include "debug.h" #define MAX_SONS 10 volatile sig_atomic_t keep_going = 1; sem_t read_sem; sem_t write_sem; void break_loop(int sig_num); int instantiate_proxy(char* forwarder, int read_from_sockfd); int fake_server(char* listener, char* forwarder); void break_loop(int sig_num) { keep_going = 0; signal(SIGINT, break_loop); } int fake_server(char* listener, char* forwarder) { pid_t cpid[MAX_SONS]; pid_t wpid; int status = -1; int i; int sockfd; struct sockaddr_in servaddr; u_int16_t port = 53; /* listening socket */ memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port=htons(port); if (inet_pton(AF_INET, listener, &servaddr.sin_addr.s_addr) != 1) { perror("Cannot convert listener exiting\n"); exit(EXIT_FAILURE); } // this is the listening socket sockfd=socket(AF_INET, SOCK_DGRAM, 0); if (sockfd == -1) { perror("Cannot allocate listening socket. Exiting\n"); exit(EXIT_FAILURE); } if (bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) == -1) { perror("Cannot complete bind..."); fprintf(stderr, "%s", strerror(errno)); close(sockfd); exit(EXIT_FAILURE); } if(sem_init(&read_sem, 1, 1) < 0) { perror("Read semaphore initilization"); exit(EXIT_FAILURE); } if(sem_init(&write_sem, 1, 1) < 0) { perror("Read semaphore initilization"); exit(EXIT_FAILURE); } // install a signal handler in oder to break endless loop signal(SIGINT, break_loop); for (i = 0; i < MAX_SONS; i++) { if ((cpid[i] = fork()) == - 1) { perror("Cannot complete fork for all children. Exiting\n"); exit(EXIT_FAILURE); } else if (cpid[i] == 0) { fprintf(stderr, "I'm the son %d...let's do some dirty work... :( \n", getpid()); instantiate_proxy(forwarder, sockfd); return 1; } } while(keep_going) { fprintf(stderr, "I'm the father...so...I will sleep for a while\n"); sleep(13); } while ((wpid = wait(&status)) > 0) { if(WIFEXITED(status)) { fprintf(stderr, "Process %d had a clean exit and returned %d\n", (int)wpid, WEXITSTATUS(status)); } else { fprintf(stderr, "Process %d exited not due to a return call\n", (int)wpid); } } return 1; } int instantiate_proxy(char* forwarder, int read_from_sockfd) { socket_pool_t* pool; int pool_capacity = 10; /* number of consecutive timeouts in order to clean used queue */ uint32_t tmouts = 0; int maxfd = -1; fd_set rd_set; struct sockaddr_in remservaddr; socklen_t len; int rcv_bytes; char msg[1000]; char msg1[1000]; pid_t pid; struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; int n; int sockfd = read_from_sockfd; pid = getpid(); /* forwarding socket */ memset(&remservaddr, 0, sizeof(struct sockaddr_in)); remservaddr.sin_family = AF_INET; remservaddr.sin_port = htons(53); // end relay socket if (inet_pton(AF_INET, forwarder, &remservaddr.sin_addr.s_addr) != 1) { perror("Cannot convert forwarder exiting\n"); return EXIT_FAILURE; } // proxy socket pool = socket_pool_create(pool_capacity); if (!pool) { perror("Socket pool is null...."); return EXIT_FAILURE; } FD_ZERO(&rd_set); /* set read file descriptor set for select driven loop */ rd_set = pool->rd_set; FD_SET(sockfd, &rd_set); maxfd = (sockfd > socket_pool_max_fd_used(pool)) ? sockfd + 1: socket_pool_max_fd_used(pool) + 1; while (keep_going) { int i; int ret = 0; char straddr[INET_ADDRSTRLEN]; timeout.tv_sec = 5; timeout.tv_usec = 0; if ((ret = select(maxfd, &rd_set, NULL, NULL, &timeout)) == -1) { if (errno == EINTR) return 1; else { ERROR_MSG(stderr, "Select returned -1 %d(%s)\n", errno, strerror(errno)); return EXIT_FAILURE; } } else if (!ret) { // timeout ;-) ERROR_MSG(stderr, "Timeout from child %d consecutive timeouts %u\n", pid, tmouts); if (socket_pool_how_many_used(pool) == (socket_pool_capacity(pool) - (tmouts % socket_pool_capacity(pool)))) { tmouts++; DEBUG_MSG(stderr, "\t Child %d least recently used used element\n", pid); socket_pool_release(pool, pool->used_tail); ERROR_MSG(stderr, "\t Child %d Now %d used element left\n", pid, socket_pool_how_many_used(pool)); } /* set read file descriptor set for next iteration */ rd_set = pool->rd_set; FD_SET(sockfd, &rd_set); // skip to next iteration continue; } tmouts = 0; // we have a new request from attackers ;-) if (FD_ISSET(sockfd, &rd_set)) { timeout.tv_sec = 5; timeout.tv_usec = 0; conversation_t* proxy = socket_pool_acquire(pool); if (proxy) { //now relay traffic len = sizeof(proxy->clientaddr); fprintf(stderr, "Child %d want to read...\n", pid); sem_wait(&read_sem); fprintf(stderr, "\tChild %d entered read critical section...\n", pid); n = recvfrom(sockfd, msg, 1000, 0, (struct sockaddr *)&(proxy->clientaddr), &len); fprintf(stderr, "\tChild %d finished read critical section...\n", pid); sem_post(&read_sem); fprintf(stderr, "Child %d exited read critical section...\n", pid); inet_ntop(AF_INET, &(proxy->clientaddr.sin_addr), straddr, INET_ADDRSTRLEN); FD_SET(sockfd, &rd_set); printf("-------------------------------------------------------\n"); msg[n] = '\0'; for (i = 0; i < n; i++) printf("%2X", (int)msg[i]); printf("\n"); printf("-------------------------------------------------------\n"); if(sendto(proxy->sock_fd, msg, n, 0, (struct sockaddr *)&remservaddr, sizeof(remservaddr)) == -1) { perror("Errore mentre effettuo il relay"); continue; } //else { // inet_ntop(AF_INET, &remservaddr.sin_addr, straddr, INET_ADDRSTRLEN); // printf("Ho spedito %d bytes verso %s\n", n, straddr); // } } else { fprintf(stderr, "We don't have elements available or pool is null discard message\n"); FD_CLR(sockfd, &rd_set); } } // see if we can free some element conversation_t* elem; // go from the tail to the head...tail element is the oldest... for (elem = pool->used_tail; elem != NULL; elem = elem->prev) { //printf("Child %d checking for element %d\n", pid, elem->sock_fd); if(FD_ISSET(elem->sock_fd, &rd_set)) { // we got an answer // end relay...give response back printf("Got a message from fd = %d\n", elem->sock_fd); printf("Now we have %d used element, %d free element\n", socket_pool_how_many_used(pool), socket_pool_how_many_free(pool)); rcv_bytes = recvfrom(elem->sock_fd, msg1, 1000, 0, NULL, NULL); // send back response and then release socket fprintf(stderr, "Child %d want to write...\n", pid); sem_wait(&write_sem); fprintf(stderr, "\tChild %d entered write critical section...\n", pid); sendto(sockfd, msg1, rcv_bytes, 0, (struct sockaddr *)&elem->clientaddr, sizeof(elem->clientaddr)); fprintf(stderr, "\tChild %d finished write critical section...\n", pid); sem_post(&write_sem); fprintf(stderr, "Child %d exited write critical section...\n", pid); socket_pool_release(pool, elem); fprintf(stderr, "Release: Now we have %d used element, %d free element\n", socket_pool_how_many_used(pool),socket_pool_how_many_free(pool)); //break; } } } close(sockfd); socket_pool_free(pool); return 1; //exit(EXIT_SUCCESS); } int main(int argc, char** argv) { if (argc < 3) { FATAL_ERROR(stderr, "\nPlease run with %s <listen address> <forward address>\n", argv[0]); exit(EXIT_FAILURE); } fake_server(argv[1], argv[2]); return 1; }
abes975/dorayaki
src/udp_proxy.c
C
gpl-3.0
9,406
//Factorial Trailing Zeroes class Solution { public: int trailingZeroes(int n) { if(n == 0) return 0; int n2 = log2(n); int n5 = log(n)/log(5); int x2 = 0; int x5 = 0; for(int i = 1;i <= n2;i++) x2 += n/pow(2, i); for(int i = 1;i <= n5;i++) x5 += n/pow(5, i); return min(x2, x5); } };
codinganywhere/leetcode_solutions
172.cpp
C++
gpl-3.0
393
public javascripts
DFEAGILEDEVOPS/MTC
admin/public/javascripts/README.md
Markdown
gpl-3.0
18
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.*; import javafx.stage.Stage; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class Main extends Application { /** * @param args the command line arguments */ public static void main(String[] args) { Application.launch(Main.class, (java.lang.String[])null); } @Override public void start(Stage primaryStage) { try { BorderPane page = (BorderPane) FXMLLoader.load(Main.class.getResource("matrix.fxml")); Scene scene = new Scene(page); primaryStage.setResizable(false); primaryStage.setScene(scene); primaryStage.setTitle("Feuerwehrleitstelle"); primaryStage.show(); } catch (Exception ex) { System.out.println(ex); } } }
vidister/Ausbildung
berufsschule/as/Feuerwehrleitsystem/Main.java
Java
gpl-3.0
925
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LogicLayer.Models { public class Message { public bool IsSuccess { get; set; } public string Content { get; set; } } }
anbinhtrong/JwPlayer
ShowSubtitleInJwPlayer/LogicLayer/Models/Message.cs
C#
gpl-3.0
277
require 'test_helper' class Issue::CpublishTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
ImJayQiu/ssics
test/models/issue/cpublish_test.rb
Ruby
gpl-3.0
129
import os, random rfilename=random.choice(os.listdir("/storage/pictures")) rextension=os.path.splitext(rfilename)[1] picturespath='/storage/pictures/' #TODO Probably dont need a forloop can possibly do random* #TODO What if the directory is empty? for filename in os.listdir(picturespath): if filename.startswith("random"): extension=os.path.splitext(filename)[1] newname=picturespath + str(random.random()).rsplit('.',1)[1] + extension # rename the existing random wallpaper to something random filename=picturespath+filename os.rename(filename, newname) # now rename the newly randomly founded file to be random rfilename=picturespath+rfilename os.rename(rfilename, picturespath+'random'+rextension)
shoaibali/kodi.background.rotator
randombackground.py
Python
gpl-3.0
713
# -*- encoding: utf-8 -*- import os from abjad.tools import documentationtools from abjad.tools import systemtools from abjad.tools.developerscripttools.DeveloperScript import DeveloperScript from abjad.tools.developerscripttools.ReplaceInFilesScript \ import ReplaceInFilesScript class RenameModulesScript(DeveloperScript): r'''Renames classes and functions. Handle renaming the module and package, as well as any tests, documentation or mentions of the class throughout the Abjad codebase: .. shell:: ajv rename --help ''' ### PUBLIC PROPERTIES ### @property def alias(self): r'''Alias of script. Returns ``'rename'``. ''' return 'rename' @property def long_description(self): r'''Long description of script. Returns string or none. ''' return None @property def scripting_group(self): r'''Scripting group of script. Returns none. ''' return None @property def short_description(self): r'''Short description of script. Returns string. ''' return 'Rename public modules.' @property def version(self): r'''Version of script. Returns float. ''' return 1.0 ### PRIVATE METHODS ### def _codebase_name_to_codebase_docs_path(self, codebase): from abjad import abjad_configuration if codebase == 'mainline': return os.path.join( abjad_configuration.abjad_directory, 'docs', 'source', 'api', 'tools', ) elif codebase == 'experimental': return os.path.join( abjad_configuration.abjad_experimental_directory, 'docs', 'source', 'tools', ) message = 'bad codebase name: {!r}.' message = message.format(codebase) raise Exception(message) def _codebase_name_to_codebase_tools_path(self, codebase): from abjad import abjad_configuration if codebase == 'mainline': return os.path.join( abjad_configuration.abjad_directory, 'tools') elif codebase == 'experimental': return os.path.join( abjad_configuration.abjad_experimental_directory, 'tools') message = 'bad codebase name: {!r}.' message = message.format(codebase) raise Exception(message) def _confirm_name_changes(self, old_codebase, old_tools_package_name, old_module_name, new_codebase, new_tools_package_name, new_module_name, ): max_codebase = max(len(old_codebase), len(new_codebase)) old_codebase = old_codebase.ljust(max_codebase) new_codebase = new_codebase.ljust(max_codebase) print('') print('Is ...') print('') print(' [{}] {}.{}()'.format( old_codebase, old_tools_package_name, old_module_name)) print(' ===>') print(' [{}] {}.{}()'.format( new_codebase, new_tools_package_name, new_module_name)) print('') string = raw_input('... correct [yes, no, abort]? ').lower() print('') if string in ('y', 'yes'): return True elif string in ('a', 'abort', 'q', 'quit'): raise SystemExit elif string in ('n', 'no'): return False def _get_object_names(self, kind, codebase, tools_package_name): assert kind in ('class', 'function') tools_path = self._codebase_name_to_codebase_tools_path(codebase) path = os.path.join(tools_path, tools_package_name) if kind == 'class': generator = documentationtools.yield_all_classes( code_root=path, include_private_objects=True, ) elif kind == 'function': generator = documentationtools.yield_all_functions( code_root=path, include_private_objects=True, ) return tuple(sorted(generator, key=lambda x: x.__name__)) def _get_tools_package_names(self, codebase): tools_path = self._codebase_name_to_codebase_tools_path(codebase) names = [] for x in os.listdir(tools_path): if os.path.isdir(os.path.join(tools_path, x)): if not x.startswith(('_', '.')): names.append(x) return tuple(sorted(names)) def _parse_tools_package_path(self, path): from abjad import abjad_configuration if '.' not in path: raise SystemExit tools_package_name, module_name = path.split('.') mainline_tools_directory = os.path.join( abjad_configuration.abjad_directory, 'tools', ) for directory_name in os.listdir(mainline_tools_directory): directory = os.path.join( mainline_tools_directory, directory_name) if not os.path.isdir(directory): continue elif directory_name != tools_package_name: continue return 'mainline', tools_package_name, module_name experimental_tools_directory = os.path.join( abjad_configuration.abjad_experimental_directory, 'tools', ) for directory_name in os.listdir(mainline_tools_directory): directory = os.path.join( experimental_tools_directory, directory_name) if not os.path.isdir(directory): continue elif directory_name != tools_package_name: continue return 'experimental', tools_package_name, module_name raise SystemExit def _rename_old_api_page(self, old_codebase, old_tools_package_name, old_module_name, new_codebase, new_tools_package_name, new_module_name, ): print('Renaming old API page ...') old_docs_path = self._codebase_name_to_codebase_docs_path(old_codebase) new_docs_path = self._codebase_name_to_codebase_docs_path(new_codebase) old_rst_file_name = old_module_name + '.rst' new_rst_file_name = new_module_name + '.rst' old_api_path = os.path.join( old_docs_path, old_tools_package_name, old_rst_file_name) new_api_path = os.path.join( new_docs_path, new_tools_package_name, new_rst_file_name) command = 'mv {} {}'.format( old_api_path, new_api_path) systemtools.IOManager.spawn_subprocess(command) print('') def _rename_old_module(self, old_codebase, old_tools_package_name, old_module_name, new_codebase, new_tools_package_name, new_module_name, ): print('Renaming old module ...') old_tools_path = self._codebase_name_to_codebase_tools_path( old_codebase) new_tools_path = self._codebase_name_to_codebase_tools_path( new_codebase) old_module = old_module_name + '.py' old_path = os.path.join( old_tools_path, old_tools_package_name, old_module) new_module = new_module_name + '.py' new_path = os.path.join( new_tools_path, new_tools_package_name, new_module) command = 'git mv -f {} {}'.format( old_path, new_path) systemtools.IOManager.spawn_subprocess(command) print('') def _rename_old_test_files(self, old_codebase, old_tools_package_name, old_module_name, new_codebase, new_tools_package_name, new_module_name, ): print('Renaming old test file(s) ...') old_tools_path = self._codebase_name_to_codebase_tools_path( old_codebase) old_test_path = os.path.join( old_tools_path, old_tools_package_name, 'test') if not os.path.exists(old_test_path): return new_tools_path = self._codebase_name_to_codebase_tools_path( new_codebase) new_test_path = os.path.join( new_tools_path, new_tools_package_name, 'test') old_test_file_prefix = 'test_{}_{}'.format( old_tools_package_name, old_module_name) old_test_file_names = [x for x in os.listdir(old_test_path) if x.startswith(old_test_file_prefix) and x.endswith('.py')] for old_test_file_name in old_test_file_names: old_test_file_path = os.path.join( old_test_path, old_test_file_name) old_test_file_suffix = old_test_file_name[ len(old_test_file_prefix):] new_test_file_name = 'test_{}_{}{}'.format( new_tools_package_name, new_module_name, old_test_file_suffix) new_test_file_path = os.path.join( new_test_path, new_test_file_name) command = 'git mv -f {} {}'.format( old_test_file_path, new_test_file_path) systemtools.IOManager.spawn_subprocess(command) print('') def _update_codebase(self, old_codebase, old_tools_package_name, old_module_name, new_codebase, new_tools_package_name, new_module_name, ): from abjad import abjad_configuration without_dirs = ['--without-dirs', 'build', '--without-dirs', '_build'] directory = abjad_configuration.abjad_root_directory print('Updating codebase ...') print('') old_text = '{}.{}'.format(old_tools_package_name, old_module_name) new_text = '{}.{}'.format(new_tools_package_name, new_module_name) command = [ directory, old_text, new_text, '--force', '--whole-words-only', #'--verbose', ] command.extend(without_dirs) ReplaceInFilesScript()(command) print('') old_text = 'test_{}_{}_'.format( old_tools_package_name, old_module_name) new_text = 'test_{}_{}_'.format( new_tools_package_name, new_module_name) command = [directory, old_text, new_text, '--force', '--verbose'] command.extend(without_dirs) ReplaceInFilesScript()(command) print('') old_text = old_module_name new_text = new_module_name command = [ directory, old_text, new_text, '--force', '--whole-words-only', #'--verbose', ] command.extend(without_dirs) ReplaceInFilesScript()(command) print('') ### PUBLIC METHODS ### def process_args(self, args): r'''Processes `args`. Returns none. ''' systemtools.IOManager.clear_terminal() # Handle source path: old_codebase, old_tools_package_name, old_module_name = \ self._parse_tools_package_path(args.source) old_codebase_tools_path = self._codebase_name_to_codebase_tools_path( old_codebase) old_module_path = os.path.join( old_codebase_tools_path, old_tools_package_name, old_module_name + '.py', ) if not os.path.exists(old_module_path): message = 'source does not exist: {}' message = message.format(old_module_path) raise SystemExit(message) # Handle destination path: new_codebase, new_tools_package_name, new_module_name = \ self._parse_tools_package_path(args.destination) new_codebase_tools_path = self._codebase_name_to_codebase_tools_path( new_codebase) new_module_path = os.path.join( new_codebase_tools_path, new_tools_package_name, new_module_name + '.py', ) if os.path.exists(new_module_path): message = 'destination already exists: {}' message = message.format(old_module_path) raise SystemExit(message) # Process changes: new_args = ( old_codebase, old_tools_package_name, old_module_name, new_codebase, new_tools_package_name, new_module_name, ) if not self._confirm_name_changes(*new_args): raise SystemExit self._rename_old_test_files(*new_args) self._rename_old_api_page(*new_args) self._rename_old_module(*new_args) self._update_codebase(*new_args) raise SystemExit def setup_argument_parser(self, parser): r'''Sets up argument `parser`. Returns none. ''' parser.add_argument( 'source', help='toolspackage path of source module', ) parser.add_argument( 'destination', help='toolspackage path of destination module', )
mscuthbert/abjad
abjad/tools/developerscripttools/RenameModulesScript.py
Python
gpl-3.0
13,078
""" Module defining the Event class which is used to manage collissions and check their validity """ from itertools import combinations from copy import copy from particle import Particle class EventParticle(object): def __init__(self, particle1, particle2): self.particle1 = particle1 self.particle2 = particle2 self.id = (self.particle1.getCollisionCountAsCopy(), self.particle2.getCollisionCountAsCopy()) self.timeUntilCollision = self.particle1.collideParticle(self.particle2) def isValid(self): return self.id == (self.particle1.getCollisionCountAsCopy(), self.particle2.getCollisionCountAsCopy()) def reevaluateCollisionTime(self): self.id = (self.particle1.getCollisionCountAsCopy(), self.particle2.getCollisionCountAsCopy()) self.timeUntilCollision = self.particle1.collideParticle(self.particle2) def doCollision(self): self.particle1.bounceParticle(self.particle2) class EventWallX(object): def __init__(self, particle): self.particle = particle self.id = self.particle.getCollisionCountAsCopy() self.timeUntilCollision = self.particle.collidesWallX() def isValid(self): return self.id == self.particle.getCollisionCountAsCopy() def reevaluateCollisionTime(self): self.id = self.particle.getCollisionCountAsCopy() self.timeUntilCollision = self.particle.collidesWallX() def doCollision(self): self.particle.bounceX() class EventWallY(object): def __init__(self, particle): self.particle = particle self.id = self.particle.getCollisionCountAsCopy() self.timeUntilCollision = self.particle.collidesWallY() def isValid(self): return self.id == self.particle.getCollisionCountAsCopy() def reevaluateCollisionTime(self): self.id = self.particle.getCollisionCountAsCopy() self.timeUntilCollision = self.particle.collidesWallY() def doCollision(self): self.particle.bounceY() class EventManager(object): def __init__(self, ListOfParticles): self.ListOfParticles = ListOfParticles self.ListOfEvents = [] for (particle1, particle2) in combinations(self.ListOfParticles, 2): self.ListOfEvents.append(EventParticle(particle1, particle2)) for particle in self.ListOfParticles: self.ListOfEvents.append(EventWallX(particle)) self.ListOfEvents.append(EventWallY(particle)) self.sortEventList() def sortEventList(self): def sorting_closure(event): if event.timeUntilCollision is None or event.timeUntilCollision < 0.0: return 1.0e7 else: return event.timeUntilCollision self.ListOfEvents = sorted(self.ListOfEvents, key=sorting_closure) def step(self): for event in self.ListOfEvents: if not event.isValid(): event.reevaluateCollisionTime() self.sortEventList() collTime = copy(self.ListOfEvents[0].timeUntilCollision) for particle in self.ListOfParticles: particle.advance(collTime) self.ListOfEvents[0].doCollision() for event in self.ListOfEvents: if event.timeUntilCollision is not None: event.timeUntilCollision -= collTime if __name__ == '__main__': import numpy as np import pylab as plt a = Particle(np.array([0.1, 0.5]), np.array([0.01, 0.1]), 0.05, 2.0) b = Particle(np.array([0.4, 0.5]), np.array([-0.1, 0.01]), 0.05, 2.0) manager = EventManager([a,b]) for i in range(20): plt.title(a.t) plt.scatter([a._x[0], b._x[0]], [a._x[1], b._x[1]]) print a._x print b._x plt.xlim([0,1]) plt.ylim([0,1]) plt.show() manager.step()
hniemeyer/HardSphereSim
EventManager.py
Python
gpl-3.0
4,177
# -*- coding: utf-8 -*- """ Projy template for PythonPackage. """ # system from datetime import date from os import mkdir, rmdir from shutil import move from subprocess import call # parent class from projy.templates.ProjyTemplate import ProjyTemplate # collectors from projy.collectors.AuthorCollector import AuthorCollector from projy.collectors.AuthorMailCollector import AuthorMailCollector class DjangoProjectTemplate(ProjyTemplate): """ Projy template class for PythonPackage. """ def __init__(self): ProjyTemplate.__init__(self) def directories(self): """ Return the names of directories to be created. """ directories_description = [ self.project_name, self.project_name + '/conf', self.project_name + '/static', ] return directories_description def files(self): """ Return the names of files to be created. """ files_description = [ # configuration [ self.project_name, 'Makefile', 'DjangoMakefileTemplate' ], [ self.project_name + '/conf', 'requirements_base.txt', 'DjangoRequirementsBaseTemplate' ], [ self.project_name + '/conf', 'requirements_dev.txt', 'DjangoRequirementsDevTemplate' ], [ self.project_name + '/conf', 'requirements_production.txt', 'DjangoRequirementsProdTemplate' ], [ self.project_name + '/conf', 'nginx.conf', 'DjangoNginxConfTemplate' ], [ self.project_name + '/conf', 'supervisord.conf', 'DjangoSupervisorConfTemplate' ], [ self.project_name, 'fabfile.py', 'DjangoFabfileTemplate' ], [ self.project_name, 'CHANGES.txt', 'PythonPackageCHANGESFileTemplate' ], [ self.project_name, 'LICENSE.txt', 'GPL3FileTemplate' ], [ self.project_name, 'README.txt', 'READMEReSTFileTemplate' ], [ self.project_name, '.gitignore', 'DjangoGitignoreTemplate' ], # django files [ self.project_name, 'dev.py', 'DjangoSettingsDevTemplate' ], [ self.project_name, 'prod.py', 'DjangoSettingsProdTemplate' ], ] return files_description def substitutes(self): """ Return the substitutions for the templating replacements. """ author_collector = AuthorCollector() mail_collector = AuthorMailCollector() substitute_dict = { 'project': self.project_name, 'project_lower': self.project_name.lower(), 'date': date.today().isoformat(), 'author': author_collector.collect(), 'author_email': mail_collector.collect(), } return substitute_dict def posthook(self): # build the virtualenv call(['make']) # create the Django project call(['./venv/bin/django-admin.py', 'startproject', self.project_name]) # transform original settings files into 3 files for different env mkdir('{p}/settings'.format(p=self.project_name)) self.touch('{p}/settings/__init__.py'.format(p=self.project_name)) move('dev.py', '{p}/settings'.format(p=self.project_name)) move('prod.py', '{p}/settings'.format(p=self.project_name)) move('{p}/{p}/settings.py'.format(p=self.project_name), '{p}/settings/base.py'.format(p=self.project_name)) # organize files nicely mkdir('{p}/templates'.format(p=self.project_name)) move('{p}/manage.py'.format(p=self.project_name), 'manage.py') move('{p}/{p}/__init__.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) move('{p}/{p}/urls.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) move('{p}/{p}/wsgi.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) rmdir('{p}/{p}'.format(p=self.project_name)) # create empty git repo call(['git', 'init']) # replace some lines self.replace_in_file('{p}/wsgi.py'.format(p=self.project_name), '"{p}.settings"'.format(p=self.project_name), '"{p}.settings.production"'.format(p=self.project_name)) self.replace_in_file('{p}/settings/base.py'.format(p=self.project_name), u" # ('Your Name', 'your_email@example.com'),", u" ('{}', '{}'),".format(self.substitutes()['author'], self.substitutes()['author_email']))
stephanepechard/projy
projy/templates/DjangoProjectTemplate.py
Python
gpl-3.0
4,869
#ifndef RECTC_H #define RECTC_H #include <QDebug> #include "coordinates.h" class RectC { public: RectC() {} RectC(const Coordinates &topLeft, const Coordinates &bottomRight) : _tl(topLeft), _br(bottomRight) {} RectC(const Coordinates &center, double radius); bool isNull() const {return _tl.isNull() && _br.isNull();} bool isValid() const {return (_tl.isValid() && _br.isValid() && _tl != _br);} Coordinates topLeft() const {return _tl;} Coordinates bottomRight() const {return _br;} Coordinates center() const {return Coordinates((_tl.lon() + _br.lon()) / 2.0, (_tl.lat() + _br.lat()) / 2.0);} RectC operator|(const RectC &r) const; RectC &operator|=(const RectC &r) {*this = *this | r; return *this;} RectC operator&(const RectC &r) const; RectC &operator&=(const RectC &r) {*this = *this & r; return *this;} RectC united(const Coordinates &c) const; private: Coordinates _tl, _br; }; #ifndef QT_NO_DEBUG QDebug operator<<(QDebug dbg, const RectC &rect); #endif // QT_NO_DEBUG #endif // RECTC_H
halftux/GPXSee
src/common/rectc.h
C
gpl-3.0
1,037
# Copy current unfinished logfile to initramfs for debug purpose. # Usually REAR_LOGFILE=/var/log/rear/rear-$HOSTNAME.log # The REAR_LOGFILE name set by main script from LOGFILE in default.conf # but later user config files are sourced in main script where LOGFILE can be set different # so that the user config LOGFILE basename (except a trailing '.log') is used as target logfile name: logfile_basename=$( basename $LOGFILE ) LogPrint "Copying logfile $REAR_LOGFILE into initramfs as '/tmp/${logfile_basename%.*}-partial-$(date -Iseconds).log'" mkdir -p $v $ROOTFS_DIR/tmp >&2 cp -a $v $REAR_LOGFILE $ROOTFS_DIR/tmp/${logfile_basename%.*}-partial-$(date -Iseconds).log >&2
terreActive/rear
usr/share/rear/rescue/default/910_copy_logfile.sh
Shell
gpl-3.0
676
package com.epam.wilma.stubconfig.json.parser; /*========================================================================== Copyright since 2013, EPAM Systems This file is part of Wilma. Wilma 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. Wilma 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 Wilma. If not, see <http://www.gnu.org/licenses/>. ===========================================================================*/ import com.epam.wilma.domain.stubconfig.dialog.response.ResponseFormatter; import com.epam.wilma.domain.stubconfig.dialog.response.ResponseFormatterDescriptor; import com.epam.wilma.domain.stubconfig.exception.DescriptorCannotBeParsedException; import com.epam.wilma.domain.stubconfig.exception.DescriptorValidationFailedException; import com.epam.wilma.domain.stubconfig.parameter.ParameterList; import com.epam.wilma.stubconfig.configuration.StubConfigurationAccess; import com.epam.wilma.stubconfig.configuration.domain.PropertyDto; import com.epam.wilma.stubconfig.initializer.template.ResponseFormatterInitializer; import com.epam.wilma.stubconfig.json.parser.helper.ObjectParser; import com.epam.wilma.stubconfig.json.parser.helper.ParameterListParser; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.LinkedHashSet; import java.util.Set; /** * Builds a set of {@link ResponseFormatter}s from a JSON object. * * @author Tamas_Kohegyi */ @Component public class ResponseFormatterDescriptorJsonParser implements ObjectParser<Set<ResponseFormatterDescriptor>> { private static final String RESPONSE_FORMATTER_SET_INVOKER_TAG = "responseFormatterSetInvoker"; private static final String RESPONSE_FORMATTER_TAG = "responseFormatter"; private Integer maxDepthOfJsonTree; @Autowired private ResponseFormatterInitializer formatterInitializer; @Autowired private StubConfigurationAccess configurationAccess; @Autowired private ParameterListParser parameterListParser; @Override public Set<ResponseFormatterDescriptor> parseObject(final JSONObject responseDescriptorObject, final JSONObject root) { //This number represents the depth of the subtree int depth = 0; return parse(responseDescriptorObject, root, depth); } private Set<ResponseFormatterDescriptor> parse(final JSONObject responseDescriptorObject, final JSONObject root, final int depth) { Set<ResponseFormatterDescriptor> responseFormatterDescriptorSet = new LinkedHashSet<>(); if (responseDescriptorObject.has("responseFormatterSet")) { JSONArray responseFormatterSet = responseDescriptorObject.getJSONArray("responseFormatterSet"); for (int i = 0; i < responseFormatterSet.length(); i++) { JSONObject formatter = responseFormatterSet.getJSONObject(i); if (formatter.has(RESPONSE_FORMATTER_TAG)) { //response formatter responseFormatterDescriptorSet.add(parseResponseFormatter(formatter.getJSONObject(RESPONSE_FORMATTER_TAG), root)); } else { if (formatter.has(RESPONSE_FORMATTER_SET_INVOKER_TAG)) { //response formatter set invoker String name = formatter.getString(RESPONSE_FORMATTER_SET_INVOKER_TAG); int newDepth = validateDepth(depth, name); responseFormatterDescriptorSet.addAll(parseResponseFormatterSetInvoker(name, root, newDepth)); } } } } return responseFormatterDescriptorSet; } private Set<ResponseFormatterDescriptor> parseResponseFormatterSetInvoker(final String responseFormatterSetName, final JSONObject root, final int depth) { JSONObject formatterSet = null; boolean found = false; if (root.has("responseFormatterSets")) { JSONArray responseFormatterSetArray = root.getJSONArray("responseFormatterSets"); for (int i = 0; responseFormatterSetArray.length() > i; i++) { JSONObject responseFormatterSet = responseFormatterSetArray.getJSONObject(i); String name = responseFormatterSet.getString("name"); if (name.contentEquals(responseFormatterSetName)) { formatterSet = responseFormatterSet; found = true; break; } } } else { throw new DescriptorCannotBeParsedException("There is no Response Formatter Set defined."); } if (!found) { throw new DescriptorCannotBeParsedException("Cannot find Response Formatter Set with name: '" + responseFormatterSetName + "'."); } return parse(formatterSet, root, depth); } private ResponseFormatterDescriptor parseResponseFormatter(final JSONObject responseFormatterObject, final JSONObject root) { String clazz = responseFormatterObject.getString("class"); ParameterList params = parameterListParser.parseObject(responseFormatterObject, root); ResponseFormatter responseFormatter = formatterInitializer.getExternalClassObject(clazz); return new ResponseFormatterDescriptor(responseFormatter, params); } private int validateDepth(final int depth, final String invokerName) { int newDepth = depth + 1; getMaxDepth(); if (newDepth >= maxDepthOfJsonTree) { throw new DescriptorValidationFailedException( "Validation of stub descriptor failed: Response-descriptor subtree is too deep or contains circles, error occurs at: responseFormatterSetInvoker = '" + invokerName + "'"); } return newDepth; } private void getMaxDepth() { if (maxDepthOfJsonTree == null) { PropertyDto properties = configurationAccess.getProperties(); maxDepthOfJsonTree = properties.getMaxDepthOfTree(); } } }
epam/Wilma
wilma-application/modules/wilma-stub-configuration-parser/src/main/java/com/epam/wilma/stubconfig/json/parser/ResponseFormatterDescriptorJsonParser.java
Java
gpl-3.0
6,671
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Host; use App\SwitchModel; use App\PortPlusOid; use App\Port; use App\LinkA; use App\LinkB; use App\Submap; use App\Http\Requests; use App\Http\Controllers\Controller; class LinkController extends Controller { // Show Link Dashboard public function index() { $data['hosts'] = Host::orderBy('name', 'asc')->get(); $data['portPlusOids'] = PortPlusOid::orderBy('id', 'asc')->get(); $data['ports'] = Port::orderBy('name', 'asc')->get(); $data['linkAs'] = LinkA::orderBy('created_at', 'desc')->get(); $data['linkBs'] = LinkB::orderBy('created_at', 'desc')->get(); return view('link.index', $data); } // Call PortPlusOids to select public function callPortPlusOids($hostId) { $host = Host::find($hostId); $hostSwitchModel = $host->switchModel->id; $portPlusOids = \DB::table('port_plus_oids') ->join('port_plus_oid_switch_model', 'port_plus_oids.id', '=', 'port_plus_oid_switch_model.port_plus_oid_id') ->join('ports', 'ports.id', '=', 'port_plus_oids.port_id') ->select('port_plus_oids.id', 'ports.name') ->where('switch_model_id', '=', $hostSwitchModel) ->orderBy('ports.name', 'asc') ->get(); return response()->json($portPlusOids); } // Add new Link public function store(Request $request) { $this->validate($request, [ 'hostA' => 'required', 'portPlusOidA' => 'required', 'hostB' => 'required', 'portPlusOidB' => 'required', ]); $linkA = new LinkA; $linkA->host_id = $request->hostA; $linkA->port_plus_oid_id = $request->portPlusOidA; $hostA = Host::find($request->hostA); $linkA->host()->associate($hostA); $portPlusOidA = PortPlusOid::find($request->portPlusOidA); $linkA->portPlusOid()->associate($portPlusOidA); $linkA->save(); $linkB = new LinkB; $linkB->host_id = $request->hostB; $linkB->port_plus_oid_id = $request->portPlusOidB; $hostB = Host::find($request->hostB); $linkB->host()->associate($hostB); $portPlusOidB = PortPlusOid::find($request->portPlusOidB); $linkB->portPlusOid()->associate($portPlusOidB); $linkB->linkA()->associate($linkA); $linkB->save(); $submapA = $linkA->host->submap->id; $submapB = $linkB->host->submap->id; if($submapA != $submapB) { $linkC = new LinkA; $linkC->host_id = $linkB->host_id; $linkC->port_plus_oid_id = $linkB->port_plus_oid_id; $linkC->save(); $linkD = new LinkB; $linkD->host_id = $linkA->host_id; $linkD->port_plus_oid_id = $linkA->port_plus_oid_id; $linkD->link_a_id = $linkC->id; $linkD->save(); } return redirect('/link'); } // Delete Link public function destroy(Request $request) { $linkA = LinkA::find($request->id); $linkB = LinkB::find($linkA->LinkB->id); $linkB->delete(); $linkA->delete(); return redirect('/link'); } // Show Link Edit Form public function edit($id) { $data['linkA'] = LinkA::find($id); $data['hosts'] = Host::orderBy('name', 'asc')->get(); $data['portPlusOids'] = PortPlusOid::orderBy('id', 'asc')->get(); $data['ports'] = Port::orderBy('name', 'asc')->get(); $data['linkAs'] = LinkA::orderBy('created_at', 'desc')->get(); $data['linkBs'] = LinkB::orderBy('created_at', 'desc')->get(); return view('link.edit', $data); } // Update Link public function update(Request $request) { $linkA = LinkA::find($request->id); $linkA->host_id = $request->hostA; $linkA->port_plus_oid_id = $request->portPlusOidA; $linkA->save(); $linkB = LinkB::find($linkA->linkB->id); $linkB->host_id = $request->hostB; $linkB->port_plus_oid_id = $request->portPlusOidB; $linkB->save(); return redirect('/link'); } }
carloswimmer/mapsys
app/Http/Controllers/LinkController.php
PHP
gpl-3.0
3,665
# - Try to find readline include dirs and libraries # # Usage of this module as follows: # # find_package(Readline) # # Variables used by this module, they can change the default behaviour and need # to be set before calling find_package: # # READLINE_INSTALL_PATH Set this variable to the root installation of # readline if the module has problems finding the # proper installation path. # # Variables defined by this module: # # READLINE_INCLUDE_PATH The readline include directories. # READLINE_LIBRARY The readline library. find_path(READLINE_INSTALL_PATH NAMES include/readline/readline.h ) find_path(READLINE_INCLUDE_PATH NAMES readline/readline.h HINTS ${READLINE_INSTALL_PATH}/include ) find_library(READLINE_LIBRARY NAMES readline HINTS ${READLINE_INSTALL_PATH}/lib ) if(READLINE_INCLUDE_PATH AND READLINE_LIBRARY) message(STATUS "readline include : ${READLINE_INCLUDE_PATH}") message(STATUS "readline libs : ${READLINE_LIBRARY}") else(READLINE_INCLUDE_PATH AND READLINE_LIBRARY) message(FATAL "libreadline not found") endif(READLINE_INCLUDE_PATH AND READLINE_LIBRARY) mark_as_advanced( READLINE_INSTALL_PATH READLINE_INCLUDE_PATH READLINE_LIBRARY )
thelfer/tfel-plot
cmake/modules/FindReadLine.cmake
CMake
gpl-3.0
1,282
/* ################################################################ ### SLIDE ANYTHING PLUGIN - STYLE FOR TINYMCE EDITOR BUTTOND ### ################################################################ */ i.mce-i-icon { font:400 20px/1 dashicons; padding:0px; vertical-align:top; speak:none; -webkit-font-smoothing:antialiased; -moz-osx-font-smoothing:grayscale; margin-left:-2px; padding-right:2px }
rUmbelino/lemuel
wp-content/plugins/slide-anything/css/tinymce_style.css
CSS
gpl-3.0
429
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * 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 com.watabou.pixeldungeon.scenes; import java.util.HashMap; import java.util.Locale; import com.watabou.noosa.BitmapText; import com.watabou.noosa.BitmapTextMultiline; import com.watabou.noosa.Camera; import com.watabou.noosa.Game; import com.watabou.noosa.Group; import com.watabou.noosa.Image; import com.watabou.noosa.audio.Sample; import com.watabou.noosa.particles.BitmaskEmitter; import com.watabou.noosa.particles.Emitter; import com.watabou.noosa.ui.Button; import com.watabou.pixeldungeon.Assets; import com.watabou.pixeldungeon.Badges; import com.watabou.pixeldungeon.Dungeon; import com.watabou.pixeldungeon.GamesInProgress; import com.watabou.pixeldungeon.PixelDungeon; import com.watabou.pixeldungeon.R; import com.watabou.pixeldungeon.actors.hero.HeroClass; import com.watabou.pixeldungeon.effects.BannerSprites; import com.watabou.pixeldungeon.effects.BannerSprites.Type; import com.watabou.pixeldungeon.effects.Speck; import com.watabou.pixeldungeon.ui.Archs; import com.watabou.pixeldungeon.ui.ExitButton; import com.watabou.pixeldungeon.ui.Icons; import com.watabou.pixeldungeon.ui.RedButton; import com.watabou.pixeldungeon.utils.Utils; import com.watabou.pixeldungeon.windows.WndChallenges; import com.watabou.pixeldungeon.windows.WndClass; import com.watabou.pixeldungeon.windows.WndMessage; import com.watabou.pixeldungeon.windows.WndOptions; import com.watabou.utils.Callback; public class StartScene extends PixelScene { private static final float BUTTON_HEIGHT = 24; private static final float GAP = 2; private static final String TXT_LOAD = Game.getVar(R.string.StartScene_Load); private static final String TXT_NEW = Game.getVar(R.string.StartScene_New); private static final String TXT_ERASE = Game.getVar(R.string.StartScene_Erase); private static final String TXT_DPTH_LVL = Game.getVar(R.string.StartScene_Depth); private static final String TXT_REALLY = Game.getVar(R.string.StartScene_Really); private static final String TXT_WARNING = Game.getVar(R.string.StartScene_Warning); private static final String TXT_YES = Game.getVar(R.string.StartScene_Yes); private static final String TXT_NO = Game.getVar(R.string.StartScene_No); private static final String TXT_UNLOCK = Game.getVar(R.string.StartScene_Unlock); private static final String TXT_WIN_THE_GAME = Game.getVar(R.string.StartScene_WinGame); private static final float WIDTH_P = 116; private static final float HEIGHT_P = 220; private static final float WIDTH_L = 224; private static final float HEIGHT_L = 124; private static HashMap<HeroClass, ClassShield> shields = new HashMap<HeroClass, ClassShield>(); private float buttonX; private float buttonY; private GameButton btnLoad; private GameButton btnNewGame; private boolean huntressUnlocked; private Group unlock; public static HeroClass curClass; @Override public void create() { super.create(); Badges.loadGlobal(); uiCamera.visible = false; int w = Camera.main.width; int h = Camera.main.height; float width, height; if (PixelDungeon.landscape()) { width = WIDTH_L; height = HEIGHT_L; } else { width = WIDTH_P; height = HEIGHT_P; } float left = (w - width) / 2; float top = (h - height) / 2; float bottom = h - top; Archs archs = new Archs(); archs.setSize( w, h ); add( archs ); Image title = BannerSprites.get( Type.SELECT_YOUR_HERO ); title.x = align( (w - title.width()) / 2 ); title.y = align( top ); add( title ); buttonX = left; buttonY = bottom - BUTTON_HEIGHT; btnNewGame = new GameButton( TXT_NEW ) { @Override protected void onClick() { if (GamesInProgress.check( curClass ) != null) { StartScene.this.add( new WndOptions( TXT_REALLY, TXT_WARNING, TXT_YES, TXT_NO ) { @Override protected void onSelect( int index ) { if (index == 0) { startNewGame(); } } } ); } else { startNewGame(); } } }; add( btnNewGame ); btnLoad = new GameButton( TXT_LOAD ) { @Override protected void onClick() { InterlevelScene.mode = InterlevelScene.Mode.CONTINUE; Game.switchScene( InterlevelScene.class ); } }; add( btnLoad ); float centralHeight = buttonY - title.y - title.height(); HeroClass[] classes = { HeroClass.WARRIOR, HeroClass.MAGE, HeroClass.ROGUE, HeroClass.HUNTRESS }; for (HeroClass cl : classes) { ClassShield shield = new ClassShield( cl ); shields.put( cl, shield ); add( shield ); } if (PixelDungeon.landscape()) { float shieldW = width / 4; float shieldH = Math.min( centralHeight, shieldW ); top = title.y + title.height + (centralHeight - shieldH) / 2; for (int i=0; i < classes.length; i++) { ClassShield shield = shields.get( classes[i] ); shield.setRect( left + i * shieldW, top, shieldW, shieldH ); } ChallengeButton challenge = new ChallengeButton(); challenge.setPos( w / 2 - challenge.width() / 2, top + shieldH - challenge.height() / 2 ); add( challenge ); } else { float shieldW = width / 2; float shieldH = Math.min( centralHeight / 2, shieldW * 1.2f ); top = title.y + title.height() + centralHeight / 2 - shieldH; for (int i=0; i < classes.length; i++) { ClassShield shield = shields.get( classes[i] ); shield.setRect( left + (i % 2) * shieldW, top + (i / 2) * shieldH, shieldW, shieldH ); } ChallengeButton challenge = new ChallengeButton(); challenge.setPos( w / 2 - challenge.width() / 2, top + shieldH - challenge.height() / 2 ); add( challenge ); } unlock = new Group(); add( unlock ); if (!(huntressUnlocked = Badges.isUnlocked( Badges.Badge.BOSS_SLAIN_3 ))) { BitmapTextMultiline text = PixelScene.createMultiline( TXT_UNLOCK, 9 ); text.maxWidth = (int)width; text.measure(); float pos = (bottom - BUTTON_HEIGHT) + (BUTTON_HEIGHT - text.height()) / 2; for (BitmapText line : text.new LineSplitter().split()) { line.measure(); line.hardlight( 0xFFFF00 ); line.x = PixelScene.align( w / 2 - line.width() / 2 ); line.y = PixelScene.align( pos ); unlock.add( line ); pos += line.height(); } } ExitButton btnExit = new ExitButton(); btnExit.setPos( Camera.main.width - btnExit.width(), 0 ); add( btnExit ); curClass = null; updateClass( HeroClass.values()[PixelDungeon.lastClass()] ); fadeIn(); Badges.loadingListener = new Callback() { @Override public void call() { if (Game.scene() == StartScene.this) { PixelDungeon.switchNoFade( StartScene.class ); } } }; } @Override public void destroy() { Badges.saveGlobal(); Badges.loadingListener = null; super.destroy(); } private void updateClass( HeroClass cl ) { if (curClass == cl) { add( new WndClass( cl ) ); return; } if (curClass != null) { shields.get( curClass ).highlight( false ); } shields.get( curClass = cl ).highlight( true ); if (cl != HeroClass.HUNTRESS || huntressUnlocked) { unlock.visible = false; GamesInProgress.Info info = GamesInProgress.check( curClass ); if (info != null) { btnLoad.visible = true; btnLoad.secondary( Utils.format( TXT_DPTH_LVL, info.depth, info.level ), info.challenges ); btnNewGame.visible = true; btnNewGame.secondary( TXT_ERASE, false ); float w = (Camera.main.width - GAP) / 2 - buttonX; btnLoad.setRect( buttonX, buttonY, w, BUTTON_HEIGHT ); btnNewGame.setRect( btnLoad.right() + GAP, buttonY, w, BUTTON_HEIGHT ); } else { btnLoad.visible = false; btnNewGame.visible = true; btnNewGame.secondary( null, false ); btnNewGame.setRect( buttonX, buttonY, Camera.main.width - buttonX * 2, BUTTON_HEIGHT ); } } else { unlock.visible = true; btnLoad.visible = false; btnNewGame.visible = false; } } private void startNewGame() { Dungeon.hero = null; InterlevelScene.mode = InterlevelScene.Mode.DESCEND; if (PixelDungeon.intro()) { PixelDungeon.intro( false ); Game.switchScene( IntroScene.class ); } else { Game.switchScene( InterlevelScene.class ); } } @Override protected void onBackPressed() { PixelDungeon.switchNoFade( TitleScene.class ); } private static class GameButton extends RedButton { private static final int SECONDARY_COLOR_N = 0xCACFC2; private static final int SECONDARY_COLOR_H = 0xFFFF88; private BitmapText secondary; public GameButton( String primary ) { super( primary ); this.secondary.text( null ); } @Override protected void createChildren() { super.createChildren(); secondary = createText( 6 ); add( secondary ); } @Override protected void layout() { super.layout(); if (secondary.text().length() > 0) { text.y = align( y + (height - text.height() - secondary.baseLine()) / 2 ); secondary.x = align( x + (width - secondary.width()) / 2 ); secondary.y = align( text.y + text.height() ); } else { text.y = align( y + (height - text.baseLine()) / 2 ); } } public void secondary( String text, boolean highlighted ) { secondary.text( text ); secondary.measure(); secondary.hardlight( highlighted ? SECONDARY_COLOR_H : SECONDARY_COLOR_N ); } } private class ClassShield extends Button { private static final float MIN_BRIGHTNESS = 0.6f; private static final int BASIC_NORMAL = 0x444444; private static final int BASIC_HIGHLIGHTED = 0xCACFC2; private static final int MASTERY_NORMAL = 0x666644; private static final int MASTERY_HIGHLIGHTED= 0xFFFF88; private static final int WIDTH = 24; private static final int HEIGHT = 28; private static final int SCALE = 2; private HeroClass cl; private Image avatar; private BitmapText name; private Emitter emitter; private float brightness; private int normal; private int highlighted; public ClassShield( HeroClass cl ) { super(); this.cl = cl; avatar.frame( cl.ordinal() * WIDTH, 0, WIDTH, HEIGHT ); avatar.scale.set( SCALE ); if (Badges.isUnlocked( cl.masteryBadge() )) { normal = MASTERY_NORMAL; highlighted = MASTERY_HIGHLIGHTED; } else { normal = BASIC_NORMAL; highlighted = BASIC_HIGHLIGHTED; } //name.text( cl.name() );//Adjusted to load the translated names as each player class name.text( cl.title().toUpperCase(Locale.getDefault()) ); name.measure(); name.hardlight( normal ); brightness = MIN_BRIGHTNESS; updateBrightness(); } @Override protected void createChildren() { super.createChildren(); avatar = new Image( Assets.AVATARS ); add( avatar ); name = PixelScene.createText( 9 ); add( name ); emitter = new BitmaskEmitter( avatar ); add( emitter ); } @Override protected void layout() { super.layout(); avatar.x = align( x + (width - avatar.width()) / 2 ); avatar.y = align( y + (height - avatar.height() - name.height()) / 2 ); name.x = align( x + (width - name.width()) / 2 ); name.y = avatar.y + avatar.height() + SCALE; } @Override protected void onTouchDown() { emitter.revive(); emitter.start( Speck.factory( Speck.LIGHT ), 0.05f, 7 ); Sample.INSTANCE.play( Assets.SND_CLICK, 1, 1, 1.2f ); updateClass( cl ); } @Override public void update() { super.update(); if (brightness < 1.0f && brightness > MIN_BRIGHTNESS) { if ((brightness -= Game.elapsed) <= MIN_BRIGHTNESS) { brightness = MIN_BRIGHTNESS; } updateBrightness(); } } public void highlight( boolean value ) { if (value) { brightness = 1.0f; name.hardlight( highlighted ); } else { brightness = 0.999f; name.hardlight( normal ); } updateBrightness(); } private void updateBrightness() { avatar.gm = avatar.bm = avatar.rm = avatar.am = brightness; } } private class ChallengeButton extends Button { private Image image; public ChallengeButton() { super(); width = image.width; height = image.height; image.am = Badges.isUnlocked( Badges.Badge.VICTORY ) ? 1.0f : 0.5f; } @Override protected void createChildren() { super.createChildren(); image = Icons.get( PixelDungeon.challenges() > 0 ? Icons.CHALLENGE_ON :Icons.CHALLENGE_OFF ); add( image ); } @Override protected void layout() { super.layout(); image.x = align( x ); image.y = align( y ); } @Override protected void onClick() { if (Badges.isUnlocked( Badges.Badge.VICTORY )) { StartScene.this.add( new WndChallenges( PixelDungeon.challenges(), true ) { public void onBackPressed() { super.onBackPressed(); image.copy( Icons.get( PixelDungeon.challenges() > 0 ? Icons.CHALLENGE_ON :Icons.CHALLENGE_OFF ) ); }; } ); } else { StartScene.this.add( new WndMessage( TXT_WIN_THE_GAME ) ); } } @Override protected void onTouchDown() { Sample.INSTANCE.play( Assets.SND_CLICK ); } } }
rodriformiga/pixel-dungeon
src/com/watabou/pixeldungeon/scenes/StartScene.java
Java
gpl-3.0
13,966
package com.github.epd.sprout.items.wands; import com.github.epd.sprout.Assets; import com.github.epd.sprout.Dungeon; import com.github.epd.sprout.actors.Actor; import com.github.epd.sprout.actors.Char; import com.github.epd.sprout.actors.buffs.Buff; import com.github.epd.sprout.actors.buffs.Invisibility; import com.github.epd.sprout.actors.hero.Hero; import com.github.epd.sprout.actors.hero.HeroClass; import com.github.epd.sprout.effects.MagicMissile; import com.github.epd.sprout.items.Item; import com.github.epd.sprout.items.KindOfWeapon; import com.github.epd.sprout.items.bags.Bag; import com.github.epd.sprout.items.rings.RingOfMagic.Magic; import com.github.epd.sprout.mechanics.Ballistica; import com.github.epd.sprout.messages.Messages; import com.github.epd.sprout.scenes.CellSelector; import com.github.epd.sprout.scenes.GameScene; import com.github.epd.sprout.ui.QuickSlotButton; import com.github.epd.sprout.utils.GLog; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Bundle; import com.watabou.utils.Callback; import com.watabou.utils.Random; import java.util.ArrayList; public abstract class Wand extends KindOfWeapon { //TODO: Damage balancing private static final int USAGES_TO_KNOW = 20; public static final String AC_ZAP = Messages.get(Wand.class, "ac_zap"); private static final String TXT_WOOD = Messages.get(Wand.class, "wood"); private static final String TXT_DAMAGE = Messages.get(Wand.class, "damage"); private static final String TXT_WEAPON = Messages.get(Wand.class, "weapon"); private static final String TXT_FIZZLES = Messages.get(Wand.class, "fizzles"); private static final String TXT_SELF_TARGET = Messages.get(Wand.class, "self_target"); private static final String TXT_IDENTIFY = Messages.get(Wand.class, "identify"); private static final String TXT_REINFORCED = Messages.get(Wand.class, "re"); private static final float TIME_TO_ZAP = 1f; public int maxCharges = initialCharges(); public int curCharges = maxCharges; private float partialCharge = 0f; protected Charger charger; private boolean curChargeKnown = false; private int usagesToKnow = USAGES_TO_KNOW; protected int collisionProperties = Ballistica.MAGIC_BOLT; { defaultAction = AC_ZAP; usesTargeting = true; } public Wand() { super(); calculateDamage(); } @Override public ArrayList<String> actions(Hero hero) { ArrayList<String> actions = super.actions(hero); if (curCharges > 0 || !curChargeKnown) { actions.add(AC_ZAP); } if (hero.heroClass != HeroClass.MAGE) { actions.remove(AC_EQUIP); actions.remove(AC_UNEQUIP); } return actions; } @Override public boolean doUnequip(Hero hero, boolean collect, boolean single) { onDetach(); return super.doUnequip(hero, collect, single); } @Override public void activate(Hero hero) { charge(hero); } @Override public void execute(Hero hero, String action) { if (action.equals(AC_ZAP)) { curUser = hero; curItem = this; GameScene.selectCell(zapper); } else { super.execute(hero, action); } } protected abstract void onZap(Ballistica attack); @Override public boolean collect(Bag container) { if (super.collect(container)) { if (container.owner != null) { charge(container.owner); } return true; } else { return false; } } public void charge(Char owner) { if (charger == null) charger = new Charger(); charger.attachTo(owner); } public void charge(Char owner, float chargeScaleFactor) { charge(owner); charger.setScaleFactor(chargeScaleFactor); } @Override public void onDetach() { stopCharging(); } public void stopCharging() { if (charger != null) { charger.detach(); charger = null; } } public int level() { int magicLevel = 0; if (charger != null) { Magic magic = charger.target.buff(Magic.class); if (magic != null) { magicLevel = magic.level; } return magic == null ? level : Math.max(level + magicLevel, 0); } else { return level; } } @Override public Item identify() { curChargeKnown = true; super.identify(); updateQuickslot(); return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(super.toString()); String status = status(); if (status != null) { sb.append(" (" + status + ")"); } return sb.toString(); } @Override public String info() { StringBuilder info = new StringBuilder(desc()); if (Dungeon.hero.heroClass == HeroClass.MAGE) { info.append("\n\n"); if (levelKnown) { info.append(String.format(TXT_DAMAGE, MIN, MAX)); } else { info.append(String.format(TXT_WEAPON)); } } if (reinforced) { info.append(String.format(TXT_REINFORCED)); } return info.toString(); } @Override public boolean isIdentified() { return super.isIdentified() && curChargeKnown; } @Override public String status() { if (levelKnown) { return (curChargeKnown ? curCharges : "?") + "/" + maxCharges; } else { return null; } } @Override public Item upgrade() { super.upgrade(); updateLevel(); curCharges = Math.min(curCharges + 1, maxCharges); updateQuickslot(); return this; } @Override public Item degrade() { super.degrade(); updateLevel(); updateQuickslot(); return this; } public void updateLevel() { maxCharges = Math.min(initialCharges() + level, 14); curCharges = Math.min(curCharges, maxCharges); calculateDamage(); } protected int initialCharges() { return 2; } protected int chargesPerCast() { return 1; } private void calculateDamage() { int tier = 1 + level / 3; MIN = tier; MAX = (tier * tier - tier + 10) / 2 + level; } protected void fx(Ballistica bolt, Callback callback) { MagicMissile.whiteLight(curUser.sprite.parent, bolt.sourcePos, bolt.collisionPos, callback); Sample.INSTANCE.play(Assets.SND_ZAP); } protected void wandUsed() { usagesToKnow -= chargesPerCast(); curCharges -= chargesPerCast(); if (!isIdentified() && usagesToKnow <= 0) { identify(); GLog.w(TXT_IDENTIFY, name()); } else { updateQuickslot(); } curUser.spendAndNext(TIME_TO_ZAP); } protected void wandEmpty() { curCharges = 0; updateQuickslot(); } @Override public Item random() { int n = 0; if (Random.Int(3) == 0) { n++; if (Random.Int(5) == 0) { n++; } } upgrade(n); return this; } @Override public int price() { int price = 75; if (cursed && cursedKnown) { price /= 2; } if (levelKnown) { if (level > 0) { price *= (level + 1); } else if (level < 0) { price /= (1 - level); } } if (price < 1) { price = 1; } return price; } @Override public void proc(Char attacker, Char defender, int damage){ } private static final String UNFAMILIRIARITY = "unfamiliarity"; private static final String MAX_CHARGES = "maxCharges"; private static final String CUR_CHARGES = "curCharges"; private static final String CUR_CHARGE_KNOWN = "curChargeKnown"; private static final String PARTIALCHARGE = "partialCharge"; @Override public void storeInBundle(Bundle bundle) { super.storeInBundle(bundle); bundle.put(UNFAMILIRIARITY, usagesToKnow); bundle.put(MAX_CHARGES, maxCharges); bundle.put(CUR_CHARGES, curCharges); bundle.put(CUR_CHARGE_KNOWN, curChargeKnown); bundle.put(PARTIALCHARGE, partialCharge); } @Override public void restoreFromBundle(Bundle bundle) { super.restoreFromBundle(bundle); if ((usagesToKnow = bundle.getInt(UNFAMILIRIARITY)) == 0) { usagesToKnow = USAGES_TO_KNOW; } maxCharges = bundle.getInt(MAX_CHARGES); curCharges = bundle.getInt(CUR_CHARGES); curChargeKnown = bundle.getBoolean(CUR_CHARGE_KNOWN); partialCharge = bundle.getFloat(PARTIALCHARGE); } protected static CellSelector.Listener zapper = new CellSelector.Listener() { @Override public void onSelect(Integer target) { if (target != null) { if (!(Item.curItem instanceof Wand)){ return; } final Wand curWand = (Wand) Item.curItem; final Ballistica shot = new Ballistica(curUser.pos, target, curWand.collisionProperties); int cell = shot.collisionPos; if (target == curUser.pos || cell == curUser.pos) { GLog.i(TXT_SELF_TARGET); return; } curUser.sprite.zap(cell); //attempts to target the cell aimed at if something is there, otherwise targets the collision pos. if (Actor.findChar(target) != null) QuickSlotButton.target(Actor.findChar(target)); else QuickSlotButton.target(Actor.findChar(cell)); if (curWand.curCharges >= curWand.chargesPerCast()) { curUser.busy(); curWand.fx(shot, new Callback() { public void call() { curWand.onZap(shot); curWand.wandUsed(); } }); Invisibility.dispel(); } else { curUser.spendAndNext(TIME_TO_ZAP); GLog.w(TXT_FIZZLES); } } } @Override public String prompt() { return Messages.get(Wand.class, "prompt"); } }; protected class Charger extends Buff { private static final float BASE_CHARGE_DELAY = 10f; private static final float SCALING_CHARGE_ADDITION = 40f; private static final float NORMAL_SCALE_FACTOR = 0.85f; float scalingFactor = NORMAL_SCALE_FACTOR; @Override public boolean attachTo(Char target) { super.attachTo(target); return true; } @Override public boolean act() { if (curCharges < maxCharges) gainCharge(); if (partialCharge >= 1 && curCharges < maxCharges) { partialCharge--; curCharges++; updateQuickslot(); } spend(TICK); return true; } private void gainCharge() { int missingCharges = maxCharges - curCharges; float turnsToCharge = (float) (BASE_CHARGE_DELAY + (SCALING_CHARGE_ADDITION * Math.pow(scalingFactor, missingCharges))); partialCharge += 1f / turnsToCharge; } private void setScaleFactor(float value) { this.scalingFactor = value; } } }
G2159687/espd
app/src/main/java/com/github/epd/sprout/items/wands/Wand.java
Java
gpl-3.0
9,921
<?php require_once "API.php"; $API = new API(); $API->rest(); ?>
sergiocastro95/TFG
Desarrollo/Server/rest/Index.php
PHP
gpl-3.0
78
<?php class ControllerCatalogCategory extends Controller { private $error = array(); public function index() { $this->load->language('catalog/category'); $this->document->title = $this->language->get('heading_title'); $this->load->model('catalog/category'); $this->getList(); } public function insert() { $this->load->language('catalog/category'); $this->document->title = $this->language->get('heading_title'); $this->load->model('catalog/category'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) { $this->model_catalog_category->addCategory($this->request->post); $this->session->data['success'] = $this->language->get('text_success'); $this->redirect(HTTPS_SERVER . 'index.php?route=catalog/category&token=' . $this->session->data['token']); } $this->getForm(); } public function update() { $this->load->language('catalog/category'); $this->document->title = $this->language->get('heading_title'); $this->load->model('catalog/category'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) { $this->model_catalog_category->editCategory($this->request->get['category_id'], $this->request->post); $this->session->data['success'] = $this->language->get('text_success'); $this->redirect(HTTPS_SERVER . 'index.php?route=catalog/category&token=' . $this->session->data['token']); } $this->getForm(); } public function delete() { $this->load->language('catalog/category'); $this->document->title = $this->language->get('heading_title'); $this->load->model('catalog/category'); if (isset($this->request->post['selected']) && $this->validateDelete()) { foreach ($this->request->post['selected'] as $category_id) { $this->model_catalog_category->deleteCategory($category_id); } $this->session->data['success'] = $this->language->get('text_success'); $this->redirect(HTTPS_SERVER . 'index.php?route=catalog/category&token=' . $this->session->data['token']); } $this->getList(); } private function getList() { $this->document->breadcrumbs = array(); $this->document->breadcrumbs[] = array( 'href' => HTTPS_SERVER . 'index.php?route=common/home&token=' . $this->session->data['token'], 'text' => $this->language->get('text_home'), 'separator' => FALSE ); $this->document->breadcrumbs[] = array( 'href' => HTTPS_SERVER . 'index.php?route=catalog/category&token=' . $this->session->data['token'], 'text' => $this->language->get('heading_title'), 'separator' => ' :: ' ); $this->data['insert'] = HTTPS_SERVER . 'index.php?route=catalog/category/insert&token=' . $this->session->data['token']; $this->data['delete'] = HTTPS_SERVER . 'index.php?route=catalog/category/delete&token=' . $this->session->data['token']; $this->data['categories'] = array(); $results = $this->model_catalog_category->getCategories(0); foreach ($results as $result) { $action = array(); $action[] = array( 'text' => $this->language->get('text_edit'), 'href' => HTTPS_SERVER . 'index.php?route=catalog/category/update&token=' . $this->session->data['token'] . '&category_id=' . $result['category_id'] ); $this->data['categories'][] = array( 'category_id' => $result['category_id'], 'name' => $result['name'], 'sort_order' => $result['sort_order'], 'selected' => isset($this->request->post['selected']) && in_array($result['category_id'], $this->request->post['selected']), 'action' => $action ); } $this->data['heading_title'] = $this->language->get('heading_title'); $this->data['text_no_results'] = $this->language->get('text_no_results'); $this->data['column_name'] = $this->language->get('column_name'); $this->data['column_sort_order'] = $this->language->get('column_sort_order'); $this->data['column_action'] = $this->language->get('column_action'); $this->data['button_insert'] = $this->language->get('button_insert'); $this->data['button_delete'] = $this->language->get('button_delete'); if (isset($this->error['warning'])) { $this->data['error_warning'] = $this->error['warning']; } else { $this->data['error_warning'] = ''; } if (isset($this->session->data['success'])) { $this->data['success'] = $this->session->data['success']; unset($this->session->data['success']); } else { $this->data['success'] = ''; } $this->template = 'catalog/category_list.tpl'; $this->children = array( 'common/header', 'common/footer' ); $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression')); } private function getForm() { $this->data['heading_title'] = $this->language->get('heading_title'); $this->data['text_none'] = $this->language->get('text_none'); $this->data['text_default'] = $this->language->get('text_default'); $this->data['text_image_manager'] = $this->language->get('text_image_manager'); $this->data['text_enabled'] = $this->language->get('text_enabled'); $this->data['text_disabled'] = $this->language->get('text_disabled'); $this->data['entry_name'] = $this->language->get('entry_name'); $this->data['entry_meta_keywords'] = $this->language->get('entry_meta_keywords'); $this->data['entry_meta_description'] = $this->language->get('entry_meta_description'); $this->data['entry_description'] = $this->language->get('entry_description'); $this->data['entry_store'] = $this->language->get('entry_store'); $this->data['entry_keyword'] = $this->language->get('entry_keyword'); $this->data['entry_category'] = $this->language->get('entry_category'); $this->data['entry_sort_order'] = $this->language->get('entry_sort_order'); $this->data['entry_image'] = $this->language->get('entry_image'); $this->data['entry_status'] = $this->language->get('entry_status'); $this->data['button_save'] = $this->language->get('button_save'); $this->data['button_cancel'] = $this->language->get('button_cancel'); $this->data['tab_general'] = $this->language->get('tab_general'); $this->data['tab_data'] = $this->language->get('tab_data'); if (isset($this->error['warning'])) { $this->data['error_warning'] = $this->error['warning']; } else { $this->data['error_warning'] = ''; } if (isset($this->error['name'])) { $this->data['error_name'] = $this->error['name']; } else { $this->data['error_name'] = ''; } $this->document->breadcrumbs = array(); $this->document->breadcrumbs[] = array( 'href' => HTTPS_SERVER . 'index.php?route=common/home&token=' . $this->session->data['token'], 'text' => $this->language->get('text_home'), 'separator' => FALSE ); $this->document->breadcrumbs[] = array( 'href' => HTTPS_SERVER . 'index.php?route=catalog/category&token=' . $this->session->data['token'], 'text' => $this->language->get('heading_title'), 'separator' => ' :: ' ); if (!isset($this->request->get['category_id'])) { $this->data['action'] = HTTPS_SERVER . 'index.php?route=catalog/category/insert&token=' . $this->session->data['token']; } else { $this->data['action'] = HTTPS_SERVER . 'index.php?route=catalog/category/update&token=' . $this->session->data['token'] . '&category_id=' . $this->request->get['category_id']; } $this->data['cancel'] = HTTPS_SERVER . 'index.php?route=catalog/category&token=' . $this->session->data['token']; $this->data['token'] = $this->session->data['token']; if (isset($this->request->get['category_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) { $category_info = $this->model_catalog_category->getCategory($this->request->get['category_id']); } $this->load->model('localisation/language'); $this->data['languages'] = $this->model_localisation_language->getLanguages(); if (isset($this->request->post['category_description'])) { $this->data['category_description'] = $this->request->post['category_description']; } elseif (isset($category_info)) { $this->data['category_description'] = $this->model_catalog_category->getCategoryDescriptions($this->request->get['category_id']); } else { $this->data['category_description'] = array(); } if (isset($this->request->post['status'])) { $this->data['status'] = $this->request->post['status']; } elseif (isset($category_info)) { $this->data['status'] = $category_info['status']; } else { $this->data['status'] = 1; } $categories = $this->model_catalog_category->getCategories(0); // Remove own id from list if (isset($category_info)) { foreach ($categories as $key => $category) { if ($category['category_id'] == $category_info['category_id']) { unset($categories[$key]); } } } $this->data['categories'] = $categories; if (isset($this->request->post['parent_id'])) { $this->data['parent_id'] = $this->request->post['parent_id']; } elseif (isset($category_info)) { $this->data['parent_id'] = $category_info['parent_id']; } else { $this->data['parent_id'] = 0; } $this->load->model('setting/store'); $this->data['stores'] = $this->model_setting_store->getStores(); if (isset($this->request->post['category_store'])) { $this->data['category_store'] = $this->request->post['category_store']; } elseif (isset($category_info)) { $this->data['category_store'] = $this->model_catalog_category->getCategoryStores($this->request->get['category_id']); } else { $this->data['category_store'] = array(0); } if (isset($this->request->post['keyword'])) { $this->data['keyword'] = $this->request->post['keyword']; } elseif (isset($category_info)) { $this->data['keyword'] = $category_info['keyword']; } else { $this->data['keyword'] = ''; } if (isset($this->request->post['image'])) { $this->data['image'] = $this->request->post['image']; } elseif (isset($category_info)) { $this->data['image'] = $category_info['image']; } else { $this->data['image'] = ''; } $this->load->model('tool/image'); if (isset($category_info) && $category_info['image'] && file_exists(DIR_IMAGE . $category_info['image'])) { $this->data['preview'] = $this->model_tool_image->resize($category_info['image'], 100, 100); } else { $this->data['preview'] = $this->model_tool_image->resize('no_image.jpg', 100, 100); } if (isset($this->request->post['sort_order'])) { $this->data['sort_order'] = $this->request->post['sort_order']; } elseif (isset($category_info)) { $this->data['sort_order'] = $category_info['sort_order']; } else { $this->data['sort_order'] = 0; } $this->template = 'catalog/category_form.tpl'; $this->children = array( 'common/header', 'common/footer' ); $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression')); } private function validateForm() { if (!$this->user->hasPermission('modify', 'catalog/category')) { $this->error['warning'] = $this->language->get('error_permission'); } foreach ($this->request->post['category_description'] as $language_id => $value) { if ((strlen(utf8_decode($value['name'])) < 2) || (strlen(utf8_decode($value['name'])) > 255)) { $this->error['name'][$language_id] = $this->language->get('error_name'); } } if (!$this->error) { return TRUE; } else { if (!isset($this->error['warning'])) { $this->error['warning'] = $this->language->get('error_required_data'); } return FALSE; } } private function validateDelete() { if (!$this->user->hasPermission('modify', 'catalog/category')) { $this->error['warning'] = $this->language->get('error_permission'); } if (!$this->error) { return TRUE; } else { return FALSE; } } } ?>
kzawner/andreaherbaty.pl
upload/admin/controller/catalog/category.php
PHP
gpl-3.0
11,952
videojs-soundcloud ================== [![Build Status](https://travis-ci.org/LoveIsGrief/videojs-soundcloud.svg?branch=master)](https://travis-ci.org/LoveIsGrief/videojs-soundcloud) A [videojs/video-js](https://github.com/videojs/video.js) plugin to support soundcloud track links like: - https://soundcloud.com/vaughan-1-1/this-is-what-crazy-looks-like - [Example](https://loveisgrief.github.io/videojs-soundcloud/) ------- `npm install && grunt compile` will compile - [src/media.soundcloud.coffee](src/media.soundcloud.coffee) - [index.jade](index.jade) One can then open the generated `index.html`. Developing ---------- * `npm install` to prepare the environment * `npm test` to run the tests once (Karma with Jasmine) * `npm run karma` to run tests continuously once a file is changed * `grunt` after `npm install` to prepare running the example at **example/index.html** * `grunt watch` to continuously compile coffee and jade, and run livereload for the example you can run this alongside `npm run karma` if you wish How it works ============ We create an iframe (with a soundcloud-embed URL) in the player-element and, using the soundcloud [Widget API](http://developers.soundcloud.com/docs/api/html5-widget), we initialize a widget that will give us the control methods, getters and setters we need. Once the iframe is created it is hidden! More in detail notes -------------------- > [**Getters**](http://developers.soundcloud.com/docs/api/html5-widget#methods) > Since communication between the parent page and the widget's iframe is implemented through [window.postMessage](https://developer.mozilla.org/en/DOM/window.postMessage), it's not possible to return the value synchronously. Because of this, every getter method accepts a callback function as a parameter which, when called, will be given the return value of the getter method. Due to this we have quite a few state variables when using the widget API. Documentation ------------- Is generated with [Codo](https://github.com/coffeedoc/codo) and hosted on [coffeedoc.info](http://coffeedoc.info/github/LoveIsGrief/videojs-soundcloud/master/). Props to them :)
LoveIsGrief/videojs-soundcloud
README.md
Markdown
gpl-3.0
2,166
package md5b60ffeb829f638581ab2bb9b1a7f4f3f; public class PlatformRenderer extends android.view.ViewGroup implements mono.android.IGCUserPeer { /** @hide */ public static final String __md_methods; static { __md_methods = "n_onMeasure:(II)V:GetOnMeasure_IIHandler\n" + "n_onLayout:(ZIIII)V:GetOnLayout_ZIIIIHandler\n" + "n_dispatchTouchEvent:(Landroid/view/MotionEvent;)Z:GetDispatchTouchEvent_Landroid_view_MotionEvent_Handler\n" + ""; mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.PlatformRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", PlatformRenderer.class, __md_methods); } public PlatformRenderer (android.content.Context p0) throws java.lang.Throwable { super (p0); if (getClass () == PlatformRenderer.class) mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.PlatformRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0 }); } public PlatformRenderer (android.content.Context p0, android.util.AttributeSet p1) throws java.lang.Throwable { super (p0, p1); if (getClass () == PlatformRenderer.class) mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.PlatformRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0, p1 }); } public PlatformRenderer (android.content.Context p0, android.util.AttributeSet p1, int p2) throws java.lang.Throwable { super (p0, p1, p2); if (getClass () == PlatformRenderer.class) mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.PlatformRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0, p1, p2 }); } public PlatformRenderer (android.content.Context p0, android.util.AttributeSet p1, int p2, int p3) throws java.lang.Throwable { super (p0, p1, p2, p3); if (getClass () == PlatformRenderer.class) mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.PlatformRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0, p1, p2, p3 }); } public void onMeasure (int p0, int p1) { n_onMeasure (p0, p1); } private native void n_onMeasure (int p0, int p1); public void onLayout (boolean p0, int p1, int p2, int p3, int p4) { n_onLayout (p0, p1, p2, p3, p4); } private native void n_onLayout (boolean p0, int p1, int p2, int p3, int p4); public boolean dispatchTouchEvent (android.view.MotionEvent p0) { return n_dispatchTouchEvent (p0); } private native boolean n_dispatchTouchEvent (android.view.MotionEvent p0); private java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
ThatOldFox/Project2PasswordSafe
Project2/Project2/Project2.Droid/obj/Debug/android/src/md5b60ffeb829f638581ab2bb9b1a7f4f3f/PlatformRenderer.java
Java
gpl-3.0
4,179
/* This file is part of Arkhados. Arkhados is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Arkhados is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Arkhados. If not, see <http://www.gnu.org/licenses/>. */ package arkhados.spell; import arkhados.CollisionGroups; import arkhados.World; import arkhados.controls.CEntityEvent; import arkhados.controls.CProjectile; import arkhados.controls.CSpellBuff; import arkhados.controls.CTimedExistence; import arkhados.entityevents.ARemovalEvent; import arkhados.util.AbstractNodeBuilder; import arkhados.util.BuildParameters; import arkhados.util.UserData; import com.jme3.asset.AssetManager; import com.jme3.bullet.collision.shapes.SphereCollisionShape; import com.jme3.bullet.control.GhostControl; import com.jme3.bullet.control.RigidBodyControl; import com.jme3.effect.ParticleEmitter; import com.jme3.effect.ParticleMesh; import com.jme3.effect.shapes.EmitterSphereShape; import com.jme3.material.Material; import com.jme3.material.RenderState; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Sphere; public class PelletBuilder extends AbstractNodeBuilder { private float damage; public PelletBuilder(float damage) { this.damage = damage; } @Override public Node build(BuildParameters params) { Sphere sphere = new Sphere(8, 8, 0.3f); Geometry projectileGeom = new Geometry("projectile-geom", sphere); Node node = new Node("projectile"); node.setLocalTranslation(params.location); node.attachChild(projectileGeom); Material material = new Material(assets, "Common/MatDefs/Misc/Unshaded.j3md"); material.setColor("Color", ColorRGBA.Yellow); node.setMaterial(material); node.setUserData(UserData.SPEED_MOVEMENT, 220f); node.setUserData(UserData.MASS, 0.30f); node.setUserData(UserData.DAMAGE, damage); node.setUserData(UserData.IMPULSE_FACTOR, 0f); if (world.isClient()) { node.addControl(new CEntityEvent()); /** * Here we specify what happens on client side when pellet is * removed. In this case we want explosion effect. */ APelletRemoval removalAction = new APelletRemoval(assets); removalAction.setPellet(node); node.getControl(CEntityEvent.class) .setOnRemoval(removalAction); } SphereCollisionShape collisionShape = new SphereCollisionShape(1.7f); RigidBodyControl physicsBody = new RigidBodyControl(collisionShape, (float) node.getUserData(UserData.MASS)); /** * We don't want projectiles to collide with each other so we give them * their own collision group and prevent them from colliding with that * group. */ physicsBody.setCollisionGroup(CollisionGroups.NONE); physicsBody.setCollideWithGroups(CollisionGroups.NONE); /** * Add collision with characters */ GhostControl collision = new GhostControl(collisionShape); collision.setCollisionGroup(CollisionGroups.PROJECTILES); collision.setCollideWithGroups(CollisionGroups.CHARACTERS); node.addControl(collision); node.addControl(physicsBody); node.addControl(new CProjectile()); CSpellBuff buffControl = new CSpellBuff(); node.addControl(buffControl); return node; } } class APelletRemoval implements ARemovalEvent { private AssetManager assetManager; private Spatial pellet; public APelletRemoval(AssetManager assetManager) { super(); this.assetManager = assetManager; } private void createSmallExplosion(Node root, Vector3f location) { ParticleEmitter fire = new ParticleEmitter("shotgun-explosion", ParticleMesh.Type.Triangle, 20); Material material = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md"); material.setTexture("Texture", assetManager.loadTexture("Effects/flame.png")); fire.setMaterial(material); fire.setImagesX(2); fire.setImagesY(2); fire.setSelectRandomImage(true); fire.setGravity(Vector3f.ZERO); fire.setRandomAngle(true); fire.setStartColor(new ColorRGBA(0.95f, 0.150f, 0.0f, 0.40f)); fire.setEndColor(new ColorRGBA(1.0f, 1.0f, 0.0f, 0.0f)); fire.setLowLife(0.1f); fire.setHighLife(0.3f); fire.setNumParticles(100); fire.setStartSize(0.50f); fire.setEndSize(1.0f); fire.getParticleInfluencer() .setInitialVelocity(Vector3f.UNIT_X.mult(1.0f)); fire.getParticleInfluencer().setVelocityVariation(6f); fire.setShape(new EmitterSphereShape(Vector3f.ZERO, 0.2f)); fire.setParticlesPerSec(0f); root.attachChild(fire); fire.setLocalTranslation(location); fire.emitAllParticles(); fire.addControl(new CTimedExistence(1f)); } private void createSmokePuff(Node root, Vector3f location) { ParticleEmitter smokePuff = new ParticleEmitter("smoke-puff", ParticleMesh.Type.Triangle, 20); Material material = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md"); material.setTexture("Texture", assetManager.loadTexture("Effects/flame_alpha.png")); material.getAdditionalRenderState() .setBlendMode(RenderState.BlendMode.Alpha); smokePuff.setMaterial(material); smokePuff.setImagesX(2); smokePuff.setImagesY(2); smokePuff.setSelectRandomImage(true); smokePuff.setStartColor(new ColorRGBA(0.5f, 0.5f, 0.5f, 0.2f)); smokePuff.setStartColor(new ColorRGBA(0.5f, 0.5f, 0.5f, 0.1f)); smokePuff.getParticleInfluencer() .setInitialVelocity(Vector3f.UNIT_X.mult(5f)); smokePuff.getParticleInfluencer().setVelocityVariation(1f); smokePuff.setStartSize(2f); smokePuff.setEndSize(6f); smokePuff.setGravity(Vector3f.ZERO); smokePuff.setLowLife(0.75f); smokePuff.setHighLife(1f); smokePuff.setParticlesPerSec(0f); smokePuff.setRandomAngle(true); smokePuff.setShape(new EmitterSphereShape(Vector3f.ZERO, 4f)); root.attachChild(smokePuff); smokePuff.setLocalTranslation(location); smokePuff.emitAllParticles(); smokePuff.addControl(new CTimedExistence(1f)); } @Override public void exec(World world, int reason) { Vector3f worldTranslation = pellet.getWorldTranslation(); createSmokePuff(world.getWorldRoot(), worldTranslation); createSmallExplosion(world.getWorldRoot(), worldTranslation); } public void setPellet(Spatial pellet) { this.pellet = pellet; } }
Xatalos/Arkhados
src/arkhados/spell/PelletBuilder.java
Java
gpl-3.0
7,503
/* * Copyright 2012 Amazon Technologies, Inc. * * Licensed under the Amazon Software License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/asl * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.mturk.cmd.summary; import com.amazonaws.mturk.addon.HITResults; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * A results summarizer that is specific to the <i>Image Category</i> sample. */ public class ImageCategoryResultsSummarizer implements ResultsSummarizer{ /** * Default separator for the fields in the assignment records (results file). */ private static final char DEFAULT_FIELD_SEPARATOR = '\t'; /** * Non-public access: allow only the factory to instantiate this. */ ImageCategoryResultsSummarizer(){ } /** * List of columns in the final summary of the <i>image category</i> sample. */ private static final List<String> summaryFields = Arrays.asList("HIT ID", "Image URL", "Question", "Answer", "Score", "%"); /** * @see ResultsSummarizer#getSummaryFields() */ public List<String> getSummaryFields() { return summaryFields; } /** * @see ResultsSummarizer#getSummary(String) */ public Map<String, List<String>> getSummary(String resultsFile) throws ParseException { // hitid is always required. String[] requiredFields = new String[]{ "annotation", "Answer.category", "assignments" }; int[] fieldIndices = new int[3]; Map<String, List<String[]>> hitAssignments = SummaryUtils.parseHitAssignments( resultsFile, requiredFields, fieldIndices, HITResults.DELIMITER); int urlIndex = fieldIndices[0]; int answerIndex = fieldIndices[1]; int numAssignmentsIndex = fieldIndices[2]; // we've built our hitId -> List<assignments> map. // hitId -> imageFileNNN.jpg Map<String, String> hitImageFilenames = SummaryUtils.extractQuestion(hitAssignments, urlIndex); // get the results summarized. // hitId -> "Answer", "Score", "%" Map<String, List<String>> hitResultsSummaries = SummaryUtils.summarizeResults(hitAssignments, answerIndex, numAssignmentsIndex); if(hitResultsSummaries.size() != hitImageFilenames.size()){ throw new RuntimeException("Did not find image names for all HITs"); } // merge the 2 partial sets of summary fields Map<String, List<String>> finalSummaries = new LinkedHashMap<String, List<String>>(); // see fields listed in summaryFields above for(String hitId : hitImageFilenames.keySet()){ List<String> fields = new ArrayList<String>(); fields.add(hitId); fields.add(hitImageFilenames.get(hitId)); fields.add("Category:"); fields.addAll(hitResultsSummaries.get(hitId)); finalSummaries.put(hitId, fields); } return finalSummaries; } }
ucberkeley/moocchat
turk/src/com/amazonaws/mturk/cmd/summary/ImageCategoryResultsSummarizer.java
Java
gpl-3.0
3,433
/** * Copyright (C) 2012 The Serval Project * * This file is part of Serval Software (http://www.servalproject.org) * * Serval Software is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This source code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this source code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.servalproject.rhizome; import java.io.DataOutput; import java.io.IOException; import java.io.RandomAccessFile; import org.servalproject.meshms.SimpleMeshMS; import org.servalproject.servald.SubscriberId; public class RhizomeMessage implements RhizomeMessageLogEntry.Filling { public static final byte SWITCH_BYTE = 0x02; public final String senderDID; public final String recipientDID; public final long millis; public final String message; /** Create a rhizome message from all of its properties. * * @author Andrew Bettison <andrew@servalproject.com> */ public RhizomeMessage(String senderDID, String recipientDID, long millis, String message) { this.senderDID = senderDID; this.recipientDID = recipientDID; this.millis = millis; this.message = message; } public RhizomeMessage(RandomAccessFile ra, int length) throws IOException { this.millis = ra.readLong(); this.senderDID = ra.readUTF(); this.recipientDID = ra.readUTF(); this.message = ra.readUTF(); } public SimpleMeshMS toMeshMs(SubscriberId sender, SubscriberId recipient) { return new SimpleMeshMS(sender, recipient, senderDID, recipientDID, millis, message); } @Override public byte getSwitchByte() { return SWITCH_BYTE; } @Override public void writeTo(DataOutput dout) throws IOException { dout.writeLong(this.millis); dout.writeUTF(this.senderDID == null ? "" : this.senderDID); dout.writeUTF(this.recipientDID == null ? "" : this.recipientDID); dout.writeUTF(this.message == null ? "" : this.message); } @Override public String toString() { return this.getClass().getName() + "(senderDID=" + this.senderDID + ", recipientDID=" + this.recipientDID + ", millis=" + this.millis + ", message='" + this.message + "'" + ")"; } }
aiQon/crowdshare
src/org/servalproject/rhizome/RhizomeMessage.java
Java
gpl-3.0
2,635
// Part of AtomViewer: AtomViewer is a tool to display and analyse // atomistic simulations // // Copyright (C) 2013 ICAMS, Ruhr-Universität Bochum // // AtomViewer 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. // // AtomViewer 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 AtomViewer. If not, see <http://www.gnu.org/licenses/> package model.io; import java.io.File; import javax.swing.filechooser.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import gui.PrimitiveProperty; import gui.ProgressMonitor; import javax.swing.SwingWorker; import common.FastDeletableArrayList; import common.FastTFloatArrayList; import common.Vec3; import model.*; import model.ImportConfiguration.ImportStates; public abstract class MDFileLoader{ protected File[] filesToRead; public SwingWorker<AtomData, String> getNewSwingWorker(){ return new Worker(); } private class Worker extends SwingWorker<AtomData, String>{ @Override protected final AtomData doInBackground() throws Exception{ ProgressMonitor progressMonitor = ProgressMonitor.createNewProgressMonitor(this); progressMonitor.setActivityName("Reading file"); AtomData toReturn = null; AtomData previous = null; //If new files are to be appended on the current file set, get the //last in the set of currently opened files if (ImportStates.APPEND_FILES.isActive()){ previous = Configuration.getCurrentAtomData(); while (previous.getNext()!=null) previous = previous.getNext(); } for (File f : filesToRead){ ProgressMonitor.getProgressMonitor().setCurrentFilename(f.getName()); Filter<Atom> filter = ImportConfiguration.getInstance().getCrystalStructure().getIgnoreAtomsDuringImportFilter(); toReturn = readInputData(f, previous, filter); previous = toReturn; } //Set ranges for customColums for (DataColumnInfo cci : toReturn.getDataColumnInfos()) if (!cci.isInitialRangeGiven()) cci.findRange(toReturn, true); progressMonitor.destroy(); filesToRead = null; return toReturn; } } public void setFilesToRead(File[] files){ this.filesToRead = files; } /** * Creates a single instance of AtomData from {@code f}. * @param f the file containing the atomic data * @param previous an instance of AtomData that is the previous data in a linked list. * May be null if this is the first file in a list. * @param atomFilter A filter that ignores certain atoms already during import. * Can be null, in which case no atoms are filtered * @return An instance of AtomData read from file, possibly linking to a previous data sets * @throws IOException */ public abstract AtomData readInputData(File f, AtomData previous, Filter<Atom> atomFilter) throws Exception; public abstract FileFilter getDefaultFileFilter(); /** * Reads the header from a file and returns an array containing the * names of all optionally importable values and their units (if available) * @param f The file to read the header from * @return array with Strings of optional values first entry is the value name, second the unit * @throws IOException */ public abstract String[][] getColumnNamesUnitsFromHeader(File f) throws IOException; /** * Provides a name for this type of file reader * @return */ public abstract String getName(); public abstract Map<String, DataColumnInfo.Component> getDefaultNamesForComponents(); public List<PrimitiveProperty<?>> getOptions(){ return new ArrayList<PrimitiveProperty<?>>(); } /** * Data from MD input must be stored in this container and then passed into */ public static class ImportDataContainer{ public Vec3 boxSizeX = new Vec3(); public Vec3 boxSizeY = new Vec3(); public Vec3 boxSizeZ = new Vec3(); public Vec3 offset = new Vec3(); public boolean[] pbc = ImportConfiguration.getInstance().getPeriodicBoundaryConditions().clone(); public RBVStorage rbvStorage = new RBVStorage(); /** * All atoms are stored in this list */ public FastDeletableArrayList<Atom> atoms = new FastDeletableArrayList<Atom>(); public List<FastTFloatArrayList> dataArrays = new ArrayList<FastTFloatArrayList>(); /** * The largest (virtual) elements number found in all imported files */ public byte maxElementNumber = 1; /** * A map for the element names */ public Map<Integer, String> elementNames = new HashMap<Integer, String>(); //Some flags for imported or calculated values //Set to true if values are imported from files public boolean rbvAvailable = false; public boolean atomTypesAvailable = false; public boolean grainsImported = false; /** * Meta data found in the file header */ public Map<String, Object> fileMetaData = null; /** * Identifier of the simulation, usually the filename */ public String name; /** * The fully qualified filename for the file */ public String fullPathAndFilename; public BoxParameter box; public ImportDataContainer() { for (int i=0; i<ImportConfiguration.getInstance().getDataColumns().size(); i++) dataArrays.add(new FastTFloatArrayList()); } public void makeBox(){ box = new BoxParameter(boxSizeX, boxSizeY, boxSizeZ, pbc[0], pbc[1], pbc[2]); box.setOffset(offset); } } }
CBegau/AtomViewer
src/model/io/MDFileLoader.java
Java
gpl-3.0
5,838
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Family of BOWDEN, William and CUTCLIFFE, Grace</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li class = "CurrentSection"><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="RelationshipDetail"> <h2>Family of BOWDEN, William and CUTCLIFFE, Grace<sup><small></small></sup></h2> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Husband</td> <td class="ColumnValue"> <a href="../../../ppl/d/c/d15f5fdb679753775eef1a71bcd.html">BOWDEN, William<span class="grampsid"> [I2663]</span></a> </td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Wife</td> <td class="ColumnValue"> <a href="../../../ppl/0/7/d15f5fdb69777c6c8312db17c70.html">CUTCLIFFE, Grace<span class="grampsid"> [I2664]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">&nbsp;</td> <td class="ColumnValue"> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> <a href="../../../evt/5/b/d15f60c0a11193a7e5bc1dbdb5.html" title="Marriage"> Marriage <span class="grampsid"> [E21462]</span> </a> </td> <td class="ColumnDate">1776-02-20</td> <td class="ColumnPlace"> <a href="../../../plc/d/e/d15f60b8246534c278a2d02d2ed.html" title=""> </a> </td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> <a href="../../../evt/6/c/d15f60c0a2668bec5cae02706c6.html" title="Family (Primary)"> Family (Primary) <span class="grampsid"> [E21463]</span> </a> </td> <td class="ColumnDate">&nbsp;</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> <a href="#sref1a">1a</a> </td> </tr> </tbody> </table> </td> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">Attributes</td> <td class="ColumnValue"> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">A812CE1D8E80B64E97A83182E38B85E27E66</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </td> </tr> </tr> </table> </div> <div class="subsection" id="attributes"> <h4>Attributes</h4> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">A812CE1D8E80B64E97A83182E38B85E27E66</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/5/0/d15f5fb6d26ad69bdfd4fe2605.html" title="Cutcliffe-Willis marriage, 4 Nov 1811, Combe Martin, Devon , England" name ="sref1"> Cutcliffe-Willis marriage, 4 Nov 1811, Combe Martin, Devon , England <span class="grampsid"> [S0202]</span> </a> <ol> <li id="sref1a"> <ul> <li> Page: No. 284 </li> <li> Confidence: Very High </li> <li> Source text: <div class="grampsstylednote"><p>&nbsp;</p><p>[Entry Recording Date : 4 NOV 1811]</p></div> </li> <li> General: <p></p> </li> </ul> </li> </ol> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:45<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/fam/e/6/d15f5fdb68f6429d090f547256e.html
HTML
gpl-3.0
6,806
$LOAD_PATH << File.dirname(__FILE__)+'/../lib' $LOAD_PATH << File.dirname(__FILE__)+'./lib' require 'test/unit' require 'pp' require 'HMC/Resource' class TestHMCResource < Test::Unit::TestCase def test_name string = 'lpar:root/ibmhscS1_0|1*9131-52A*6535CCG|IBMHSC_Partition' resource = Resource.new(string) assert_equal('IBMHSC_Partition', resource.type_long) assert_equal('lpar', resource.type ) assert_equal('1', resource.lpar ) assert_equal('9131-52A*6535CCG', resource.frame) end def test_name2 string = 'lpar:root/ibmhscS1_0|ALL_PARTITIONS*9131-52A*6535CCG|IBMHSC_Partition' resource = Resource.new(string) assert_equal('IBMHSC_Partition', resource.type_long, ) assert_equal('lpar', resource.type, ) assert_equal('ALL_PARTITIONS', resource.lpar) assert_equal('9131-52A*6535CCG', resource.frame) end # test data taken from: https://www-304.ibm.com/webapp/set2/.../hmc_best_practices.pdf def test_cec string = 'cec:root/ibmhscS1_0|9406-520*10007CA|IBMHSC_ComputerSystem' resource = Resource.new(string) assert_equal('IBMHSC_ComputerSystem', resource.type_long) assert_equal('cec', resource.type) assert_equal('9406-520*10007CA', resource.frame) end # source: own power5 frame def test_frame string = 'frame:root/ibmhscS1_0|9131-52A*6535CCG|IBMHSC_Frame' resource = Resource.new(string) assert_equal('IBMHSC_Frame', resource.type_long) assert_equal('frame', resource.type) assert_equal('9131-52A*6535CCG', resource.frame) end end
ziutus/hmc_vios_aix
test/hmc_resoure_test.rb
Ruby
gpl-3.0
1,594
/* Copyright (C) 2016 PencilBlue, LLC 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/>. */ //dependencies var util = require('./util.js'); module.exports = function AdminNavigationModule(pb) { //PB dependencies var SecurityService = pb.SecurityService; var GLOBAL_SITE = pb.SiteService.GLOBAL_SITE; /** * Provides function to construct the structure needed to display the navigation * in the Admin section of the application. * * @module Services * @submodule Admin * @class AdminNavigation * @constructor */ function AdminNavigation() {} /** * * @private * @static * @property additions * @type {Array} */ AdminNavigation.additions = {}; /** * * @private * @static * @property childrenAdditions * @type {Object} */ AdminNavigation.childrenAdditions = {}; /** * * @private * @static * @readonly * @property MULTISITE_NAV * @return {Array} */ var MULTISITE_NAV = Object.freeze({ id: 'site_entity', title: 'admin.MANAGE_SITES', icon: 'sitemap', href: '/admin/sites', access: SecurityService.ACCESS_ADMINISTRATOR } ); /** * * @private * @static * @readonly * @property CONTENT_NAV * @return {Array} */ var CONTENT_NAV = Object.freeze({ id: 'content', title: 'generic.CONTENT', icon: 'quote-right', href: '#', access: SecurityService.ACCESS_WRITER, children: [ { id: 'navigation', title: 'generic.NAVIGATION', icon: 'th-large', href: '/admin/content/navigation', access: SecurityService.ACCESS_EDITOR }, { id: 'topics', title: 'admin.TOPICS', icon: 'tags', href: '/admin/content/topics', access: SecurityService.ACCESS_EDITOR }, { id: 'pages', title: 'admin.PAGES', icon: 'file-o', href: '/admin/content/pages', access: SecurityService.ACCESS_EDITOR }, { id: 'articles', title: 'admin.ARTICLES', icon: 'files-o', href: '/admin/content/articles', access: SecurityService.ACCESS_WRITER }, { id: 'media', title: 'admin.MEDIA', icon: 'camera', href: '/admin/content/media', access: SecurityService.ACCESS_WRITER }, { id: 'comments', title: 'generic.COMMENTS', icon: 'comments', href: '/admin/content/comments', access: SecurityService.ACCESS_EDITOR }, { id: 'custom_objects', title: 'admin.CUSTOM_OBJECTS', icon: 'cubes', href: '/admin/content/objects/types', access: SecurityService.ACCESS_EDITOR } ] }); var PLUGINS_NAV = Object.freeze({ id: 'plugins', title: 'admin.PLUGINS', icon: 'puzzle-piece', href: '#', access: SecurityService.ACCESS_ADMINISTRATOR, children: [ { divider: true, id: 'manage', title: 'generic.MANAGE', icon: 'upload', href: '/admin/plugins' }, { id: 'themes', title: 'admin.THEMES', icon: 'magic', href: '/admin/themes' } ] }); var USERS_NAV = Object.freeze({ id: 'users', title: 'admin.USERS', icon: 'users', href: '#', access: SecurityService.ACCESS_EDITOR, children: [ { id: 'manage', title: 'generic.MANAGE', icon: 'users', href: '/admin/users', access: SecurityService.ACCESS_EDITOR }, { id: 'permissions', title: 'generic.PERMISSIONS', icon: 'lock', href: '/admin/users/permissions', access: SecurityService.ACCESS_ADMINISTRATOR } ] }); var VIEW_SITE_NAV = Object.freeze({ id: 'view_site', title: 'admin.VIEW_SITE', icon: 'desktop', href: '/', access: SecurityService.ACCESS_WRITER }); var LOGOUT_NAV = Object.freeze({ id: 'logout', title: 'generic.LOGOUT', icon: 'power-off', href: '/actions/logout', access: SecurityService.ACCESS_WRITER }); function buildSettingsNavigation(site) { var settingsNav = { id: 'settings', title: 'admin.SETTINGS', icon: 'cogs', href: '#', access: SecurityService.ACCESS_ADMINISTRATOR, children: [ { id: 'site_settings', title: 'admin.SITE_SETTINGS', icon: 'cog', href: '/admin/site_settings', access: SecurityService.ACCESS_ADMINISTRATOR }, { id: 'content_settings', title: 'admin.CONTENT', icon: 'quote-right', href: '/admin/site_settings/content', access: SecurityService.ACCESS_ADMINISTRATOR }, { id: 'email_settings', title: 'users.EMAIL', icon: 'envelope', href: '/admin/site_settings/email', access: SecurityService.ACCESS_ADMINISTRATOR } ] }; if (pb.SiteService.isGlobal(site)) { settingsNav.children.push({ id: 'library_settings', title: 'site_settings.LIBRARIES', icon: 'book', href: '/admin/site_settings/libraries', access: SecurityService.ACCESS_ADMINISTRATOR }); } return Object.freeze(settingsNav); } function getDefaultNavigation(site) { return util.clone([CONTENT_NAV, PLUGINS_NAV, USERS_NAV, buildSettingsNavigation(site), VIEW_SITE_NAV, LOGOUT_NAV]); } function getMultiSiteNavigation() { return util.clone([MULTISITE_NAV]); } function getGlobalScopeNavigation(site) { return util.clone([PLUGINS_NAV, USERS_NAV, buildSettingsNavigation(site), LOGOUT_NAV]); } /** * * @private * @static * @method getAdditions * @return {Array} */ function getAdditions(site) { return getAdditionsInScope(AdminNavigation.additions, site); } /** * * @private * @static * @method getChildrenAdditions * @return {Object} */ function getChildrenAdditions(site) { return getAdditionsInScope(AdminNavigation.childrenAdditions, site); } /** * @private * @method getAdditionsInScope * @param {Object} additions * @param {String} site */ function getAdditionsInScope(additions, site) { if (additions[site]) { return util.clone(additions[site]); } else if (additions[pb.SiteService.GLOBAL_SITE]) { return util.clone(additions[pb.SiteService.GLOBAL_SITE]); } return util.clone(additions); } /** * * @private * @static * @method buildNavigation * @return {Array} */ function buildNavigation(site) { var i; var navigation = []; var additions = getAdditions(site); var childrenAdditions = getChildrenAdditions(site); if (pb.config.multisite.enabled) { var multiSiteAdditions = getMultiSiteNavigation(); util.arrayPushAll(multiSiteAdditions, navigation); } if (pb.config.multisite.enabled && pb.SiteService.isGlobal(site)) { // Don't include content or view site in the nav for multitenancy global scope. util.arrayPushAll(getGlobalScopeNavigation(site), navigation); } else { var defaultNavigation = getDefaultNavigation(site); util.arrayPushAll(defaultNavigation, navigation); } util.arrayPushAll(additions, navigation); //retrieve the nav items to iterate over var ids = Object.keys(childrenAdditions); if (ids.length === 0) { return navigation; } //convert to hash to create quick lookup var lookup = util.arrayToHash(navigation, function(navigation, i) { return navigation[i].id; }); //add additions Object.keys(childrenAdditions).forEach(function(id) { var children = childrenAdditions[id]; //find the nav that the children should be added to var nav = lookup[id]; if (!nav) { return; } if (!util.isArray(nav.children)) { nav.children = []; } util.arrayPushAll(children, nav.children); }); return navigation; } /** * @private * @static * @method localizeNavigation * @param {Array} navigation * @param {Localization} ls * @return {Array} */ function localizeNavigation(navigation, ls) { navigation.forEach(function(nav) { nav.title = ls.g(nav.title); if(util.isArray(nav.children)) { nav.children = localizeNavigation(nav.children, ls); } }); return navigation; } /** * @private * @static * @method isDuplicate * @param {String} id * @param {Array} navigation * @return {boolean} */ function isDuplicate(id, navigation, site) { if (!navigation) { navigation = buildNavigation(site); } for (var i = 0; i < navigation.length; i++) { var node = navigation[i]; if (node.id === id) { return true; } if (node.children && isDuplicate(id, node.children, site)) { return true; } } return false; } function exists(id, site) { var isGlobal = pb.SiteService.isGlobal(site); var nav = buildNavigation(site); return isDuplicate(id, nav) || (!isGlobal && isDuplicate(id, buildNavigation(pb.SiteService.GLOBAL_SITE))); } /** * @private * @static * @method isDefaultNode * @param {String} id * @return {Boolean} */ function isDefaultNode(id, site) { return isDuplicate(id, getDefaultNavigation(site)); } /** * Retrive the admin navigation hierarchy * @static * @method get * @param {object} session * @param {array} activeMenuItems Array of nav item names that are active * @param {Object} ls Localization service * @return {object} Admin navigation */ AdminNavigation.get = function (session, activeMenuItems, ls, site) { var navigation = AdminNavigation.removeUnauthorized( session, buildNavigation(site), activeMenuItems ); return localizeNavigation(navigation, ls); }; AdminNavigation.addChild = function(parentId, node) { AdminNavigation.addChildToSite(parentId, node, pb.SiteService.GLOBAL_SITE); } /** * Adds a new child node to an existing top level node * @static * @method addChildToSite * @param {String} parentId * @param {Object} node * @param {String} site - site unique id * @return {Boolean} */ AdminNavigation.addChildToSite = function (parentId, node, site) { if (util.isNullOrUndefined(site)) { site = GLOBAL_SITE; } if (exists(node.id, site)) { return false; } var additionsMap; if (!(site in AdminNavigation.childrenAdditions)) { additionsMap = AdminNavigation.childrenAdditions[site] = {}; } else { additionsMap = AdminNavigation.childrenAdditions[site]; } if (!additionsMap[parentId]) { additionsMap[parentId] = []; } additionsMap[parentId].push(node); return true; }; /** * Adds a new top level node * @static * @method add * @param {Object} node * @param {String} [site='global'] * @return {Boolean} */ AdminNavigation.add = function(node, site) { if (util.isNullOrUndefined(site)) { site = GLOBAL_SITE; } if (exists(node.id, site)) { return false; } if (!(site in AdminNavigation.additions)) { AdminNavigation.additions[site] = []; } AdminNavigation.additions[site].push(node); return true; }; /** * Adds a new top level node * @static * @method addToSite * @param {Object} node * @param {String} site * @return {Boolean} */ AdminNavigation.addToSite = function (node, site) { return AdminNavigation.add(node, site); }; /** * Remove a navigation node * @static * @method remove * @param id * @param {String} [site='global'] * @return {boolean} */ AdminNavigation.remove = function(id, site) { if (util.isNullOrUndefined(site)) { site = GLOBAL_SITE; } if (!isDuplicate(id, buildNavigation(site))) { return false; } if (isDefaultNode(id)) { pb.log.warn("Admin Navigation: Attempting to remove default Node %s", id); return false; } function removeNode(id, navigation) { for (var i = 0; i < navigation.length; i++) { if (navigation[i].id === id) { navigation.splice(i, 1); return navigation; } if (navigation[i].children) { navigation[i].children = removeNode(id, navigation[i].children); } } return navigation; } AdminNavigation.additions[site] = removeNode(id, AdminNavigation.additions[site]); var childAdditionsMap = AdminNavigation.childrenAdditions[site]; util.forEach(childAdditionsMap, function(value, key) { if(key === id){ delete childAdditionsMap[key]; }else { childAdditionsMap[key] = removeNode(id, value); } }); return true; }; /** * Remove a navigation node * @static * @method removeFromSite * @param id * @param {String} site * @return {boolean} */ AdminNavigation.removeFromSite = function (id, site) { return AdminNavigation.remove(id, site); }; /** * @static * @method removeUnauthorized * @param {Object} session * @param {Array} adminNavigation * @param {Array} activeItems * @return {Array} */ AdminNavigation.removeUnauthorized = function (session, adminNavigation, activeItems) { for (var i = 0; i < adminNavigation.length; i++) { if (typeof adminNavigation[i].access !== 'undefined') { if (!pb.security.isAuthorized(session, {admin_level: adminNavigation[i].access})) { adminNavigation.splice(i, 1); i--; continue; } } for (var o = 0; o < activeItems.length; o++) { if (activeItems[o] === adminNavigation[i].id) { adminNavigation[i].active = 'active'; break; } } if (typeof adminNavigation[i].children !== 'undefined') { if (adminNavigation[i].children.length > 0) { adminNavigation[i].dropdown = 'dropdown'; for (var j = 0; j < adminNavigation[i].children.length; j++) { if (typeof adminNavigation[i].children[j].access !== 'undefined') { if (!pb.security.isAuthorized(session, {admin_level: adminNavigation[i].children[j].access})) { adminNavigation[i].children.splice(j, 1); j--; continue; } } for (var p = 0; p < activeItems.length; p++) { if (activeItems[p] == adminNavigation[i].children[j].id) { adminNavigation[i].children[j].active = 'active'; break; } } } } } } return adminNavigation; }; //exports return AdminNavigation; };
Whatsit2yaa/vast-tundra-84597
include/admin_navigation.js
JavaScript
gpl-3.0
18,087
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (version 1.7.0_40) on Mon Jun 06 23:43:38 CEST 2016 --> <title>Overview List</title> <meta name="date" content="2016-06-06"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <div class="indexHeader"><a href="allclasses-frame.html" target="packageFrame">All Classes</a></div> <div class="indexContainer"> <h2 title="Packages">Packages</h2> <ul title="Packages"> <li><a href="centralapp/controlers/package-frame.html" target="packageFrame">centralapp.controlers</a></li> <li><a href="centralapp/model/package-frame.html" target="packageFrame">centralapp.model</a></li> <li><a href="centralapp/views/package-frame.html" target="packageFrame">centralapp.views</a></li> <li><a href="slaves/package-frame.html" target="packageFrame">slaves</a></li> </ul> </div> <p>&nbsp;</p> </body> </html>
Edroxis/DI3_Projet4_Pointeuse
doc/overview-frame.html
HTML
gpl-3.0
998
// SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2009-2013 Marianne Gagnon // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "states_screens/dialogs/player_info_dialog.hpp" #include <IGUIStaticText.h> #include <IGUIEnvironment.h> #include "audio/sfx_manager.hpp" #include "challenges/unlock_manager.hpp" #include "config/player.hpp" #include "guiengine/engine.hpp" #include "guiengine/widgets/button_widget.hpp" #include "guiengine/widgets/label_widget.hpp" #include "guiengine/scalable_font.hpp" #include "guiengine/widgets/text_box_widget.hpp" #include "states_screens/options_screen_players.hpp" #include "states_screens/state_manager.hpp" #include "utils/string_utils.hpp" #include "utils/translation.hpp" using namespace GUIEngine; using namespace irr::gui; using namespace irr::core; // ----------------------------------------------------------------------------- PlayerInfoDialog::PlayerInfoDialog(PlayerProfile* player, const float w, const float h) : ModalDialog(w, h) { m_player = player; showRegularDialog(); } // ----------------------------------------------------------------------------- PlayerInfoDialog::~PlayerInfoDialog() { if (m_player != NULL) { OptionsScreenPlayers::getInstance()->selectPlayer( translations->fribidize(m_player->getName()) ); } } // ----------------------------------------------------------------------------- void PlayerInfoDialog::showRegularDialog() { clearWindow(); const int y1 = m_area.getHeight()/6; const int y2 = m_area.getHeight()*2/6; const int y3 = m_area.getHeight()*3/6; const int y4 = m_area.getHeight()*5/6; ScalableFont* font = GUIEngine::getFont(); const int textHeight = GUIEngine::getFontHeight(); const int buttonHeight = textHeight + 10; { textCtrl = new TextBoxWidget(); textCtrl->m_properties[PROP_ID] = "newname"; textCtrl->setText(m_player->getName()); textCtrl->m_x = 50; textCtrl->m_y = y1 - textHeight/2; textCtrl->m_w = m_area.getWidth()-100; textCtrl->m_h = textHeight + 5; textCtrl->setParent(m_irrlicht_window); m_widgets.push_back(textCtrl); textCtrl->add(); } { ButtonWidget* widget = new ButtonWidget(); widget->m_properties[PROP_ID] = "renameplayer"; //I18N: In the player info dialog widget->setText( _("Rename") ); const int textWidth = font->getDimension( widget->getText().c_str() ).Width + 40; widget->m_x = m_area.getWidth()/2 - textWidth/2; widget->m_y = y2; widget->m_w = textWidth; widget->m_h = buttonHeight; widget->setParent(m_irrlicht_window); m_widgets.push_back(widget); widget->add(); } { ButtonWidget* widget = new ButtonWidget(); widget->m_properties[PROP_ID] = "cancel"; widget->setText( _("Cancel") ); const int textWidth = font->getDimension(widget->getText().c_str()).Width + 40; widget->m_x = m_area.getWidth()/2 - textWidth/2; widget->m_y = y3; widget->m_w = textWidth; widget->m_h = buttonHeight; widget->setParent(m_irrlicht_window); m_widgets.push_back(widget); widget->add(); } { ButtonWidget* widget = new ButtonWidget(); widget->m_properties[PROP_ID] = "removeplayer"; //I18N: In the player info dialog widget->setText( _("Remove")); const int textWidth = font->getDimension(widget->getText().c_str()).Width + 40; widget->m_x = m_area.getWidth()/2 - textWidth/2; widget->m_y = y4; widget->m_w = textWidth; widget->m_h = buttonHeight; widget->setParent(m_irrlicht_window); m_widgets.push_back(widget); widget->add(); } textCtrl->setFocusForPlayer( PLAYER_ID_GAME_MASTER ); } // ----------------------------------------------------------------------------- void PlayerInfoDialog::showConfirmDialog() { clearWindow(); IGUIFont* font = GUIEngine::getFont(); const int textHeight = GUIEngine::getFontHeight(); const int buttonHeight = textHeight + 10; irr::core::stringw message = //I18N: In the player info dialog (when deleting) _("Do you really want to delete player '%s' ?", m_player->getName()); if (unlock_manager->getCurrentSlotID() == m_player->getUniqueID()) { message = _("You cannot delete this player because it is currently in use."); } core::rect< s32 > area_left(5, 0, m_area.getWidth()-5, m_area.getHeight()/2); // When there is no need to tab through / click on images/labels, // we can add irrlicht labels directly // (more complicated uses require the use of our widget set) IGUIStaticText* a = GUIEngine::getGUIEnv()->addStaticText( message.c_str(), area_left, false /* border */, true /* word wrap */, m_irrlicht_window); a->setTextAlignment(EGUIA_CENTER, EGUIA_CENTER); if (unlock_manager->getCurrentSlotID() != m_player->getUniqueID()) { ButtonWidget* widget = new ButtonWidget(); widget->m_properties[PROP_ID] = "confirmremove"; //I18N: In the player info dialog (when deleting) widget->setText( _("Confirm Remove") ); const int textWidth = font->getDimension(widget->getText().c_str()).Width + 40; widget->m_x = m_area.getWidth()/2 - textWidth/2; widget->m_y = m_area.getHeight()/2; widget->m_w = textWidth; widget->m_h = buttonHeight; widget->setParent(m_irrlicht_window); m_widgets.push_back(widget); widget->add(); } { ButtonWidget* widget = new ButtonWidget(); widget->m_properties[PROP_ID] = "cancelremove"; //I18N: In the player info dialog (when deleting) widget->setText( _("Cancel Remove") ); const int textWidth = font->getDimension( widget->getText().c_str() ).Width + 40; widget->m_x = m_area.getWidth()/2 - textWidth/2; widget->m_y = m_area.getHeight()*3/4; widget->m_w = textWidth; widget->m_h = buttonHeight; widget->setParent(m_irrlicht_window); m_widgets.push_back(widget); widget->add(); widget->setFocusForPlayer( PLAYER_ID_GAME_MASTER ); } } // ----------------------------------------------------------------------------- void PlayerInfoDialog::onEnterPressedInternal() { } // ----------------------------------------------------------------------------- GUIEngine::EventPropagation PlayerInfoDialog::processEvent(const std::string& eventSource) { if (eventSource == "renameplayer") { // accept entered name stringw playerName = textCtrl->getText().trim(); const int playerAmount = UserConfigParams::m_all_players.size(); for(int n=0; n<playerAmount; n++) { if (UserConfigParams::m_all_players.get(n) == m_player) continue; if (UserConfigParams::m_all_players[n].getName() == playerName) { ButtonWidget* label = getWidget<ButtonWidget>("renameplayer"); label->setBadge(BAD_BADGE); sfx_manager->quickSound( "anvil" ); return GUIEngine::EVENT_BLOCK; } } if (playerName.size() <= 0) return GUIEngine::EVENT_BLOCK; OptionsScreenPlayers::getInstance()->renamePlayer( playerName, m_player ); // irrLicht is too stupid to remove focus from deleted widgets // so do it by hand GUIEngine::getGUIEnv()->removeFocus( textCtrl->getIrrlichtElement() ); GUIEngine::getGUIEnv()->removeFocus( m_irrlicht_window ); ModalDialog::dismiss(); dismiss(); return GUIEngine::EVENT_BLOCK; } else if (eventSource == "removeplayer") { showConfirmDialog(); return GUIEngine::EVENT_BLOCK; } else if (eventSource == "confirmremove") { OptionsScreenPlayers::getInstance()->deletePlayer( m_player ); m_player = NULL; // irrLicht is too stupid to remove focus from deleted widgets // so do it by hand GUIEngine::getGUIEnv()->removeFocus( textCtrl->getIrrlichtElement() ); GUIEngine::getGUIEnv()->removeFocus( m_irrlicht_window ); ModalDialog::dismiss(); return GUIEngine::EVENT_BLOCK; } else if(eventSource == "cancelremove") { showRegularDialog(); return GUIEngine::EVENT_BLOCK; } else if(eventSource == "cancel") { // irrLicht is too stupid to remove focus from deleted widgets // so do it by hand GUIEngine::getGUIEnv()->removeFocus( textCtrl->getIrrlichtElement() ); GUIEngine::getGUIEnv()->removeFocus( m_irrlicht_window ); ModalDialog::dismiss(); return GUIEngine::EVENT_BLOCK; } return GUIEngine::EVENT_LET; } // -----------------------------------------------------------------------------
deveee/supertuxkart-0.8.1-updates
src/states_screens/dialogs/player_info_dialog.cpp
C++
gpl-3.0
9,818
#!/usr/bin/python # The file is part of the WRL Project. # # The WRL Project 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. # # The WRL Project 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/>. # # Copyright (C) 2017, Andrew McConachie, <andrew.mcconachie@icann.org> import os import sys import random import dns.resolver numTestDomains = 100 numTopTLDs = 100 ignoreDomains = ['com', 'net', 'jobs', 'cat', 'mil', 'edu', 'gov', 'int', 'arpa'] serverZone = '.ws.sp.am' # DNS Zone containing CNAME records pointing to whois FQDNs def dbg(s): # print s pass random.seed() zFiles = os.listdir('zonefiles/') #dbgFiles = 10 # How many files to read while developing this, remove when finished coding tlds = [] for zf in zFiles: # if len(tlds) >= dbgFiles: # For developing, remove when finished coding # break dbg(zf) tld = {} if zf.find(".txt") == -1: dbg("This should not happen") continue zfh = open('zonefiles/' + zf, 'r') lines = zfh.read().splitlines() zfh.close() dbg("after file read") tld['name'] = lines[0].split(".")[0].strip() if tld['name'] in ignoreDomains: dbg("Ignoring:" + tld['name']) continue dbg("after name split") rrs = [] for line in lines: rr = line.split("\t") rrs.append(rr) dbg("after rr split") ns = [] for rr in rrs: if rr[3].lower() == 'ns': ns.append(rr[0].split(".")[0]) dbg("after counting NS records") if len(ns) < numTestDomains: continue else: tld['size'] = len(ns) tld['domains'] = random.sample(ns, numTestDomains) for d in tld['domains']: dbg(d + "." + tld['name']) dbg(tld['name'] + ": " + str(tld['size'])) tlds.append(tld) tlds.sort(key=lambda tld: tld['size'], reverse=True) for ii in xrange(numTopTLDs): # Find FQDN of whois server d = dns.resolver.Resolver() try: resp = d.query(tlds[ii]['name'] + serverZone, 'CNAME') if len(resp.rrset) < 1: whois = 'UNKNOWN' else: whois = str(resp.rrset[0]).strip('.') except: whois = 'UNKNOWN' s = whois + ',' for dom in tlds[ii]['domains']: s += dom + '.' + tlds[ii]['name'] + ',' print s.strip(',')
smutt/WRL
topThick.py
Python
gpl-3.0
2,656
// ***************************************************************************** // hrtimer.cpp Tao3D project // ***************************************************************************** // // File description: // // // // // // // // // ***************************************************************************** // This software is licensed under the GNU General Public License v3 // (C) 2019, Christophe de Dinechin <christophe@dinechin.org> // (C) 2011, Jérôme Forissier <jerome@taodyne.com> // ***************************************************************************** // This file is part of Tao3D // // Tao3D is free software: you can r 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. // // Tao3D 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 Tao3D, in a file named COPYING. // If not, see <https://www.gnu.org/licenses/>. // ***************************************************************************** // hrtimer.cpp - written and placed in the public domain by Wei Dai #include "pch.h" #include "hrtimer.h" #include "misc.h" #include <stddef.h> // for NULL #include <time.h> #if defined(CRYPTOPP_WIN32_AVAILABLE) #include <windows.h> #elif defined(CRYPTOPP_UNIX_AVAILABLE) #include <sys/time.h> #include <sys/times.h> #include <unistd.h> #endif #include <assert.h> NAMESPACE_BEGIN(CryptoPP) #ifndef CRYPTOPP_IMPORTS double TimerBase::ConvertTo(TimerWord t, Unit unit) { static unsigned long unitsPerSecondTable[] = {1, 1000, 1000*1000, 1000*1000*1000}; assert(unit < sizeof(unitsPerSecondTable) / sizeof(unitsPerSecondTable[0])); return (double)CRYPTOPP_VC6_INT64 t * unitsPerSecondTable[unit] / CRYPTOPP_VC6_INT64 TicksPerSecond(); } void TimerBase::StartTimer() { m_last = m_start = GetCurrentTimerValue(); m_started = true; } double TimerBase::ElapsedTimeAsDouble() { if (m_stuckAtZero) return 0; if (m_started) { TimerWord now = GetCurrentTimerValue(); if (m_last < now) // protect against OS bugs where time goes backwards m_last = now; return ConvertTo(m_last - m_start, m_timerUnit); } StartTimer(); return 0; } unsigned long TimerBase::ElapsedTime() { double elapsed = ElapsedTimeAsDouble(); assert(elapsed <= ULONG_MAX); return (unsigned long)elapsed; } TimerWord Timer::GetCurrentTimerValue() { #if defined(CRYPTOPP_WIN32_AVAILABLE) LARGE_INTEGER now; if (!QueryPerformanceCounter(&now)) throw Exception(Exception::OTHER_ERROR, "Timer: QueryPerformanceCounter failed with error " + IntToString(GetLastError())); return now.QuadPart; #elif defined(CRYPTOPP_UNIX_AVAILABLE) timeval now; gettimeofday(&now, NULL); return (TimerWord)now.tv_sec * 1000000 + now.tv_usec; #else clock_t now; return clock(); #endif } TimerWord Timer::TicksPerSecond() { #if defined(CRYPTOPP_WIN32_AVAILABLE) static LARGE_INTEGER freq = {0}; if (freq.QuadPart == 0) { if (!QueryPerformanceFrequency(&freq)) throw Exception(Exception::OTHER_ERROR, "Timer: QueryPerformanceFrequency failed with error " + IntToString(GetLastError())); } return freq.QuadPart; #elif defined(CRYPTOPP_UNIX_AVAILABLE) return 1000000; #else return CLOCKS_PER_SEC; #endif } #endif // #ifndef CRYPTOPP_IMPORTS TimerWord ThreadUserTimer::GetCurrentTimerValue() { #if defined(CRYPTOPP_WIN32_AVAILABLE) static bool getCurrentThreadImplemented = true; if (getCurrentThreadImplemented) { FILETIME now, ignored; if (!GetThreadTimes(GetCurrentThread(), &ignored, &ignored, &ignored, &now)) { DWORD lastError = GetLastError(); if (lastError == ERROR_CALL_NOT_IMPLEMENTED) { getCurrentThreadImplemented = false; goto GetCurrentThreadNotImplemented; } throw Exception(Exception::OTHER_ERROR, "ThreadUserTimer: GetThreadTimes failed with error " + IntToString(lastError)); } return now.dwLowDateTime + ((TimerWord)now.dwHighDateTime << 32); } GetCurrentThreadNotImplemented: return (TimerWord)clock() * (10*1000*1000 / CLOCKS_PER_SEC); #elif defined(CRYPTOPP_UNIX_AVAILABLE) tms now; times(&now); return now.tms_utime; #else return clock(); #endif } TimerWord ThreadUserTimer::TicksPerSecond() { #if defined(CRYPTOPP_WIN32_AVAILABLE) return 10*1000*1000; #elif defined(CRYPTOPP_UNIX_AVAILABLE) static const long ticksPerSecond = sysconf(_SC_CLK_TCK); return ticksPerSecond; #else return CLOCKS_PER_SEC; #endif } NAMESPACE_END
c3d/tao-3D
libcryptopp/cryptopp/hrtimer.cpp
C++
gpl-3.0
4,791
#pragma region Copyright (c) 2014-2017 OpenRCT2 Developers /***************************************************************************** * OpenRCT2, an open source clone of Roller Coaster Tycoon 2. * * OpenRCT2 is the work of many authors, a full list can be found in contributors.md * For more information, visit https://github.com/OpenRCT2/OpenRCT2 * * OpenRCT2 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. * * A full copy of the GNU General Public License can be found in licence.txt *****************************************************************************/ #pragma endregion #include "../../common.h" #include "../../interface/viewport.h" #include "../../paint/paint.h" #include "../../paint/supports.h" #include "../Track.h" #include "../track_paint.h" #include "../vehicle_paint.h" enum { SPR_ROTO_DROP_TOWER_SEGMENT = 14558, SPR_ROTO_DROP_TOWER_SEGMENT_TOP = 14559, SPR_ROTO_DROP_TOWER_BASE = 14560, SPR_ROTO_DROP_TOWER_BASE_SEGMENT = 14561, SPR_ROTO_DROP_TOWER_BASE_90_DEG = 14562, SPR_ROTO_DROP_TOWER_BASE_SEGMENT_90_DEG = 14563, }; /** * * rct2: 0x006D5DA9 */ void vehicle_visual_roto_drop(paint_session * session, sint32 x, sint32 imageDirection, sint32 y, sint32 z, rct_vehicle * vehicle, const rct_ride_entry_vehicle * vehicleEntry) { sint32 image_id; sint32 baseImage_id = (vehicleEntry->base_image_id + 4) + ((vehicle->var_C5 / 4) & 0x3); if (vehicle->restraints_position >= 64) { baseImage_id += 7; baseImage_id += (vehicle->restraints_position / 64); } const uint8 rotation = get_current_rotation(); // Draw back: image_id = baseImage_id | SPRITE_ID_PALETTE_COLOUR_2(vehicle->colours.body_colour, vehicle->colours.trim_colour); sub_98197C(session, image_id, 0, 0, 2, 2, 41, z, -11, -11, z + 1, rotation); // Draw front: image_id = (baseImage_id + 4) | SPRITE_ID_PALETTE_COLOUR_2(vehicle->colours.body_colour, vehicle->colours.trim_colour); sub_98197C(session, image_id, 0, 0, 16, 16, 41, z, -5, -5, z + 1, rotation); uint8 riding_peep_sprites[64]; memset(riding_peep_sprites, 0xFF, sizeof(riding_peep_sprites)); for (sint32 i = 0; i < vehicle->num_peeps; i++) { uint8 cl = (i & 3) * 16; cl += (i & 0xFC); cl += vehicle->var_C5 / 4; cl += (imageDirection / 8) * 16; cl &= 0x3F; riding_peep_sprites[cl] = vehicle->peep_tshirt_colours[i]; } // Draw riding peep sprites in back to front order: for (sint32 j = 0; j <= 48; j++) { sint32 i = (j % 2) ? (48 - (j / 2)) : (j / 2); if (riding_peep_sprites[i] != 0xFF) { baseImage_id = vehicleEntry->base_image_id + 20 + i; if (vehicle->restraints_position >= 64) { baseImage_id += 64; baseImage_id += vehicle->restraints_position / 64; } image_id = baseImage_id | SPRITE_ID_PALETTE_COLOUR_1(riding_peep_sprites[i]); sub_98199C(session, image_id, 0, 0, 16, 16, 41, z, -5, -5, z + 1, rotation); } }; assert(vehicleEntry->effect_visual == 1); // Although called in original code, effect_visual (splash effects) are not used for many rides and does not make sense so // it was taken out } /** rct2: 0x00886194 */ static void paint_roto_drop_base(paint_session * session, uint8 rideIndex, uint8 trackSequence, uint8 direction, sint32 height, rct_map_element * mapElement) { trackSequence = track_map_3x3[direction][trackSequence]; sint32 edges = edges_3x3[trackSequence]; Ride * ride = get_ride(rideIndex); LocationXY16 position = session->MapPosition; wooden_a_supports_paint_setup(session, (direction & 1), 0, height, session->TrackColours[SCHEME_MISC], NULL); uint32 imageId = SPR_FLOOR_METAL_B | session->TrackColours[SCHEME_SUPPORTS]; sub_98197C(session, imageId, 0, 0, 32, 32, 1, height, 0, 0, height, get_current_rotation()); track_paint_util_paint_fences(session, edges, position, mapElement, ride, session->TrackColours[SCHEME_TRACK], height, fenceSpritesMetalB, get_current_rotation()); if (trackSequence == 0) { imageId = (direction & 1 ? SPR_ROTO_DROP_TOWER_BASE_90_DEG : SPR_ROTO_DROP_TOWER_BASE) | session->TrackColours[SCHEME_TRACK]; sub_98197C(session, imageId, 0, 0, 2, 2, 27, height, 8, 8, height + 3, get_current_rotation()); imageId = (direction & 1 ? SPR_ROTO_DROP_TOWER_BASE_SEGMENT_90_DEG : SPR_ROTO_DROP_TOWER_BASE_SEGMENT) | session->TrackColours[SCHEME_TRACK]; sub_98197C(session, imageId, 0, 0, 2, 2, 30, height + 32, 8, 8, height + 32, get_current_rotation()); imageId = (direction & 1 ? SPR_ROTO_DROP_TOWER_BASE_SEGMENT_90_DEG : SPR_ROTO_DROP_TOWER_BASE_SEGMENT) | session->TrackColours[SCHEME_TRACK]; sub_98197C(session, imageId, 0, 0, 2, 2, 30, height + 64, 8, 8, height + 64, get_current_rotation()); paint_util_set_vertical_tunnel(session, height + 96); paint_util_set_segment_support_height(session, SEGMENTS_ALL, 0xFFFF, 0); #ifdef __TESTPAINT__ paint_util_set_general_support_height(session, height + 32, 0x20); #else paint_util_set_general_support_height(session, height + 96, 0x20); #endif return; } sint32 blockedSegments = 0; switch (trackSequence) { case 1: blockedSegments = SEGMENT_B8 | SEGMENT_C8 | SEGMENT_B4 | SEGMENT_CC | SEGMENT_BC; break; case 2: blockedSegments = SEGMENT_B4 | SEGMENT_CC | SEGMENT_BC; break; case 3: blockedSegments = SEGMENT_B4 | SEGMENT_CC | SEGMENT_BC | SEGMENT_D4 | SEGMENT_C0; break; case 4: blockedSegments = SEGMENT_B4 | SEGMENT_C8 | SEGMENT_B8; break; case 5: blockedSegments = SEGMENT_BC | SEGMENT_D4 | SEGMENT_C0; break; case 6: blockedSegments = SEGMENT_B4 | SEGMENT_C8 | SEGMENT_B8 | SEGMENT_D0 | SEGMENT_C0; break; case 7: blockedSegments = SEGMENT_B8 | SEGMENT_D0 | SEGMENT_C0 | SEGMENT_D4 | SEGMENT_BC; break; case 8: blockedSegments = SEGMENT_B8 | SEGMENT_D0 | SEGMENT_C0; break; } paint_util_set_segment_support_height(session, blockedSegments, 0xFFFF, 0); paint_util_set_segment_support_height(session, SEGMENTS_ALL & ~blockedSegments, height + 2, 0x20); paint_util_set_general_support_height(session, height + 32, 0x20); } /** rct2: 0x008861A4 */ static void paint_roto_drop_tower_section(paint_session * session, uint8 rideIndex, uint8 trackSequence, uint8 direction, sint32 height, rct_map_element * mapElement) { if (trackSequence == 1) { return; } uint32 imageId = SPR_ROTO_DROP_TOWER_SEGMENT | session->TrackColours[SCHEME_TRACK]; sub_98197C(session, imageId, 0, 0, 2, 2, 30, height, 8, 8, height, get_current_rotation()); rct_map_element * nextMapElement = mapElement + 1; if (map_element_is_last_for_tile(mapElement) || mapElement->clearance_height != nextMapElement->base_height) { imageId = SPR_ROTO_DROP_TOWER_SEGMENT_TOP | session->TrackColours[SCHEME_TRACK]; sub_98199C(session, imageId, 0, 0, 2, 2, 30, height, 8, 8, height, get_current_rotation()); } paint_util_set_segment_support_height(session, SEGMENTS_ALL, 0xFFFF, 0); paint_util_set_vertical_tunnel(session, height + 32); paint_util_set_general_support_height(session, height + 32, 0x20); } /** * rct2: 0x00886074 */ TRACK_PAINT_FUNCTION get_track_paint_function_roto_drop(sint32 trackType, sint32 direction) { switch (trackType) { case TRACK_ELEM_TOWER_BASE: return paint_roto_drop_base; case TRACK_ELEM_TOWER_SECTION: return paint_roto_drop_tower_section; } return NULL; }
gDanix/OpenRCT2
src/openrct2/ride/thrill/RotoDrop.cpp
C++
gpl-3.0
8,223
/* * Copyright (C) 2017 Ian Buttimer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ie.ianbuttimer.moviequest.data; import android.text.TextUtils; import java.util.Date; import ie.ianbuttimer.moviequest.utils.DbUtils; import static ie.ianbuttimer.moviequest.data.MovieContract.MovieEntry.COLUMN_JSON; import static ie.ianbuttimer.moviequest.data.MovieContract.MovieEntry.COLUMN_TIMESTAMP; /** * Builder class for a Movie ContentValue objects */ @SuppressWarnings("unused") public class MovieContentValues extends DbContentValues { public static class Builder extends DbContentValues.Builder { /** * Constructor */ Builder() { super(); } /** * {@inheritDoc} */ @Override public Builder setId(int id) { super.setId(id); return this; } /** * Set the JSON string * @param json Json string to set * @return Builder to facilitate chaining */ public Builder setJson(String json) { if (!TextUtils.isEmpty(json)) { cv.put(COLUMN_JSON, json); } return this; } /** * Set the timestamp to the current date & time * @return Builder to facilitate chaining */ public Builder setTimestamp() { return setTimestamp(new Date()); } /** * Set the timestamp to the specified date & time * @param timestamp Timestamp to set * @return Builder to facilitate chaining */ public Builder setTimestamp(Date timestamp) { cv.put(COLUMN_TIMESTAMP, DbUtils.getTimestamp(timestamp)); return this; } @Override public Builder clear() { super.clear(); return this; } } /** * Get a builder instance * @return New builder instance */ public static Builder builder() { return new Builder(); } }
ibuttimer/moviequest
app/src/main/java/ie/ianbuttimer/moviequest/data/MovieContentValues.java
Java
gpl-3.0
2,658
#pragma once #include <memory> #include "storm/models/ModelType.h" #include "storm/models/sparse/StandardRewardModel.h" #include "storm/models/sparse/Model.h" #include "storm/storage/sparse/ModelComponents.h" namespace storm { namespace utility { namespace builder { template<typename ValueType, typename RewardModelType = storm::models::sparse::StandardRewardModel<ValueType>> std::shared_ptr<storm::models::sparse::Model<ValueType, RewardModelType>> buildModelFromComponents(storm::models::ModelType modelType, storm::storage::sparse::ModelComponents<ValueType, RewardModelType>&& components); } } }
MazZzinatus/storm
src/storm/utility/builder.h
C
gpl-3.0
670
/* * Copyright (c) 2015, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** \file * \brief Build code for Haig SOM DFA. */ #ifndef NG_HAIG_H #define NG_HAIG_H #include "ue2common.h" #include "som/som.h" #include <memory> #include <vector> namespace ue2 { class CharReach; class NGHolder; struct Grey; struct raw_som_dfa; #define HAIG_FINAL_DFA_STATE_LIMIT 16383 #define HAIG_HARD_DFA_STATE_LIMIT 8192 /* unordered_som_triggers being true indicates that a live haig may be subjected * to later tops arriving with earlier soms (without the haig going dead in * between) */ std::unique_ptr<raw_som_dfa> attemptToBuildHaig(const NGHolder &g, som_type som, u32 somPrecision, const std::vector<std::vector<CharReach>> &triggers, const Grey &grey, bool unordered_som_triggers = false); std::unique_ptr<raw_som_dfa> attemptToMergeHaig(const std::vector<const raw_som_dfa *> &dfas, u32 limit = HAIG_HARD_DFA_STATE_LIMIT); } // namespace ue2 #endif
variar/klogg
3rdparty/hyperscan/src/nfagraph/ng_haig.h
C
gpl-3.0
2,496
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="http://www.petercorke.com/RVC/common/toolboxhelp.css"> <title>M-File Help: angvec2tr</title> </head> <body> <table border="0" cellspacing="0" width="100%"> <tr class="subheader"> <td class="headertitle">M-File Help: angvec2tr</td> <td class="subheader-left"><a href="matlab:open angvec2tr">View code for angvec2tr</a></td> </tr> </table> <h1>angvec2tr</h1><p><span class="helptopic">Convert angle and vector orientation to a homogeneous transform</span></p><strong>T</strong> = <span style="color:red>angvec2tr</span>(<strong>theta</strong>, <strong>v</strong>) is a homogeneous transform matrix equivalent to a rotation of <strong>theta</strong> about the vector <strong>v</strong>. <h2>Note</h2> <ul> <li>the translational part is zero.</li> </ul> <h2>See also</h2> <p> <a href="matlab:doc eul2tr">eul2tr</a>, <a href="matlab:doc rpy2tr">rpy2tr</a>, <a href="matlab:doc angvec2r">angvec2r</a></p> <hr> <table border="0" width="100%" cellpadding="0" cellspacing="0"> <tr class="subheader" valign="top"><td>&nbsp;</td></tr></table> <p class="copy">&copy; 1990-2011 Peter Corke.</p> </body></html>
m-morelli/softgrasp
thirdparties/rvctools/robot/info/html/angvec2tr.html
HTML
gpl-3.0
1,255
#----------------------------------------------------------------------------- # Copyright (c) 2013-2016, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- from PyInstaller.utils.hooks import exec_statement # This needed because comtypes wx.lib.activex generates some stuff. exec_statement("import wx.lib.activex")
ijat/Hotspot-PUTRA-Auto-login
PyInstaller-3.2/PyInstaller/hooks/hook-wx.lib.activex.py
Python
gpl-3.0
571
<?php include( 'header.php' ); ?> <article class = "text"> <h1>Responsiville Main object</h1> <p> The Responsiville framework defines -and depends on it- a <code>Responsiville.Main</code> object, which is a singleton. This means that only one instance of it is available in each web page. This object is the cornerstone of the Responsiville framework. The whole framework and all its modules depend on it to function and implement their responsive behaviour. </p> <p> First the <code>Responsiville.Main</code> object needs to be instantiated and initialised: </p> <pre><code class = "language-javascript"> $( function () { // Instantiate the Responsiville framework main object. var responsiville = new Responsiville.Main({ debug : true, debugUI : true }); // Initialise the Responsiville framework main object. responsiville.init(); }); </code></pre> <p> After having been initialised one can access it like this: </p> <pre><code class = "language-javascript"> // Acquire the Responsiville singleton instance. var responsiville = Responsiville.Main.getInstance(); // Do something when the framework has initialised. responsiville.on( 'init', function () { // The "this" scope refers to the responsiville instance. console.dir( 'The Responsiville framework has initialised' ); }); // Do something when the current breakpoint changes. responsiville.on( 'change', function () { // The "this" scope refers to the responsiville instance. console.dir( 'The breakpoint has changed to => ' + this.currentBreakpoint.name ); }); // Do something when entering the tablet breakpoint. responsiville.on( 'enter.tablet', function () { // The "this" scope refers to the responsiville instance. console.dir( 'The breakpoint has changed to "tablet"' ); }); </code></pre> <h2>Initialisation process</h2> <p> The instantiation and initialiasation process of the Responsiville Main object is done automatically by default. So, in most cases, one does not need to instantiate and initialise it. This behaviour is controlled by the <code>Responsiville.AUTO_INIT</code> flag, which is <code>true</code> by default. Look at the &quot;installing&quot; and &quot;initialising&quot; sections of this documentation for more details on this subject. </p> <h2>Responsiville Main events</h2> <p> The events of the Responsiville Main object are the most fundamental events of the whole framework because they control all the responsive behaviour of the framework itself, and its modules as well. It is these events that control and trigger behaviour that depends on screen/viewport dimensions and its changes (resizes, breakpoint changes, orientation changes, etc). </p> <p> You can read more on these events and how to use them in the corresponding documentation section. </p> </article> <?php include( 'footer.php' ); ?>
wpgreece/wpgreece-theme
inc/vanilla/responsiville/demo/main.php
PHP
gpl-3.0
3,461
/*************************************************************** * This source files comes from the xLights project * https://www.xlights.org * https://github.com/smeighan/xLights * See the github commit history for a record of contributing * developers. * Copyright claimed based on commit dates recorded in Github * License: https://github.com/smeighan/xLights/blob/master/License.txt **************************************************************/ #include "ListenerARTNet.h" #include <log4cpp/Category.hh> #include <wx/socket.h> #include "../../xLights/outputs/ArtNetOutput.h" #include "ListenerManager.h" #include "../../xLights/UtilFunctions.h" bool ListenerARTNet::IsValidHeader(uint8_t* buffer) { return buffer[0] == 'A' && buffer[1] == 'r' && buffer[2] == 't' && buffer[3] == '-' && buffer[4] == 'N' && buffer[5] == 'e' && buffer[6] == 't' && buffer[7] == 0x00; } ListenerARTNet::ListenerARTNet(ListenerManager* listenerManager) : ListenerBase(listenerManager) { _socket = nullptr; } void ListenerARTNet::Start() { static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base")); logger_base.debug("ARTNet listener starting."); _thread = new ListenerThread(this); } void ListenerARTNet::Stop() { static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base")); if (!_stop) { logger_base.debug("ARTNet listener stopping."); if (_socket != nullptr) _socket->SetTimeout(0); if (_thread != nullptr) { _stop = true; _thread->Stop(); _thread->Delete(); delete _thread; _thread = nullptr; } } } void ListenerARTNet::StartProcess() { static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base")); wxIPV4address localaddr; if (IPOutput::GetLocalIP() == "") { localaddr.AnyAddress(); } else { localaddr.Hostname(IPOutput::GetLocalIP()); } localaddr.Service(ARTNET_PORT); _socket = new wxDatagramSocket(localaddr, wxSOCKET_BROADCAST | wxSOCKET_REUSEADDR); if (_socket == nullptr) { logger_base.error("Error opening datagram for ARTNet reception. %s", (const char *)localaddr.IPAddress().c_str()); } else if (!_socket->IsOk()) { logger_base.error("Error opening datagram for ARTNet reception. %s OK : FALSE", (const char *)localaddr.IPAddress().c_str()); delete _socket; _socket = nullptr; } else if (_socket->Error()) { logger_base.error("Error opening datagram for ARTNet reception. %d : %s %s", _socket->LastError(), (const char*)DecodeIPError(_socket->LastError()).c_str(), (const char *)localaddr.IPAddress().c_str()); delete _socket; _socket = nullptr; } else { _socket->SetTimeout(1); _socket->Notify(false); logger_base.info("ARTNet reception datagram opened successfully."); _isOk = true; } } void ListenerARTNet::StopProcess() { static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base")); if (_socket != nullptr) { logger_base.info("ARTNet Listener closed."); _socket->Close(); delete _socket; _socket = nullptr; } } void ListenerARTNet::Poll() { //static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base")); if (_socket != nullptr) { unsigned char buffer[2048]; memset(buffer, 0x00, sizeof(buffer)); //wxStopWatch sw; //logger_base.debug("Trying to read ARTNet packet."); _socket->Read(&buffer[0], sizeof(buffer)); if (_stop) return; //logger_base.debug(" Read done. %ldms", sw.Time()); if (_socket->GetLastIOReadSize() == 0) { _socket->WaitForRead(0, 50); } else { if (IsValidHeader(buffer)) { int size = ((buffer[16] << 8) + buffer[17]) & 0x0FFF; //logger_base.debug("Processing packet."); if (buffer[9] == 0x50) { // ARTNet data packet int universe = (buffer[13] << 8) + buffer[14]; _listenerManager->ProcessPacket(GetType(), universe, &buffer[ARTNET_PACKET_HEADERLEN], size); } else if (buffer[9] == 0x99) { // Trigger data packet int oem = (((int)buffer[12])<<8) + buffer[13]; _listenerManager->ProcessPacket(GetType() + "Trigger", oem, &buffer[14], 2); } else if (buffer[9] == 0x97) { // Timecode data packet int frames = buffer[14]; int secs = buffer[15]; int mins = buffer[16]; int hours = buffer[17]; int mode = buffer[18]; long ms = ((hours * 60 + mins) * 60 + secs) * 1000; switch (mode) { case 0: //24 fps ms += frames * 1000 / 24; break; case 1: //25 fps ms += frames * 1000 / 25; break; case 2: //29.97 fps ms += frames * 100000 / 2997; break; case 3: //30 fps ms += frames * 1000 / 30; break; default: break; } //logger_base.debug("Timecode packet mode %d %d:%d:%d.%d => %ldms", mode, hours, mins, secs, frames, ms); if (ms == 0) { // This is a stop _listenerManager->Sync("", 0xFFFFFFFF, GetType()); } else { _listenerManager->Sync("", ms, GetType()); } } //logger_base.debug("Processing packet done."); } } } }
cjd/xLights
xSchedule/events/ListenerARTNet.cpp
C++
gpl-3.0
6,484
# dominant
stikagold/dominant
README.md
Markdown
gpl-3.0
10
#include <stdio.h> double f(int n) { int i = 0; int k = 1; double r = 0.000; double fi = 0.000; for (i = 1; i < n+ 1; ++i) { fi = i; r += k*1.000/fi; k = -k; } return r; } int main() { int n; int m; scanf("%d",&n); while(n-- >0 ) { scanf("%d",&m); printf("%.2lf\n",f(m)); } return 0; }
JetMeta/Zds
hd/2011.cpp
C++
gpl-3.0
396
/////////////////////////////////////////////////////////////////////////////// // Name: src/msw/gdiplus.cpp // Purpose: implements wrappers for GDI+ flat API // Author: Vadim Zeitlin // Created: 2007-03-14 // Copyright: (c) 2007 Vadim Zeitlin <vadim@wxwidgets.org> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_GRAPHICS_CONTEXT #ifndef WX_PRECOMP #include "wx/cpp.h" #include "wx/log.h" #include "wx/module.h" #include "wx/string.h" #endif // WX_PRECOMP #include "wx/dynload.h" #include "wx/msw/wrapgdip.h" // w32api headers used by both MinGW and Cygwin wrongly define UINT16 inside // Gdiplus namespace in gdiplus.h which results in ambiguity errors when using // this type as UINT16 is also defined in global scope by windows.h (or rather // basetsd.h included from it), so we redefine it to work around this problem. #if defined(__CYGWIN__) || defined(__MINGW32__) #define UINT16 unsigned short #endif // ---------------------------------------------------------------------------- // helper macros // ---------------------------------------------------------------------------- // return the name we use for the type of the function with the given name // (without "Gdip" prefix) #define wxGDIPLUS_FUNC_T(name) Gdip##name##_t // to avoid repeating all (several hundreds) of GDI+ functions names several // times in this file, we define a macro which allows us to apply another macro // to all (or almost all, as we sometimes have to handle functions not // returning GpStatus separately) these functions at once // this macro expands into an invocation of the given macro m for all GDI+ // functions returning standard GpStatus // // m is called with the name of the function without "Gdip" prefix as the first // argument, the list of function parameters with their names as the second one // and the list of just the parameter names as the third one #define wxFOR_ALL_GDIPLUS_STATUS_FUNCS(m) \ m(CreatePath, (GpFillMode brushMode, GpPath **path), (brushMode, path)) \ m(CreatePath2, (GDIPCONST GpPointF* a1, GDIPCONST BYTE* a2, INT a3, GpFillMode a4, GpPath **path), (a1, a2, a3, a4, path)) \ m(CreatePath2I, (GDIPCONST GpPoint* a1, GDIPCONST BYTE* a2, INT a3, GpFillMode a4, GpPath **path), (a1, a2, a3, a4, path)) \ m(ClonePath, (GpPath* path, GpPath **clonePath), (path, clonePath)) \ m(DeletePath, (GpPath* path), (path)) \ m(ResetPath, (GpPath* path), (path)) \ m(GetPointCount, (GpPath* path, INT* count), (path, count)) \ m(GetPathTypes, (GpPath* path, BYTE* types, INT count), (path, types, count)) \ m(GetPathPoints, (GpPath* a1, GpPointF* points, INT count), (a1, points, count)) \ m(GetPathPointsI, (GpPath* a1, GpPoint* points, INT count), (a1, points, count)) \ m(GetPathFillMode, (GpPath *path, GpFillMode *fillmode), (path, fillmode)) \ m(SetPathFillMode, (GpPath *path, GpFillMode fillmode), (path, fillmode)) \ m(GetPathData, (GpPath *path, GpPathData* pathData), (path, pathData)) \ m(StartPathFigure, (GpPath *path), (path)) \ m(ClosePathFigure, (GpPath *path), (path)) \ m(ClosePathFigures, (GpPath *path), (path)) \ m(SetPathMarker, (GpPath* path), (path)) \ m(ClearPathMarkers, (GpPath* path), (path)) \ m(ReversePath, (GpPath* path), (path)) \ m(GetPathLastPoint, (GpPath* path, GpPointF* lastPoint), (path, lastPoint)) \ m(AddPathLine, (GpPath *path, REAL x1, REAL y1, REAL x2, REAL y2), (path, x1, y1, x2, y2)) \ m(AddPathLine2, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathArc, (GpPath *path, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (path, x, y, width, height, startAngle, sweepAngle)) \ m(AddPathBezier, (GpPath *path, REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4), (path, x1, y1, x2, y2, x3, y3, x4, y4)) \ m(AddPathBeziers, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathCurve, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathCurve2, (GpPath *path, GDIPCONST GpPointF *points, INT count, REAL tension), (path, points, count, tension)) \ m(AddPathCurve3, (GpPath *path, GDIPCONST GpPointF *points, INT count, INT offset, INT numberOfSegments, REAL tension), (path, points, count, offset, numberOfSegments, tension)) \ m(AddPathClosedCurve, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathClosedCurve2, (GpPath *path, GDIPCONST GpPointF *points, INT count, REAL tension), (path, points, count, tension)) \ m(AddPathRectangle, (GpPath *path, REAL x, REAL y, REAL width, REAL height), (path, x, y, width, height)) \ m(AddPathRectangles, (GpPath *path, GDIPCONST GpRectF *rects, INT count), (path, rects, count)) \ m(AddPathEllipse, (GpPath *path, REAL x, REAL y, REAL width, REAL height), (path, x, y, width, height)) \ m(AddPathPie, (GpPath *path, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (path, x, y, width, height, startAngle, sweepAngle)) \ m(AddPathPolygon, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathPath, (GpPath *path, GDIPCONST GpPath* addingPath, BOOL connect), (path, addingPath, connect)) \ m(AddPathString, (GpPath *path, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFontFamily *family, INT style, REAL emSize, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *format), (path, string, length, family, style, emSize, layoutRect, format)) \ m(AddPathStringI, (GpPath *path, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFontFamily *family, INT style, REAL emSize, GDIPCONST Rect *layoutRect, GDIPCONST GpStringFormat *format), (path, string, length, family, style, emSize, layoutRect, format)) \ m(AddPathLineI, (GpPath *path, INT x1, INT y1, INT x2, INT y2), (path, x1, y1, x2, y2)) \ m(AddPathLine2I, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(AddPathArcI, (GpPath *path, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (path, x, y, width, height, startAngle, sweepAngle)) \ m(AddPathBezierI, (GpPath *path, INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4), (path, x1, y1, x2, y2, x3, y3, x4, y4)) \ m(AddPathBeziersI, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(AddPathCurveI, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(AddPathCurve2I, (GpPath *path, GDIPCONST GpPoint *points, INT count, REAL tension), (path, points, count, tension)) \ m(AddPathCurve3I, (GpPath *path, GDIPCONST GpPoint *points, INT count, INT offset, INT numberOfSegments, REAL tension), (path, points, count, offset, numberOfSegments, tension)) \ m(AddPathClosedCurveI, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(AddPathClosedCurve2I, (GpPath *path, GDIPCONST GpPoint *points, INT count, REAL tension), (path, points, count, tension)) \ m(AddPathRectangleI, (GpPath *path, INT x, INT y, INT width, INT height), (path, x, y, width, height)) \ m(AddPathRectanglesI, (GpPath *path, GDIPCONST GpRect *rects, INT count), (path, rects, count)) \ m(AddPathEllipseI, (GpPath *path, INT x, INT y, INT width, INT height), (path, x, y, width, height)) \ m(AddPathPieI, (GpPath *path, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (path, x, y, width, height, startAngle, sweepAngle)) \ m(AddPathPolygonI, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(FlattenPath, (GpPath *path, GpMatrix* matrix, REAL flatness), (path, matrix, flatness)) \ m(WindingModeOutline, (GpPath *path, GpMatrix *matrix, REAL flatness), (path, matrix, flatness)) \ m(WidenPath, (GpPath *nativePath, GpPen *pen, GpMatrix *matrix, REAL flatness), (nativePath, pen, matrix, flatness)) \ m(WarpPath, (GpPath *path, GpMatrix* matrix, GDIPCONST GpPointF *points, INT count, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, WarpMode warpMode, REAL flatness), (path, matrix, points, count, srcx, srcy, srcwidth, srcheight, warpMode, flatness)) \ m(TransformPath, (GpPath* path, GpMatrix* matrix), (path, matrix)) \ m(GetPathWorldBounds, (GpPath* path, GpRectF* bounds, GDIPCONST GpMatrix *matrix, GDIPCONST GpPen *pen), (path, bounds, matrix, pen)) \ m(GetPathWorldBoundsI, (GpPath* path, GpRect* bounds, GDIPCONST GpMatrix *matrix, GDIPCONST GpPen *pen), (path, bounds, matrix, pen)) \ m(IsVisiblePathPoint, (GpPath* path, REAL x, REAL y, GpGraphics *graphics, BOOL *result), (path, x, y, graphics, result)) \ m(IsVisiblePathPointI, (GpPath* path, INT x, INT y, GpGraphics *graphics, BOOL *result), (path, x, y, graphics, result)) \ m(IsOutlineVisiblePathPoint, (GpPath* path, REAL x, REAL y, GpPen *pen, GpGraphics *graphics, BOOL *result), (path, x, y, pen, graphics, result)) \ m(IsOutlineVisiblePathPointI, (GpPath* path, INT x, INT y, GpPen *pen, GpGraphics *graphics, BOOL *result), (path, x, y, pen, graphics, result)) \ m(CreatePathIter, (GpPathIterator **iterator, GpPath* path), (iterator, path)) \ m(DeletePathIter, (GpPathIterator *iterator), (iterator)) \ m(PathIterNextSubpath, (GpPathIterator* iterator, INT *resultCount, INT* startIndex, INT* endIndex, BOOL* isClosed), (iterator, resultCount, startIndex, endIndex, isClosed)) \ m(PathIterNextSubpathPath, (GpPathIterator* iterator, INT* resultCount, GpPath* path, BOOL* isClosed), (iterator, resultCount, path, isClosed)) \ m(PathIterNextPathType, (GpPathIterator* iterator, INT* resultCount, BYTE* pathType, INT* startIndex, INT* endIndex), (iterator, resultCount, pathType, startIndex, endIndex)) \ m(PathIterNextMarker, (GpPathIterator* iterator, INT *resultCount, INT* startIndex, INT* endIndex), (iterator, resultCount, startIndex, endIndex)) \ m(PathIterNextMarkerPath, (GpPathIterator* iterator, INT* resultCount, GpPath* path), (iterator, resultCount, path)) \ m(PathIterGetCount, (GpPathIterator* iterator, INT* count), (iterator, count)) \ m(PathIterGetSubpathCount, (GpPathIterator* iterator, INT* count), (iterator, count)) \ m(PathIterIsValid, (GpPathIterator* iterator, BOOL* valid), (iterator, valid)) \ m(PathIterHasCurve, (GpPathIterator* iterator, BOOL* hasCurve), (iterator, hasCurve)) \ m(PathIterRewind, (GpPathIterator* iterator), (iterator)) \ m(PathIterEnumerate, (GpPathIterator* iterator, INT* resultCount, GpPointF *points, BYTE *types, INT count), (iterator, resultCount, points, types, count)) \ m(PathIterCopyData, (GpPathIterator* iterator, INT* resultCount, GpPointF* points, BYTE* types, INT startIndex, INT endIndex), (iterator, resultCount, points, types, startIndex, endIndex)) \ m(CreateMatrix, (GpMatrix **matrix), (matrix)) \ m(CreateMatrix2, (REAL m11, REAL m12, REAL m21, REAL m22, REAL dx, REAL dy, GpMatrix **matrix), (m11, m12, m21, m22, dx, dy, matrix)) \ m(CreateMatrix3, (GDIPCONST GpRectF *rect, GDIPCONST GpPointF *dstplg, GpMatrix **matrix), (rect, dstplg, matrix)) \ m(CreateMatrix3I, (GDIPCONST GpRect *rect, GDIPCONST GpPoint *dstplg, GpMatrix **matrix), (rect, dstplg, matrix)) \ m(CloneMatrix, (GpMatrix *matrix, GpMatrix **cloneMatrix), (matrix, cloneMatrix)) \ m(DeleteMatrix, (GpMatrix *matrix), (matrix)) \ m(SetMatrixElements, (GpMatrix *matrix, REAL m11, REAL m12, REAL m21, REAL m22, REAL dx, REAL dy), (matrix, m11, m12, m21, m22, dx, dy)) \ m(MultiplyMatrix, (GpMatrix *matrix, GpMatrix* matrix2, GpMatrixOrder order), (matrix, matrix2, order)) \ m(TranslateMatrix, (GpMatrix *matrix, REAL offsetX, REAL offsetY, GpMatrixOrder order), (matrix, offsetX, offsetY, order)) \ m(ScaleMatrix, (GpMatrix *matrix, REAL scaleX, REAL scaleY, GpMatrixOrder order), (matrix, scaleX, scaleY, order)) \ m(RotateMatrix, (GpMatrix *matrix, REAL angle, GpMatrixOrder order), (matrix, angle, order)) \ m(ShearMatrix, (GpMatrix *matrix, REAL shearX, REAL shearY, GpMatrixOrder order), (matrix, shearX, shearY, order)) \ m(InvertMatrix, (GpMatrix *matrix), (matrix)) \ m(TransformMatrixPoints, (GpMatrix *matrix, GpPointF *pts, INT count), (matrix, pts, count)) \ m(TransformMatrixPointsI, (GpMatrix *matrix, GpPoint *pts, INT count), (matrix, pts, count)) \ m(VectorTransformMatrixPoints, (GpMatrix *matrix, GpPointF *pts, INT count), (matrix, pts, count)) \ m(VectorTransformMatrixPointsI, (GpMatrix *matrix, GpPoint *pts, INT count), (matrix, pts, count)) \ m(GetMatrixElements, (GDIPCONST GpMatrix *matrix, REAL *matrixOut), (matrix, matrixOut)) \ m(IsMatrixInvertible, (GDIPCONST GpMatrix *matrix, BOOL *result), (matrix, result)) \ m(IsMatrixIdentity, (GDIPCONST GpMatrix *matrix, BOOL *result), (matrix, result)) \ m(IsMatrixEqual, (GDIPCONST GpMatrix *matrix, GDIPCONST GpMatrix *matrix2, BOOL *result), (matrix, matrix2, result)) \ m(CreateRegion, (GpRegion **region), (region)) \ m(CreateRegionRect, (GDIPCONST GpRectF *rect, GpRegion **region), (rect, region)) \ m(CreateRegionRectI, (GDIPCONST GpRect *rect, GpRegion **region), (rect, region)) \ m(CreateRegionPath, (GpPath *path, GpRegion **region), (path, region)) \ m(CreateRegionRgnData, (GDIPCONST BYTE *regionData, INT size, GpRegion **region), (regionData, size, region)) \ m(CreateRegionHrgn, (HRGN hRgn, GpRegion **region), (hRgn, region)) \ m(CloneRegion, (GpRegion *region, GpRegion **cloneRegion), (region, cloneRegion)) \ m(DeleteRegion, (GpRegion *region), (region)) \ m(SetInfinite, (GpRegion *region), (region)) \ m(SetEmpty, (GpRegion *region), (region)) \ m(CombineRegionRect, (GpRegion *region, GDIPCONST GpRectF *rect, CombineMode combineMode), (region, rect, combineMode)) \ m(CombineRegionRectI, (GpRegion *region, GDIPCONST GpRect *rect, CombineMode combineMode), (region, rect, combineMode)) \ m(CombineRegionPath, (GpRegion *region, GpPath *path, CombineMode combineMode), (region, path, combineMode)) \ m(CombineRegionRegion, (GpRegion *region, GpRegion *region2, CombineMode combineMode), (region, region2, combineMode)) \ m(TranslateRegion, (GpRegion *region, REAL dx, REAL dy), (region, dx, dy)) \ m(TranslateRegionI, (GpRegion *region, INT dx, INT dy), (region, dx, dy)) \ m(TransformRegion, (GpRegion *region, GpMatrix *matrix), (region, matrix)) \ m(GetRegionBounds, (GpRegion *region, GpGraphics *graphics, GpRectF *rect), (region, graphics, rect)) \ m(GetRegionBoundsI, (GpRegion *region, GpGraphics *graphics, GpRect *rect), (region, graphics, rect)) \ m(GetRegionHRgn, (GpRegion *region, GpGraphics *graphics, HRGN *hRgn), (region, graphics, hRgn)) \ m(IsEmptyRegion, (GpRegion *region, GpGraphics *graphics, BOOL *result), (region, graphics, result)) \ m(IsInfiniteRegion, (GpRegion *region, GpGraphics *graphics, BOOL *result), (region, graphics, result)) \ m(IsEqualRegion, (GpRegion *region, GpRegion *region2, GpGraphics *graphics, BOOL *result), (region, region2, graphics, result)) \ m(GetRegionDataSize, (GpRegion *region, UINT *bufferSize), (region, bufferSize)) \ m(GetRegionData, (GpRegion *region, BYTE *buffer, UINT bufferSize, UINT *sizeFilled), (region, buffer, bufferSize, sizeFilled)) \ m(IsVisibleRegionPoint, (GpRegion *region, REAL x, REAL y, GpGraphics *graphics, BOOL *result), (region, x, y, graphics, result)) \ m(IsVisibleRegionPointI, (GpRegion *region, INT x, INT y, GpGraphics *graphics, BOOL *result), (region, x, y, graphics, result)) \ m(IsVisibleRegionRect, (GpRegion *region, REAL x, REAL y, REAL width, REAL height, GpGraphics *graphics, BOOL *result), (region, x, y, width, height, graphics, result)) \ m(IsVisibleRegionRectI, (GpRegion *region, INT x, INT y, INT width, INT height, GpGraphics *graphics, BOOL *result), (region, x, y, width, height, graphics, result)) \ m(GetRegionScansCount, (GpRegion *region, UINT* count, GpMatrix* matrix), (region, count, matrix)) \ m(GetRegionScans, (GpRegion *region, GpRectF* rects, INT* count, GpMatrix* matrix), (region, rects, count, matrix)) \ m(GetRegionScansI, (GpRegion *region, GpRect* rects, INT* count, GpMatrix* matrix), (region, rects, count, matrix)) \ m(CloneBrush, (GpBrush *brush, GpBrush **cloneBrush), (brush, cloneBrush)) \ m(DeleteBrush, (GpBrush *brush), (brush)) \ m(GetBrushType, (GpBrush *brush, GpBrushType *type), (brush, type)) \ m(CreateHatchBrush, (GpHatchStyle hatchstyle, ARGB forecol, ARGB backcol, GpHatch **brush), (hatchstyle, forecol, backcol, brush)) \ m(GetHatchStyle, (GpHatch *brush, GpHatchStyle *hatchstyle), (brush, hatchstyle)) \ m(GetHatchForegroundColor, (GpHatch *brush, ARGB* forecol), (brush, forecol)) \ m(GetHatchBackgroundColor, (GpHatch *brush, ARGB* backcol), (brush, backcol)) \ m(CreateTexture, (GpImage *image, GpWrapMode wrapmode, GpTexture **texture), (image, wrapmode, texture)) \ m(CreateTexture2, (GpImage *image, GpWrapMode wrapmode, REAL x, REAL y, REAL width, REAL height, GpTexture **texture), (image, wrapmode, x, y, width, height, texture)) \ m(CreateTextureIA, (GpImage *image, GDIPCONST GpImageAttributes *imageAttributes, REAL x, REAL y, REAL width, REAL height, GpTexture **texture), (image, imageAttributes, x, y, width, height, texture)) \ m(CreateTexture2I, (GpImage *image, GpWrapMode wrapmode, INT x, INT y, INT width, INT height, GpTexture **texture), (image, wrapmode, x, y, width, height, texture)) \ m(CreateTextureIAI, (GpImage *image, GDIPCONST GpImageAttributes *imageAttributes, INT x, INT y, INT width, INT height, GpTexture **texture), (image, imageAttributes, x, y, width, height, texture)) \ m(GetTextureTransform, (GpTexture *brush, GpMatrix *matrix), (brush, matrix)) \ m(SetTextureTransform, (GpTexture *brush, GDIPCONST GpMatrix *matrix), (brush, matrix)) \ m(ResetTextureTransform, (GpTexture* brush), (brush)) \ m(MultiplyTextureTransform, (GpTexture* brush, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (brush, matrix, order)) \ m(TranslateTextureTransform, (GpTexture* brush, REAL dx, REAL dy, GpMatrixOrder order), (brush, dx, dy, order)) \ m(ScaleTextureTransform, (GpTexture* brush, REAL sx, REAL sy, GpMatrixOrder order), (brush, sx, sy, order)) \ m(RotateTextureTransform, (GpTexture* brush, REAL angle, GpMatrixOrder order), (brush, angle, order)) \ m(SetTextureWrapMode, (GpTexture *brush, GpWrapMode wrapmode), (brush, wrapmode)) \ m(GetTextureWrapMode, (GpTexture *brush, GpWrapMode *wrapmode), (brush, wrapmode)) \ m(GetTextureImage, (GpTexture *brush, GpImage **image), (brush, image)) \ m(CreateSolidFill, (ARGB color, GpSolidFill **brush), (color, brush)) \ m(SetSolidFillColor, (GpSolidFill *brush, ARGB color), (brush, color)) \ m(GetSolidFillColor, (GpSolidFill *brush, ARGB *color), (brush, color)) \ m(CreateLineBrush, (GDIPCONST GpPointF* point1, GDIPCONST GpPointF* point2, ARGB color1, ARGB color2, GpWrapMode wrapMode, GpLineGradient **lineGradient), (point1, point2, color1, color2, wrapMode, lineGradient)) \ m(CreateLineBrushI, (GDIPCONST GpPoint* point1, GDIPCONST GpPoint* point2, ARGB color1, ARGB color2, GpWrapMode wrapMode, GpLineGradient **lineGradient), (point1, point2, color1, color2, wrapMode, lineGradient)) \ m(CreateLineBrushFromRect, (GDIPCONST GpRectF* rect, ARGB color1, ARGB color2, LinearGradientMode mode, GpWrapMode wrapMode, GpLineGradient **lineGradient), (rect, color1, color2, mode, wrapMode, lineGradient)) \ m(CreateLineBrushFromRectI, (GDIPCONST GpRect* rect, ARGB color1, ARGB color2, LinearGradientMode mode, GpWrapMode wrapMode, GpLineGradient **lineGradient), (rect, color1, color2, mode, wrapMode, lineGradient)) \ m(CreateLineBrushFromRectWithAngle, (GDIPCONST GpRectF* rect, ARGB color1, ARGB color2, REAL angle, BOOL isAngleScalable, GpWrapMode wrapMode, GpLineGradient **lineGradient), (rect, color1, color2, angle, isAngleScalable, wrapMode, lineGradient)) \ m(CreateLineBrushFromRectWithAngleI, (GDIPCONST GpRect* rect, ARGB color1, ARGB color2, REAL angle, BOOL isAngleScalable, GpWrapMode wrapMode, GpLineGradient **lineGradient), (rect, color1, color2, angle, isAngleScalable, wrapMode, lineGradient)) \ m(SetLineColors, (GpLineGradient *brush, ARGB color1, ARGB color2), (brush, color1, color2)) \ m(GetLineColors, (GpLineGradient *brush, ARGB* colors), (brush, colors)) \ m(GetLineRect, (GpLineGradient *brush, GpRectF *rect), (brush, rect)) \ m(GetLineRectI, (GpLineGradient *brush, GpRect *rect), (brush, rect)) \ m(SetLineGammaCorrection, (GpLineGradient *brush, BOOL useGammaCorrection), (brush, useGammaCorrection)) \ m(GetLineGammaCorrection, (GpLineGradient *brush, BOOL *useGammaCorrection), (brush, useGammaCorrection)) \ m(GetLineBlendCount, (GpLineGradient *brush, INT *count), (brush, count)) \ m(GetLineBlend, (GpLineGradient *brush, REAL *blend, REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetLineBlend, (GpLineGradient *brush, GDIPCONST REAL *blend, GDIPCONST REAL* positions, INT count), (brush, blend, positions, count)) \ m(GetLinePresetBlendCount, (GpLineGradient *brush, INT *count), (brush, count)) \ m(GetLinePresetBlend, (GpLineGradient *brush, ARGB *blend, REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetLinePresetBlend, (GpLineGradient *brush, GDIPCONST ARGB *blend, GDIPCONST REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetLineSigmaBlend, (GpLineGradient *brush, REAL focus, REAL scale), (brush, focus, scale)) \ m(SetLineLinearBlend, (GpLineGradient *brush, REAL focus, REAL scale), (brush, focus, scale)) \ m(SetLineWrapMode, (GpLineGradient *brush, GpWrapMode wrapmode), (brush, wrapmode)) \ m(GetLineWrapMode, (GpLineGradient *brush, GpWrapMode *wrapmode), (brush, wrapmode)) \ m(GetLineTransform, (GpLineGradient *brush, GpMatrix *matrix), (brush, matrix)) \ m(SetLineTransform, (GpLineGradient *brush, GDIPCONST GpMatrix *matrix), (brush, matrix)) \ m(ResetLineTransform, (GpLineGradient* brush), (brush)) \ m(MultiplyLineTransform, (GpLineGradient* brush, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (brush, matrix, order)) \ m(TranslateLineTransform, (GpLineGradient* brush, REAL dx, REAL dy, GpMatrixOrder order), (brush, dx, dy, order)) \ m(ScaleLineTransform, (GpLineGradient* brush, REAL sx, REAL sy, GpMatrixOrder order), (brush, sx, sy, order)) \ m(RotateLineTransform, (GpLineGradient* brush, REAL angle, GpMatrixOrder order), (brush, angle, order)) \ m(CreatePathGradient, (GDIPCONST GpPointF* points, INT count, GpWrapMode wrapMode, GpPathGradient **polyGradient), (points, count, wrapMode, polyGradient)) \ m(CreatePathGradientI, (GDIPCONST GpPoint* points, INT count, GpWrapMode wrapMode, GpPathGradient **polyGradient), (points, count, wrapMode, polyGradient)) \ m(CreatePathGradientFromPath, (GDIPCONST GpPath* path, GpPathGradient **polyGradient), (path, polyGradient)) \ m(GetPathGradientCenterColor, (GpPathGradient *brush, ARGB* colors), (brush, colors)) \ m(SetPathGradientCenterColor, (GpPathGradient *brush, ARGB colors), (brush, colors)) \ m(GetPathGradientSurroundColorsWithCount, (GpPathGradient *brush, ARGB* color, INT* count), (brush, color, count)) \ m(SetPathGradientSurroundColorsWithCount, (GpPathGradient *brush, GDIPCONST ARGB* color, INT* count), (brush, color, count)) \ m(GetPathGradientPath, (GpPathGradient *brush, GpPath *path), (brush, path)) \ m(SetPathGradientPath, (GpPathGradient *brush, GDIPCONST GpPath *path), (brush, path)) \ m(GetPathGradientCenterPoint, (GpPathGradient *brush, GpPointF* points), (brush, points)) \ m(GetPathGradientCenterPointI, (GpPathGradient *brush, GpPoint* points), (brush, points)) \ m(SetPathGradientCenterPoint, (GpPathGradient *brush, GDIPCONST GpPointF* points), (brush, points)) \ m(SetPathGradientCenterPointI, (GpPathGradient *brush, GDIPCONST GpPoint* points), (brush, points)) \ m(GetPathGradientRect, (GpPathGradient *brush, GpRectF *rect), (brush, rect)) \ m(GetPathGradientRectI, (GpPathGradient *brush, GpRect *rect), (brush, rect)) \ m(GetPathGradientPointCount, (GpPathGradient *brush, INT* count), (brush, count)) \ m(GetPathGradientSurroundColorCount, (GpPathGradient *brush, INT* count), (brush, count)) \ m(SetPathGradientGammaCorrection, (GpPathGradient *brush, BOOL useGammaCorrection), (brush, useGammaCorrection)) \ m(GetPathGradientGammaCorrection, (GpPathGradient *brush, BOOL *useGammaCorrection), (brush, useGammaCorrection)) \ m(GetPathGradientBlendCount, (GpPathGradient *brush, INT *count), (brush, count)) \ m(GetPathGradientBlend, (GpPathGradient *brush, REAL *blend, REAL *positions, INT count), (brush, blend, positions, count)) \ m(SetPathGradientBlend, (GpPathGradient *brush, GDIPCONST REAL *blend, GDIPCONST REAL *positions, INT count), (brush, blend, positions, count)) \ m(GetPathGradientPresetBlendCount, (GpPathGradient *brush, INT *count), (brush, count)) \ m(GetPathGradientPresetBlend, (GpPathGradient *brush, ARGB *blend, REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetPathGradientPresetBlend, (GpPathGradient *brush, GDIPCONST ARGB *blend, GDIPCONST REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetPathGradientSigmaBlend, (GpPathGradient *brush, REAL focus, REAL scale), (brush, focus, scale)) \ m(SetPathGradientLinearBlend, (GpPathGradient *brush, REAL focus, REAL scale), (brush, focus, scale)) \ m(GetPathGradientWrapMode, (GpPathGradient *brush, GpWrapMode *wrapmode), (brush, wrapmode)) \ m(SetPathGradientWrapMode, (GpPathGradient *brush, GpWrapMode wrapmode), (brush, wrapmode)) \ m(GetPathGradientTransform, (GpPathGradient *brush, GpMatrix *matrix), (brush, matrix)) \ m(SetPathGradientTransform, (GpPathGradient *brush, GpMatrix *matrix), (brush, matrix)) \ m(ResetPathGradientTransform, (GpPathGradient* brush), (brush)) \ m(MultiplyPathGradientTransform, (GpPathGradient* brush, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (brush, matrix, order)) \ m(TranslatePathGradientTransform, (GpPathGradient* brush, REAL dx, REAL dy, GpMatrixOrder order), (brush, dx, dy, order)) \ m(ScalePathGradientTransform, (GpPathGradient* brush, REAL sx, REAL sy, GpMatrixOrder order), (brush, sx, sy, order)) \ m(RotatePathGradientTransform, (GpPathGradient* brush, REAL angle, GpMatrixOrder order), (brush, angle, order)) \ m(GetPathGradientFocusScales, (GpPathGradient *brush, REAL* xScale, REAL* yScale), (brush, xScale, yScale)) \ m(SetPathGradientFocusScales, (GpPathGradient *brush, REAL xScale, REAL yScale), (brush, xScale, yScale)) \ m(CreatePen1, (ARGB color, REAL width, GpUnit unit, GpPen **pen), (color, width, unit, pen)) \ m(CreatePen2, (GpBrush *brush, REAL width, GpUnit unit, GpPen **pen), (brush, width, unit, pen)) \ m(ClonePen, (GpPen *pen, GpPen **clonepen), (pen, clonepen)) \ m(DeletePen, (GpPen *pen), (pen)) \ m(SetPenWidth, (GpPen *pen, REAL width), (pen, width)) \ m(GetPenWidth, (GpPen *pen, REAL *width), (pen, width)) \ m(SetPenUnit, (GpPen *pen, GpUnit unit), (pen, unit)) \ m(GetPenUnit, (GpPen *pen, GpUnit *unit), (pen, unit)) \ m(SetPenLineCap197819, (GpPen *pen, GpLineCap startCap, GpLineCap endCap, GpDashCap dashCap), (pen, startCap, endCap, dashCap)) \ m(SetPenStartCap, (GpPen *pen, GpLineCap startCap), (pen, startCap)) \ m(SetPenEndCap, (GpPen *pen, GpLineCap endCap), (pen, endCap)) \ m(SetPenDashCap197819, (GpPen *pen, GpDashCap dashCap), (pen, dashCap)) \ m(GetPenStartCap, (GpPen *pen, GpLineCap *startCap), (pen, startCap)) \ m(GetPenEndCap, (GpPen *pen, GpLineCap *endCap), (pen, endCap)) \ m(GetPenDashCap197819, (GpPen *pen, GpDashCap *dashCap), (pen, dashCap)) \ m(SetPenLineJoin, (GpPen *pen, GpLineJoin lineJoin), (pen, lineJoin)) \ m(GetPenLineJoin, (GpPen *pen, GpLineJoin *lineJoin), (pen, lineJoin)) \ m(SetPenCustomStartCap, (GpPen *pen, GpCustomLineCap* customCap), (pen, customCap)) \ m(GetPenCustomStartCap, (GpPen *pen, GpCustomLineCap** customCap), (pen, customCap)) \ m(SetPenCustomEndCap, (GpPen *pen, GpCustomLineCap* customCap), (pen, customCap)) \ m(GetPenCustomEndCap, (GpPen *pen, GpCustomLineCap** customCap), (pen, customCap)) \ m(SetPenMiterLimit, (GpPen *pen, REAL miterLimit), (pen, miterLimit)) \ m(GetPenMiterLimit, (GpPen *pen, REAL *miterLimit), (pen, miterLimit)) \ m(SetPenMode, (GpPen *pen, GpPenAlignment penMode), (pen, penMode)) \ m(GetPenMode, (GpPen *pen, GpPenAlignment *penMode), (pen, penMode)) \ m(SetPenTransform, (GpPen *pen, GpMatrix *matrix), (pen, matrix)) \ m(GetPenTransform, (GpPen *pen, GpMatrix *matrix), (pen, matrix)) \ m(ResetPenTransform, (GpPen *pen), (pen)) \ m(MultiplyPenTransform, (GpPen *pen, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (pen, matrix, order)) \ m(TranslatePenTransform, (GpPen *pen, REAL dx, REAL dy, GpMatrixOrder order), (pen, dx, dy, order)) \ m(ScalePenTransform, (GpPen *pen, REAL sx, REAL sy, GpMatrixOrder order), (pen, sx, sy, order)) \ m(RotatePenTransform, (GpPen *pen, REAL angle, GpMatrixOrder order), (pen, angle, order)) \ m(SetPenColor, (GpPen *pen, ARGB argb), (pen, argb)) \ m(GetPenColor, (GpPen *pen, ARGB *argb), (pen, argb)) \ m(SetPenBrushFill, (GpPen *pen, GpBrush *brush), (pen, brush)) \ m(GetPenBrushFill, (GpPen *pen, GpBrush **brush), (pen, brush)) \ m(GetPenFillType, (GpPen *pen, GpPenType* type), (pen, type)) \ m(GetPenDashStyle, (GpPen *pen, GpDashStyle *dashstyle), (pen, dashstyle)) \ m(SetPenDashStyle, (GpPen *pen, GpDashStyle dashstyle), (pen, dashstyle)) \ m(GetPenDashOffset, (GpPen *pen, REAL *offset), (pen, offset)) \ m(SetPenDashOffset, (GpPen *pen, REAL offset), (pen, offset)) \ m(GetPenDashCount, (GpPen *pen, INT *count), (pen, count)) \ m(SetPenDashArray, (GpPen *pen, GDIPCONST REAL *dash, INT count), (pen, dash, count)) \ m(GetPenDashArray, (GpPen *pen, REAL *dash, INT count), (pen, dash, count)) \ m(GetPenCompoundCount, (GpPen *pen, INT *count), (pen, count)) \ m(SetPenCompoundArray, (GpPen *pen, GDIPCONST REAL *dash, INT count), (pen, dash, count)) \ m(GetPenCompoundArray, (GpPen *pen, REAL *dash, INT count), (pen, dash, count)) \ m(CreateCustomLineCap, (GpPath* fillPath, GpPath* strokePath, GpLineCap baseCap, REAL baseInset, GpCustomLineCap **customCap), (fillPath, strokePath, baseCap, baseInset, customCap)) \ m(DeleteCustomLineCap, (GpCustomLineCap* customCap), (customCap)) \ m(CloneCustomLineCap, (GpCustomLineCap* customCap, GpCustomLineCap** clonedCap), (customCap, clonedCap)) \ m(GetCustomLineCapType, (GpCustomLineCap* customCap, CustomLineCapType* capType), (customCap, capType)) \ m(SetCustomLineCapStrokeCaps, (GpCustomLineCap* customCap, GpLineCap startCap, GpLineCap endCap), (customCap, startCap, endCap)) \ m(GetCustomLineCapStrokeCaps, (GpCustomLineCap* customCap, GpLineCap* startCap, GpLineCap* endCap), (customCap, startCap, endCap)) \ m(SetCustomLineCapStrokeJoin, (GpCustomLineCap* customCap, GpLineJoin lineJoin), (customCap, lineJoin)) \ m(GetCustomLineCapStrokeJoin, (GpCustomLineCap* customCap, GpLineJoin* lineJoin), (customCap, lineJoin)) \ m(SetCustomLineCapBaseCap, (GpCustomLineCap* customCap, GpLineCap baseCap), (customCap, baseCap)) \ m(GetCustomLineCapBaseCap, (GpCustomLineCap* customCap, GpLineCap* baseCap), (customCap, baseCap)) \ m(SetCustomLineCapBaseInset, (GpCustomLineCap* customCap, REAL inset), (customCap, inset)) \ m(GetCustomLineCapBaseInset, (GpCustomLineCap* customCap, REAL* inset), (customCap, inset)) \ m(SetCustomLineCapWidthScale, (GpCustomLineCap* customCap, REAL widthScale), (customCap, widthScale)) \ m(GetCustomLineCapWidthScale, (GpCustomLineCap* customCap, REAL* widthScale), (customCap, widthScale)) \ m(CreateAdjustableArrowCap, (REAL height, REAL width, BOOL isFilled, GpAdjustableArrowCap **cap), (height, width, isFilled, cap)) \ m(SetAdjustableArrowCapHeight, (GpAdjustableArrowCap* cap, REAL height), (cap, height)) \ m(GetAdjustableArrowCapHeight, (GpAdjustableArrowCap* cap, REAL* height), (cap, height)) \ m(SetAdjustableArrowCapWidth, (GpAdjustableArrowCap* cap, REAL width), (cap, width)) \ m(GetAdjustableArrowCapWidth, (GpAdjustableArrowCap* cap, REAL* width), (cap, width)) \ m(SetAdjustableArrowCapMiddleInset, (GpAdjustableArrowCap* cap, REAL middleInset), (cap, middleInset)) \ m(GetAdjustableArrowCapMiddleInset, (GpAdjustableArrowCap* cap, REAL* middleInset), (cap, middleInset)) \ m(SetAdjustableArrowCapFillState, (GpAdjustableArrowCap* cap, BOOL fillState), (cap, fillState)) \ m(GetAdjustableArrowCapFillState, (GpAdjustableArrowCap* cap, BOOL* fillState), (cap, fillState)) \ m(LoadImageFromStream, (IStream* stream, GpImage **image), (stream, image)) \ m(LoadImageFromFile, (GDIPCONST WCHAR* filename, GpImage **image), (filename, image)) \ m(LoadImageFromStreamICM, (IStream* stream, GpImage **image), (stream, image)) \ m(LoadImageFromFileICM, (GDIPCONST WCHAR* filename, GpImage **image), (filename, image)) \ m(CloneImage, (GpImage *image, GpImage **cloneImage), (image, cloneImage)) \ m(DisposeImage, (GpImage *image), (image)) \ m(SaveImageToFile, (GpImage *image, GDIPCONST WCHAR* filename, GDIPCONST CLSID* clsidEncoder, GDIPCONST EncoderParameters* encoderParams), (image, filename, clsidEncoder, encoderParams)) \ m(SaveImageToStream, (GpImage *image, IStream* stream, GDIPCONST CLSID* clsidEncoder, GDIPCONST EncoderParameters* encoderParams), (image, stream, clsidEncoder, encoderParams)) \ m(SaveAdd, (GpImage *image, GDIPCONST EncoderParameters* encoderParams), (image, encoderParams)) \ m(SaveAddImage, (GpImage *image, GpImage* newImage, GDIPCONST EncoderParameters* encoderParams), (image, newImage, encoderParams)) \ m(GetImageGraphicsContext, (GpImage *image, GpGraphics **graphics), (image, graphics)) \ m(GetImageBounds, (GpImage *image, GpRectF *srcRect, GpUnit *srcUnit), (image, srcRect, srcUnit)) \ m(GetImageDimension, (GpImage *image, REAL *width, REAL *height), (image, width, height)) \ m(GetImageType, (GpImage *image, ImageType *type), (image, type)) \ m(GetImageWidth, (GpImage *image, UINT *width), (image, width)) \ m(GetImageHeight, (GpImage *image, UINT *height), (image, height)) \ m(GetImageHorizontalResolution, (GpImage *image, REAL *resolution), (image, resolution)) \ m(GetImageVerticalResolution, (GpImage *image, REAL *resolution), (image, resolution)) \ m(GetImageFlags, (GpImage *image, UINT *flags), (image, flags)) \ m(GetImageRawFormat, (GpImage *image, GUID *format), (image, format)) \ m(GetImagePixelFormat, (GpImage *image, PixelFormat *format), (image, format)) \ m(GetImageThumbnail, (GpImage *image, UINT thumbWidth, UINT thumbHeight, GpImage **thumbImage, GetThumbnailImageAbort callback, VOID *callbackData), (image, thumbWidth, thumbHeight, thumbImage, callback, callbackData)) \ m(GetEncoderParameterListSize, (GpImage *image, GDIPCONST CLSID* clsidEncoder, UINT* size), (image, clsidEncoder, size)) \ m(GetEncoderParameterList, (GpImage *image, GDIPCONST CLSID* clsidEncoder, UINT size, EncoderParameters* buffer), (image, clsidEncoder, size, buffer)) \ m(ImageGetFrameDimensionsCount, (GpImage* image, UINT* count), (image, count)) \ m(ImageGetFrameDimensionsList, (GpImage* image, GUID* dimensionIDs, UINT count), (image, dimensionIDs, count)) \ m(ImageGetFrameCount, (GpImage *image, GDIPCONST GUID* dimensionID, UINT* count), (image, dimensionID, count)) \ m(ImageSelectActiveFrame, (GpImage *image, GDIPCONST GUID* dimensionID, UINT frameIndex), (image, dimensionID, frameIndex)) \ m(ImageRotateFlip, (GpImage *image, RotateFlipType rfType), (image, rfType)) \ m(GetImagePalette, (GpImage *image, ColorPalette *palette, INT size), (image, palette, size)) \ m(SetImagePalette, (GpImage *image, GDIPCONST ColorPalette *palette), (image, palette)) \ m(GetImagePaletteSize, (GpImage *image, INT *size), (image, size)) \ m(GetPropertyCount, (GpImage *image, UINT* numOfProperty), (image, numOfProperty)) \ m(GetPropertyIdList, (GpImage *image, UINT numOfProperty, PROPID* list), (image, numOfProperty, list)) \ m(GetPropertyItemSize, (GpImage *image, PROPID propId, UINT* size), (image, propId, size)) \ m(GetPropertyItem, (GpImage *image, PROPID propId,UINT propSize, PropertyItem* buffer), (image, propId, propSize, buffer)) \ m(GetPropertySize, (GpImage *image, UINT* totalBufferSize, UINT* numProperties), (image, totalBufferSize, numProperties)) \ m(GetAllPropertyItems, (GpImage *image, UINT totalBufferSize, UINT numProperties, PropertyItem* allItems), (image, totalBufferSize, numProperties, allItems)) \ m(RemovePropertyItem, (GpImage *image, PROPID propId), (image, propId)) \ m(SetPropertyItem, (GpImage *image, GDIPCONST PropertyItem* item), (image, item)) \ m(ImageForceValidation, (GpImage *image), (image)) \ m(CreateBitmapFromStream, (IStream* stream, GpBitmap **bitmap), (stream, bitmap)) \ m(CreateBitmapFromFile, (GDIPCONST WCHAR* filename, GpBitmap **bitmap), (filename, bitmap)) \ m(CreateBitmapFromStreamICM, (IStream* stream, GpBitmap **bitmap), (stream, bitmap)) \ m(CreateBitmapFromFileICM, (GDIPCONST WCHAR* filename, GpBitmap **bitmap), (filename, bitmap)) \ m(CreateBitmapFromScan0, (INT width, INT height, INT stride, PixelFormat format, BYTE* scan0, GpBitmap** bitmap), (width, height, stride, format, scan0, bitmap)) \ m(CreateBitmapFromGraphics, (INT width, INT height, GpGraphics* target, GpBitmap** bitmap), (width, height, target, bitmap)) \ m(CreateBitmapFromDirectDrawSurface, (IDirectDrawSurface7* surface, GpBitmap** bitmap), (surface, bitmap)) \ m(CreateBitmapFromGdiDib, (GDIPCONST BITMAPINFO* gdiBitmapInfo, VOID* gdiBitmapData, GpBitmap** bitmap), (gdiBitmapInfo, gdiBitmapData, bitmap)) \ m(CreateBitmapFromHBITMAP, (HBITMAP hbm, HPALETTE hpal, GpBitmap** bitmap), (hbm, hpal, bitmap)) \ m(CreateHBITMAPFromBitmap, (GpBitmap* bitmap, HBITMAP* hbmReturn, ARGB background), (bitmap, hbmReturn, background)) \ m(CreateBitmapFromHICON, (HICON hicon, GpBitmap** bitmap), (hicon, bitmap)) \ m(CreateHICONFromBitmap, (GpBitmap* bitmap, HICON* hbmReturn), (bitmap, hbmReturn)) \ m(CreateBitmapFromResource, (HINSTANCE hInstance, GDIPCONST WCHAR* lpBitmapName, GpBitmap** bitmap), (hInstance, lpBitmapName, bitmap)) \ m(CloneBitmapArea, (REAL x, REAL y, REAL width, REAL height, PixelFormat format, GpBitmap *srcBitmap, GpBitmap **dstBitmap), (x, y, width, height, format, srcBitmap, dstBitmap)) \ m(CloneBitmapAreaI, (INT x, INT y, INT width, INT height, PixelFormat format, GpBitmap *srcBitmap, GpBitmap **dstBitmap), (x, y, width, height, format, srcBitmap, dstBitmap)) \ m(BitmapLockBits, (GpBitmap* bitmap, GDIPCONST GpRect* rect, UINT flags, PixelFormat format, BitmapData* lockedBitmapData), (bitmap, rect, flags, format, lockedBitmapData)) \ m(BitmapUnlockBits, (GpBitmap* bitmap, BitmapData* lockedBitmapData), (bitmap, lockedBitmapData)) \ m(BitmapGetPixel, (GpBitmap* bitmap, INT x, INT y, ARGB *color), (bitmap, x, y, color)) \ m(BitmapSetPixel, (GpBitmap* bitmap, INT x, INT y, ARGB color), (bitmap, x, y, color)) \ m(BitmapSetResolution, (GpBitmap* bitmap, REAL xdpi, REAL ydpi), (bitmap, xdpi, ydpi)) \ m(CreateImageAttributes, (GpImageAttributes **imageattr), (imageattr)) \ m(CloneImageAttributes, (GDIPCONST GpImageAttributes *imageattr, GpImageAttributes **cloneImageattr), (imageattr, cloneImageattr)) \ m(DisposeImageAttributes, (GpImageAttributes *imageattr), (imageattr)) \ m(SetImageAttributesToIdentity, (GpImageAttributes *imageattr, ColorAdjustType type), (imageattr, type)) \ m(ResetImageAttributes, (GpImageAttributes *imageattr, ColorAdjustType type), (imageattr, type)) \ m(SetImageAttributesColorMatrix, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, GDIPCONST ColorMatrix* colorMatrix, GDIPCONST ColorMatrix* grayMatrix, ColorMatrixFlags flags), (imageattr, type, enableFlag, colorMatrix, grayMatrix, flags)) \ m(SetImageAttributesThreshold, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, REAL threshold), (imageattr, type, enableFlag, threshold)) \ m(SetImageAttributesGamma, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, REAL gamma), (imageattr, type, enableFlag, gamma)) \ m(SetImageAttributesNoOp, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag), (imageattr, type, enableFlag)) \ m(SetImageAttributesColorKeys, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, ARGB colorLow, ARGB colorHigh), (imageattr, type, enableFlag, colorLow, colorHigh)) \ m(SetImageAttributesOutputChannel, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, ColorChannelFlags channelFlags), (imageattr, type, enableFlag, channelFlags)) \ m(SetImageAttributesOutputChannelColorProfile, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, GDIPCONST WCHAR *colorProfileFilename), (imageattr, type, enableFlag, colorProfileFilename)) \ m(SetImageAttributesRemapTable, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, UINT mapSize, GDIPCONST ColorMap *map), (imageattr, type, enableFlag, mapSize, map)) \ m(SetImageAttributesWrapMode, (GpImageAttributes *imageAttr, WrapMode wrap, ARGB argb, BOOL clamp), (imageAttr, wrap, argb, clamp)) \ m(GetImageAttributesAdjustedPalette, (GpImageAttributes *imageAttr, ColorPalette *colorPalette, ColorAdjustType colorAdjustType), (imageAttr, colorPalette, colorAdjustType)) \ m(Flush, (GpGraphics *graphics, GpFlushIntention intention), (graphics, intention)) \ m(CreateFromHDC, (HDC hdc, GpGraphics **graphics), (hdc, graphics)) \ m(CreateFromHDC2, (HDC hdc, HANDLE hDevice, GpGraphics **graphics), (hdc, hDevice, graphics)) \ m(CreateFromHWND, (HWND hwnd, GpGraphics **graphics), (hwnd, graphics)) \ m(CreateFromHWNDICM, (HWND hwnd, GpGraphics **graphics), (hwnd, graphics)) \ m(DeleteGraphics, (GpGraphics *graphics), (graphics)) \ m(GetDC, (GpGraphics* graphics, HDC *hdc), (graphics, hdc)) \ m(ReleaseDC, (GpGraphics* graphics, HDC hdc), (graphics, hdc)) \ m(SetCompositingMode, (GpGraphics *graphics, CompositingMode compositingMode), (graphics, compositingMode)) \ m(GetCompositingMode, (GpGraphics *graphics, CompositingMode *compositingMode), (graphics, compositingMode)) \ m(SetRenderingOrigin, (GpGraphics *graphics, INT x, INT y), (graphics, x, y)) \ m(GetRenderingOrigin, (GpGraphics *graphics, INT *x, INT *y), (graphics, x, y)) \ m(SetCompositingQuality, (GpGraphics *graphics, CompositingQuality compositingQuality), (graphics, compositingQuality)) \ m(GetCompositingQuality, (GpGraphics *graphics, CompositingQuality *compositingQuality), (graphics, compositingQuality)) \ m(SetSmoothingMode, (GpGraphics *graphics, SmoothingMode smoothingMode), (graphics, smoothingMode)) \ m(GetSmoothingMode, (GpGraphics *graphics, SmoothingMode *smoothingMode), (graphics, smoothingMode)) \ m(SetPixelOffsetMode, (GpGraphics* graphics, PixelOffsetMode pixelOffsetMode), (graphics, pixelOffsetMode)) \ m(GetPixelOffsetMode, (GpGraphics *graphics, PixelOffsetMode *pixelOffsetMode), (graphics, pixelOffsetMode)) \ m(SetTextRenderingHint, (GpGraphics *graphics, TextRenderingHint mode), (graphics, mode)) \ m(GetTextRenderingHint, (GpGraphics *graphics, TextRenderingHint *mode), (graphics, mode)) \ m(SetTextContrast, (GpGraphics *graphics, UINT contrast), (graphics, contrast)) \ m(GetTextContrast, (GpGraphics *graphics, UINT *contrast), (graphics, contrast)) \ m(SetInterpolationMode, (GpGraphics *graphics, InterpolationMode interpolationMode), (graphics, interpolationMode)) \ m(GetInterpolationMode, (GpGraphics *graphics, InterpolationMode *interpolationMode), (graphics, interpolationMode)) \ m(SetWorldTransform, (GpGraphics *graphics, GpMatrix *matrix), (graphics, matrix)) \ m(ResetWorldTransform, (GpGraphics *graphics), (graphics)) \ m(MultiplyWorldTransform, (GpGraphics *graphics, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (graphics, matrix, order)) \ m(TranslateWorldTransform, (GpGraphics *graphics, REAL dx, REAL dy, GpMatrixOrder order), (graphics, dx, dy, order)) \ m(ScaleWorldTransform, (GpGraphics *graphics, REAL sx, REAL sy, GpMatrixOrder order), (graphics, sx, sy, order)) \ m(RotateWorldTransform, (GpGraphics *graphics, REAL angle, GpMatrixOrder order), (graphics, angle, order)) \ m(GetWorldTransform, (GpGraphics *graphics, GpMatrix *matrix), (graphics, matrix)) \ m(ResetPageTransform, (GpGraphics *graphics), (graphics)) \ m(GetPageUnit, (GpGraphics *graphics, GpUnit *unit), (graphics, unit)) \ m(GetPageScale, (GpGraphics *graphics, REAL *scale), (graphics, scale)) \ m(SetPageUnit, (GpGraphics *graphics, GpUnit unit), (graphics, unit)) \ m(SetPageScale, (GpGraphics *graphics, REAL scale), (graphics, scale)) \ m(GetDpiX, (GpGraphics *graphics, REAL* dpi), (graphics, dpi)) \ m(GetDpiY, (GpGraphics *graphics, REAL* dpi), (graphics, dpi)) \ m(TransformPoints, (GpGraphics *graphics, GpCoordinateSpace destSpace, GpCoordinateSpace srcSpace, GpPointF *points, INT count), (graphics, destSpace, srcSpace, points, count)) \ m(TransformPointsI, (GpGraphics *graphics, GpCoordinateSpace destSpace, GpCoordinateSpace srcSpace, GpPoint *points, INT count), (graphics, destSpace, srcSpace, points, count)) \ m(GetNearestColor, (GpGraphics *graphics, ARGB* argb), (graphics, argb)) \ m(DrawLine, (GpGraphics *graphics, GpPen *pen, REAL x1, REAL y1, REAL x2, REAL y2), (graphics, pen, x1, y1, x2, y2)) \ m(DrawLineI, (GpGraphics *graphics, GpPen *pen, INT x1, INT y1, INT x2, INT y2), (graphics, pen, x1, y1, x2, y2)) \ m(DrawLines, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawLinesI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawArc, (GpGraphics *graphics, GpPen *pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (graphics, pen, x, y, width, height, startAngle, sweepAngle)) \ m(DrawArcI, (GpGraphics *graphics, GpPen *pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (graphics, pen, x, y, width, height, startAngle, sweepAngle)) \ m(DrawBezier, (GpGraphics *graphics, GpPen *pen, REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4), (graphics, pen, x1, y1, x2, y2, x3, y3, x4, y4)) \ m(DrawBezierI, (GpGraphics *graphics, GpPen *pen, INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4), (graphics, pen, x1, y1, x2, y2, x3, y3, x4, y4)) \ m(DrawBeziers, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawBeziersI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawRectangle, (GpGraphics *graphics, GpPen *pen, REAL x, REAL y, REAL width, REAL height), (graphics, pen, x, y, width, height)) \ m(DrawRectangleI, (GpGraphics *graphics, GpPen *pen, INT x, INT y, INT width, INT height), (graphics, pen, x, y, width, height)) \ m(DrawRectangles, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpRectF *rects, INT count), (graphics, pen, rects, count)) \ m(DrawRectanglesI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpRect *rects, INT count), (graphics, pen, rects, count)) \ m(DrawEllipse, (GpGraphics *graphics, GpPen *pen, REAL x, REAL y, REAL width, REAL height), (graphics, pen, x, y, width, height)) \ m(DrawEllipseI, (GpGraphics *graphics, GpPen *pen, INT x, INT y, INT width, INT height), (graphics, pen, x, y, width, height)) \ m(DrawPie, (GpGraphics *graphics, GpPen *pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (graphics, pen, x, y, width, height, startAngle, sweepAngle)) \ m(DrawPieI, (GpGraphics *graphics, GpPen *pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (graphics, pen, x, y, width, height, startAngle, sweepAngle)) \ m(DrawPolygon, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawPolygonI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawPath, (GpGraphics *graphics, GpPen *pen, GpPath *path), (graphics, pen, path)) \ m(DrawCurve, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawCurveI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawCurve2, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count, REAL tension), (graphics, pen, points, count, tension)) \ m(DrawCurve2I, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count, REAL tension), (graphics, pen, points, count, tension)) \ m(DrawCurve3, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count, INT offset, INT numberOfSegments, REAL tension), (graphics, pen, points, count, offset, numberOfSegments, tension)) \ m(DrawCurve3I, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count, INT offset, INT numberOfSegments, REAL tension), (graphics, pen, points, count, offset, numberOfSegments, tension)) \ m(DrawClosedCurve, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawClosedCurveI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawClosedCurve2, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count, REAL tension), (graphics, pen, points, count, tension)) \ m(DrawClosedCurve2I, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count, REAL tension), (graphics, pen, points, count, tension)) \ m(GraphicsClear, (GpGraphics *graphics, ARGB color), (graphics, color)) \ m(FillRectangle, (GpGraphics *graphics, GpBrush *brush, REAL x, REAL y, REAL width, REAL height), (graphics, brush, x, y, width, height)) \ m(FillRectangleI, (GpGraphics *graphics, GpBrush *brush, INT x, INT y, INT width, INT height), (graphics, brush, x, y, width, height)) \ m(FillRectangles, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRectF *rects, INT count), (graphics, brush, rects, count)) \ m(FillRectanglesI, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRect *rects, INT count), (graphics, brush, rects, count)) \ m(FillPolygon, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPointF *points, INT count, GpFillMode fillMode), (graphics, brush, points, count, fillMode)) \ m(FillPolygonI, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPoint *points, INT count, GpFillMode fillMode), (graphics, brush, points, count, fillMode)) \ m(FillPolygon2, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPointF *points, INT count), (graphics, brush, points, count)) \ m(FillPolygon2I, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPoint *points, INT count), (graphics, brush, points, count)) \ m(FillEllipse, (GpGraphics *graphics, GpBrush *brush, REAL x, REAL y, REAL width, REAL height), (graphics, brush, x, y, width, height)) \ m(FillEllipseI, (GpGraphics *graphics, GpBrush *brush, INT x, INT y, INT width, INT height), (graphics, brush, x, y, width, height)) \ m(FillPie, (GpGraphics *graphics, GpBrush *brush, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (graphics, brush, x, y, width, height, startAngle, sweepAngle)) \ m(FillPieI, (GpGraphics *graphics, GpBrush *brush, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (graphics, brush, x, y, width, height, startAngle, sweepAngle)) \ m(FillPath, (GpGraphics *graphics, GpBrush *brush, GpPath *path), (graphics, brush, path)) \ m(FillClosedCurve, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPointF *points, INT count), (graphics, brush, points, count)) \ m(FillClosedCurveI, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPoint *points, INT count), (graphics, brush, points, count)) \ m(FillClosedCurve2, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPointF *points, INT count, REAL tension, GpFillMode fillMode), (graphics, brush, points, count, tension, fillMode)) \ m(FillClosedCurve2I, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPoint *points, INT count, REAL tension, GpFillMode fillMode), (graphics, brush, points, count, tension, fillMode)) \ m(FillRegion, (GpGraphics *graphics, GpBrush *brush, GpRegion *region), (graphics, brush, region)) \ m(DrawImage, (GpGraphics *graphics, GpImage *image, REAL x, REAL y), (graphics, image, x, y)) \ m(DrawImageI, (GpGraphics *graphics, GpImage *image, INT x, INT y), (graphics, image, x, y)) \ m(DrawImageRect, (GpGraphics *graphics, GpImage *image, REAL x, REAL y, REAL width, REAL height), (graphics, image, x, y, width, height)) \ m(DrawImageRectI, (GpGraphics *graphics, GpImage *image, INT x, INT y, INT width, INT height), (graphics, image, x, y, width, height)) \ m(DrawImagePoints, (GpGraphics *graphics, GpImage *image, GDIPCONST GpPointF *dstpoints, INT count), (graphics, image, dstpoints, count)) \ m(DrawImagePointsI, (GpGraphics *graphics, GpImage *image, GDIPCONST GpPoint *dstpoints, INT count), (graphics, image, dstpoints, count)) \ m(DrawImagePointRect, (GpGraphics *graphics, GpImage *image, REAL x, REAL y, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, GpUnit srcUnit), (graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit)) \ m(DrawImagePointRectI, (GpGraphics *graphics, GpImage *image, INT x, INT y, INT srcx, INT srcy, INT srcwidth, INT srcheight, GpUnit srcUnit), (graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit)) \ m(DrawImageRectRect, (GpGraphics *graphics, GpImage *image, REAL dstx, REAL dsty, REAL dstwidth, REAL dstheight, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback, VOID *callbackData), (graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData)) \ m(DrawImageRectRectI, (GpGraphics *graphics, GpImage *image, INT dstx, INT dsty, INT dstwidth, INT dstheight, INT srcx, INT srcy, INT srcwidth, INT srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback, VOID *callbackData), (graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData)) \ m(DrawImagePointsRect, (GpGraphics *graphics, GpImage *image, GDIPCONST GpPointF *points, INT count, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback, VOID *callbackData), (graphics, image, points, count, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData)) \ m(DrawImagePointsRectI, (GpGraphics *graphics, GpImage *image, GDIPCONST GpPoint *points, INT count, INT srcx, INT srcy, INT srcwidth, INT srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback, VOID *callbackData), (graphics, image, points, count, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData)) \ m(EnumerateMetafileDestPoint, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST PointF & destPoint, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoint, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestPointI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Point & destPoint, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoint, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestRect, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST RectF & destRect, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destRect, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestRectI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Rect & destRect, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destRect, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestPoints, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST PointF *destPoints, INT count, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoints, count, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestPointsI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Point *destPoints, INT count, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoints, count, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestPoint, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST PointF & destPoint, GDIPCONST RectF & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoint, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestPointI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Point & destPoint, GDIPCONST Rect & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoint, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestRect, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST RectF & destRect, GDIPCONST RectF & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destRect, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestRectI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Rect & destRect, GDIPCONST Rect & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destRect, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestPoints, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST PointF *destPoints, INT count, GDIPCONST RectF & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoints, count, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestPointsI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Point *destPoints, INT count, GDIPCONST Rect & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoints, count, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(PlayMetafileRecord, (GDIPCONST GpMetafile *metafile, EmfPlusRecordType recordType, UINT flags, UINT dataSize, GDIPCONST BYTE *data), (metafile, recordType, flags, dataSize, data)) \ m(SetClipGraphics, (GpGraphics *graphics, GpGraphics *srcgraphics, CombineMode combineMode), (graphics, srcgraphics, combineMode)) \ m(SetClipRect, (GpGraphics *graphics, REAL x, REAL y, REAL width, REAL height, CombineMode combineMode), (graphics, x, y, width, height, combineMode)) \ m(SetClipRectI, (GpGraphics *graphics, INT x, INT y, INT width, INT height, CombineMode combineMode), (graphics, x, y, width, height, combineMode)) \ m(SetClipPath, (GpGraphics *graphics, GpPath *path, CombineMode combineMode), (graphics, path, combineMode)) \ m(SetClipRegion, (GpGraphics *graphics, GpRegion *region, CombineMode combineMode), (graphics, region, combineMode)) \ m(SetClipHrgn, (GpGraphics *graphics, HRGN hRgn, CombineMode combineMode), (graphics, hRgn, combineMode)) \ m(ResetClip, (GpGraphics *graphics), (graphics)) \ m(TranslateClip, (GpGraphics *graphics, REAL dx, REAL dy), (graphics, dx, dy)) \ m(TranslateClipI, (GpGraphics *graphics, INT dx, INT dy), (graphics, dx, dy)) \ m(GetClip, (GpGraphics *graphics, GpRegion *region), (graphics, region)) \ m(GetClipBounds, (GpGraphics *graphics, GpRectF *rect), (graphics, rect)) \ m(GetClipBoundsI, (GpGraphics *graphics, GpRect *rect), (graphics, rect)) \ m(IsClipEmpty, (GpGraphics *graphics, BOOL *result), (graphics, result)) \ m(GetVisibleClipBounds, (GpGraphics *graphics, GpRectF *rect), (graphics, rect)) \ m(GetVisibleClipBoundsI, (GpGraphics *graphics, GpRect *rect), (graphics, rect)) \ m(IsVisibleClipEmpty, (GpGraphics *graphics, BOOL *result), (graphics, result)) \ m(IsVisiblePoint, (GpGraphics *graphics, REAL x, REAL y, BOOL *result), (graphics, x, y, result)) \ m(IsVisiblePointI, (GpGraphics *graphics, INT x, INT y, BOOL *result), (graphics, x, y, result)) \ m(IsVisibleRect, (GpGraphics *graphics, REAL x, REAL y, REAL width, REAL height, BOOL *result), (graphics, x, y, width, height, result)) \ m(IsVisibleRectI, (GpGraphics *graphics, INT x, INT y, INT width, INT height, BOOL *result), (graphics, x, y, width, height, result)) \ m(SaveGraphics, (GpGraphics *graphics, GraphicsState *state), (graphics, state)) \ m(RestoreGraphics, (GpGraphics *graphics, GraphicsState state), (graphics, state)) \ m(BeginContainer, (GpGraphics *graphics, GDIPCONST GpRectF* dstrect, GDIPCONST GpRectF *srcrect, GpUnit unit, GraphicsContainer *state), (graphics, dstrect, srcrect, unit, state)) \ m(BeginContainerI, (GpGraphics *graphics, GDIPCONST GpRect* dstrect, GDIPCONST GpRect *srcrect, GpUnit unit, GraphicsContainer *state), (graphics, dstrect, srcrect, unit, state)) \ m(BeginContainer2, (GpGraphics *graphics, GraphicsContainer* state), (graphics, state)) \ m(EndContainer, (GpGraphics *graphics, GraphicsContainer state), (graphics, state)) \ m(GetMetafileHeaderFromEmf, (HENHMETAFILE hEmf, MetafileHeader *header), (hEmf, header)) \ m(GetMetafileHeaderFromFile, (GDIPCONST WCHAR* filename, MetafileHeader *header), (filename, header)) \ m(GetMetafileHeaderFromStream, (IStream *stream, MetafileHeader *header), (stream, header)) \ m(GetMetafileHeaderFromMetafile, (GpMetafile *metafile, MetafileHeader *header), (metafile, header)) \ m(GetHemfFromMetafile, (GpMetafile *metafile, HENHMETAFILE *hEmf), (metafile, hEmf)) \ m(CreateStreamOnFile, (GDIPCONST WCHAR *filename, UINT access, IStream **stream), (filename, access, stream)) \ m(CreateMetafileFromWmf, (HMETAFILE hWmf, BOOL deleteWmf, GDIPCONST WmfPlaceableFileHeader *wmfPlaceableFileHeader, GpMetafile **metafile), (hWmf, deleteWmf, wmfPlaceableFileHeader, metafile)) \ m(CreateMetafileFromEmf, (HENHMETAFILE hEmf, BOOL deleteEmf, GpMetafile **metafile), (hEmf, deleteEmf, metafile)) \ m(CreateMetafileFromFile, (GDIPCONST WCHAR* file, GpMetafile **metafile), (file, metafile)) \ m(CreateMetafileFromWmfFile, (GDIPCONST WCHAR* file, GDIPCONST WmfPlaceableFileHeader *wmfPlaceableFileHeader, GpMetafile **metafile), (file, wmfPlaceableFileHeader, metafile)) \ m(CreateMetafileFromStream, (IStream *stream, GpMetafile **metafile), (stream, metafile)) \ m(RecordMetafile, (HDC referenceHdc, EmfType type, GDIPCONST GpRectF *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileI, (HDC referenceHdc, EmfType type, GDIPCONST GpRect *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileFileName, (GDIPCONST WCHAR* fileName, HDC referenceHdc, EmfType type, GDIPCONST GpRectF *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (fileName, referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileFileNameI, (GDIPCONST WCHAR* fileName, HDC referenceHdc, EmfType type, GDIPCONST GpRect *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (fileName, referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileStream, (IStream *stream, HDC referenceHdc, EmfType type, GDIPCONST GpRectF *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (stream, referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileStreamI, (IStream *stream, HDC referenceHdc, EmfType type, GDIPCONST GpRect *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (stream, referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(SetMetafileDownLevelRasterizationLimit, (GpMetafile *metafile, UINT metafileRasterizationLimitDpi), (metafile, metafileRasterizationLimitDpi)) \ m(GetMetafileDownLevelRasterizationLimit, (GDIPCONST GpMetafile *metafile, UINT *metafileRasterizationLimitDpi), (metafile, metafileRasterizationLimitDpi)) \ m(GetImageDecodersSize, (UINT *numDecoders, UINT *size), (numDecoders, size)) \ m(GetImageDecoders, (UINT numDecoders, UINT size, ImageCodecInfo *decoders), (numDecoders, size, decoders)) \ m(GetImageEncodersSize, (UINT *numEncoders, UINT *size), (numEncoders, size)) \ m(GetImageEncoders, (UINT numEncoders, UINT size, ImageCodecInfo *encoders), (numEncoders, size, encoders)) \ m(Comment, (GpGraphics* graphics, UINT sizeData, GDIPCONST BYTE *data), (graphics, sizeData, data)) \ m(CreateFontFamilyFromName, (GDIPCONST WCHAR *name, GpFontCollection *fontCollection, GpFontFamily **FontFamily), (name, fontCollection, FontFamily)) \ m(DeleteFontFamily, (GpFontFamily *FontFamily), (FontFamily)) \ m(CloneFontFamily, (GpFontFamily *FontFamily, GpFontFamily **clonedFontFamily), (FontFamily, clonedFontFamily)) \ m(GetGenericFontFamilySansSerif, (GpFontFamily **nativeFamily), (nativeFamily)) \ m(GetGenericFontFamilySerif, (GpFontFamily **nativeFamily), (nativeFamily)) \ m(GetGenericFontFamilyMonospace, (GpFontFamily **nativeFamily), (nativeFamily)) \ m(GetFamilyName, (GDIPCONST GpFontFamily *family, WCHAR name[LF_FACESIZE], LANGID language), (family, name, language)) \ m(IsStyleAvailable, (GDIPCONST GpFontFamily *family, INT style, BOOL *IsStyleAvailable), (family, style, IsStyleAvailable)) \ m(GetEmHeight, (GDIPCONST GpFontFamily *family, INT style, UINT16 *EmHeight), (family, style, EmHeight)) \ m(GetCellAscent, (GDIPCONST GpFontFamily *family, INT style, UINT16 *CellAscent), (family, style, CellAscent)) \ m(GetCellDescent, (GDIPCONST GpFontFamily *family, INT style, UINT16 *CellDescent), (family, style, CellDescent)) \ m(GetLineSpacing, (GDIPCONST GpFontFamily *family, INT style, UINT16 *LineSpacing), (family, style, LineSpacing)) \ m(CreateFontFromDC, (HDC hdc, GpFont **font), (hdc, font)) \ m(CreateFontFromLogfontA, (HDC hdc, GDIPCONST LOGFONTA *logfont, GpFont **font), (hdc, logfont, font)) \ m(CreateFontFromLogfontW, (HDC hdc, GDIPCONST LOGFONTW *logfont, GpFont **font), (hdc, logfont, font)) \ m(CreateFont, (GDIPCONST GpFontFamily *fontFamily, REAL emSize, INT style, Unit unit, GpFont **font), (fontFamily, emSize, style, unit, font)) \ m(CloneFont, (GpFont* font, GpFont** cloneFont), (font, cloneFont)) \ m(DeleteFont, (GpFont* font), (font)) \ m(GetFamily, (GpFont *font, GpFontFamily **family), (font, family)) \ m(GetFontStyle, (GpFont *font, INT *style), (font, style)) \ m(GetFontSize, (GpFont *font, REAL *size), (font, size)) \ m(GetFontUnit, (GpFont *font, Unit *unit), (font, unit)) \ m(GetFontHeight, (GDIPCONST GpFont *font, GDIPCONST GpGraphics *graphics, REAL *height), (font, graphics, height)) \ m(GetFontHeightGivenDPI, (GDIPCONST GpFont *font, REAL dpi, REAL *height), (font, dpi, height)) \ m(GetLogFontA, (GpFont *font, GpGraphics *graphics, LOGFONTA *logfontA), (font, graphics, logfontA)) \ m(GetLogFontW, (GpFont *font, GpGraphics *graphics, LOGFONTW *logfontW), (font, graphics, logfontW)) \ m(NewInstalledFontCollection, (GpFontCollection** fontCollection), (fontCollection)) \ m(NewPrivateFontCollection, (GpFontCollection** fontCollection), (fontCollection)) \ m(DeletePrivateFontCollection, (GpFontCollection** fontCollection), (fontCollection)) \ m(GetFontCollectionFamilyCount, (GpFontCollection* fontCollection, INT *numFound), (fontCollection, numFound)) \ m(GetFontCollectionFamilyList, (GpFontCollection* fontCollection, INT numSought, GpFontFamily* gpfamilies[], INT* numFound), (fontCollection, numSought, gpfamilies, numFound)) \ m(PrivateAddFontFile, (GpFontCollection* fontCollection, GDIPCONST WCHAR* filename), (fontCollection, filename)) \ m(PrivateAddMemoryFont, (GpFontCollection* fontCollection, GDIPCONST void* memory, INT length), (fontCollection, memory, length)) \ m(DrawString, (GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *stringFormat, GDIPCONST GpBrush *brush), (graphics, string, length, font, layoutRect, stringFormat, brush)) \ m(MeasureString, (GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *stringFormat, RectF *boundingBox, INT *codepointsFitted, INT *linesFilled), (graphics, string, length, font, layoutRect, stringFormat, boundingBox, codepointsFitted, linesFilled)) \ m(MeasureCharacterRanges, (GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF &layoutRect, GDIPCONST GpStringFormat *stringFormat, INT regionCount, GpRegion **regions), (graphics, string, length, font, layoutRect, stringFormat, regionCount, regions)) \ m(DrawDriverString, (GpGraphics *graphics, GDIPCONST UINT16 *text, INT length, GDIPCONST GpFont *font, GDIPCONST GpBrush *brush, GDIPCONST PointF *positions, INT flags, GDIPCONST GpMatrix *matrix), (graphics, text, length, font, brush, positions, flags, matrix)) \ m(MeasureDriverString, (GpGraphics *graphics, GDIPCONST UINT16 *text, INT length, GDIPCONST GpFont *font, GDIPCONST PointF *positions, INT flags, GDIPCONST GpMatrix *matrix, RectF *boundingBox), (graphics, text, length, font, positions, flags, matrix, boundingBox)) \ m(CreateStringFormat, (INT formatAttributes, LANGID language, GpStringFormat **format), (formatAttributes, language, format)) \ m(StringFormatGetGenericDefault, (GpStringFormat **format), (format)) \ m(StringFormatGetGenericTypographic, (GpStringFormat **format), (format)) \ m(DeleteStringFormat, (GpStringFormat *format), (format)) \ m(CloneStringFormat, (GDIPCONST GpStringFormat *format, GpStringFormat **newFormat), (format, newFormat)) \ m(SetStringFormatFlags, (GpStringFormat *format, INT flags), (format, flags)) \ m(GetStringFormatFlags, (GDIPCONST GpStringFormat *format, INT *flags), (format, flags)) \ m(SetStringFormatAlign, (GpStringFormat *format, StringAlignment align), (format, align)) \ m(GetStringFormatAlign, (GDIPCONST GpStringFormat *format, StringAlignment *align), (format, align)) \ m(SetStringFormatLineAlign, (GpStringFormat *format, StringAlignment align), (format, align)) \ m(GetStringFormatLineAlign, (GDIPCONST GpStringFormat *format, StringAlignment *align), (format, align)) \ m(SetStringFormatTrimming, (GpStringFormat *format, StringTrimming trimming), (format, trimming)) \ m(GetStringFormatTrimming, (GDIPCONST GpStringFormat *format, StringTrimming *trimming), (format, trimming)) \ m(SetStringFormatHotkeyPrefix, (GpStringFormat *format, INT hotkeyPrefix), (format, hotkeyPrefix)) \ m(GetStringFormatHotkeyPrefix, (GDIPCONST GpStringFormat *format, INT *hotkeyPrefix), (format, hotkeyPrefix)) \ m(SetStringFormatTabStops, (GpStringFormat *format, REAL firstTabOffset, INT count, GDIPCONST REAL *tabStops), (format, firstTabOffset, count, tabStops)) \ m(GetStringFormatTabStops, (GDIPCONST GpStringFormat *format, INT count, REAL *firstTabOffset, REAL *tabStops), (format, count, firstTabOffset, tabStops)) \ m(GetStringFormatTabStopCount, (GDIPCONST GpStringFormat *format, INT *count), (format, count)) \ m(SetStringFormatDigitSubstitution, (GpStringFormat *format, LANGID language, StringDigitSubstitute substitute), (format, language, substitute)) \ m(GetStringFormatDigitSubstitution, (GDIPCONST GpStringFormat *format, LANGID *language, StringDigitSubstitute *substitute), (format, language, substitute)) \ m(GetStringFormatMeasurableCharacterRangeCount, (GDIPCONST GpStringFormat *format, INT *count), (format, count)) \ m(SetStringFormatMeasurableCharacterRanges, (GpStringFormat *format, INT rangeCount, GDIPCONST CharacterRange *ranges), (format, rangeCount, ranges)) \ m(CreateCachedBitmap, (GpBitmap *bitmap, GpGraphics *graphics, GpCachedBitmap **cachedBitmap), (bitmap, graphics, cachedBitmap)) \ m(DeleteCachedBitmap, (GpCachedBitmap *cachedBitmap), (cachedBitmap)) \ m(DrawCachedBitmap, (GpGraphics *graphics, GpCachedBitmap *cachedBitmap, INT x, INT y), (graphics, cachedBitmap, x, y)) \ m(SetImageAttributesCachedBackground, (GpImageAttributes *imageattr, BOOL enableFlag), (imageattr, enableFlag)) \ m(TestControl, (GpTestControlEnum control, void *param), (control, param)) \ // non-standard/problematic functions, to review later if needed #if 0 // these functions don't seem to exist in the DLL even though they are // declared in the header m(SetImageAttributesICMMode, (GpImageAttributes *imageAttr, BOOL on), (imageAttr, on)) \ m(FontCollectionEnumerable, (GpFontCollection* fontCollection, GpGraphics* graphics, INT *numFound), (fontCollection, graphics, numFound)) \ m(FontCollectionEnumerate, (GpFontCollection* fontCollection, INT numSought, GpFontFamily* gpfamilies[], INT* numFound, GpGraphics* graphics), (fontCollection, numSought, gpfamilies, numFound, graphics)) \ GpStatus GdipGetMetafileHeaderFromWmf( HMETAFILE hWmf, GDIPCONST WmfPlaceableFileHeader * wmfPlaceableFileHeader, MetafileHeader * header ); HPALETTE WINGDIPAPI GdipCreateHalftonePalette(); UINT WINGDIPAPI GdipEmfToWmfBits( HENHMETAFILE hemf, UINT cbData16, LPBYTE pData16, INT iMapMode, INT eFlags ); #endif // 0 // this macro expands into an invocation of the given macro m for all GDI+ // functions: m is called with the name of the function without "Gdip" prefix #define wxFOR_ALL_GDIP_FUNCNAMES(m) \ m(Alloc, (size_t size), (size)) \ m(Free, (void *ptr), (ptr)) \ wxFOR_ALL_GDIPLUS_STATUS_FUNCS(m) // unfortunately we need a separate macro for these functions as they have // "Gdiplus" prefix instead of "Gdip" for (almost) all the others (and also // WINAPI calling convention instead of WINGDIPAPI although they happen to be // both stdcall in fact) #define wxFOR_ALL_GDIPLUS_FUNCNAMES(m) \ m(Startup, (ULONG_PTR *token, \ const GdiplusStartupInput *input, \ GdiplusStartupOutput *output), \ (token, input, output)) \ m(Shutdown, (ULONG_PTR token), (token)) \ m(NotificationHook, (ULONG_PTR *token), (token)) \ m(NotificationUnhook, (ULONG_PTR token), (token)) \ #define wxFOR_ALL_FUNCNAMES(m) \ wxFOR_ALL_GDIP_FUNCNAMES(m) \ wxFOR_ALL_GDIPLUS_FUNCNAMES(m) // ---------------------------------------------------------------------------- // declare typedefs for types of all GDI+ functions // ---------------------------------------------------------------------------- extern "C" { typedef void* (WINGDIPAPI *wxGDIPLUS_FUNC_T(Alloc))(size_t size); typedef void (WINGDIPAPI *wxGDIPLUS_FUNC_T(Free))(void* ptr); typedef Status (WINAPI *wxGDIPLUS_FUNC_T(Startup))(ULONG_PTR *token, const GdiplusStartupInput *input, GdiplusStartupOutput *output); typedef void (WINAPI *wxGDIPLUS_FUNC_T(Shutdown))(ULONG_PTR token); typedef GpStatus (WINAPI *wxGDIPLUS_FUNC_T(NotificationHook))(ULONG_PTR *token); typedef void (WINAPI *wxGDIPLUS_FUNC_T(NotificationUnhook))(ULONG_PTR token); #define wxDECL_GDIPLUS_FUNC_TYPE(name, params, args) \ typedef GpStatus (WINGDIPAPI *wxGDIPLUS_FUNC_T(name)) params ; wxFOR_ALL_GDIPLUS_STATUS_FUNCS(wxDECL_GDIPLUS_FUNC_TYPE) #undef wxDECL_GDIPLUS_FUNC_TYPE // Special hack for w32api headers that reference this variable which is // normally defined in w32api-specific gdiplus.lib but as we don't link with it // and load gdiplus.dll dynamically, it's not defined in our case resulting in // linking errors -- so just provide it ourselves, it doesn't matter where it // is and if Cygwin headers are modified to not use it in the future, it's not // a big deal neither, we'll just have an unused pointer. #if defined(__CYGWIN__) || defined(__MINGW32__) void *_GdipStringFormatCachedGenericTypographic = NULL; #endif // __CYGWIN__ || __MINGW32__ } // extern "C" // ============================================================================ // wxGdiPlus helper class // ============================================================================ class wxGdiPlus { public: // load GDI+ DLL when we're called for the first time, return true on // success or false on failure static bool Initialize() { if ( m_initialized == -1 ) m_initialized = DoInit(); return m_initialized == 1; } // check if we're initialized without loading the GDI+ DLL static bool IsInitialized() { return m_initialized == 1; } // shutdown: should be called on termination to unload the GDI+ DLL, safe // to call even if we hadn't loaded it static void Terminate() { if ( m_hdll ) { wxDynamicLibrary::Unload(m_hdll); m_hdll = 0; } m_initialized = -1; } // define function pointers as members #define wxDECL_GDIPLUS_FUNC_MEMBER(name, params, args) \ static wxGDIPLUS_FUNC_T(name) name; wxFOR_ALL_FUNCNAMES(wxDECL_GDIPLUS_FUNC_MEMBER) #undef wxDECL_GDIPLUS_FUNC_MEMBER private: // do load the GDI+ DLL and bind all the functions static bool DoInit(); // initially -1 meaning unknown, set to false or true by Initialize() static int m_initialized; // handle of the GDI+ DLL if we loaded it successfully static wxDllType m_hdll; }; #define wxINIT_GDIPLUS_FUNC(name, params, args) \ wxGDIPLUS_FUNC_T(name) wxGdiPlus::name = NULL; wxFOR_ALL_FUNCNAMES(wxINIT_GDIPLUS_FUNC) #undef wxINIT_GDIPLUS_FUNC int wxGdiPlus::m_initialized = -1; wxDllType wxGdiPlus::m_hdll = 0; /* static */ bool wxGdiPlus::DoInit() { // we're prepared to handler errors so suppress log messages about them wxLogNull noLog; wxDynamicLibrary dllGdip(wxT("gdiplus.dll"), wxDL_VERBATIM); if ( !dllGdip.IsLoaded() ) return false; // use RawGetSymbol() for efficiency, we have ~600 functions to load... #define wxDO_LOAD_FUNC(name, namedll) \ name = (wxGDIPLUS_FUNC_T(name))dllGdip.RawGetSymbol(namedll); \ if ( !name ) \ return false; #define wxLOAD_GDIPLUS_FUNC(name, params, args) \ wxDO_LOAD_FUNC(name, wxT("Gdiplus") wxSTRINGIZE_T(name)) wxFOR_ALL_GDIPLUS_FUNCNAMES(wxLOAD_GDIPLUS_FUNC) #undef wxLOAD_GDIPLUS_FUNC #define wxLOAD_GDIP_FUNC(name, params, args) \ wxDO_LOAD_FUNC(name, wxT("Gdip") wxSTRINGIZE_T(name)) wxFOR_ALL_GDIP_FUNCNAMES(wxLOAD_GDIP_FUNC) #undef wxLOAD_GDIP_FUNC // ok, prevent the DLL from being unloaded right now, we'll do it later m_hdll = dllGdip.Detach(); return true; } // ============================================================================ // module to unload GDI+ DLL on program termination // ============================================================================ class wxGdiPlusModule : public wxModule { public: virtual bool OnInit() wxOVERRIDE { return true; } virtual void OnExit() wxOVERRIDE { wxGdiPlus::Terminate(); } wxDECLARE_DYNAMIC_CLASS(wxGdiPlusModule); }; wxIMPLEMENT_DYNAMIC_CLASS(wxGdiPlusModule, wxModule); // ============================================================================ // implementation of the functions themselves // ============================================================================ extern "C" { void* WINGDIPAPI GdipAlloc(size_t size) { return wxGdiPlus::Initialize() ? wxGdiPlus::Alloc(size) : NULL; } void WINGDIPAPI GdipFree(void* ptr) { if ( wxGdiPlus::Initialize() ) wxGdiPlus::Free(ptr); } Status WINAPI GdiplusStartup(ULONG_PTR *token, const GdiplusStartupInput *input, GdiplusStartupOutput *output) { return wxGdiPlus::Initialize() ? wxGdiPlus::Startup(token, input, output) : GdiplusNotInitialized; } void WINAPI GdiplusShutdown(ULONG_PTR token) { if ( wxGdiPlus::IsInitialized() ) wxGdiPlus::Shutdown(token); } #define wxIMPL_GDIPLUS_FUNC(name, params, args) \ GpStatus WINGDIPAPI \ Gdip##name params \ { \ return wxGdiPlus::Initialize() ? wxGdiPlus::name args \ : GdiplusNotInitialized; \ } wxFOR_ALL_GDIPLUS_STATUS_FUNCS(wxIMPL_GDIPLUS_FUNC) #undef wxIMPL_GDIPLUS_FUNC } // extern "C" #endif // wxUSE_GRAPHICS_CONTEXT
CarlosManuelRodr/wxChaos
libs/wxMSW-3.1.4/src/msw/gdiplus.cpp
C++
gpl-3.0
84,448
/** * Swift-Cardinal Object Notation * https://github.com/norstone-tech/scon * * Copyright (c) BlueStone Technological Enterprises Inc., 2016-2019 * Copyright (c) Norstone Technologies 2021 * Licensed under the GNU GPLv3 license. */ /* eslint-disable no-magic-numbers, no-mixed-operators, sort-keys */ "use strict"; const MAGIC_NUMBER = Buffer.from([7, 83, 67, 51]); const BASE_TYPES = { EOF: 0, NULL: 1 << 5, BOOLEAN: 2 << 5, FLOAT_FIXED: 3 << 5, INT_VAR: 4 << 5, STRING_ZERO_TERM: 5 << 5, STRING_LENGTH_PREFIXED: 6 << 5, OBJECT: 7 << 5 }; const HEADER_BYTE = { BASE_TYPES: 0b11100000, BASE_TYPE_VARIANT: 0b00010000, HAS_EXTENDED_TYPE: 0b00001000, IS_REFERENCE_DEFINITION: 0b00000100, KEY_IS_REFERENCE: 0b00000010, KEY_IS_REFERENCE_SLOT: 0b00000010, // only relevent when IS_REFERENCE_DEFINITION // Both of the above means parse the key as a varint instead of a null-terminated string VALUE_IS_REFERENCE: 0b00000001 }; const EXTENDED_TYPES = { INT_VAR: { FLOAT_64_SAFE_INT: 0, UINT8: 2, SINT8: 3, UINT16: 4, SINT16: 5, UINT32: 6, SINT32: 7, UINT64: 8, SINT64: 9, UINT128: 10, SINT128: 11, UINT256: 12, SINT256: 13, INF_INT: 16, // Default DATE_S: 32, DATE_MS: 33 }, OBJECT: { // Parsing variant 0 OBJECT: 0, STRING_KEY_MAP_ALT: 1, STRING_KEY_MAP: 2, // Parsing variant 1 ARRAY: 0, SET: 1, ANY_KEY_MAP: 2 } }; const VARINT_RAGES = { FLOAT_64_SAFE_INT: { MIN_VALUE: BigInt(Number.MIN_SAFE_INTEGER), MAX_VALUE: BigInt(Number.MAX_SAFE_INTEGER) }, UINT8: { MIN_VALUE: 0n, MAX_VALUE: 2n ** 8n - 1n }, SINT8: { MIN_VALUE: (-2n) ** 7n, MAX_VALUE: 2n ** 7n - 1n }, UINT16: { MIN_VALUE: 0n, MAX_VALUE: 2n ** 16n - 1n }, SINT16: { MIN_VALUE: (-2n) ** 15n, MAX_VALUE: 2n ** 15n - 1n }, UINT32: { MIN_VALUE: 0n, MAX_VALUE: 2n ** 32n - 1n }, SINT32: { MIN_VALUE: (-2n) ** 31n, MAX_VALUE: 2n ** 31n - 1n }, UINT64: { MIN_VALUE: 0n, MAX_VALUE: 2n ** 64n - 1n }, SINT64: { MIN_VALUE: (-2n) ** 63n, MAX_VALUE: 2n ** 63n - 1n }, UINT128: { MIN_VALUE: 0n, MAX_VALUE: 2n ** 128n - 1n }, SINT128: { MIN_VALUE: (-2n) ** 127n, MAX_VALUE: 2n ** 127n - 1n }, UINT256: { MIN_VALUE: 0n, MAX_VALUE: 2n ** 256n - 1n }, SINT256: { MIN_VALUE: (-2n) ** 255n, MAX_VALUE: 2n ** 255n - 1n } }; module.exports = { MAGIC_NUMBER, BASE_TYPES, HEADER_BYTE, EXTENDED_TYPES, EXTENDED_TYPE_USER: 0b10000000, VARINT_EXTEND: 0b10000000, VARINT_VALUE: 0b01111111, VARINT_RAGES };
BlueStone-Tech-Enterprises/scon
lib/conf.js
JavaScript
gpl-3.0
2,496
/* Report an error and exit. Copyright 2016-2019 Free Software Foundation, Inc. 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, 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. */ #ifndef DIE_H # define DIE_H # include <error.h> # include <stdbool.h> # include <verify.h> /* Like 'error (STATUS, ...)', except STATUS must be a nonzero constant. This may pacify the compiler or help it generate better code. */ # define die(status, ...) \ verify_expr (status, (error (status, __VA_ARGS__), assume (false))) #endif /* DIE_H */
komh/coreutils-os2
src/die.h
C
gpl-3.0
1,146
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) 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/ **********************************************************************/ /** * <p> * @author Written by Alejandro Tortosa (University of Granada) 15/10/2008 * @author Modified by Xavi Solé (La Salle, Ramón Llull University - Barcelona) 03/12/2008 * @version 1.4 * @since JDK1.2 * </p> */ package keel.Algorithms.Rule_Learning.Ripper; import keel.Dataset.*; import java.io.IOException; import org.core.*; public class Ripper { /** * Implementation of the classification algorithm Ripper, according to the paper [Cohen95] * and the Weka's implementation. */ public static int W=1; //'Worth' metric public static int A=2; //'Accuracy'metric MyDataset train, val, test; //the datasets for training, validation and test String outputTr, outputTst, outputRules; //the names for the output files Randomize rand; //random numbers generator double pct; //ratio of growing/pruning instances int K; //number of optimization private boolean somethingWrong = false; //to check if everything is correct. /** * It reads the data from the input files (training, validation and test) and parse all the parameters * from the parameters array. * @param parameters parseParameters It contains the input files, output files and parameters */ public Ripper(parseParameters parameters) { train = new MyDataset(); val = new MyDataset(); test = new MyDataset(); try { System.out.println("\nReading the training set: " + parameters.getTrainingInputFile()); train.readClassificationSet(parameters.getTrainingInputFile(), true); System.out.println("\nReading the validation set: " + parameters.getValidationInputFile()); val.readClassificationSet(parameters.getValidationInputFile(), false); System.out.println("\nReading the test set: " + parameters.getTestInputFile()); test.readClassificationSet(parameters.getTestInputFile(), false); } catch (IOException e) { System.err.println("There was a problem while reading the input data-sets: " + e); somethingWrong = true; } //We may check if there are some numerical attributes, because our algorithm may not handle them: //somethingWrong = somethingWrong || train.hasNumericalAttributes(); //somethingWrong = somethingWrong || train.hasMissingAttributes(); outputTr = parameters.getTrainingOutputFile(); outputTst = parameters.getTestOutputFile(); if ( parameters.getNOutputFiles()==0){ System.err.println("No se ha especificado archivo para las reglas."); System.err.println("Usando nombre por defecto: rules-out.txt"); outputRules="rules-out.txt"; } else outputRules = parameters.getOutputFile(0); long seed = Long.parseLong(parameters.getParameter(0)); pct = Double.parseDouble(parameters.getParameter(1)); K = Integer.parseInt(parameters.getParameter(2)); rand=new Randomize(); rand.setSeed(seed); } /** * It launches the algorithm. */ public void execute() { if (somethingWrong) { //We do not execute the program System.err.println("An error was found, the data-set have numerical values."); System.err.println("Aborting the program"); //We should not use the statement: System.exit(-1); } else { //We do here the algorithm's operations Ruleset[] rulesets=this.ripperMulticlass(train); //Classificates the datasets' entries, according the generated rulesets String[] classification_train=train.classify(rulesets,rulesets.length); String[] classification_val=val.classify(rulesets,rulesets.length); String[] classification_test=test.classify(rulesets,rulesets.length); //Finally we should fill the training and test output files doOutput(this.val, this.outputTr, classification_val); doOutput(this.test, this.outputTst, classification_test); doRulesOutput2(this.outputRules,rulesets); System.out.println("Algorithm Finished"); } } /** * It generates the output file from a given dataset and stores it in a file. * @param dataset myDataset input dataset * @param filename String the name of the file * @param classification String[] gererated classification of the dataset */ private void doOutput(MyDataset dataset, String filename,String[] classification) { String output = new String(""); output = dataset.copyHeader(); //we insert the header in the output file //We write the output for each example for (int i = 0; i < dataset.getnData(); i++) { output += dataset.getOutputAsString(i) + " " +classification[i] + "\n"; } Fichero.escribeFichero(filename, output); } /** * It generates the output rules file from a given ruleset and stores it in a file * @param filename String the name of the file * @param rulesets Rulesets[] the rulesets (one for each class) */ private void doRulesOutput(String filename,Ruleset[] rulesets) { String output = new String(""); for (int i=0;i<rulesets.length-1;i++){ output+="if("; for(int j=0;j<rulesets[i].size();j++){ Rule current=rulesets[i].getRule(j); output+="("; for (int k=0;k<current.size();k++){ output+=current.getSimpleRule(k); if (k!=current.size()-1) output+=" && "; } output+=")"; if (j!=rulesets[i].size()-1) output+=" || "; } output+=")\n\t"; output+="output="+rulesets[i].getType()+"\nelse "; } output+="\n\toutput="+rulesets[rulesets.length-1].getType(); Fichero.escribeFichero(filename, output); } /** * It generates the output rules file from a given ruleset and stores it in a file * @param filename String the name of the file * @param rulesets Rulesets[] the rulesets (one for each class) */ private void doRulesOutput2(String filename,Ruleset[] rulesets) { String output = new String(""); int rules = 0; for (int i = 0; i < rulesets.length;i++){ rules += rulesets[i].size(); } output += "@Number of Rules: "+rules+"\n"; for (int i=0;i<rulesets.length-1;i++){ Mask class_filter=new Mask(train.size()); train.filterByClass(class_filter,rulesets[i].getType()); for(int j=0;j<rulesets[i].size();j++){ output+="if("; Rule current=rulesets[i].getRule(j); for (int k=0;k<current.size();k++){ output+=current.getSimpleRule(k); if (k!=current.size()-1) output+=" && "; } int covered=current.apply(train); int accuracy=current.apply(train,class_filter); output+=") ("+accuracy+"/"+covered+")\n\t"; output+="output="+rulesets[i].getType()+"\nelse "; } } output+="\n\toutput="+rulesets[rulesets.length-1].getType(); Fichero.escribeFichero(filename, output); } /** * It grows a rule maximizing the following heuristic: * h= p*(log(p/t)-log(P/T)) * p/t: number of positive/total instances covered by the current rule * P/T: number of positive/total instances * @param data MyDataset the dataset * @param positives Mask active positive entries * @param negatives Mask active negative entries * @return the grown rule */ public Rule grow(MyDataset data,Mask positives,Mask negatives){ return grow(new Rule(),data,positives,negatives); } /** * It expands a rule, greedily adding simple rules, maximizing the following heuristic: * h= p*(log(p/t)-log(P/T)) * p/t: number of positive/total instances covered by the current rule * P/T: number of positive/total instances * @param rule Rule the base rule * @param data MyDataset the dataset * @param grow_pos Mask active positive entries * @param grow_neg Mask active negative entries * @return the grown rule */ public Rule grow(Rule rule,MyDataset data,Mask grow_pos,Mask grow_neg){ double best_v=0,best_h=-Double.MAX_VALUE; if (grow_pos.getnActive()<0) return new Rule(); Mask positives = grow_pos.copy(); Mask negatives = grow_neg.copy(); int[] attributes=new int[data.getnInputs()]; int nattributes=attributes.length; for (int i=0;i<attributes.length;i++){ attributes[i]=i; } if (rule.size()>0){ //Elimination of the attributes already used by the rule int[] aux = new int[data.getnInputs()]; for (int i = 0; i < rule.size(); i++) { attributes[rule.getSimpleRule(i).getAttribute()] = -1; } int j = 0; for (int i = 0; i < nattributes; i++) { if (attributes[i] != -1) { aux[j] = attributes[i]; j++; } } attributes = aux; nattributes = j; data.filter(positives,rule); data.filter(negatives,rule); } while (negatives.getnActive()>0 && nattributes>0 && positives.getnActive()>0){ int A=-1,P=-1; //A->best attribute, P-> relative position inside Attributes double V=0,best_global=-Double.MAX_VALUE; int Op=-1; double C=Utilities.log2(positives.getnActive()/((double) (positives.getnActive()+negatives.getnActive()))); for (int i=0;i<nattributes;i++){ int ai=attributes[i]; Score score=new Score(); positives.resetIndex(); while (positives.next()){ if (!data.isMissing(positives,ai)){ double[] exemple=data.getExample(positives); int pos = score.findKey(exemple[ai]); if (pos!=-1) score.addPositive(pos); else score.addKey(exemple[ai],Score.POSITIVE); } } negatives.resetIndex(); while (negatives.next()){ if (!data.isMissing(negatives,ai)){ double[] exemple=data.getExample(negatives); int pos = score.findKey(exemple[ai]); if (pos!=-1) score.addNegative(pos); else score.addKey(exemple[ai],Score.NEGATIVE); } } //First, to find the best value for the current attribute best_v=0; best_h=-Double.MAX_VALUE; int best_operator=-1; if(Attributes.getInputAttribute(ai).getType()==Attribute.NOMINAL){ for (int j = 0; j < score.size(); j++) { double h = score.getPositive(j) * (Utilities.log2(score.getPositive(j) / ( (double) score.getTotal(j))) -C); if (h > best_h) { best_h = h; best_v = score.getKey(j); best_operator=Rule.EQUAL; } } } else{ score.sort(); int total_pos=positives.getnActive(),total_neg=negatives.getnActive(); //Evaluating the first element as cutting point with operator <= int count_pos=0; int count_neg=0; if (score.size()==1 && score.getPositive(0)!=0){ best_h = count_pos * (Utilities.log2(score.getPositive(0)/( (double) score.getNegative(0) + score.getPositive(0))) - C); best_v = score.getKey(0); best_operator=Rule.EQUAL; } else if (score.size()==1){ best_h = -Double.MAX_VALUE; best_v = score.getKey(0); best_operator=Rule.EQUAL; } else best_h = -Double.MAX_VALUE; for (int j = 0; j < score.size()-1; j++) { //Evaluating the j-th element as cutting point with > count_pos+=score.getPositive(j); count_neg+=score.getNegative(j); double h_lower; if (count_pos!=0) h_lower = count_pos * (Utilities.log2(count_pos / ( (double) count_neg+count_pos)) -C); else h_lower = -Double.MAX_VALUE; //Evaluating the (j-1)th element as cutting point with > int count_pos_g=total_pos-count_pos; int count_neg_g=total_neg-count_neg; double h_greater; if (count_pos_g!=0) h_greater = count_pos_g * (Utilities.log2(count_pos_g / ( (double) count_neg_g+count_pos_g)) -C); else h_greater=-Double.MAX_VALUE; //Comparing with the best so far if (h_lower>h_greater && h_lower > best_h) { best_h = h_lower; best_v = score.getKey(j); best_operator=Rule.LOWER; } else if (h_greater>best_h){ best_h = h_greater; best_v = score.getKey(j); best_operator=Rule.GREATER; } } } //Later, test if it is the best couple so far if (best_h>best_global){ P=i; A=ai; V=best_v; Op=best_operator; best_global=best_h; } } //2.Add to the rule the couple (A,V) //Julian - If no attribute could be found, do not add the couple //I really don't know if this assumption it is correct, but it allows the program //to finish, so... if(A!=-1){ rule.grow(A,V,Op); data.filter(positives,A,V,Op); data.filter(negatives,A,V,Op); attributes[P]=attributes[nattributes-1]; } nattributes--; } return rule; } /** * It prunes a rule, according with one of two heuristics: * W= (p+1)/(t+2) * A= (p+n')/T * p/t: number of positive/total instances covered by the current rule * n': number of negative instances not covered by the current rule (true negatives) * T: number of total instances * @param rule Rule the rule to prune * @param data MyDataset the dataset * @param positives Mask active positive entries * @param negatives Mask active negative entries * @param metric int heuristic's selector (A or W) * @return the pruned rule. */ public Rule prune(Rule rule,MyDataset data,Mask positives,Mask negatives,int metric){ double p,t,T,n,n_prime; double h,next_h=0.0; p=rule.apply(data,positives); T=positives.getnActive()+negatives.getnActive(); n=rule.apply(data,negatives); n_prime=negatives.getnActive()-n; if (metric==A){ next_h=(p+n_prime)/T; } if (metric==W){ t=p+n; next_h=(p+1)/(t+2); } do{ h=next_h; p=rule.apply(data,positives,rule.size()-1); T=positives.getnActive()+negatives.getnActive(); n=rule.apply(data,negatives,rule.size()-1); n_prime=negatives.getnActive()-n; if (metric==A){ next_h=(p+n_prime)/T; } if (metric==W){ t=p+n; next_h=(p+1)/(t+2); } if (h<next_h && rule.size()>1){ rule.prune(rule.size()-1); } }while(h<next_h && rule.size()>0 && rule.size()>1); return rule; } /** * It implements the algorithm Ripperk itself: * 1. In each iteration, it takes the class with less instances in the dataset and * it splits this into positive (those of the taken class) and negative (the rest) instances. * 2. Then it invokes Ripper2 to generates a Ruleset for the taken class. * 3. Finally, it removes the instances covered by the ruleset and it carries on whit the next iteration. * @param data MyDataset the dataset * @return a vector with a Ruleset for each class. */ public Ruleset[] ripperMulticlass(MyDataset data){ Ruleset[] rules=new Ruleset[data.getnClasses()]; Pair[] ordered_classes=new Pair[data.getnClasses()]; for (int i=0;i<data.getnClasses();i++){ ordered_classes[i]=new Pair(); ordered_classes[i].key=i; ordered_classes[i].value=data.numberInstances(i); } Utilities.mergeSort(ordered_classes,data.getnClasses()); Mask positives,negatives; Mask base=new Mask(data.size()); for (int i=0;i<data.getnClasses()-1;i++){ String target_class=Attributes.getOutputAttribute(0).getNominalValue(ordered_classes[i].key); positives=base.copy(); data.filterByClass(positives,target_class); negatives=base.and(positives.complement()); rules[i]=ripperK(data,positives,negatives); rules[i].setType(target_class); base=negatives.copy(); } rules[rules.length-1]=new Ruleset(); rules[rules.length-1].addRule(new Rule()); rules[rules.length-1].setType(Attributes.getOutputAttribute(0).getNominalValue(ordered_classes[data.getnClasses()-1].key)); return rules; } /** * It implements the Ripper2's Build Phase: * Iteratively, it grows and prunes rules until the descrition length (DL) of the ruleset * and examples is 64 bits greater than the smallest DL met so far, or there are * no positive examples, or the error rate >= 50%. * The prune metric used here is W. * @param rules Ruleset the rules generated so far * @param data MyDataset the dataset * @param pos Mask active positive entries of data * @param neg Mask active negative entries of data * @return rules with the new grown & pruned rules */ public Ruleset IREPstar(Ruleset rules, MyDataset data, Mask pos, Mask neg){ double error_ratio,smallest_mdl,new_mdl; smallest_mdl=Double.MAX_VALUE-64.0; new_mdl=Double.MAX_VALUE; Mask positives=pos.copy(),negatives=neg.copy(); do{ //Splitting of the two dataset into two prune dataset and two grow dataset Mask[] gp_pos=positives.split(pct,rand); Mask grow_pos=gp_pos[0], prune_pos=gp_pos[1]; Mask[] gp_neg=negatives.split(pct,rand); Mask grow_neg=gp_neg[0], prune_neg=gp_neg[1]; //Grow & Prune Rule new_rule=grow(data,grow_pos,grow_neg); System.out.println("Regla criada\n"+new_rule); prune(new_rule,data,prune_pos,prune_neg,Ripper.W); System.out.println("Regla podada\n"+new_rule); //Estimation of the error ratio rules.addRule(new_rule); //double errors=new_rule.apply(data,prune_neg); //error_ratio=errors/prune_neg.getnActive(); new_mdl=rules.getMDL(data,positives,negatives); if (new_mdl<=smallest_mdl+64){ System.out.println("Regla añadida\n"+new_rule); data.substract(positives,new_rule); data.substract(negatives,new_rule); if (new_mdl<smallest_mdl) smallest_mdl = new_mdl; } else rules.removeRule(rules.size()-1); }while(positives.getnActive()>0 && new_mdl<=smallest_mdl+64); return rules; } /** * It implements the Ripper2's Optimization Phase: * After generating the initial ruleset {Ri}, * generate and prune two variants of each rule Ri from randomized data * using the grow and prune method. But one variant is generated from an empty rule * while the other is generated by greedily adding antecedents to the original rule. * Moreover, the pruning metric used here is A. Then the smallest possible DL for * each variant and the original rule is computed. The variant with the minimal DL * is selected as the final representative of Ri in the ruleset. [WEKA] * @param rules Ruleset the rules from the build phase * @param data MyDataset the dataset * @param positives Mask active positive entries * @param negatives Mask active negative entries * @return the optimized rules */ public Ruleset optimize(Ruleset rules,MyDataset data,Mask positives,Mask negatives){ for (int i=0;i<rules.size();i++){ //Splitting of the two dataset into two prune dataset and two grow dataset Mask[] gp_pos=positives.split(pct,rand); Mask grow_pos=gp_pos[0], prune_pos=gp_pos[1]; Mask[] gp_neg=negatives.split(pct,rand); Mask grow_neg=gp_neg[0], prune_neg=gp_neg[1]; //Removing from the pruning set of all instances that are covered by the other rules data.substract(prune_pos,rules,i); data.substract(prune_neg,rules,i); //Creation of the competing rules Rule revision=grow(data,grow_pos,grow_neg); //from scratch Rule replacement=rules.getRule(i).getCopy(); grow(replacement,data,grow_pos,grow_neg); //from the current rule prune(revision,data,prune_pos,prune_neg,Ripper.A); prune(replacement,data,prune_pos,prune_neg,Ripper.A); //Select the representative Rule current=rules.getRule(i); double current_mdl=rules.getMDL(data,positives,negatives); rules.removeRule(i); rules.insertRule(revision,i); double revision_mdl=rules.getMDL(data,positives,negatives); rules.removeRule(i); rules.insertRule(replacement,i); double replacement_mdl=rules.getMDL(data,positives,negatives); rules.removeRule(i); if (current_mdl<=revision_mdl && current_mdl<=replacement_mdl) rules.insertRule(current,i); else if(revision_mdl<=replacement_mdl) rules.insertRule(revision,i); else rules.insertRule(replacement,i); } return rules; } /** * It implements the algorithm Ripper2: * 1. Build Phase * 2. Optimization Phase * 3. MOP UP: If there are not covered entries, repeat the Build Phase for these entries. * 4. CLEAN UP: Remove those rules that increase the description's length (DL) * @param data MyDataset the dataset * @param positives Mask active positive entries * @param negatives Mask active negative entries * @return the generated ruleset */ public Ruleset ripperK(MyDataset data,Mask positives,Mask negatives){ Ruleset rules=new Ruleset(); /**********************Growing & Prunning***************************************/ IREPstar(rules,data,positives,negatives); for (int i=0;i<K;i++){ /**********************Optimization********************************************/ optimize(rules, data, positives, negatives); /*************************************MOP UP******************************/ Mask p = positives.copy(); data.substract(p, rules); if (p.getnActive() > 0) { IREPstar(rules, data, p, negatives); } } /*************************************CLEAN UP******************************/ rules.removeDuplicates(); rules.pulish(data,positives,negatives); return rules; } public MyDataset getData(){return train;} }
adofsauron/KEEL
src/keel/Algorithms/Rule_Learning/Ripper/Ripper.java
Java
gpl-3.0
23,149
## balance Show accounts and their balances. Aliases: b, bal. `--change` : show balance change in each period (default) `--cumulative` : show balance change accumulated across periods (in multicolumn reports) `-H --historical` : show historical ending balance in each period (includes postings before report start date) `--tree` : show accounts as a tree; amounts include subaccounts (default in simple reports) `--flat` : show accounts as a list; amounts exclude subaccounts except when account is depth-clipped (default in multicolumn reports) `-A --average` : show a row average column (in multicolumn mode) `-T --row-total` : show a row total column (in multicolumn mode) `-N --no-total` : don't show the final total row `--drop=N` : omit N leading account name parts (in flat mode) `--no-elide` : don't squash boring parent accounts (in tree mode) `--format=LINEFORMAT` : in single-column balance reports: use this custom line format `-O FMT --output-format=FMT ` : select the output format. Supported formats: txt, csv. `-o FILE --output-file=FILE` : write output to FILE. A file extension matching one of the above formats selects that format. `--pretty-tables` : Use unicode to display prettier tables. `--sort-amount` : Sort by amount (total row amount, or by average if that is displayed), instead of account name (in flat mode) The balance command displays accounts and balances. It is hledger's most featureful and versatile command. ```shell $ hledger balance $-1 assets $1 bank:saving $-2 cash $2 expenses $1 food $1 supplies $-2 income $-1 gifts $-1 salary $1 liabilities:debts -------------------- 0 ``` More precisely, the balance command shows the *change* to each account's balance caused by all (matched) postings. In the common case where you do not filter by date and your journal sets the correct opening balances, this is the same as the account's ending balance. By default, accounts are displayed hierarchically, with subaccounts indented below their parent. "Boring" accounts, which contain a single interesting subaccount and no balance of their own, are elided into the following line for more compact output. (Use `--no-elide` to prevent this. Eliding of boring accounts is not yet supported in multicolumn reports.) Each account's balance is the "inclusive" balance - it includes the balances of any subaccounts. Accounts which have zero balance (and no non-zero subaccounts) are omitted. Use `-E/--empty` to show them. A final total is displayed by default; use `-N/--no-total` to suppress it: ```shell $ hledger balance -p 2008/6 expenses --no-total $2 expenses $1 food $1 supplies ``` ### Flat mode To see a flat list of full account names instead of the default hierarchical display, use `--flat`. In this mode, accounts (unless depth-clipped) show their "exclusive" balance, excluding any subaccount balances. In this mode, you can also use `--drop N` to omit the first few account name components. ```shell $ hledger balance -p 2008/6 expenses -N --flat --drop 1 $1 food $1 supplies ``` ### Depth limited balance reports With `--depth N`, balance shows accounts only to the specified depth. This is very useful to show a complex charts of accounts in less detail. In flat mode, balances from accounts below the depth limit will be shown as part of a parent account at the depth limit. ```shell $ hledger balance -N --depth 1 $-1 assets $2 expenses $-2 income $1 liabilities ``` <!-- $ for y in 2006 2007 2008 2009 2010; do echo; echo $y; hledger -f $y.journal balance ^expenses --depth 2; done --> ### Multicolumn balance reports With a [reporting interval](#reporting-interval), multiple balance columns will be shown, one for each report period. There are three types of multi-column balance report, showing different information: 1. By default: each column shows the sum of postings in that period, ie the account's change of balance in that period. This is useful eg for a monthly income statement: <!-- multi-column income statement: $ hledger balance ^income ^expense -p 'monthly this year' --depth 3 or cashflow statement: $ hledger balance ^assets ^liabilities 'not:(receivable|payable)' -p 'weekly this month' --> ```shell $ hledger balance --quarterly income expenses -E Balance changes in 2008: || 2008q1 2008q2 2008q3 2008q4 ===================++================================= expenses:food || 0 $1 0 0 expenses:supplies || 0 $1 0 0 income:gifts || 0 $-1 0 0 income:salary || $-1 0 0 0 -------------------++--------------------------------- || $-1 $1 0 0 ``` 2. With `--cumulative`: each column shows the ending balance for that period, accumulating the changes across periods, starting from 0 at the report start date: ```shell $ hledger balance --quarterly income expenses -E --cumulative Ending balances (cumulative) in 2008: || 2008/03/31 2008/06/30 2008/09/30 2008/12/31 ===================++================================================= expenses:food || 0 $1 $1 $1 expenses:supplies || 0 $1 $1 $1 income:gifts || 0 $-1 $-1 $-1 income:salary || $-1 $-1 $-1 $-1 -------------------++------------------------------------------------- || $-1 0 0 0 ``` 3. With `--historical/-H`: each column shows the actual historical ending balance for that period, accumulating the changes across periods, starting from the actual balance at the report start date. This is useful eg for a multi-period balance sheet, and when you are showing only the data after a certain start date: ```shell $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1 Ending balances (historical) in 2008/04/01-2008/12/31: || 2008/06/30 2008/09/30 2008/12/31 ======================++===================================== assets:bank:checking || $1 $1 0 assets:bank:saving || $1 $1 $1 assets:cash || $-2 $-2 $-2 liabilities:debts || 0 0 $1 ----------------------++------------------------------------- || 0 0 0 ``` Multi-column balance reports display accounts in flat mode by default; to see the hierarchy, use `--tree`. With a reporting interval (like `--quarterly` above), the report start/end dates will be adjusted if necessary so that they encompass the displayed report periods. This is so that the first and last periods will be "full" and comparable to the others. The `-E/--empty` flag does two things in multicolumn balance reports: first, the report will show all columns within the specified report period (without -E, leading and trailing columns with all zeroes are not shown). Second, all accounts which existed at the report start date will be considered, not just the ones with activity during the report period (use -E to include low-activity accounts which would otherwise would be omitted). The `-T/--row-total` flag adds an additional column showing the total for each row. The `-A/--average` flag adds a column showing the average value in each row. Here's an example of all three: ```shell $ hledger balance -Q income expenses --tree -ETA Balance changes in 2008: || 2008q1 2008q2 2008q3 2008q4 Total Average ============++=================================================== expenses || 0 $2 0 0 $2 $1 food || 0 $1 0 0 $1 0 supplies || 0 $1 0 0 $1 0 income || $-1 $-1 0 0 $-2 $-1 gifts || 0 $-1 0 0 $-1 0 salary || $-1 0 0 0 $-1 0 ------------++--------------------------------------------------- || $-1 $1 0 0 0 0 # Average is rounded to the dollar here since all journal amounts are ``` ### Custom balance output In simple (non-multi-column) balance reports, you can customise the output with `--format FMT`: ```shell $ hledger balance --format "%20(account) %12(total)" assets $-1 bank:saving $1 cash $-2 expenses $2 food $1 supplies $1 income $-2 gifts $-1 salary $-1 liabilities:debts $1 --------------------------------- 0 ``` The FMT format string (plus a newline) specifies the formatting applied to each account/balance pair. It may contain any suitable text, with data fields interpolated like so: `%[MIN][.MAX](FIELDNAME)` - MIN pads with spaces to at least this width (optional) - MAX truncates at this width (optional) - FIELDNAME must be enclosed in parentheses, and can be one of: - `depth_spacer` - a number of spaces equal to the account's depth, or if MIN is specified, MIN * depth spaces. - `account` - the account's name - `total` - the account's balance/posted total, right justified Also, FMT can begin with an optional prefix to control how multi-commodity amounts are rendered: - `%_` - render on multiple lines, bottom-aligned (the default) - `%^` - render on multiple lines, top-aligned - `%,` - render on one line, comma-separated There are some quirks. Eg in one-line mode, `%(depth_spacer)` has no effect, instead `%(account)` has indentation built in. <!-- XXX retest: Consistent column widths are not well enforced, causing ragged edges unless you set suitable widths. Beware of specifying a maximum width; it will clip account names and amounts that are too wide, with no visible indication. --> Experimentation may be needed to get pleasing results. Some example formats: - `%(total)` - the account's total - `%-20.20(account)` - the account's name, left justified, padded to 20 characters and clipped at 20 characters - `%,%-50(account) %25(total)` - account name padded to 50 characters, total padded to 20 characters, with multiple commodities rendered on one line - `%20(total) %2(depth_spacer)%-(account)` - the default format for the single-column balance report ### Colour support The balance command shows negative amounts in red, if: - the `TERM` environment variable is not set to `dumb` - the output is not being redirected or piped anywhere ### Output destination The balance, print, register and stats commands can write their output to a destination other than the console. This is controlled by the `-o/--output-file` option. ```shell $ hledger balance -o - # write to stdout (the default) $ hledger balance -o FILE # write to FILE ``` ### CSV output The balance, print and register commands can write their output as CSV. This is useful for exporting data to other applications, eg to make charts in a spreadsheet. This is controlled by the `-O/--output-format` option, or by specifying a `.csv` file extension with `-o/--output-file`. ```shell $ hledger balance -O csv # write CSV to stdout $ hledger balance -o FILE.csv # write CSV to FILE.csv ```
ony/hledger
hledger/doc/balance.m4.md
Markdown
gpl-3.0
12,131
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.arboriculture; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import net.minecraft.command.CommandException; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.command.WrongUsageException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import com.mojang.authlib.GameProfile; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.IArboristTracker; import forestry.api.arboriculture.ITreekeepingMode; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.core.config.Defaults; import forestry.core.config.Version; import forestry.core.proxy.Proxies; import forestry.core.utils.CommandMC; import forestry.core.utils.StringUtil; import forestry.plugins.PluginArboriculture; public class CommandTreekeepingMode extends CommandMC { String[] modeStrings; public CommandTreekeepingMode() { modeStrings = new String[PluginArboriculture.treeInterface.getTreekeepingModes().size()]; for (int i = 0; i < PluginArboriculture.treeInterface.getTreekeepingModes().size(); i++) modeStrings[i] = PluginArboriculture.treeInterface.getTreekeepingModes().get(i).getName(); } @Override public int compareTo(Object arg0) { return this.getCommandName().compareTo(((ICommand) arg0).getCommandName()); } @Override public String getCommandName() { return "treekeeping"; } @Override public String getCommandUsage(ICommandSender var1) { return "/" + this.getCommandName() + " help"; } @SuppressWarnings("rawtypes") @Override public List getCommandAliases() { return null; } @Override public void processCommand(ICommandSender sender, String[] arguments) { if (arguments.length <= 0) throw new WrongUsageException(StringUtil.localizeAndFormat("chat.help", this.getCommandUsage(sender))); if (arguments[0].matches("list")) listModes(sender, arguments); else if (arguments[0].matches("info")) listModeInfo(sender, arguments); else if (arguments[0].matches("set")) { if (arguments.length <= 1) throw new WrongUsageException("/" + this.getCommandName() + " set [<world-#>] <mode-name>"); World world = getWorld(sender, arguments); String desired = arguments[arguments.length - 1]; ITreekeepingMode mode = PluginArboriculture.treeInterface.getTreekeepingMode(desired); if (mode == null) throw new CommandException(StringUtil.localize("chat.trees.command.treekeeping.error"), desired); PluginArboriculture.treeInterface.setTreekeepingMode(world, mode.getName()); func_152373_a(sender, this, StringUtil.localize("chat.trees.command.treekeeping.set"), mode.getName()); } else if (arguments[0].matches("save")) { if (arguments.length <= 1) throw new WrongUsageException("/" + this.getCommandName() + " save <player-name>"); saveStatistics(sender, arguments); } else if (arguments[0].matches("help")) { sendChatMessage(sender, StringUtil.localizeAndFormat("chat.trees.command.help.0", this.getCommandName())); sendChatMessage(sender, StringUtil.localize("chat.trees.command.help.1")); sendChatMessage(sender, StringUtil.localize("chat.trees.command.help.2")); sendChatMessage(sender, StringUtil.localize("chat.trees.command.help.3")); sendChatMessage(sender, StringUtil.localize("chat.trees.command.help.4")); sendChatMessage(sender, StringUtil.localize("chat.trees.command.help.5")); } } private void saveStatistics(ICommandSender sender, String[] arguments) { String newLine = System.getProperty("line.separator"); World world = getWorld(sender, arguments); String player = arguments[1]; Collection<String> statistics = new ArrayList<String>(); statistics.add(String.format("Treekeeping statistics for %s on %s:", player, DateFormat.getInstance().format(new Date()))); statistics.add(""); statistics.add("MODE: " + PluginArboriculture.treeInterface.getTreekeepingMode(world).getName()); statistics.add(""); GameProfile profile = MinecraftServer.getServer().func_152358_ax().func_152655_a(player); IArboristTracker tracker = PluginArboriculture.treeInterface.getBreedingTracker(world, profile); if (tracker == null) statistics.add("No statistics found."); else { statistics.add("BRED:"); statistics.add("-----"); statistics.add(""); Collection<IAlleleTreeSpecies> species = new ArrayList<IAlleleTreeSpecies>(); for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) if (allele instanceof IAlleleTreeSpecies) species.add((IAlleleTreeSpecies) allele); statistics.add(String.format("SPECIES (%s):", species.size())); statistics.add("-------------"); statistics.add(""); for (IAlleleTreeSpecies allele : species) statistics.add(generateSpeciesListEntry(allele, tracker)); } File file = new File(Proxies.common.getForestryRoot(), "config/" + Defaults.MOD.toLowerCase(Locale.ENGLISH) + "/stats/" + player + ".log"); try { if (file.getParentFile() != null) file.getParentFile().mkdirs(); if (!file.exists() && !file.createNewFile()) { sendChatMessage(sender, "Log file could not be created. Failed to save statistics."); return; } if (!file.canWrite()) { sendChatMessage(sender, "Cannot write to log file. Failed to save statistics."); return; } FileOutputStream fileout = new FileOutputStream(file); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileout, "UTF-8")); writer.write("# " + Defaults.MOD + newLine + "# " + Version.getVersion() + newLine); for (String line : statistics) writer.write(line + newLine); writer.close(); } catch (Exception ex) { sendChatMessage(sender, "Write operation threw an exception. Failed to save statistics."); ex.printStackTrace(); } sendChatMessage(sender, "Saved statistics for player " + player); } private String generateSpeciesListEntry(IAlleleTreeSpecies species, IArboristTracker tracker) { String discovered = "[ ]"; if (tracker.isDiscovered(species)) discovered = "[ X ]"; String blacklisted = "[ ]"; if (AlleleManager.alleleRegistry.isBlacklisted(species.getUID())) blacklisted = "[ BL ]"; String notcounted = "[ ]"; if (!species.isCounted()) notcounted = "[ NC ]"; return String.format("%s %s %s\t%-40s %-20s %-20s", discovered, blacklisted, notcounted, species.getUID(), species.getName(), species.getAuthority()); } private void listModes(ICommandSender sender, String[] arguments) { World world = getWorld(sender, arguments); sendChatMessage(sender, "Current: " + PluginArboriculture.treeInterface.getTreekeepingMode(world).getName() + " (#" + world.getWorldInfo().getSaveVersion() + ")"); String help = ""; for (ITreekeepingMode mode : PluginArboriculture.treeInterface.getTreekeepingModes()) { if (!help.isEmpty()) help += ", "; help += mode.getName(); } sendChatMessage(sender, "Available modes: " + help); return; } private void listModeInfo(ICommandSender sender, String[] arguments) { if (arguments.length <= 1) throw new WrongUsageException("/" + this.getCommandName() + " info <mode-name>"); ITreekeepingMode found = null; for (ITreekeepingMode mode : PluginArboriculture.treeInterface.getTreekeepingModes()) if (mode.getName().equalsIgnoreCase(arguments[1])) { found = mode; break; } if (found == null) throw new CommandException("No treekeeping mode called '%s' is available.", arguments[1]); sendChatMessage(sender, "\u00A7aMode: " + found.getName()); for (String desc : found.getDescription()) sendChatMessage(sender, StringUtil.localize(desc)); } @Override public boolean canCommandSenderUseCommand(ICommandSender sender) { if (sender instanceof EntityPlayer) return Proxies.common.isOp((EntityPlayer) sender); else return sender.canCommandSenderUseCommand(4, getCommandName()); } @SuppressWarnings("rawtypes") @Override public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { return getListOfStringsMatchingLastWord(incomplete, modeStrings); } }
bdew/ForestryMC
src/main/java/forestry/arboriculture/CommandTreekeepingMode.java
Java
gpl-3.0
9,001
#ifndef OPENBOOK_FS_GUI_LISTKNOWNPEERS_H_ #define OPENBOOK_FS_GUI_LISTKNOWNPEERS_H_ #include "Options.h" #include <QStringList> namespace openbook { namespace filesystem { namespace gui { class ListKnownPeers: public Options { public: static const std::string COMMAND; static const std::string DESCRIPTION; ListKnownPeers(QString port= "3030"); QStringList go(); }; } } } #endif
cheshirekow/codebase
src/openbookfs/gui/commands/ListKnownPeers.h
C
gpl-3.0
428
/* * Copyright (C) 2012 Russell King * Written from the i915 driver. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <drm/drmP.h> #include <drm/drm_fb_helper.h> #include "armada_crtc.h" #include "armada_drm.h" #include "armada_fb.h" #include "armada_gem.h" static /*const*/ struct fb_ops armada_fb_ops = { .owner = THIS_MODULE, .fb_check_var = drm_fb_helper_check_var, .fb_set_par = drm_fb_helper_set_par, .fb_fillrect = drm_fb_helper_cfb_fillrect, .fb_copyarea = drm_fb_helper_cfb_copyarea, .fb_imageblit = drm_fb_helper_cfb_imageblit, .fb_pan_display = drm_fb_helper_pan_display, .fb_blank = drm_fb_helper_blank, .fb_setcmap = drm_fb_helper_setcmap, .fb_debug_enter = drm_fb_helper_debug_enter, .fb_debug_leave = drm_fb_helper_debug_leave, }; static int armada_fb_create(struct drm_fb_helper *fbh, struct drm_fb_helper_surface_size *sizes) { struct drm_device *dev = fbh->dev; struct drm_mode_fb_cmd2 mode; struct armada_framebuffer *dfb; struct armada_gem_object *obj; struct fb_info *info; int size, ret; void *ptr; memset(&mode, 0, sizeof(mode)); mode.width = sizes->surface_width; mode.height = sizes->surface_height; mode.pitches[0] = armada_pitch(mode.width, sizes->surface_bpp); mode.pixel_format = drm_mode_legacy_fb_format(sizes->surface_bpp, sizes->surface_depth); size = mode.pitches[0] * mode.height; obj = armada_gem_alloc_private_object(dev, size); if (!obj) { DRM_ERROR("failed to allocate fb memory\n"); return -ENOMEM; } ret = armada_gem_linear_back(dev, obj); if (ret) { drm_gem_object_unreference_unlocked(&obj->obj); return ret; } ptr = armada_gem_map_object(dev, obj); if (!ptr) { drm_gem_object_unreference_unlocked(&obj->obj); return -ENOMEM; } dfb = armada_framebuffer_create(dev, &mode, obj); /* * A reference is now held by the framebuffer object if * successful, otherwise this drops the ref for the error path. */ drm_gem_object_unreference_unlocked(&obj->obj); if (IS_ERR(dfb)) { return PTR_ERR(dfb); } info = drm_fb_helper_alloc_fbi(fbh); if (IS_ERR(info)) { ret = PTR_ERR(info); goto err_fballoc; } strlcpy(info->fix.id, "armada-drmfb", sizeof(info->fix.id)); info->par = fbh; info->flags = FBINFO_DEFAULT | FBINFO_CAN_FORCE_OUTPUT; info->fbops = &armada_fb_ops; info->fix.smem_start = obj->phys_addr; info->fix.smem_len = obj->obj.size; info->screen_size = obj->obj.size; info->screen_base = ptr; fbh->fb = &dfb->fb; drm_fb_helper_fill_fix(info, dfb->fb.pitches[0], dfb->fb.depth); drm_fb_helper_fill_var(info, fbh, sizes->fb_width, sizes->fb_height); DRM_DEBUG_KMS("allocated %dx%d %dbpp fb: 0x%08llx\n", dfb->fb.width, dfb->fb.height, dfb->fb.bits_per_pixel, (unsigned long long)obj->phys_addr); return 0; err_fballoc: dfb->fb.funcs->destroy(&dfb->fb); return ret; } static int armada_fb_probe(struct drm_fb_helper *fbh, struct drm_fb_helper_surface_size *sizes) { int ret = 0; if (!fbh->fb) { ret = armada_fb_create(fbh, sizes); if (ret == 0) { ret = 1; } } return ret; } static const struct drm_fb_helper_funcs armada_fb_helper_funcs = { .gamma_set = armada_drm_crtc_gamma_set, .gamma_get = armada_drm_crtc_gamma_get, .fb_probe = armada_fb_probe, }; int armada_fbdev_init(struct drm_device *dev) { struct armada_private *priv = dev->dev_private; struct drm_fb_helper *fbh; int ret; fbh = devm_kzalloc(dev->dev, sizeof(*fbh), GFP_KERNEL); if (!fbh) { return -ENOMEM; } priv->fbdev = fbh; drm_fb_helper_prepare(dev, fbh, &armada_fb_helper_funcs); ret = drm_fb_helper_init(dev, fbh, 1, 1); if (ret) { DRM_ERROR("failed to initialize drm fb helper\n"); goto err_fb_helper; } ret = drm_fb_helper_single_add_all_connectors(fbh); if (ret) { DRM_ERROR("failed to add fb connectors\n"); goto err_fb_setup; } ret = drm_fb_helper_initial_config(fbh, 32); if (ret) { DRM_ERROR("failed to set initial config\n"); goto err_fb_setup; } return 0; err_fb_setup: drm_fb_helper_release_fbi(fbh); drm_fb_helper_fini(fbh); err_fb_helper: priv->fbdev = NULL; return ret; } void armada_fbdev_lastclose(struct drm_device *dev) { struct armada_private *priv = dev->dev_private; if (priv->fbdev) { drm_fb_helper_restore_fbdev_mode_unlocked(priv->fbdev); } } void armada_fbdev_fini(struct drm_device *dev) { struct armada_private *priv = dev->dev_private; struct drm_fb_helper *fbh = priv->fbdev; if (fbh) { drm_fb_helper_unregister_fbi(fbh); drm_fb_helper_release_fbi(fbh); drm_fb_helper_fini(fbh); if (fbh->fb) { fbh->fb->funcs->destroy(fbh->fb); } priv->fbdev = NULL; } }
williamfdevine/PrettyLinux
drivers/gpu/drm/armada/armada_fbdev.c
C
gpl-3.0
4,872
#ifndef ANALYSERPITCH_H #define ANALYSERPITCH_H #include <QObject> #include <QPointer> #include <QString> #include <QList> #include <QStandardItemModel> #include "PraalineCore/Base/RealTime.h" namespace Praaline { namespace Core { class Corpus; class CorpusCommunication; class Interval; class IntervalTier; class StatisticalMeasureDefinition; } } struct AnalyserMacroprosodyData; class AnalyserMacroprosody : public QObject { Q_OBJECT public: explicit AnalyserMacroprosody(QObject *parent = nullptr); virtual ~AnalyserMacroprosody(); static QList<QString> groupingLevels(); static QList<QString> measureIDs(const QString &groupingLevel); static Praaline::Core::StatisticalMeasureDefinition measureDefinition(const QString &groupingLevel, const QString &measureID); double measure(const QString &groupingLevel, const QString &key, const QString &measureID) const; QPointer<QStandardItemModel> model(); void setMacroUnitsLevel(const QString &); void setMetadataAttributesCommunication(const QStringList &attributeIDs); void setMetadataAttributesSpeaker(const QStringList &attributeIDs); void setMetadataAttributesAnnotation(const QStringList &attributeIDs); QString calculate(QPointer<Praaline::Core::Corpus> corpus, Praaline::Core::CorpusCommunication *com); QString calculate(QPointer<Praaline::Core::Corpus> corpus, const QString &communicationID, const QString &annotationID, const QString &speakerIDfilter = QString(), const QList<Praaline::Core::Interval *> &units = QList<Praaline::Core::Interval *>()); signals: public slots: private: AnalyserMacroprosodyData *d; }; #endif // ANALYSERPITCH_H
praaline/Praaline
app/statistics/prosody/AnalyserMacroprosody.h
C
gpl-3.0
1,719
\hypertarget{classSimulation}{}\section{Simulation Class Reference} \label{classSimulation}\index{Simulation@{Simulation}} Class containing all \hyperlink{classEnvironment}{Environment} objects, as well control-\/flow attributes for the simulation. {\ttfamily \#include $<$Simulation.\+hpp$>$} Inheritance diagram for Simulation\+:\begin{figure}[H] \begin{center} \leavevmode \includegraphics[height=4.000000cm]{classSimulation} \end{center} \end{figure} \subsection*{Public Member Functions} \begin{DoxyCompactItemize} \item \mbox{\Hypertarget{classSimulation_ae902fd16a0f0c24d3b49c96cead9fcf9}\label{classSimulation_ae902fd16a0f0c24d3b49c96cead9fcf9}} {\bfseries Simulation} (vector$<$ \hyperlink{classEnvironment}{Environment} $>$ \+\_\+env) \item \mbox{\Hypertarget{classSimulation_a44dc929698224fbf195b9d9936fae82a}\label{classSimulation_a44dc929698224fbf195b9d9936fae82a}} bool {\bfseries get\+Complete\+Start} () \item \mbox{\Hypertarget{classSimulation_adca9200350aad6630085d6f50ef910f3}\label{classSimulation_adca9200350aad6630085d6f50ef910f3}} void {\bfseries set\+Complete\+Start} (bool new\+Val) \item \mbox{\Hypertarget{classSimulation_a31e406c0ad5849a8e6496393ccbb3483}\label{classSimulation_a31e406c0ad5849a8e6496393ccbb3483}} bool {\bfseries get\+Complete\+End} () \item \mbox{\Hypertarget{classSimulation_a0e8a32be7804eca80992fa6d1d27b0be}\label{classSimulation_a0e8a32be7804eca80992fa6d1d27b0be}} void {\bfseries set\+Complete\+End} (bool new\+Val) \item \mbox{\Hypertarget{classSimulation_a0cf743fa59385016d9e699fb0093317c}\label{classSimulation_a0cf743fa59385016d9e699fb0093317c}} int {\bfseries get\+Num\+Steps} () \item \mbox{\Hypertarget{classSimulation_a68c66b40439322e4bda57eaa11386ce6}\label{classSimulation_a68c66b40439322e4bda57eaa11386ce6}} void {\bfseries set\+Num\+Steps} (int new\+Val) \item \mbox{\Hypertarget{classSimulation_a57f25582cd263d9739e9d72e75832a67}\label{classSimulation_a57f25582cd263d9739e9d72e75832a67}} int {\bfseries get\+Save\+Div} () \item \mbox{\Hypertarget{classSimulation_a5346ad2601beff7e3918e25dd667ab4b}\label{classSimulation_a5346ad2601beff7e3918e25dd667ab4b}} void {\bfseries set\+Save\+Div} (int new\+Val) \item \mbox{\Hypertarget{classSimulation_a0110a1fad0e2390ea90fa387fe09cbdc}\label{classSimulation_a0110a1fad0e2390ea90fa387fe09cbdc}} vector$<$ \hyperlink{classEnvironment}{Environment} $>$ $\ast$ {\bfseries get\+Envs} () \item \mbox{\Hypertarget{classSimulation_a8223c6354f021efcb667815fbd0682c0}\label{classSimulation_a8223c6354f021efcb667815fbd0682c0}} void {\bfseries add\+Env} (\hyperlink{classEnvironment}{Environment} new\+Val) \item virtual int \hyperlink{classSimulation_a7eb16da89581b496d33b77efbb63b9cd}{run\+Sim} (int run\+Number) \begin{DoxyCompactList}\small\item\em Method that runs the main loop of the simulation. \end{DoxyCompactList}\end{DoxyCompactItemize} \subsection*{Protected Attributes} \begin{DoxyCompactItemize} \item int \hyperlink{classSimulation_a999ce13c1a3d4dca2bf92e346d8b709f}{num\+Steps} \item int \hyperlink{classSimulation_ae8f095e92da49a648954416b351e27c8}{save\+Div} \item bool \hyperlink{classSimulation_a84cd73f44cff4fdbbb40fb98b49f8026}{complete\+Start} = false \item bool \hyperlink{classSimulation_a17bcf189d0f10fa47e4b2dc4b53d4939}{complete\+End} = false \item vector$<$ \hyperlink{classEnvironment}{Environment} $>$ \hyperlink{classSimulation_a29309017ca18043de245ef843b56c533}{envs} \end{DoxyCompactItemize} \subsection{Detailed Description} Class containing all \hyperlink{classEnvironment}{Environment} objects, as well control-\/flow attributes for the simulation. The \hyperlink{classSimulation}{Simulation} class contains all \hyperlink{classEnvironment}{Environment} objects. It updates them each time\+Step, and is also in charge of deciding when to save what (for all save types). \subsection{Member Function Documentation} \mbox{\Hypertarget{classSimulation_a7eb16da89581b496d33b77efbb63b9cd}\label{classSimulation_a7eb16da89581b496d33b77efbb63b9cd}} \index{Simulation@{Simulation}!run\+Sim@{run\+Sim}} \index{run\+Sim@{run\+Sim}!Simulation@{Simulation}} \subsubsection{\texorpdfstring{run\+Sim()}{runSim()}} {\footnotesize\ttfamily int Simulation\+::run\+Sim (\begin{DoxyParamCaption}\item[{int}]{run\+Number }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [virtual]}} Method that runs the main loop of the simulation. \begin{DoxyParams}{Parameters} {\em run\+Number} & ID of the current run of the simulation. \\ \hline \end{DoxyParams} Reimplemented in \hyperlink{classMultiSimulation_a235347d04fd0c7e1a2e35d7a39e77583}{Multi\+Simulation}, \hyperlink{classMultiEvoSimulation_a89c9806ac998c06230cdd41cc6a532bf}{Multi\+Evo\+Simulation}, \hyperlink{classE2MSimulation_aeac4e92c10f89a5c953ace5b1327d20b}{E2\+M\+Simulation}, \hyperlink{classEvoSimulation_aa43aa351dec24c638e56995a67a4f0f5}{Evo\+Simulation}, \hyperlink{classE2Simulation_a28028881fd443d2445b562512cb2169c}{E2\+Simulation}, \hyperlink{classMultiEcoSimulation_ad490e089c083d06d80c62af9e1564ac3}{Multi\+Eco\+Simulation}, and \hyperlink{classEcoSimulation_a72ec5e7dffb4231b2cb363b632788622}{Eco\+Simulation}. \subsection{Field Documentation} \mbox{\Hypertarget{classSimulation_a17bcf189d0f10fa47e4b2dc4b53d4939}\label{classSimulation_a17bcf189d0f10fa47e4b2dc4b53d4939}} \index{Simulation@{Simulation}!complete\+End@{complete\+End}} \index{complete\+End@{complete\+End}!Simulation@{Simulation}} \subsubsection{\texorpdfstring{complete\+End}{completeEnd}} {\footnotesize\ttfamily bool Simulation\+::complete\+End = false\hspace{0.3cm}{\ttfamily [protected]}} Determines whether or not a complete save is made at the end of the simulation. \mbox{\Hypertarget{classSimulation_a84cd73f44cff4fdbbb40fb98b49f8026}\label{classSimulation_a84cd73f44cff4fdbbb40fb98b49f8026}} \index{Simulation@{Simulation}!complete\+Start@{complete\+Start}} \index{complete\+Start@{complete\+Start}!Simulation@{Simulation}} \subsubsection{\texorpdfstring{complete\+Start}{completeStart}} {\footnotesize\ttfamily bool Simulation\+::complete\+Start = false\hspace{0.3cm}{\ttfamily [protected]}} Determines whether or not a complete save is made at the beginning of the simulation. \mbox{\Hypertarget{classSimulation_a29309017ca18043de245ef843b56c533}\label{classSimulation_a29309017ca18043de245ef843b56c533}} \index{Simulation@{Simulation}!envs@{envs}} \index{envs@{envs}!Simulation@{Simulation}} \subsubsection{\texorpdfstring{envs}{envs}} {\footnotesize\ttfamily vector$<$\hyperlink{classEnvironment}{Environment}$>$ Simulation\+::envs\hspace{0.3cm}{\ttfamily [protected]}} List containing all environments of the simulation \mbox{\Hypertarget{classSimulation_a999ce13c1a3d4dca2bf92e346d8b709f}\label{classSimulation_a999ce13c1a3d4dca2bf92e346d8b709f}} \index{Simulation@{Simulation}!num\+Steps@{num\+Steps}} \index{num\+Steps@{num\+Steps}!Simulation@{Simulation}} \subsubsection{\texorpdfstring{num\+Steps}{numSteps}} {\footnotesize\ttfamily int Simulation\+::num\+Steps\hspace{0.3cm}{\ttfamily [protected]}} Number of steps for which the simulation should be run \mbox{\Hypertarget{classSimulation_ae8f095e92da49a648954416b351e27c8}\label{classSimulation_ae8f095e92da49a648954416b351e27c8}} \index{Simulation@{Simulation}!save\+Div@{save\+Div}} \index{save\+Div@{save\+Div}!Simulation@{Simulation}} \subsubsection{\texorpdfstring{save\+Div}{saveDiv}} {\footnotesize\ttfamily int Simulation\+::save\+Div\hspace{0.3cm}{\ttfamily [protected]}} Each how many steps densities are saved (in raw\+Save file) The documentation for this class was generated from the following files\+:\begin{DoxyCompactItemize} \item \hyperlink{Simulation_8hpp}{Simulation.\+hpp}\item Simulation.\+cpp\end{DoxyCompactItemize}
melchior-zimmermann/popSim
doxyDoc/latex/classSimulation.tex
TeX
gpl-3.0
7,728
#include <stdio.h> #include <stdlib.h> #include "tables_sort.h" void B_InsertSort(NodeType R[], int n) { int i, j; int p; int q; R[0].next = 1; R[1].next = 0; for (i = 2; i < n; i++) { j = 0; while (R[R[j].next].data < R[i].data && R[j].next != 0) j = R[j].next; R[i].next = R[j].next; R[j].next = i; } } int main() { int i; NodeType array[9]; //NodeType array[9] = {32767, 49, 38, 65, 97, 76, 13, 27, 49}; for (i = 0; i < 9; i++) //scanf("%d", &(array[i].data)); array[i].data = 8 - i; printf("---------------before sorted----------------\n"); for (i = 0; i < 9; i++) printf("%d ", array[i].data); printf("\n"); printf("---------------after sorted-----------------\n"); B_InsertSort(array, 9); for (i = 0; array[i].next != 0; i = array[i].next) printf("%d ", array[array[i].next].data); printf("\n"); return 0; }
lilianglaoding/codeprimer
CLab/DataStruct/Sort/Table_Sort/tables_sort.c
C
gpl-3.0
895
<?php /* * Inizializzazione di una classe Settings di impostazione per definire le variabili di collegamento al DB */ class Settings{ /** * @author sanvi <sanvi.simo@gmail.com> */ private $settings; function getSettings(){ $this->settings['host'] = "localhost"; $this->settings['user'] = "tuo_user"; $this->settings['pass'] = "tua_password"; $this->settings['database'] = "tuo db"; return $this->settings; } } ?>
sanvisimo/solari
PHP/settings.php
PHP
gpl-3.0
510
<html> <head> <title>Enviando Correo Entidad --- OrfeoGPL</title> <link rel="stylesheet" href="../estilos/orfeo.css"> </head> <body> <center><img src='http://volimpo/iconos/tuxTx.gif'></center> <?php // envio de respuesta via email // Obtiene los datos de la respuesta rapida. $ruta_raiz = "../"; $ruta_libs= $ruta_raiz."respuestaRapida/"; define('ADODB_ASSOC_CASE', 0); define('SMARTY_DIR', $ruta_libs . 'libs/'); define('FPDF_FONTPATH', $ruta_raiz."fpdf/font/"); require_once("../include/db/ConnectionHandler.php"); require_once($ruta_raiz."_conf/constantes.php"); require_once("dompdf_config.inc.php"); include_once("../class_control/AplIntegrada.php"); include_once(ORFEOPATH . "class_control/anexo.php"); include_once(ORFEOPATH . "class_control/anex_tipo.php"); include_once($ruta_raiz."include/tx/Tx.php"); include_once("../include/tx/Radicacion.php"); include_once("../class_control/Municipio.php"); include_once("../envios/class.phpmailer.php"); set_time_limit(0); $db = new ConnectionHandler("$ruta_raiz"); $db->conn->SetFetchMode(ADODB_FETCH_ASSOC); $verradicado = $_POST["radPadre"]. "\n"; function StrValido($cadena) { $login = strtolower($cadena); $b = array("á","é","í","ó","ú","ä","ë","ï","ö","ü","à","è","ì","ò","ù","ñ",",",".",";",":","¡","!","¿","?",'"',"/","&","\n"); $c = array("a","e","i","o","u","a","e","i","o","u","a","e","i","o","u","n","","","","","","","","",'',"","","",); $login = str_replace($b,$c,$login); return $login; } function FechaFormateada($FechaStamp) { $ano = date('Y', $FechaStamp); //<-- Año $mes = date('m', $FechaStamp); //<-- número de mes (01-31) $dia = date('d', $FechaStamp); //<-- Día del mes (1-31) $dialetra = date('w', $FechaStamp); //Día de la semana(0-7) switch ($dialetra) { case 0 : $dialetra = "Domingo"; break; case 1 : $dialetra = "Lunes"; break; case 2 : $dialetra = "Martes"; break; case 3 : $dialetra = "Miércoles"; break; case 4 : $dialetra = "Jueves"; break; case 5 : $dialetra = "Viernes"; break; case 6 : $dialetra = "Sábado"; break; } switch ($mes) { case '01' : $mesletra = "Enero"; break; case '02' : $mesletra = "Febrero"; break; case '03' : $mesletra = "Marzo"; break; case '04' : $mesletra = "Abril"; break; case '05' : $mesletra = "Mayo"; break; case '06' : $mesletra = "Junio"; break; case '07' : $mesletra = "Julio"; break; case '08' : $mesletra = "Agosto"; break; case '09' : $mesletra = "Septiembre"; break; case '10' : $mesletra = "Octubre"; break; case '11' : $mesletra = "Noviembre"; break; case '12' : $mesletra = "Diciembre"; break; } return "$dialetra, $dia de $mesletra de $ano"; } function makeLabel($db, $tdoc) { // params to variables $sqlE = "SELECT SGD_PQR_LABEL FROM SGD_PQR_MASTER WHERE ID = $tdoc"; return $db->conn->Execute($sqlE); } function radi_paht($db, $ruta, $numerad) { // params to variables $ruta .= ".pdf"; $sqlE = "UPDATE RADICADO SET RADI_PATH = ('$ruta') where radi_nume_radi = $numerad"; return $db->conn->Execute($sqlE); } function nom_muni_dpto($muni, $dep, $db) { // params to variables $sqlE = " SELECT a.MUNI_NOMB, b.DPTO_NOMB FROM MUNICIPIO a, DEPARTAMENTO b WHERE (a.ID_PAIS = 170) AND (a.ID_CONT = 1) AND (a.DPTO_CODI = $dep) AND (a.MUNI_CODI = $muni) AND (a.DPTO_CODI=b.DPTO_CODI) AND (a.ID_PAIS=b.ID_PAIS) AND (a.ID_CONT=b.ID_CONT)"; return $db->conn->Execute($sqlE); } $hist = new Historico($db); $Tx = new Tx($db); $ddate = date("d"); $mdate = date("m"); $adate = date("Y"); $fechproc4 = substr($adate,2,4); $fechrd = $ddate.$mdate.$fechproc4; $tdoc = 0; // tipo documental no definido //DATOS A VALIDAR EN RADICADO // session_start(); $coddepe = $_POST["depecodi"]; $radi_usua_actu = $_POST["usuacodi"]; $usua = $_POST["usualog"]; $codigoCiu = $_POST["codigoCiu"]; $usMailSelect = $_POST["usMailSelect"]; $ent = '1'; $tpDepeRad = $coddepe ; $radUsuaDoc = $codigoCiu; if ($_SESSION["krd"]) $krd = $_SESSION["krd"]; //Para crear el numero de radicado se realiza el siguiente procedimiento //$newRadicado = date("Y") . $this->dependencia . str_pad($secNew,$this->noDigitosRad,"0", STR_PAD_LEFT) . $tpRad; //este se puede ver en el archivo Radicacion.php $isql_consec= "select DEPE_RAD_TP$ent as secuencia from DEPENDENCIA WHERE DEPE_CODI = $tpDepeRad"; $creaNoRad = $db->conn->Execute($isql_consec); $tpDepeRad = $creaNoRad->fields["secuencia"]; //Email del usuario //DATOS EMPRESA $sigla = 'null'; $iden = $db->nextId("sec_ciu_ciudadano");// uniqe key ?????????????????????????????? $email = $_POST['usMailSelect']; //mail $pais = 170; //OK, codigo pais $cont = 1; //id del continente $asu = $_POST["respuesta"]; // RADICADO $rad = new Radicacion($db); $rad->radiTipoDeri = 0; // ok ???? $rad->radiCuentai = 'null'; // ok, Cuenta Interna, Oficio, Referencia $rad->eespCodi = $iden; //codigo emepresa de servicios publicos bodega $rad->mrecCodi = 3; // medio de correspondencia, 3 internet $rad->radiFechOfic = "$ddate/$mdate/$adate"; // igual fecha radicado; $rad->radiNumeDeri = $verradicado; //ok, radicado padre $rad->radiPais = $pais; //OK, codigo pais $rad->descAnex = '.'; //OK anexos $rad->raAsun = "Respuesta al radicado " . $verradicado; // ok asunto $rad->radiDepeActu = $coddepe; // ok dependencia actual responsable $rad->radiUsuaActu = $radi_usua_actu; // ok usuario actual responsable $rad->radiDepeRadi = $coddepe; //ok dependencia que radica $rad->usuaCodi = $radi_usua_actu; // ok usuario actual responsable $rad->dependencia = $coddepe; //ok dependencia que radica $rad->trteCodi = 0; //ok, tipo de codigo de remitente $rad->tdocCodi = $tdoc; //ok, tipo documental $rad->tdidCodi = 0; //ok, ???? $rad->carpCodi = 1; //ok, carpeta entradas $rad->carPer = 0; //ok, carpeta personal $rad->ra_asun = "Respuesta al radicado " . $verradicado; $rad->radiPath = 'null'; $rad->sgd_apli_codi = '0'; $rad->usuaDoc = $radUsuaDoc; $codTx = 62; $nurad = $rad->newRadicado($ent,$tpDepeRad); if ($nurad=="-1") echo"<script type='text/javascript'>alert('No se creo radicado de salida');exit();</script>"; if(!$nurad) echo "<hr>RADICADO GENERADO <HR>$nurad<hr>"; $nextval = $db->nextId("sec_dir_direcciones"); $emailEMisorMensaje = $_POST["destinatario"]; $isql = "insert into SGD_DIR_DRECCIONES( SGD_TRD_CODIGO, SGD_DIR_NOMREMDES, SGD_DIR_DOC, DPTO_CODI, MUNI_CODI, id_pais, id_cont, SGD_DOC_FUN, SGD_OEM_CODIGO, SGD_CIU_CODIGO, SGD_ESP_CODI, RADI_NUME_RADI, SGD_SEC_CODIGO, SGD_DIR_DIRECCION, SGD_DIR_TELEFONO, SGD_DIR_MAIL, SGD_DIR_TIPO, SGD_DIR_CODIGO, SGD_DIR_NOMBRE) values( 1, NULL, NULL, 11, 1, 170, 1, NULL, NULL, NULL, NULL, $nurad, 0, NULL, NULL, '$emailEMisorMensaje', 1, $nextval, NULL)"; $rsg = $db->conn->Execute($isql); $mensajeHistorico = "Se envia respuesta rapida"; $adjuntos = $_SESSION["archivosAdjuntos"]; if($adjuntos != null){ $mensajeHistorico .= ", con archivos adjuntos"; } $numRadicadoPadre = $verradicado; //inserta el evento del radicado padre. $radicadosSel[0] = $numRadicadoPadre; $hist->insertarHistorico($radicadosSel, $coddepe, $radi_usua_actu, $coddepe, $radi_usua_actu, $mensajeHistorico, $codTx); //Inserta el evento del radicado de respuesta nuevo. $radicadosSel[0] = $nurad; $hist->insertarHistorico($radicadosSel, $coddepe, $radi_usua_actu, $coddepe, $radi_usua_actu, "", 2); //Agregar un nuevo evento en el historico para que //muestre como contestado y no genere alarmas. //A la respuesta se le agrega el siguiente evento $hist->insertarHistorico($radicadosSel, $coddepe, $radi_usua_actu, $coddepe, $radi_usua_actu, "Imagen asociada desde respuesta rapida", 42); $Radicado = $nurad; $correo = $email; $numradicado = $Radicado; $fecha1 = time(); $fecha = FechaFormateada($fecha1); $lugar = "Bogota DC"; //variables para generar el pdf con l no olvidar \n para dividir filas $pie = "Calle 26 # 13 - 19 Bogotá, D.C., Colombia PBX 381 5000 www.dnp.gov.co"; $mensaje = "Atentamente"; if(trim($_POST["destinatario"])){ $emailSend = split(";",$_POST["destinatario"]); $enviadoA = ""; foreach($emailSend as $mailDir){ if(Trim($mailDir)) $enviadoA .= ">".$mailDir. "\n"; } } $conCopiaA =""; if(trim($_POST["concopia"])){ $emailSend = split(";",$_POST["concopia"]); foreach($emailSend as $mailDir){ if(Trim($mailDir)) $conCopiaA .="CC>".$mailDir."\n"; } } $receptor="Respuesta Web \nCorreo electronico: $correo \n \nDestinatarios: \n". $enviadoA . $conCopiaA; #($pie, $numRadicadoPadre, $numradicado, $fecha, $lugar, $asu, $mensaje, $receptor); //Construye las opciones necesario para el anexo del radicado. //El archivo se guarda en la ruta que origina el radicado padre //este campo se adjunta en el radipath $primerno = substr($numRadicadoPadre, 0, 4); $segundono = substr($numRadicadoPadre, 4, 3); $rutaArchivo = "/" . $primerno . "/" . $segundono . "/docs/" .$enlace; $adjuntos[count($adjuntos)]=$rutaArchivo; ?> <center> <TABLE class=borde_tab width="90%"> <tr> <td class=titulos2> <? echo "<b>Radicado pdf Enviado $rutaArchivo </b><br>"; //Se crea pdf $radicado_rem = 7; $radi = $Radicado; $sqlFechaHoy = $db->conn->OffsetDate(0, $db->conn->sysTimeStamp); $anex = & new Anexo($db); $anexTip = & new Anex_tipo($db); $radicado_rem = 1; $auxnumero = $anex->obtenerMaximoNumeroAnexo($radi); do { $auxnumero += 1; $codigo = trim($numRadicadoPadre) . trim(str_pad($auxnumero, 5, "0", STR_PAD_LEFT)); }while ($anex->existeAnexo($codigo)); $anexTip->anex_tipo_codigo(7); $ext = 'pdf'; $auxnumero = str_pad($auxnumero, 5, "0", STR_PAD_LEFT); $tipo = 7; #pdf $tamano = 1000; $auxsololect = 'N'; $descr = 'Pdf respuesta'; $isql = "insert into anexos (SGD_REM_DESTINO, ANEX_RADI_NUME, ANEX_CODIGO, ANEX_ESTADO, ANEX_TIPO, ANEX_TAMANO, ANEX_SOLO_LECT, ANEX_CREADOR, ANEX_DESC, ANEX_NUMERO, ANEX_NOMB_ARCHIVO, ANEX_BORRADO, ANEX_SALIDA, SGD_DIR_TIPO, ANEX_DEPE_CREADOR, SGD_TPR_CODIGO, ANEX_FECH_ANEX, SGD_APLI_CODI, SGD_TRAD_CODIGO, RADI_NUME_SALIDA, SGD_EXP_NUMERO, ANEX_ESTADO_EMAIL) values ($radicado_rem, $numRadicadoPadre, '$codigo', 2, $tipo, $tamano, '$auxsololect', '$usua', '$descr', $auxnumero, '$enlace', 'N', 1, $radicado_rem, $coddepe, NULL, $sqlFechaHoy, NULL, 1, $Radicado, NULL,1)"; $bien = $db->conn->Execute($isql); // Si actualizo BD correctamente if ($bien) { echo "</br></br> anexado ok </br>"; } else { echo "</br></br> anexado ERROR </br>"; } $strServer="172.16.1.92:25"; //Envio de correo $resultadoEnvio = enviarCorreo($Radicado,$usMailSelect,"Respuesta_Web",$_POST["usuanomb"],$_POST["destinatario"],$strServer,$adjuntos,"",$asu,$_POST["concopia"],$numRadicadoPadre,$rutaArchivo,$db); //Funcion que realiza el envio de correo. function enviarCorreo($verradicado2, $correo, $usuario, $Nomb_usua, $Email_usua, $servidorSmtp, $adjuntos, $ext, $respuesta, $correocopia, $nurad, $rutaArchivo, $db) { $mail = new PHPMailer(); $cuerpo = "<br>El Departamento Nacional de Planeacion <br> ha dado respuesta a su solicitud No. " . $nurad . " mediante el oficio No." . $verradicado2 . ", la cual tambien puede ser consultada en el portal Web del DNP.</p> <br><br><b><center>Si no puede visualizar bien el correo, o no llegaron bien los Adjuntos, puede Consultarlos en : <a href='http://orfeo.dnp.gov.co/pqr/consulta.php?rad=$nurad'>http://orfeo.dnp.gov.co/pqr/consulta.php</a><br><br><br>".htmlspecialchars($respuesta)."</b></center><BR> "; $db = new ConnectionHandler("$ruta_raiz"); $db->conn->SetFetchMode(ADODB_FETCH_ASSOC); $iSqlRadPadre = "Select RADI_PATH from radicado where radi_nume_radi=$nurad"; $rsPath = $db->conn->Execute($iSqlRadPadre); $pathPadre = $rsPath->fields["RADI_PATH"]; $mail->Mailer = "smtp"; $mail->From = $correo; $mail->FromName = $usuario; $mail->Host = $servidorSmtp; $mail->Mailer = "smtp"; $mail->SMTPAuth = "true"; $mail->Subject = "Respuesta al radicado " . $nurad . " Departamento Nacional de Planeacion"; $mail->AltBody = "Para ver el mensaje, por favor use un visor de E-mail compatible!"; $mail->Body = $cuerpo; $mail->IsHTML(true); $mail->SMTPDebug = 0; // enables SMTP debug information (for testing) // 1 = errors and messages // 2 = messages only if(trim($Email_usua)){ $emailSend = split(";",$Email_usua); $enviadoA = ""; foreach($emailSend as $mailDir){ if($mailDir) $mail->AddAddress(trim($mailDir)); echo ">".$mailDir . " <br> "; $enviadoA .= ">".$mailDir. " <br> "; } } $conCopiaA =""; if(trim($correocopia)){ $emailSend = split(";",$correocopia); foreach($emailSend as $mailDir){ if($mailDir) $mail->AddCC(trim($mailDir)); echo "CC> ".$mailDir . " <br> "; $conCopiaA .="CC>".$mailDir."<br>"; } } $conCopiaOcultaA= ""; if(trim($_POST["concopiaOculta"])){ $emailSend = split(";",$_POST["concopiaOculta"]); foreach($emailSend as $mailDir){ if($mailDir) $mail->AddBCC(trim($mailDir)); echo "BCC> ".$mailDir . " <br> "; $conCopiaOcultaA .= $mailDir; } } $mail->AddReplyTo($correo, $usuario); $posExt = stripos($pathPadre,"."); $docRecibido = "Documento Recibido".substr($pathPadre,$posExt,strlen($pathPadre)); //$docRecibido = str_replace("/".$nurad,"DocRecibido", $pathP); $mail->AddAttachment("../bodega/".$pathPadre, $docRecibido); $mail->AddAttachment("../bodega/".$rutaArchivo, "Respuesta".$verradicado2.".pdf"); //$anex = new Anexo($db); if ($adjuntos != NULL){ $i=0; $usua = $_POST["usualog"]; $anexo = new Anexo($db); while($i < count($adjuntos)){ if($i<(count($adjuntos)-1)) { $anexoAno = date('Y'); $mail->AddAttachment("../bodega/tmp/".$adjuntos[$i], $adjuntos[$i]); $anexo->anex_radi_nume = $nurad; $anexo->usuaCodi = 1; $anexo->depe_codi = coddepe; $anexo->anex_solo_lect = "'S'"; $anexo->anex_tamano = "0"; $anexo->anex_creador = "'".$usua."'"; $anexo->anex_desc = "Adjunto: ". str_replace($adjuntos[$i], "", $adjuntos[$i]); $anexo->anex_nomb_archivo = $adjuntos[$i]; $auxnumero = $anexo->obtenerMaximoNumeroAnexo($nurad); $anexoCodigo = $anexo->anexarFilaRadicado($auxnumero); $file = $adjuntos[$i]; $destin = "../bodega/tmp/".$file; $newfile = "../bodega". $anexo->anexoRutaArchivo; if (!copy($destin, $newfile)) { echo "<font color=RED><B>No se Pudo Copiar el archivo < $file > ...</B></FONT><br>"; } } $i++; } } if (!$mail->Send()) { echo "<BR><BR><CENTER><font color=RED><B>Error enviando correo: " . $mail->ErrorInfo . "<br>Destinatario: " . $Email_usua . "</B></FONT></CENTER><br>"; //return false; $envioOk = "No"; }else{ $mail->ClearAddresses(); $mail->ClearAttachments(); $envioOk = "Si"; $sql_sgd_renv_codigo = "select SGD_RENV_CODIGO FROM SGD_RENV_REGENVIO ORDER BY SGD_RENV_CODIGO DESC "; $rsRegenvio = $db->conn->SelectLimit($sql_sgd_renv_codigo,2); $nextval = $rsRegenvio->fields["SGD_RENV_CODIGO"]; $nextval++; //$db->conn->debug= true; $fechaActual = $db->conn->OffsetDate(0,$db->conn->sysTimeStamp); $destinatarios = "Destino:".$_POST["destinatario"]." Copia:".$_POST["concopia"]; $dependencia = $_POST["depecodi"]; $iSqlEnvio = "INSERT INTO SGD_RENV_REGENVIO(SGD_RENV_CODIGO ,SGD_FENV_CODIGO,SGD_RENV_FECH,RADI_NUME_SAL,SGD_RENV_DESTINO,SGD_RENV_MAIL ,SGD_RENV_PESO,SGD_RENV_VALOR,SGD_RENV_ESTADO,USUA_DOC,SGD_RENV_NOMBRE ,SGD_RENV_PLANILLA,SGD_RENV_FECH_SAL,DEPE_CODI,SGD_DIR_TIPO,RADI_NUME_GRUPO,SGD_RENV_DIR ,SGD_RENV_CANTIDAD,SGD_RENV_TIPO,SGD_RENV_OBSERVA ,SGD_RENV_GRUPO,SGD_RENV_VALORTOTAL,SGD_RENV_VALISTAMIENTO,SGD_RENV_VDESCUENTO,SGD_RENV_VADICIONAL,SGD_DEPE_GENERA,SGD_RENV_PAIS,SGD_RENV_NUMGUIA) VALUES ($nextval ,106 ,$fechaActual ,$verradicado2,'$destinatarios' ,'$destinatarios','0','0',1,".$_SESSION["usua_doc"]." ,'".$_POST["destinatario"]."', '0' ,$fechaActual ,".$dependencia.", 1,$verradicado2 ,'$destinatarios' ,1 ,1 ,'Envio Respuesta Rapida a Correo Electronico' ,$verradicado2 ,'0','0','0','0' ,$dependencia ,'Colombia' ,'0')"; $rsRegenvio = $db->conn->query($iSqlEnvio); return $envioOk; } } if ($adjuntos != NULL){ $i=0; echo "<br><b>Adjuntos Enviados!".$verradicado2."</b><br>"; while($i < count($adjuntos)){ IF(unlink($adjuntos[$i])) ECHO "".$adjuntos[$i]."<br>"; $i++; } } ?> </td> </tr> <tr> <td align="center"> <? $isqlDepR = "SELECT RADI_DEPE_ACTU, RADI_USUA_ACTU FROM RADICADO WHERE RADI_NUME_RADI = '$nurad'"; $rsDepR = $db->conn->Execute($isqlDepR); if ($rsDepR === false) { echo "Error de Consulta"; echo $db->conn->ErrorMsg(); exit(1); } $coddepe = $rsDepR->fields['RADI_DEPE_ACTU']; $codusua = $rsDepR->fields['RADI_USUA_ACTU']; $ind_ProcAnex="N"; $tsub = 0; $codserie = 0; ?> <iframe src="../radicacion/tipificar_documento.php?nurad=<? echo $nurad;?>&dependencia=<? echo $coddepe;?>&krd=<? echo $krd;?>" width=100% height=400></iframe> <form><p> <input type="button" value="Salir" class="botones" onclick="window.close();"> </p> </form> </td> </tr> </table> </center> <? unset($_SESSION["archivosAdjuntos"]); if($resultadoEnvio=="Si") { unset($_SESSION["archivosAdjuntos"]); echo "<script> alert('Se ha recibido la solicitud de Envio Correctamente. Si hay algun problema en el envio, el servidor de correo le informar posteriormente.') </script>"; } ?> </body> </html>
anicma/orfeo
respuesta_rapida/construccionRespuestaRapida.php
PHP
gpl-3.0
22,003
/* * SslSocket.cpp * * Created on: Apr 6, 2014 * Author: lion */ #include "SslSocket.h" #include "Stream.h" #include "PKey.h" namespace fibjs { result_t SslSocket_base::_new(X509Cert_base *crt, PKey_base *key, obj_ptr<SslSocket_base> &retVal) { obj_ptr<SslSocket> ss = new SslSocket(); result_t hr = ss->setCert(crt, key); if (hr < 0) return hr; retVal = ss; return 0; } result_t SslSocket_base::_new(v8::Local<v8::Array> certs, obj_ptr<SslSocket_base> &retVal) { obj_ptr<SslSocket> ss = new SslSocket(); int32_t sz = certs->Length(); if (sz) { v8::Local<v8::Value> sCrt = v8::String::NewFromUtf8(isolate, "crt", v8::String::kNormalString, 3); v8::Local<v8::Value> sKey = v8::String::NewFromUtf8(isolate, "key", v8::String::kNormalString, 3); int32_t i; for (i = 0; i < sz; i ++) { v8::Local<v8::Value> v = certs->Get(i); if (v->IsObject()) { v8::Local<v8::Object> o = v->ToObject(); obj_ptr<X509Cert_base> crt = X509Cert_base::getInstance(o->Get(sCrt)); if (!crt) return CALL_E_INVALIDARG; obj_ptr<PKey_base> key = PKey_base::getInstance(o->Get(sKey)); if (!key) return CALL_E_INVALIDARG; result_t hr = ss->setCert(crt, key); if (hr < 0) return hr; } else return CALL_E_INVALIDARG; } } retVal = ss; return 0; } SslSocket::SslSocket() { ssl_init(&m_ssl); ssl_set_authmode(&m_ssl, g_ssl.m_authmode); ssl_set_rng(&m_ssl, ctr_drbg_random, &g_ssl.ctr_drbg); ssl_set_bio(&m_ssl, my_recv, this, my_send, this); m_recv_pos = 0; } SslSocket::~SslSocket() { ssl_free(&m_ssl); memset(&m_ssl, 0, sizeof(m_ssl)); } result_t SslSocket::setCert(X509Cert_base *crt, PKey_base *key) { result_t hr; bool priv; hr = key->isPrivate(priv); if (hr < 0) return hr; if (!priv) return CALL_E_INVALIDARG; int ret = ssl_set_own_cert(&m_ssl, &((X509Cert *)crt)->m_crt, &((PKey *)key)->m_key); if (ret != 0) return _ssl::setError(ret); m_crts.push_back(crt); m_keys.push_back(key); return 0; } int SslSocket::my_recv(unsigned char *buf, size_t len) { if (!len) return 0; if (m_recv_pos < 0) return POLARSSL_ERR_NET_CONN_RESET; if (m_recv_pos == m_recv.length()) { m_recv_pos = 0; m_recv.resize(0); return POLARSSL_ERR_NET_WANT_READ; } if (len > m_recv.length() - m_recv_pos) len = m_recv.length() - m_recv_pos; memcpy(buf, m_recv.c_str() + m_recv_pos, len); m_recv_pos += (int)len; return (int)len; } int SslSocket::my_recv(void *ctx, unsigned char *buf, size_t len) { return ((SslSocket *)ctx)->my_recv(buf, len); } int SslSocket::my_send(const unsigned char *buf, size_t len) { if (!len) return 0; if (m_send.length() > 8192) return POLARSSL_ERR_NET_WANT_WRITE; m_send.append((const char *)buf, len); return (int)len; } int SslSocket::my_send(void *ctx, const unsigned char *buf, size_t len) { return ((SslSocket *)ctx)->my_send(buf, len); } result_t SslSocket::read(int32_t bytes, obj_ptr<Buffer_base> &retVal, exlib::AsyncEvent *ac) { class asyncRead: public asyncSsl { public: asyncRead(SslSocket *pThis, int32_t bytes, obj_ptr<Buffer_base> &retVal, exlib::AsyncEvent *ac) : asyncSsl(pThis, ac), m_bytes(bytes), m_retVal(retVal) { if (m_bytes == -1) m_bytes = 8192; m_buf.resize(m_bytes); } public: virtual int process() { int ret = ssl_read(&m_pThis->m_ssl, (unsigned char *)&m_buf[0], m_bytes); if (ret > 0) { m_buf.resize(ret); m_retVal = new Buffer(m_buf); return 0; } if (ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE) return ret; m_pThis->m_send.resize(0); return 0; } virtual int finally() { return m_retVal ? 0 : CALL_RETURN_NULL; } private: int32_t m_bytes; std::string m_buf; obj_ptr<Buffer_base> &m_retVal; }; if (!m_s) return CALL_E_INVALID_CALL; if (!ac) return CALL_E_NOSYNC; return (new asyncRead(this, bytes, retVal, ac))->post(0); } result_t SslSocket::write(Buffer_base *data, exlib::AsyncEvent *ac) { class asyncWrite: public asyncSsl { public: asyncWrite(SslSocket *pThis, Buffer_base *data, exlib::AsyncEvent *ac) : asyncSsl(pThis, ac) { data->toString(m_buf); } public: virtual int process() { int ret = ssl_write(&m_pThis->m_ssl, (const unsigned char *)m_buf.c_str(), m_buf.length()); if (ret == m_buf.length()) return 0; return ret; } private: std::string m_buf; }; if (!m_s) return CALL_E_INVALID_CALL; if (!ac) return CALL_E_NOSYNC; return (new asyncWrite(this, data, ac))->post(0); } result_t SslSocket::close(exlib::AsyncEvent *ac) { class asyncClose: public asyncSsl { public: asyncClose(SslSocket *pThis, exlib::AsyncEvent *ac) : asyncSsl(pThis, ac) { } public: virtual int process() { return ssl_close_notify(&m_pThis->m_ssl); } }; if (!m_s) return CALL_E_INVALID_CALL; if (!ac) return CALL_E_NOSYNC; return (new asyncClose(this, ac))->post(0); } result_t SslSocket::copyTo(Stream_base *stm, int64_t bytes, int64_t &retVal, exlib::AsyncEvent *ac) { return copyStream(this, stm, bytes, retVal, ac); } result_t SslSocket::get_verification(int32_t &retVal) { retVal = m_ssl.authmode; return 0; } result_t SslSocket::set_verification(int32_t newVal) { if (newVal < ssl_base::_VERIFY_NONE || newVal > ssl_base::_VERIFY_REQUIRED) return CALL_E_INVALIDARG; ssl_set_authmode(&m_ssl, newVal); return 0; } result_t SslSocket::get_ca(obj_ptr<X509Cert_base> &retVal) { if (!m_ca) m_ca = new X509Cert(); retVal = m_ca; return 0; } result_t SslSocket::get_peerCert(obj_ptr<X509Cert_base> &retVal) { const x509_crt *crt = ssl_get_peer_cert(&m_ssl); if (!crt) return CALL_RETURN_NULL; obj_ptr<X509Cert> crtObject = new X509Cert(); result_t hr = crtObject->load(crt); if (hr < 0) return hr; retVal = crtObject; return 0; } result_t SslSocket::handshake(int32_t *retVal, exlib::AsyncEvent *ac) { class asyncHandshake: public asyncSsl { public: asyncHandshake(SslSocket *pThis, int32_t *retVal, exlib::AsyncEvent *ac) : asyncSsl(pThis, ac), m_retVal(retVal) { } public: virtual int process() { return ssl_handshake(&m_pThis->m_ssl); } virtual int finally() { if (m_retVal) *m_retVal = ssl_get_verify_result(&m_pThis->m_ssl); return 0; } private: int32_t *m_retVal; }; return (new asyncHandshake(this, retVal, ac))->post(0); } result_t SslSocket::connect(Stream_base *s, const char *server_name, int32_t &retVal, exlib::AsyncEvent *ac) { if (m_s) return CALL_E_INVALID_CALL; if (!ac) return CALL_E_NOSYNC; m_s = s; ssl_set_endpoint(&m_ssl, SSL_IS_CLIENT); if (!m_ca) m_ca = g_ssl.m_ca; ssl_set_ca_chain(&m_ssl, &m_ca->m_crt, NULL, NULL); if (server_name && *server_name) ssl_set_hostname(&m_ssl, server_name); return handshake(&retVal, ac); } result_t SslSocket::accept(Stream_base *s, obj_ptr<SslSocket_base> &retVal, exlib::AsyncEvent *ac) { if (m_s) return CALL_E_INVALID_CALL; if (!ac) return CALL_E_NOSYNC; obj_ptr<SslSocket> ss = new SslSocket(); retVal = ss; int sz = (int)m_crts.size(); int i; result_t hr; for (i = 0; i < sz; i ++) { hr = ss->setCert(m_crts[i], m_keys[i]); if (hr < 0) return hr; } ss->m_s = s; ssl_set_authmode(&ss->m_ssl, m_ssl.authmode); ssl_set_endpoint(&ss->m_ssl, SSL_IS_SERVER); if (m_ca) { ss->m_ca = m_ca; ssl_set_ca_chain(&ss->m_ssl, &m_ca->m_crt, NULL, NULL); } ssl_set_session_cache(&ss->m_ssl, ssl_cache_get, &g_ssl.m_cache, ssl_cache_set, &g_ssl.m_cache); return ss->handshake(NULL, ac); } }
jiachenning/fibjs
fibjs/src/SslSocket.cpp
C++
gpl-3.0
9,212
# xspf-tools Tools for manipulating and creating [xspf](http://xspf.org/) playlists (e.g. VLC Player Playlists) | Travis | Jenkins | | --- | --- | | [![Build Status](https://travis-ci.org/thedava/xspf-tools.svg?branch=master)](https://travis-ci.org/thedava/xspf-tools) | [![Build Status](https://jenkins.davahome.net/buildStatus/icon?job=thedava%2Fxspf-tools%2Fmaster&style=plastic)](#) | See the full documentation in the [wiki](https://github.com/thedava/xspf-tools/wiki).
thedava/xspf-tools
README.md
Markdown
gpl-3.0
478
/* * Copyright (C) 2011-2013 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2013 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (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/>. */ /* ScriptData SDName: Boss_Flamegor SD%Complete: 100 SDComment: SDCategory: Blackwing Lair EndScriptData */ #include "ScriptPCH.h" enum Emotes { EMOTE_FRENZY = -1469031 }; enum Spells { SPELL_SHADOWFLAME = 22539, SPELL_WINGBUFFET = 23339, SPELL_FRENZY = 23342 //This spell periodically triggers fire nova }; class boss_flamegor : public CreatureScript { public: boss_flamegor() : CreatureScript("boss_flamegor") { } CreatureAI* GetAI(Creature* creature) const { return new boss_flamegorAI (creature); } struct boss_flamegorAI : public ScriptedAI { boss_flamegorAI(Creature* creature) : ScriptedAI(creature) {} uint32 ShadowFlame_Timer; uint32 WingBuffet_Timer; uint32 Frenzy_Timer; void Reset() { ShadowFlame_Timer = 21000; //These times are probably wrong WingBuffet_Timer = 35000; Frenzy_Timer = 10000; } void EnterCombat(Unit* /*who*/) { DoZoneInCombat(); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; //ShadowFlame_Timer if (ShadowFlame_Timer <= diff) { DoCast(me->getVictim(), SPELL_SHADOWFLAME); ShadowFlame_Timer = urand(15000, 22000); } else ShadowFlame_Timer -= diff; //WingBuffet_Timer if (WingBuffet_Timer <= diff) { DoCast(me->getVictim(), SPELL_WINGBUFFET); if (DoGetThreat(me->getVictim())) DoModifyThreatPercent(me->getVictim(), -75); WingBuffet_Timer = 25000; } else WingBuffet_Timer -= diff; //Frenzy_Timer if (Frenzy_Timer <= diff) { DoScriptText(EMOTE_FRENZY, me); DoCast(me, SPELL_FRENZY); Frenzy_Timer = urand(8000, 10000); } else Frenzy_Timer -= diff; DoMeleeAttackIfReady(); } }; }; void AddSC_boss_flamegor() { new boss_flamegor(); }
Crash911/RaptoredSkyFire
src/server/scripts/EasternKingdoms/BlackwingLair/boss_flamegor.cpp
C++
gpl-3.0
3,098
/**************************************************************************** ** ** Copyright (C) 2017-2019 N7 Space sp. z o. o. ** Contact: http://n7space.com ** ** This file is part of ASN.1/ACN Plugin for QtCreator. ** ** Plugin was developed under a programme and funded by ** European Space Agency. ** ** This Plugin 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 Plugin is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ** ****************************************************************************/ #include "visitor.h" using namespace Asn1Acn::Internal::Data; Visitor::~Visitor() {}
n7mobile/asn1scc.IDE
src/data/visitor.cpp
C++
gpl-3.0
1,119
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using OpenHardwareMonitor.Hardware; namespace TempAlert.Client { public partial class MainForm : Form { private Computer computer = new Computer(); private float currentMaxTemp = 0; private DateTime nextAlert = DateTime.UtcNow; private bool alerting = true; private ConfigSet config; public MainForm() { InitializeComponent(); this.FormClosing += MainForm_FormClosing; computer.CPUEnabled = true; computer.GPUEnabled = true; computer.MainboardEnabled = true; computer.HDDEnabled = true; computer.RAMEnabled = true; computer.Open(); UpdateTemps(); updateTimer.Tick += UpdateTemps_Tick; updateTimer.Enabled = true; config = new ConfigSet(); } private void UpdateTemps_Tick(object sender, EventArgs e) { UpdateTemps(); HighTemperatureAlertCheck(); } private void UpdateTemps() { var readingsText = new StringBuilder(); var tempList = new List<ISensor>(); foreach (var hardware in computer.Hardware) { hardware.Update(); var tempsensors = hardware.Sensors.Where(s => s.SensorType == SensorType.Temperature); if (tempsensors.Count() == 0) { // nothing to show for this device continue; } readingsText.AppendLine(hardware.Name + ":"); foreach (var sensor in tempsensors) { if (sensor.Value.HasValue) { tempList.Add(sensor); readingsText.AppendLine(sensor.Name + " is @ " + sensor.Value + "°C"); } } readingsText.AppendLine("-----"); } sensorReadingsTextBox.Text = readingsText.ToString(); if (tempList.Count > 0) { currentMaxTemp = tempList.Max(t => t.Value).Value; maxTempLabel.Text = currentMaxTemp.ToString() + "°C"; } else { maxTempLabel.ResetText(); } } private void HighTemperatureAlertCheck() { if (nextAlert > DateTime.UtcNow || !alerting) { return; } if (currentMaxTemp > config.UpperThreshold) { HighTemperatureAlert(currentMaxTemp); } } private void HighTemperatureAlert(float max) { alerting = false; MessageBox.Show("A device is reporting abnormally high temperatures. It is reporting a temperature of " + max.ToString() + "°C", "TempAlert Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); nextAlert = DateTime.UtcNow.AddMinutes(5); alerting = true; } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { this.Hide(); e.Cancel = true; notifyIcon.ShowBalloonTip(0, "TempAlert is still running", "TempAlert is continuing to monitor your computer in the background.", ToolTipIcon.Info); } } private void QuitToolStripMenuItem_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure you want to quit? This will stop monitoring.", "Quit?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Application.Exit(); } } private void NotifyIcon_DoubleClick(object sender, EventArgs e) { this.Show(); } private void MainForm_FormClosing(object sender, EventArgs e) { notifyIcon.Dispose(); } private void MinsToolStripMenuItem_Click(object sender, EventArgs e) { nextAlert = DateTime.UtcNow + TimeSpan.FromMinutes(10); } private void Snooze1hrToolStrip_Click(object sender, EventArgs e) { nextAlert = DateTime.UtcNow + TimeSpan.FromHours(1); } private void SnoozeTillRebootToolStrip_Click(object sender, EventArgs e) { alerting = false; } private void AboutToolStripMenuItem_Click(object sender, EventArgs e) { new AboutBox().ShowDialog(); } private void ShowCurrentToolStripMenuItem_Click(object sender, EventArgs e) { new ShowConfig(config).ShowDialog(); } private void ReloadToolStripMenuItem_Click(object sender, EventArgs e) { config.Reload(); } } }
rphi/TempAlert
TempAlert/MainForm.cs
C#
gpl-3.0
5,255
/* * Copyright (C) 2008-2009 Julien Danjou <julien@danjou.info> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. * * Except as contained in this notice, the names of the authors or * their institutions shall not be used in advertising or otherwise to * promote the sale, use or other dealings in this Software without * prior written authorization from the authors. */ /** * @defgroup xcb__event_t XCB Event Functions * * These functions ease the handling of X events received. * * @{ */ #ifndef __XCB_EVENT_H__ #define __XCB_EVENT_H__ #include <xcb/xcb.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Bit mask to find event type regardless of event source. * * Each event in the X11 protocol contains an 8-bit type code. * The most-significant bit in this code is set if the event was * generated from a SendEvent request. This mask can be used to * determine the type of event regardless of how the event was * generated. See the X11R6 protocol specification for details. */ #define XCB_EVENT_RESPONSE_TYPE_MASK (0x7f) #define XCB_EVENT_RESPONSE_TYPE(e) (e->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) #define XCB_EVENT_SENT(e) (e->response_type & ~XCB_EVENT_RESPONSE_TYPE_MASK) #define XCB_EVENT_ERROR_TYPE(e) (*((uint8_t *) e + 1)) #define XCB_EVENT_REQUEST_TYPE(e) (*((uint8_t *) e + 10)) typedef int (*xcb_generic_event_handler_t)(void *data, xcb_connection_t *c, xcb_generic_event_t *event); typedef int (*xcb_generic_error_handler_t)(void *data, xcb_connection_t *c, xcb_generic_error_t *error); typedef struct xcb_event_handler xcb_event_handler_t; struct xcb_event_handler { xcb_generic_event_handler_t handler; void *data; }; typedef struct xcb_event_handlers xcb_event_handlers_t; struct xcb_event_handlers { xcb_event_handler_t event[126]; xcb_event_handler_t error[256]; xcb_connection_t *c; }; /** * @brief Initialize event handlers data structure. * @param c The connection to the X server. * @param evenths A pointer to the event handler data structure to initialize. */ void xcb_event_handlers_init(xcb_connection_t *c, xcb_event_handlers_t *evenths); /** * @brief Get X connection used in event handlers. * @param evenths The event handlers. * @return The connection to the X server. */ xcb_connection_t *xcb_event_get_xcb_connection(xcb_event_handlers_t *evenths); /** * @brief Wait for event and handle it with event handler. * @param evenths The event handlers. */ void xcb_event_wait_for_event_loop(xcb_event_handlers_t *evenths); /** * @brief Poll for event and handle it with event handler. * @param evenths The event handlers. */ void xcb_event_poll_for_event_loop(xcb_event_handlers_t *evenths); /** * @brief Handle an event using event handlers from event handlers data * structure. * @param evenths The event handlers. * @param event The event to handle. * @return The return value of the handler, or 0 if no handler exists for this * event. */ int xcb_event_handle(xcb_event_handlers_t *evenths, xcb_generic_event_t *event); /** * @brief Set an event handler for an event type. * @param evenths The event handlers data structure. * @param event The event type. * @param handler The callback function to call for this event type. * @param data Optional data pointer to pass to handler callback function. */ void xcb_event_set_handler(xcb_event_handlers_t *evenths, int event, xcb_generic_event_handler_t handler, void *data); /** * @brief Set an error handler for an error type. * @param evenths The error handlers data structure. * @param error The error type. * @param handler The callback function to call for this error type. * @param data Optional data pointer to pass to handler callback function. */ void xcb_event_set_error_handler(xcb_event_handlers_t *evenths, int error, xcb_generic_error_handler_t handler, void *data); #define XCB_EVENT_MAKE_EVENT_HANDLER(lkind, ukind) \ static inline void xcb_event_set_##lkind##_handler(xcb_event_handlers_t *evenths, int (*handler)(void *, xcb_connection_t *, xcb_##lkind##_event_t *), void *data) \ { \ xcb_event_set_handler(evenths, XCB_##ukind, (xcb_generic_event_handler_t) handler, data); \ } XCB_EVENT_MAKE_EVENT_HANDLER(key_press, KEY_PRESS) XCB_EVENT_MAKE_EVENT_HANDLER(key_release, KEY_RELEASE) XCB_EVENT_MAKE_EVENT_HANDLER(button_press, BUTTON_PRESS) XCB_EVENT_MAKE_EVENT_HANDLER(button_release, BUTTON_RELEASE) XCB_EVENT_MAKE_EVENT_HANDLER(motion_notify, MOTION_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(enter_notify, ENTER_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(leave_notify, LEAVE_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(focus_in, FOCUS_IN) XCB_EVENT_MAKE_EVENT_HANDLER(focus_out, FOCUS_OUT) XCB_EVENT_MAKE_EVENT_HANDLER(keymap_notify, KEYMAP_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(expose, EXPOSE) XCB_EVENT_MAKE_EVENT_HANDLER(graphics_exposure, GRAPHICS_EXPOSURE) XCB_EVENT_MAKE_EVENT_HANDLER(no_exposure, NO_EXPOSURE) XCB_EVENT_MAKE_EVENT_HANDLER(visibility_notify, VISIBILITY_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(create_notify, CREATE_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(destroy_notify, DESTROY_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(unmap_notify, UNMAP_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(map_notify, MAP_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(map_request, MAP_REQUEST) XCB_EVENT_MAKE_EVENT_HANDLER(reparent_notify, REPARENT_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(configure_notify, CONFIGURE_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(configure_request, CONFIGURE_REQUEST) XCB_EVENT_MAKE_EVENT_HANDLER(gravity_notify, GRAVITY_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(resize_request, RESIZE_REQUEST) XCB_EVENT_MAKE_EVENT_HANDLER(circulate_notify, CIRCULATE_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(circulate_request, CIRCULATE_REQUEST) XCB_EVENT_MAKE_EVENT_HANDLER(property_notify, PROPERTY_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(selection_clear, SELECTION_CLEAR) XCB_EVENT_MAKE_EVENT_HANDLER(selection_request, SELECTION_REQUEST) XCB_EVENT_MAKE_EVENT_HANDLER(selection_notify, SELECTION_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(colormap_notify, COLORMAP_NOTIFY) XCB_EVENT_MAKE_EVENT_HANDLER(client_message, CLIENT_MESSAGE) XCB_EVENT_MAKE_EVENT_HANDLER(mapping_notify, MAPPING_NOTIFY) /** Everyting is ok */ #define XCB_EVENT_ERROR_SUCESS 0 /** Bad request code */ #define XCB_EVENT_ERROR_BAD_REQUEST 1 /** Int parameter out of range */ #define XCB_EVENT_ERROR_BAD_VALUE 2 /** Parameter not a Window */ #define XCB_EVENT_ERROR_BAD_WINDOW 3 /** Parameter not a Pixmap */ #define XCB_EVENT_ERROR_BAD_PIXMAP 4 /** Parameter not an Atom */ #define XCB_EVENT_ERROR_BAD_ATOM 5 /** Parameter not a Cursor */ #define XCB_EVENT_ERROR_BAD_CURSOR 6 /** Parameter not a Font */ #define XCB_EVENT_ERROR_BAD_FONT 7 /** Parameter mismatch */ #define XCB_EVENT_ERROR_BAD_MATCH 8 /** Parameter not a Pixmap or Window */ #define XCB_EVENT_ERROR_BAD_DRAWABLE 9 /* Depending on context: - key/button already grabbed - attempt to free an illegal cmap entry - attempt to store into a read-only color map entry. - attempt to modify the access control list from other than the local host. */ #define XCB_EVENT_ERROR_BAD_ACCESS 10 /** Insufficient resources */ #define XCB_EVENT_ERROR_BAD_ALLOC 11 /** No such colormap */ #define XCB_EVENT_ERROR_BAD_COLOR 12 /** Parameter not a GC */ #define XCB_EVENT_ERROR_BAD_GC 13 /** Choice not in range or already used */ #define XCB_EVENT_ERROR_BAD_ID_CHOICE 14 /** Font or color name doesn't exist */ #define XCB_EVENT_ERROR_BAD_NAME 15 /** Request length incorrect */ #define XCB_EVENT_ERROR_BAD_LENGTH 16 /** Server is defective */ #define XCB_EVENT_ERROR_BAD_IMPLEMENTATION 17 /** * @brief Convert an event reponse type to a label. * @param type The event type. * @return A string with the event name, or NULL if unknown. */ const char * xcb_event_get_label(uint8_t type); /** * @brief Convert an event error type to a label. * @param type The erro type. * @return A string with the event name, or NULL if unknown or if the event is * not an error. */ const char * xcb_event_get_error_label(uint8_t type); /** * @brief Convert an event request type to a label. * @param type The request type. * @return A string with the event name, or NULL if unknown or if the event is * not an error. */ const char * xcb_event_get_request_label(uint8_t type); #ifdef __cplusplus } #endif /** * @} */ #endif /* __XCB_EVENT_H__ */
chriskmanx/qmole
XORG2/xcb-util-0.3.5/event/xcb_event.h
C
gpl-3.0
9,370
# rasPyCNCController # Copyright 2016 Francesco Santini <francesco.santini@gmail.com> # # This file is part of rasPyCNCController. # # rasPyCNCController 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. # # rasPyCNCController 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 rasPyCNCController. If not, see <http://www.gnu.org/licenses/>. from PySide import QtCore from GCodeAnalyzer import GCodeAnalyzer import sys import pycnc_config class GCodeLoader(QtCore.QThread): load_finished = QtCore.Signal() load_error = QtCore.Signal(object) def __init__(self): QtCore.QThread.__init__(self) self.file = None self.gcode = None self.times = None self.bBox = None self.loaded = False self.totalTime = 0 self.busy = False self.g0_feed = pycnc_config.G0_FEED def run(self): self.loaded = False self.gcode = [] self.times = [] self.bBox = None self.totalTime = 0 self.busy = True analyzer = GCodeAnalyzer() analyzer.fastf = self.g0_feed try: with open(self.file) as f: for line in f: analyzer.Analyze(line) self.gcode.append(line) self.times.append(analyzer.getTravelTime()*60) # time returned is in minutes: convert to seconds except: self.busy = False e = sys.exc_info()[0] self.load_error.emit("%s" % e) return self.busy = False self.loaded = True self.totalTime = self.times[-1] self.bBox = analyzer.getBoundingBox() self.load_finished.emit() def load(self, file): self.file = file self.start()
fsantini/rasPyCNCController
gcode/GCodeLoader.py
Python
gpl-3.0
2,216
using System; namespace Server.Items { public class TransientItem : Item { private TimeSpan m_LifeSpan; [CommandProperty( AccessLevel.GameMaster )] public TimeSpan LifeSpan { get { return m_LifeSpan; } set { m_LifeSpan = value; if ( m_Timer != null ) m_Timer.Stop(); m_CreationTime = DateTime.UtcNow; m_Timer = Timer.DelayCall( TimeSpan.FromSeconds( 5 ), TimeSpan.FromSeconds( 5 ), new TimerCallback( CheckExpiry ) ); } } private DateTime m_CreationTime; [CommandProperty( AccessLevel.GameMaster )] public DateTime CreationTime { get { return m_CreationTime; } set { m_CreationTime = value; } } private Timer m_Timer; public virtual void Expire( Mobile parent ) { if ( parent != null ) parent.SendLocalizedMessage( 1072515, ( this.Name == null ? string.Format( "#{0}", LabelNumber ) : this.Name ) ); // The ~1_name~ expired... Effects.PlaySound( GetWorldLocation(), Map, 0x201 ); this.Delete(); } public virtual void SendTimeRemainingMessage( Mobile to ) { to.SendLocalizedMessage( 1072516, String.Format( "{0}\t{1}", ( this.Name == null ? string.Format( "#{0}", LabelNumber ) : this.Name ), (int) m_LifeSpan.TotalSeconds ) ); // ~1_name~ will expire in ~2_val~ seconds! } public override void OnDelete() { if ( m_Timer != null ) m_Timer.Stop(); base.OnDelete(); } public virtual void CheckExpiry() { if ( ( m_CreationTime + m_LifeSpan ) < DateTime.UtcNow ) Expire( RootParent as Mobile ); else InvalidateProperties(); } [Constructable] public TransientItem( int itemID, TimeSpan lifeSpan ) : base( itemID ) { m_CreationTime = DateTime.UtcNow; m_LifeSpan = lifeSpan; m_Timer = Timer.DelayCall( TimeSpan.FromSeconds( 5 ), TimeSpan.FromSeconds( 5 ), new TimerCallback( CheckExpiry ) ); } [Constructable] public TransientItem( int itemID ) : base( itemID ) { m_CreationTime = DateTime.MinValue; m_LifeSpan = TimeSpan.Zero; } public TransientItem( Serial serial ) : base( serial ) { } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( m_Timer != null ) { TimeSpan remaining = ( ( m_CreationTime + m_LifeSpan ) - DateTime.UtcNow ); list.Add( 1072517, ( (int) remaining.TotalSeconds ).ToString() ); // Lifespan: ~1_val~ seconds } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); writer.Write( m_LifeSpan ); writer.Write( m_CreationTime ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */ reader.ReadInt(); m_LifeSpan = reader.ReadTimeSpan(); m_CreationTime = reader.ReadDateTime(); if ( m_LifeSpan != TimeSpan.Zero ) m_Timer = Timer.DelayCall( TimeSpan.FromSeconds( 5 ), TimeSpan.FromSeconds( 5 ), new TimerCallback( CheckExpiry ) ); } } }
GenerationOfWorlds/GOW
Scripts/Core/Mondains Legacy/Magic/Spellweaving/TransientItem.cs
C#
gpl-3.0
2,973
----------------------------------- -- Area: Dynamis Qufim -- MOB: Vanguard_Predator ----------------------------------- mixins = {require("scripts/mixins/job_special")} ----------------------------------- function onMobDeath(mob, player, isKiller) end
Hozu/darkstar
scripts/zones/Dynamis-Qufim/mobs/Vanguard_Predator.lua
Lua
gpl-3.0
254
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Introduction</title> <link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../lambda.html" title="Chapter&#160;11.&#160;Boost.Lambda"> <link rel="prev" href="getting_started.html" title="Getting Started"> <link rel="next" href="using_library.html" title="Using the library"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td> <td align="center"><a href="../../../index.html">Home</a></td> <td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="getting_started.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../lambda.html"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="using_library.html"><img src="../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h2 class="title" style="clear: both"> <a name="id2137131"></a>Introduction</h2></div></div></div> <div class="toc"><dl> <dt><span class="section"><a href="s03.html#id2137137">Motivation</a></span></dt> <dt><span class="section"><a href="s03.html#id2137398">Introduction to lambda expressions</a></span></dt> </dl></div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="id2137137"></a>Motivation</h3></div></div></div> <p>The Standard Template Library (STL) <a class="xref" href="../lambda.html#cit:stepanov:94" title="The Standard Template Library">[<abbr class="abbrev">STL94</abbr>]</a>, now part of the C++ Standard Library <a class="xref" href="../lambda.html#cit:c++:98" title="International Standard, Programming Languages &#8211; C++">[<abbr class="abbrev">C++98</abbr>]</a>, is a generic container and algorithm library. Typically STL algorithms operate on container elements via <span class="emphasis"><em>function objects</em></span>. These function objects are passed as arguments to the algorithms. </p> <p> Any C++ construct that can be called with the function call syntax is a function object. The STL contains predefined function objects for some common cases (such as <code class="literal">plus</code>, <code class="literal">less</code> and <code class="literal">not1</code>). As an example, one possible implementation for the standard <code class="literal">plus</code> template is: </p> <pre class="programlisting"> template &lt;class T&gt; struct plus : public binary_function&lt;T, T, T&gt; { T operator()(const T&amp; i, const T&amp; j) const { return i + j; } }; </pre> <p> The base class <code class="literal">binary_function&lt;T, T, T&gt;</code> contains typedefs for the argument and return types of the function object, which are needed to make the function object <span class="emphasis"><em>adaptable</em></span>. </p> <p> In addition to the basic function object classes, such as the one above, the STL contains <span class="emphasis"><em>binder</em></span> templates for creating a unary function object from an adaptable binary function object by fixing one of the arguments to a constant value. For example, instead of having to explicitly write a function object class like: </p> <pre class="programlisting"> class plus_1 { int _i; public: plus_1(const int&amp; i) : _i(i) {} int operator()(const int&amp; j) { return _i + j; } }; </pre> <p> the equivalent functionality can be achieved with the <code class="literal">plus</code> template and one of the binder templates (<code class="literal">bind1st</code>). E.g., the following two expressions create function objects with identical functionalities; when invoked, both return the result of adding <code class="literal">1</code> to the argument of the function object: </p> <pre class="programlisting"> plus_1(1) bind1st(plus&lt;int&gt;(), 1) </pre> <p> The subexpression <code class="literal">plus&lt;int&gt;()</code> in the latter line is a binary function object which computes the sum of two integers, and <code class="literal">bind1st</code> invokes this function object partially binding the first argument to <code class="literal">1</code>. As an example of using the above function object, the following code adds <code class="literal">1</code> to each element of some container <code class="literal">a</code> and outputs the results into the standard output stream <code class="literal">cout</code>. </p> <pre class="programlisting"> transform(a.begin(), a.end(), ostream_iterator&lt;int&gt;(cout), bind1st(plus&lt;int&gt;(), 1)); </pre> <p> </p> <p> To make the binder templates more generally applicable, the STL contains <span class="emphasis"><em>adaptors</em></span> for making pointers or references to functions, and pointers to member functions, adaptable. Finally, some STL implementations contain function composition operations as extensions to the standard <a class="xref" href="../lambda.html#cit:sgi:02" title="The SGI Standard Template Library">[<abbr class="abbrev">SGI02</abbr>]</a>. </p> <p> All these tools aim at one goal: to make it possible to specify <span class="emphasis"><em>unnamed functions</em></span> in a call of an STL algorithm, in other words, to pass code fragments as an argument to a function. However, this goal is attained only partially. The simple example above shows that the definition of unnamed functions with the standard tools is cumbersome. Complex expressions involving functors, adaptors, binders and function composition operations tend to be difficult to comprehend. In addition to this, there are significant restrictions in applying the standard tools. E.g. the standard binders allow only one argument of a binary function to be bound; there are no binders for 3-ary, 4-ary etc. functions. </p> <p> The Boost Lambda Library provides solutions for the problems described above: </p> <div class="itemizedlist"><ul class="itemizedlist" type="disc"> <li class="listitem"> <p> Unnamed functions can be created easily with an intuitive syntax. The above example can be written as: </p> <pre class="programlisting"> transform(a.begin(), a.end(), ostream_iterator&lt;int&gt;(cout), 1 + _1); </pre> <p> or even more intuitively: </p> <pre class="programlisting"> for_each(a.begin(), a.end(), cout &lt;&lt; (1 + _1)); </pre> <p> </p> </li> <li class="listitem"><p> Most of the restrictions in argument binding are removed, arbitrary arguments of practically any C++ function can be bound. </p></li> <li class="listitem"><p> Separate function composition operations are not needed, as function composition is supported implicitly. </p></li> </ul></div> <p> </p> </div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="id2137398"></a>Introduction to lambda expressions</h3></div></div></div> <div class="toc"><dl> <dt><span class="section"><a href="s03.html#lambda.partial_function_application">Partial function application</a></span></dt> <dt><span class="section"><a href="s03.html#lambda.terminology">Terminology</a></span></dt> </dl></div> <p> Lambda expression are common in functional programming languages. Their syntax varies between languages (and between different forms of lambda calculus), but the basic form of a lambda expressions is: </p> <pre class="programlisting"> lambda x<sub>1</sub> ... x<sub>n</sub>.e </pre> <p> A lambda expression defines an unnamed function and consists of: </p> <div class="itemizedlist"><ul class="itemizedlist" type="disc"> <li class="listitem"><p> the parameters of this function: <code class="literal">x<sub>1</sub> ... x<sub>n</sub></code>. </p></li> <li class="listitem"><p>the expression e which computes the value of the function in terms of the parameters <code class="literal">x<sub>1</sub> ... x<sub>n</sub></code>. </p></li> </ul></div> <p> A simple example of a lambda expression is </p> <pre class="programlisting"> lambda x y.x+y </pre> <p> Applying the lambda function means substituting the formal parameters with the actual arguments: </p> <pre class="programlisting"> (lambda x y.x+y) 2 3 = 2 + 3 = 5 </pre> <p> </p> <p> In the C++ version of lambda expressions the <code class="literal">lambda x<sub>1</sub> ... x<sub>n</sub></code> part is missing and the formal parameters have predefined names. In the current version of the library, there are three such predefined formal parameters, called <span class="emphasis"><em>placeholders</em></span>: <code class="literal">_1</code>, <code class="literal">_2</code> and <code class="literal">_3</code>. They refer to the first, second and third argument of the function defined by the lambda expression. For example, the C++ version of the definition </p> <pre class="programlisting">lambda x y.x+y</pre> <p> is </p> <pre class="programlisting">_1 + _2</pre> <p> </p> <p> Hence, there is no syntactic keyword for C++ lambda expressions. The use of a placeholder as an operand implies that the operator invocation is a lambda expression. However, this is true only for operator invocations. Lambda expressions containing function calls, control structures, casts etc. require special syntactic constructs. Most importantly, function calls need to be wrapped inside a <code class="literal">bind</code> function. As an example, consider the lambda expression: </p> <pre class="programlisting">lambda x y.foo(x,y)</pre> <p> Rather than <code class="literal">foo(_1, _2)</code>, the C++ counterpart for this expression is: </p> <pre class="programlisting">bind(foo, _1, _2)</pre> <p> We refer to this type of C++ lambda expressions as <span class="emphasis"><em>bind expressions</em></span>. </p> <p>A lambda expression defines a C++ function object, hence function application syntax is like calling any other function object, for instance: <code class="literal">(_1 + _2)(i, j)</code>. </p> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="lambda.partial_function_application"></a>Partial function application</h4></div></div></div> <p> A bind expression is in effect a <span class="emphasis"><em>partial function application</em></span>. In partial function application, some of the arguments of a function are bound to fixed values. The result is another function, with possibly fewer arguments. When called with the unbound arguments, this new function invokes the original function with the merged argument list of bound and unbound arguments. </p> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="lambda.terminology"></a>Terminology</h4></div></div></div> <p> A lambda expression defines a function. A C++ lambda expression concretely constructs a function object, <span class="emphasis"><em>a functor</em></span>, when evaluated. We use the name <span class="emphasis"><em>lambda functor</em></span> to refer to such a function object. Hence, in the terminology adopted here, the result of evaluating a lambda expression is a lambda functor. </p> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 1999-2004 Jaakko J&#228;rvi, Gary Powell<p>Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file <code class="filename">LICENSE_1_0.txt</code> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)</p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="getting_started.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../lambda.html"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="using_library.html"><img src="../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
gorkinovich/DefendersOfMankind
dependencies/boost-1.46.0/doc/html/lambda/s03.html
HTML
gpl-3.0
12,819
<? EWGLogout(WGSL("term","Session closed"),"Ok"); if (!WGisHTTPAuth()) { ?> <div class="WGWActivity" data-wgid="main"> <div class="sysLogout"><%<term_h>%><br><br> <a href="#_close()" class="WGButton">Ok</a></div> </div> <? } ?>
epto/webgui8
wwwroot/bin/app/webgui/logout.app/layout.php
PHP
gpl-3.0
237
/****************************/ /* THIS IS OPEN SOURCE CODE */ /****************************/ /** * @author Jose Pedro Oliveira * * test case for the linux-net component * * @brief * List all net events codes and names */ #include <stdio.h> #include <stdlib.h> #include "papi_test.h" int main (int argc, char **argv) { int retval,cid,numcmp; int total_events=0; int code; char event_name[PAPI_MAX_STR_LEN]; int r; const PAPI_component_info_t *cmpinfo = NULL; /* Set TESTS_QUIET variable */ tests_quiet( argc, argv ); /* PAPI Initialization */ retval = PAPI_library_init( PAPI_VER_CURRENT ); if ( retval != PAPI_VER_CURRENT ) { test_fail(__FILE__, __LINE__,"PAPI_library_init failed\n",retval); } if (!TESTS_QUIET) { printf("Listing all net events\n"); } numcmp = PAPI_num_components(); for(cid=0; cid<numcmp; cid++) { if ( (cmpinfo = PAPI_get_component_info(cid)) == NULL) { test_fail(__FILE__, __LINE__,"PAPI_get_component_info failed\n",-1); } if ( strstr(cmpinfo->name, "net") == NULL) { continue; } if (!TESTS_QUIET) { printf("Component %d (%d) - %d events - %s\n", cid, cmpinfo->CmpIdx, cmpinfo->num_native_events, cmpinfo->name); } code = PAPI_NATIVE_MASK; r = PAPI_enum_cmp_event( &code, PAPI_ENUM_FIRST, cid ); while ( r == PAPI_OK ) { retval = PAPI_event_code_to_name( code, event_name ); if ( retval != PAPI_OK ) { test_fail( __FILE__, __LINE__, "PAPI_event_code_to_name", retval ); } if (!TESTS_QUIET) { printf("0x%x %s\n", code, event_name); } total_events++; r = PAPI_enum_cmp_event( &code, PAPI_ENUM_EVENTS, cid ); } } if (total_events==0) { test_skip(__FILE__,__LINE__,"No net events found", 0); } test_pass( __FILE__, NULL, 0 ); return 0; } // vim:set ai ts=4 sw=4 sts=4 et:
drahoslavzan/MKP-PSO
libs/papi-5.1.0/src/components/net/tests/net_list_events.c
C
gpl-3.0
2,095
//--------------------------------------------------------------------------------------- // // ghc::filesystem - A C++17-like filesystem implementation for C++11/C++14 // //--------------------------------------------------------------------------------------- // // Copyright (c) 2018, Steffen Schümann <s.schuemann@pobox.com> // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //--------------------------------------------------------------------------------------- // fs_fwd.hpp - The forwarding header for the header/implementation seperated usage of // ghc::filesystem. // This file can be include at any place, where ghc::filesystem api is needed while // not bleeding implementation details (e.g. system includes) into the global namespace, // as long as one cpp includes fs_impl.hpp to deliver the matching implementations. //--------------------------------------------------------------------------------------- #ifndef GHC_FILESYSTEM_FWD_H #define GHC_FILESYSTEM_FWD_H #define GHC_FILESYSTEM_FWD #include <ghc/filesystem.hpp> #endif // GHC_FILESYSTEM_FWD_H
COMBINE-lab/pufferfish
include/ghc/fs_fwd.hpp
C++
gpl-3.0
2,574
/* Copyright (c) 2012, Lunar Workshop, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by Lunar Workshop, Inc. 4. Neither the name of the Lunar Workshop nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY LUNAR WORKSHOP INC ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LUNAR WORKSHOP BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LW_RAYTRACE_H #define LW_RAYTRACE_H #include <modelconverter/convmesh.h> #include <geometry.h> namespace raytrace { class CTraceResult { public: Vector m_vecHit; size_t m_iFace; CConversionMeshInstance* m_pMeshInstance; }; class CKDTri { public: CKDTri(); CKDTri(size_t v1, size_t v2, size_t v3, size_t iMeshInstanceVertsIndex, size_t iFace, CConversionMeshInstance* pMeshInstance = nullptr); public: size_t v[3]; size_t m_iMeshInstanceVertsIndex; size_t m_iFace; CConversionMeshInstance* m_pMeshInstance; }; class CKDNode { public: CKDNode(CKDNode* pParent = NULL, AABB oBounds = AABB(), class CKDTree* pTree = NULL); ~CKDNode(); public: // Reserves memory for triangles all at once, for faster allocation void ReserveTriangles(size_t iEstimatedTriangles); void AddTriangle(size_t v1, size_t v2, size_t v3, size_t iMeshInstanceVertsIndex, size_t iFace, CConversionMeshInstance* pMeshInstance); void RemoveArea(const AABB& oBox); void CalcBounds(); void BuildTriList(); void PassTriList(); void Build(); bool Raytrace(const Ray& rayTrace, CTraceResult* pTR = NULL); bool Raytrace(const Vector& vecStart, const Vector& vecEnd, CTraceResult* pTR = NULL); float Closest(const Vector& vecPoint); const CKDNode* GetLeftChild() const { return m_pLeft; }; const CKDNode* GetRightChild() const { return m_pRight; }; AABB GetBounds() const { return m_oBounds; }; size_t GetSplitAxis() const { return m_iSplitAxis; }; float GetSplitPos() const { return m_flSplitPos; }; protected: CKDNode* m_pParent; CKDNode* m_pLeft; CKDNode* m_pRight; CKDTree* m_pTree; size_t m_iDepth; tvector<CKDTri> m_aTris; size_t m_iTriangles; // This node and all child nodes AABB m_oBounds; size_t m_iSplitAxis; float m_flSplitPos; }; class CKDTree { friend class CKDNode; public: CKDTree(class CRaytracer* pTracer, size_t iMaxDepth = 15); ~CKDTree(); public: // Reserves memory for triangles all at once, for faster allocation void ReserveTriangles(size_t iEstimatedTriangles); void AddTriangle(size_t v1, size_t v2, size_t v3, size_t iMeshInstanceVertsIndex, size_t iFace, CConversionMeshInstance* pMeshInstance); void RemoveArea(const AABB& oBox); void BuildTree(); bool Raytrace(const Ray& rayTrace, CTraceResult* pTR = NULL); bool Raytrace(const Vector& vecStart, const Vector& vecEnd, CTraceResult* pTR = NULL); float Closest(const Vector& vecPoint); const CKDNode* GetTopNode() const { return m_pTop; }; bool IsBuilt() { return m_bBuilt; }; size_t GetMaxDepth() { return m_iMaxDepth; }; protected: class CRaytracer* m_pRaytracer; CKDNode* m_pTop; bool m_bBuilt; size_t m_iMaxDepth; }; class CRaytracer { friend class CKDNode; public: CRaytracer(CConversionScene* pScene = NULL, size_t iMaxDepth = 15); ~CRaytracer(); public: bool Raytrace(const Ray& rayTrace, CTraceResult* pTR = NULL); bool Raytrace(const Vector& vecStart, const Vector& vecEnd, CTraceResult* pTR = NULL); bool RaytraceBruteForce(const Ray& rayTrace, CTraceResult* pTR = NULL); float Closest(const Vector& vecPoint); void AddMeshesFromNode(CConversionSceneNode* pNode); void AddMeshInstance(CConversionMeshInstance* pMeshInstance); void BuildTree(); void RemoveArea(const AABB& oBox); const CKDTree* GetTree() const { return m_pTree; }; protected: CConversionScene* m_pScene; CKDTree* m_pTree; size_t m_iMaxDepth; tvector<tvector<Vector>> m_aaMeshInstanceVerts; }; }; #endif
BSVino/SMAK
raytracer/raytracer.h
C
gpl-3.0
5,370
<?php namespace SmartCat\Client\Normalizer; use Carbon\Carbon; class TranslationMemoryModelNormalizer extends AbstractNormalizer { public function supportsDenormalization($data, $type, $format = null) { if ($type !== 'SmartCat\\Client\\Model\\TranslationMemoryModel') { return false; } return true; } public function supportsNormalization($data, $format = null) { if ($data instanceof \SmartCat\Client\Model\TranslationMemoryModel) { return true; } return false; } public function denormalize($data, $class, $format = null, array $context = array()) { $object = new \SmartCat\Client\Model\TranslationMemoryModel(); if (property_exists($data, 'id')) { $object->setId($data->{'id'}); } if (property_exists($data, 'accountId')) { $object->setAccountId($data->{'accountId'}); } if (property_exists($data, 'clientId')) { $object->setClientId($data->{'clientId'}); } if (property_exists($data, 'name')) { $object->setName($data->{'name'}); } if (property_exists($data, 'description')) { $object->setDescription($data->{'description'}); } if (property_exists($data, 'sourceLanguage')) { $object->setSourceLanguage($data->{'sourceLanguage'}); } if (property_exists($data, 'targetLanguages')) { $values = array(); foreach ($data->{'targetLanguages'} as $value) { $values[] = $value; } $object->setTargetLanguages($values); } if (property_exists($data, 'createdDate')) { $object->setCreatedDate($data->{'createdDate'}); } if (property_exists($data, 'isAutomaticallyCreated')) { $object->setIsAutomaticallyCreated($data->{'isAutomaticallyCreated'}); } if (property_exists($data, 'unitCountByLanguageId')) { $values_1 = new \ArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS); foreach ($data->{'unitCountByLanguageId'} as $key => $value_1) { $values_1[$key] = $value_1; } $object->setUnitCountByLanguageId($values_1); } return $object; } public function normalize($object, $format = null, array $context = array()) { $data = new \stdClass(); if (null !== $object->getId()) { $data->{'id'} = $object->getId(); } if (null !== $object->getAccountId()) { $data->{'accountId'} = $object->getAccountId(); } if (null !== $object->getClientId()) { $data->{'clientId'} = $object->getClientId(); } if (null !== $object->getName()) { $data->{'name'} = $object->getName(); } if (null !== $object->getDescription()) { $data->{'description'} = $object->getDescription(); } if (null !== $object->getSourceLanguage()) { $data->{'sourceLanguage'} = $object->getSourceLanguage(); } if (null !== $object->getTargetLanguages()) { $values = array(); foreach ($object->getTargetLanguages() as $value) { $values[] = $value; } $data->{'targetLanguages'} = $values; } if (null !== $object->getCreatedDate()) { $data->{'createdDate'} = Carbon::parse($object->getCreatedDate())->toISOString(); } if (null !== $object->getIsAutomaticallyCreated()) { $data->{'isAutomaticallyCreated'} = $object->getIsAutomaticallyCreated(); } if (null !== $object->getUnitCountByLanguageId()) { $values_1 = new \stdClass(); foreach ($object->getUnitCountByLanguageId() as $key => $value_1) { $values_1->{$key} = $value_1; } $data->{'unitCountByLanguageId'} = $values_1; } return $data; } }
smartcatai/SmartCAT-API
src/SmartCAT/API/Normalizer/TranslationMemoryModelNormalizer.php
PHP
gpl-3.0
4,058
# Authors: Karl MacMillan <kmacmill@redhat.com> # # Copyright (C) 2007 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import absolute_import # pylint: disable=deprecated-module from optparse import ( Option, Values, OptionParser, IndentedHelpFormatter, OptionValueError) # pylint: enable=deprecated-module from copy import copy from configparser import SafeConfigParser from urllib.parse import urlsplit import socket import functools from dns.exception import DNSException import dns.name from ipaplatform.paths import paths from ipapython.dn import DN from ipapython.dnsutil import query_srv from ipapython.ipautil import CheckedIPAddress, CheckedIPAddressLoopback class IPAConfigError(Exception): def __init__(self, msg=''): self.msg = msg Exception.__init__(self, msg) def __repr__(self): return self.msg __str__ = __repr__ class IPAFormatter(IndentedHelpFormatter): """Our own optparse formatter that indents multiple lined usage string.""" def format_usage(self, usage): usage_string = "Usage:" spacing = " " * len(usage_string) lines = usage.split("\n") ret = "%s %s\n" % (usage_string, lines[0]) for line in lines[1:]: ret += "%s %s\n" % (spacing, line) return ret def check_ip_option(option, opt, value, allow_loopback=False): try: if allow_loopback: return CheckedIPAddressLoopback(value) else: return CheckedIPAddress(value) except Exception as e: raise OptionValueError("option {}: invalid IP address {}: {}" .format(opt, value, e)) def check_dn_option(option, opt, value): try: return DN(value) except Exception as e: raise OptionValueError("option %s: invalid DN: %s" % (opt, e)) def check_constructor(option, opt, value): con = option.constructor assert con is not None, "Oops! Developer forgot to set 'constructor' kwarg" try: return con(value) except Exception as e: raise OptionValueError("option {} invalid: {}".format(opt, e)) class IPAOption(Option): """ optparse.Option subclass with support of options labeled as security-sensitive such as passwords. """ ATTRS = Option.ATTRS + ["sensitive", "constructor"] TYPES = Option.TYPES + ("ip", "dn", "constructor", "ip_with_loopback") TYPE_CHECKER = copy(Option.TYPE_CHECKER) TYPE_CHECKER["ip"] = check_ip_option TYPE_CHECKER["ip_with_loopback"] = functools.partial(check_ip_option, allow_loopback=True) TYPE_CHECKER["dn"] = check_dn_option TYPE_CHECKER["constructor"] = check_constructor class IPAOptionParser(OptionParser): """ optparse.OptionParser subclass that uses IPAOption by default for storing options. """ def __init__(self, usage=None, option_list=None, option_class=IPAOption, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=True, prog=None): OptionParser.__init__(self, usage, option_list, option_class, version, conflict_handler, description, formatter, add_help_option, prog) def get_safe_opts(self, opts): """ Returns all options except those with sensitive=True in the same fashion as parse_args would """ all_opts_dict = { o.dest: o for o in self._get_all_options() if hasattr(o, 'sensitive') } safe_opts_dict = {} for option, value in opts.__dict__.items(): if not all_opts_dict[option].sensitive: safe_opts_dict[option] = value return Values(safe_opts_dict) def verify_args(parser, args, needed_args = None): """Verify that we have all positional arguments we need, if not, exit.""" if needed_args: needed_list = needed_args.split(" ") else: needed_list = [] len_need = len(needed_list) len_have = len(args) if len_have > len_need: parser.error("too many arguments") elif len_have < len_need: parser.error("no %s specified" % needed_list[len_have]) class IPAConfig: def __init__(self): self.default_realm = None self.default_server = [] self.default_domain = None def get_realm(self): if self.default_realm: return self.default_realm else: raise IPAConfigError("no default realm") def get_server(self): if len(self.default_server): return self.default_server else: raise IPAConfigError("no default server") def get_domain(self): if self.default_domain: return self.default_domain else: raise IPAConfigError("no default domain") # Global library config config = IPAConfig() def __parse_config(discover_server = True): p = SafeConfigParser() p.read(paths.IPA_DEFAULT_CONF) try: if not config.default_realm: config.default_realm = p.get("global", "realm") except Exception: pass if discover_server: try: s = p.get("global", "xmlrpc_uri") server = urlsplit(s) config.default_server.append(server.netloc) except Exception: pass try: if not config.default_domain: config.default_domain = p.get("global", "domain") except Exception: pass def __discover_config(discover_server = True): servers = [] try: if not config.default_domain: # try once with REALM -> domain domain = str(config.default_realm).lower() name = "_ldap._tcp." + domain try: servers = query_srv(name) except DNSException: # try cycling on domain components of FQDN try: domain = dns.name.from_text(socket.getfqdn()) except DNSException: return False while True: domain = domain.parent() if str(domain) == '.': return False name = "_ldap._tcp.%s" % domain try: servers = query_srv(name) break except DNSException: pass config.default_domain = str(domain).rstrip(".") if discover_server: if not servers: name = "_ldap._tcp.%s." % config.default_domain try: servers = query_srv(name) except DNSException: pass for server in servers: hostname = str(server.target).rstrip(".") config.default_server.append(hostname) except Exception: pass return None def add_standard_options(parser): parser.add_option("--realm", dest="realm", help="Override default IPA realm") parser.add_option("--server", dest="server", help="Override default FQDN of IPA server") parser.add_option("--domain", dest="domain", help="Override default IPA DNS domain") def init_config(options=None): if options: config.default_realm = options.realm config.default_domain = options.domain if options.server: config.default_server.extend(options.server.split(",")) if len(config.default_server): discover_server = False else: discover_server = True __parse_config(discover_server) __discover_config(discover_server) # make sure the server list only contains unique items new_server = [] for server in config.default_server: if server not in new_server: new_server.append(server) config.default_server = new_server if not config.default_realm: raise IPAConfigError("IPA realm not found in DNS, in the config file (/etc/ipa/default.conf) or on the command line.") if not config.default_server: raise IPAConfigError("IPA server not found in DNS, in the config file (/etc/ipa/default.conf) or on the command line.") if not config.default_domain: raise IPAConfigError("IPA domain not found in the config file (/etc/ipa/default.conf) or on the command line.")
encukou/freeipa
ipapython/config.py
Python
gpl-3.0
9,257
ENT.Type = "anim" ENT.Base = "base_gmodentity" ENT.PrintName = "Smoke less powder" ENT.Author = "H.A.Z.G" ENT.Purpose = "Crafting part" ENT.Spawnable = false ENT.AdminSpawnable = false
AndyClausen/PNRP_HazG
postnukerp/entities/entities/intm_smokelesspowder/shared.lua
Lua
gpl-3.0
206
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Xml; using CP77.CR2W.Reflection; using FastMember; namespace CP77.CR2W.Types { /// <summary> /// A pointer to a chunk within the same cr2w file. /// </summary> [REDMeta(EREDMetaInfo.REDStruct)] public class multiChannelCurve<T> : CVariable, ICurveDataAccessor where T : CVariable { public enum EInterPolationType { Constant, Linear, BezierQuadratic, BezierCubic, Hermite } public enum ELinkType { Normal, Smooth, SmoothSymmertric } public multiChannelCurve(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { //NumChannels = new CUInt32(cr2w, this, nameof(NumChannels)); InterPolationType = new CEnum<EInterPolationType>(cr2w, this, nameof(InterPolationType)); LinkType = new CEnum<ELinkType>(cr2w, this, nameof(LinkType)); Alignment = new CUInt32(cr2w, this, nameof(Alignment)); Data = new CByteArray(cr2w, this, nameof(Data)); } [Ordinal(1)] [REDBuffer] public CUInt32 NumChannels { get; set; } [Ordinal(2)] [REDBuffer(true)] public CEnum<EInterPolationType> InterPolationType { get; set; } [Ordinal(3)] [REDBuffer(true)] public CEnum<ELinkType> LinkType { get; set; } [Ordinal(4)] [REDBuffer(true)] public CUInt32 Alignment { get; set; } [Ordinal(5)] [REDBuffer(true)] public CByteArray Data { get; set; } public string Elementtype { get; set; } //private List<CurvePoint<T>> Elements { get; set; } = new(); public override string REDType => $"multiChannelCurve:{Elementtype}"; public override void Read(BinaryReader file, uint size) { base.Read(file, size); var interPolationTypeByte = (int)file.ReadByte(); InterPolationType.WrappedEnum = (EInterPolationType) interPolationTypeByte; var linkTypeByte = (int)file.ReadByte(); LinkType.WrappedEnum = (ELinkType) linkTypeByte; Alignment.Read(file, 4); Data.Read(file, 0); } public override void Write(BinaryWriter file) { base.Write(file); file.Write((byte)InterPolationType.WrappedEnum); file.Write((byte)LinkType.WrappedEnum); Alignment.Write(file); Data.Write(file); } //public override List<IEditableVariable> GetEditableVariables() //{ // return Elements.Cast<IEditableVariable>().ToList(); //} } }
Traderain/Wolven-kit
CP77.CR2W/Types/Generic/multiChannelCurve.cs
C#
gpl-3.0
2,809
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.caritas.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.validation.constraints.NotNull; /** * * @author tecnologia */ @Embeddable public class EncSocioNutriciaSegPK implements Serializable { @Basic(optional = false) @NotNull @Column(name = "Expediente") private int expediente; @Basic(optional = false) @NotNull @Column(name = "AreaGeo") private char areaGeo; public EncSocioNutriciaSegPK() { } public EncSocioNutriciaSegPK(int expediente, char areaGeo) { this.expediente = expediente; this.areaGeo = areaGeo; } public int getExpediente() { return expediente; } public void setExpediente(int expediente) { this.expediente = expediente; } public char getAreaGeo() { return areaGeo; } public void setAreaGeo(char areaGeo) { this.areaGeo = areaGeo; } @Override public int hashCode() { int hash = 0; hash += (int) expediente; hash += (int) areaGeo; return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof EncSocioNutriciaSegPK)) { return false; } EncSocioNutriciaSegPK other = (EncSocioNutriciaSegPK) object; if (this.expediente != other.expediente) { return false; } if (this.areaGeo != other.areaGeo) { return false; } return true; } @Override public String toString() { return "com.caritas.entity.EncSocioNutriciaSegPK[ expediente=" + expediente + ", areaGeo=" + areaGeo + " ]"; } }
ITESM-BancoDeAlimentos/BAM
RealSystem/BACMty-ejb/src/java/com/caritas/entity/EncSocioNutriciaSegPK.java
Java
gpl-3.0
1,941
#!/bin/sh omniidl -bpython -I"%RTM_ROOT%rtm\idl" -I"C:\UserDefType" idl/DataBase.idl
Nobu19800/MovieDataBaseInputRTC
idlcompile.sh
Shell
gpl-3.0
86
# RPiGpio **RPiGpio** - *Simplifies raspberry pi gpio access* **RPiOperant** - *Example client program demonstrating capabilities* Author: Jesse McClure, Copyright 2014 License: GPLv3 / CC-BY-SA ## Using RPioGpio The RPiGpio program must be run as root - this can be accomplished by launching from init at boot. A systemd service file is included for distros which use systemd (e.g., ArchlinuxARM). RPiGpio creates to user-accessible fifo pipes in /tmp, one for send messages to RPiGpio to change pin settings (change outputs) and the other for receiving events from RPiGpio (inputs). Interaction with these fifos can be handled by using the constants and inline functions defined in RPiGpio.h (for compiled client programs) or RPiGPio.sh (for shell script clients - this is not yet tested and may not currently work as RPiGpio requires a process have the event fifo open for reading before it proceeds). RPiOperant provides an example of a compiled client for song-preference test for songbirds using RPiGpio.c. The constants, macros, and functions available are as follows: <dl> <dt>RPiPinMask</dt><dd> bitwise *and* with a message to get a pin fit-field that the message applies to. </dd><dt>RPiMsgMask</dt><dd> bitwise *and* with a message to get the message type. Note that this is not likely of use for client programs. </dd><dt>RPiMsgSetOff</dt><dd> bitwise *or* with your message to turn off outputs </dd><dt>RPiMsgSetOn</dt><dd> bitwise *or* with your message to turn on outputs </dd><dt>RPiMsgQueryState</dt><dd> bitwise *or* with your message to query the state of all pins </dd><dt>RPiMsgInit</dt><dd> must be the first message sent when a client program starts. Bitwise *or* any pin numbers that are to be used as inputs, otherwise all pins default to being outputs. </dd><dt>RPiMsgStop</dt><dd> send this message before shutting down a client program. </dd></dl> NOTE: descriptions for the following coming soon RPiEventMask RPiEventError RPiEventChange RPiEventState RPiEventUnused RPiDetailMask RPiExported RPiDirection RPiFatalError RPiPin(x) open_gpio(); void close_gpio(); int check_event(int sec, int usec); flush_events(); void send_msg(int msg); ## Client programs Client programs should do the following: 1. call *open_gpio* (compiled clients only) 1. call *send_msg* passing a RPiMsgInit message bitwise-or'ed with an RPiPin(pin) for every pin to be used as an input. 1. The following may be used as needed: - Send message: * RPiMsgStateOn/Off bitwise-or'ed with any RPiPin(num) you wish to turn on/off. Multiple output pins can be specified. * RPiMsgQueryState to trigger a response with the state of ever pin. - Handle events: * call *check_event* with a limit of seconds and/or useconds which will be used as the timeout value for a select() read. The return value will be an integer bitfield specifying an event or error message. * call *flush_events* to discard any messages currently in the queue. (not implemented in RPiGpio.sh yet) 1. call *send_msg* with a RPiMsgStop message 1. call *close_gpio* (compiled clients only)
TrilbyWhite/RPiGpio
README.md
Markdown
gpl-3.0
3,130
package net.mcthunder.commands; import net.mcthunder.api.Command; import net.mcthunder.entity.Player; import java.util.Arrays; public class Broadcast extends Command { public Broadcast(){ super("broadcast", Arrays.asList("say"), "Broadcast a server message", "/broadcast {message}", 5000, "core.broadcast"); } @Override public boolean execute(Player player, String[] args) { if (args.length == 0) return false; return true; } }
Lukario45/MCThunder
src/main/java/net/mcthunder/commands/Broadcast.java
Java
gpl-3.0
488
<?xml version="1.0" encoding="utf-8"?> <!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" xml:lang="en" lang="en"> <head> <title>ActionView::Resolver</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" /> <script src="../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.2.0</span><br /> <h1> <span class="type">Class</span> ActionView::Resolver <span class="parent">&lt; <a href="../Object.html">Object</a> </span> </h1> <ul class="files"> <li><a href="../../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/template/resolver_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/template/resolver.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <div class="description"> <h1 id="class-ActionView::Resolver-label-Action+View+Resolver">Action View <a href="Resolver.html">Resolver</a></h1> </div> <!-- Namespace --> <div class="sectiontitle">Namespace</div> <ul> <li> <span class="type">CLASS</span> <a href="Resolver/Cache.html">ActionView::Resolver::Cache</a> </li> <li> <span class="type">CLASS</span> <a href="Resolver/Path.html">ActionView::Resolver::Path</a> </li> </ul> <!-- Method ref --> <div class="sectiontitle">Methods</div> <dl class="methods"> <dt>C</dt> <dd> <ul> <li> <a href="#method-i-clear_cache">clear_cache</a> </li> </ul> </dd> <dt>F</dt> <dd> <ul> <li> <a href="#method-i-find_all">find_all</a> </li> </ul> </dd> <dt>N</dt> <dd> <ul> <li> <a href="#method-c-new">new</a> </li> </ul> </dd> </dl> <!-- Methods --> <div class="sectiontitle">Class Public methods</div> <div class="method"> <div class="title method-title" id="method-c-new"> <b>new</b>() <a href="../../classes/ActionView/Resolver.html#method-c-new" name="method-c-new" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-c-new_source')" id="l_method-c-new_source">show</a> </p> <div id="method-c-new_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/template/resolver.rb, line 105</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">initialize</span> <span class="ruby-ivar">@cache</span> = <span class="ruby-constant">Cache</span>.<span class="ruby-identifier">new</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="sectiontitle">Instance Public methods</div> <div class="method"> <div class="title method-title" id="method-i-clear_cache"> <b>clear_cache</b>() <a href="../../classes/ActionView/Resolver.html#method-i-clear_cache" name="method-i-clear_cache" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-clear_cache_source')" id="l_method-i-clear_cache_source">show</a> </p> <div id="method-i-clear_cache_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/template/resolver.rb, line 109</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">clear_cache</span> <span class="ruby-ivar">@cache</span>.<span class="ruby-identifier">clear</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="method-i-find_all"> <b>find_all</b>(name, prefix=nil, partial=false, details={}, key=nil, locals=[]) <a href="../../classes/ActionView/Resolver.html#method-i-find_all" name="method-i-find_all" class="permalink">Link</a> </div> <div class="description"> <p>Normalizes the arguments and passes it on to find_templates.</p> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-find_all_source')" id="l_method-i-find_all_source">show</a> </p> <div id="method-i-find_all_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/template/resolver.rb, line 114</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">find_all</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">prefix</span>=<span class="ruby-keyword">nil</span>, <span class="ruby-identifier">partial</span>=<span class="ruby-keyword">false</span>, <span class="ruby-identifier">details</span>={}, <span class="ruby-identifier">key</span>=<span class="ruby-keyword">nil</span>, <span class="ruby-identifier">locals</span>=[]) <span class="ruby-identifier">cached</span>(<span class="ruby-identifier">key</span>, [<span class="ruby-identifier">name</span>, <span class="ruby-identifier">prefix</span>, <span class="ruby-identifier">partial</span>], <span class="ruby-identifier">details</span>, <span class="ruby-identifier">locals</span>) <span class="ruby-keyword">do</span> <span class="ruby-identifier">find_templates</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">prefix</span>, <span class="ruby-identifier">partial</span>, <span class="ruby-identifier">details</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> </div> </div> </body> </html>
rafaellc28/Portfolio
doc/api/classes/ActionView/Resolver.html
HTML
gpl-3.0
8,264
script.module.torrent2http ========================== This add-on is binding to [torrent2http](https://github.com/anteo/torrent2http) client. It is bundled with torrent2http binaries for Android ARM, Linux x86/x64/ARM, Windows x86/x64 and Darwin/OSX x64 platforms. You can download it from my [repository](http://bit.ly/184XKjm) This add-on can be used to stream media files from torrents without need to download entire files. Internally, it runs pre-compiled torrent2http client binary, which starts local HTTP server, presenting contents of torrent. Next, request to HTTP server can be sent to receive list of files or to start streaming of needed file inside of torrent. Usage ----- ### Get list of files inside torrent ### Getting list of files inside torrent is straightforward: ```python import xbmc from torrent2http import State, Engine, MediaType from contextlib import closing # Create instance of Engine engine = Engine(uri="...") files = [] # Ensure we'll close engine on exception with closing(engine): # Start engine engine.start() # Wait until files received while not files and not xbmc.abortRequested: # Will list only video files in torrent files = engine.list(media_types=[MediaType.VIDEO]) # Check if there is loading torrent error and raise exception engine.check_torrent_error() xbmc.sleep(200) ``` ### Start streaming ### ```python import xbmc from torrent2http import State, Engine, MediaType from contextlib import closing # XBMC addon handle handle = ... # Playable list item listitem = ... # We can know file_id of needed video file on this step, if no, we'll try to detect one. file_id = None # Flag will set to True when engine is ready to resolve URL to XBMC ready = False # Set pre-buffer size to 15Mb. This is a size of file that need to be downloaded before we resolve URL to XMBC pre_buffer_bytes = 15*1024*1024 engine = Engine(uri="...") with closing(engine): # Start engine and instruct torrent2http to begin download first file, # so it can start searching and connecting to peers engine.start(file_id or 0) while not xbmc.abortRequested and not ready: xbmc.sleep(500) status = engine.status() # Check if there is loading torrent error and raise exception engine.check_torrent_error(status) # Trying to detect file_id if file_id is None: # Get torrent files list, filtered by video file type only files = engine.list(media_types=[MediaType.VIDEO]) # If torrent metadata is not loaded yet then continue if files is None: continue # Torrent has no video files if not files: break # Select first matching file file_id = files[0].index file_status = files[0] else: # If we've got file_id already, get file status file_status = engine.file_status(file_id) # If torrent metadata is not loaded yet then continue if not file_status: continue if status.state == State.DOWNLOADING: # Wait until minimum pre_buffer_bytes downloaded before we resolve URL to XBMC if file_status.download >= pre_buffer_bytes: ready = True break elif status.state in [State.FINISHED, State.SEEDING]: # We have already downloaded file ready = True break # Here you can update pre-buffer progress dialog, for example. # Note that State.CHECKING also need waiting until fully finished, so it better to use resume_file option # for engine to avoid CHECKING state if possible. # ... if ready: # Resolve URL to XBMC listitem.SetPath(file_status.url) xbmcplugin.SetResolvedUrl(handle, True, listitem) # Wait until playing finished or abort requested while not xbmc.abortRequested and xbmc.Player().isPlaying(): xbmc.sleep(500) ``` ### Fully working example ### You can look into fully working [example](https://github.com/anteo/plugin.video.okino/blob/master/resources/lib/okino/torrent/stream/t2h_stream.py). This is excerpt from my plugin using script.module.torrent2http. It rather complicated but it includes error handling, showing progress dialog and other features.
chimkentec/KodiMODo_rep
script.module.torrent2http/README.md
Markdown
gpl-3.0
4,455
package TFC.Items.ItemBlocks; import java.util.List; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Icon; import net.minecraft.world.World; import TFC.API.ISize; import TFC.API.Enums.EnumSize; import TFC.API.Enums.EnumWeight; import TFC.Core.HeatIndex; import TFC.Core.HeatManager; import TFC.Core.TFC_ItemHeat; import TFC.Core.TFC_Settings; import TFC.Items.ItemTerra; public class ItemTerraBlock extends ItemBlock implements ISize { public String[] MetaNames; public Icon[] icons; public String folder; public ItemTerraBlock(int par1) { super(par1); setHasSubtypes(true); this.setCreativeTab(CreativeTabs.tabBlock); folder = ""; } public ItemTerraBlock setFolder(String f) { folder = f; return this; } @Override public String getUnlocalizedName(ItemStack itemstack) { if(MetaNames != null) return getUnlocalizedName().concat("."+ MetaNames[itemstack.getItemDamage()]); return super.getUnlocalizedName(itemstack); } @Override public void onUpdate(ItemStack is, World world, Entity entity, int i, boolean isSelected) { if (!world.isRemote && is.hasTagCompound()) { NBTTagCompound stackTagCompound = is.getTagCompound(); if(stackTagCompound.hasKey("temperature")) { TFC_ItemHeat.HandleItemHeat(is, (int)entity.posX, (int)entity.posY, (int)entity.posZ); } } } @Override public int getMetadata(int i) { return i; } @Override public void addInformation(ItemStack is, EntityPlayer player, List arraylist, boolean flag) { ItemTerra.addSizeInformation(this, arraylist); if(TFC_Settings.enableDebugMode) arraylist.add(getUnlocalizedName(is)); if (is.hasTagCompound()) { NBTTagCompound stackTagCompound = is.getTagCompound(); if(stackTagCompound.hasKey("temperature")) { float temp = stackTagCompound.getFloat("temperature"); float meltTemp = -1; float boilTemp = 10000; HeatIndex hi = HeatManager.getInstance().findMatchingIndex(is); if(hi != null) { meltTemp = hi.meltTemp; boilTemp = hi.boilTemp; } if(meltTemp != -1) { if(is.itemID == Item.stick.itemID) arraylist.add(TFC_ItemHeat.getHeatColorTorch(temp, meltTemp)); else arraylist.add(TFC_ItemHeat.getHeatColor(temp, meltTemp, boilTemp)); } } } } @Override public boolean getShareTag() { return true; } @Override public int getItemStackLimit() { if(canStack()) return this.getSize().stackSize * getWeight().multiplier; else return 1; } @Override public EnumSize getSize() { // TODO Auto-generated method stub return EnumSize.VERYSMALL; } @Override public boolean canStack() { // TODO Auto-generated method stub return true; } @Override public EnumWeight getWeight() { // TODO Auto-generated method stub return EnumWeight.HEAVY; } @Override public void registerIcons(IconRegister registerer) { /*if(MetaNames != null) { icons = new Icon[MetaNames.length]; for(int i = 0; i < MetaNames.length; i++) { icons[i] = registerer.registerIcon(folder+MetaNames[i]); } }*/ } }
Timeslice42/TFCraft
TFC_Shared/src/TFC/Items/ItemBlocks/ItemTerraBlock.java
Java
gpl-3.0
3,563
/* * Copyright (C) 2015 The CyanogenMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "jni_CMActions" #include <errno.h> #include <fcntl.h> #include <jni.h> #include <pthread.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <linux/stm401.h> #include <cutils/log.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> #define PACKED __attribute__((__packed__)) #define UNUSED __attribute__((__unused__)) #define STM401_DEVICE "/dev/stm401" #define STM401_IR_WAKE_CONFIG_MASK 0x000007FE #define STM401_IR_CONTROL_DISABLE 0x00000001 #define STM401_IR_CONFIG_TUNING_NUMBER_MIN 6 #define STM401_IR_CONFIG_TUNING_NUMBER_MAX 7 struct PACKED stm401_ir_led_config { uint8_t ambient_selection; uint16_t ambient_offset_hp; uint16_t idle_event_minimum_above_noise; uint16_t idle_hysteresis_threshold; uint16_t presence_event_minimum_above_noise; uint16_t presence_hysteresis_threshold; uint16_t prox_event_minimum_above_noise; uint16_t prox_hysteresis_threshold; uint16_t prox_object_close_minimum_above_noise; uint16_t prox_hovering_minimum_above_noise; uint16_t prox_covering_minimum_hp; uint16_t prox_covering_minimum_lp; uint8_t prox_feature_support; uint16_t swipe_event_minimum_above_noise; uint16_t swipe_hysteresis_threshold; uint16_t swipe_complete_level1_minimum_above_idle; uint16_t swipe_complete_level1_minimum_threshold; uint16_t swipe_complete_level2_minimum_above_idle; uint16_t swipe_complete_level2_minimum_threshold; uint16_t swipe_complete_level3_minimum_above_idle; uint16_t swipe_complete_level3_minimum_threshold; uint16_t swipe_reading_high_threshold; }; /* size = 0x2A */ struct PACKED stm401_ir_config { uint8_t size; uint8_t tuning_number; /* 4 - 6 are valid values */ uint32_t cmd_control; uint32_t cmd_config; struct stm401_ir_led_config top_right_config; struct stm401_ir_led_config bottom_left_config; struct stm401_ir_led_config bottom_right_config; struct stm401_ir_led_config bottom_both_config; uint16_t idle_count; uint8_t idle_event_count; uint16_t noise_minimum; uint8_t noise_padding; uint8_t noise_period; uint8_t object_valid_delay; uint8_t prox_cover_count; uint8_t prox_event_count; uint8_t prox_hower_count; uint8_t presence_event_count; uint8_t swipe_count; uint8_t swipe_event_count; uint16_t swipe_high_threshold; uint8_t swipe_fast_level1_threshold; uint8_t swipe_fast_level2_threshold; uint8_t swipe_is_equal_level1_threshold; uint8_t swipe_is_equal_level2_threshold; uint8_t swipe_is_equal_level3_threshold; uint8_t motion_scale_shift; uint8_t swipe_high_level1_multiplier; uint8_t swipe_high_level2_multiplier; uint16_t ambient_min_reading; uint16_t ambient_max_reading; uint8_t swipe_ignore_count; uint16_t swipe_vertical_pref_delta; uint16_t swipe_vertical_ignore_delta; uint8_t swipe_vertical_ignore_count; }; /* size = 0xD4 */ static pthread_mutex_t ioctl_mutex = PTHREAD_MUTEX_INITIALIZER; int stm401_ioctl(unsigned long request, unsigned char* data) { int fd = open(STM401_DEVICE, O_RDWR); if (fd < 0) { ALOGE("%s: Failed to open " STM401_DEVICE ": %s\n", __func__, strerror(errno)); return 1; } int ret = ioctl(fd, request, data); close(fd); if (ret) { ALOGE("%s: Failed to ioctl " STM401_DEVICE ": %s\n", __func__, strerror(errno)); return 1; } return 0; } int read_ir_config(struct stm401_ir_config* config, int check_version) { memset(config, 0, sizeof(struct stm401_ir_config)); config->size = sizeof(struct stm401_ir_config); if (stm401_ioctl(STM401_IOCTL_GET_IR_CONFIG, (unsigned char*)config)) { return 1; } if (check_version && (config->tuning_number < STM401_IR_CONFIG_TUNING_NUMBER_MIN || config->tuning_number > STM401_IR_CONFIG_TUNING_NUMBER_MAX)) { ALOGE("%s: Found tuning number %d, but expected %d..%d!\n", __func__, config->tuning_number, STM401_IR_CONFIG_TUNING_NUMBER_MIN, STM401_IR_CONFIG_TUNING_NUMBER_MAX); return 1; } return 0; } int write_ir_config(struct stm401_ir_config* config) { return stm401_ioctl(STM401_IOCTL_SET_IR_CONFIG, (unsigned char*)config); } int set_ir_disabled(int disabled) { struct stm401_ir_config config; pthread_mutex_lock(&ioctl_mutex); if (read_ir_config(&config, 1)) { goto err; } if (disabled) { config.cmd_control |= STM401_IR_CONTROL_DISABLE; } else { config.cmd_control &= ~STM401_IR_CONTROL_DISABLE; } if (write_ir_config(&config)) { goto err; } pthread_mutex_unlock(&ioctl_mutex); return 0; err: pthread_mutex_unlock(&ioctl_mutex); return 1; } int set_ir_wake_config(int wake_config) { struct stm401_ir_config config; pthread_mutex_lock(&ioctl_mutex); if (read_ir_config(&config, 1)) { goto err; } config.cmd_config = wake_config & STM401_IR_WAKE_CONFIG_MASK; if (write_ir_config(&config)) { goto err; } pthread_mutex_unlock(&ioctl_mutex); return 0; err: pthread_mutex_unlock(&ioctl_mutex); return 1; } JNIEXPORT jboolean JNICALL Java_com_cyanogenmod_settings_device_IrGestureManager_nativeSetIrDisabled( UNUSED JNIEnv *env, UNUSED jclass thiz, jboolean disabled) { return set_ir_disabled(disabled == JNI_TRUE) ? JNI_FALSE : JNI_TRUE; } JNIEXPORT jboolean JNICALL Java_com_cyanogenmod_settings_device_IrGestureManager_nativeSetIrWakeConfig( UNUSED JNIEnv *env, UNUSED jclass thiz, jint wakeConfig) { return set_ir_wake_config((int)wakeConfig) ? JNI_FALSE : JNI_TRUE; }
luckybucky98/Egg-Marshmallow
CM13-Victara/cmactions/jni/jni_CMActions.c
C
gpl-3.0
6,406
/* when one clicks on the little 'trash can' fontawesome icon, it should act as though it's a link, and change the cursor to a hand */ .historycursor { cursor: pointer; } /* Override bootstrap primary colour to OXFORD BLUE */ .btn-primary { background-color: #002649; } .text-muted { color: #888; } /* Override jumbotron settings */ .jumbotron { min-height: 1px; padding-top: 10px !important; padding-bottom: 10px !important; padding-left: 10px !important; padding-right: 10px !important; } .jumbotron h1{ color: #fff; } .jumbotron p{ color: #bbb; } /* Override navbar size */ .navbar-nav > li > a, .navbar-brand { padding-top:5px !important; padding-bottom:0 !important; height: 30px; } /* Override hover colours, adapted from: http://stackoverflow.com/a/19203953 */ .navbar-nav > li > a:hover, .navbar-nav > li > a:focus { background-color: #93C54B; color: #002649; } .navbar {min-height:30px !important;} /* style.css */ /* BASIC STYLINGS ============================================================================= */ body { padding-top:20px; } /* form styling */ /* #content-container { background:#2f2f2f; margin-bottom:20px; border-radius:5px; } */ #content-container { margin-bottom:20px; border-radius:5px; } #content-container .page-header { background:#FFF; margin:0; padding:30px; border-top-left-radius:5px; border-top-right-radius:5px; } /* numbered buttons */ #status-buttons { } #status-buttons a { color:#002649; display:inline-block; font-size:12px; margin-right:10px; text-align:center; text-transform:uppercase; } #status-buttons a:hover { text-decoration:none; } /* we will style the span as the circled number */ /* #status-buttons span { background:#0a0a0a; display:block; height:50px; margin:0 auto 50px; padding-top:0px; width:50px; border-radius:50%; } */ /* active buttons turn light green-blue*/ #status-buttons a.active span { background:#93C54B; } /* style.css */ /* ANIMATION STYLINGS ============================================================================= */ #vcfform { position:relative; min-height:300px; overflow:hidden; padding:30px; } #content-views { width:auto; } /* basic styling for entering and leaving */ /* left and right added to ensure full width */ #content-views.ng-enter, #content-views.ng-leave { position:absolute; left:30px; right:30px; transition:0.5s all ease; -moz-transition:0.5s all ease; -webkit-transition:0.5s all ease; } /* enter animation */ #content-views.ng-enter { -webkit-animation:slideInRight 0.5s both ease; -moz-animation:slideInRight 0.5s both ease; animation:slideInRight 0.5s both ease; } /* leave animation */ #content-views.ng-leave { -webkit-animation:slideOutLeft 0.5s both ease; -moz-animation:slideOutLeft 0.5s both ease; animation:slideOutLeft 0.5s both ease; } /* ANIMATIONS ============================================================================= */ /* slide out to the left */ @keyframes slideOutLeft { to { transform: translateX(-200%); } } @-moz-keyframes slideOutLeft { to { -moz-transform: translateX(-200%); } } @-webkit-keyframes slideOutLeft { to { -webkit-transform: translateX(-200%); } } /* slide in from the right */ @keyframes slideInRight { from { transform:translateX(200%); } to { transform: translateX(0); } } @-moz-keyframes slideInRight { from { -moz-transform:translateX(200%); } to { -moz-transform: translateX(0); } } @-webkit-keyframes slideInRight { from { -webkit-transform:translateX(200%); } to { -webkit-transform: translateX(0); } }
BSGOxford/BrowseVCF
web/css/style.css
CSS
gpl-3.0
3,807
omup ==== About ----------- Omup is a simple omploader uploader written in python. It does not depend on PycURL or any other external library. Currently supports Python 3 only. Dependenies ----------- * python >= 3 Command line parameters ----------------------- ###Synopsis omup.py [-h] [-p] [-s] [-b] file ###Parameters ``` positional arguments: file file to upload optional arguments: -h, --help show help message and exit -p, --prompt prompt before upload -s, --short show a shorter file url (strips filename) -b, --bbc show BBC code ``` Return data ----------- Omup returns by default the full url of the uploaded file so you can easily get it with `wget`. e.g.: `$ omup.py /tmp/foo.png` returns `http://ompldr.org/vSoMeId/foo.png` while if the `-s` parameter is supplied, returns a shorter version like `http://ompldr.org/vSoMeId`. License ------- 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 version 3 of the License. A copy of theGNU General Public License can be found in [GNU Licence Page](http://www.gnu.org/licenses/gpl.html)
tlatsas/omup
README.md
Markdown
gpl-3.0
1,205
/* * script.cpp * External model functionality * * iWaQa model framework 2010-2017 * * SYSTEM/MODEL * */ #include "script.h" #include "datatable.h" #include "model.h" #include <stdlib.h> //--------------------------------------------------------------------------------- iWQScript::iWQScript() { mCommand = "echo Hello World!"; mExportTableName = "_data.dat"; mImportTableName = mExportTableName; mExportParametersName = "_pars.dat"; mOrder = 999; mReturnStatus = -9; mDataTable=NULL; mCommonParameters=NULL; mExportTabDelimitedParamaters=false; } //--------------------------------------------------------------------------------- bool iWQScript::execute() { //check tools if(!mDataTable){ mReturnStatus=-6; return false; } if(!mCommonParameters){ mReturnStatus=-5; return false; } if(mCommand.size()==0){ mReturnStatus=-4; return false; } if(mExportTableName.size()==0){ mReturnStatus=-3; return false; } if(mImportTableName.size()==0){ mReturnStatus=-2; return false; } if(mExportParametersName.size()==0){ mReturnStatus=-1; return false; } //save data table and parameters mDataTable->writeToFile(mExportTableName); mCommonParameters->saveToFile(mExportParametersName, mExportTabDelimitedParamaters); //tab delimited export //run script mReturnStatus = system(mCommand.c_str()); //reload data table mDataTable->reloadFromFile(mImportTableName); return (mReturnStatus==0); } //---------------------------------------------------------------------------------
hontimar/iWaQa
src/script.cpp
C++
gpl-3.0
1,543
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 1998-2011, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #include "PyIlmBaseConfigInternal.h" #include "PyImathBasicTypes.h" #include <Python.h> #include <boost/python.hpp> #include "PyImath.h" #include "PyImathExport.h" #include "PyImathFixedArray.h" #include "PyImathFixedVArray.h" using namespace boost::python; namespace PyImath { void register_basicTypes() { class_<BoolArray> bclass = BoolArray::register_("Fixed length array of bool"); add_comparison_functions(bclass); class_<SignedCharArray> scclass = SignedCharArray::register_("Fixed length array of signed chars"); add_arithmetic_math_functions(scclass); add_mod_math_functions(scclass); add_comparison_functions(scclass); add_ordered_comparison_functions(scclass); class_<UnsignedCharArray> ucclass = UnsignedCharArray::register_("Fixed length array of unsigned chars"); add_arithmetic_math_functions(ucclass); add_mod_math_functions(ucclass); add_comparison_functions(ucclass); add_ordered_comparison_functions(ucclass); class_<ShortArray> sclass = ShortArray::register_("Fixed length array of shorts"); add_arithmetic_math_functions(sclass); add_mod_math_functions(sclass); add_comparison_functions(sclass); add_ordered_comparison_functions(sclass); class_<UnsignedShortArray> usclass = UnsignedShortArray::register_("Fixed length array of unsigned shorts"); add_arithmetic_math_functions(usclass); add_mod_math_functions(usclass); add_comparison_functions(usclass); add_ordered_comparison_functions(usclass); class_<IntArray> iclass = IntArray::register_("Fixed length array of ints"); add_arithmetic_math_functions(iclass); add_mod_math_functions(iclass); add_comparison_functions(iclass); add_ordered_comparison_functions(iclass); add_explicit_construction_from_type<float>(iclass); add_explicit_construction_from_type<double>(iclass); class_<UnsignedIntArray> uiclass = UnsignedIntArray::register_("Fixed length array of unsigned ints"); add_arithmetic_math_functions(uiclass); add_mod_math_functions(uiclass); add_comparison_functions(uiclass); add_ordered_comparison_functions(uiclass); add_explicit_construction_from_type<float>(uiclass); add_explicit_construction_from_type<double>(uiclass); class_<FloatArray> fclass = FloatArray::register_("Fixed length array of floats"); add_arithmetic_math_functions(fclass); add_pow_math_functions(fclass); add_comparison_functions(fclass); add_ordered_comparison_functions(fclass); add_explicit_construction_from_type<int>(fclass); add_explicit_construction_from_type<double>(fclass); class_<DoubleArray> dclass = DoubleArray::register_("Fixed length array of doubles"); add_arithmetic_math_functions(dclass); add_pow_math_functions(dclass); add_comparison_functions(dclass); add_ordered_comparison_functions(dclass); add_explicit_construction_from_type<int>(dclass); add_explicit_construction_from_type<float>(dclass); class_<VIntArray> ivclass = VIntArray::register_("Variable fixed length array of ints"); // Don't add other functionality until its defined better. } } // namespace PyImath
AlienCowEatCake/ImageViewer
src/ThirdParty/OpenEXR/openexr-2.5.7/PyIlmBase/PyImath/PyImathBasicTypes.cpp
C++
gpl-3.0
4,972
namespace Goji.Data { using System; using System.ComponentModel; using System.Windows; using System.Windows.Data; using System.Windows.Markup; /// <summary> /// Can be used to localize properties of UI elements. /// <para /> /// Use this markup extension if your translation key should be provides by a <see cref="Binding"/>. /// </summary> [MarkupExtensionReturnType(typeof(string))] public class BindingTranslationExtension : TranslationExtensionBase<Binding> { /// <summary> /// Initializes a new instance of the <see cref="BindingTranslationExtension"/> class. /// </summary> public BindingTranslationExtension() { } /// <summary> /// Initializes a new instance of the <see cref="BindingTranslationExtension"/> class. /// </summary> /// <param name="key">The key who is used as placeholder for the translation-value.</param> public BindingTranslationExtension(Binding key) : base(key) { } /// <summary> /// Returns an object that is provided as the translation of the target translation-key. /// </summary> /// <param name="serviceProvider">>A service provider helper that can provide services for the markup extension.</param> /// <returns>The object value to set on the property where the extension is applied.</returns> /// <exception cref="System.Exception">The <c>Key</c> property is not specified.</exception> public override object ProvideValue(IServiceProvider serviceProvider) { this.ThrowIfKeyNotSpecified(); MultiBinding binding = new MultiBinding(); binding.Bindings.Add(this.Key); IProvideValueTarget provideValueTarget = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; if (provideValueTarget != null) { if (provideValueTarget.TargetObject is DependencyObject targetObject) { var bindingSource = new LocalizationPropertyBindingSource(LocalizationProperties.TranslationProviderProperty, targetObject); binding.Bindings.Add(bindingSource.Binding); binding.Converter = new TranslationConverter(targetObject, this.TranslationProvider, this.Language, this.StringFormat, this.FallbackValue); if (DesignerProperties.GetIsInDesignMode(targetObject)) return string.IsNullOrEmpty(this.StringFormat) ? this.FallbackValue : string.Format(this.StringFormat, this.FallbackValue); return binding.ProvideValue(serviceProvider); } else { return this; } } return base.ProvideValue(serviceProvider); } } }
MartinKuschnik/Goji
Goji/Data/BindingTranslationExtension.cs
C#
gpl-3.0
2,931
"""Define and instantiate the configuration class for Robottelo.""" import logging import os import sys from logging import config from nailgun import entities, entity_mixins from nailgun.config import ServerConfig from robottelo.config import casts from six.moves.urllib.parse import urlunsplit, urljoin from six.moves.configparser import ( NoOptionError, NoSectionError, ConfigParser ) LOGGER = logging.getLogger(__name__) SETTINGS_FILE_NAME = 'robottelo.properties' class ImproperlyConfigured(Exception): """Indicates that Robottelo somehow is improperly configured. For example, if settings file can not be found or some required configuration is not defined. """ def get_project_root(): """Return the path to the Robottelo project root directory. :return: A directory path. :rtype: str """ return os.path.realpath(os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, )) class INIReader(object): """ConfigParser wrapper able to cast value when reading INI options.""" # Helper casters cast_boolean = casts.Boolean() cast_dict = casts.Dict() cast_list = casts.List() cast_logging_level = casts.LoggingLevel() cast_tuple = casts.Tuple() cast_webdriver_desired_capabilities = casts.WebdriverDesiredCapabilities() def __init__(self, path): self.config_parser = ConfigParser() with open(path) as handler: self.config_parser.readfp(handler) if sys.version_info[0] < 3: # ConfigParser.readfp is deprecated on Python3, read_file # replaces it self.config_parser.readfp(handler) else: self.config_parser.read_file(handler) def get(self, section, option, default=None, cast=None): """Read an option from a section of a INI file. The default value will return if the look up option is not available. The value will be cast using a callable if specified otherwise a string will be returned. :param section: Section to look for. :param option: Option to look for. :param default: The value that should be used if the option is not defined. :param cast: If provided the value will be cast using the cast provided. """ try: value = self.config_parser.get(section, option) if cast is not None: if cast is bool: value = self.cast_boolean(value) elif cast is dict: value = self.cast_dict(value) elif cast is list: value = self.cast_list(value) elif cast is tuple: value = self.cast_tuple(value) else: value = cast(value) except (NoSectionError, NoOptionError): value = default return value def has_section(self, section): """Check if section is available.""" return self.config_parser.has_section(section) class FeatureSettings(object): """Settings related to a feature. Create a instance of this class and assign attributes to map to the feature options. """ def read(self, reader): """Subclasses must implement this method in order to populate itself with expected settings values. :param reader: An INIReader instance to read the settings. """ raise NotImplementedError('Subclasses must implement read method.') def validate(self): """Subclasses must implement this method in order to validade the settings and raise ``ImproperlyConfigured`` if any issue is found. """ raise NotImplementedError('Subclasses must implement validate method.') class ServerSettings(FeatureSettings): """Satellite server settings definitions.""" def __init__(self, *args, **kwargs): super(ServerSettings, self).__init__(*args, **kwargs) self.admin_password = None self.admin_username = None self.hostname = None self.port = None self.scheme = None self.ssh_key = None self.ssh_password = None self.ssh_username = None def read(self, reader): """Read and validate Satellite server settings.""" self.admin_password = reader.get( 'server', 'admin_password', 'changeme') self.admin_username = reader.get( 'server', 'admin_username', 'admin') self.hostname = reader.get('server', 'hostname') self.port = reader.get('server', 'port', cast=int) self.scheme = reader.get('server', 'scheme', 'https') self.ssh_key = reader.get('server', 'ssh_key') self.ssh_password = reader.get('server', 'ssh_password') self.ssh_username = reader.get('server', 'ssh_username', 'root') def validate(self): validation_errors = [] if self.hostname is None: validation_errors.append('[server] hostname must be provided.') if (self.ssh_key is None and self.ssh_password is None): validation_errors.append( '[server] ssh_key or ssh_password must be provided.') return validation_errors def get_credentials(self): """Return credentials for interacting with a Foreman deployment API. :return: A username-password pair. :rtype: tuple """ return (self.admin_username, self.admin_password) def get_url(self): """Return the base URL of the Foreman deployment being tested. The following values from the config file are used to build the URL: * ``[server] scheme`` (default: https) * ``[server] hostname`` (required) * ``[server] port`` (default: none) Setting ``port`` to 80 does *not* imply that ``scheme`` is 'https'. If ``port`` is 80 and ``scheme`` is unset, ``scheme`` will still default to 'https'. :return: A URL. :rtype: str """ if not self.scheme: scheme = 'https' else: scheme = self.scheme # All anticipated error cases have been handled at this point. if not self.port: return urlunsplit((scheme, self.hostname, '', '', '')) else: return urlunsplit(( scheme, '{0}:{1}'.format(self.hostname, self.port), '', '', '' )) def get_pub_url(self): """Return the pub URL of the server being tested. The following values from the config file are used to build the URL: * ``main.server.hostname`` (required) :return: The pub directory URL. :rtype: str """ return urlunsplit(('http', self.hostname, 'pub/', '', '')) def get_cert_rpm_url(self): """Return the Katello cert RPM URL of the server being tested. The following values from the config file are used to build the URL: * ``main.server.hostname`` (required) :return: The Katello cert RPM URL. :rtype: str """ return urljoin( self.get_pub_url(), 'katello-ca-consumer-latest.noarch.rpm') class ClientsSettings(FeatureSettings): """Clients settings definitions.""" def __init__(self, *args, **kwargs): super(ClientsSettings, self).__init__(*args, **kwargs) self.image_dir = None self.provisioning_server = None def read(self, reader): """Read clients settings.""" self.image_dir = reader.get( 'clients', 'image_dir', '/opt/robottelo/images') self.provisioning_server = reader.get( 'clients', 'provisioning_server') def validate(self): """Validate clients settings.""" validation_errors = [] if self.provisioning_server is None: validation_errors.append( '[clients] provisioning_server option must be provided.') return validation_errors class DockerSettings(FeatureSettings): """Docker settings definitions.""" def __init__(self, *args, **kwargs): super(DockerSettings, self).__init__(*args, **kwargs) self.unix_socket = None self.external_url = None self.external_registry_1 = None self.external_registry_2 = None def read(self, reader): """Read docker settings.""" self.unix_socket = reader.get( 'docker', 'unix_socket', False, bool) self.external_url = reader.get('docker', 'external_url') self.external_registry_1 = reader.get('docker', 'external_registry_1') self.external_registry_2 = reader.get('docker', 'external_registry_2') def validate(self): """Validate docker settings.""" validation_errors = [] if not any((self.unix_socket, self.external_url)): validation_errors.append( 'Either [docker] unix_socket or external_url options must ' 'be provided or enabled.') if not all((self.external_registry_1, self.external_registry_2)): validation_errors.append( 'Both [docker] external_registry_1 and external_registry_2 ' 'options must be provided.') return validation_errors def get_unix_socket_url(self): """Use the unix socket connection to the local docker daemon. Make sure that your Satellite server's docker is configured to allow foreman user accessing it. This can be done by:: $ groupadd docker $ usermod -aG docker foreman # Add -G docker to the options for the docker daemon $ systemctl restart docker $ katello-service restart """ return ( 'unix:///var/run/docker.sock' if self.unix_socket else None ) class FakeManifestSettings(FeatureSettings): """Fake manifest settings defintitions.""" def __init__(self, *args, **kwargs): super(FakeManifestSettings, self).__init__(*args, **kwargs) self.cert_url = None self.key_url = None self.url = None def read(self, reader): """Read fake manifest settings.""" self.cert_url = reader.get( 'fake_manifest', 'cert_url') self.key_url = reader.get( 'fake_manifest', 'key_url') self.url = reader.get( 'fake_manifest', 'url') def validate(self): """Validate fake manifest settings.""" validation_errors = [] if not all(vars(self).values()): validation_errors.append( 'All [fake_manifest] cert_url, key_url, url options must ' 'be provided.' ) return validation_errors class LDAPSettings(FeatureSettings): """LDAP settings definitions.""" def __init__(self, *args, **kwargs): super(LDAPSettings, self).__init__(*args, **kwargs) self.basedn = None self.grpbasedn = None self.hostname = None self.password = None self.username = None def read(self, reader): """Read LDAP settings.""" self.basedn = reader.get('ldap', 'basedn') self.grpbasedn = reader.get('ldap', 'grpbasedn') self.hostname = reader.get('ldap', 'hostname') self.password = reader.get('ldap', 'password') self.username = reader.get('ldap', 'username') def validate(self): """Validate LDAP settings.""" validation_errors = [] if not all(vars(self).values()): validation_errors.append( 'All [ldap] basedn, grpbasedn, hostname, password, ' 'username options must be provided.' ) return validation_errors class LibvirtHostSettings(FeatureSettings): """Libvirt host settings definitions.""" def __init__(self, *args, **kwargs): super(LibvirtHostSettings, self).__init__(*args, **kwargs) self.libvirt_image_dir = None self.libvirt_hostname = None def read(self, reader): """Read libvirt host settings.""" self.libvirt_image_dir = reader.get( 'compute_resources', 'libvirt_image_dir', '/var/lib/libvirt/images' ) self.libvirt_hostname = reader.get( 'compute_resources', 'libvirt_hostname') def validate(self): """Validate libvirt host settings.""" validation_errors = [] if self.libvirt_hostname is None: validation_errors.append( '[compute_resources] libvirt_hostname option must be provided.' ) return validation_errors class FakeCapsuleSettings(FeatureSettings): """Fake Capsule settings definitions.""" def __init__(self, *args, **kwargs): super(FakeCapsuleSettings, self).__init__(*args, **kwargs) self.port_range = None def read(self, reader): """Read fake capsule settings""" self.port_range = reader.get( 'fake_capsules', 'port_range', cast=tuple ) def validate(self): """Validate fake capsule settings.""" validation_errors = [] if self.port_range is None: validation_errors.append( '[fake_capsules] port_range option must be provided.' ) return validation_errors class RHEVSettings(FeatureSettings): """RHEV settings definitions.""" def __init__(self, *args, **kwargs): super(RHEVSettings, self).__init__(*args, **kwargs) # Compute Resource Information self.hostname = None self.username = None self.password = None self.datacenter = None self.vm_name = None # Image Information self.image_os = None self.image_arch = None self.image_username = None self.image_password = None self.image_name = None def read(self, reader): """Read rhev settings.""" # Compute Resource Information self.hostname = reader.get('rhev', 'hostname') self.username = reader.get('rhev', 'username') self.password = reader.get('rhev', 'password') self.datacenter = reader.get('rhev', 'datacenter') self.vm_name = reader.get('rhev', 'vm_name') # Image Information self.image_os = reader.get('rhev', 'image_os') self.image_arch = reader.get('rhev', 'image_arch') self.image_username = reader.get('rhev', 'image_username') self.image_password = reader.get('rhev', 'image_password') self.image_name = reader.get('rhev', 'image_name') def validate(self): """Validate rhev settings.""" validation_errors = [] if not all(vars(self).values()): validation_errors.append( 'All [rhev] hostname, username, password, datacenter, ' 'vm_name, image_name, image_os, image_arch, image_usernam, ' 'image_name options must be provided.' ) return validation_errors class VmWareSettings(FeatureSettings): """VmWare settings definitions.""" def __init__(self, *args, **kwargs): super(VmWareSettings, self).__init__(*args, **kwargs) # Compute Resource Information self.vcenter = None self.username = None self.password = None self.datacenter = None self.vm_name = None # Image Information self.image_os = None self.image_arch = None self.image_username = None self.image_password = None self.image_name = None def read(self, reader): """Read vmware settings.""" # Compute Resource Information self.vcenter = reader.get('vmware', 'hostname') self.username = reader.get('vmware', 'username') self.password = reader.get('vmware', 'password') self.datacenter = reader.get('vmware', 'datacenter') self.vm_name = reader.get('vmware', 'vm_name') # Image Information self.image_os = reader.get('vmware', 'image_os') self.image_arch = reader.get('vmware', 'image_arch') self.image_username = reader.get('vmware', 'image_username') self.image_password = reader.get('vmware', 'image_password') self.image_name = reader.get('vmware', 'image_name') def validate(self): """Validate vmware settings.""" validation_errors = [] if not all(vars(self).values()): validation_errors.append( 'All [vmware] hostname, username, password, datacenter, ' 'vm_name, image_name, image_os, image_arch, image_usernam, ' 'image_name options must be provided.' ) return validation_errors class DiscoveryISOSettings(FeatureSettings): """Discovery ISO name settings definition.""" def __init__(self, *args, **kwargs): super(DiscoveryISOSettings, self).__init__(*args, **kwargs) self.discovery_iso = None def read(self, reader): """Read discovery iso setting.""" self.discovery_iso = reader.get('discovery', 'discovery_iso') def validate(self): """Validate discovery iso name setting.""" validation_errors = [] if self.discovery_iso is None: validation_errors.append( '[discovery] discovery iso name must be provided.' ) return validation_errors class OscapSettings(FeatureSettings): """Oscap settings definitions.""" def __init__(self, *args, **kwargs): super(OscapSettings, self).__init__(*args, **kwargs) self.content_path = None def read(self, reader): """Read Oscap settings.""" self.content_path = reader.get('oscap', 'content_path') def validate(self): """Validate Oscap settings.""" validation_errors = [] if self.content_path is None: validation_errors.append( '[oscap] content_path option must be provided.' ) return validation_errors class PerformanceSettings(FeatureSettings): """Performance settings definitions.""" def __init__(self, *args, **kwargs): super(PerformanceSettings, self).__init__(*args, **kwargs) self.time_hammer = None self.cdn_address = None self.virtual_machines = None self.fresh_install_savepoint = None self.enabled_repos_savepoint = None self.csv_buckets_count = None self.sync_count = None self.sync_type = None self.repos = None def read(self, reader): """Read performance settings.""" self.time_hammer = reader.get( 'performance', 'time_hammer', False, bool) self.cdn_address = reader.get( 'performance', 'cdn_address') self.virtual_machines = reader.get( 'performance', 'virtual_machines', cast=list) self.fresh_install_savepoint = reader.get( 'performance', 'fresh_install_savepoint') self.enabled_repos_savepoint = reader.get( 'performance', 'enabled_repos_savepoint') self.csv_buckets_count = reader.get( 'performance', 'csv_buckets_count', 10, int) self.sync_count = reader.get( 'performance', 'sync_count', 3, int) self.sync_type = reader.get( 'performance', 'sync_type', 'sync') self.repos = reader.get( 'performance', 'repos', cast=list) def validate(self): """Validate performance settings.""" validation_errors = [] if self.cdn_address is None: validation_errors.append( '[performance] cdn_address must be provided.') if self.virtual_machines is None: validation_errors.append( '[performance] virtual_machines must be provided.') if self.fresh_install_savepoint is None: validation_errors.append( '[performance] fresh_install_savepoint must be provided.') if self.enabled_repos_savepoint is None: validation_errors.append( '[performance] enabled_repos_savepoint must be provided.') return validation_errors class RHAISettings(FeatureSettings): """RHAI settings definitions.""" def __init__(self, *args, **kwargs): super(RHAISettings, self).__init__(*args, **kwargs) self.insights_client_el6repo = None self.insights_client_el7repo = None def read(self, reader): """Read RHAI settings.""" self.insights_client_el6repo = reader.get( 'rhai', 'insights_client_el6repo') self.insights_client_el7repo = reader.get( 'rhai', 'insights_client_el7repo') def validate(self): """Validate RHAI settings.""" return [] class TransitionSettings(FeatureSettings): """Transition settings definitions.""" def __init__(self, *args, **kwargs): super(TransitionSettings, self).__init__(*args, **kwargs) self.exported_data = None def read(self, reader): """Read transition settings.""" self.exported_data = reader.get('transition', 'exported_data') def validate(self): """Validate transition settings.""" validation_errors = [] if self.exported_data is None: validation_errors.append( '[transition] exported_data must be provided.') return validation_errors class VlanNetworkSettings(FeatureSettings): """Vlan Network settings definitions.""" def __init__(self, *args, **kwargs): super(VlanNetworkSettings, self).__init__(*args, **kwargs) self.subnet = None self.netmask = None self.gateway = None self.bridge = None def read(self, reader): """Read Vlan Network settings.""" self.subnet = reader.get('vlan_networking', 'subnet') self.netmask = reader.get('vlan_networking', 'netmask') self.gateway = reader.get('vlan_networking', 'gateway') self.bridge = reader.get('vlan_networking', 'bridge') def validate(self): """Validate Vlan Network settings.""" validation_errors = [] if not all(vars(self).values()): validation_errors.append( 'All [vlan_networking] subnet, netmask, gateway, bridge ' 'options must be provided.') return validation_errors class UpgradeSettings(FeatureSettings): """Satellite upgrade settings definitions.""" def __init__(self, *args, **kwargs): super(UpgradeSettings, self).__init__(*args, **kwargs) self.upgrade_data = None def read(self, reader): """Read and validate Satellite server settings.""" self.upgrade_data = reader.get('upgrade', 'upgrade_data') def validate(self): validation_errors = [] if self.upgrade_data is None: validation_errors.append('[upgrade] data must be provided.') return validation_errors class Settings(object): """Robottelo's settings representation.""" def __init__(self): self._all_features = None self._configured = False self._validation_errors = [] self.browser = None self.locale = None self.project = None self.reader = None self.rhel6_repo = None self.rhel7_repo = None self.screenshots_path = None self.saucelabs_key = None self.saucelabs_user = None self.server = ServerSettings() self.run_one_datapoint = None self.upstream = None self.verbosity = None self.webdriver = None self.webdriver_binary = None self.webdriver_desired_capabilities = None # Features self.clients = ClientsSettings() self.compute_resources = LibvirtHostSettings() self.discovery = DiscoveryISOSettings() self.docker = DockerSettings() self.fake_capsules = FakeCapsuleSettings() self.fake_manifest = FakeManifestSettings() self.ldap = LDAPSettings() self.oscap = OscapSettings() self.performance = PerformanceSettings() self.rhai = RHAISettings() self.rhev = RHEVSettings() self.transition = TransitionSettings() self.vlan_networking = VlanNetworkSettings() self.upgrade = UpgradeSettings() self.vmware = VmWareSettings() def configure(self): """Read the settings file and parse the configuration. :raises: ImproperlyConfigured if any issue is found during the parsing or validation of the configuration. """ if self.configured: # TODO: what to do here, raise and exception, just skip or ...? return # Expect the settings file to be on the robottelo project root. settings_path = os.path.join(get_project_root(), SETTINGS_FILE_NAME) if not os.path.isfile(settings_path): raise ImproperlyConfigured( 'Not able to find settings file at {}'.format(settings_path)) self.reader = INIReader(settings_path) self._read_robottelo_settings() self._validation_errors.extend( self._validate_robottelo_settings()) self.server.read(self.reader) self._validation_errors.extend(self.server.validate()) if self.reader.has_section('clients'): self.clients.read(self.reader) self._validation_errors.extend(self.clients.validate()) if self.reader.has_section('compute_resources'): self.compute_resources.read(self.reader) self._validation_errors.extend(self.compute_resources.validate()) if self.reader.has_section('discovery'): self.discovery.read(self.reader) self._validation_errors.extend(self.discovery.validate()) if self.reader.has_section('docker'): self.docker.read(self.reader) self._validation_errors.extend(self.docker.validate()) if self.reader.has_section('fake_capsules'): self.fake_capsules.read(self.reader) self._validation_errors.extend(self.fake_capsules.validate()) if self.reader.has_section('fake_manifest'): self.fake_manifest.read(self.reader) self._validation_errors.extend(self.fake_manifest.validate()) if self.reader.has_section('ldap'): self.ldap.read(self.reader) self._validation_errors.extend(self.ldap.validate()) if self.reader.has_section('oscap'): self.oscap.read(self.reader) self._validation_errors.extend(self.oscap.validate()) if self.reader.has_section('performance'): self.performance.read(self.reader) self._validation_errors.extend(self.performance.validate()) if self.reader.has_section('rhai'): self.rhai.read(self.reader) self._validation_errors.extend(self.rhai.validate()) if self.reader.has_section('rhev'): self.rhev.read(self.reader) self._validation_errors.extend(self.rhev.validate()) if self.reader.has_section('transition'): self.transition.read(self.reader) self._validation_errors.extend(self.transition.validate()) if self.reader.has_section('vlan_networking'): self.vlan_networking.read(self.reader) self._validation_errors.extend(self.vlan_networking.validate()) if self.reader.has_section('upgrade'): self.upgrade.read(self.reader) self._validation_errors.extend(self.upgrade.validate()) if self.reader.has_section('vmware'): self.vmware.read(self.reader) self._validation_errors.extend(self.vmware.validate()) if self._validation_errors: raise ImproperlyConfigured( 'Failed to validate the configuration, check the message(s):\n' '{}'.format('\n'.join(self._validation_errors)) ) self._configure_logging() self._configure_third_party_logging() self._configure_entities() self._configured = True def _read_robottelo_settings(self): """Read Robottelo's general settings.""" self.log_driver_commands = self.reader.get( 'robottelo', 'log_driver_commands', ['newSession', 'windowMaximize', 'get', 'findElement', 'sendKeysToElement', 'clickElement', 'mouseMoveTo'], list ) self.browser = self.reader.get( 'robottelo', 'browser', 'selenium') self.locale = self.reader.get('robottelo', 'locale', 'en_US.UTF-8') self.project = self.reader.get('robottelo', 'project', 'sat') self.rhel6_repo = self.reader.get('robottelo', 'rhel6_repo', None) self.rhel7_repo = self.reader.get('robottelo', 'rhel7_repo', None) self.screenshots_path = self.reader.get( 'robottelo', 'screenshots_path', '/tmp/robottelo/screenshots') self.run_one_datapoint = self.reader.get( 'robottelo', 'run_one_datapoint', False, bool) self.cleanup = self.reader.get('robottelo', 'cleanup', False, bool) self.upstream = self.reader.get('robottelo', 'upstream', True, bool) self.verbosity = self.reader.get( 'robottelo', 'verbosity', INIReader.cast_logging_level('debug'), INIReader.cast_logging_level ) self.webdriver = self.reader.get( 'robottelo', 'webdriver', 'firefox') self.saucelabs_user = self.reader.get( 'robottelo', 'saucelabs_user', None) self.saucelabs_key = self.reader.get( 'robottelo', 'saucelabs_key', None) self.webdriver_binary = self.reader.get( 'robottelo', 'webdriver_binary', None) self.webdriver_desired_capabilities = self.reader.get( 'robottelo', 'webdriver_desired_capabilities', None, cast=INIReader.cast_webdriver_desired_capabilities ) self.window_manager_command = self.reader.get( 'robottelo', 'window_manager_command', None) def _validate_robottelo_settings(self): """Validate Robottelo's general settings.""" validation_errors = [] browsers = ('selenium', 'docker', 'saucelabs') webdrivers = ('chrome', 'firefox', 'ie', 'phantomjs', 'remote') if self.browser not in browsers: validation_errors.append( '[robottelo] browser should be one of {0}.' .format(', '.join(browsers)) ) if self.webdriver not in webdrivers: validation_errors.append( '[robottelo] webdriver should be one of {0}.' .format(', '.join(webdrivers)) ) if self.browser == 'saucelabs': if self.saucelabs_user is None: validation_errors.append( '[robottelo] saucelabs_user must be provided when ' 'browser is saucelabs.' ) if self.saucelabs_key is None: validation_errors.append( '[robottelo] saucelabs_key must be provided when ' 'browser is saucelabs.' ) return validation_errors @property def configured(self): """Returns True if the settings have already been configured.""" return self._configured @property def all_features(self): """List all expected feature settings sections.""" if self._all_features is None: self._all_features = [ name for name, value in vars(self).items() if isinstance(value, FeatureSettings) ] return self._all_features def _configure_entities(self): """Configure NailGun's entity classes. Do the following: * Set ``entity_mixins.CREATE_MISSING`` to ``True``. This causes method ``EntityCreateMixin.create_raw`` to generate values for empty and required fields. * Set ``nailgun.entity_mixins.DEFAULT_SERVER_CONFIG`` to whatever is returned by :meth:`robottelo.helpers.get_nailgun_config`. See ``robottelo.entity_mixins.Entity`` for more information on the effects of this. * Set a default value for ``nailgun.entities.GPGKey.content``. * Set the default value for ``nailgun.entities.DockerComputeResource.url`` if either ``docker.internal_url`` or ``docker.external_url`` is set in the configuration file. """ entity_mixins.CREATE_MISSING = True entity_mixins.DEFAULT_SERVER_CONFIG = ServerConfig( self.server.get_url(), self.server.get_credentials(), verify=False, ) gpgkey_init = entities.GPGKey.__init__ def patched_gpgkey_init(self, server_config=None, **kwargs): """Set a default value on the ``content`` field.""" gpgkey_init(self, server_config, **kwargs) self._fields['content'].default = os.path.join( get_project_root(), 'tests', 'foreman', 'data', 'valid_gpg_key.txt' ) entities.GPGKey.__init__ = patched_gpgkey_init # NailGun provides a default value for ComputeResource.url. We override # that value if `docker.internal_url` or `docker.external_url` is set. docker_url = None # Try getting internal url docker_url = self.docker.get_unix_socket_url() # Try getting external url if docker_url is None: docker_url = self.docker.external_url if docker_url is not None: dockercr_init = entities.DockerComputeResource.__init__ def patched_dockercr_init(self, server_config=None, **kwargs): """Set a default value on the ``docker_url`` field.""" dockercr_init(self, server_config, **kwargs) self._fields['url'].default = docker_url entities.DockerComputeResource.__init__ = patched_dockercr_init def _configure_logging(self): """Configure logging for the entire framework. If a config named ``logging.conf`` exists in Robottelo's root directory, the logger is configured using the options in that file. Otherwise, a custom logging output format is set, and default values are used for all other logging options. """ # All output should be made by the logging module, including warnings logging.captureWarnings(True) # Set the logging level based on the Robottelo's verbosity for name in ('nailgun', 'robottelo'): logging.getLogger(name).setLevel(self.verbosity) # Allow overriding logging config based on the presence of logging.conf # file on Robottelo's project root logging_conf_path = os.path.join(get_project_root(), 'logging.conf') if os.path.isfile(logging_conf_path): config.fileConfig(logging_conf_path) else: logging.basicConfig( format='%(levelname)s %(module)s:%(lineno)d: %(message)s' ) def _configure_third_party_logging(self): """Increase the level of third party packages logging.""" loggers = ( 'bugzilla', 'easyprocess', 'paramiko', 'requests.packages.urllib3.connectionpool', 'selenium.webdriver.remote.remote_connection', ) for logger in loggers: logging.getLogger(logger).setLevel(logging.WARNING)
Ichimonji10/robottelo
robottelo/config/base.py
Python
gpl-3.0
35,889
<!-- * Autor = Javi Cancela * Fecha = 19 de nov. de 2015 * Licencia = gpl3.0 * Version = 1.0 * Descripcion = */ /* Copyright (C) 2015 Javier Cancela 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/>. */ --> <html> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <script type="text/javascript"> function validar(){ if (document.getElementById("alta").checked === false){ alert("se envia a baja"); document.getElementById("formulario").action = "http://www.baja.asp" } } </script> <form method="post" id="formulario" name="formulario" onsubmit="return validar()" action="http://www.alta.asp"> <input type="checkbox" id="alta" name="alta" value="Darse de alta" checked="checked">Butter <br> <input type="submit" value="Enviar datos" name="enviar"> </form> </body> </html>
cancelajavi/2-DAW
workspace/Tema5_JS/Ejercicios2Tema5/ejer1.html
HTML
gpl-3.0
1,486
//---------------------------------------------------------------------------- /** @file RlTimeControl.cpp */ //---------------------------------------------------------------------------- #include "SgSystem.h" #include "RlTimeControl.h" #include "SgTimeRecord.h" using namespace std; //---------------------------------------------------------------------------- IMPLEMENT_OBJECT(RlTimeControl); RlTimeControl::RlTimeControl(GoBoard& board) : GoTimeControl(board), RlAutoObject(board), m_fraction(1.0) { } void RlTimeControl::LoadSettings(istream& settings) { double remain, finalspace, fastfactor; int fastopen; settings >> RlSetting<int>("FastOpen", fastopen); settings >> RlSetting<double>("FastFactor", fastfactor); settings >> RlSetting<double>("RemainingConstant", remain); settings >> RlSetting<double>("MinTime", m_quickTime); settings >> RlSetting<double>("FinalSpace", finalspace); settings >> RlSetting<double>("Fraction", m_fraction); settings >> RlSetting<double>("SafetyTime", m_safetyTime); SetFastOpenMoves(fastopen); SetFastOpenFactor(fastfactor); SetRemainingConstant(remain); SetMinTime(m_quickTime); SetFinalSpace(finalspace); } double RlTimeControl::TimeForCurrentMove(const SgTimeRecord& timeRecord, bool quiet) { double timeForMove = m_fraction * GoTimeControl::TimeForCurrentMove( timeRecord, quiet); double timeLeft = timeRecord.TimeLeft(m_board.ToPlay()); if (timeLeft < m_safetyTime && timeRecord.MovesLeft(m_board.ToPlay()) != 1) return m_quickTime; if (m_fastAfterPass && m_board.GetLastMove() == SG_PASS) return m_quickTime; return timeForMove; } //----------------------------------------------------------------------------
svn2github/rlgo
rlgo/RlTimeControl.cpp
C++
gpl-3.0
1,816
/* Copyright (C) 2009 Brendan Doherty Copyright (C) 2011 Gerhard Olsson This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Diagnostics; using System.Drawing; using System.Collections.Generic; using ZoneFiveSoftware.Common.Data; using ZoneFiveSoftware.Common.Data.GPS; using ZoneFiveSoftware.Common.Data.Fitness; using ZoneFiveSoftware.Common.Data.Measurement; using ZoneFiveSoftware.Common.Visuals.Fitness; using ITrailExport; using TrailsPlugin.Data; using TrailsPlugin.Utils; using GpsRunningPlugin.Util; namespace TrailsPlugin.Export { public sealed class CFTrailResult : ITrailResult { public CFTrailResult(TrailResult tr) { this.m_tr = tr; } private TrailResult m_tr; /**********************************************************/ #region Implementation of ITrailResult float ITrailResult.AvgCadence { get { return this.m_tr.AvgCadence; } } float ITrailResult.AvgGrade { get { return 100 * this.m_tr.AscAvgGrade; } } float ITrailResult.AvgHR { get { return this.m_tr.AvgHR; } } double ITrailResult.AvgPace { get { return (float)UnitUtil.Pace.ConvertFrom(this.m_tr.AvgSpeed); } } float ITrailResult.AvgPower { get { return this.m_tr.AvgPower; } } float ITrailResult.AvgSpeed { get { return (float)UnitUtil.Speed.ConvertFrom(this.m_tr.AvgSpeed); } } INumericTimeDataSeries ITrailResult.CadencePerMinuteTrack { get { return this.m_tr.CadencePerMinuteTrack0(); } } IActivityCategory ITrailResult.Category { get { return this.m_tr.Category; } } INumericTimeDataSeries ITrailResult.CopyTrailTrack(INumericTimeDataSeries source) { return this.m_tr.CopyTrailTrack(source); } string ITrailResult.Distance { get { return UnitUtil.Distance.ToString(this.m_tr.Distance, ""); } } IDistanceDataTrack ITrailResult.DistanceMetersTrack { get { return this.m_tr.DistanceMetersTrack; } } TimeSpan ITrailResult.Duration { get { return this.m_tr.Duration; } } string ITrailResult.ElevChg { get { return (this.m_tr.ElevChg > 0 ? "+" : "") + UnitUtil.Elevation.ToString(this.m_tr.ElevChg, ""); } } INumericTimeDataSeries ITrailResult.ElevationMetersTrack { get { return this.m_tr.ElevationMetersTrack0(); } } TimeSpan ITrailResult.EndTime { get { return this.m_tr.EndTimeOfDay; } } double ITrailResult.FastestPace { get { return UnitUtil.Pace.ConvertFrom(this.m_tr.FastestSpeed, this.m_tr.Activity); } } float ITrailResult.FastestSpeed { get { return (float)UnitUtil.Speed.ConvertFrom(this.m_tr.FastestSpeed, this.m_tr.Activity); } } INumericTimeDataSeries ITrailResult.GradeTrack { get { return this.m_tr.GradeTrack0(); } } INumericTimeDataSeries ITrailResult.HeartRatePerMinuteTrack { get { return this.m_tr.HeartRatePerMinuteTrack0(); } } float ITrailResult.MaxHR { get { return this.m_tr.MaxHR; } } int ITrailResult.Order { get { return this.m_tr.Order; } } INumericTimeDataSeries ITrailResult.PaceTrack { get { return this.m_tr.PaceTrack0(); } } INumericTimeDataSeries ITrailResult.PowerWattsTrack { get { return this.m_tr.PowerWattsTrack0(); } } INumericTimeDataSeries ITrailResult.SpeedTrack { get { return this.m_tr.SpeedTrack0(); } } TimeSpan ITrailResult.StartTime { get { return this.m_tr.StartTimeOfDay; } } #endregion } }
gerhardol/trails
Export/CFTrailResult.cs
C#
gpl-3.0
5,046
/* http.h - HTTP protocol handler * Copyright (C) 1999, 2000, 2001, 2003, 2006, * 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - 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. * * or * * - 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. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #ifndef GNUPG_COMMON_HTTP_H #define GNUPG_COMMON_HTTP_H #include <gpg-error.h> #include "strlist.h" struct uri_tuple_s { struct uri_tuple_s *next; const char *name; /* A pointer into name. */ char *value; /* A pointer to value (a Nul is always appended). */ size_t valuelen; /* The real length of the value; we need it because the value may contain embedded Nuls. */ int no_value; /* True if no value has been given in the URL. */ }; typedef struct uri_tuple_s *uri_tuple_t; struct parsed_uri_s { /* All these pointers point into BUFFER; most stuff is not escaped. */ char *scheme; /* Pointer to the scheme string (always lowercase). */ unsigned int is_http:1; /* This is a HTTP style URI. */ unsigned int use_tls:1; /* Whether TLS should be used. */ unsigned int opaque:1;/* Unknown scheme; PATH has the rest. */ unsigned int v6lit:1; /* Host was given as a literal v6 address. */ char *auth; /* username/password for basic auth. */ char *host; /* Host (converted to lowercase). */ unsigned short port; /* Port (always set if the host is set). */ char *path; /* Path. */ uri_tuple_t params; /* ";xxxxx" */ uri_tuple_t query; /* "?xxx=yyy" */ char buffer[1]; /* Buffer which holds a (modified) copy of the URI. */ }; typedef struct parsed_uri_s *parsed_uri_t; typedef enum { HTTP_REQ_GET = 1, HTTP_REQ_HEAD = 2, HTTP_REQ_POST = 3, HTTP_REQ_PATCH = 4, HTTP_REQ_OPAQUE = 5 /* Internal use. */ } http_req_t; /* We put the flag values into an enum, so that gdb can display them. */ enum { HTTP_FLAG_TRY_PROXY = 1, /* Try to use a proxy. */ HTTP_FLAG_SHUTDOWN = 2, /* Close sending end after the request. */ HTTP_FLAG_LOG_RESP = 8, /* Log the server respone. */ HTTP_FLAG_FORCE_TLS = 16, /* Force the use opf TLS. */ HTTP_FLAG_IGNORE_CL = 32, /* Ignore content-length. */ HTTP_FLAG_IGNORE_IPv4 = 64, /* Do not use IPv4. */ HTTP_FLAG_IGNORE_IPv6 = 128, /* Do not use IPv6. */ HTTP_FLAG_AUTH_BEARER = 512 /* Use Bearer authtype instead of Basic. */ }; struct http_session_s; typedef struct http_session_s *http_session_t; struct http_context_s; typedef struct http_context_s *http_t; void http_register_tls_callback (gpg_error_t (*cb)(http_t,http_session_t,int)); void http_register_tls_ca (const char *fname); gpg_error_t http_session_new (http_session_t *r_session, const char *tls_priority); http_session_t http_session_ref (http_session_t sess); void http_session_release (http_session_t sess); void http_session_set_log_cb (http_session_t sess, void (*cb)(http_session_t, gpg_error_t, const char *, const void **, size_t *)); gpg_error_t http_parse_uri (parsed_uri_t *ret_uri, const char *uri, int no_scheme_check); void http_release_parsed_uri (parsed_uri_t uri); gpg_error_t http_raw_connect (http_t *r_hd, const char *server, unsigned short port, unsigned int flags, const char *srvtag); gpg_error_t http_open (http_t *r_hd, http_req_t reqtype, const char *url, const char *httphost, const char *auth, unsigned int flags, const char *proxy, http_session_t session, const char *srvtag, strlist_t headers); void http_start_data (http_t hd); gpg_error_t http_wait_response (http_t hd); void http_close (http_t hd, int keep_read_stream); gpg_error_t http_open_document (http_t *r_hd, const char *document, const char *auth, unsigned int flags, const char *proxy, http_session_t session, const char *srvtag, strlist_t headers); estream_t http_get_read_ptr (http_t hd); estream_t http_get_write_ptr (http_t hd); unsigned int http_get_status_code (http_t hd); const char *http_get_tls_info (http_t hd, const char *what); const char *http_get_header (http_t hd, const char *name); const char **http_get_header_names (http_t hd); gpg_error_t http_verify_server_credentials (http_session_t sess); char *http_escape_string (const char *string, const char *specials); char *http_escape_data (const void *data, size_t datalen, const char *specials); #endif /*GNUPG_COMMON_HTTP_H*/
gpg/payproc
src/http.h
C
gpl-3.0
5,791
/* This file is part of mantoQSAR. mantoQSAR - Quantitative structure-activity relationship descriptor calculation and modeling for biomolecules. Copyright (C) 2016 Jörg Kittelmann mantoQSAR is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. mantoQSAR 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 mantoQSAR. If not, see <http://www.gnu.org/licenses/>. */ package org.mantoQSAR.gui.molecule; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileFilter; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileSystemView; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.mantoQSAR.core.util.ColorStatic; import org.mantoQSAR.gui.GuiModel; public class ProjectTree extends JPanel { private FileSystemView fileSystemView; private final JTree tree; private DefaultTreeModel treeModel; private GuiModel guiModel; private MoleculeController moleculeController; public ProjectTree() { guiModel = GuiModel.getInstance(); moleculeController = MoleculeController.getInstance(); fileSystemView = FileSystemView.getFileSystemView(); this.setLayout(new BorderLayout()); DefaultMutableTreeNode root = new DefaultMutableTreeNode(); treeModel = new DefaultTreeModel(root); TreeSelectionListener treeSelectionListener = new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent tse) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tse.getPath().getLastPathComponent(); File file = (File) node.getUserObject(); if (!file.isFile()) { showChildren(node, 2); } if (file.isFile()) { showFileContent(node); } } }; FileFilter directoryFilter = new FileFilter() { @Override public boolean accept(File file) { return file.isDirectory(); } }; File projectFolder = guiModel.getMantoProjectFolder(); System.out.println(ColorStatic.PURPLE + "Project folder identified as " + projectFolder.toString() + ColorStatic.RESET); File[] projectRoot = projectFolder.listFiles(directoryFilter); DefaultMutableTreeNode node = new DefaultMutableTreeNode(projectFolder); root.add(node); showChildren(node, 3); MouseListener ml = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); if (selRow != -1) { if (e.getClickCount() == 1) { } else if (e.getClickCount() == 2) { DefaultMutableTreeNode tn = (DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent(); File f = (File) tn.getUserObject(); moleculeController.openProject(f); } } } }; tree = new JTree(treeModel); tree.setRootVisible(false); tree.addTreeSelectionListener(treeSelectionListener); tree.addMouseListener(ml); tree.setCellRenderer(new FileTreeCellRenderer()); tree.expandRow(0); tree.setBorder(new EmptyBorder(5, 5, 5, 5)); JScrollPane treeScroll = new JScrollPane(tree); add(treeScroll, BorderLayout.CENTER); } public void showRootFile() { tree.setSelectionInterval(0, 0); } private TreePath findTreePath(File find) { for (int ii = 0; ii < tree.getRowCount(); ii++) { TreePath treePath = tree.getPathForRow(ii); Object object = treePath.getLastPathComponent(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) object; File nodeFile = (File) node.getUserObject(); if (nodeFile == find) { return treePath; } } return null; } private void showErrorMessage(String errorMessage, String errorTitle) { JOptionPane.showMessageDialog( this, errorMessage, errorTitle, JOptionPane.ERROR_MESSAGE ); } private void showChildren(final DefaultMutableTreeNode node, final Integer depth) { if (depth <= 0) { return; } File file = (File) node.getUserObject(); if (file.isDirectory()) { File[] files = fileSystemView.getFiles(file, true); //!! node.removeAllChildren(); for (File child : files) { DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child); if (!child.isDirectory() & depth > 2) { // do not show files in main directory } else { node.add(childNode); } if (child.isDirectory()) { showChildren(childNode, depth - 1); } } } } private void showFileContent(DefaultMutableTreeNode node) { File file = (File) node.getUserObject(); String extension = ""; String fileName = file.toString(); int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i + 1); } if ("pqr".equals(extension) || "pdb".equals(extension)) { } } class FileTreeCellRenderer extends DefaultTreeCellRenderer { private final FileSystemView fileSystemView; private final JLabel label; private final ImageIcon folderCollapseImage = new ImageIcon(this.getClass().getResource("/org/mantoQSAR/gui/resources/icons/folder-open-img16x16.png")); private final ImageIcon folderExpandImage = new ImageIcon(this.getClass().getResource("/org/mantoQSAR/gui/resources/icons/folder-img16x16.png")); private final ImageIcon fileImage = new ImageIcon(this.getClass().getResource("/org/mantoQSAR/gui/resources/icons/text-x-generic-img16x16.png")); public FileTreeCellRenderer() { label = new JLabel(); label.setOpaque(true); fileSystemView = FileSystemView.getFileSystemView(); } @Override public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; File file = (File) node.getUserObject(); label.setIcon(fileImage); if (file.isDirectory()) { label.setIcon(folderCollapseImage); } if (expanded) { label.setIcon(folderExpandImage); } if (file.isDirectory()) { label.setText(fileSystemView.getSystemDisplayName(file)); } else { label.setText(file.getName()); } label.setToolTipText(file.getPath()); if (selected) { label.setBackground(backgroundSelectionColor); label.setForeground(textSelectionColor); } else { label.setBackground(backgroundNonSelectionColor); label.setForeground(textNonSelectionColor); } return label; } } }
jorkKit/mantoQSAR
gui/src/org/mantoQSAR/gui/molecule/ProjectTree.java
Java
gpl-3.0
8,673
package com.thirtySix.repository; import org.springframework.data.repository.PagingAndSortingRepository; import com.thirtySix.model.Booking; public interface BookingRepository extends PagingAndSortingRepository<Booking, String> { }
AbnerLin/ThirtySix
src/main/java/com/thirtySix/repository/BookingRepository.java
Java
gpl-3.0
237
<?php /** * Piwik - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik\Plugins\Actions\Reports; use Piwik\Piwik; use Piwik\Plugin\ViewDataTable; use Piwik\Plugins\Actions\Columns\EntryPageTitle; use Piwik\Plugins\Actions\Columns\Metrics\AveragePageGenerationTime; use Piwik\Plugins\Actions\Columns\Metrics\AverageTimeOnPage; use Piwik\Plugins\Actions\Columns\Metrics\BounceRate; use Piwik\Plugins\Actions\Columns\Metrics\ExitRate; use Piwik\Plugin\ReportsProvider; use Piwik\Report\ReportWidgetFactory; use Piwik\Widget\WidgetsList; class GetEntryPageTitles extends Base { protected function init() { parent::init(); $this->dimension = new EntryPageTitle(); $this->name = Piwik::translate('Actions_EntryPageTitles'); $this->documentation = Piwik::translate('Actions_EntryPageTitlesReportDocumentation', '<br />') . ' ' . Piwik::translate('General_UsePlusMinusIconsDocumentation'); $this->metrics = array('entry_nb_visits', 'entry_bounce_count'); $this->processedMetrics = array( new AverageTimeOnPage(), new BounceRate(), new ExitRate(), new AveragePageGenerationTime() ); $this->order = 6; $this->actionToLoadSubTables = $this->action; $this->subcategoryId = 'Actions_SubmenuPagesEntry'; } public function configureWidgets(WidgetsList $widgetsList, ReportWidgetFactory $factory) { $widgetsList->addWidgetConfig($factory->createWidget()->setName('Actions_WidgetEntryPageTitles')); } public function getProcessedMetrics() { $result = parent::getProcessedMetrics(); // these metrics are not displayed in the API.getProcessedReport version of this report, // so they are removed here. unset($result['avg_time_on_page']); unset($result['exit_rate']); return $result; } protected function getMetricsDocumentation() { $metrics = parent::getMetricsDocumentation(); $metrics['bounce_rate'] = Piwik::translate('General_ColumnPageBounceRateDocumentation'); // remove these metrics from API.getProcessedReport version of this report unset($metrics['avg_time_on_page']); unset($metrics['exit_rate']); return $metrics; } public function configureView(ViewDataTable $view) { $view->config->addTranslations(array('label' => $this->dimension->getName())); $view->config->columns_to_display = array('label', 'entry_nb_visits', 'entry_bounce_count', 'bounce_rate'); $view->config->title = $this->name; $view->requestConfig->filter_sort_column = 'entry_nb_visits'; $this->addPageDisplayProperties($view); $this->addBaseDisplayProperties($view); } public function getRelatedReports() { return array( ReportsProvider::factory('Actions', 'getPageTitles'), ReportsProvider::factory('Actions', 'getEntryPageUrls') ); } }
piwik/piwik
plugins/Actions/Reports/GetEntryPageTitles.php
PHP
gpl-3.0
3,152