code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// CellError.hpp // // Copyright (C) 2006-2007 Peter Graves <peter@armedbear.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 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #ifndef __CELL_ERROR_HPP #define __CELL_ERROR_HPP class CellError : public Condition { private: static Layout * get_layout_for_class(); public: CellError() : Condition(WIDETAG_CONDITION, get_layout_for_class()) { set_slot_value(S_name, NIL); } CellError(Value name) : Condition(WIDETAG_CONDITION, get_layout_for_class()) { set_slot_value(S_name, name); } void initialize(Value initargs); virtual Value type_of() const { return S_cell_error; } virtual Value class_of() const { return C_cell_error; } virtual bool typep(Value type) const; }; #endif // CellError.hpp
gnooth/xcl
kernel/CellError.hpp
C++
gpl-2.0
1,431
/* * Grace - GRaphing, Advanced Computation and Exploration of data * * Home page: http://plasma-gate.weizmann.ac.il/Grace/ * * Copyright (c) 1991-1995 Paul J Turner, Portland, OR * Copyright (c) 1996-2002 Grace Development Team * * Maintained by Evgeny Stambulchik * * Modified by Andreas Winter 2008-2011 * * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * * spreadsheet data stuff * */ ///#include <config.h> #include <cstdio> #include <cstdlib> #include <cstring> #include "defines.h" #include "globals.h" #include "utils.h" #include "graphs.h" #include "graphutils.h" #include "files.h" #include "ssdata.h" #include "parser.h" #include "noxprotos.h" extern bool exchange_point_comma; extern int new_set_no; double *copy_data_column(double *src, int nrows) { double *dest; dest = (double*)xmalloc(nrows*sizeof(double)); if (dest != NULL) { memcpy(dest, src, nrows*sizeof(double)); } return dest; } char **copy_string_column(char **src, int nrows) { char **dest; int i; dest = (char **)xmalloc(nrows*sizeof(char *)); if (dest != NULL) { for (i = 0; i < nrows; i++) dest[i] =copy_string(NULL, src[i]); } return dest; } /* TODO: index_shift */ double *allocate_index_data(int nrows) { int i; double *retval; retval = (double*)xmalloc(nrows*sizeof(double)); if (retval != NULL) { for (i = 0; i < nrows; i++) { retval[i] = i; } } return retval; } double *allocate_mesh(double start, double stop, int len) { int i; double *retval; retval = (double*)xmalloc(len*sizeof(double)); if (retval != NULL) { double s = (start + stop)/2, d = (stop - start)/2; for (i = 0; i < len; i++) { retval[i] = s + d*((double) (2*i + 1 - len)/(len - 1)); } } return retval; } static ss_data blockdata = {0, 0, NULL, NULL}; void set_blockdata(ss_data *ssd) { free_ss_data(&blockdata); if (ssd) { memcpy(&blockdata, ssd, sizeof(ss_data)); } } int get_blockncols(void) { return blockdata.ncols; } int get_blocknrows(void) { return blockdata.nrows; } int *get_blockformats(void) { return blockdata.formats; } int realloc_ss_data(ss_data *ssd, int nrows) { int i, j; char **sp; for (i = 0; i < ssd->ncols; i++) { if (ssd->formats[i] == FFORMAT_STRING) { sp = (char **) ssd->data[i]; for (j = nrows; j < ssd->nrows; j++) { XCFREE(sp[j]); } ssd->data[i] = (char **)xrealloc(ssd->data[i], nrows*sizeof(char *)); sp = (char **) ssd->data[i]; for (j = ssd->nrows; j < nrows; j++) { sp[j] = NULL; } } else { ssd->data[i] = (double*)xrealloc(ssd->data[i], nrows*sizeof(double)); } } ssd->nrows = nrows; return RETURN_SUCCESS; } void free_ss_data(ss_data *ssd) { if (ssd) { int i, j; char **sp; for (i = 0; i < ssd->ncols; i++) { if (ssd->formats && ssd->formats[i] == FFORMAT_STRING) { sp = (char **) ssd->data[i]; for (j = 0; j < ssd->nrows; j++) { XCFREE(sp[j]); } } XCFREE(ssd->data[i]); } XCFREE(ssd->data); XCFREE(ssd->formats); ssd->nrows = 0; ssd->ncols = 0; } } int init_ss_data(ss_data *ssd, int ncols, int *formats) { int i; ssd->data = (void**)xmalloc(ncols*sizeof(void*)); for (i = 0; i < ncols; i++) { ssd->data[i] = NULL; } ssd->formats = (int*)xmalloc(ncols*sizeof(int)); memcpy(ssd->formats, formats, ncols*sizeof(int)); ssd->ncols = ncols; ssd->nrows = 0; return RETURN_SUCCESS; } static char *next_token(char *s, char **token, int *quoted) { *quoted = FALSE; *token = NULL; if (s == NULL) { return NULL; } while (*s == ' ' || *s == '\t') { s++; } if (*s == '"') { s++; *token = s; while (*s != '\0' && (*s != '"' || (*s == '"' && *(s - 1) == '\\'))) { s++; } if (*s == '"') { /* successfully identified a quoted string */ *quoted = TRUE; } } else { *token = s; if (**token == '\n') { /* EOL reached */ return NULL; } while (*s != '\n' && *s != '\0' && *s != ' ' && *s != '\t') { s++; } } if (*s != '\0') { *s = '\0'; s++; return s; } else { return NULL; } } int parse_ss_row(const char *s, int *nncols, int *nscols, int **formats) { int ncols; int quoted; char *buf, *s1, *token; double value; Dates_format df_pref, ddummy; const char *sdummy; *nscols = 0; *nncols = 0; *formats = NULL; df_pref = get_date_hint(); buf = copy_string(NULL, s); s1 = buf; while ((s1 = next_token(s1, &token, &quoted)) != NULL) { if (token == NULL) { *nscols = 0; *nncols = 0; XCFREE(*formats); xfree(buf); return RETURN_FAILURE; } ncols = *nncols + *nscols; /* reallocate the formats array */ if (ncols % 10 == 0) { *formats = (int*)xrealloc(*formats, (ncols + 10)*sizeof(int)); } if (quoted) { (*formats)[ncols] = FFORMAT_STRING; (*nscols)++; } else if (parse_date(token, df_pref, FALSE, &value, &ddummy) == RETURN_SUCCESS) { (*formats)[ncols] = FFORMAT_DATE; (*nncols)++; } else if (parse_float(token, &value, &sdummy) == RETURN_SUCCESS) { (*formats)[ncols] = FFORMAT_NUMBER; (*nncols)++; } else { /* last resort - treat the field as string, even if not quoted */ (*formats)[ncols] = FFORMAT_STRING; (*nscols)++; } } xfree(buf); return RETURN_SUCCESS; } /* NOTE: the input string will be corrupted! */ int insert_data_row(ss_data *ssd, int row, char *s) { int i, j; int ncols = ssd->ncols; char *token; int quoted; char **sp; double *np; Dates_format df_pref, ddummy; const char *sdummy; int res; if (exchange_point_comma) { j=strlen(s); for (i=0;i<j;i++) { if (s[i]=='.') s[i]=','; else if (s[i]==',') s[i]='.'; } } df_pref = get_date_hint(); for (i = 0; i < ncols; i++) { s = next_token(s, &token, &quoted); if (s == NULL || token == NULL) { /* invalid line: free the already allocated string fields */ for (j = 0; j < i; j++) { if (ssd->formats[j] == FFORMAT_STRING) { sp = (char **) ssd->data[j]; XCFREE(sp[row]); } } return RETURN_FAILURE; } else { if (ssd->formats[i] == FFORMAT_STRING) { sp = (char **) ssd->data[i]; sp[row] = copy_string(NULL, token); if (sp[row] != NULL) { res = RETURN_SUCCESS; } else { res = RETURN_FAILURE; } } else if (ssd->formats[i] == FFORMAT_DATE) { np = (double *) ssd->data[i]; res = parse_date(token, df_pref, FALSE, &np[row], &ddummy); } else { np = (double *) ssd->data[i]; res = parse_float(token, &np[row], &sdummy); } if (res != RETURN_SUCCESS) { for (j = 0; j < i; j++) { if (ssd->formats[j] == FFORMAT_STRING) { sp = (char **) ssd->data[j]; XCFREE(sp[row]); } } return RETURN_FAILURE; } } } return RETURN_SUCCESS; } int store_data(ss_data *ssd, int load_type, char *label) { int ncols, nncols, nncols_req, nscols, nrows; int i, j; double *xdata; int gno, setno; int x_from_index; if (ssd == NULL) { return RETURN_FAILURE; } ncols = ssd->ncols; nrows = ssd->nrows; if (ncols <= 0 || nrows <= 0) { return RETURN_FAILURE; } nncols = 0; for (j = 0; j < ncols; j++) { if (ssd->formats[j] != FFORMAT_STRING) { nncols++; } } nscols = ncols - nncols; gno = get_parser_gno(); if (is_valid_gno(gno) != TRUE) { return RETURN_FAILURE; } switch (load_type) { case LOAD_SINGLE: if (nscols > 1) { errmsg("Can not use more than one column of strings per set"); free_ss_data(ssd); return RETURN_FAILURE; } nncols_req = settype_cols(curtype); x_from_index = FALSE; if (nncols_req == nncols + 1) { x_from_index = TRUE; } else if (nncols_req != nncols) { errmsg("Column count incorrect"); return RETURN_FAILURE; } new_set_no=setno = nextset(gno); set_dataset_type(gno, setno, curtype); nncols = 0; if (x_from_index) { xdata = allocate_index_data(nrows); if (xdata == NULL) { free_ss_data(ssd); } setcol(gno, setno, nncols, xdata, nrows); nncols++; } for (j = 0; j < ncols; j++) { if (ssd->formats[j] == FFORMAT_STRING) { set_set_strings(gno, setno, nrows, (char **) ssd->data[j]); } else { setcol(gno, setno, nncols, (double *) ssd->data[j], nrows); nncols++; } } if (!strlen(getcomment(gno, setno))) { setcomment(gno, setno, label); } XCFREE(ssd->data); XCFREE(ssd->formats); break; case LOAD_NXY: if (nscols != 0) { errmsg("Can not yet use strings when reading in data as NXY"); free_ss_data(ssd); return RETURN_FAILURE; } for (i = 0; i < ncols - 1; i++) { setno = nextset(gno); if (setno == -1) { free_ss_data(ssd); return RETURN_FAILURE; } if (i > 0) { xdata = copy_data_column((double *) ssd->data[0], nrows); if (xdata == NULL) { free_ss_data(ssd); } } else { xdata = (double *) ssd->data[0]; } set_dataset_type(gno, setno, SET_XY); setcol(gno, setno, DATA_X, xdata, nrows); setcol(gno, setno, DATA_Y, (double *) ssd->data[i + 1], nrows); setcomment(gno, setno, label); } XCFREE(ssd->data); XCFREE(ssd->formats); break; case LOAD_BLOCK: set_blockdata(ssd); break; default: errmsg("Internal error"); free_ss_data(ssd); return RETURN_FAILURE; } return RETURN_SUCCESS; } int field_string_to_cols(const char *fs, int *nc, int **cols, int *scol) { int col; char *s, *buf; buf = copy_string(NULL, fs); if (buf == NULL) { return RETURN_FAILURE; } s = buf; *nc = 0; while ((s = strtok(s, ":")) != NULL) { (*nc)++; s = NULL; } *cols = (int*)xmalloc((*nc)*sizeof(int)); if (*cols == NULL) { xfree(buf); return RETURN_FAILURE; } strcpy(buf, fs); s = buf; *nc = 0; *scol = -1; while ((s = strtok(s, ":")) != NULL) { int strcol; if (*s == '{') { char *s1; strcol = TRUE; s++; if ((s1 = strchr(s, '}')) != NULL) { *s1 = '\0'; } } else { strcol = FALSE; } col = atoi(s); col--; if (strcol) { *scol = col; } else { (*cols)[*nc] = col; (*nc)++; } s = NULL; } xfree(buf); return RETURN_SUCCESS; } char *cols_to_field_string(int nc, int *cols, int scol) { int i; char *s, buf[32]; s = NULL; for (i = 0; i < nc; i++) { sprintf(buf, "%d", cols[i] + 1); if (i != 0) { s = concat_strings(s, ":"); } s = concat_strings(s, buf); } if (scol >= 0) { sprintf(buf, ":{%d}", scol + 1); s = concat_strings(s, buf); } return s; } int create_set_fromblock(int gno, int setno, int type, int nc, int *coli, int scol, int autoscale) { int i, ncols, blockncols, blocklen, column; double *cdata; char buf[256], *s; blockncols = get_blockncols(); if (blockncols <= 0) { errmsg("No block data read"); return RETURN_FAILURE; } blocklen = get_blocknrows(); ncols = settype_cols(type); if (nc > ncols) { errmsg("Too many columns scanned in column string"); return RETURN_FAILURE; } if (nc < ncols) { errmsg("Too few columns scanned in column string"); return RETURN_FAILURE; } for (i = 0; i < nc; i++) { if (coli[i] < -1 || coli[i] >= blockncols) { errmsg("Column index out of range"); return RETURN_FAILURE; } } if (scol >= blockncols) { errmsg("String column index out of range"); return RETURN_FAILURE; } new_set_no = setno; if (setno == NEW_SET) { new_set_no = setno = nextset(gno); if (setno == -1) { return RETURN_FAILURE; } } /* clear data stored in the set, if any */ killsetdata(gno, setno); if (activateset(gno, setno) != RETURN_SUCCESS) { return RETURN_FAILURE; } set_dataset_type(gno, setno, type); for (i = 0; i < nc; i++) { column = coli[i]; if (column == -1) { cdata = allocate_index_data(blocklen); } else { if (blockdata.formats[column] != FFORMAT_STRING) { cdata = copy_data_column((double *) blockdata.data[column], blocklen); } else { errmsg("Tried to read doubles from strings!"); killsetdata(gno, setno); return RETURN_FAILURE; } } if (cdata == NULL) { killsetdata(gno, setno); return RETURN_FAILURE; } setcol(gno, setno, i, cdata, blocklen); } /* strings, if any */ if (scol >= 0) { if (blockdata.formats[scol] != FFORMAT_STRING) { errmsg("Tried to read strings from doubles!"); killsetdata(gno, setno); return RETURN_FAILURE; } else { set_set_strings(gno, setno, blocklen, copy_string_column((char **) blockdata.data[scol], blocklen)); } } s = cols_to_field_string(nc, coli, scol); sprintf(buf, "Cols %s", s); xfree(s); setcomment(gno, setno, buf); autoscale_graph(gno, autoscale); return RETURN_SUCCESS; }
OS2World/APP-ANALYSIS-QtGrace
src/ssdata.cpp
C++
gpl-2.0
16,004
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Uncomment to debug. If you aren't me, I bet you want to change the paths, too. import sys from wsnamelet import wsnamelet_globals if wsnamelet_globals.debug: sys.stdout = open ("/home/munizao/hacks/wsnamelet/debug.stdout", "w", buffering=1) sys.stderr = open ("/home/munizao/hacks/wsnamelet/debug.stderr", "w", buffering=1) import gi gi.require_version("Gtk", "3.0") gi.require_version("MatePanelApplet", "4.0") from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GObject from gi.repository import Pango from gi.repository import MatePanelApplet gi.require_version ("Wnck", "3.0") from gi.repository import Wnck from gi.repository import Gio #Internationalize import locale import gettext gettext.bindtextdomain('wsnamelet', wsnamelet_globals.localedir) gettext.textdomain('wsnamelet') locale.bindtextdomain('wsnamelet', wsnamelet_globals.localedir) locale.textdomain('wsnamelet') gettext.install('wsnamelet', wsnamelet_globals.localedir) #screen = None class WSNamePrefs(object): def __init__(self, applet): self.applet = applet self.dialog = Gtk.Dialog("Workspace Name Applet Preferences", None, Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)) self.dialog.set_border_width(10) width_spin_label = Gtk.Label(label=_("Applet width in pixels:")) width_adj = Gtk.Adjustment(lower=30, upper=500, step_incr=1) self.width_spin_button = Gtk.SpinButton.new(width_adj, 0.0, 0) self.applet.settings.bind("width", self.width_spin_button, "value", Gio.SettingsBindFlags.DEFAULT) width_spin_hbox = Gtk.HBox() width_spin_hbox.pack_start(width_spin_label, True, True, 0) width_spin_hbox.pack_start(self.width_spin_button, True, True, 0) self.dialog.vbox.add(width_spin_hbox) class WSNameEntry(Gtk.Entry): def __init__(self, applet): Gtk.Widget.__init__(self) self.connect("activate", self._on_activate) self.connect("key-release-event", self._on_key_release) self.applet = applet def _on_activate(self, event): text = self.get_text() self.applet.workspace.change_name(text) self.applet.label.set_text(text) self.applet.exit_editing() def _on_key_release(self, widget, event): if event.keyval == Gdk.KEY_Escape: self.applet.exit_editing() class WSNameApplet(MatePanelApplet.Applet): _name_change_handler_id = None workspace = None settings = None prefs = None width = 100 editing = False def __init__(self, applet): self.applet = applet; menuxml = """ <menuitem name="Prefs" action="Prefs" /> <menuitem name="About" action="About" /> """ actions = [("Prefs", Gtk.STOCK_PREFERENCES, "Preferences", None, None, self._display_prefs), ("About", Gtk.STOCK_ABOUT, "About", None, None, self._display_about)] actiongroup = Gtk.ActionGroup.new("WsnameActions") actiongroup.add_actions(actions, None) applet.setup_menu(menuxml, actiongroup) self.init() def _display_about(self, action): about = Gtk.AboutDialog() about.set_program_name("Workspace Name Applet") about.set_version(wsnamelet_globals.version) about.set_copyright("© 2006 - 2015 Alexandre Muñiz") about.set_comments("View and change the name of the current workspace.\n\nTo change the workspace name, click on the applet, type the new name, and press Enter.") about.set_website("https://github.com/munizao/mate-workspace-name-applet") about.connect ("response", lambda self, *args: self.destroy ()) about.show_all() def _display_prefs(self, action): self.prefs.dialog.show_all() self.prefs.dialog.run() self.prefs.dialog.hide() def set_width(self, width): self.width = width self.button.set_size_request(width, -1) self.button.queue_resize() self.entry.set_size_request(width, -1) self.entry.queue_resize() def on_width_changed(self, settings, key): width = settings.get_int(key) self.set_width(width) def init(self): self.button = Gtk.Button() self.button.connect("button-press-event", self._on_button_press) self.button.connect("button-release-event", self._on_button_release) self.label = Gtk.Label() self.label.set_ellipsize(Pango.EllipsizeMode.END) self.applet.add(self.button) self.button.add(self.label) self.entry = WSNameEntry(self) self.entry.connect("button-press-event", self._on_entry_button_press) try: self.settings = Gio.Settings.new("com.puzzleapper.wsname-applet-py") self.set_width(self.settings.get_int("width")) self.settings.connect("changed::width", self.on_width_changed) except: self.set_width(100) self.screen = Wnck.Screen.get_default() self.workspace = really_get_active_workspace(self.screen) self.screen.connect("active_workspace_changed", self._on_workspace_changed) self.button.set_tooltip_text(_("Click to change the name of the current workspace")) self._name_change_handler_id = None self.prefs = WSNamePrefs(self) self.show_workspace_name() self.applet.show_all() return True def _on_button_press(self, button, event, data=None): if event.button != 1: button.stop_emission("button-press-event") def _on_button_release(self, button, event, data=None): if event.type == Gdk.EventType.BUTTON_RELEASE and event.button == 1: self.editing = True self.applet.remove(self.button) self.applet.add(self.entry) self.entry.set_text(self.workspace.get_name()) self.entry.set_position(-1) self.entry.select_region(0, -1) self.applet.request_focus(event.time) GObject.timeout_add(0, self.entry.grab_focus) self.applet.show_all() def _on_entry_button_press(self, entry, event, data=None): self.applet.request_focus(event.time) def _on_workspace_changed(self, event, old_workspace): if self.editing: self.exit_editing() if (self._name_change_handler_id): self.workspace.disconnect(self._name_change_handler_id) self.workspace = really_get_active_workspace(self.screen) self._name_change_handler_id = self.workspace.connect("name-changed", self._on_workspace_name_changed) self.show_workspace_name() def _on_workspace_name_changed(self, event): self.show_workspace_name() def show_workspace_name(self): if self.workspace: self.label.set_text(self.workspace.get_name()) self.applet.show_all() def exit_editing(self): self.editing = False self.applet.remove(self.entry) self.applet.add(self.button) def really_get_active_workspace(screen): # This bit is needed because wnck is asynchronous. while Gtk.events_pending(): Gtk.main_iteration() return screen.get_active_workspace() def applet_factory(applet, iid, data): WSNameApplet(applet) return True MatePanelApplet.Applet.factory_main("WsnameAppletFactory", True, MatePanelApplet.Applet.__gtype__, applet_factory, None)
munizao/mate-workspace-name-applet
wsname_applet.py
Python
gpl-2.0
7,780
/** * Copyright (C) 2002-2022 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.networking; import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLStreamException; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.common.io.FreeColXMLReader; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.server.FreeColServer; import net.sf.freecol.server.ai.AIPlayer; /** * The message sent to tell a client to show an attack animation. */ public class AnimateAttackMessage extends ObjectMessage { public static final String TAG = "animateAttack"; private static final String ATTACKER_TAG = "attacker"; private static final String ATTACKER_TILE_TAG = "attackerTile"; private static final String DEFENDER_TAG = "defender"; private static final String DEFENDER_TILE_TAG = "defenderTile"; private static final String SUCCESS_TAG = "success"; /** * Create a new {@code AnimateAttackMessage} for the supplied attacker, * defender, result and visibility information. * * @param attacker The attacking {@code Unit}. * @param defender The defending {@code Unit}. * @param result Whether the attack succeeds. * @param addAttacker Whether to attach the attacker unit. * @param addDefender Whether to attach the defender unit. */ public AnimateAttackMessage(Unit attacker, Unit defender, boolean result, boolean addAttacker, boolean addDefender) { super(TAG, ATTACKER_TAG, attacker.getId(), ATTACKER_TILE_TAG, attacker.getTile().getId(), DEFENDER_TAG, defender.getId(), DEFENDER_TILE_TAG, defender.getTile().getId(), SUCCESS_TAG, Boolean.toString(result)); if (addAttacker) { appendChild((attacker.isOnCarrier()) ? attacker.getCarrier() : attacker); } if (addDefender) { appendChild((defender.isOnCarrier()) ? defender.getCarrier() : defender); } } /** * Create a new {@code AnimateAttackMessage} from a stream. * * @param game The {@code Game} this message belongs to. * @param xr The {@code FreeColXMLReader} to read from. * @exception XMLStreamException if there is a problem reading the stream. */ public AnimateAttackMessage(Game game, FreeColXMLReader xr) throws XMLStreamException { super(TAG, xr, ATTACKER_TAG, ATTACKER_TILE_TAG, DEFENDER_TAG, DEFENDER_TILE_TAG, SUCCESS_TAG); FreeColXMLReader.ReadScope rs = xr.replaceScope(FreeColXMLReader.ReadScope.NOINTERN); List<Unit> units = new ArrayList<>(); try { while (xr.moreTags()) { String tag = xr.getLocalName(); if (Unit.TAG.equals(tag)) { Unit u = xr.readFreeColObject(game, Unit.class); if (u != null) units.add(u); } else { expected(Unit.TAG, tag); } xr.expectTag(tag); } xr.expectTag(TAG); } finally { xr.replaceScope(rs); } appendChildren(units); } /** * Get a unit by key. * * @param game The {@code Game} to look up the unit in. * @param key An attribute key to extract the unit identifier with. * @return The attacker {@code Unit}. */ private Unit getUnit(Game game, String key) { final String id = getStringAttribute(key); if (id == null) return null; Unit unit = game.getFreeColGameObject(id, Unit.class); if (unit != null) return unit; for (Unit u : getChildren(Unit.class)) { if (id.equals(u.getId())) { u.intern(); return u; } if ((u = u.getCarriedUnitById(id)) != null) { u.intern(); return u; } } return null; } /** * Get the attacker unit. * * @param game The {@code Game} to look up the unit in. * @return The attacker {@code Unit}. */ private Unit getAttacker(Game game) { return getUnit(game, ATTACKER_TAG); } /** * Get the defender unit. * * @param game The {@code Game} to look up the unit in. * @return The defender {@code Unit}. */ private Unit getDefender(Game game) { return getUnit(game, DEFENDER_TAG); } /** * Get the attacker tile. * * @param game The {@code Game} to look up the tile in. * @return The attacker {@code Tile}. */ private Tile getAttackerTile(Game game) { return game.getFreeColGameObject(getStringAttribute(ATTACKER_TILE_TAG), Tile.class); } /** * Get the defender tile. * * @param game The {@code Game} to look up the tile in. * @return The defender {@code Tile}. */ private Tile getDefenderTile(Game game) { return game.getFreeColGameObject(getStringAttribute(DEFENDER_TILE_TAG), Tile.class); } /** * Get the result of the attack. * * @return The result. */ private boolean getResult() { return getBooleanAttribute(SUCCESS_TAG, Boolean.FALSE); } /** * {@inheritDoc} */ @Override public MessagePriority getPriority() { return Message.MessagePriority.ANIMATION; } /** * {@inheritDoc} */ @Override public void aiHandler(FreeColServer freeColServer, AIPlayer aiPlayer) { // Ignored } /** * {@inheritDoc} */ @Override public void clientHandler(FreeColClient freeColClient) { final Game game = freeColClient.getGame(); final Player player = freeColClient.getMyPlayer(); final Tile attackerTile = getAttackerTile(game); final Tile defenderTile = getDefenderTile(game); final boolean result = getResult(); final Unit attacker = getAttacker(game); final Unit defender = getDefender(game); if (attacker == null) { logger.warning("Attack animation missing attacker unit."); return; } if (defender == null) { logger.warning("Attack animation missing defender unit."); return; } if (attackerTile == null) { logger.warning("Attack animation for: " + player.getId() + " omitted attacker tile."); } if (defenderTile == null) { logger.warning("Attack animation for: " + player.getId() + " omitted defender tile."); } // This only performs animation, if required. It does not // actually perform an attack. igc(freeColClient) .animateAttackHandler(attacker, defender, attackerTile, defenderTile, result); clientGeneric(freeColClient); } }
FreeCol/freecol
src/net/sf/freecol/common/networking/AnimateAttackMessage.java
Java
gpl-2.0
7,919
<?php /** * @copyright Copyright (C) 2009-2012 ACYBA SARL - All rights reserved. * @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL */ defined('_JEXEC') or die('Restricted access'); ?> <?php class listsmailType{ var $type = 'news'; function load(){ $db = JFactory::getDBO(); $query = 'SELECT a.listid as listid,COUNT(a.mailid) as total FROM `#__acymailing_mail` as c'; $query .= ' JOIN `#__acymailing_listmail` as a ON a.mailid = c.mailid'; $query .= ' WHERE c.type = \''.$this->type.'\' GROUP BY a.listid'; $db->setQuery($query); $alllists = $db->loadObjectList('listid'); $allnames = array(); if(!empty($alllists)){ $db->setQuery('SELECT name,listid FROM `#__acymailing_list` WHERE listid IN ('.implode(',',array_keys($alllists)).') ORDER BY ordering ASC'); $allnames = $db->loadObjectList('listid'); } $this->values = array(); $this->values[] = JHTML::_('select.option', '0', JText::_('ALL_LISTS') ); foreach($allnames as $listid => $oneName){ $this->values[] = JHTML::_('select.option', $listid, $oneName->name.' ( '.$alllists[$listid]->total.' )' ); } } function display($map,$value){ $this->load(); return JHTML::_('select.genericlist', $this->values, $map, 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', (int) $value ); } }
anhtuan8591/shop
administrator/components/com_acymailing/types/listsmail.php
PHP
gpl-2.0
1,355
/* #Identification: TAGSORT.FOR #Revision: B003 #Task: Sort for PALL #First issue: 901019 #Author: POLA Ivan Polak #Changes: %datum: %autor: #===============================================================*/ #include <stdio.h> int TagSort(unsigned long *ival,int *itag,int ip,int ik) { /*#parametry: ival - i - pole s hodnotami klicu itag - o - pole ukazatelu do ival ip,ik -i - pocatecni a koncovy index tridene casti ival return: 1 = O.K. 2 = preplneni vnitr. zasobniku (asi nemuze nastat) 4 = kiks (urcite nemuze nastat) #Funkce: V poli ITAG jsou po skonceni prace adresy do pole IVAL a to tak, aby posloupnost IVAL(ITAG(i)) byla SESTUPNA (!). Trideni metodou QUICKSORT se zasobnikem. TAGSORT vznikl z EXTSOR, ktery vznikl upravou MON3SOR_L:QSORT1.FOR resp. MON3SOR_L:UMQSOR tr.: #parameters: ival - i - field with values of sorting keys itag - o - field of pointers to ival ip,ik -i - initial and final index of sorted parts ival return: 1 = O.K. 2 = overflow if the inner storage (probably cannot happen) 4 = flop (certainly cannot happen) #Funkce: After having finished the operation, the field ITAG contains the addresses into the field IVAL in that way, that the order of IVAL(ITAG(i)) will be DESCENDING (!). Sorting with method QUICKSORT with storage. TAGSORT emerged from EXTSOR, that was developed from MON3SOR_L:QSORT1.FOR resp. MON3SOR_L:UMQSOR c *************************************************************** */ #define MQSTA 200 int qsta[MQSTA]; // storage int jx,is, l,r, i,j, ispr,iw; //auxiliary variable // ********************************************************************** // main: for(i=ip; i <= ik; i++) itag[i]= i; // initial setting itag is=1; // whole field into storage qsta[is]=ip; qsta[is+1]=ik; //-------------------- L10: l=qsta[is]; // take from storage r=qsta[is+1]; is=is-2; //------------------- L20: i=l; // sorting section <i,j> j=r; ispr=((l+r)/2)+1; if(ispr > r) ispr=r; if(ispr < l) ispr=l; // central/middle index jx=itag[ispr]; //------------------- // 30 if(a[i]-x[1]) 200,110,300 // 200=.true. 300=.false //30 if(ival[itag[i]] .lt. ival[jx] ) then L30: if( ival[itag[i]] > ival[jx] ) //descending! goto L200; // 200=.true. 300=.false else goto L300; L200: i++; goto L30; // 300 if(x[1]-a[j]) 600,410,700 // 600=.true. 700=.false //300 if( ival[jx] .lt. ival[itag[j]] ) then L300: if( ival[jx] > ival[itag[j]] ) //descend. goto L600; // 600=.true. 700=.false else goto L700; L600: j--; goto L300; L700: if(i <= j) // prohozeni (tr.: swap) { if(i == j) goto L33; // call lib$movc3(len,a(i),waa) // call lib$movc3(len,a(j),a(i)) // call lib$movc3(len,waa,a(j)) //-------- super secure - pol 930114 !!!!!!!!!!!!!!1 if(i<ip || j>ik) return 4; //----------------------------------- iw=itag[i]; itag[i]=itag[j]; itag[j]=iw; L33: i++; j--; } if(i <= j) goto L30; if(i < r) // save right part into stacku {is=is+2; //p: if(is >= MQSTA) perror("TagSort-plny zasobnik"); //stop '' if(is >= MQSTA) return 2; qsta[is]=i; qsta[is+1]=r; } r=j; // sorting of the rest of left part if(l < r) goto L20; if(is > 0) goto L10; return 1; }
kompowiec/Arachne-WWW-browser
TAGSORT.C
C++
gpl-2.0
3,616
package net.demilich.metastone.game.spells.desc.condition; import net.demilich.metastone.game.GameContext; import net.demilich.metastone.game.Player; import net.demilich.metastone.game.entities.Entity; import net.demilich.metastone.game.logic.GameLogic; public class ManaMaxedCondition extends Condition { public ManaMaxedCondition(ConditionDesc desc) { super(desc); } @Override protected boolean isFulfilled(GameContext context, Player player, ConditionDesc desc, Entity target) { return player.getMaxMana() >= GameLogic.MAX_MANA; } }
rafaelkalan/metastone
src/main/java/net/demilich/metastone/game/spells/desc/condition/ManaMaxedCondition.java
Java
gpl-2.0
569
<?php /** * Cue * * @package Cue * @author Brady Vercher * @copyright Copyright (c) 2014, AudioTheme, LLC * @license GPL-2.0+ */ /** * Main plugin class. * * @package Cue * @since 1.0.0 */ class Cue { /** * Load the plugin. * * @since 1.0.0 */ public function load_plugin() { self::load_textdomain(); if ( is_admin() ) { self::load_admin(); } add_action( 'init', array( $this, 'init' ), 15 ); add_action( 'widgets_init', array( $this, 'widgets_init' ) ); add_action( 'cue_after_playlist', array( $this, 'print_playlist_settings' ), 10, 3 ); add_filter( 'cue_playlist_tracks', array( $this, 'wp_playlist_tracks_format' ), 10, 3 ); add_action( 'customize_register', array( $this, 'customize_register' ) ); } /** * Localize the plugin strings. * * @since 1.0.0 */ protected function load_textdomain() { load_plugin_textdomain( 'cue', false, dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/languages' ); } /** * Load admin functionality. * * @since 1.1.0 */ protected function load_admin() { $admin = new Cue_Admin(); $admin->load(); } /** * Attach hooks and load custom functionality on init. * * @since 1.0.0 */ public function init() { self::register_post_type(); // Register scripts and styles. self::register_assets(); // Add a shortcode to include a playlist in a post. add_shortcode( 'cue', array( $this, 'cue_shortcode_handler' ) ); } /** * Register the playlist widget. * * @since 1.0.0 */ public function widgets_init() { register_widget( 'Cue_Widget_Playlist' ); } /** * Register the playlist post type. * * @since 1.0.0 */ protected function register_post_type() { $labels = array( 'name' => _x( 'Playlists', 'post format general name', 'cue' ), 'singular_name' => _x( 'Playlist', 'post format singular name', 'cue' ), 'add_new' => _x( 'Add New', 'playlist', 'cue' ), 'add_new_item' => __( 'Add New Playlist', 'cue' ), 'edit_item' => __( 'Edit Playlist', 'cue' ), 'new_item' => __( 'New Playlist', 'cue' ), 'view_item' => __( 'View Playlist', 'cue' ), 'search_items' => __( 'Search Playlists', 'cue' ), 'not_found' => __( 'No playlists found.', 'cue' ), 'not_found_in_trash' => __( 'No playlists found in Trash.', 'cue' ), 'all_items' => __( 'All Playlists', 'cue' ), 'menu_name' => __( 'Playlists', 'cue' ), 'name_admin_bar' => _x( 'Playlist', 'add new on admin bar', 'cue' ) ); $args = array( 'can_export' => true, 'capability_type' => 'post', 'has_archive' => false, 'hierarchical' => false, 'labels' => $labels, 'menu_icon' => 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeD0iMHB4IiB5PSIwcHgiIHZpZXdCb3g9IjAgMCAyMCAyMCIgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMjAgMjAiIHhtbDpzcGFjZT0icHJlc2VydmUiPjxyZWN0IGZpbGw9IiMwMTAxMDEiIHg9IjEiIHk9IjQiIHdpZHRoPSIxMCIgaGVpZ2h0PSIyIi8+PHBhdGggZmlsbD0iIzAxMDEwMSIgZD0iTTEzLjAxIDMuMDMxdjcuMzVjLTAuNDU2LTAuMjE4LTAuOTYxLTAuMzUtMS41LTAuMzVjLTEuOTMzIDAtMy41IDEuNTY3LTMuNSAzLjVzMS41NjcgMy41IDMuNSAzLjVzMy41LTEuNTY3IDMuNS0zLjV2LTcuNSBsNC0xdi0zTDEzLjAxIDMuMDMxeiIvPjxwYXRoIGZpbGw9IiMwMTAxMDEiIGQ9Ik02LjAxIDEzLjUzMWMwLTAuMTcxIDAuMDMyLTAuMzMzIDAuMDQ4LTAuNUgxLjAxdjJoNS4yMTNDNi4wODggMTQuNiA2IDE0LjEgNiAxMy41MzF6Ii8+PHBhdGggZmlsbD0iIzAxMDEwMSIgZD0iTTcuMjk0IDEwLjAzMUgxLjAxdjJoNS4yMzNDNi40NTUgMTEuMyA2LjggMTAuNiA3LjMgMTAuMDMxeiIvPjxwYXRoIGZpbGw9IiMwMTAxMDEiIGQ9Ik0xMS4wMSA4LjA1NFY3LjAzMWgtMTB2Mmg3LjM2N0M5LjE0IDguNSAxMCA4LjEgMTEgOC4wNTR6Ii8+PC9zdmc+', 'public' => false, 'publicly_queryable' => false, 'rewrite' => false, 'show_ui' => true, 'show_in_admin_bar' => false, 'show_in_menu' => true, 'show_in_nav_menus' => false, 'supports' => array( 'title', 'thumbnail' ), ); $args = apply_filters( 'cue_playlist_args', $args ); register_post_type( 'cue_playlist', $args ); } /** * Register scripts and styles. * * @since 1.0.0 */ protected function register_assets() { wp_register_style( 'cue', CUE_URL . 'assets/css/cue.min.css', array( 'mediaelement' ), '1.0.0' ); wp_register_script( 'jquery-cue', CUE_URL . 'assets/js/vendor/jquery.cue.min.js', array( 'jquery', 'mediaelement' ), '1.1.3', true ); wp_register_script( 'cue', CUE_URL . 'assets/js/cue.min.js', array( 'jquery-cue' ), '1.0.0', true ); wp_localize_script( 'cue', '_cueSettings', array( 'l10n' => array( 'nextTrack' => __( 'Next Track', 'cue' ), 'previousTrack' => __( 'Previous Track', 'cue' ), 'togglePlayer' => __( 'Toggle Player', 'cue' ), 'togglePlaylist' => __( 'Toggle Playlist', 'cue' ), ), ) ); } /** * Enqueue scripts and styles. * * @since 1.0.0 */ public static function enqueue_assets() { wp_enqueue_style( 'cue' ); wp_enqueue_script( 'cue' ); } /** * Playlist shortcode handler. * * @since 1.0.0 * * @param array $atts Optional. List of shortcode attributes. * @return string HTML output. */ public function cue_shortcode_handler( $atts = array() ) { $atts = shortcode_atts( array( 'id' => 0, 'show_playlist' => true, 'template' => '', ), $atts, 'cue' ); $id = $atts['id']; unset( $atts['id'] ); $atts['show_playlist'] = $this->shortcode_bool( $atts['show_playlist'] ); ob_start(); cue_playlist( $id, $atts ); return ob_get_clean(); } /** * Print playlist settings as a JSON script tag. * * @since 1.1.0 * * @param WP_Post $playlist Playlist post object. * @param array $tracks List of tracks. * @param array $args */ public function print_playlist_settings( $playlist, $tracks, $args ) { $thumbnail = ''; if ( has_post_thumbnail( $playlist->ID ) ) { $thumbnail_id = get_post_thumbnail_id( $playlist->ID ); $size = apply_filters( 'cue_artwork_size', array( 300, 300 ) ); $image = image_downsize( $thumbnail_id, $size ); $thumbnail = $image[0]; } $settings = apply_filters( 'cue_playlist_settings', array( 'thumbnail' => $thumbnail, 'tracks' => $tracks, ), $playlist, $args ); ?> <script type="application/json" class="cue-playlist-data"><?php echo json_encode( $settings ); ?></script> <?php } /** * Transform the Cue track syntax into the format used by WP Playlists. * * @since 1.1.1 * * @param array $tracks Array of tracks. * @param WP_Post $playlist Playlist post object. * @param string $context Context the tracks will be used in. * @return array */ public function wp_playlist_tracks_format( $tracks, $playlist, $context ) { if ( ! empty( $tracks ) ) { // 'wp-playlist' == $context && foreach ( $tracks as $key => $track ) { $tracks[ $key ]['meta'] = array( 'artist' => $track['artist'], 'length_formatted' => $track['length'], ); $tracks[ $key ]['src'] = $track['audioUrl']; $tracks[ $key ]['thumb']['src'] = $track['artworkUrl']; } } return $tracks; } /** * Add a Customizer section for selecting playlists for registered players. * * @since 1.1.1 * * @param WP_Customize_Manager $wp_customize Customizer instance. */ public function customize_register( $wp_customize ) { $description = ''; $players = get_cue_players(); if ( empty( $players ) ) { return; } $playlists = get_posts( array( 'post_type' => 'cue_playlist', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'asc', ) ); $wp_customize->add_section( 'cue', array( 'title' => __( 'Cue Players', 'cue' ), 'description' => __( 'Choose a playlist for each registered player.', 'cue' ), 'priority' => 115, ) ); if ( empty( $playlists ) ) { $playlists = array(); $description = sprintf( __( '<a href="%s">Create a playlist</a> for this player.', 'cue' ), admin_url( 'post-new.php?post_type=cue_playlist' ) ); } else { // Create an array: ID => post_title $playlists = array_combine( wp_list_pluck( $playlists, 'ID' ), wp_list_pluck( $playlists, 'post_title' ) ); } $playlists = array( 0 => '' ) + $playlists; foreach ( $players as $id => $player ) { $id = sanitize_key( $id ); $wp_customize->add_setting( 'cue_players[' . $id . ']', array( 'capability' => 'edit_theme_options', 'sanitize_callback' => 'absint', ) ); $wp_customize->add_control( 'cue_player_' . $id, array( 'choices' => $playlists, 'description' => $description, 'label' => $player['name'], 'section' => 'cue', 'settings' => 'cue_players[' . $id . ']', 'type' => 'select', ) ); } } /** * Helper method to determine if a shortcode attribute is true or false. * * @since 1.2.4 * * @param string|int|bool $var Attribute value. * * @return bool */ protected function shortcode_bool( $var ) { $falsey = array( 'false', '0', 'no', 'n' ); return ( ! $var || in_array( strtolower( $var ), $falsey ) ) ? false : true; } }
ola0411/ola
wp-content/plugins/cue/includes/class-cue.php
PHP
gpl-2.0
9,482
# Scrapes FIFA website, extracts team players and inserts them on a database # Requires gems watir-webdriver, headless and pg # Also, headless needs xvfb require 'watir-webdriver' require 'headless' require 'pg' headless = Headless.new headless.start player_url_fmt = 'http://www.fifa.com/worldcup/teams/team=%s/players.html'; urls = { 'USA' => '43921', 'CHI' => '43925', 'MEX' => '43911', 'HON' => '43909', 'CRC' => '43901', 'COL' => '43926', 'ECU' => '43927', 'BRA' => '43924', 'URU' => '43930', 'ARG' => '43922', 'ENG' => '43942', 'NED' => '43960', 'BEL' => '43935', 'GER' => '43948', 'FRA' => '43946', 'SUI' => '43971', 'CRO' => '43938', 'BIH' => '44037', 'ITA' => '43954', 'ESP' => '43969', 'POR' => '43963', 'GRE' => '43949', 'ALG' => '43843', 'IRN' => '43817', 'GHA' => '43860', 'NGA' => '43876', 'CIV' => '43854', 'CMR' => '43849', 'JPN' => '43819', 'KOR' => '43822', 'AUS' => '43976', 'RUS' => '43965' } div_cls = 'p-n' pl_cls = 'p-n-webname' pl_fieldpos = 'p-i-fieldpos' pl_club = 'p-i-clubname' conn = PGconn.open( :hostaddr => '127.0.0.1', :port => 5432, :dbname => 'smb2014', :user => 'scraper', :password => 'scraper123' ) conn.prepare('insert', "insert into players(team_id, name, field_position_id, club) values ((select id from team where code=$1), $2, (select id from field_position where name = $3), $4);") urls.each do |code, url_number| b = Watir::Browser.new 'ff' url = sprintf player_url_fmt % [url_number] b.goto url b.divs(:class => div_cls).map do |div| name = div.span(:class => pl_cls) pos = div.span(:class => pl_fieldpos) team = div.span(:class => pl_club) printf "country: %s, name: %s, field position: %s, team: %s\n", code, name.text, pos.text, team.text conn.exec_prepared( 'insert', [code, name.text, pos.text, team.text] ) end b.close end conn.close headless.destroy
cgortaris/smb2014
scraper/players.rb
Ruby
gpl-2.0
2,054
<?php // $Id$ // ------------------------------------------------------------------------ // // XOOPS - PHP Content Management System // // Copyright (c) 2000 XOOPS.org // // <http://www.xoops.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 2 of the License, or // // (at your option) any later version. // // You may not change or alter any portion of this comment or credits // // of supporting developers from this source code or any supporting // // source code which is considered copyrighted (c) material of the // // original comment or credit authors. // // 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 // // ------------------------------------------------------------------------ // // URL: http://www.xoops.org/ // // Project: The XOOPS Project // // -------------------------------------------------------------------------// if (!defined("XOOPS_ROOT_PATH")) { die("XOOPS root path not defined"); } include_once XOOPS_ROOT_PATH."/modules/smartobject/class/smartobject.php"; class SmartbillingSupplier extends SmartObject { function SmartbillingSupplier() { $this->quickInitVar('supplierid', XOBJ_DTYPE_INT, true); $this->quickInitVar('name', XOBJ_DTYPE_TXTBOX, true, _CO_SBILLING_SUPPLIER_NAME, _CO_SBILLING_SUPPLIER_NAME_DSC); $this->quickInitVar('note', XOBJ_DTYPE_TXTAREA, false, _CO_SBILLING_SUPPLIER_NOTE, _CO_SBILLING_SUPPLIER_NOTE_DSC); } function getVar($key, $format = 's') { if ($format == 's' && in_array($key, array(''))) { return call_user_func(array($this,$key)); } return parent::getVar($key, $format); } } class SmartbillingSupplierHandler extends SmartPersistableObjectHandler { function SmartbillingSupplierHandler($db) { $this->SmartPersistableObjectHandler($db, 'supplier', 'supplierid', 'name', '', 'smartbilling'); } } ?>
ImpressCMS/impresscms-module-smartbilling
class/supplier.php
PHP
gpl-2.0
2,856
<?php /** * @version 1.7.0 formscrm $ * @package formscrm * @copyright Copyright © 2010 - All rights reserved. * @license GNU/GPL * @author serrbiz * @author mail nobody@nobody.com * * * @MVC architecture generated by MVC generator tool at http://www.alphaplug.com */ // no direct access defined('_JEXEC') or die('Restricted access'); jimport('joomla.application.component.modellist'); // Your custom code here global $mainframe; require_once(JPATH_ADMINISTRATOR.'/components/com_formscrm/helpers/helper.php'); require_once(JPATH_ADMINISTRATOR.'/components/com_formscrm/helpers/reusefunction.class.php'); $reusefunction=new reusefunction(); $leadInfos=$this->leadInfos; $user=$this->user; $allCampaignInfo = sbfAdmin::getAllCampaign(-1,'dropdown'); $obj= array(); //Modified By Sapna Talreja On 29th feb 2008 frm $obj= "new" to $obj=array $allCampaignInfo = sbfAdmin::insertInArray($allCampaignInfo,1,$obj); $allCampaignInfo1[0] = new stdClass(); $allCampaignInfo1[0]->value = "-1"; $allCampaignInfo1[0]->text = "All"; $allCampaignInfo=array_merge($allCampaignInfo1,$allCampaignInfo); //For 1.7 /*$search_word = $mainframe->getUserStateFromRequest( "search_word", 'search_word', '' ); $select_campaign = intval( $mainframe->getUserStateFromRequest( "select_campaign", 'select_campaign', -1 ) ); $created_date = $mainframe->getUserStateFromRequest( "created_date", "created_date", 'All') ; $end_date = $mainframe->getUserStateFromRequest( "end_date", 'end_date', 'All' ); $hideclosed = $mainframe->getUserStateFromRequest( "hideclosed", 'hideclosed', '' );*/ //For 1.7 $search_word = JModelList::getUserStateFromRequest( "search_word", 'search_word', '' ); $select_campaign = intval( JModelList::getUserStateFromRequest( "select_campaign", 'select_campaign', -1 ) ); $created_date = JModelList::getUserStateFromRequest( "created_date", "created_date", 'All') ; $end_date = JModelList::getUserStateFromRequest( "end_date", 'end_date', 'All' ); $hideclosed = JModelList::getUserStateFromRequest( "hideclosed", 'hideclosed', '' ); // $select_gids=$confdata[0]->gid; $select_gid = explode( ',', $select_gids ); $created_date = JModelList::getUserStateFromRequest( "created_date", "created_date", 'All') ; $end_date = JModelList::getUserStateFromRequest( "end_date", 'end_date', 'All' ); ?> <link href="<?php echo JURI::root();?>components/com_formscrm/assets/css/serrbiz.css" rel="stylesheet" type="text/css" id="css"/> <style type="text/css"> input, select { border:1px solid silver; font-size:10px; } </style> <script type="text/javascript"> function fun_submitform() { var frm=document.adminForm; frm.option.value='com_formscrm'; frm.submit(); } // function tableOrdering(name,order) { var frm=document.adminForm; frm.option.value='com_formscrm'; frm.name.value=name; frm.order.value=order; frm.submit(); //location.href = 'index.php?option=com_formscrm&task=view&name='+name+'&order='+order; } // function fun_hideclosed(val) { var frm=document.adminForm; frm.hideclosed.value=val; frm.submit(); } </script> <div id="serrbiz-formslt"> <form name="adminForm" action="index.php?option=com_formscrm&view=formscrm" method="post" enctype="multipart/form-data"> <input type="hidden" name="option" value="com_formscrm"> <input type="hidden" name="task" value="<?php echo $_REQUEST['task'];?>"> <input type="hidden" name="Itemid" value="<?php echo $_REQUEST['Itemid'];?>"> <input type="hidden" name="name" value="" /> <input type="hidden" name="order" value="" /> <table width="100%" border="0" cellspacing="3" cellpadding="1" class="search-block"> <tr> <td nowrap="nowrap">Search Word</td> <td align="left"><input type="text" name="search_word" size="20" value="<?php echo $search_word;?>"/></td> <td>Select Form</td> <td align="left"><?php //echo mosHTML::selectList($allCampaignInfo, 'select_campaign', 'class="inputbox" onChange="document.adminForm.submit();" ', 'value', 'text', $select_campaign); echo JHTML::_('select.genericlist', $allCampaignInfo, 'select_campaign', 'size="1" class="inputbox" onChange="document.adminForm.submit()"', 'value', 'text', $select_campaign); ?></td> </tr> <tr> <td>Start Date</td> <td> <?php if($_REQUEST["created"]){ $start_date = $_REQUEST["created"]; } else { $start_date = $created_date; } ?> <?php // echo JHTML::_('calendar',$created_date, 'created_date', 'created_date', '%Y-%m-%d', array('class'=>'inputbox', 'size'=>'18', 'maxlength'=>'19',"readonly" => "readonly")); echo JHTML::calendar( $created_date, "created_date", "created_date", "%Y-%m-%d", "readonly=\"readonly\" size=\"16\" maxlength=\"10\" " );//For J1.7?> </td> <td>End Date</td> <td > <?php if($_REQUEST["end_date"]){ $end_date = $_REQUEST["end_date"]; } else { $end_date = $end_date; } ?> <?php //echo JHTML::_('calendar',$end_date, 'end_date', 'end_date', '%Y-%m-%d', array('class'=>'inputbox', 'size'=>'18', 'maxlength'=>'19' ,"readonly" => "readonly")); echo JHTML::calendar( $end_date, "end_date", "end_date", "%Y-%m-%d", "readonly=\"readonly\" size=\"16\" maxlength=\"10\" " );//For J1.7 ?></td> </tr> <tr> <td>Number of leads per page</td> <td><?php //echo $pagination->getLimitBox(); ?> <?php if(count($leadInfos) > 0) echo $this->pagination->getLimitBox(); else {?> <select name="s2" > <option value="5">5</option> <option value="10">10</option> <option value="15">15</option> <option value="20" selected="selected">20</option> <option value="25">25</option> <option value="30">30</option> <option value="50">50</option> <option value="100">100</option> <option value="ALL">ALL</option> </select> <?php } ?> </td> <td>Hide Closed:</td><td> <select name="hideclosed" id="hideclosed" class="inputbox" onChange="fun_hideclosed(this.value);" style="width:95px;"> <option value="1" <?php if($_REQUEST['hideclosed'] == 1) { ?> selected="selected" <?php }?> >Yes</option> <option value="2" <?php if($_REQUEST['hideclosed'] == 2 || $_REQUEST['hideclosed'] == '') { ?> selected="selected" <?php } ?> >No</option> <option value="3"<?php if($_REQUEST['hideclosed'] == 3) { ?> selected="selected" <?php }?> >Show only closed.</option> </select> </tr> <tr><td colspan="4" align="right"><input type="button" value="Search" name="searchform" onclick="javascript:fun_submitform()"></td></tr> </table> <table cellspacing=2 cellpadding=2 border="0" class="listing-block"> <tr> <?php if(in_array($user->id,$select_gid)) { ?><td width="10%"><?php if($_REQUEST['order']=='DESC') {?><a href="javascript:tableOrdering('campaign_name','ASC');" style="text-decoration:none" title="Click to sort by this column"><strong>Form </strong>&nbsp;<img alt="" src="media/system/images/sort_desc.png"></a><?php } else {?><a href="javascript:tableOrdering('campaign_name','DESC');" style="text-decoration:none" title="Click to sort by this column"><strong>Form </strong>&nbsp;<img alt="" src="media/system/images/sort_asc.png"></a><?php } ?></td><?php } ?> <!--<td width="10%" ><strong>TC</strong></td> --> <td width="15%"><?php if($_REQUEST['order']=='DESC') {?><a href="javascript:tableOrdering('name','ASC');" style="text-decoration:none" title="Click to sort by this column"><strong>First Name</strong>&nbsp;<img alt="" src="media/system/images/sort_desc.png"></a><?php } else {?><a href="javascript:tableOrdering('name','DESC');" style="text-decoration:none" title="Click to sort by this column"><strong>First Name</strong>&nbsp;<img alt="" src="media/system/images/sort_asc.png"></a><?php } ?></td> <td width="10%"><?php if($_REQUEST['order']=='DESC') {?><a href="javascript:tableOrdering('lastname','ASC');" style="text-decoration:none" title="Click to sort by this column"><strong>Last Name</strong>&nbsp;<img alt="" src="media/system/images/sort_desc.png"></a><?php } else {?><a href="javascript:tableOrdering('lastname','DESC');" style="text-decoration:none" title="Click to sort by this column"><strong>Last Name</strong>&nbsp;<img alt="" src="media/system/images/sort_asc.png"></a><?php } ?></td> <td width="10%"><?php if($_REQUEST['order']=='DESC') {?><a href="javascript:tableOrdering('date_added','ASC');" style="text-decoration:none" title="Click to sort by this column"><strong>Date Added</strong>&nbsp;<img alt="" src="media/system/images/sort_desc.png"></a><?php } else {?><a href="javascript:tableOrdering('date_added','DESC');" style="text-decoration:none" title="Click to sort by this column"><strong>Date Added</strong>&nbsp;<img alt="" src="media/system/images/sort_asc.png"></a><?php } ?></td> <td width="10%"><?php if($_REQUEST['order']=='DESC') {?><a href="javascript:tableOrdering('status','ASC');" style="text-decoration:none" title="Click to sort by this column"><strong>Status</strong>&nbsp;<img alt="" src="media/system/images/sort_desc.png"></a><?php } else {?><a href="javascript:tableOrdering('status','DESC');" style="text-decoration:none" title="Click to sort by this column"><strong>Status</strong>&nbsp;<img alt="" src="media/system/images/sort_asc.png"></a><?php } ?></td> <!--<td width="15%"><strong>Email</strong></td> --> <td width="4%" align="left"><strong>Details</strong></td> </tr> <?php $database = &JFactory::getDbo(); for($c=0;$c<count($leadInfos);$c++) { $qry1="SELECT `custom_field_value`,custom_field_id FROM `#__sbf_campaigns_custom_field_value` WHERE user_campaign_id = ".$leadInfos[$c]->UCID; $database->setQuery($qry1); $leadData1 = $database->loadObjectList(); for($j=0;$j<count($leadData1);$j++) { switch($leadData1[$j]->custom_field_id) { case '1' : $leadInfos[$c]->name = $leadData1[$j]->custom_field_value; break; case '2' : $leadInfos[$c]->lastname = $leadData1[$j]->custom_field_value; break; case '3' : $leadInfos[$c]->email = $leadData1[$j]->custom_field_value; break; case '10': $leadInfos[$c]->phone = $leadData1[$j]->custom_field_value; break; } } } if(count($leadInfos) > 0) { foreach ($leadInfos as $leadInfo){ ?> <tr align="left"> <?php if(in_array($user->id,$select_gid)) { echo '<td height="20">'; echo $leadInfo->campaign_name; echo '</td>';}?> <td><?php if($leadInfo->name!='') echo $leadInfo->name; else echo '<span style="color:#990000">na</span>'; ?></td> <td><?php if($leadInfo->lastname!='') echo $leadInfo->lastname; else echo '<span style="color:#990000">na</span>'; ?></td> <td><?php if($leadInfo->date_added!='') echo JHTML::_('date',$leadInfo->date_added, "m/d/Y"); else echo '<span style="color:#990000">na</span>'; ?></td> <td><?php if($leadInfo->status==0) echo "Open"; else echo "Close"; ?></td> <td><a href="index.php?option=com_formscrm&task=leadDetail&id=<?php echo $leadInfo->UCID; ?>&Itemid=<?php echo $_REQUEST['Itemid']; ?>" title="View Details"><!--<img src="administrator/components/com_formscrm/assets/images/icons-17x17-d.jpg" border="0" />-->Details</a></td> </tr> <?php } ?> <?php } else { ?> <tr> <td colspan="7"> No Leads assigned </td> </tr> <?php } ?> <!--<input type="hidden" name="task" value="view" />--> <?php if(count($leadInfos) > 0) {?> <tr> <td colspan="7"> <table width="100%" align="center" class="pagination-block"> <tr> <td align="center"><div id="pagination"><?php //echo $this->pagination->writePagesLinks(); ?><?php //echo $this->pagination->getListFooter(); ?><?php echo $this->pagination->getPagesLinks(); ?><div> </td><td align="center"><?php echo $this->pagination->getPagesCounter(); ?> </td></tr></table> </td> </tr> <?php } ?> </table> </td> </tr> </table> </form> </div>
nicholasdickey/hudsonwilde
components/com_formscrm/views/formscrm/tmpl/default (copy)1.php
PHP
gpl-2.0
11,987
<?php /** * @package WordPress * @subpackage Construction PRO * @version 1.0.0 * * Single Project Template * Created by CMSMasters * */ get_header(); $cmsmasters_option = construction_pro_get_global_options(); $project_tags = get_the_terms(get_the_ID(), 'pj-tags'); $cmsmasters_project_author_box = get_post_meta(get_the_ID(), 'cmsmasters_project_author_box', true); $cmsmasters_project_more_posts = get_post_meta(get_the_ID(), 'cmsmasters_project_more_posts', true); echo '<!--_________________________ Start Content _________________________ -->' . "\n" . '<div class="middle_content entry" role="main">' . "\n\t"; if (have_posts()) : the_post(); echo '<div class="portfolio opened-article">' . "\n"; if (get_post_format() != '') { get_template_part('framework/postType/portfolio/post/' . get_post_format()); } else { get_template_part('framework/postType/portfolio/post/standard'); } if ($cmsmasters_project_author_box == 'true') { construction_pro_author_box(esc_html__('About author', 'construction-pro'), 'h2'); } if ($project_tags) { $tgsarray = array(); foreach ($project_tags as $tagone) { $tgsarray[] = $tagone->term_id; } } else { $tgsarray = ''; } if ($cmsmasters_project_more_posts != 'hide') { construction_pro_related( 'h2', $cmsmasters_project_more_posts, $tgsarray, $cmsmasters_option[CMSMASTERS_SHORTNAME . '_portfolio_more_projects_count'], $cmsmasters_option[CMSMASTERS_SHORTNAME . '_portfolio_more_projects_pause'], 'project' ); } comments_template(); echo '</div>'; endif; echo '</div>' . "\n" . '<!-- _________________________ Finish Content _________________________ -->' . "\n\n"; get_footer();
womza/macromad
wp-content/themes/construction-pro/single-project.php
PHP
gpl-2.0
1,743
require "rails_helper" describe "changing my password", js: true do context "when changing my password" do let(:user) { create(:user, password: "password") } before { http_login(user) } it "displays a confirmation message" do visit my_dashboard_path click_link(I18n.t("my.shared.my_nav.change_password")) within(".form-horizontal") do fill_in("user_old_password", with: "password") fill_in("user_password", with: "secret") fill_in("user_password_confirmation", with: "secret") end click_button "Update password" expect(page).to have_content(I18n.translate("my.passwords.updated")) end end end
cakeside/cakeside
spec/features/change_password_spec.rb
Ruby
gpl-2.0
677
<?php /** * Core file * * @author Vince Wooll <sales@jomres.net> * @version Jomres 7 * @package Jomres * @copyright 2005-2013 Vince Wooll * Jomres (tm) PHP, CSS & Javascript files are released under both MIT and GPL2 licenses. This means that you can choose the license that best suits your project, and use it accordingly. **/ // ################################################################ defined( '_JOMRES_INITCHECK' ) or die( '' ); // ################################################################ class j16000editinplace { function j16000editinplace() { // Must be in all minicomponents. Minicomponents with templates that can contain editable text should run $this->template_touch() else just return $MiniComponents = jomres_singleton_abstract::getInstance( 'mcHandler' ); if ( $MiniComponents->template_touch ) { $this->template_touchable = false; return; } $customText = jomresGetParam( $_POST, 'value', '', 'string' ); $theConstant = filter_var( $_POST[ 'pk' ], FILTER_SANITIZE_SPECIAL_CHARS ); //$lang = jomresGetParam( $_REQUEST, 'lang', '' ); $result = updateCustomText( $theConstant, $customText, true, 0 ); //$result = false; if ( $result ) { header( "Status: 200" ); echo jomres_decode( $customText ); } else { header( "Status: 500" ); echo "Something burped"; } } // This must be included in every Event/Mini-component function getRetVals() { return null; } } ?>
parksandwildlife/parkstay
jomres/core-minicomponents/j16000editinplace.class.php
PHP
gpl-2.0
1,484
package com.inspector.objectinspector.view; import com.general.view.jtreetable.TableTreeNode; import com.inspector.objectinspector.presenter.ObjectInspectorPresenterInterface; public interface ObjectInspectorViewInterface { public void setController(ObjectInspectorPresenterInterface objectInspectorPresenter); public void clearTable(); public TableTreeNode getRoot(); public void refreshTable(); public ObjectInspectorView getView() ; }
DiegoArranzGarcia/JavaTracer
JavaTracer/src/com/inspector/objectinspector/view/ObjectInspectorViewInterface.java
Java
gpl-2.0
450
/// <summary> /// Routines for detecting devices and receiving device notifications. /// </summary> using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace USBHID { sealed internal partial class DeviceManagement { /// <summary> /// Compares two device path names. Used to find out if the device name /// of a recently attached or removed device matches the name of a /// device the application is communicating with. /// </summary> /// /// <param name="m"> a WM_DEVICECHANGE message. A call to RegisterDeviceNotification /// causes WM_DEVICECHANGE messages to be passed to an OnDeviceChange routine.. </param> /// <param name="mydevicePathName"> a device pathname returned by /// SetupDiGetDeviceInterfaceDetail in an SP_DEVICE_INTERFACE_DETAIL_DATA structure. </param> /// /// <returns> /// True if the names match, False if not. /// </returns> /// internal Boolean DeviceNameMatch(Message m, String mydevicePathName) { Int32 stringSize; try { DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1(); DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR(); // The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure. Marshal.PtrToStructure(m.LParam, devBroadcastHeader); if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)) { // The dbch_devicetype parameter indicates that the event applies to a device interface. // So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure, // which begins with a DEV_BROADCAST_HDR. // Obtain the number of characters in dbch_name by subtracting the 32 bytes // in the strucutre that are not part of dbch_name and dividing by 2 because there are // 2 bytes per character. stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2); // The dbcc_name parameter of devBroadcastDeviceInterface contains the device name. // Trim dbcc_name to match the size of the String. devBroadcastDeviceInterface.dbcc_name = new Char[stringSize + 1]; // Marshal data from the unmanaged block pointed to by m.LParam // to the managed object devBroadcastDeviceInterface. Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface); // Store the device name in a String. String DeviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize); // Compare the name of the newly attached device with the name of the device // the application is accessing (mydevicePathName). // Set ignorecase True. if ((String.Compare(DeviceNameString, mydevicePathName, true) == 0)) { return true; } else { return false; } } } catch { throw; } return false; } /// <summary> /// Use SetupDi API functions to retrieve the device path name of an /// attached device that belongs to a device interface class. /// </summary> /// /// <param name="myGuid"> an interface class GUID. </param> /// <param name="devicePathName"> a pointer to the device path name /// of an attached device. </param> /// /// <returns> /// True if a device is found, False if not. /// </returns> internal Boolean FindDeviceFromGuid(System.Guid myGuid, ref String[] devicePathName) { Int32 bufferSize = 0; IntPtr detailDataBuffer = IntPtr.Zero; Boolean deviceFound; IntPtr deviceInfoSet = new System.IntPtr(); Boolean lastDevice = false; Int32 memberIndex = 0; SP_DEVICE_INTERFACE_DATA MyDeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(); Boolean success; try { // *** // API function // summary // Retrieves a device information set for a specified group of devices. // SetupDiEnumDeviceInterfaces uses the device information set. // parameters // Interface class GUID. // Null to retrieve information for all device instances. // Optional handle to a top-level window (unused here). // Flags to limit the returned information to currently present devices // and devices that expose interfaces in the class specified by the GUID. // Returns // Handle to a device information set for the devices. // *** deviceInfoSet = SetupDiGetClassDevs(ref myGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); deviceFound = false; memberIndex = 0; // The cbSize element of the MyDeviceInterfaceData structure must be set to // the structure's size in bytes. // The size is 28 bytes for 32-bit code and 32 bits for 64-bit code. MyDeviceInterfaceData.cbSize = Marshal.SizeOf(MyDeviceInterfaceData); do { // Begin with 0 and increment through the device information set until // no more devices are available. // *** // API function // summary // Retrieves a handle to a SP_DEVICE_INTERFACE_DATA structure for a device. // On return, MyDeviceInterfaceData contains the handle to a // SP_DEVICE_INTERFACE_DATA structure for a detected device. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs. // Optional SP_DEVINFO_DATA structure that defines a device instance // that is a member of a device information set. // Device interface GUID. // Index to specify a device in a device information set. // Pointer to a handle to a SP_DEVICE_INTERFACE_DATA structure for a device. // Returns // True on success. // *** success = SetupDiEnumDeviceInterfaces (deviceInfoSet, IntPtr.Zero, ref myGuid, memberIndex, ref MyDeviceInterfaceData); // Find out if a device information set was retrieved. if (!success) { lastDevice = true; } else { // A device is present. // *** // API function: // summary: // Retrieves an SP_DEVICE_INTERFACE_DETAIL_DATA structure // containing information about a device. // To retrieve the information, call this function twice. // The first time returns the size of the structure. // The second time returns a pointer to the data. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs // SP_DEVICE_INTERFACE_DATA structure returned by SetupDiEnumDeviceInterfaces // A returned pointer to an SP_DEVICE_INTERFACE_DETAIL_DATA // Structure to receive information about the specified interface. // The size of the SP_DEVICE_INTERFACE_DETAIL_DATA structure. // Pointer to a variable that will receive the returned required size of the // SP_DEVICE_INTERFACE_DETAIL_DATA structure. // Returned pointer to an SP_DEVINFO_DATA structure to receive information about the device. // Returns // True on success. // *** success = SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref MyDeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero); // Allocate memory for the SP_DEVICE_INTERFACE_DETAIL_DATA structure using the returned buffer size. detailDataBuffer = Marshal.AllocHGlobal(bufferSize); // Store cbSize in the first bytes of the array. The number of bytes varies with 32- and 64-bit systems. Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); // Call SetupDiGetDeviceInterfaceDetail again. // This time, pass a pointer to DetailDataBuffer // and the returned required buffer size. success = SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref MyDeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, IntPtr.Zero); // Skip over cbsize (4 bytes) to get the address of the devicePathName. IntPtr pDevicePathName; if (IntPtr.Size == 4) pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4); else pDevicePathName = new IntPtr(detailDataBuffer.ToInt64() + 4); // Get the String containing the devicePathName. devicePathName[memberIndex] = Marshal.PtrToStringAuto(pDevicePathName); if (detailDataBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(detailDataBuffer); } deviceFound = true; } memberIndex = memberIndex + 1; } while (!((lastDevice == true))); return deviceFound; } catch { throw; } finally { // *** // API function // summary // Frees the memory reserved for the DeviceInfoSet returned by SetupDiGetClassDevs. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs. // returns // True on success. // *** if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } } /// <summary> /// Requests to receive a notification when a device is attached or removed. /// </summary> /// /// <param name="devicePathName"> handle to a device. </param> /// <param name="formHandle"> handle to the window that will receive device events. </param> /// <param name="classGuid"> device interface GUID. </param> /// <param name="deviceNotificationHandle"> returned device notification handle. </param> /// /// <returns> /// True on success. /// </returns> /// internal Boolean RegisterForDeviceNotifications(String devicePathName, IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) { // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; try { // Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure. // Set the size. size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; // Request to receive notifications about a class of devices. devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; // Specify the interface class to receive notifications about. devBroadcastDeviceInterface.dbcc_classguid = classGuid; // Allocate memory for the buffer that holds the DEV_BROADCAST_DEVICEINTERFACE structure. devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); // Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer. // Set fDeleteOld True to prevent memory leaks. Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); // *** // API function // summary // Request to receive notification messages when a device in an interface class // is attached or removed. // parameters // Handle to the window that will receive device events. // Pointer to a DEV_BROADCAST_DEVICEINTERFACE to specify the type of // device to send notifications for. // DEVICE_NOTIFY_WINDOW_HANDLE indicates the handle is a window handle. // Returns // Device notification handle or NULL on failure. // *** deviceNotificationHandle = RegisterDeviceNotification(formHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); // Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to // the managed object devBroadcastDeviceInterface Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((IntPtr.Size == 4) && (deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32())) { return false; } else if ((IntPtr.Size == 8) && (deviceNotificationHandle.ToInt64() == IntPtr.Zero.ToInt64())) { return false; } else { return true; } } catch { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } } /// <summary> /// Requests to stop receiving notification messages when a device in an /// interface class is attached or removed. /// </summary> /// /// <param name="deviceNotificationHandle"> handle returned previously by /// RegisterDeviceNotification. </param> internal void StopReceivingDeviceNotifications(IntPtr deviceNotificationHandle) { try { // *** // API function // summary // Stop receiving notification messages. // parameters // Handle returned previously by RegisterDeviceNotification. // returns // True on success. // *** // Ignore failures. DeviceManagement.UnregisterDeviceNotification(deviceNotificationHandle); } catch { throw; } } } }
Raydium/UpdateTool_Win
GenericHid_DeviceManagement.cs
C#
gpl-2.0
13,367
/* Copyright (c) 2009 Kevin Ottens <ervin@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "appendjob.h" #include <KDE/KLocalizedString> #include "job_p.h" #include "message_p.h" #include "session_p.h" #include "rfccodecs.h" namespace KIMAP { class AppendJobPrivate : public JobPrivate { public: AppendJobPrivate( Session *session, const QString& name ) : JobPrivate( session, name ), uid( 0 ) { } ~AppendJobPrivate() { } QString mailBox; QList<QByteArray> flags; KDateTime internalDate; QByteArray content; qint64 uid; }; } using namespace KIMAP; AppendJob::AppendJob( Session *session ) : Job( *new AppendJobPrivate( session, i18n( "Append" ) ) ) { } AppendJob::~AppendJob() { } void AppendJob::setMailBox( const QString &mailBox ) { Q_D( AppendJob ); d->mailBox = mailBox; } QString AppendJob::mailBox() const { Q_D( const AppendJob ); return d->mailBox; } void AppendJob::setFlags( const QList<QByteArray> &flags) { Q_D( AppendJob ); d->flags = flags; } QList<QByteArray> AppendJob::flags() const { Q_D( const AppendJob ); return d->flags; } void AppendJob::setInternalDate( const KDateTime &internalDate ) { Q_D( AppendJob ); d->internalDate = internalDate; } KDateTime AppendJob::internalDate() const { Q_D( const AppendJob ); return d->internalDate; } void AppendJob::setContent( const QByteArray &content ) { Q_D( AppendJob ); d->content = content; } QByteArray AppendJob::content() const { Q_D( const AppendJob ); return d->content; } qint64 AppendJob::uid() const { Q_D( const AppendJob ); return d->uid; } void AppendJob::doStart() { Q_D( AppendJob ); QByteArray parameters = '\"' + KIMAP::encodeImapFolderName( d->mailBox.toUtf8() ) + '\"'; if ( !d->flags.isEmpty() ) { parameters += " ("; foreach ( const QByteArray &flag, d->flags ) { parameters+= flag + ' '; } parameters.chop( 1 ); parameters += ')'; } if ( !d->internalDate.isNull() ) { parameters += " \"" + d->internalDate.toString( QString::fromAscii( "%d-%:b-%Y %H:%M:%S %z" ) ).toLatin1() + '\"'; } parameters += " {" + QByteArray::number( d->content.size() ) + '}'; d->tags << d->sessionInternal()->sendCommand( "APPEND", parameters ); } void AppendJob::handleResponse( const Message &response ) { Q_D( AppendJob ); for ( QList<Message::Part>::ConstIterator it = response.responseCode.begin(); it != response.responseCode.end(); ++it ) { if ( it->toString() == "APPENDUID" ) { it = it + 2; if ( it != response.responseCode.end() ) { d->uid = it->toString().toLongLong(); } break; } } if ( handleErrorReplies( response ) == NotHandled ) { if ( !response.content.isEmpty() && response.content[0].toString() == "+" ) { d->sessionInternal()->sendData( d->content ); } } }
kolab-groupware/kdepimlibs
kimap/appendjob.cpp
C++
gpl-2.0
3,632
<?php /** * The template for displaying image attachments. * * @package meetup * @since meetup 0.1 */ get_header(); ?> <div id="primary" class="content-area image-attachment full-width"> <div id="content" class="site-content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php /** * Get all the attached images */ $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type'=> 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) ); ?> <?php // If we have just 1 attachment, let's hide the image navigation if ( count( $attachments ) > 1 ) : ?> <nav id="image-navigation" class="site-navigation"> <span class="next-image"><?php next_image_link( false, sprintf( '%1$s<i class="icon-to-end"></i>', __( 'Next', 'meetup' ) ) ); ?></span> <span class="previous-image"><?php previous_image_link( false, sprintf( '<i class="icon-to-start"></i>%1$s', __( 'Previous', 'meetup' ) ) ); ?></span> <span class="back-to-post"><a href="<?php echo get_permalink( $post->post_parent ); ?> class="icon-cancel"><?php _e( 'Go back to post', 'meetup' ) ?></a></span> </nav><!-- #image-navigation --> <?php endif; ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <h1 class="entry-title"><?php the_title(); ?></h1> <div class="entry-meta"> <?php $metadata = wp_get_attachment_metadata(); printf( __( 'Published <span class="entry-date"><time class="entry-date" datetime="%1$s" pubdate>%2$s</time></span> at <a href="%3$s" title="Link to full-size image">%4$s &times; %5$s</a> in <a href="%6$s" title="Return to %7$s" rel="gallery">%7$s</a>', 'meetup' ), esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ), wp_get_attachment_url(), $metadata['width'], $metadata['height'], get_permalink( $post->post_parent ), get_the_title( $post->post_parent ) ); ?> <?php edit_post_link( __( 'Edit', 'meetup' ), '<span class="sep"> | </span> <span class="edit-link">', '</span>' ); ?> <?php if ( count( $attachments ) == 1 ) : ?> <p class="back-to-post"><a href="<?php echo get_permalink( $post->post_parent ); ?>" class="icon-cancel"><?php _e( 'Go back to post', 'meetup' ) ?></a></p> <?php endif; ?> </div><!-- .entry-meta --> </header><!-- .entry-header --> <div class="entry-content"> <div class="entry-attachment"> <figure class="attachment"> <?php /** * Grab the IDs of all the image attachments in a gallery so we can get the URL of the next adjacent image in a gallery, * or the first image (if we're looking at the last image in a gallery), or, in a gallery of one, just the link to that image file */ foreach ( $attachments as $k => $attachment ) { if ( $attachment->ID == $post->ID ) break; } $k++; // If there is more than 1 attachment in a gallery if ( count( $attachments ) > 1 ) { if ( isset( $attachments[ $k ] ) ) // get the URL of the next image attachment $next_attachment_url = get_attachment_link( $attachments[ $k ]->ID ); else // or get the URL of the first image attachment $next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID ); } else { // or, if there's only 1 image, get the URL of the image $next_attachment_url = wp_get_attachment_url(); } ?> <a href="<?php echo $next_attachment_url; ?>" title="<?php echo esc_attr( get_the_title() ); ?>" rel="attachment"><?php $attachment_size = apply_filters( 'meetup_attachment_size', array( 1200, 1200 ) ); // Filterable image size. echo wp_get_attachment_image( $post->ID, $attachment_size ); ?></a> <?php if ( ! empty( $post->post_excerpt ) ) : ?> <figcaption class="entry-caption"> <?php the_excerpt(); ?> </figcaption><!-- .entry-caption --> <?php endif; ?> <?php /** * Photographer credit line if the Glück plugin is active */ if( function_exists( 'glueck_get_photo_credit_line' ) ) : echo glueck_get_photo_credit_line( $attachment->ID ); endif ?> </figure><!-- .attachment --> </div><!-- .entry-attachment --> <div class="entry-description"> <?php the_content(); ?> </div> <?php wp_link_pages(); ?> </div><!-- .entry-content --> <footer class="entry-meta"> <?php if ( comments_open() && pings_open() ) : // Comments and trackbacks open ?> <?php printf( __( '<a class="comment-link" href="#respond" title="Post a comment">Post a comment</a> or leave a trackback: <a class="trackback-link" href="%s" title="Trackback URL for your post" rel="trackback">Trackback URL</a>.', 'meetup' ), get_trackback_url() ); ?> <?php elseif ( ! comments_open() && pings_open() ) : // Only trackbacks open ?> <?php printf( __( 'Comments are closed, but you can leave a trackback: <a class="trackback-link" href="%s" title="Trackback URL for your post" rel="trackback">Trackback URL</a>.', 'meetup' ), get_trackback_url() ); ?> <?php elseif ( comments_open() && ! pings_open() ) : // Only comments open ?> <?php _e( 'Trackbacks are closed, but you can <a class="comment-link" href="#respond" title="Post a comment">post a comment</a>.', 'meetup' ); ?> <?php elseif ( ! comments_open() && ! pings_open() ) : // Comments and trackbacks closed ?> <?php _e( 'Both comments and trackbacks are currently closed.', 'meetup' ); ?> <?php endif; ?> <span class="sep"> | </span> <?php meetup_social_sharing( get_the_ID() ); ?> <?php edit_post_link( __( 'Edit', 'meetup' ), '<span class="sep"> | </span> <span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-meta --> </article><!-- #post-<?php the_ID(); ?> --> <?php comments_template(); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content .site-content --> </div><!-- #primary .content-area .image-attachment --> <?php get_sidebar(); ?> <?php get_footer(); ?>
glueckpress/meetup
image.php
PHP
gpl-2.0
6,589
<?php /** * @version $Id: Joomla.php 3472 2006-05-13 01:04:18Z eddieajau $ * @package Joomla * @copyright Copyright (C) 2005 Open Source Matters. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ class patTemplate_Function_Joomla extends patTemplate_Function { /** * name of the function * @access private * @var string */ var $_name = 'Joomla'; /** * call the function * * @access public * @param array parameters of the function (= attributes of the tag) * @param string content of the tag * @return string content to insert into the template */ function call( $params, $content ) { if( !isset( $params['macro'] ) ) { return false; } $macro = strtolower( $params['macro'] ); switch ($macro) { case 'initeditor': return initEditor( true ); break; } return false; } } ?>
jpatriciogarcia/movistaropen
includes/patTemplate/patTemplate/Function/Joomla.php
PHP
gpl-2.0
1,284
<?php class ThietkewebSlider { protected static $instance; protected function __clone(){} protected function __construct(){} protected static function get_instance() { if(self::$instance === null) { self::$instance = new ThietkewebSlider(); } return self::$instance; } public static function run() { $instance = self::get_instance(); //register post type add_action('init', [$instance, 'register_post_type']); //register meta box add_action('admin_init', [$instance, 'register_meta_box']); //register scripts add_action('admin_enqueue_scripts', [$instance, 'register_scripts']); //save meta box add_action('save_post', [$instance, 'save_meta_box']); //register columns // add_filter('manage_edit-slider_columns'); // hook old add_filter('manage_slider_posts_columns', [$instance, 'register_columns']); //hook new like above // register column as sortable add_filter('manage_edit-slider_sortable_columns', [$instance, 'sortable_columns']); //show list slider add_action('manage_slider_posts_custom_column', [$instance, 'list_sliders'], 10, 2); //two argument //force open post thumbnail if not open add_action('after_setup_theme', function(){ add_theme_support('post-thumbnails'); }); return $instance; } // Register Custom Post Type public static function register_post_type(){ $instance = self::get_instance(); $labels = array( 'name' => _x( 'Sliders', 'Post Type General Name', 'thietkeweb' ), 'singular_name' => _x( 'Slider', 'Post Type Singular Name', 'thietkeweb' ), 'menu_name' => __( 'Slider', 'thietkeweb' ), 'name_admin_bar' => __( 'Post Type', 'thietkeweb' ), 'archives' => __( 'Item Archives', 'thietkeweb' ), 'parent_item_colon' => __( 'Parent Item:', 'thietkeweb' ), 'all_items' => __( 'All Items', 'thietkeweb' ), 'add_new_item' => __( 'Add New Item', 'thietkeweb' ), 'add_new' => __( 'Add New', 'thietkeweb' ), 'new_item' => __( 'New Item', 'thietkeweb' ), 'edit_item' => __( 'Edit Item', 'thietkeweb' ), 'update_item' => __( 'Update Item', 'thietkeweb' ), 'view_item' => __( 'View Item', 'thietkeweb' ), 'search_items' => __( 'Search Item', 'thietkeweb' ), 'not_found' => __( 'Not found', 'thietkeweb' ), 'not_found_in_trash' => __( 'Not found in Trash', 'thietkeweb' ), 'featured_image' => __( 'Featured Image', 'thietkeweb' ), 'set_featured_image' => __( 'Set featured image', 'thietkeweb' ), 'remove_featured_image' => __( 'Remove featured image', 'thietkeweb' ), 'use_featured_image' => __( 'Use as featured image', 'thietkeweb' ), 'insert_into_item' => __( 'Insert into item', 'thietkeweb' ), 'uploaded_to_this_item' => __( 'Uploaded to this item', 'thietkeweb' ), 'items_list' => __( 'Items list', 'thietkeweb' ), 'items_list_navigation' => __( 'Items list navigation', 'thietkeweb' ), 'filter_items_list' => __( 'Filter items list', 'thietkeweb' ), ); $args = array( 'label' => __( 'Slider', 'thietkeweb' ), 'description' => __( 'Post Type Description', 'thietkeweb' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'thumbnail', ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', ); register_post_type('slider', $args); return $instance; } public static function register_meta_box() { $instance = self::get_instance(); add_meta_box( 'slider_property' ,__( 'Slider Property', 'thietkeweb' ) , function($post) { $post_meta = get_post_meta( $post->ID, 'slider'); require(TH_THEME_DIR.'/views/admin/slider-metabox.php'); } ,'slider' ,'advanced' ,'high' ); return $instance; } public static function save_meta_box($post_id) { /* * We need to verify this came from our screen and with proper authorization, * because the save_post action can be triggered at other times. */ // Check if our nonce is set. if ( ! isset( $_POST['th_slider_security'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['th_slider_security'], $post_id ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } /* OK, it's safe for us to save the data now. */ // Make sure that it is set. if ( ! isset( $_POST['slider'] ) ) { return; } $data = $_POST['slider']; $data['link'] = (isset($data['link'])) ? sanitize_text_field($data['link']) : ''; $data['priority'] = (isset($data['priority'])) ? sanitize_text_field($data['priority']) : '1'; $data['status'] = (isset($data['status'])) ? sanitize_text_field($data['status']) : '0'; // Sanitize user input. // $data = sanitize_text_field( $data ); // Update the meta field in the database. update_post_meta( $post_id, 'slider', $data ); update_post_meta( $post_id, 'slider_priority', $data['priority'] ); } public static function register_scripts() { wp_register_style('thietkeweb_admin_css', TH_THEME_URL.'/css/admin/admin-style.css'); wp_enqueue_style('thietkeweb_admin_css'); wp_register_script('thietkeweb_admin_js', TH_THEME_URL.'/js/admin/admin.js'); wp_enqueue_script('thietkeweb_admin_js'); } public static function register_columns($columns) { $columns = [ 'cb' => $columns['cb'], 'title' => $columns['title'], 'post_thumb' => __('Image', 'thietkeweb'), 'link' => __('Link', 'thietkeweb'), 'priority' => __('Priority', 'thietkeweb'), 'status' => __('Status', 'thietkeweb'), 'date' => $columns['date'] ]; return $columns; } public static function sortable_columns($sortable_columns) { $sortable_columns = [ 'title' => 'title', 'priority' => 'priority', 'status' => 'status', ]; return $sortable_columns; } public static function list_sliders($columns, $post_id) { $data = get_post_meta($post_id, 'slider')[0]; switch ($columns) { case 'post_thumb': if(has_post_thumbnail( $post_id )) { echo get_the_post_thumbnail( $post_id, 'thumbnail' ); } break; case 'link': echo $data['link']; break; case 'priority': echo $data['priority']; break; case 'status': echo ($data['status'] == 1) ? __('Active', 'thietkeweb') : __('Deactive', 'thietkeweb'); break; default: # code... break; } } }
noluong/wordpress
wp-content/themes/thietkeweb/includes/class.thietkeweb-slider.php
PHP
gpl-2.0
7,500
<?php class CategoriasController extends Controller { public $layout = '//layouts/admin'; public function actionIndex() { $CategoryData = Yii::app()->db->createCommand()->select(' * ')->from('categoria')->queryAll(); $this->render('index', array('CategoryData' => $CategoryData)); } public function actionForms() { $this->render('forms'); } public function actionCreate() { FB::info($_POST, "____________________POST"); $model = new Categoria; if(!empty($_POST)){ $_POST['metas'] = implode(",", $_POST['metas']); $model->attributes = $_POST; $_POST['activo']=="true" ? $model->activo = 1 : $model->activo = 0; $model->fechaDeCreacion = new CDbExpression('NOW()'); FB::INFO($model->attributes, '_______________________ATTRIBUTES'); if ($model->save()){ $storeFolder = getcwd() . '\\assets\\images\\categorias\\'; FB::info($storeFolder, "storeFolder"); if (!is_dir($storeFolder)) mkdir($storeFolder, 0777,true); $type = $_FILES['imagen']['type']; $extension = explode('/', $type); if (!empty($_FILES)) { $tempFile = $_FILES['imagen']['tmp_name']; $targetPath = $storeFolder; $nuevoNombre = $model->idCategoria.'_'. $_POST['nuevoNombre'].'.'.$extension[1]; $targetFile = $targetPath . $nuevoNombre; if (move_uploaded_file($tempFile, $targetFile)) { FB::info("La imagen ha sido cargada al servidor.", "EXITO-Erasto"); $model->imagen = $nuevoNombre; FB::info( $model->imagen, "modelo imagen"); } else { FB::info("No se guardo al imagen", "error erasto"); } } if ($model->save()) { Yii::app()->user->setFlash("success", "La Categoria se Guardo Correctamente"); } Yii::app()->user->setFlash("warning", "No se pudo guardar la categoria, por favor intente de nuevo."); } } $this->render('create'); } public function actionUpdateajx() { FB::INFO($_POST, '__________________________POST'); if ($_POST['Categoria'] && Yii::app()->request->isAjaxRequest) { $sql = "UPDATE categoria SET nombre = :nombre, posicion = :posicion WHERE idCategoria = :idCategoria"; $parameters = array( ":idCategoria" => $_POST['Categoria']['idCategoria'], ':nombre' => $_POST['Categoria']['nombre'], ':posicion' => $_POST['Categoria']['posicion'] ); if (Yii::app()->db->createCommand($sql)->execute($parameters)) { $Content = $this->GetDataTableContent(); echo CJSON::encode(array( 'requestresult' => 'ok', 'message' => "Datos Actualizados Correctamente...", 'content' => $Content )); return; } else { echo CJSON::encode(array( 'requestresult' => 'error', 'message' => "No se pudo Actualizar, intente de nuevo." )); return; } } return; } public function actionTest() { $CategoryData = Yii::app()->db->createCommand()->select(' * ')->from('categoria')->queryAll(); $this->render('test', array('CategoryData' => $CategoryData)); } public function actionDTable() { /* Array of database columns which should be read and sent back to DataTables. Use a space where * you want to insert a non-database field (for example a counter or static image) */ $aColumns = array( 'idCategoria', 'nombre', 'imagen', 'posicion', 'fechaDeCreacion' ); /* Indexed column (used for fast and accurate table cardinality) */ $sIndexColumn = "idCategoria"; /* DB table to use */ $sTable = "categoria"; /* Database connection information */ $gaSql['user'] = "root"; $gaSql['password'] = ""; $gaSql['db'] = "mesa_regalos"; $gaSql['server'] = "127.0.0.1"; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * If you just want to use the basic configuration for DataTables with PHP server-side, there is * no need to edit below this line */ /* * MySQL connection */ $gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password']) or die('Could not open connection to server'); mysql_select_db($gaSql['db'], $gaSql['link']) or die('Could not select database ' . $gaSql['db']); /* * Paging */ $sLimit = ""; if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength']!='-1') { $sLimit = "LIMIT " . mysql_real_escape_string($_GET['iDisplayStart']) . ", " . mysql_real_escape_string($_GET['iDisplayLength']); } /* * Ordering */ if (isset($_GET['iSortCol_0'])) { $sOrder = "ORDER BY "; for ($i = 0; $i<intval($_GET['iSortingCols']); $i++) { if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])]=="true") { $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . " " . mysql_real_escape_string($_GET['sSortDir_' . $i]) . ", "; } } $sOrder = substr_replace($sOrder, "", -2); if ($sOrder=="ORDER BY") { $sOrder = ""; } } /* * Filtering * NOTE this does not match the built-in DataTables filtering which does it * word by word on any field. It's possible to do here, but concerned about efficiency * on very large tables, and MySQL's regex functionality is very limited */ $sWhere = ""; if ($_GET['sSearch']!="") { $sWhere = "WHERE ("; for ($i = 0; $i<count($aColumns); $i++) { $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR "; } $sWhere = substr_replace($sWhere, "", -3); $sWhere .= ')'; } /* Individual column filtering */ for ($i = 0; $i<count($aColumns); $i++) { if ($_GET['bSearchable_' . $i]=="true" && $_GET['sSearch_' . $i]!='') { if ($sWhere=="") { $sWhere = "WHERE "; } else { $sWhere .= " AND "; } $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' "; } } /* * SQL queries * Get data to display */ $sQuery = " SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM $sTable $sWhere $sOrder $sLimit "; $rResult = mysql_query($sQuery, $gaSql['link']) or die(mysql_error()); /* Data set length after filtering */ $sQuery = " SELECT FOUND_ROWS() "; $rResultFilterTotal = mysql_query($sQuery, $gaSql['link']) or die(mysql_error()); $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal); $iFilteredTotal = $aResultFilterTotal[0]; /* Total data set length */ $sQuery = " SELECT COUNT(" . $sIndexColumn . ") FROM $sTable "; $rResultTotal = mysql_query($sQuery, $gaSql['link']) or die(mysql_error()); $aResultTotal = mysql_fetch_array($rResultTotal); $iTotal = $aResultTotal[0]; /* * Output */ $output = array( "sEcho" => intval($_GET['sEcho']), "iTotalRecords" => $iTotal, "iTotalDisplayRecords" => $iFilteredTotal, "aaData" => array() ); while ($aRow = mysql_fetch_array($rResult)) { $row = array(); for ($i = 0; $i<count($aColumns); $i++) { if ($aColumns[$i]=="version") { /* Special output formatting for 'version' column */ $row[] = ($aRow[$aColumns[$i]]=="0") ? '-' : $aRow[$aColumns[$i]]; } else if ($aColumns[$i]!=' ') { /* General output */ $row[] = $aRow[$aColumns[$i]]; } } $output['aaData'][] = $row; } echo json_encode($output); } } ?>
JotaOwen/M-R
mesa_regalos/protected/controllers/CategoriasController.php
PHP
gpl-2.0
9,260
<?php /* ** Zabbix ** Copyright (C) 2001-2015 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__).'/include/config.inc.php'; require_once dirname(__FILE__).'/include/images.inc.php'; $page['title'] = _('Configuration of images'); $page['file'] = 'adm.images.php'; $page['hist_arg'] = array(); require_once dirname(__FILE__).'/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array( 'imageid' => array(T_ZBX_INT, O_NO, P_SYS, DB_ID, 'isset({form})&&{form}=="update"'), 'name' => array(T_ZBX_STR, O_NO, null, NOT_EMPTY, 'isset({save})'), 'imagetype' => array(T_ZBX_INT, O_OPT, null, IN('1,2'), 'isset({save})'), 'save' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'delete' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'form' => array(T_ZBX_STR, O_OPT, P_SYS, null, null) ); check_fields($fields); /* * Permissions */ if (isset($_REQUEST['imageid'])) { $dbImage = DBfetch(DBselect('SELECT i.imagetype,i.name FROM images i WHERE i.imageid='.zbx_dbstr(get_request('imageid')))); if (empty($dbImage)) { access_deny(); } } /* * Actions */ if (isset($_REQUEST['save'])) { if (isset($_REQUEST['imageid'])) { $msgOk = _('Image updated'); $msgFail = _('Cannot update image'); } else { $msgOk = _('Image added'); $msgFail = _('Cannot add image'); } try { DBstart(); if (isset($_FILES['image'])) { $file = new CUploadFile($_FILES['image']); $image = null; if ($file->wasUploaded()) { $file->validateImageSize(); $image = base64_encode($file->getContent()); } } if (isset($_REQUEST['imageid'])) { $result = API::Image()->update(array( 'imageid' => $_REQUEST['imageid'], 'name' => $_REQUEST['name'], 'imagetype' => $_REQUEST['imagetype'], 'image' => $image )); $audit_action = 'Image ['.$_REQUEST['name'].'] updated'; } else { $result = API::Image()->create(array( 'name' => $_REQUEST['name'], 'imagetype' => $_REQUEST['imagetype'], 'image' => $image )); $audit_action = 'Image ['.$_REQUEST['name'].'] added'; } if ($result) { add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_IMAGE, $audit_action); unset($_REQUEST['form']); } DBend($result); show_messages($result, $msgOk, $msgFail); } catch (Exception $e) { DBend(false); error($e->getMessage()); show_error_message($msgFail); } } elseif (isset($_REQUEST['delete']) && isset($_REQUEST['imageid'])) { $image = get_image_by_imageid($_REQUEST['imageid']); $result = API::Image()->delete($_REQUEST['imageid']); if ($result) { add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_IMAGE, 'Image ['.$image['name'].'] deleted'); unset($_REQUEST['form'], $image, $_REQUEST['imageid']); } show_messages($result, _('Image deleted'), _('Cannot delete image')); } /* * Display */ $form = new CForm(); $form->cleanItems(); $generalComboBox = new CComboBox('configDropDown', 'adm.images.php', 'redirect(this.options[this.selectedIndex].value);'); $generalComboBox->addItems(array( 'adm.gui.php' => _('GUI'), 'adm.housekeeper.php' => _('Housekeeping'), 'adm.images.php' => _('Images'), 'adm.iconmapping.php' => _('Icon mapping'), 'adm.regexps.php' => _('Regular expressions'), 'adm.macros.php' => _('Macros'), 'adm.valuemapping.php' => _('Value mapping'), 'adm.workingtime.php' => _('Working time'), 'adm.triggerseverities.php' => _('Trigger severities'), 'adm.triggerdisplayoptions.php' => _('Trigger displaying options'), 'adm.other.php' => _('Other') )); $form->addItem($generalComboBox); if (!isset($_REQUEST['form'])) { $form->addItem(new CSubmit('form', _('Create image'))); } $imageWidget = new CWidget(); $imageWidget->addPageHeader(_('CONFIGURATION OF IMAGES'), $form); $data = array( 'form' => get_request('form'), 'displayNodes' => is_array(get_current_nodeid()), 'widget' => &$imageWidget ); if (!empty($data['form'])) { if (isset($_REQUEST['imageid'])) { $data['imageid'] = $_REQUEST['imageid']; $data['imagename'] = $dbImage['name']; $data['imagetype'] = $dbImage['imagetype']; } else { $data['imageid'] = null; $data['imagename'] = get_request('name', ''); $data['imagetype'] = get_request('imagetype', 1); } $imageForm = new CView('administration.general.image.edit', $data); } else { $data['imagetype'] = get_request('imagetype', IMAGE_TYPE_ICON); $data['images'] = API::Image()->get(array( 'filter' => array('imagetype' => $data['imagetype']), 'output' => array('imageid', 'imagetype', 'name') )); order_result($data['images'], 'name'); // nodes if ($data['displayNodes']) { foreach ($data['images'] as &$image) { $image['nodename'] = get_node_name_by_elid($image['imageid'], true).NAME_DELIMITER; } unset($image); } $imageForm = new CView('administration.general.image.list', $data); } $imageWidget->addItem($imageForm->render()); $imageWidget->show(); require_once dirname(__FILE__).'/include/page_footer.php';
gplessis/dotdeb-zabbix
frontends/php/adm.images.php
PHP
gpl-2.0
5,643
/* * Autshumato Terminology Management System (TMS) * Free web application for the management of multilingual terminology databases (termbanks). * * Copyright (C) 2013 Centre for Text Technology (CTexT®), North-West University * and Department of Arts and Culture, Government of South Africa * Home page: http://www.nwu.co.za/ctext * Project page: http://autshumatotms.sourceforge.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tms2.server.usercategory; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.servlet.http.HttpSession; import tms2.server.sql.StoredProcedureManager; import tms2.server.user.UserManager; import tms2.shared.User; import tms2.shared.UserCategory; /** * * @author I. Lavangee * */ public class UserCategoryManager { /** * Retrieves all the user categories including the users the belong to each. * Used by the User & Categories panel in the Administration Interface. * @param connection * @return * @throws SQLException */ public static ArrayList<UserCategory> getAllUserCategoriesWithUsers(Connection connection, HttpSession session, String authToken) throws SQLException { ArrayList<UserCategory> userCategories = new ArrayList<UserCategory>(); String sql = "select * from tms.usercategories"; CallableStatement stored_procedure = StoredProcedureManager.genericReturnedRef(connection, sql); ResultSet results = (ResultSet) stored_procedure.getObject(1); while (results.next()) { int userCategoryId = results.getInt("usercategoryid"); ArrayList<User> users = UserManager.getAllUsersByCategory(connection, userCategoryId); UserCategory category = newUserCategoryWithUsers(results, users); userCategories.add(category); } results.close(); stored_procedure.close(); return userCategories; } public static UserCategory getUserCategoryByUserCategoryId(Connection connection, long userCategoryId) throws SQLException { UserCategory userCategory = null; String sql = "select * from tms.usercategories where usercategoryid = " + userCategoryId; CallableStatement stored_procedure = StoredProcedureManager.genericReturnedRef(connection, sql); ResultSet results = (ResultSet) stored_procedure.getObject(1); if (results.next()) userCategory = newUserCategory(results); results.close(); stored_procedure.close(); return userCategory; } public static boolean getUserCategoryIsAdmin(Connection connection, long userCategoryId) throws SQLException { boolean isAdmin = false; String sql = "select isadmin from tms.usercategories where usercategoryid = " + userCategoryId; CallableStatement stored_procedure = StoredProcedureManager.genericReturnedRef(connection, sql); ResultSet results = (ResultSet) stored_procedure.getObject(1); if (results.next()) isAdmin = results.getBoolean("isadmin"); results.close(); stored_procedure.close(); return isAdmin; } public static UserCategory updateUserCategory(Connection connection, UserCategory userCategory, boolean is_updating) throws SQLException { UserCategory updated = null; CallableStatement stored_procedure = null; if (is_updating) stored_procedure = StoredProcedureManager.updateUserCategory(connection, userCategory); else stored_procedure = StoredProcedureManager.createUserCategory(connection, userCategory); long result = -1; result = (Long)stored_procedure.getObject(1); if (result > -1) updated = getUserCategoryByUserCategoryId(connection, result); stored_procedure.close(); return updated; } public static void deleteUserCategory(Connection connection, UserCategory userCategory, String authToken, HttpSession session) throws SQLException { String sql = "delete from tms.usercategories where usercategoryid = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, userCategory.getUserCategoryId()); statement.executeUpdate(); } private static UserCategory newUserCategory(ResultSet results) throws SQLException { UserCategory userCategory = new UserCategory(); userCategory.setUserCategoryId(results.getInt("usercategoryid")); userCategory.setUserCategoryName(results.getString("usercategory")); userCategory.setAdmin(results.getBoolean("isadmin")); return userCategory; } // Create a UserCategory instance, with all the users belonging to this category, using the result set provided. private static UserCategory newUserCategoryWithUsers(ResultSet results, ArrayList<User> users) throws SQLException { UserCategory userCategory = new UserCategory(); userCategory.setUserCategoryId(results.getInt("usercategoryid")); userCategory.setUserCategoryName(results.getString("usercategory")); userCategory.setAdmin(results.getBoolean("isadmin")); userCategory.setUsers(users); return userCategory; } }
ismail-l/test-repo
src/tms2/server/usercategory/UserCategoryManager.java
Java
gpl-2.0
5,586
/** * */ package tuwien.dbai.wpps.core.wpmodel.physmodel.im.instadp; import tuwien.dbai.wpps.core.wpmodel.IContainsRDFResource; import tuwien.dbai.wpps.ontschema.InterfaceModelOnt; import com.hp.hpl.jena.rdf.model.Resource; /** * @author Ruslan (ruslanrf@gmail.com) * @created Jul 3, 2012 5:58:16 PM */ public enum EFontStyle implements IContainsRDFResource { NORMAL_FONT_STYLE(InterfaceModelOnt.NormalFontStyle), ITALIC(InterfaceModelOnt.Italic), OBLIQUE(InterfaceModelOnt.Oblique) ; EFontStyle(Resource fontStyle) { this.fontStyle = fontStyle; } private final Resource fontStyle; @Override public Resource getRdfResource() { return fontStyle; } }
ruslanrf/wpps
wpps_plugins/tuwien.dbai.wpps.core/src/tuwien/dbai/wpps/core/wpmodel/physmodel/im/instadp/EFontStyle.java
Java
gpl-2.0
680
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package com.mediatek.bluetooth.map.cache; import com.mediatek.bluetooth.map.util.UtcUtil; public class FolderListObject{ private String mTime = UtcUtil.getCurrentTime(); // "yyyymmddTHHMMSSZ", or "" if none private int mSize; private String mName; public void setName(String name){ mName = name; } public void setSize(int size){ mSize = size; } }
rex-xxx/mt6572_x201
mediatek/packages/apps/Bluetooth/profiles/map/src/com/mediatek/bluetooth/map/cache/FolderListObject.java
Java
gpl-2.0
2,588
/* * This file is part of the KDE wacomtablet project. For copyright * information and license terms see the AUTHORS and COPYING files * in the top-level directory of this distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "hwbuttondialog.h" #include "ui_hwbuttondialog.h" #include <QMouseEvent> #include <QPushButton> static unsigned int QtButton2X11Button(Qt::MouseButton qtbutton) { // We could probably just use log2 here, but I don't know if this can backfire // Qt seems to offer no function for getting index of a set flag unsigned int button = qtbutton; unsigned int buttonNumber = 0; while (button > 0) { buttonNumber++; button >>= 1; } if (buttonNumber < 4) { return buttonNumber; } else { // X11 buttons 4-7 are reserved for scroll wheel return buttonNumber + 4; } } using namespace Wacom; HWButtonDialog::HWButtonDialog(int maxButtons, QWidget *parent) : QDialog(parent) , ui(new Ui::HWButtonDialog) , m_maxButtons(maxButtons) , m_nextButton(1) { ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); nextButton(); } HWButtonDialog::~HWButtonDialog() { delete ui; } void HWButtonDialog::nextButton() { if(m_nextButton <= m_maxButtons) { QString text = i18n("Please press Button %1 on the tablet now.", m_nextButton); text.prepend(QLatin1String("<b>")); text.append(QLatin1String("</b>")); ui->textEdit->insertHtml(text); ui->textEdit->insertHtml(QLatin1String("<br>")); QTextCursor cursor = ui->textEdit->textCursor(); cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); ui->textEdit->setTextCursor(cursor); } } void HWButtonDialog::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::MouseButton::NoButton) { return; } hwKey(QtButton2X11Button(event->button())); } void HWButtonDialog::hwKey(unsigned int button) { if(m_nextButton <= m_maxButtons) { QString text = i18n("Hardware button %1 detected.", button); ui->textEdit->insertHtml(text); ui->textEdit->insertHtml(QLatin1String("<br><br>")); QTextCursor cursor = ui->textEdit->textCursor(); cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); ui->textEdit->setTextCursor(cursor); m_buttonMap << button; m_nextButton++; } if(m_nextButton > m_maxButtons) { ui->textEdit->insertHtml(i18n("All buttons detected. Please close dialog")); ui->textEdit->insertHtml(QLatin1String("<br>")); QTextCursor cursor = ui->textEdit->textCursor(); cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); ui->textEdit->setTextCursor(cursor); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); } else { nextButton(); } } QList<unsigned int> HWButtonDialog::buttonMap() const { return m_buttonMap; }
KDE/wacomtablet
src/tabletfinder/hwbuttondialog.cpp
C++
gpl-2.0
3,618
package nl.tdegroot.games.pixxel.map.tiled; public class Tile { public int tileID; public int firstGID,lastGID; public Tile(int tileID, int firstGID, int lastGID) { this.tileID = tileID; this.firstGID = firstGID; this.lastGID = lastGID; } }
Desmaster/Pixxel
map/tiled/Tile.java
Java
gpl-2.0
285
package org.nized.web.domain; import java.util.Date; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize @JsonDeserialize public class Checkin { private Person person; // Based on email stored in DB private Date date_scanned; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Date getDateScanned() { return date_scanned; } public void setDateScanned(Date dateScanned) { this.date_scanned = dateScanned; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((date_scanned == null) ? 0 : date_scanned.hashCode()); result = prime * result + ((person == null) ? 0 : person.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Checkin other = (Checkin) obj; if (date_scanned == null) { if (other.date_scanned != null) { return false; } } else if (!date_scanned.equals(other.date_scanned)) { return false; } if (person == null) { if (other.person != null) { return false; } } else if (!person.equals(other.person)) { return false; } return true; } @Override public String toString() { return "Checkin [person=" + person + ", date_scanned=" + date_scanned + "]"; } }
ryan-gyger/senior-web
src/main/java/org/nized/web/domain/Checkin.java
Java
gpl-2.0
1,597
/* * Copyright (c) 2009-2014, Treehouse Networks Ltd. New Zealand * 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. * * 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. */ /* * Fake Basic Authentication program for Squid. * * This code gets the user details and returns OK. * It is intended for testing use and as a base for further implementation. */ #include "squid.h" #include "helpers/defines.h" #include <cstring> /** * options: * -d enable debugging. * -h interface help. */ char *program_name = NULL; static void usage(void) { fprintf(stderr, "Usage: %s [-d] [-v] [-h]\n" " -d enable debugging.\n" " -h this message\n\n", program_name); } static void process_options(int argc, char *argv[]) { int opt; opterr = 0; while (-1 != (opt = getopt(argc, argv, "hd"))) { switch (opt) { case 'd': debug_enabled = 1; break; case 'h': usage(); exit(0); default: fprintf(stderr, "%s: FATAL: unknown option: -%c. Exiting\n", program_name, opt); usage(); exit(1); } } } int main(int argc, char *argv[]) { char buf[HELPER_INPUT_BUFFER]; int buflen = 0; setbuf(stdout, NULL); setbuf(stderr, NULL); program_name = argv[0]; process_options(argc, argv); debug("%s build " __DATE__ ", " __TIME__ " starting up...\n", program_name); while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL) { char *p; if ((p = strchr(buf, '\n')) != NULL) { *p = '\0'; /* strip \n */ buflen = p - buf; /* length is known already */ } else buflen = strlen(buf); /* keep this so we only scan the buffer for \0 once per loop */ debug("Got %d bytes '%s' from Squid\n", buflen, buf); /* send 'OK' result back to Squid */ SEND_OK(""); } debug("%s build " __DATE__ ", " __TIME__ " shutting down...\n", program_name); exit(0); }
lgcosta/squid3
helpers/basic_auth/fake/fake.cc
C++
gpl-2.0
3,267
/* * @author Stéphane LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2021 Vanilla Forums Inc. * @license GPL-2.0-only */ import { globalVariables } from "@library/styles/globalStyleVars"; import { useThemeCache } from "@library/styles/themeCache"; import { formElementsVariables } from "@library/forms/formElementStyles"; import { ColorsUtils } from "@library/styles/ColorsUtils"; import { absolutePosition, borderRadii, defaultTransition, flexHelper, getVerticalPaddingForTextInput, importantUnit, singleBorder, userSelect, } from "@library/styles/styleHelpers"; import { styleUnit } from "@library/styles/styleUnit"; import { Mixins } from "@library/styles/Mixins"; import { calc, important, percent, px, translateX } from "csx"; import { titleBarVariables } from "@library/headers/TitleBar.variables"; import { buttonGlobalVariables } from "@library/forms/Button.variables"; import { buttonResetMixin } from "@library/forms/buttonMixins"; import { oneColumnVariables } from "@library/layout/Section.variables"; import { shadowHelper } from "@library/styles/shadowHelpers"; import { inputBlockClasses } from "@library/forms/InputBlockStyles"; import { css, CSSObject } from "@emotion/css"; import { inputVariables } from "@library/forms/inputStyles"; import { suggestedTextStyleHelper } from "@library/features/search/suggestedTextStyles"; import { searchResultsVariables } from "@library/features/search/searchResultsStyles"; import { paddingOffsetBasedOnBorderRadius } from "@library/forms/paddingOffsetFromBorderRadius"; import { selectBoxClasses } from "@library/forms/select/selectBoxStyles"; import { SearchBarPresets } from "@library/banner/SearchBarPresets"; import { IBorderRadiusValue } from "@library/styles/cssUtilsTypes"; import { searchBarVariables } from "./SearchBar.variables"; import { metasVariables } from "@library/metas/Metas.variables"; export interface ISearchBarOverwrites { borderRadius?: IBorderRadiusValue; compact?: boolean; preset?: SearchBarPresets; } export const searchBarClasses = useThemeCache((overwrites?: ISearchBarOverwrites) => { const shadow = shadowHelper(); const classesInputBlock = inputBlockClasses(); const vars = searchBarVariables(); const { compact = vars.options.compact, borderRadius = vars.border.radius, preset = vars.options.preset } = overwrites || {}; const globalVars = globalVariables(); const metasVars = metasVariables(); const layoutVars = oneColumnVariables(); const inputVars = inputVariables(); const titleBarVars = titleBarVariables(); const formElementVars = formElementsVariables(); const mediaQueries = layoutVars.mediaQueries(); const borderStyle = overwrites && overwrites.preset ? overwrites.preset : vars.options.preset; const isOuterBordered = borderStyle === SearchBarPresets.BORDER; const isInsetBordered = borderStyle === SearchBarPresets.NO_BORDER; const borderColor = isInsetBordered ? vars.input.bg : vars.border.color; const independentRoot = css({ display: "block", height: percent(100), }); const verticalPadding = getVerticalPaddingForTextInput( vars.sizing.height, inputVars.font.size as number, formElementVars.border.width * 2, ); const calculatedHeight = vars.sizing.height - verticalPadding * 2 - formElementVars.border.width * 2; const borderVars = vars.border || globalVars.border; const paddingOffset = paddingOffsetBasedOnBorderRadius({ radius: borderRadius, extraPadding: vars.search.fullBorderRadius.extraHorizontalPadding, height: vars.sizing.height, side: "right", }); const root = css({ cursor: "pointer", ...{ ".searchBar__placeholder": { color: ColorsUtils.colorOut(vars.placeholder.color), margin: "auto", height: styleUnit(calculatedHeight), lineHeight: styleUnit(calculatedHeight), overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", top: 0, transform: "none", cursor: "text", // Needed otherwise you can't use copy/paste in the context menu. // @see https://github.com/JedWatson/react-select/issues/612 // @see https://github.com/vanilla/support/issues/3252 pointerEvents: "none", }, ".suggestedTextInput-valueContainer": { ...{ [`.${classesInputBlock.inputText}`]: { height: "auto", }, "& > *": { width: percent(100), }, }, }, ".wrap__control": { width: percent(100), }, ".searchBar__control": { border: 0, backgroundColor: ColorsUtils.colorOut(globalVars.elementaryColors.transparent), width: percent(100), flexBasis: percent(100), ...{ "&.searchBar__control--is-focused": { boxShadow: "none", }, }, }, ".searchBar__value-container": { position: "static", overflow: "auto", cursor: "text", display: "flex", justifyContent: "center", alignItems: "center", lineHeight: styleUnit(globalVars.lineHeights.base * globalVars.fonts.size.medium), fontSize: styleUnit(inputVars.font.size), height: styleUnit(calculatedHeight), "& > div": { width: percent(100), }, }, ".searchBar__indicators": { display: "none", }, ".searchBar__input": { width: percent(100), }, ".searchBar__input input": { margin: 0, height: "auto", minHeight: 0, width: important(`100%`), borderRadius: important(0), lineHeight: styleUnit(globalVars.lineHeights.base * globalVars.fonts.size.medium), }, }, }); const submitButton = css({ ...Mixins.button(compact ? vars.compactSubmitButton : vars.submitButton), margin: "-1px", "&:hover, &:focus": { zIndex: 2, }, paddingRight: importantUnit(buttonGlobalVariables().padding.horizontal + paddingOffset.right), ...mediaQueries.oneColumnDown({ minWidth: 0, }), }); // The styles have been split here so they can be exported to the compatibility styles. const searchResultsStyles = { title: { ...Mixins.font({ ...globalVars.fontSizeAndWeightVars("large", "semiBold"), lineHeight: globalVars.lineHeights.condensed, }), }, meta: { ...Mixins.font(metasVars.font), }, excerpt: { marginTop: styleUnit(searchResultsVariables().excerpt.margin), ...Mixins.font({ ...globalVars.fontSizeAndWeightVars("medium"), color: vars.results.fg, lineHeight: globalVars.lineHeights.excerpt, }), }, }; const results = css({ position: "absolute", width: percent(100), backgroundColor: ColorsUtils.colorOut(vars.results.bg), color: ColorsUtils.colorOut(vars.results.fg), ...borderRadii({ all: Math.min(parseInt(borderRadius.toString()), 6), }), ...{ "&:empty": { display: important("none"), }, ".suggestedTextInput__placeholder": { color: ColorsUtils.colorOut(formElementVars.placeholder.color), }, ".suggestedTextInput-noOptions": { padding: px(12), }, ".suggestedTextInput-head": { ...flexHelper().middleLeft(), justifyContent: "space-between", }, ".suggestedTextInput-option": { ...suggestedTextStyleHelper().option, margin: 0, }, ".suggestedTextInput-menuItems": { margin: 0, padding: 0, }, ".suggestedTextInput-item": { listStyle: "none", ...{ "& + .suggestedTextInput-item": { borderTop: `solid 1px ${globalVars.border.color.toString()}`, }, }, }, ".suggestedTextInput-title": { ...searchResultsStyles.title, }, ".suggestedTextInput-title .suggestedTextInput-searchingFor": { fontWeight: globalVars.fonts.weights.normal, }, }, }); const resultsAsModal = css({ position: "absolute", top: styleUnit(vars.sizing.height), left: 0, overflow: "hidden", boxSizing: "border-box", ...shadow.dropDown(), zIndex: 2, }); const clear = css({ position: "relative", display: "flex", boxSizing: "border-box", height: styleUnit(vars.sizing.height), width: styleUnit(vars.sizing.height), color: ColorsUtils.colorOut(globalVars.mixBgAndFg(0.78)), transform: translateX(`${styleUnit(4)}`), ...{ "&, &.buttonIcon": { border: "none", boxShadow: "none", }, "&:hover": { color: ColorsUtils.colorOut(vars.stateColors.hover), }, "&:focus": { color: ColorsUtils.colorOut(vars.stateColors.focus), }, }, }); const mainConditionalStyles = isInsetBordered ? { padding: `0 ${styleUnit(borderVars.width)}`, } : {}; const main = css({ flexGrow: 1, position: "relative", borderRadius: 0, ...mainConditionalStyles, ...{ "&&.withoutButton.withoutScope": { ...borderRadii({ right: borderRadius, left: borderRadius, }), }, "&&.withButton.withScope": { ...borderRadii({ left: borderRadius, }), }, "&&.withoutButton.withScope": { ...borderRadii({ right: borderRadius, }), }, "&&.withButton.withoutScope": { ...borderRadii({ left: borderRadius, right: 0, }), }, "&.isFocused": { zIndex: isOuterBordered ? 3 : 1, }, "&.isHovered": { zIndex: isOuterBordered ? 3 : undefined, }, }, }); const valueContainerConditionalStyles = isInsetBordered ? { position: "absolute", top: 0, left: 0, height: calc(`100% - 2px`), minHeight: calc(`100% - 2px`), width: calc(`100% - 2px`), margin: styleUnit(1), } : { height: percent(100), }; const valueContainer = css({ ...{ "&&&": { ...valueContainerConditionalStyles, display: "flex", alignItems: "center", backgroundColor: ColorsUtils.colorOut(vars.input.bg), color: ColorsUtils.colorOut(vars.input.fg), cursor: "text", flexWrap: "nowrap", justifyContent: "flex-start", borderRadius: 0, zIndex: isInsetBordered ? 2 : undefined, ...defaultTransition("border-color"), ...Mixins.border({ color: borderColor, }), ...borderRadii({ all: borderRadius, }), }, "&&&:not(.isFocused)": { borderColor: ColorsUtils.colorOut(isInsetBordered ? vars.input.bg : vars.border.color), }, "&&&:not(.isFocused).isHovered": { borderColor: ColorsUtils.colorOut(vars.stateColors.hover), }, [`&&&&.isFocused .${main}`]: { borderColor: ColorsUtils.colorOut(vars.stateColors.hover), }, // -- Text Input Radius -- // Both sides round "&&.inputText.withoutButton.withoutScope": { paddingLeft: styleUnit(vars.searchIcon.gap), ...borderRadii({ all: borderRadius, }), }, // Right side flat "&&.inputText.withButton.withoutScope": { paddingLeft: styleUnit(vars.searchIcon.gap), paddingRight: styleUnit(vars.searchIcon.gap), ...borderRadii({ left: borderRadius, right: 0, }), }, [`&&.inputText.withButton.withoutScope .${clear}`]: { ...absolutePosition.topRight(), bottom: 0, ...Mixins.margin({ vertical: "auto", }), transform: translateX(styleUnit(vars.border.width * 2)), }, // Both sides flat "&&.inputText.withButton.withScope": { ...borderRadii({ left: 0, }), }, // Left side flat "&&.inputText.withoutButton.withScope:not(.compactScope)": { paddingRight: styleUnit(vars.searchIcon.gap), }, "&&.inputText.withoutButton.withScope": { ...borderRadii({ right: borderRadius, left: 0, }), }, }, } as CSSObject); // Has a search button attached. const compoundValueContainer = css({ ...{ "&&": { borderTopRightRadius: important(0), borderBottomRightRadius: important(0), }, }, }); const actionButton = css({ marginLeft: -borderVars.width, }); const label = css({ display: "flex", alignItems: "center", justifyContent: "flex-start", }); const scopeSeparatorStyle = isOuterBordered ? { display: "none", } : { ...absolutePosition.topRight(), bottom: 0, margin: "auto 0", height: percent(90), width: styleUnit(borderVars.width), borderRight: singleBorder({ color: borderVars.color, }), }; const scopeSeparator = css(scopeSeparatorStyle); const content = css({ display: "flex", alignItems: "stretch", justifyContent: "flex-start", position: "relative", backgroundColor: ColorsUtils.colorOut(vars.input.bg), width: percent(100), height: percent(100), ...{ "&&.withoutButton.withoutScope": { ...borderRadii({ all: borderRadius, }), }, "&&.withButton.withScope": {}, "&&.withoutButton.withScope": { ...borderRadii({ all: borderRadius, }), }, "&&.withButton.withoutScope": { ...borderRadii({ left: borderRadius, right: 0, }), }, [`&.hasFocus .${scopeSeparator}`]: { display: "none", }, [`&.hasFocus .${valueContainer}`]: { borderColor: ColorsUtils.colorOut(vars.stateColors.focus), }, }, }); // special selector const heading = css({ ...{ "&&": { marginBottom: styleUnit(vars.heading.margin), }, }, }); const icon = css({}); const iconContainer = (alignRight?: boolean) => { const { compact = false } = overwrites || {}; const horizontalPosition = styleUnit(compact ? vars.scope.compact.padding : vars.scope.padding); const conditionalStyle = alignRight ? { right: horizontalPosition, } : { left: horizontalPosition, }; return css({ ...buttonResetMixin(), position: "absolute", top: 0, bottom: 0, ...conditionalStyle, height: percent(100), display: "flex", alignItems: "center", justifyContent: "center", zIndex: 5, outline: 0, color: ColorsUtils.colorOut(vars.searchIcon.fg), ...{ [`.${icon}`]: { width: styleUnit(vars.searchIcon.width), height: styleUnit(vars.searchIcon.height), }, [`&&& + .searchBar-valueContainer`]: { paddingLeft: styleUnit(vars.searchIcon.gap), }, "&:hover": { color: ColorsUtils.colorOut(vars.stateColors.hover), }, "&:focus": { color: ColorsUtils.colorOut(vars.stateColors.focus), }, }, }); }; const iconContainerBigInput = css({ ...{ "&&": { height: styleUnit(vars.sizing.height), }, }, }); const menu = css({ display: "flex", alignItems: "flex-start", justifyContent: "flex-start", ...{ "&.hasFocus .searchBar-valueContainer": { borderColor: ColorsUtils.colorOut(vars.stateColors.focus), }, "&&": { position: "relative", }, ".searchBar__menu-list": { maxHeight: calc(`100vh - ${styleUnit(titleBarVars.sizing.height)}`), width: percent(100), }, ".searchBar__input": { color: ColorsUtils.colorOut(globalVars.mainColors.fg), width: percent(100), display: important("block"), ...{ input: { width: important(percent(100).toString()), lineHeight: globalVars.lineHeights.base, }, }, }, ".suggestedTextInput-menu": { borderRadius: styleUnit(globalVars.border.radius), marginTop: styleUnit(-formElementVars.border.width), marginBottom: styleUnit(-formElementVars.border.width), }, "&:empty": { display: "none", }, }, }); const { selectBoxDropdown, buttonIcon } = selectBoxClasses(); const scopeSelect = css({ display: "flex", width: calc("100%"), height: calc("100%"), justifyContent: "center", alignItems: "stretch", ...{ [`.${selectBoxDropdown}`]: { position: "relative", padding: isInsetBordered ? styleUnit(vars.border.width) : undefined, width: percent(100), height: percent(100), }, }, }); const scopeToggleConditionalStyles: CSSObject = isInsetBordered ? { position: "absolute", top: 0, left: 0, height: calc(`100% - 2px`), width: calc(`100% - 2px`), margin: styleUnit(vars.noBorder.offset), } : { width: percent(100), height: percent(100), }; const scopeToggle = css({ display: "flex", justifyContent: "stretch", alignItems: "center", lineHeight: "2em", flexWrap: "nowrap", ...scopeToggleConditionalStyles, ...Mixins.border({ color: borderColor, }), ...userSelect(), backgroundColor: ColorsUtils.colorOut(globalVars.mainColors.bg), ...Mixins.padding({ horizontal: compact ? vars.scope.compact.padding : vars.scope.padding, }), outline: 0, ...borderRadii({ left: borderRadius, right: 0, }), ...{ [`.${buttonIcon}`]: { width: styleUnit(vars.scopeIcon.width), flexBasis: styleUnit(vars.scopeIcon.width), height: styleUnit(vars.scopeIcon.width * vars.scopeIcon.ratio), margin: "0 0 0 auto", color: ColorsUtils.colorOut(vars.input.fg), }, "&:focus, &:hover, &:active, &.focus-visible": { zIndex: 3, }, "&:hover": { borderColor: ColorsUtils.colorOut(vars.stateColors.hover), }, "&:active": { borderColor: ColorsUtils.colorOut(vars.stateColors.active), }, "&:focus, &.focus-visible": { borderColor: ColorsUtils.colorOut(vars.stateColors.focus), }, // Nested above doesn't work [`&:focus .${scopeSeparator}, &:hover .${scopeSeparator}, &:active .${scopeSeparator}, &.focus-visible .${scopeSeparator}`]: { display: "none", }, }, }); const scopeLabelWrap = css({ display: "flex", textOverflow: "ellipsis", whiteSpace: "nowrap", overflow: "hidden", lineHeight: 2, color: ColorsUtils.colorOut(vars.input.fg), }); const scope = css({ position: "relative", minHeight: styleUnit(vars.sizing.height), width: styleUnit(compact ? vars.scope.compact.width : vars.scope.width), flexBasis: styleUnit(compact ? vars.scope.compact.width : vars.scope.width), display: "flex", alignItems: "stretch", justifyContent: "flex-start", backgroundColor: ColorsUtils.colorOut(globalVars.mainColors.bg), paddingRight: isInsetBordered ? styleUnit(vars.border.width) : undefined, transform: isOuterBordered ? translateX(styleUnit(vars.border.width)) : undefined, zIndex: isOuterBordered ? 2 : undefined, ...borderRadii({ left: borderRadius, right: 0, }), ...{ [` &.isOpen .${scopeSeparator}, &.isActive .${scopeSeparator} `]: { display: "none", }, [`.${scopeToggle}`]: { ...borderRadii({ left: borderRadius, right: 0, }), }, [`&.isCompact .${scopeToggle}`]: { paddingLeft: styleUnit(12), paddingRight: styleUnit(12), }, [`& + .${main}`]: { maxWidth: calc(`100% - ${styleUnit(compact ? vars.scope.compact.width : vars.scope.width)}`), flexBasis: calc(`100% - ${styleUnit(compact ? vars.scope.compact.width : vars.scope.width)}`), }, }, }); const wrap = css({ display: "flex", height: percent(100), width: percent(100), }); const form = css({ display: "flex", width: percent(100), flexWrap: "nowrap", alignItems: "center", }); const closeButton = css({ marginLeft: styleUnit(6), borderRadius: "6px", }); const compactIcon = css({ ...{ "&&": { width: styleUnit(vars.searchIcon.width), height: styleUnit(vars.searchIcon.height), }, }, }); const standardContainer = css({ display: "block", position: "relative", height: styleUnit(vars.sizing.height), marginBottom: styleUnit(globalVars.gutter.size), }); const firstItemBorderTop = css({ borderTop: `solid 1px ${globalVars.border.color.toString()}`, }); return { root, submitButton, independentRoot, compoundValueContainer, valueContainer, actionButton, label, clear, form, content, heading, iconContainer, iconContainerBigInput, icon, results, resultsAsModal, menu, searchResultsStyles, // for compatibility scope, scopeToggle, scopeSeparator, scopeSelect, scopeLabelWrap, closeButton, wrap, main, compactIcon, standardContainer, firstItemBorderTop, }; });
vanilla/vanilla
library/src/scripts/features/search/SearchBar.styles.ts
TypeScript
gpl-2.0
25,564
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2013 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef STARTPOINT_HPP #define STARTPOINT_HPP #include "OrderedTaskPoint.hpp" #include "Task/TaskBehaviour.hpp" #include "Task/Ordered/StartConstraints.hpp" /** * A StartPoint is an abstract OrderedTaskPoint, * can manage start transitions * but does not yet have an observation zone. * No taskpoints shall be present preceding a StartPoint. * * \todo * - gate start time? * - enabled/disabled for multiple start points */ class StartPoint final : public OrderedTaskPoint { fixed safety_height; TaskStartMargins margins; /** * A copy of OrderedTaskSettings::start_constraints, managed by * SetOrderedTaskSettings(). */ StartConstraints constraints; public: /** * Constructor. Sets task area to non-scorable; distances * are relative to crossing point or origin. * * @param _oz Observation zone for this task point * @param wp Waypoint origin of turnpoint * @param tb Task Behaviour defining options (esp safety heights) * @param to OrderedTask Behaviour defining options * * @return Partially-initialised object */ StartPoint(ObservationZonePoint *_oz, const Waypoint &wp, const TaskBehaviour &tb, const StartConstraints &constraints); bool DoesRequireArm() const { return constraints.require_arm; } /** * Manually sets the start time */ void SetHasExitedOverride () { ScoredTaskPoint::SetHasExited(true); } /** * Find correct start point for either FAI or US contest * - for US, use actual start location (or center of cylinder if actual * start is in back half) * - for FAI use closest point on boundary of cylinder * Updates stats, samples and states for start, intermediate and finish transitions * Should only be performed when the aircraft state is inside the sector * * @param state Current aircraft state * @param next Next task point following the start * @param * @para do we find a point on the border instead of the actual start point */ void find_best_start(const AircraftState &state, const OrderedTaskPoint &next, const TaskProjection &projection, bool subtract_start_radius); /* virtual methods from class TaskPoint */ virtual fixed GetElevation() const override; /* virtual methods from class ScoredTaskPoint */ virtual bool CheckExitTransition(const AircraftState &ref_now, const AircraftState &ref_last) const override; /* virtual methods from class OrderedTaskPoint */ virtual void SetTaskBehaviour(const TaskBehaviour &tb) override; virtual void SetOrderedTaskSettings(const OrderedTaskSettings &s) override; virtual void SetNeighbours(OrderedTaskPoint *prev, OrderedTaskPoint *next) override; virtual bool IsInSector(const AircraftState &ref) const override; virtual bool UpdateSampleNear(const AircraftState &state, const TaskProjection &projection) override; private: /* virtual methods from class ScoredTaskPoint */ virtual bool ScoreLastExit() const override { return true; } }; #endif
DRNadler/DRN_TopHat
src/Engine/Task/Ordered/Points/StartPoint.hpp
C++
gpl-2.0
4,095
# -*- coding: utf-8 -*- """ Created on Wed Aug 19 17:08:36 2015 @author: jgimenez """ from PyQt4 import QtGui, QtCore import os import time import subprocess types = {} types['p'] = 'scalar' types['U'] = 'vector' types['p_rgh'] = 'scalar' types['k'] = 'scalar' types['epsilon'] = 'scalar' types['omega'] = 'scalar' types['alpha'] = 'scalar' types['nut'] = 'scalar' types['nuTilda'] = 'scalar' types['nuSgs'] = 'scalar' unknowns = ['U','p','p_rgh','alpha','k','nuSgs','epsilon','omega','nuTilda','nut'] def drange(start, stop, step): r = start while r < stop: yield r r += step def command_window(palette): brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) def currentFields(currentFolder,filterTurb=True,nproc=1): #veo los campos que tengo en el directorio inicial timedir = 0 currtime = 0 logname = '%s/dirFeatures.log'%currentFolder logerrorname = '%s/error.log'%currentFolder #print 'nproc: %s'%nproc if nproc<=1: command = 'dirFeaturesFoam -case %s 1> %s 2> %s' % (currentFolder,logname,logerrorname) else: command = 'mpirun -np %s dirFeaturesFoam -case %s -parallel 1> %s 2> %s' % (nproc,currentFolder,logname,logerrorname) #print 'command: %s'%command #p = subprocess.Popen([command],shell=True) #p.wait() os.system(command) log = open(logname, 'r') for linea in log: if "Current Time" in linea: currtime = linea.split('=')[1].strip() timedir = '%s/%s'%(currentFolder,currtime) from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile #Levanto todos los campos y me fijo cual se ca a utilizar (dependiendo del turbulence model) allturb = ['k','epsilon','omega','nuSgs','nut','nuTilda'] #le dejo los que voy a utilizar filename = '%s/constant/turbulenceProperties'%currentFolder e=False try: tprop = ParsedParameterFile(filename,createZipped=False) except IOError as e: tprop = {} if (not e): if tprop['simulationType']=='RASModel': filename = '%s/constant/RASProperties'%currentFolder Rprop = ParsedParameterFile(filename,createZipped=False) if Rprop['RASModel']=='kEpsilon': allturb.remove('k') allturb.remove('epsilon') if Rprop['RASModel']=='kOmega' or Rprop['RASModel']=='kOmegaSST': allturb.remove('k') allturb.remove('omega') elif tprop['simulationType']=='LESModel': filename = '%s/constant/LESProperties'%currentFolder Lprop = ParsedParameterFile(filename,createZipped=False) if Lprop['LESModel']=='Smagorinsky': allturb.remove('nuSgs') NO_FIELDS = ['T0', 'T1', 'T2', 'T3', 'T4', 'nonOrth', 'skew'] if filterTurb: for it in allturb: NO_FIELDS.append(it) command = 'rm -f %s/*~ %s/*.old'%(timedir,timedir) os.system(command) while not os.path.isfile(logname): continue #Esta linea la agrego porque a veces se resetea el caso y se borra #el folder de currentTime. Por eso uso el 0, siempre estoy seguro que #esta presente if not os.path.isdir(str(timedir)): timedir = '%s/0'%currentFolder fields = [ f for f in os.listdir(timedir) if (f not in NO_FIELDS and f in unknowns) ] return [timedir,fields,currtime] def backupFile(f): filename = f if os.path.isfile(filename) and os.path.getsize(filename) > 0: newfilepath = filename+'.backup' command = 'cp %s %s'%(filename,newfilepath) os.system(command) def get_screen_resolutions(): output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0] resolution = output.split()[0].split(b'x') return resolution
jmarcelogimenez/petroSym
petroSym/utils.py
Python
gpl-2.0
11,739
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Axel Kohlmeyer (Temple U) ------------------------------------------------------------------------- */ #include "math.h" #include "pair_lj_cut_coul_cut_omp.h" #include "atom.h" #include "comm.h" #include "force.h" #include "neighbor.h" #include "neigh_list.h" #include "suffix.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ PairLJCutCoulCutOMP::PairLJCutCoulCutOMP(LAMMPS *lmp) : PairLJCutCoulCut(lmp), ThrOMP(lmp, THR_PAIR) { suffix_flag |= Suffix::OMP; respa_enable = 0; } /* ---------------------------------------------------------------------- */ void PairLJCutCoulCutOMP::compute(int eflag, int vflag) { if (eflag || vflag) { ev_setup(eflag,vflag); } else evflag = vflag_fdotr = 0; const int nall = atom->nlocal + atom->nghost; const int nthreads = comm->nthreads; const int inum = list->inum; #if defined(_OPENMP) #pragma omp parallel default(none) shared(eflag,vflag) #endif { int ifrom, ito, tid; loop_setup_thr(ifrom, ito, tid, inum, nthreads); ThrData *thr = fix->get_thr(tid); thr->timer(Timer::START); ev_setup_thr(eflag, vflag, nall, eatom, vatom, thr); if (evflag) { if (eflag) { if (force->newton_pair) eval<1,1,1>(ifrom, ito, thr); else eval<1,1,0>(ifrom, ito, thr); } else { if (force->newton_pair) eval<1,0,1>(ifrom, ito, thr); else eval<1,0,0>(ifrom, ito, thr); } } else { if (force->newton_pair) eval<0,0,1>(ifrom, ito, thr); else eval<0,0,0>(ifrom, ito, thr); } thr->timer(Timer::PAIR); reduce_thr(this, eflag, vflag, thr); } // end of omp parallel region } /* ---------------------------------------------------------------------- */ template <int EVFLAG, int EFLAG, int NEWTON_PAIR> void PairLJCutCoulCutOMP::eval(int iifrom, int iito, ThrData * const thr) { int i,j,ii,jj,jnum,itype,jtype; double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,evdwl,ecoul,fpair; double rsq,rinv,r2inv,r6inv,forcecoul,forcelj,factor_coul,factor_lj; int *ilist,*jlist,*numneigh,**firstneigh; evdwl = ecoul = 0.0; const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0]; dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0]; const double * _noalias const q = atom->q; const int * _noalias const type = atom->type; const int nlocal = atom->nlocal; const double * _noalias const special_coul = force->special_coul; const double * _noalias const special_lj = force->special_lj; const double qqrd2e = force->qqrd2e; double fxtmp,fytmp,fztmp; ilist = list->ilist; numneigh = list->numneigh; firstneigh = list->firstneigh; // loop over neighbors of my atoms for (ii = iifrom; ii < iito; ++ii) { i = ilist[ii]; qtmp = q[i]; xtmp = x[i].x; ytmp = x[i].y; ztmp = x[i].z; itype = type[i]; jlist = firstneigh[i]; jnum = numneigh[i]; fxtmp=fytmp=fztmp=0.0; for (jj = 0; jj < jnum; jj++) { j = jlist[jj]; factor_lj = special_lj[sbmask(j)]; factor_coul = special_coul[sbmask(j)]; j &= NEIGHMASK; delx = xtmp - x[j].x; dely = ytmp - x[j].y; delz = ztmp - x[j].z; rsq = delx*delx + dely*dely + delz*delz; jtype = type[j]; if (rsq < cutsq[itype][jtype]) { r2inv = 1.0/rsq; if (rsq < cut_coulsq[itype][jtype]) { rinv = sqrt(r2inv); forcecoul = qqrd2e * qtmp*q[j]*rinv; forcecoul *= factor_coul; } else forcecoul = 0.0; if (rsq < cut_ljsq[itype][jtype]) { r6inv = r2inv*r2inv*r2inv; forcelj = r6inv * (lj1[itype][jtype]*r6inv - lj2[itype][jtype]); forcelj *= factor_lj; } else forcelj = 0.0; fpair = (forcecoul + forcelj) * r2inv; fxtmp += delx*fpair; fytmp += dely*fpair; fztmp += delz*fpair; if (NEWTON_PAIR || j < nlocal) { f[j].x -= delx*fpair; f[j].y -= dely*fpair; f[j].z -= delz*fpair; } if (EFLAG) { if (rsq < cut_coulsq[itype][jtype]) ecoul = factor_coul * qqrd2e * qtmp*q[j]*rinv; else ecoul = 0.0; if (rsq < cut_ljsq[itype][jtype]) { evdwl = r6inv*(lj3[itype][jtype]*r6inv-lj4[itype][jtype]) - offset[itype][jtype]; evdwl *= factor_lj; } else evdwl = 0.0; } if (EVFLAG) ev_tally_thr(this, i,j,nlocal,NEWTON_PAIR, evdwl,ecoul,fpair,delx,dely,delz,thr); } } f[i].x += fxtmp; f[i].y += fytmp; f[i].z += fztmp; } } /* ---------------------------------------------------------------------- */ double PairLJCutCoulCutOMP::memory_usage() { double bytes = memory_usage_thr(); bytes += PairLJCutCoulCut::memory_usage(); return bytes; }
milfeld/lammps
src/USER-OMP/pair_lj_cut_coul_cut_omp.cpp
C++
gpl-2.0
5,371
/** * cordova Web Intent plugin * Copyright (c) Boris Smus 2010 * */ var WebIntent = function() { }; WebIntent.prototype.ACTION_SEND = "android.intent.action.SEND"; WebIntent.prototype.ACTION_VIEW= "android.intent.action.VIEW"; WebIntent.prototype.EXTRA_TEXT = "android.intent.extra.TEXT"; WebIntent.prototype.EXTRA_SUBJECT = "android.intent.extra.SUBJECT"; WebIntent.prototype.EXTRA_STREAM = "android.intent.extra.STREAM"; WebIntent.prototype.EXTRA_EMAIL = "android.intent.extra.EMAIL"; WebIntent.prototype.startActivity = function(params, success, fail) { return cordova.exec(function(args) { success(args); }, function(args) { fail(args); }, 'WebIntent', 'startActivity', [params]); }; WebIntent.prototype.hasExtra = function(params, success, fail) { return cordova.exec(function(args) { success(args); }, function(args) { fail(args); }, 'WebIntent', 'hasExtra', [params]); }; WebIntent.prototype.saveImage = function(b64String, params, win, fail) { return cordova.exec(win, fail, "WebIntent", "saveImage", [b64String, params]); }; WebIntent.prototype.createAccount = function(params, win, fail) { return cordova.exec(win, fail, "WebIntent", "createAccount", [params]); }; WebIntent.prototype.getUri = function(success, fail) { return cordova.exec(function(args) { success(args); }, function(args) { fail(args); }, 'WebIntent', 'getUri', []); }; WebIntent.prototype.getExtra = function(params, success, fail) { return cordova.exec(function(args) { success(args); }, function(args) { fail(args); }, 'WebIntent', 'getExtra', [params]); }; WebIntent.prototype.getAccounts = function(params, success, fail) { return cordova.exec(function(args) { success(args); }, function(args) { fail(args); }, 'WebIntent', 'getAccounts', [params]); }; WebIntent.prototype.clearCookies = function(params, success, fail) { return cordova.exec(function(args) { success(args); }, function(args) { fail(args); }, 'WebIntent', 'clearCookies', [params]); }; WebIntent.prototype.onNewIntent = function(callback) { return cordova.exec(function(args) { callback(args); }, function(args) { }, 'WebIntent', 'onNewIntent', []); }; WebIntent.prototype.sendBroadcast = function(params, success, fail) { return cordova.exec(function(args) { success(args); }, function(args) { fail(args); }, 'WebIntent', 'sendBroadcast', [params]); }; cordova.addConstructor(function() { window.webintent = new WebIntent(); // backwards compatibility window.plugins = window.plugins || {}; window.plugins.webintent = window.webintent; });
ComunidadeExpresso/expressomobile-www
js/libs/cordova/webintent.js
JavaScript
gpl-2.0
3,059
<?php /** Themify Default Variables @var object */ global $themify; ?> <?php themify_layout_after(); //hook ?> </div> <!--/body --> <div id="footerwrap"> <?php themify_footer_before(); //hook ?> <div id="footer" class="pagewidth clearfix"> <?php themify_footer_start(); //hook ?> <?php get_template_part( 'includes/footer-widgets'); ?> <?php if (function_exists('wp_nav_menu')) { wp_nav_menu(array('theme_location' => 'footer-nav' , 'fallback_cb' => '' , 'container' => '' , 'menu_id' => 'footer-nav' , 'menu_class' => 'footer-nav')); } ?> <div class="footer-text"> <?php if(themify_get('setting-footer_text_left') != "") { echo themify_get('setting-footer_text_left'); } else { echo '&copy; <a href="'.home_url().'">'.get_bloginfo('name').'</a> '.date('Y') . '<br />'; } ?> <?php if(themify_get('setting-footer_text_right') != "") { echo themify_get('setting-footer_text_right'); } else { echo apply_filters('themify_footer_text_two', 'Powered by <a href="http://wordpress.org">WordPress</a> &bull; <a href="http://themify.me">Themify WordPress Themes</a>'); } ?> </div> <!--/footer-text --> <?php themify_footer_end(); //hook ?> </div> <!--/footer --> <?php themify_footer_after(); //hook ?> </div> <!--/footerwrap --> </div> <!--/pagewrap --> <?php /** * Stylesheets and Javascript files are enqueued in theme-functions.php */ ?> <!-- wp_footer --> <?php wp_footer(); ?> <?php themify_body_end(); //hook ?> </body> </html>
msoledade/scusp
wp-content/themes/itheme2/footer.php
PHP
gpl-2.0
1,578
/* * Copyright (C) 2009 University of Southern California and * Andrew D. Smith * * Authors: Andrew D. Smith * * 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 "FileIterator.hpp" #include "GenomicRegion.hpp" #include "MappedRead.hpp" #include <iostream> using std::istream; using std::vector; using std::string; /* THIS FUNCTION FILLS A BUFFER FOR GenomicRegion OBJECTS */ void fill_buffer(std::ifstream &in, const size_t buffer_start, vector<GenomicRegion> &buffer) { GenomicRegion tmp; size_t i = buffer_start; assert(buffer_start <= buffer.size()); for (; i != buffer.size() && !in.eof(); ++i) { in >> tmp; buffer[i].swap(tmp); in.peek(); } if (i < buffer.size()) buffer.erase(buffer.begin() + i, buffer.end()); } /* THIS FUNCTION FILLS A BUFFER FOR THE ACTUAL READS, REPRESENTED AS * STRINGS, AND MUST BE IN A FASTA FORMAT FILE */ void fill_buffer(std::ifstream &in, const size_t buffer_start, vector<string> &buffer) { string tmp; size_t i = buffer_start; for (; i != buffer.size() && !in.eof(); ++i) { // the read name... in >> tmp; // DANGER: assumes that the name of the read has no // spaces in it!! // the read itself: in >> buffer[i]; in.peek(); } if (i < buffer.size()) buffer.erase(buffer.begin() + i, buffer.end()); } /* THIS FUNCTION FILLS A BUFFER FOR THE ACTUAL READS, REPRESENTED AS * RECORDS IN A FASTQ FILE, INCLUDING THE QUALITY SCORES */ void fill_buffer(std::ifstream &in, const size_t buffer_start, vector<FASTQRecord> &buffer) { string tmp, read_seq, scores_seq; size_t i = buffer_start; for (; i != buffer.size() && !in.eof(); ++i) { // the read name... in >> tmp; // DANGER: assumes that the name of the read has no // spaces in it!! // the read itself: in >> read_seq; in >> tmp; in >> scores_seq; buffer[i] = std::make_pair(read_seq, scores_seq); in.peek(); } if (i < buffer.size()) buffer.erase(buffer.begin() + i, buffer.end()); } /* THIS FUNCTION FILLS A BUFFER FOR THE ACTUAL READS, REPRESENTED AS * RECORDS IN A FASTQ FILE, INCLUDING THE QUALITY SCORES */ void fill_buffer(std::ifstream &in, const size_t buffer_start, vector<MappedRead> &buffer) { size_t i = buffer_start; for (; i != buffer.size() && !in.eof(); ++i) { in >> buffer[i]; in.peek(); } if (i < buffer.size()) buffer.erase(buffer.begin() + i, buffer.end()); }
timydaley/dean_cylindrical_tranform
smithlab_cpp/FileIterator.cpp
C++
gpl-2.0
3,126
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ru" sourcelanguage="en"> <context> <name>U2::LocalWorkflow::CallVariantsPrompter</name> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="690"/> <source>unset</source> <translation>не указан</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="698"/> <source>For reference sequence from &lt;u&gt;%1&lt;/u&gt;,</source> <translation>Для референсной последовательности из &lt;u&gt;%1&lt;/u&gt;,</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="701"/> <source>with assembly data provided by &lt;u&gt;%1&lt;/u&gt;</source> <translation>с данными сборки, произведенными &lt;u&gt;%1&lt;/u&gt;</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="703"/> <source>%1 call variants %2.</source> <translation>%1 вызов вариантов %2.</translation> </message> </context> <context> <name>U2::LocalWorkflow::CallVariantsTask</name> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="52"/> <source>Call variants for %1</source> <translation>Вызов вариантов для %1</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="65"/> <source>reference</source> <translation>референс</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="67"/> <source>assembly</source> <translation>сборка</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="75"/> <source>The %1 file does not exist: %2</source> <translation>The %1 file does not exist: %2</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="88"/> <source>No assembly files</source> <translation>No assembly files</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="93"/> <source>No dbi storage</source> <translation>No dbi storage</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="97"/> <source>No sequence URL</source> <translation>No sequence URL</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="135"/> <source>No document loaded</source> <translation>No document loaded</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="139"/> <source>Incorrect variant track object in %1</source> <translation>Incorrect variant track object in %1</translation> </message> </context> <context> <name>U2::LocalWorkflow::CallVariantsWorker</name> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="135"/> <source>Empty input slot: %1</source> <translation>Входной слот пуст: %1</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="155"/> <source>Input sequences</source> <translation>Входные последовательности</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="156"/> <source>A nucleotide reference sequence.</source> <translation>Нуклеотидная референсная последовательность.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="163"/> <source>Input assembly</source> <translation>Входная сборка</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="164"/> <source>Position sorted alignment file</source> <translation>Сортированный файл выравнивания</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="171"/> <source>Output variations</source> <translation>Выходные вариации</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="172"/> <source>Output tracks with SNPs and short INDELs</source> <translation>Выходные треки с SNP и короткими INDEL</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="177"/> <source>Call Variants with SAMtools</source> <translation>Поиск вариабельных позиций с помощью SAMtools</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="178"/> <source>Calls SNPs and INDELS with SAMtools mpileup and bcftools.</source> <translation>этот элемент ищет однонуклеотидные вариации (SNP) и короткие вставки или выпадения (indels) при помощи SAMtools mpileup и bcftools.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="186"/> <source>Output variants file</source> <translation>Выходной файл</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="187"/> <source>The url to the file with the extracted variations.</source> <translation>Путь до файла с извлеченными вариациями.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="190"/> <source>Use reference from</source> <translation type="unfinished"></translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="191"/> <source>&lt;p&gt;Specify &quot;File&quot; to set a single reference sequence for all input NGS assemblies. The reference should be set in the &quot;Reference&quot; parameter.&lt;/p&gt;&lt;p&gt;Specify &quot;Input port&quot; to be able to set different references for difference NGS assemblies. The references should be input via the &quot;Input sequences&quot; port (e.g. use datasets in the &quot;Read Sequence&quot; element).&lt;/p&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="197"/> <source>Reference</source> <translation type="unfinished"></translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="198"/> <source>&lt;p&gt;Specify a file with the reference sequence.&lt;/p&gt;&lt;p&gt;The sequence will be used as reference for all datasets with NGS assemblies.&lt;/p&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="202"/> <source>Illumina-1.3+ encoding</source> <translation>Кодирование Illumina-1.3+</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="203"/> <source>Assume the quality is in the Illumina 1.3+ encoding (mpileup)(-6).</source> <translation>значения качества в кодировке Illumina 1.3+. Соответствует опции mpileup -6.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="206"/> <source>Count anomalous read pairs</source> <translation>Учитывать аномальные пары прочтений</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="207"/> <source>Do not skip anomalous read pairs in variant calling(mpileup)(-A).</source> <translation>не пропускать аномальные пары прочтений при поиске вариаций. Соответствует опции mpileup -A.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="210"/> <source>Disable BAQ computation</source> <translation>Отключить расчет BAQ</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="211"/> <source>Disable probabilistic realignment for the computation of base alignment quality (BAQ). BAQ is the Phred-scaled probability of a read base being misaligned. Applying this option greatly helps to reduce false SNPs caused by misalignments. (mpileup)(-B).</source> <translation>не выполнять выравнивание для расчета качества выравнивания каждого нуклеотида (base alignment quality, BAQ). BAQ - это приведенная к шкале Phred вероятность того, что данный нуклеотид выровнен неверно. Расчет BAQ сильно снижает вероятность ложного нахождения SNP из-за неверного выравнивания. Соответствует опции mpileup -B.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="216"/> <source>Mapping quality downgrading coefficient</source> <translation>Коэффициент снижения качества выравнивания</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="217"/> <source>Coefficient for downgrading mapping quality for reads containing excessive mismatches. Given a read with a phred-scaled mapping quality q of being generated from the mapped position, the new mapping quality is about sqrt((INT-q)/INT)*INT. A zero value disables this functionality; if enabled, the recommended value for BWA is 50 (mpileup)(-C).</source> <translation>применить коэффициент, отражающий снижение качества выравнивания прочтений, содержащих много замен. Если прочтение обладает качеством выравнивания q, новое значение качества выравнивания составит около sqrt[(INT-q)/INT]*INT. Значение 0 отключает эту опцию. Рекомендуемым значением для BWA является 50. Cjjndtncndetn jgwbb ьзшдугз -C INT.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="222"/> <source>Max number of reads per input BAM</source> <translation>Максимальное число прочтений для входного BAM-файла</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="223"/> <source>At a position, read maximally the number of reads per input BAM (mpileup)(-d).</source> <translation>максимальное число прочтений, которое следует прочитать для каждой позиции из входного BAM-файла. Соответствует опции mpileup -d.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="226"/> <source>Extended BAQ computation</source> <translation>Расширенный расчет BAQ</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="227"/> <source>Extended BAQ computation. This option helps sensitivity especially for MNPs, but may hurt specificity a little bit (mpileup)(-E).</source> <translation>Расширенные расчет BAQ. Эта опция увеличивает чувствительность, особенно в случае множественных замен (MNPs), однако может снижать специфичность.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="231"/> <source>BED or position list file</source> <translation>BED-файл или файл со списком позиций</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="232"/> <source>BED or position list file containing a list of regions or sites where pileup or BCF should be generated (mpileup)(-l).</source> <translation>BED-файл или файл со списком позиций или участков, для которых необходимо сгенерировать pileup или BCF. Соответствует опции mpileup -l.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="236"/> <source>Pileup region</source> <translation>Pileup для участка</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="237"/> <source>Only generate pileup in region STR (mpileup)(-r).</source> <translation>генерировать pileup только для участка STR. Соответствует опции mpileup -r STR.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="240"/> <source>Minimum mapping quality</source> <translation>Минимальное качество выравнивания</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="241"/> <source>Minimum mapping quality for an alignment to be used (mpileup)(-q).</source> <translation>использовать выравнивания только с таким или более хорошим качеством. Соответствует опции mpileup -q.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="244"/> <source>Minimum base quality</source> <translation>Минимальное качество нуклеотида</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="245"/> <source>Minimum base quality for a base to be considered (mpileup)(-Q).</source> <translation>учитывать нуклеотиды только с таким или более хорошим качеством. Соответствует опции mpileup -Q.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="248"/> <source>Gap extension error</source> <translation>Ошибка расширения пробела</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="249"/> <source>Phred-scaled gap extension sequencing error probability. Reducing INT leads to longer indels (mpileup)(-e).</source> <translation>Вероятность ошибки расширения пробела. (-e).</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="252"/> <source>Homopolymer errors coefficient</source> <translation>Коэффициент ошибок в гомополимерных участках</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="253"/> <source>Coefficient for modeling homopolymer errors. Given an l-long homopolymer run, the sequencing error of an indel of size s is modeled as INT*s/l (mpileup)(-h).</source> <translation>Коэффициент для моделирования ошибок в участках гомополимеров. Для гомополимера длиной l ошибка секвенирования для вставки/выпадения длиной s рассчитывается как INT*s/l. Соответствует опции mpileup -h.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="256"/> <source>No INDELs</source> <translation>Не искать INDELs</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="257"/> <source>Do not perform INDEL calling (mpileup)(-I).</source> <translation>не выполнять поиск вставок/выпадений. Соответствует опции mpileup -l.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="260"/> <source>Max INDEL depth</source> <translation>Максимальное покрытие для поиска INDELs</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="261"/> <source>Skip INDEL calling if the average per-sample depth is above INT (mpileup)(-L).</source> <translation>не выполнять поиск вставок/выпадений если среднее покрытие образца превышает INT. Соответствует опции mpileup -L INT.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="264"/> <source>Gap open error</source> <translation>Ошибка открытия пробела</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="265"/> <source>Phred-scaled gap open sequencing error probability. Reducing INT leads to more indel calls (mpileup)(-o).</source> <translation>вероятность ошибки секвенирования, приводящей к открытию пробела, в шкале Phred. Снижение значения INT приводит к увеличению числа найденных вставок/выпадений. Соответствует опции mpileup -o INT.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="268"/> <source>List of platforms for indels</source> <translation>Список платформ для поиска вставок/выпадений</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="269"/> <source>Comma dilimited list of platforms (determined by @RG-PL) from which indel candidates are obtained.It is recommended to collect indel candidates from sequencing technologies that have low indel error rate such as ILLUMINA (mpileup)(-P).</source> <translation>список через запятую названий платформ в формате @RG-PL, для которых необходимо проводить поиск возможных вставок/выпадений. Этот анализ рекомендуется проводить для данных платформ секвенирования, обладающих низким уровнем ошибок типа вставка/выпадение (например, ILLUMINA). Соответствует опции mpileup -P.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="274"/> <source>Retain all possible alternate</source> <translation>Сохранять все альтернативные варианты</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="275"/> <source>Retain all possible alternate alleles at variant sites. By default, the view command discards unlikely alleles (bcf view)(-A).</source> <translation>сохранять все аллельные варианты в вариабельных позициях. По умолчанию команда view отбрасывает аллели с низкой вероятностью. Соответствует опции bcftools view -A.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="278"/> <source>Indicate PL</source> <translation>Указать PL</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="279"/> <source>Indicate PL is generated by r921 or before (ordering is different) (bcf view)(-F).</source> <translation>указать, получены ли данные с помощью r921 или более ранней версии платформы (отличаются сортировкой). Соответствует опции bcftools view -F.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="282"/> <source>No genotype information</source> <translation>Не отображать информацию о генотипе</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="283"/> <source>Suppress all individual genotype information (bcf view)(-G).</source> <translation>отключить отображение всей информации о генотипе индивидуума. Соответствует опции bcftools view -G.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="286"/> <source>A/C/G/T only</source> <translation>Только A/C/G/T</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="287"/> <source>Skip sites where the REF field is not A/C/G/T (bcf view)(-N).</source> <translation>отбрасывать сайты, где поле REF содержит значение не из списка A/C/G/T. Соответствует опции bcftools view -N.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="290"/> <source>List of sites</source> <translation>Список позиций</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="291"/> <source>List of sites at which information are outputted (bcf view)(-l).</source> <translation>список позиций, для которых необходимо вывести информацию. Соответствует опции bcftools view -l STR.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="294"/> <source>QCALL likelihood</source> <translation>Вероятность в QCALL</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="295"/> <source>Output the QCALL likelihood format (bcf view)(-Q).</source> <translation>выводить значения вероятности в формате QCALL. Соответствует опции bcftools view -Q.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="298"/> <source>List of samples</source> <translation>Список образцов</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="299"/> <source>List of samples to use. The first column in the input gives the sample names and the second gives the ploidy, which can only be 1 or 2. When the 2nd column is absent, the sample ploidy is assumed to be 2. In the output, the ordering of samples will be identical to the one in FILE (bcf view)(-s).</source> <translation>список образцов, которые необходимо использовать. В первом столбце необходимо перечислить названия образцов, во втором - плоидность. Если второй столбец отсутствует, плоидность считается равной 2. Порядок образцов в выходном файле будет соответствовать порядку во входном файле. Соответствует опции bcftools view -s.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="305"/> <source>Min samples fraction</source> <translation>Минимальная доля образцов</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="306"/> <source>skip loci where the fraction of samples covered by reads is below FLOAT (bcf view)(-d).</source> <translation>пропустить участок если доля образцов, у которых этот участок покрыт прочтениями, ниже указанного значения. Соответствует опции bcftools view -d FLOAT.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="309"/> <source>Per-sample genotypes</source> <translation>Генотип для каждого образца</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="310"/> <source>Call per-sample genotypes at variant sites (bcf view)(-g).</source> <translation>отобразить генотип для каждого образца и каждой вариабельной позиции. Соответствует опции bcftools view -g.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="313"/> <source>INDEL-to-SNP Ratio</source> <translation>Соотношение INDEL-to-SNP</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="314"/> <source>Ratio of INDEL-to-SNP mutation rate (bcf view)(-i).</source> <translation>указать отношение скоростей появления вставок/выпадений и замен. Соответствует опции bcftools view -i FLOAT.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="317"/> <source>Max P(ref|D)</source> <translation>Максимальное P(ref|D)</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="318"/> <source>A site is considered to be a variant if P(ref|D)&lt;FLOAT (bcf view)(-p).</source> <translation>считать позицию вариабельной, если вероятность совпадения с референсом (P(ref|D)) меньше указанного значения. Соответствует опции bcftools view -p FLOAT.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="321"/> <source>Prior allele frequency spectrum</source> <translation>Априорное распределение частот аллелей</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="322"/> <source>If STR can be full, cond2, flat or the file consisting of error output from a previous variant calling run (bcf view)(-P).</source> <translation>значение из следующего списка: full, cond2, flat - или файл, содержащий список ошибок в предыдущем запуске. Соответствует опции bcftools view -P STR.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="325"/> <source>Mutation rate</source> <translation>Скорость накоплений мутаций</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="326"/> <source>Scaled mutation rate for variant calling (bcf view)(-t).</source> <translation>нормализованная скорость накопления мутаций для поиска вариаций. Соответствует опции bcftools view -t.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="329"/> <source>Pair/trio calling</source> <translation>Поиск вариаций в парных образцах или трио</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="330"/> <source>Enable pair/trio calling. For trio calling, option -s is usually needed to be applied to configure the trio members and their ordering. In the file supplied to the option -s, the first sample must be the child, the second the father and the third the mother. The valid values of STR are &apos;‘pair’&apos;, &apos;‘trioauto’&apos;, &apos;‘trioxd’&apos; and &apos;‘trioxs’&apos;, where &apos;‘pair’&apos; calls differences between two input samples, and &apos;‘trioxd’&apos; (&apos;‘trioxs’&apos;)specifies that the input is from the X chromosome non-PAR regions and the child is a female (male) (bcf view)(-T).</source> <translation>включить поиск вариаций в парах или трио образцов. Для работы с трио необходимо также применить опцию -s для настройки входящих в трио образцов и порядка их сортировки. В файле, переданном опции -s, первому образцу должны соответствовать данные для ребенка, второму - для отца, третьему - для матери. Корректными значениями этого параметра являются &apos;‘pair’&apos;, &apos;‘trioauto’&apos;, &apos;‘trioxd’&apos; и &apos;‘trioxs’&apos;, где &apos;‘pair’&apos; позволяет найти различия между двумя образцами, а &apos;‘trioxd’&apos; или &apos;‘trioxs’&apos; указывает на то, что на вход поданы данные для X - хромосомы за вычетом псевдоаутосомного участка, а ребенок женского (мужского) пола. Соответствует опции bcftools view -T.</translation> </message> <message> <source>Enable pair/trio calling. For trio calling, option -s is usually needed to be applied to configure the trio members and their ordering. In the file supplied to the option -s, the first sample must be the child, the second the father and the third the mother. The valid values of STR are &apos;‘pair’&apos;, &apos;‘trioauto’&apos;, &apos;‘trioxd’&apos; and &apos;‘trioxs’&apos;, where &apos;‘pair’&apos; calls differences between two input samples, and &apos;‘trioxd’&apos; (&apos;‘trioxs’&apos;)specifies that the input is from the X chromosome non-PAR regions and the child is a female (male) (bcf view)(-T).</source> <translation type="vanished">Позволен двойной/тройной вызов (-T).</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="337"/> <source>N group-1 samples</source> <translation>Число образцов в группе 1</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="338"/> <source>Number of group-1 samples. This option is used for dividing the samples into two groups for contrast SNP calling or association test. When this option is in use, the followingVCF INFO will be outputted: PC2, PCHI2 and QCHI2 (bcf view)(-1).</source> <translation>число образцов в первой группе. Эта опция используется для разделения образцов на две группы для поиска различающихся SNP или проведения анализа ассоциаций. Если эта опция включена, в выходном файле будут добавлены следующие значения VCF INFO: PC2, PCHI2 и QCHI2. Соответствует опции bcftools view -1.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="343"/> <source>N permutations</source> <translation>Число перестановок</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="344"/> <source>Number of permutations for association test (effective only with -1) (bcf view)(-U).</source> <translation>число перестановок для анализа ассоциаций. Работает только в том случае, если включена опция -1. Соответствует опции bcftools view -U.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="347"/> <source>Max P(chi^2)</source> <translation>Максимальное P(chi^2)</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="348"/> <source>Only perform permutations for P(chi^2)&lt;FLOAT (N permutations) (bcf view)(-X).</source> <translation>выполнять перестановки только для меньших значений P(chi^2), чем указанное значение. Соответствует опции bcftools view -X FLOAT.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="352"/> <source>Minimum RMS quality</source> <translation>Минимальное качество RMS</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="353"/> <source>Minimum RMS mapping quality for SNPs (varFilter) (-Q).</source> <translation>минимальное качество выравнивания RMS для SNP. Соответствует опции varFilter -Q.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="355"/> <source>Minimum read depth</source> <translation>Минимальная глубина покрытия</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="356"/> <source>Minimum read depth (varFilter) (-d).</source> <translation>Минимальная глубина покрытия для прочтения. Соответствует опции varFilter -d.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="358"/> <source>Maximum read depth</source> <translation>Максимальная глубина покрытия</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="359"/> <source>Maximum read depth (varFilter) (-D).</source> <translation>Максимальная глубина покрытия для прочтения. Соответствует опции varFilter -d.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="361"/> <source>Alternate bases</source> <translation>Альтернативные нуклеотиды</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="362"/> <source>Minimum number of alternate bases (varFilter) (-a).</source> <translation>минимальное число прочтений, содержащих в этой позиции не соответствующий референсному вариант. Соответствует опции varFilter -a.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="364"/> <source>Gap size</source> <translation>Длина пробела</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="365"/> <source>SNP within INT bp around a gap to be filtered (varFilter) (-w).</source> <translation>длина участка, включающего вставку/выпадение, на котором следует отбросить SNP. Соответствует опции varFilter -w.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="367"/> <source>Window size</source> <translation>Размер окна</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="368"/> <source>Window size for filtering adjacent gaps (varFilter) (-W).</source> <translation>Размер окна для фильтрации смежных пробелов. Соответствует опции varFilter -W.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="370"/> <source>Strand bias</source> <translation>Смещение по разным цепям</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="371"/> <source>Minimum P-value for strand bias (given PV4) (varFilter) (-1).</source> <translation>минимальное P-значение для добавления информации о неравномерном распределении вариаций по двум цепям. Соответствует опции varFilter -1.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="373"/> <source>BaseQ bias</source> <translation>Смещение BaseQ</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="374"/> <source>Minimum P-value for baseQ bias (varFilter) (-2).</source> <translation>минимальное P-значение для добавления информации о неравномерном распределении качества нуклеотида (baseQ). Соответствует опции varFilter -2.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="376"/> <source>MapQ bias</source> <translation>Смещение MapQ</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="377"/> <source>Minimum P-value for mapQ bias (varFilter) (-3).</source> <translation>минимальное P-значение для добавления информации о неравномерном распределении качества выравнивания (mapQ). Соответствует опции varFilter -3.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="379"/> <source>End distance bias</source> <translation>Смещение расстояния до конца прочтения</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="380"/> <source>Minimum P-value for end distance bias (varFilter) (-4).</source> <translation>минимальное P-значение для добавления информации о неравномерном распределении расстояния от вариабельного сайта до конца прочтения. Соответствует опции varFilter -4.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="382"/> <source>HWE</source> <translation>HWE</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="383"/> <source>Minimum P-value for HWE (plus F&lt;0) (varFilter) (-e).</source> <translation>минимальное P-значение для добавления информации о распределении Харди-Вайнберга (HWE). Соответствует опции varFilter -e.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="385"/> <source>Log filtered</source> <translation>Лог фильтрации</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="386"/> <source>Print filtered variants into the log (varFilter) (-p).</source> <translation>записывать отфильтрованные вариации в лог-файл. Соответствует опции varFilter -p.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="658"/> <source>Input port</source> <translation type="unfinished"></translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="659"/> <source>File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="842"/> <source>Assembly URL slot is empty. Please, specify the URL slot</source> <translation>Assembly URL slot is empty. Please, specify the URL slot</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="867"/> <source>Ref sequence URL slot is empty. Please, specify the URL slot</source> <translation>Ref sequence URL slot is empty. Please, specify the URL slot</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="946"/> <source>Not enough references</source> <translation>Not enough references</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="951"/> <source>The dataset slot is not binded, only the first reference sequence against all assemblies was processed.</source> <translation>The dataset slot is not binded, only the first reference sequence against all assemblies was processed.</translation> </message> <message> <location filename="../src/SamtoolMpileupWorker.cpp" line="954"/> <source>Not enough assemblies</source> <translation>Not enough assemblies</translation> </message> </context> <context> <name>U2::LocalWorkflow::SamtoolsMpileupTask</name> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="161"/> <source>Samtool mpileup for %1 </source> <translation>Samtool mpileup для %1 </translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="168"/> <source>No reference sequence URL to do pileup</source> <translation>No reference sequence URL to do pileup</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="173"/> <source>No assembly URL to do pileup</source> <translation>No assembly URL to do pileup</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="179"/> <source>There is an assembly with an empty path</source> <translation>There is an assembly with an empty path</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="188"/> <source>Can not create the folder: </source> <translation>Can not create the folder: </translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="243"/> <source>Can not run %1 tool</source> <translation>Can not run %1 tool</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="249"/> <source>%1 tool exited with code %2</source> <translation>%1 tool exited with code %2</translation> </message> <message> <location filename="../src/AssemblySamtoolsMpileup.cpp" line="251"/> <source>Tool %1 finished successfully</source> <translation>Tool %1 finished successfully</translation> </message> </context> <context> <name>U2::SamtoolsPlugin</name> <message> <location filename="../src/SamtoolsPlugin.cpp" line="36"/> <source>Samtools plugin</source> <translation>Samtools plugin</translation> </message> <message> <location filename="../src/SamtoolsPlugin.cpp" line="36"/> <source>Samtools plugin for NGS data analysis</source> <translation>Samtools плагин для анализа данных NGS</translation> </message> </context> </TS>
ggrekhov/ugene
src/plugins_3rdparty/variants/transl/russian.ts
TypeScript
gpl-2.0
46,704
<?php if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly // lib include 'lib/AB_BookingConfiguration.php'; include 'lib/AB_Controller.php'; include 'lib/AB_Entity.php'; include 'lib/AB_Query.php'; include 'lib/AB_Form.php'; include 'lib/AB_NotificationCodes.php'; include 'lib/AB_NotificationSender.php'; include 'lib/AB_SMS.php'; include 'lib/AB_Validator.php'; // lib/curl include 'lib/curl/curl.php'; include 'lib/curl/curl_response.php'; // lib/utils include 'lib/utils/AB_Utils.php'; include 'lib/utils/AB_Instance.php'; include 'lib/utils/AB_DateTimeUtils.php'; // lib/entities include 'lib/entities/AB_Appointment.php'; include 'lib/entities/AB_Category.php'; include 'lib/entities/AB_Coupon.php'; include 'lib/entities/AB_Customer.php'; include 'lib/entities/AB_CustomerAppointment.php'; include 'lib/entities/AB_Holiday.php'; include 'lib/entities/AB_SentNotification.php'; include 'lib/entities/AB_Notification.php'; include 'lib/entities/AB_Payment.php'; include 'lib/entities/AB_ScheduleItemBreak.php'; include 'lib/entities/AB_Service.php'; include 'lib/entities/AB_Staff.php'; include 'lib/entities/AB_StaffScheduleItem.php'; include 'lib/entities/AB_StaffService.php'; // backend/modules include 'backend/modules/appearance/AB_AppearanceController.php'; include 'backend/modules/calendar/AB_CalendarController.php'; include 'backend/modules/calendar/forms/AB_AppointmentForm.php'; include 'backend/modules/coupons/AB_CouponsController.php'; include 'backend/modules/coupons/forms/AB_CouponForm.php'; include 'backend/modules/custom_fields/AB_CustomFieldsController.php'; include 'backend/modules/customer/AB_CustomerController.php'; include 'backend/modules/customer/forms/AB_CustomerForm.php'; include 'backend/modules/notifications/AB_NotificationsController.php'; include 'backend/modules/notifications/forms/AB_NotificationsForm.php'; include 'backend/modules/payment/AB_PaymentController.php'; include 'backend/modules/service/AB_ServiceController.php'; include 'backend/modules/service/forms/AB_CategoryForm.php'; include 'backend/modules/service/forms/AB_ServiceForm.php'; include 'backend/modules/settings/AB_SettingsController.php'; include 'backend/modules/settings/forms/AB_CompanyForm.php'; include 'backend/modules/settings/forms/AB_PaymentsForm.php'; include 'backend/modules/settings/forms/AB_BusinessHoursForm.php'; include 'backend/modules/sms/AB_SmsController.php'; include 'backend/modules/staff/AB_StaffController.php'; include 'backend/modules/staff/forms/AB_StaffMemberForm.php'; include 'backend/modules/staff/forms/AB_StaffMemberEditForm.php'; include 'backend/modules/staff/forms/AB_StaffMemberNewForm.php'; include 'backend/modules/staff/forms/AB_StaffScheduleForm.php'; include 'backend/modules/staff/forms/AB_StaffScheduleItemBreakForm.php'; include 'backend/modules/staff/forms/AB_StaffServicesForm.php'; include 'backend/modules/staff/forms/widget/AB_TimeChoiceWidget.php'; include 'backend/modules/tinymce/AB_TinyMCE_Plugin.php'; include 'backend/modules/appointments/AB_AppointmentsController.php'; // frontend/modules include 'frontend/modules/authorize.net/AB_AuthorizeNetController.php'; include 'frontend/modules/booking/AB_BookingController.php'; include 'frontend/modules/booking/lib/AB_UserBookingData.php'; include 'frontend/modules/booking/lib/AB_AvailableTime.php'; include 'frontend/modules/customer_profile/AB_CustomerProfileController.php'; include 'frontend/modules/paypal/AB_PayPalController.php'; include 'frontend/modules/stripe/AB_StripeController.php'; include 'frontend/modules/woocommerce/AB_WooCommerceController.php'; include 'backend/AB_Backend.php'; include 'frontend/AB_Frontend.php'; include 'installer.php'; include 'updates.php';
patrickcurl/monks
wp-content/plugins/appointment-booking/includes.php
PHP
gpl-2.0
3,721
/* Copyright (c) 2004-2006, The Dojo Foundation All Rights Reserved. Licensed under the Academic Free License version 2.1 or above OR the modified BSD license. For more information on Dojo licensing, see: http://dojotoolkit.org/community/licensing.shtml */ dojo.provide("dojo.data.old.Item"); dojo.require("dojo.data.old.Observable"); dojo.require("dojo.data.old.Value"); dojo.require("dojo.lang.common"); dojo.require("dojo.lang.assert"); dojo.data.old.Item = function (dataProvider) { dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional:true}); dojo.data.old.Observable.call(this); this._dataProvider = dataProvider; this._dictionaryOfAttributeValues = {}; }; dojo.inherits(dojo.data.old.Item, dojo.data.old.Observable); dojo.data.old.Item.compare = function (itemOne, itemTwo) { dojo.lang.assertType(itemOne, dojo.data.old.Item); if (!dojo.lang.isOfType(itemTwo, dojo.data.old.Item)) { return -1; } var nameOne = itemOne.getName(); var nameTwo = itemTwo.getName(); if (nameOne == nameTwo) { var attributeArrayOne = itemOne.getAttributes(); var attributeArrayTwo = itemTwo.getAttributes(); if (attributeArrayOne.length != attributeArrayTwo.length) { if (attributeArrayOne.length > attributeArrayTwo.length) { return 1; } else { return -1; } } for (var i in attributeArrayOne) { var attribute = attributeArrayOne[i]; var arrayOfValuesOne = itemOne.getValues(attribute); var arrayOfValuesTwo = itemTwo.getValues(attribute); dojo.lang.assert(arrayOfValuesOne && (arrayOfValuesOne.length > 0)); if (!arrayOfValuesTwo) { return 1; } if (arrayOfValuesOne.length != arrayOfValuesTwo.length) { if (arrayOfValuesOne.length > arrayOfValuesTwo.length) { return 1; } else { return -1; } } for (var j in arrayOfValuesOne) { var value = arrayOfValuesOne[j]; if (!itemTwo.hasAttributeValue(value)) { return 1; } } return 0; } } else { if (nameOne > nameTwo) { return 1; } else { return -1; } } }; dojo.data.old.Item.prototype.toString = function () { var arrayOfStrings = []; var attributes = this.getAttributes(); for (var i in attributes) { var attribute = attributes[i]; var arrayOfValues = this.getValues(attribute); var valueString; if (arrayOfValues.length == 1) { valueString = arrayOfValues[0]; } else { valueString = "["; valueString += arrayOfValues.join(", "); valueString += "]"; } arrayOfStrings.push(" " + attribute + ": " + valueString); } var returnString = "{ "; returnString += arrayOfStrings.join(",\n"); returnString += " }"; return returnString; }; dojo.data.old.Item.prototype.compare = function (otherItem) { return dojo.data.old.Item.compare(this, otherItem); }; dojo.data.old.Item.prototype.isEqual = function (otherItem) { return (this.compare(otherItem) == 0); }; dojo.data.old.Item.prototype.getName = function () { return this.get("name"); }; dojo.data.old.Item.prototype.get = function (attributeId) { var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId]; if (dojo.lang.isUndefined(literalOrValueOrArray)) { return null; } if (literalOrValueOrArray instanceof dojo.data.old.Value) { return literalOrValueOrArray.getValue(); } if (dojo.lang.isArray(literalOrValueOrArray)) { var dojoDataValue = literalOrValueOrArray[0]; return dojoDataValue.getValue(); } return literalOrValueOrArray; }; dojo.data.old.Item.prototype.getValue = function (attributeId) { var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId]; if (dojo.lang.isUndefined(literalOrValueOrArray)) { return null; } if (literalOrValueOrArray instanceof dojo.data.old.Value) { return literalOrValueOrArray; } if (dojo.lang.isArray(literalOrValueOrArray)) { var dojoDataValue = literalOrValueOrArray[0]; return dojoDataValue; } var literal = literalOrValueOrArray; dojoDataValue = new dojo.data.old.Value(literal); this._dictionaryOfAttributeValues[attributeId] = dojoDataValue; return dojoDataValue; }; dojo.data.old.Item.prototype.getValues = function (attributeId) { var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId]; if (dojo.lang.isUndefined(literalOrValueOrArray)) { return null; } if (literalOrValueOrArray instanceof dojo.data.old.Value) { var array = [literalOrValueOrArray]; this._dictionaryOfAttributeValues[attributeId] = array; return array; } if (dojo.lang.isArray(literalOrValueOrArray)) { return literalOrValueOrArray; } var literal = literalOrValueOrArray; var dojoDataValue = new dojo.data.old.Value(literal); array = [dojoDataValue]; this._dictionaryOfAttributeValues[attributeId] = array; return array; }; dojo.data.old.Item.prototype.load = function (attributeId, value) { this._dataProvider.registerAttribute(attributeId); var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId]; if (dojo.lang.isUndefined(literalOrValueOrArray)) { this._dictionaryOfAttributeValues[attributeId] = value; return; } if (!(value instanceof dojo.data.old.Value)) { value = new dojo.data.old.Value(value); } if (literalOrValueOrArray instanceof dojo.data.old.Value) { var array = [literalOrValueOrArray, value]; this._dictionaryOfAttributeValues[attributeId] = array; return; } if (dojo.lang.isArray(literalOrValueOrArray)) { literalOrValueOrArray.push(value); return; } var literal = literalOrValueOrArray; var dojoDataValue = new dojo.data.old.Value(literal); array = [dojoDataValue, value]; this._dictionaryOfAttributeValues[attributeId] = array; }; dojo.data.old.Item.prototype.set = function (attributeId, value) { this._dataProvider.registerAttribute(attributeId); this._dictionaryOfAttributeValues[attributeId] = value; this._dataProvider.noteChange(this, attributeId, value); }; dojo.data.old.Item.prototype.setValue = function (attributeId, value) { this.set(attributeId, value); }; dojo.data.old.Item.prototype.addValue = function (attributeId, value) { this.load(attributeId, value); this._dataProvider.noteChange(this, attributeId, value); }; dojo.data.old.Item.prototype.setValues = function (attributeId, arrayOfValues) { dojo.lang.assertType(arrayOfValues, Array); this._dataProvider.registerAttribute(attributeId); var finalArray = []; this._dictionaryOfAttributeValues[attributeId] = finalArray; for (var i in arrayOfValues) { var value = arrayOfValues[i]; if (!(value instanceof dojo.data.old.Value)) { value = new dojo.data.old.Value(value); } finalArray.push(value); this._dataProvider.noteChange(this, attributeId, value); } }; dojo.data.old.Item.prototype.getAttributes = function () { var arrayOfAttributes = []; for (var key in this._dictionaryOfAttributeValues) { arrayOfAttributes.push(this._dataProvider.getAttribute(key)); } return arrayOfAttributes; }; dojo.data.old.Item.prototype.hasAttribute = function (attributeId) { return (attributeId in this._dictionaryOfAttributeValues); }; dojo.data.old.Item.prototype.hasAttributeValue = function (attributeId, value) { var arrayOfValues = this.getValues(attributeId); for (var i in arrayOfValues) { var candidateValue = arrayOfValues[i]; if (candidateValue.isEqual(value)) { return true; } } return false; };
freemed/freemed
ui/dojo/htdocs/dojo/src/data/old/Item.js
JavaScript
gpl-2.0
7,279
import os import numpy as np import matplotlib.pyplot as plt from matplotlib import cm, colors initDir = '../init/' nlat = 31 nlon = 30 # Dimensions L = 1.5e7 c0 = 2 timeDim = L / c0 / (60. * 60. * 24) H = 200 tau_0 = 1.0922666667e-2 delta_T = 1. sampFreq = 0.35 / 0.06 * 12 # (in year^-1) # Case definition muRng = np.array([2.1, 2.5, 2.7, 2.75, 2.8, 2.85, 2.9, 2.95, 3., 3.1, 3.3, 3.7]) #amu0Rng = np.arange(0.1, 0.51, 0.1) #amu0Rng = np.array([0.2]) amu0Rng = np.array([0.75, 1.]) #epsRng = np.arange(0., 0.11, 0.05) epsRng = np.array([0.]) sNoise = 'without noise' # spinup = int(sampFreq * 10) # timeWin = np.array([0, -1]) spinup = 0 timeWin = np.array([0, int(sampFreq * 1000)]) neof = 1 prefix = 'zc' simType = '_%deof_seasonal' % (neof,) indicesDir = '../observables/' field_h = (1, 'Thermocline depth', r'$h$', 'm', H, r'$h^2$') field_T = (2, 'SST', 'T', r'$^\circ C$', delta_T, r'$(^\circ C)^2$') #field_u_A = (3, 'Wind stress due to coupling', r'$u_A$', 'm/s', tau_0) #field_taux = (4, 'External wind-stress', 'taux', 'm/s', tau_0) # Indices definition # Nino3 #nino3Def = ('NINO3', 'nino3') nino3Def = ('Eastern', 'nino3') # Nino4 #nino4Def = ('NINO4', 'nino4') nino4Def = ('Western', 'nino4') # Field and index choice fieldDef = field_T indexDef = nino3Def #fieldDef = field_h #indexDef = nino4Def #fieldDef = field_u_A #indexDef = nino4Def #fieldDef = field_taux #indexDef = nino4Def fs_default = 'x-large' fs_latex = 'xx-large' fs_xlabel = fs_default fs_ylabel = fs_default fs_xticklabels = fs_default fs_yticklabels = fs_default fs_legend_title = fs_default fs_legend_labels = fs_default fs_cbar_label = fs_default # figFormat = 'eps' figFormat = 'png' dpi = 300 for eps in epsRng: for amu0 in amu0Rng: for mu in muRng: postfix = '_mu%04d_amu0%04d_eps%04d' \ % (np.round(mu * 1000, 1), np.round(amu0 * 1000, 1), np.round(eps * 1000, 1)) resDir = '%s%s%s/' % (prefix, simType, postfix) indicesPath = '%s/%s' % (indicesDir, resDir) pltDir = resDir os.system('mkdir %s %s 2> /dev/null' % (pltDir, indicesPath)) # Read dataset indexData = np.loadtxt('%s/%s.txt' % (indicesPath, indexDef[1])) timeND = indexData[:, 0] timeFull = timeND * timeDim / 365 indexFull = indexData[:, fieldDef[0]] * fieldDef[4] # Remove spinup index = indexFull[spinup:] time = timeFull[spinup:] nt = time.shape[0] # Plot time-series linewidth = 2 fig = plt.figure() ax = fig.add_subplot(111) ax.plot(time[timeWin[0]:timeWin[1]], index[timeWin[0]:timeWin[1]], linewidth=linewidth) # plt.title('Time-series of %s averaged over %s\nfor mu = %.4f and eps = %.4f' % (fieldDef[1], indexDef[0], mu, eps)) ax.set_xlabel('years', fontsize=fs_latex) ax.set_ylabel('%s %s (%s)' \ % (indexDef[0], fieldDef[1], fieldDef[3]), fontsize=fs_latex) # ax.set_xlim(0, 250) # ax.set_ylim(29.70, 30.) plt.setp(ax.get_xticklabels(), fontsize=fs_xticklabels) plt.setp(ax.get_yticklabels(), fontsize=fs_yticklabels) fig.savefig('%s/%s%s%s.png' % (pltDir, indexDef[1], fieldDef[2], postfix), bbox_inches='tight') # Get periodogram of zonal wind stress averaged over index nRAVG = 1 window = np.hamming(nt) # Get nearest larger power of 2 if np.log2(nt) != int(np.log2(nt)): nfft = 2**(int(np.log2(nt)) + 1) else: nfft = nt # Get frequencies and shift zero frequency to center freq = np.fft.fftfreq(nfft, d=1./sampFreq) freq = np.fft.fftshift(freq) ts = index - index.mean(0) # Apply window tsWindowed = ts * window # Fourier transform and shift zero frequency to center fts = np.fft.fft(tsWindowed, nfft, 0) fts = np.fft.fftshift(fts) # Get periodogram perio = np.abs(fts / nt)**2 # Apply running average perioRAVG = perio.copy() for iavg in np.arange(nRAVG/2, nfft-nRAVG/2): perioRAVG[iavg] = perio[iavg-nRAVG/2:iavg+nRAVG/2 + 1].mean()\ / nRAVG # Plot fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(freq, np.log10(perioRAVG), '-k') # ax.set_xscale('log') # ax.set_yscale('log') ax.set_xlim(0, 4) #ax.set_ylim(0, vmax) ax.set_xlabel(r'years$^{-1}$', fontsize=fs_latex) ax.set_ylabel(fieldDef[5], fontsize=fs_latex) plt.setp(ax.get_xticklabels(), fontsize=fs_xticklabels) plt.setp(ax.get_yticklabels(), fontsize=fs_yticklabels) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.text(xlim[0] + 0.2 * (xlim[1] - xlim[0]), ylim[0] + 0.1 * (ylim[1] - ylim[0]), r'$\mu = %.3f$ %s' % (mu, sNoise), fontsize=32) # plt.title('Periodogram of %s averaged over %s\nfor mu = %.1f and eps = %.2f' % (fieldDef[1], indexDef[0], mu, eps)) fig.savefig('%s/%s%sPerio%s.%s' \ % (pltDir, indexDef[1], fieldDef[2], postfix, figFormat), bbox_inches='tight', dpi=dpi)
atantet/transferCZ
plot/plot_index_loop_seasonal.py
Python
gpl-2.0
5,743
<?php /** * @file * Addon file to display help block on Admin UI. */ if(!defined('e107_INIT')) { exit; } // [PLUGINS]/voice/languages/[LANGUAGE]/[LANGUAGE]_admin.php e107::lan('squadxml', true, true); /** * Class voice_help. */ class voice_help { private $action; public function __construct() { $this->action = varset($_GET['action'], ''); $this->renderHelpBlock(); } public function renderHelpBlock() { switch($this->action) { default: $block = $this->getHelpBlockListPage(); break; } if(!empty($block)) { e107::getRender()->tablerender($block['title'], $block['body']); } } public function getHelpBlockListPage() { e107::js('footer', 'https://buttons.github.io/buttons.js'); $content = ''; $issue = array( 'href="https://github.com/LaocheXe/SquadXML-PHP/issues"', 'class="github-button"', 'data-icon="octicon-issue-opened"', 'data-style="mega"', 'data-count-api="/repos/LaocheXe/SquadXML-PHP#open_issues_count"', 'data-count-aria-label="# issues on GitHub"', 'aria-label="Issue LaocheXe/SquadXML-PHP on GitHub"', ); $star = array( 'href="https://github.com/LaocheXe/SquadXML-PHP"', 'class="github-button"', 'data-icon="octicon-star"', 'data-style="mega"', 'data-count-href="/LaocheXe/SquadXML-PHP/stargazers"', 'data-count-api="/repos/LaocheXe/SquadXML-PHP#stargazers_count"', 'data-count-aria-label="# stargazers on GitHub"', 'aria-label="Star LaocheXe/SquadXML-PHP on GitHub"', ); $content .= '<p class="text-center">' . LAN_SQDXML_ADMIN_HELP_03 . '</p>'; $content .= '<p class="text-center">'; $content .= '<a ' . implode(" ", $issue) . '>' . LAN_SQDXML_ADMIN_HELP_04 . '</a>'; $content .= '</p>'; $content .= '<p class="text-center">' . LAN_SQDXML_ADMIN_HELP_02 . '</p>'; $content .= '<p class="text-center">'; $content .= '<a ' . implode(" ", $star) . '>' . LAN_SQDXML_ADMIN_HELP_05 . '</a>'; $content .= '</p>'; $beerImage = '<img src="https://beerpay.io/LaocheXe/SquadXML-PHP/badge.svg" />'; $beerWishImage = '<img src="https://beerpay.io/LaocheXe/SquadXML-PHP/make-wish.svg" />'; $content .= '<p class="text-center">' . LAN_SQDXML_ADMIN_HELP_06 . '</p>'; $content .= '<p class="text-center">'; $content .= '<a href="https://beerpay.io/LaocheXe/SquadXML-PHP">' . $beerImage . '</a>'; $content .= '</p>'; $content .= '<p class="text-center">'; $content .= '<a href="https://beerpay.io/LaocheXe/SquadXML-PHP">' . $beerWishImage . '</a>'; $content .= '</p>'; $block = array( 'title' => LAN_SQDXML_ADMIN_HELP_01, 'body' => $content, ); return $block; } } new voice_help();
LaocheXe/SquadXML-PHP
squadxml/e_help.php
PHP
gpl-2.0
2,652
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "annotator.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
richard-schwab/annotatorjs-django
manage.py
Python
gpl-2.0
252
<?php /** * @package Joomla.Site * @subpackage com_contact * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; JHtml::_('behavior.keepalive'); JHtml::_('behavior.formvalidation'); JHtml::_('behavior.tooltip'); if (isset($this->error)) : ?> <div class="contact-error"> <?php echo $this->error; ?> </div> <?php endif; ?> <form action="<?php echo JRoute::_('index.php'); ?>" method="post" name="frmContact" class="contact-form form-validate"> <p> <input name="jform[contact_name]" type="text" class="inputType inputType1" id="frmHoTen" size="100" data-default="Họ & Tên" data-require="required" data-warning="Vui lòng nhập nội dung cần Liên hệ" /> <input name="jform[contact_email]" type="text" class="inputType inputType1" id="frmEmail" size="100" data-default="Địa chỉ email" data-require="email" data-warning="Cần nhập địa chỉ email hợp lệ!" /> <input name="jform[contact_subject]" type="text" class="inputType inputType1" id="frmPhone" size="100" data-default="Điện thoại" data-require="required" data-warning="Vui lòng nhập nội dung cần Liên hệ" /> </p> <p class="full"> <textarea name="jform[contact_message]" cols="45" rows="5" class="inputType inputType2" id="frmNoiDung" data-default="Nội dung" data-require="required" data-warning="Vui lòng nhập nội dung cần Liên hệ"></textarea> </p> <p> <input name="submit" type="submit" class="inputButton" value="Gửi đi" /> </p> <input type="hidden" name="option" value="com_contact" /> <input type="hidden" name="task" value="contact.submit" /> <input type="hidden" name="return" value="<?php echo $this->return_page;?>" /> <input type="hidden" name="id" value="<?php echo $this->contact->slug; ?>" /> <?php echo JHtml::_('form.token'); ?> </form>
devthuan/lotteryhcm
templates/xskt/html/com_contact/contact/default_form.php
PHP
gpl-2.0
2,084
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package net.nexustools.jvm.runtime.java.lang.reflect; /** * ParameterizedType represents a parameterized type such as * Collection&lt;String&gt;. * * <p>A parameterized type is created the first time it is needed by a * reflective method, as specified in this package. When a * parameterized type p is created, the generic type declaration that * p instantiates is resolved, and all type arguments of p are created * recursively. See {@link net.nexustools.jvm.runtime.java.lang.reflect.TypeVariable * TypeVariable} for details on the creation process for type * variables. Repeated creation of a parameterized type has no effect. * * <p>Instances of classes that implement this interface must implement * an equals() method that equates any two instances that share the * same generic type declaration and have equal type parameters. * * @since 1.5 */ public interface ParameterizedType extends Type { /** * Returns an array of {@code Type} objects representing the actual type * arguments to this type. * * <p>Note that in some cases, the returned array be empty. This can occur * if this type represents a non-parameterized type nested within * a parameterized type. * * @return an array of {@code Type} objects representing the actual type * arguments to this type * @throws TypeNotPresentException if any of the * actual type arguments refers to a non-existent type declaration * @throws MalformedParameterizedTypeException if any of the * actual type parameters refer to a parameterized type that cannot * be instantiated for any reason * @since 1.5 */ Type[] getActualTypeArguments(); /** * Returns the {@code Type} object representing the class or interface * that declared this type. * * @return the {@code Type} object representing the class or interface * that declared this type * @since 1.5 */ Type getRawType(); /** * Returns a {@code Type} object representing the type that this type * is a member of. For example, if this type is {@code O<T>.I<S>}, * return a representation of {@code O<T>}. * * <p>If this type is a top-level type, {@code null} is returned. * * @return a {@code Type} object representing the type that * this type is a member of. If this type is a top-level type, * {@code null} is returned * @throws TypeNotPresentException if the owner type * refers to a non-existent type declaration * @throws MalformedParameterizedTypeException if the owner type * refers to a parameterized type that cannot be instantiated * for any reason * @since 1.5 */ Type getOwnerType(); }
NexusTools/JVM.JS-JavaRuntime
src/net/nexustools/jvm/runtime/java/lang/reflect/ParameterizedType.java
Java
gpl-2.0
3,996
# _dialogs.py import wx import _widgets as _wgt from wx.lib.wordwrap import wordwrap __version__ = '1.0.0' import logging log = logging.getLogger('root') class CustomDialog(wx.Dialog): def __init__(self, parent, *arg, **kw): style = (wx.NO_BORDER | wx.CLIP_CHILDREN) self.borderColour = wx.BLACK wx.Dialog.__init__(self, parent, title='Fancy', style = style) self.Bind(wx.EVT_MOTION, self.OnMouse) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnSetBorderColour(self, color): self.borderColour = color def OnPaint(self, event): evtObj = event.GetEventObject() evtObjBG = evtObj.GetBackgroundColour() dc = wx.PaintDC(evtObj) dc = wx.GCDC(dc) w, h = self.GetSizeTuple() r = 10 dc.SetPen( wx.Pen(self.borderColour,3) ) dc.SetBrush( wx.Brush(evtObjBG)) dc.DrawRectangle( 0,0,w,h ) def OnMouse(self, event): """implement dragging""" if not event.Dragging(): self._dragPos = None return self.CaptureMouse() if not self._dragPos: self._dragPos = event.GetPosition() else: pos = event.GetPosition() displacement = self._dragPos - pos self.SetPosition( self.GetPosition() - displacement ) self.ReleaseMouse() event.Skip() class MyMessageDialog(CustomDialog): def __init__(self, parent, msg, myStyle, *arg, **kw): self._msg = msg self._style = myStyle super(MyMessageDialog, self).__init__(parent, *arg, **kw) self._panel = wx.Panel(self) self._message = wordwrap(str(self._msg), 350, wx.ClientDC(self)) self.stcText = wx.StaticText(self._panel, -1, self._message) self.stcText.SetFocus() self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) panelSizer.Add(self.stcText, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add(self.btnOk, 0, wx.ALL|wx.CENTRE, 5) if self._style != None and 'INC_CANCEL' in self._style: self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel') btnSizer.Add(self.btnCancel, 0, wx.ALL|wx.CENTRE, 5) panelSizer.Add(btnSizer, 0, wx.ALL|wx.CENTRE, 5) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2) self.SetSizerAndFit(mainSizer) self._panel.Bind(wx.EVT_MOTION, self.OnMouse) self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK) self.CenterOnParent() def OnOk(self, event): self.EndModal(wx.ID_OK) class ClearBtnLocks(CustomDialog): def __init__(self, parent, *arg, **kw): super(ClearBtnLocks, self).__init__(parent, *arg, **kw) self.parent = parent self.OnInitUI() self.OnInitLayout() self.OnBindEvents() self.CenterOnParent() self.OnSetBorderColour(wx.Colour(46,139,87,255)) def OnInitUI(self): self._panel = wx.Panel(self) self.cbDayStart = wx.CheckBox(self._panel, -1, 'Clear Start of Day') self.cbLunchStart = wx.CheckBox(self._panel, -1, 'Clear Start of Lunch') self.cbLunchEnd = wx.CheckBox(self._panel, -1, 'Clear End of Lunch') self.cbDayEnd = wx.CheckBox(self._panel, -1, 'Clear End of Day') self.cbCheckAll = wx.CheckBox(self._panel, 0, 'Select All') self.cbList = ( self.cbDayStart, self.cbLunchStart, self.cbLunchEnd, self.cbDayEnd ) self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel') def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) statBox = wx.StaticBox(self._panel, label='Which Buttons to Enable?') sbSizer = wx.StaticBoxSizer(statBox, wx.VERTICAL) cbSizer = wx.FlexGridSizer(3, 2, 3, 3) cbSizer.AddMany( [ (self.cbDayStart, 0, wx.ALL, 1), (self.cbLunchStart, 0, wx.ALL, 1), (self.cbLunchEnd, 0, wx.ALL, 1), (self.cbDayEnd, 0, wx.ALL, 1), (self.cbCheckAll, 0, wx.ALL, 1) ] ) sbSizer.Add(cbSizer, 0, wx.ALL, 1) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add(self.btnOk, 0, wx.ALL, 5) btnSizer.Add(self.btnCancel, 0, wx.ALL, 5) sbSizer.Add(btnSizer, 1, wx.ALL|wx.CENTRE, 1) panelSizer.Add(sbSizer, 0, wx.ALL | wx.EXPAND, 5) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2) self.SetSizerAndFit(mainSizer) def OnBindEvents(self): self._panel.Bind(wx.EVT_MOTION, self.OnMouse) self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK) for cbOption in self.cbList: cbOption.Bind(wx.EVT_CHECKBOX, self.ClearSelectAll) self.cbCheckAll.Bind(wx.EVT_CHECKBOX, self.OnSelectAll) def OnSelectAll(self, event): if self.cbCheckAll.GetValue(): self.cbDayStart.SetValue(True) self.cbLunchStart.SetValue(True) self.cbLunchEnd.SetValue(True) self.cbDayEnd.SetValue(True) else: self.cbDayStart.SetValue(False) self.cbLunchStart.SetValue(False) self.cbLunchEnd.SetValue(False) self.cbDayEnd.SetValue(False) def ClearSelectAll(self, event): self.cbCheckAll.SetValue(False) def OnOk(self, event): log.debug('User prompted: Confirm button reset.') _msg = 'You are about to reset button locks!\nDo you wish to continue?' _style = 'INC_CANCEL' dlg = MyMessageDialog(self, msg=_msg, myStyle=_style) dlg.OnSetBorderColour(wx.Colour(255,165,0,255)) if dlg.ShowModal() == wx.ID_OK: if self.cbDayStart.GetValue(): self.parent.btnStartDay.Enable(True) self.parent.txtStartDay.SetValue('') log.debug( '\'Start of Day\' button enabled by user.') if self.cbLunchStart.GetValue(): self.parent.btnStartLunch.Enable(True) self.parent.txtStartLunch.SetValue('') log.debug( '\'Start of Lunch\' button enabled by user.') if self.cbLunchEnd.GetValue(): self.parent.btnEndLunch.Enable(True) self.parent.txtEndLunch.SetValue('') log.debug( '\'End of Lunch\' button enabled by user.') if self.cbDayEnd.GetValue(): self.parent.btnEndDay.Enable(True) self.parent.txtEndDay.SetValue('') log.debug( '\'End of Day\' button enabled by user.') event.Skip() self.EndModal(wx.ID_OK) def OnCancel(self, event): self.EndModal(wx.ID_CANCEL) class EnterEmail(CustomDialog): def __init__(self, parent, eType, *arg, **kw): self.eType = eType super(EnterEmail, self).__init__(parent, *arg, **kw) self.parent = parent self.idEmail = wx.NewId() self.OnInitUI() self.OnInitLayout() self.OnBindEvents() self.OnSetBorderColour(wx.Colour(205,133,63,255)) def OnInitUI(self): self._panel = wx.Panel(self) self.sb = wx.StaticBox(self._panel, label='') self.dEmail = wx.TextCtrl(self._panel, id=self.idEmail, value='', style=wx.TE_PROCESS_ENTER|wx.SIMPLE_BORDER) if self.eType == 'DEST': self.sb.SetLabel('Confirm destination email address:') #log.debug( # 'User is updating Destination email address.') self.dEmail.SetValue('enter @ default . email') elif self.eType == 'CC': #log.debug( # 'User is updating CC email address.') self.sb.SetLabel('Enter email address to CC:') elif self.eType == 'BUG': self.sb.SetLabel('Confirm email address for Bug Reports:') self.dEmail.SetValue('bug @ report . email') self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel') def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) sbSizer1 = wx.StaticBoxSizer(self.sb, wx.VERTICAL) sbSizer1.Add(self.dEmail, 1, wx.ALL|wx.EXPAND, 5) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add(self.btnOk, 1, wx.ALL, 5) btnSizer.Add(self.btnCancel, 1, wx.ALL, 5) sbSizer1.Add(btnSizer, 1, wx.ALL|wx.EXPAND, 5) panelSizer.Add(sbSizer1, 1, wx.ALL|wx.EXPAND, 3) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 2) self.SetSizerAndFit(mainSizer) self.SetPosition( (400,300) ) def OnBindEvents(self): self._panel.Bind(wx.EVT_MOTION, self.OnMouse) self.dEmail.Bind(wx.EVT_TEXT_ENTER, self.OnOk) def GetAddress(self): emailAddress = self.dEmail.GetValue() if '@' in emailAddress and '.' in emailAddress.split('@')[1]: return emailAddress else: return '' def OnOk(self, event): self.EndModal(wx.ID_OK) class ViewEmail(CustomDialog): def __init__(self, parent, eType, eMail, *arg, **kw): self.eType = eType self.eMail = eMail super(ViewEmail, self).__init__(parent, *arg, **kw) self.OnInitUI() self.OnInitLayout() self.OnSetBorderColour(wx.Colour(55,95,215,255)) def OnInitUI(self): self._panel = wx.Panel(self) self.statBox = wx.StaticBox(self._panel, label='') self.statEmail = wx.StaticText(self._panel, label='') statFont = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL) self.statEmail.SetFont(statFont) if self.eType == 'DEST': self.statBox.SetLabel('Destination Address:') elif self.eType == 'CC': self.statBox.SetLabel('\'Carbon Copy\' Address:') elif self.eType == 'BUG': self.statBox.SetLabel('\'Bug Report\' Address:') emailString = wordwrap( str(self.eMail), 350,wx.ClientDC(self._panel)) self.statEmail.SetLabel(emailString) self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) sbSizer1 = wx.StaticBoxSizer(self.statBox, wx.VERTICAL) sbSizer1.Add(self.statEmail, 1, wx.ALL|wx.CENTER, 3) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add(self.btnOk, 1, wx.ALL|wx.CENTER, 5) sbSizer1.Add(btnSizer, 1, wx.ALL|wx.CENTER, 5) panelSizer.Add(sbSizer1, 1, wx.ALL|wx.EXPAND, 5) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 3) self.SetSizerAndFit(mainSizer) def OnOk(self, event): if self.IsModal(): self.EndModal(wx.ID_OK) class AboutWindow(CustomDialog): def __init__(self, parent, ver, *arg, **kw): self._ver = ver super(AboutWindow, self).__init__(parent, *arg, **kw) '''Create and define the About dialog window.''' self._idHyperlink = wx.NewId() self.OnInitWidgets() self.OnInitLayout() self.OnBindEvents() self.CenterOnParent() def OnInitWidgets(self): self._panel = wx.Panel(self) self.titleText = wx.StaticText(self._panel, -1, 'Clock Punch v%s' % self._ver) titleFont = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.BOLD) self.titleText.SetFont(titleFont) self.webLink = _wgt.CustomHyperlink(self._panel, self._idHyperlink, label = 'Written using Python', url = "http://en.wikipedia.org/wiki/Python_programming_language" ) description = wordwrap( "This is the Clock Puncher." " \n-The original Time Punch application re-written." " \nIt allows you to easily send the various time punch" " emails at the click of a button." "\n\nPlease do not report any issues with this program to DS IT as" " it is not an officially supported application.", 350, wx.ClientDC(self)) self.descText = wx.StaticText(self._panel, -1, description) self.licenseHeader = wx.StaticText(self._panel, -1, 'Licensing:') licenseFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD) self.licenseHeader.SetFont(licenseFont) license = wordwrap('Main program: GPL v3' '\nPython: PSF License' '\npyWin32: PSF License' '\nWMI: MIT License' '\nwxPython: wxWidgets License', 350, wx.ClientDC(self)) self.licenseText = wx.StaticText(self._panel, -1, license) self.devHeader = wx.StaticText(self._panel, -1, 'Developer(s):') devFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD) self.devHeader.SetFont(devFont) developers = wordwrap( 'Program Writer:' '\nMichael Stover', 500, wx.ClientDC(self)) self.devText = wx.StaticText(self._panel, -1, developers) self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK', size=(50,-1)) def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) titleSizer = wx.BoxSizer(wx.HORIZONTAL) titleSizer.Add(self.titleText, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER, 2) descriptSizer = wx.BoxSizer(wx.VERTICAL) descriptSizer.Add(self.descText, 1, wx.ALL|wx.EXPAND, 2) descriptSizer.Add(self.webLink, 0, wx.ALL, 2) licenseSizer = wx.BoxSizer(wx.VERTICAL) licenseSizer.Add(self.licenseHeader, 0, wx.ALL|wx.EXPAND|wx.CENTER, 2) licenseSizer.Add(self.licenseText, 1, wx.ALL|wx.EXPAND, 2) developSizer = wx.BoxSizer(wx.VERTICAL) developSizer.Add(self.devHeader, 0, wx.ALL|wx.EXPAND|wx.CENTER, 2) developSizer.Add(self.devText, 1, wx.ALL|wx.EXPAND, 2) buttonSizer = wx.BoxSizer(wx.HORIZONTAL) buttonSizer.Add(self.btnOk, 0, wx.ALL|wx.ALIGN_RIGHT, 2) panelSizer.Add(titleSizer, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER, 2) panelSizer.Add(descriptSizer, 0, wx.ALL|wx.EXPAND, 2) panelSizer.Add(wx.StaticLine( self._panel, -1, style=wx.LI_HORIZONTAL ), 1, wx.ALL|wx.EXPAND, 5 ) panelSizer.Add(licenseSizer, 0, wx.ALL|wx.EXPAND, 2) panelSizer.Add(wx.StaticLine( self._panel, -1, style=wx.LI_HORIZONTAL ), 1, wx.ALL|wx.EXPAND, 5 ) panelSizer.Add(developSizer, 0, wx.ALL|wx.EXPAND, 2) panelSizer.Add(buttonSizer, 0, wx.ALL|wx.ALIGN_CENTER, 2) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 2) self.SetSizerAndFit(mainSizer) def OnBindEvents(self): self.Bind(wx.EVT_HYPERLINK, self.OnLinkClicked, id=self._idHyperlink) self._panel.Bind(wx.EVT_MOTION, self.OnMouse) def OnLinkClicked(self, event=None): evtObj = event.GetEventObject() if isinstance(evtObj, wx.HyperlinkCtrl): print evtObj.GetURL() def OnOk(self, event): if self.IsModal(): self.EndModal(wx.ID_OK) class HelpWindow(CustomDialog): def __init__(self, parent, *arg, **kw): super(HelpWindow, self).__init__(parent, *arg, **kw) pass class BugReport(CustomDialog): def __init__(self, parent, *arg, **kw): super(BugReport, self).__init__(parent, *arg, **kw) self.OnSetBorderColour(wx.Colour(153, 0, 0, 255)) self.OnInitUI() self.OnInitLayout() self.OnBindEvents() def OnInitUI(self): self._panel = wx.Panel(self) self._panel.SetBackgroundColour(wx.Colour(230,230,230,255)) self._titleBox = wx.StaticText( self._panel, -1, ' Bug Report Submission', style=wx.NO_BORDER ) titleFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD) self._titleBox.SetFont(titleFont) self._titleBox.SetBackgroundColour(wx.WHITE) summary = wordwrap( 'Thank you for taking this opportunity to submit ' 'a bug report for this program.\n\nPlease enter a ' 'brief description into the box below. I will ' 'investigate the bug report as soon as possible.' '\n\nUpon clicking Submit the program will also ' 'locate and collect any logs for review. These ' 'will be sent as attachments to the email.' '\n\nNo personal information is collected.' '\nYou will be able to preview the report before ' 'it is sent.', 350, wx.ClientDC(self)) self.bugTips = wx.StaticText(self._panel, -1, summary, style=wx.NO_BORDER|wx.TE_CENTER ) self.bugTips.SetBackgroundColour(wx.WHITE) self.summaryBox = wx.TextCtrl(self._panel, -1, value='', style=wx.TE_MULTILINE|wx.SIMPLE_BORDER) self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel') def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) titleSizer = wx.BoxSizer(wx.HORIZONTAL) titleSizer.Add(self._titleBox, 1, wx.ALL|wx.EXPAND, 3) panelSizer.Add(titleSizer, 0, wx.EXPAND|wx.CENTRE, 3) tipsSizer = wx.BoxSizer(wx.HORIZONTAL) tipsSizer.Add(self.bugTips, 1, wx.EXPAND, 3) panelSizer.Add(tipsSizer, 1, wx.ALL|wx.EXPAND, 3) summarySizer = wx.BoxSizer(wx.HORIZONTAL) summarySizer.Add(self.summaryBox, 1, wx.ALL|wx.EXPAND, 3) panelSizer.Add(summarySizer, 1, wx.ALL|wx.EXPAND, 1) buttonSizer = wx.BoxSizer(wx.HORIZONTAL) buttonSizer.Add(self.btnOk, 1, wx.ALL, 3) buttonSizer.Add(self.btnCancel, 1, wx.ALL, 3) panelSizer.Add(buttonSizer, 0, wx.EXPAND, 1) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL, 3) self.SetSizerAndFit(mainSizer) def OnBindEvents(self): self._panel.Bind(wx.EVT_MOTION, self.OnMouse) self._titleBox.Bind(wx.EVT_MOTION, self.OnMouse) self.bugTips.Bind(wx.EVT_MOTION, self.OnMouse) def OnGetSummary(self, event=None): return self.summaryBox.GetValue() def OnClose(self, event): self.EndModal(event.GetId()) import logging log = logging.getLogger('root') log.debug('Dialogs Module %s Initialized.' % __version__)
Hakugin/TimeClock
_dialogs.py
Python
gpl-2.0
19,476
""" WSGI config for SysuLesson project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SysuLesson.settings") application = get_wsgi_application()
chenzeyuczy/keba
src/SysuLesson/wsgi.py
Python
gpl-2.0
397
import config from '@automattic/calypso-config'; import debugFactory from 'debug'; // Enable/disable ad-tracking // These should not be put in the json config as they must not differ across environments export const isGoogleAnalyticsEnabled = true; export const isGoogleAnalyticsEnhancedEcommerceEnabled = true; export const isFloodlightEnabled = true; export const isFacebookEnabled = true; export const isBingEnabled = true; export const isGeminiEnabled = false; export const isWpcomGoogleAdsGtagEnabled = true; export const isJetpackGoogleAdsGtagEnabled = true; export const isQuantcastEnabled = false; export const isExperianEnabled = true; export const isOutbrainEnabled = true; export const isPinterestEnabled = true; export const isIconMediaEnabled = false; export const isTwitterEnabled = true; export const isLinkedinEnabled = false; export const isCriteoEnabled = false; export const isPandoraEnabled = false; export const isQuoraEnabled = false; export const isAdRollEnabled = false; /** * Module variables */ export const debug = debugFactory( 'calypso:analytics:ad-tracking' ); export const FACEBOOK_TRACKING_SCRIPT_URL = 'https://connect.facebook.net/en_US/fbevents.js'; export const GOOGLE_GTAG_SCRIPT_URL = 'https://www.googletagmanager.com/gtag/js?id='; export const BING_TRACKING_SCRIPT_URL = 'https://bat.bing.com/bat.js'; export const CRITEO_TRACKING_SCRIPT_URL = 'https://static.criteo.net/js/ld/ld.js'; export const YAHOO_GEMINI_CONVERSION_PIXEL_URL = 'https://sp.analytics.yahoo.com/spp.pl?a=10000&.yp=10014088&ec=wordpresspurchase'; export const YAHOO_GEMINI_AUDIENCE_BUILDING_PIXEL_URL = 'https://sp.analytics.yahoo.com/spp.pl?a=10000&.yp=10014088'; export const PANDORA_CONVERSION_PIXEL_URL = 'https://data.adxcel-ec2.com/pixel/?ad_log=referer&action=purchase&pixid=7efc5994-458b-494f-94b3-31862eee9e26'; export const EXPERIAN_CONVERSION_PIXEL_URL = 'https://d.turn.com/r/dd/id/L21rdC84MTYvY2lkLzE3NDc0MzIzNDgvdC8yL2NhdC8zMjE4NzUwOQ'; export const ICON_MEDIA_RETARGETING_PIXEL_URL = 'https://tags.w55c.net/rs?id=cab35a3a79dc4173b8ce2c47adad2cea&t=marketing'; export const ICON_MEDIA_SIGNUP_PIXEL_URL = 'https://tags.w55c.net/rs?id=d239e9cb6d164f7299d2dbf7298f930a&t=marketing'; export const ICON_MEDIA_ORDER_PIXEL_URL = 'https://tags.w55c.net/rs?id=d299eef42f2d4135a96d0d40ace66f3a&t=checkout'; export const ADROLL_PAGEVIEW_PIXEL_URL_1 = 'https://d.adroll.com/ipixel/PEJHFPIHPJC2PD3IMTCWTT/WV6A5O5PBJBIBDYGZHVBM5?name=ded132f8'; export const ADROLL_PAGEVIEW_PIXEL_URL_2 = 'https://d.adroll.com/fb/ipixel/PEJHFPIHPJC2PD3IMTCWTT/WV6A5O5PBJBIBDYGZHVBM5?name=ded132f8'; export const ADROLL_PURCHASE_PIXEL_URL_1 = 'https://d.adroll.com/ipixel/PEJHFPIHPJC2PD3IMTCWTT/WV6A5O5PBJBIBDYGZHVBM5?name=8eb337b5'; export const ADROLL_PURCHASE_PIXEL_URL_2 = 'https://d.adroll.com/fb/ipixel/PEJHFPIHPJC2PD3IMTCWTT/WV6A5O5PBJBIBDYGZHVBM5?name=8eb337b5'; export const TWITTER_TRACKING_SCRIPT_URL = 'https://static.ads-twitter.com/uwt.js'; export const LINKED_IN_SCRIPT_URL = 'https://snap.licdn.com/li.lms-analytics/insight.min.js'; export const QUORA_SCRIPT_URL = 'https://a.quora.com/qevents.js'; export const OUTBRAIN_SCRIPT_URL = 'https://amplify.outbrain.com/cp/obtp.js'; export const PINTEREST_SCRIPT_URL = 'https://s.pinimg.com/ct/core.js'; export const TRACKING_IDS = { bingInit: '4074038', criteo: '31321', dcmFloodlightAdvertiserId: '6355556', facebookInit: '823166884443641', facebookJetpackInit: '919484458159593', fullStory: '120RG4', fullStoryJetpack: '181XXV', linkedInPartnerId: '195308', outbrainAdvId: '00f0f5287433c2851cc0cb917c7ff0465e', pinterestInit: '2613194105266', quantcast: 'p-3Ma3jHaQMB_bS', quoraPixelId: '420845cb70e444938cf0728887a74ca1', twitterPixelId: 'nvzbs', wpcomGoogleAnalyticsGtag: config( 'google_analytics_key' ), wpcomFloodlightGtag: 'DC-6355556', wpcomGoogleAdsGtag: 'AW-946162814', wpcomGoogleAdsGtagSignupStart: 'AW-946162814/baDICKzQiq4BEP6YlcMD', // "WordPress.com Signup Start" wpcomGoogleAdsGtagRegistration: 'AW-946162814/_6cKCK6miZYBEP6YlcMD', // "WordPress.com Registration" wpcomGoogleAdsGtagSignup: 'AW-946162814/5-NnCKy3xZQBEP6YlcMD', // "All Calypso Signups (WordPress.com)" wpcomGoogleAdsGtagAddToCart: 'AW-946162814/MF4yCNi_kZYBEP6YlcMD', // "WordPress.com AddToCart" wpcomGoogleAdsGtagPurchase: 'AW-946162814/taG8CPW8spQBEP6YlcMD', // "WordPress.com Purchase Gtag" jetpackGoogleAnalyticsGtag: 'UA-52447-43', // Jetpack Gtag (Analytics) for use in Jetpack x WordPress.com Flows jetpackGoogleAdsGtagPurchase: 'AW-946162814/kIF1CL3ApfsBEP6YlcMD', }; // This name is something we created to store a session id for DCM Floodlight session tracking export const DCM_FLOODLIGHT_SESSION_COOKIE_NAME = 'dcmsid'; export const DCM_FLOODLIGHT_SESSION_LENGTH_IN_SECONDS = 1800; export const GA_PRODUCT_BRAND_WPCOM = 'WordPress.com'; export const GA_PRODUCT_BRAND_JETPACK = 'Jetpack';
Automattic/wp-calypso
client/lib/analytics/ad-tracking/constants.js
JavaScript
gpl-2.0
4,877
<?php /** * Generates the tabs that are used in the options menu */ function optionsframework_tabs() { $counter = 0; $optionsframework_settings = get_option('options_framework_theme'); $options = optionsframework_options(); $menu = ''; foreach ($options as $value) { $counter++; // Heading for Navigation if ($value['type'] == "heading") { $id = ! empty( $value['id'] ) ? $value['id'] : $value['name']; $jquery_click_hook = preg_replace('/[^a-zA-Z0-9._\-]/', '', strtolower($id) ); $jquery_click_hook = "of-option-" . $jquery_click_hook; $_href = esc_attr( '#'. $jquery_click_hook ); $_href_2 = esc_attr( '#'. $jquery_click_hook ); $_rel = ' normal'; if(isset($value['external']) && $value['external'] == true) : global $pagenow; $_href = admin_url( 'themes.php?page=options-framework' ) . '&section='.$value['section'].esc_attr( '#'. $jquery_click_hook ); $_rel = ' external'; endif; $menu .= '<a rel="'.$_href_2.'" id="'. esc_attr( $jquery_click_hook ) . '-tab" class="nav-tab'.$_rel.'" title="' . esc_attr( $value['name'] ) . '" href="' . $_href . '">' . esc_html( $value['name'] ) . '</a>'; } } return $menu; } /** * Generates the options fields that are used in the form. */ function optionsframework_fields() { global $allowedtags; $optionsframework_settings = get_option('optionsframework'); // Gets the unique option id if ( isset( $optionsframework_settings['id'] ) ) { $option_name = $optionsframework_settings['id']; } else { $option_name = 'optionsframework'; }; $settings = get_option($option_name); $options = optionsframework_options(); $counter = 0; $menu = ''; foreach ( $options as $value ) { $counter++; $val = ''; $select_value = ''; $checked = ''; $output = ''; // Wrap all options if ( ( $value['type'] != "heading" ) && ( $value['type'] != "info" ) && ( $value['type'] != "subheading" )) { // Keep all ids lowercase with no spaces $value['id'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', strtolower($value['id']) ); $id = 'section-' . $value['id']; $class = 'section '; if ( isset( $value['type'] ) ) { $class .= ' section-' . $value['type']; } if ( isset( $value['class'] ) ) { $class .= ' ' . $value['class']; } $output .= '<div id="' . esc_attr( $id ) .'" class="' . esc_attr( $class ) . '">'."\n"; if ( isset( $value['name'] ) ) { $output .= '<h4 class="heading">' . esc_html( $value['name'] ) . '</h4>' . "\n"; } if ( $value['type'] != 'editor' ) { $output .= '<div class="option">' . "\n" . '<div class="controls">' . "\n"; } else { $output .= '<div class="option">' . "\n" . '<div>' . "\n"; } } // Set default value to $val if ( isset( $value['std'] ) ) { $val = $value['std']; } // If the option is already saved, ovveride $val if ( ( $value['type'] != 'heading' ) && ( $value['type'] != 'info') && ( $value['type'] != "subheading" ) ) { if ( isset( $settings[($value['id'])]) ) { $val = $settings[($value['id'])]; // Striping slashes of non-array options if ( !is_array($val) ) { $val = stripslashes( $val ); } } } // If there is a description save it for labels $explain_value = ''; if ( isset( $value['desc'] ) ) { $explain_value = $value['desc']; } switch ( $value['type'] ) { // Basic text input case 'text': $output .= '<input id="' . esc_attr( $value['id'] ) . '" class="of-input" name="' . esc_attr( $option_name . '[' . $value['id'] . ']' ) . '" type="text" value="' . esc_attr( $val ) . '" />'; break; // Password input case 'password': $output .= '<input id="' . esc_attr( $value['id'] ) . '" class="of-input" name="' . esc_attr( $option_name . '[' . $value['id'] . ']' ) . '" type="password" value="' . esc_attr( $val ) . '" />'; break; // Textarea case 'textarea': $rows = '8'; if ( isset( $value['settings']['rows'] ) ) { $custom_rows = $value['settings']['rows']; if ( is_numeric( $custom_rows ) ) { $rows = $custom_rows; } } $val = stripslashes( $val ); $output .= '<textarea id="' . esc_attr( $value['id'] ) . '" class="of-input" name="' . esc_attr( $option_name . '[' . $value['id'] . ']' ) . '" rows="' . $rows . '">' . esc_textarea( $val ) . '</textarea>'; break; // Select Box case 'select': $output .= '<select class="of-input" name="' . esc_attr( $option_name . '[' . $value['id'] . ']' ) . '" id="' . esc_attr( $value['id'] ) . '">'; foreach ($value['options'] as $key => $option ) { $selected = ''; if ( $val != '' ) { if ( $val == $key) { $selected = ' selected="selected"';} } $output .= '<option'. $selected .' value="' . esc_attr( $key ) . '">' . esc_html( $option ) . '</option>'; } $output .= '</select>'; break; // Radio Box case "radio": $name = $option_name .'['. $value['id'] .']'; foreach ($value['options'] as $key => $option) { $id = $option_name . '-' . $value['id'] .'-'. $key; $output .= '<input class="of-input of-radio" type="radio" name="' . esc_attr( $name ) . '" id="' . esc_attr( $id ) . '" value="'. esc_attr( $key ) . '" '. checked( $val, $key, false) .' /><label for="' . esc_attr( $id ) . '">' . esc_html( $option ) . '</label>'; } break; // Image Selectors case "images": $name = $option_name .'['. $value['id'] .']'; foreach ( $value['options'] as $key => $option ) { $selected = ''; $checked = ''; if ( $val != '' ) { if ( $val == $key ) { $selected = ' of-radio-img-selected'; $checked = ' checked="checked"'; } } $output .= '<input type="radio" id="' . esc_attr( $value['id'] .'_'. $key) . '" class="of-radio-img-radio" value="' . esc_attr( $key ) . '" name="' . esc_attr( $name ) . '" '. $checked .' />'; $output .= '<div class="of-radio-img-label">' . esc_html( $key ) . '</div>'; $output .= '<img src="' . esc_url( $option ) . '" alt="' . $option .'" class="of-radio-img-img' . $selected .'" onclick="document.getElementById(\''. esc_attr($value['id'] .'_'. $key) .'\').checked=true;" />'; } break; // Checkbox case "checkbox": $output .= '<input id="' . esc_attr( $value['id'] ) . '" class="checkbox of-input" type="checkbox" name="' . esc_attr( $option_name . '[' . $value['id'] . ']' ) . '" '. checked( $val, 1, false) .' />'; $output .= '<label class="explain" for="' . esc_attr( $value['id'] ) . '">' . wp_kses( $explain_value, $allowedtags) . '</label>'; break; // Multicheck case "multicheck": foreach ($value['options'] as $key => $option) { $checked = ''; $label = $option; $option = preg_replace('/[^a-zA-Z0-9._\-]/', '', strtolower($key)); $id = $option_name . '-' . $value['id'] . '-'. $option; $name = $option_name . '[' . $value['id'] . '][' . $option .']'; if ( isset($val[$option]) ) { $checked = checked($val[$option], 1, false); } $output .= '<input id="' . esc_attr( $id ) . '" class="checkbox of-input" type="checkbox" name="' . esc_attr( $name ) . '" ' . $checked . ' /><label for="' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>'; } break; // Color picker case "color": $default_color = ''; if ( isset($value['std']) ) { if ( $val != $value['std'] ) $default_color = ' data-default-color="' .$value['std'] . '" '; } $output .= '<input name="' . esc_attr( $option_name . '[' . $value['id'] . ']' ) . '" id="' . esc_attr( $value['id'] ) . '" class="of-color" type="text" value="' . esc_attr( $val ) . '"' . $default_color .' />'; break; // Uploader case "upload": $output .= optionsframework_medialibrary_uploader( $value['id'], $val, null ); break; // Typography case 'typography': unset( $font_size, $font_style, $font_face, $font_color ); $typography_defaults = array( 'size' => '', 'face' => '', 'style' => '', 'color' => '', 'line_height' => '', 'disable-color' => false, 'disable-line-height' => false, 'disable-size' => false, 'disable-styles' => false, ); $typography_stored = wp_parse_args( $val, $typography_defaults ); $typography_options = array( 'sizes' => of_recognized_font_sizes(), 'line_heights' => of_recognized_font_heights(), 'faces' => @of_recognized_font_faces(), 'styles' => of_recognized_font_styles(), 'color' => true, 'disable-color' => false, 'disable-line-height' => false, 'disable-size' => false, 'disable-styles' => false, ); if ( isset( $value['options'] ) ) { $typography_options = wp_parse_args( $value['options'], $typography_options ); if( isset($typography_options['disable-color']) && $typography_options['disable-color'] == true) $typography_options['color'] = false; if( isset($typography_options['disable-line-height']) && $typography_options['disable-line-height'] == true ) $typography_options['line_heights'] = false; if( isset($typography_options['disable-size']) && $typography_options['disable-size'] == true ) $typography_options['sizes'] = false; if( isset($typography_options['disable-styles']) && $typography_options['disable-styles'] == true ) $typography_options['styles'] = false; } // Font Size if ( $typography_options['sizes'] ) { $font_size = '<select class="of-typography of-typography-size" name="' . esc_attr( $option_name . '[' . $value['id'] . '][size]' ) . '" id="' . esc_attr( $value['id'] . '_size' ) . '">'; $font_size .= '<option value="">Size</option>'; $sizes = $typography_options['sizes']; foreach ( $sizes as $i ) { if( is_int($i) ) : $size = $i . 'px'; $font_size .= '<option value="' . esc_attr( $size ) . '" ' . selected( $typography_stored['size'], $size, false ) . '>' . esc_html( $size ) . '</option>'; endif; } $font_size .= '</select>'; } if ( $typography_options['line_heights'] != false ) { $font_line_height = '<select class="of-typography of-typography-height" name="' . esc_attr( $option_name . '[' . $value['id'] . '][line_height]' ) . '" id="' . esc_attr( $value['id'] . '_height' ) . '">'; $font_line_height .= '<option value="">Line Height</option>'; $heights = $typography_options['line_heights']; foreach ( $heights as $i ) { $height = $i . 'px'; $font_line_height .= '<option value="' . esc_attr( $height ) . '" ' . selected( $typography_stored['line_height'], $height, false ) . '>' . esc_html( $height ) . '</option>'; } $font_line_height .= '</select>'; } // Font Face if ( $typography_options['faces'] ) { $font_face = '<select class="of-typography of-typography-face" name="' . esc_attr( $option_name . '[' . $value['id'] . '][face]' ) . '" id="' . esc_attr( $value['id'] . '_face' ) . '">'; $font_face .= '<option value="">Font Family</option>'; $faces = $typography_options['faces']; foreach ( $faces as $key => $face ) { $font_face .= '<option value="' . esc_attr( $key ) . '" ' . selected( $typography_stored['face'], $key, false ) . '>' . esc_html( $face ) . '</option>'; } $font_face .= '</select>'; } // Font Styles if ( $typography_options['styles'] ) { $font_style = '<select class="of-typography of-typography-style" name="'.$option_name.'['.$value['id'].'][style]" id="'. $value['id'].'_style">'; $font_style .= '<option value="">Style</option>'; $styles = $typography_options['styles']; foreach ( $styles as $key => $style ) { $font_style .= '<option value="' . esc_attr( $key ) . '" ' . selected( $typography_stored['style'], $key, false ) . '>'. $style .'</option>'; } $font_style .= '</select>'; } // Font Color if ( $typography_options['color'] ) { $default_color = ''; if ( isset($value['std']['color']) ) { if ( $val != $value['std']['color'] ) $default_color = ' data-default-color="' .$value['std']['color'] . '" '; } $font_color = '<input name="' . esc_attr( $option_name . '[' . $value['id'] . '][color]' ) . '" id="' . esc_attr( $value['id'] . '_color' ) . '" class="of-color of-typography-color type="text" value="' . esc_attr( $typography_stored['color'] ) . '"' . $default_color .' />'; } // Allow modification/injection of typography fields $typography_fields = compact( 'font_size', 'font_face', 'font_style', 'font_line_height', 'font_color' ); $typography_fields = apply_filters( 'of_typography_fields', $typography_fields, $typography_stored, $option_name, $value ); $output .= implode( '', $typography_fields ); break; // Background case 'background': $background = $val; // Background Color $default_color = ''; if ( isset($value['std']['color']) ) { if ( $val != $value['std']['color'] ) $default_color = ' data-default-color="' .$value['std']['color'] . '" '; } $output .= '<input name="' . esc_attr( $option_name . '[' . $value['id'] . '][color]' ) . '" id="' . esc_attr( $value['id'] . '_color' ) . '" class="of-color of-background-color" type="text" value="' . esc_attr( $background['color'] ) . '"' . $default_color .' />'; // Background Image - New AJAX Uploader using Media Library if (!isset($background['image'])) { $background['image'] = ''; } $output .= optionsframework_medialibrary_uploader( $value['id'], $background['image'], null, '',0,'image'); $class = 'of-background-properties'; if ( '' == $background['image'] ) { $class .= ' hide'; } $output .= '<div class="' . esc_attr( $class ) . '">'; // Background Repeat $output .= '<select class="of-background of-background-repeat" name="' . esc_attr( $option_name . '[' . $value['id'] . '][repeat]' ) . '" id="' . esc_attr( $value['id'] . '_repeat' ) . '">'; $repeats = of_recognized_background_repeat(); foreach ($repeats as $key => $repeat) { $output .= '<option value="' . esc_attr( $key ) . '" ' . selected( $background['repeat'], $key, false ) . '>'. esc_html( $repeat ) . '</option>'; } $output .= '</select>'; // Background Position $output .= '<select class="of-background of-background-position" name="' . esc_attr( $option_name . '[' . $value['id'] . '][position]' ) . '" id="' . esc_attr( $value['id'] . '_position' ) . '">'; $positions = of_recognized_background_position(); foreach ($positions as $key=>$position) { $output .= '<option value="' . esc_attr( $key ) . '" ' . selected( $background['position'], $key, false ) . '>'. esc_html( $position ) . '</option>'; } $output .= '</select>'; // Background Attachment $output .= '<select class="of-background of-background-attachment" name="' . esc_attr( $option_name . '[' . $value['id'] . '][attachment]' ) . '" id="' . esc_attr( $value['id'] . '_attachment' ) . '">'; $attachments = of_recognized_background_attachment(); foreach ($attachments as $key => $attachment) { $output .= '<option value="' . esc_attr( $key ) . '" ' . selected( $background['attachment'], $key, false ) . '>' . esc_html( $attachment ) . '</option>'; } $output .= '</select>'; $output .= '</div>'; break; // Editor case 'editor': $output .= '<div class="explain">' . wp_kses( $explain_value, $allowedtags) . '</div>'."\n"; echo $output; $textarea_name = esc_attr( $option_name . '[' . $value['id'] . ']' ); $default_editor_settings = array( 'textarea_name' => $textarea_name, 'media_buttons' => false, /*'tinymce' => array( 'plugins' => 'wordpress' )*/ ); $editor_settings = array(); if ( isset( $value['settings'] ) ) { $editor_settings = $value['settings']; } $editor_settings = array_merge($editor_settings, $default_editor_settings); wp_editor( $val, $value['id'], $editor_settings ); $output = ''; break; // Info case "info": $id = ''; $class = 'section'; if ( isset( $value['id'] ) ) { $id = 'id="' . esc_attr( $value['id'] ) . '" '; } if ( isset( $value['type'] ) ) { $class .= ' section-' . $value['type']; } if ( isset( $value['class'] ) ) { $class .= ' ' . $value['class']; } $output .= '<div ' . $id . 'class="' . esc_attr( $class ) . '">' . "\n"; if ( isset($value['name']) ) { $output .= '<h4 class="heading">' . esc_html( $value['name'] ) . '</h4>' . "\n"; } if ( $value['desc'] ) { $output .= apply_filters('of_sanitize_info', $value['desc'] ) . "\n"; } $output .= '</div>' . "\n"; break; // Heading for Navigation case "heading": if ($counter >= 2) { $output .= '</div>'."\n"; } $jquery_click_hook = preg_replace('/[^a-zA-Z0-9._\-]/', '', strtolower($value['name']) ); $jquery_click_hook = "of-option-" . $jquery_click_hook; $menu .= '<a id="'. esc_attr( $jquery_click_hook ) . '-tab" class="nav-tab" title="' . esc_attr( $value['name'] ) . '" href="' . esc_attr( '#'. $jquery_click_hook ) . '">' . esc_html( $value['name'] ) . '</a>'; $output .= '<div class="group" id="' . esc_attr( $jquery_click_hook ) . '">'; //$output .= '<h3>' . esc_html( $value['name'] ) . '</h3>' . "\n"; break; // Uploader case "page_selector": wp_enqueue_script('jquery-ui-core'); wp_enqueue_script('jquery-ui-widget'); wp_enqueue_script('jquery-ui-mouse'); wp_enqueue_script('jquery-ui-sortable'); wp_enqueue_style( 'xt-pagemanager', get_template_directory_uri() . '/xt_framework/options/css/page_manager.css', array(), NULL, 'all' ); wp_enqueue_script( 'xt-pagemanager', get_template_directory_uri() . '/xt_framework/options/js/page_manager.js', array('jquery-ui-sortable'), NULL ); $output .= '<div class="pages-custom" id="pages-custom">'; if ( esc_attr( $val ) != '' ) { $sides = esc_attr( $val ); $sides = explode(";", $sides); foreach ($sides as $side) { $side = explode(',', $side); $extText = 'Normal'; if(@$side[1] == 'y') $extText = 'External'; if($side[0] != '') { $output .= '<div class="single-page ui-sortable"><div><span data-external="'.@$side[1].'" rel="'.$side[0].'">'.get_the_title($side[0]).'</span><a class="external external-'.$side[1].'" href="#">'.$extText.'</a><a href="#" class="remove-item">Remove</a></div></div>'; } } } $output .= '</div>'; $output .= ' <div class="new-area"> <label for="new-page">Add Page to Menu</label> '.wp_dropdown_pages( array('echo' => 0) ).'<a class="button-primary" id="new-page" href="#">Add Page to Menu</a> </div>'; $output .= '<input id="' . esc_attr( $value['id'] ) . '" class="of-input" name="' . esc_attr( $option_name . '[' . $value['id'] . ']' ) . '" type="hidden" value="' . esc_attr( $val ) . '" />'; break; // Uploader case "subheading": $output .= '<h4 class="xt-subheading">'.$value['name'].'</h4>'; break; } if ( ( $value['type'] != "heading" ) && ( $value['type'] != "info" ) && ( $value['type'] != "subheading" ) ) { $output .= '</div>'; if ( ( $value['type'] != "checkbox" ) && ( $value['type'] != "editor" ) ) { $allowedtags['br'] = array(); $allowedtags['small'] = array(); $allowedtags['a'] = array('href' => array(), 'target' => array('_self', '', '_blank') ); $output .= '<div class="explain">' . wp_kses( $explain_value, $allowedtags) . '</div>'."\n"; } $output .= '</div></div>'."\n"; } echo $output; } echo '</div>'; }
javalidigital/javali
wp-content/themes/identiq/xt_framework/options/options-interface.php
PHP
gpl-2.0
19,403
<?php class UT2_protection_obfuscate_email_Tweak { function settings() { return UT2_Helper::switcher( 'protection_obfuscate_email', array( 'title' => __( 'Obfuscate Email', UT2_SLUG ) ) ); } function tweak() { add_filter( 'the_content', array( $this, '_do' ), 20 ); add_filter( 'the_excerpt', array( $this, '_do' ), 20 ); add_filter( 'widget_text', array( $this, '_do' ), 20 ); } function _do( $text ) { return preg_replace_callback('/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4})/i', array( $this, '_obfuscate' ), $text); } function _obfuscate( $result ) { return antispambot($result[1]); } }
cchuang6/wp_adora
wp-content/plugins/ultimate-tweaker/sections/content_protection/protection_obfuscate_email/tweak.php
PHP
gpl-2.0
647
// created on 29/11/2007 // Npgsql.NpgsqlConnectionStringBuilder.cs // // Author: // Glen Parker (glenebob@nwlink.com) // Ben Sagal (bensagal@gmail.com) // Tao Wang (dancefire@gmail.com) // // Copyright (C) 2007 The Npgsql Development Team // npgsql-general@gborg.postgresql.org // http://gborg.postgresql.org/project/npgsql/projdisplay.php // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph and the following two paragraphs appear in all copies. // // IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS // DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS // ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. using System; using System.Collections.Generic; //using System.Text; namespace Npgsql { internal class Cache<TEntity> : LinkedList<KeyValuePair<string, TEntity>> where TEntity : class { private int _cache_size = 20; private object locker = new object(); /// <summary> /// Set Cache Size. The default value is 20. /// </summary> public int CacheSize { get { return _cache_size; } set { if (value < 0) { throw new ArgumentOutOfRangeException("CacheSize"); } _cache_size = value; if (this.Count > _cache_size) { lock (locker) { while (_cache_size < this.Count) { RemoveLast(); } } } } } /// <summary> /// Lookup cached entity. null will returned if not match. /// For both get{} and set{} apply LRU rule. /// </summary> /// <param name="key">key</param> /// <returns></returns> public TEntity this[string key] { get { lock (locker) { for (LinkedListNode<KeyValuePair<string, TEntity>> node = this.First; node != null; node = node.Next) { if (node.Value.Key == key) { this.Remove(node); this.AddFirst(node); return node.Value.Value; } } } return null; } set { lock (locker) { for (LinkedListNode<KeyValuePair<string, TEntity>> node = this.First; node != null; node = node.Next) { if (node.Value.Key == key) { this.Remove(node); this.AddFirst(node); return; } } if (this.CacheSize > 0) { this.AddFirst(new KeyValuePair<string, TEntity>(key, value)); if (this.Count > this.CacheSize) { this.RemoveLast(); } } } } } public Cache() : base() { } public Cache(int cacheSize) : base() { this._cache_size = cacheSize; } } }
dvchinh/HTQLNHCS
Common/NpgSQL.2.0.13.91-Fixbugs/Npgsql/Cache.cs
C#
gpl-2.0
3,188
<?php /** * The Header for our theme. * * Displays all of the <head> section and everything up till <div id="main"> * * @package Toolbox * @since Toolbox 0.1 */ ?><!DOCTYPE html> <!--[if IE 6]> <html id="ie6" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 7]> <html id="ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html id="ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!--> <html <?php language_attributes(); ?>> <!--<![endif]--> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width" /> <title><?php /* * Print the <title> tag based on what is being viewed. */ global $page, $paged; wp_title( '|', true, 'right' ); // Add the blog name. bloginfo( 'name' ); // Add the blog description for the home/front page. $site_description = get_bloginfo( 'description', 'display' ); if ( $site_description && ( is_home() || is_front_page() ) ) echo " | $site_description"; // Add a page number if necessary: if ( $paged >= 2 || $page >= 2 ) echo ' | ' . sprintf( __( 'Page %s', 'toolbox' ), max( $paged, $page ) ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" /> <?php if ( is_singular() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); ?> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script> <![endif]--> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="page" class="hfeed"> <?php do_action( 'before' ); ?> <header id="branding" role="banner"> <hgroup> <h1 id="site-title"><a href="<?php echo home_url( '/' ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <h2 id="site-description"><?php bloginfo( 'description' ); ?></h2> </hgroup> <nav id="access" role="navigation"> <h1 class="assistive-text section-heading"><?php _e( 'Main menu', 'toolbox' ); ?></h1> <div class="skip-link screen-reader-text"><a href="#content" title="<?php esc_attr_e( 'Skip to content', 'toolbox' ); ?>"><?php _e( 'Skip to content', 'toolbox' ); ?></a></div> <?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?> </nav><!-- #access --> </header><!-- #branding --> <div id="main">
mbeall/toolbox-lifepointe
header.php
PHP
gpl-2.0
2,564
/* * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C) * 2009 Royal Institute of Technology (KTH) * * GVoD is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package se.sics.gvod.bootstrap.cclient; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import se.sics.caracaldb.Key; import se.sics.caracaldb.KeyRange; /** * @author Alex Ormenisan <aaor@sics.se> */ public class CaracalKeyFactory { private static byte[] prefix; static { String schema = "gvod-v1"; try { prefix = MessageDigest.getInstance("MD5").digest(schema.getBytes()); } catch (NoSuchAlgorithmException ex) { System.exit(1); throw new RuntimeException(ex); } } private final static byte peerKey = 0x01; private final static byte fileMetaKey = 0x02; public static KeyRange getOverlayRange(int overlayId) { ByteBuffer startKey = ByteBuffer.allocate(sizeofOverlayKeyPrefix()); startKey.put(prefix); startKey.putInt(overlayId); startKey.put(peerKey); ByteBuffer endKey = ByteBuffer.allocate(sizeofOverlayKeyPrefix()); endKey.put(prefix); endKey.putInt(overlayId); endKey.put(fileMetaKey); return new KeyRange(KeyRange.Bound.CLOSED, new Key(startKey), new Key(endKey), KeyRange.Bound.OPEN); } public static Key getOverlayPeerKey(int overlayId, int nodeId) { ByteBuffer oKey = ByteBuffer.allocate(sizeofOverlayPeerKey()); oKey.put(prefix); oKey.putInt(overlayId); oKey.put(peerKey); oKey.putInt(nodeId); return new Key(oKey); } public static Key getFileMetadataKey(int overlayId) { ByteBuffer byteKey = ByteBuffer.allocate(sizeofOverlayKeyPrefix()); byteKey.put(prefix); byteKey.putInt(overlayId); byteKey.put(fileMetaKey); return new Key(byteKey); } private static int sizeofOverlayKeyPrefix() { int size = 0; size += prefix.length; size += Integer.SIZE/8; //overlayId; size += Byte.SIZE/8; //key type = overlay peer key return size; } private static int sizeofOverlayPeerKey() { int size = 0; size += sizeofOverlayKeyPrefix(); size += Integer.SIZE/8; //nodeId; return size; } public static class KeyException extends Exception { public KeyException(String message) { super(message); } } }
o-alex/GVoD
bootstrap/server/caracal-client/src/main/java/se/sics/gvod/bootstrap/cclient/CaracalKeyFactory.java
Java
gpl-2.0
3,205
<div class="spinner" style="display: none;"><img class="spinner-img" src="/sites/all/modules/france/fr_mobile_registration/images/spinner.gif"/></div> <div class="container"> <div class="content-card-regist"> <h1>Je renseigne ma Carte Carrefour pour profiter de tous les bons plans de l'appli</h1> <p id="title_1">Sélectionnez votre Carte :</p> <div class="row"> <?php //var_dump($form['cards']); ?> <label for="radio_card_fid" class="cards_col card_fid"> <input type="radio" <?php print $form['cards']['FID']['#disabled']; ?> name="<?php print $form['cards']['#name']; ?>" value="<?php print $form['cards']['FID']['#return_value']; ?>" id="radio_card_fid"<?php if ($form['cards']['FID']['#return_value'] == $form['cards']['FID']['#default_value']): print ' checked="checked"'; endif; ?>> <?php $img_path1 = $base_url . '/' . drupal_get_path('module','fr_mobile_registration') . '/images/carte_fid.jpg'; ?> <img class="cards" src="<?php print $img_path1; ?>" for="radio_card_fid" /> <p class="under_cards" >Carte Carrefour</p> </label> <label for="radio_card_pass" class="cards_col card_pass"> <input type="radio" <?php print $form['cards']['PASS']['#disabled']; ?> name="<?php print $form['cards']['#name']; ?>" value="<?php print $form['cards']['PASS']['#return_value']; ?>" id="radio_card_pass"<?php if ($form['cards']['PASS']['#return_value'] == $form['cards']['PASS']['#default_value']): print ' checked="checked"'; endif; ?>> <?php $img_path2 = $base_url . '/' . drupal_get_path('module','fr_mobile_registration') . '/images/carte_pass.jpg'; ?> <img class="cards" src="<?php print $img_path2; ?>"/> <p class="under_cards" >Carte PASS MASTERCARD</p> </label> </div> <div style="clear:both;"></div> <div class="form-group"> <p id="title_2">N° de Carte : </p> <?php print drupal_render($form['cardFIDFirst']); ?> <?php print drupal_render($form['cardFIDSecond']); ?> <?php print drupal_render($form['cardPASS']); ?> </div> <p class="tips_1">Votre <b>Code Personnel à 5 chiffres</b> est indispensable pour sécuriser votre Carte, il ne vous sera demandé qu'une seule fois</p> <p class="tips_2"><a href="#" onclick="card_registration_ask_personal_code_onclick()" class="spanUnderline" id="get-personal-code">Tapez ici pour l'obtenir immédiatement par email ou SMS</a></p> <p class="center"><?php print drupal_render($form['personal_code']); ?></p> <?php print drupal_render($form['form_build_id']); print drupal_render($form['form_id']); print drupal_render($form['form_token']); print drupal_render($form['imagefield']); print drupal_render($form['civility']); print drupal_render($form['fr_last_name']); print drupal_render($form['fr_first_name']); print drupal_render($form['mail']); print drupal_render($form['pass']); print drupal_render($form['fr_birthdate']); print drupal_render($form['card_number']); print drupal_render($form['personal_code']); print drupal_render($form['process']); print drupal_render($form['card_type']); print drupal_render($form['ignore_hidden']); ?> </div> </div> <div class="buttons-bottom"> <?php if ($form['ignore_hidden']['#value'] == 'ignore') { ?> <input class="submitBtn form-submit btnGrey affiliationBtn" type="button" onclick="card_affiliation_skip();" id="edit-save" name="ignore" value="Ignorer"/><?php print drupal_render($form['save']); ?> <?php } else { ?> <input class="submitBtn form-submit btnGrey affiliationBtn" type="submit" id="edit-save" name="ignore" value="Ignorer"/><?php print drupal_render($form['save']); ?> <?php } ?> </div> <script type="text/javascript" src="/sites/all/modules/france/fr_mobile_registration/js/jquery-1.11.3.min.js"></script>
singhneeraj/fr-portal
sites/all/modules/france/fr_mobile_registration/theme/fr_mobile_card_registration_form.tpl.php
PHP
gpl-2.0
4,186
package de.geotech.systems.kriging; public class DataPoint { String name, region, date, typ; double xCoordinate, yCoordinate; int id; int isValuePoint; Integer data, intData; boolean hasConvergence = true; }
GeoTechSystems/GeoTechMobile
app/src/main/java/de/geotech/systems/kriging/DataPoint.java
Java
gpl-2.0
219
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003 - Marauroa * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.client.gui.login; import games.stendhal.client.StendhalClient; import games.stendhal.client.stendhal; import games.stendhal.client.gui.ProgressBar; import games.stendhal.client.gui.WindowUtils; import games.stendhal.client.gui.layout.SBoxLayout; import games.stendhal.client.sprite.DataLoader; import games.stendhal.client.update.ClientGameConfiguration; import java.awt.Component; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import marauroa.client.BannedAddressException; import marauroa.client.LoginFailedException; import marauroa.client.TimeoutException; import marauroa.common.io.Persistence; import marauroa.common.net.InvalidVersionException; import marauroa.common.net.message.MessageS2CLoginNACK; import org.apache.log4j.Logger; /** * Server login dialog. * */ public class LoginDialog extends JDialog { private static final long serialVersionUID = -1182930046629241075L; private ProfileList profiles; private JComboBox profilesComboBox; private JCheckBox saveLoginBox; private JCheckBox savePasswordBox; private JTextField usernameField; private JPasswordField passwordField; private JTextField serverField; private JTextField serverPortField; private JButton loginButton; private JButton removeButton; // End of variables declaration private final StendhalClient client; private ProgressBar progressBar; // Object checking that all required fields are filled private DataValidator fieldValidator; /** * Create a new LoginDialog. * * @param owner parent window * @param client client */ public LoginDialog(final Frame owner, final StendhalClient client) { super(owner, true); this.client = client; initializeComponent(); WindowUtils.closeOnEscape(this); } /** * Create the dialog contents. */ private void initializeComponent() { this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (getOwner() == null) { System.exit(0); } getOwner().setEnabled(true); dispose(); } }); JLabel l; this.setTitle("Login to Server"); this.setResizable(false); // // contentPane // JComponent contentPane = (JComponent) getContentPane(); contentPane.setLayout(new GridBagLayout()); final int pad = SBoxLayout.COMMON_PADDING; contentPane.setBorder(BorderFactory.createEmptyBorder(pad, pad, pad, pad)); final GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.LINE_START; /* * Profiles */ l = new JLabel("Account profiles"); c.insets = new Insets(4, 4, 15, 4); // column c.gridx = 0; // row c.gridy = 0; contentPane.add(l, c); profilesComboBox = new JComboBox(); profilesComboBox.addActionListener(new ProfilesCB()); /* * Remove profile button */ removeButton = createRemoveButton(); // Container for the profiles list and the remove button JComponent box = SBoxLayout.createContainer(SBoxLayout.HORIZONTAL, pad); profilesComboBox.setAlignmentY(Component.CENTER_ALIGNMENT); box.add(profilesComboBox); box.add(removeButton); c.gridx = 1; c.gridy = 0; c.fill = GridBagConstraints.BOTH; contentPane.add(box, c); /* * Server Host */ l = new JLabel("Server name"); c.insets = new Insets(4, 4, 4, 4); // column c.gridx = 0; // row c.gridy = 1; contentPane.add(l, c); serverField = new JTextField( ClientGameConfiguration.get("DEFAULT_SERVER")); c.gridx = 1; c.gridy = 1; c.fill = GridBagConstraints.BOTH; contentPane.add(serverField, c); /* * Server Port */ l = new JLabel("Server port"); c.insets = new Insets(4, 4, 4, 4); c.gridx = 0; c.gridy = 2; contentPane.add(l, c); serverPortField = new JTextField( ClientGameConfiguration.get("DEFAULT_PORT")); c.gridx = 1; c.gridy = 2; c.insets = new Insets(4, 4, 4, 4); c.fill = GridBagConstraints.BOTH; contentPane.add(serverPortField, c); /* * Username */ l = new JLabel("Type your username"); c.insets = new Insets(4, 4, 4, 4); c.gridx = 0; c.gridy = 3; contentPane.add(l, c); usernameField = new JTextField(); c.gridx = 1; c.gridy = 3; c.fill = GridBagConstraints.BOTH; contentPane.add(usernameField, c); /* * Password */ l = new JLabel("Type your password"); c.gridx = 0; c.gridy = 4; c.fill = GridBagConstraints.NONE; contentPane.add(l, c); passwordField = new JPasswordField(); c.gridx = 1; c.gridy = 4; c.fill = GridBagConstraints.BOTH; contentPane.add(passwordField, c); /* * Save Profile/Login */ saveLoginBox = new JCheckBox("Save login profile locally"); saveLoginBox.setSelected(false); c.gridx = 0; c.gridy = 5; c.fill = GridBagConstraints.NONE; contentPane.add(saveLoginBox, c); /* * Save Profile Password */ savePasswordBox = new JCheckBox("Save password"); savePasswordBox.setSelected(true); savePasswordBox.setEnabled(false); c.gridx = 0; c.gridy = 6; c.fill = GridBagConstraints.NONE; c.insets = new Insets(0, 20, 0, 0); contentPane.add(savePasswordBox, c); loginButton = new JButton(); loginButton.setText("Login to Server"); loginButton.setMnemonic(KeyEvent.VK_L); this.rootPane.setDefaultButton(loginButton); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { loginButtonActionPerformed(); } }); c.gridx = 1; c.gridy = 5; c.gridheight = 2; c.anchor = GridBagConstraints.CENTER; c.insets = new Insets(15, 4, 4, 4); contentPane.add(loginButton, c); // Before loading profiles so that we can catch the data filled from // there bindEditListener(); /* * Load saved profiles */ profiles = loadProfiles(); populateProfiles(profiles); /* * Add this callback after everything is initialized */ saveLoginBox.addChangeListener(new SaveProfileStateCB()); // // Dialog // this.pack(); usernameField.requestFocusInWindow(); if (getOwner() != null) { getOwner().setEnabled(false); this.setLocationRelativeTo(getOwner()); } } /** * Prepare the field validator and bind it to the relevant text fields. */ private void bindEditListener() { fieldValidator = new DataValidator(loginButton, serverField.getDocument(), serverPortField.getDocument(), usernameField.getDocument(), passwordField.getDocument()); } /** * Create the remove character button. * * @return JButton */ private JButton createRemoveButton() { final URL url = DataLoader.getResource("data/gui/trash.png"); ImageIcon icon = new ImageIcon(url); JButton button = new JButton(icon); // Clear the margins that buttons normally add button.setMargin(new Insets(0, 0, 0, 0)); button.setToolTipText("Remove the selected account from the list"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { removeButtonActionPerformed(); } }); return button; } /** * Called when the login button is activated. */ private void loginButtonActionPerformed() { // If this window isn't enabled, we shouldn't act. if (!isEnabled()) { return; } setEnabled(false); Profile profile; profile = new Profile(); profile.setHost((serverField.getText()).trim()); try { profile.setPort(Integer.parseInt(serverPortField.getText().trim())); // Support for saving port number. Only save when input is a number // intensifly@gmx.com } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(this, "That is not a valid port number. Please try again.", "Invalid port", JOptionPane.WARNING_MESSAGE); return; } profile.setUser(usernameField.getText().trim()); profile.setPassword(new String(passwordField.getPassword())); /* * Save profile? */ if (saveLoginBox.isSelected()) { profiles.add(profile); populateProfiles(profiles); if (savePasswordBox.isSelected()) { saveProfiles(profiles); } else { final String pw = profile.getPassword(); profile.setPassword(""); saveProfiles(profiles); profile.setPassword(pw); } } /* * Run the connection procces in separate thread. added by TheGeneral */ final Thread t = new Thread(new ConnectRunnable(profile), "Login"); t.start(); } /** * Called when the remove profile button is activated. */ private void removeButtonActionPerformed() { // If this window isn't enabled, we shouldn't act. if (!isEnabled() || (profiles.profiles.size() == 0)) { return; } setEnabled(false); Profile profile; profile = (Profile) profilesComboBox.getSelectedItem(); Object[] options = { "Remove", "Cancel" }; Integer confirmRemoveProfile = JOptionPane.showOptionDialog(this, "This will permanently remove a user profile from your local list of accounts.\n" + "It will not delete an account on any servers.\n" + "Are you sure you want to remove \'" + profile.getUser() + "@" + profile.getHost() + "\' profile?", "Remove user profile from local list of accounts", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (confirmRemoveProfile == 0) { profiles.remove(profile); saveProfiles(profiles); profiles = loadProfiles(); populateProfiles(profiles); } setEnabled(true); } @Override public void setEnabled(final boolean b) { super.setEnabled(b); // Enabling login button is conditional fieldValidator.revalidate(); removeButton.setEnabled(b); } /** * Connect to a server using a given profile. * * @param profile profile used for login */ public void connect(final Profile profile) { // We are not in EDT SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar = new ProgressBar(LoginDialog.this); progressBar.start(); } }); try { client.connect(profile.getHost(), profile.getPort()); // for each major connection milestone call step(). progressBar is // created in EDT, so it is not guaranteed non null in the main // thread. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.step(); } }); } catch (final Exception ex) { // if something goes horribly just cancel the progressbar SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.cancel(); setEnabled(true); } }); String message = "unable to connect to server"; if (profile != null) { message = message + " " + profile.getHost() + ":" + profile.getPort(); } else { message = message + ", because profile was null"; } Logger.getLogger(LoginDialog.class).error(message, ex); handleError("Unable to connect to server. Did you misspell the server name?", "Connection failed"); return; } try { client.setAccountUsername(profile.getUser()); client.setCharacter(profile.getCharacter()); client.login(profile.getUser(), profile.getPassword(), profile.getSeed()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.finish(); // workaround near failures in AWT at openjdk (tested on openjdk-1.6.0.0) try { setVisible(false); } catch (NullPointerException npe) { Logger.getLogger(LoginDialog.class).error("Error probably related to bug in JRE occured", npe); LoginDialog.this.dispose(); } } }); } catch (final InvalidVersionException e) { handleError("You are running an incompatible version of Stendhal. Please update", "Invalid version"); } catch (final TimeoutException e) { handleError("Server is not available right now.\nThe server may be down or, if you are using a custom server,\nyou may have entered its name and port number incorrectly.", "Error Logging In"); } catch (final LoginFailedException e) { handleError(e.getMessage(), "Login failed"); if (e.getReason() == MessageS2CLoginNACK.Reasons.SEED_WRONG) { System.exit(1); } } catch (final BannedAddressException e) { handleError("Your IP is banned. If you think this is not right, please send a Support Request to http://sourceforge.net/tracker/?func=add&group_id=1111&atid=201111", "IP Banned"); } } /** * Displays the error message, removes the progress bar and * either enabled the login dialog in interactive mode or exits * the client in non interactive mode. * * @param errorMessage error message * @param errorTitle title of error dialog box */ private void handleError(final String errorMessage, final String errorTitle) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.cancel(); JOptionPane.showMessageDialog( LoginDialog.this, errorMessage, errorTitle, JOptionPane.ERROR_MESSAGE); if (isVisible()) { setEnabled(true); } else { // Hack for non interactive login System.exit(1); } } }); } /** * Load saves profiles. * @return ProfileList */ private ProfileList loadProfiles() { final ProfileList tmpProfiles = new ProfileList(); try { final InputStream is = Persistence.get().getInputStream(false, stendhal.getGameFolder(), "user.dat"); try { tmpProfiles.load(is); } finally { is.close(); } } catch (final FileNotFoundException fnfe) { // Ignore } catch (final IOException ioex) { JOptionPane.showMessageDialog(this, "An error occurred while loading your login information", "Error Loading Login Information", JOptionPane.WARNING_MESSAGE); } return tmpProfiles; } /** * Populate the profiles combobox and select the default. * * @param profiles profile data */ private void populateProfiles(final ProfileList profiles) { profilesComboBox.removeAllItems(); for (Profile p : profiles) { profilesComboBox.addItem(p); } /* * The last profile (if any) is the default. */ final int count = profilesComboBox.getItemCount(); if (count != 0) { profilesComboBox.setSelectedIndex(count - 1); } } /** * Called when a profile selection is changed. */ private void profilesCB() { Profile profile; String host; profile = (Profile) profilesComboBox.getSelectedItem(); if (profile != null) { host = profile.getHost(); serverField.setText(host); serverPortField.setText(String.valueOf(profile.getPort())); usernameField.setText(profile.getUser()); passwordField.setText(profile.getPassword()); } else { serverPortField.setText(String.valueOf(Profile.DEFAULT_SERVER_PORT)); usernameField.setText(""); passwordField.setText(""); } } /** * Checks that a group of Documents (text fields) is not empty, and enables * or disables a JComponent on that condition. */ private static class DataValidator implements DocumentListener { private final Document[] documents; private final JComponent component; /** * Create a new DataValidator. * * @param component component to be enabled depending on the state of * documents * @param docs documents */ DataValidator(JComponent component, Document... docs) { this.component = component; documents = docs; for (Document doc : docs) { doc.addDocumentListener(this); } revalidate(); } @Override public void insertUpdate(DocumentEvent e) { revalidate(); } @Override public void removeUpdate(DocumentEvent e) { if (e.getDocument().getLength() == 0) { component.setEnabled(false); } } @Override public void changedUpdate(DocumentEvent e) { // Attribute change - ignore } /** * Do a full document state check and set the component status according * to the result. */ final void revalidate() { for (Document doc : documents) { if (doc.getLength() == 0) { component.setEnabled(false); return; } } component.setEnabled(true); } } /* * Author: Da_MusH Description: Methods for saving and loading login * information to disk. These should probably make a separate class in the * future, but it will work for now. comment: Thegeneral has added encoding * for password and username. Changed for multiple profiles. */ private void saveProfiles(final ProfileList profiles) { try { final OutputStream os = Persistence.get().getOutputStream(false, stendhal.getGameFolder(), "user.dat"); try { profiles.save(os); } finally { os.close(); } } catch (final IOException ioex) { JOptionPane.showMessageDialog(this, "An error occurred while saving your login information", "Error Saving Login Information", JOptionPane.WARNING_MESSAGE); } } /** * Called when save profile selection change. */ private void saveProfileStateCB() { savePasswordBox.setEnabled(saveLoginBox.isSelected()); } /** * Server connect thread runnable. */ private final class ConnectRunnable implements Runnable { private final Profile profile; /** * Create a new ConnectRunnable. * * @param profile profile used for connection */ private ConnectRunnable(final Profile profile) { this.profile = profile; } @Override public void run() { connect(profile); } } /** * Profiles combobox selection change listener. */ private class ProfilesCB implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { profilesCB(); } } /** * Save profile selection change. */ private class SaveProfileStateCB implements ChangeListener { @Override public void stateChanged(final ChangeEvent ev) { saveProfileStateCB(); } } }
dkfellows/stendhal
src/games/stendhal/client/gui/login/LoginDialog.java
Java
gpl-2.0
19,502
# -- coding: utf-8 -- # Das Modul argv aus Packet sys wird importiert from sys import argv # Die Variablen script und filename werden entpackt # sie müssen dem Script als Argumente mitgegeben werden beim ausführen # z.B so: python ex15_reading_files.py ex15_sample.txt script, filename = argv # Der Inhalt der Datei ex15_sample.txt, der # dem Script beim Ausführen als Argument mitgegeben wurde, # wird in die Variable txt geschrieben txt = open(filename) # Der Dateiname von ex15_sample.txt wird ausgegeben print "Here's your file %r:" % filename # Der Inhalt von txt (und damit der Inhalt von ex15_sample.txt) wird ausgegeben print txt.read() # Man könnte denken, dass man es auch so machen könnte ... # print 'ex15_sample.txt'.read() # aber das geht NICHT, weil # String kein Attribut read haben!!! # AttributeError: 'str' object has no attribute 'read' print "Type the filename again:" # neue Eingabeaufforderung, dadurch wird der Inhalt der Datei (deren Namen man eingibt) # in die Variable file_again geschrieben file_again = open(raw_input("> ")) # Der Inhalt von file_again wird ausgegeben print file_again.read(), 'geht!!!' # Inhalt von ex15_sample.txt wird in die Variable txt_again geschrieben txt_again = open('ex15_sample.txt') # Inhalt von txt_again wird ausgegeben print txt_again.read(), 'das geht auch'
Tset-Noitamotua/_learnpython
LearnPythonTheHardWay/ex15_reading_files.py
Python
gpl-2.0
1,354
<?php /** * @package Joomla.Administrator * @subpackage com_helloworld * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access to this file defined('_JEXEC') or die; ?> <?php echo "<pre>"; //print_r($this->trademarkCompleted); echo "</pre>"; ?> <div class="sfContainer"> <div class="sfGrids"> <div class="sfGrid-Col-3"> <div class="sfGrids"> <div class="sfGrid-Col-12"> <?php BusinessServicesHelpersHelper::menu($this->menu); ?> <div id="datepicker"></div> </div> </div> </div> <div class="sfGrid-Col-9"> <h3>My Completed Sevices</h3> <div class="sfGrids"> <div class="sfGrid-Col-12"> <div class="sfGrids"> <div class="sfGrid-Col-10 col-centered"> <div class="sfGrids col-bordered"> <?php if(count($this->trademarkCompleted)): ?> <table> <thead> <tr> <th>Registerd ID</th> <th>Service Name</th> <th>Applied On</th> <th>Comment</th> <th></th> </tr> </thead> <tbody> <?php foreach ($this->trademarkCompleted as $service){ ?> <tr> <td><?php echo "$service->register_id"; ?></td> <td><?php echo $this->service_name[$service->service_flag]; ?></td> <td></td> <td><?php echo "$service->date_created"; ?></td> <td><a href="#">Go to</a></td> </tr> <?php } ?> </tbody> </table> <?php endif; ?> </div> </div> </div> </div> </div> </div> </div> </div>
ankibalyan/businesssetup
components/com_businessservices/views/businessservices/tmpl/cservices.php
PHP
gpl-2.0
1,713
<?php /** * Updates installable extension server API interface. * * @package WordPoints * @since 2.4.0 */ /** * Interface for a remote API offering extension updates that are auto-installable. * * @since 2.4.0 */ interface WordPoints_Extension_Server_API_Updates_InstallableI extends WordPoints_Extension_Server_API_UpdatesI { /** * Gets the URL of the zip package for the latest version of an extension. * * @since 2.4.0 * * @param WordPoints_Extension_Server_API_Extension_DataI $extension_data The extension data. * * @return string The package URL. */ public function get_extension_package_url( WordPoints_Extension_Server_API_Extension_DataI $extension_data ); } // EOF
WordPoints/wordpoints
src/classes/extension/server/api/updates/installablei.php
PHP
gpl-2.0
713
<?php /** * Web1.0MPC\Mpd - a PHP interface to MPD (Music Player Daemon). * Copyright (C) 2011-2014 Marcus Geuecke (web10mpc [at] geuecke [dot] org) * * 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; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @copyright Copyright (C) 2011-2014 Marcus Geuecke (web10mpc [at] geuecke [dot] org) * @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2 or later */ namespace Web10Mpc\Mpd; /** * Exception thrown if MPD database is in an unexpected state. * * This can be used by clients if certain requirements on file tags are not met, * for example inconsistent mapping of "artist" to "artistsort" tags. */ class MpdDatabaseException extends MpdException { } ?>
mgi/web10mpc
class/Web10Mpc/Mpd/MpdDatabaseException.php
PHP
gpl-2.0
1,359
/* * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.security; import ikvm.internal.CallerID; import sun.misc.Unsafe; import sun.security.util.Debug; /** * <p> The AccessController class is used for access control operations * and decisions. * * <p> More specifically, the AccessController class is used for * three purposes: * * <ul> * <li> to decide whether an access to a critical system * resource is to be allowed or denied, based on the security policy * currently in effect,<p> * <li>to mark code as being "privileged", thus affecting subsequent * access determinations, and<p> * <li>to obtain a "snapshot" of the current calling context so * access-control decisions from a different context can be made with * respect to the saved context. </ul> * * <p> The {@link #checkPermission(Permission) checkPermission} method * determines whether the access request indicated by a specified * permission should be granted or denied. A sample call appears * below. In this example, <code>checkPermission</code> will determine * whether or not to grant "read" access to the file named "testFile" in * the "/temp" directory. * * <pre> * * FilePermission perm = new FilePermission("/temp/testFile", "read"); * AccessController.checkPermission(perm); * * </pre> * * <p> If a requested access is allowed, * <code>checkPermission</code> returns quietly. If denied, an * AccessControlException is * thrown. AccessControlException can also be thrown if the requested * permission is of an incorrect type or contains an invalid value. * Such information is given whenever possible. * * Suppose the current thread traversed m callers, in the order of caller 1 * to caller 2 to caller m. Then caller m invoked the * <code>checkPermission</code> method. * The <code>checkPermission </code>method determines whether access * is granted or denied based on the following algorithm: * * <pre> {@code * for (int i = m; i > 0; i--) { * * if (caller i's domain does not have the permission) * throw AccessControlException * * else if (caller i is marked as privileged) { * if (a context was specified in the call to doPrivileged) * context.checkPermission(permission) * return; * } * }; * * // Next, check the context inherited when the thread was created. * // Whenever a new thread is created, the AccessControlContext at * // that time is stored and associated with the new thread, as the * // "inherited" context. * * inheritedContext.checkPermission(permission); * }</pre> * * <p> A caller can be marked as being "privileged" * (see {@link #doPrivileged(PrivilegedAction) doPrivileged} and below). * When making access control decisions, the <code>checkPermission</code> * method stops checking if it reaches a caller that * was marked as "privileged" via a <code>doPrivileged</code> * call without a context argument (see below for information about a * context argument). If that caller's domain has the * specified permission, no further checking is done and * <code>checkPermission</code> * returns quietly, indicating that the requested access is allowed. * If that domain does not have the specified permission, an exception * is thrown, as usual. * * <p> The normal use of the "privileged" feature is as follows. If you * don't need to return a value from within the "privileged" block, do * the following: * * <pre> {@code * somemethod() { * ...normal code here... * AccessController.doPrivileged(new PrivilegedAction<Void>() { * public Void run() { * // privileged code goes here, for example: * System.loadLibrary("awt"); * return null; // nothing to return * } * }); * ...normal code here... * }}</pre> * * <p> * PrivilegedAction is an interface with a single method, named * <code>run</code>. * The above example shows creation of an implementation * of that interface; a concrete implementation of the * <code>run</code> method is supplied. * When the call to <code>doPrivileged</code> is made, an * instance of the PrivilegedAction implementation is passed * to it. The <code>doPrivileged</code> method calls the * <code>run</code> method from the PrivilegedAction * implementation after enabling privileges, and returns the * <code>run</code> method's return value as the * <code>doPrivileged</code> return value (which is * ignored in this example). * * <p> If you need to return a value, you can do something like the following: * * <pre> {@code * somemethod() { * ...normal code here... * String user = AccessController.doPrivileged( * new PrivilegedAction<String>() { * public String run() { * return System.getProperty("user.name"); * } * }); * ...normal code here... * }}</pre> * * <p>If the action performed in your <code>run</code> method could * throw a "checked" exception (those listed in the <code>throws</code> clause * of a method), then you need to use the * <code>PrivilegedExceptionAction</code> interface instead of the * <code>PrivilegedAction</code> interface: * * <pre> {@code * somemethod() throws FileNotFoundException { * ...normal code here... * try { * FileInputStream fis = AccessController.doPrivileged( * new PrivilegedExceptionAction<FileInputStream>() { * public FileInputStream run() throws FileNotFoundException { * return new FileInputStream("someFile"); * } * }); * } catch (PrivilegedActionException e) { * // e.getException() should be an instance of FileNotFoundException, * // as only "checked" exceptions will be "wrapped" in a * // PrivilegedActionException. * throw (FileNotFoundException) e.getException(); * } * ...normal code here... * }}</pre> * * <p> Be *very* careful in your use of the "privileged" construct, and * always remember to make the privileged code section as small as possible. * * <p> Note that <code>checkPermission</code> always performs security checks * within the context of the currently executing thread. * Sometimes a security check that should be made within a given context * will actually need to be done from within a * <i>different</i> context (for example, from within a worker thread). * The {@link #getContext() getContext} method and * AccessControlContext class are provided * for this situation. The <code>getContext</code> method takes a "snapshot" * of the current calling context, and places * it in an AccessControlContext object, which it returns. A sample call is * the following: * * <pre> * * AccessControlContext acc = AccessController.getContext() * * </pre> * * <p> * AccessControlContext itself has a <code>checkPermission</code> method * that makes access decisions based on the context <i>it</i> encapsulates, * rather than that of the current execution thread. * Code within a different context can thus call that method on the * previously-saved AccessControlContext object. A sample call is the * following: * * <pre> * * acc.checkPermission(permission) * * </pre> * * <p> There are also times where you don't know a priori which permissions * to check the context against. In these cases you can use the * doPrivileged method that takes a context: * * <pre> {@code * somemethod() { * AccessController.doPrivileged(new PrivilegedAction<Object>() { * public Object run() { * // Code goes here. Any permission checks within this * // run method will require that the intersection of the * // callers protection domain and the snapshot's * // context have the desired permission. * } * }, acc); * ...normal code here... * }}</pre> * * @see AccessControlContext * * @author Li Gong * @author Roland Schemers */ public final class AccessController { @cli.System.ThreadStaticAttribute.Annotation private static PrivilegedElement privileged_stack_top; private static final class PrivilegedElement { CallerID callerID; AccessControlContext context; } private static Object doPrivileged(Object action, AccessControlContext context, CallerID callerID) { PrivilegedElement savedPrivilegedElement = privileged_stack_top; try { PrivilegedElement pi = new PrivilegedElement(); pi.callerID = callerID; pi.context = context; privileged_stack_top = pi; try { if (action instanceof PrivilegedAction) { return ((PrivilegedAction)action).run(); } else { return ((PrivilegedExceptionAction)action).run(); } } catch (Exception x) { if (!(x instanceof RuntimeException)) { Unsafe.getUnsafe().throwException(new PrivilegedActionException(x)); } throw (RuntimeException)x; } } finally { privileged_stack_top = savedPrivilegedElement; } } /** * Don't allow anyone to instantiate an AccessController */ private AccessController() { } /** * Performs the specified <code>PrivilegedAction</code> with privileges * enabled. The action is performed with <i>all</i> of the permissions * possessed by the caller's protection domain. * * <p> If the action's <code>run</code> method throws an (unchecked) * exception, it will propagate through this method. * * <p> Note that any DomainCombiner associated with the current * AccessControlContext will be ignored while the action is performed. * * @param action the action to be performed. * * @return the value returned by the action's <code>run</code> method. * * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction,AccessControlContext) * @see #doPrivileged(PrivilegedExceptionAction) * @see #doPrivilegedWithCombiner(PrivilegedAction) * @see java.security.DomainCombiner */ @ikvm.internal.HasCallerID public static <T> T doPrivileged(PrivilegedAction<T> action) { return (T)doPrivileged(action, null, CallerID.getCallerID()); } /** * Performs the specified <code>PrivilegedAction</code> with privileges * enabled. The action is performed with <i>all</i> of the permissions * possessed by the caller's protection domain. * * <p> If the action's <code>run</code> method throws an (unchecked) * exception, it will propagate through this method. * * <p> This method preserves the current AccessControlContext's * DomainCombiner (which may be null) while the action is performed. * * @param action the action to be performed. * * @return the value returned by the action's <code>run</code> method. * * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see java.security.DomainCombiner * * @since 1.6 */ public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action) { DomainCombiner dc = null; AccessControlContext acc = getStackAccessControlContext(); if (acc == null || (dc = acc.getAssignedCombiner()) == null) { return AccessController.doPrivileged(action); } return AccessController.doPrivileged(action, preserveCombiner(dc)); } /** * Performs the specified <code>PrivilegedAction</code> with privileges * enabled and restricted by the specified * <code>AccessControlContext</code>. * The action is performed with the intersection of the permissions * possessed by the caller's protection domain, and those possessed * by the domains represented by the specified * <code>AccessControlContext</code>. * <p> * If the action's <code>run</code> method throws an (unchecked) exception, * it will propagate through this method. * * @param action the action to be performed. * @param context an <i>access control context</i> * representing the restriction to be applied to the * caller's domain's privileges before performing * the specified action. If the context is * <code>null</code>, * then no additional restriction is applied. * * @return the value returned by the action's <code>run</code> method. * * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext) */ @ikvm.internal.HasCallerID public static <T> T doPrivileged(PrivilegedAction<T> action, AccessControlContext context) { return (T)doPrivileged(action, context, CallerID.getCallerID()); } /** * Performs the specified <code>PrivilegedExceptionAction</code> with * privileges enabled. The action is performed with <i>all</i> of the * permissions possessed by the caller's protection domain. * * <p> If the action's <code>run</code> method throws an <i>unchecked</i> * exception, it will propagate through this method. * * <p> Note that any DomainCombiner associated with the current * AccessControlContext will be ignored while the action is performed. * * @param action the action to be performed * * @return the value returned by the action's <code>run</code> method * * @exception PrivilegedActionException if the specified action's * <code>run</code> method threw a <i>checked</i> exception * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext) * @see #doPrivilegedWithCombiner(PrivilegedExceptionAction) * @see java.security.DomainCombiner */ @ikvm.internal.HasCallerID public static <T> T doPrivileged(PrivilegedExceptionAction<T> action) throws PrivilegedActionException { return (T)doPrivileged(action, null, CallerID.getCallerID()); } /** * Performs the specified <code>PrivilegedExceptionAction</code> with * privileges enabled. The action is performed with <i>all</i> of the * permissions possessed by the caller's protection domain. * * <p> If the action's <code>run</code> method throws an <i>unchecked</i> * exception, it will propagate through this method. * * <p> This method preserves the current AccessControlContext's * DomainCombiner (which may be null) while the action is performed. * * @param action the action to be performed. * * @return the value returned by the action's <code>run</code> method * * @exception PrivilegedActionException if the specified action's * <code>run</code> method threw a <i>checked</i> exception * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext) * @see java.security.DomainCombiner * * @since 1.6 */ public static <T> T doPrivilegedWithCombiner (PrivilegedExceptionAction<T> action) throws PrivilegedActionException { DomainCombiner dc = null; AccessControlContext acc = getStackAccessControlContext(); if (acc == null || (dc = acc.getAssignedCombiner()) == null) { return AccessController.doPrivileged(action); } return AccessController.doPrivileged(action, preserveCombiner(dc)); } /** * preserve the combiner across the doPrivileged call */ private static AccessControlContext preserveCombiner (DomainCombiner combiner) { /** * callerClass[0] = Reflection.getCallerClass * callerClass[1] = AccessController.preserveCombiner * callerClass[2] = AccessController.doPrivileged * callerClass[3] = caller */ final Class callerClass = sun.reflect.Reflection.getCallerClass(3); ProtectionDomain callerPd = doPrivileged (new PrivilegedAction<ProtectionDomain>() { public ProtectionDomain run() { return callerClass.getProtectionDomain(); } }); // perform 'combine' on the caller of doPrivileged, // even if the caller is from the bootclasspath ProtectionDomain[] pds = new ProtectionDomain[] {callerPd}; return new AccessControlContext(combiner.combine(pds, null), combiner); } /** * Performs the specified <code>PrivilegedExceptionAction</code> with * privileges enabled and restricted by the specified * <code>AccessControlContext</code>. The action is performed with the * intersection of the the permissions possessed by the caller's * protection domain, and those possessed by the domains represented by the * specified <code>AccessControlContext</code>. * <p> * If the action's <code>run</code> method throws an <i>unchecked</i> * exception, it will propagate through this method. * * @param action the action to be performed * @param context an <i>access control context</i> * representing the restriction to be applied to the * caller's domain's privileges before performing * the specified action. If the context is * <code>null</code>, * then no additional restriction is applied. * * @return the value returned by the action's <code>run</code> method * * @exception PrivilegedActionException if the specified action's * <code>run</code> method * threw a <i>checked</i> exception * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext) */ @ikvm.internal.HasCallerID public static <T> T doPrivileged(PrivilegedExceptionAction<T> action, AccessControlContext context) throws PrivilegedActionException { return (T)doPrivileged(action, context, CallerID.getCallerID()); } /** * Returns the AccessControl context. i.e., it gets * the protection domains of all the callers on the stack, * starting at the first class with a non-null * ProtectionDomain. * * @return the access control context based on the current stack or * null if there was only privileged system code. */ private static AccessControlContext getStackAccessControlContext() { AccessControlContext context = null; CallerID callerID = null; PrivilegedElement pi = privileged_stack_top; if (pi != null) { context = pi.context; callerID = pi.callerID; } return getStackAccessControlContext(context, callerID); } private static native AccessControlContext getStackAccessControlContext(AccessControlContext context, CallerID callerID); /** * Returns the "inherited" AccessControl context. This is the context * that existed when the thread was created. Package private so * AccessControlContext can use it. */ static native AccessControlContext getInheritedAccessControlContext(); /** * This method takes a "snapshot" of the current calling context, which * includes the current Thread's inherited AccessControlContext, * and places it in an AccessControlContext object. This context may then * be checked at a later point, possibly in another thread. * * @see AccessControlContext * * @return the AccessControlContext based on the current context. */ public static AccessControlContext getContext() { AccessControlContext acc = getStackAccessControlContext(); if (acc == null) { // all we had was privileged system code. We don't want // to return null though, so we construct a real ACC. return new AccessControlContext(null, true); } else { return acc.optimize(); } } /** * Determines whether the access request indicated by the * specified permission should be allowed or denied, based on * the current AccessControlContext and security policy. * This method quietly returns if the access request * is permitted, or throws a suitable AccessControlException otherwise. * * @param perm the requested permission. * * @exception AccessControlException if the specified permission * is not permitted, based on the current security policy. * @exception NullPointerException if the specified permission * is <code>null</code> and is checked based on the * security policy currently in effect. */ public static void checkPermission(Permission perm) throws AccessControlException { //System.err.println("checkPermission "+perm); //Thread.currentThread().dumpStack(); if (perm == null) { throw new NullPointerException("permission can't be null"); } AccessControlContext stack = getStackAccessControlContext(); // if context is null, we had privileged system code on the stack. if (stack == null) { Debug debug = AccessControlContext.getDebug(); boolean dumpDebug = false; if (debug != null) { dumpDebug = !Debug.isOn("codebase="); dumpDebug &= !Debug.isOn("permission=") || Debug.isOn("permission=" + perm.getClass().getCanonicalName()); } if (dumpDebug && Debug.isOn("stack")) { Thread.currentThread().dumpStack(); } if (dumpDebug && Debug.isOn("domain")) { debug.println("domain (context is null)"); } if (dumpDebug) { debug.println("access allowed "+perm); } return; } AccessControlContext acc = stack.optimize(); acc.checkPermission(perm); } }
mdavid/IKVM.NET-cvs-clone
openjdk/java/security/AccessController.java
Java
gpl-2.0
23,993
<?php $allTabs = apply_filters( 'tribe_settings_all_tabs', array() ); $networkTab = array( 'priority' => 10, 'network_admin' => true, 'fields' => apply_filters( 'tribe_network_settings_tab_fields', array( 'info-start' => array( 'type' => 'html', 'html' => '<div id="modern-tribe-info">', ), 'info-box-title' => array( 'type' => 'html', 'html' => '<h1>' . esc_html__( 'Network Settings', 'the-events-calendar' ) . '</h1>', ), 'info-box-description' => array( 'type' => 'html', 'html' => '<p>' . esc_html__( 'This is where all of the global network settings for Modern Tribe\'s The Events Calendar can be modified.', 'the-events-calendar' ) . '</p>', ), 'info-end' => array( 'type' => 'html', 'html' => '</div>', ), 'hideSettingsTabs' => array( 'type' => 'checkbox_list', 'label' => esc_html__( 'Hide the following settings tabs on every site:', 'the-events-calendar' ), 'default' => false, 'options' => $allTabs, 'validation_type' => 'options_multi', 'can_be_empty' => true, ), ) ) );
casedot/AllYourBaseTemplate
wp-content/plugins/the-events-calendar/src/admin-views/tribe-options-network.php
PHP
gpl-2.0
1,198
/* * copyright (C) 2013 Christian P Rasmussen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cprasmu.rascam.camera.model; public enum MeteringMode { AVERAGE (0,"average","Average"), SPOT (1,"spot","Spot"), BACKLIT (2,"backlit","Backlit"), MATRIX (3,"matrix","Matrix"); public int mode; public String name; public String displayName; private MeteringMode(int mode, String name,String displayName) { this.mode = mode; this.name = name; this.displayName=displayName; } public static MeteringMode fromInt(int code) { switch(code) { case 0: return AVERAGE; case 1: return SPOT; case 2: return BACKLIT; case 3: return MATRIX; } return null; } public MeteringMode next(){ if(this.equals(AVERAGE)){ return SPOT; } else if(this.equals(SPOT)){ return BACKLIT; } else if(this.equals(BACKLIT)){ return MATRIX; } else if(this.equals(MATRIX)){ return AVERAGE; } else { return null; } } public MeteringMode previous(){ if(this.equals(MATRIX)){ return BACKLIT; } else if(this.equals(BACKLIT)){ return SPOT; } else if(this.equals(SPOT)){ return AVERAGE; } else if(this.equals(AVERAGE)){ return MATRIX; } else { return null; } } }
cprasmu/RasCam-Server
src/cprasmu/rascam/camera/model/MeteringMode.java
Java
gpl-2.0
1,840
$(document).ready(function(){ createCaroussel($('div[data-caroussel=caroussel]')); setVisibleInCaroussel($('div[data-caroussel=caroussel]'), 0); setAutoChange($('div[data-caroussel=caroussel]')); }); function createCaroussel(carousselElement){ carousselElement.append('<div class="caroussel"></div>'); carousselElement.append('<div class="caroussel-pin-wrapper"></div>'); var pins = carousselElement.find('.caroussel-pin-wrapper'); var data = carousselElement.find('[data-caroussel=data]'); data.hide(); // ADD EACH IMAGE FROM DATA data.children('span[data-url]').each(function(){ $(this).closest('div[data-caroussel=caroussel]').find('.caroussel').append('<div class="caroussel-img-wrapper"><img src="'+$(this).attr('data-url')+'"/></div>'); if ($(this).parent().attr('data-caroussel-pin') != 'false') $(this).closest('div[data-caroussel=caroussel]').find('.caroussel-pin-wrapper').append('<div class="caroussel-pin"></div>'); }); // COUNT THE NUMBER OF IMAGES AND MEMORIZE DELAY AND COUNT carousselElement.each(function(){ $(this).attr('data-nbr-images', $(this).find('.caroussel-img-wrapper').length); var delay = parseInt($(this).find('[data-caroussel=data]').attr('data-caroussel-delay')); if (delay){ $(this).attr('data-delay', delay); // ADD A PROGRESS INDICATOR ON THE IMAGE if ($(this).find('[data-caroussel=data]').attr('data-caroussel-progress-bar') == 'true') $(this).find('.caroussel').append('<div class="caroussel-progress-bar"></div>'); $(window).resize(function(e){ adjustProgressBar($('div[data-caroussel=caroussel]')); }); } }); // ADD EVENT HANDLER ON PINS pins.find('.caroussel-pin').click(function(e){ setVisibleInCaroussel($(this).closest('div[data-caroussel=caroussel]'), $(this).index()); setAutoChange($(this).closest('div[data-caroussel=caroussel]')); }); // ADD CLICK EVENT ON PHOTOS carousselElement.find('.caroussel-img-wrapper img').click(function(e){ // click on right of the photo if (e.pageX < ($(this).offset().left + ($(this).width() / 4))){ var caroussel = $(this).closest('div[data-caroussel=caroussel]'); decreaseVisibleInCaroussel(caroussel); setAutoChange(caroussel); } else if (e.pageX > ($(this).offset().left + (3 * ($(this).width() / 4)))){ var caroussel = $(this).closest('div[data-caroussel=caroussel]'); increaseVisibleInCaroussel(caroussel); setAutoChange(caroussel); } }); } function setAutoChange(carousselElement){ // SET AUTOMATIC FUNCTION carousselElement.each(function(){ var caroussel = $(this); if (parseInt(caroussel.attr('data-delay'))){ // IF A LOOP FUNCTION IS ALREADY ATTACHED, WE CLOSE IT if (parseInt(caroussel.attr('data-interval-function'))) clearInterval(parseInt(caroussel.attr('data-interval-function'))); if (parseInt(caroussel.attr('data-interval-function-progress-bar'))) clearInterval(parseInt(caroussel.attr('data-interval-function-progress-bar'))); // WE LAUNCH A LOOP FUNCTION TO CHANGE THE IMAGE caroussel.attr('data-interval-function', setInterval(function(){ increaseVisibleInCaroussel(caroussel); }, parseInt(caroussel.attr('data-delay')))); // WE LAUNCH A LOOP FUNCTION TO CHANGE THE PROGRESS BAR if (caroussel.find('[data-caroussel=data]').attr('data-caroussel-progress-bar') == 'true'){ var nbrOfRefreshRequired = parseInt(caroussel.attr('data-delay')) / 40; caroussel.attr('data-interval-function-progress-bar', setInterval(function(){ var progressBar = caroussel.find('.caroussel-progress-bar'); progressBar.css('width', Math.min(progressBar.width() + parseInt(progressBar.attr('data-width'))/nbrOfRefreshRequired, parseInt(progressBar.attr('data-width')))); }, 39)); } } }); } function increaseVisibleInCaroussel(carousselElement){ setVisibleInCaroussel(carousselElement, (parseInt(carousselElement.attr('data-current-index'))+1) % carousselElement.attr('data-nbr-images')); } function decreaseVisibleInCaroussel(carousselElement){ var index = parseInt(carousselElement.attr('data-current-index')) - 1; if (index < 0) index = parseInt(carousselElement.attr('data-nbr-images')) + index; setVisibleInCaroussel(carousselElement, index); } function setVisibleInCaroussel(carousselElement, index){ // MEMORIZE THE INDEX carousselElement.attr('data-current-index', index); // SHOW THE IMAGE carousselElement.find('.caroussel').find('.caroussel-img-wrapper').hide(); carousselElement.find('.caroussel').find('.caroussel-img-wrapper:eq('+index+')').show(); // ACTIVE THE PIN carousselElement.find('.caroussel-pin-wrapper').find('.caroussel-pin').removeClass('active'); carousselElement.find('.caroussel-pin-wrapper').find('.caroussel-pin:eq('+index+')').addClass('active'); // INITIALIZE THE PROGRESS BAR if (carousselElement.find('[data-caroussel=data]').attr('data-caroussel-progress-bar') == 'true'){ adjustProgressBar(carousselElement); carousselElement.find('.caroussel').each(function(){ $(this).find('.caroussel-progress-bar').css('width', 0); }); } } function adjustProgressBar(carousselElement){ carousselElement.find('.caroussel').each(function(){ var progressBar = $(this).find('.caroussel-progress-bar'); var visibleImgWrapper = $(this).find('.caroussel-img-wrapper:visible'); progressBar.css('top', visibleImgWrapper.offset().top + (visibleImgWrapper.height()*(9/10))); progressBar.css('left', visibleImgWrapper.offset().left); progressBar.css('height', visibleImgWrapper.height()/10); progressBar.attr('data-width', visibleImgWrapper.width()); }); }
Remi-Laot-CreiZyz/caroussel-jquery
caroussel.js
JavaScript
gpl-2.0
5,546
/* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* In here, we rewrite queries (to obfuscate passwords etc.) that need it before we log them. Stored procedures may also rewrite their statements (to show the actual values of their variables etc.). There is currently no scenario where a statement can be eligible for both rewrites. (see sp_instr.cc) Special consideration will need to be taken if this assertion is changed. We also do not intersect with query cache at this time, as QC only caches SELECTs (which we don't rewrite). If and when QC becomes more general, it should probably cache the rewritten query along with the user-submitted one. (see sql_parse.cc) */ #include "auth_common.h" // append_user #include "sql_parse.h" // get_current_user #include "sql_show.h" // append_identifier #include "sp_head.h" // struct set_var_base #include "rpl_slave.h" // SLAVE_SQL, SLAVE_IO /** Append a key/value pair to a string, with an optional preceeding comma. For numeric values. @param str The string to append to @param comma Prepend a comma? @param txt C-string, must end in a space @param len strlen(txt) @param val numeric value @param cond only append if this evaluates to true @retval false if any subsequent key/value pair would be the first */ bool append_int(String *str, bool comma, const char *txt, size_t len, long val, int cond) { if (cond) { String numbuf(42); if (comma) str->append(STRING_WITH_LEN(", ")); str->append(txt,len); numbuf.set((longlong)val,&my_charset_bin); str->append(numbuf); return true; } return comma; } /** Append a key/value pair to a string if the value is non-NULL, with an optional preceeding comma. @param str The string to append to @param comma Prepend a comma? @param key C-string: the key, must be non-NULL @param val C-string: the value @retval false if any subsequent key/value pair would be the first */ bool append_str(String *str, bool comma, const char *key, const char *val) { if (val) { if (comma) str->append(STRING_WITH_LEN(", ")); str->append(key); str->append(STRING_WITH_LEN(" '")); str->append(val); str->append(STRING_WITH_LEN("'")); return true; } return comma; } /** Rewrite a GRANT statement. @param thd The THD to rewrite for. @param rlb An empty String object to put the rewritten query in. */ static void mysql_rewrite_grant(THD *thd, String *rlb) { LEX *lex= thd->lex; TABLE_LIST *first_table= (TABLE_LIST*) lex->select_lex->table_list.first; bool comma= FALSE, comma_inner; String cols(1024); int c; rlb->append(STRING_WITH_LEN("GRANT ")); if (lex->all_privileges) rlb->append(STRING_WITH_LEN("ALL PRIVILEGES")); else { ulong priv; for (c= 0, priv= SELECT_ACL; priv <= GLOBAL_ACLS; c++, priv <<= 1) { if (priv == GRANT_ACL) continue; comma_inner= FALSE; if (lex->columns.elements) // show columns, if any { class LEX_COLUMN *column; List_iterator <LEX_COLUMN> column_iter(lex->columns); cols.length(0); cols.append(STRING_WITH_LEN(" (")); /* If the statement was GRANT SELECT(f2), INSERT(f3), UPDATE(f1,f3, f2), our list cols will contain the order f2, f3, f1, and thus that's the order we'll recreate the privilege: UPDATE (f2, f3, f1) */ while ((column= column_iter++)) { if (column->rights & priv) { if (comma_inner) cols.append(STRING_WITH_LEN(", ")); else comma_inner= TRUE; cols.append(column->column.ptr(),column->column.length()); } } cols.append(STRING_WITH_LEN(")")); } if (comma_inner || (lex->grant & priv)) // show privilege name { if (comma) rlb->append(STRING_WITH_LEN(", ")); else comma= TRUE; rlb->append(command_array[c],command_lengths[c]); if (!(lex->grant & priv)) // general outranks specific rlb->append(cols); } } if (!comma) // no privs, default to USAGE rlb->append(STRING_WITH_LEN("USAGE")); } rlb->append(STRING_WITH_LEN(" ON ")); switch(lex->type) { case TYPE_ENUM_PROCEDURE: rlb->append(STRING_WITH_LEN("PROCEDURE ")); break; case TYPE_ENUM_FUNCTION: rlb->append(STRING_WITH_LEN("FUNCTION ")); break; default: break; } if (first_table) { append_identifier(thd, rlb, first_table->db, strlen(first_table->db)); rlb->append(STRING_WITH_LEN(".")); append_identifier(thd, rlb, first_table->table_name, strlen(first_table->table_name)); } else { if (lex->current_select()->db) append_identifier(thd, rlb, lex->current_select()->db, strlen(lex->current_select()->db)); else rlb->append("*"); rlb->append(STRING_WITH_LEN(".*")); } rlb->append(STRING_WITH_LEN(" TO ")); { LEX_USER *user_name, *tmp_user_name; List_iterator <LEX_USER> user_list(lex->users_list); bool comma= FALSE; while ((tmp_user_name= user_list++)) { if ((user_name= get_current_user(thd, tmp_user_name))) { append_user(thd, rlb, user_name, comma, true); comma= TRUE; } } } if (lex->ssl_type != SSL_TYPE_NOT_SPECIFIED) { rlb->append(STRING_WITH_LEN(" REQUIRE")); switch (lex->ssl_type) { case SSL_TYPE_SPECIFIED: if (lex->x509_subject) { rlb->append(STRING_WITH_LEN(" SUBJECT '")); rlb->append(lex->x509_subject); rlb->append(STRING_WITH_LEN("'")); } if (lex->x509_issuer) { rlb->append(STRING_WITH_LEN(" ISSUER '")); rlb->append(lex->x509_issuer); rlb->append(STRING_WITH_LEN("'")); } if (lex->ssl_cipher) { rlb->append(STRING_WITH_LEN(" CIPHER '")); rlb->append(lex->ssl_cipher); rlb->append(STRING_WITH_LEN("'")); } break; case SSL_TYPE_X509: rlb->append(STRING_WITH_LEN(" X509")); break; case SSL_TYPE_ANY: rlb->append(STRING_WITH_LEN(" SSL")); break; case SSL_TYPE_NOT_SPECIFIED: /* fall-thru */ case SSL_TYPE_NONE: rlb->append(STRING_WITH_LEN(" NONE")); break; } } if (lex->mqh.specified_limits || (lex->grant & GRANT_ACL)) { rlb->append(STRING_WITH_LEN(" WITH")); if (lex->grant & GRANT_ACL) rlb->append(STRING_WITH_LEN(" GRANT OPTION")); append_int(rlb, false, STRING_WITH_LEN(" MAX_QUERIES_PER_HOUR "), lex->mqh.questions, lex->mqh.specified_limits & USER_RESOURCES::QUERIES_PER_HOUR); append_int(rlb, false, STRING_WITH_LEN(" MAX_UPDATES_PER_HOUR "), lex->mqh.updates, lex->mqh.specified_limits & USER_RESOURCES::UPDATES_PER_HOUR); append_int(rlb, false, STRING_WITH_LEN(" MAX_CONNECTIONS_PER_HOUR "), lex->mqh.conn_per_hour, lex->mqh.specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR); append_int(rlb, false, STRING_WITH_LEN(" MAX_USER_CONNECTIONS "), lex->mqh.user_conn, lex->mqh.specified_limits & USER_RESOURCES::USER_CONNECTIONS); } } /** Rewrite a SET statement. @param thd The THD to rewrite for. @param rlb An empty String object to put the rewritten query in. */ static void mysql_rewrite_set(THD *thd, String *rlb) { LEX *lex= thd->lex; List_iterator_fast<set_var_base> it(lex->var_list); set_var_base *var; bool comma= FALSE; rlb->append(STRING_WITH_LEN("SET ")); while ((var= it++)) { if (comma) rlb->append(STRING_WITH_LEN(",")); else comma= TRUE; var->print(thd, rlb); } } /** Rewrite CREATE USER statement. @param thd The THD to rewrite for. @param rlb An empty String object to put the rewritten query in. */ static void mysql_rewrite_create_user(THD *thd, String *rlb) { LEX *lex= thd->lex; LEX_USER *user_name, *tmp_user_name; List_iterator <LEX_USER> user_list(lex->users_list); bool comma= FALSE; rlb->append(STRING_WITH_LEN("CREATE USER ")); while ((tmp_user_name= user_list++)) { if ((user_name= get_current_user(thd, tmp_user_name))) { append_user(thd, rlb, user_name, comma, TRUE); comma= TRUE; } } } /** Rewrite a CHANGE MASTER statement. @param thd The THD to rewrite for. @param rlb An empty String object to put the rewritten query in. */ static void mysql_rewrite_change_master(THD *thd, String *rlb) { LEX *lex= thd->lex; rlb->append(STRING_WITH_LEN("CHANGE MASTER TO")); if (lex->mi.host) { rlb->append(STRING_WITH_LEN(" MASTER_HOST = '")); rlb->append(lex->mi.host); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.user) { rlb->append(STRING_WITH_LEN(" MASTER_USER = '")); rlb->append(lex->mi.user); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.password) { rlb->append(STRING_WITH_LEN(" MASTER_PASSWORD = <secret>")); } if (lex->mi.port) { rlb->append(STRING_WITH_LEN(" MASTER_PORT = ")); rlb->append_ulonglong(lex->mi.port); } if (lex->mi.connect_retry) { rlb->append(STRING_WITH_LEN(" MASTER_CONNECT_RETRY = ")); rlb->append_ulonglong(lex->mi.connect_retry); } if (lex->mi.ssl) { rlb->append(STRING_WITH_LEN(" MASTER_SSL = ")); rlb->append(lex->mi.ssl == LEX_MASTER_INFO::LEX_MI_ENABLE ? "1" : "0"); } if (lex->mi.ssl_ca) { rlb->append(STRING_WITH_LEN(" MASTER_SSL_CA = '")); rlb->append(lex->mi.ssl_ca); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.ssl_capath) { rlb->append(STRING_WITH_LEN(" MASTER_SSL_CAPATH = '")); rlb->append(lex->mi.ssl_capath); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.ssl_cert) { rlb->append(STRING_WITH_LEN(" MASTER_SSL_CERT = '")); rlb->append(lex->mi.ssl_cert); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.ssl_cipher) { rlb->append(STRING_WITH_LEN(" MASTER_SSL_CIPHER = '")); rlb->append(lex->mi.ssl_cipher); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.ssl_key) { rlb->append(STRING_WITH_LEN(" MASTER_SSL_KEY = '")); rlb->append(lex->mi.ssl_key); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.log_file_name) { rlb->append(STRING_WITH_LEN(" MASTER_LOG_FILE = '")); rlb->append(lex->mi.log_file_name); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.pos) { rlb->append(STRING_WITH_LEN(" MASTER_LOG_POS = ")); rlb->append_ulonglong(lex->mi.pos); } if (lex->mi.relay_log_name) { rlb->append(STRING_WITH_LEN(" RELAY_LOG_FILE = '")); rlb->append(lex->mi.relay_log_name); rlb->append(STRING_WITH_LEN("'")); } if (lex->mi.relay_log_pos) { rlb->append(STRING_WITH_LEN(" RELAY_LOG_POS = ")); rlb->append_ulonglong(lex->mi.relay_log_pos); } if (lex->mi.ssl_verify_server_cert) { rlb->append(STRING_WITH_LEN(" MASTER_SSL_VERIFY_SERVER_CERT = ")); rlb->append(lex->mi.ssl_verify_server_cert == LEX_MASTER_INFO::LEX_MI_ENABLE ? "1" : "0"); } if (lex->mi.repl_ignore_server_ids_opt) { bool first= TRUE; rlb->append(STRING_WITH_LEN(" IGNORE_SERVER_IDS = ( ")); for (uint i= 0; i < lex->mi.repl_ignore_server_ids.elements; i++) { ulong s_id; get_dynamic(&lex->mi.repl_ignore_server_ids, (uchar*) &s_id, i); if (first) first= FALSE; else rlb->append(STRING_WITH_LEN(", ")); rlb->append_ulonglong(s_id); } rlb->append(STRING_WITH_LEN(" )")); } if (lex->mi.heartbeat_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED) { rlb->append(STRING_WITH_LEN(" MASTER_HEARTBEAT_PERIOD = ")); if (lex->mi.heartbeat_opt == LEX_MASTER_INFO::LEX_MI_DISABLE) rlb->append(STRING_WITH_LEN("0")); else { char buf[64]; snprintf(buf, 64, "%f", lex->mi.heartbeat_period); rlb->append(buf); } } } /** Rewrite a START SLAVE statement. @param thd The THD to rewrite for. @param rlb An empty String object to put the rewritten query in. */ static void mysql_rewrite_start_slave(THD *thd, String *rlb) { LEX *lex= thd->lex; if (!lex->slave_connection.password) return; rlb->append(STRING_WITH_LEN("START SLAVE")); if (lex->slave_thd_opt & SLAVE_IO) rlb->append(STRING_WITH_LEN(" IO_THREAD")); /* we have printed the IO THREAD related options */ if (lex->slave_thd_opt & SLAVE_IO && lex->slave_thd_opt & SLAVE_SQL) rlb->append(STRING_WITH_LEN(",")); if (lex->slave_thd_opt & SLAVE_SQL) rlb->append(STRING_WITH_LEN(" SQL_THREAD")); /* until options */ if (lex->mi.log_file_name || lex->mi.relay_log_name) { rlb->append(STRING_WITH_LEN(" UNTIL")); if (lex->mi.log_file_name) { rlb->append(STRING_WITH_LEN(" MASTER_LOG_FILE = '")); rlb->append(lex->mi.log_file_name); rlb->append(STRING_WITH_LEN("', ")); rlb->append(STRING_WITH_LEN("MASTER_LOG_POS = ")); rlb->append_ulonglong(lex->mi.pos); } if (lex->mi.relay_log_name) { rlb->append(STRING_WITH_LEN(" RELAY_LOG_FILE = '")); rlb->append(lex->mi.relay_log_name); rlb->append(STRING_WITH_LEN("', ")); rlb->append(STRING_WITH_LEN("RELAY_LOG_POS = ")); rlb->append_ulonglong(lex->mi.relay_log_pos); } } /* connection options */ if (lex->slave_connection.user) { rlb->append(STRING_WITH_LEN(" USER = '")); rlb->append(lex->slave_connection.user); rlb->append(STRING_WITH_LEN("'")); } if (lex->slave_connection.password) rlb->append(STRING_WITH_LEN(" PASSWORD = '<secret>'")); if (lex->slave_connection.plugin_auth) { rlb->append(STRING_WITH_LEN(" DEFAULT_AUTH = '")); rlb->append(lex->slave_connection.plugin_auth); rlb->append(STRING_WITH_LEN("'")); } if (lex->slave_connection.plugin_dir) { rlb->append(STRING_WITH_LEN(" PLUGIN_DIR = '")); rlb->append(lex->slave_connection.plugin_dir); rlb->append(STRING_WITH_LEN("'")); } } /** Rewrite a SERVER OPTIONS clause (for CREATE SERVER and ALTER SERVER). @param thd The THD to rewrite for. @param rlb An empty String object to put the rewritten query in. */ static void mysql_rewrite_server_options(THD *thd, String *rlb) { LEX *lex= thd->lex; rlb->append(STRING_WITH_LEN(" OPTIONS ( ")); rlb->append(STRING_WITH_LEN("PASSWORD '<secret>'")); append_str(rlb, true, "USER", lex->server_options.get_username()); append_str(rlb, true, "HOST", lex->server_options.get_host()); append_str(rlb, true, "DATABASE", lex->server_options.get_db()); append_str(rlb, true, "OWNER", lex->server_options.get_owner()); append_str(rlb, true, "SOCKET", lex->server_options.get_socket()); append_int(rlb, true, STRING_WITH_LEN("PORT "), lex->server_options.get_port(), lex->server_options.get_port() != Server_options::PORT_NOT_SET); rlb->append(STRING_WITH_LEN(" )")); } /** Rewrite a CREATE SERVER statement. @param thd The THD to rewrite for. @param rlb An empty String object to put the rewritten query in. */ static void mysql_rewrite_create_server(THD *thd, String *rlb) { LEX *lex= thd->lex; if (!lex->server_options.get_password()) return; rlb->append(STRING_WITH_LEN("CREATE SERVER ")); rlb->append(lex->server_options.m_server_name.str ? lex->server_options.m_server_name.str : ""); rlb->append(STRING_WITH_LEN(" FOREIGN DATA WRAPPER '")); rlb->append(lex->server_options.get_scheme() ? lex->server_options.get_scheme() : ""); rlb->append(STRING_WITH_LEN("'")); mysql_rewrite_server_options(thd, rlb); } /** Rewrite a ALTER SERVER statement. @param thd The THD to rewrite for. @param rlb An empty String object to put the rewritten query in. */ static void mysql_rewrite_alter_server(THD *thd, String *rlb) { LEX *lex= thd->lex; if (!lex->server_options.get_password()) return; rlb->append(STRING_WITH_LEN("ALTER SERVER ")); rlb->append(lex->server_options.m_server_name.str ? lex->server_options.m_server_name.str : ""); mysql_rewrite_server_options(thd, rlb); } /** Rewrite a query (to obfuscate passwords etc.) Side-effects: thd->rewritten_query will contain a rewritten query, or be cleared if no rewriting took place. @param thd The THD to rewrite for. */ void mysql_rewrite_query(THD *thd) { String *rlb= &thd->rewritten_query; rlb->free(); if (thd->lex->contains_plaintext_password) { switch(thd->lex->sql_command) { case SQLCOM_GRANT: mysql_rewrite_grant(thd, rlb); break; case SQLCOM_SET_OPTION: mysql_rewrite_set(thd, rlb); break; case SQLCOM_CREATE_USER: mysql_rewrite_create_user(thd, rlb); break; case SQLCOM_CHANGE_MASTER: mysql_rewrite_change_master(thd, rlb); break; case SQLCOM_SLAVE_START: mysql_rewrite_start_slave(thd, rlb); break; case SQLCOM_CREATE_SERVER: mysql_rewrite_create_server(thd, rlb); break; case SQLCOM_ALTER_SERVER: mysql_rewrite_alter_server(thd, rlb); break; default: /* unhandled query types are legal. */ break; } } }
zach14c/mysql
sql/sql_rewrite.cc
C++
gpl-2.0
18,637
/* vim: set sw=4 sts=4 et nofoldenable : */ /* * Copyright (c) 2007, 2008 Danny van Dyk <danny.dyk@uni-dortmund.de> * Copyright (c) 2007, 2008 Dirk Ribbrock <dirk.ribbrock@uni-dortmund.de> * * This file is part of the LA C++ library. LibLa 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. * * LibLa 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 */ #pragma once #ifndef LIBLA_GUARD_ALGORITHM_HH #define LIBLA_GUARD_ALGORITHM_HH 1 #include <honei/la/dense_vector.hh> #include <honei/la/dense_matrix.hh> #include <honei/la/sparse_matrix.hh> #include <honei/la/banded_matrix.hh> #include <honei/la/banded_matrix_qx.hh> #include <honei/util/tags.hh> #include <honei/mpi/dense_vector_mpi-fwd.hh> #include <honei/la/vector_error.hh> #ifdef HONEI_GMP #include <gmpxx.h> #endif #include <limits> namespace honei { /** * \{ * * Copies data from a source container to a destination container. * The destination container data will reside in Tag_'s memory * * \ingroup grpalgorithm */ template <typename Tag_, typename DT_> void copy(const DenseVectorContinuousBase<DT_> & source, DenseVectorContinuousBase<DT_> & dest) { CONTEXT("When copying elements from DenseVectorContinuousBase to DenseVectorContinuousBase:"); ASSERT(source.elements() != dest.elements(), "trying to copy data from a DenseVectorContinuousBase to the very same DenseVectorContinuousBase!"); if (source.size() != dest.size()) throw VectorSizeDoesNotMatch(dest.size(), source.size()); if (Tag_::tag_value == tags::tv_gpu_multi_core) { // TODO copy vektor parts direkt to the corresponding gpu memory /*DenseVectorRange<DT_> s1(source.range(source.size()/2, 0)); DenseVectorRange<DT_> d1(dest.range(dest.size()/2, 0)); DenseVectorRange<DT_> s2(source.range(source.size()/2 + source.size()%2, source.size()/2)); DenseVectorRange<DT_> d2(dest.range(dest.size()/2 + dest.size()%2, dest.size()/2)); cudaSumDVdouble task1(a1, b1, blocksize); cuda::GPUPool::instance()->enqueue(task2, 0)->wait(); cuda::GPUPool::instance()->enqueue(task2, 1)->wait();*/ dest.lock(lm_write_only); source.lock(lm_read_only); dest.unlock(lm_write_only); source.unlock(lm_read_only); TypeTraits<DT_>::copy(source.elements(), dest.elements(), dest.size()); } #ifdef HONEI_GMP else if (typeid(DT_) == typeid(mpf_class)) { TypeTraits<DT_>::copy(source.elements(), dest.elements(), source.size()); } #endif else { MemoryArbiter::instance()->copy(Tag_::memory_value, source.memid(), source.address(), dest.memid(), dest.address(), source.size() * sizeof(DT_)); } } template <typename Tag_, typename DT_> void copy(const DenseVectorMPI<DT_> & source, DenseVectorMPI<DT_> & dest) { CONTEXT("When copying elements from DenseVectorMPI to DenseVectorMPI:"); ASSERT(source.elements() != dest.elements(), "trying to copy data from a DenseVectorMPI to the very same DenseVectorMPI!"); if (source.size() != dest.size()) throw VectorSizeDoesNotMatch(dest.size(), source.size()); /*if (Tag_::tag_value == tags::tv_gpu_multi_core) { dest.lock(lm_write_only); source.lock(lm_read_only); dest.unlock(lm_write_only); source.unlock(lm_read_only); TypeTraits<DT_>::copy(source.elements(), dest.elements(), dest.size()); } else*/ { MemoryArbiter::instance()->copy(Tag_::memory_value, source.vector().memid(), source.vector().address(), dest.vector().memid(), dest.vector().address(), source.vector().size() * sizeof(DT_)); } } template <typename IT_, typename DT_> void copy(const IT_ & begin, const IT_ & end, DenseVector<DT_> & dest) { CONTEXT("When copying elements from iterator range to DenseVector:"); if (end.index() - begin.index() != dest.size()) throw VectorSizeDoesNotMatch(dest.size(), end.index() - begin.index()); typename DenseVector<DT_>::ConstElementIterator i(begin), i_end(end); for (typename DenseVector<DT_>::ElementIterator d(dest.begin_elements()) ; i != i_end ; ++i, ++d) { *d = *i; } } template <typename Tag_, typename DT_> void copy(const BandedMatrixQx<Q1Type, DT_> & source, BandedMatrixQx<Q1Type, DT_> & dest) { CONTEXT("When copying elements from BandedMatrixQ1 to BandedMatrixQ1:"); if (source.size() != dest.size()) throw VectorSizeDoesNotMatch(dest.size(), source.size()); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(LL).memid(), source.band(LL).address(), dest.band(LL).memid(), dest.band(LL).address(), source.band(LL).size() * sizeof(DT_)); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(LD).memid(), source.band(LD).address(), dest.band(LD).memid(), dest.band(LD).address(), source.band(LD).size() * sizeof(DT_)); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(LU).memid(), source.band(LU).address(), dest.band(LU).memid(), dest.band(LU).address(), source.band(LU).size() * sizeof(DT_)); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(DL).memid(), source.band(DL).address(), dest.band(DL).memid(), dest.band(DL).address(), source.band(DL).size() * sizeof(DT_)); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(DD).memid(), source.band(DD).address(), dest.band(DD).memid(), dest.band(DD).address(), source.band(DD).size() * sizeof(DT_)); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(DU).memid(), source.band(DU).address(), dest.band(DU).memid(), dest.band(DU).address(), source.band(DU).size() * sizeof(DT_)); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(UL).memid(), source.band(UL).address(), dest.band(UL).memid(), dest.band(UL).address(), source.band(UL).size() * sizeof(DT_)); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(UD).memid(), source.band(UD).address(), dest.band(UD).memid(), dest.band(UD).address(), source.band(UD).size() * sizeof(DT_)); MemoryArbiter::instance()->copy(Tag_::memory_value, source.band(UU).memid(), source.band(UU).address(), dest.band(UU).memid(), dest.band(UU).address(), source.band(UU).size() * sizeof(DT_)); } /// \} /** * \{ * * Converts data from a source container to a destination container. * * \ingroup grpalgorithm */ template <typename Tag_, typename DataType_> void convert(DenseVector<DataType_> & copy, const DenseVector<DataType_> & orig) { CONTEXT("When converting DenseVector to DenseVector:"); if (copy.size() != orig.size()) throw VectorSizeDoesNotMatch(orig.size(), copy.size()); MemoryArbiter::instance()->copy(Tag_::memory_value, orig.memid(), orig.address(), copy.memid(), copy.address(), orig.size() * sizeof(DataType_)); } template <typename Tag_> void convert(DenseVector<double> & copy, const DenseVector<float> & orig) { CONTEXT("When converting DenseVector to DenseVector:"); if (copy.size() != orig.size()) throw VectorSizeDoesNotMatch(orig.size(), copy.size()); MemoryArbiter::instance()->convert_float_double(Tag_::memory_value, orig.memid(), orig.address(), copy.memid(), copy.address(), orig.size() * sizeof(float)); } template <typename Tag_> void convert(DenseVector<float> & copy, const DenseVector<double> & orig) { CONTEXT("When converting DenseVector to DenseVector:"); if (copy.size() != orig.size()) throw VectorSizeDoesNotMatch(orig.size(), copy.size()); MemoryArbiter::instance()->convert_double_float(Tag_::memory_value, orig.memid(), orig.address(), copy.memid(), copy.address(), orig.size() * sizeof(double)); } #ifdef HONEI_GMP template <typename Tag_> void convert(DenseVector<mpf_class> & copy, const DenseVector<double> & orig) { CONTEXT("When converting DenseVector to DenseVector:"); if (copy.size() != orig.size()) throw VectorSizeDoesNotMatch(orig.size(), copy.size()); for (unsigned long i(0) ; i < copy.size() ; ++i) { mpf_class t(orig[i]); copy[i] = t; } } #endif template <typename DataType_> void convert(DenseVectorBase<DataType_> & copy, const DenseVectorBase<DataType_> & orig) { CONTEXT("When converting DenseVectorBase to DenseVectorBase:"); if (copy.size() != orig.size()) throw VectorSizeDoesNotMatch(orig.size(), copy.size()); copy = orig.copy(); } template <typename DataType_, typename OrigType_> void convert(DenseVectorBase<DataType_> & copy, const DenseVectorBase<OrigType_> & orig) { CONTEXT("When converting DenseVectorBase to DenseVectorBase:"); if (copy.size() != orig.size()) throw VectorSizeDoesNotMatch(orig.size(), copy.size()); copy.lock(lm_write_only); orig.lock(lm_read_only); typename DenseVector<DataType_>::ElementIterator f(copy.begin_elements()); for (typename DenseVector<OrigType_>::ConstElementIterator i(orig.begin_elements()), i_end(orig.end_elements()) ; i != i_end ; ++i, ++f) { *f = *i; } copy.unlock(lm_write_only); orig.unlock(lm_read_only); } template <typename DataType_> void convert(SparseVector<DataType_> & copy, const SparseVector<DataType_> & orig) { CONTEXT("When converting SparseVector to SparseVector:"); if (copy.size() != orig.size()) throw VectorSizeDoesNotMatch(orig.size(), copy.size()); copy = orig.copy(); } template <typename DataType_, typename OrigType_> void convert(SparseVector<DataType_> & copy, const SparseVector<OrigType_> & orig) { CONTEXT("When converting SparseVector to SparseVector:"); if (copy.size() != orig.size()) throw VectorSizeDoesNotMatch(orig.size(), copy.size()); for (typename SparseVector<OrigType_>::NonZeroConstElementIterator i(orig.begin_non_zero_elements()), i_end(orig.end_non_zero_elements()) ; i != i_end ; ++i) { copy[i.index()] = *i; } } template <typename DataType_> void convert(DenseMatrix<DataType_> & copy, const DenseMatrix<DataType_> & orig) { CONTEXT("When converting DenseMatrix to DenseMatrix:"); if (copy.rows() != orig.rows()) throw MatrixRowsDoNotMatch(orig.rows(), copy.rows()); if (copy.columns() != orig.columns()) throw MatrixColumnsDoNotMatch(orig.columns(), copy.columns()); copy = orig.copy(); } template <typename DataType_, typename OrigType_> void convert(DenseMatrix<DataType_> & copy, const DenseMatrix<OrigType_> & orig) { CONTEXT("When converting DenseMatrix to DenseMatrix:"); if (copy.rows() != orig.rows()) throw MatrixRowsDoNotMatch(orig.rows(), copy.rows()); if (copy.columns() != orig.columns()) throw MatrixColumnsDoNotMatch(orig.columns(), copy.columns()); copy.lock(lm_write_only); orig.lock(lm_read_only); TypeTraits<OrigType_>::convert(copy.elements(), orig.elements(), orig.columns() * orig.rows()); copy.unlock(lm_write_only); orig.unlock(lm_read_only); } template <typename DataType_> void convert(SparseMatrix<DataType_> & copy, const SparseMatrix<DataType_> & orig) { CONTEXT("When converting SparseMatrix to SparseMatrix:"); if (copy.rows() != orig.rows()) throw MatrixRowsDoNotMatch(orig.rows(), copy.rows()); if (copy.columns() != orig.columns()) throw MatrixColumnsDoNotMatch(orig.columns(), copy.columns()); copy = orig.copy(); } template <typename DataType_, typename OrigType_> void convert(SparseMatrix<DataType_> & copy, const SparseMatrix<OrigType_> & orig) { CONTEXT("When converting SparseMatrix to SparseMatrix:"); if (copy.rows() != orig.rows()) throw MatrixRowsDoNotMatch(orig.rows(), copy.rows()); if (copy.columns() != orig.columns()) throw MatrixColumnsDoNotMatch(orig.columns(), copy.columns()); for (unsigned long i(0) ; i < orig.rows() ; ++i) { convert(copy[i], orig[i]); } } template <typename DataType_> void convert(BandedMatrix<DataType_> & copy, const BandedMatrix<DataType_> & orig) { CONTEXT("When converting BandedMatrix to BandedMatrix:"); if (copy.size() != orig.size()) throw MatrixSizeDoesNotMatch(orig.size(), copy.size()); copy = orig.copy(); } template <typename DataType_, typename OrigType_> void convert(BandedMatrix<DataType_> & copy, const BandedMatrix<OrigType_> & orig) { CONTEXT("When converting BandedMatrix to BandedMatrix:"); if (copy.size() != orig.size()) throw MatrixSizeDoesNotMatch(orig.size(), copy.size()); for (typename BandedMatrix<OrigType_>::ConstBandIterator band(orig.begin_non_zero_bands()), band_end(orig.end_non_zero_bands()) ; band != band_end ; ++band) { convert(copy.band_unsigned(band.index()), *band); } } /// \} /** * \{ * * Fills a container with a given prototype. * * \ingroup grpalgorithm */ template <typename Tag_> void fill(DenseVectorContinuousBase<float> & dest, const float & proto = float(0)) { CONTEXT("When filling DenseVectorContinuousBase with '" + stringify(proto) + "':"); //TypeTraits<DT_>::fill(dest.elements(), dest.size(), proto); MemoryArbiter::instance()->fill(Tag_::memory_value, dest.memid(), dest.address(), dest.size() * sizeof(float), proto); } template <typename Tag_> void fill(DenseVectorContinuousBase<double> & dest, const double & proto = double(0)) { CONTEXT("When filling DenseVectorContinuousBase with '" + stringify(proto) + "':"); //TypeTraits<DT_>::fill(dest.elements(), dest.size(), proto); MemoryArbiter::instance()->fill(Tag_::memory_value, dest.memid(), dest.address(), dest.size() * sizeof(double), proto); } template <typename Tag_, typename DT_> void fill(DenseVectorMPI<DT_> & dest, const DT_ & proto = DT_(0)) { CONTEXT("When filling DenseVectorMPI with '" + stringify(proto) + "':"); MemoryArbiter::instance()->fill(Tag_::memory_value, dest.vector().memid(), dest.vector().address(), dest.vector().size() * sizeof(DT_), proto); } template <typename Tag_> void fill(const DenseMatrix<float> & dest, const float & proto = float(0)) { CONTEXT("When filling DenseMatrix with '" + stringify(proto) + "':"); //TypeTraits<DT_>::fill(dest.elements(), dest.rows() * dest.columns(), proto); MemoryArbiter::instance()->fill(Tag_::memory_value, dest.memid(), dest.address(), dest.size() * sizeof(float), proto); } template <typename Tag_> void fill(const DenseMatrix<double> & dest, const double & proto = double(0)) { CONTEXT("When filling DenseMatrix with '" + stringify(proto) + "':"); //TypeTraits<DT_>::fill(dest.elements(), dest.rows() * dest.columns(), proto); MemoryArbiter::instance()->fill(Tag_::memory_value, dest.memid(), dest.address(), dest.size() * sizeof(double), proto); } template <typename Tag, typename DT_> void fill(const DenseVectorContinuousBase<DT_> & dest, const DT_ & proto = DT_(0)) { CONTEXT("When filling DenseVectorContinuousBase with '" + stringify(proto) + "':"); dest.lock(lm_write_only); TypeTraits<DT_>::fill(dest.elements(), dest.size(), proto); dest.unlock(lm_write_only); } template <typename Tag, typename DT_> void fill(const DenseMatrix<DT_> & dest, const DT_ & proto = DT_(0)) { CONTEXT("When filling DenseMatrix with '" + stringify(proto) + "':"); dest.lock(lm_write_only); TypeTraits<DT_>::fill(dest.elements(), dest.rows() * dest.columns(), proto); dest.unlock(lm_write_only); } template <typename IT_, typename DT_> void fill(const IT_ & begin, const IT_ & end, const DT_ & proto = DT_(0)) { CONTEXT("When filling elements of iterator range with '" + stringify(proto) + "':"); for (IT_ i(begin), i_end(end) ; i != i_end ; ++i) { *i = proto; } } /// \} } #endif
dribbroc/HONEI
honei/la/algorithm.hh
C++
gpl-2.0
17,910
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark 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 2. * * The OWASP Benchmark 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. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest02153") public class BenchmarkTest02153 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = request.getParameter("vector"); if (param == null) param = ""; String bar = doSomething(param); String cmd = org.owasp.benchmark.helpers.Utils.getInsecureOSCommandString(this.getClass().getClassLoader()); String[] args = {cmd}; String[] argsEnv = { bar }; Runtime r = Runtime.getRuntime(); try { Process p = r.exec(args, argsEnv, new java.io.File(System.getProperty("user.dir"))); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } // end doPost private static String doSomething(String param) throws ServletException, IOException { // Chain a bunch of propagators in sequence String a56534 = param; //assign StringBuilder b56534 = new StringBuilder(a56534); // stick in stringbuilder b56534.append(" SafeStuff"); // append some safe content b56534.replace(b56534.length()-"Chars".length(),b56534.length(),"Chars"); //replace some of the end content java.util.HashMap<String,Object> map56534 = new java.util.HashMap<String,Object>(); map56534.put("key56534", b56534.toString()); // put in a collection String c56534 = (String)map56534.get("key56534"); // get it back out String d56534 = c56534.substring(0,c56534.length()-1); // extract most of it String e56534 = new String( new sun.misc.BASE64Decoder().decodeBuffer( new sun.misc.BASE64Encoder().encode( d56534.getBytes() ) )); // B64 encode and decode it String f56534 = e56534.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String g56534 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe' String bar = thing.doSomething(g56534); // reflection return bar; } }
ganncamp/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest02153.java
Java
gpl-2.0
3,459
/** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.iucn.whp.dbservice.service; import com.liferay.portal.service.InvokableLocalService; /** * @author alok.sen */ public class assessment_statusLocalServiceClp implements assessment_statusLocalService { public assessment_statusLocalServiceClp( InvokableLocalService invokableLocalService) { _invokableLocalService = invokableLocalService; _methodName0 = "addassessment_status"; _methodParameterTypes0 = new String[] { "com.iucn.whp.dbservice.model.assessment_status" }; _methodName1 = "createassessment_status"; _methodParameterTypes1 = new String[] { "long" }; _methodName2 = "deleteassessment_status"; _methodParameterTypes2 = new String[] { "long" }; _methodName3 = "deleteassessment_status"; _methodParameterTypes3 = new String[] { "com.iucn.whp.dbservice.model.assessment_status" }; _methodName4 = "dynamicQuery"; _methodParameterTypes4 = new String[] { }; _methodName5 = "dynamicQuery"; _methodParameterTypes5 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName6 = "dynamicQuery"; _methodParameterTypes6 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int" }; _methodName7 = "dynamicQuery"; _methodParameterTypes7 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int", "com.liferay.portal.kernel.util.OrderByComparator" }; _methodName8 = "dynamicQueryCount"; _methodParameterTypes8 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName9 = "fetchassessment_status"; _methodParameterTypes9 = new String[] { "long" }; _methodName10 = "getassessment_status"; _methodParameterTypes10 = new String[] { "long" }; _methodName11 = "getPersistedModel"; _methodParameterTypes11 = new String[] { "java.io.Serializable" }; _methodName12 = "getassessment_statuses"; _methodParameterTypes12 = new String[] { "int", "int" }; _methodName13 = "getassessment_statusesCount"; _methodParameterTypes13 = new String[] { }; _methodName14 = "updateassessment_status"; _methodParameterTypes14 = new String[] { "com.iucn.whp.dbservice.model.assessment_status" }; _methodName15 = "updateassessment_status"; _methodParameterTypes15 = new String[] { "com.iucn.whp.dbservice.model.assessment_status", "boolean" }; _methodName16 = "getBeanIdentifier"; _methodParameterTypes16 = new String[] { }; _methodName17 = "setBeanIdentifier"; _methodParameterTypes17 = new String[] { "java.lang.String" }; _methodName19 = "findAll"; _methodParameterTypes19 = new String[] { }; } public com.iucn.whp.dbservice.model.assessment_status addassessment_status( com.iucn.whp.dbservice.model.assessment_status assessment_status) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName0, _methodParameterTypes0, new Object[] { ClpSerializer.translateInput( assessment_status) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status createassessment_status( long statusid) { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName1, _methodParameterTypes1, new Object[] { statusid }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status deleteassessment_status( long statusid) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName2, _methodParameterTypes2, new Object[] { statusid }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status deleteassessment_status( com.iucn.whp.dbservice.model.assessment_status assessment_status) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName3, _methodParameterTypes3, new Object[] { ClpSerializer.translateInput( assessment_status) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery() { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName4, _methodParameterTypes4, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.liferay.portal.kernel.dao.orm.DynamicQuery)ClpSerializer.translateOutput(returnObj); } @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName5, _methodParameterTypes5, new Object[] { ClpSerializer.translateInput(dynamicQuery) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName6, _methodParameterTypes6, new Object[] { ClpSerializer.translateInput(dynamicQuery), start, end }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName7, _methodParameterTypes7, new Object[] { ClpSerializer.translateInput(dynamicQuery), start, end, ClpSerializer.translateInput(orderByComparator) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } public long dynamicQueryCount( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName8, _methodParameterTypes8, new Object[] { ClpSerializer.translateInput(dynamicQuery) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return ((Long)returnObj).longValue(); } public com.iucn.whp.dbservice.model.assessment_status fetchassessment_status( long statusid) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName9, _methodParameterTypes9, new Object[] { statusid }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status getassessment_status( long statusid) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName10, _methodParameterTypes10, new Object[] { statusid }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.liferay.portal.model.PersistedModel getPersistedModel( java.io.Serializable primaryKeyObj) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName11, _methodParameterTypes11, new Object[] { ClpSerializer.translateInput(primaryKeyObj) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.liferay.portal.model.PersistedModel)ClpSerializer.translateOutput(returnObj); } public java.util.List<com.iucn.whp.dbservice.model.assessment_status> getassessment_statuses( int start, int end) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName12, _methodParameterTypes12, new Object[] { start, end }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List<com.iucn.whp.dbservice.model.assessment_status>)ClpSerializer.translateOutput(returnObj); } public int getassessment_statusesCount() throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName13, _methodParameterTypes13, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return ((Integer)returnObj).intValue(); } public com.iucn.whp.dbservice.model.assessment_status updateassessment_status( com.iucn.whp.dbservice.model.assessment_status assessment_status) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName14, _methodParameterTypes14, new Object[] { ClpSerializer.translateInput( assessment_status) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status updateassessment_status( com.iucn.whp.dbservice.model.assessment_status assessment_status, boolean merge) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName15, _methodParameterTypes15, new Object[] { ClpSerializer.translateInput(assessment_status), merge }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public java.lang.String getBeanIdentifier() { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName16, _methodParameterTypes16, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.lang.String)ClpSerializer.translateOutput(returnObj); } public void setBeanIdentifier(java.lang.String beanIdentifier) { try { _invokableLocalService.invokeMethod(_methodName17, _methodParameterTypes17, new Object[] { ClpSerializer.translateInput(beanIdentifier) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } } public java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { throw new UnsupportedOperationException(); } public java.util.List<com.iucn.whp.dbservice.model.assessment_status> findAll() throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName19, _methodParameterTypes19, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List<com.iucn.whp.dbservice.model.assessment_status>)ClpSerializer.translateOutput(returnObj); } private InvokableLocalService _invokableLocalService; private String _methodName0; private String[] _methodParameterTypes0; private String _methodName1; private String[] _methodParameterTypes1; private String _methodName2; private String[] _methodParameterTypes2; private String _methodName3; private String[] _methodParameterTypes3; private String _methodName4; private String[] _methodParameterTypes4; private String _methodName5; private String[] _methodParameterTypes5; private String _methodName6; private String[] _methodParameterTypes6; private String _methodName7; private String[] _methodParameterTypes7; private String _methodName8; private String[] _methodParameterTypes8; private String _methodName9; private String[] _methodParameterTypes9; private String _methodName10; private String[] _methodParameterTypes10; private String _methodName11; private String[] _methodParameterTypes11; private String _methodName12; private String[] _methodParameterTypes12; private String _methodName13; private String[] _methodParameterTypes13; private String _methodName14; private String[] _methodParameterTypes14; private String _methodName15; private String[] _methodParameterTypes15; private String _methodName16; private String[] _methodParameterTypes16; private String _methodName17; private String[] _methodParameterTypes17; private String _methodName19; private String[] _methodParameterTypes19; }
iucn-whp/world-heritage-outlook
portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/service/assessment_statusLocalServiceClp.java
Java
gpl-2.0
20,922
#include <algorithm> #include "native/base/mutex.h" #include "native/base/timeutil.h" #include "GeDisasm.h" #include "GPUCommon.h" #include "GPUState.h" #include "ChunkFile.h" #include "Core/Config.h" #include "Core/CoreTiming.h" #include "Core/MemMap.h" #include "Core/Host.h" #include "Core/Reporting.h" #include "Core/HLE/sceKernelMemory.h" #include "Core/HLE/sceKernelInterrupt.h" #include "Core/HLE/sceGe.h" GPUCommon::GPUCommon() : currentList(NULL), isbreak(false), drawCompleteTicks(0), busyTicks(0), dumpNextFrame_(false), dumpThisFrame_(false), interruptsEnabled_(true), curTickEst_(0) { memset(dls, 0, sizeof(dls)); for (int i = 0; i < DisplayListMaxCount; ++i) { dls[i].state = PSP_GE_DL_STATE_NONE; dls[i].waitTicks = 0; } SetThreadEnabled(g_Config.bSeparateCPUThread); } void GPUCommon::PopDLQueue() { easy_guard guard(listLock); if(!dlQueue.empty()) { dlQueue.pop_front(); if(!dlQueue.empty()) { bool running = currentList->state == PSP_GE_DL_STATE_RUNNING; currentList = &dls[dlQueue.front()]; if (running) currentList->state = PSP_GE_DL_STATE_RUNNING; } else { currentList = NULL; } } } u32 GPUCommon::DrawSync(int mode) { // FIXME: Workaround for displaylists sometimes hanging unprocessed. Not yet sure of the cause. if (g_Config.bSeparateCPUThread) { // FIXME: Workaround for displaylists sometimes hanging unprocessed. Not yet sure of the cause. ScheduleEvent(GPU_EVENT_PROCESS_QUEUE); // Sync first, because the CPU is usually faster than the emulated GPU. SyncThread(); } easy_guard guard(listLock); if (mode < 0 || mode > 1) return SCE_KERNEL_ERROR_INVALID_MODE; if (mode == 0) { if (!__KernelIsDispatchEnabled()) { return SCE_KERNEL_ERROR_CAN_NOT_WAIT; } if (__IsInInterrupt()) { return SCE_KERNEL_ERROR_ILLEGAL_CONTEXT; } if (drawCompleteTicks > CoreTiming::GetTicks()) { __GeWaitCurrentThread(WAITTYPE_GEDRAWSYNC, 1, "GeDrawSync"); } else { for (int i = 0; i < DisplayListMaxCount; ++i) { if (dls[i].state == PSP_GE_DL_STATE_COMPLETED) { dls[i].state = PSP_GE_DL_STATE_NONE; } } } return 0; } // If there's no current list, it must be complete. DisplayList *top = NULL; for (auto it = dlQueue.begin(), end = dlQueue.end(); it != end; ++it) { if (dls[*it].state != PSP_GE_DL_STATE_COMPLETED) { top = &dls[*it]; break; } } if (!top || top->state == PSP_GE_DL_STATE_COMPLETED) return PSP_GE_LIST_COMPLETED; if (currentList->pc == currentList->stall) return PSP_GE_LIST_STALLING; return PSP_GE_LIST_DRAWING; } void GPUCommon::CheckDrawSync() { easy_guard guard(listLock); if (dlQueue.empty()) { for (int i = 0; i < DisplayListMaxCount; ++i) dls[i].state = PSP_GE_DL_STATE_NONE; } } int GPUCommon::ListSync(int listid, int mode) { if (g_Config.bSeparateCPUThread) { // FIXME: Workaround for displaylists sometimes hanging unprocessed. Not yet sure of the cause. ScheduleEvent(GPU_EVENT_PROCESS_QUEUE); // Sync first, because the CPU is usually faster than the emulated GPU. SyncThread(); } easy_guard guard(listLock); if (listid < 0 || listid >= DisplayListMaxCount) return SCE_KERNEL_ERROR_INVALID_ID; if (mode < 0 || mode > 1) return SCE_KERNEL_ERROR_INVALID_MODE; DisplayList& dl = dls[listid]; if (mode == 1) { switch (dl.state) { case PSP_GE_DL_STATE_QUEUED: if (dl.interrupted) return PSP_GE_LIST_PAUSED; return PSP_GE_LIST_QUEUED; case PSP_GE_DL_STATE_RUNNING: if (dl.pc == dl.stall) return PSP_GE_LIST_STALLING; return PSP_GE_LIST_DRAWING; case PSP_GE_DL_STATE_COMPLETED: return PSP_GE_LIST_COMPLETED; case PSP_GE_DL_STATE_PAUSED: return PSP_GE_LIST_PAUSED; default: return SCE_KERNEL_ERROR_INVALID_ID; } } if (!__KernelIsDispatchEnabled()) { return SCE_KERNEL_ERROR_CAN_NOT_WAIT; } if (__IsInInterrupt()) { return SCE_KERNEL_ERROR_ILLEGAL_CONTEXT; } if (dl.waitTicks > CoreTiming::GetTicks()) { __GeWaitCurrentThread(WAITTYPE_GELISTSYNC, listid, "GeListSync"); } return PSP_GE_LIST_COMPLETED; } u32 GPUCommon::EnqueueList(u32 listpc, u32 stall, int subIntrBase, bool head) { easy_guard guard(listLock); // TODO Check the stack values in missing arg and ajust the stack depth // Check alignment // TODO Check the context and stack alignement too if (((listpc | stall) & 3) != 0) return 0x80000103; int id = -1; bool oldCompatibility = true; if (sceKernelGetCompiledSdkVersion() > 0x01FFFFFF) { //numStacks = 0; //stack = NULL; oldCompatibility = false; } u64 currentTicks = CoreTiming::GetTicks(); for (int i = 0; i < DisplayListMaxCount; ++i) { if (dls[i].state != PSP_GE_DL_STATE_NONE && dls[i].state != PSP_GE_DL_STATE_COMPLETED) { if (dls[i].pc == listpc && !oldCompatibility) { ERROR_LOG(G3D, "sceGeListEnqueue: can't enqueue, list address %08X already used", listpc); return 0x80000021; } //if(dls[i].stack == stack) { // ERROR_LOG(G3D, "sceGeListEnqueue: can't enqueue, list stack %08X already used", context); // return 0x80000021; //} } if (dls[i].state == PSP_GE_DL_STATE_NONE && !dls[i].pendingInterrupt) { // Prefer a list that isn't used id = i; break; } if (id < 0 && dls[i].state == PSP_GE_DL_STATE_COMPLETED && !dls[i].pendingInterrupt && dls[i].waitTicks < currentTicks) { id = i; } } if (id < 0) { ERROR_LOG_REPORT(G3D, "No DL ID available to enqueue"); for(auto it = dlQueue.begin(); it != dlQueue.end(); ++it) { DisplayList &dl = dls[*it]; DEBUG_LOG(G3D, "DisplayList %d status %d pc %08x stall %08x", *it, dl.state, dl.pc, dl.stall); } return SCE_KERNEL_ERROR_OUT_OF_MEMORY; } DisplayList &dl = dls[id]; dl.id = id; dl.startpc = listpc & 0x0FFFFFFF; dl.pc = listpc & 0x0FFFFFFF; dl.stall = stall & 0x0FFFFFFF; dl.subIntrBase = std::max(subIntrBase, -1); dl.stackptr = 0; dl.signal = PSP_GE_SIGNAL_NONE; dl.interrupted = false; dl.waitTicks = (u64)-1; dl.interruptsEnabled = interruptsEnabled_; if (head) { if (currentList) { if (currentList->state != PSP_GE_DL_STATE_PAUSED) return SCE_KERNEL_ERROR_INVALID_VALUE; currentList->state = PSP_GE_DL_STATE_QUEUED; } dl.state = PSP_GE_DL_STATE_PAUSED; currentList = &dl; dlQueue.push_front(id); } else if (currentList) { dl.state = PSP_GE_DL_STATE_QUEUED; dlQueue.push_back(id); } else { dl.state = PSP_GE_DL_STATE_RUNNING; currentList = &dl; dlQueue.push_front(id); drawCompleteTicks = (u64)-1; // TODO save context when starting the list if param is set guard.unlock(); ProcessDLQueue(); } return id; } u32 GPUCommon::DequeueList(int listid) { easy_guard guard(listLock); if (listid < 0 || listid >= DisplayListMaxCount || dls[listid].state == PSP_GE_DL_STATE_NONE) return SCE_KERNEL_ERROR_INVALID_ID; if (dls[listid].state == PSP_GE_DL_STATE_RUNNING || dls[listid].state == PSP_GE_DL_STATE_PAUSED) return 0x80000021; dls[listid].state = PSP_GE_DL_STATE_NONE; if (listid == dlQueue.front()) PopDLQueue(); else dlQueue.remove(listid); dls[listid].waitTicks = 0; __GeTriggerWait(WAITTYPE_GELISTSYNC, listid); CheckDrawSync(); return 0; } u32 GPUCommon::UpdateStall(int listid, u32 newstall) { easy_guard guard(listLock); if (listid < 0 || listid >= DisplayListMaxCount || dls[listid].state == PSP_GE_DL_STATE_NONE) return SCE_KERNEL_ERROR_INVALID_ID; dls[listid].stall = newstall & 0x0FFFFFFF; if (dls[listid].signal == PSP_GE_SIGNAL_HANDLER_PAUSE) dls[listid].signal = PSP_GE_SIGNAL_HANDLER_SUSPEND; guard.unlock(); ProcessDLQueue(); return 0; } u32 GPUCommon::Continue() { easy_guard guard(listLock); if (!currentList) return 0; if (currentList->state == PSP_GE_DL_STATE_PAUSED) { if (!isbreak) { if (currentList->signal == PSP_GE_SIGNAL_HANDLER_PAUSE) return 0x80000021; currentList->state = PSP_GE_DL_STATE_RUNNING; currentList->signal = PSP_GE_SIGNAL_NONE; // TODO Restore context of DL is necessary // TODO Restore BASE // We have a list now, so it's not complete. drawCompleteTicks = (u64)-1; } else currentList->state = PSP_GE_DL_STATE_QUEUED; } else if (currentList->state == PSP_GE_DL_STATE_RUNNING) { if (sceKernelGetCompiledSdkVersion() >= 0x02000000) return 0x80000020; return -1; } else { if (sceKernelGetCompiledSdkVersion() >= 0x02000000) return 0x80000004; return -1; } guard.unlock(); ProcessDLQueue(); return 0; } u32 GPUCommon::Break(int mode) { easy_guard guard(listLock); if (mode < 0 || mode > 1) return SCE_KERNEL_ERROR_INVALID_MODE; if (!currentList) return 0x80000020; if (mode == 1) { // Clear the queue dlQueue.clear(); for (int i = 0; i < DisplayListMaxCount; ++i) { dls[i].state = PSP_GE_DL_STATE_NONE; dls[i].signal = PSP_GE_SIGNAL_NONE; } currentList = NULL; return 0; } if (currentList->state == PSP_GE_DL_STATE_NONE || currentList->state == PSP_GE_DL_STATE_COMPLETED) { if (sceKernelGetCompiledSdkVersion() >= 0x02000000) return 0x80000004; return -1; } if (currentList->state == PSP_GE_DL_STATE_PAUSED) { if (sceKernelGetCompiledSdkVersion() > 0x02000010) { if (currentList->signal == PSP_GE_SIGNAL_HANDLER_PAUSE) { ERROR_LOG_REPORT(G3D, "sceGeBreak: can't break signal-pausing list"); } else return 0x80000020; } return 0x80000021; } if (currentList->state == PSP_GE_DL_STATE_QUEUED) { currentList->state = PSP_GE_DL_STATE_PAUSED; return currentList->id; } // TODO Save BASE // TODO Adjust pc to be just before SIGNAL/END // TODO: Is this right? if (currentList->signal == PSP_GE_SIGNAL_SYNC) currentList->pc += 8; currentList->interrupted = true; currentList->state = PSP_GE_DL_STATE_PAUSED; currentList->signal = PSP_GE_SIGNAL_HANDLER_SUSPEND; isbreak = true; return currentList->id; } bool GPUCommon::InterpretList(DisplayList &list) { // Initialized to avoid a race condition with bShowDebugStats changing. double start = 0.0; if (g_Config.bShowDebugStats) { time_update(); start = time_now_d(); } easy_guard guard(listLock); // TODO: This has to be right... but it freezes right now? //if (list.state == PSP_GE_DL_STATE_PAUSED) // return false; currentList = &list; // I don't know if this is the correct place to zero this, but something // need to do it. See Sol Trigger title screen. // TODO: Maybe this is per list? Should a stalled list remember the old value? gstate_c.offsetAddr = 0; if (!Memory::IsValidAddress(list.pc)) { ERROR_LOG_REPORT(G3D, "DL PC = %08x WTF!!!!", list.pc); return true; } #if defined(USING_QT_UI) if (host->GpuStep()) { host->SendGPUStart(); } #endif cycleLastPC = list.pc; downcount = list.stall == 0 ? 0x0FFFFFFF : (list.stall - list.pc) / 4; list.state = PSP_GE_DL_STATE_RUNNING; list.interrupted = false; gpuState = list.pc == list.stall ? GPUSTATE_STALL : GPUSTATE_RUNNING; guard.unlock(); const bool dumpThisFrame = dumpThisFrame_; // TODO: Add check for displaylist debugger. const bool useFastRunLoop = !dumpThisFrame; while (gpuState == GPUSTATE_RUNNING) { { easy_guard innerGuard(listLock); if (list.pc == list.stall) { gpuState = GPUSTATE_STALL; downcount = 0; } } if (useFastRunLoop) { FastRunLoop(list); } else { SlowRunLoop(list); } { easy_guard innerGuard(listLock); downcount = list.stall == 0 ? 0x0FFFFFFF : (list.stall - list.pc) / 4; if (gpuState == GPUSTATE_STALL && list.stall != list.pc) { // Unstalled. gpuState = GPUSTATE_RUNNING; } } } // We haven't run the op at list.pc, so it shouldn't count. if (cycleLastPC != list.pc) { UpdatePC(list.pc - 4, list.pc); } if (g_Config.bShowDebugStats) { time_update(); gpuStats.msProcessingDisplayLists += time_now_d() - start; } return gpuState == GPUSTATE_DONE || gpuState == GPUSTATE_ERROR; } void GPUCommon::SlowRunLoop(DisplayList &list) { const bool dumpThisFrame = dumpThisFrame_; while (downcount > 0) { u32 op = Memory::ReadUnchecked_U32(list.pc); u32 cmd = op >> 24; #if defined(USING_QT_UI) if (host->GpuStep()) host->SendGPUWait(cmd, list.pc, &gstate); #endif u32 diff = op ^ gstate.cmdmem[cmd]; PreExecuteOp(op, diff); if (dumpThisFrame) { char temp[256]; u32 prev = Memory::ReadUnchecked_U32(list.pc - 4); GeDisassembleOp(list.pc, op, prev, temp); NOTICE_LOG(G3D, "%s", temp); } gstate.cmdmem[cmd] = op; ExecuteOp(op, diff); list.pc += 4; --downcount; } } // The newPC parameter is used for jumps, we don't count cycles between. inline void GPUCommon::UpdatePC(u32 currentPC, u32 newPC) { // Rough estimate, 2 CPU ticks (it's double the clock rate) per GPU instruction. int executed = (currentPC - cycleLastPC) / 4; cyclesExecuted += 2 * executed; gpuStats.otherGPUCycles += 2 * executed; cycleLastPC = newPC == 0 ? currentPC : newPC; gpuStats.gpuCommandsAtCallLevel[std::min(currentList->stackptr, 3)] += executed; // Exit the runloop and recalculate things. This isn't common. downcount = 0; } void GPUCommon::ReapplyGfxState() { if (IsOnSeparateCPUThread()) { ScheduleEvent(GPU_EVENT_REAPPLY_GFX_STATE); } else { ReapplyGfxStateInternal(); } } void GPUCommon::ReapplyGfxStateInternal() { // ShaderManager_DirtyShader(); // The commands are embedded in the command memory so we can just reexecute the words. Convenient. // To be safe we pass 0xFFFFFFFF as the diff. /* ExecuteOp(gstate.cmdmem[GE_CMD_ALPHABLENDENABLE], 0xFFFFFFFF); ExecuteOp(gstate.cmdmem[GE_CMD_ALPHATESTENABLE], 0xFFFFFFFF); ExecuteOp(gstate.cmdmem[GE_CMD_BLENDMODE], 0xFFFFFFFF); ExecuteOp(gstate.cmdmem[GE_CMD_ZTEST], 0xFFFFFFFF); ExecuteOp(gstate.cmdmem[GE_CMD_ZTESTENABLE], 0xFFFFFFFF); ExecuteOp(gstate.cmdmem[GE_CMD_CULL], 0xFFFFFFFF); ExecuteOp(gstate.cmdmem[GE_CMD_CULLFACEENABLE], 0xFFFFFFFF); ExecuteOp(gstate.cmdmem[GE_CMD_SCISSOR1], 0xFFFFFFFF); ExecuteOp(gstate.cmdmem[GE_CMD_SCISSOR2], 0xFFFFFFFF); */ for (int i = GE_CMD_VERTEXTYPE; i < GE_CMD_BONEMATRIXNUMBER; i++) { if (i != GE_CMD_ORIGIN) { ExecuteOp(gstate.cmdmem[i], 0xFFFFFFFF); } } // Can't write to bonematrixnumber here for (int i = GE_CMD_MORPHWEIGHT0; i < GE_CMD_PATCHFACING; i++) { ExecuteOp(gstate.cmdmem[i], 0xFFFFFFFF); } // There are a few here in the middle that we shouldn't execute... for (int i = GE_CMD_VIEWPORTX1; i < GE_CMD_TRANSFERSTART; i++) { ExecuteOp(gstate.cmdmem[i], 0xFFFFFFFF); } // TODO: there's more... } inline void GPUCommon::UpdateState(GPUState state) { gpuState = state; if (state != GPUSTATE_RUNNING) downcount = 0; } void GPUCommon::ProcessEvent(GPUEvent ev) { switch (ev.type) { case GPU_EVENT_PROCESS_QUEUE: ProcessDLQueueInternal(); break; case GPU_EVENT_REAPPLY_GFX_STATE: ReapplyGfxStateInternal(); break; default: ERROR_LOG_REPORT(G3D, "Unexpected GPU event type: %d", (int)ev); } } int GPUCommon::GetNextListIndex() { easy_guard guard(listLock); auto iter = dlQueue.begin(); if (iter != dlQueue.end()) { return *iter; } else { return -1; } } bool GPUCommon::ProcessDLQueue() { ScheduleEvent(GPU_EVENT_PROCESS_QUEUE); return true; } void GPUCommon::ProcessDLQueueInternal() { startingTicks = CoreTiming::GetTicks(); cyclesExecuted = 0; UpdateTickEstimate(std::max(busyTicks, startingTicks + cyclesExecuted)); // Seems to be correct behaviour to process the list anyway? if (startingTicks < busyTicks) { DEBUG_LOG(G3D, "Can't execute a list yet, still busy for %lld ticks", busyTicks - startingTicks); //return; } for (int listIndex = GetNextListIndex(); listIndex != -1; listIndex = GetNextListIndex()) { DisplayList &l = dls[listIndex]; DEBUG_LOG(G3D, "Okay, starting DL execution at %08x - stall = %08x", l.pc, l.stall); if (!InterpretList(l)) { return; } else { easy_guard guard(listLock); // At the end, we can remove it from the queue and continue. dlQueue.erase(std::remove(dlQueue.begin(), dlQueue.end(), listIndex), dlQueue.end()); UpdateTickEstimate(std::max(busyTicks, startingTicks + cyclesExecuted)); } } easy_guard guard(listLock); currentList = NULL; drawCompleteTicks = startingTicks + cyclesExecuted; busyTicks = std::max(busyTicks, drawCompleteTicks); __GeTriggerSync(WAITTYPE_GEDRAWSYNC, 1, drawCompleteTicks); // Since the event is in CoreTiming, we're in sync. Just set 0 now. UpdateTickEstimate(0); } void GPUCommon::PreExecuteOp(u32 op, u32 diff) { // Nothing to do } void GPUCommon::ExecuteOp(u32 op, u32 diff) { u32 cmd = op >> 24; u32 data = op & 0xFFFFFF; // Handle control and drawing commands here directly. The others we delegate. switch (cmd) { case GE_CMD_NOP: break; case GE_CMD_OFFSETADDR: gstate_c.offsetAddr = data << 8; break; case GE_CMD_ORIGIN: { easy_guard guard(listLock); gstate_c.offsetAddr = currentList->pc; } break; case GE_CMD_JUMP: { easy_guard guard(listLock); u32 target = gstate_c.getRelativeAddress(data); if (Memory::IsValidAddress(target)) { UpdatePC(currentList->pc, target - 4); currentList->pc = target - 4; // pc will be increased after we return, counteract that } else { ERROR_LOG_REPORT(G3D, "JUMP to illegal address %08x - ignoring! data=%06x", target, data); } } break; case GE_CMD_CALL: { easy_guard guard(listLock); // Saint Seiya needs correct support for relative calls. u32 retval = currentList->pc + 4; u32 target = gstate_c.getRelativeAddress(data); if (currentList->stackptr == ARRAY_SIZE(currentList->stack)) { ERROR_LOG_REPORT(G3D, "CALL: Stack full!"); } else if (!Memory::IsValidAddress(target)) { ERROR_LOG_REPORT(G3D, "CALL to illegal address %08x - ignoring! data=%06x", target, data); } else { auto &stackEntry = currentList->stack[currentList->stackptr++]; stackEntry.pc = retval; stackEntry.offsetAddr = gstate_c.offsetAddr; UpdatePC(currentList->pc, target - 4); currentList->pc = target - 4; // pc will be increased after we return, counteract that } } break; case GE_CMD_RET: { easy_guard guard(listLock); if (currentList->stackptr == 0) { ERROR_LOG_REPORT(G3D, "RET: Stack empty!"); } else { auto &stackEntry = currentList->stack[--currentList->stackptr]; gstate_c.offsetAddr = stackEntry.offsetAddr; u32 target = (currentList->pc & 0xF0000000) | (stackEntry.pc & 0x0FFFFFFF); UpdatePC(currentList->pc, target - 4); currentList->pc = target - 4; if (!Memory::IsValidAddress(currentList->pc)) { ERROR_LOG_REPORT(G3D, "Invalid DL PC %08x on return", currentList->pc); UpdateState(GPUSTATE_ERROR); } } } break; case GE_CMD_SIGNAL: case GE_CMD_FINISH: // Processed in GE_END. break; case GE_CMD_END: { easy_guard guard(listLock); u32 prev = Memory::ReadUnchecked_U32(currentList->pc - 4); UpdatePC(currentList->pc); switch (prev >> 24) { case GE_CMD_SIGNAL: { // TODO: see http://code.google.com/p/jpcsp/source/detail?r=2935# SignalBehavior behaviour = static_cast<SignalBehavior>((prev >> 16) & 0xFF); int signal = prev & 0xFFFF; int enddata = data & 0xFFFF; bool trigger = true; currentList->subIntrToken = signal; switch (behaviour) { case PSP_GE_SIGNAL_HANDLER_SUSPEND: if (sceKernelGetCompiledSdkVersion() <= 0x02000010) currentList->state = PSP_GE_DL_STATE_PAUSED; currentList->signal = behaviour; DEBUG_LOG(G3D, "Signal with Wait UNIMPLEMENTED! signal/end: %04x %04x", signal, enddata); break; case PSP_GE_SIGNAL_HANDLER_CONTINUE: currentList->signal = behaviour; DEBUG_LOG(G3D, "Signal without wait. signal/end: %04x %04x", signal, enddata); break; case PSP_GE_SIGNAL_HANDLER_PAUSE: currentList->state = PSP_GE_DL_STATE_PAUSED; currentList->signal = behaviour; ERROR_LOG_REPORT(G3D, "Signal with Pause UNIMPLEMENTED! signal/end: %04x %04x", signal, enddata); break; case PSP_GE_SIGNAL_SYNC: currentList->signal = behaviour; DEBUG_LOG(G3D, "Signal with Sync. signal/end: %04x %04x", signal, enddata); break; case PSP_GE_SIGNAL_JUMP: { trigger = false; currentList->signal = behaviour; // pc will be increased after we return, counteract that. u32 target = ((signal << 16) | enddata) - 4; if (!Memory::IsValidAddress(target)) { ERROR_LOG_REPORT(G3D, "Signal with Jump: bad address. signal/end: %04x %04x", signal, enddata); } else { UpdatePC(currentList->pc, target); currentList->pc = target; DEBUG_LOG(G3D, "Signal with Jump. signal/end: %04x %04x", signal, enddata); } } break; case PSP_GE_SIGNAL_CALL: { trigger = false; currentList->signal = behaviour; // pc will be increased after we return, counteract that. u32 target = ((signal << 16) | enddata) - 4; if (currentList->stackptr == ARRAY_SIZE(currentList->stack)) { ERROR_LOG_REPORT(G3D, "Signal with Call: stack full. signal/end: %04x %04x", signal, enddata); } else if (!Memory::IsValidAddress(target)) { ERROR_LOG_REPORT(G3D, "Signal with Call: bad address. signal/end: %04x %04x", signal, enddata); } else { // TODO: This might save/restore other state... auto &stackEntry = currentList->stack[currentList->stackptr++]; stackEntry.pc = currentList->pc; stackEntry.offsetAddr = gstate_c.offsetAddr; UpdatePC(currentList->pc, target); currentList->pc = target; DEBUG_LOG(G3D, "Signal with Call. signal/end: %04x %04x", signal, enddata); } } break; case PSP_GE_SIGNAL_RET: { trigger = false; currentList->signal = behaviour; if (currentList->stackptr == 0) { ERROR_LOG_REPORT(G3D, "Signal with Return: stack empty. signal/end: %04x %04x", signal, enddata); } else { // TODO: This might save/restore other state... auto &stackEntry = currentList->stack[--currentList->stackptr]; gstate_c.offsetAddr = stackEntry.offsetAddr; UpdatePC(currentList->pc, stackEntry.pc); currentList->pc = stackEntry.pc; DEBUG_LOG(G3D, "Signal with Return. signal/end: %04x %04x", signal, enddata); } } break; default: ERROR_LOG_REPORT(G3D, "UNKNOWN Signal UNIMPLEMENTED %i ! signal/end: %04x %04x", behaviour, signal, enddata); break; } // TODO: Technically, jump/call/ret should generate an interrupt, but before the pc change maybe? if (currentList->interruptsEnabled && trigger) { if (__GeTriggerInterrupt(currentList->id, currentList->pc, startingTicks + cyclesExecuted)) { currentList->pendingInterrupt = true; UpdateState(GPUSTATE_INTERRUPT); } } } break; case GE_CMD_FINISH: switch (currentList->signal) { case PSP_GE_SIGNAL_HANDLER_PAUSE: if (currentList->interruptsEnabled) { if (__GeTriggerInterrupt(currentList->id, currentList->pc, startingTicks + cyclesExecuted)) { currentList->pendingInterrupt = true; UpdateState(GPUSTATE_INTERRUPT); } } break; case PSP_GE_SIGNAL_SYNC: currentList->signal = PSP_GE_SIGNAL_NONE; // TODO: Technically this should still cause an interrupt. Probably for memory sync. break; default: currentList->subIntrToken = prev & 0xFFFF; currentList->state = PSP_GE_DL_STATE_COMPLETED; UpdateState(GPUSTATE_DONE); if (currentList->interruptsEnabled && __GeTriggerInterrupt(currentList->id, currentList->pc, startingTicks + cyclesExecuted)) { currentList->pendingInterrupt = true; } else { currentList->waitTicks = startingTicks + cyclesExecuted; busyTicks = std::max(busyTicks, currentList->waitTicks); __GeTriggerSync(WAITTYPE_GELISTSYNC, currentList->id, currentList->waitTicks); } break; } break; default: DEBUG_LOG(G3D,"Ah, not finished: %06x", prev & 0xFFFFFF); break; } break; } default: DEBUG_LOG(G3D,"DL Unknown: %08x @ %08x", op, currentList == NULL ? 0 : currentList->pc); break; } } void GPUCommon::DoState(PointerWrap &p) { easy_guard guard(listLock); p.Do<int>(dlQueue); p.DoArray(dls, ARRAY_SIZE(dls)); int currentID = 0; if (currentList != NULL) { ptrdiff_t off = currentList - &dls[0]; currentID = (int) (off / sizeof(DisplayList)); } p.Do(currentID); if (currentID == 0) { currentList = NULL; } else { currentList = &dls[currentID]; } p.Do(interruptRunning); p.Do(gpuState); p.Do(isbreak); p.Do(drawCompleteTicks); p.Do(busyTicks); p.DoMarker("GPUCommon"); } void GPUCommon::InterruptStart(int listid) { interruptRunning = true; } void GPUCommon::InterruptEnd(int listid) { easy_guard guard(listLock); interruptRunning = false; isbreak = false; DisplayList &dl = dls[listid]; dl.pendingInterrupt = false; // TODO: Unless the signal handler could change it? if (dl.state == PSP_GE_DL_STATE_COMPLETED || dl.state == PSP_GE_DL_STATE_NONE) { dl.waitTicks = 0; __GeTriggerWait(WAITTYPE_GELISTSYNC, listid); } if (dl.signal == PSP_GE_SIGNAL_HANDLER_PAUSE) dl.signal = PSP_GE_SIGNAL_HANDLER_SUSPEND; guard.unlock(); ProcessDLQueue(); } // TODO: Maybe cleaner to keep this in GE and trigger the clear directly? void GPUCommon::SyncEnd(WaitType waitType, int listid, bool wokeThreads) { easy_guard guard(listLock); if (waitType == WAITTYPE_GEDRAWSYNC && wokeThreads) { for (int i = 0; i < DisplayListMaxCount; ++i) { if (dls[i].state == PSP_GE_DL_STATE_COMPLETED) { dls[i].state = PSP_GE_DL_STATE_NONE; } } } }
Ced2911/psychic-octo-wookie
GPU/GPUCommon.cpp
C++
gpl-2.0
25,531
/* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Adds a public API for the browsers' localStorage called * TYPO3.Storage.Client and the Backend Users "uc", * available via TYPO3.Storage.Persistent */ define('TYPO3/CMS/Backend/Storage', ['jquery'], function ($) { var Storage = { Client: {}, Persistent: { _data: false } }; /** * simple localStorage wrapper, common functions get/set/clear */ Storage.Client.get = function(key) { return localStorage.getItem('t3-' + key); }; Storage.Client.set = function(key, value) { return localStorage.setItem('t3-' + key, value); }; Storage.Client.clear = function() { localStorage.clear(); }; /** * checks if a key was set before, useful to not do all the undefined checks all the time */ Storage.Client.isset = function(key) { var value = this.get(key); return (typeof value !== 'undefined' && typeof value !== 'null' && value != 'undefined'); }; /** * persistent storage, stores everything on the server * via AJAX, does a greedy load on read * common functions get/set/clear */ Storage.Persistent.get = function(key) { if (this._data === false) { var value; this._loadFromServer().done(function() { value = Storage.Persistent._getRecursiveDataByDeepKey(Storage.Persistent._data, key.split('.')); }); return value; } else { return this._getRecursiveDataByDeepKey(this._data, key.split('.')); } }; Storage.Persistent.set = function(key, value) { if (this._data !== false) { this._data = this._setRecursiveDataByDeepKey(this._data, key.split('.'), value); } return this._storeOnServer(key, value); }; Storage.Persistent.addToList = function(key, value) { return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'addToList', key: key, value: value}}).done(function(data) { Storage.Persistent._data = data; }); }; Storage.Persistent.removeFromList = function(key, value) { return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'removeFromList', key: key, value: value}}).done(function(data) { Storage.Persistent._data = data; }); }; Storage.Persistent.unset = function(key) { return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'unset', key: key}}).done(function(data) { Storage.Persistent._data = data; }); }; Storage.Persistent.clear = function() { $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'clear'}}); this._data = false; }; /** * checks if a key was set before, useful to not do all the undefined checks all the time */ Storage.Persistent.isset = function(key) { var value = this.get(key); return (typeof value !== 'undefined' && typeof value !== 'null' && value != 'undefined'); }; /** * loads the data from outside, only used for the initial call from BackendController * @param data */ Storage.Persistent.load = function(data) { this._data = data; }; /** * loads all data from the server * @returns jQuery Deferred * @private */ Storage.Persistent._loadFromServer = function() { return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'getAll'}, async: false}).done(function(data) { Storage.Persistent._data = data; }); }; /** * stores data on the server, and gets the updated data on return * to always be up-to-date inside the browser * @returns jQuery Deferred * @private */ Storage.Persistent._storeOnServer = function(key, value) { return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'set', key: key, value: value}}).done(function(data) { Storage.Persistent._data = data; }); }; /** * helper function used to set a value which could have been a flat object key data["my.foo.bar"] to * data[my][foo][bar] * is called recursively by itself * * @param data the data to be uased as base * @param keyParts the keyParts for the subtree * @param value the value to be set * @returns the data object * @private */ Storage.Persistent._setRecursiveDataByDeepKey = function(data, keyParts, value) { if (keyParts.length === 1) { data = data || {}; data[keyParts[0]] = value; } else { var firstKey = keyParts.shift(); data[firstKey] = this._setRecursiveDataByDeepKey(data[firstKey] || {}, keyParts, value); } return data; }; /** * helper function used to set a value which could have been a flat object key data["my.foo.bar"] to * data[my][foo][bar] * is called recursively by itself * * @param data the data to be uased as base * @param keyParts the keyParts for the subtree * @returns {*} * @private */ Storage.Persistent._getRecursiveDataByDeepKey = function(data, keyParts) { if (keyParts.length === 1) { return (data || {})[keyParts[0]]; } else { var firstKey = keyParts.shift(); return this._getRecursiveDataByDeepKey(data[firstKey] || {}, keyParts); } }; /** * return the Storage object, and attach it to the global TYPO3 object on the global frame */ return function() { top.TYPO3.Storage = Storage; return Storage; }(); });
dalder/TYPO3.CMS
typo3/sysext/backend/Resources/Public/JavaScript/Storage.js
JavaScript
gpl-2.0
5,501
package org.ecocean.servlet.export; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import org.ecocean.*; import org.ecocean.servlet.ServletUtilities; import java.lang.StringBuffer; //adds spots to a new encounter public class IndividualSearchExportCapture extends HttpServlet{ public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //set the response response.setContentType("text/html"); PrintWriter out = response.getWriter(); String context="context0"; context=ServletUtilities.getContext(request); Shepherd myShepherd = new Shepherd(context); Vector<MarkedIndividual> rIndividuals = new Vector<MarkedIndividual>(); myShepherd.beginDBTransaction(); String order = ""; String locCode=request.getParameter("locationCodeField"); MarkedIndividualQueryResult result = IndividualQueryProcessor.processQuery(myShepherd, request, order); rIndividuals = result.getResult(); int numIndividuals=rIndividuals.size(); int numSharks=0; out.println("<pre>"); out.println("title='Example CAPTURE Export of Marked Individuals from the "+CommonConfiguration.getHTMLTitle(context)+"'"); try { int startYear=(new Integer(request.getParameter("year1"))).intValue(); int startMonth=(new Integer(request.getParameter("month1"))).intValue(); int endMonth=(new Integer(request.getParameter("month2"))).intValue(); int endYear=(new Integer(request.getParameter("year2"))).intValue(); //check for seasons wrapping over years int wrapsYear=0; if(startMonth>endMonth) {wrapsYear=1;} int numYearsCovered=endYear-startYear-wrapsYear+1; out.println("task read captures x matrix occasions="+numYearsCovered); //now, let's print out our capture histories //out.println("<br><br>Capture histories for live recaptures modeling: "+startYear+"-"+endYear+", months "+startMonth+"-"+endMonth+"<br><br><pre>"); int maxLengthID=0; for(int p=0;p<numIndividuals;p++) { MarkedIndividual s=rIndividuals.get(p); if(s.getIndividualID().length()>maxLengthID){maxLengthID=s.getIndividualID().length();} } out.println("format='(a"+maxLengthID+","+numYearsCovered+"f1.0)'"); out.println("read input data"); for(int i=0;i<numIndividuals;i++) { MarkedIndividual s=rIndividuals.get(i); boolean wasSightedInRequestedLocation=false; if((request.getParameter("locationCodeField")!=null)&&(!request.getParameter("locationCodeField").trim().equals(""))){ wasSightedInRequestedLocation=s.wasSightedInLocationCode(locCode); } else{ wasSightedInRequestedLocation=true; } if((wasSightedInRequestedLocation)&&(s.wasSightedInPeriod(startYear,startMonth,endYear,endMonth))) { boolean wasReleased=false; StringBuffer sb=new StringBuffer(); //lets print out each shark's capture history for(int f=startYear;f<=(endYear-wrapsYear);f++) { boolean sharkWasSeen=false; if((request.getParameter("locationCodeField")!=null)&&(!request.getParameter("locationCodeField").trim().equals(""))){ sharkWasSeen=s.wasSightedInPeriod(f,startMonth,1,(f+wrapsYear),endMonth, 31, locCode); } else{ sharkWasSeen=s.wasSightedInPeriod(f,startMonth,1,(f+wrapsYear),endMonth, 31); } if(sharkWasSeen){ sb.append("1"); wasReleased=true; } else{ sb.append("0"); } } if(wasReleased) { String adjustedID=s.getIndividualID(); while(adjustedID.length()<maxLengthID){adjustedID+="X";} out.println(adjustedID+sb.toString()); numSharks++; } } //end if } //end while myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); } catch(Exception e) { out.println("<p><strong>Error encountered</strong></p>"); out.println("<p>Please let the webmaster know you encountered an error at: IndividualSearchExportCapture servlet</p>"); e.printStackTrace(); myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); } out.println("task closure test<br/>task model selection"); //out.println("task population estimate ALL"); //out.println("task population estimate NULL JACKKNIFE REMOVAL ZIPPEN MT-CH MH-CH MTH-CH"); out.println("task population estimate ALL"); out.close(); } }
gforghetti/jenkins-tomcat-wildbook
src/main/java/org/ecocean/servlet/export/IndividualSearchExportCapture.java
Java
gpl-2.0
5,158
package com.peiban.app.ui; import java.util.List; import java.util.Map; import net.tsz.afinal.http.AjaxCallBack; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.peiban.R; import com.peiban.app.Constants; import com.peiban.app.api.AlbumApi; import com.peiban.app.api.ErrorCode; import com.peiban.app.api.FriendApi; import com.peiban.app.api.UserInfoApi; import com.peiban.app.control.AlbumControl; import com.peiban.app.control.DialogMark; import com.peiban.app.ui.common.ChatPrompt; import com.peiban.app.ui.common.ChatPrompt.ChatPromptLisenter; import com.peiban.app.ui.common.FinalOnloadBitmap; import com.peiban.command.TextdescTool; import com.peiban.vo.AlbumVo; import com.peiban.vo.CustomerVo; /** * * 功能: 详细资料 <br /> * 日期:2013-5-28<br /> * 地点:淘高手网<br /> * 版本:ver 1.0<br /> * * @author fighter * @since */ public abstract class DetailActivity extends BaseActivity { private static final String TAG = DetailActivity.class.getCanonicalName(); private static final String FRIEND = "好友可见"; private static final String VIP_TAG = "VIP/认证可见"; /** 头像 */ private ImageView imgHead; /** 角标 */ private ImageView imgSubscript; /** 认证提示 */ private TextView txtAuth; /** 认证与 成为 VIP 按钮 */ private Button btnAuth; private Button btnVip; /** 用户名 */ private TextView txtUserName; /** 性别 */ private ImageView imgSex; /** 年龄 */ private TextView txtAge; /** 在线状态 */ private TextView txtLineState; /** 签名 */ private TextView txtSign; /** 相册 */ private LinearLayout layoutAlbum; private TextView textAlbum; /** * 项目列表 */ private LinearLayout layoutProject; /** QQ */ private TextView txtQq; /** 身高 */ private TextView txtHeight; /** 体重 */ private TextView txtBody; /** 职业 */ private TextView txtProfession; /** 手机号码 */ private TextView txtPhone; /** 薪资意愿 */ private TextView txtWages; /** 兴趣爱好 */ private TextView txtHobby; private Button btnSayHello; private Button btnAddFriend; private Button btnApply1; private Button btnApply2; private LinearLayout mDetailsInfo; private LinearLayout mDetailsInfoHide; private LinearLayout mApply; private CustomerVo customer; private UserInfoApi userInfoApi; private FriendApi friendApi; private DialogMark dialogMark; @Override protected void initTitle() { setBtnBack(); setTitleContent(R.string.details_title); } @Override protected void baseInit() { super.baseInit(); customer = (CustomerVo) getIntent().getSerializableExtra("data"); if (customer == null) { Toast.makeText(getBaseContext(), "操作错误.", Toast.LENGTH_SHORT) .show(); finish(); return; } dialogMark = new DialogMark(DetailActivity.this, customer) { @Override protected void markName(String markName) { DetailActivity.this.markName(markName); } }; userInfoApi = new UserInfoApi(); friendApi = new FriendApi(); mDetailsInfo = (LinearLayout) this.findViewById(R.id.details_info); mApply = (LinearLayout) this.findViewById(R.id.details_apply); this.imgHead = (ImageView) this .findViewById(R.id.details_head_img_head); this.imgSex = (ImageView) this.findViewById(R.id.details_head_img_sex); this.imgSubscript = (ImageView) this .findViewById(R.id.details_head_img_subscript); this.txtUserName = (TextView) this .findViewById(R.id.details_head_txt_username); this.txtAge = (TextView) this.findViewById(R.id.details_head_txt_age); this.txtLineState = (TextView) this .findViewById(R.id.details_head_txt_line_state); this.txtAuth = (TextView) this .findViewById(R.id.details_head_txt_auth_state); this.textAlbum = (TextView) this.findViewById(R.id.details_layout_albums_tag); this.btnAuth = (Button) this.findViewById(R.id.details_head_btn_auth); this.btnVip = (Button) this.findViewById(R.id.details_head_btn_vip); this.txtSign = (TextView) this.findViewById(R.id.detail_info_signature); this.txtHeight = (TextView) this.findViewById(R.id.detail_info_tall); this.txtBody = (TextView) this.findViewById(R.id.detail_info_weight); this.txtProfession = (TextView) this.findViewById(R.id.detail_info_job); this.txtPhone = (TextView) this .findViewById(R.id.detail_info_mobilephone); this.txtQq = (TextView) this.findViewById(R.id.detail_info_qq); this.txtWages = (TextView) this.findViewById(R.id.detail_info_salary); this.txtHobby = (TextView) this.findViewById(R.id.detail_info_savor); this.layoutAlbum = (LinearLayout) this .findViewById(R.id.details_layout_albums); //this.layoutProject = (LinearLayout)this.findViewById(R.id.details_layout_projects); this.btnApply1 = (Button) this.findViewById(R.id.details_apply_btn1); this.btnApply2 = (Button) this.findViewById(R.id.details_apply_btn2); this.btnAddFriend = (Button) this .findViewById(R.id.details_btn_add_friend); this.btnSayHello = (Button) this .findViewById(R.id.details_btn_say_hello); this.mDetailsInfoHide = (LinearLayout) this .findViewById(R.id.details_info_hide); addLitener(); showHeadInfo(); getScore(); getApplyAuth(); } private void addLitener() { View.OnClickListener l = new DetailOnClick(); getBtnAddFriend().setOnClickListener(l); getBtnSayHello().setOnClickListener(l); getBtnApply1().setOnClickListener(l); getBtnApply2().setOnClickListener(l); getImgHead().setOnClickListener(l); } /** * 更新我的信息 * * @author fighter <br /> * 创建时间:2013-6-19<br /> * 修改时间:<br /> */ protected void updateHeadInfo() { CustomerVo tempVo = getMyCustomerVo(); if(tempVo != null){ customer = tempVo; } showHeadInfo(); showInfo(); } protected void showHeadInfo() { if ("1".equals(customer.getSex())) { this.imgSex.setImageResource(R.drawable.sex_man); } else { this.imgSex.setImageResource(R.drawable.sex_woman); } if(Constants.CustomerType.CHATTING.equals(customer.getCustomertype())){ if("1".equals(customer.getAgent())){ imgSubscript.setImageResource(R.drawable.subscript_economic); imgSubscript.setVisibility(View.VISIBLE); }else if("1".equals(customer.getHeadattest())){ imgSubscript.setVisibility(View.VISIBLE); imgSubscript.setBackgroundResource(R.drawable.subscript_auth); }else{ imgSubscript.setVisibility(View.GONE); } }else{ if("1".equals(customer.getVip())){ imgSubscript.setVisibility(View.VISIBLE); imgSubscript.setBackgroundResource(R.drawable.subscript_vip); }else{ imgSubscript.setVisibility(View.GONE); } } FinalOnloadBitmap.finalDisplay(getBaseContext(), customer, imgHead, getHeadBitmap()); this.txtWages.setText(customer.getSalary()); String name = TextdescTool.getCustomerName(customer); this.txtUserName.setText(name); this.txtAge.setText(TextdescTool.dateToAge(customer.getBirthday()) + "岁"); showInfo(); } /** * 展现信息 * * 作者:fighter <br /> * 创建时间:2013-5-28<br /> * 修改时间:<br /> */ public void showInfo() { mDetailsInfo.setVisibility(View.VISIBLE); mDetailsInfoHide.setVisibility(View.GONE); this.txtSign.setText(customer.getSign()); this.txtQq.setText(customer.getQq()); this.txtBody.setText(customer.getWeight()); this.txtHeight.setText(customer.getHeight()); this.txtPhone.setText(customer.getPhone()); this.txtProfession.setText(customer.getProfession()); this.txtHobby.setText(customer.getInterest()); } public void hideInfo() { // mDetailsInfo.setVisibility(View.GONE); // mDetailsInfoHide.setVisibility(View.VISIBLE); } public void hideApply() { mApply.setVisibility(View.GONE); } public void showApply() { mApply.setVisibility(View.VISIBLE); } protected void markName(final String markName) { if (!checkNetWork()) { return; } friendApi.markFriend(getUserInfoVo().getUid(), customer.getUid(), markName, new AjaxCallBack<String>() { @Override public void onStart() { super.onStart(); getWaitDialog().setMessage("修改中..."); getWaitDialog().show(); } @Override public void onSuccess(String t) { super.onSuccess(t); getWaitDialog().cancel(); String data = ErrorCode.getData(getBaseContext(), t); if (data != null) { if ("1".equals(data)) { markNameSuccess(markName); } } } @Override public void onFailure(Throwable t, String strMsg) { super.onFailure(t, strMsg); getWaitDialog().cancel(); showToast(strMsg); } }); } protected void markNameSuccess(String markName) { getPromptDialog().addCannel(); getPromptDialog().removeConfirm(); getPromptDialog().setCannelText("确定"); getPromptDialog().setMessage("修改成功!"); getPromptDialog().show(); customer.setMarkName(markName); showHeadInfo(); } protected void getNetworkAlum(){ } /** * 从服务器获取相册信息 * */ protected void getNetworkAlbum() { // TODO 从服务器获取相册信息 if (!checkNetWork()) { showToast(getResources().getString(R.string.toast_network)); }else { AlbumApi albumApi = new AlbumApi(); String uid = getUserInfoVo().getUid(); albumApi.getAlbum(uid, getCustomer().getUid(), new AjaxCallBack<String>() { @Override public void onStart() { // TODO 准备从服务器获取 super.onStart(); } @Override public void onSuccess(String t) { // TODO 服务器获取成功 super.onSuccess(t); String data = ErrorCode.getData(t); if (!"".equals(data)) { showAlbum(data); } else { getLayoutAlbum().setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(getUserInfoVo().getUid().equals(getCustomer().getUid())){ Intent intent=new Intent(DetailActivity.this,AlbumActivity.class); startActivity(intent); }else{ Intent intent=new Intent(DetailActivity.this,FriendAlbumActivity.class); intent.putExtra("touid", getCustomer().getUid()); startActivity(intent); } } }); getWaitDialog().dismiss(); } } @Override public void onFailure(Throwable t, String strMsg) { // TODO 服务器获取失败 super.onFailure(t, strMsg); } }); } } /** * 显示相册信息 * * */ private void showAlbum(String data) { if(DEBUG){ Log.e("相册:", data); } if(FRIEND.equals(data)){ textAlbum.setVisibility(View.VISIBLE); textAlbum.setText(FRIEND); layoutAlbum.setVisibility(View.GONE); }else if(VIP_TAG.equals(data)){ textAlbum.setVisibility(View.VISIBLE); textAlbum.setText(VIP_TAG); layoutAlbum.setVisibility(View.GONE); }else{ textAlbum.setVisibility(View.GONE); layoutAlbum.setVisibility(View.VISIBLE); try { List<AlbumVo> albumList=null; albumList=JSONArray.parseArray(data, AlbumVo.class); AlbumControl albumControl=new AlbumControl(DetailActivity.this,getLayoutAlbum(),albumList); albumControl.showAlbum(getUserInfoVo().getUid(),getCustomer().getUid()); } catch (Exception e) { // TODO: handle exception } } } /** * 获取积分 * * 作者:fighter <br /> * 创建时间:2013-5-28<br /> * 修改时间:<br /> */ protected void getScore() { getUserInfoApi().getScore(getUserInfoVo().getUid(), getCustomer().getUid(), new AjaxCallBack<String>() { @Override public void onSuccess(String t) { super.onSuccess(t); int errorCode = ErrorCode.getError(t); if (errorCode == 0) { Map<String, String> data = (Map<String, String>) JSON .parse(ErrorCode.getData(t)); scoreUploadSuccess(data); } else { scoreUploadError(); } } @Override public void onFailure(Throwable t, String strMsg) { super.onFailure(t, strMsg); scoreUploadError(); } }); } /** * 获取评分成功. * * @param data * ascore 外表评分 sscore 服务评分 usercp 等级 作者:fighter <br /> * 创建时间:2013-5-28<br /> * 修改时间:<br /> */ protected abstract void scoreUploadSuccess(Map<String, String> data); /** * 评分获取失败 * * 作者:fighter <br /> * 创建时间:2013-5-28<br /> * 修改时间:<br /> */ protected abstract void scoreUploadError(); /** * @return the 头像 */ public ImageView getImgHead() { return imgHead; } /** * @return the 用户名 */ public TextView getTxtUserName() { return txtUserName; } /** * @return the 性别 */ public ImageView getImgSex() { return imgSex; } /** * @return the 年龄 */ public TextView getTxtAge() { return txtAge; } /** * @return the 在线状态 */ public TextView getTxtLineState() { return txtLineState; } /** * @return the 个性签名 */ public TextView getTxtSign() { return txtSign; } /** * @return the 相册 */ public LinearLayout getLayoutAlbum() { return layoutAlbum; } /** * @return the qq */ public TextView getTxtQq() { return txtQq; } /** * @return the 身高 */ public TextView getTxtHeight() { return txtHeight; } /** * @return the 体重 */ public TextView getTxtBody() { return txtBody; } /** * @return the 职业 */ public TextView getTxtProfession() { return txtProfession; } /** * @return the 手机号 */ public TextView getTxtPhone() { return txtPhone; } /** * @return the 资金意愿 */ public TextView getTxtWages() { return txtWages; } /** * @return the 兴趣 */ public TextView getTxtHobby() { return txtHobby; } /** * @return the 角标 */ public ImageView getImgSubscript() { return imgSubscript; } public DialogMark getDialogMark() { return dialogMark; } /** * @return the 认证按钮 */ public Button getBtnAuth() { return btnAuth; } public Button getBtnVip() { return btnVip; } /** * @return the 认证提示 */ public TextView getTxtAuth() { return txtAuth; } /** * @return 打招呼按钮 */ public Button getBtnSayHello() { return btnSayHello; } /** * @return 添加好友按钮 */ public Button getBtnAddFriend() { return btnAddFriend; } /** * @return the customer */ public CustomerVo getCustomer() { return customer; } /** * @return the btnApply1 */ public Button getBtnApply1() { return btnApply1; } /** * @return the btnApply2 */ public Button getBtnApply2() { return btnApply2; } /** * @return the 用户信息接口 */ public UserInfoApi getUserInfoApi() { return userInfoApi; } /** * 获取是否能查看好友信息权限. * * 作者:fighter <br /> * 创建时间:2013-5-29<br /> * 修改时间:<br /> */ protected void applyAuth() { if (!checkNetWork()) return; } /*** * 获取是否有查看权限. * * 作者:fighter <br /> * 创建时间:2013-6-14<br /> * 修改时间:<br /> */ protected void getApplyAuth() { } /** * 申请查看 * * 作者:fighter <br /> * 创建时间:2013-5-29<br /> * 修改时间:<br /> */ protected void apply1Action() { if(!checkCustomerType()){ return; } getUserInfoApi().applyAuth(getUserInfoVo().getUid(), customer.getUid(), new ApplyAuthCallback()); } protected void apply2Action() { if (!checkNetWork()) { showToast(getResources().getString(R.string.toast_network)); return; } System.out.println("评价::;;"); if (Constants.CustomerType.CHATTING.equals(getCustomer() .getCustomertype())) { Intent intent = new Intent(DetailActivity.this, EvaluateActivity.class); intent.putExtra("data", getCustomer()); startActivity(intent); } else { evaluateSorce(); } } /** * 判断用户类型评分 * */ public void evaluateSorce() { if (Constants.CustomerType.CHATTING.equals(getCustomer() .getCustomertype())) { editSorce(getCustomer().getAscore(), getCustomer().getSscore()); } else { editSorce("0", "0"); } } /** * 评分 Param asorce:外貌评分,ssorce:服务评分 ps:外貌评分和服务评分都是0即上传魅力值 * */ public void editSorce(String asorce, String ssorce) { userInfoApi.editScore(getUserInfoVo().getUid(), getCustomer().getUid(), asorce, ssorce, new AjaxCallBack<String>() { @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); getWaitDialog().setMessage("提交请求"); getWaitDialog().show(); } @Override public void onSuccess(String t) { // TODO Auto-generated method stub super.onSuccess(t); String data = ErrorCode.getData(getBaseContext(), t); if (data != null && "1".equals(data)) { getWaitDialog().setMessage("提交成功"); } else { getWaitDialog().setMessage("提交失败"); } getWaitDialog().cancel(); } @Override public void onFailure(Throwable t, String strMsg) { // TODO Auto-generated method stub super.onFailure(t, strMsg); getWaitDialog().setMessage("提交失败:" + strMsg); getWaitDialog().cancel(); } }); } protected void addFriendAction() { //20151119 暂时不验证用户 // if(!checkCustomerType()){ // return; // } if (!checkNetWork()) return; getFriendApi().toFriend(getUserInfoVo().getUid(), getCustomer().getUid(), new AddFriendCallback()); } protected void sayHelloAction() { //20151119 // if(!checkCustomerType()){ // return; // } // 1. 判断本地是否有该用户. CustomerVo tempCustomerVo = null; try { tempCustomerVo = getFinalDb().findById(getCustomer().getUid(), CustomerVo.class); } catch (Exception e) { } // 2. 没有就保存. if (tempCustomerVo == null) { try { getCustomer().setFriend("0"); getFinalDb().save(getCustomer()); } catch (Exception e) { } } // if(!ChatPrompt.isShow(getBaseContext())){ // ChatPrompt.showPrompt(this, new ChatPromptLisenter(this){ // // @Override // public void onClick(View v) { // super.onClick(v); // Intent intent = new Intent(DetailActivity.this, ChatMainActivity.class); // intent.putExtra("data", getCustomer()); // startActivity(intent); // } // // }); // }else{ Intent intent = new Intent(DetailActivity.this, ChatMainActivity.class); intent.putExtra("data", getCustomer()); startActivity(intent); // } } class DetailOnClick implements View.OnClickListener { @Override public void onClick(View v) { if (v == getBtnAddFriend()) { addFriendAction(); } else if (v == getBtnSayHello()) { sayHelloAction(); } else if (v == getBtnApply1()) { apply1Action(); } else if (v == getBtnApply2()) { apply2Action(); } else if (v.getId() == R.id.detail_layout_albums) { if (getUserInfoVo().getUid() != getCustomer().getUid()) { Intent intent = new Intent(DetailActivity.this, FriendAlbumActivity.class); intent.putExtra("fid", getCustomer().getUid()); startActivity(intent); } }else if(v == getImgHead()){ Intent intent = new Intent(DetailActivity.this, ShowHeadActivity.class); intent.putExtra("data", customer.getHead()); startActivity(intent); } } } /** * @return the friendApi */ public FriendApi getFriendApi() { return friendApi; } /*** * 效验用户是否给我授权权限查看用户信息 * * @author fighter <br /> * 创建时间:2013-6-20<br /> * 修改时间:<br /> */ protected void checkUserAuth(){ if("1".equals(customer.getFriend())){ return; } getUserInfoApi().checkAuth(getUserInfoVo().getUid(), customer.getUid(), new AjaxCallBack<String>() { @Override public void onSuccess(String t) { super.onSuccess(t); try { String data = ErrorCode.getData(t); if(data != null){ // 如果没有权限 显示申请查看信息. if(!"1".equals(data)){ getBtnApply1().setVisibility(View.VISIBLE); } } } catch (Exception e) { // TODO: handle exception } } }); } /** * 获取用户在服务器上的信息 * * @author fighter <br /> * 创建时间:2013-6-27<br /> * 修改时间:<br /> */ protected void getRefresh() { Log.d(TAG, "getRefresh()"); getUserInfoApi().getInfo(getMyCustomerVo().getUid(), customer.getUid(), new AjaxCallBack<String>() { @Override public void onSuccess(String t) { super.onSuccess(t); Log.v(TAG, t); try { String data = ErrorCode.getData(t); if(!TextUtils.isEmpty(data)){ CustomerVo customerVo = JSONObject.toJavaObject(JSONObject.parseObject(data), CustomerVo.class); customer = customerVo; showHeadInfo(); showInfo(); System.out.println("显示成功!"); } } catch (Exception e) { Log.e(TAG, "getRefresh()", e); } } }); } private boolean checkUserType(){ boolean flag = false; if("1".equals(customer.getFriend())){ flag = true; }else{ // 如果是陪聊用户 检查是否是认证 if(Constants.CustomerType.CHATTING.equals(getMyCustomerVo().getCustomertype())){ if("1".equals(getMyCustomerVo().getHeadattest())){ flag = true; }else{ flag = false; } } // 如果是寻伴用户 检查是否是VIP if(Constants.CustomerType.WITHCHAT.equals(getMyCustomerVo().getCustomertype())){ if("1".equals(getMyCustomerVo().getVip())){ flag = true; }else{ flag = false; } } } return flag; } private boolean checkCustomerType(){ boolean flag = false; if("1".equals(customer.getFriend())){ flag = true; }else{ // 如果是陪聊用户 检查是否是认证 if(Constants.CustomerType.CHATTING.equals(getMyCustomerVo().getCustomertype())){ if("1".equals(getMyCustomerVo().getHeadattest())){ flag = true; }else{ flag = false; gotoAuth(); } } // 如果是寻伴用户 检查是否是VIP if(Constants.CustomerType.WITHCHAT.equals(getMyCustomerVo().getCustomertype())){ if("1".equals(getMyCustomerVo().getVip())){ flag = true; }else{ flag = false; gotoVip(); } } } return flag; } /** * 我要认证 * * @author fighter <br /> * 创建时间:2013-6-20<br /> * 修改时间:<br /> */ private void gotoAuth(){ getPromptDialog().addCannel(); getPromptDialog().addConfirm(new View.OnClickListener() { @Override public void onClick(View v) { // 去认证头像. getPromptDialog().cancel(); Intent intent = new Intent(DetailActivity.this, HeadAuthActivity.class); startActivity(intent); } }); getPromptDialog().setMessage("成为VIP/认证用户!"); getPromptDialog().setCannelText("以后在说"); getPromptDialog().setConfirmText("我要认证"); getPromptDialog().show(); } /*** * 提示是否成为VIP * * @author fighter <br /> * 创建时间:2013-6-20<br /> * 修改时间:<br /> */ private void gotoVip(){ getPromptDialog().addCannel(); getPromptDialog().addConfirm(new View.OnClickListener() { @Override public void onClick(View v) { // 去认证头像. getPromptDialog().cancel(); Intent intent = new Intent(DetailActivity.this, MyPointActivity.class); startActivity(intent); } }); getPromptDialog().setMessage("成为VIP用户!"); getPromptDialog().setCannelText("以后在说"); getPromptDialog().setConfirmText("成为VIP"); getPromptDialog().show(); } }
sidney9111/Weixin_android
src/com/peiban/app/ui/DetailActivity.java
Java
gpl-2.0
24,070
/****************************************************************************** * Product: Compiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.adempierelbr.process; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import org.adempierelbr.model.X_LBR_AverageCost; import org.adempierelbr.model.X_LBR_AverageCostLine; import org.adempierelbr.util.AdempiereLBR; import org.compiere.model.MPeriod; import org.compiere.process.ProcessInfoParameter; import org.compiere.process.SvrProcess; import org.compiere.util.DB; import org.compiere.util.Env; import org.compiere.util.Msg; /** * Average Cost BR * * @author Ricardo Santana * @contributor Mario Grigioni * @version $Id: ProcAvgCostCreate.java, 30/07/2006 00:51:01 ralexsander Exp $ */ public class ProcAvgCostCreate extends SvrProcess { private int p_LBR_AverageCost_ID = 0; private String costType = ""; private final String MANUFACTURED = X_LBR_AverageCostLine.LBR_AVGCOSTTYPE_Manufactured; private final String PUCHASED = X_LBR_AverageCostLine.LBR_AVGCOSTTYPE_Purchased; public String trxName = null; /** * Prepare */ protected void prepare () { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("lbr_AvgCostType")) costType = (String) para[i].getParameter(); else log.log(Level.SEVERE, "Unknown Parameter: " + name); } p_LBR_AverageCost_ID = getRecord_ID(); } // prepare /** * Process * @return Info * @throws Exception */ protected String doIt() throws Exception { if (p_LBR_AverageCost_ID == 0) { log.warning("LBR_AverageCost_ID=" + p_LBR_AverageCost_ID); return "ERR: No LBR_AverageCost_ID"; } X_LBR_AverageCost avgCost = new X_LBR_AverageCost(getCtx(), p_LBR_AverageCost_ID, trxName); MPeriod period = new MPeriod(getCtx(), avgCost.getC_Period_ID(), trxName); cleanupLines(avgCost.get_ID(),costType); Map<Integer,BigDecimal> nfsComp = getNfComplementar(period); String sql = ""; if(costType.equals(PUCHASED)){ sql = "SELECT DISTINCT aux.M_Product_ID, QtyOnDate(aux.M_Product_ID, ?), " + "aux.CurrentCostPrice, SUM(aux.TotalCost), SUM(aux.QtyEntered) " + "FROM( " + "SELECT p.M_Product_ID, COALESCE(c.CurrentCostPrice,0) as CurrentCostPrice, " + "CASE WHEN ( il.LBR_CFOP_ID IN (SELECT LBR_CFOP_ID FROM LBR_CFOP WHERE Value LIKE '%.116' OR Value LIKE '%.117') ) " + "THEN " + "(SUM((il.PriceEntered-(il.lbr_PriceEnteredBR*0.0925))*il.QtyEntered)) " + "ELSE " + "SUM(il.PriceEntered*il.QtyEntered) " + "END AS TotalCost, " + "SUM(il.QtyEntered) as QtyEntered " + "FROM C_Invoice i " + "INNER JOIN C_InvoiceLine il ON i.C_Invoice_ID = il.C_Invoice_ID " + "INNER JOIN C_DocType dt ON dt.C_DocType_ID=i.C_DocTypeTarget_ID " + "INNER JOIN M_Product p ON p.M_Product_ID = il.M_Product_ID " + "LEFT JOIN M_Cost c ON (c.M_Product_ID = il.M_Product_ID AND " + "c.M_CostElement_ID = ?) " + "WHERE i.DocStatus IN ('CL', 'CO') " + "AND p.ProductType = 'I' " + "AND i.AD_Client_ID = ? " + "AND p.IsPurchased = 'Y' " + "AND PriceEntered > 0 " + "AND QtyEntered > 0 " + "AND dt.DocBaseType = 'API' " + "AND ((dt.lbr_HasOpenItems = 'Y' AND il.LBR_CFOP_ID NOT IN (SELECT LBR_CFOP_ID FROM LBR_CFOP WHERE Value LIKE '%.922')) " + "OR (dt.lbr_HasOpenItems = 'N' AND il.LBR_CFOP_ID IN (SELECT LBR_CFOP_ID FROM LBR_CFOP WHERE Value LIKE '%.116' OR Value LIKE '%.117'))) " + "AND TRUNC(i.DateAcct) BETWEEN ? AND ? " + "GROUP BY p.M_Product_ID, c.CurrentCostPrice, il.LBR_CFOP_ID " + "ORDER BY CurrentCostPrice DESC) aux " + "GROUP BY aux.M_Product_ID, aux.CurrentCostPrice"; } else if(costType.equals(MANUFACTURED)){ sql = "SELECT PlanCost.M_Product_ID, QtyOnDate(PlanCost.M_Product_ID, ?), c.CurrentCostPrice, " + "SUM(Custo*ProductionQty) AS Custo, SUM(ProductionQty) AS Qtd " + "FROM " + "(SELECT pp.M_ProductionPlan_ID, pp.M_Product_ID, pp.ProductionQty AS ProductionQty, " + "SUM((ABS(pl.MovementQty)/ABS(pp.ProductionQty)) * c.CurrentCostPrice) AS Custo FROM M_Production pr " + "INNER JOIN M_ProductionPlan pp ON pr.M_Production_ID=pp.M_Production_ID " + "INNER JOIN M_ProductionLine pl ON (pl.M_ProductionPlan_ID=pp.M_ProductionPlan_ID AND pl.M_Product_ID <> pp.M_Product_ID) " + "INNER JOIN M_Cost c ON (c.M_Product_ID=pl.M_Product_ID AND c.M_CostElement_ID=?) " + "WHERE pr.Processed='Y' " + "AND pr.AD_Client_ID=? " + "AND TRUNC(pr.MovementDate) BETWEEN ? AND ? " + " GROUP BY pp.M_ProductionPlan_ID, pp.M_Product_ID, pp.ProductionQty " + ") PlanCost INNER JOIN M_Cost c ON (c.M_Product_ID=PlanCost.M_Product_ID AND c.M_CostElement_ID=?) " + "GROUP BY PlanCost.M_Product_ID, CurrentCostPrice"; } PreparedStatement pstmt = null; ResultSet rs = null; try { int i=1; pstmt = DB.prepareStatement (sql, trxName); pstmt.setTimestamp(i++, AdempiereLBR.addDays(period.getStartDate(), -1)); pstmt.setInt(i++, avgCost.getM_CostElement_ID()); pstmt.setInt(i++, avgCost.getAD_Client_ID()); pstmt.setTimestamp(i++, period.getStartDate()); pstmt.setTimestamp(i++, period.getEndDate()); if(costType.equals(MANUFACTURED)) pstmt.setInt(i++, avgCost.getM_CostElement_ID()); rs = pstmt.executeQuery (); while (rs.next ()) { X_LBR_AverageCostLine line = new X_LBR_AverageCostLine(getCtx(), 0, trxName); line.setLBR_AverageCost_ID(p_LBR_AverageCost_ID); line.setM_Product_ID(rs.getInt(1)); line.setCurrentQty(rs.getBigDecimal(2)); line.setCurrentCostPrice(rs.getBigDecimal(3)); line.setCumulatedAmt(rs.getBigDecimal(4)); line.setCumulatedQty(rs.getBigDecimal(5)); line.setlbr_AvgCostType(costType); BigDecimal totCurrent = line.getCurrentCostPrice().multiply(line.getCurrentQty()); BigDecimal totCumulated = line.getCumulatedAmt(); if (costType.equals(PUCHASED) && !nfsComp.isEmpty()){ BigDecimal compAmt = nfsComp.get(rs.getInt(1)); if (compAmt != null && compAmt.signum() == 1){ totCumulated = totCumulated.add(compAmt); line.setExpenseAmt(compAmt); } } BigDecimal total = totCurrent.add(totCumulated); BigDecimal sumQty = line.getCurrentQty().add(line.getCumulatedQty()); if(sumQty.signum() == 0) { sumQty = Env.ONE; line.setDescription("ERRO NO CALCULO, DIVIDIDO POR ZERO"); } line.setFutureCostPrice(total.divide(sumQty, 12, BigDecimal.ROUND_HALF_UP)); line.save(); } /** Executar varias vezes devido aos niveis da LDM */ if(costType.equals(MANUFACTURED)) { int j=0; BigDecimal oldCost = Env.ZERO; Boolean allLevelsOK = false; while(!allLevelsOK) { i=1; sql = "SELECT PlanCost.M_Product_ID, PlanCost.LBR_AverageCostLine_ID, " + "SUM(Custo*ProductionQty) AS Custo, SUM(ProductionQty) AS Qtd " + "FROM " + "(SELECT pp.M_ProductionPlan_ID, pp.M_Product_ID, avgl.LBR_AverageCostLine_ID, pp.ProductionQty AS ProductionQty, " + "SUM((ABS(pl.MovementQty)/ABS(pp.ProductionQty)) * (CASE WHEN new_avg_cost.FutureCostPrice IS NOT NULL OR new_avg_cost.FutureCostPrice > 0 THEN new_avg_cost.FutureCostPrice ELSE c.CurrentCostPrice END)) AS Custo FROM M_Production pr " + "INNER JOIN M_ProductionPlan pp ON pr.M_Production_ID=pp.M_Production_ID " + "INNER JOIN M_ProductionLine pl ON (pl.M_ProductionPlan_ID=pp.M_ProductionPlan_ID AND pl.M_Product_ID <> pp.M_Product_ID) " + "INNER JOIN M_Cost c ON (c.M_Product_ID=pl.M_Product_ID AND c.M_CostElement_ID=?) " + "INNER JOIN LBR_AverageCostLine avgl ON (avgl.M_Product_ID=pp.M_Product_ID AND avgl.LBR_AverageCost_ID=? AND avgl.lbr_AvgCostType='M') " + " LEFT JOIN LBR_AverageCostLine new_avg_cost ON (new_avg_cost.M_Product_ID=pl.M_Product_ID AND new_avg_cost.LBR_AverageCost_ID=? AND new_avg_cost.lbr_AvgCostType='M') " + "WHERE pr.Processed='Y' " + "AND pr.AD_Client_ID=? " + "AND TRUNC(pr.MovementDate) BETWEEN ? AND ? " + "GROUP BY pp.M_ProductionPlan_ID, pp.M_Product_ID, pp.ProductionQty, avgl.LBR_AverageCostLine_ID " + ") PlanCost " + "GROUP BY PlanCost.M_Product_ID, PlanCost.LBR_AverageCostLine_ID"; pstmt = DB.prepareStatement (sql, trxName); pstmt.setInt(i++, avgCost.getM_CostElement_ID()); pstmt.setInt(i++, avgCost.getLBR_AverageCost_ID()); pstmt.setInt(i++, avgCost.getLBR_AverageCost_ID()); pstmt.setInt(i++, avgCost.getAD_Client_ID()); pstmt.setTimestamp(i++, period.getStartDate()); pstmt.setTimestamp(i++, period.getEndDate()); rs = pstmt.executeQuery (); while (rs.next ()) { X_LBR_AverageCostLine line = new X_LBR_AverageCostLine(getCtx(), rs.getInt(2), trxName); line.setCumulatedAmt(rs.getBigDecimal(3)); line.setCumulatedQty(rs.getBigDecimal(4)); BigDecimal totCurrent = line.getCurrentCostPrice().multiply(line.getCurrentQty()); BigDecimal totCumulated = line.getCumulatedAmt(); BigDecimal total = totCurrent.add(totCumulated); BigDecimal sumQty = line.getCurrentQty().add(line.getCumulatedQty()); if(sumQty.signum() == 0) { sumQty = Env.ONE; line.setDescription("ERRO NO CALCULO, DIVIDIDO POR ZERO"); } line.setFutureCostPrice(total.divide(sumQty, 12, BigDecimal.ROUND_HALF_UP)); line.save(); } BigDecimal result = DB.getSQLValueBD(avgCost.get_TrxName(), "SELECT SUM(CumulatedAmt+ExpenseAmt) " + "FROM LBR_AverageCostLine WHERE LBR_AverageCost_ID=?", avgCost.getLBR_AverageCost_ID()); log.info("Passo: " + j + " / Cost total: " + result); if(result.compareTo(oldCost) == 0 || j > 29) allLevelsOK = true; else{ oldCost = result; j++; } } } // Produtos Comprados if(costType.equals(PUCHASED)) avgCost.setlbr_AvgStep1(true); // Produtos Fabricados else avgCost.setlbr_AvgStep3(true); avgCost.save(trxName); } catch (Exception e) { log.log (Level.SEVERE, sql, e); } finally{ DB.close(rs, pstmt); } return Msg.getMsg(Env.getAD_Language(getCtx()), "ProcessOK", true); } // doIt private void cleanupLines(int ID, String costType){ String sql = "DELETE FROM LBR_AverageCostLine " + "WHERE lbr_AvgCostType=? AND LBR_AverageCost_ID=?"; DB.executeUpdate(sql, new Object[]{costType,ID}, false, trxName); } //cleanupLine private Map<Integer,BigDecimal> getNfComplementar(MPeriod period){ String sql = "SELECT M_Product_ID, SUM(ComplAmt) FROM ( " + "SELECT nfComplementar.*, (TotalLines * perct) as ComplAmt FROM ( " + "SELECT M_Product_ID, LineTotalAmt, " + "(SELECT TotalLines FROM LBR_NotaFiscal WHERE nfl.LBR_NotaFiscal_ID = LBR_NotaFiscal.LBR_NotaFiscal_ID) as GrandTotal, " + "ROUND(LineTotalAmt / (SELECT TotalLines FROM LBR_NotaFiscal WHERE nfl.LBR_NotaFiscal_ID = LBR_NotaFiscal.LBR_NotaFiscal_ID),4) as perct, " + "compl.LBR_RefNotaFiscal_ID, compl.TotalLines " + "FROM LBR_NotaFiscalLine nfl " + "INNER JOIN " + "(SELECT ref.LBR_NotaFiscal_ID as LBR_RefNotaFiscal_ID, complementar.LineNetAmt as TotalLines " + "FROM C_InvoiceLine complementar " + "INNER JOIN C_Invoice i ON (complementar.C_Invoice_ID = i.C_Invoice_ID) " + "INNER JOIN LBR_NotaFiscal ref ON (complementar.LBR_NotaFiscal_ID = ref.LBR_NotaFiscal_ID) " + "WHERE i.DocStatus='CO' AND complementar.C_Charge_ID = 3000114 " + "AND i.dateacct BETWEEN ? and ?) compl " + "ON (nfl.LBR_NotaFiscal_ID = compl.LBR_RefNotaFiscal_ID)) nfComplementar) " + "GROUP BY M_Product_ID"; Map<Integer, BigDecimal> nfs = new HashMap<Integer,BigDecimal>(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt.setTimestamp(1, period.getStartDate()); pstmt.setTimestamp(2, period.getEndDate()); rs = pstmt.executeQuery (); while (rs.next ()) { nfs.put(rs.getInt(1), rs.getBigDecimal(2)); } } catch (Exception e) { log.log(Level.SEVERE, "", e); } finally{ DB.close(rs, pstmt); } return nfs; } } //ProcAvgCostCreate
mgrigioni/oseb
base/src/org/adempierelbr/process/ProcAvgCostCreate.java
Java
gpl-2.0
13,740
<?php /** * fontset * * @version 1.2 * @author Creative Pulse * @copyright Creative Pulse 2009-2013 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL * @link http://www.creativepulse.gr */ // no direct access defined('_JEXEC') or die('Restricted access'); if ($mod->instance_id() == 1) { $document =& JFactory::getDocument(); $document->addStyleSheet('modules/mod_fontset/css/default.css'); } echo '<div id="mod_fontset_' . $mod->instance_id() . '" class="mod_fontset"> <span class="mod_fontset_smaller" onclick="mod_fontset_size_set(-2)">A-</span> &nbsp; <span class="mod_fontset_reset" onclick="mod_fontset_size_reset()">A</span> &nbsp; <span class="mod_fontset_larger" onclick="mod_fontset_size_set(2)">A+</span> </div> '; ?>
creativepulse/fontset
fontset-joomla15/mod_fontset/tmpl/default.php
PHP
gpl-2.0
757
/* Shape Settings Tab */ TP.shapesStore = Ext.create('Ext.data.Store', { fields: ['name', 'data'], proxy: { type: 'ajax', url: 'panorama.cgi?task=userdata_shapes', reader: { type: 'json', root: 'data' } }, data : thruk_shape_data }); TP.iconsetsStore = Ext.create('Ext.data.Store', { fields: ['name', 'sample', 'value', 'fileset'], proxy: { type: 'ajax', url: 'panorama.cgi?task=userdata_iconsets&withempty=1', reader: { type: 'json', root: 'data' } }, autoLoad: true, data : thruk_iconset_data }); TP.iconTypesStore = Ext.create('Ext.data.Store', { fields: ['name', 'value', 'icon'], autoLoad: false, data : [{value:'TP.HostStatusIcon', name:'Host', icon:url_prefix+'plugins/panorama/images/server.png'}, {value:'TP.HostgroupStatusIcon', name:'Hostgroup', icon:url_prefix+'plugins/panorama/images/server_link.png'}, {value:'TP.ServiceStatusIcon', name:'Service', icon:url_prefix+'plugins/panorama/images/computer.png'}, {value:'TP.ServicegroupStatusIcon', name:'Service Group', icon:url_prefix+'plugins/panorama/images/computer_link.png'}, {value:'TP.FilterStatusIcon', name:'Custom Filter', icon:url_prefix+'plugins/panorama/images/page_find.png'} ] }); TP.iconSettingsWindow = undefined; TP.iconShowEditDialog = function(panel) { panel.stateful = false; var tab = Ext.getCmp(panel.panel_id); var lastType = panel.xdata.appearance.type; // make sure only one window is open at a time if(TP.iconSettingsWindow != undefined) { TP.iconSettingsWindow.destroy(); } tab.disableMapControlsTemp(); TP.resetMoveIcons(); TP.skipRender = false; var defaultSpeedoSource = 'problems'; var perfDataUpdate = function() { // ensure fresh and correct performance data window.perfdata = {}; panel.setIconLabel(undefined, true); // update speedo var data = [['number of problems', 'problems'], ['number of problems (incl. warnings)', 'problems_warn']]; for(var key in perfdata) { if(defaultSpeedoSource == 'problems') { defaultSpeedoSource = 'perfdata:'+key; } var r = TP.getPerfDataMinMax(perfdata[key], '?'); var options = r.min+" - "+r.max; data.push(['Perf. Data: '+key+' ('+options+')', 'perfdata:'+key]); } /* use availability data as source */ var xdata = TP.get_icon_form_xdata(settingsWindow); if(xdata.label && xdata.label.labeltext && TP.availabilities && TP.availabilities[panel.id]) { var avail = TP.availabilities[panel.id]; for(var key in avail) { var d = avail[key]; var last = d.last != undefined ? d.last : '...'; if(last == -1) { last = '...'; } var options = d.opts['d']; if(d.opts['tm']) { options += '/'+d.opts['tm']; } data.push(['Availability: '+last+'% ('+options+')', 'avail:'+key]); } } var cbo = Ext.getCmp('speedosourceStore'); TP.updateArrayStoreKV(cbo.store, data); // update shape var data = [['fixed', 'fixed']]; for(var key in perfdata) { var r = TP.getPerfDataMinMax(perfdata[key], 100); var options = r.min+" - "+r.max; data.push(['Perf. Data: '+key+' ('+options+')', 'perfdata:'+key]); } var cbo = Ext.getCmp('shapesourceStore'); TP.updateArrayStoreKV(cbo.store, data); var cbo = Ext.getCmp('connectorsourceStore'); TP.updateArrayStoreKV(cbo.store, data); } /* General Settings Tab */ var stateUpdate = function() { var xdata = TP.get_icon_form_xdata(settingsWindow); TP.updateAllIcons(Ext.getCmp(panel.panel_id), panel.id, xdata); labelUpdate(); // update performance data stores perfDataUpdate(); } var generalItems = panel.getGeneralItems(); if(generalItems != undefined && panel.xdata.cls != 'TP.StaticIcon') { generalItems.unshift({ xtype: 'combobox', name: 'newcls', fieldLabel: 'Filter Type', displayField: 'name', valueField: 'value', store: TP.iconTypesStore, editable: false, listConfig : { getInnerTpl: function(displayField) { return '<div class="x-combo-list-item"><img src="{icon}" height=16 width=16 style="vertical-align:top; margin-right: 3px;">{name}<\/div>'; } }, value: panel.xdata.cls, listeners: { change: function(This, newValue, oldValue, eOpts) { if(TP.iconSettingsWindow == undefined) { return; } TP.iconSettingsWindow.mask('changing...'); var key = panel.id; var xdata = TP.get_icon_form_xdata(settingsWindow); var conf = {xdata: xdata}; conf.xdata.cls = newValue; panel.redrawOnly = true; panel.destroy(); TP.timeouts['timeout_' + key + '_show_settings'] = window.setTimeout(function() { TP.iconSettingsWindow.skipRestore = true; /* does not exist when changing a newly placed icon */ if(TP.cp.state[key]) { TP.cp.state[key].xdata.cls = newValue; } panel = TP.add_panlet({id:key, skip_state:true, tb:tab, autoshow:true, state:conf, type:newValue}, false); panel.xdata = conf.xdata; panel.classChanged = newValue; TP.iconShowEditDialog(panel); TP.cp.state[key].xdata.cls = oldValue; }, 50); } } }); } var generalTab = { title : 'General', type : 'panel', hidden: generalItems != undefined ? false : true, items: [{ xtype : 'panel', layout: 'fit', border: 0, items: [{ xtype: 'form', id: 'generalForm', bodyPadding: 2, border: 0, bodyStyle: 'overflow-y: auto;', submitEmptyText: false, defaults: { anchor: '-12', labelWidth: panel.generalLabelWidth || 132, listeners: { change: function(This, newValue, oldValue, eOpts) { if(newValue != "") { stateUpdate() } } } }, items: generalItems }] }] }; var updateDisabledFields = function(xdata) { var originalRenderUpdate = renderUpdate; renderUpdate = Ext.emptyFn; Ext.getCmp('shapeheightfield').setDisabled(xdata.appearance.shapelocked); Ext.getCmp('shapetogglelocked').toggle(xdata.appearance.shapelocked); Ext.getCmp('pieheightfield').setDisabled(xdata.appearance.pielocked); Ext.getCmp('pietogglelocked').toggle(xdata.appearance.pielocked); if(xdata.appearance.type == "connector" || xdata.appearance.type == "none") { Ext.getCmp('rotationfield').setVisible(false); } else { Ext.getCmp('rotationfield').setVisible(true); } renderUpdate = originalRenderUpdate; }; /* Layout Settings Tab */ var layoutTab = { title: 'Layout', type: 'panel', items: [{ xtype : 'panel', layout: 'fit', border: 0, items: [{ xtype: 'form', id: 'layoutForm', bodyPadding: 2, border: 0, bodyStyle: 'overflow-y: auto;', submitEmptyText: false, defaults: { anchor: '-12', labelWidth: 80 }, items: [{ fieldLabel: 'Position', xtype: 'fieldcontainer', layout: 'table', items: [{ xtype: 'label', text: 'x:', style: 'margin-left: 0; margin-right: 2px;' }, { xtype: 'numberfield', name: 'x', width: 55, value: panel.xdata.layout.x, listeners: { change: function(This, newValue, oldValue, eOpts) { if(!panel.noMoreMoves) { panel.noMoreMoves = true; var y = Number(This.up('panel').getValues().y); panel.setPosition(newValue, y); panel.noMoreMoves = false; } } }}, { xtype: 'label', text: 'y:', style: 'margin-left: 10px; margin-right: 2px;' }, { xtype: 'numberfield', name: 'y', width: 55, value: panel.xdata.layout.y, listeners: { change: function(This, newValue, oldValue, eOpts) { if(!panel.noMoreMoves) { panel.noMoreMoves = true; var x = Number(This.up('panel').getValues().x); panel.setPosition(x, newValue); panel.noMoreMoves = false; } } }}, { xtype: 'label', text: '(use cursor keys)', style: 'margin-left: 10px;', cls: 'form-hint' } ] }, { fieldLabel: 'Rotation', xtype: 'numberunit', allowDecimals: false, name: 'rotation', id: 'rotationfield', unit: '°', minValue: -360, maxValue: 360, step: 15, value: panel.xdata.layout.rotation != undefined ? panel.xdata.layout.rotation : 0, listeners: { change: function(This) { var xdata = TP.get_icon_form_xdata(settingsWindow); panel.applyRotation(This.value, xdata); } } }, { fieldLabel: 'Z-Index', xtype: 'numberfield', allowDecimals: false, name: 'zindex', minValue: -10, maxValue: 100, step: 1, value: panel.xdata.layout.zindex != undefined ? panel.xdata.layout.zindex : 0, listeners: { change: function(This) { var xdata = TP.get_icon_form_xdata(settingsWindow); panel.applyZindex(This.value, xdata); } } }, { fieldLabel: 'Scale', id: 'layoutscale', xtype: 'numberunit', unit: '%', allowDecimals: true, name: 'scale', minValue: 0, maxValue: 10000, step: 1, value: panel.xdata.layout.scale != undefined ? panel.xdata.layout.scale : 100, listeners: { change: function(This) { var xdata = TP.get_icon_form_xdata(settingsWindow); panel.applyScale(This.value, xdata); } }, disabled: (panel.hasScale || panel.xdata.appearance.type == 'icon') ? false : true, hidden: panel.iconType == 'text' ? true : false }] }] }] }; TP.shapesStore.load(); var renderUpdate = Ext.emptyFn; var renderUpdateDo = function(forceColor, forceRenderItem) { if(TP.skipRender) { return; } var xdata = TP.get_icon_form_xdata(settingsWindow); if(panel.iconType == 'image') { panel.setRenderItem(xdata); } if(xdata.appearance == undefined) { return; } if(xdata.appearance.type == undefined) { return; } if(xdata.appearance.type == 'shape') { forceRenderItem = true; } if(xdata.appearance.type != lastType || forceRenderItem) { if(panel.setRenderItem) { panel.setRenderItem(xdata, forceRenderItem); } } lastType = xdata.appearance.type; if(xdata.appearance.type == 'shape') { panel.shapeRender(xdata, forceColor); } if(xdata.appearance.type == 'pie') { panel.pieRender(xdata, forceColor); } if(xdata.appearance.type == 'speedometer') { panel.speedoRender(xdata, forceColor); } if(xdata.appearance.type == 'connector') { panel.connectorRender(xdata, forceColor); } labelUpdate(); updateDisabledFields(xdata); } var appearanceTab = { title: 'Appearance', type: 'panel', hidden: panel.hideAppearanceTab, listeners: { show: perfDataUpdate }, items: [{ xtype : 'panel', layout: 'fit', border: 0, items: [{ xtype: 'form', id: 'appearanceForm', bodyPadding: 2, border: 0, bodyStyle: 'overflow-y: auto;', submitEmptyText: false, defaults: { anchor: '-12', labelWidth: 60, listeners: { change: function() { renderUpdate(); } } }, items: [{ /* appearance type */ xtype: 'combobox', fieldLabel: 'Type', name: 'type', store: [['none','Label Only'], ['icon','Icon'], ['connector', 'Line / Arrow / Watermark'], ['pie', 'Pie Chart'], ['speedometer', 'Speedometer'], ['shape', 'Shape']], id: 'appearance_types', editable: false, listeners: { change: function(This, newValue, oldValue, eOpts) { Ext.getCmp('appearanceForm').items.each(function(f, i) { if(f.cls != undefined) { if(f.cls.match(newValue)) { f.show(); } else { f.hide(); } } }); if(newValue == 'icon' || panel.hasScale) { Ext.getCmp('layoutscale').setDisabled(false); } else { Ext.getCmp('layoutscale').setDisabled(true); } if(newValue == 'shape') { // fill in defaults var values = Ext.getCmp('appearanceForm').getForm().getValues(); if(!values['shapename']) { values['shapename'] = 'arrow'; values['shapelocked'] = true; values['shapewidth'] = 50; values['shapeheight'] = 50; values['shapecolor_ok'] = '#199C0F'; values['shapecolor_warning'] = '#CDCD0A'; values['shapecolor_critical'] = '#CA1414'; values['shapecolor_unknown'] = '#CC740F'; values['shapegradient'] = 0; values['shapesource'] = 'fixed'; } var originalRenderUpdate = renderUpdate; renderUpdate = Ext.emptyFn; Ext.getCmp('appearanceForm').getForm().setValues(values); renderUpdate = originalRenderUpdate; } if(newValue == 'pie') { // fill in defaults var values = Ext.getCmp('appearanceForm').getForm().getValues(); if(!values['piewidth']) { values['piewidth'] = 50; values['pieheight'] = 50; values['pielocked'] = true; values['pieshadow'] = false; values['piedonut'] = 0; values['pielabel'] = false; values['piegradient'] = 0; values['piecolor_ok'] = '#199C0F'; values['piecolor_warning'] = '#CDCD0A'; values['piecolor_critical'] = '#CA1414'; values['piecolor_unknown'] = '#CC740F'; values['piecolor_up'] = '#199C0F'; values['piecolor_down'] = '#CA1414'; values['piecolor_unreachable'] = '#CA1414'; } Ext.getCmp('appearanceForm').getForm().setValues(values); } if(newValue == 'speedometer') { // fill in defaults var values = Ext.getCmp('appearanceForm').getForm().getValues(); if(!values['speedowidth']) { values['speedowidth'] = 180; values['speedoshadow'] = false; values['speedoneedle'] = false; values['speedodonut'] = 0; values['speedogradient'] = 0; values['speedosource'] = defaultSpeedoSource; values['speedomargin'] = 5; values['speedosteps'] = 10; values['speedocolor_ok'] = '#199C0F'; values['speedocolor_warning'] = '#CDCD0A'; values['speedocolor_critical'] = '#CA1414'; values['speedocolor_unknown'] = '#CC740F'; values['speedocolor_bg'] = '#DDDDDD'; } Ext.getCmp('appearanceForm').getForm().setValues(values); } if(newValue == 'connector') { // fill in defaults var values = Ext.getCmp('appearanceForm').getForm().getValues(); if(!values['connectorwidth']) { var pos = panel.getPosition(); values['connectorfromx'] = pos[0]-100; values['connectorfromy'] = pos[1]; values['connectortox'] = pos[0]+100; values['connectortoy'] = pos[1]; values['connectorwidth'] = 3; values['connectorarrowtype'] = 'both'; values['connectorarrowwidth'] = 10; values['connectorarrowlength'] = 20; values['connectorarrowinset'] = 2; values['connectorcolor_ok'] = '#199C0F'; values['connectorcolor_warning'] = '#CDCD0A'; values['connectorcolor_critical'] = '#CA1414'; values['connectorcolor_unknown'] = '#CC740F'; values['connectorgradient'] = 0; values['connectorsource'] = 'fixed'; } var originalRenderUpdate = renderUpdate; renderUpdate = Ext.emptyFn; Ext.getCmp('appearanceForm').getForm().setValues(values); renderUpdate = originalRenderUpdate; } renderUpdate(); } } }, /* Icons */ { fieldLabel: 'Icon Set', id: 'iconset_field', xtype: 'combobox', name: 'iconset', cls: 'icon', store: TP.iconsetsStore, value: '', emptyText: 'use dashboards default icon set', displayField: 'name', valueField: 'value', listConfig : { getInnerTpl: function(displayField) { return '<div class="x-combo-list-item"><img src="{sample}" height=16 width=16 style="vertical-align:top; margin-right: 3px;">{name}<\/div>'; } }, listeners: { change: function(This) { renderUpdate(undefined, true); } } }, { xtype: 'panel', cls: 'icon', html: 'Place image sets in: '+usercontent_folder+'/images/status/', style: 'text-align: center;', bodyCls: 'form-hint', padding: '10 0 0 0', border: 0 }, /* Shapes */ { fieldLabel: 'Shape', xtype: 'combobox', name: 'shapename', cls: 'shape', store: TP.shapesStore, displayField: 'name', valueField: 'name', listConfig : { getInnerTpl: function(displayField) { TP.tmpid = 0; return '<div class="x-combo-list-item"><span name="{name}" height=16 width=16 style="vertical-align:top; margin-right: 3px;"><\/span>{name}<\/div>'; } }, listeners: { afterrender: function(This) { var me = This; me.shapes = []; This.getPicker().addListener('show', function(This) { Ext.Array.each(This.el.dom.getElementsByTagName('SPAN'), function(item, idx) { TP.show_shape_preview(item, panel, me.shapes); }); }); This.getPicker().addListener('refresh', function(This) { Ext.Array.each(This.el.dom.getElementsByTagName('SPAN'), function(item, idx) { TP.show_shape_preview(item, panel, me.shapes); }); }); }, destroy: function(This) { // clean up Ext.Array.each(This.shapes, function(item, idx) { item.destroy() }); }, change: function(This) { renderUpdate(); } } }, { fieldLabel: 'Size', xtype: 'fieldcontainer', name: 'shapesize', cls: 'shape', layout: 'table', defaults: { listeners: { change: function() { renderUpdate() } } }, items: [{ xtype: 'label', text: 'Width:', style: 'margin-left: 0; margin-right: 2px;' }, { xtype: 'numberunit', name: 'shapewidth', unit: 'px', width: 65, value: panel.xdata.appearance.shapewidth }, { xtype: 'label', text: 'Height:', style: 'margin-left: 10px; margin-right: 2px;' }, { xtype: 'numberunit', name: 'shapeheight', unit: 'px', width: 65, value: panel.xdata.appearance.shapeheight, id: 'shapeheightfield' }, { xtype: 'button', width: 22, icon: url_prefix+'plugins/panorama/images/link.png', enableToggle: true, style: 'margin-left: 2px; margin-top: -6px;', id: 'shapetogglelocked', toggleHandler: function(btn, state) { this.up('form').getForm().setValues({shapelocked: state ? '1' : '' }); renderUpdate(); } }, { xtype: 'hidden', name: 'shapelocked' } ] }, { fieldLabel: 'Colors', cls: 'shape', xtype: 'fieldcontainer', layout: { type: 'table', columns: 4, tableAttrs: { style: { width: '100%' } } }, defaults: { listeners: { change: function() { renderUpdateDo() } }, mouseover: function(color) { renderUpdateDo(color); }, mouseout: function(color) { renderUpdateDo(); } }, items: [ { xtype: 'label', text: panel.iconType == 'host' ? 'Up: ' : 'Ok: ' }, { xtype: 'colorcbo', name: 'shapecolor_ok', value: panel.xdata.appearance.shapecolor_ok, width: 80, tdAttrs: { style: 'padding-right: 10px;'}, colorGradient: { start: '#D3D3AE', stop: '#00FF00' } }, { xtype: 'label', text: panel.iconType == 'host' ? 'Unreachable: ' : 'Warning: ' }, { xtype: 'colorcbo', name: 'shapecolor_warning', value: panel.xdata.appearance.shapecolor_warning, width: 80, colorGradient: { start: '#E1E174', stop: '#FFFF00' } }, { xtype: 'label', text: panel.iconType == 'host' ? 'Down: ' : 'Critical: ' }, { xtype: 'colorcbo', name: 'shapecolor_critical', value: panel.xdata.appearance.shapecolor_critical, width: 80, colorGradient: { start: '#D3AEAE', stop: '#FF0000' } }, { xtype: 'label', text: 'Unknown: ', hidden: panel.iconType == 'host' ? true : false }, { xtype: 'colorcbo', name: 'shapecolor_unknown', value: panel.xdata.appearance.shapecolor_unknown, width: 80, colorGradient: { start: '#DAB891', stop: '#FF8900' }, hidden: panel.iconType == 'host' ? true : false }] }, { fieldLabel: 'Gradient', cls: 'shape', xtype: 'fieldcontainer', layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'numberfield', allowDecimals: true, name: 'shapegradient', maxValue: 1, minValue: -1, step: 0.05, value: panel.xdata.appearance.shapegradient, width: 55, listeners: { change: function() { renderUpdate(); } } }, { xtype: 'label', text: 'Source:', margins: {top: 2, right: 2, bottom: 0, left: 10} }, { name: 'shapesource', xtype: 'combobox', id: 'shapesourceStore', displayField: 'name', valueField: 'value', queryMode: 'local', store: { fields: ['name', 'value'], data: [] }, editable: false, value: panel.xdata.appearance.shapesource, listeners: { focus: perfDataUpdate, change: function() { renderUpdate(); } }, flex: 1 }] }, { xtype: 'panel', cls: 'shape', html: 'Place shapes in: '+usercontent_folder+'/shapes/', style: 'text-align: center;', bodyCls: 'form-hint', padding: '10 0 0 0', border: 0 }, /* Connector */ { fieldLabel: 'From', xtype: 'fieldcontainer', name: 'connectorfrom', cls: 'connector', layout: { type: 'hbox', align: 'stretch' }, defaults: { listeners: { change: function() { renderUpdate(); } } }, items: [{ xtype: 'label', text: 'x', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'connectorfromx', width: 70, unit: 'px', value: panel.xdata.appearance.connectorfromx }, { xtype: 'label', text: 'y', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'connectorfromy', width: 70, unit: 'px', value: panel.xdata.appearance.connectorfromy },{ xtype: 'label', text: 'Endpoints', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'combobox', name: 'connectorarrowtype', width: 70, matchFieldWidth: false, value: panel.xdata.appearance.connectorarrowtype, store: ['both', 'left', 'right', 'none'], listConfig : { getInnerTpl: function(displayField) { return '<div class="x-combo-list-item"><img src="'+url_prefix+'plugins/panorama/images/connector_type_{field1}.png" height=16 width=77 style="vertical-align:top; margin-right: 3px;"> {field1}<\/div>'; } } }] }, { fieldLabel: 'To', xtype: 'fieldcontainer', name: 'connectorto', cls: 'connector', layout: { type: 'hbox', align: 'stretch' }, defaults: { listeners: { change: function() { renderUpdate(); } } }, items: [{ xtype: 'label', text: 'x', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'connectortox', width: 70, unit: 'px', value: panel.xdata.appearance.connectortox }, { xtype: 'label', text: 'y', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'connectortoy', width: 70, unit: 'px', value: panel.xdata.appearance.connectortoy }] }, { fieldLabel: 'Size', xtype: 'fieldcontainer', name: 'connectorsize', cls: 'connector', layout: { type: 'hbox', align: 'stretch' }, defaults: { listeners: { change: function() { renderUpdate(); } } }, items: [{ xtype: 'label', text: 'Width', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'connectorwidth', width: 60, unit: 'px', value: panel.xdata.appearance.connectorwidth }, { xtype: 'label', text: 'Variable Width', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'checkbox', name: 'connectorvariable' }] }, { fieldLabel: 'Endpoints', xtype: 'fieldcontainer', name: 'connectorarrow', cls: 'connector', layout: { type: 'hbox', align: 'stretch' }, defaults: { listeners: { change: function() { renderUpdate(); } } }, items: [{ xtype: 'label', text: 'Width', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'connectorarrowwidth', width: 60, unit: 'px', minValue: 0, value: panel.xdata.appearance.connectorarrowwidth }, { xtype: 'label', text: 'Length', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'connectorarrowlength', width: 60, minValue: 0, unit: 'px', value: panel.xdata.appearance.connectorarrowlength }, { xtype: 'label', text: 'Inset', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'connectorarrowinset', width: 60, unit: 'px', value: panel.xdata.appearance.connectorarrowinset }] }, { fieldLabel: 'Colors', cls: 'connector', xtype: 'fieldcontainer', layout: { type: 'table', columns: 4, tableAttrs: { style: { width: '100%' } } }, defaults: { listeners: { change: function() { renderUpdateDo() } }, mouseover: function(color) { renderUpdateDo(color); }, mouseout: function(color) { renderUpdateDo(); } }, items: [ { xtype: 'label', text: panel.iconType == 'host' ? 'Up ' : 'Ok ' }, { xtype: 'colorcbo', name: 'connectorcolor_ok', value: panel.xdata.appearance.connectorcolor_ok, width: 80, tdAttrs: { style: 'padding-right: 10px;'}, colorGradient: { start: '#D3D3AE', stop: '#00FF00' } }, { xtype: 'label', text: panel.iconType == 'host' ? 'Unreachable ' : 'Warning ' }, { xtype: 'colorcbo', name: 'connectorcolor_warning', value: panel.xdata.appearance.connectorcolor_warning, width: 80, colorGradient: { start: '#E1E174', stop: '#FFFF00' } }, { xtype: 'label', text: panel.iconType == 'host' ? 'Down ' : 'Critical ' }, { xtype: 'colorcbo', name: 'connectorcolor_critical', value: panel.xdata.appearance.connectorcolor_critical, width: 80, colorGradient: { start: '#D3AEAE', stop: '#FF0000' } }, { xtype: 'label', text: 'Unknown ', hidden: panel.iconType == 'host' ? true : false }, { xtype: 'colorcbo', name: 'connectorcolor_unknown', value: panel.xdata.appearance.connectorcolor_unknown, width: 80, colorGradient: { start: '#DAB891', stop: '#FF8900' }, hidden: panel.iconType == 'host' ? true : false }] }, { fieldLabel: 'Gradient', cls: 'connector', xtype: 'fieldcontainer', layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'numberfield', allowDecimals: true, name: 'connectorgradient', maxValue: 1, minValue: -1, step: 0.05, value: panel.xdata.appearance.connectorgradient, width: 55, listeners: { change: function() { renderUpdate(); } } }, { xtype: 'label', text: 'Source', margins: {top: 2, right: 2, bottom: 0, left: 10} }, { name: 'connectorsource', xtype: 'combobox', id: 'connectorsourceStore', displayField: 'name', valueField: 'value', queryMode: 'local', store: { fields: ['name', 'value'], data: [] }, editable: false, value: panel.xdata.appearance.connectorsource, listeners: { focus: perfDataUpdate, change: function() { renderUpdate(); } }, flex: 1 }] }, { fieldLabel: 'Options', xtype: 'fieldcontainer', cls: 'connector', layout: 'table', defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } }, items: [ { xtype: 'label', text: 'Cust. Perf. Data Min', style: 'margin-left: 0px; margin-right: 2px;' }, { xtype: 'numberfield', allowDecimals: true, width: 70, name: 'connectormin', step: 100 }, { xtype: 'label', text: 'Max', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'numberfield', allowDecimals: true, width: 70, name: 'connectormax', step: 100 } ] }, /* Pie Chart */ { fieldLabel: 'Size', xtype: 'fieldcontainer', cls: 'pie', layout: 'table', defaults: { listeners: { change: function() { renderUpdate() } } }, items: [{ xtype: 'label', text: 'Width:', style: 'margin-left: 0; margin-right: 2px;' }, { xtype: 'numberunit', name: 'piewidth', unit: 'px', width: 65, value: panel.xdata.appearance.piewidth }, { xtype: 'label', text: 'Height:', style: 'margin-left: 10px; margin-right: 2px;' }, { xtype: 'numberunit', name: 'pieheight', unit: 'px', width: 65, value: panel.xdata.appearance.pieheight, id: 'pieheightfield' }, { xtype: 'button', width: 22, icon: url_prefix+'plugins/panorama/images/link.png', enableToggle: true, style: 'margin-left: 2px; margin-top: -6px;', id: 'pietogglelocked', toggleHandler: function(btn, state) { this.up('form').getForm().setValues({pielocked: state ? '1' : '' }); renderUpdate(); } }, { xtype: 'hidden', name: 'pielocked' } ] }, { fieldLabel: 'Options', xtype: 'fieldcontainer', cls: 'pie', layout: 'table', defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } }, items: [ { xtype: 'label', text: 'Shadow:', style: 'margin-left: 0px; margin-right: 2px;', hidden: true }, { xtype: 'checkbox', name: 'pieshadow', hidden: true }, { xtype: 'label', text: 'Label Name:', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'checkbox', name: 'pielabel' }, { xtype: 'label', text: 'Label Value:', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'checkbox', name: 'pielabelval' }, { xtype: 'label', text: 'Donut:', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'numberunit', allowDecimals: false, width: 60, name: 'piedonut', unit: 'px' }] }, { fieldLabel: 'Colors', cls: 'pie', xtype: 'fieldcontainer', layout: { type: 'table', columns: 4, tableAttrs: { style: { width: '100%' } } }, defaults: { listeners: { change: function() { renderUpdateDo() } }, mouseover: function(color) { renderUpdateDo(color); }, mouseout: function(color) { renderUpdateDo(); } }, items: [ { xtype: 'label', text: 'Ok:' }, { xtype: 'colorcbo', name: 'piecolor_ok', value: panel.xdata.appearance.piecolor_ok, width: 80, tdAttrs: { style: 'padding-right: 10px;'}, colorGradient: { start: '#D3D3AE', stop: '#00FF00' } }, { xtype: 'label', text: 'Warning:' }, { xtype: 'colorcbo', name: 'piecolor_warning', value: panel.xdata.appearance.piecolor_warning, width: 80, colorGradient: { start: '#E1E174', stop: '#FFFF00' } }, { xtype: 'label', text: 'Critical:' }, { xtype: 'colorcbo', name: 'piecolor_critical', value: panel.xdata.appearance.piecolor_critical, width: 80, colorGradient: { start: '#D3AEAE', stop: '#FF0000' } }, { xtype: 'label', text: 'Unknown:' }, { xtype: 'colorcbo', name: 'piecolor_unknown', value: panel.xdata.appearance.piecolor_unknown, width: 80, colorGradient: { start: '#DAB891', stop: '#FF8900' } }, { xtype: 'label', text: 'Up:' }, { xtype: 'colorcbo', name: 'piecolor_up', value: panel.xdata.appearance.piecolor_up, width: 80, colorGradient: { start: '#D3D3AE', stop: '#00FF00' } }, { xtype: 'label', text: 'Down:' }, { xtype: 'colorcbo', name: 'piecolor_down', value: panel.xdata.appearance.piecolor_down, width: 80, colorGradient: { start: '#D3AEAE', stop: '#FF0000' } }, { xtype: 'label', text: 'Unreachable:' }, { xtype: 'colorcbo', name: 'piecolor_unreachable', value: panel.xdata.appearance.piecolor_unreachable, width: 80, colorGradient: { start: '#D3AEAE', stop: '#FF0000' } }, { xtype: 'label', text: 'Gradient:' }, { xtype: 'numberfield', allowDecimals: true, width: 80, name: 'piegradient', maxValue: 1, minValue: -1, step: 0.05, value: panel.xdata.appearance.piegradient } ] }, /* Speedometer Chart */ { fieldLabel: 'Size', xtype: 'fieldcontainer', cls: 'speedometer', layout: 'table', defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } }, items: [{ xtype: 'label', text: 'Width:', style: 'margin-left: 0; margin-right: 2px;' }, { xtype: 'numberunit', name: 'speedowidth', unit: 'px', width: 65, value: panel.xdata.appearance.speedowidth }, { xtype: 'label', text: 'Shadow:', style: 'margin-left: 0px; margin-right: 2px;', hidden: true }, { xtype: 'checkbox', name: 'speedoshadow', hidden: true }, { xtype: 'label', text: 'Needle:', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'checkbox', name: 'speedoneedle' }, { xtype: 'label', text: 'Donut:', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'numberunit', allowDecimals: false, width: 60, name: 'speedodonut', unit: 'px' } ] }, { fieldLabel: 'Axis', xtype: 'fieldcontainer', cls: 'speedometer', layout: 'table', defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } }, items: [ { xtype: 'label', text: 'Steps:', style: 'margin-left: 0px; margin-right: 2px;' }, { xtype: 'numberfield', allowDecimals: false, width: 60, name: 'speedosteps', step: 1, minValue: 0, maxValue: 1000 }, { xtype: 'label', text: 'Margin:', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'numberunit', allowDecimals: false, width: 60, name: 'speedomargin', unit: 'px' }] }, { fieldLabel: 'Colors', cls: 'speedometer', xtype: 'fieldcontainer', layout: { type: 'table', columns: 4, tableAttrs: { style: { width: '100%' } } }, defaults: { listeners: { change: function() { renderUpdateDo() } }, mouseover: function(color) { renderUpdateDo(color); }, mouseout: function(color) { renderUpdateDo(); } }, items: [ { xtype: 'label', text: panel.iconType == 'host' ? 'Up: ' : 'Ok: ' }, { xtype: 'colorcbo', name: 'speedocolor_ok', value: panel.xdata.appearance.speedocolor_ok, width: 80, tdAttrs: { style: 'padding-right: 10px;'}, colorGradient: { start: '#D3D3AE', stop: '#00FF00' } }, { xtype: 'label', text: panel.iconType == 'host' ? 'Unreachable: ' : 'Warning: ' }, { xtype: 'colorcbo', name: 'speedocolor_warning', value: panel.xdata.appearance.speedocolor_warning, width: 80, colorGradient: { start: '#E1E174', stop: '#FFFF00' } }, { xtype: 'label', text: panel.iconType == 'host' ? 'Down: ' : 'Critical: ' }, { xtype: 'colorcbo', name: 'speedocolor_critical', value: panel.xdata.appearance.speedocolor_critical, width: 80, colorGradient: { start: '#D3AEAE', stop: '#FF0000' } }, { xtype: 'label', text: 'Unknown:' }, { xtype: 'colorcbo', name: 'speedocolor_unknown', value: panel.xdata.appearance.speedocolor_unknown, width: 80, colorGradient: { start: '#DAB891', stop: '#FF8900' } }, { xtype: 'label', text: 'Background:' }, { xtype: 'colorcbo', name: 'speedocolor_bg', value: panel.xdata.appearance.speedocolor_bg, width: 80 }, { xtype: 'label', text: 'Gradient:' }, { xtype: 'numberfield', allowDecimals: true, width: 80, name: 'speedogradient', maxValue: 1, minValue: -1, step: 0.05, value: panel.xdata.appearance.speedogradient } ] }, { fieldLabel: 'Source', name: 'speedosource', xtype: 'combobox', cls: 'speedometer', id: 'speedosourceStore', displayField: 'name', valueField: 'value', queryMode: 'local', store: { fields: ['name', 'value'], data: [] }, editable: false, listeners: { focus: perfDataUpdate, change: function() { renderUpdate(undefined, true) } } }, { fieldLabel: 'Options', xtype: 'fieldcontainer', cls: 'speedometer', layout: 'table', defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } }, items: [{ xtype: 'label', text: 'Invert:', style: 'margin-left: 0; margin-right: 2px;' }, { xtype: 'checkbox', name: 'speedoinvert' }, { xtype: 'label', text: 'Min:', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'numberfield', allowDecimals: true, width: 70, name: 'speedomin', step: 100 }, { xtype: 'label', text: 'Max:', style: 'margin-left: 8px; margin-right: 2px;' }, { xtype: 'numberfield', allowDecimals: true, width: 70, name: 'speedomax', step: 100 } ] }] }] }] }; /* Link Settings Tab */ var server_actions_menu = []; Ext.Array.each(action_menu_actions, function(name, i) { server_actions_menu.push({ text: name, icon: url_prefix+'plugins/panorama/images/cog.png', handler: function(This, eOpts) { This.up('form').getForm().setValues({link: 'server://'+name+'/'}) } }); }); var action_menus_menu = []; Ext.Array.each(action_menu_items, function(val, i) { var name = val[0]; action_menus_menu.push({ text: name, icon: url_prefix+'plugins/panorama/images/cog.png', handler: function(This, eOpts) { This.up('form').getForm().setValues({link: 'menu://'+name+'/'}) } }); }); var linkTab = { title: 'Link', type: 'panel', items: [{ xtype : 'panel', layout: 'fit', border: 0, items: [{ xtype: 'form', id: 'linkForm', bodyPadding: 2, border: 0, bodyStyle: 'overflow-y: auto;', submitEmptyText: false, defaults: { anchor: '-12', labelWidth: 132 }, items: [{ fieldLabel: 'Hyperlink', xtype: 'textfield', name: 'link', emptyText: 'http://... or predefined from below' }, { fieldLabel: 'Predefined Links', xtype: 'fieldcontainer', items: [{ xtype: 'button', text: 'Choose', icon: url_prefix+'plugins/panorama/images/world.png', menu: { items: [{ text: 'My Dashboards', icon: url_prefix+'plugins/panorama/images/user_suit.png', menu: [{ text: 'Loading...', icon: url_prefix+'plugins/panorama/images/loading-icon.gif', disabled: true }] }, { text: 'Public Dashboards', icon: url_prefix+'plugins/panorama/images/world.png', menu: [{ text: 'Loading...', icon: url_prefix+'plugins/panorama/images/loading-icon.gif', disabled: true }] }, { text: 'Show Details', icon: url_prefix+'plugins/panorama/images/application_view_columns.png', handler: function(This, eOpts) { This.up('form').getForm().setValues({link: 'dashboard://show_details'}) } }, { text: 'Refresh', icon: url_prefix+'plugins/panorama/images/arrow_refresh.png', handler: function(This, eOpts) { This.up('form').getForm().setValues({link: 'dashboard://refresh'}) } }, { text: 'Server Actions', icon: url_prefix+'plugins/panorama/images/lightning_go.png', menu: server_actions_menu, disabled: server_actions_menu.length > 0 ? false : true }, { text: 'Action Menus', icon: url_prefix+'plugins/panorama/images/lightning_go.png', menu: action_menus_menu, disabled: action_menus_menu.length > 0 ? false : true }], listeners: { afterrender: function(This, eOpts) { TP.load_dashboard_menu_items(This.items.get(0).menu, 'panorama.cgi?task=dashboard_list&list=my', function(val) { This.up('form').getForm().setValues({link: 'dashboard://'+val.replace(/^tabpan-tab_/,'')})}, true); TP.load_dashboard_menu_items(This.items.get(1).menu, 'panorama.cgi?task=dashboard_list&list=public', function(val) { This.up('form').getForm().setValues({link: 'dashboard://'+val.replace(/^tabpan-tab_/,'')})}, true); } } } }] }, { fieldLabel: 'New Tab', xtype: 'checkbox', name: 'newtab', boxLabel: '(opens links in new tab or window)' }] }] }] }; /* Label Settings Tab */ var labelUpdate = function() { var xdata = TP.get_icon_form_xdata(settingsWindow); panel.setIconLabel(xdata.label || {}, true); }; var labelTab = { title: 'Label', type: 'panel', items: [{ xtype : 'panel', layout: 'fit', border: 0, items: [{ xtype: 'form', id: 'labelForm', bodyPadding: 2, border: 0, bodyStyle: 'overflow-y: auto;', submitEmptyText: false, defaults: { anchor: '-12', labelWidth: 80, listeners: { change: labelUpdate } }, items: [{ fieldLabel: 'Labeltext', xtype: 'fieldcontainer', layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'textfield', name: 'labeltext', flex: 1, id: 'label_textfield', listeners: { change: labelUpdate } }, { xtype: 'button', icon: url_prefix+'plugins/panorama/images/lightning_go.png', margins: {top: 0, right: 0, bottom: 0, left: 3}, tooltip: 'open label editor wizard', handler: function(btn) { TP.openLabelEditorWindow(panel); } }] }, { fieldLabel: 'Color', xtype: 'colorcbo', name: 'fontcolor', value: '#000000', mouseover: function(color) { var oldValue=this.getValue(); this.setValue(color); labelUpdate(); this.setRawValue(oldValue); }, mouseout: function(color) { labelUpdate(); } }, { xtype: 'fieldcontainer', fieldLabel: 'Font', layout: { type: 'hbox', align: 'stretch' }, defaults: { listeners: { change: labelUpdate } }, items: [{ name: 'fontfamily', xtype: 'fontcbo', value: '', flex: 1, editable: false }, { xtype: 'numberunit', allowDecimals: false, name: 'fontsize', width: 60, unit: 'px', margins: {top: 0, right: 0, bottom: 0, left: 3}, value: panel.xdata.label.fontsize != undefined ? panel.xdata.label.fontsize : 14 }, { xtype: 'hiddenfield', name: 'fontitalic', value: panel.xdata.label.fontitalic }, { xtype: 'button', enableToggle: true, name: 'fontitalic', icon: url_prefix+'plugins/panorama/images/text_italic.png', margins: {top: 0, right: 0, bottom: 0, left: 3}, toggleHandler: function(btn, state) { this.up('form').getForm().setValues({fontitalic: state ? '1' : '' }); }, listeners: { afterrender: function() { if(panel.xdata.label.fontitalic) { this.toggle(); } } } }, { xtype: 'hiddenfield', name: 'fontbold', value: panel.xdata.label.fontbold }, { xtype: 'button', enableToggle: true, name: 'fontbold', icon: url_prefix+'plugins/panorama/images/text_bold.png', margins: {top: 0, right: 0, bottom: 0, left: 3}, toggleHandler: function(btn, state) { this.up('form').getForm().setValues({fontbold: state ? '1' : ''}); }, listeners: { afterrender: function() { if(panel.xdata.label.fontbold) { this.toggle(); } } } }] }, { xtype: 'fieldcontainer', fieldLabel: 'Position', layout: { type: 'hbox', align: 'stretch' }, defaults: { listeners: { change: labelUpdate } }, items: [{ name: 'position', xtype: 'combobox', store: ['below', 'above', 'left', 'right', 'center', 'top-left'], value: 'below', flex: 1, editable: false }, { xtype: 'label', text: 'Offset: x', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'offsetx', width: 60, unit: 'px' }, { xtype: 'label', text: 'y', margins: {top: 3, right: 2, bottom: 0, left: 7} }, { xtype: 'numberunit', allowDecimals: false, name: 'offsety', width: 60, unit: 'px' }] }, { fieldLabel: 'Orientation', name: 'orientation', xtype: 'combobox', store: ['horizontal', 'vertical'], value: 'horizontal', editable: false }, { fieldLabel: 'Background', xtype: 'colorcbo', name: 'bgcolor', value: '', mouseover: function(color) { var oldValue=this.getValue(); this.setValue(color); labelUpdate(); this.setRawValue(oldValue); }, mouseout: function(color) { labelUpdate(); } }, { xtype: 'fieldcontainer', fieldLabel: 'Border', layout: { type: 'hbox', align: 'stretch' }, defaults: { listeners: { change: labelUpdate } }, items: [{ xtype: 'colorcbo', name: 'bordercolor', value: '', mouseover: function(color) { var oldValue=this.getValue(); this.setValue(color); labelUpdate(); this.setRawValue(oldValue); }, mouseout: function(color) { labelUpdate(); }, flex: 1, margins: {top: 0, right: 3, bottom: 0, left: 0} }, { xtype: 'numberunit', allowDecimals: false, name: 'bordersize', width: 60, unit: 'px' }] }, { fieldLabel: 'Backgr. Size', xtype: 'fieldcontainer', layout: 'table', items: [{ xtype: 'label', text: 'width:', style: 'margin-left: 0; margin-right: 2px;' }, { xtype: 'numberfield', name: 'width', width: 55, value: panel.xdata.label.width, listeners: { change: function(This, newValue, oldValue, eOpts) { labelUpdate(); } }}, { xtype: 'label', text: 'height:', style: 'margin-left: 10px; margin-right: 2px;' }, { xtype: 'numberfield', name: 'height', width: 55, value: panel.xdata.label.height, listeners: { change: function(This, newValue, oldValue, eOpts) { labelUpdate(); } }} ] } ] }] }] }; /* Source Tab */ var sourceTab = { title: 'Source', type: 'panel', listeners: { activate: function(This) { var xdata = TP.get_icon_form_xdata(settingsWindow); var j = Ext.JSON.encode(xdata); try { j = JSON.stringify(xdata, null, 2); } catch(err) { TP.logError(panel.id, "jsonStringifyException", err); } this.down('form').getForm().setValues({source: j, sourceError: ''}); } }, items: [{ xtype : 'panel', layout: 'fit', border: 0, items: [{ xtype: 'form', id: 'sourceForm', bodyPadding: 2, border: 0, bodyStyle: 'overflow-y: auto;', submitEmptyText: false, defaults: { anchor: '-12', labelWidth: 50 }, items: [{ fieldLabel: 'Source', xtype: 'textarea', name: 'source', height: 190 }, { fieldLabel: ' ', labelSeparator: '', xtype: 'fieldcontainer', items: [{ xtype: 'button', name: 'sourceapply', text: 'Apply', width: 100, handler: function(btn) { var values = Ext.getCmp('sourceForm').getForm().getValues(); try { var xdata = Ext.JSON.decode(values.source); TP.setIconSettingsValues(xdata); } catch(err) { TP.logError(panel.id, "jsonDecodeException", err); Ext.getCmp('sourceForm').getForm().setValues({sourceError: err}); } } }] }, { fieldLabel: ' ', labelSeparator: '', xtype: 'displayfield', name: 'sourceError', value: '' }] }] }] }; var tabPanel = new Ext.TabPanel({ activeTab : panel.initialSettingsTab ? panel.initialSettingsTab : 0, enableTabScroll : true, items : [ generalTab, layoutTab, appearanceTab, linkTab, labelTab, sourceTab ] }); /* add current available backends */ var backendItem = TP.getFormField(Ext.getCmp("generalForm"), 'backends'); if(backendItem) { TP.updateArrayStoreKV(backendItem.store, TP.getAvailableBackendsTab(tab)); if(backendItem.store.count() <= 1) { backendItem.hide(); } } var settingsWindow = new Ext.Window({ height: 350, width: 400, layout: 'fit', items: tabPanel, panel: panel, title: 'Icon Settings', buttonAlign: 'center', fbar: [/* panlet setting cancel button */ { xtype: 'button', text: 'cancel', handler: function(This) { settingsWindow.destroy(); } }, /* panlet setting save button */ { xtype: 'button', text: 'save', handler: function() { settingsWindow.skipRestore = true; panel.stateful = true; delete panel.xdata.label; delete panel.xdata.link; var xdata = TP.get_icon_form_xdata(settingsWindow); TP.log('['+this.id+'] icon config updated: '+Ext.JSON.encode(xdata)); for(var key in xdata) { panel.xdata[key] = xdata[key]; } panel.applyState({xdata: panel.xdata}); if(panel.classChanged) { panel.xdata.cls = panel.classChanged; } panel.forceSaveState(); delete TP.iconSettingsWindow; settingsWindow.destroy(); panel.firstRun = false; panel.applyXdata(); var tab = Ext.getCmp(panel.panel_id); TP.updateAllIcons(tab, panel.id); TP.updateAllLabelAvailability(tab, panel.id); } } ], listeners: { afterRender: function (This) { var form = This.items.getAt(0).items.getAt(1).down('form').getForm(); this.nav = Ext.create('Ext.util.KeyNav', this.el, { 'left': function(evt){ form.setValues({x: Number(form.getValues().x)-1}); }, 'right': function(evt){ form.setValues({x: Number(form.getValues().x)+1}); }, 'up': function(evt){ form.setValues({y: Number(form.getValues().y)-1}); }, 'down': function(evt){ form.setValues({y: Number(form.getValues().y)+1}); }, ignoreInputFields: true, scope: panel }); }, destroy: function() { delete TP.iconSettingsWindow; panel.stateful = true; if(!settingsWindow.skipRestore) { // if we cancel directly after adding a new icon, destroy it tab.enableMapControlsTemp(); if(panel.firstRun) { panel.destroy(); } else { if(panel.classChanged) { var key = panel.id; panel.redrawOnly = true; panel.destroy(); TP.timeouts['timeout_' + key + '_show_settings'] = window.setTimeout(function() { panel = TP.add_panlet({id:key, skip_state:true, tb:tab, autoshow:true}, false); TP.updateAllIcons(Ext.getCmp(panel.panel_id), panel.id); }, 50); return; } else { // restore position and layout if(panel.setRenderItem) { panel.setRenderItem(undefined, true); } if(TP.cp.state[panel.id]) { panel.applyXdata(TP.cp.state[panel.id].xdata); } } } } if(panel.el) { panel.el.dom.style.outline = ""; panel.setIconLabel(); } if(panel.dragEl1 && panel.dragEl1.el) { panel.dragEl1.el.dom.style.outline = ""; } if(panel.dragEl2 && panel.dragEl2.el) { panel.dragEl2.el.dom.style.outline = ""; } if(panel.labelEl && panel.labelEl.el) { panel.labelEl.el.dom.style.outline = ""; } TP.updateAllIcons(Ext.getCmp(panel.panel_id)); // workaround to put labels in front } } }).show(); tab.body.unmask(); TP.setIconSettingsValues(panel.xdata); TP.iconSettingsWindow = settingsWindow; // new mouseover tips while settings are open TP.iconTip.hide(); // move settings window next to panel itself var showAtPos = TP.getNextToPanelPos(panel, settingsWindow.width, settingsWindow.height); panel.setIconLabel(undefined, true); settingsWindow.showAt(showAtPos); TP.iconSettingsWindow.panel = panel; settingsWindow.renderUpdateDo = renderUpdateDo; renderUpdate = function(forceColor, forceRenderItem) { if(TP.skipRender) { return; } TP.reduceDelayEvents(TP.iconSettingsWindow, function() { if(TP.skipRender) { return; } if(!TP.iconSettingsWindow) { return; } TP.iconSettingsWindow.renderUpdateDo(forceColor, forceRenderItem); }, 100, 'timeout_settings_render_update'); }; settingsWindow.renderUpdate = renderUpdate; renderUpdate(); /* highlight current icon */ if(panel.xdata.appearance.type == "connector") { panel.dragEl1.el.dom.style.outline = "2px dotted orange"; panel.dragEl2.el.dom.style.outline = "2px dotted orange"; } else if (panel.iconType == "text") { panel.labelEl.el.dom.style.outline = "2px dotted orange"; } else { panel.el.dom.style.outline = "2px dotted orange"; } window.setTimeout(function() { TP.iconSettingsWindow.toFront(); }, 100); TP.modalWindows.push(settingsWindow); }; TP.get_icon_form_xdata = function(settingsWindow) { var xdata = { general: Ext.getCmp('generalForm').getForm().getValues(), layout: Ext.getCmp('layoutForm').getForm().getValues(), appearance: Ext.getCmp('appearanceForm').getForm().getValues(), link: Ext.getCmp('linkForm').getForm().getValues(), label: Ext.getCmp('labelForm').getForm().getValues() } // clean up if(xdata.label.labeltext == '') { delete xdata.label; } if(xdata.link.link == '') { delete xdata.link; } if(xdata.layout.rotation == 0) { delete xdata.layout.rotation; } Ext.getCmp('appearance_types').store.each(function(data, i) { var t = data.raw[0]; for(var key in xdata.appearance) { var t2 = t; if(t == 'speedometer') { t2 = 'speedo'; } var p = new RegExp('^'+t2, 'g'); if(key.match(p) && t != xdata.appearance.type) { delete xdata.appearance[key]; } } }); if(settingsWindow.panel.hideAppearanceTab) { delete xdata.appearance; } if(settingsWindow.panel.iconType == 'text') { delete xdata.general; } if(xdata.appearance) { delete xdata.appearance.speedoshadow; delete xdata.appearance.pieshadow; } if(xdata.general) { delete xdata.general.newcls; } return(xdata); } TP.openLabelEditorWindow = function(panel) { var oldValue = Ext.getCmp('label_textfield').getValue(); var perf_data = ''; window.perfdata = {}; // ensure fresh and correct performance data panel.setIconLabel(undefined, true); for(var key in perfdata) { delete perfdata[key].perf; delete perfdata[key].key; for(var key2 in perfdata[key]) { var keyname = '.'+key; if(key.match(/[^a-zA-Z]/)) { keyname = '[\''+key+'\']'; } perf_data += '<tr><td><\/td><td><i>perfdata'+keyname+'.'+key2+'<\/i><\/td><td>'+perfdata[key][key2]+'<\/td><\/tr>' } } var labelEditorWindow = new Ext.Window({ height: 500, width: 650, layout: 'fit', title: 'Label Editor', modal: true, buttonAlign: 'center', fbar: [/* panlet setting cancel button */ { xtype: 'button', text: 'cancel', handler: function(This) { var labelEditorWindow = This.up('window'); Ext.getCmp('label_textfield').setValue(oldValue); labelEditorWindow.destroy(); } }, /* panlet setting save button */ { xtype: 'button', text: 'save', handler: function(This) { var labelEditorWindow = This.up('window'); Ext.getCmp('label_textfield').setValue(labelEditorWindow.down('textarea').getValue()) labelEditorWindow.destroy(); } } ], items: [{ xtype: 'form', bodyPadding: 2, border: 0, bodyStyle: 'overflow-y: auto;', submitEmptyText: false, layout: 'anchor', defaults: { width: '99%', labelWidth: 40 }, items: [{ xtype: 'textarea', fieldLabel: 'Label', value: Ext.getCmp('label_textfield').getValue().replace(/<br>/g,"<br>\n"), id: 'label_textfield_edit', height: 90, listeners: { change: function(This) { Ext.getCmp('label_textfield').setValue(This.getValue()) } } }, { fieldLabel: 'Help', xtype: 'fieldcontainer', items: [{ xtype: 'label', cls: 'labelhelp', html: '<p>Use HTML to format your label<br>' +'Ex.: <i>Host &lt;b&gt;{{name}}&lt;/b&gt;<\/i>, Newlines: <i>&lt;br&gt;<\/i><\/p>' +'<p>It is possible to create dynamic labels with {{placeholders}}.<br>' +'Ex.: <i>Host {{name}}: {{plugin_output}}<\/i><\/p>' +'<p>You may also do calculations inside placeholders like this:<br>' +'Ex.: <i>Group XY {{totals.ok}}/{{totals.ok + totals.critical + totals.warning + totals.unknown}}<\/i><\/p>' +'<p>use sprintf to format numbers:<br>' +'Ex.: <i>{{sprintf("%.2f %s",perfdata.rta.val, perfdata.rta.unit)}}<\/i><\/p>' +'<p>use strftime to format timestamps:<br>' +'Ex.: <i>{{strftime("%Y-%m-%d",last_check)}}<\/i><\/p>' +'<p>conditionals are possible:<br>' +'Ex.: <i>{{ if(acknowledged) {...} else {...} }}<\/i><\/p>' +'<p>There are different variables available depending on the type of icon/widget:<br>' +'<table><tr><th>Groups/Filters:<\/th><td><i>totals.services.ok<\/i><\/td><td>totals number of ok services<\/td><\/tr>' +'<tr><td><\/td><td><i>totals.services.warning<\/i><\/td><td>totals number of warning services<\/td><\/tr>' +'<tr><td><\/td><td><i>totals.services.critical<\/i><\/td><td>totals number of critical services<\/td><\/tr>' +'<tr><td><\/td><td><i>totals.services.unknown<\/i><\/td><td>totals number of unknown services<\/td><\/tr>' +'<tr><td><\/td><td><i>totals.hosts.up<\/i><\/td><td>totals number of up hosts<\/td><\/tr>' +'<tr><td><\/td><td><i>totals.hosts.down<\/i><\/td><td>totals number of down hosts<\/td><\/tr>' +'<tr><td><\/td><td><i>totals.hosts.unreachable<\/i><\/td><td>totals number of unreachable hosts<\/td><\/tr>' +'<tr><th>Hosts:<\/th><td><i>name<\/i><\/td><td>Hostname<\/td><\/tr>' +'<tr><td><\/td><td><i>state<\/i><\/td><td>State: 0 - Ok, 1 - Warning, 2 - Critical,...<\/td><\/tr>' +'<tr><td><\/td><td><i>performance_data<\/i><\/td><td>Performance data. Use list below to access specific values<\/td><\/tr>' +'<tr><td><\/td><td><i>has_been_checked<\/i><\/td><td>Has this host been checked: 0 - No, 1 - Yes<\/td><\/tr>' +'<tr><td><\/td><td><i>scheduled_downtime_depth<\/i><\/td><td>Downtime: 0 - No, &gtl;=1 - Yes<\/td><\/tr>' +'<tr><td><\/td><td><i>acknowledged<\/i><\/td><td>Has this host been acknowledged: 0 - No, 1 - Yes<\/td><\/tr>' +'<tr><td><\/td><td><i>last_check<\/i><\/td><td>Timestamp of last check<\/td><\/tr>' +'<tr><td><\/td><td><i>last_state_change<\/i><\/td><td>Timestamp of last state change<\/td><\/tr>' +'<tr><td><\/td><td><i>last_notification<\/i><\/td><td>Timestamp of last notification<\/td><\/tr>' +'<tr><td><\/td><td><i>plugin_output<\/i><\/td><td>Plugin Output<\/td><\/tr>' +'<tr><th>Services:<\/th><td><i>host_name<\/i><\/td><td>Hostname<\/td><\/tr>' +'<tr><td><\/td><td><i>description<\/i><\/td><td>Servicename<\/td><\/tr>' +'<tr><td><\/td><td colspan=2>(other attributes are identical to hosts)<\/td><\/tr>' +'<tr><th>Performance Data:<\/th><td colspan=2>(available performance data with their current values)<\/td><\/tr>' +perf_data +'<tr><th>Availability Data:<\/th><td colspan=2><\/td><\/tr>' +'<tr><td><\/td><td><i>{{ sprintf("%.2f", availability({d: "60m"})) }}%<\/i><\/td><td>availability for the last 60 minutes<\/td><\/tr>' +'<tr><td><\/td><td><i>{{ sprintf("%.2f", availability({d: "24h"})) }}%<\/i><\/td><td>availability for the last 24 hours<\/td><\/tr>' +'<tr><td><\/td><td><i>{{ sprintf("%.2f", availability({d: "7d"})) }}%<\/i><\/td><td>availability for the last 7 days<\/td><\/tr>' +'<tr><td><\/td><td><i>{{ sprintf("%.2f", availability({d: "31d"})) }}%<\/i><\/td><td>availability for the last 31 days<\/td><\/tr>' +'<tr><td><\/td><td colspan=2><i>{{ sprintf("%.2f", availability({d: "24h", tm: "5x8"})) }}%<\/i><\/td><\/tr>' +'<tr><td><\/td><td><\/td><td>availability for the last 24 hours within given timeperiod<\/td><\/tr>' +'<\/table>', listeners: { afterrender: function(This) { var examples = This.el.dom.getElementsByTagName('i'); Ext.Array.each(examples, function(el, i) { el.className = "clickable"; el.onclick = function(i) { var cur = Ext.getCmp('label_textfield_edit').getValue(); var val = Ext.htmlDecode(el.innerHTML); if(!val.match(/\{\{.*?\}\}/) && (val.match(/^perfdata\./) || val.match(/^perfdata\[/) || val.match(/^totals\./) || val.match(/^avail\./) || val.match(/^[a-z_]+$/))) { val = '{{'+val+'}}'; } if(val.match(/<br>/)) { val += "\n"; } Ext.getCmp('label_textfield_edit').setValue(cur+val); Ext.getCmp('label_textfield_edit').up('form').body.dom.scrollTop=0; Ext.getCmp('label_textfield_edit').focus(); } }); } } }] }] }] }).show(); Ext.getCmp('label_textfield').setValue(" "); Ext.getCmp('label_textfield').setValue(Ext.getCmp('label_textfield_edit').getValue()); TP.modalWindows.push(labelEditorWindow); labelEditorWindow.toFront(); } TP.setIconSettingsValues = function(xdata) { xdata = TP.clone(xdata); // set some defaults if(!xdata.label) { xdata.label = { labeltext: '' }; } if(!xdata.label.fontsize) { xdata.label.fontsize = 14; } if(!xdata.label.bordersize) { xdata.label.bordersize = 1; } Ext.getCmp('generalForm').getForm().setValues(xdata.general); Ext.getCmp('layoutForm').getForm().setValues(xdata.layout); Ext.getCmp('appearanceForm').getForm().setValues(xdata.appearance); Ext.getCmp('linkForm').getForm().setValues(xdata.link); Ext.getCmp('labelForm').getForm().setValues(xdata.label); } TP.getNextToPanelPos = function(panel, width, height) { if(!panel || !panel.el) { return([0,0]); } var sizes = []; sizes.push(panel.getSize().width); if(panel.labelEl) { sizes.push(panel.labelEl.getSize().width); } sizes.push(180); // max size of new speedos var offsetLeft = 30; var offsetRight = Ext.Array.max(sizes) + 10; var offsetY = 40; var panelPos = panel.getPosition(); var viewPortSize = TP.viewport.getSize(); if(viewPortSize.width > panelPos[0] + width+offsetRight) { panelPos[0] = panelPos[0] + offsetRight; } else { panelPos[0] = panelPos[0] - width - offsetLeft; } if(panelPos[1] - 50 < 0) { panelPos[1] = offsetY; } else if(viewPortSize.height > panelPos[1] + height - offsetY) { panelPos[1] = panelPos[1] - offsetY; } else { panelPos[1] = viewPortSize.height - height - offsetY; } // make sure its on the screen if(panelPos[0] < 0) { panelPos[0] = 0; } if(panelPos[1] < 20) { panelPos[1] = 20; } return(panelPos); }
awiddersheim/Thruk
plugins/plugins-available/panorama/root/js/panorama_js_panlet_icon_widgets_settings.js
JavaScript
gpl-2.0
94,388
// drumkv1widget_elements.cpp // /**************************************************************************** Copyright (C) 2012-2020, rncbc aka Rui Nuno Capela. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *****************************************************************************/ #include "drumkv1widget_elements.h" #include "drumkv1widget.h" #include "drumkv1_ui.h" #include "drumkv1_sample.h" #include <QApplication> #include <QHeaderView> #include <QFileInfo> #include <QMimeData> #include <QDrag> #include <QUrl> #include <QIcon> #include <QPixmap> #include <QTimer> #include <QDragEnterEvent> #include <QDragMoveEvent> #include <QDropEvent> //---------------------------------------------------------------------------- // drumkv1widget_elements_model -- List model. // Constructor. drumkv1widget_elements_model::drumkv1widget_elements_model ( drumkv1_ui *pDrumkUi, QObject *pParent ) : QAbstractItemModel(pParent), m_pDrumkUi(pDrumkUi) { QIcon icon; icon.addPixmap( QPixmap(":/images/ledOff.png"), QIcon::Normal, QIcon::Off); icon.addPixmap( QPixmap(":/images/ledOn.png"), QIcon::Normal, QIcon::On); m_pixmaps[0] = new QPixmap( icon.pixmap(12, 12, QIcon::Normal, QIcon::Off)); m_pixmaps[1] = new QPixmap( icon.pixmap(12, 12, QIcon::Normal, QIcon::On)); m_headers << tr("Element") << tr("Sample"); for (int i = 0; i < MAX_NOTES; ++i) m_notes_on[i] = 0; reset(); } // Destructor. drumkv1widget_elements_model::~drumkv1widget_elements_model (void) { delete m_pixmaps[1]; delete m_pixmaps[0]; } int drumkv1widget_elements_model::rowCount ( const QModelIndex& /*parent*/ ) const { return MAX_NOTES; } int drumkv1widget_elements_model::columnCount ( const QModelIndex& /*parent*/ ) const { return m_headers.count(); } QVariant drumkv1widget_elements_model::headerData ( int section, Qt::Orientation orient, int role ) const { if (orient == Qt::Horizontal) { switch (role) { case Qt::DisplayRole: return m_headers.at(section); case Qt::TextAlignmentRole: return columnAlignment(section); default: break; } } return QVariant(); } QVariant drumkv1widget_elements_model::data ( const QModelIndex& index, int role ) const { switch (role) { case Qt::DecorationRole: if (index.column() == 0) return *m_pixmaps[m_notes_on[index.row()] > 0 ? 1 : 0]; break; case Qt::DisplayRole: return itemDisplay(index); case Qt::TextAlignmentRole: return columnAlignment(index.column()); case Qt::ToolTipRole: return itemToolTip(index); default: break; } return QVariant(); } QModelIndex drumkv1widget_elements_model::index ( int row, int column, const QModelIndex& /*parent*/) const { return createIndex(row, column, (m_pDrumkUi ? m_pDrumkUi->element(row) : nullptr)); } QModelIndex drumkv1widget_elements_model::parent ( const QModelIndex& ) const { return QModelIndex(); } drumkv1_element *drumkv1widget_elements_model::elementFromIndex ( const QModelIndex& index ) const { return static_cast<drumkv1_element *> (index.internalPointer()); } drumkv1_ui *drumkv1widget_elements_model::instance (void) const { return m_pDrumkUi; } void drumkv1widget_elements_model::midiInLedNote ( int key, int vel ) { if (vel > 0) { m_notes_on[key] = vel; midiInLedUpdate(key); } else if (m_notes_on[key] > 0) { QTimer::singleShot(200, this, SLOT(midiInLedTimeout())); } } void drumkv1widget_elements_model::midiInLedTimeout (void) { for (int key = 0; key < MAX_NOTES; ++key) { if (m_notes_on[key] > 0) { m_notes_on[key] = 0; midiInLedUpdate(key); } } } void drumkv1widget_elements_model::midiInLedUpdate ( int key ) { const QModelIndex& index = drumkv1widget_elements_model::index(key, 0); #if QT_VERSION >= QT_VERSION_CHECK(5, 1, 0) emit dataChanged(index, index, QVector<int>() << Qt::DecorationRole); #else emit dataChanged(index, index); #endif } void drumkv1widget_elements_model::reset (void) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QAbstractItemModel::reset(); #else QAbstractItemModel::beginResetModel(); QAbstractItemModel::endResetModel(); #endif } QString drumkv1widget_elements_model::itemDisplay ( const QModelIndex& index ) const { switch (index.column()) { case 0: // Element. return drumkv1widget::completeNoteName(index.row()); case 1: // Sample. drumkv1_element *element = elementFromIndex(index); if (element) { const char *pszSampleFile = element->sampleFile(); if (pszSampleFile) return QFileInfo(pszSampleFile).completeBaseName(); else return tr("(None)"); } } return QString('-'); } QString drumkv1widget_elements_model::itemToolTip ( const QModelIndex& index ) const { QString sToolTip = '[' + drumkv1widget::completeNoteName(index.row()) + ']'; drumkv1_element *element = elementFromIndex(index); if (element) { const char *pszSampleFile = element->sampleFile(); if (pszSampleFile) { sToolTip += '\n'; sToolTip += QFileInfo(pszSampleFile).completeBaseName(); } } return sToolTip; } int drumkv1widget_elements_model::columnAlignment( int /*column*/ ) const { return int(Qt::AlignLeft | Qt::AlignVCenter); } //---------------------------------------------------------------------------- // drumkv1widget_elements -- Custom (tree) list view. // Constructor. drumkv1widget_elements::drumkv1widget_elements ( QWidget *pParent ) : QTreeView(pParent), m_pModel(nullptr), m_pDragSample(nullptr), m_iDirectNoteOn(-1), m_iDirectNoteOnVelocity(64) { resetDragState(); } // Destructor. drumkv1widget_elements::~drumkv1widget_elements (void) { if (m_pModel) delete m_pModel; } // Settlers. void drumkv1widget_elements::setInstance ( drumkv1_ui *pDrumkUi ) { if (m_pModel) delete m_pModel; m_pModel = new drumkv1widget_elements_model(pDrumkUi); QTreeView::setModel(m_pModel); QTreeView::setSelectionMode(QAbstractItemView::SingleSelection); QTreeView::setRootIsDecorated(false); QTreeView::setUniformRowHeights(true); QTreeView::setItemsExpandable(false); QTreeView::setAllColumnsShowFocus(true); QTreeView::setAlternatingRowColors(true); QTreeView::setMinimumSize(QSize(360, 80)); QTreeView::setSizePolicy( QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); QTreeView::setAcceptDrops(true); QHeaderView *pHeader = QTreeView::header(); pHeader->setDefaultAlignment(Qt::AlignLeft); pHeader->setStretchLastSection(true); // Element selectors QObject::connect(QTreeView::selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)), SLOT(currentRowChanged(const QModelIndex&, const QModelIndex&))); QObject::connect(this, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(doubleClicked(const QModelIndex&))); } drumkv1_ui *drumkv1widget_elements::instance (void) const { return (m_pModel ? m_pModel->instance() : nullptr); } // Current element accessors. void drumkv1widget_elements::setCurrentIndex ( int row ) { QTreeView::setCurrentIndex(m_pModel->index(row, 0)); } int drumkv1widget_elements::currentIndex (void) const { return QTreeView::currentIndex().row(); } // Internal slot handlers. void drumkv1widget_elements::currentRowChanged ( const QModelIndex& current, const QModelIndex& /*previous*/ ) { emit itemActivated(current.row()); } void drumkv1widget_elements::doubleClicked ( const QModelIndex& index ) { emit itemDoubleClicked(index.row()); } // Mouse interaction. void drumkv1widget_elements::mousePressEvent ( QMouseEvent *pMouseEvent ) { if (pMouseEvent->button() == Qt::LeftButton) { const QPoint& pos = pMouseEvent->pos(); if (pos.x() > 0 && pos.x() < 16) { directNoteOn(QTreeView::indexAt(pos).row()); return; // avoid double-clicks... } else { m_dragState = DragStart; m_posDrag = pos; } } QTreeView::mousePressEvent(pMouseEvent); } void drumkv1widget_elements::mouseMoveEvent ( QMouseEvent *pMouseEvent ) { QTreeView::mouseMoveEvent(pMouseEvent); if (m_dragState == DragStart && (m_posDrag - pMouseEvent->pos()).manhattanLength() > QApplication::startDragDistance()) { drumkv1_element *element = static_cast<drumkv1_element *> ( QTreeView::currentIndex().internalPointer()); // Start dragging alright... if (element && element->sample()) { QList<QUrl> urls; m_pDragSample = element->sample(); urls.append(QUrl::fromLocalFile(m_pDragSample->filename())); QMimeData *pMimeData = new QMimeData(); pMimeData->setUrls(urls);; QDrag *pDrag = new QDrag(this); pDrag->setMimeData(pMimeData); pDrag->exec(Qt::CopyAction); } resetDragState(); } } void drumkv1widget_elements::mouseReleaseEvent ( QMouseEvent *pMouseEvent ) { QTreeView::mouseReleaseEvent(pMouseEvent); directNoteOff(); m_pDragSample = nullptr; resetDragState(); } // Drag-n-drop (more of the later) support. void drumkv1widget_elements::dragEnterEvent ( QDragEnterEvent *pDragEnterEvent ) { QTreeView::dragEnterEvent(pDragEnterEvent); if (pDragEnterEvent->mimeData()->hasUrls()) pDragEnterEvent->acceptProposedAction(); } void drumkv1widget_elements::dragMoveEvent ( QDragMoveEvent *pDragMoveEvent ) { QTreeView::dragMoveEvent(pDragMoveEvent); if (pDragMoveEvent->mimeData()->hasUrls()) { const QModelIndex& index #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) = QTreeView::indexAt(pDragMoveEvent->position().toPoint()); #else = QTreeView::indexAt(pDragMoveEvent->pos()); #endif if (index.isValid()) { setCurrentIndex(index.row()); if (m_pDragSample) { drumkv1_element *element = static_cast<drumkv1_element *> ( index.internalPointer()); // Start dragging alright... if (element && m_pDragSample == element->sample()) return; } pDragMoveEvent->acceptProposedAction(); } } } void drumkv1widget_elements::dropEvent ( QDropEvent *pDropEvent ) { QTreeView::dropEvent(pDropEvent); const QMimeData *pMimeData = pDropEvent->mimeData(); if (pMimeData->hasUrls()) { const QString& sFilename = QListIterator<QUrl>(pMimeData->urls()).peekNext().toLocalFile(); if (!sFilename.isEmpty()) emit itemLoadSampleFile(sFilename, currentIndex()); } } // Reset drag/select state. void drumkv1widget_elements::resetDragState (void) { m_dragState = DragNone; } // Refreshner. void drumkv1widget_elements::refresh (void) { if (m_pModel == nullptr) return; QItemSelectionModel *pSelectionModel = QTreeView::selectionModel(); const QModelIndex& index = pSelectionModel->currentIndex(); m_pModel->reset(); QTreeView::header()->resizeSections(QHeaderView::ResizeToContents); pSelectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate); } // Default size hint. QSize drumkv1widget_elements::sizeHint (void) const { return QSize(360, 80); } // MIDI input status update void drumkv1widget_elements::midiInLedNote ( int key, int vel ) { if (m_pModel) m_pModel->midiInLedNote(key, vel); } // Direct note-on/off methods. void drumkv1widget_elements::directNoteOn ( int key ) { if (m_pModel == nullptr || key < 0) return; drumkv1_ui *pDrumkUi = m_pModel->instance(); if (pDrumkUi == nullptr) return; m_iDirectNoteOn = key; pDrumkUi->directNoteOn(m_iDirectNoteOn, m_iDirectNoteOnVelocity); drumkv1_sample *pSample = pDrumkUi->sample(); if (pSample) { const float srate_ms = 0.001f * pSample->sampleRate(); const int timeout_ms = int(float(pSample->length() >> 1) / srate_ms); QTimer::singleShot(timeout_ms, this, SLOT(directNoteOff())); } } void drumkv1widget_elements::directNoteOff (void) { if (m_pModel == nullptr || m_iDirectNoteOn < 0) return; drumkv1_ui *pDrumkUi = m_pModel->instance(); if (pDrumkUi == nullptr) return; pDrumkUi->directNoteOn(m_iDirectNoteOn, 0); // note-off! m_iDirectNoteOn = -1; } // Direct note-on velocity accessors. void drumkv1widget_elements::setDirectNoteOnVelocity ( int vel ) { m_iDirectNoteOnVelocity = vel; } int drumkv1widget_elements::directNoteOnVelocity (void) const { return m_iDirectNoteOnVelocity; } // end of drumkv1widget_elements.cpp
rncbc/drumkv1
src/drumkv1widget_elements.cpp
C++
gpl-2.0
12,654
(function() { angular.module('hb5').controller('HbFontaineListController', ['$attrs', '$scope', 'GeoxmlService', '$routeParams', '$log', '$filter', '$timeout', 'hbAlertMessages', 'hbUtil', function($attrs, $scope, GeoxmlService, $routeParams, $log, $filter, $timeout, hbAlertMessages, hbUtil) { $log.debug(" >>>> HbFontaineListController called..."); // FONTAINE default order is by "Address" stored in NOM field $scope.predicate = 'IDENTIFIANT.NOM'; $scope.reverse = false; // Object holding user entered search (filter) criteria $scope.search = { "objectif" : "", "nom" : "", "alias" : "", "remark" : "", "text" : "" }; // Initialise general search text with search request parameter if defined. // This is only expected from Dashboard calls. if ($routeParams.search) { $scope.search.text = $routeParams.search; } /** * Apply fontaine specific filters and sorting. */ var filterSortElfins = function(elfins_p, search_p, predicate_p, reverse_p) { // Apply prestationListFilter var filteredSortedElfins = $filter('fontaineListFilter')(elfins_p, search_p); filteredSortedElfins = $filter('fontaineListAnyFilter')(filteredSortedElfins, search_p.text); // Apply predicate, reverse sorting filteredSortedElfins = $filter('orderBy')(filteredSortedElfins, predicate_p, reverse_p); return filteredSortedElfins; }; /** * Update filtered collection when search or sorting criteria are modified. */ $scope.$watch('[search,predicate,reverse]', function(newSearch, oldSearch) { //$log.debug(">>>>> HbFontaineListController search, predicate or reverse UPDATED <<<<< \n" + angular.toJson(newSearch) ); if ($scope.elfins!=null) { $scope.filteredElfins = filterSortElfins($scope.elfins, $scope.search, $scope.predicate, $scope.reverse); } }, true); /** * elfins can result from queries taking possibly seconds to tens of seconds to complete. * This requires watching for elfins result availability before computing filteredElfins.length. */ $scope.$watch('elfins', function() { if ($scope.elfins!=null) { $scope.filteredElfins = filterSortElfins($scope.elfins, $scope.search, $scope.predicate, $scope.reverse); } else { //$log.debug(">>>>> HbFontaineListController elfins NOT YET LOADED <<<<<"); } }); /** * Set focus on the list global search field */ var focusOnSearchField = function() { $('#globalSearchField').focus(); }; $timeout(focusOnSearchField, 250, false); }]); })();
bsisa/hb-ui
main/src/fontaine/hbFontaineListController.js
JavaScript
gpl-2.0
2,720
<?php defined( '_JEXEC' ) or die( '=;)' ); jimport('joomla.application.component.controller'); class controllBase extends JController { function setAllapotMegtartLink(){ $model = $this->getModel($this->model); if(@$model->xmlParser){ $this->session(); $node = $model->xmlParser->getGroup( "condFields" ); foreach($node->childNodes as $e_){ if(is_a($e_, "DOMElement")){ $name = $e_->getAttribute('name'); $v = $this->getSessionVar($name); if(is_array($v) && count($v) ){ foreach($v as $v_){ $req = jrequest::getvar($name); if(isset( $req ) ){ $this->redirectSaveOk.="&{$name}[]={$v_}"; } } }else{ $this->redirectSaveOk.="&{$name}={$v}"; $this->cancelLink.="&{$name}={$v}&Itemid={$this->Itemid}"; } } } } //die( $this->redirectSaveOk ); } function __construct($config = array()) { global $option, $Itemid; parent::__construct($config); $this->user = jfactory::getuser(); $auth =& JFactory::getACL(); $this->option = $option; $this->Itemid = $Itemid; if($tmpl=JRequest::getVar("tmpl", "") ) { $this->tmpl="&tmpl={$tmpl}"; }else{ $this->tmpl=""; } //echo $this->tmpl; $this -> setSessionVar("kapcsolodo_id", JRequest::getVaR("kapcsolodo_id", $this -> getSessionVar("kapcsolodo_id") ) ); //echo $this->getSessionVaR("kapcsolodo_id")." kapcsolodo_id **"; //die($this->getSessionVaR("kapcsolodo_id")." kapcsolodo_id **"); //die; $controller = jrequest::getVar( "controller", "wh" ); if( $this->user->id ){ if( $this->ellenorizJog() ){ $this->setAllapotMegtartLink(); }elseif( $controller!="wh" ){ $msg = jtext::_( "NINCS_JOGA" ); $this->setRedirect( "index.php?option=com_wh&controller=wh", $msg ); } }else{ $this->setRedirect("index.php"); } }// function function getUserGroupNameArray(){ $user =& JFactory::getUser(); $db =& Jfactory::getdbo(); $groups = $user->get('groups'); $array = array(); foreach ($groups as $gid){ $q = "select title from #__usergroups where id = {$gid}"; $db->setquery($q); $array[]=$db->loadresult(); //print_r($db->loadobject()); } //print_r($array); die(); return $array; } function ellenorizJog(){ //die($this->user->usertype.'da'); if(in_array($this->user->usertype, array("Szuper felhasználók","Super Administrator", "administrator", "Super Users") ) ) return true; $arr = felhasznaloiJogok::_(); //print_r($this->user); die($this->user->usertype); $jogok = $this->getUserGroupNameArray(); //print_r($jogok); //die('fds'); foreach( $arr[ $jogok[0] ] as $a ){ //print_r($a); die(); if( in_array($this->controller, explode(",", $a) ) ){ //die('fds'); return true; } } return false; } function keep(){ //die("-------"); $this->session(); JRequest::setVar( 'view', $this->model ); //JRequest::setVar('hidemainmenu', 1); parent::display(); } function session() { //$data = $_REQUEST; @$sess =& JSession::getInstance(); $model = $this->getModel($this->model); foreach($model->getFormFieldArray() as $varname ){ $value = JRequest::getVar($varname); //echo $varname." : {$value} *********************<br />"; if($value) { $sess->set($varname, $value); }else{ if( isset($value) && $varname<>"id" ){ $sess->set($varname, ""); } } } //exit; } function add(){ $model = $this->getModel($this->model); $model->deleteSession(); //die( $this->addLink ); $this->setRedirect($this->addLink); } function add_(){ $model = $this->getModel($this->model); $model->deleteSession(); JRequest::setVar("view", $this->view); parent::display(); } function display() { JRequest::setVar("view", $this->view); parent::display(); }// function function edit() { $this->session(); JRequest::setVar( 'view', $this->model ); JRequest::setVar('hidemainmenu', 1); //exit; parent::display(); }// function function apply() { JRequest::setVar('hidemainmenu', 1); $model = $this->getModel($this->model); $this->session(); $errorFields = $model->checkMandatoryFields(); //print_r($errorFields);exit; if(!count($errorFields) ){ if ($id = $model->store()) { $msg = JText::_( 'SIKERES MENTES' ); } else { $msg = JText::_( 'HIBAS MENTES' ); } //parent::display(); }else{ $msg = JText::_( 'HIBAS MEZOK' ); } //print_r($_POST);exit; //$urlParameters = $this->getUrlParameters($model); $errorFields_="&errorFields[]="; $errorFields_ .= implode("&errorFields[]=",$errorFields); $task = "edit"; $layout=jrequest::getvar('layout','default'); if($id){ $fromlist = 1; }else{ $fromlist=""; $id = $this->getSessionVar("id"); if(!$id){ //$task = "add"; } } $link = "index.php?option=com_wh&task={$task}&controller={$this->controller}&cid[]={$id}&fromlist={$fromlist}{$errorFields_}{$this->tmpl}&layout={$layout}"; //die($link); $this->setRedirect($link, $msg); }// function function getUrlParameters($model){ $url=""; foreach($model->getFormFieldArray() as $parName){ $val = JRequest::getVar($parName); if(is_array($val)){ //echo $val; //exit; foreach($val as $v){ $url.="{$parName}[]={$v}&"; } }else{ $url.="{$parName}={$val}&"; } } return $url; } function save() { $this->session(); $model = $this->getModel($this->model); $errorFields = $model->checkMandatoryFields(); //print_r(JRequest::getVar("kat_id")); //die($this->model); if(!count($errorFields) ){ if ($id = $model->store() ) { $msg = JText::_( 'SIKERES MENTES' ); } else { //die($errorFields); $msg = JText::_( 'Hiba tortent mentes kozben' ); } $link = $this->redirectSaveOk; $model->deleteSession(); $this->setRedirect($link, $msg); }else{ JRequest::setVar('hidemainmenu', 1); $msg = JText::_( 'HIBAS MEZOK' ); $errorFields_="&errorFields[]="; $errorFields_.=implode("&errorFields[]=",$errorFields); $link = "index.php?option={$this->option}&task=edit&controller={$this->controller}&cid={$id}{$errorFields_}{$this->tmpl}"; $this->setRedirect($link, $msg); } }// function function save_and_new() { //die('lefut'); $this->session(); $model = $this->getModel($this->model); $errorFields = $model->checkMandatoryFields(); //die($this->model); if(!count($errorFields) ){ if ($id = $model->store() ) { $msg = JText::_( 'SIKERES MENTES' ); } else { //die($errorFields); $msg = JText::_( 'Hiba tortent mentes kozben' ); } $link = $this->addLink; $model->deleteSession(); $this->setRedirect($link, $msg); }else{ JRequest::setVar('hidemainmenu', 1); $msg = JText::_( 'HIBAS MEZOK' ); $errorFields_="&errorFields[]="; $errorFields_.=implode("&errorFields[]=",$errorFields); $link = $this->addLink; $this->setRedirect($link, $msg); } } function remove() { $model = $this->getModel($this->model); if(!$model->delete($this->jTable)) { $msg = JText::_( "HIBA MENTES KOZBEN" ); } else { $msg = JText::_( "SIKERES TORLES" ); } $this->setAllapotMegtartLink(); //die( $this->redirectSaveOk ); $this -> setredirect($this->redirectSaveOk , $msg ); //$this->setRedirect( "index.php?option={$this->option}&controller={$this->controller}{$this->tmpl}", $msg ); }// function /** * cancel editing a record * @return void */ function cancel() { $msg = JText::_( 'Cancel' ); $model = $this->getModel($this->model); $model->deleteSession(); //$this->setAllapotMegtartLink(); //die("-------"); $this->setRedirect( $this->redirectSaveOk, $msg ); }// function function setSessionVar($var, $value){ @$sess =& JSession::getInstance(); $sess->set( $var, $value ); } function getSessionVar($var){ @$sess =& JSession::getInstance(); //$o_ = $sess->get("padData"); return $sess->get($var); //print_r($o_); exit; //return $o_->$var; } }
taccsi/bklntrl
components/com_wh/helpers/baseController.php
PHP
gpl-2.0
8,021
from django.db import models from django_crypto_fields.fields import EncryptedTextField from edc_base.model.models import BaseUuidModel try: from edc_sync.mixins import SyncMixin except ImportError: SyncMixin = type('SyncMixin', (object, ), {}) from ..managers import CallLogManager class CallLog (SyncMixin, BaseUuidModel): """Maintains a log of calls for a particular participant.""" subject_identifier = models.CharField( verbose_name="Subject Identifier", max_length=50, blank=True, db_index=True, unique=True, ) locator_information = EncryptedTextField( help_text=('This information has been imported from' 'the previous locator. You may update as required.') ) contact_notes = EncryptedTextField( null=True, blank=True, help_text='' ) label = models.CharField( max_length=25, null=True, editable=False, help_text="from followup list" ) # history = AuditTrail() objects = CallLogManager() def natural_key(self): return self.subject_identifier class Meta: app_label = 'edc_contact'
botswana-harvard/edc-contact
edc_contact/models/call_log.py
Python
gpl-2.0
1,199
<?php namespace Starter\routers; use common\routers\TemplateRouter; use Starter\views\AdminPanel\AddUserView; use Starter\views\AdminPanel\EditUserView; use Starter\views\AdminPanel\LeftMenuView; use Starter\views\AdminPanel\LoginFormView; use Starter\views\AdminPanel\NavbarView; use Starter\views\AdminPanel\UsersTableView; class AdminPanelRestRouter extends TemplateRouter { use TraitRestRouter; public function index() { $this->response->templates = [ (new UsersTableView())->get_template_model()->to_array(), (new LeftMenuView())->get_template_model()->to_array(), (new NavbarView())->get_template_model()->to_array() ]; } public function users($page = 1) { $this->response->templates = [ (new UsersTableView($page))->get_template_model()->to_array() ]; } public function login() { $this->response->templates = [ (new LoginFormView())->get_template_model()->to_array() ]; } public function add_user() { $this->response->templates = [ (new AddUserView())->get_template_model()->to_array() ]; } public function edit_user($id) { $this->response->templates = [ (new EditUserView($id))->get_template_model()->to_array() ]; } }
one-more/peach_framework
templates/starter/routers/adminpanelrestrouter.php
PHP
gpl-2.0
1,342
# SecuML # Copyright (C) 2016-2017 ANSSI # # SecuML is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # SecuML 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 SecuML. If not, see <http://www.gnu.org/licenses/>. import copy import pandas as pd import scipy from SecuML.core.Tools import matrix_tools from .AnnotationQuery import AnnotationQuery class Category(object): def __init__(self, label=None, family=None): self.assignLabelFamily(label, family) self.instances_ids = [] self.probas = [] self.entropy = [] self.likelihood = [] self.df = None self.annotation_queries = {} self.annotated_instances = [] self.num_annotated_instances = 0 # To display the annotation queries in the web GUI self.queries = [] self.queries_confidence = [] def generateAnnotationQuery(self, instance_id, predicted_proba, suggested_label, suggested_family, confidence=None): return AnnotationQuery(instance_id, predicted_proba, suggested_label, suggested_family, confidence=confidence) def assignLabelFamily(self, label, family): self.family = family if label != 'all': self.label = label else: self.label = label def numInstances(self): return len(self.instances_ids) def setWeight(self, weight): self.weight = weight def setNumAnnotations(self, num_annotations): self.num_annotations = num_annotations def addInstance(self, instance_id, probas, annotated): self.instances_ids.append(instance_id) entropy = None proba = None likelihood = None if probas is not None: entropy = scipy.stats.entropy(probas) proba = max(probas) self.entropy.append(entropy) self.probas.append(proba) self.likelihood.append(likelihood) if annotated: self.annotated_instances.append(instance_id) self.num_annotated_instances += 1 def finalComputation(self): self.df = pd.DataFrame({'proba': self.probas, 'entropy': self.entropy, 'likelihood': self.likelihood}, index=list(map(str, self.instances_ids))) def annotateAuto(self, iteration): for k, queries in self.annotation_queries.items(): for q, query in enumerate(queries): query.annotateAuto(iteration, self.label) def getManualAnnotations(self, iteration): for k, queries in self.annotation_queries.items(): for q, query in enumerate(queries): query.getManualAnnotation(iteration) def checkAnnotationQueriesAnswered(self, iteration): for k, queries in self.annotation_queries.items(): for q, query in enumerate(queries): if not query.checkAnswered(iteration): return False return True def setLikelihood(self, likelihood): self.likelihood = likelihood self.df['likelihood'] = likelihood def getLikelihood(self, instances): df = pd.DataFrame({'likelihood': self.likelihood}, index=list(map(str, self.instances_ids))) selected_df = df.loc[list(map(str, instances)), :] return selected_df['likelihood'].tolist() def getCategoryLabel(self): return self.label def getCategoryFamily(self): return self.family def toJson(self): obj = {} obj['label'] = self.label obj['family'] = self.family obj['annotation_queries'] = {} for kind, queries in self.annotation_queries.items(): obj['annotation_queries'][kind] = [] for q, query in enumerate(queries): obj['annotation_queries'][kind].append(query.toJson()) return obj @staticmethod def fromJson(obj): category = Category() category.instances_ids = obj['instances_ids'] category.label = obj['label'] return category def exportAnnotationQueries(self): annotation_queries = {} annotation_queries['instance_ids'] = self.queries annotation_queries['confidence'] = self.queries_confidence annotation_queries['label'] = self.label return annotation_queries def generateAnnotationQueries(self, cluster_strategy): queries_types = cluster_strategy.split('_') num_queries_types = len(queries_types) total_num_queries = 0 annotated_instances = copy.deepcopy(self.annotated_instances) for q, queries_type in enumerate(queries_types): if q == (num_queries_types - 1): num_queries = self.num_annotations - total_num_queries else: num_queries = self.num_annotations // num_queries_types if queries_type == 'center': queries = self.queryHighLikelihoodInstances( annotated_instances, num_queries) elif queries_type == 'anomalous': queries = self.queryLowLikelihoodInstances( annotated_instances, num_queries) elif queries_type == 'uncertain': queries = self.queryUncertainInstances( annotated_instances, num_queries) elif queries_type == 'random': queries = self.queryRandomInstances( annotated_instances, num_queries) else: raise ValueError() annotated_instances += queries total_num_queries += len(queries) assert(total_num_queries == self.num_annotations) def queryUncertainInstances(self, drop_instances, num_instances): if num_instances == 0: return [] queries_df = self.getSelectedInstancesDataframe(drop_instances) matrix_tools.sortDataFrame(queries_df, 'entropy', False, True) queries_df = queries_df.head(num_instances) self.addAnnotationQueries('uncertain', 'low', queries_df) return list(map(int, queries_df.index.values.tolist())) def queryHighLikelihoodInstances(self, drop_instances, num_instances): if num_instances == 0: return [] queries_df = self.getSelectedInstancesDataframe(drop_instances) matrix_tools.sortDataFrame(queries_df, 'likelihood', False, True) queries_df = queries_df.head(num_instances) self.addAnnotationQueries('high_likelihood', 'high', queries_df) return list(map(int, queries_df.index.values.tolist())) def queryLowLikelihoodInstances(self, drop_instances, num_instances): if num_instances == 0: return [] queries_df = self.getSelectedInstancesDataframe(drop_instances) matrix_tools.sortDataFrame(queries_df, 'likelihood', True, True) queries_df = queries_df.head(num_instances) self.addAnnotationQueries('low_likelihood', 'low', queries_df) return list(map(int, queries_df.index.values.tolist())) def queryRandomInstances(self, drop_instances, num_instances): if num_instances == 0: return [] queries_df = self.getSelectedInstancesDataframe(drop_instances) queries_df = queries_df.sample(n=num_instances, axis=0) self.addAnnotationQueries('random', 'low', queries_df) return list(map(int, queries_df.index.values.tolist())) def addAnnotationQueries(self, kind, confidence, queries_df): if kind not in list(self.annotation_queries.keys()): self.annotation_queries[kind] = [] for index, row in queries_df.iterrows(): query = self.generateAnnotationQuery(int(index), row['likelihood'], self.label, self.family, confidence=confidence) self.annotation_queries[kind].append(query) self.queries.append(int(index)) self.queries_confidence.append(confidence) def getSelectedInstancesDataframe(self, drop_instances): if drop_instances is None: selected_instances = self.instances_ids else: selected_instances = [ x for x in self.instances_ids if x not in drop_instances] selected_df = self.df.loc[list(map(str, selected_instances)), :] return selected_df
ah-anssi/SecuML
SecuML/core/ActiveLearning/QueryStrategies/AnnotationQueries/Category.py
Python
gpl-2.0
8,916
using Newtonsoft.Json; using RedditReader.Common; using RedditReader.Data; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel.Resources; using Windows.Data.Json; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Graphics.Display; using Windows.Storage; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; // The Universal Hub Application project template is documented at http://go.microsoft.com/fwlink/?LinkID=391955 namespace RedditReader { public sealed partial class HubPage : Page { private readonly NavigationHelper navigationHelper; private readonly ObservableDictionary defaultViewModel = new ObservableDictionary(); List<SubredditDataItem> Subreddits = null; public HubPage() { this.InitializeComponent(); // Hub is only supported in Portrait orientation DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait; this.NavigationCacheMode = NavigationCacheMode.Required; this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += this.NavigationHelper_LoadState; } private async void LoadData() { try { if (Subreddits == null) { if (Reddit.Reddit.LoginHelper.IsLoggedIn()) { signInBtn.Content = "sign out"; var reddits = await Reddit.Reddit.Reddit.GetSubreddits(100); var subreddits = new List<SubredditDataItem>(); foreach (var child in reddits.Data.Children) { var defReddit = new SubredditDataItem(child.Data.DisplayName, false, ""); subreddits.Add(defReddit); } string json = JsonConvert.SerializeObject(subreddits); Reddit.Database.SetValue("reddits", json); Subreddits = subreddits; } else { signInBtn.Content = "sign in"; if (Reddit.Database.GetValue("reddits") == null) { var defreddits = await Reddit.Reddit.Reddit.GetDefaultSubreddits(); var defSubreddits = new List<SubredditDataItem>(); foreach (var child in defreddits.Data.Children) { var defReddit = new SubredditDataItem(child.Data.DisplayName, false, ""); defSubreddits.Add(defReddit); } string json = JsonConvert.SerializeObject(defSubreddits); Reddit.Database.SetValue("reddits", json); Subreddits = defSubreddits; } else { Subreddits = JsonConvert.DeserializeObject<List<SubredditDataItem>>((string)Reddit.Database.GetValue("reddits")); } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } Debug.WriteLine(Subreddits[0].Name); List<TextPostDataItem> items = new List<TextPostDataItem>(); int cnt = 0; while (cnt < 10) { TextPostDataItem post = new TextPostDataItem("Test post #" + cnt, "empty", new Random(23).Next(10, 3000), new Random(213).Next(10, 9000), new Random(43).Next(10, 9000), new Random(35).Next(10, 5000), "marsmax", "", Vote.Neutral); items.Add(post); cnt++; } Subreddits = Subreddits.OrderByDescending(o => o.IsFavourite).ToList(); //var settings = ApplicationData.Current.LocalSettings.Values; var hubData = new HubDataItem(items, "none", "none", "0% read", "", "igbyecf iuweviuw ycvuivcy ushyvc kchyvssadhy vcayscvu aluyvc uyasvd clasyvclcv ay vcoaiysvc iacs yvaicyvo", Subreddits); Hub.DataContext = hubData; } public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { LoadData(); } #region NavigationHelper registration /// <summary> /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// <para> /// Page specific logic should be placed in event handlers for the /// <see cref="NavigationHelper.LoadState"/> /// and <see cref="NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. /// </para> /// </summary> /// <param name="e">Event data that describes how this page was reached.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { this.navigationHelper.OnNavigatedFrom(e); } #endregion private void AddRemoveFavouriteSubreddit(object sender) { var s = sender as AppBarToggleButton; //var settings = ApplicationData.Current.LocalSettings.Values; if (s.Tag != null) { var item = Subreddits.Find(i => i.Name == s.Tag.ToString()); item.IsFavourite = !item.IsFavourite; LoadData(); } } private void Hub_SectionsInViewChanged(object sender, SectionsInViewChangedEventArgs e) { if (e.AddedSections.Contains(SubredditsHub)) BottomAppBar.ClosedDisplayMode = AppBarClosedDisplayMode.Compact; if (e.RemovedSections.Contains(SubredditsHub)) BottomAppBar.ClosedDisplayMode = AppBarClosedDisplayMode.Minimal; } private async void AppBarButton_Click(object sender, RoutedEventArgs e) { if (signInBtn.Content.ToString() == "sign in") { SignInPage sip = new SignInPage(); await sip.ShowAsync(); LoadData(); } else { Reddit.Reddit.LoginHelper.Logout(); LoadData(); } } private void StackPanel_Tapped(object sender, TappedRoutedEventArgs e) { var tag = (sender as StackPanel).Tag.ToString(); Frame.Navigate(typeof(SubredditPage), tag); } private void ListView_ItemClick(object sender, ItemClickEventArgs e) { } private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e) { var s = sender as MenuFlyoutItem; if (s.Tag != null) { var item = Subreddits.Find(i => i.Name == s.Tag.ToString()); item.IsFavourite = !item.IsFavourite; item.Update(item.IsFavourite); LoadData(); } } private void StackPanel_Holding(object sender, HoldingRoutedEventArgs e) { FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender); } } }
skulltah/Readdit
Read.er/Read.er.WindowsPhone/HubPage.xaml.cs
C#
gpl-2.0
8,244
# encoding: utf-8 require 'rubygems' require 'taglib' require 'log4r' include Log4r Encoding.default_internal = 'UTF-8' Encoding.default_external = 'UTF-8' # Utils to manipulate and do things with years class YearUtils include Singleton def initialize @log = Logger.new 'YearUtils' @log.outputters = Outputter.stdout @log.level=FATAL end def verbose(activate) if activate @log.level=DEBUG end end # Choose a year according to the possibilities # nil is returned if none or more than one option is needed def choose_year(year_list) # Check there are more then one full_year or year option all_full_years = year_list.uniq.map{|y| if full_year?(y) then y end}.compact all_short_years = year_list.uniq.map{|y| unless full_year?(y) then y end}.compact if year_list.empty? @log.warn('No possible years found!') nil elsif year_list.uniq.size==1 #one unique result year_list.first elsif all_full_years.size == 1 and all_short_years.size == 1 and year_in_full_year?(all_short_years.first, all_full_years.first) # If only one full and one short year exits and the full year is the year return all_full_years.first else @log.warn("Several possible years were found: #{year_list[0..-1].join(", ")}") nil end end def year_in_full_year?(y, fy) Regexp.new("^#{y}") =~ fy #compare ^year with full year not $&.nil? end def full_year?(year) if year.nil? return false end split_date = year.split('-') split_date.length==3 && split_date[0].length==4 && split_date[1].length==2 && split_date[2].length==2 end end #YearUtils
morsmodre/tangotag
lib/year_utils.rb
Ruby
gpl-2.0
1,720
package cn.chenqingcan.cmdtext; import java.io.*; import cn.chenqingcan.util.*; /** * 看文件开头几行 * @author 陈庆灿 */ public class Head { //------------------------------------------------------------------------ /** 程序入口 */ public static void main(String[] args) { TextFileInfo file; int lineno; try { file = TextFileInfo.prompt(); } catch (Throwable e) { return; } for (;;) { try { lineno = VolcanoConsoleUtil.inputInteger("行数"); } catch (Throwable e) { return; } try { echoHeadLine(file, lineno); } catch (Throwable e) { System.err.println(VolcanoExceptionUtil.throwableToSimpleString(e)); } } } //------------------------------------------------------------------------ /** 指定行数回显文件开头 */ private static void echoHeadLine(final TextFileInfo file, final int lineno) throws Throwable { try (BufferedReader reader = VolcanoFileUtil.openFileReader(file.getFileName(), file.getCharset())) { for (int n = 0 ; n < lineno ; n++) { String s = reader.readLine(); if (s == null) { return; } System.out.println(s); } } } }
ActiveVolcano/cmd-text
src/main/java/cn/chenqingcan/cmdtext/Head.java
Java
gpl-2.0
1,175
/* Copyright (C) 2005-2009 Michel de Boer <michel@twinklephone.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "definitions.h" #include "hdr_route.h" #include "parse_ctrl.h" t_hdr_route::t_hdr_route() : t_header("Route") { route_to_first_route = false; } void t_hdr_route::add_route(const t_route &r) { populated = true; route_list.push_back(r); } string t_hdr_route::encode(void) const { return (t_parser::multi_values_as_list ? t_header::encode() : encode_multi_header()); } string t_hdr_route::encode_multi_header(void) const { string s; if (!populated) return s; for (list<t_route>::const_iterator i = route_list.begin(); i != route_list.end(); i++) { s += header_name; s += ": "; s += i->encode(); s += CRLF; } return s; } string t_hdr_route::encode_value(void) const { string s; if (!populated) return s; for (list<t_route>::const_iterator i = route_list.begin(); i != route_list.end(); i++) { if (i != route_list.begin()) s += ","; s += i->encode(); } return s; }
LubosD/twinkle
src/parser/hdr_route.cpp
C++
gpl-2.0
1,655
<?php require("../../includes/header.php"); ?><h1>Mike and Matrices</h1><div class="content"> <h3> Read problems statements in <a target="_blank" href="http://www.codechef.com/download/translated/LTIME07/mandarin/MIKE1.pdf">Mandarin Chinese</a> and <a target="_blank" href="http://www.codechef.com/download/translated/LTIME07/russian/MIKE1.pdf">Russian</a>.</h3> <p>Mike is given a matrix <b>A</b>, <b>N</b> and <b>M</b> are numbers of rows and columns respectively. <b>A<sub>1, 1</sub></b> is the number in the top left corner. All the numbers in <b>A</b> are non-negative integers. He also has <b>L</b> pairs of integers (<b>i<sub>k</sub></b>, <b>j<sub>k</sub></b>). His task is to calculate <b>A<sub>i<sub>1</sub>, j<sub>1</sub></sub></b> + <b>A<sub>i<sub>2</sub>, j<sub>2</sub></sub></b> + ... + <b>A<sub>i<sub>L</sub>, j<sub>L</sub></sub></b>. </p> <p> Unfortunately, Mike forgot if <b>A<sub>i, j</sub></b> was a number in the <b>i</b>'th row and <b>j</b>'th column or vice versa, if <b>A<sub>i, j</sub></b> was a number in the <b>j</b>'th row and <b>i</b>'th column. </p> <p> So, Mike decided to calculate both <b>E<sub>1</sub></b> = <b>A<sub>i<sub>1</sub>, j<sub>1</sub></sub></b> + <b>A<sub>i<sub>2</sub>, j<sub>2</sub></sub></b> + ... + <b>A<sub>i<sub>L</sub>, j<sub>L</sub></sub></b> and <b>E<sub>2</sub></b> = <b>A<sub>j<sub>1</sub>, i<sub>1</sub></sub></b> + <b>A<sub>j<sub>2</sub>, i<sub>2</sub></sub></b> + ... + <b>A<sub>j<sub>L</sub>, i<sub>L</sub></sub></b>. If it is impossible to calculate <b>E<sub>1</sub></b>(i.e. one of the summands doesn't exist), then let's assume, that it is equal to <b>-1</b>. If it is impossible to calculate <b>E<sub>2</sub></b>, then let's also assume, that it is equal to <b>-1</b>. </p> <p> Your task is to calculate <b>max(<b>E<sub>1</sub></b>, <b>E<sub>2</sub></b>)</b>. </p> <h3>Input</h3> <p> The first line contains two integers <b>N</b> and <b>M</b>, denoting the number of rows and the number of columns respectively.<br /><br /> Each of next <b>N</b> lines contains <b>M</b> integers. The <b>j</b>'th integer in the <b>(i + 1)</b>'th line of the input denotes <b>A<sub>i, j</sub></b>.<br /> </p> <p> The <b>(N + 2)</b>'th line contains an integer <b>L</b>, denoting the number of pairs of integers, that Mike has.<br /><br /> Each of next <b>L</b> lines contains a pair of integers. The <b>(N + 2 + k)</b>-th line in the input contains a pair (<b>i<sub>k</sub></b>, <b>j<sub>k</sub></b>). </p> <h3>Output</h3> <p>The first line should contain an integer, denoting <b>max(<b>E<sub>1</sub></b>, <b>E<sub>2</sub></b>)</b>.</p> <h3>Examples</h3> <pre><b>Input:</b> 3 2 1 2 4 5 7 0 2 1 2 2 2 <b>Output:</b> 9 </pre> <pre><b>Input:</b> 1 3 1 2 3 2 1 3 3 1 <b>Output:</b> -1 </pre> <pre><b>Input:</b> 1 3 1 2 3 2 1 1 3 1 <b>Output:</b> 4 </pre> <h3>Explanation</h3> <p> In the first test case <b>N</b> equals to 3, <b>M</b> equals to 2, <b>L</b> equals to 2. <b>E<sub>1</sub></b> = 2 + 5 = 7, <b>E<sub>2</sub></b> = 4 + 5 = 9. The answer is <b>max(<b>E<sub>1</sub></b>, <b>E<sub>2</sub></b>)</b> = <b>max(</b>7<b>,</b> 9<b>)</b> = 9; </p> <p> In the second test case <b>N</b> equals to 1, <b>M</b> equals to 3, <b>L</b> equals to 2. It is impossible to calculate <b>E<sub>1</sub></b> and <b>E<sub>2</sub></b>, because <b>A<sub>3, 1</sub></b> doesn't exist. So the answer is <b>max(<b>E<sub>1</sub></b>, <b>E<sub>2</sub></b>)</b> = <b>max(</b>-1<b>,</b> -1<b>)</b> = -1; </p> <p> In the third test case <b>N</b> equals to 1, <b>M</b> equals to 3, <b>L</b> equals to 2. It is impossible to calculate <b>E<sub>1</sub></b>, because <b>A<sub>3, 1</sub></b> doesn't exist. So <b>E<sub>1</sub></b> is equal to -1. <b>E<sub>2</sub></b> = 1 + 3 = 4. The answer is <b>max(<b>E<sub>1</sub></b>, <b>E<sub>2</sub></b>)</b> = <b>max(</b>-1<b>,</b>4<b>)</b> = 4. </p> <h3>Scoring</h3> <p> 1 ≤ <b>i<sub>k</sub></b>, <b>j<sub>k</sub></b> ≤ 500 for each test case. </p> <p> Subtask 1 (10 points): 1 ≤ <b>N</b>, <b>M</b>, <b>L</b> ≤ 5, 0 ≤ <b>A<sub>i, j</sub></b> ≤ 10;<br /><br /> Subtask 2 (12 points): 1 ≤ <b>N</b>, <b>M</b>, <b>L</b> ≤ 300, 0 ≤ <b>A<sub>i, j</sub></b> ≤ 10<sup>6</sup>, all the numbers in <b>A</b> are equal;<br /><br /> Subtask 3 (20 points): 1 ≤ <b>N</b>, <b>M</b>, <b>L</b> ≤ 300, 0 ≤ <b>A<sub>i, j</sub></b> ≤ 10<sup>9</sup>;<br /><br /> Subtask 4 (26 points): 1 ≤ <b>N</b>, <b>M</b>, <b>L</b> ≤ 500, 0 ≤ <b>A<sub>i, j</sub></b> ≤ 10<sup>9</sup>;<br /><br /> Subtask 5 (32 points): 1 ≤ <b>N</b>, <b>M</b> ≤ 500, 1 ≤ <b>L</b> ≤ 250 000, 0 ≤ <b>A<sub>i, j</sub></b> ≤ 10<sup>9</sup>.<br /> </p> </div><table cellspacing="0" cellpadding="0" align="left"> <tr> <td width="14%">Author:</td> <td><a href="/users/kostya_by">kostya_by</a></td> </tr> <tr> <td width="14%">Date Added:</td> <td>28-11-2013</td> </tr> <tr> <td width="14%">Time Limit:</td> <td>1 sec</td> </tr> <tr> <td width="14%">Source Limit:</td> <td>50000 Bytes</td> </tr> <tr> <td width="14%">Languages:</td> <td>ADA, ASM, BASH, BF, C, C99 strict, CAML, CLOJ, CLPS, CPP 4.3.2, CPP 4.8.1, CPP11, CS2, D, ERL, FORT, FS, GO, HASK, ICK, ICON, JAR, JAVA, JS, LISP clisp, LISP sbcl, LUA, NEM, NICE, NODEJS, PAS fpc, PAS gpc, PERL, PERL6, PHP, PIKE, PRLG, PYTH, PYTH 3.1.2, RUBY, SCALA, SCM guile, SCM qobi, ST, TCL, TEXT, WSPC</td> </tr> </table> <?php require("../../includes/footer.php"); ?>
tacoder/Virtual-Codechef-Contests
contest/LTIME07/MIKE1.php
PHP
gpl-2.0
5,578
#!/usr/bin/env python # -*- coding: utf-8 -*- """ python library for the AR.Drone 1.0 (1.11.5) and 2.0 (2.2.9). parts of code from Bastian Venthur, Jean-Baptiste Passot, Florian Lacrampe. tested with Python 2.7.3 and AR.Drone vanilla firmware 1.11.5. """ # < imports >-------------------------------------------------------------------------------------- import logging import multiprocessing import sys import threading import time import arATCmds import arNetwork import arIPCThread # < variáveis globais >---------------------------------------------------------------------------- # logging level w_logLvl = logging.ERROR # < class ARDrone >-------------------------------------------------------------------------------- class ARDrone ( object ): """ ARDrone class. instanciate this class to control AR.Drone and receive decoded video and navdata. """ # --------------------------------------------------------------------------------------------- # ARDrone::__init__ # --------------------------------------------------------------------------------------------- def __init__ ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::__init__" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.seq_nr = 1 self.timer_t = 0.2 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.lock = threading.Lock () self.speed = 0.2 self.at ( arATCmds.at_config, "general:navdata_demo", "TRUE" ) self.vid_pipe, vid_pipe_other = multiprocessing.Pipe () self.nav_pipe, nav_pipe_other = multiprocessing.Pipe () self.com_pipe, com_pipe_other = multiprocessing.Pipe () self.network_process = arNetwork.ARDroneNetworkProcess ( nav_pipe_other, vid_pipe_other, com_pipe_other ) self.network_process.start () self.ipc_thread = arIPCThread.IPCThread ( self ) self.ipc_thread.start () self.image = None self.navdata = {} self.time = 0 # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::apply_command # --------------------------------------------------------------------------------------------- def apply_command ( self, f_command ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::apply_command" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) las_available_commands = [ "emergency", "hover", "land", "move_backward", "move_down", "move_forward", "move_left", "move_right", "move_up", "takeoff", "turn_left", "turn_right", ] # validade command if ( f_command not in las_available_commands ): # sherlock logger # l_log.error ( "Command %s not recognized !" % f_command ) # sherlock logger # l_log.debug ( "<< (E01)" ) return if ( "hover" != f_command ): self.last_command_is_hovering = False if ( "emergency" == f_command ): self.reset () elif (( "hover" == f_command ) and ( not self.last_command_is_hovering )): self.hover () self.last_command_is_hovering = True elif ( "land" == f_command ): self.land () self.last_command_is_hovering = True elif ( "move_backward" == f_command ): self.move_backward () elif ( "move_forward" == f_command ): self.move_forward () elif ( "move_down" == f_command ): self.move_down () elif ( "move_up" == f_command ): self.move_up () elif ( "move_left" == f_command ): self.move_left () elif ( "move_right" == f_command ): self.move_right () elif ( "takeoff" == f_command ): self.takeoff () self.last_command_is_hovering = True elif ( "turn_left" == f_command ): self.turn_left () elif ( "turn_right" == f_command ): self.turn_right () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::at # --------------------------------------------------------------------------------------------- def at ( self, f_cmd, *args, **kwargs ): """ wrapper for the low level at commands. this method takes care that the sequence number is increased after each at command and the watchdog timer is started to make sure the drone receives a command at least every second. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::at" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.lock.acquire () self.com_watchdog_timer.cancel () f_cmd ( self.seq_nr, *args, **kwargs ) self.seq_nr += 1 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.com_watchdog_timer.start () self.lock.release () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::commwdg # --------------------------------------------------------------------------------------------- def commwdg ( self ): """ communication watchdog signal. this needs to be send regulary to keep the communication with the drone alive. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::commwdg" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_comwdg ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_boom # --------------------------------------------------------------------------------------------- def event_boom ( self ): """ boom event """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_boom" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_THETA_30_DEG # total duration in seconds of the animation lf_secs = 1000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_thetamixed # --------------------------------------------------------------------------------------------- def event_thetamixed ( self ): """ make the drone execute thetamixed ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_thetamixed" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_THETA_MIXED # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_turnarround # --------------------------------------------------------------------------------------------- def event_turnarround ( self ): """ make the drone turnarround. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_turnarround" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_TURNAROUND # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_yawdance # --------------------------------------------------------------------------------------------- def event_yawdance ( self ): """ make the drone execute yawdance YEAH ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_yawdance" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_YAW_DANCE # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_yawshake # --------------------------------------------------------------------------------------------- def event_yawshake ( self ): """ Make the drone execute yawshake YEAH ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_yawshake" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_YAW_SHAKE # total duration in seconds of the animation lf_secs = 2000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::get_image # --------------------------------------------------------------------------------------------- def get_image ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::get_image" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) _im = np.copy ( self.image ) # sherlock logger # l_log.debug ( "<<" ) return _im # --------------------------------------------------------------------------------------------- # ARDrone::get_navdata # --------------------------------------------------------------------------------------------- def get_navdata ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::get_navdata" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( "><" ) return self.navdata # --------------------------------------------------------------------------------------------- # ARDrone::halt # --------------------------------------------------------------------------------------------- def halt ( self ): """ shutdown the drone. does not land or halt the actual drone, but the communication with the drone. Should call it at the end of application to close all sockets, pipes, processes and threads related with this object. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::halt" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.lock.acquire () self.com_watchdog_timer.cancel () self.com_pipe.send ( "die!" ) self.network_process.terminate () # 2.0 ? self.network_process.join () self.ipc_thread.stop () # 2.0 ? self.ipc_thread.join () # 2.0 ? self.lock.release () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::hover # --------------------------------------------------------------------------------------------- def hover ( self ): """ make the drone hover. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::hover" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, False, 0, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::land # --------------------------------------------------------------------------------------------- def land ( self ): """ make the drone land. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::land" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ref, False ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move # --------------------------------------------------------------------------------------------- def move ( self, ff_lr, ff_fb, ff_vv, ff_va ): """ makes the drone move (translate/rotate). @param lr : left-right tilt: float [-1..1] negative: left / positive: right @param rb : front-back tilt: float [-1..1] negative: forwards / positive: backwards @param vv : vertical speed: float [-1..1] negative: go down / positive: rise @param va : angular speed: float [-1..1] negative: spin left / positive: spin right """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # validate inputs # assert ( 1. >= ff_lr >= -1. ) # assert ( 1. >= ff_fb >= -1. ) # assert ( 1. >= ff_vv >= -1. ) # assert ( 1. >= ff_va >= -1. ) # move drone self.at ( arATCmds.at_pcmd, True, float ( ff_lr ), float ( ff_fb ), float ( ff_vv ), float ( ff_va )) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_backward # --------------------------------------------------------------------------------------------- def move_backward ( self ): """ make the drone move backwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_backward" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, self.speed, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_down # --------------------------------------------------------------------------------------------- def move_down ( self ): """ make the drone decent downwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_down" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, -self.speed, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_forward # --------------------------------------------------------------------------------------------- def move_forward ( self ): """ make the drone move forward. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_forward" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, -self.speed, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_left # --------------------------------------------------------------------------------------------- def move_left ( self ): """ make the drone move left. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_left" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, -self.speed, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_right # --------------------------------------------------------------------------------------------- def move_right ( self ): """ make the drone move right. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_right" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, self.speed, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_up # --------------------------------------------------------------------------------------------- def move_up ( self ): """ make the drone rise upwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_up" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, self.speed, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::reset # --------------------------------------------------------------------------------------------- def reset ( self ): """ toggle the drone's emergency state. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::reset" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ftrim ) time.sleep ( 0.1 ) self.at ( arATCmds.at_ref, False, True ) time.sleep ( 0.1 ) self.at ( arATCmds.at_ref, False, False ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_image # --------------------------------------------------------------------------------------------- def set_image ( self, fo_image ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_image" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) if ( f_image.shape == self.image_shape ): self.image = fo_image self.image = fo_image # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_navdata # --------------------------------------------------------------------------------------------- def set_navdata ( self, fo_navdata ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_navdata" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.navdata = fo_navdata # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_speed # --------------------------------------------------------------------------------------------- def set_speed ( self, ff_speed ): """ set the drone's speed. valid values are floats from [0..1] """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_speed" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # validate input # assert ( 1. >= ff_speed >= 0. ) # set speed self.speed = float ( ff_speed ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::takeoff # --------------------------------------------------------------------------------------------- def takeoff ( self ): """ make the drone takeoff. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::takeoff" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # calibrate drone self.at ( arATCmds.at_ftrim ) # set maximum altitude self.at ( arATCmds.at_config, "control:altitude_max", "20000" ) # take-off self.at ( arATCmds.at_ref, True ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::trim # --------------------------------------------------------------------------------------------- def trim ( self ): """ flat trim the drone. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::trim" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ftrim ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::turn_left # --------------------------------------------------------------------------------------------- def turn_left ( self ): """ make the drone rotate left. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::turn_left" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, 0, -self.speed ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::turn_right # --------------------------------------------------------------------------------------------- def turn_right ( self ): """ make the drone rotate right. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::turn_right" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, 0, self.speed ) # sherlock logger # l_log.debug ( "<<" ) # < class ARDrone2 >------------------------------------------------------------------------------- class ARDrone2 ( ARDrone ): """ ARDrone2 class instanciate this class to control your drone and receive decoded video and navdata. """ # --------------------------------------------------------------------------------------------- # ARDrone2::__init__ # --------------------------------------------------------------------------------------------- def __init__ ( self, is_ar_drone_2 = True, hd = False ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::__init__" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # init super class ARDrone.__init__ ( self ) self.seq_nr = 1 self.timer_t = 0.2 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.lock = threading.Lock () self.speed = 0.2 self.image_shape = ( 720, 1080, 1 ) time.sleep ( 0.2 ) self.config_ids_string = [ arDefs.SESSION_ID, arDefs.USER_ID, arDefs.APP_ID ] self.configure_multisession ( arDefs.SESSION_ID, arDefs.USER_ID, arDefs.APP_ID, self.config_ids_string ) self.set_session_id ( self.config_ids_string, arDefs.SESSION_ID ) time.sleep ( 0.2 ) self.set_profile_id ( self.config_ids_string, arDefs.USER_ID ) time.sleep ( 0.2 ) self.set_app_id ( self.config_ids_string, arDefs.APP_ID ) time.sleep ( 0.2 ) self.set_video_bitrate_control_mode ( self.config_ids_string, "1" ) time.sleep ( 0.2 ) self.set_video_bitrate ( self.config_ids_string, "500" ) time.sleep ( 0.2 ) self.set_max_bitrate ( self.config_ids_string, "500" ) time.sleep ( 0.2 ) self.set_fps ( self.config_ids_string, "30" ) time.sleep ( 0.2 ) self.set_video_codec ( self.config_ids_string, 0x80 ) self.last_command_is_hovering = True self.com_pipe, com_pipe_other = multiprocessing.Pipe () self.navdata = {} self.navdata [ 0 ] = { "ctrl_state":0, "battery":0, "theta":0, "phi":0, "psi":0, "altitude":0, "vx":0, "vy":0, "vz":0, "num_frames":0 } self.network_process = arNetwork.ARDrone2NetworkProcess ( com_pipe_other, is_ar_drone_2, self ) self.network_process.start () self.image = np.zeros ( self.image_shape, np.uint8 ) self.time = 0 self.last_command_is_hovering = True time.sleep ( 1.0 ) self.at ( arATCmds.at_config_ids, self.config_ids_string ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::configure_multisession # --------------------------------------------------------------------------------------------- def configure_multisession ( self, f_session_id, f_user_id, f_app_id, f_config_ids_string ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::configure_multisession" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config, "custom:session_id", f_session_id ) self.at ( arATCmds.at_config, "custom:profile_id", f_user_id ) self.at ( arATCmds.at_config, "custom:application_id", f_app_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_app_id # --------------------------------------------------------------------------------------------- def set_app_id ( self, f_config_ids_string, f_app_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_app_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:application_id", f_app_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_fps # --------------------------------------------------------------------------------------------- def set_fps ( self, f_config_ids_string, f_fps ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_fps" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:codec_fps", f_fps ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_max_bitrate # --------------------------------------------------------------------------------------------- def set_max_bitrate ( self, f_config_ids_string, f_max_bitrate ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_max_bitrate" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:max_bitrate", f_max_bitrate ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_profile_id # --------------------------------------------------------------------------------------------- def set_profile_id ( self, f_config_ids_string, f_profile_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_profile_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:profile_id", f_profile_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_session_id # --------------------------------------------------------------------------------------------- def set_session_id ( self, f_config_ids_string, f_session_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_session_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:session_id", f_session_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_bitrate # --------------------------------------------------------------------------------------------- def set_video_bitrate ( self, f_config_ids_string, f_bitrate ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_bitrate" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:bitrate", f_bitrate ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_bitrate_control_mode # --------------------------------------------------------------------------------------------- def set_video_bitrate_control_mode ( self, f_config_ids_string, f_mode ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_bitrate_control_mode" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:bitrate_control_mode", f_mode ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_codec # --------------------------------------------------------------------------------------------- def set_video_codec ( self, f_config_ids_string, f_codec ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_codec" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:video_codec", f_codec ) # sherlock logger # l_log.debug ( "<<" ) # ------------------------------------------------------------------------------------------------- # the bootstrap process # ------------------------------------------------------------------------------------------------- if ( "__main__" == __name__ ): import termios import fcntl import os l_fd = sys.stdin.fileno () l_old_term = termios.tcgetattr ( l_fd ) l_new_attr = termios.tcgetattr ( l_fd ) l_new_attr [ 3 ] = l_new_attr [ 3 ] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr ( l_fd, termios.TCSANOW, l_new_attr ) l_old_flags = fcntl.fcntl ( l_fd, fcntl.F_GETFL ) fcntl.fcntl ( l_fd, fcntl.F_SETFL, l_old_flags | os.O_NONBLOCK ) lo_drone = ARDrone () # assert ( lo_drone ) try: while ( True ): try: lc_c = sys.stdin.read ( 1 ) lc_c = lc_c.lower () print "Got character", lc_c # left ? if ( 'a' == lc_c ): lo_drone.move_left () # right ? elif ( 'd' == lc_c ): lo_drone.move_right () # forward ? elif ( 'w' == lc_c ): lo_drone.move_forward () # backward ? elif ( 's' == lc_c ): lo_drone.move_backward () # land ? elif ( ' ' == lc_c ): lo_drone.land () # takeoff ? elif ( '\n' == lc_c ): lo_drone.takeoff () # turn left ? elif ( 'q' == lc_c ): lo_drone.turn_left () # turn right ? elif ( 'e' == lc_c ): lo_drone.turn_right () # move up ? elif ( '1' == lc_c ): lo_drone.move_up () # hover ? elif ( '2' == lc_c ): lo_drone.hover () # move down ? elif ( '3' == lc_c ): lo_drone.move_down () # reset ? elif ( 't' == lc_c ): lo_drone.reset () # hover ? elif ( 'x' == lc_c ): lo_drone.hover () # trim ? elif ( 'y' == lc_c ): lo_drone.trim () except IOError: pass finally: termios.tcsetattr ( l_fd, termios.TCSAFLUSH, l_old_term ) fcntl.fcntl ( l_fd, fcntl.F_SETFL, l_old_flags ) lo_drone.halt () # < the end >-------------------------------------------------------------------------------------- #
projeto-si-lansab/si-lansab
ARDrone/libARDrone.py
Python
gpl-2.0
36,206
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace KKMono1 { /// <summary> /// This is the main type for your game. /// </summary> public class GameBubbles : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D imageKK; public GameBubbles() { graphics = new GraphicsDeviceManager(this); graphics.SynchronizeWithVerticalRetrace = true; graphics.PreferredBackBufferWidth = 1920; graphics.PreferredBackBufferHeight = 1080; graphics.GraphicsProfile = GraphicsProfile.HiDef; graphics.HardwareModeSwitch = false; Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here Window.Title = "Bubbles"; base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here var path = @"Images\Ball"; imageKK = Content.Load<Texture2D>(path); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } private KeyboardState keysLast = new KeyboardState(); /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); //count++; var keys = Keyboard.GetState(); if (keys.IsKeyDown(Keys.LeftAlt) && keys.IsKeyDown(Keys.Enter) && keysLast.IsKeyUp(Keys.Enter)) graphics.ToggleFullScreen(); keysLast = keys; // TODO: Add your update logic here base.Update(gameTime); } private int count = 0; /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { count++; GraphicsDevice.Clear(Color.Black); // TODO: Add your drawing code here spriteBatch.Begin(); /*spriteBatch.Draw(imageKK, Vector2.Zero, Color.White); spriteBatch.Draw(imageKK, position: new Vector2(500, 0), effects: SpriteEffects.FlipHorizontally); spriteBatch.Draw(imageKK, position: new Vector2(500, 0), rotation: 1, scale: new Vector2(0.1f, 0.1f));*/ var randpos = new Random(0); for (int i = 0; i < 10000; i++) { var color = new Color((float)randpos.NextDouble(), (float)randpos.NextDouble(), (float)randpos.NextDouble()); var position = new Vector2((float)randpos.NextDouble() * 1920, (float)randpos.NextDouble() * 1080); position += new Vector2((float)(20 * Math.Cos((count + randpos.NextDouble() * 1000) / 15f)), (float)(20 * Math.Sin((count + randpos.NextDouble() * 1000) / 25f))); var size = (float)(0.8 + 0.4 * randpos.NextDouble()); var rotation = (randpos.NextDouble() + (double)count / 100) * 2 * Math.PI; //spriteBatch.Draw(imageKK, position: position, rotation: (float)rotation, scale: new Vector2(size, size), origin: new Vector2(32, 32), color: color); spriteBatch.Draw(imageKK, position: position, rotation: (float)rotation, scale: new Vector2(size, size), origin: new Vector2(32, 32), color: new Color(color, 0.5f)); } spriteBatch.End(); // 3D //graphics.GraphicsDevice.DrawUserPrimitives base.Draw(gameTime); } } }
Kaskelot/Monolot
KKMono1/GameBubbles.cs
C#
gpl-2.0
5,054
import logging from gettext import gettext as _ from typing import Tuple from aai_framework.dial import ColorTxt from aai_framework.interface import ModuleInterface from .main import vars_, Vars logger = logging.getLogger(__name__) class Module(ModuleInterface): ID = 'pkgs' LEN_INSTALL = 2665 @property def vars_(self) -> Vars: return vars_ @property def name(self) -> str: return _('Дополнительное ПО') @property def menu_item(self) -> Tuple[str, str]: text = [ColorTxt('(' + _('ВЫПОЛНЕНО') + ')').green.bold if self.is_run else ''] return super().get_menu_item(text)
AnTAVR/aai2
src/modules/pkgs/m_main.py
Python
gpl-2.0
667
<?php /** * strateg Theme Customizer * * @package strateg */ /** * Sanitization functions */ function sanitize_race_id($raceid){ $len = strlen($raceid); if($len < 4){ return ''; } $a = str_split($raceid); $ret = ''; $len = min($len, 8); for($i = 0; $i < $len; $i++){ $o = ord($a[$i]); if(($o >= ord('a') && $o <= ord('z')) || ($o >= ord('A') && $o <= ord('Z')) || ($o >= ord('0') && $o <= ord('9')) || $a[$i] == '-' || $a[$i] == '_' || $a[$i] == '.'){ $ret .= $a[$i]; } else { $ret .= 'x'; } } return $ret; } function sanitize_date($date){ $format = get_option('date_format'); if($d = date_create_from_format($format, str_replace(' ', '', $date))){ return $d->format($format); }else{ return ''; } } /** * Add postMessage support for site title and description for the Theme Customizer. * * @param WP_Customize_Manager $wp_customize Theme Customizer object. */ function strateg_customize_register( $wp_customize ) { $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; $wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage'; $wp_customize->add_section( 'title_image_section' , array( 'title' => __( 'Title image', 'strateg' ), 'priority' => 90 )); $wp_customize->add_setting( 'title_image' ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'title_image', array( 'label' => __('Title image', 'strateg' ), 'section' => 'title_image_section', 'settings' => 'title_image' ) )); $wp_customize->add_section( 'entry_form_section' , array( 'title' => __( 'Entry form', 'strateg' ), 'priority' => 180 )); $wp_customize->add_setting('entry_race_id', array( 'sanitize_callback' => 'sanitize_race_id', )); $wp_customize->add_setting('entry_deadline', array( 'sanitize_callback' => 'sanitize_date', )); $wp_customize->add_setting('entry_show_meal'); $wp_customize->add_setting('entries_enabled'); $wp_customize->add_setting('entry_debug'); $wp_customize->add_control('entry_race_id', array( 'type' => 'text', 'label' => 'Identifikátor závodu (4 - 8 znaků)', 'section' => 'entry_form_section', )); $wp_customize->add_control( 'entry_deadline', array( 'type' => 'text', 'label' => 'Přihlášky do', 'section' => 'entry_form_section', )); $wp_customize->add_control( 'entry_show_meal', array( 'type' => 'checkbox', 'label' => 'Zobrazit dotaz na jídlo', 'section' => 'entry_form_section', )); $wp_customize->add_control( 'entries_enabled', array( 'type' => 'checkbox', 'label' => 'Povolit přihlášky', 'section' => 'entry_form_section', )); $wp_customize->add_control( 'entry_debug', array( 'type' => 'checkbox', 'label' => 'Ladicí výstup', 'section' => 'entry_form_section', )); } add_action( 'customize_register', 'strateg_customize_register' ); /** * Binds JS handlers to make Theme Customizer preview reload changes asynchronously. */ function strateg_customize_preview_js() { wp_enqueue_script( 'strateg_customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '20151215', true ); } add_action( 'customize_preview_init', 'strateg_customize_preview_js' );
horakmar/wp_theme-strateg
inc/customizer.php
PHP
gpl-2.0
3,631
package cn.ift8.spring.normal.annotation.normal; /** * Created by IFT8 * on 2015/8/16. */ public class Student { private Long sid; private String sname; @Override public String toString() { return "Student{" + "sid=" + sid + ", sname='" + sname + '\'' + '}'; } }
IFT8/Spring
src/cn/ift8/spring/normal/annotation/normal/Student.java
Java
gpl-2.0
344
<table class="form-table"> <tbody> <tr> <th><label for="address">Адрес</label></th> <td><textarea name="address" id="address" rows="5" cols="30"></textarea></td> </tr> </tbody></table>
Artenka/DressRoom
wp-content/plugins/wp-shop-original/views/admin/user.profile.customer.php
PHP
gpl-2.0
199
// FileZilla Server - a Windows ftp server // Copyright (C) 2002-2016 - Tim Kosse <tim.kosse@filezilla-project.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 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // OptionsIpFilterPage.cpp: Implementierungsdatei // #include "stdafx.h" #include "filezilla server.h" #include "OptionsDlg.h" #include "OptionsPage.h" #include "OptionsIpFilterPage.h" #include "../iputils.h" #if defined _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // Dialogfeld COptionsIpFilterPage COptionsIpFilterPage::COptionsIpFilterPage(COptionsDlg *pOptionsDlg, CWnd* pParent /*=NULL*/) : COptionsPage(pOptionsDlg, COptionsIpFilterPage::IDD, pParent) { //{{AFX_DATA_INIT(COptionsIpFilterPage) //}}AFX_DATA_INIT } void COptionsIpFilterPage::DoDataExchange(CDataExchange* pDX) { COptionsPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(COptionsIpFilterPage) DDX_Text(pDX, IDC_OPTIONS_IPFILTER_ALLOWED, m_AllowedAddresses); DDX_Text(pDX, IDC_OPTIONS_IPFILTER_DISALLOWED, m_DisallowedAddresses); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(COptionsIpFilterPage, COptionsPage) //{{AFX_MSG_MAP(COptionsIpFilterPage) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // Behandlungsroutinen für Nachrichten COptionsIpFilterPage BOOL COptionsIpFilterPage::OnInitDialog() { COptionsPage::OnInitDialog(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX-Eigenschaftenseiten sollten FALSE zurückgeben } BOOL COptionsIpFilterPage::IsDataValid() { if (!UpdateData(TRUE)) { return FALSE; } if (!ParseIPFilter(std::wstring(m_DisallowedAddresses))) { GetDlgItem(IDC_OPTIONS_IPFILTER_DISALLOWED)->SetFocus(); AfxMessageBox(_T("Invalid IP address/range/mask")); return false; } if (!ParseIPFilter(std::wstring(m_AllowedAddresses))) { GetDlgItem(IDC_OPTIONS_IPFILTER_ALLOWED)->SetFocus(); AfxMessageBox(_T("Invalid IP address/range/mask")); return false; } return TRUE; } void COptionsIpFilterPage::SaveData() { m_pOptionsDlg->SetOption(OPTION_IPFILTER_ALLOWED, m_AllowedAddresses.GetString()); m_pOptionsDlg->SetOption(OPTION_IPFILTER_DISALLOWED, m_DisallowedAddresses.GetString()); } void COptionsIpFilterPage::LoadData() { m_AllowedAddresses = m_pOptionsDlg->GetOption(OPTION_IPFILTER_ALLOWED).c_str(); m_DisallowedAddresses = m_pOptionsDlg->GetOption(OPTION_IPFILTER_DISALLOWED).c_str(); }
zedfoxus/filezilla-server
source/Interface/OptionsIpFilterPage.cpp
C++
gpl-2.0
3,181
package com.github.didmar.jrl.utils.plot; import java.io.File; import java.io.IOException; import java.io.PrintStream; import org.eclipse.jdt.annotation.NonNullByDefault; /** * This class is used to communicate with a gnuplot instance. See * http://www.gnuplot.info/ for details about gnuplot. Note that gnuplot exits, * when the java program does. However, by sending the <tt>&quot;exit&quot;</tt> * command to gnuplot via {@link Gnuplot#execute(String)}, the gnuplot process * exits, too. In order to quit a gnuplot session, the method * {@link Gnuplot#close()} first sends the <tt>&quot;exit&quot;</tt> command to * gnuplot and then closes the communication channel. * <p> * If the default constructor does not work on your system, try to set the * gnuplot executable in the public static field * {@link com.github.didmar.jrl.utils.plot.Gnuplot#executable}. * * This class is borrowed from the Java XCSF library. * * @author Didier Marin */ @NonNullByDefault public final class Gnuplot { /** * Gnuplot executable on the filesystem */ public final static String executable = getGnuplotExecutableName(); // communication channel: console.output -> process.input private final PrintStream console; /** * Default constructor executes a OS-specific command to start gnuplot and * establishes the communication. If this constructor does not work on your * machine, you can specify the executable in * {@link com.github.didmar.jrl.utils.plot.Gnuplot#executable}. * <p> * <b>Windows</b><br/> * Gnuplot is expected to be installed at the default location, that is * * <pre> * C:\&lt;localized program files directory&gt;\gnuplot\bin\pgnuplot.exe * </pre> * * where the <tt>Program Files</tt> directory name depends on the language * set for the OS. This constructor retrieves the localized name of this * directory. * <p> * <b>Linux</b><br/> * On linux systems the <tt>gnuplot</tt> executable has to be linked in one * of the default pathes in order to be available system-wide. * <p> * <b>Other Operating Systems</b><br/> * Other operating systems are not available to the developers and comments * on how defaults on these systems would look like are very welcome. * * @throws IOException * if the system fails to execute gnuplot */ public Gnuplot() throws IOException { // start the gnuplot process and connect channels Process p = Runtime.getRuntime().exec(executable); console = new PrintStream(p.getOutputStream()); } public static String getGnuplotExecutableName() { final String os = System.getProperty("os.name").toLowerCase(); if (os.contains("linux")) { // assume that path is set return "gnuplot"; } if (os.contains("windows")) { // assume default installation path, i.e. // <localized:program files>/gnuplot/ String programFiles = System.getenv("ProgramFiles"); if (programFiles == null) { // nothing found? ups. programFiles = "C:" + File.separatorChar + "Program Files"; } // assert separator if (!programFiles.endsWith(File.separator)) { programFiles += File.separatorChar; } return programFiles + "gnuplot" + File.separatorChar + "bin" + File.separatorChar + "pgnuplot.exe"; } throw new RuntimeException("Operating system '" + os + "' is not supported. " + "If you have Gnuplot installed, " + "specify the executable command via" + System.getProperty("line.separator") + "Gnuplot.executable " + "= \"your executable\""); } /** * Sends the given <code>command</code> to gnuplot. Multiple commands can be * seperated with a semicolon. * * @param command * the command to execute on the gnuplot process */ public final void execute(String command) { console.println(command); console.flush(); } /** * Exit gnuplot and close the in/out streams. */ public final void close() { this.execute("exit"); console.close(); } /* * (non-Javadoc) * * @see java.lang.Object#finalize() */ @Override protected final void finalize() throws Throwable { this.close(); super.finalize(); } }
didmar/jrl
src/main/java/com/github/didmar/jrl/utils/plot/Gnuplot.java
Java
gpl-2.0
4,145
/*************************************************************************** * Copyright (C) 2006 by ludo * * ludo42fr@free.fr * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * * In addition, as a special exception, the copyright holders give * * permission to link the code of this program with any edition of * * the Qt library by Trolltech AS, Norway (or with modified versions * * of Qt that use the same license as Qt), and distribute linked * * combinations including the two. You must obey the GNU General * * Public License in all respects for all of the code used other than * * Qt. If you modify this file, you may extend this exception to * * your version of the file, but you are not obligated to do so. If * * you do not wish to do so, delete this exception statement from * * your version. * ***************************************************************************/ #include "TypePixmap.h" #include <QApplication> #include <QDebug> #include <QStyleOptionButton> #include <QColor> #include <QBitmap> PropertyItemPixmap::PropertyItemPixmap( QString name, const QVariant &value, PropertyItem *parent ) : PropertyItem( name, parent ) { setData( value ); setValueRenderer( PropertyRendererPixmap::K_ID ); } ///////////////////////////////////////////////////////////// const QString PropertyRendererPixmap::K_ID = "RENDER_PIXMAP_DEF"; PropertyRendererPixmap::PropertyRendererPixmap( QObject *parent ) : PropertyRenderer( parent ) { } void PropertyRendererPixmap::paintProperty ( QPainter * painter, const QStyleOptionViewItem &option, const QModelIndex &index ) { static const int i = 16; PropertyItem *data = modelIndexToData( index ); if ( data == 0 ) return ; QRect rect = option.rect; QRect pixRec = QRect( rect.left() + i / 2, rect.top() + ( rect.height() - i ) / 2, i, i ); QPixmap pix = getPixmapFromQVariant( data->data() ); painter->drawPixmap( pixRec, pix ); } QPixmap PropertyRendererPixmap::getPixmapFromQVariant( const QVariant&px ) const { switch ( px.type() ) { case QVariant::Bitmap: return px.value<QBitmap>(); case QVariant::Image: return QPixmap::fromImage( px.value<QImage>() ); case QVariant::Pixmap: return px.value<QPixmap>(); default: return QPixmap(); } return QPixmap(); //<- on ne devrait jamais arriver la ;) } QSize PropertyRendererPixmap::sizeHint( const QStyleOptionViewItem & option, const QModelIndex &index ) { return option.rect.size(); }
MassMessage/qpropertygrid
src/property/defaulttype/TypePixmap.cpp
C++
gpl-2.0
3,803
<?php /* * ZenMagick - Another PHP framework. * Copyright (C) 2006-2012 zenmagick.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 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ namespace ZenMagick\ZenMagickBundle\DependencyInjection\Loader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; /** * Yaml loader for dependency injection container definitions. * * <p>Based on the <em>symfony2</em> dependency injection component.</p> * * <p>This class allows to load YAML strings into the container by <em>abusing</em> the <code>FileLocator</code> and a few other * bits of the symfony DI loader system.</p> * * @author DerManoMann <mano@zenmagick.org> */ class YamlLoader extends YamlFileLoader { /** * {@inheritDoc} */ public function __construct(ContainerBuilder $container, FileLocator $locator=null) { parent::__construct($container, new EchoFileLocator(dirname(__FILE__))); } /** * {@inheritDoc} */ protected function addResource($path) { // nothing } /** * {@inheritDoc} * * <p>Just return the given yaml.</p> */ public function loadFile($yaml) { return $yaml; } /** * {@inheritDoc} */ public function findFile($file) { return $file; } /** * {@inheritDoc} * * <p>Accept <code>array</code> resources with a '<em>services</em>' key.</p> */ public function supports($resource, $type=null) { return is_array($resource) && array_key_exists('services', $resource); } } /** * Fake class to allow loading yaml from strings. */ class EchoFileLocator extends FileLocator { public function locate($name, $currentPath=null, $first=true) { return $name; } }
ZenMagick/ZenMagick
src/ZenMagick/ZenMagickBundle/DependencyInjection/Loader/YamlLoader.php
PHP
gpl-2.0
2,468
<?php /** * @file * Contains \Drupal\Core\Field\Plugin\Field\FieldFormatter\StringFormatter. */ namespace Drupal\Core\Field\Plugin\Field\FieldFormatter; use Drupal\Core\Entity\EntityManagerInterface; use Drupal\Core\Field\FieldDefinitionInterface; use Drupal\Core\Field\FieldItemInterface; use Drupal\Core\Field\FieldItemListInterface; use Drupal\Core\Field\FormatterBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Plugin implementation of the 'string' formatter. * * @FieldFormatter( * id = "string", * label = @Translation("Plain text"), * field_types = { * "string", * "uri", * }, * quickedit = { * "editor" = "plain_text" * } * ) */ class StringFormatter extends FormatterBase implements ContainerFactoryPluginInterface { /** * Constructs a StringFormatter instance. * * @param string $plugin_id * The plugin_id for the formatter. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The definition of the field to which the formatter is associated. * @param array $settings * The formatter settings. * @param string $label * The formatter label display setting. * @param string $view_mode * The view mode. * @param array $third_party_settings * Any third party settings settings. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. */ public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityManagerInterface $entity_manager) { parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings); $this->entityManager = $entity_manager; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container->get('entity.manager') ); } /** * {@inheritdoc} */ public static function defaultSettings() { $options = parent::defaultSettings(); $options['link_to_entity'] = FALSE; return $options; } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $form = parent::settingsForm($form, $form_state); $entity_type = $this->entityManager->getDefinition($this->fieldDefinition->getTargetEntityTypeId()); $form['link_to_entity'] = [ '#type' => 'checkbox', '#title' => $this->t('Link to the @entity_label', ['@entity_label' => $entity_type->getLabel()]), '#default_value' => $this->getSetting('link_to_entity'), ]; return $form; } /** * {@inheritdoc} */ public function settingsSummary() { $summary = []; if ($this->getSetting('link_to_entity')) { $entity_type = $this->entityManager->getDefinition($this->fieldDefinition->getTargetEntityTypeId()); $summary[] = $this->t('Linked to the @entity_label', ['@entity_label' => $entity_type->getLabel()]); } return $summary; } /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $elements = array(); $url = NULL; if ($this->getSetting('link_to_entity')) { // For the default revision this falls back to 'canonical' $url = $items->getEntity()->urlInfo('revision'); } foreach ($items as $delta => $item) { $view_value = $this->viewValue($item); if ($url) { $elements[$delta] = [ '#type' => 'link', '#title' => $view_value, '#url' => $url, ]; } else { $elements[$delta] = $view_value; } } return $elements; } /** * Generate the output appropriate for one field item. * * @param \Drupal\Core\Field\FieldItemInterface $item * One field item. * * @return array * The textual output generated as a render array. */ protected function viewValue(FieldItemInterface $item) { // The text value has no text format assigned to it, so the user input // should equal the output, including newlines. return [ '#type' => 'inline_template', '#template' => '{{ value|nl2br }}', '#context' => ['value' => $item->value], ]; } }
papillon-cendre/d8
core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/StringFormatter.php
PHP
gpl-2.0
4,793
/** * Copyright (c) 2013-2015. Department of Computer Science, University of Victoria. All Rights Reserved. * This software is published under the GPL GNU General Public 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; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Computer Science * LeadLab * University of Victoria * Victoria, Canada */ package org.oscarehr.ws.rest.to.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name="favorite") public class FavoriteTo1 implements Serializable { private static final long serialVersionUID = 1L; private Integer favoriteId; private String brandName; private String genericName; private String atc; private String favoriteName; // DIN number in Canada. private String regionalIdentifier; private Integer providerNo; private float takeMin; private float takeMax; private String frequency; private Integer duration; private String durationUnit; private Integer quantity; private String route; private String form; private String method; private Boolean prn; private Integer repeats; private String instructions; private Float strength; private String strengthUnit; private String externalProvider; private Boolean longTerm; private Boolean noSubstitutions; public Integer getId() { return favoriteId; } public void setId(Integer id) { this.favoriteId = id; } public Integer getFavoriteId() { return favoriteId; } public void setFavoriteId(Integer id) { this.favoriteId = id; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getGenericName() { return genericName; } public void setGenericName(String genericName) { this.genericName = genericName; } public String getAtc() { return atc; } public void setAtc(String atc) { this.atc = atc; } public String getFavoriteName() { return favoriteName; } public void setFavoriteName(String favoriteName) { this.favoriteName = favoriteName; } public String getRegionalIdentifier() { return regionalIdentifier; } public void setRegionalIdentifier(String regionalIdentifier) { this.regionalIdentifier = regionalIdentifier; } public Integer getProviderNo() { return providerNo; } public void setProviderNo(Integer providerNo) { this.providerNo = providerNo; } public float getTakeMin() { return takeMin; } public void setTakeMin(float takeMin) { this.takeMin = takeMin; } public float getTakeMax() { return takeMax; } public void setTakeMax(float takeMax) { this.takeMax = takeMax; } public String getFrequency() { return frequency; } public void setFrequency(String frequency) { this.frequency = frequency; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public String getDurationUnit() { return durationUnit; } public void setDurationUnit(String durationUnit) { this.durationUnit = durationUnit; } public String getRoute() { return route; } public void setRoute(String route) { this.route = route; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Boolean getPrn() { return prn; } public void setPrn(Boolean prn) { this.prn = prn; } public Integer getRepeats() { return repeats; } public void setRepeats(Integer repeats) { this.repeats = repeats; } public String getInstructions() { return instructions; } public void setInstructions(String instructions) { this.instructions = instructions; } public Float getStrength() { return strength; } public void setStrength(Float strength) { this.strength = strength; } public String getStrengthUnit() { return strengthUnit; } public void setStrengthUnit(String strengthUnit) { this.strengthUnit = strengthUnit; } public String getExternalProvider() { return externalProvider; } public void setExternalProvider(String externalProvider) { this.externalProvider = externalProvider; } public Boolean getLongTerm() { return longTerm; } public void setLongTerm(Boolean longTerm) { this.longTerm = longTerm; } public Boolean getNoSubstitutions() { return noSubstitutions; } public void setNoSubstitutions(Boolean noSubstitutions) { this.noSubstitutions = noSubstitutions; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } }
scoophealth/oscar
src/main/java/org/oscarehr/ws/rest/to/model/FavoriteTo1.java
Java
gpl-2.0
6,203
<?php /** * Template part for displaying a message that posts cannot be found * * @link https://codex.wordpress.org/Template_Hierarchy * * @package inward-revenue */ ?> <section class="no-results not-found"> <header class="page-header"> <h1 class="page-title"><?php esc_html_e( 'Nothing Found', 'cap-theme' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?> <p><?php printf( wp_kses( /* translators: 1: link to WP admin new post page. */ __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'cap-theme' ), array( 'a' => array( 'href' => array(), ), ) ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p> <?php elseif ( is_search() ) : ?> <p><?php esc_html_e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'cap-theme' ); ?></p> <?php get_search_form(); else : ?> <p><?php esc_html_e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching can help.', 'cap-theme' ); ?></p> <?php get_search_form(); endif; ?> </div><!-- .page-content --> </section><!-- .no-results -->
felixgrowoffshore/inwardsrevenue
template-parts/content-none.php
PHP
gpl-2.0
1,276
<?php if ( ! defined( 'ABSPATH' ) ) die( 'Forbidden' ); /** * Plugin Name: Unyson * Plugin URI: http://unyson.themefuse.com/ * Description: A free drag & drop framework that comes with a bunch of built in extensions that will help you develop premium themes fast & easy. * Version: 2.3.1 * Author: ThemeFuse * Author URI: http://themefuse.com * License: GPL2+ * Text Domain: fw * Domain Path: /languages/ */ if (defined('FW')) { /** * The plugin was already loaded (maybe as another plugin with different directory name) */ } else { { /** @internal */ function _filter_fw_framework_plugin_directory_uri() { return plugin_dir_url( __FILE__ ) . 'framework'; } add_filter( 'fw_framework_directory_uri', '_filter_fw_framework_plugin_directory_uri' ); } require dirname( __FILE__ ) . '/framework/bootstrap.php'; /** * Plugin related functionality * * Note: * The framework doesn't know that it's used as a plugin. * It can be localed in the theme directory or any other directory. * Only its path and uri is known (specified above) */ { /** @internal */ function _action_fw_plugin_activate() { { require_once dirname(__FILE__) .'/framework/includes/term-meta/function_fw_term_meta_setup_blog.php'; if (is_multisite() && is_network_admin()) { global $wpdb; $blogs = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = '{$wpdb->siteid}'" ); foreach ( $blogs as $blog_id ) { switch_to_blog( $blog_id ); _fw_term_meta_setup_blog( $blog_id ); } do {} while ( restore_current_blog() ); } else { _fw_term_meta_setup_blog(); } } // add special option (is used in another action) update_option('_fw_plugin_activated', true); } register_activation_hook( __FILE__, '_action_fw_plugin_activate' ); /** @internal */ function _action_fw_plugin_check_if_was_activated() { if (get_option('_fw_plugin_activated')) { delete_option('_fw_plugin_activated'); do_action('fw_after_plugin_activate'); } } add_action('current_screen', '_action_fw_plugin_check_if_was_activated', 100); // as late as possible, but to be able to make redirects (content not started) /** @internal */ function _action_fw_term_meta_new_blog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) { if ( is_plugin_active_for_network( plugin_basename( __FILE__ ) ) ) { require_once dirname(__FILE__) .'/framework/includes/term-meta/function_fw_term_meta_setup_blog.php'; switch_to_blog( $blog_id ); _fw_term_meta_setup_blog(); do {} while ( restore_current_blog() ); } } add_action( 'wpmu_new_blog', '_action_fw_term_meta_new_blog', 10, 6 ); /** * @param int $blog_id Blog ID * @param bool $drop True if blog's table should be dropped. Default is false. * @internal */ function _action_fw_delete_blog( $blog_id, $drop ) { if ($drop) { // delete table created by the _fw_term_meta_setup_blog() function /** @var WPDB $wpdb */ global $wpdb; if (property_exists($wpdb, 'fw_termmeta')) { // it should exist, but check to be sure $wpdb->query("DROP TABLE IF EXISTS {$wpdb->fw_termmeta};"); } } } add_action( 'delete_blog', '_action_fw_delete_blog', 10, 2 ); /** @internal */ function _filter_fw_check_if_plugin_pre_update( $result, $data ) { if ( isset( $data['plugin'] ) && $data['plugin'] === plugin_basename( __FILE__ ) ) { /** * Before plugin update */ do_action( 'fw_plugin_pre_update' ); } return $result; } add_filter( 'upgrader_pre_install', '_filter_fw_check_if_plugin_pre_update', 10, 2 ); /** @internal */ function _filter_fw_check_if_plugin_post_update( $result, $data ) { if ( isset( $data['plugin'] ) && $data['plugin'] === plugin_basename( __FILE__ ) ) { /** * After plugin update */ do_action( 'fw_plugin_post_update' ); } return $result; } add_filter( 'upgrader_post_install', '_filter_fw_check_if_plugin_post_update', 10, 2 ); /** @internal */ function _filter_fw_plugin_action_list( $actions ) { return apply_filters( 'fw_plugin_action_list', $actions ); } add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), '_filter_fw_plugin_action_list' ); /** @internal */ function _action_fw_textdomain() { load_plugin_textdomain( 'fw', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); } add_action( 'plugins_loaded', '_action_fw_textdomain' ); /** @internal */ function _filter_fw_tmp_dir( $dir ) { /** * Some users force WP_Filesystem to use the 'direct' method <?php define( 'FS_METHOD', 'direct' ); ?> and set chmod 777 to the unyson/ plugin. * By default tmp dir is WP_CONTENT_DIR.'/tmp' and WP_Filesystem can't create it with 'direct' method, then users can't download and install extensions. * In order to prevent this situation, create the temporary directory inside the plugin folder. */ return dirname( __FILE__ ) . '/tmp'; } add_filter( 'fw_tmp_dir', '_filter_fw_tmp_dir' ); } }
alireza--noori/initial-portfolio-website-test-
wp-content/plugins/unyson/unyson.php
PHP
gpl-2.0
5,054
/* * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C) * 2009 Royal Institute of Technology (KTH) * * GVoD is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package se.sics.gvod.system; import com.google.common.util.concurrent.SettableFuture; import se.sics.gvod.manager.VoDManagerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.sics.gvod.bootstrap.client.BootstrapClientComp; import se.sics.gvod.bootstrap.client.BootstrapClientInit; import se.sics.gvod.bootstrap.client.BootstrapClientPort; import se.sics.gvod.bootstrap.server.BootstrapServerComp; import se.sics.gvod.bootstrap.server.peermanager.PeerManagerPort; import se.sics.gvod.common.utility.UtilityUpdatePort; import se.sics.gvod.core.VoDComp; import se.sics.gvod.core.VoDInit; import se.sics.gvod.core.VoDPort; import se.sics.kompics.Component; import se.sics.kompics.ComponentDefinition; import se.sics.kompics.Init; import se.sics.kompics.Positive; import se.sics.kompics.network.Network; import se.sics.kompics.timer.Timer; import se.sics.p2ptoolbox.util.traits.Nated; /** * @author Alex Ormenisan <aaor@sics.se> */ public class HostManagerComp extends ComponentDefinition { private static final Logger log = LoggerFactory.getLogger(HostManagerComp.class); private Positive<Network> network = requires(Network.class); private Positive<Timer> timer = requires(Timer.class); private Component vodMngr; private Component vod; private Component bootstrapClient; private Component bootstrapServer; private Component peerManager; private Component globalCroupier; private final HostManagerConfig config; public HostManagerComp(HostManagerInit init) { log.debug("starting... - self {}, bootstrap server {}", new Object[]{init.config.getSelf(), init.config.getCaracalClient()}); this.config = init.config; this.vodMngr = create(VoDManagerImpl.class, new VoDManagerImpl.VoDManagerInit(config.getVoDManagerConfig())); init.gvodSyncIFuture.set(vodMngr.getComponent()); this.vod = create(VoDComp.class, new VoDInit(config.getVoDConfig())); this.bootstrapClient = create(BootstrapClientComp.class, new BootstrapClientInit(config.getBootstrapClientConfig())); log.info("{} node is Natted:{}", config.getSelf(), config.getSelf().hasTrait(Nated.class)); if (!config.getSelf().hasTrait(Nated.class)) { bootstrapServer = create(BootstrapServerComp.class, new BootstrapServerComp.BootstrapServerInit(config.getBootstrapServerConfig())); peerManager = init.peerManager; connect(bootstrapServer.getNegative(Network.class), network); connect(bootstrapServer.getNegative(PeerManagerPort.class), peerManager.getPositive(PeerManagerPort.class)); } else { bootstrapServer = null; peerManager = null; } connect(vodMngr.getNegative(VoDPort.class), vod.getPositive(VoDPort.class)); connect(vod.getNegative(Network.class), network); connect(vod.getNegative(BootstrapClientPort.class), bootstrapClient.getPositive(BootstrapClientPort.class)); connect(vod.getNegative(Timer.class), timer); connect(bootstrapClient.getNegative(Network.class), network); connect(bootstrapClient.getNegative(Timer.class), timer); connect(bootstrapClient.getNegative(UtilityUpdatePort.class), vod.getPositive(UtilityUpdatePort.class)); connect(vodMngr.getNegative(UtilityUpdatePort.class), vod.getPositive(UtilityUpdatePort.class)); } public static class HostManagerInit extends Init<HostManagerComp> { public final HostManagerConfig config; public final Component peerManager; public final SettableFuture gvodSyncIFuture; public HostManagerInit(HostManagerConfig config, Component peerManager, SettableFuture gvodSyncIFuture) { this.config = config; this.peerManager = peerManager; this.gvodSyncIFuture = gvodSyncIFuture; } } }
o-alex/GVoD
system/src/main/java/se/sics/gvod/system/HostManagerComp.java
Java
gpl-2.0
4,732