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
package be.neutrinet.ispng.security; import be.neutrinet.ispng.vpn.Users; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import org.apache.log4j.Logger; import java.sql.SQLException; import java.util.UUID; /** * Created by wannes on 12/20/14. */ @DatabaseTable(tableName = "session_tokens") public class SessionToken { @DatabaseField(canBeNull = false) private UUID user; @DatabaseField(canBeNull = false) private String address; @DatabaseField(canBeNull = false) private long creationTime; @DatabaseField(id = true) private UUID token; private SessionToken() { } public SessionToken(UUID user, String address) { this.user = user; this.address = address; this.creationTime = System.currentTimeMillis(); this.token = UUID.randomUUID(); try { SessionTokens.dao.create(this); } catch (SQLException ex) { Logger.getLogger(getClass()).error("Failed to create session token", ex); } } public UUID getToken() { return token; } public UUID getUser() { return user; } public String getAddress() { return address; } public long getCreationTime() { return creationTime; } public boolean valid() { if (Users.isRelatedService(this.user)) return true; return System.currentTimeMillis() - this.creationTime <= 3600 * 1000; } }
Neutrinet/ISP-ng
src/main/java/be/neutrinet/ispng/security/SessionToken.java
Java
gpl-3.0
1,487
import React, { Component } from 'react'; import { Link } from 'react-router-dom' import { CSSTransition } from 'react-transition-group'; class Nav extends Component { constructor(props) { super(props); this.state = { menuActive: false } this.handleClick = this.handleClick.bind(this); } handleClick() { var obj = {}; obj['menuActive'] = !this.state.menuActive; this.setState(obj); } render() { return ( <div className={this.state.menuActive? 'nav active': 'nav'} > <div className='nav__button' onClick={this.handleClick}> <div className='nav__buttonPart' /> <div className='nav__buttonPart' /> <div className='nav__buttonPart' /> <div className="nav__buttonTitle"> {this.state.menuActive? <div>Close</div> : <div>Menu</div>} </div> </div> <div className='nav__menuBox'> <ul className='nav__menu'> <li className='nav__menuItem'> <Link to='/'> home </Link> </li> <li className='nav__menuItem'> <Link to='/'> blog </Link> </li> <li className='nav__menuItem'> <Link to='/About'> about </Link> </li> </ul> </div> <CSSTransition in={this.state.menuActive} timeout={300} classNames="nav__background" > <div className="nav__background"/> </CSSTransition> <CSSTransition in={this.state.menuActive} timeout={300} classNames="nav__shadowBackground" > <div className="nav__shadowBackground"/> </CSSTransition> </div> ); } } export default Nav;
7sleepwalker/addicted-to-mnt
src/js/Components/Nav.js
JavaScript
gpl-3.0
1,662
using GIELIE.Data.Interfaces; using System; namespace GIELIE.Data.DTO.Models { public class Category : ICategory { public Guid CategoryId { get; set; } public string Description { get; set; } } }
FoulFruit/Gielie
GIELIE.DataTransferObjects/Models/Category.cs
C#
gpl-3.0
285
package demo.designpatterns.simplefactory; /** * Created by Roger Xu on 2017/6/24. */ public class MobileFactory { public Mobile getMobile(String title) throws Exception { if (title.equalsIgnoreCase("nokia")) { return new Nokia(); } else if (title.equalsIgnoreCase("motorola")) { return new Motorola(); } else { throw new Exception("no such " + title + " mobile found"); } } }
rogerxu/design-patterns
src/main/java/demo/designpatterns/simplefactory/MobileFactory.java
Java
gpl-3.0
456
Bitrix 16.5 Business Demo = 2766fc7626da327759c9a996f5e98720
gohdan/DFC
known_files/hashes/bitrix/modules/sale/install/admin/sale_stat_graph_money.php
PHP
gpl-3.0
61
/** * Contains methods for working with device using the MODBUS protocol over * RS232 */ package kernel.modbus;
OmicronProject/BakeoutController-Basic
src/main/java/kernel/modbus/package-info.java
Java
gpl-3.0
114
package problem0137 func singleNumber(nums []int) int { var ans int32 for i := 0; i < 32; i++ { cnt := 0 for _, num := range nums { if (num & (1 << uint(i))) > 0 { cnt++ } } if cnt%3 == 1 { ans |= 1 << uint(i) } } return int(ans) }
zjbztianya/LeetCode
Algorithms/0137.single-number-ii/single-number-ii.go
GO
gpl-3.0
260
/* * Orthos backend functions. Mostly inspired by slim DM code. * Big thanks to Per Liden, Simone Rota and Johannes Winkelmann. * * [exa] */ #include "sys.h" #include "settings.h" //#define _GNU_SOURCE #include <sys/types.h> #include <sys/time.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <shadow.h> #include <pwd.h> #include <grp.h> #include <X11/Xlib.h> #include <X11/Xmu/WinUtil.h> #include <stdlib.h> #include <string.h> #include <string> #include <iostream> using namespace std; /* * DEFAULT_PATH is the PATH argument with which the * session shall be executed. As long as anyone can set his own session, * PLEASE take care of right path setting externally, OR correct it here and * mail it to me. thx. */ #define DEFAULT_PATH (get_setting("default_path")) #define XSERVER_PATH (get_setting("Xserver")) #define XAUTH_PATH (get_setting("Xauth")) #define SERVER_AUTH (get_setting("server_auth")) #define SERVER_DISPLAY (get_setting("display")) #define SERVER_ARGS (get_setting("server_args")) static Display* active_display; static pid_t server_pid = 0; static char magic_cookie[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; static void generate_magic_cookie() { static bool random_initd = 0; if (!random_initd) { struct timeval tv; struct timezone tz; gettimeofday (&tv, &tz); srand (tv.tv_sec ^ tv.tv_usec); random_initd = 1; } char p[] = "0123456789abcdef"; for (int i = 0; i < 32;++i) magic_cookie[i] = p[rand() %16]; } static int server_timeout (int time) { pid_t p; do { p = waitpid (server_pid, 0, WNOHANG); if (p == server_pid) return 0; usleep (10000); } while ( (time--) > 0); return 1; } int x_server_blank () { Display*d=active_display; if(!d)return 1; GC gc = XCreateGC(d, DefaultRootWindow(d), 0, 0); XSetForeground(d,gc,BlackPixel(d,DefaultScreen(d))); XFillRectangle(d,DefaultRootWindow(d),gc,0,0, XWidthOfScreen(ScreenOfDisplay(d,DefaultScreen(d))), XWidthOfScreen(ScreenOfDisplay(d,DefaultScreen(d)))); XFlush(d); XFreeGC(d,gc); return 0; } static int wait_for_server() { for (int i = 0;i < 30;++i) if ( (active_display = XOpenDisplay (SERVER_DISPLAY) ) ) return 0; //ok else if (!server_timeout (1) ) return 2; //server died return 1; //timeout } static int add_xauth (const char*fn) { unlink(fn); string cmd = string (XAUTH_PATH) + " -q -f " + fn + " add " + SERVER_DISPLAY + " . " + magic_cookie; /* * note: system() may possibly fail to set xauth. * but then the process might get ressurected somehow * by some client scripts, so we don't suppose that * it's all doomed. * * Also, auth number could be possibly seen in ps ax. * too bad. lol. */ return system (cmd.c_str() ); } static void signal_handler(int n) { cerr << "killed by signal: " << n << endl; x_server_stop(); orthos_kill(n); } static int catch_error (Display*dpy, XErrorEvent*ev) { return 0; } int sys_setup() { signal (SIGTTIN, SIG_IGN); signal (SIGTTOU, SIG_IGN); signal (SIGUSR1, SIG_IGN); signal (SIGHUP, SIG_IGN); signal (SIGQUIT, signal_handler); signal (SIGTERM, signal_handler); signal (SIGINT, signal_handler); signal (SIGKILL, signal_handler); signal (SIGALRM, SIG_IGN); XSetErrorHandler (catch_error); return 0; } int sys_reset_signals() { signal (SIGTTIN, SIG_DFL); signal (SIGTTOU, SIG_DFL); signal (SIGUSR1, SIG_DFL); signal (SIGHUP, SIG_DFL); signal (SIGQUIT, SIG_DFL); signal (SIGTERM, SIG_DFL); signal (SIGINT, SIG_DFL); signal (SIGKILL, SIG_DFL); signal (SIGALRM, SIG_DFL); return 0; } int x_server_start () { if (server_pid) if (!x_server_running() ) x_server_stop(); server_pid = 0; generate_magic_cookie(); pid_t p = fork(); if (!p) { //spawned process if(add_xauth (SERVER_AUTH)) exit(-2); //close(0); //close(1); //close(2); setpgid (0, getpid() ); string cmdline = string (XSERVER_PATH) + " " + SERVER_DISPLAY + " -auth " + SERVER_AUTH + " " + SERVER_ARGS; sys_exec (cmdline.c_str() ); exit (-1); } if (p < 0) return -1; //too bad server_pid = p; if(!server_timeout(5)) { cerr <<"server timed out"<<endl; return 1; } setenv ("XAUTHORITY", SERVER_AUTH, 1); setenv ("DISPLAY", SERVER_DISPLAY, 1); if (int t=wait_for_server() ) { cerr << "server connection timed out "<<t<<endl; server_pid = 0; return 2; } x_server_blank(); //evarything seemez ok return 0; } int x_server_stop () { if(!server_pid) return 0; //alrdy stopped if(active_display) XCloseDisplay(active_display); active_display=0; unsetenv("XAUTHORITY"); unsetenv("DISPLAY"); errno = 0; if (killpg (server_pid, SIGTERM) < 0) { if (errno == EPERM) return -1; if (errno == ESRCH) return 0; //possibly killed now } if (!server_timeout (10) ) { //shutdown wait //shutdown ok return 0; } errno = 0; if (killpg (server_pid, SIGKILL) < 0) if (errno == ESRCH) return 0; if (server_timeout (3) ) //server didn't die return -2; //evarything ouk server_pid=0; unlink(SERVER_AUTH); return 0; } int x_server_running () { Display*d = XOpenDisplay (SERVER_DISPLAY); if (!d) return 1; XCloseDisplay (d); return 0; } int x_get_resolution (int*x, int*y) { XWindowAttributes attribs; *x=0;*y=0; Display*d=active_display; if(!d)return 1; XGetWindowAttributes(d,DefaultRootWindow(d),&attribs); *x=attribs.width; *y=attribs.height; return 0; } int sys_auth_user (const char*username, const char*password) { struct passwd*pw; struct spwd*sp; char*encrypted, *correct; pw = getpwnam (username); endpwent(); if (!pw) return 1; //user doesn't really exist sp = getspnam (pw->pw_name); endspent(); if (sp) correct = sp->sp_pwdp; else correct = pw->pw_passwd; encrypted = crypt (password, correct); return strcmp (encrypted, correct) ? 2 : 0; // bad pw=2, success=0 } int sys_do_login_user (const char*username, const char*session) { if (!server_pid) return -2; //server lack lol. x_server_blank(); XCloseDisplay(active_display); //server killing protection active_display=0; struct passwd*pw; pw = getpwnam (username); endpwent(); if (!pw) return -1; //user not found //check against empty shells if (pw->pw_shell[0] == 0) { setusershell(); strcpy (pw->pw_shell, getusershell() ); endusershell(); } //fork off pid_t pid; pid = fork(); if (!pid) { //spawned child string xauth_file = string (pw->pw_dir) + "/.Xauthority"; chdir(pw->pw_dir); //set all the environment (we shall inherit the rest) setenv ("HOME", pw->pw_dir, 1); setenv ("SHELL", pw->pw_shell, 1); setenv ("USER", pw->pw_name, 1); setenv ("LOGNAME", pw->pw_name, 1); //setenv ("PATH", DEFAULT_PATH, 1); //path can be default ok? setenv ("DISPLAY", SERVER_DISPLAY, 1); setenv ("XAUTHORITY", xauth_file.c_str(), 1); //switch UID and stuff if (initgroups (pw->pw_name, pw->pw_gid) || setgid (pw->pw_gid) || setuid (pw->pw_uid) ) exit (-1); //write xauth add_xauth (xauth_file.c_str() ); //now charge da laz0rz and exec session. sys_exec(session,pw->pw_shell,true); } if (pid == -1) //failed to fork. die. return -2; //wait for session. pid_t wpid = -1; int status = 0; while (wpid != pid) wpid = wait (&status); killpg (server_pid, SIGHUP); sleep(1); //so we dont get killed along active_display=XOpenDisplay(SERVER_DISPLAY); if(!active_display)return -3; return status; } int sys_exec (const char*cmd, const char*shell, bool login) { /* * use the shell and builtins to parse the arguments. * it's not the fastest, but surely the cleanest way. */ string a = "exec "; a += cmd; char*args[] = {login?(char*)((string("-")+shell).c_str()):(char*)shell, (char*)"-c", (char*) (a.c_str() ), 0}; return execve (shell, args, environ); } int sys_spawn(const char*cmd, const char*shell) { pid_t p=fork(); if(p<0)return 1; if(p) return 0; setsid(); if(sys_exec(cmd,shell))_exit(1); return -1; //definately bad here! } int fork_to_background() { pid_t p=fork(); if(p) return p; //also handles errors if(!get_bool_setting("debug")) { close(0); close(1); close(2); } setsid(); return 0; }
aur-archive/orthos
sys.cpp
C++
gpl-3.0
8,120
/* * PropertiesToolBar.java * * Copyright (C) 2002-2017 Takis Diakoumis * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.executequery.gui.prefs; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.util.Collections; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.executequery.Constants; import org.executequery.GUIUtilities; import org.underworldlabs.swing.actions.ActionUtilities; import org.underworldlabs.swing.actions.ReflectiveAction; import org.underworldlabs.swing.toolbar.ButtonComparator; import org.underworldlabs.swing.toolbar.ToolBarButton; import org.underworldlabs.swing.toolbar.ToolBarProperties; import org.underworldlabs.swing.toolbar.ToolBarWrapper; /** * * @author Takis Diakoumis */ public class PropertiesToolBar extends AbstractPropertiesBasePanel { private Vector selections; private JTable table; private ToolBarButtonModel toolButtonModel; private static IconCellRenderer iconRenderer; private static NameCellRenderer nameRenderer; private JButton moveUpButton; private JButton moveDownButton; private JButton addSeparatorButton; private JButton removeSeparatorButton; /** The tool bar name */ private String toolBarName; /** The tool bar wrapper */ private ToolBarWrapper toolBar; public PropertiesToolBar(String toolBarName) { this.toolBarName = toolBarName; try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() { ReflectiveAction action = new ReflectiveAction(this); moveUpButton = ActionUtilities.createButton( action, GUIUtilities.loadIcon("Up16.png", true), null, "moveUp"); moveDownButton = ActionUtilities.createButton( action, GUIUtilities.loadIcon("Down16.png", true), null, "moveDown"); moveUpButton.setMargin(Constants.EMPTY_INSETS); moveDownButton.setMargin(Constants.EMPTY_INSETS); addSeparatorButton = ActionUtilities.createButton( action, "Add Separator", "addSeparator"); addSeparatorButton.setToolTipText("Adds a separator above the selection"); removeSeparatorButton = ActionUtilities.createButton( action, "Remove Separator", "removeSeparator"); removeSeparatorButton.setToolTipText("Removes the selected separator"); ToolBarWrapper _toolBar = ToolBarProperties.getToolBar(toolBarName); toolBar = (ToolBarWrapper)_toolBar.clone(); selections = toolBar.getButtonsVector(); setInitialValues(); iconRenderer = new IconCellRenderer(); nameRenderer = new NameCellRenderer(); toolButtonModel = new ToolBarButtonModel(); table = new JTable(toolButtonModel); setTableProperties(); JScrollPane scroller = new JScrollPane(table); scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroller.getViewport().setBackground(table.getBackground()); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = 0; gbc.gridx = 0; gbc.weightx = 1.0; gbc.insets.bottom = 5; gbc.gridwidth = 2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTHWEST; panel.add(new JLabel(toolBarName + " - Buttons"), gbc); gbc.gridy++; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.BOTH; panel.add(scroller, gbc); gbc.gridy++; gbc.weighty = 0; gbc.insets.bottom = 10; gbc.insets.right = 10; gbc.gridwidth = 1; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(addSeparatorButton, gbc); gbc.gridx++; gbc.insets.right = 0; panel.add(removeSeparatorButton, gbc); JPanel movePanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc2 = new GridBagConstraints(); gbc2.gridy = 0; gbc2.insets.bottom = 10; gbc2.anchor = GridBagConstraints.CENTER; movePanel.add(moveUpButton, gbc2); gbc2.gridy++; gbc2.insets.bottom = 5; gbc2.insets.top = 5; movePanel.add(new JLabel("Move"), gbc2); gbc2.gridy++; gbc2.insets.bottom = 10; movePanel.add(moveDownButton, gbc2); gbc.gridx++; gbc.gridy = 0; gbc.weighty = 1.0; gbc.weightx = 0; gbc.insets.left = 5; gbc.anchor = GridBagConstraints.CENTER; gbc.gridheight = GridBagConstraints.REMAINDER; gbc.fill = GridBagConstraints.NONE; panel.add(movePanel, gbc); addContent(panel); } private void setTableProperties() { table.setTableHeader(null); table.setColumnSelectionAllowed(false); table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setIntercellSpacing(new Dimension(0,0)); table.setShowGrid(false); table.setRowHeight(28); table.doLayout(); TableColumnModel tcm = table.getColumnModel(); tcm.getColumn(0).setPreferredWidth(30); TableColumn col = tcm.getColumn(1); col.setPreferredWidth(40); col.setCellRenderer(iconRenderer); col = tcm.getColumn(2); col.setPreferredWidth(251); col.setCellRenderer(nameRenderer); } private void setInitialValues() { Collections.sort(selections, new ButtonComparator()); } public void restoreDefaults() { ToolBarWrapper _toolBar = ToolBarProperties.getDefaultToolBar(toolBarName); toolBar = (ToolBarWrapper)_toolBar.clone(); selections = toolBar.getButtonsVector(); Collections.sort(selections, new ButtonComparator()); toolButtonModel.fireTableRowsUpdated(0, selections.size()-1); } public void save() { int size = selections.size(); Vector buttons = new Vector(selections.size()); // update the buttons for (int i = 0; i < size; i++) { ToolBarButton tb = (ToolBarButton)selections.elementAt(i); if (tb.isVisible()) tb.setOrder(i); else tb.setOrder(1000); buttons.add(tb); } toolBar.setButtonsVector(buttons); ToolBarProperties.resetToolBar(toolBarName, toolBar); } public void addSeparator(ActionEvent e) { int selection = table.getSelectedRow(); if (selection == -1) { return; } ToolBarButton tb = new ToolBarButton(ToolBarButton.SEPARATOR_ID); tb.setOrder(selection); tb.setVisible(true); selections.insertElementAt(tb, selection); toolButtonModel.fireTableRowsInserted(selection == 0 ? 0 : selection - 1, selection == 0 ? 1 : selection); } public void removeSeparator(ActionEvent e) { int selection = table.getSelectedRow(); if (selection == -1) { return; } ToolBarButton remove = (ToolBarButton)selections.elementAt(selection); if (!remove.isSeparator()) { return; } selections.removeElementAt(selection); toolButtonModel.fireTableRowsDeleted(selection, selection); } public void moveUp(ActionEvent e) { int selection = table.getSelectedRow(); if (selection <= 0) { return; } int newPostn = selection - 1; ToolBarButton move = (ToolBarButton)selections.elementAt(selection); selections.removeElementAt(selection); selections.add(newPostn, move); table.setRowSelectionInterval(newPostn, newPostn); toolButtonModel.fireTableRowsUpdated(newPostn, selection); } public void moveDown(ActionEvent e) { int selection = table.getSelectedRow(); if (selection == -1 || selection == selections.size() - 1) { return; } int newPostn = selection + 1; ToolBarButton move = (ToolBarButton)selections.elementAt(selection); selections.removeElementAt(selection); selections.add(newPostn, move); table.setRowSelectionInterval(newPostn, newPostn); toolButtonModel.fireTableRowsUpdated(selection, newPostn); } private class ToolBarButtonModel extends AbstractTableModel { public ToolBarButtonModel() {} public int getColumnCount() { return 3; } public int getRowCount() { return selections.size(); } public Object getValueAt(int row, int col) { ToolBarButton tbb = (ToolBarButton)selections.elementAt(row); switch(col) { case 0: return new Boolean(tbb.isVisible()); case 1: return tbb.getIcon(); case 2: return tbb.getName(); default: return null; } } public void setValueAt(Object value, int row, int col) { ToolBarButton tbb = (ToolBarButton)selections.elementAt(row); if (col == 0) tbb.setVisible(((Boolean)value).booleanValue()); fireTableRowsUpdated(row, row); } public boolean isCellEditable(int row, int col) { if (col == 0) return true; else return false; } public Class getColumnClass(int col) { if (col == 0) return Boolean.class; else return String.class; } public void addNewRow() { } } // CreateTableModel public class NameCellRenderer extends JLabel implements TableCellRenderer { public NameCellRenderer() { //setFont(panelFont); setOpaque(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); setText(value.toString()); setBorder(null); return this; } } // class NameCellRenderer public class IconCellRenderer extends JLabel implements TableCellRenderer { public IconCellRenderer() { setOpaque(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); setHorizontalAlignment(JLabel.CENTER); setIcon((ImageIcon)value); return this; } } // class IconCellRenderer }
takisd123/executequery
src/org/executequery/gui/prefs/PropertiesToolBar.java
Java
gpl-3.0
13,636
package com.compwiz1548.elementaltemples.item; public class ItemForestRelic extends ItemET { public ItemForestRelic() { super(); this.setUnlocalizedName("forestRelic"); this.setMaxStackSize(1); } }
compwiz1548/ElementalTemples
src/main/java/com/compwiz1548/elementaltemples/item/ItemForestRelic.java
Java
gpl-3.0
235
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Web; using Deveel.Data.Util; namespace Deveel.Data.Net.Security { public class OAuthParameters : ICloneable { private readonly IDictionary<string, string> parameters; private NameValueCollection additionalParameters; private const string AuthorizationHeaderParameter = "Authorization"; private const string WwwAuthenticateHeaderParameter = "WWW-Authenticate"; private const string OAuthAuthScheme = "OAuth"; private static readonly Regex OAuthCredentialsRegex = new Regex(@"^" + OAuthAuthScheme + @"\s+", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex StringEscapeSequence = new Regex(@"\\([""'\0abfnrtv]|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]+)", RegexOptions.Compiled); /// <summary> /// Create a new empty OAuthParameters. /// </summary> public OAuthParameters() { parameters = new Dictionary<string, string>(); Callback = null; ConsumerKey = null; Nonce = null; Realm = null; Signature = null; SignatureMethod = null; Timestamp = null; Token = null; TokenSecret = null; Version = null; Verifier = null; additionalParameters = new NameValueCollection(); } public string Callback { get { return parameters[OAuthParameterKeys.Callback]; } set { parameters[OAuthParameterKeys.Callback] = value; } } public string ConsumerKey { get { return parameters[OAuthParameterKeys.ConsumerKey]; } set { parameters[OAuthParameterKeys.ConsumerKey] = value; } } public string Nonce { get { return parameters[OAuthParameterKeys.Nonce]; } set { parameters[OAuthParameterKeys.Nonce] = value; } } public string Realm { get { return parameters[OAuthParameterKeys.Realm]; } set { parameters[OAuthParameterKeys.Realm] = value; } } public string Signature { get { return parameters[OAuthParameterKeys.Signature]; } set { parameters[OAuthParameterKeys.Signature] = value; } } public string SignatureMethod { get { return parameters[OAuthParameterKeys.SignatureMethod]; } set { parameters[OAuthParameterKeys.SignatureMethod] = value; } } public string Timestamp { get { return parameters[OAuthParameterKeys.Timestamp]; } set { parameters[OAuthParameterKeys.Timestamp] = value; } } public string Token { get { return parameters[OAuthParameterKeys.Token]; } set { parameters[OAuthParameterKeys.Token] = value; } } public string TokenSecret { get { return parameters[OAuthParameterKeys.TokenSecret]; } set { parameters[OAuthParameterKeys.TokenSecret] = value; } } public string Version { get { return parameters[OAuthParameterKeys.Version]; } set { parameters[OAuthParameterKeys.Version] = value; } } public string Verifier { get { return parameters[OAuthParameterKeys.Verifier]; } set { parameters[OAuthParameterKeys.Verifier] = value; } } public bool HasProblem { get { return AdditionalParameters[OAuthErrorParameterKeys.Problem] != null; } } public NameValueCollection AdditionalParameters { get { return additionalParameters; } } public string ProblemAdvice { get { return additionalParameters[OAuthErrorParameterKeys.ProblemAdvice]; } set { additionalParameters[OAuthErrorParameterKeys.ProblemAdvice] = value; } } public string ProblemType { get { return additionalParameters[OAuthErrorParameterKeys.Problem]; } set { additionalParameters[OAuthErrorParameterKeys.Problem] = value; } } public string AcceptableVersions { get { return additionalParameters[OAuthErrorParameterKeys.AcceptableVersions]; } set { additionalParameters[OAuthErrorParameterKeys.AcceptableVersions] = value; } } public string ParametersAbsent { get { return additionalParameters[OAuthErrorParameterKeys.ParametersAbsent]; } set { additionalParameters[OAuthErrorParameterKeys.ParametersAbsent] = value; } } public string ParametersRejected { get { return additionalParameters[OAuthErrorParameterKeys.ParametersRejected]; } set { additionalParameters[OAuthErrorParameterKeys.ParametersAbsent] = value; } } public string AcceptableTimestamps { get { return additionalParameters[OAuthErrorParameterKeys.AcceptableTimestamps]; } set { additionalParameters[OAuthErrorParameterKeys.AcceptableTimestamps] = value; } } public static OAuthParameters Parse(IHttpRequest request) { return Parse(request, OAuthParameterSources.ServiceProviderDefault); } public static OAuthParameters Parse(IHttpRequest request, OAuthParameterSources sources) { return DoParse(request.Headers[AuthorizationHeaderParameter], request.Headers[WwwAuthenticateHeaderParameter], request.Form, request.QueryString, sources, true); } public static OAuthParameters Parse(HttpWebResponse response) { if (response == null) return null; NameValueCollection bodyParams = new NameValueCollection(); using (MemoryStream ms = new MemoryStream()) { Stream stream = response.GetResponseStream(); byte[] buffer = new byte[32768]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } Encoding bodyEncoding = Encoding.ASCII; if (!String.IsNullOrEmpty(response.ContentEncoding)) bodyEncoding = Encoding.GetEncoding(response.ContentEncoding); string responseBody = bodyEncoding.GetString(ms.ToArray()); string[] nameValuePairs = responseBody.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nameValuePair in nameValuePairs) { string[] nameValuePairParts = nameValuePair.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (nameValuePairParts.Length == 2) bodyParams.Add(HttpUtility.UrlDecode(nameValuePairParts[0]), HttpUtility.UrlDecode(nameValuePairParts[1])); } if (bodyParams.Count == 0 && responseBody.Trim().Length > 0) bodyParams.Add(OAuthErrorParameterKeys.Problem, responseBody); } return DoParse(null, response.Headers[WwwAuthenticateHeaderParameter], bodyParams, null, OAuthParameterSources.ConsumerDefault, false); } public static OAuthParameters Parse(OAuthResource response) { if (response == null) return null; NameValueCollection bodyParams = new NameValueCollection(); using (MemoryStream ms = new MemoryStream()) { Stream stream = response.GetResponseStream(); byte[] buffer = new byte[32768]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } Encoding bodyEncoding = Encoding.ASCII; if (!String.IsNullOrEmpty(response.ContentEncoding)) bodyEncoding = Encoding.GetEncoding(response.ContentEncoding); string responseBody = bodyEncoding.GetString(ms.ToArray()); string[] nameValuePairs = responseBody.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nameValuePair in nameValuePairs) { string[] nameValuePairParts = nameValuePair.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (nameValuePairParts.Length == 2) bodyParams.Add(HttpUtility.UrlDecode(nameValuePairParts[0]), HttpUtility.UrlDecode(nameValuePairParts[1])); } // Reset the stream stream.Position = 0; } return DoParse(null, response.Headers[WwwAuthenticateHeaderParameter], bodyParams, null, OAuthParameterSources.ConsumerDefault, false); } public static OAuthParameters Parse(NameValueCollection parameterCollection) { return DoParse(null, null, parameterCollection, null, OAuthParameterSources.PostBody, true); } public static NameValueCollection GetNonOAuthParameters(params NameValueCollection[] parameterCollections) { NameValueCollection @params = new NameValueCollection(); foreach (NameValueCollection paramCollection in parameterCollections) if (paramCollection != null) foreach (string key in paramCollection.AllKeys) if (Array.IndexOf(OAuthParameterKeys.ReservedParameterNames, key) < 0) foreach (string value in paramCollection.GetValues(key)) @params.Add(key, value); return @params; } public OAuthParameters Clone() { var clone = new OAuthParameters(); foreach (KeyValuePair<string, string> item in parameters) clone.parameters[item.Key] = item.Value; clone.additionalParameters = new NameValueCollection(additionalParameters); return clone; } object ICloneable.Clone() { return Clone(); } public void Sign(Uri requestUri, string httpMethod, IConsumer consumer, IToken token, ISignProvider signingProvider) { if (token != null) Token = token.Token; OAuthParameters signingParameters = Clone(); var signingUri = new UriBuilder(requestUri); // Normalize the request uri for signing if (!string.IsNullOrEmpty(requestUri.Query)) { // TODO: Will the parameters necessarily be Rfc3698 encoded here? If not, then Rfc3968.SplitAndDecode will throw FormatException signingParameters.AdditionalParameters.Add(Rfc3986.SplitAndDecode(requestUri.Query.Substring(1))); signingUri.Query = null; } if (signingProvider == null) // There is no signing provider for this signature method throw new OAuthRequestException(null, OAuthProblemTypes.SignatureMethodRejected); // Compute the signature Signature = signingProvider.ComputeSignature( Security.Signature.Create(httpMethod, signingUri.Uri, signingParameters), consumer.Secret, (token != null && token.Secret != null) ? token.Secret : null); } public string ToHeader() { string[] excludedParameters = { OAuthParameterKeys.Realm, OAuthParameterKeys.TokenSecret }; StringBuilder refAuthHeader = new StringBuilder(OAuthAuthScheme); refAuthHeader.Append(" "); bool first = true; if (!String.IsNullOrEmpty(Realm)) { EncodeHeaderValue(refAuthHeader, OAuthParameterKeys.Realm, Realm, first ? string.Empty : ", ", true); first = false; } foreach (string key in parameters.Keys) { if (parameters[key] != null && Array.IndexOf(excludedParameters, key) < 0) { EncodeHeaderValue(refAuthHeader, key, parameters[key], first ? string.Empty : ", ", true); first = false; } } return refAuthHeader.ToString(); } public string ToQueryString() { string[] excludedParameters = { OAuthParameterKeys.Realm, OAuthParameterKeys.TokenSecret }; StringBuilder queryString = new StringBuilder(); bool first = true; foreach (string key in parameters.Keys) { if (parameters[key] != null && Array.IndexOf(excludedParameters, key) < 0) { EncodeHeaderValue(queryString, key, parameters[key], first ? String.Empty : "&", false); first = false; } } foreach (string key in additionalParameters.Keys) { string[] values = additionalParameters.GetValues(key); if (values == null || values.Length == 0) continue; foreach (string value in values) { EncodeHeaderValue(queryString, key, value, first ? string.Empty : "&", false); first = false; } } return queryString.ToString(); } public void RequireAllOf(params string[] requiredParameters) { List<string> missing = new List<string>(); foreach (string requiredParameter in requiredParameters) if (string.IsNullOrEmpty(parameters[requiredParameter])) missing.Add(requiredParameter); if (missing.Count > 0) throw new ParametersAbsentException(null, missing.ToArray()); } public void AllowOnly(params string[] allowedParameters) { List<string> invalid = new List<string>(); foreach (var parameter in parameters.Keys) if (!String.IsNullOrEmpty(parameters[parameter])) if (Array.IndexOf(allowedParameters, parameter) < 0) invalid.Add(parameter); foreach (var parameter in AdditionalParameters.AllKeys) if (!string.IsNullOrEmpty(AdditionalParameters[parameter])) if (Array.IndexOf(allowedParameters, parameter) < 0) invalid.Add(parameter); if (invalid.Count > 0) throw new ParametersRejectedException(null, invalid.ToArray()); } public void RequireVersion(params string[] allowedVersions) { if (allowedVersions == null) throw new ArgumentNullException("allowedVersions"); if (allowedVersions.Length < 1) throw new ArgumentException("allowedVersions argument is mandatory", "allowedVersions"); if (!String.IsNullOrEmpty(parameters[OAuthParameterKeys.Version])) foreach (string allowedVersion in allowedVersions) if (allowedVersion.Equals(parameters[OAuthParameterKeys.Version])) return; throw new VersionRejectedException(null, allowedVersions[0], allowedVersions[allowedVersions.Length - 1]); } public NameValueCollection OAuthRequestParams() { ////We don't send the realm or token secret in the querystring or post body. return OAuthRequestParams(OAuthParameterKeys.Realm, OAuthParameterKeys.TokenSecret); } private static int CompareKeys(KeyValuePair<string,string> right, KeyValuePair<string, string> left) { return left.Key.Equals(right.Key, StringComparison.Ordinal) ? String.Compare(left.Value, right.Value, StringComparison.Ordinal) : String.Compare(left.Key, right.Key, StringComparison.Ordinal); } public string ToNormalizedString(params string[] excludedParameters) { List<KeyValuePair<string,string>> @params = new List<KeyValuePair<string, string>>(); // Add OAuth parameters whose values are not null except excluded parameters foreach (string param in parameters.Keys) if (parameters[param] != null && Array.IndexOf(excludedParameters, param) < 0) @params.Add(new KeyValuePair<string, string>(Rfc3986.Encode(param), Rfc3986.Encode(parameters[param]))); // Add all additional parameters foreach (var param in additionalParameters.AllKeys) foreach (var value in additionalParameters.GetValues(param) ?? new string[] { }) @params.Add(new KeyValuePair<string, string>(Rfc3986.Encode(param), Rfc3986.Encode(value))); // Sort parameters into lexicographic order (by key and value) @params.Sort(CompareKeys); // Concatenate and encode string equals = "="; string ampersand = "&"; StringBuilder parms = new StringBuilder(); bool first = true; foreach (var pair in @params) { if (first) first = false; else parms.Append(ampersand); parms.Append(pair.Key).Append(equals).Append(pair.Value); } return parms.ToString(); } internal static OAuthParameters DoParse(string authHeader, string wwwAuthHeader, NameValueCollection form, NameValueCollection queryString, OAuthParameterSources sources, bool validateParameters) { if (sources == OAuthParameterSources.None) throw new ArgumentException("sources must not be OAuthParameterSources.None", "sources"); bool useAuthHeader = (sources & OAuthParameterSources.AuthorizationHeader) == OAuthParameterSources.AuthorizationHeader; bool useWwwAuthHeader = (sources & OAuthParameterSources.AuthenticateHeader) == OAuthParameterSources.AuthenticateHeader; bool usePost = (sources & OAuthParameterSources.PostBody) == OAuthParameterSources.PostBody; bool useQueryString = (sources & OAuthParameterSources.QueryString) == OAuthParameterSources.QueryString; NameValueCollection authHeaderParams = useAuthHeader ? ParseAuthHeader(authHeader) : null; NameValueCollection wwwAuthHeaderParams = useWwwAuthHeader ? ParseAuthHeader(wwwAuthHeader) : null; NameValueCollection postParams = usePost ? form : null; NameValueCollection queryStringParams = useQueryString ? queryString : null; // Do validation if required if (validateParameters) { /* * Check for any duplicated OAuth parameters */ ResultInfo<string[]> result = CheckForDuplicateReservedParameters(authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); if (!result) throw new ParametersRejectedException(null, result); /* * Check for non-reserved parameters prefixed with oauth_ */ result = CheckForInvalidParameterNames(authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); if (!result) throw new ParametersRejectedException(null, result); } OAuthParameters parameters = new OAuthParameters(); parameters.Callback = GetParam(OAuthParameterKeys.Callback, authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); parameters.ConsumerKey = GetParam(OAuthParameterKeys.ConsumerKey, authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); parameters.Nonce = GetParam(OAuthParameterKeys.Nonce, authHeaderParams, postParams, wwwAuthHeaderParams, queryStringParams); parameters.Realm = authHeaderParams != null ? authHeaderParams[OAuthParameterKeys.Realm] : null; parameters.Signature = GetParam(OAuthParameterKeys.Signature, authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); parameters.SignatureMethod = GetParam(OAuthParameterKeys.SignatureMethod, wwwAuthHeaderParams, authHeaderParams, postParams, queryStringParams); parameters.Timestamp = GetParam(OAuthParameterKeys.Timestamp, authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); parameters.Token = GetParam(OAuthParameterKeys.Token, authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); parameters.TokenSecret = GetParam(OAuthParameterKeys.TokenSecret, authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); parameters.Version = GetParam(OAuthParameterKeys.Version, authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); parameters.Verifier = GetParam(OAuthParameterKeys.Verifier, authHeaderParams, wwwAuthHeaderParams, postParams, queryStringParams); parameters.additionalParameters = GetNonOAuthParameters(wwwAuthHeaderParams, postParams, queryStringParams); return parameters; } private static void EncodeHeaderValue(StringBuilder buffer, string key, string value, string separator, bool quote) { buffer.Append(separator); buffer.Append(Rfc3986.Encode(key)); buffer.Append("="); if (quote) buffer.Append('"'); buffer.Append(Rfc3986.Encode(value)); if (quote) buffer.Append('"'); } private static string EvaluateAuthHeaderMatch(Match match) { Group group = match.Groups[1]; if (group.Length == 1) { switch (group.Value) { case "\"": return "\""; case "'": return "'"; case "\\": return "\\"; case "0": return "\0"; case "a": return "\a"; case "b": return "\b"; case "f": return "\f"; case "n": return "\n"; case "r": return "\r"; case "t": return "\t"; case "v": return "\v"; } } return String.Format(CultureInfo.InvariantCulture, "{0}", char.Parse(group.Value)); } private static NameValueCollection ParseAuthHeader(string authHeader) { if (!String.IsNullOrEmpty(authHeader)) { NameValueCollection @params = new NameValueCollection(); // Check for OAuth auth-scheme Match authSchemeMatch = OAuthCredentialsRegex.Match(authHeader); if (authSchemeMatch.Success) { // We have OAuth credentials in the Authorization header; parse the parts // Sad-to-say, but this code is much simpler than the regex for it! string[] authParameterValuePairs = authHeader.Substring(authSchemeMatch.Length).Split(','); foreach (string authParameterValuePair in authParameterValuePairs) { string[] parts = authParameterValuePair.Trim().Split('='); if (parts.Length == 2) { string parameter = parts[0]; string value = parts[1]; if (value.StartsWith("\"", StringComparison.Ordinal) && value.EndsWith("\"", StringComparison.Ordinal)) { value = value.Substring(1, value.Length - 2); try { value = StringEscapeSequence.Replace(value, EvaluateAuthHeaderMatch); } catch (FormatException) { continue; } // Add the parameter and value @params.Add(Rfc3986.Decode(parameter), Rfc3986.Decode(value)); } } } } return @params; } return null; } private static ResultInfo<string[]> CheckForDuplicateReservedParameters(params NameValueCollection[] paramCollections) { List<string> duplicated = new List<string>(); int count; foreach (string param in OAuthParameterKeys.ReservedParameterNames) { count = 0; foreach (NameValueCollection paramCollection in paramCollections) if (paramCollection != null) { string[] values = paramCollection.GetValues(param); if (values != null) count += values.Length; } if (count > 1) duplicated.Add(param); } return duplicated.Count > 0 ? new ResultInfo<string[]>(false, duplicated.ToArray()) : new ResultInfo<string[]>(true, null); } private static ResultInfo<string[]> CheckForInvalidParameterNames( params NameValueCollection[] paramCollections) { List<string> invalid = new List<string>(); foreach (NameValueCollection paramCollection in paramCollections) if (paramCollection != null) foreach (string param in paramCollection.Keys) { if (param != null && param.StartsWith(OAuthParameterKeys.OAuthParameterPrefix, StringComparison.Ordinal) && Array.IndexOf(OAuthParameterKeys.ReservedParameterNames, param) < 0) { invalid.Add(param); } } return invalid.Count > 0 ? new ResultInfo<string[]>(false, invalid.ToArray()) : new ResultInfo<string[]>(true, null); } private static string GetParam(string param, params NameValueCollection[] paramCollections) { foreach (NameValueCollection paramCollection in paramCollections) if (paramCollection != null && !string.IsNullOrEmpty(paramCollection[param])) return paramCollection[param]; return null; } private NameValueCollection OAuthRequestParams(params string[] excludedParameters) { NameValueCollection @params = new NameValueCollection(); // Add OAuth parameters whose values are not null except excluded parameters foreach (string param in parameters.Keys) if (parameters[param] != null && Array.IndexOf(excludedParameters, param) < 0) @params.Add(param, parameters[param]); return @params; } } }
deveel/cloudb-oauth
src/cloudb-oauth/Deveel.Data.Net.Security/OAuthParameters.cs
C#
gpl-3.0
22,848
/* * VerticalGlass.java * Copyright (C) 2010-2011 Jonas Eriksson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.zkt.zmask.masks; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import org.zkt.zmask.Image; import org.zkt.zmask.GeneralProperties; import org.zkt.zmask.utils.PropertyDescription; import org.zkt.zmask.utils.PropertyException; import org.zkt.zmask.utils.PropertyHandler; /** * The vertical glass mask * * @author zqad */ public class VerticalGlass implements Mask { public String getDescription() { return "Vertical Glass"; } public boolean needClone() { return false; } public boolean needWhole() { return false; } public boolean runBare() { return false; } public BufferedImage runMask(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); BufferedImage bi = new BufferedImage(width, height, image.getType()); Graphics2D g = (Graphics2D)bi.getGraphics(); g.scale(-1.0, 1.0); int bs = GeneralProperties.getInstance().getBlockSize().width; for (int i = 0; i <= width - bs; i += bs) g.drawImage(image.getSubimage(i, 0, bs, height), -1 * i - bs, 0, null); int remainder = width % bs; if (remainder != 0) g.drawImage(image.getSubimage(width - remainder, 0, remainder, height), width - remainder, 0, null); return bi; } public void runMask(Image image) { throw new UnsupportedOperationException("Not supported."); } public PropertyDescription[] getProperties() { return null; } }
zqad/zmask
src/org/zkt/zmask/masks/VerticalGlass.java
Java
gpl-3.0
2,138
# ../gungame/core/messages/hooks.py """Provides a way to hook GunGame messages.""" # ============================================================================= # >> IMPORTS # ============================================================================= # Source.Python from core import AutoUnload # GunGame from .manager import message_manager # ============================================================================= # >> CLASSES # ============================================================================= class MessageHook(AutoUnload): """Decorator used to register message hooks.""" def __init__(self, message_name): """Store the message name.""" self.message_name = message_name self.callback = None def __call__(self, callback): """Store the callback and register the hook.""" self.callback = callback message_manager.hook_message(self.message_name, self.callback) def _unload_instance(self): """Unregister the message hook.""" message_manager.unhook_message(self.message_name, self.callback) class MessagePrefixHook(AutoUnload): """Decorator used to register message prefix hooks.""" def __init__(self, message_prefix): """Store the message prefix.""" self.message_prefix = message_prefix self.callback = None def __call__(self, callback): """Store the callback and register the hook.""" self.callback = callback message_manager.hook_prefix(self.message_prefix, self.callback) def _unload_instance(self): """Unregister the message prefix hook.""" message_manager.unhook_prefix(self.message_prefix, self.callback)
GunGame-Dev-Team/GunGame-SP
addons/source-python/plugins/gungame/core/messages/hooks.py
Python
gpl-3.0
1,705
<?php namespace App\Admin\Controllers; use App\CriterioDesempateGrupoEvento; use App\Http\Controllers\Controller; use Encore\Admin\Controllers\HasResourceActions; use Encore\Admin\Form; use Encore\Admin\Grid; use Encore\Admin\Layout\Content; use Encore\Admin\Show; class CriterioDesempateGrupoEventoController extends Controller { use HasResourceActions; /** * Index interface. * * @param Content $content * @return Content */ public function index(Content $content) { return $content ->header('Index') ->description('description') ->body($this->grid()); } /** * Show interface. * * @param mixed $id * @param Content $content * @return Content */ public function show($id, Content $content) { return $content ->header('Detail') ->description('description') ->body($this->detail($id)); } /** * Edit interface. * * @param mixed $id * @param Content $content * @return Content */ public function edit($id, Content $content) { return $content ->header('Edit') ->description('description') ->body($this->form()->edit($id)); } /** * Create interface. * * @param Content $content * @return Content */ public function create(Content $content) { return $content ->header('Create') ->description('description') ->body($this->form()); } /** * Make a grid builder. * * @return Grid */ protected function grid() { $grid = new Grid(new CriterioDesempateGrupoEvento); return $grid; } /** * Make a show builder. * * @param mixed $id * @return Show */ protected function detail($id) { $show = new Show(CriterioDesempateGrupoEvento::findOrFail($id)); return $show; } /** * Make a form builder. * * @return Form */ protected function form() { $form = new Form(new CriterioDesempateGrupoEvento); return $form; } }
XadrezSuico/XadrezSuico
app/Admin/Controllers/CriterioDesempateGrupoEventoController.php
PHP
gpl-3.0
2,228
package com.neemre.bitplexus.backend.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedStoredProcedureQueries; import javax.persistence.NamedStoredProcedureQuery; import javax.persistence.ParameterMode; import javax.persistence.SequenceGenerator; import javax.persistence.StoredProcedureParameter; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.annotations.Generated; import org.hibernate.annotations.GenerationTime; import com.google.common.base.Function; import com.google.common.collect.Ordering; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; @Data @NoArgsConstructor @AllArgsConstructor @ToString(callSuper = true) @EqualsAndHashCode(callSuper = false) @Entity @Table(name = "address_type", schema = "public") @SequenceGenerator(name = "seq_address_type_id", sequenceName = "seq_address_type_address_type_id", allocationSize = 1) @NamedStoredProcedureQueries(value = { @NamedStoredProcedureQuery(name = "findIdByAddressAndChainCode", procedureName = "f_get_address_type_id", parameters = { @StoredProcedureParameter(mode = ParameterMode.IN, name = "in_address", type = String.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "in_chain_code", type = String.class)}) }) public class AddressType extends BaseEntity { public static final Ordering<AddressType> LEADING_SYMBOL_ORDERING = Ordering.natural().nullsLast() .onResultOf(new LeadingSymbolExtractor()); public static final Ordering<AddressType> NAME_ORDERING = Ordering.natural().nullsLast() .onResultOf(new NameExtractor()); public static final Ordering<AddressType> NATURAL_ORDERING = NAME_ORDERING .compound(LEADING_SYMBOL_ORDERING); private static final long serialVersionUID = 1L; @NotNull @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_address_type_id") @Column(name = "address_type_id", insertable = false, updatable = false) private Short addressTypeId; @NotNull @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "chain_id", updatable = false) private Chain chain; @NotNull @Size(max = 30) @Column(name = "code") private String code; @NotNull @Size(max = 60) @Column(name = "name") private String name; @NotNull @Size(min = 1, max = 1) @Pattern(regexp = "^[1-9a-km-zA-HJ-NP-Z]*$") @Column(name = "leading_symbol", updatable = false) private String leadingSymbol; @Past @Generated(GenerationTime.INSERT) @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_at", insertable = false, updatable = false) private Date createdAt; @NotNull @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "created_by", updatable = false) private Employee createdBy; @Past @Generated(GenerationTime.ALWAYS) @Temporal(TemporalType.TIMESTAMP) @Column(name = "updated_at", insertable = false, updatable = false) private Date updatedAt; @ManyToOne(fetch = FetchType.LAZY, optional = true) @JoinColumn(name = "updated_by", insertable = false) private Employee updatedBy; public void setChain(Chain chain) { if (this.chain != chain) { if (this.chain != null) { this.chain.removeAddressType(this); } this.chain = chain; if (chain != null) { chain.addAddressType(this); } } } private static class LeadingSymbolExtractor implements Function<AddressType, String> { @Override public String apply(AddressType addressType) { return addressType.getLeadingSymbol(); } } private static class NameExtractor implements Function<AddressType, String> { @Override public String apply(AddressType addressType) { return addressType.getName(); } } }
priiduneemre/bitplexus
src/main/java/com/neemre/bitplexus/backend/model/AddressType.java
Java
gpl-3.0
4,237
# coding=utf-8 """ NodeChains are sequential orders of :mod:`~pySPACE.missions.nodes` .. image:: ../../graphics/node_chain.png :width: 500 There are two main use cases: * the application for :mod:`~pySPACE.run.launch_live` and the :mod:`~pySPACE.environments.live` using the default :class:`NodeChain` and * the benchmarking with :mod:`~pySPACE.run.launch` using the :class:`BenchmarkNodeChain` with the :mod:`~pySPACE.missions.operations.node_chain` operation. .. seealso:: - :mod:`~pySPACE.missions.nodes` - :ref:`node_list` - :mod:`~pySPACE.missions.operations.node_chain` operation .. image:: ../../graphics/launch_live.png :width: 500 .. todo:: Documentation This module extends/reimplements the original MDP flow class and has some additional methods like reset(), save() etc. Furthermore it supports the construction of NodeChains and also running them inside nodes in parallel. MDP is distributed under the following BSD license:: This file is part of Modular toolkit for Data Processing (MDP). All the code in this package is distributed under the following conditions: Copyright (c) 2003-2012, MDP Developers <mdp-toolkit-devel@lists.sourceforge.net> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Modular toolkit for Data Processing (MDP) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys import os if __name__ == '__main__': # add root of the code to system path file_path = os.path.dirname(os.path.abspath(__file__)) pyspace_path = file_path[:file_path.rfind('pySPACE')-1] if not pyspace_path in sys.path: sys.path.append(pyspace_path) import cPickle import gc import logging import multiprocessing import shutil import socket import time import uuid import yaml import pySPACE from pySPACE.tools.filesystem import create_directory from pySPACE.tools.socket_utils import talk, inform from pySPACE.tools.conversion import python2yaml, replace_parameters_and_convert, replace_parameters import copy import warnings import traceback import numpy class CrashRecoveryException(Exception): """Class to handle crash recovery """ def __init__(self, *args): """Allow crash recovery. Arguments: (error_string, crashing_obj, parent_exception) The crashing object is kept in self.crashing_obj The triggering parent exception is kept in ``self.parent_exception``. """ errstr = args[0] self.crashing_obj = args[1] self.parent_exception = args[2] # ?? python 2.5: super(CrashRecoveryException, self).__init__(errstr) super(CrashRecoveryException,self).__init__(self, errstr) def dump(self, filename = None): """ Save a pickle dump of the crashing object on filename. If filename is None, the crash dump is saved on a file created by the tempfile module. Return the filename. """ import cPickle import tempfile if filename is None: (fd, filename)=tempfile.mkstemp(suffix=".pic", prefix="NodeChainCrash_") fl = os.fdopen(fd, 'w+b', -1) else: fl = open(filename, 'w+b', -1) cPickle.dump(self.crashing_obj, fl) fl.close() return filename class NodeChainException(Exception): """Base class for exceptions in node chains.""" pass class NodeChainExceptionCR(CrashRecoveryException, NodeChainException): """Class to handle crash recovery """ def __init__(self, *args): """Allow crash recovery. Arguments: (error_string, flow_instance, parent_exception) The triggering parent exception is kept in self.parent_exception. If ``flow_instance._crash_recovery`` is set, save a crash dump of flow_instance on the file self.filename """ CrashRecoveryException.__init__(self, *args) rec = self.crashing_obj._crash_recovery errstr = args[0] if rec: if isinstance(rec, str): name = rec else: name = None name = CrashRecoveryException.dump(self, name) dumpinfo = '\nA crash dump is available on: "%s"' % name self.filename = name errstr = errstr+dumpinfo Exception.__init__(self, errstr) class NodeChain(object): """ Reimplement/overwrite mdp.Flow methods e.g., for supervised learning """ def __init__(self, node_sequence, crash_recovery=False, verbose=False): """ Creates the NodeChain based on the node_sequence .. note:: The NodeChain cannot be executed before not all trainable nodes have been trained, i.e. self.trained() == True. """ self._check_nodes_consistency(node_sequence) self.flow = node_sequence self.verbose = verbose self.set_crash_recovery(crash_recovery) # Register the direct predecessor of a node as its input # (i.e. we assume linear flows) for i in range(len(node_sequence) - 1): node_sequence[i+1].register_input_node(node_sequence[i]) self.use_test_data = False # set a default run number self[-1].set_run_number(0) # give this flow a unique identifier self.id = str(uuid.uuid4()) self.handler = None self.store_intermediate_results = True def train(self, data_iterators=None): """ Train NodeChain with data from iterator or source node The method can proceed in two different ways: * If no data is provided, it is checked that the first node of the flow is a source node. If that is the case, the data provided by this node is passed forward through the flow. During this forward propagation, the flow is trained. The request of the data is done in the last node. * If a list of data iterators is provided, then it is checked that no source and split nodes are contained in the NodeChain. these nodes only include already a data handling and should not be used, when training is done in different way. Furthermore, split nodes are relevant for benchmarking. One iterator for each node has to be given. If only one is given, or no list, it is mapped to a list with the same iterator for each node. .. note:: The iterator approach is normally not used in pySPACE, because pySPACE supplies the data with special source nodes and is doing the training automatically without explicit calls on data samples. The approach came with MDP. .. todo:: The iterator approach needs some use cases and testings, especially, because it is not used in the normal setting. """ if data_iterators is not None: # Check if no source and split nodes are contained in the node chain assert(not self[0].is_source_node()), \ "Node chains with source nodes cannot be trained "\ "with external data_iterators!" for node in self: assert(not node.is_split_node()), \ "Node chains with split nodes cannot be trained "\ "with external data_iterators!" # prepare iterables if not type(data_iterators) == list: data_iterators = [data_iterators] * len(self.flow) elif not len(data_iterators)==len(self.flow): data_iterators = [data_iterators] * len(self.flow) # Delegate to iterative training self.iter_train(data_iterators) else: # Use the pySPACE train semantic and not MDP type # Check if the first node of the node chain is a source node assert(self[0].is_source_node()), \ "Training of a node chain without source node requires a "\ "data_iterator argument!" # Training is accomplished by requesting the iterator # of the last node of the chain. This node will recursively call # the train method of all its predecessor nodes. # As soon as the first element is yielded the node has been trained. for _ in self[-1].request_data_for_training( use_test_data=self.use_test_data): return def iter_train(self, data_iterables): """ Train all trainable nodes in the NodeChain with data from iterator *data_iterables* is a list of iterables, one for each node in the chain. The iterators returned by the iterables must return data arrays that are then used for the node training (so the data arrays are the data for the nodes). Note that the data arrays are processed by the nodes which are in front of the node that gets trained, so the data dimension must match the input dimension of the first node. If a node has only a single training phase then instead of an iterable you can alternatively provide an iterator (including generator-type iterators). For nodes with multiple training phases this is not possible, since the iterator cannot be restarted after the first iteration. For more information on iterators and iterables see http://docs.python.org/library/stdtypes.html#iterator-types . In the special case that *data_iterables* is one single array, it is used as the data array *x* for all nodes and training phases. Instead of a data array *x* the iterators can also return a list or tuple, where the first entry is *x* and the following are args for the training of the node (e.g., for supervised training). """ data_iterables = self._train_check_iterables(data_iterables) # train each Node successively for i in range(len(self.flow)): if self.verbose: print "Training node #%d (%s)" % (i, str(self.flow[i])) self._train_node(data_iterables[i], i) if self.verbose: print "Training finished" self._close_last_node() def trained(self): """ Returns whether the complete training is finished, i.e. if all nodes have been trained. """ return self[-1].get_remaining_train_phase() == 0 def execute(self, data_iterators=None): """ Process the data through all nodes """ if data_iterators is not None: # Delegate to super class return self.iter_execute(data_iterators) else: # Use the evaluate semantic # Check if the first node of the flow is a source node assert (self[0].is_source_node()), \ "Evaluation of a node chain without source node requires a " \ "data_iterator argument!" # This is accomplished by calling the request_data_for_testing # method of the last node of the chain. This node will recursively # call the request_data_for_testing method of all its predecessor # nodes return self[-1].process() def iter_execute(self, iterable, nodenr = None): """ Process the data through all nodes in the chain till *nodenr* 'iterable' is an iterable or iterator (note that a list is also an iterable), which returns data arrays that are used as input. Alternatively, one can specify one data array as input. If 'nodenr' is specified, the flow is executed only up to node nr. 'nodenr'. This is equivalent to 'flow[:nodenr+1](iterable)'. .. note:: In contrary to MDP, results are not concatenated to one big object. Each data object remains separate. """ if isinstance(iterable, numpy.ndarray): return self._execute_seq(iterable, nodenr) res = [] empty_iterator = True for x in iterable: empty_iterator = False res.append(self._execute_seq(x, nodenr)) if empty_iterator: errstr = ("The execute data iterator is empty.") raise NodeChainException(errstr) return res def _inc_train(self, data, class_label=None): """ Iterate through the nodes to train them """ for node in self: if node.is_retrainable() and not node.buffering and hasattr(node, "_inc_train"): if not node.retraining_phase: node.retraining_phase=True node.start_retraining() node._inc_train(data,class_label) if not (hasattr(self, "buffering") and self.buffering): data = node.execute(data) else: # workaround to inherit meta data self.buffering = False data = node.execute(data) self.buffering = True def save(self, filename, protocol = -1): """ Save a pickled representation to *filename* If *filename* is None, return a string. .. note:: the pickled NodeChain is not guaranteed to be upward or backward compatible. .. note:: Having C-Code in the node might cause problems with saving. Therefore, the code has special handling for the LibSVMClassifierNode. .. todo:: Intrinsic node methods for storing should be used. .. seealso:: :func:`store_node_chain` """ if self[-1].__class__.__name__ in ["LibSVMClassifierNode"] \ and self[-1].multinomial: indx = filename.find(".pickle") if indx != -1: self[-1].save_model(filename[0:indx]+'.model') else: self[-1].save_model(filename+'.model') import cPickle odict = self.__dict__.copy() # copy the dict since we change it # Remove other non-pickable stuff remove_keys=[] k = 0 for key, value in odict.iteritems(): if key == "input_node" or key == "flow": continue try: cPickle.dumps(value) except (ValueError, TypeError, cPickle.PicklingError): remove_keys.append(key) for key in remove_keys: odict.pop(key) self.__dict__ = odict if filename is None: return cPickle.dumps(self, protocol) else: # if protocol != 0 open the file in binary mode if protocol != 0: mode = 'wb' else: mode = 'w' flh = open(filename , mode) cPickle.dump(self, flh, protocol) flh.close() def get_output_type(self, input_type, as_string=True): """ Returns the output type of the entire node chain Recursively iterate over nodes in flow """ output = input_type for i in range(len(self.flow)): if i == 0: output = self.flow[i].get_output_type( input_type, as_string=True) else: output = self.flow[i].get_output_type(output, as_string=True) if as_string: return output else: return self.string_to_class(output) @staticmethod def string_to_class(string_encoding): """ given a string variable, outputs a class instance e.g. obtaining a TimeSeries """ from pySPACE.resources.data_types.time_series import TimeSeries from pySPACE.resources.data_types.feature_vector import FeatureVector from pySPACE.resources.data_types.prediction_vector import PredictionVector if "TimeSeries" in string_encoding: return TimeSeries elif "PredictionVector" in string_encoding: return PredictionVector elif "FeatureVector" in string_encoding: return FeatureVector else: raise NotImplementedError ################# # MDP Code copy # def _propagate_exception(self, exception, nodenr): # capture exception. the traceback of the error is printed and a # new exception, containing the identity of the node in the NodeChain # is raised. Allow crash recovery. (etype, val, tb) = sys.exc_info() prev = ''.join(traceback.format_exception(exception.__class__, exception,tb)) act = "\n! Exception in node #%d (%s):\n" % (nodenr, str(self.flow[nodenr])) errstr = ''.join(('\n', 40*'-', act, 'Node Traceback:\n', prev, 40*'-')) raise NodeChainExceptionCR(errstr, self, exception) def _train_node(self, data_iterable, nodenr): """ Train a single node in the flow. nodenr -- index of the node in the flow """ node = self.flow[nodenr] if (data_iterable is not None) and (not node.is_trainable()): # attempted to train a node although it is not trainable. # raise a warning and continue with the next node. # wrnstr = "\n! Node %d is not trainable" % nodenr + \ # "\nYou probably need a 'None' iterable for"+\ # " this node. Continuing anyway." #warnings.warn(wrnstr, UserWarning) return elif (data_iterable is None) and node.is_training(): # None instead of iterable is passed to a training node err_str = ("\n! Node %d is training" " but instead of iterable received 'None'." % nodenr) raise NodeChainException(err_str) elif (data_iterable is None) and (not node.is_trainable()): # skip training if node is not trainable return try: train_arg_keys = self._get_required_train_args(node) train_args_needed = bool(len(train_arg_keys)) ## We leave the last training phase open for the ## CheckpointFlow class. ## Checkpoint functions must close it explicitly if needed! ## Note that the last training_phase is closed ## automatically when the node is executed. while True: empty_iterator = True for x in data_iterable: empty_iterator = False # the arguments following the first are passed only to the # currently trained node, allowing the implementation of # supervised nodes if (type(x) is tuple) or (type(x) is list): arg = x[1:] x = x[0] else: arg = () # check if the required number of arguments was given if train_args_needed: if len(train_arg_keys) != len(arg): err = ("Wrong number of arguments provided by " + "the iterable for node #%d " % nodenr + "(%d needed, %d given).\n" % (len(train_arg_keys), len(arg)) + "List of required argument keys: " + str(train_arg_keys)) raise NodeChainException(err) # filter x through the previous nodes if nodenr > 0: x = self._execute_seq(x, nodenr-1) # train current node node.train(x, *arg) if empty_iterator: if node.get_current_train_phase() == 1: err_str = ("The training data iteration for node " "no. %d could not be repeated for the " "second training phase, you probably " "provided an iterator instead of an " "iterable." % (nodenr+1)) raise NodeChainException(err_str) else: err_str = ("The training data iterator for node " "no. %d is empty." % (nodenr+1)) raise NodeChainException(err_str) self._stop_training_hook() # close the previous training phase node.stop_training() if node.get_remaining_train_phase() > 0: continue else: break except self.flow[-1].TrainingFinishedException, e: # attempted to train a node although its training phase is already # finished. raise a warning and continue with the next node. wrnstr = ("\n! Node %d training phase already finished" " Continuing anyway." % nodenr) warnings.warn(wrnstr, UserWarning) except NodeChainExceptionCR, e: # this exception was already propagated, # probably during the execution of a node upstream in the flow (exc_type, val) = sys.exc_info()[:2] prev = ''.join(traceback.format_exception_only(e.__class__, e)) prev = prev[prev.find('\n')+1:] act = "\nWhile training node #%d (%s):\n" % (nodenr, str(self.flow[nodenr])) err_str = ''.join(('\n', 40*'=', act, prev, 40*'=')) raise NodeChainException(err_str) except Exception, e: # capture any other exception occurred during training. self._propagate_exception(e, nodenr) def _stop_training_hook(self): """Hook method that is called before stop_training is called.""" pass @staticmethod def _get_required_train_args(node): """Return arguments in addition to self and x for node.train. Arguments that have a default value are ignored. """ import inspect train_arg_spec = inspect.getargspec(node.train) train_arg_keys = train_arg_spec[0][2:] # ignore self, x if train_arg_spec[3]: # subtract arguments with a default value train_arg_keys = train_arg_keys[:-len(train_arg_spec[3])] return train_arg_keys def _train_check_iterables(self, data_iterables): """Return the data iterables after some checks and sanitizing. Note that this method does not distinguish between iterables and iterators, so this must be taken care of later. """ # verifies that the number of iterables matches that of # the signal nodes and multiplies them if needed. flow = self.flow # # if a single array is given wrap it in a list of lists, # # note that a list of 2d arrays is not valid # if isinstance(data_iterables, numpy.ndarray): # data_iterables = [[data_iterables]] * len(flow) if not isinstance(data_iterables, list): err_str = ("'data_iterables' must be either a list of " "iterables or an array, but got %s" % str(type(data_iterables))) raise NodeChainException(err_str) # check that all elements are iterable for i, iterable in enumerate(data_iterables): if (iterable is not None) and (not hasattr(iterable, '__iter__')): err = ("Element number %d in the data_iterables" " list is not an iterable." % i) raise NodeChainException(err) # check that the number of data_iterables is correct if len(data_iterables) != len(flow): err_str = ("%d data iterables specified," " %d needed" % (len(data_iterables), len(flow))) raise NodeChainException(err_str) return data_iterables def _close_last_node(self): if self.verbose: print "Close the training phase of the last node" try: self.flow[-1].stop_training() except self.flow[-1].TrainingFinishedException: pass except Exception, e: self._propagate_exception(e, len(self.flow)-1) def set_crash_recovery(self, state = True): """Set crash recovery capabilities. When a node raises an Exception during training, execution, or inverse execution that the flow is unable to handle, a NodeChainExceptionCR is raised. If crash recovery is set, a crash dump of the flow instance is saved for later inspection. The original exception can be found as the 'parent_exception' attribute of the NodeChainExceptionCR instance. - If 'state' = False, disable crash recovery. - If 'state' is a string, the crash dump is saved on a file with that name. - If 'state' = True, the crash dump is saved on a file created by the tempfile module. """ self._crash_recovery = state def _execute_seq(self, x, nodenr = None): """ Executes input data 'x' through the nodes 0..'node_nr' included If no *nodenr* is specified, the complete node chain is used for processing. """ flow = self.flow if nodenr is None: nodenr = len(flow)-1 for node_index in range(nodenr+1): try: x = flow[node_index].execute(x) except Exception, e: self._propagate_exception(e, node_index) return x def copy(self, protocol=None): """Return a deep copy of the flow. The protocol parameter should not be used. """ import copy if protocol is not None: warnings.warn("protocol parameter to copy() is ignored", DeprecationWarning, stacklevel=2) return copy.deepcopy(self) def __call__(self, iterable, nodenr = None): """Calling an instance is equivalent to call its 'execute' method.""" return self.iter_execute(iterable, nodenr=nodenr) ###### string representation def __str__(self): nodes = ', '.join([str(x) for x in self.flow]) return '['+nodes+']' def __repr__(self): # this should look like a valid Python expression that # could be used to recreate an object with the same value # eval(repr(object)) == object name = type(self).__name__ pad = len(name)+2 sep = ',\n'+' '*pad nodes = sep.join([repr(x) for x in self.flow]) return '%s([%s])' % (name, nodes) ###### private container methods def __len__(self): return len(self.flow) def _check_dimension_consistency(self, out, inp): """Raise ValueError when both dimensions are set and different.""" if ((out and inp) is not None) and out != inp: errstr = "dimensions mismatch: %s != %s" % (str(out), str(inp)) raise ValueError(errstr) def _check_nodes_consistency(self, flow = None): """Check the dimension consistency of a list of nodes.""" if flow is None: flow = self.flow len_flow = len(flow) for i in range(1, len_flow): out = flow[i-1].output_dim inp = flow[i].input_dim self._check_dimension_consistency(out, inp) def _check_value_type_isnode(self, value): if not isinstance(value, pySPACE.missions.nodes.base.BaseNode): raise TypeError("flow item must be Node instance") def __getitem__(self, key): if isinstance(key, slice): flow_slice = self.flow[key] self._check_nodes_consistency(flow_slice) return self.__class__(flow_slice) else: return self.flow[key] def __setitem__(self, key, value): if isinstance(key, slice): [self._check_value_type_isnode(item) for item in value] else: self._check_value_type_isnode(value) # make a copy of list flow_copy = list(self.flow) flow_copy[key] = value # check dimension consistency self._check_nodes_consistency(flow_copy) # if no exception was raised, accept the new sequence self.flow = flow_copy def __delitem__(self, key): # make a copy of list flow_copy = list(self.flow) del flow_copy[key] # check dimension consistency self._check_nodes_consistency(flow_copy) # if no exception was raised, accept the new sequence self.flow = flow_copy def __contains__(self, item): return self.flow.__contains__(item) def __iter__(self): return self.flow.__iter__() def __add__(self, other): # append other to self if isinstance(other, NodeChain): flow_copy = list(self.flow).__add__(other.flow) # check dimension consistency self._check_nodes_consistency(flow_copy) # if no exception was raised, accept the new sequence return self.__class__(flow_copy) elif isinstance(other, pySPACE.missions.nodes.base.BaseNode): flow_copy = list(self.flow) flow_copy.append(other) # check dimension consistency self._check_nodes_consistency(flow_copy) # if no exception was raised, accept the new sequence return self.__class__(flow_copy) else: err_str = ('can only concatenate flow or node' ' (not \'%s\') to flow' % (type(other).__name__)) raise TypeError(err_str) def __iadd__(self, other): # append other to self if isinstance(other, NodeChain): self.flow += other.flow elif isinstance(other, pySPACE.missions.nodes.base.BaseNode): self.flow.append(other) else: err_str = ('can only concatenate flow or node' ' (not \'%s\') to flow' % (type(other).__name__)) raise TypeError(err_str) self._check_nodes_consistency(self.flow) return self ###### public container methods def append(self, x): """flow.append(node) -- append node to flow end""" self[len(self):len(self)] = [x] def extend(self, x): """flow.extend(iterable) -- extend flow by appending elements from the iterable""" if not isinstance(x, NodeChain): err_str = ('can only concatenate flow' ' (not \'%s\') to flow' % (type(x).__name__)) raise TypeError(err_str) self[len(self):len(self)] = x def insert(self, i, x): """flow.insert(index, node) -- insert node before index""" self[i:i] = [x] def pop(self, i = -1): """flow.pop([index]) -> node -- remove and return node at index (default last)""" x = self[i] del self[i] return x def reset(self): """ Reset the flow and obey permanent_attributes where available Method was moved to the end of class code, due to program environment problems which needed the __getitem__ method beforehand. """ for i in range(len(self)): self[i].reset() class BenchmarkNodeChain(NodeChain): """ This subclass overwrites the train method in order to provide a more convenient way of doing supervised learning. Furthermore, it contains a benchmark method that can be used for benchmarking. This includes logging, setting of run numbers, delivering the result collection, handling of source and sink nodes, ... :Author: Jan Hendrik Metzen (jhm@informatik.uni-bremen.de) :Created: 2008/08/18 """ def __init__(self, node_sequence): """ Creates the BenchmarkNodeChain based on the node_sequence """ super(BenchmarkNodeChain, self).__init__(node_sequence) # Each BenchmarkNodeChain must start with an source node # and end with a sink node assert(self[0].is_source_node()), \ "A benchmark flow must start with a source node" assert(self[-1].is_sink_node()), \ "A benchmark flow must end with a sink node" def use_next_split(self): """ Use the next split of the data into training and test data This method is useful for pySPACE-benchmarking """ # This is handled by calling use_next_split() of the last node of # the flow which will recursively call predecessor nodes in the flow # until a node is found that handles the splitting return self[-1].use_next_split() def benchmark(self, input_collection, run=0, persistency_directory=None, store_node_chain=False): """ Perform the benchmarking of this data flow with the given collection Benchmarking is accomplished by iterating through all splits of the data into training and test data. **Parameters**: :input_collection: A sequence of data/label-tuples that serves as a generator or a BaseDataset which contains the data to be processed. :run: The current run which defines all random seeds within the flow. :persistency_directory: Optional information of the nodes as well as the trained node chain (if *store_node_chain* is not False) are stored to the given *persistency_directory*. :store_node_chain: If True the trained flow is stored to *persistency_directory*. If *store_node_chain* is a tuple of length 2---lets say (i1,i2)-- only the subflow starting at the i1-th node and ending at the (i2-1)-th node is stored. This may be useful when the stored flow should be used in an ensemble. """ # Inform the first node of this flow about the input collection if hasattr(input_collection,'__iter__'): # assume a generator is given self[0].set_generator(input_collection) else: # assume BaseDataset self[0].set_input_dataset(input_collection) # Inform all nodes recursively about the number of the current run self[-1].set_run_number(int(run)) # set temp file folder if persistency_directory != None: self[-1].set_temp_dir(persistency_directory+os.sep+"temp_dir") split_counter = 0 # For every split of the dataset while True: # As long as more splits are available # Compute the results for the current split # by calling the method on its last node self[-1].process_current_split() if persistency_directory != None: if store_node_chain: self.store_node_chain(persistency_directory + os.sep + \ "node_chain_sp%s.pickle" % split_counter, store_node_chain) # Store nodes that should be persistent self.store_persistent_nodes(persistency_directory) # If no more splits are available if not self.use_next_split(): break split_counter += 1 # print "Input benchmark" # print gc.get_referrers(self[0].collection) # During the flow numerous pointers are put to the flow but they are # not deleted. So memory is not given free, which can be seen by the # upper comment. Therefore we now free the input collection and only # then the gc collector can free the memory. Otherwise under not yet # found reasons, the pointers to the input collection will remain even # between processes. if hasattr(input_collection,'__iter__'): self[0].set_generator(None) else: self[0].set_input_dataset(None) gc.collect() # Return the result collection of this flow return self[-1].get_result_dataset() def __call__(self, iterable=None, train_instances=None, runs=[]): """ Call *execute* or *benchmark* and return (id, PerformanceResultSummary) If *iterable* is given, calling an instance is equivalent to call its 'execute' method. If *train_instances* and *runs* are given, 'benchmark' is called for every run number specified and results are merged. This is useful for e.g. parallel execution of subflows with the multiprocessing module, since instance methods can not be serialized in Python but whole objects. """ if iterable != None: return self.execute(iterable) elif train_instances != None and runs != []: # parallelization case # we have to reinitialize logging cause otherwise deadlocks occur # when parallelization is done via multiprocessing.Pool self.prepare_logging() for ind, run in enumerate(runs): result = self.benchmark(train_instances, run=run) if ind == 0: result_collection = result else: result_collection.data.update(result.data) # reset node chain for new training if another call of # :func:`benchmark` is expected. if not ind == len(runs) - 1: self.reset() self.clean_logging() return (self.id, result_collection) else: import warnings warnings.warn("__call__ methods needs at least one parameter (data)") return None def store_node_chain(self, result_dir, store_node_chain): """ Pickle this flow into *result_dir* for later usage""" if isinstance(store_node_chain,basestring): store_node_chain = eval(store_node_chain) if isinstance(store_node_chain,tuple): assert(len(store_node_chain) == 2) # Keep only subflow starting at the i1-th node and ending at the # (i2-1) node. flow = NodeChain(self.flow[store_node_chain[0]:store_node_chain[1]]) elif isinstance(store_node_chain,list): # Keep only nodes with indices contained in the list # nodes have to be copied, otherwise input_node-refs of current flow # are overwritten from copy import copy store_node_list = [copy(node) for ind, node in enumerate(self.flow) \ if ind in store_node_chain] flow = NodeChain(store_node_list) else: # Per default, get rid of source and sink nodes flow = NodeChain(self.flow[1:-1]) input_node = flow[0].input_node flow[0].input_node = None flow.save(result_dir) def prepare_logging(self): """ Set up logging This method is only needed if one forks subflows, i.e. to execute them via multiprocessing.Pool """ # Prepare remote logging root_logger = logging.getLogger("%s-%s" % (socket.gethostname(), os.getpid())) root_logger.setLevel(logging.DEBUG) root_logger.propagate = False if len(root_logger.handlers)==0: self.handler = logging.handlers.SocketHandler(socket.gethostname(), logging.handlers.DEFAULT_TCP_LOGGING_PORT) root_logger.addHandler(self.handler) def clean_logging(self): """ Remove logging handlers if existing Call this method only if you have called *prepare_logging* before. """ # Remove potential logging handlers if self.handler is not None: self.handler.close() root_logger = logging.getLogger("%s-%s" % (socket.gethostname(), os.getpid())) root_logger.removeHandler(self.handler) def store_persistent_nodes(self, result_dir): """ Store all nodes that should be persistent """ # For all node for index, node in enumerate(self): # Store them in the result dir if they enabled storing node.store_state(result_dir, index) class NodeChainFactory(object): """ Provide static methods to create and instantiate data flows :Author: Jan Hendrik Metzen (jhm@informatik.uni-bremen.de) :Created: 2009/01/26 """ @staticmethod def flow_from_yaml(Flow_Class, flow_spec): """ Creates a Flow object Reads from the given *flow_spec*, which should be a valid YAML specification of a NodeChain object, and returns this dataflow object. **Parameters** :Flow_Class: The class name of node chain to create. Valid are 'NodeChain' and 'BenchmarkNodeChain'. :flow_spec: A valid YAML specification stream; this could be a file object, a string representation of the YAML file or the Python representation of the YAML file (list of dicts) """ from pySPACE.missions.nodes.base_node import BaseNode # Reads and parses the YAML file if necessary if type(flow_spec) != list: dataflow_spec = yaml.load(flow_spec) else: dataflow_spec = flow_spec node_sequence = [] # For all nodes of the flow for node_spec in dataflow_spec: # Use factory method to create node node_obj = BaseNode.node_from_yaml(node_spec) # Append this node to the sequence of node node_sequence.append(node_obj) # Check if the nodes have to cache their outputs for index, node in enumerate(node_sequence): # If a node is trainable, it uses the outputs of its input node # at least twice, so we have to cache. if node.is_trainable(): node_sequence[index - 1].set_permanent_attributes(caching = True) # Split node might also request the data from their input nodes # (once for each split), depending on their implementation. We # assume the worst case and activate caching if node.is_split_node(): node_sequence[index - 1].set_permanent_attributes(caching = True) # Create the flow based on the node sequence and the given flow class # and return it return Flow_Class(node_sequence) @staticmethod def instantiate(template, parametrization): """ Instantiate a template recursively for the given parameterization Instantiate means to replace the parameter in the template by the chosen value. **Parameters** :template: A dictionary with key-value pairs, where values might contain parameter keys which have to be replaced. A typical example of a template would be a Python representation of a node read from YAML. :parametrization: A dictionary with parameter names as keys and exact one value for this parameter as value. """ instance = {} for key, value in template.iteritems(): if value in parametrization.keys(): # Replacement instance[key] = parametrization[value] elif isinstance(value, dict): # Recursive call instance[key] = NodeChainFactory.instantiate(value, parametrization) elif isinstance(value, basestring): # String replacement for param_key, param_value in parametrization.iteritems(): try: value = value.replace(param_key, repr(param_value)) except: value = value.replace(param_key, python2yaml(param_value)) instance[key] = value elif hasattr(value, "__iter__"): # Iterate over all items in sequence instance[key] = [] for iter_item in value: if iter_item in parametrization.keys(): # Replacement instance[key].append(parametrization[iter_item]) elif isinstance(iter_item, dict): instance[key].append(NodeChainFactory.instantiate( iter_item, parametrization)) elif isinstance(value, basestring): # String replacement for param_key, param_value in parametrization.iteritems(): try: iter_item = iter_item.replace(param_key, repr(param_value)) except: iter_item = iter_item.replace( param_key, python2yaml(param_value)) instance[key] = value else: instance[key].append(iter_item) else: # Not parameterized instance[key] = value return instance @staticmethod def replace_parameters_in_node_chain(node_chain_template, parametrization): node_chain_template = copy.copy(node_chain_template) if parametrization == {}: return node_chain_template elif type(node_chain_template) == list: return [NodeChainFactory.instantiate( template=node,parametrization=parametrization) for node in node_chain_template] elif isinstance(node_chain_template, basestring): node_chain_template = \ replace_parameters(node_chain_template, parametrization) return node_chain_template class SubflowHandler(object): """ Interface for nodes to generate and execute subflows (subnode-chains) A subflow means a node chain used inside a node for processing data. This class provides functions that can be used by nodes to generate and execute subflows. It serves thereby as a communication daemon to the backend (if it is used). Most important when inheriting from this class is that the subclass MUST be a node. The reason is that this class uses node functionality, e.g. logging, the *temp_dir*-variable and so on. **Parameters** :processing_modality: One of the valid strings: 'backend', 'serial', 'local'. :backend: The current backends modality is used. This is implemented at the moment only for 'LoadlevelerBackend' and 'LocalBackend'. :serial: All subflows are executed sequentially, i.e. one after the other. :local: Subflows are executed in a Pool using *pool_size* cpus. This may be also needed when no backend is used. (*optional, default: 'serial'*) :pool_size: If a parallelization is based on using several processes on a local system in parallel, e.g. option 'backend' and :class:`pySPACEMulticoreBackend` or option 'local', the number of worker processes for subflow evaluation has to be specified. .. note:: When using the LocalBackend, there is also the possibility to specify the pool size of parallel executed processes, e.g. data sets. Your total number of cpu's should be pool size (pySPACE) + pool size (subflows). (*optional, default: 2*) :batch_size: If parallelization of subflow execution is done together with the :class:`~pySPACE.environments.backends.ll_backend.LoadLevelerBackend`, *batch_size* determines how many subflows are executed in one serial LoadLeveler job. This option is useful if execution of a single subflow is really short (range of seconds) since there is significant overhead in creating new jobs. (*optional, default: 1*) :Author: Anett Seeland (anett.seeland@dfki.de) :Created: 2012/09/04 :LastChange: 2012/11/06 batch_size option added """ def __init__(self, processing_modality='serial', pool_size=2, batch_size=1, **kwargs): self.modality = processing_modality self.pool_size = int(pool_size) self.batch_size = int(batch_size) # a flag to send pool_size / batch_size only once to the backend self.already_send = False self.backend_com = None self.backend_name = None # to indicate the end of a message received over a socket self.end_token = '!END!' if processing_modality not in ["serial", "local", "backend"]: import warnings warnings.warn("Processing modality not found! Serial mode is used!") self.modality = 'serial' @staticmethod def generate_subflow(flow_template, parametrization=None, flow_class=None): """ Return a *flow_class* object of the given *flow_template* This methods wraps two function calls (NodeChainFactory.instantiate and NodeChainFactory.flow_from_yaml. **Parameters** :flow_template: List of dicts - a valid representation of a node chain. Alternatively, a YAML-String representation could be used, which simplifies parameter replacement. :parametrization: A dictionary with parameter names as keys and exact one value for this parameter as value. Passed to NodeChainFactory.instantiate (*optional, default: None*) :flow_class: The flow class name of which an object should be returned (*optional, default: BenchmarkNodeChain*) """ if flow_class is None: flow_class = BenchmarkNodeChain flow_spec = NodeChainFactory.replace_parameters_in_node_chain( flow_template,parametrization) # create a new Benchmark flow flow = NodeChainFactory.flow_from_yaml(flow_class, flow_spec) return flow def execute_subflows(self, train_instances, subflows, run_numbers=None): """ Execute subflows and return result collection. **Parameters** :training_instances: List of training instances which should be used to execute *subflows*. :subflows: List of BenchmarkNodeChain objects. ..note:: Note that every subflow object is stored in memory! :run_numbers: All subflows will be executed with every run_number specified in this list. If None, the current self.run_number (from the node class) is used. (*optional, default: None*) """ if run_numbers == None: run_numbers = [self.run_number] # in case of serial backend, modality is mapped to serial # in the other case communication must be set up and # jobs need to be submitted to backend if self.modality == 'backend': self.backend_com = pySPACE.configuration.backend_com if not self.backend_com is None: # ask for backend_name # create a socket and keep it alive as long as possible since # handshaking costs really time client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(self.backend_com) client_socket, self.backend_name = talk('name' + self.end_token, client_socket, self.backend_com) else: import warnings #necessary for serial backend! warnings.warn("Seems that no backend is used! Modality of subflow execution "\ "has to be specified! Assuming serial backend.") self.backend_name = 'serial' self._log("Preparing subflows for backend execution.") if self.backend_name in ['loadl','mcore'] : # we have to pickle training instances and store it on disk store_path = os.path.join(self.temp_dir, "sp%d" % self.current_split) create_directory(store_path) filename = os.path.join(store_path, "subflow_data.pickle") if not os.path.isfile(filename): cPickle.dump(train_instances, open(filename,'wb'), protocol=cPickle.HIGHEST_PROTOCOL) subflows_to_compute = [subflows[ind].id for ind in \ range(len(subflows))] if self.backend_name == 'loadl': # send batch_size to backend if not already done if not self.already_send: client_socket = inform("subflow_batchsize;%d%s" % \ (self.batch_size, self.end_token), client_socket, self.backend_com) self.already_send = True for subflow in subflows: cPickle.dump(subflow, open(os.path.join(store_path, subflow.id+".pickle"),"wb"), protocol=cPickle.HIGHEST_PROTOCOL) send_flows = subflows_to_compute else: # backend_name == mcore # send pool_size to backend if not already done if not self.already_send: client_socket = inform("subflow_poolsize;%d%s" % \ (self.pool_size, self.end_token), client_socket, self.backend_com) self.already_send = True # send flow objects via socket send_flows = [cPickle.dumps(subflow, cPickle.HIGHEST_PROTOCOL) \ for subflow in subflows] # inform backend client_socket,msg = talk('execute_subflows;%s;%d;%s;%s%s' % \ (store_path, len(subflows), str(send_flows), str(run_numbers), self.end_token), client_socket, self.backend_com) time.sleep(10) not_finished_subflows = set(subflows_to_compute) while len(not_finished_subflows) != 0: # ask backend for finished jobs client_socket, msg = talk('is_ready;%d;%s%s' % \ (len(not_finished_subflows), str(not_finished_subflows), self.end_token), client_socket, self.backend_com) # parse message finished_subflows = eval(msg) #should be a set # set difference not_finished_subflows -= finished_subflows time.sleep(10) if self.backend_name == 'loadl': # read results and delete store_dir result_pattern = os.path.join(store_path, '%s_result.pickle') result_collections = [cPickle.load(open(result_pattern % \ subflows[ind].id,'rb')) for ind in range(len(subflows))] # ..todo:: check if errors have occurred and if so do not delete! shutil.rmtree(store_path) else: # backend_name == mcore # ask backend to send results client_socket, msg = talk("send_results;%s!END!" % \ subflows_to_compute, client_socket, self.backend_com) # should be a list of collections results = eval(msg) result_collections = [cPickle.loads(result) for result in results] self._log("Finished subflow execution.") client_socket.shutdown(socket.SHUT_RDWR) client_socket.close() return result_collections elif self.backend_name == 'serial': # do the same as modality=='serial' self.modality = 'serial' else: # e.g. mpi backend : import warnings warnings.warn("Subflow Handling with %s backend not supported,"\ " serial-modality is used!" % self.backend_name) self.modality = 'serial' if self.modality == 'serial': # serial execution # .. note:: the here executed flows can not store anything. # meta data of result collection is NOT updated! results = [subflow(train_instances=train_instances, runs=run_numbers) for subflow in subflows] result_collections = [result[1] for result in results] return result_collections else: # modality local, e.g. usage without backend in application case self._log("Subflow Handler starts processes in pool.") pool = multiprocessing.Pool(processes=self.pool_size) results = [pool.apply_async(func=subflow, kwds={"train_instances": train_instances, "runs": run_numbers}) \ for subflow in subflows] pool.close() self._log("Waiting for parallel processes to finish.") pool.join() result_collections = [result.get()[1] for result in results] del pool return result_collections
Crespo911/pyspace
pySPACE/environments/chains/node_chain.py
Python
gpl-3.0
60,058
import pandas as pd adv = pd.read_csv('Advertising.csv') tv_budget_x = adv.TV.tolist() print(tv_budget_x)
akanuragkumar/tensorflow-basics
ex1.py
Python
gpl-3.0
110
package com.dotmarketing.portlets.dashboard.model; import java.io.Serializable; import java.util.Date; public class DashboardSummaryPeriod implements Serializable { private static final long serialVersionUID = 1L; private long id; private Date fullDate; private int day; private String dayName; private int week; private int month; private String monthName; private String year; public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getFullDate() { return fullDate; } public void setFullDate(Date fullDate) { this.fullDate = fullDate; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public String getDayName() { return dayName; } public void setDayName(String dayName) { this.dayName = dayName; } public int getWeek() { return week; } public void setWeek(int week) { this.week = week; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public String getMonthName() { return monthName; } public void setMonthName(String monthName) { this.monthName = monthName; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } }
ggonzales/ksl
src/com/dotmarketing/portlets/dashboard/model/DashboardSummaryPeriod.java
Java
gpl-3.0
1,302
package ltf.namerank.dao.fs; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import ltf.namerank.dao.DictItemDao; import ltf.namerank.entity.DictItem; import ltf.namerank.entity.DictItem_Bm8; import ltf.namerank.utils.PathUtils; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static ltf.namerank.utils.FileUtils.file2Str; import static ltf.namerank.utils.FileUtils.str2File; /** * @author ltf * @since 6/11/16, 5:17 PM */ @Component public class DictItemDaoImpl implements DictItemDao { @Override public void saveDictItem(DictItem dictItem) { File f = new File(PathUtils.getJsonHome() + "/dict", dictItem.getZi()); Map<String, DictItem> items = new HashMap<>(); if (f.exists()) { try { items = JSON.parseObject(file2Str(f), items.getClass()); } catch (IOException e) { e.printStackTrace(); } } items.put(dictItem.getItemType(), dictItem); try { str2File(JSON.toJSONString(items, true), f); } catch (IOException e) { e.printStackTrace(); } } @Override public DictItem loadItemsByZi(String zi) { File f = new File(PathUtils.getJsonHome() + "/dict", zi); if (!f.exists()) return null; List<DictItem> list = new ArrayList<>(2); Map<String, DictItem_Bm8> items = new HashMap<>(); try { items = JSON.parseObject(file2Str(f), new TypeReference<Map<String, DictItem_Bm8>>() { }); return items.get("DictItem_Bm8"); } catch (IOException e) { e.printStackTrace(); } return null; } }
ltf/lab
jlab/namerank/src/main/java/ltf/namerank/dao/fs/DictItemDaoImpl.java
Java
gpl-3.0
1,864
<?php /** * The Expression Database. * view auth/admin/reset_password.php * reset_password form *@copyright Laboratoire de Recherche en Sciences Vegetales 2016-2020 *@author Bruno SAVELLI<savelli@lrsv.ups-tlse.fr> *@author Sylvain PICARD<sylvain.picard@lrsv.ups-tlse.fr> *@version 1.0 *@package ExpressWeb *@subpackage views */ ?> <!-- ////////////// auth/admin/reset_password ////////////// --> <h1><?php echo lang('reset_password_heading');?></h1> <div id="infoMessage"><?php echo $message;?></div> <?php echo form_open("auth/reset_password/" . $code);?> <p> <label for="new_password"><?php echo sprintf(lang('reset_password_new_password_label'), $min_password_length);?></label> <br /> <?php echo form_input($new_password);?> </p> <p> <?php echo lang('reset_password_new_password_confirm_label', 'new_password_confirm');?> <br /> <?php echo form_input($new_password_confirm);?> </p> <?php echo form_input($user_id);?> <?php echo form_hidden($csrf); ?> <p><?php echo form_submit('submit', lang('reset_password_submit_btn'));?></p> <?php echo form_close();?> <!-- ////////////// End auth/admin/reset_password ////////////// -->
PeroxiBase/ExpressWeb
application/views/auth/admin/reset_password.php
PHP
gpl-3.0
1,180
/* * ModelManager.java * * DMXControl for Android * * Copyright (c) 2012 DMXControl-For-Android. All rights reserved. * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either * version 3, june 2007 of the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License (gpl.txt) along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * For further information, please contact info [(at)] dmxcontrol.de * * */ package de.dmxcontrol.model; import android.util.Log; import java.util.HashMap; import java.util.Map; import de.dmxcontrol.device.EntitySelection; import de.dmxcontrol.model.BaseModel.OnModelListener; public class ModelManager { private final static String TAG = "modelmanager"; public enum Type { Color, Gobo, Position, Dimmer, Strobe, Shutter, Zoom, Focus, Iris, Frost, Effect } private Map<Type, BaseModel> mModels = new HashMap<Type, BaseModel>(); private static Map<Type, Class<? extends BaseModel>> mTypeLookup = new HashMap<Type, Class<? extends BaseModel>>(); private Map<OnModelListener, Boolean> mDefaultModelListeners = new HashMap<OnModelListener, Boolean>(); private EntitySelection mEntitySelection; public ModelManager(EntitySelection es) { addDefaultModelListener(es); mEntitySelection = es; } public EntitySelection getEntitySelection() { return mEntitySelection; } public void addDefaultModelListener(OnModelListener listener) { mDefaultModelListeners.put(listener, true); } @SuppressWarnings("unchecked") public <T extends BaseModel> T getModel(Type type) { if(mModels.containsKey(type)) { return (T) mModels.get(type); } else { T model; model = create(type); mModels.put(type, (BaseModel) model); return model; } } @SuppressWarnings("unchecked") private <T extends BaseModel> T create(Type type) { Class<? extends BaseModel> clazz = mTypeLookup.get(type); T model; try { model = (T) clazz.getDeclaredConstructors()[0].newInstance(this); } catch(Exception e) { Log.e(TAG, "error creation of model with class " + clazz.getName()); Log.e(TAG, "exception: ", e); return null; } model.addDefaultListener(mDefaultModelListeners); return model; } static { mTypeLookup.put(Type.Color, ColorModel.class); mTypeLookup.put(Type.Gobo, GoboModel.class); mTypeLookup.put(Type.Position, PositionModel.class); mTypeLookup.put(Type.Dimmer, DimmerModel.class); mTypeLookup.put(Type.Strobe, StrobeModel.class); mTypeLookup.put(Type.Shutter, ShutterModel.class); mTypeLookup.put(Type.Zoom, ZoomModel.class); mTypeLookup.put(Type.Focus, FocusModel.class); mTypeLookup.put(Type.Iris, IrisModel.class); mTypeLookup.put(Type.Frost, FrostModel.class); mTypeLookup.put(Type.Effect, EffectModel.class); } }
DMXControl/DMXControl-for-Android
DMXControl/src/de/dmxcontrol/model/ModelManager.java
Java
gpl-3.0
3,722
/* * Copyright (C) 2009-2016 by the geOrchestra PSC * * This file is part of geOrchestra. * * geOrchestra 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. * * geOrchestra 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 * geOrchestra. If not, see <http://www.gnu.org/licenses/>. */ /* * @requires GeoExt/Lang.js */ /* * French translation file */ OpenLayers.Lang.fr = OpenLayers.Util.extend(OpenLayers.Lang.fr, { /* General purpose strings */ "Yes": "Oui", "No": "Non", "OK": "OK", "or": "ou", "Cancel": "Annuler", "Save": "Sauvegarder", "Loading...": "Chargement...", "File": "Fichier", "Layer": "Couche", "layers": "couches", "Description": "Description", "Error": "Erreur", "Server": "Serveur", "Close": "Fermer", "labelSeparator": " : ", "File submission failed or invalid file": "L'envoi du fichier a échoué - le fichier est peut-être non valide", "Type": "Type", "Title": "Titre", "Actions": "Actions", "Incorrect server response.": "Réponse du serveur incorrecte.", "No features found.": "Aucun objet trouvé.", /* GEOR.js strings */ "Cities": "Localités", "Recentering on GeoNames cities": "Recentrage sur localités<br />de la base GeoNames", "Referentials": "Référentiels", "Recentering on a selection of referential layers": "Recentrage sur une sélection<br />de couches \"référentiels\"", "Addresses": "Adresses", "Recentering on a given address": "Recentrage sur point adresse", "Available layers": "Couches disponibles", "WMS Search": "Recherche WMS", "WFS Search": "Recherche WFS", "resultspanel.emptytext": "<p>Sélectionnez l'outil d'interrogation " + "ou construisez une requête sur une couche.<br />" + "Les attributs des objets s'afficheront dans ce cadre.</p>", /* GEOR_ClassificationPanel.js strings */ "Attribute": "Attribut", "Number of classes": "Nombre de classes", "Minimum size": "Taille minimum", "Maximum size": "Taille maximum", "First color": "Première couleur", "Last color": "Dernière couleur", "Palette": "Palette", "Auto classification": "Classification automatique", "Classify": "Classifier", "Unique values": "Valeurs uniques", "Color range": "Plages de couleurs", "Proportional symbols": "Symboles proportionnels", /* GEOR_FeatureDataModel.js strings */ "objects": "objets", /* GEOR_address.js strings */ "Go to: ": "Aller à : ", "searching...": "recherche en cours...", "adressSearchExemple": "ex: 4, Hugo, Brest", /* GEOR_ajaxglobal.js strings strings */ "Server did not respond.": "Le serveur n'a pas répondu.", "Server access denied.": "Le serveur a refusé de répondre.", "ajax.badresponse": "Le service a répondu, mais le contenu de la " + "réponse n'est pas conforme à celle attendue", "Server unavailable.": "Le serveur est temporairement indisponible. Veuillez réessayer ultérieurement.", "Too much data.": "Données trop volumineuses.", "Server exception.": "Le serveur a renvoyé une exception.", "ajax.defaultexception": "Pour plus d'information, vous pouvez " + "chercher le code de retour sur <a href=\"http://" + "en.wikipedia.org/wiki/List_of_HTTP_status_codes\" target=\"_blank\">" + "cette page</a>.", "An error occured.<br />": "Une erreur est survenue.<br />", "Warning : browser may freeze": "Attention : risque de blocage du navigateur", "ajaxglobal.data.too.big": "Les données provenant du serveur sont trop " + "volumineuses.<br />Le serveur a envoyé ${SENT}KO " + "(la limite est à ${LIMIT}KO)<br />Voulez-vous tout de même continuer ?", /* GEOR_config.js strings */ /* GEOR_cswbrowser.js strings */ "NAME layer": "Couche ${NAME}", "Metadata without a name": "Métadonnée non nommée", "The getDomain CSW query failed": "La requête CSW getDomain a échoué", "Error for the thesaurus": "Erreur sur le thésaurus", "Missing key to access the thesaurus": "Absence de clé pour accéder à ce thésaurus", "Keywords query failed": "La requête des mots clés a échoué", "Thesaurus:": "Thésaurus :", "Thesaurus": "Thésaurus", "cswbrowser.default.thesaurus.mismatch": "Administrateur : problème de configuration - " + "la variable DEFAULT_THESAURUS_KEY ne correspond à aucune" + " valeur exportée par GeoNetwork", /* GEOR_cswquerier.js strings */ "cswquerier.help.title": "Syntaxe pour la recherche avancée", "cswquerier.help.message": "<ul><li><b>@mot</b> cherche dans le nom de l'organisation.</li><li><b>#mot</b> cherche dans les mots clés de la métadonnée.</li><li><b>?mot</b> élargit la recherche à tous les champs de la métadonnée.</li></ul>", "NAME layer on VALUE": "Couche ${NAME} sur ${VALUE}", "Show metadata essentials in a window": "Afficher les métadonnées basiques", "Show metadata sheet in a new browser tab": "Afficher la métadonnée complète dans un nouvel onglet", "more": "plus", "Click to select or deselect the layer": "Cliquez pour sélectionner ou désélectionner la couche", "Open the URL url in a new window": "Ouvrir l'url ${URL} dans une nouvelle fenêtre", "Unreachable server": "Serveur non disponible", "Catalogue": "Catalogue", "Find": "Chercher", "in": "dans", "No linked layer.": "Aucune couche.", "One layer found.": "Une couche trouvée.", "NB layers found.": "${NB} couches trouvées.", "NB metadata match the query.": "${NB} métadonnées correspondent à la requête.", "A single metadata matches the query.": "Une unique métadonnée correspond à la requête.", "Precise your request.": "Précisez votre requête.", "No metadata matches the query.": "Aucune métadonnée ne correspond à la requête.", "Limit to map extent": "Limiter à l'étendue de la carte", "Search limited to current map extent.": "Recherche limitée à l'étendue de la carte.", /* GEOR_fileupload.js strings */ "2D only": "géométries 2D", "Local file": "Fichier", "The service is inactive": "Le service est inactif", "Upload a vector data file.": "Uploadez un fichier de données vectorielles.", "The allowed formats are the following: ": "Les formats acceptés sont les suivants : ", "Use ZIP compression for multifiles formats, such as": "Utilisez la compression ZIP pour les formats multi-fichiers comme", "fileupload_error_incompleteMIF": "Fichier MIF/MID incomplet.", "fileupload_error_incompleteSHP": "Fichier shapefile incomplet.", "fileupload_error_incompleteTAB": "Fichier TAB incomplet.", "fileupload_error_ioError": "Erreur d'I/O sur le serveur. Contacter l'administrateur de la plateforme pour plus de détails.", "fileupload_error_multipleFiles": "L'archive ZIP contient plusieurs fichiers de données. Elle ne doit en contenir qu'un seul.", "fileupload_error_outOfMemory": "Le serveur ne dispose plus de la mémoire suffisante. Contacter l'administrateur de la plateforme pour plus de détails.", "fileupload_error_sizeError": "Le fichier est trop grand pour pouvoir être traité.", "fileupload_error_unsupportedFormat": "Ce format de données n'est pas géré par l'application.", "fileupload_error_projectionError": "Une erreur est survenue lors de la lecture des coordonnées géographiques. Êtes-vous sûr que le fichier contient les informations de projection ?", "server upload error: ERROR": "L'upload du fichier a échoué. ${ERROR}", /* GEOR_geonames.js strings */ /* GEOR_getfeatureinfo.js strings */ "<div>Searching...</div>": "<div>Recherche en cours...</div>", "<div>No layer selected</div>": "<div>Aucune couche sélectionnée</div>", "<div>Search on objects active for NAME layer. Click on the map.</div>": "<div>Recherche d\'objets activée sur la couche ${NAME}. " + "Cliquez sur la carte.</div>", "WMS GetFeatureInfo at ": "GetFeatureInfo WMS sur ", /* GEOR_layerfinder.js strings */ "metadata": "métadonnée", "Add layers from local files": "Ajouter des couches en uploadant un fichier depuis votre ordinateur", "Find layers searching in metadata": "Trouvez des couches en cherchant dans les métadonnées", "Find layers from keywords": "Trouvez des couches par mots clés", "Find layers querying OGC services": "Trouvez des couches en interrogeant des services OGC", "layerfinder.layer.unavailable": "La couche ${NAME} n'a pas été trouvée dans le service WMS.<br/<br/>" + "Peut-être n'avez-vous pas le droit d'y accéder " + "ou alors cette couche n'est plus disponible", "Layer projection is not compatible": "La projection de la couche n'est pas compatible.", "The NAME layer does not contain a valid geometry column": "La couche ${NAME} ne possède pas de colonne géométrique valide.", "Add": "Ajouter", "Add layers from a ...": "Ajouter des couches depuis un ...", "Malformed URL": "URL non conforme.", "Queryable": "Interrogeable", "Opaque": "Opaque", "OGC server": "Serveur OGC", "I'm looking for ...": "Je recherche ...", "Service type": "Type de service", "Choose a server": "Choisissez un serveur", "... or enter its address": "... ou saisissez son adresse", "The server is publishing one layer with an incompatible projection": "Le serveur publie une couche dont la projection n'est pas compatible", "The server is publishing NB layers with an incompatible projection": "Le serveur publie ${NB} couches dont la projection n'est pas " + "compatible", "This server does not support HTTP POST": "Ce serveur ne supporte pas HTTP POST", "Unreachable server or insufficient rights": "Réponse invalide du " + "serveur. Raisons possibles : droits insuffisants, " + "serveur injoignable, trop de données, etc.", /* GEOR_managelayers.js strings */ "layergroup": "couche composite", "Service": "Service", "Protocol": "Protocole", "About this layer": "A propos de cette couche", "Set as overlay": "Passer en calque", "Set as baselayer": "Passer en couche de fond", "Tiled mode" : "Mode tuilé", "Confirm NAME layer deletion ?": "Voulez-vous réellement supprimer la couche ${NAME} ?", "1:MAXSCALE to 1:MINSCALE": "1:${MAXSCALE} à 1:${MINSCALE}", "Visibility range (indicative):<br />from TEXT": "Plage de visibilité (indicative):<br />de ${TEXT}", "Information on objects of this layer": "Interroger les objets de cette couche", "default style": "style par défaut", "no styling": "absence de style", "Recenter on the layer": "Recentrer sur la couche", "Impossible to get layer extent": "Impossible d'obtenir l'étendue de la couche.", "Refresh layer": "Recharger la couche", "Show metadata": "Afficher les métadonnées", "Edit symbology": "Éditer la symbologie", "Build a query": "Construire une requête", "Download data": "Extraire les données", "Choose a style": "Choisir un style", "Modify format": "Modifier le format", "Delete this layer": "Supprimer cette couche", "Push up this layer": "Monter cette couche", "Push down this layer": "descendre cette couche", "Add layers": "Ajouter des couches", "Remove all layers": "Supprimer toutes les couches", "Are you sure you want to remove all layers ?": "Voulez vous réellement supprimer toutes les couches ?", "source: ": "source : ", "unknown": "inconnue", "Draw new point": "Dessiner un nouveau point", "Draw new line": "Dessiner une nouvelle ligne", "Draw new polygon": "Dessiner un nouveau polygone", "Edition": "Edition", "Editing": "Edition en cours", "Switch on/off edit mode for this layer": "Basculer cette couche en mode édition", "No geometry column.": "Colonne géométrique non détectée.", "Geometry column type (TYPE) is unsupported.": "Le type de la colonne géométrique (${TYPE}) n'est pas supporté.", "Switching to attributes-only edition.": "Seuls les attributs des objets existants seront éditables.", /* GEOR_map.js strings */ "Location map": "Carte de situation", "Warning after loading layer": "Avertissement suite au chargement de couche", "The <b>NAME</b> layer could not appear for this reason: ": "La couche <b>${NAME}</b> pourrait ne pas apparaître pour " + "la raison suivante : ", "Min/max visibility scales are invalid": "Les échelles min/max de visibilité sont invalides.", "Visibility range does not match map scales": "La plage de visibilité ne correspond pas aux échelles de la carte.", "Geografic extent does not match map extent": "L'étendue géographique ne correspond pas à celle de la carte.", /* GEOR_mapinit.js strings */ "Add layers from WMS services": "Ajouter des couches depuis des services WMS", "Add layers from WFS services": "Ajouter des couches depuis des services WFS", "NB layers not imported": "${NB} couches non importées", "One layer not imported": "Une couche non importée", "mapinit.layers.load.error": "Les couches nommées ${LIST} n'ont pas pu être chargées. " + "Raisons possibles : droits insuffisants, SRS incompatible ou couche non existante", "NB layers imported": "${NB} couches importées", "One layer imported": "Une couche importée", "No layer imported": "Aucune couche importée", "The provided context is not valid": "Le contexte fourni n'est pas valide", "The default context is not defined (and it is a BIG problem!)": "Le contexte par défaut n'est pas défini " + "(et ce n'est pas du tout normal !)", "Error while loading file": "Erreur au chargement du fichier", /* GEOR_mappanel.js strings */ "Coordinates in ": "Coordonnées en ", "scale picker": "échelle", /* GEOR_ows.js strings */ "The NAME layer was not found in WMS service.": "La couche ${NAME} n'a pas été trouvée dans le service WMS.", "Problem restoring a context saved with buggy Chrome 36 or 37": "Nous ne pouvons restaurer un contexte enregistré avec Chrome 36 ou 37", /* GEOR_print.js strings */ "Sources: ": "Sources : ", "Source: ": "Source : ", "Projection: PROJ": "Projection : ${PROJ}", "Print error": "Impression impossible", "Print server returned an error": "Le service d'impression a signalé une erreur.", "Contact platform administrator": "Contactez l'administrateur de la plateforme.", "Layer unavailable for printing": "Couche non disponible pour impression", "The NAME layer cannot be printed.": "La couche ${NAME} ne peut pas encore être imprimée.", "Unable to print": "Impression non disponible", "The print server is currently unreachable": "Le service d'impression est actuellement inaccessible.", "print.unknown.layout": "Erreur de configuration: DEFAULT_PRINT_LAYOUT " + "${LAYOUT} n'est pas dans la liste des formats d'impression", "print.unknown.resolution": "Erreur de configuration: DEFAULT_PRINT_RESOLUTION " + "${RESOLUTION} n'est pas dans la liste des résolutions d'impression", "print.unknown.format": "Erreur de configuration: le format " + "${FORMAT} n'est pas supporté par le serveur d'impression", "Pick an output format": "Choisissez un format de sortie", "Comments": "Commentaires", "Scale: ": "Échelle : ", "Date: ": "Date : ", "Minimap": "Mini-carte", "North": "Nord", "Scale": "Échelle", "Date": "Date", "Legend": "Légende", "Format": "Format", "Resolution": "Résolution", "Print the map": "Impression de la carte", "Print": "Imprimer", "Printing...": "Impression en cours...", "Print current map": "Imprimer la carte courante", /* GEOR_Querier.js strings */ "Fields of filters with a red mark are mandatory": "Vous devez remplir " + "les champs des filtres marqués en rouge.", "Request on NAME": "Requêteur sur ${NAME}", "WFS GetFeature on filter": "GetFeature WFS sur un filtre", "Search": "Rechercher", "querier.layer.no.geom": "La couche ne possède pas de colonne géométrique." + "<br />Le requêteur géométrique ne sera pas fonctionnel.", "querier.layer.error": "Impossible d'obtenir les caractéristiques de la couche demandée." + "<br />Le requêteur ne sera pas disponible.", /* GEOR_referentials.js strings */ "Referential": "Référentiel", "There is no geometry column in the selected referential": "Le référentiel sélectionné ne possède pas de colonne géométrique", "Choose a referential": "Choisissez un référentiel", /* GEOR_resultspanel.js strings */ "Symbology": "Symbologie", "Edit this panel's features symbology": "Editer la symbologie de la sélection", "Reset": "Réinitialiser", "Export is not possible: features have no geometry": "Export impossible : absence de géométries", "resultspanel.maxfeature.reached": " <span ext:qtip=\"Utilisez un navigateur plus performant " + "pour augmenter le nombre d'objets affichables\">" + "Nombre maximum d'objets atteint (${NB})</span>", "NB results": "${NB} résultats", "One result": "1 résultat", "No result": "Aucun résultat", "Clean": "Effacer", "All": "Tous", "None": "Aucun", "Invert selection": "Inverser la sélection", "Actions on the selection or on all results if no row is selected": "Actions sur la sélection ou sur tous les résultats si aucun n'est sélectionné", "Store the geometry": "Enregistrer la géométrie", "Aggregates the geometries of the selected features and stores it in your browser for later use in the querier": "La géométrie des objets sélectionnés est enregistrée pour un usage ultérieur dans le requêteur", "Geometry successfully stored in this browser": "Géométrie enregistrée avec succès sur ce navigateur", "Clean all results on the map and in the table": "Supprimer les " + "résultats affichés sur la carte et dans le tableau", "Zoom": "Zoom", "Zoom to results extent": "Cadrer l'étendue de la carte sur celle " + "des résultats", "Export": "Export", "Export results as": "Exporter l'ensemble des résultats en", "<p>No result for this request.</p>": "<p>Aucun objet ne " + "correspond à votre requête.</p>", /* GEOR_scalecombo.js strings */ /* GEOR_selectfeature.js strings */ "<div>Select features activated on NAME layer. Click on the map.</div>": "<div>Sélection d\'objets activée sur la couche ${NAME}. " + "Cliquez sur la carte.</div>", "OpenLayers SelectFeature":"Sélection d\'objets", /* GEOR_styler.js strings */ "Download style": "Télécharger le style", "You can download your SLD style at ": "Votre SLD est disponible à " + "l\'adresse suivante : ", "Thanks!": "Merci !", "Saving SLD": "Sauvegarde du SLD", "Some classes are invalid, verify that all fields are correct": "Des " + "classes ne sont pas valides, vérifier que les champs sont corrects", "Get SLD": "Récupération du SLD", "Malformed SLD": "Le SLD n'est pas conforme.", "circle": "cercle", "square": "carré", "triangle": "triangle", "star": "étoile", "cross": "croix", "x": "x", "customized...": "personnalisé...", "Classification ...<br/>(this operation can take some time)": "Classification ...<br/>(cette opération peut prendre du temps)", "Class": "Classe", "Untitled": "Sans titre", "styler.guidelines": "Utiliser le bouton \"+\" pour créer une classe, et le bouton " + "\"Analyse\" pour créer un ensemble de classes définies par une " + "analyse thématique.</p>", "Analyze": "Analyse", "Add a class": "Ajouter une classe", "Delete the selected class": "Supprimer la classe sélectionnée", "Styler": "Styleur", "Apply": "Appliquer", "Impossible to complete the operation:": "Opération impossible :", "no available attribute": "aucun attribut disponible.", /* GEOR_toolbar.js strings */ "m": "m", "hectares": "hectares", "zoom to global extent of the map": "zoom sur l'étendue globale de la " + "carte", "pan": "glisser - déplacer la carte", "zoom in": "zoom en avant (pour zoomer sur une emprise: appuyer sur SHIFT + dessiner l'emprise)", "zoom out": "zoom en arrière", "back to previous zoom": "revenir à la précédente emprise", "go to next zoom": "aller à l'emprise suivante", "Login": "Connexion", "Logout": "Déconnexion", "Help": "Aide", "Query all active layers": "Interroger toutes les couches actives", "Show legend": "Afficher la légende", "Leave this page ? You will lose the current cartographic context.": "Vous allez quitter cette page et perdre le contexte cartographique " + "courant", "Online help": "Aide en ligne", "Display the user guide": "Afficher le guide de l'utilisateur", "Contextual help": "Aide contextuelle", "Activate or deactivate contextual help bubbles": "Activer ou désactiver les bulles d'aide contextuelle", /* GEOR_tools.js strings */ "Tools": "Outils", "tools": "outils", "tool": "outil", "No tool": "aucun outil", "Manage tools": "Gérer les outils", "remember the selection": "se souvenir de la sélection", "Available tools:": "Outils disponibles :", "Click to select or deselect the tool": "Cliquez pour (dé)sélectionner l'outil", "Could not load addon ADDONNAME": "Impossible de charger l'addon ${ADDONNAME}", "Your new tools are now available in the tools menu.": 'Vos nouveaux outils sont disponibles dans le menu "outils"', /* GEOR_util.js strings */ "Characters": "Caractères", "Digital": "Numérique", "Boolean": "Booléen", "Other": "Autre", "Confirmation": "Confirmation", "Information": "Information", "pointOfContact": "contact", "custodian": "producteur", "distributor": "distributeur", "originator": "instigateur", "More": "Plus", "Could not parse metadata.": "Impossible d'analyser la métadonnée", "Could not get metadata.": "Impossible d'obtenir la métadonnée", /* GEOR_waiter.js strings */ /* GEOR_wmc.js strings */ "The provided file is not a valid OGC context": "Le fichier fourni n'est pas un contexte OGC valide", "Warning: trying to restore WMC with a different projection (PROJCODE1, while map SRS is PROJCODE2). Strange things might occur !": "Attention: le contexte restauré avait été sauvegardé en ${PROJCODE1} alors que la carte actuelle est en ${PROJCODE2}. Il pourrait y avoir des comportements inattendus.", /* GEOR_wmcbrowser.js strings */ "all contexts": "toutes les cartes", "Could not find WMC file": "Le fichier spécifié n'existe pas", "... or a local context": "... ou une carte locale", "Load or add the layers from one of these map contexts:": "Charger ou ajouter les couches de l'une de ces cartes :", "A unique OSM layer": "Une unique couche OpenStreetMap", "default viewer context": "carte par défaut", "(default)": "<br/>(carte par défaut)", /* GEOR_workspace.js strings */ "Created:": "Date de création : ", "Last accessed:": "Date de dernier accès : ", "Access count:": "Nombre d'accès : ", "Permalink:": "Permalien : ", "My contexts": "Mes cartes", "Created": "Création", "Accessed": "Accédé", "Count": "Accès", "View": "Visualiser", "View the selected context": "Visualiser la carte sélectionnée (attention : remplacera la carte courante)", "Download": "Télécharger", "Download the selected context": "Télécharger la carte sélectionnée", "Delete": "Supprimer", "Delete the selected context": "Supprimer la carte sélectionnée", "Failed to delete context": "Impossible de supprimer la carte", "Manage my contexts": "Gérer mes cartes", "Keywords": "Mots clés", "comma separated keywords": "mots clés séparés par une virgule", "Save to metadata": "Créer une métadonnée", "in group": "dans le groupe", "The context title is mandatory": "Le titre de la carte est obligatoire", "There was an error creating the metadata.": "La création de la métadonnée a échoué.", "Share this map": "Partager cette carte", "Mobile viewer": "Visualiseur mobile", "Mobile compatible viewer on sdi.georchestra.org": "Visualiseur mobile sur sdi.georchestra.org", "Desktop viewer": "Visualiseur web", "Desktop viewer on sdi.georchestra.org": "Visualiseur web sur sdi.georchestra.org", "Abstract": "Résumé", "Context saving": "Sauvegarde de la carte", "The file is required.": "Un nom de fichier est nécessaire.", "Context restoring": "Restauration d'une carte", "<p>Please note that the WMC must be UTF-8 encoded</p>": "<p>Notez que le" + " fichier de contexte doit être encodé en UTF-8.</p>", "Load": "Charger", "Workspace": "Espace de travail", "Save the map context": "Sauvegarder la carte", "Load a map context": "Charger une carte", "Get a permalink": "Obtenir un permalien", "Permalink": "Permalien", "Share your map with this URL: ": "Partagez la carte avec l'adresse suivante : ", /* GEOR_edit.js */ "Req.": "Req.", // requis "Required": "Requis", "Not required": "Non requis", "Synchronization failed.": "Erreur lors de la synchronisation.", "Edit activated": "Edition activée", "Hover the feature you wish to edit, or choose \"new feature\" in the edit menu": "Survolez les objets de la couche que vous souhaitez modifier, ou choisissez \"nouvel objet\" dans le menu d'édition de la couche", /* GeoExt.data.CSW.js */ "no abstract": "pas de résumé" // no trailing comma }); GeoExt.Lang.add("fr", { "GeoExt.ux.FeatureEditorGrid.prototype": { deleteMsgTitle: "Suppression", deleteMsg: "Confirmer la suppression de cet objet vectoriel ?", deleteButtonText: "Supprimer", deleteButtonTooltip: "Supprimer cet objet", cancelMsgTitle: "Annulation", cancelMsg: "L'objet a été modifié localement. Confirmer l'abandon des changements ?", cancelButtonText: "Annuler", cancelButtonTooltip: "Abandonner les modifications en cours", saveButtonText: "Enregistrer", saveButtonTooltip: "Enregistrer les modifications", nameHeader: "Attribut", valueHeader: "Valeur" } });
jusabatier/georchestra
mapfishapp/src/main/webapp/app/js/GEOR_Lang/fr.js
JavaScript
gpl-3.0
27,587
package cz.devaty.projects.gio; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.stream.Collectors; public class Main { /** * předmět a -> 3., 7.O * předmět b -> 4., 8.O * předmět c -> 3., 7.O, 4., 8.O */ private static String FILE = "a.csv"; private static char[] groups = {'A', 'B',}; //'C', 'D', 'E'}; private static ArrayList<Student> students; private static ArrayList<Seminar> seminars; public static void main(String[] args) { try { loadData(); seminars = seminars.stream().distinct().collect(Collectors.toCollection(ArrayList::new)); computeGroups(); } catch (FileNotFoundException e) { System.out.println("Error loading data"); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } private static void computeGroups() throws CloneNotSupportedException { //variace s opakováním for (int i = 0; i < 12; i++) { seminars.remove(0); } ArrayList<ArrayList<Seminar>> variations = new ArrayList<>(); brute(variations, 0); } private static void brute(ArrayList<ArrayList<Seminar>> variations, int count) throws CloneNotSupportedException { if (count < seminars.size()) { for (int i = 0; i < groups.length; i++) { seminars.get(count).setGroup(groups[i]); brute(variations, count + 1); } } else { //defensive copy ArrayList<Seminar> sem = new ArrayList<>(); for (int i = 0; i < seminars.size(); i++) { sem.add(seminars.get(i).clone()); } variations.add(sem); } } private static double countConflicts(int lastIndex) { double result = 0; for (int i = 0; i < lastIndex; i++) { result += Student.conflictsPerStudent(students.get(i)); } return result; } private static void loadData() throws FileNotFoundException { seminars = new ArrayList<>(); students = new ArrayList<>(); BufferedReader in = new BufferedReader(new FileReader(FILE)); while (true) { try { String s = in.readLine(); if (s == null) return; String[] line = s.split(";"); ArrayList<Seminar> sem = new ArrayList<>(); for (int i = 2; i < line.length; i++) { sem.add(new Seminar(line[i])); seminars.add(new Seminar(line[i])); } students.add(new Student(line[1], line[2], sem)); } catch (IOException e) { return; } } } }
MrMid/gio-seminare
rozvrhovac/src/cz/devaty/projects/gio/Main.java
Java
gpl-3.0
2,895
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) $Revision: 5171 $ (Revision of last commit) $Date: 2012-01-07 08:08:06 +0000 (Sat, 07 Jan 2012) $ (Date of last commit) $Author: greebo $ (Author of last commit) ******************************************************************************/ #include "precompiled_engine.h" #pragma hdrstop static bool versioned = RegisterVersionedFile("$Id: draw_nv20.cpp 5171 2012-01-07 08:08:06Z greebo $"); #include "tr_local.h" typedef enum { FPROG_BUMP_AND_LIGHT, FPROG_DIFFUSE_COLOR, FPROG_SPECULAR_COLOR, FPROG_DIFFUSE_AND_SPECULAR_COLOR, FPROG_NUM_FRAGMENT_PROGRAMS } fragmentProgram_t; GLuint fragmentDisplayListBase; // FPROG_NUM_FRAGMENT_PROGRAMS lists void RB_NV20_DependentSpecularPass( const drawInteraction_t *din ); void RB_NV20_DependentAmbientPass( void ); /* ========================================================================================= GENERAL INTERACTION RENDERING ========================================================================================= */ /* ==================== GL_SelectTextureNoClient ==================== */ void GL_SelectTextureNoClient( int unit ) { backEnd.glState.currenttmu = unit; qglActiveTextureARB( GL_TEXTURE0_ARB + unit ); RB_LogComment( "glActiveTextureARB( %i )\n", unit ); } /* ================== RB_NV20_BumpAndLightFragment ================== */ static void RB_NV20_BumpAndLightFragment( void ) { if ( r_useCombinerDisplayLists.GetBool() ) { qglCallList( fragmentDisplayListBase + FPROG_BUMP_AND_LIGHT ); return; } // program the nvidia register combiners qglCombinerParameteriNV( GL_NUM_GENERAL_COMBINERS_NV, 3 ); // stage 0 rgb performs the dot product // SPARE0 = TEXTURE0 dot TEXTURE1 qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE1_ARB, GL_EXPAND_NORMAL_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE0_ARB, GL_EXPAND_NORMAL_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER0_NV, GL_RGB, GL_SPARE0_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, GL_TRUE, GL_FALSE, GL_FALSE ); // stage 1 rgb multiplies texture 2 and 3 together // SPARE1 = TEXTURE2 * TEXTURE3 qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE2_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE3_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER1_NV, GL_RGB, GL_SPARE1_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); // stage 1 alpha does nohing // stage 2 color multiplies spare0 * spare 1 just for debugging // SPARE0 = SPARE0 * SPARE1 qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_B_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER2_NV, GL_RGB, GL_SPARE0_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); // stage 2 alpha multiples spare0 * spare 1 // SPARE0 = SPARE0 * SPARE1 qglCombinerInputNV( GL_COMBINER2_NV, GL_ALPHA, GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_BLUE ); qglCombinerInputNV( GL_COMBINER2_NV, GL_ALPHA, GL_VARIABLE_B_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_BLUE ); qglCombinerOutputNV( GL_COMBINER2_NV, GL_ALPHA, GL_SPARE0_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); // final combiner qglFinalCombinerInputNV( GL_VARIABLE_D_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_A_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_G_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_ALPHA ); } /* ================== RB_NV20_DI_BumpAndLightPass We are going to write alpha as light falloff * ( bump dot light ) * lightProjection If the light isn't a monoLightShader, the lightProjection will be skipped, because it will have to be done on an itterated basis ================== */ static void RB_NV20_DI_BumpAndLightPass( const drawInteraction_t *din, bool monoLightShader ) { RB_LogComment( "---------- RB_NV_BumpAndLightPass ----------\n" ); GL_State( GLS_COLORMASK | GLS_DEPTHMASK | backEnd.depthFunc ); // texture 0 is the normalization cube map // GL_TEXTURE0_ARB will be the normalized vector // towards the light source #ifdef MACOS_X GL_SelectTexture( 0 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 0 ); #endif if ( din->ambientLight ) { globalImages->ambientNormalMap->Bind(); } else { globalImages->normalCubeMapImage->Bind(); } // texture 1 will be the per-surface bump map #ifdef MACOS_X GL_SelectTexture( 1 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 1 ); #endif din->bumpImage->Bind(); // texture 2 will be the light falloff texture #ifdef MACOS_X GL_SelectTexture( 2 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 2 ); #endif din->lightFalloffImage->Bind(); // texture 3 will be the light projection texture #ifdef MACOS_X GL_SelectTexture( 3 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 3 ); #endif if ( monoLightShader ) { din->lightImage->Bind(); } else { // if the projected texture is multi-colored, we // will need to do it in subsequent passes globalImages->whiteImage->Bind(); } // bind our "fragment program" RB_NV20_BumpAndLightFragment(); // draw it qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, VPROG_NV20_BUMP_AND_LIGHT ); RB_DrawElementsWithCounters( din->surf->geo ); } /* ================== RB_NV20_DiffuseColorFragment ================== */ static void RB_NV20_DiffuseColorFragment( void ) { if ( r_useCombinerDisplayLists.GetBool() ) { qglCallList( fragmentDisplayListBase + FPROG_DIFFUSE_COLOR ); return; } // program the nvidia register combiners qglCombinerParameteriNV( GL_NUM_GENERAL_COMBINERS_NV, 1 ); // stage 0 is free, so we always do the multiply of the vertex color // when the vertex color is inverted, qglCombinerInputNV(GL_VARIABLE_B_NV) will be changed qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_PRIMARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER0_NV, GL_RGB, GL_TEXTURE0_ARB, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); qglCombinerOutputNV( GL_COMBINER0_NV, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); // for GL_CONSTANT_COLOR0_NV * TEXTURE0 * TEXTURE1 qglFinalCombinerInputNV( GL_VARIABLE_A_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_B_NV, GL_E_TIMES_F_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_D_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_E_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_F_NV, GL_TEXTURE1_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_G_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_ALPHA ); } /* ================== RB_NV20_DI_DiffuseColorPass ================== */ static void RB_NV20_DI_DiffuseColorPass( const drawInteraction_t *din ) { RB_LogComment( "---------- RB_NV20_DiffuseColorPass ----------\n" ); GL_State( GLS_SRCBLEND_DST_ALPHA | GLS_DSTBLEND_ONE | GLS_DEPTHMASK | GLS_ALPHAMASK | backEnd.depthFunc ); // texture 0 will be the per-surface diffuse map #ifdef MACOS_X GL_SelectTexture( 0 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 0 ); #endif din->diffuseImage->Bind(); // texture 1 will be the light projected texture #ifdef MACOS_X GL_SelectTexture( 1 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 1 ); #endif din->lightImage->Bind(); // texture 2 is disabled #ifdef MACOS_X GL_SelectTexture( 2 ); qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 2 ); #endif globalImages->BindNull(); // texture 3 is disabled #ifdef MACOS_X GL_SelectTexture( 3 ); qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 3 ); #endif globalImages->BindNull(); // bind our "fragment program" RB_NV20_DiffuseColorFragment(); // override one parameter for inverted vertex color if ( din->vertexColor == SVC_INVERSE_MODULATE ) { qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_PRIMARY_COLOR_NV, GL_UNSIGNED_INVERT_NV, GL_RGB ); } // draw it qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, VPROG_NV20_DIFFUSE_COLOR ); RB_DrawElementsWithCounters( din->surf->geo ); } /* ================== RB_NV20_SpecularColorFragment ================== */ static void RB_NV20_SpecularColorFragment( void ) { if ( r_useCombinerDisplayLists.GetBool() ) { qglCallList( fragmentDisplayListBase + FPROG_SPECULAR_COLOR ); return; } // program the nvidia register combiners qglCombinerParameteriNV( GL_NUM_GENERAL_COMBINERS_NV, 4 ); // we want GL_CONSTANT_COLOR1_NV * PRIMARY_COLOR * TEXTURE2 * TEXTURE3 * specular( TEXTURE0 * TEXTURE1 ) // stage 0 rgb performs the dot product // GL_SPARE0_NV = ( TEXTURE0 dot TEXTURE1 - 0.5 ) * 2 // TEXTURE2 = TEXTURE2 * PRIMARY_COLOR // the scale and bias steepen the specular curve qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE1_ARB, GL_EXPAND_NORMAL_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE0_ARB, GL_EXPAND_NORMAL_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER0_NV, GL_RGB, GL_SPARE0_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_SCALE_BY_TWO_NV, GL_BIAS_BY_NEGATIVE_ONE_HALF_NV, GL_TRUE, GL_FALSE, GL_FALSE ); // stage 0 alpha does nothing // stage 1 color takes bump * bump // GL_SPARE0_NV = ( GL_SPARE0_NV * GL_SPARE0_NV - 0.5 ) * 2 // the scale and bias steepen the specular curve qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER1_NV, GL_RGB, GL_SPARE0_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_SCALE_BY_TWO_NV, GL_BIAS_BY_NEGATIVE_ONE_HALF_NV, GL_FALSE, GL_FALSE, GL_FALSE ); // stage 1 alpha does nothing // stage 2 color // GL_SPARE0_NV = GL_SPARE0_NV * TEXTURE3 // SECONDARY_COLOR = CONSTANT_COLOR * TEXTURE2 qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE3_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_C_NV, GL_CONSTANT_COLOR1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_D_NV, GL_TEXTURE2_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER2_NV, GL_RGB, GL_SPARE0_NV, GL_SECONDARY_COLOR_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); // stage 2 alpha does nothing // stage 3 scales the texture by the vertex color qglCombinerInputNV( GL_COMBINER3_NV, GL_RGB, GL_VARIABLE_A_NV, GL_SECONDARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER3_NV, GL_RGB, GL_VARIABLE_B_NV, GL_PRIMARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER3_NV, GL_RGB, GL_SECONDARY_COLOR_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); // stage 3 alpha does nothing // final combiner = GL_SPARE0_NV * SECONDARY_COLOR + PRIMARY_COLOR * SECONDARY_COLOR qglFinalCombinerInputNV( GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_B_NV, GL_SECONDARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_D_NV, GL_E_TIMES_F_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_E_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_F_NV, GL_SECONDARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_G_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_ALPHA ); } /* ================== RB_NV20_DI_SpecularColorPass ================== */ static void RB_NV20_DI_SpecularColorPass( const drawInteraction_t *din ) { RB_LogComment( "---------- RB_NV20_SpecularColorPass ----------\n" ); GL_State( GLS_SRCBLEND_DST_ALPHA | GLS_DSTBLEND_ONE | GLS_DEPTHMASK | GLS_ALPHAMASK | backEnd.depthFunc ); // texture 0 is the normalization cube map for the half angle #ifdef MACOS_X GL_SelectTexture( 0 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 0 ); #endif globalImages->normalCubeMapImage->Bind(); // texture 1 will be the per-surface bump map #ifdef MACOS_X GL_SelectTexture( 1 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 1 ); #endif din->bumpImage->Bind(); // texture 2 will be the per-surface specular map #ifdef MACOS_X GL_SelectTexture( 2 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 2 ); #endif din->specularImage->Bind(); // texture 3 will be the light projected texture #ifdef MACOS_X GL_SelectTexture( 3 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 3 ); #endif din->lightImage->Bind(); // bind our "fragment program" RB_NV20_SpecularColorFragment(); // override one parameter for inverted vertex color if ( din->vertexColor == SVC_INVERSE_MODULATE ) { qglCombinerInputNV( GL_COMBINER3_NV, GL_RGB, GL_VARIABLE_B_NV, GL_PRIMARY_COLOR_NV, GL_UNSIGNED_INVERT_NV, GL_RGB ); } // draw it qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, VPROG_NV20_SPECULAR_COLOR ); RB_DrawElementsWithCounters( din->surf->geo ); } /* ================== RB_NV20_DiffuseAndSpecularColorFragment ================== */ static void RB_NV20_DiffuseAndSpecularColorFragment( void ) { if ( r_useCombinerDisplayLists.GetBool() ) { qglCallList( fragmentDisplayListBase + FPROG_DIFFUSE_AND_SPECULAR_COLOR ); return; } // program the nvidia register combiners qglCombinerParameteriNV( GL_NUM_GENERAL_COMBINERS_NV, 3 ); // GL_CONSTANT_COLOR0_NV will be the diffuse color // GL_CONSTANT_COLOR1_NV will be the specular color // stage 0 rgb performs the dot product // GL_SECONDARY_COLOR_NV = ( TEXTURE0 dot TEXTURE1 - 0.5 ) * 2 // the scale and bias steepen the specular curve qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE1_ARB, GL_EXPAND_NORMAL_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE0_ARB, GL_EXPAND_NORMAL_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER0_NV, GL_RGB, GL_SECONDARY_COLOR_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_SCALE_BY_TWO_NV, GL_BIAS_BY_NEGATIVE_ONE_HALF_NV, GL_TRUE, GL_FALSE, GL_FALSE ); // stage 0 alpha does nothing // stage 1 color takes bump * bump // PRIMARY_COLOR = ( GL_SECONDARY_COLOR_NV * GL_SECONDARY_COLOR_NV - 0.5 ) * 2 // the scale and bias steepen the specular curve qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_SECONDARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_SECONDARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER1_NV, GL_RGB, GL_SECONDARY_COLOR_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_SCALE_BY_TWO_NV, GL_BIAS_BY_NEGATIVE_ONE_HALF_NV, GL_FALSE, GL_FALSE, GL_FALSE ); // stage 1 alpha does nothing // stage 2 color // PRIMARY_COLOR = ( PRIMARY_COLOR * TEXTURE3 ) * 2 // SPARE0 = 1.0 * 1.0 (needed for final combiner) qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_A_NV, GL_SECONDARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE3_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB ); qglCombinerInputNV( GL_COMBINER2_NV, GL_RGB, GL_VARIABLE_D_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB ); qglCombinerOutputNV( GL_COMBINER2_NV, GL_RGB, GL_SECONDARY_COLOR_NV, GL_SPARE0_NV, GL_DISCARD_NV, GL_SCALE_BY_TWO_NV, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); // stage 2 alpha does nothing // final combiner = TEXTURE2_ARB * CONSTANT_COLOR0_NV + PRIMARY_COLOR_NV * CONSTANT_COLOR1_NV // alpha = GL_ZERO qglFinalCombinerInputNV( GL_VARIABLE_A_NV, GL_CONSTANT_COLOR1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_B_NV, GL_SECONDARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_D_NV, GL_E_TIMES_F_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_E_NV, GL_TEXTURE2_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_F_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); qglFinalCombinerInputNV( GL_VARIABLE_G_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_ALPHA ); } /* ================== RB_NV20_DI_DiffuseAndSpecularColorPass ================== */ static void RB_NV20_DI_DiffuseAndSpecularColorPass( const drawInteraction_t *din ) { RB_LogComment( "---------- RB_NV20_DI_DiffuseAndSpecularColorPass ----------\n" ); GL_State( GLS_SRCBLEND_DST_ALPHA | GLS_DSTBLEND_ONE | GLS_DEPTHMASK | backEnd.depthFunc ); // texture 0 is the normalization cube map for the half angle // still bound from RB_NV_BumpAndLightPass // GL_SelectTextureNoClient( 0 ); // GL_Bind( tr.normalCubeMapImage ); // texture 1 is the per-surface bump map // still bound from RB_NV_BumpAndLightPass // GL_SelectTextureNoClient( 1 ); // GL_Bind( din->bumpImage ); // texture 2 is the per-surface diffuse map #ifdef MACOS_X GL_SelectTexture( 2 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 2 ); #endif din->diffuseImage->Bind(); // texture 3 is the per-surface specular map #ifdef MACOS_X GL_SelectTexture( 3 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 3 ); #endif din->specularImage->Bind(); // bind our "fragment program" RB_NV20_DiffuseAndSpecularColorFragment(); // draw it qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, VPROG_NV20_DIFFUSE_AND_SPECULAR_COLOR ); RB_DrawElementsWithCounters( din->surf->geo ); } /* ================== RB_NV20_DrawInteraction ================== */ static void RB_NV20_DrawInteraction( const drawInteraction_t *din ) { const drawSurf_t *surf = din->surf; // load all the vertex program parameters qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_LIGHT_ORIGIN, din->localLightOrigin.ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_VIEW_ORIGIN, din->localViewOrigin.ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_LIGHT_PROJECT_S, din->lightProjection[0].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_LIGHT_PROJECT_T, din->lightProjection[1].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_LIGHT_PROJECT_Q, din->lightProjection[2].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_LIGHT_FALLOFF_S, din->lightProjection[3].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_BUMP_MATRIX_S, din->bumpMatrix[0].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_BUMP_MATRIX_T, din->bumpMatrix[1].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_DIFFUSE_MATRIX_S, din->diffuseMatrix[0].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_DIFFUSE_MATRIX_T, din->diffuseMatrix[1].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_SPECULAR_MATRIX_S, din->specularMatrix[0].ToFloatPtr() ); qglProgramEnvParameter4fvARB( GL_VERTEX_PROGRAM_ARB, PP_SPECULAR_MATRIX_T, din->specularMatrix[1].ToFloatPtr() ); // set the constant colors qglCombinerParameterfvNV( GL_CONSTANT_COLOR0_NV, din->diffuseColor.ToFloatPtr() ); qglCombinerParameterfvNV( GL_CONSTANT_COLOR1_NV, din->specularColor.ToFloatPtr() ); // vertex color passes should be pretty rare (cross-faded bump map surfaces), so always // run them down as three-passes if ( din->vertexColor != SVC_IGNORE ) { qglEnableClientState( GL_COLOR_ARRAY ); RB_NV20_DI_BumpAndLightPass( din, false ); RB_NV20_DI_DiffuseColorPass( din ); RB_NV20_DI_SpecularColorPass( din ); qglDisableClientState( GL_COLOR_ARRAY ); return; } qglColor3f( 1, 1, 1 ); // on an ideal card, we would now just bind the textures and call a // single pass vertex / fragment program, but // on NV20, we need to decide which single / dual / tripple pass set of programs to use // ambient light could be done as a single pass if we want to optimize for it // monochrome light is two passes int internalFormat = din->lightImage->internalFormat; if ( ( r_useNV20MonoLights.GetInteger() == 2 ) || ( din->lightImage->isMonochrome && r_useNV20MonoLights.GetInteger() ) ) { // do a two-pass rendering RB_NV20_DI_BumpAndLightPass( din, true ); RB_NV20_DI_DiffuseAndSpecularColorPass( din ); } else { // general case is three passes // ( bump dot lightDir ) * lightFalloff // diffuse * lightProject // specular * ( bump dot halfAngle extended ) * lightProject RB_NV20_DI_BumpAndLightPass( din, false ); RB_NV20_DI_DiffuseColorPass( din ); RB_NV20_DI_SpecularColorPass( din ); } } /* ============= RB_NV20_CreateDrawInteractions ============= */ static void RB_NV20_CreateDrawInteractions( const drawSurf_t *surf ) { if ( !surf ) { return; } qglEnable( GL_VERTEX_PROGRAM_ARB ); qglEnable( GL_REGISTER_COMBINERS_NV ); #ifdef MACOS_X GL_SelectTexture(0); qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); #else qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); qglEnableVertexAttribArrayARB( 8 ); qglEnableVertexAttribArrayARB( 9 ); qglEnableVertexAttribArrayARB( 10 ); qglEnableVertexAttribArrayARB( 11 ); #endif for ( ; surf ; surf=surf->nextOnLight ) { // set the vertex pointers idDrawVert *ac = (idDrawVert *)vertexCache.Position( surf->geo->ambientCache ); qglColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( idDrawVert ), ac->color ); #ifdef MACOS_X GL_SelectTexture( 0 ); qglTexCoordPointer( 2, GL_FLOAT, sizeof( idDrawVert ), ac->st.ToFloatPtr() ); GL_SelectTexture( 1 ); qglTexCoordPointer( 3, GL_FLOAT, sizeof( idDrawVert ), ac->tangents[0].ToFloatPtr() ); GL_SelectTexture( 2 ); qglTexCoordPointer( 3, GL_FLOAT, sizeof( idDrawVert ), ac->tangents[1].ToFloatPtr() ); GL_SelectTexture( 3 ); qglTexCoordPointer( 3, GL_FLOAT, sizeof( idDrawVert ), ac->normal.ToFloatPtr() ); GL_SelectTexture( 0 ); #else qglVertexAttribPointerARB( 11, 3, GL_FLOAT, false, sizeof( idDrawVert ), ac->normal.ToFloatPtr() ); qglVertexAttribPointerARB( 10, 3, GL_FLOAT, false, sizeof( idDrawVert ), ac->tangents[1].ToFloatPtr() ); qglVertexAttribPointerARB( 9, 3, GL_FLOAT, false, sizeof( idDrawVert ), ac->tangents[0].ToFloatPtr() ); qglVertexAttribPointerARB( 8, 2, GL_FLOAT, false, sizeof( idDrawVert ), ac->st.ToFloatPtr() ); #endif qglVertexPointer( 3, GL_FLOAT, sizeof( idDrawVert ), ac->xyz.ToFloatPtr() ); RB_CreateSingleDrawInteractions( surf, RB_NV20_DrawInteraction ); } #ifndef MACOS_X qglDisableVertexAttribArrayARB( 8 ); qglDisableVertexAttribArrayARB( 9 ); qglDisableVertexAttribArrayARB( 10 ); qglDisableVertexAttribArrayARB( 11 ); #endif // disable features #ifdef MACOS_X GL_SelectTexture( 3 ); globalImages->BindNull(); qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); GL_SelectTexture( 2 ); globalImages->BindNull(); qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); GL_SelectTexture( 1 ); globalImages->BindNull(); qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); #else GL_SelectTextureNoClient( 3 ); globalImages->BindNull(); GL_SelectTextureNoClient( 2 ); globalImages->BindNull(); GL_SelectTextureNoClient( 1 ); globalImages->BindNull(); #endif backEnd.glState.currenttmu = -1; GL_SelectTexture( 0 ); qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); qglDisable( GL_VERTEX_PROGRAM_ARB ); qglDisable( GL_REGISTER_COMBINERS_NV ); } //====================================================================================== /* ================== RB_NV20_DrawInteractions ================== */ void RB_NV20_DrawInteractions( void ) { viewLight_t *vLight; // // for each light, perform adding and shadowing // for ( vLight = backEnd.viewDef->viewLights ; vLight ; vLight = vLight->next ) { // do fogging later if ( vLight->lightShader->IsFogLight() ) { continue; } if ( vLight->lightShader->IsBlendLight() ) { continue; } if ( !vLight->localInteractions && !vLight->globalInteractions && !vLight->translucentInteractions ) { continue; } backEnd.vLight = vLight; RB_LogComment( "---------- RB_RenderViewLight 0x%p ----------\n", vLight ); // clear the stencil buffer if needed if ( vLight->globalShadows || vLight->localShadows ) { backEnd.currentScissor = vLight->scissorRect; if ( r_useScissor.GetBool() ) { qglScissor( backEnd.viewDef->viewport.x1 + backEnd.currentScissor.x1, backEnd.viewDef->viewport.y1 + backEnd.currentScissor.y1, backEnd.currentScissor.x2 + 1 - backEnd.currentScissor.x1, backEnd.currentScissor.y2 + 1 - backEnd.currentScissor.y1 ); } qglClear( GL_STENCIL_BUFFER_BIT ); } else { // no shadows, so no need to read or write the stencil buffer // we might in theory want to use GL_ALWAYS instead of disabling // completely, to satisfy the invarience rules qglStencilFunc( GL_ALWAYS, 128, 255 ); } backEnd.depthFunc = GLS_DEPTHFUNC_EQUAL; if ( r_useShadowVertexProgram.GetBool() ) { qglEnable( GL_VERTEX_PROGRAM_ARB ); qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, VPROG_STENCIL_SHADOW ); RB_StencilShadowPass( vLight->globalShadows ); RB_NV20_CreateDrawInteractions( vLight->localInteractions ); qglEnable( GL_VERTEX_PROGRAM_ARB ); qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, VPROG_STENCIL_SHADOW ); RB_StencilShadowPass( vLight->localShadows ); RB_NV20_CreateDrawInteractions( vLight->globalInteractions ); qglDisable( GL_VERTEX_PROGRAM_ARB ); // if there weren't any globalInteractions, it would have stayed on } else { RB_StencilShadowPass( vLight->globalShadows ); RB_NV20_CreateDrawInteractions( vLight->localInteractions ); RB_StencilShadowPass( vLight->localShadows ); RB_NV20_CreateDrawInteractions( vLight->globalInteractions ); } // translucent surfaces never get stencil shadowed if ( r_skipTranslucent.GetBool() ) { continue; } qglStencilFunc( GL_ALWAYS, 128, 255 ); backEnd.depthFunc = GLS_DEPTHFUNC_LESS; RB_NV20_CreateDrawInteractions( vLight->translucentInteractions ); backEnd.depthFunc = GLS_DEPTHFUNC_EQUAL; } } //======================================================================= /* ================== R_NV20_Init ================== */ void R_NV20_Init( void ) { glConfig.allowNV20Path = false; common->Printf( "---------- R_NV20_Init ----------\n" ); if ( !glConfig.registerCombinersAvailable || !glConfig.ARBVertexProgramAvailable || glConfig.maxTextureUnits < 4 ) { common->Printf( "Not available.\n" ); return; } GL_CheckErrors(); // create our "fragment program" display lists fragmentDisplayListBase = qglGenLists( FPROG_NUM_FRAGMENT_PROGRAMS ); // force them to issue commands to build the list bool temp = r_useCombinerDisplayLists.GetBool(); r_useCombinerDisplayLists.SetBool( false ); qglNewList( fragmentDisplayListBase + FPROG_BUMP_AND_LIGHT, GL_COMPILE ); RB_NV20_BumpAndLightFragment(); qglEndList(); qglNewList( fragmentDisplayListBase + FPROG_DIFFUSE_COLOR, GL_COMPILE ); RB_NV20_DiffuseColorFragment(); qglEndList(); qglNewList( fragmentDisplayListBase + FPROG_SPECULAR_COLOR, GL_COMPILE ); RB_NV20_SpecularColorFragment(); qglEndList(); qglNewList( fragmentDisplayListBase + FPROG_DIFFUSE_AND_SPECULAR_COLOR, GL_COMPILE ); RB_NV20_DiffuseAndSpecularColorFragment(); qglEndList(); r_useCombinerDisplayLists.SetBool( temp ); common->Printf( "---------------------------------\n" ); glConfig.allowNV20Path = true; }
Extant-1/ThieVR
renderer/draw_nv20.cpp
C++
gpl-3.0
29,712
(function () { angular .module("WebAppMaker") .controller("EditPageController", EditPageController) .controller("PageListController", PageListController) .controller("NewPageController", NewPageController); function EditPageController(PageService, $routeParams, $location) { var vm = this; vm.updatePage = updatePage; vm.deletePage = deletePage; vm.userId = $routeParams['uid']; vm.websiteId = $routeParams['wid']; vm.pageId = $routeParams['pid']; function init() { PageService.findPageById(vm.pageId) .then( res => { vm.page = res.data; }, res => { vm.pageNotFound = true; }); } init(); function updatePage(page) { PageService.updatePage( vm.pageId, page ) .then( res => { $location.url(`/user/${vm.userId}/website/${vm.websiteId}/page`); }, res => { vm.errorUpdating = true; }); } function deletePage() { PageService.deletePage(vm.pageId) .then( res => { $location.url(`/user/${ vm.userId }/website/${ vm.websiteId }/page`); }, res => { vm.errorDeleting = true; }); } }; function PageListController(PageService, $routeParams) { var vm = this; var userId = $routeParams.uid; var websiteId = $routeParams.wid; vm.userId = userId; vm.websiteId = websiteId; function init() { PageService.findPagesByWebsiteId( vm.websiteId ) .then( res => { vm.pages = res.data; }, res => { vm.error = true; }); } init(); }; function NewPageController(PageService, $routeParams, $location) { var vm = this; vm.create = create; function init() { vm.userId = $routeParams.uid; vm.websiteId = $routeParams.wid; PageService.findPagesByWebsiteId( vm.websiteId ) .then( res => { vm.pages = res.data; }, res => { vm.error = true; }); } init(); function create(newPage) { PageService.createPage( vm.websiteId, newPage ) .then( res => { $location.url(`/user/${ vm.userId }/website/${ vm.websiteId }/page`); }, res => { vm.errorCreating = true; }); } }; })();
knuevena/knueven-andrew-webdev
public/assignment/views/page/page.controller.client.js
JavaScript
gpl-3.0
2,586
from django.contrib import admin #from .models import Tag #import sys #import importlib #importlib.reload(sys) #admin.site.register(Tag) # Register your models here.
summerzhangft/summer
tag/admin.py
Python
gpl-3.0
167
package is.idega.idegaweb.campus.business; import javax.ejb.CreateException; import com.idega.business.IBOHomeImpl; public class ContractRenewalServiceHomeImpl extends IBOHomeImpl implements ContractRenewalServiceHome { public Class getBeanInterfaceClass() { return ContractRenewalService.class; } public ContractRenewalService create() throws CreateException { return (ContractRenewalService) super.createIBO(); } }
idega/platform2
src/is/idega/idegaweb/campus/business/ContractRenewalServiceHomeImpl.java
Java
gpl-3.0
430
//======================================================================= // Author: Donovan Parks // // Copyright 2009 Donovan Parks // // This file is part of Chameleon. // // Chameleon 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. // // Chameleon 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 Chameleon. If not, see <http://www.gnu.org/licenses/>. //======================================================================= #ifndef AUTO_COLLAPSE_DLG_HPP #define AUTO_COLLAPSE_DLG_HPP #include "ui_AutoCollapseDialog.h" #include "stdafx.h" #include "VisualTree.hpp" class AutoCollapseDlg : public QDockWidget { Q_OBJECT public: AutoCollapseDlg(QWidget *parent = 0, Qt::WFlags flags = 0); ~AutoCollapseDlg() {} VisualTree::AUTO_COLLAPSE_CONSTRAINT GetCollapseVariable(); float GetCollapseConstraint() { return ui.spinFilterValue->value(); } signals: void Run(); private slots: void Execute(); void TopLevelChanged(bool bFloating); private: Ui::AutoCollapseDlg ui; }; #endif
dparks1134/Chameleon
Src/AutoCollapseDlg.hpp
C++
gpl-3.0
1,457
package org.reunionemu.jreunion.model.quests.restrictions; import org.reunionemu.jreunion.model.quests.Restriction; /** * @author Aidamina * @license http://reunion.googlecode.com/svn/trunk/license.txt */ public interface RaceRestriction extends Restriction { public Integer getId(); }
ReunionDev/reunion
jreunion/src/main/java/org/reunionemu/jreunion/model/quests/restrictions/RaceRestriction.java
Java
gpl-3.0
294
using System.Timers; using Artemis.Core.Services; using Artemis.UI.Services; using Stylet; namespace Artemis.UI.Screens.Header { public class SimpleHeaderViewModel : Screen { private readonly ICoreService _coreService; private readonly IDebugService _debugService; private string _frameTime; private Timer _frameTimeUpdateTimer; public SimpleHeaderViewModel(string displayName, ICoreService coreService, IDebugService debugService) { DisplayName = displayName; _coreService = coreService; _debugService = debugService; } public string FrameTime { get => _frameTime; set => SetAndNotify(ref _frameTime, value); } public void ShowDebugger() { _debugService.ShowDebugger(); } private void UpdateFrameTime() { FrameTime = $"Frame time: {_coreService.FrameTime.TotalMilliseconds:F2} ms"; } private void OnFrameTimeUpdateTimerOnElapsed(object sender, ElapsedEventArgs args) { UpdateFrameTime(); } #region Overrides of Screen /// <inheritdoc /> protected override void OnInitialActivate() { _frameTimeUpdateTimer = new Timer(500); _frameTimeUpdateTimer.Elapsed += OnFrameTimeUpdateTimerOnElapsed; _frameTimeUpdateTimer.Start(); UpdateFrameTime(); base.OnInitialActivate(); } /// <inheritdoc /> protected override void OnClose() { _frameTimeUpdateTimer.Elapsed -= OnFrameTimeUpdateTimerOnElapsed; _frameTimeUpdateTimer?.Dispose(); _frameTimeUpdateTimer = null; base.OnClose(); } #endregion } }
SpoinkyNL/Artemis
src/Artemis.UI/Screens/Header/SimpleHeaderViewModel.cs
C#
gpl-3.0
1,857
package fi.otavanopisto.pyramus.domainmodel.clientapplications; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.TableGenerator; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; @Entity public class ClientApplicationAccessToken { public Long getId() { return id; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public Long getExpires() { return expires; } public void setExpires(Long expires) { this.expires = expires; } public ClientApplication getClientApplication() { return clientApplication; } public void setClientApplication(ClientApplication clientApplication) { this.clientApplication = clientApplication; } public ClientApplicationAuthorizationCode getClientApplicationAuthorizationCode() { return clientApplicationAuthorizationCode; } public void setClientApplicationAuthorizationCode(ClientApplicationAuthorizationCode clientApplicationAuthorizationCode) { this.clientApplicationAuthorizationCode = clientApplicationAuthorizationCode; } public String getRefreshToken() { return refreshToken; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "ClientApplicationAccessToken") @TableGenerator(name = "ClientApplicationAccessToken", allocationSize = 1, table = "hibernate_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_next_hi_value") private Long id; @NotNull @NotEmpty @Column(nullable = false, unique=true) private String accessToken; @NotEmpty @Column(nullable = false) private String refreshToken; @NotNull @Column(nullable = false) private Long expires; @NotNull @ManyToOne @JoinColumn(name = "app_id", nullable = false) private ClientApplication clientApplication; @NotNull @OneToOne @JoinColumn(name = "clientApplicationAuthorizationCode", unique = true, nullable = false) private ClientApplicationAuthorizationCode clientApplicationAuthorizationCode; }
otavanopisto/pyramus
persistence/src/main/java/fi/otavanopisto/pyramus/domainmodel/clientapplications/ClientApplicationAccessToken.java
Java
gpl-3.0
2,460
<?php $cantresidencias = Doctrine::getTable('Funcionarios_Residencia')->findByFuncionarioIdAndStatus(sfContext::getInstance()->getUser()->getAttribute('funcionario_id'),'A'); if ($cantresidencias[0]!=''){ foreach($cantresidencias as $residencia): $estados = Doctrine::getTable('Public_Estado')->findById($residencia->getEstadoId()); $municipios = Doctrine::getTable('Public_Municipio')->findById($residencia->getMunicipioId()); $parroquias = Doctrine::getTable('Public_Parroquia')->findById($residencia->getParroquiaId()); $id = $residencia->getId(); ?> <div align="right" style="position: relative; right: 5px; top: 5px;"> <a style="right: 0px;" title="Editar" href="#" onclick="javascript:abrir_notificacion_derecha('infoResidencial?residencia_accion=editar&res_id=<?php echo $id; ?>'); return false;"> <?php echo image_tag('icon/edit.png'); ?> </a> &nbsp;&nbsp;&nbsp; <a style="right: 0px;" title="Eliminar" href="<?php echo url_for('ficha/eliminarResidencia?res_id='.$id) ?>" onclick="javascript:if(confirm('Esta seguro de eliminar?')){return true}else{return false};"> <?php echo image_tag('icon/delete.png'); ?> </a> </div> <div class="sf_admin_form_row sf_admin_text"> <div> <label style="width: 10em;" for="">Dirección:</label> <div class="content"> &nbsp; </div> </div> </div> <div class="sf_admin_form_row sf_admin_text"> <div class=""> <?php echo $residencia->getDirAvCalleEsq(); ?>&nbsp;<br> Urb. <?php echo $residencia->getDirUrbanizacion(); ?>&nbsp; , Edif/casa: <?php echo $residencia->getDirEdfCasa(); ?>&nbsp;<br> Piso: <?php echo $residencia->getDirPiso(); ?>&nbsp;, Apto/Nombre: <?php echo $residencia->getDirAptNombre(); ?>&nbsp;<br> Ciudad: <?php echo $residencia->getDirCiudad(); ?>&nbsp; <br> Estado: <?php echo $estados[0]; ?>&nbsp;/ municipio <?php echo $municipios[0]; ?>&nbsp; / parroquia <?php echo $parroquias[0]; ?>&nbsp; <br> Pto de referencia: <?php echo $residencia->getDirPuntoReferencia(); ?>&nbsp; <br> Telefonos: <?php echo $residencia->getTelfUno(); ?>, <?php echo $residencia->getTelfDos(); ?>&nbsp; </div> </div> <?php endforeach; ?> <?php } else { ?> <div class="sf_admin_form_row sf_admin_text" style="min-height: 70px;"> <div class="f16n gris_medio" style="text-align: justify;"> Tu información residencial es importante, ............... </div> </div> <?php } ?>
mwveliz/siglas-mppp
apps/funcionarios/modules/ficha/templates/_info_residencial.php
PHP
gpl-3.0
2,604
// accurate implementation of the complex expm1 function #include <complex> #include "Rcpp.h" using namespace std; complex<double> expm1c(complex<double> z) { complex<double> ii(0,1); return exp(imag(z)*ii) * expm1(real(z)) + ii * sin(imag(z)) - 2 * sin(imag(z)/2) * sin(imag(z)/2); }
piotrek-orlowski/affineModelR
src/expm1c.cpp
C++
gpl-3.0
290
<?php class Sesion { private static $id; public static function crearSesion() { session_start(); } public static function destruirSesion() { session_start(); session_unset(); session_destroy(); self::$id = null; } public static function getId() { return self::$id; } public static function setId() { //session_regenerate_id(); self::$id = session_id(); } public static function setValor(string $clave, string $valor) { $_SESSION[$clave] = $valor; } public static function getValor(string $clave) { return $_SESSION[$clave]; } }
UNAH-SISTEMAS/2017-1PAC-POO
313_clase_sesion/sesion.class.php
PHP
gpl-3.0
701
volScalarField& alpha2(mixture.alpha2()); const dimensionedScalar& rho1 = mixture.rho1(); const dimensionedScalar& rho2 = mixture.rho2(); twoPhaseChangeModel& phaseChange = phaseChangePtr(); tmp<volScalarField> rAU;
OpenFOAM/OpenFOAM-dev
applications/solvers/multiphase/interFoam/createFieldRefs.H
C++
gpl-3.0
218
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jul 22 17:01:36 2019 @author: raf """ # IMPORT STUFF from pdb import set_trace as stop import copy import numpy as np from collections import OrderedDict import string as st import os import pandas as pd from vison.datamodel import cdp from vison.support import files from vison.fpa import fpa as fpamod from vison.metatests.metacal import MetaCal from vison.plot import plots_fpa as plfpa from vison.support import vcal, utils from vison.datamodel import core as vcore from vison.ogse import ogse from vison.inject import lib as ilib import matplotlib.cm as cm from matplotlib import pyplot as plt plt.switch_backend('TkAgg') from matplotlib.colors import Normalize # END IMPORT cols2keep = [ 'test', 'sn_ccd1', 'sn_ccd2', 'sn_ccd3', 'sn_roe', 'sn_rpsu', 'exptime', 'vstart', 'vend', 'rdmode', 'flushes', 'siflsh', 'siflsh_p', 'swellw', 'swelldly', 'inisweep', 'cdpu_clk', 'chinj', 'chinj_on', 'chinj_of', 'id_wid', 'id_dly', 'chin_dly', 'v_tpump', 's_tpump', 'v_tp_mod', 's_tp_mod', 'v_tp_cnt', 's_tp_cnt', 'dwell_v', 'dwell_s', 'toi_fl', 'toi_tp', 'toi_ro', 'toi_ch', 'motr', 'motr_cnt', 'motr_siz', 'source', 'wave', 'mirr_on', 'mirr_pos', 'R1C1_TT', 'R1C1_TB', 'R1C2_TT', 'R1C2_TB', 'R1C3_TT', 'R1C3_TB', 'IDL', 'IDH', 'IG1_1_T', 'IG1_2_T', 'IG1_3_T', 'IG1_1_B', 'IG1_2_B', 'IG1_3_B', 'IG2_T', 'IG2_B', 'OD_1_T', 'OD_2_T', 'OD_3_T', 'OD_1_B', 'OD_2_B', 'OD_3_B', 'RD_T', 'RD_B', 'time', 'HK_CCD1_TEMP_T', 'HK_CCD2_TEMP_T', 'HK_CCD3_TEMP_T', 'HK_CCD1_TEMP_B', 'HK_CCD2_TEMP_B', 'HK_CCD3_TEMP_B', 'HK_CCD1_OD_T', 'HK_CCD2_OD_T', 'HK_CCD3_OD_T', 'HK_CCD1_OD_B', 'HK_CCD2_OD_B', 'HK_CCD3_OD_B', 'HK_COMM_RD_T', 'HK_COMM_RD_B', 'HK_CCD1_IG1_T', 'HK_CCD2_IG1_T', 'HK_CCD3_IG1_T', 'HK_CCD1_IG1_B', 'HK_CCD2_IG1_B', 'HK_CCD3_IG1_B', 'HK_COMM_IG2_T', 'HK_COMM_IG2_B', 'HK_FPGA_BIAS_ID2', 'HK_VID_PCB_TEMP_T', 'HK_VID_PCB_TEMP_B', 'HK_RPSU_TEMP1', 'HK_FPGA_PCB_TEMP_T', 'HK_FPGA_PCB_TEMP_B', 'HK_RPSU_TEMP_2', 'HK_RPSU_28V_PRI_I', 'chk_NPIXOFF', 'chk_NPIXSAT', 'offset_pre', 'offset_ove', 'std_pre', 'std_ove'] class MetaChinj01(MetaCal): """ """ def __init__(self, **kwargs): """ """ super(MetaChinj01, self).__init__(**kwargs) self.testnames = ['CHINJ01'] self.incols = cols2keep self.ParsedTable = OrderedDict() allgains = files.cPickleRead(kwargs['cdps']['gain']) self.cdps['GAIN'] = OrderedDict() for block in self.blocks: self.cdps['GAIN'][block] = allgains[block]['PTC01'].copy() self.products['METAFIT'] = OrderedDict() self.products['VERPROFILES'] = OrderedDict() self.products['HORPROFILES'] = OrderedDict() self.init_fignames() self.init_outcdpnames() def parse_single_test(self, jrep, block, testname, inventoryitem): """ """ NCCDs = len(self.CCDs) NQuads = len(self.Quads) session = inventoryitem['session'] CCDkeys = ['CCD%i' % CCD for CCD in self.CCDs] IndexS = vcore.vMultiIndex([vcore.vIndex('ix', vals=[0])]) IndexCQ = vcore.vMultiIndex([vcore.vIndex('ix', vals=[0]), vcore.vIndex('CCD', vals=self.CCDs), vcore.vIndex('Quad', vals=self.Quads)]) #idd = copy.deepcopy(inventoryitem['dd']) sidd = self.parse_single_test_gen(jrep, block, testname, inventoryitem) # TEST SCPECIFIC # TO BE ADDED: # OFFSETS: pre, img, ove # RON: pre, img, ove # REFERENCES TO PROFILES CHAMBER = sidd.meta['inputs']['CHAMBER'] CHAMBER_key = CHAMBER[0] chamber_v = np.array([CHAMBER_key]) sidd.addColumn(chamber_v, 'CHAMBERKEY', IndexS, ix=0) block_v = np.array([block]) sidd.addColumn(block_v, 'BLOCK', IndexS, ix=0) test_v = np.array([jrep + 1]) sidd.addColumn(test_v, 'REP', IndexS, ix=0) test_v = np.array([session]) sidd.addColumn(test_v, 'SESSION', IndexS, ix=0) test_v = np.array([testname]) sidd.addColumn(test_v, 'TEST', IndexS, ix=0) productspath = os.path.join(inventoryitem['resroot'], 'products') metafitcdp_pick = os.path.join(productspath, os.path.split(sidd.products['METAFIT_CDP'])[-1]) metafitcdp = files.cPickleRead(metafitcdp_pick) metafit = copy.deepcopy(metafitcdp['data']['ANALYSIS']) metafitkey = '%s_%s_%s_%i' % (testname, block, session, jrep + 1) self.products['METAFIT'][metafitkey] = copy.deepcopy(metafit) metafitkey_v = np.array([metafitkey]) sidd.addColumn(metafitkey_v, 'METAFIT', IndexS, ix=0) metacdp_pick = os.path.join(productspath, os.path.split( sidd.products['META_CDP'])[-1]) # change to META_CDP metacdp = files.cPickleRead(metacdp_pick) meta = metacdp['data']['ANALYSIS'] # this is a pandas DataFrame tmp_v_CQ = np.zeros((1, NCCDs, NQuads)) bgd_adu_v = tmp_v_CQ.copy() ig1_thresh_v = tmp_v_CQ.copy() ig1_notch_v = tmp_v_CQ.copy() slope_v = tmp_v_CQ.copy() n_adu_v = tmp_v_CQ.copy() for iCCD, CCDk in enumerate(CCDkeys): for kQ, Q in enumerate(self.Quads): ixloc = np.where((meta['CCD'] == iCCD + 1) & (meta['Q'] == kQ + 1)) bgd_adu_v[0, iCCD, kQ] = meta['BGD_ADU'][ixloc[0][0]] ig1_thresh_v[0, iCCD, kQ] = meta['IG1_THRESH'][ixloc[0][0]] ig1_notch_v[0, iCCD, kQ] = meta['IG1_NOTCH'][ixloc[0][0]] slope_v[0, iCCD, kQ] = meta['S'][ixloc[0][0]] n_adu_v[0, iCCD, kQ] = meta['N_ADU'][ixloc[0][0]] sidd.addColumn(bgd_adu_v, 'FIT_BGD_ADU', IndexCQ) sidd.addColumn(ig1_thresh_v, 'FIT_IG1_THRESH', IndexCQ) sidd.addColumn(ig1_notch_v, 'FIT_IG1_NOTCH', IndexCQ) sidd.addColumn(slope_v, 'FIT_SLOPE', IndexCQ) sidd.addColumn(n_adu_v, 'FIT_N_ADU', IndexCQ) # charge injection profiles verprofspick = os.path.join(productspath, os.path.split(sidd.products['PROFS_ALCOL'])[-1]) verprofs = files.cPickleRead(verprofspick) vprofkey = '%s_%s_%s_%i' % (testname, block, session, jrep + 1) self.products['VERPROFILES'][vprofkey] = verprofs.copy() vprofskeys_v = np.zeros((1),dtype='U50') vprofskeys_v[0] = vprofkey sidd.addColumn(vprofskeys_v, 'VERPROFS_KEY', IndexS) horprofspick = os.path.join(productspath, os.path.split(sidd.products['PROFS_ALROW'])[-1]) horprofs = files.cPickleRead(horprofspick) hprofkey = '%s_%s_%s_%i' % (testname, block, session, jrep + 1) self.products['HORPROFILES'][hprofkey] = horprofs.copy() hprofskeys_v = np.zeros((1),dtype='U50') hprofskeys_v[0] = hprofkey sidd.addColumn(hprofskeys_v, 'HORPROFS_KEY', IndexS) # flatten sidd to table sit = sidd.flattentoTable() return sit def _get_extractor_NOTCH_fromPT(self, units): """ """ def _extract_NOTCH_fromPT(PT, block, CCDk, Q): ixblock = self.get_ixblock(PT, block) column = 'FIT_N_ADU_%s_Quad%s' % (CCDk, Q) if units == 'ADU': unitsConvFactor = 1 elif units == 'E': unitsConvFactor = self.cdps['GAIN'][block][CCDk][Q][0] Notch = np.nanmedian(PT[column][ixblock]) * unitsConvFactor return Notch return _extract_NOTCH_fromPT def _get_injcurve(self, _chfitdf, ixCCD, ixQ, IG1raw, gain): """ """ ixsel = np.where((_chfitdf['CCD'] == ixCCD) & (_chfitdf['Q'] == ixQ)) pars = ['BGD', 'K', 'XT', 'XN', 'A', 'N'] trans = dict(BGD='b', K='k', XT='xt', XN='xN', A='a', N='N') parsdict = dict() for par in pars: parsdict[trans[par]] = _chfitdf[par].values[ixsel][0] parsdict['IG1'] = IG1raw.copy() inj = ilib.f_Inj_vs_IG1_ReLU(**parsdict) * 2.**16 # ADU inj_kel = inj * gain / 1.E3 return inj_kel def _get_CHIG1_MAP_from_PT(self, kind='CAL'): """ """ CHIG1MAP = OrderedDict() CHIG1MAP['labelkeys'] = self.Quads PT = self.ParsedTable['CHINJ01'] column = 'METAFIT' IG1s = [2.5, 6.75] dIG1 = 0.05 NIG1 = (IG1s[1] - IG1s[0]) / dIG1 + 1 IG1raw = np.arange(NIG1) * dIG1 + IG1s[0] for jY in range(self.NSLICES_FPA): for iX in range(self.NCOLS_FPA): Ckey = 'C_%i%i' % (jY + 1, iX + 1) CHIG1MAP[Ckey] = OrderedDict() locator = self.fpa.FPA_MAP[Ckey] block = locator[0] CCDk = locator[1] jCCD = int(CCDk[-1]) ixblock = np.where(PT['BLOCK'] == block) if len(ixblock[0]) == 0: CHIG1MAP[Ckey] = OrderedDict(x=OrderedDict(), y=OrderedDict()) for Q in self.Quads: CHIG1MAP[Ckey]['x'][Q] = [] CHIG1MAP[Ckey]['y'][Q] = [] continue _chkey = PT[column][ixblock][0] _chfitdf = self.products['METAFIT'][_chkey] _ccd_chfitdict = OrderedDict(x=OrderedDict(), y=OrderedDict()) for kQ, Q in enumerate(self.Quads): roeVCal = self.roeVCals[block] IG1cal = roeVCal.fcal_HK(IG1raw, 'IG1', jCCD, Q) gain = self.cdps['GAIN'][block][CCDk][Q][0] inj_kel = self._get_injcurve(_chfitdf, jCCD, kQ + 1, IG1raw, gain) if kind == 'CAL': _IG1 = IG1cal.copy() elif kind == 'RAW': _IG1 = IG1raw.copy() _ccd_chfitdict['x'][Q] = _IG1.copy() _ccd_chfitdict['y'][Q] = inj_kel.copy() CHIG1MAP[Ckey] = _ccd_chfitdict.copy() return CHIG1MAP def _get_XYdict_INJ(self, kind='CAL'): x = dict() y = dict() PT = self.ParsedTable['CHINJ01'] column = 'METAFIT' IG1s = [2.5, 6.75] dIG1 = 0.05 NIG1 = (IG1s[1] - IG1s[0]) / dIG1 + 1 IG1raw = np.arange(NIG1) * dIG1 + IG1s[0] labelkeys = [] for block in self.flight_blocks: ixblock = np.where(PT['BLOCK'] == block) ch_key = PT[column][ixblock][0] chfitdf = self.products['METAFIT'][ch_key] for iCCD, CCD in enumerate(self.CCDs): CCDk = 'CCD%i' % CCD for kQ, Q in enumerate(self.Quads): roeVCal = self.roeVCals[block] IG1cal = roeVCal.fcal_HK(IG1raw, 'IG1', iCCD + 1, Q) gain = self.cdps['GAIN'][block][CCDk][Q][0] if kind == 'CAL': _IG1 = IG1cal.copy() elif kind == 'RAW': _IG1 = IG1raw.copy() pkey = '%s_%s_%s' % (block, CCDk, Q) inj_kel = self._get_injcurve(chfitdf, iCCD + 1, kQ + 1, IG1raw, gain) x[pkey] = _IG1.copy() y[pkey] = inj_kel.copy() labelkeys.append(pkey) CHdict = dict(x=x, y=y, labelkeys=labelkeys) return CHdict def _extract_INJCURVES_PAR_fromPT(self,PT,block,CCDk,Q): """ """ ixblock = self.get_ixblock(PT,block) column = 'METAFIT' ch_key = PT[column][ixblock][0] chfitdf = self.products['METAFIT'][ch_key] ixCCD = ['CCD1','CCD2','CCD3'].index(CCDk)+1 ixQ = ['E','F','G','H'].index(Q)+1 ixsel = np.where((chfitdf['CCD'] == ixCCD) & (chfitdf['Q'] == ixQ)) pars = ['BGD', 'K', 'XT', 'XN', 'A', 'N'] trans = dict(BGD='b', K='k', XT='xt', XN='xN', A='a', N='N') parsdict = dict() for par in pars: parsdict[trans[par]] = '%.3e' % chfitdf[par].values[ixsel][0] return parsdict def _get_XYdict_PROFS(self,proftype, IG1=4.5, Quads=None, doNorm=False, xrangeNorm=None): """ """ if Quads is None: Quads = self.Quads x = dict() y = dict() labelkeys = [] PT = self.ParsedTable['CHINJ01'] profcol = '%sPROFS_KEY' % proftype.upper() prodkey = '%sPROFILES' % proftype.upper() for block in self.flight_blocks: ixsel = np.where(PT['BLOCK'] == block) prof_key = PT[profcol][ixsel][0] i_Prof = self.products[prodkey][prof_key].copy() IG1key = 'IG1_%.2fV' % IG1 for iCCD, CCD in enumerate(self.CCDs): CCDk = 'CCD%i' % CCD for kQ, Q in enumerate(Quads): pkey = '%s_%s_%s' % (block, CCDk, Q) _pcq = i_Prof['data'][CCDk][Q].copy() _x = _pcq['x'][IG1key].copy() _y = _pcq['y'][IG1key].copy() x[pkey] = _x if doNorm: if xrangeNorm is not None: norm = np.nanmedian(_y[xrangeNorm[0]:xrangeNorm[1]]) else: norm = np.nanmedian(_y) y[pkey] = _y / norm labelkeys.append(pkey) Pdict = dict(x=x,y=y,labelkeys=labelkeys) return Pdict def init_fignames(self): """ """ if not os.path.exists(self.figspath): os.system('mkdir %s' % self.figspath) self.figs['NOTCH_ADU_MAP'] = os.path.join(self.figspath, 'NOTCH_ADU_MAP.png') self.figs['NOTCH_ELE_MAP'] = os.path.join(self.figspath, 'NOTCH_ELE_MAP.png') self.figs['CHINJ01_curves_IG1_RAW'] = os.path.join(self.figspath, 'CHINJ01_CURVES_IG1_RAW.png') self.figs['CHINJ01_curves_IG1_CAL'] = os.path.join(self.figspath, 'CHINJ01_CURVES_IG1_CAL.png') self.figs['CHINJ01_curves_MAP_IG1_CAL'] = os.path.join(self.figspath, 'CHINJ01_CURVES_MAP_IG1_CAL.png') for proftype in ['ver','hor']: for ccdhalf in ['top','bot']: figkey = 'PROFS_%s_%s' % (proftype.upper(),ccdhalf.upper()) self.figs[figkey] = os.path.join(self.figspath, 'CHINJ01_%s_%s_PROFILES.png' % \ (proftype.upper(),ccdhalf.upper())) for ccdhalf in ['top','bot']: figkey = 'PROFS_ver_%s_ZOOM' % (ccdhalf.upper(),) self.figs[figkey] = os.path.join(self.figspath, 'CHINJ01_ver_%s_ZOOM_PROFILES.png' % \ (ccdhalf.upper()),) def init_outcdpnames(self): if not os.path.exists(self.cdpspath): os.system('mkdir %s' % self.cdpspath) self.outcdps['INJCURVES'] = 'CHINJ01_INJCURVES_PAR.json' self.outcdps['INJPROF_XLSX_HOR'] = 'CHINJ01_INJPROFILES_HOR.xlsx' self.outcdps['INJPROF_XLSX_VER'] = 'CHINJ01_INJPROFILES_VER.xlsx' self.outcdps['INJPROF_FITS_HOR'] = 'CHINJ01_INJPROFILES_HOR.fits' self.outcdps['INJPROF_FITS_VER'] = 'CHINJ01_INJPROFILES_VER.fits' def _extract_NUNHOR_fromPT(self, PT, block, CCDk, Q): """ """ IG1 = 4.5 ixblock = self.get_ixblock(PT, block) profcol = 'HORPROFS_KEY' prodkey = 'HORPROFILES' prof_key = PT[profcol][ixblock][0] i_Prof = self.products[prodkey][prof_key].copy() IG1key = 'IG1_%.2fV' % IG1 _pcq = i_Prof['data'][CCDk][Q].copy() _y = _pcq['y'][IG1key].copy() return np.nanstd(_y)/np.nanmean(_y)*100. def _get_injprof_dfdict(self, direction, pandice=False): """ """ injprofs = OrderedDict() Quads = self.Quads PT = self.ParsedTable['CHINJ01'] profcol = '{}PROFS_KEY'.format(direction.upper()) prodkey = '{}PROFILES'.format(direction.upper()) for ib, block in enumerate(self.flight_blocks): injprofs[block] = OrderedDict() ixsel = np.where(PT['BLOCK'] == block) prof_key = PT[profcol][ixsel][0] i_Prof = self.products[prodkey][prof_key].copy() if ib==0: rawIG1keys = list(i_Prof['data']['CCD1']['E']['x'].keys()) IG1values = [float(item.replace('IG1_','').replace('V','')) for item in rawIG1keys] _order = np.argsort(IG1values) IG1keys = np.array(rawIG1keys)[_order].tolist() IG1values = np.array(IG1values)[_order].tolist() for IG1key in IG1keys: for iCCD, CCD in enumerate(self.CCDs): CCDk = 'CCD%i' % CCD Ckey = self.fpa.get_Ckey_from_BlockCCD(block, CCD) for kQ, Q in enumerate(Quads): _pcq = i_Prof['data'][CCDk][Q].copy() _x = _pcq['x'][IG1key].copy() _y = _pcq['y'][IG1key].copy() #_y /= np.nanmedian(_y) if iCCD==0 and kQ==0: injprofs[block]['pixel'] = _x.copy() injprofs[block]['%s_%s_%s' % (Ckey,Q,IG1key)] = _y.copy() if pandice: for block in self.flight_blocks: injprofs[block] = pd.DataFrame.from_dict(injprofs[block]) return injprofs, IG1values def get_injprof_xlsx_cdp(self, direction, inCDP_header=None): """ """ CDP_header = OrderedDict() if CDP_header is not None: CDP_header.update(inCDP_header) cdpname = self.outcdps['INJPROF_XLSX_%s' % direction.upper()] path = self.cdpspath injprof_cdp = cdp.Tables_CDP() injprof_cdp.rootname = os.path.splitext(cdpname)[0] injprof_cdp.path = path injprofs_meta = OrderedDict() injprofs, IG1values = self._get_injprof_dfdict(direction, pandice=True) injprofs_meta['IG1'] = IG1values.__repr__() #injprofs_meta['norm'] = 'median' injprof_cdp.ingest_inputs(data=injprofs.copy(), meta=injprofs_meta.copy(), header=CDP_header.copy()) injprof_cdp.init_wb_and_fillAll( header_title='CHINJ01: INJPROFS-%s' % direction.upper()) return injprof_cdp def get_injprof_fits_cdp(self, direction, inCDP_header=None): """ """ CDP_header = OrderedDict() if inCDP_header is not None: CDP_header.update(inCDP_header) cdpname = self.outcdps['INJPROF_FITS_%s' % direction.upper()] path = self.cdpspath injprof_cdp = cdp.FitsTables_CDP() injprof_cdp.rootname = os.path.splitext(cdpname)[0] injprof_cdp.path = path injprofs_meta = OrderedDict() injprofs, IG1values = self._get_injprof_dfdict(direction, pandice=False) injprofs_meta['IG1'] = IG1values.__repr__() #injprofs_meta['norm'] = 'median' CDP_header = self.FITSify_CDP_header(CDP_header) injprof_cdp.ingest_inputs(data=injprofs.copy(), meta=injprofs_meta.copy(), header=CDP_header.copy()) injprof_cdp.init_HL_and_fillAll() injprof_cdp.hdulist[0].header.insert(list(CDP_header.keys())[0], ('title', 'CHINJ01: INJPROFS-%s' % direction.upper())) return injprof_cdp def dump_aggregated_results(self): """ """ if self.report is not None: self.report.add_Section(keyword='dump', Title='Aggregated Results', level=0) self.add_DataAlbaran2Report() function, module = utils.get_function_module() CDP_header = self.CDP_header.copy() CDP_header.update(dict(function=function, module=module)) CDP_header['DATE'] = self.get_time_tag() # Histogram of Slopes [ADU/electrons] # Histogram of Notch [ADU/electrons] # Histogram of IG1_THRESH # Injection level vs. Calibrated IG1, MAP CURVES_IG1CAL_MAP = self._get_CHIG1_MAP_from_PT(kind='CAL') figkey1 = 'CHINJ01_curves_MAP_IG1_CAL' figname1 = self.figs[figkey1] self.plot_XYMAP(CURVES_IG1CAL_MAP, **dict( suptitle='Charge Injection Curves - Calibrated IG1', doLegend=True, ylabel='Inj [kel]', xlabel='IG1 [V]', corekwargs=dict(E=dict(linestyle='-', marker='', color='r'), F=dict(linestyle='-', marker='', color='g'), G=dict(linestyle='-', marker='', color='b'), H=dict(linestyle='-', marker='', color='m')), figname=figname1 )) if self.report is not None: self.addFigure2Report(figname1, figkey=figkey1, caption='CHINJ01: Charge injection level [ke-] as a function of '+\ 'calibrated IG1 voltage.', texfraction=0.7) # saving charge injection parameters to a json CDP ICURVES_PAR_MAP = self.get_FPAMAP_from_PT( self.ParsedTable['CHINJ01'], extractor=self._extract_INJCURVES_PAR_fromPT) ic_header = OrderedDict() ic_header['title'] = 'Injection Curves Parameters' ic_header['test'] = 'CHINJ01' ic_header.update(CDP_header) ic_meta = OrderedDict() ic_meta['units'] ='/2^16 ADU', ic_meta['model'] = 'I=b+1/(1+exp(-K(IG1-XT))) * (-A*(IG1-XN)[IG1<XN] + N)' ic_meta['structure'] = '' ic_cdp = cdp.Json_CDP(rootname=self.outcdps['INJCURVES'], path=self.cdpspath) ic_cdp.ingest_inputs(data=ICURVES_PAR_MAP, header = ic_header, meta=ic_meta) ic_cdp.savehardcopy() # Injection level vs. Calibrated IG1, single plot IG1CAL_Singledict = self._get_XYdict_INJ(kind='CAL') figkey2 = 'CHINJ01_curves_IG1_CAL' figname2 = self.figs[figkey2] IG1CAL_kwargs = dict( title='Charge Injection Curves - Calibrated IG1', doLegend=False, xlabel='IG1 (Calibrated) [V]', ylabel='Injection [kel]', figname=figname2) corekwargs = dict() for block in self.flight_blocks: for iCCD in self.CCDs: corekwargs['%s_CCD%i_E' % (block, iCCD)] = dict(linestyle='-', marker='', color='#FF4600') # red corekwargs['%s_CCD%i_F' % (block, iCCD)] = dict(linestyle='-', marker='', color='#61FF00') # green corekwargs['%s_CCD%i_G' % (block, iCCD)] = dict(linestyle='-', marker='', color='#00FFE0') # cyan corekwargs['%s_CCD%i_H' % (block, iCCD)] = dict(linestyle='-', marker='', color='#1700FF') # blue IG1CAL_kwargs['corekwargs'] = corekwargs.copy() self.plot_XY(IG1CAL_Singledict, **IG1CAL_kwargs) if self.report is not None: self.addFigure2Report(figname2, figkey=figkey2, caption='CHINJ01: Charge injection level [ke-] as a function of '+\ 'calibrated IG1 voltage.', texfraction=0.7) # Injection level vs. Non-Calibrated IG1, single plot IG1RAW_Singledict = self._get_XYdict_INJ(kind='RAW') figkey3 = 'CHINJ01_curves_IG1_RAW' figname3 = self.figs[figkey3] IG1RAW_kwargs = dict( title='Charge Injection Curves - RAW IG1', doLegend=False, xlabel='IG1 (RAW) [V]', ylabel='Injection [kel]', figname=figname3) corekwargs = dict() for block in self.flight_blocks: for iCCD in self.CCDs: corekwargs['%s_CCD%i_E' % (block, iCCD)] = dict(linestyle='-', marker='', color='#FF4600') # red corekwargs['%s_CCD%i_F' % (block, iCCD)] = dict(linestyle='-', marker='', color='#61FF00') # green corekwargs['%s_CCD%i_G' % (block, iCCD)] = dict(linestyle='-', marker='', color='#00FFE0') # cyan corekwargs['%s_CCD%i_H' % (block, iCCD)] = dict(linestyle='-', marker='', color='#1700FF') # blue IG1RAW_kwargs['corekwargs'] = corekwargs.copy() self.plot_XY(IG1RAW_Singledict, **IG1RAW_kwargs) if self.report is not None: self.addFigure2Report(figname3, figkey=figkey3, caption='CHINJ01: Charge injection level [ke-] as a function of '+\ 'Non-calibrated IG1 voltage.', texfraction=0.7) # Notch level vs. calibrated IG2 # Notch level vs. calibrated IDL # Notch level vs. calibrated OD # Notch injection map, ADUs NOTCHADUMAP = self.get_FPAMAP_from_PT( self.ParsedTable['CHINJ01'], extractor=self._get_extractor_NOTCH_fromPT( units='ADU')) figkey4 = 'NOTCH_ADU_MAP' figname4 = self.figs[figkey4] self.plot_SimpleMAP(NOTCHADUMAP, **dict( suptitle='CHINJ01: NOTCH INJECTION [ADU]', ColorbarText='ADU', figname=figname4)) if self.report is not None: self.addFigure2Report(figname4, figkey=figkey4, caption='CHINJ01: notch injection level, in ADU.', texfraction=0.7) # Notch injection map, ELECTRONs NOTCHEMAP = self.get_FPAMAP_from_PT(self.ParsedTable['CHINJ01'], extractor=self._get_extractor_NOTCH_fromPT(units='E')) figkey5 = 'NOTCH_ELE_MAP' figname5 = self.figs[figkey5] self.plot_SimpleMAP(NOTCHEMAP, **dict( suptitle='CHINJ01: NOTCH INJECTION [ELECTRONS]', ColorbarText='electrons', figname=figname5)) if self.report is not None: self.addFigure2Report(figname5, figkey=figkey5, caption='CHINJ01: notch injection level, in electrons.', texfraction=0.7) # Average injection profiles IG1profs = 4.5 xlabels_profs = dict(hor='column [pix]', ver='row [pix]') ylabels_profs = dict(hor='Injection level [Normalized]', ver='Injection level [ADU]',) proftypes = ['hor','ver'] ccdhalves = ['top','bot'] BLOCKcolors = cm.rainbow(np.linspace(0, 1, len(self.flight_blocks))) pointcorekwargs = dict() for jblock, block in enumerate(self.flight_blocks): jcolor = BLOCKcolors[jblock] for iCCD in self.CCDs: for kQ in self.Quads: pointcorekwargs['%s_CCD%i_%s' % (block, iCCD, kQ)] = dict( linestyle='', marker='.', color=jcolor, ms=2.0) for ccdhalf in ccdhalves: if ccdhalf == 'top': _Quads = ['G','H'] elif ccdhalf == 'bot': _Quads = ['E','F'] for proftype in proftypes: if proftype == 'hor': xrangeNorm = None elif proftype == 'ver': xrangeNorm = [10,20] XY_profs = self._get_XYdict_PROFS(proftype=proftype, IG1=IG1profs,Quads=_Quads, doNorm=True, xrangeNorm=xrangeNorm) figkey6 = 'PROFS_%s_%s' % (proftype.upper(),ccdhalf.upper()) figname6 = self.figs[figkey6] title = 'CHINJ01: Direction: %s, CCDHalf: %s' % \ (proftype.upper(),ccdhalf.upper()), if proftype == 'ver': xlim=[0,50] ylim=None elif proftype == 'hor': xlim=None ylim=[0.5,1.5] profkwargs = dict( title=title, doLegend=False, xlabel=xlabels_profs[proftype], xlim=xlim, ylim=ylim, ylabel=ylabels_profs[proftype], figname=figname6, corekwargs=pointcorekwargs) self.plot_XY(XY_profs, **profkwargs) if proftype == 'ver': captemp = 'CHINJ01: Average (normalized) injection profiles in vertical direction (along CCD columns) '+\ 'for IG1=%.2fV. Only the 2 channels in the CCD %s-half are shown '+\ '(%s, %s). Each colour corresponds to a '+\ 'different block (2x3 quadrant-channels in each colour).' elif proftype == 'hor': captemp = 'CHINJ01: Average injection profiles in horizontal direction (along CCD rows) '+\ 'for IG1=%.2fV. The profiles have been normalized by the median injection level. '+\ 'Only the 2 channels in the CCD %s-half are shown (%s, %s). Each colour corresponds to a '+\ 'different block (2x3 quadrant-channels in each colour).' if self.report is not None: self.addFigure2Report(figname6, figkey=figkey6, caption= captemp % (IG1profs, ccdhalf, _Quads[0],_Quads[1]), texfraction=0.7) # Average injection vertical profiles, zoomed in to highlight # non-perfect charge injection shut-down. pointcorekwargs = dict() for jblock, block in enumerate(self.flight_blocks): jcolor = BLOCKcolors[jblock] for iCCD in self.CCDs: for kQ in self.Quads: pointcorekwargs['%s_CCD%i_%s' % (block, iCCD, kQ)] = dict( linestyle='', marker='.', color=jcolor, ms=2.0) for ccdhalf in ccdhalves: if ccdhalf == 'top': _Quads = ['G','H'] elif ccdhalf == 'bot': _Quads = ['E','F'] XY_profs = self._get_XYdict_PROFS(proftype='ver', IG1=IG1profs,Quads=_Quads, doNorm=True, xrangeNorm=[10,20]) figkey7 = 'PROFS_ver_%s_ZOOM' % (ccdhalf.upper(),) figname7 = self.figs[figkey7] title = 'CHINJ01: Direction: ver, CCDHalf: %s, ZOOM-in' % \ (ccdhalf.upper(),), xlim=[25,50] ylim=[0,4.e-3] profkwargs = dict( title=title, doLegend=False, xlabel=xlabels_profs[proftype], xlim=xlim, ylim=ylim, ylabel=ylabels_profs[proftype], figname=figname7, corekwargs=pointcorekwargs) self.plot_XY(XY_profs, **profkwargs) captemp = 'CHINJ01: Average injection profiles in vertical direction (along CCD columns) '+\ 'for IG1=%.2fV. Only the 2 channels in the CCD %s-half are shown '+\ '(%s, %s). Each colour corresponds to a '+\ 'different block (2x3 quadrant-channels in each colour). Zoomed in '+\ 'to highlight injection shutdown profile.' if self.report is not None: self.addFigure2Report(figname7, figkey=figkey7, caption= captemp % (IG1profs, ccdhalf, _Quads[0],_Quads[1]), texfraction=0.7) # creating and saving INJ PROFILES CDPs. for direction in ['hor','ver']: _injprof_xlsx_cdp = self.get_injprof_xlsx_cdp(direction=direction, inCDP_header=CDP_header) _injprof_xlsx_cdp.savehardcopy() _injprof_fits_cdp = self.get_injprof_fits_cdp(direction=direction, inCDP_header=CDP_header) _injprof_fits_cdp.savehardcopy() # reporting non-uniformity of injection lines to report if self.report is not None: NUN_HOR = self.get_FPAMAP_from_PT(self.ParsedTable['CHINJ01'], extractor=self._extract_NUNHOR_fromPT) nun_cdpdict = dict( caption='CHINJ01: Non-Uniformity of the injection lines, rms, as percentage.', valformat='%.2f') ignore = self.add_StdQuadsTable2Report( Matrix = NUN_HOR, cdpdict = nun_cdpdict)
ruymanengithub/vison
vison/metatests/chinj01.py
Python
gpl-3.0
34,380
vetor[10] = {31, 16, 45, 87, 37, 99, 21, 43, 10, 48} valorProcurado = 87 indice = -1 for (i = 0; i < vetor.length - 1; i++) { if (vetor[i] == valorProcurado) { indice = i } }
amasiero/algoritmos_estrutura_dados
aula_04/beamer/src/sequencial.java
Java
gpl-3.0
193
define(['react','app','dataTable','dataTableBoot'], function (React,app,DataTable,dataTableBoot) { return React.createClass({ mixins: [app.mixins.touchMixins()], getInitialState : function() { var dataSet = []; return { dataSet:dataSet, mainChecker:[], emailInFolder:0, displayedFolder:"", }; }, componentWillReceiveProps: function(nextProps) { //console.log(this.props.folderId); if(this.props.folderId!=nextProps.folderId && this.props.folderId!=""){ this.updateEmails(nextProps.folderId,''); //console.log(nextProps.folderId); } //this.setState({ // likesIncreasing: nextProps.likeCount > this.props.likeCount //}); }, updateEmails: function(folderId,noRefresh) { var thisComp = this; var emails = app.user.get('emails')['folders'][folderId]; // if (thisComp.state.emailInFolder == Object.keys(emails).length && thisComp.state.displayedFolder == app.transform.from64str(app.user.get('folders')[folderId]['name'])) { //} else { var emailListCopy=app.user.get("folderCached"); if(emailListCopy[folderId]===undefined){ emailListCopy[folderId]={}; } thisComp.setState({ "displayedFolder": app.transform.from64str(app.user.get('folders')[folderId]['name']), "emailInFolder": Object.keys(emails).length }); app.user.set({ 'currentFolder': app.transform.from64str(app.user.get('folders')[folderId]['name']) }); //console.log(app.user.get('folders')[folderId]['role']); if (app.user.get('folders')[folderId]['role'] != undefined) { var t = app.transform.from64str(app.user.get('folders')[folderId]['role']); } else { var t = ''; } //console.log(t); var data = []; var d = new Date(); var trusted = app.user.get("trustedSenders"); var encrypted2 = ""; $.each(emails, function (index, folderData) { if(emailListCopy[folderId][index]!==undefined){ var unread = folderData['st'] == 0 ? "unread" : folderData['st'] == 1 ? "fa fa-mail-reply" : folderData['st'] == 2 ? "fa fa-mail-forward" : ""; var row = { "DT_RowId": index, "email": { "display": '<div class="email no-padding ' + unread + '">' + emailListCopy[folderId][index]["checkBpart"] + emailListCopy[folderId][index]["dateAtPart"] + emailListCopy[folderId][index]["fromPart"] + '<div class="title ellipsisText col-xs-10 col-md-6"><span>' + emailListCopy[folderId][index]["sb"] + '</span> - ' + emailListCopy[folderId][index]["bd"] + '</div>' +emailListCopy[folderId][index]["tagPart"] + '</div>', //"open":folderData['o']?1:0, "timestamp": emailListCopy[folderId][index]["timestamp"] } }; }else { var time = folderData['tr'] != undefined ? folderData['tr'] : folderData['tc'] != undefined ? folderData['tc'] : ''; //console.log(time); if (d.toDateString() == new Date(parseInt(time + '000')).toDateString()) { var dispTime = new Date(parseInt(time + '000')).toLocaleTimeString(); } else { var dispTime = new Date(parseInt(time + '000')).toLocaleDateString(); } var fromEmail = []; var fromTitle = []; var recipient = []; var recipientTitle = []; var trust = ""; if (folderData['to'].length > 0) { $.each(folderData['to'], function (indexTo, email) { // console.log(email); if (app.transform.check64str(email)) { var str = app.transform.from64str(email); } else { var str = email; } recipient.push(app.globalF.parseEmail(str)['name']); recipientTitle.push(app.globalF.parseEmail(str)['email']); }); } else if (Object.keys(folderData['to']).length > 0) { $.each(folderData['to'], function (indexTo, email) { try { var str = app.transform.from64str(indexTo); var name = ""; if (email === undefined) { name = str; } else { if (email['name'] === undefined) { name = str; } else { if (email['name'] === "") { name = str; } else { name = app.transform.from64str(email['name']); } } } recipient.push(name); recipientTitle.push(str); } catch (err) { recipient.push('error'); recipientTitle.push('error'); } }); } //console.log(recipient); if (t == 'Sent' || t == 'Draft') { // console.log(folderData['to']); // console.log(folderData['cc']); // console.log(folderData['bcc']); fromEmail = ''; fromTitle = ''; if (folderData['cc'] != undefined && Object.keys(folderData['cc']).length > 0) { $.each(folderData['cc'], function (indexCC, email) { try { var str = app.transform.from64str(indexCC); var name = ""; if (email === undefined) { name = str; } else { if (email['name'] === undefined) { name = str; } else { if (email['name'] === "") { name = str; } else { name = app.transform.from64str(email['name']); } } } recipient.push(name); recipientTitle.push(str); } catch (err) { recipient.push('error'); recipientTitle.push('error'); } }); } if (folderData['bcc'] != undefined && Object.keys(folderData['bcc']).length > 0) { $.each(folderData['bcc'], function (indexBCC, email) { try { var str = app.transform.from64str(indexBCC); var name = ""; if (email === undefined) { name = str; } else { if (email['name'] === undefined) { name = str; } else { if (email['name'] === "") { name = str; } else { name = app.transform.from64str(email['name']); } } } recipient.push(name); recipientTitle.push(str); } catch (err) { recipient.push('error'); recipientTitle.push('error'); } }); } recipient = recipient.join(', '); recipientTitle = recipientTitle.join(', '); fromEmail = recipient; fromTitle = recipientTitle; } else { var str = app.transform.from64str(folderData['fr']); //console.log(str); fromEmail = app.globalF.parseEmail(str, true)['name']; fromTitle = app.globalF.parseEmail(str, true)['email']; if (trusted.indexOf(app.transform.SHA256(app.globalF.parseEmail(str)['email'])) !== -1) { //console.log('X'); trust = "<img src='/img/logo/logo.png' style='height:25px'/>" } else { trust = "" } recipient = recipient.join(', '); recipientTitle = recipientTitle.join(', '); } if (folderData['tg'].length > 0) { //console.log(folderData['tg']); var tag = folderData['tg'][0]['name']; } else { var tag = ""; } if (parseInt(folderData['en']) == 1) { encrypted2 = "<i class='fa fa-lock fa-lg'></i>"; } else if (parseInt(folderData['en']) == 0) { encrypted2 = "<i class='fa fa-unlock fa-lg'></i>"; } else if (parseInt(folderData['en']) == 3) { encrypted2 = ""; } //console.log(tag); tag = app.globalF.stripHTML(app.transform.from64str(tag)); //console.log(app.transform.from64str(tag)); var unread = folderData['st'] == 0 ? "unread" : folderData['st'] == 1 ? "fa fa-mail-reply" : folderData['st'] == 2 ? "fa fa-mail-forward" : ""; var attch = folderData['at'] == "1" ? '<span class="fa fa-paperclip fa-lg"></span>' : ""; if (fromEmail == "") { fromEmail = fromTitle; } var checkBpart = '<label><input class="emailchk hidden-xs" type="checkbox"/></label>'; var fromPart = '<span class="from no-padding col-xs-8 col-md-3 ellipsisText margin-right-10" data-placement="bottom" data-toggle="popover-hover" title="" data-content="' + fromTitle + '">' + trust + ' ' + fromEmail + '</span>'; var dateAtPart = '<span class="no-padding date col-xs-3 col-sm-2">' + attch + '&nbsp;' + encrypted2 + ' ' + dispTime + '<span class="label label-primary f-s-10"></span><span class="label label-primary f-s-10"></span></span>'; var tagPart = '<div class="mailListLabel pull-right text-right col-xs-2"><div class="ellipsisText visible-xs"><span class="label label-success">' + tag + '</span></div><div class="ellipsisText hidden-xs col-xs-12 pull-right"><span class="label label-success">' + tag + '</span></div></div>'; emailListCopy[folderId][index]={ "DT_RowId": index, "unread":unread, "checkBpart":checkBpart, "dateAtPart":dateAtPart, "fromPart":fromPart, "sb":app.transform.escapeTags(app.transform.from64str(folderData['sb'])), "bd":app.transform.escapeTags(app.transform.from64str(folderData['bd'])), "tagPart":tagPart, "timestamp": time }; var row = { "DT_RowId": index, "email": { "display": '<div class="email no-padding ' + emailListCopy[folderId][index]["unread"] + '">' + emailListCopy[folderId][index]["checkBpart"] + emailListCopy[folderId][index]["dateAtPart"] + emailListCopy[folderId][index]["fromPart"] + '<div class="title ellipsisText col-xs-10 col-md-6"><span>' + emailListCopy[folderId][index]["sb"] + '</span> - ' + emailListCopy[folderId][index]["bd"] + '</div>' +emailListCopy[folderId][index]["tagPart"] + '</div>', //"open":folderData['o']?1:0, "timestamp": emailListCopy[folderId][index]["timestamp"] } }; } data.push(row); }); app.user.set({"folderCached":emailListCopy}); // console.log(data); var t = $('#emailListTable').DataTable(); t.clear(); if (noRefresh == '') { t.draw(); //$('#mMiddlePanel').scrollTop(0); } t.rows.add(data); t.draw(false); this.attachTooltip(); $('#emailListTable td').click(function () { var selectedEmails = app.user.get('selectedEmails'); if ($(this).find('.emailchk').prop("checked")) { selectedEmails[$(this).parents('tr').attr('id')] = true; } else { delete selectedEmails[$(this).parents('tr').attr('id')]; } // console.log(selectedEmails); }); //} }, componentDidMount: function() { //todo delete // setInterval(function(){ // console.log('sdsads'); // app.globalF.syncUpdates(); //},10000); //console.log(this.state.dataSet); var dtSet=this.state.dataSet; var thisComp=this; //require(['dataTable','dataTableBoot'], function(DataTable,dataTableBoot) { //data example //}); $('#emailListTable').dataTable( { "dom": '<"#checkAll"><"#emailListNavigation"pi>rt<"pull-right"p><"pull-right"i>', "data": dtSet, "columns": [ { data: { _: "email.display", sort: "email.timestamp", filter: "email.display" } } ], "columnDefs": [ { "sClass": 'col-xs-12 border-right text-align-left no-padding padding-vertical-10', "targets": 0}, { "orderDataType": "data-sort", "targets": 0 } ], "sPaginationType": "simple", "order": [[0,"desc"]], "iDisplayLength": app.user.get("mailPerPage"), "language": { "emptyTable": "Empty", "info": "_START_ - _END_ of _TOTAL_", "infoEmpty": "No entries", "paginate": { "sPrevious": "<i class='fa fa-chevron-left'></i>", "sNext": "<i class='fa fa-chevron-right'></i>" } }, fnDrawCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { $("#emailListTable thead").remove(); //console.log(nRow); //console.log($('#mMiddlePanel').scrollTop()); //$('#mMiddlePanel').scrollTop(0); }, "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { // console.log($(nRow).attr('id')); // console.log(app.user.get('currentMessageView')['id']); if($(nRow).attr('id')==app.user.get('currentMessageView')['id']){ $(nRow).addClass('selected') } if( app.user.get("selectedEmails")[$(nRow).attr('id')]!==undefined){ $(nRow).find('.emailchk').prop('checked',true); } //$(nRow).attr('id', aData[0]); return nRow; } } ); //console.log(app.globalF.getInboxFolderId()); app.globalF.getInboxFolderId(function(inbox){ thisComp.updateEmails(inbox,''); }); app.user.on("change:resetSelectedItems",function() { if(app.user.get("resetSelectedItems")){ app.user.set({"selectedEmails":{}}); app.user.set({"resetSelectedItems":false}); } },thisComp); // app.user.set({"resetSelectedItems":true}); app.user.on("change:emailListRefresh",function() { // console.log(app.user.get("resetSelectedItems")); thisComp.updateEmails(thisComp.props.folderId,'noRefresh') // $('#selectAll>input').prop("checked",false); },thisComp); var container = $('#checkAll'); //$(thisComp.selectAll()).appendTo(container); var mainChecker=[]; $('#checkAll').html('<div class="btn-group btn btn-default borderless pull-left hidden-xs" id="selectAll"><input type="checkbox"/> </div>'); /* <i class="fa fa-angle-down fa-lg" data-toggle="dropdown"></i><ul id="mvtofolder1" class="dropdown-menu"><li><a id="thisPage">this page</a></li><li><a id="wholeFolder">All in folder</a></li></ul> */ /* $('#thisPage').click( function () { if($('#selectAll>input').prop("checked")){ $('#selectAll>input').prop("checked",false); }else{ $('#selectAll>input').prop("checked",true); } thisComp.selectThisPage(thisComp.state.selectedEmails); } ); $('#wholeFolder').click( function () { if($('#selectAll>input').prop("checked")){ $('#selectAll>input').prop("checked",false); }else{ $('#selectAll>input').prop("checked",true); } thisComp.selectAll(thisComp.state.selectedEmails); } ); */ $('#selectAll').change(function() { var selectedEmails=app.user.get('selectedEmails'); if($('#selectAll>input').prop("checked")){ $(".emailchk").prop('checked', true); $( ".emailchk" ).each(function( index ) { var messageId=$( this ).closest('tr').attr('id'); selectedEmails[messageId]=true; }); // console.log(selectedEmails); }else{ //console.log('unselecting') //console.log(selectedEmails); $(".emailchk").prop('checked', false); app.user.set({"selectedEmails":{}}); } // console.log($('#selectAll>input').prop("checked")); }); }, /*selectThisPage:function(thisComp){ selectedEmails=thisComp.state.selectedEmails; },*/ componentWillUnmount: function () { app.user.off("change:emailListRefresh"); }, handleClick: function(i,event) { switch(i) { case 'wholeFolder': // console.log('wholeFolder') break; case 'thisPage': // console.log('thisPage') break; case 'readEmail': //console.log('ghfghfg'); var thisComp=this; var folder=app.user.get('folders')[this.props.folderId]['name']; app.mixins.canNavigate(function(decision){ if(decision){ var id=$(event.target).parents('tr').attr('id'); if(!$(event.target).is('input')){ app.globalF.resetCurrentMessage(); app.globalF.resetDraftMessage(); Backbone.history.navigate("/mail/"+app.transform.from64str(folder), { trigger : true }); if(id!=undefined && $(event.target).attr('type')!="checkbox" && $(event.target).prop("tagName")!="LABEL"){ var table = $('#emailListTable').DataTable(); table.$('tr.selected').removeClass('selected'); $(event.target).parents('tr').toggleClass('selected'); //table.row('.selected').remove().draw( false ); //var modKey=app.user.get('emails')['messages'][id]['mK']; //console.log(id); //console.log(modKey); app.globalF.renderEmail(id); //thisComp.handleClick('editFolder',id); app.mixins.hidePopHover(); //thisComp.handleClick('toggleEmail'); } } }else{ } }); break; } }, attachTooltip: function() { //console.log('gg'); $('[data-toggle="popover-hover"]').popover({ trigger: "hover" ,container: 'body'}); $('[data-toggle="popover-hover"]').on('shown.bs.popover', function () { var $pop = $(this); setTimeout(function () { $pop.popover('hide'); }, 5000); }); }, componentDidUpdate:function(){ //this.attachTooltip(); }, render: function () { var middleClass="Middle inbox checkcentr col-lg-6 col-xs-12"; //console.log(this.props.panel.middlePanel); //$('[data-toggle="popover-hover"]').popover({ trigger: "hover" ,container: 'body'}); return ( <div className={this.props.panel.middlePanel+ " no-padding"} id="mMiddlePanel"> <table className="table table-hover table-inbox row-border clickable" id="emailListTable" onClick={this.handleClick.bind(this, 'readEmail')}> </table> </div> ); } }); });
SCRYPTmail/frontEnd
app/src/authorized/mailbox/middlepanel/emailList.js
JavaScript
gpl-3.0
23,324
package de.baleipzig.iris.ui.playground; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener; import com.vaadin.spring.annotation.SpringView; import com.vaadin.spring.annotation.UIScope; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; import javax.annotation.PostConstruct; @UIScope @SpringView(name = RonnyView.VIEW_NAME) public class RonnyView extends VerticalLayout implements View { public static final String VIEW_NAME = "ronny"; @PostConstruct void init() { this.addComponent(new Label("Ronnys Spielwiese")); } @Override public void enter(ViewChangeListener.ViewChangeEvent event) { } }
fluoxa/Iris
src/main/java/de/baleipzig/iris/ui/playground/RonnyView.java
Java
gpl-3.0
681
<?php return [ /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used by | the validator class. Some of these rules have multiple versions such | as the size rules. Feel free to tweak each of these messages here. | */ 'accepted' => 'Το πεδίο :attribute πρέπει να γίνει αποδεκτό.', 'active_url' => 'Το πεδίο :attribute δεν είναι αποδεκτή διεύθυνση URL.', 'after' => 'Το πεδίο :attribute πρέπει να είναι μία ημερομηνία μετά από :date.', 'after_or_equal' => 'Το πεδίο :attribute πρέπει να είναι μία ημερομηνία ίδια ή μετά από :date.', 'alpha' => 'Το πεδίο :attribute μπορεί να περιέχει μόνο γράμματα.', 'alpha_dash' => 'Το πεδίο :attribute μπορεί να περιέχει μόνο γράμματα, αριθμούς, και παύλες.', 'alpha_num' => 'Το πεδίο :attribute μπορεί να περιέχει μόνο γράμματα και αριθμούς.', 'array' => 'Το πεδίο :attribute πρέπει να είναι ένας πίνακας.', 'before' => 'Το πεδίο :attribute πρέπει να είναι μία ημερομηνία πριν από :date.', 'before_or_equal' => 'Το πεδίο :attribute πρέπει να είναι μία ημερομηνία ίδια ή πριν από :date.', 'between' => [ 'numeric' => 'Το πεδίο :attribute πρέπει να είναι μεταξύ :min - :max.', 'file' => 'Το πεδίο :attribute πρέπει να είναι μεταξύ :min - :max kilobytes.', 'string' => 'Το πεδίο :attribute πρέπει να είναι μεταξύ :min - :max χαρακτήρες.', 'array' => 'Το πεδίο :attribute πρέπει να έχει μεταξύ :min - :max αντικείμενα.', ], 'boolean' => 'Το πεδίο :attribute πρέπει να είναι true ή false.', 'confirmed' => 'Η επιβεβαίωση του :attribute δεν ταιριάζει.', 'date' => 'Το πεδίο :attribute δεν είναι έγκυρη ημερομηνία.', 'date_format' => 'Το πεδίο :attribute δεν είναι της μορφής :format.', 'different' => 'Το πεδίο :attribute και :other πρέπει να είναι <strong>διαφορετικά</strong>.', 'digits' => 'Το πεδίο :attribute πρέπει να είναι :digits ψηφία.', 'digits_between' => 'Το πεδίο :attribute πρέπει να είναι μεταξύ :min και :max ψηφία.', 'dimensions' => 'Το πεδίο :attribute περιέχει μη έγκυρες διαστάσεις εικόνας.', 'distinct' => 'Το πεδίο :attribute περιέχει δύο φορές την ίδια τιμή.', 'email' => 'Το πεδίο :attribute πρέπει να είναι μία έγκυρη <strong>διεύθυνση email</strong>.', 'ends_with' => 'Το :attribute πρέπει να τελειώνει με ένα από τα παρακάτω: :values', 'exists' => 'Το επιλεγμένο :attribute δεν είναι έγκυρο.', 'file' => 'Το πεδίο :attribute πρέπει να είναι ένα <strong>αρχείο</strong>.', 'filled' => 'Το πεδίο :attribute πρέπει έχει μία <strong>αξία</strong>.', 'image' => 'Το πεδίο :attribute πρέπει να είναι <strong>image</strong>.', 'in' => 'Το επιλεγμένο :attribute δεν είναι έγκυρο.', 'in_array' => 'Το πεδίο :attribute δεν υπάρχει σε :other.', 'integer' => 'Το πεδίο :attribute πρέπει να είναι <strong>ακαίρεο</strong>.', 'ip' => 'Το πεδίο :attribute πρέπει να είναι μία έγκυρη διεύθυνση IP.', 'json' => 'Το πεδίο :attribute πρέπει να είναι μία έγκυρη συμβολοσειρά JSON.', 'max' => [ 'numeric' => 'Το πεδίο :attribute δεν μπορεί να είναι μεγαλύτερο από :max.', 'file' => 'Το πεδίο :attribute δεν μπορεί να είναι μεγαλύτερό :max kilobytes.', 'string' => 'Το πεδίο :attribute δεν μπορεί να έχει περισσότερους από :max χαρακτήρες.', 'array' => 'Το πεδίο :attribute δεν μπορεί να έχει περισσότερα από :max αντικείμενα.', ], 'mimes' => 'Το πεδίο :attribute πρέπει να είναι αρχείο τύπου: :values.', 'mimetypes' => 'Το πεδίο :attribute πρέπει να είναι αρχείο τύπου: :values.', 'min' => [ 'numeric' => 'Το πεδίο :attribute πρέπει να είναι τουλάχιστον :min.', 'file' => 'Το πεδίο :attribute πρέπει να είναι τουλάχιστον :min kilobytes.', 'string' => 'Το πεδίο :attribute πρέπει να έχει τουλάχιστον :min χαρακτήρες.', 'array' => 'Το πεδίο :attribute πρέπει να έχει τουλάχιστον :min αντικείμενα.', ], 'not_in' => 'Το επιλεγμένο :attribute δεν είναι αποδεκτό.', 'numeric' => 'Το πεδίο :attribute πρέπει να είναι αριθμός.', 'present' => 'Το πεδίο :attribute πρέπει να <strong>υπάρχει</strong>.', 'regex' => 'Η μορφή του :attribute είναι <strong>μή έγκυρη</strong>.', 'required' => 'Το πεδίο :attribute <strong>απαιτείται</strong>.', 'required_if' => 'Το πεδίο :attribute είναι απαραίτητο όταν το πεδίο :other είναι :value.', 'required_unless' => 'Το πεδίο :attribute είναι απαραίτητο εκτός αν το πεδίο :other εμπεριέχει :values.', 'required_with' => 'Το πεδίο :attribute είναι απαραίτητο όταν υπάρχει :values.', 'required_with_all' => 'Το πεδίο :attribute είναι απαραίτητο όταν υπάρχουν :values.', 'required_without' => 'Το πεδίο :attribute είναι απαραίτητο όταν δεν υπάρχει :values.', 'required_without_all' => 'Το πεδίο :attribute είναι απαραίτητο όταν δεν υπάρχει κανένα από :values.', 'same' => 'Τα πεδία :attribute και :other πρέπει να είναι ίδια.', 'size' => [ 'numeric' => 'Το πεδίο :attribute πρέπει να είναι :size.', 'file' => 'Το πεδίο :attribute πρέπει να είναι :size kilobytes.', 'string' => 'Το :attribute πρέπει να είναι <strong>:size characters</strong>.', 'array' => 'Το πεδίο :attribute πρέπει να περιέχει :size αντικείμενα.', ], 'string' => 'Το :attribute πρέπει να είναι ένα <strong>string</strong>.', 'timezone' => 'Το πεδίο :attribute πρέπει να είναι μία έγκυρη ζώνη ώρας.', 'unique' => 'Το πεδίο :attribute <strong>χρησιμοποιείται</strong>.', 'uploaded' => 'Το :attribute <strong>απέτυχε</strong> να μεταφορτωθεί.', 'url' => 'Η μορφή του :attribute είναι <strong>μή έγκυρη</strong>.', /* |-------------------------------------------------------------------------- | Custom Validation Language Lines |-------------------------------------------------------------------------- | | Here you may specify custom validation messages for attributes using the | convention "attribute.rule" to name the lines. This makes it quick to | specify a specific custom language line for a given attribute rule. | */ 'custom' => [ 'attribute-name' => [ 'rule-name' => 'προσαρμοσμένο-μήνυμα', ], 'invalid_currency' => 'Το πεδίο :attribute δεν είναι έγκυρος κωδικός νομίσματος.', 'invalid_amount' => 'Το πεδίο :attribute δεν είναι έγκυρο ποσό.', 'invalid_extension' => 'Η επέκταση του αρχείου δεν είναι έγκυρη.', ], /* |-------------------------------------------------------------------------- | Custom Validation Attributes |-------------------------------------------------------------------------- | | The following language lines are used to swap attribute place-holders | with something more reader friendly such as E-Mail Address instead | of "email". This simply helps us make messages a little cleaner. | */ 'attributes' => [], ];
akaunting/akaunting
resources/lang/el-GR/validation.php
PHP
gpl-3.0
10,007
<?php /***************************************************************************\ * SPIP, Systeme de publication pour l'internet * * * * Copyright (c) 2001-2012 * * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James * * * * Ce programme est un logiciel libre distribue sous licence GNU/GPL. * * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. * \***************************************************************************/ if (!defined('_ECRIRE_INC_VERSION')) return; include_spip('inc/presentation'); include_spip('inc/acces'); // pour low_sec (iCal) // http://doc.spip.org/@afficher_liens_calendrier function afficher_liens_calendrier($lien, $icone, $texte) { global $spip_display; $charge = icone_horizontale_display(_T('ical_methode_http'), $lien, "calendrier-24.gif","", false); $abonne = icone_horizontale_display (_T('ical_methode_webcal'), preg_replace("@https?://@", "webcal://", $lien), "calendrier-24.gif", "", false); echo debut_cadre_enfonce($icone, true); echo $texte; if ($spip_display == 4) echo $charge,$abonne; else { echo "<table style='width: 100%;'><tr><td style='width: 200px;'>"; echo $charge; echo "</td>"; echo "<td> &nbsp; </td>"; echo "<td style='width: 200px;'>"; echo $abonne; echo "</td></tr></table>"; } echo fin_cadre_enfonce(true); } // http://doc.spip.org/@exec_synchro_dist function exec_synchro_dist() { ///// debut de la page $commencer_page = charger_fonction('commencer_page', 'inc'); echo $commencer_page(_T("icone_suivi_activite"), "accueil", "synchro"); echo "<br /><br />"; echo gros_titre(_T("icone_suivi_activite"),'', false); echo debut_gauche('', true); echo debut_boite_info(true); echo "<div class='verdana2'>"; echo _T('ical_info1').'<br /><br />'; echo _T('ical_info2', array('spipnet' => $GLOBALS['home_server'] . '/' . $GLOBALS['spip_lang'] . '_suivi')); echo "</div>"; echo fin_boite_info(true); $adresse_suivi_inscription=$GLOBALS['meta']["adresse_suivi_inscription"]; echo debut_droite('', true); /// /// Suivi par mailing-list /// if ($GLOBALS['meta']["suivi_edito"] == "oui" AND strlen($GLOBALS['meta']["adresse_suivi"]) > 3 AND strlen($adresse_suivi_inscription) > 3) { echo debut_cadre_enfonce("racine-site-24.gif", true, "", _T('ical_titre_mailing')); echo _T('info_config_suivi_explication'), propre("<b style='text-align: center'>[->$adresse_suivi_inscription]</b>"); echo fin_cadre_enfonce(true); } /// /// Suivi par agenda iCal (taches + rendez-vous) /// echo debut_cadre_relief("agenda-24.gif", true, "", _T('icone_calendrier')); echo _T('calendrier_synchro'); echo '<p>'._T('ical_info_calendrier').'</p>'; $id_auteur = $GLOBALS['visiteur_session']['id_auteur']; afficher_liens_calendrier(generer_url_public('ical'),'', _T('ical_texte_public')); afficher_liens_calendrier(generer_url_public("ical_prive", "id_auteur=$id_auteur&arg=".afficher_low_sec($id_auteur,'ical')),'cadenas-24.gif', _T('ical_texte_prive')); echo fin_cadre_relief(true); /// /// Suivi par RSS /// echo debut_cadre_relief("site-24.gif", true, "", _T('ical_titre_rss')); echo _T('ical_texte_rss'); echo "<p>"._T("ical_texte_rss_articles")."</p>"; echo propre("<cadre>" . generer_url_public('backend') . "</cadre>"); echo "<p>"._T("ical_texte_rss_articles2")."</p>"; $bouton = http_img_pack( 'feed.png', 'RSS', ''); $result = sql_allfetsel("id_rubrique, titre", "spip_rubriques", 'id_parent=0','', '0+titre,titre'); $res = ''; foreach($result as $row){ $h = generer_url_public('backend', "id_rubrique=" . $row['id_rubrique']); $titre_rubrique = typo($row['titre']); $titre = htmlspecialchars($titre_rubrique); $res .= "\n<li><a href='$h' title=\"$titre\">$bouton&nbsp; $titre_rubrique</a></li>"; } if ($res) echo "\n<ul>", $res, "\n</ul>"; if ($GLOBALS['meta']['activer_breves'] == "oui") { echo "<p>"._T("ical_texte_rss_breves")."</p>"; echo "<ul><li><a href='", generer_url_public('backend-breves', ""), "' title=\"", _T('ical_lien_rss_breves'), "\">", $bouton, '&nbsp; ' . _T('ical_lien_rss_breves'), "</a></li></ul>"; } echo fin_cadre_relief(true); /// /// Suivi par Javascript /// echo debut_cadre_relief("doc-24.gif", true, "", _T('ical_titre_js')); echo _T('ical_texte_js').'<br />'; echo propre('<code> <script type="text/javascript" src="'.generer_url_public('distrib').'"> </script> </code>'); echo fin_cadre_relief(true); echo fin_gauche(), fin_page(); } ?>
VertigeASBL/DLPbeta
ecrire/exec/synchro.php
PHP
gpl-3.0
4,782
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | If this is not set then CodeIgniter will guess the protocol, domain and | path to your installation. | */ // $config['base_url'] = 'http://bsmsite.com/'; $root = "http://".$_SERVER['HTTP_HOST']; $root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']); $config['base_url'] = $root; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'AUTO' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'AUTO' Default - auto detects | 'PATH_INFO' Uses the PATH_INFO | 'QUERY_STRING' Uses the QUERY_STRING | 'REQUEST_URI' Uses the REQUEST_URI | 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO | */ $config['uri_protocol'] = 'AUTO'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify with a regular expression which characters are permitted | within your URLs. When someone tries to submit a URL with disallowed | characters they will get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; // experimental not currently in use /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | If you have enabled error logging, you can set an error threshold to | determine what gets logged. Threshold options are: | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ folder. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | system/cache/ folder. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class or the Session class you | MUST set an encryption key. See the user guide for info. | */ $config['encryption_key'] = 'sadfyui3457KJHGJHB457834kdfsd'; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_cookie_name' = the name you want for the cookie | 'sess_expiration' = the number of SECONDS you want the session to last. | by default sessions last 7200 seconds (two hours). Set to zero for no expiration. | 'sess_expire_on_close' = Whether to cause the session to expire automatically | when the browser window is closed | 'sess_encrypt_cookie' = Whether to encrypt the cookie | 'sess_use_database' = Whether to save the session data to a database | 'sess_table_name' = The name of the session database table | 'sess_match_ip' = Whether to match the user's IP address when reading the session data | 'sess_match_useragent' = Whether to match the User Agent when reading the session data | 'sess_time_to_update' = how many seconds between CI refreshing Session Information | */ $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_expire_on_close'] = FALSE; $config['sess_encrypt_cookie'] = FALSE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 300; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists. | */ $config['cookie_prefix'] = ""; $config['cookie_domain'] = ""; $config['cookie_path'] = "/"; $config['cookie_secure'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or 'gmt'. This pref tells the system whether to use | your server's local time as the master 'now' reference, or convert it to | GMT. See the 'date helper' page of the user guide for information | regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy IP | addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR | header in order to properly identify the visitor's IP address. | Comma-delimited, e.g. '10.0.1.200,10.0.1.201' | */ $config['proxy_ips'] = ''; /* End of file config.php */ /* Location: ./application/config/config.php */
ayes/artist-management
application/config/config.php
PHP
gpl-3.0
13,007
package tmp.generated_xhtml; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class Content_var_Choice110 extends Content_var_Choice1 { public Content_var_Choice110(Element_i element_i, Token firstToken, Token lastToken) { super(new Property[] { new PropertyOne<Element_i>("element_i", element_i) }, firstToken, lastToken); } public Content_var_Choice110(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public ASTNode deepCopy() { return new Content_var_Choice110(cloneProperties(),firstToken,lastToken); } public Element_i getElement_i() { return ((PropertyOne<Element_i>)getProperty("element_i")).getValue(); } }
ckaestne/CIDE
CIDE_Language_XML_concrete/src/tmp/generated_xhtml/Content_var_Choice110.java
Java
gpl-3.0
783
<?php namespace Maestro\ApiBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('maestro_api'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
wilxsv/coreMaestros
src/Maestro/ApiBundle/DependencyInjection/Configuration.php
PHP
gpl-3.0
842
#include "game/network/api.hpp" namespace Game { namespace Network { Api::Api(QObject *parent) : QObject(parent) { // Manager to send REST petitions manager = new QNetworkAccessManager(this); result = ""; limit = 5; // URL information QString host = Game::Settings::load("network:api:host").toString(); QString port = Game::Settings::load("network:api:port").toString(); base_url = QString("http://%1:%2").arg(host, port); // Signals && Slots connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestResult(QNetworkReply*))); } void Api::uploadScore(QString name, int score) { // Name of resource QString resource = "/games"; // Create a JSON object QtJson::JsonObject json; json["name"] = name; json["score"] = score; json["timestamp"] = QString::number(QDateTime::currentDateTimeUtc().toTime_t()); // Serialize object QByteArray data = QtJson::serialize(json); // Send post petition postMethod(resource, data); } void Api::getHighscores(int limit) { // Set up limit of top highscores this->limit = limit; // Name of resource QString resource = QString("/topscores"); // Send get petition getMethod(resource); // Emit signal with response QTimer *timer = new QTimer(this); timer->setSingleShot(true); connect(timer, SIGNAL(timeout()), this, SLOT(parseHighscores())); timer->start(max_timeout); } void Api::requestResult(QNetworkReply *reply) { // Error response if (reply->error() != QNetworkReply::NoError) { result = ""; return; } result = (QString)reply->readAll(); } void Api::parseHighscores() { if(result.isEmpty()) { return; } // Deserialize JSON data bool ok; QList<QVariant> data = QtJson::parse(result, ok).toList(); if (!ok) { return; } // Store top highscores QVector<QVector<QString> > highscores; for (int i = 0; i < limit; i++) { QVector<QString> element; element << data[i].toMap()["name"].toString(); element << data[i].toMap()["score"].toString(); highscores << element; } emit topHighscores(highscores); } void Api::getMethod(QString resource) { QUrl url(base_url.append(resource)); QNetworkRequest request(url); manager->get(request); } void Api::postMethod(QString resource, QByteArray data) { QUrl url(base_url.append(resource)); QNetworkRequest request(url); // Specify a JSON object is sent request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); manager->post(request, data); } } // namespace Network } // namespace Game
Madh93/simon-says-pi
src/game/network/api.cpp
C++
gpl-3.0
2,699
<?php namespace Eight\PageBundle\Widget; class Label extends AbstractWidget { public function getVars() { return array( 'label', ); } public function getLayout() { return 'EightPageBundle:Widget:label.html.twig'; } public function getName() { return 'label'; } }
matteocaberlotto/eight-page-bundle
Widget/Label.php
PHP
gpl-3.0
350
/* * Copyright (C) 2015 Rubén Héctor García (raiben@gmail.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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.velonuboso.made.core.abm.api; /** * * @author Rubén Héctor García (raiben@gmail.com) */ public interface IBehaviourTreeBlackboard { }
raiben/made
madetools/core/src/main/java/com/velonuboso/made/core/abm/api/IBehaviourTreeBlackboard.java
Java
gpl-3.0
878
""" MagPy IAGA02 input filter Written by Roman Leonhardt June 2012 - contains test, read and write function """ from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from io import open from magpy.stream import * #global variables MISSING_DATA = 99999 NOT_REPORTED = 88888 def isIAGA(filename): """ Checks whether a file is ASCII IAGA 2002 format. """ try: temp = open(filename, 'rt').readline() except: return False try: if not temp.startswith(' Format'): return False if not 'IAGA-2002' in temp: return False except: return False return True def readIAGA(filename, headonly=False, **kwargs): """ Reading IAGA2002 format data. """ starttime = kwargs.get('starttime') endtime = kwargs.get('endtime') debug = kwargs.get('debug') getfile = True array = [[] for key in KEYLIST] fh = open(filename, 'rt') # read file and split text into channels stream = DataStream() # Check whether header infromation is already present headers = {} data = [] key = None try: # get day from filename (platform independent) theday = extractDateFromString(filename)[0] day = datetime.strftime(theday,"%Y-%m-%d") # Select only files within eventually defined time range if starttime: if not datetime.strptime(day,'%Y-%m-%d') >= datetime.strptime(datetime.strftime(stream._testtime(starttime),'%Y-%m-%d'),'%Y-%m-%d'): getfile = False if endtime: if not datetime.strptime(day,'%Y-%m-%d') <= datetime.strptime(datetime.strftime(stream._testtime(endtime),'%Y-%m-%d'),'%Y-%m-%d'): getfile = False except: logging.warning("Could not identify typical IAGA date for %s. Reading all ...".format(filename)) getfile = True if getfile: loggerlib.info('Read: %s Format: %s ' % (filename, "IAGA2002")) dfpos = KEYLIST.index('df') for line in fh: if line.isspace(): # blank line continue elif line.startswith(' '): # data info infoline = line[:-4] key = infoline[:23].strip() val = infoline[23:].strip() if key.find('Source') > -1: if not val == '': stream.header['StationInstitution'] = val if key.find('Station') > -1: if not val == '': stream.header['StationName'] = val if key.find('IAGA') > -1: if not val == '': stream.header['StationIAGAcode'] = val stream.header['StationID'] = val if key.find('Latitude') > -1: if not val == '': stream.header['DataAcquisitionLatitude'] = val if key.find('Longitude') > -1: if not val == '': stream.header['DataAcquisitionLongitude'] = val if key.find('Elevation') > -1: if not val == '': stream.header['DataElevation'] = val if key.find('Format') > -1: if not val == '': stream.header['DataFormat'] = val if key.find('Reported') > -1: if not val == '': stream.header['DataComponents'] = val if key.find('Orientation') > -1: if not val == '': stream.header['DataSensorOrientation'] = val if key.find('Digital') > -1: if not val == '': stream.header['DataDigitalSampling'] = val if key.find('Interval') > -1: if not val == '': stream.header['DataSamplingFilter'] = val if key.startswith(' #'): if key.find('# V-Instrument') > -1: if not val == '': stream.header['SensorID'] = val elif key.find('# PublicationDate') > -1: if not val == '': stream.header['DataPublicationDate'] = val else: print ("formatIAGA: did not import optional header info {a}".format(a=key)) if key.find('Data Type') > -1: if not val == '': if val[0] in ['d','D']: stream.header['DataPublicationLevel'] = '4' elif val[0] in ['q','Q']: stream.header['DataPublicationLevel'] = '3' elif val[0] in ['p','P']: stream.header['DataPublicationLevel'] = '2' else: stream.header['DataPublicationLevel'] = '1' if key.find('Publication Date') > -1: if not val == '': stream.header['DataPublicationDate'] = val elif line.startswith('DATE'): # data header colsstr = line.lower().split() varstr = '' for it, elem in enumerate(colsstr): if it > 2: varstr += elem[-1] varstr = varstr[:4] stream.header["col-x"] = varstr[0].upper() stream.header["col-y"] = varstr[1].upper() stream.header["col-z"] = varstr[2].upper() stream.header["unit-col-x"] = 'nT' stream.header["unit-col-y"] = 'nT' stream.header["unit-col-z"] = 'nT' stream.header["unit-col-f"] = 'nT' if varstr.endswith('g'): stream.header["unit-col-df"] = 'nT' stream.header["col-df"] = 'G' stream.header["col-f"] = 'F' else: stream.header["col-f"] = 'F' if varstr in ['dhzf','dhzg']: #stream.header["col-x"] = 'H' #stream.header["col-y"] = 'D' #stream.header["col-z"] = 'Z' stream.header["unit-col-y"] = 'deg' stream.header['DataComponents'] = 'HDZF' elif varstr in ['ehzf','ehzg']: #stream.header["col-x"] = 'H' #stream.header["col-y"] = 'E' #stream.header["col-z"] = 'Z' stream.header['DataComponents'] = 'HEZF' elif varstr in ['dhif','dhig']: stream.header["col-x"] = 'I' stream.header["col-y"] = 'D' stream.header["col-z"] = 'F' stream.header["unit-col-x"] = 'deg' stream.header["unit-col-y"] = 'deg' stream.header['DataComponents'] = 'IDFF' elif varstr in ['hdzf','hdzg']: #stream.header["col-x"] = 'H' #stream.header["col-y"] = 'D' stream.header["unit-col-y"] = 'deg' #stream.header["col-z"] = 'Z' stream.header['DataComponents'] = 'HDZF' else: #stream.header["col-x"] = 'X' #stream.header["col-y"] = 'Y' #stream.header["col-z"] = 'Z' stream.header['DataComponents'] = 'XYZF' elif headonly: # skip data for option headonly continue elif line.startswith('%'): pass else: # data entry - may be written in multiple columns # row beinhaltet die Werte eine Zeile # transl. row values contains a line row=[] # Verwende das letzte Zeichen von "line" nicht, d.h. line[:-1], # da darin der Zeilenumbruch "\n" steht # transl. Do not use the last character of "line", d.h. line [:-1], # since this is the line break "\n" for val in line[:-1].split(): # nur nicht-leere Spalten hinzufuegen # transl. Just add non-empty columns if val.strip()!="": row.append(val.strip()) # Baue zweidimensionales Array auf # transl. Build two-dimensional array array[0].append( date2num(datetime.strptime(row[0]+'-'+row[1],"%Y-%m-%d-%H:%M:%S.%f")) ) if float(row[3]) >= NOT_REPORTED: row[3] = np.nan if float(row[4]) >= NOT_REPORTED: row[4] = np.nan if float(row[5]) >= NOT_REPORTED: row[5] = np.nan if varstr in ['dhzf','dhzg']: array[1].append( float(row[4]) ) array[2].append( float(row[3])/60.0 ) array[3].append( float(row[5]) ) elif varstr in ['ehzf','ehzg']: array[1].append( float(row[4]) ) array[2].append( float(row[3]) ) array[3].append( float(row[5]) ) elif varstr in ['dhif','dhig']: array[1].append( float(row[5])/60.0 ) array[2].append( float(row[3])/60.0 ) array[3].append( float(row[6]) ) elif varstr in ['hdzf','hdzg']: array[1].append( float(row[3]) ) array[2].append( float(row[4])/60.0 ) array[3].append( float(row[5]) ) else: array[1].append( float(row[3]) ) array[2].append( float(row[4]) ) array[3].append( float(row[5]) ) try: if float(row[6]) < NOT_REPORTED: if varstr[-1]=='f': array[4].append(float(elem[6])) elif varstr[-1]=='g' and varstr=='xyzg': array[4].append(np.sqrt(float(row[3])**2+float(row[4])**2+float(row[5])**2) - float(row[6])) array[dfpos].append(float(row[6])) elif varstr[-1]=='g' and varstr in ['hdzg','dhzg','ehzg']: array[4].append(np.sqrt(float(row[3])**2+float(row[5])**2) - float(row[6])) array[dfpos].append(float(row[6])) elif varstr[-1]=='g' and varstr in ['dhig']: array[4].append(float(row[6])) array[dfpos].append(float(row[6])) else: raise ValueError else: array[4].append(float('nan')) except: if not float(row[6]) >= NOT_REPORTED: array[4].append(float(row[6])) else: array[4].append(float('nan')) #data.append(row) fh.close() for idx, elem in enumerate(array): array[idx] = np.asarray(array[idx]) stream = DataStream([LineStruct()],stream.header,np.asarray(array)) sr = stream.samplingrate() return stream def writeIAGA(datastream, filename, **kwargs): """ Writing IAGA2002 format data. """ mode = kwargs.get('mode') useg = kwargs.get('useg') def OpenFile(filename, mode='w'): if sys.version_info >= (3,0,0): f = open(filename, mode, newline='') else: f = open(filename, mode+'b') return f if os.path.isfile(filename): if mode == 'skip': # skip existing inputs exst = read(path_or_url=filename) datastream = mergeStreams(exst,datastream,extend=True) myFile= OpenFile(filename) elif mode == 'replace': # replace existing inputs exst = read(path_or_url=filename) datastream = mergeStreams(datastream,exst,extend=True) myFile= OpenFile(filename) elif mode == 'append': myFile= OpenFile(filename,mode='a') else: # overwrite mode #os.remove(filename) ?? necessary ?? myFile= OpenFile(filename) else: myFile= OpenFile(filename) header = datastream.header datacomp = header.get('DataComponents'," ") if datacomp in ['hez','HEZ','hezf','HEZF','hezg','HEZG']: order = [1,0,2] datacomp = 'EHZ' elif datacomp in ['hdz','HDZ','hdzf','HDZF','hdzg','HDZG']: order = [1,0,2] datacomp = 'DHZ' elif datacomp in ['idf','IDF','idff','IDFF','idfg','IDFG']: order = [1,3,0] datacomp = 'DHI' elif datacomp in ['xyz','XYZ','xyzf','XYZF','xyzg','XYZG']: order = [0,1,2] datacomp = 'XYZ' elif datacomp in ['ehz','EHZ','ehzf','EHZF','ehzg','EHZG']: order = [0,1,2] datacomp = 'EHZ' elif datacomp in ['dhz','DHZ','dhzf','DHZF','dhzg','DHZG']: order = [0,1,2] datacomp = 'DHZ' elif datacomp in ['dhi','DHI','dhif','DHIF','dhig','DHIG']: order = [0,1,2] datacomp = 'DHI' else: order = [0,1,2] datacomp = 'XYZ' find = KEYLIST.index('f') findg = KEYLIST.index('df') if len(datastream.ndarray[findg]) > 0: useg = True if len(datastream.ndarray[find]) > 0: if not useg: datacomp = datacomp+'F' else: datacomp = datacomp+'G' else: datacomp = datacomp+'F' publevel = str(header.get('DataPublicationLevel'," ")) if publevel == '2': publ = 'Provisional' elif publevel == '3': publ = 'Quasi-definitive' elif publevel == '4': publ = 'Definitive' else: publ = 'Variation' proj = header.get('DataLocationReference','') longi = header.get('DataAcquisitionLongitude',' ') lati = header.get('DataAcquisitionLatitude',' ') if not longi=='' or lati=='': if proj == '': pass else: if proj.find('EPSG:') > 0: epsg = int(proj.split('EPSG:')[1].strip()) if not epsg==4326: longi,lati = convertGeoCoordinate(float(longi),float(lati),'epsg:'+str(epsg),'epsg:4326') line = [] if not mode == 'append': #if header.get('Elevation') > 0: # print(header) line.append(' Format %-15s IAGA-2002 %-34s |\n' % (' ',' ')) line.append(' Source of Data %-7s %-44s |\n' % (' ',header.get('StationInstitution'," ")[:44])) line.append(' Station Name %-9s %-44s |\n' % (' ', header.get('StationName'," ")[:44])) line.append(' IAGA Code %-12s %-44s |\n' % (' ',header.get('StationIAGAcode'," ")[:44])) line.append(' Geodetic Latitude %-4s %-44s |\n' % (' ',str(lati)[:44])) line.append(' Geodetic Longitude %-3s %-44s |\n' % (' ',str(longi)[:44])) line.append(' Elevation %-12s %-44s |\n' % (' ',str(header.get('DataElevation'," "))[:44])) line.append(' Reported %-13s %-44s |\n' % (' ',datacomp)) line.append(' Sensor Orientation %-3s %-44s |\n' % (' ',header.get('DataSensorOrientation'," ").upper()[:44])) line.append(' Digital Sampling %-5s %-44s |\n' % (' ',str(header.get('DataDigitalSampling'," "))[:44])) line.append(' Data Interval Type %-3s %-44s |\n' % (' ',(str(header.get('DataSamplingRate'," "))+' ('+header.get('DataSamplingFilter'," ")+')')[:44])) line.append(' Data Type %-12s %-44s |\n' % (' ',publ[:44])) if not header.get('DataPublicationDate','') == '': line.append(' {a:<20} {b:<45s}|\n'.format(a='Publication date',b=str(header.get('DataPublicationDate'))[:10])) # Optional header part: skipopt = False if not skipopt: if not header.get('SensorID','') == '': line.append(' #{a:<20} {b:<45s}|\n'.format(a='V-Instrument',b=header.get('SensorID')[:44])) if not header.get('SecondarySensorID','') == '': line.append(' #{a:<20} {b:<45s}|\n'.format(a='F-Instrument',b=header.get('SecondarySensorID')[:44])) if not header.get('StationMeans','') == '': try: meanlist = header.get('StationMeans') # Assume something like H:xxxx,D:xxx,Z:xxxx meanlist = meanlist.split(',') for me in meanlist: if me.startswith('H'): hval = me.split(':') line.append(' #{a:<20} {b:<45s}|\n'.format(a='Approx H',b=hval[1])) except: pass line.append(' #{a:<20} {b:<45s}|\n'.format(a='File created by',b='MagPy '+magpyversion)) iagacode = header.get('StationIAGAcode',"") line.append('DATE TIME DOY %8s %9s %9s %9s |\n' % (iagacode+datacomp[0],iagacode+datacomp[1],iagacode+datacomp[2],iagacode+datacomp[3])) try: myFile.writelines(line) # Write header sequence of strings to a file except IOError: pass try: line = [] ndtype = False if len(datastream.ndarray[0]) > 0: ndtype = True fulllength = datastream.length()[0] # Possible types: DHIF, DHZF, XYZF, or DHIG, DHZG, XYZG #datacomp = 'EHZ' #datacomp = 'DHZ' #datacomp = 'DHI' #datacomp = 'XYZ' xmult = 1.0 ymult = 1.0 zmult = 1.0 xind = order[0]+1 yind = order[1]+1 zind = order[2]+1 if len(datastream.ndarray[xind]) == 0 or len(datastream.ndarray[yind]) == 0 or len(datastream.ndarray[zind]) == 0: print("writeIAGA02: WARNING! Data missing in X, Y or Z component! Writing anyway...") find = KEYLIST.index('f') if datacomp.startswith('DHZ'): xmult = 60.0 elif datacomp.startswith('DHI'): xmult = 60.0 zmult = 60.0 for i in range(fulllength): if not ndtype: elem = datastream[i] xval = elem.x yval = elem.y zval = elem.z fval = elem.f timeval = elem.time else: if len(datastream.ndarray[xind]) > 0: xval = datastream.ndarray[xind][i]*xmult else: xval = NOT_REPORTED if len(datastream.ndarray[yind]) > 0: yval = datastream.ndarray[yind][i] if order[1] == '3': yval = datastream.ndarray[yind][i]*np.cos(datastream.ndarray[zind][i]*np.pi/180.) else: yval = NOT_REPORTED if len(datastream.ndarray[zind]) > 0: zval = datastream.ndarray[zind][i]*zmult else: zval = NOT_REPORTED if len(datastream.ndarray[find]) > 0: if not useg: fval = datastream.ndarray[find][i] else: fval = np.sqrt(xval**2+yval**2+zval**2)-datastream.ndarray[find][i] else: fval = NOT_REPORTED timeval = datastream.ndarray[0][i] row = '' try: row = datetime.strftime(num2date(timeval).replace(tzinfo=None),"%Y-%m-%d %H:%M:%S.%f") row = row[:-3] doi = datetime.strftime(num2date(timeval).replace(tzinfo=None), "%j") row += ' %s' % str(doi) except: row = '' pass if isnan(xval): row += '%13.2f' % MISSING_DATA else: row += '%13.2f' % xval if isnan(yval): row += '%10.2f' % MISSING_DATA else: row += '%10.2f' % yval if isnan(zval): row += '%10.2f' % MISSING_DATA else: row += '%10.2f' % zval if isnan(fval): row += '%10.2f' % MISSING_DATA else: row += '%10.2f' % fval line.append(row + '\n') try: myFile.writelines( line ) pass finally: myFile.close() except IOError: return False pass return True
hschovanec-usgs/magpy
magpy/lib/format_iaga02.py
Python
gpl-3.0
20,820
#include <QMessageBox> #include "charakterform.h" #include "fertigkeitform.h" #include "ui_charakterform.h" #include "ui_fertigkeitform.h" CharakterForm::CharakterForm(QDialog *parent, std::shared_ptr<CharakterManager> charakterManager) : QDialog(parent),charakterManager(charakterManager), ui(new Ui::charakterform){ ui->setupUi(this); fertigkeitForm = Ptr<FertigkeitForm>(new FertigkeitForm(this,charakterManager)); fertigkeitForm->setModal(true); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); connect(ui->weiterButton,SIGNAL(clicked()),this,SLOT(startGenerierung())); connect(ui->abbrechenButton,SIGNAL(clicked()),this,SLOT(abbrechenGenerierung())); connect(fertigkeitForm->ui->abbrechenButton,SIGNAL(clicked()),this,SLOT(abbrechenGenerierung())); connect(fertigkeitForm.get(),SIGNAL(abschliessen()),this,SLOT(abschliessenGenerierung())); connect(fertigkeitForm.get(),SIGNAL(abbrechen()),this,SLOT(abbrechenGenerierung())); } CharakterForm::~CharakterForm(){ delete ui; } void CharakterForm::startGenerierung(){ QString name = ui->lineEditName->text(); QString beschreibung = ui->textEditBeschreibung->toPlainText(); if(name == NULL || name.trimmed().size() == 0){ QMessageBox::warning(this,tr("Pflichtfeld nicht gesetzt."),tr("Bitte geben sie einen Namen für ihren Chrakter an."),QMessageBox::Ok); }else{ charakterManager->addCharakterBeschreibung(name,beschreibung); this->close(); fertigkeitForm->reset(); fertigkeitForm->show(); } } void CharakterForm::abschliessenGenerierung(){ charakterManager->insert(*(charakterManager->getCurrentCharakter().get())); charakterManager->saveCharakterToFile(); resetForm(); emit beenden(); } void CharakterForm::abbrechenGenerierung(){ foreach(QLineEdit *widget, this->findChildren<QLineEdit*>()) { widget->clear(); } foreach(QTextEdit *widget, this->findChildren<QTextEdit*>()) { widget->clear(); } this->close(); } void CharakterForm::resetForm(){ ui->lineEditName->clear(); ui->textEditBeschreibung->clear(); }
FireballGfx/FUK
Fuk/charakterform.cpp
C++
gpl-3.0
2,158
<?php session_start(); if($_SESSION['logged_in'] != true) header("Location: index.php"); ?><!doctype html> <html> <head> <meta name="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="refresh" content="3; URL=admin.php"> <link href="css/login.css" rel='stylesheet' type='text/css' /> <link href='http://fonts.googleapis.com/css?family=Open+Sans:600italic,400,300,600,700' rel='stylesheet' type='text/css'> <script src="head.js" type="text/javascript"></script> <title>SSM - Eingeloggt</title> </head> <body> <div class="main"> <h1 align="center">Willkommen <?php echo $_SESSION['usr']; ?>!</h1> <?php if(empty($_SERVER['HTTPS'])){ echo '<h3 align="center"><span style="color:red">Verbidung ungesichert!</span></h3>'; } else { echo '<h3 align="center"><span style="color:green">Verbindung gesichert.</span></h3>'; } ?> <h2 align="center">Sie haben sich erfolgreich angemeldet.</h2> <p align="center">Einen Moment bitte...</p> </div> </body> </html> <!--- <script type="text/JavaScript"> setTimeout("location.href = 'admin.php';",1500); </script> --->
jonashouben/SSM
design-html5/private.php
PHP
gpl-3.0
1,106
using System; using System.Collections.Generic; using Terraria.DataStructures; namespace Terraria { public static class Wiring { public static bool running = false; [ThreadStatic] private static Dictionary<Point16, bool> wireSkip; [ThreadStatic] private static DoubleStack<Point16> wireList; [ThreadStatic] private static Dictionary<Point16, byte> toProcess; public static Vector2[] teleport = new Vector2[2]; private static int maxPump = 20; private static int[] inPumpX = new int[Wiring.maxPump]; private static int[] inPumpY = new int[Wiring.maxPump]; private static int numInPump = 0; private static int[] outPumpX = new int[Wiring.maxPump]; private static int[] outPumpY = new int[Wiring.maxPump]; private static int numOutPump = 0; private static int maxMech = 1000; private static int[] mechX = new int[Wiring.maxMech]; private static int[] mechY = new int[Wiring.maxMech]; private static int numMechs = 0; private static int[] mechTime = new int[Wiring.maxMech]; public static void SkipWire(int x, int y) { if (wireSkip == null) wireSkip = new Dictionary<Point16, bool>(); Wiring.wireSkip[new Point16(x, y)] = true; } public static void SkipWire(Point16 point) { if (wireSkip == null) wireSkip = new Dictionary<Point16, bool>(); Wiring.wireSkip[point] = true; } public static void UpdateMech() { for (int i = Wiring.numMechs - 1; i >= 0; i--) { Wiring.mechTime[i]--; if (Main.tile[Wiring.mechX[i], Wiring.mechY[i]].active() && Main.tile[Wiring.mechX[i], Wiring.mechY[i]].type == 144) { if (Main.tile[Wiring.mechX[i], Wiring.mechY[i]].frameY == 0) { Wiring.mechTime[i] = 0; } else { int num = (int)(Main.tile[Wiring.mechX[i], Wiring.mechY[i]].frameX / 18); if (num == 0) { num = 60; } else if (num == 1) { num = 180; } else if (num == 2) { num = 300; } if (Math.IEEERemainder((double)Wiring.mechTime[i], (double)num) == 0.0) { Wiring.mechTime[i] = 18000; Wiring.TripWire(Wiring.mechX[i], Wiring.mechY[i], 1, 1); } } } if (Wiring.mechTime[i] <= 0) { if (Main.tile[Wiring.mechX[i], Wiring.mechY[i]].active() && Main.tile[Wiring.mechX[i], Wiring.mechY[i]].type == 144) { Main.tile[Wiring.mechX[i], Wiring.mechY[i]].frameY = 0; NetMessage.SendTileSquare(-1, Wiring.mechX[i], Wiring.mechY[i], 1); } for (int j = i; j < Wiring.numMechs; j++) { Wiring.mechX[j] = Wiring.mechX[j + 1]; Wiring.mechY[j] = Wiring.mechY[j + 1]; Wiring.mechTime[j] = Wiring.mechTime[j + 1]; } Wiring.numMechs--; } } } public static void hitSwitch(int i, int j) { if (Main.tile[i, j] == null) { return; } if (Main.tile[i, j].type == 135 || Main.tile[i, j].type == 314) { //Main.PlaySound(28, i * 16, j * 16, 0); Wiring.TripWire(i, j, 1, 1); return; } if (Main.tile[i, j].type == 136) { if (Main.tile[i, j].frameY == 0) { Main.tile[i, j].frameY = 18; } else { Main.tile[i, j].frameY = 0; } //Main.PlaySound(28, i * 16, j * 16, 0); Wiring.TripWire(i, j, 1, 1); return; } if (Main.tile[i, j].type == 144) { if (Main.tile[i, j].frameY == 0) { Main.tile[i, j].frameY = 18; if (Main.netMode != 1) { Wiring.checkMech(i, j, 18000); } } else { Main.tile[i, j].frameY = 0; } //Main.PlaySound(28, i * 16, j * 16, 0); return; } if (Main.tile[i, j].type == 132) { short num = 36; int num2 = (int)(Main.tile[i, j].frameX / 18 * -1); int num3 = (int)(Main.tile[i, j].frameY / 18 * -1); num2 %= 4; if (num2 < -1) { num2 += 2; num = -36; } num2 += i; num3 += j; for (int k = num2; k < num2 + 2; k++) { for (int l = num3; l < num3 + 2; l++) { if (Main.tile[k, l].type == 132) { Tile expr_1D3 = Main.tile[k, l]; expr_1D3.frameX += num; } } } WorldGen.TileFrame(num2, num3, false, false); //Main.PlaySound(28, i * 16, j * 16, 0); Wiring.TripWire(num2, num3, 2, 2); } } public static bool checkMech(int i, int j, int time) { for (int k = 0; k < Wiring.numMechs; k++) { if (Wiring.mechX[k] == i && Wiring.mechY[k] == j) { return false; } } if (Wiring.numMechs < Wiring.maxMech - 1) { Wiring.mechX[Wiring.numMechs] = i; Wiring.mechY[Wiring.numMechs] = j; Wiring.mechTime[Wiring.numMechs] = time; Wiring.numMechs++; return true; } return false; } private static void xferWater() { for (int i = 0; i < Wiring.numInPump; i++) { int num = Wiring.inPumpX[i]; int num2 = Wiring.inPumpY[i]; int liquid = (int)Main.tile[num, num2].liquid; if (liquid > 0) { bool flag = Main.tile[num, num2].lava(); bool flag2 = Main.tile[num, num2].honey(); for (int j = 0; j < Wiring.numOutPump; j++) { int num3 = Wiring.outPumpX[j]; int num4 = Wiring.outPumpY[j]; int liquid2 = (int)Main.tile[num3, num4].liquid; if (liquid2 < 255) { bool flag3 = Main.tile[num3, num4].lava(); bool flag4 = Main.tile[num3, num4].honey(); if (liquid2 == 0) { flag3 = flag; flag4 = flag2; } if (flag == flag3 && flag2 == flag4) { int num5 = liquid; if (num5 + liquid2 > 255) { num5 = 255 - liquid2; } Tile expr_102 = Main.tile[num3, num4]; expr_102.liquid += (byte)num5; Tile expr_11E = Main.tile[num, num2]; expr_11E.liquid -= (byte)num5; liquid = (int)Main.tile[num, num2].liquid; Main.tile[num3, num4].lava(flag); Main.tile[num3, num4].honey(flag2); WorldGen.SquareTileFrame(num3, num4, true); if (Main.tile[num, num2].liquid == 0) { Main.tile[num, num2].lava(false); WorldGen.SquareTileFrame(num, num2, true); break; } } } } WorldGen.SquareTileFrame(num, num2, true); } } } private static void TripWire(int left, int top, int width, int height) { if (wireList == null) wireList = new DoubleStack<Point16>(1024, 0); Wiring.running = true; if (Wiring.wireList.Count != 0) { Wiring.wireList.Clear(true); } for (int i = left; i < left + width; i++) { for (int j = top; j < top + height; j++) { Point16 back = new Point16(i, j); Tile tile = Main.tile[i, j]; if (tile != null && tile.wire()) { Wiring.wireList.PushBack(back); } } } Vector2[] array = new Vector2[6]; Wiring.teleport[0].X = -1f; Wiring.teleport[0].Y = -1f; Wiring.teleport[1].X = -1f; Wiring.teleport[1].Y = -1f; if (Wiring.wireList.Count > 0) { Wiring.numInPump = 0; Wiring.numOutPump = 0; Wiring.hitWire(Wiring.wireList, 1); if (Wiring.numInPump > 0 && Wiring.numOutPump > 0) { Wiring.xferWater(); } } for (int k = left; k < left + width; k++) { for (int l = top; l < top + height; l++) { Point16 back = new Point16(k, l); Tile tile2 = Main.tile[k, l]; if (tile2 != null && tile2.wire2()) { Wiring.wireList.PushBack(back); } } } array[0] = Wiring.teleport[0]; array[1] = Wiring.teleport[1]; Wiring.teleport[0].X = -1f; Wiring.teleport[0].Y = -1f; Wiring.teleport[1].X = -1f; Wiring.teleport[1].Y = -1f; if (Wiring.wireList.Count > 0) { Wiring.numInPump = 0; Wiring.numOutPump = 0; Wiring.hitWire(Wiring.wireList, 2); if (Wiring.numInPump > 0 && Wiring.numOutPump > 0) { Wiring.xferWater(); } } array[2] = Wiring.teleport[0]; array[3] = Wiring.teleport[1]; Wiring.teleport[0].X = -1f; Wiring.teleport[0].Y = -1f; Wiring.teleport[1].X = -1f; Wiring.teleport[1].Y = -1f; for (int m = left; m < left + width; m++) { for (int n = top; n < top + height; n++) { Point16 back = new Point16(m, n); Tile tile3 = Main.tile[m, n]; if (tile3 != null && tile3.wire3()) { Wiring.wireList.PushBack(back); } } } if (Wiring.wireList.Count > 0) { Wiring.numInPump = 0; Wiring.numOutPump = 0; Wiring.hitWire(Wiring.wireList, 3); if (Wiring.numInPump > 0 && Wiring.numOutPump > 0) { Wiring.xferWater(); } } array[4] = Wiring.teleport[0]; array[5] = Wiring.teleport[1]; for (int num = 0; num < 5; num += 2) { Wiring.teleport[0] = array[num]; Wiring.teleport[1] = array[num + 1]; if (Wiring.teleport[0].X >= 0f && Wiring.teleport[1].X >= 0f) { Wiring.Teleport(); } } Wiring.running = false; } private static void hitWire(DoubleStack<Point16> next, int wireType) { if (toProcess == null) toProcess = new Dictionary<Point16, byte>(); if (wireSkip == null) wireSkip = new Dictionary<Point16, bool>(); for (int i = 0; i < next.Count; i++) { Point16 point = next.PopFront(); Wiring.SkipWire(point); Wiring.toProcess.Add(point, 4); next.PushBack(point); } while (next.Count > 0) { Point16 key = next.PopFront(); int x = (int)key.x; int y = (int)key.y; if (!Wiring.wireSkip.ContainsKey(key)) { Wiring.hitWireSingle(x, y); } for (int j = 0; j < 4; j++) { int num; int num2; switch (j) { case 0: num = x; num2 = y + 1; break; case 1: num = x; num2 = y - 1; break; case 2: num = x + 1; num2 = y; break; case 3: num = x - 1; num2 = y; break; default: num = x; num2 = y + 1; break; } if (num >= 2 && num < Main.maxTilesX - 2 && num2 >= 2 && num2 < Main.maxTilesY - 2) { Tile tile = Main.tile[num, num2]; if (tile != null) { bool flag; switch (wireType) { case 1: flag = tile.wire(); break; case 2: flag = tile.wire2(); break; case 3: flag = tile.wire3(); break; default: flag = false; break; } if (flag) { Point16 point2 = new Point16(num, num2); byte b; if (Wiring.toProcess.TryGetValue(point2, out b)) { b -= 1; if (b == 0) { Wiring.toProcess.Remove(point2); } else { Wiring.toProcess[point2] = b; } } else { next.PushBack(point2); Wiring.toProcess.Add(point2, 3); } } } } } } Wiring.wireSkip.Clear(); Wiring.toProcess.Clear(); } private static bool hitWireSingle(int i, int j) { Tile tile = Main.tile[i, j]; int type = (int)tile.type; if (tile.active() && type >= 255 && type <= 268) { if (type >= 262) { Tile expr_35 = tile; expr_35.type -= 7; } else { Tile expr_46 = tile; expr_46.type += 7; } NetMessage.SendTileSquare(-1, i, j, 1); } if (tile.actuator() && (type != 226 || (double)j <= Main.worldSurface || NPC.downedPlantBoss)) { if (tile.inActive()) { Wiring.ReActive(i, j); } else { Wiring.DeActive(i, j); } } if (tile.active()) { if (type == 144) { Wiring.hitSwitch(i, j); WorldGen.SquareTileFrame(i, j, true); NetMessage.SendTileSquare(-1, i, j, 1); } else if (type == 130) { if (Main.tile[i, j - 1] == null || !Main.tile[i, j - 1].active() || Main.tile[i, j - 1].type != 21) { tile.type = 131; WorldGen.SquareTileFrame(i, j, true); NetMessage.SendTileSquare(-1, i, j, 1); } } else if (type == 131) { tile.type = 130; WorldGen.SquareTileFrame(i, j, true); NetMessage.SendTileSquare(-1, i, j, 1); } else if (type == 11) { if (WorldGen.CloseDoor(i, j, true)) { NetMessage.SendData(19, -1, -1, "", 1, (float)i, (float)j, 0f, 0); } } else if (type == 10) { int num = 1; if (Main.rand.Next(2) == 0) { num = -1; } if (!WorldGen.OpenDoor(i, j, num)) { if (WorldGen.OpenDoor(i, j, -num)) { NetMessage.SendData(19, -1, -1, "", 0, (float)i, (float)j, (float)(-(float)num), 0); } } else { NetMessage.SendData(19, -1, -1, "", 0, (float)i, (float)j, (float)num, 0); } } else if (type == 216) { WorldGen.LaunchRocket(i, j); Wiring.SkipWire(i, j); } else if (type == 335) { int num2 = j - (int)(tile.frameY / 18); int num3 = i - (int)(tile.frameX / 18); Wiring.SkipWire(num3, num2); Wiring.SkipWire(num3, num2 + 1); Wiring.SkipWire(num3 + 1, num2); Wiring.SkipWire(num3 + 1, num2 + 1); if (Wiring.checkMech(num3, num2, 30)) { WorldGen.LaunchRocketSmall(num3, num2); } } else if (type == 338) { int num4 = j - (int)(tile.frameY / 18); int num5 = i - (int)(tile.frameX / 18); Wiring.SkipWire(num5, num4); Wiring.SkipWire(num5, num4 + 1); if (Wiring.checkMech(num5, num4, 30)) { bool flag = false; for (int k = 0; k < 1000; k++) { if (Main.projectile[k].active && Main.projectile[k].aiStyle == 73 && Main.projectile[k].ai[0] == (float)num5 && Main.projectile[k].ai[1] == (float)num4) { flag = true; break; } } if (!flag) { Projectile.NewProjectile((float)(num5 * 16 + 8), (float)(num4 * 16 + 2), 0f, 0f, 419 + Main.rand.Next(4), 0, 0f, Main.myPlayer, (float)num5, (float)num4); } } } else if (type == 235) { int num6 = i - (int)(tile.frameX / 18); if (tile.wall != 87 || (double)j <= Main.worldSurface || NPC.downedPlantBoss) { if (Wiring.teleport[0].X == -1f) { Wiring.teleport[0].X = (float)num6; Wiring.teleport[0].Y = (float)j; if (tile.halfBrick()) { Vector2[] expr_3EF_cp_0 = Wiring.teleport; int expr_3EF_cp_1 = 0; expr_3EF_cp_0[expr_3EF_cp_1].Y = expr_3EF_cp_0[expr_3EF_cp_1].Y + 0.5f; } } else if (Wiring.teleport[0].X != (float)num6 || Wiring.teleport[0].Y != (float)j) { Wiring.teleport[1].X = (float)num6; Wiring.teleport[1].Y = (float)j; if (tile.halfBrick()) { Vector2[] expr_46C_cp_0 = Wiring.teleport; int expr_46C_cp_1 = 1; expr_46C_cp_0[expr_46C_cp_1].Y = expr_46C_cp_0[expr_46C_cp_1].Y + 0.5f; } } } } else if (type == 4) { if (tile.frameX < 66) { Tile expr_491 = tile; expr_491.frameX += 66; } else { Tile expr_4A3 = tile; expr_4A3.frameX -= 66; } NetMessage.SendTileSquare(-1, i, j, 1); } else if (type == 149) { if (tile.frameX < 54) { Tile expr_4D3 = tile; expr_4D3.frameX += 54; } else { Tile expr_4E5 = tile; expr_4E5.frameX -= 54; } NetMessage.SendTileSquare(-1, i, j, 1); } else if (type == 244) { int l; for (l = (int)(tile.frameX / 18); l >= 3; l -= 3) { } int m; for (m = (int)(tile.frameY / 18); m >= 3; m -= 3) { } int num7 = i - l; int num8 = j - m; int num9 = 54; if (Main.tile[num7, num8].frameX >= 54) { num9 = -54; } for (int n = num7; n < num7 + 3; n++) { for (int num10 = num8; num10 < num8 + 2; num10++) { Wiring.SkipWire(n, num10); Main.tile[n, num10].frameX = (short)((int)Main.tile[n, num10].frameX + num9); } } } else if (type == 42) { int num11; for (num11 = (int)(tile.frameY / 18); num11 >= 2; num11 -= 2) { } int num12 = j - num11; short num13 = 18; if (tile.frameX > 0) { num13 = -18; } Tile expr_60C = Main.tile[i, num12]; expr_60C.frameX += num13; Tile expr_62A = Main.tile[i, num12 + 1]; expr_62A.frameX += num13; Wiring.SkipWire(i, num12); Wiring.SkipWire(i, num12 + 1); NetMessage.SendTileSquare(-1, i, j, 2); } else if (type == 93) { int num14; for (num14 = (int)(tile.frameY / 18); num14 >= 3; num14 -= 3) { } num14 = j - num14; short num15 = 18; if (tile.frameX > 0) { num15 = -18; } Tile expr_69D = Main.tile[i, num14]; expr_69D.frameX += num15; Tile expr_6BB = Main.tile[i, num14 + 1]; expr_6BB.frameX += num15; Tile expr_6D9 = Main.tile[i, num14 + 2]; expr_6D9.frameX += num15; Wiring.SkipWire(i, num14); Wiring.SkipWire(i, num14 + 1); Wiring.SkipWire(i, num14 + 2); NetMessage.SendTileSquare(-1, i, num14 + 1, 3); } else if (type == 126 || type == 95 || type == 100 || type == 173) { int num16; for (num16 = (int)(tile.frameY / 18); num16 >= 2; num16 -= 2) { } num16 = j - num16; int num17 = (int)(tile.frameX / 18); if (num17 > 1) { num17 -= 2; } num17 = i - num17; short num18 = 36; if (Main.tile[num17, num16].frameX > 0) { num18 = -36; } Tile expr_795 = Main.tile[num17, num16]; expr_795.frameX += num18; Tile expr_7B4 = Main.tile[num17, num16 + 1]; expr_7B4.frameX += num18; Tile expr_7D3 = Main.tile[num17 + 1, num16]; expr_7D3.frameX += num18; Tile expr_7F4 = Main.tile[num17 + 1, num16 + 1]; expr_7F4.frameX += num18; Wiring.SkipWire(num17, num16); Wiring.SkipWire(num17 + 1, num16); Wiring.SkipWire(num17, num16 + 1); Wiring.SkipWire(num17 + 1, num16 + 1); NetMessage.SendTileSquare(-1, num17, num16, 3); } else if (type == 34) { int num19; for (num19 = (int)(tile.frameY / 18); num19 >= 3; num19 -= 3) { } int num20 = j - num19; int num21 = (int)(tile.frameX / 18); if (num21 > 2) { num21 -= 3; } num21 = i - num21; short num22 = 54; if (Main.tile[num21, num20].frameX > 0) { num22 = -54; } for (int num23 = num21; num23 < num21 + 3; num23++) { for (int num24 = num20; num24 < num20 + 3; num24++) { Tile expr_8B9 = Main.tile[num23, num24]; expr_8B9.frameX += num22; Wiring.SkipWire(num23, num24); } } NetMessage.SendTileSquare(-1, num21 + 1, num20 + 1, 3); } else if (type == 314) { if (Wiring.checkMech(i, j, 5)) { Minecart.FlipSwitchTrack(i, j); } } else if (type == 33 || type == 174) { short num25 = 18; if (tile.frameX > 0) { num25 = -18; } Tile expr_934 = tile; expr_934.frameX += num25; NetMessage.SendTileSquare(-1, i, j, 3); } else if (type == 92) { int num26 = j - (int)(tile.frameY / 18); short num27 = 18; if (tile.frameX > 0) { num27 = -18; } for (int num28 = num26; num28 < num26 + 6; num28++) { Tile expr_987 = Main.tile[i, num28]; expr_987.frameX += num27; Wiring.SkipWire(i, num28); } NetMessage.SendTileSquare(-1, i, num26 + 3, 7); } else if (type == 137) { int num29 = (int)(tile.frameY / 18); if (num29 == 0 && Wiring.checkMech(i, j, 180)) { int num30 = -1; if (tile.frameX != 0) { num30 = 1; } float speedX = (float)(12 * num30); int damage = 20; int type2 = 98; Vector2 vector = new Vector2((float)(i * 16 + 8), (float)(j * 16 + 7)); vector.X += (float)(10 * num30); vector.Y += 2f; Projectile.NewProjectile((float)((int)vector.X), (float)((int)vector.Y), speedX, 0f, type2, damage, 2f, Main.myPlayer, 0f, 0f); } if (num29 == 1 && Wiring.checkMech(i, j, 180)) { int num31 = -1; if (tile.frameX != 0) { num31 = 1; } float speedX2 = (float)(12 * num31); int damage2 = 40; int type3 = 184; Vector2 vector2 = new Vector2((float)(i * 16 + 8), (float)(j * 16 + 7)); vector2.X += (float)(10 * num31); vector2.Y += 2f; Projectile.NewProjectile((float)((int)vector2.X), (float)((int)vector2.Y), speedX2, 0f, type3, damage2, 2f, Main.myPlayer, 0f, 0f); } if (num29 == 2 && Wiring.checkMech(i, j, 180)) { int num32 = -1; if (tile.frameX != 0) { num32 = 1; } float speedX3 = (float)(5 * num32); int damage3 = 40; int type4 = 187; Vector2 vector3 = new Vector2((float)(i * 16 + 8), (float)(j * 16 + 7)); vector3.X += (float)(10 * num32); vector3.Y += 2f; Projectile.NewProjectile((float)((int)vector3.X), (float)((int)vector3.Y), speedX3, 0f, type4, damage3, 2f, Main.myPlayer, 0f, 0f); } if (num29 == 3 && Wiring.checkMech(i, j, 240)) { float speedX4 = (float)Main.rand.Next(-20, 21) * 0.05f; float speedY = 4f + (float)Main.rand.Next(0, 21) * 0.05f; int damage4 = 40; int type5 = 185; Vector2 vector4 = new Vector2((float)(i * 16 + 8), (float)(j * 16 + 16)); vector4.Y += 6f; Projectile.NewProjectile((float)((int)vector4.X), (float)((int)vector4.Y), speedX4, speedY, type5, damage4, 2f, Main.myPlayer, 0f, 0f); } if (num29 == 4 && Wiring.checkMech(i, j, 90)) { float speedX5 = 0f; float speedY2 = 8f; int damage5 = 60; int type6 = 186; Vector2 vector5 = new Vector2((float)(i * 16 + 8), (float)(j * 16 + 16)); vector5.Y += 10f; Projectile.NewProjectile((float)((int)vector5.X), (float)((int)vector5.Y), speedX5, speedY2, type6, damage5, 2f, Main.myPlayer, 0f, 0f); } } else if (type == 139 || type == 35) { WorldGen.SwitchMB(i, j); } else if (type == 207) { WorldGen.SwitchFountain(i, j); } else if (type == 141) { WorldGen.KillTile(i, j, false, false, true); NetMessage.SendTileSquare(-1, i, j, 1); Projectile.NewProjectile((float)(i * 16 + 8), (float)(j * 16 + 8), 0f, 0f, 108, 250, 10f, Main.myPlayer, 0f, 0f); } else if (type == 210) { WorldGen.ExplodeMine(i, j); } else if (type == 142 || type == 143) { int num33 = j - (int)(tile.frameY / 18); int num34 = (int)(tile.frameX / 18); if (num34 > 1) { num34 -= 2; } num34 = i - num34; Wiring.SkipWire(num34, num33); Wiring.SkipWire(num34, num33 + 1); Wiring.SkipWire(num34 + 1, num33); Wiring.SkipWire(num34 + 1, num33 + 1); if (type == 142) { for (int num35 = 0; num35 < 4; num35++) { if (Wiring.numInPump >= Wiring.maxPump - 1) { break; } int num36; int num37; if (num35 == 0) { num36 = num34; num37 = num33 + 1; } else if (num35 == 1) { num36 = num34 + 1; num37 = num33 + 1; } else if (num35 == 2) { num36 = num34; num37 = num33; } else { num36 = num34 + 1; num37 = num33; } Wiring.inPumpX[Wiring.numInPump] = num36; Wiring.inPumpY[Wiring.numInPump] = num37; Wiring.numInPump++; } } else { for (int num38 = 0; num38 < 4; num38++) { if (Wiring.numOutPump >= Wiring.maxPump - 1) { break; } int num39; int num40; if (num38 == 0) { num39 = num34; num40 = num33 + 1; } else if (num38 == 1) { num39 = num34 + 1; num40 = num33 + 1; } else if (num38 == 2) { num39 = num34; num40 = num33; } else { num39 = num34 + 1; num40 = num33; } Wiring.outPumpX[Wiring.numOutPump] = num39; Wiring.outPumpY[Wiring.numOutPump] = num40; Wiring.numOutPump++; } } } else if (type == 105) { int num41 = j - (int)(tile.frameY / 18); int num42 = (int)(tile.frameX / 18); int num43 = 0; while (num42 >= 2) { num42 -= 2; num43++; } num42 = i - num42; Wiring.SkipWire(num42, num41); Wiring.SkipWire(num42, num41 + 1); Wiring.SkipWire(num42, num41 + 2); Wiring.SkipWire(num42 + 1, num41); Wiring.SkipWire(num42 + 1, num41 + 1); Wiring.SkipWire(num42 + 1, num41 + 2); int num44 = num42 * 16 + 16; int num45 = (num41 + 3) * 16; int num46 = -1; if (num43 == 4) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 1)) { num46 = NPC.NewNPC(num44, num45 - 12, 1, 0); } } else if (num43 == 7) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 49)) { num46 = NPC.NewNPC(num44 - 4, num45 - 6, 49, 0); } } else if (num43 == 8) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 55)) { num46 = NPC.NewNPC(num44, num45 - 12, 55, 0); } } else if (num43 == 9) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 46)) { num46 = NPC.NewNPC(num44, num45 - 12, 46, 0); } } else if (num43 == 10) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 21)) { num46 = NPC.NewNPC(num44, num45, 21, 0); } } else if (num43 == 18) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 67)) { num46 = NPC.NewNPC(num44, num45 - 12, 67, 0); } } else if (num43 == 23) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 63)) { num46 = NPC.NewNPC(num44, num45 - 12, 63, 0); } } else if (num43 == 27) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 85)) { num46 = NPC.NewNPC(num44 - 9, num45, 85, 0); } } else if (num43 == 28) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 74)) { num46 = NPC.NewNPC(num44, num45 - 12, 74, 0); } } else if (num43 == 42) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 58)) { num46 = NPC.NewNPC(num44, num45 - 12, 58, 0); } } else if (num43 == 37) { if (Wiring.checkMech(i, j, 600) && Item.MechSpawn((float)num44, (float)num45, 58) && Item.MechSpawn((float)num44, (float)num45, 1734) && Item.MechSpawn((float)num44, (float)num45, 1867)) { Item.NewItem(num44, num45 - 16, 0, 0, 58, 1, false, 0, false); } } else if (num43 == 50) { if (Wiring.checkMech(i, j, 30) && NPC.MechSpawn((float)num44, (float)num45, 65) && !Collision.SolidTiles(num42 - 2, num42 + 3, num41, num41 + 2)) { num46 = NPC.NewNPC(num44, num45 - 12, 65, 0); } } else if (num43 == 2) { if (Wiring.checkMech(i, j, 600) && Item.MechSpawn((float)num44, (float)num45, 184) && Item.MechSpawn((float)num44, (float)num45, 1735) && Item.MechSpawn((float)num44, (float)num45, 1868)) { Item.NewItem(num44, num45 - 16, 0, 0, 184, 1, false, 0, false); } } else if (num43 == 17) { if (Wiring.checkMech(i, j, 600) && Item.MechSpawn((float)num44, (float)num45, 166)) { Item.NewItem(num44, num45 - 20, 0, 0, 166, 1, false, 0, false); } } else if (num43 == 40) { if (Wiring.checkMech(i, j, 300)) { int[] array = new int[10]; int num47 = 0; for (int num48 = 0; num48 < 200; num48++) { if (Main.npc[num48].active && (Main.npc[num48].type == 17 || Main.npc[num48].type == 19 || Main.npc[num48].type == 22 || Main.npc[num48].type == 38 || Main.npc[num48].type == 54 || Main.npc[num48].type == 107 || Main.npc[num48].type == 108 || Main.npc[num48].type == 142 || Main.npc[num48].type == 160 || Main.npc[num48].type == 207 || Main.npc[num48].type == 209 || Main.npc[num48].type == 227 || Main.npc[num48].type == 228 || Main.npc[num48].type == 229 || Main.npc[num48].type == 358 || Main.npc[num48].type == 369)) { array[num47] = num48; num47++; if (num47 >= 9) { break; } } } if (num47 > 0) { int num49 = array[Main.rand.Next(num47)]; Main.npc[num49].position.X = (float)(num44 - Main.npc[num49].width / 2); Main.npc[num49].position.Y = (float)(num45 - Main.npc[num49].height - 1); NetMessage.SendData(23, -1, -1, "", num49, 0f, 0f, 0f, 0); } } } else if (num43 == 41 && Wiring.checkMech(i, j, 300)) { int[] array2 = new int[10]; int num50 = 0; for (int num51 = 0; num51 < 200; num51++) { if (Main.npc[num51].active && (Main.npc[num51].type == 18 || Main.npc[num51].type == 20 || Main.npc[num51].type == 124 || Main.npc[num51].type == 178 || Main.npc[num51].type == 208 || Main.npc[num51].type == 353)) { array2[num50] = num51; num50++; if (num50 >= 9) { break; } } } if (num50 > 0) { int num52 = array2[Main.rand.Next(num50)]; Main.npc[num52].position.X = (float)(num44 - Main.npc[num52].width / 2); Main.npc[num52].position.Y = (float)(num45 - Main.npc[num52].height - 1); NetMessage.SendData(23, -1, -1, "", num52, 0f, 0f, 0f, 0); } } if (num46 >= 0) { Main.npc[num46].value = 0f; Main.npc[num46].npcSlots = 0f; } } } return true; } public static void Teleport() { if (Wiring.teleport[0].X < Wiring.teleport[1].X + 3f && Wiring.teleport[0].X > Wiring.teleport[1].X - 3f && Wiring.teleport[0].Y > Wiring.teleport[1].Y - 3f && Wiring.teleport[0].Y < Wiring.teleport[1].Y) { return; } Rectangle[] array = new Rectangle[2]; array[0].X = (int)(Wiring.teleport[0].X * 16f); array[0].Width = 48; array[0].Height = 48; array[0].Y = (int)(Wiring.teleport[0].Y * 16f - (float)array[0].Height); array[1].X = (int)(Wiring.teleport[1].X * 16f); array[1].Width = 48; array[1].Height = 48; array[1].Y = (int)(Wiring.teleport[1].Y * 16f - (float)array[1].Height); for (int i = 0; i < 2; i++) { Vector2 value = new Vector2((float)(array[1].X - array[0].X), (float)(array[1].Y - array[0].Y)); if (i == 1) { value = new Vector2((float)(array[0].X - array[1].X), (float)(array[0].Y - array[1].Y)); } for (int j = 0; j < 255; j++) { if (Main.player[j].active && !Main.player[j].dead && !Main.player[j].teleporting && array[i].Intersects(Main.player[j].getRect())) { Vector2 vector = Main.player[j].position + value; Main.player[j].teleporting = true; if (Main.netMode == 2) { ServerSock.CheckSection(j, vector); } Main.player[j].Teleport(vector, 0); if (Main.netMode == 2) { NetMessage.SendData(65, -1, -1, "", 0, (float)j, vector.X, vector.Y, 0); } } } for (int k = 0; k < 200; k++) { if (Main.npc[k].active && !Main.npc[k].teleporting && Main.npc[k].lifeMax > 5 && !Main.npc[k].boss && !Main.npc[k].noTileCollide && array[i].Intersects(Main.npc[k].getRect())) { Main.npc[k].teleporting = true; Main.npc[k].Teleport(Main.npc[k].position + value, 0); } } } for (int l = 0; l < 255; l++) { Main.player[l].teleporting = false; } for (int m = 0; m < 200; m++) { Main.npc[m].teleporting = false; } } public static bool DeActive(int i, int j) { if (!Main.tile[i, j].active() || ((!Main.tileSolid[(int)Main.tile[i, j].type] || Main.tile[i, j].type == 10) && Main.tile[i, j].type != 314)) { return false; } if (Main.tile[i, j - 1].active() && (Main.tile[i, j - 1].type == 5 || Main.tile[i, j - 1].type == 21 || Main.tile[i, j - 1].type == 26 || Main.tile[i, j - 1].type == 77 || Main.tile[i, j - 1].type == 72)) { return false; } Main.tile[i, j].inActive(true); WorldGen.SquareTileFrame(i, j, false); if (Main.netMode != 1) { NetMessage.SendTileSquare(-1, i, j, 1); } return true; } public static bool ReActive(int i, int j) { Main.tile[i, j].inActive(false); WorldGen.SquareTileFrame(i, j, false); if (Main.netMode != 1) { NetMessage.SendTileSquare(-1, i, j, 1); } return true; } } }
NyxStudios/ModBox
Server/Terraria/Wiring.cs
C#
gpl-3.0
32,943
$(function() { (function() { $('.j_toClass').each(function(index, el) { var $it = $(this); var targetTo = $it.attr('data-target'); var thisTo = $it.attr('data-this'); var targetId = $it.attr('href'); var $target = $(targetId); var _fn = { on: function() { $target.addClass(targetTo); $it.addClass(thisTo); }, off: function() { $target.removeClass(targetTo); $it.removeClass(thisTo); } }; targetTo = targetTo && targetTo !== '' ? targetTo : 'on'; thisTo = thisTo && thisTo !== '' ? thisTo : 'on'; $it.on('click', function(e) { e.preventDefault; }).on('mouseenter', function() { _fn.on(); return false; }).on('mouseleave', function() { _fn.off(); return false; }); }); })(); $('.j-tab').on('click','a',function(e){ e.preventDefault(); var $it=$(this); var targetId=$it.attr('href'); var $target=$(targetId); $it.addClass('on').siblings('.on').removeClass('on'); $target.addClass('on').siblings('.on').removeClass('on'); $target.find('img[data-src]').each(function(index, el) { var $it=$(this); var src=$it.attr('data-src'); $it.attr('src',src).removeAttr('data-src'); }); }); //弹出框 $('body').on('click','.modal-close, .modal .j-close',function(e){ e.preventDefault(); var $it=$(this); var $moldal=$it.parents('.modal'); $it.parents('.modal').removeClass('on'); }).on('click','.j-modal',function(e){ e.preventDefault(); var $it=$(this); var targetId=$it.attr('href'); var $target=$(targetId); $target.addClass('on'); }); });
pro27/kezhanbang-m
static/global/js/global.js
JavaScript
gpl-3.0
1,583
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Telegram.Td.Api; using Unigram.Collections; using Unigram.Common; using Unigram.Controls; using Unigram.Converters; using Unigram.Services; using Unigram.ViewModels.Gallery; using Windows.UI.Xaml.Controls; namespace Unigram.ViewModels.Users { public class UserPhotosViewModel : GalleryViewModelBase { private readonly DisposableMutex _loadMoreLock = new DisposableMutex(); private readonly User _user; public UserPhotosViewModel(IProtoService protoService, IEventAggregator aggregator, User user) : base(protoService, aggregator) { _user = user; Items = new MvxObservableCollection<GalleryContent> { new GalleryProfilePhoto(protoService, user) }; SelectedItem = Items[0]; FirstItem = Items[0]; Initialize(user); } private async void Initialize(User user) { using (await _loadMoreLock.WaitAsync()) { var response = await ProtoService.SendAsync(new GetUserProfilePhotos(_user.Id, 0, 20)); if (response is UserProfilePhotos photos) { TotalItems = photos.TotalCount; foreach (var item in photos.Photos) { if (item.Id == user.ProfilePhoto.Id && Items[0] is GalleryProfilePhoto main) { main.SetDate(item.AddedDate); RaisePropertyChanged(() => SelectedItem); } else { Items.Add(new GalleryUserProfilePhoto(ProtoService, _user, item)); } } } } } protected override async void LoadNext() { using (await _loadMoreLock.WaitAsync()) { var response = await ProtoService.SendAsync(new GetUserProfilePhotos(_user.Id, Items.Count, 20)); if (response is UserProfilePhotos photos) { TotalItems = photos.TotalCount; foreach (var item in photos.Photos) { Items.Add(new GalleryUserProfilePhoto(ProtoService, _user, item)); } } } } public override MvxObservableCollection<GalleryContent> Group => this.Items; public override bool CanDelete => _user != null && _user.Id == ProtoService.Options.MyId; protected override async void DeleteExecute() { var confirm = await TLMessageDialog.ShowAsync(Strings.Resources.AreYouSureDeletePhoto, Strings.Resources.AppName, Strings.Resources.OK, Strings.Resources.Cancel); if (confirm == ContentDialogResult.Primary && _selectedItem is GalleryProfilePhoto item) { var response = await ProtoService.SendAsync(new DeleteProfilePhoto(item.Id)); if (response is Ok) { var index = Items.IndexOf(item); if (index < Items.Count - 1) { SelectedItem = Items[index > 0 ? index - 1 : index + 1]; Items.Remove(item); TotalItems--; } else { NavigationService.GoBack(); } } } else if (confirm == ContentDialogResult.Primary && _selectedItem is GalleryUserProfilePhoto profileItem) { var response = await ProtoService.SendAsync(new DeleteProfilePhoto(profileItem.Id)); if (response is Ok) { NavigationService.GoBack(); } } } } }
ikarago/Unigram
Unigram/Unigram/ViewModels/Users/UserPhotosViewModel.cs
C#
gpl-3.0
4,095
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TravelingSalesmanProblem.Engine { public class Point { /* Class used as a point. Represent a location/gene in the path. */ #region Fields public int X; /* Variables used to display the path on the screen */ public int Y; public bool Visited; /* Boolean ; Is the point visited or not */ #endregion #region Constructors public Point(int X, int Y) { /* Class Constructor */ this.X = X; this.Y = Y; } #endregion #region Properties public System.Drawing.Point DrawingPoint { get { return new System.Drawing.Point(this.X, this.Y); } /* Convert this point into Drawing.Point */ } #endregion #region Public Methods public void Visit() { /* Visit the point */ this.Visited = true; } public int GetDistance(Point other) { /* Return the distance between this point and another */ int diffX = X - other.X; int diffY = Y - other.Y; return diffX * diffX + diffY * diffY; } #endregion } }
Sadikk/TPE
TravelingSalesmanProblem/TravelingSalesmanProblem/Engine/Point.cs
C#
gpl-3.0
1,385
<?php include_once('include/session.php'); function do_twinoid_auth($code) { global $error_msg; if (! isset($code)) { $error_msg = 'bug!'; return false; } $json = do_post_json('https://twinoid.com/oauth/token', array( 'client_id' => APP_TWINOID_ID, 'client_secret' => APP_SECRET_KEY, 'redirect_uri' => APP_REDIRECT_URI, 'code' => $code, 'grant_type' => 'authorization_code' ) ); if (is_string($json)) { $error_msg = "Error connecting to the Twinoid server:<br /><em>$json</em>"; return false; } if (isset($json->access_token)) { $_SESSION['token'] = $json->access_token; if (isset($json->expires_in)) { $_SESSION['token_refresh'] = time() + $json->expires_in - 60; } else { $_SESSION['token_refresh'] = time() + 300; } unset($error_msg); return true; } else if (isset($json->error)) { $error_msg = "Authentication error:<br /><em>" . $json->error . "</em>."; return false; } else { $error_msg = "Cannot parse the response from the Twinoid server."; return false; } } function getHordesMe() { global $error_msg; if (! isset($_SESSION['token'])) { return false; } $json = do_post_json('http://www.hordes.fr/tid/graph/me', array( 'access_token' => $_SESSION['token'], 'fields' => 'name,twinId,mapId,x,y,out' ) ); if (is_string($json)) { $error_msg = "Error connecting to the Twinoid server:<br /><em>$json</em>"; return false; } if (isset($json->error)) { $error_msg = "Error fetching Twinoid data:<br /><em>" . $json->error . "</em>."; return false; } $_SESSION['hordesGeneral'] = $json; return true; } function getHordesMap() { global $error_msg; if (! isset($_SESSION['token'])) { return false; } $json = do_post_json('http://www.hordes.fr/tid/graph/map', array( 'access_token' => $_SESSION['token'], 'mapId' => $_SESSION['hordesGeneral']->mapId, 'fields' => 'zones.fields(details,building),city' ) ); if (is_string($json)) { $error_msg = "Error connecting to the Twinoid server:<br /><em>$json</em>"; return false; } if (isset($json->error)) { $error_msg = "Error fetching Twinoid data:<br /><em>" . $json->error . "</em>."; return false; } $_SESSION['hordesMap']=$json; return true; } if (isset($_GET['state'])) { $redir_link = str_replace(array("^-", "^=", "^+"), array(";", "&", "^"), $_GET['state']); } else { $redir_link = ""; } if (isset($_SERVER["HTTP_HOST"])) { $redir_link = $_SERVER["HTTP_HOST"] . "/" . $redir_link; } else { $redir_link = $_SERVER["SERVER_NAME"] . "/" . $redir_link; } if (strpos($redir_link, "://") === false) { $redir_link = "http://" . $redir_link; } if (isset($_GET['code'])) { $_SESSION = array(); if (do_twinoid_auth($_GET['code'])) { if (getHordesMe()) { if(getHordesMap()){ header("Location: " . $redir_link); exit(); } } } } elseif (isset($_GET['error'])) { $_SESSION = array(); $error_msg = "Error during Twinoid redirection:<br /><em>" . $_GET['error'] . "</em>"; } else { $error_msg = "Incorrect call. Missing parameters."; } header("Location: http://wh.zenoo.fr"); //echo "<p class=\"error_box\">The connection to the Twinoid server has failed. You are not authenticated and you will not be able to use some features of this site.</p>"; ?>
Zenoo/hordesApps
[APP] BienTaMap/redir.php
PHP
gpl-3.0
3,454
package DynamicFlink; public class csv1POJO1446411691328{ String latitude; public void setLatitude(String latitude) { this.latitude = latitude; } public String getLatitude() { return this.latitude; } String longitude; public void setLongitude(String longitude) { this.longitude = longitude; } public String getLongitude() { return this.longitude; } String city_name; public void setCity_name(String city_name) { this.city_name = city_name; } public String getCity_name() { return this.city_name; } }
nict-isp/ETL-flow-editor
backend/DynamicFlink/csv1POJO1446411691328.java
Java
gpl-3.0
499
//########################################################################### // This file is part of LImA, a Library for Image Acquisition // // Copyright (C) : 2009-2017 // European Synchrotron Radiation Facility // CS40220 38043 Grenoble Cedex 9 // FRANCE // // Contact: lima@esrf.fr // // This is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This software is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. //########################################################################### #include "lima/CtSaving_ZBuffer.h" #include <string.h> // For memcpy #include <stdlib.h> // For posix_memalign #include <malloc.h> // For _aligned_malloc using namespace lima; void ZBuffer::_alloc(int buffer_size) { DEB_MEMBER_FUNCT(); DEB_PARAM() << DEB_VAR1(buffer_size); if (buffer_size == 0) THROW_CTL_ERROR(InvalidValue) << "Invalid NULL buffer_size"; used_size = 0; #ifdef __unix if(posix_memalign(&buffer,4*1024,buffer_size)) #else buffer = _aligned_malloc(buffer_size,4*1024); if(!buffer) #endif THROW_CTL_ERROR(Error) << "Can't allocate buffer"; alloc_size = buffer_size; } void ZBuffer::_deep_copy(const ZBuffer& o) { DEB_MEMBER_FUNCT(); DEB_PARAM() << DEB_VAR2(o.alloc_size, o.used_size); if (o.used_size > o.alloc_size) THROW_CTL_ERROR(Error) << "Invalid " << DEB_VAR2(o.used_size, o.alloc_size); _alloc(o.alloc_size); memcpy(buffer, o.buffer, used_size); used_size = o.used_size; } void ZBuffer::_free() { DEB_MEMBER_FUNCT(); DEB_PARAM() << DEB_VAR2(alloc_size, used_size); #ifdef __unix free(buffer); #else _aligned_free(buffer); #endif _setInvalid(); }
esrf-bliss/Lima
control/src/CtSaving_ZBuffer.cpp
C++
gpl-3.0
2,134
/* ############################### # Copyright (C) 2012 Jon Schang # # This file is part of jSchangLib, released under the LGPLv3 # # jSchangLib is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # jSchangLib is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with jSchangLib. If not, see <http://www.gnu.org/licenses/>. ############################### */ package com.jonschang.investing.valuesource; import com.jonschang.investing.model.*; /** * determine the Average True Range of the stock period * @author schang */ @SuppressWarnings(value={"unchecked"}) public class TrueRangeValueSource<Q extends Quote<I>,I extends Quotable> extends AbstractQuoteValueSource<Q,I> { /** * the average true range of a stock requires only the last two quotes */ public int getPeriods() { return 2; } /** * get the average true range of the current quote */ public double getValue() throws TooFewQuotesException { if( this.quotes.size()<2 ) throw new TooFewQuotesException("there were too few quotes: "+this.quotes.size()+" available, 2 quotes needed."); Quote today = this.quotes.get( this.quotes.size()-1 ); Quote yesterday = this.quotes.get( this.quotes.size()-2 ); double diffCurHighCurLow = today.getPriceHigh() - today.getPriceLow(); double diffCurHighPrevClose = today.getPriceHigh() - yesterday.getPriceClose(); double diffCurLowPrevClose = today.getPriceLow() - yesterday.getPriceClose(); double atr = 0; atr = diffCurHighCurLow > atr ? diffCurHighCurLow : atr; atr = diffCurHighPrevClose > atr ? diffCurHighPrevClose : atr; atr = diffCurLowPrevClose > atr ? diffCurLowPrevClose : atr; return atr; } }
jschang/jSchangLib
investing/src/main/java/com/jonschang/investing/valuesource/TrueRangeValueSource.java
Java
gpl-3.0
2,142
class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ num1, cnt1 = 0, 0 num2, cnt2 = 1, 0 for num in nums: if num == num1: cnt1 += 1 elif num == num2: cnt2 += 1 else: if cnt1 == 0: num1, cnt1 = num, 1 elif cnt2 == 0: num2, cnt2 = num, 1 else: cnt1, cnt2 = cnt1 - 1, cnt2 - 1 return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
YiqunPeng/Leetcode-pyq
solutions/229MajorityElementII.py
Python
gpl-3.0
671
'use strict'; var Dispatcher = require('../core/appDispatcher'); var EventEmitter = require('events').EventEmitter; var ActionTypes = require('./actionTypes'); var CHANGE_EVENT = 'change'; var utils = require('../core/utils'); function TradingStore() { var previousRate = null; var symbols = "GBP/USD"; var quantity = "GBP 1,000,000"; var model = null; var self = this; var store = { getInitialState: getInitialState, addChangeListener: addChangeListener, removeChangeListener: removeChangeListener }; init(); return store; //////////////////////// function init() { model = { isExecuting: false, symbols: 'GBP/USD', quantity: "GBP 1,000,000", movement: "none", spread: 1.6, buyPips: { bigFig: "1.61", fractionalPips: "5", pips: "49" }, sellPips: { bigFig: "1.61", fractionalPips: "9", pips: "47" } }; Dispatcher.register(function(action) { switch(action.actionType) { case ActionTypes.RATE_CHANGED: onRateChanged(action.updatedRate); break; case ActionTypes.TRADE_WILLEXECUTE: onTradeWillExecute(); break; case ActionTypes.TRADE_EXECUTED: onTradeDidExecute(action.updatedTrade); break; default: // no op } }); } function onTradeDidExecute(updatedTrade) { model.isExecuting = false; } function onTradeWillExecute() { model.isExecuting = true; self.emit(CHANGE_EVENT, model); } function onRateChanged(newRate) { if (model.isExecuting) { return; } model = $.extend(model, { movement: calculateMovement(previousRate || newRate, newRate), buyPips: formatPips(newRate.buy), sellPips: formatPips(newRate.sell) }, newRate); previousRate = newRate; self.emit(CHANGE_EVENT, model); } function addChangeListener(callback) { self.on(CHANGE_EVENT, callback); } function removeChangeListener(callback) { self.removeListener(CHANGE_EVENT, callback); } function calculateMovement(priorRate, newRate) { var x = newRate.buy - priorRate.buy; switch(true) { case x < 0 : return "down"; case x > 0 : return "up"; default : return "none"; } } function formatPips(spotRate) { var str = "" + spotRate; var pad = "0000000"; var ans = str + pad.substring(0, pad.length - str.length); return { bigFig: ans.substring(0, 4), pips: ans.substring(4, 6), fractionalPips: ans.substring(6, 8) }; } function getInitialState() { return model; } } utils.inherits(TradingStore, EventEmitter); module.exports = new TradingStore();
Digiterre/trading-tile-clients
react-standard-flux/src/app/trading/tradingStore.js
JavaScript
gpl-3.0
2,742
package io.github.ititus.mymod.util; public interface ICyclable<T> { T next(int i); T prev(int i); default T next() { return next(1); } default T prev() { return prev(1); } }
iTitus/MyMod
src/main/java/io/github/ititus/mymod/util/ICyclable.java
Java
gpl-3.0
221
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtMultimedia module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of other Qt classes. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <CoreServices/CoreServices.h> #include <CoreAudio/CoreAudio.h> #include <AudioUnit/AudioUnit.h> #include <AudioToolbox/AudioToolbox.h> #include <QtCore/qendian.h> #include <QtCore/qbuffer.h> #include <QtCore/qtimer.h> #include <QtCore/qdebug.h> #include <QtMultimedia/qaudiodeviceinfo.h> #include <QtMultimedia/qaudiooutput.h> #include "qaudio_mac_p.h" #include "qaudiooutput_mac_p.h" QT_BEGIN_NAMESPACE namespace { static const int default_buffer_size = 8 * 1024; class QAudioOutputBuffer : public QObject { Q_OBJECT public: QAudioOutputBuffer(int bufferSize, int maxPeriodSize, QAudioFormat const& audioFormat): m_deviceError(false), m_maxPeriodSize(maxPeriodSize), m_device(0) { m_buffer = new QAudioRingBuffer(bufferSize + (bufferSize % maxPeriodSize == 0 ? 0 : maxPeriodSize - (bufferSize % maxPeriodSize))); m_bytesPerFrame = (audioFormat.sampleSize() / 8) * audioFormat.channels(); m_periodTime = m_maxPeriodSize / m_bytesPerFrame * 1000 / audioFormat.frequency(); m_fillTimer = new QTimer(this); connect(m_fillTimer, SIGNAL(timeout()), SLOT(fillBuffer())); } ~QAudioOutputBuffer() { delete m_buffer; } qint64 readFrames(char* data, qint64 maxFrames) { bool wecan = true; qint64 framesRead = 0; while (wecan && framesRead < maxFrames) { QAudioRingBuffer::Region region = m_buffer->acquireReadRegion((maxFrames - framesRead) * m_bytesPerFrame); if (region.second > 0) { region.second -= region.second % m_bytesPerFrame; memcpy(data + (framesRead * m_bytesPerFrame), region.first, region.second); framesRead += region.second / m_bytesPerFrame; } else wecan = false; m_buffer->releaseReadRegion(region); } if (framesRead == 0 && m_deviceError) framesRead = -1; return framesRead; } qint64 writeBytes(const char* data, qint64 maxSize) { bool wecan = true; qint64 bytesWritten = 0; maxSize -= maxSize % m_bytesPerFrame; while (wecan && bytesWritten < maxSize) { QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(maxSize - bytesWritten); if (region.second > 0) { memcpy(region.first, data + bytesWritten, region.second); bytesWritten += region.second; } else wecan = false; m_buffer->releaseWriteRegion(region); } if (bytesWritten > 0) emit readyRead(); return bytesWritten; } int available() const { return m_buffer->free(); } void reset() { m_buffer->reset(); m_deviceError = false; } void setPrefetchDevice(QIODevice* device) { if (m_device != device) { m_device = device; if (m_device != 0) fillBuffer(); } } void startFillTimer() { if (m_device != 0) m_fillTimer->start(m_buffer->size() / 2 / m_maxPeriodSize * m_periodTime); } void stopFillTimer() { m_fillTimer->stop(); } signals: void readyRead(); private slots: void fillBuffer() { const int free = m_buffer->free(); const int writeSize = free - (free % m_maxPeriodSize); if (writeSize > 0) { bool wecan = true; int filled = 0; while (!m_deviceError && wecan && filled < writeSize) { QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(writeSize - filled); if (region.second > 0) { region.second = m_device->read(region.first, region.second); if (region.second > 0) filled += region.second; else if (region.second == 0) wecan = false; else if (region.second < 0) { m_fillTimer->stop(); region.second = 0; m_deviceError = true; } } else wecan = false; m_buffer->releaseWriteRegion(region); } if (filled > 0) emit readyRead(); } } private: bool m_deviceError; int m_maxPeriodSize; int m_bytesPerFrame; int m_periodTime; QIODevice* m_device; QTimer* m_fillTimer; QAudioRingBuffer* m_buffer; }; } class MacOutputDevice : public QIODevice { Q_OBJECT public: MacOutputDevice(QAudioOutputBuffer* audioBuffer, QObject* parent): QIODevice(parent), m_audioBuffer(audioBuffer) { open(QIODevice::WriteOnly | QIODevice::Unbuffered); } qint64 readData(char* data, qint64 len) { Q_UNUSED(data); Q_UNUSED(len); return 0; } qint64 writeData(const char* data, qint64 len) { return m_audioBuffer->writeBytes(data, len); } bool isSequential() const { return true; } private: QAudioOutputBuffer* m_audioBuffer; }; QAudioOutputPrivate::QAudioOutputPrivate(const QByteArray& device, const QAudioFormat& format): audioFormat(format) { QDataStream ds(device); quint32 did, mode; ds >> did >> mode; if (QAudio::Mode(mode) == QAudio::AudioInput) errorCode = QAudio::OpenError; else { isOpen = false; audioDeviceId = AudioDeviceID(did); audioUnit = 0; audioIO = 0; startTime = 0; totalFrames = 0; audioBuffer = 0; internalBufferSize = default_buffer_size; clockFrequency = AudioGetHostClockFrequency() / 1000; errorCode = QAudio::NoError; stateCode = QAudio::StoppedState; audioThreadState = Stopped; intervalTimer = new QTimer(this); intervalTimer->setInterval(1000); connect(intervalTimer, SIGNAL(timeout()), SIGNAL(notify())); } } QAudioOutputPrivate::~QAudioOutputPrivate() { close(); } bool QAudioOutputPrivate::open() { if (errorCode != QAudio::NoError) return false; if (isOpen) return true; ComponentDescription cd; cd.componentType = kAudioUnitType_Output; cd.componentSubType = kAudioUnitSubType_HALOutput; cd.componentManufacturer = kAudioUnitManufacturer_Apple; cd.componentFlags = 0; cd.componentFlagsMask = 0; // Open Component cp = FindNextComponent(NULL, &cd); if (cp == 0) { qWarning() << "QAudioOutput: Failed to find HAL Output component"; return false; } if (OpenAComponent(cp, &audioUnit) != noErr) { qWarning() << "QAudioOutput: Unable to Open Output Component"; return false; } // register callback AURenderCallbackStruct cb; cb.inputProc = renderCallback; cb.inputProcRefCon = this; if (AudioUnitSetProperty(audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, 0, &cb, sizeof(cb)) != noErr) { qWarning() << "QAudioOutput: Failed to set AudioUnit callback"; return false; } // Set Audio Device if (AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &audioDeviceId, sizeof(audioDeviceId)) != noErr) { qWarning() << "QAudioOutput: Unable to use configured device"; return false; } // Set stream format streamFormat = toAudioStreamBasicDescription(audioFormat); UInt32 size = sizeof(deviceFormat); if (AudioUnitGetProperty(audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &deviceFormat, &size) != noErr) { qWarning() << "QAudioOutput: Unable to retrieve device format"; return false; } if (AudioUnitSetProperty(audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &streamFormat, sizeof(streamFormat)) != noErr) { qWarning() << "QAudioOutput: Unable to Set Stream information"; return false; } // Allocate buffer UInt32 numberOfFrames = 0; size = sizeof(UInt32); if (AudioUnitGetProperty(audioUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &numberOfFrames, &size) != noErr) { qWarning() << "QAudioInput: Failed to get audio period size"; return false; } periodSizeBytes = (numberOfFrames * streamFormat.mSampleRate / deviceFormat.mSampleRate) * streamFormat.mBytesPerFrame; if (internalBufferSize < periodSizeBytes * 2) internalBufferSize = periodSizeBytes * 2; else internalBufferSize -= internalBufferSize % streamFormat.mBytesPerFrame; audioBuffer = new QAudioOutputBuffer(internalBufferSize, periodSizeBytes, audioFormat); connect(audioBuffer, SIGNAL(readyRead()), SLOT(inputReady())); // Pull audioIO = new MacOutputDevice(audioBuffer, this); // Init if (AudioUnitInitialize(audioUnit)) { qWarning() << "QAudioOutput: Failed to initialize AudioUnit"; return false; } isOpen = true; return true; } void QAudioOutputPrivate::close() { if (audioUnit != 0) { AudioOutputUnitStop(audioUnit); AudioUnitUninitialize(audioUnit); CloseComponent(audioUnit); } delete audioBuffer; } QAudioFormat QAudioOutputPrivate::format() const { return audioFormat; } QIODevice* QAudioOutputPrivate::start(QIODevice* device) { QIODevice* op = device; if (!open()) { stateCode = QAudio::StoppedState; errorCode = QAudio::OpenError; return audioIO; } reset(); audioBuffer->reset(); audioBuffer->setPrefetchDevice(op); if (op == 0) { op = audioIO; stateCode = QAudio::IdleState; } else stateCode = QAudio::ActiveState; // Start errorCode = QAudio::NoError; totalFrames = 0; startTime = AudioGetCurrentHostTime(); if (stateCode == QAudio::ActiveState) audioThreadStart(); emit stateChanged(stateCode); return op; } void QAudioOutputPrivate::stop() { QMutexLocker lock(&mutex); if (stateCode != QAudio::StoppedState) { audioThreadDrain(); stateCode = QAudio::StoppedState; errorCode = QAudio::NoError; QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode)); } } void QAudioOutputPrivate::reset() { QMutexLocker lock(&mutex); if (stateCode != QAudio::StoppedState) { audioThreadStop(); stateCode = QAudio::StoppedState; errorCode = QAudio::NoError; QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode)); } } void QAudioOutputPrivate::suspend() { QMutexLocker lock(&mutex); if (stateCode == QAudio::ActiveState || stateCode == QAudio::IdleState) { audioThreadStop(); stateCode = QAudio::SuspendedState; errorCode = QAudio::NoError; QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode)); } } void QAudioOutputPrivate::resume() { QMutexLocker lock(&mutex); if (stateCode == QAudio::SuspendedState) { audioThreadStart(); stateCode = QAudio::ActiveState; errorCode = QAudio::NoError; QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode)); } } int QAudioOutputPrivate::bytesFree() const { return audioBuffer->available(); } int QAudioOutputPrivate::periodSize() const { return periodSizeBytes; } void QAudioOutputPrivate::setBufferSize(int bs) { if (stateCode == QAudio::StoppedState) internalBufferSize = bs; } int QAudioOutputPrivate::bufferSize() const { return internalBufferSize; } void QAudioOutputPrivate::setNotifyInterval(int milliSeconds) { intervalTimer->setInterval(milliSeconds); } int QAudioOutputPrivate::notifyInterval() const { return intervalTimer->interval(); } qint64 QAudioOutputPrivate::processedUSecs() const { return totalFrames * 1000000 / audioFormat.frequency(); } qint64 QAudioOutputPrivate::elapsedUSecs() const { if (stateCode == QAudio::StoppedState) return 0; return (AudioGetCurrentHostTime() - startTime) / (clockFrequency / 1000); } QAudio::Error QAudioOutputPrivate::error() const { return errorCode; } QAudio::State QAudioOutputPrivate::state() const { return stateCode; } void QAudioOutputPrivate::audioThreadStart() { startTimers(); audioThreadState = Running; AudioOutputUnitStart(audioUnit); } void QAudioOutputPrivate::audioThreadStop() { stopTimers(); if (audioThreadState.testAndSetAcquire(Running, Stopped)) threadFinished.wait(&mutex); } void QAudioOutputPrivate::audioThreadDrain() { stopTimers(); if (audioThreadState.testAndSetAcquire(Running, Draining)) threadFinished.wait(&mutex); } void QAudioOutputPrivate::audioDeviceStop() { AudioOutputUnitStop(audioUnit); audioThreadState = Stopped; threadFinished.wakeOne(); } void QAudioOutputPrivate::audioDeviceIdle() { QMutexLocker lock(&mutex); if (stateCode == QAudio::ActiveState) { audioDeviceStop(); errorCode = QAudio::UnderrunError; stateCode = QAudio::IdleState; QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection); } } void QAudioOutputPrivate::audioDeviceError() { QMutexLocker lock(&mutex); if (stateCode == QAudio::ActiveState) { audioDeviceStop(); errorCode = QAudio::IOError; stateCode = QAudio::StoppedState; QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection); } } void QAudioOutputPrivate::startTimers() { audioBuffer->startFillTimer(); intervalTimer->start(); } void QAudioOutputPrivate::stopTimers() { audioBuffer->stopFillTimer(); intervalTimer->stop(); } void QAudioOutputPrivate::deviceStopped() { intervalTimer->stop(); emit stateChanged(stateCode); } void QAudioOutputPrivate::inputReady() { QMutexLocker lock(&mutex); if (stateCode == QAudio::IdleState) { audioThreadStart(); stateCode = QAudio::ActiveState; errorCode = QAudio::NoError; QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode)); } } OSStatus QAudioOutputPrivate::renderCallback(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData) { Q_UNUSED(ioActionFlags) Q_UNUSED(inTimeStamp) Q_UNUSED(inBusNumber) Q_UNUSED(inNumberFrames) QAudioOutputPrivate* d = static_cast<QAudioOutputPrivate*>(inRefCon); const int threadState = d->audioThreadState.fetchAndAddAcquire(0); if (threadState == Stopped) { ioData->mBuffers[0].mDataByteSize = 0; d->audioDeviceStop(); } else { const UInt32 bytesPerFrame = d->streamFormat.mBytesPerFrame; qint64 framesRead; framesRead = d->audioBuffer->readFrames((char*)ioData->mBuffers[0].mData, ioData->mBuffers[0].mDataByteSize / bytesPerFrame); if (framesRead > 0) { ioData->mBuffers[0].mDataByteSize = framesRead * bytesPerFrame; d->totalFrames += framesRead; } else { ioData->mBuffers[0].mDataByteSize = 0; if (framesRead == 0) { if (threadState == Draining) d->audioDeviceStop(); else d->audioDeviceIdle(); } else d->audioDeviceError(); } } return noErr; } QT_END_NAMESPACE #include "qaudiooutput_mac_p.moc"
whitequark/sparkle
sippy/multimedia/qaudiooutput_mac_p.cpp
C++
gpl-3.0
19,297
package com.exabilan.interfaces; import java.util.List; import com.exabilan.types.exalang.Answer; import com.exabilan.types.exalang.ExaLang; import com.exabilan.types.exalang.Question; public interface ResultAssociator { /** * Finds the question corresponding to a question number for a given version of Exalang */ Question getQuestion(ExaLang exalang, int questionNumber); /** * Parses the answers written in Exalang specific storage files */ List<Answer> parseAnswer(String result); }
Thomas-Gr/exaBilan
src/main/java/com/exabilan/interfaces/ResultAssociator.java
Java
gpl-3.0
529
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class AISpiderbotCheckIfFriendlyMoved : AIAutonomousConditions { [Ordinal(0)] [RED("maxAllowedDelta")] public CHandle<AIArgumentMapping> MaxAllowedDelta { get; set; } public AISpiderbotCheckIfFriendlyMoved(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/AISpiderbotCheckIfFriendlyMoved.cs
C#
gpl-3.0
424
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class scnVarComparison_FactConditionTypeParams : CVariable { [Ordinal(0)] [RED("factName")] public CName FactName { get; set; } [Ordinal(1)] [RED("value")] public CInt32 Value { get; set; } [Ordinal(2)] [RED("comparisonType")] public CEnum<EComparisonType> ComparisonType { get; set; } public scnVarComparison_FactConditionTypeParams(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/scnVarComparison_FactConditionTypeParams.cs
C#
gpl-3.0
556
/********************************************************************************************* * * 'OpenGamaWebsiteHandler.java, in plugin ummisco.gama.ui.shared, is part of the source code of the * GAMA modeling and simulation platform. * (v. 1.8.1) * * (c) 2007-2020 UMI 209 UMMISCO IRD/UPMC & Partners * * Visit https://github.com/gama-platform/gama for license information and developers contact. * * **********************************************************************************************/ package ummisco.gama.ui.commands; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import msi.gama.runtime.GAMA; public class OpenGamaWebsiteHandler extends AbstractHandler { /** * Method execute() * * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ @Override public Object execute(final ExecutionEvent event) throws ExecutionException { GAMA.getGui().openWelcomePage(false); return null; } }
gama-platform/gama
ummisco.gama.ui.shared/src/ummisco/gama/ui/commands/OpenGamaWebsiteHandler.java
Java
gpl-3.0
1,076
package com.pajato.android.gamechat; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import com.google.identitytoolkit.GitkitClient; import com.google.identitytoolkit.GitkitUser; import com.google.identitytoolkit.IdToken; import com.pajato.android.gamechat.chat.ChatManager; import com.pajato.android.gamechat.chat.ChatManagerImpl; import com.pajato.android.gamechat.game.GameManager; import com.pajato.android.gamechat.game.GameManagerImpl; import com.pajato.android.gamechat.account.AccountManager; import com.pajato.android.gamechat.account.AccountManagerImpl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ArrayList; /** * The main activity ... <tbd> */ public class MainActivity extends AppCompatActivity implements GitkitClient.SignInCallbacks { // Public class constants // Private class constants /** The logcat tag constant. */ private static final String TAG = MainActivity.class.getSimpleName(); /** The preferences file name. */ private static final String PREFS = "GameChatPrefs"; // Private instance variables /** The account manager handles all things related to accounts: signing in, switching accounts, setup, aliases, etc. */ private AccountManager mAccountManager; /** The chat manager handles all things chat: accessing rooms, history, settings, etc. */ private ChatManager mChatManager; /** The game manager handles all game related activities: mode, players, game selection, etc. */ private GameManager mGameManager; /** The top level container. */ private DrawerLayout mDrawerLayout; // Public instance methods /** * Override to implement a successful login by ensuring that the account is registered and up to date.. */ @Override public void onSignIn(IdToken idToken, GitkitUser user) { // Create a session for the given user by saving the token in the account. Log.d(TAG, String.format("Processing a successful signin: idToken/user {%s/%s}.", idToken, user)); Toast.makeText(this, "You are successfully signed in to GameChat", Toast.LENGTH_LONG).show(); mAccountManager.handleSigninSuccess(user.getUserProfile(), idToken, getSharedPreferences(PREFS, 0)); } /** Override to implement a failed signin by posting a message to the User. */ @Override public void onSignInFailed() { // Post a message and head back to the main screen. Log.d(TAG, "Processing a failed signin attempt."); Toast.makeText(this, "Sign in failed", Toast.LENGTH_LONG).show(); mAccountManager.handleSigninFailed(); } // Protected instance methods /** * Handle the signin activity result value by passing it back to the account manager. * * @param requestCode ... * @param resultCode ... * @param intent ... */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { // Pass the event off to the account manager for processing. Log.d(TAG, String.format("Processing a signin result: requestCode/resultCode/intent {%d/%d/%s}.", requestCode, resultCode, intent)); if (!mAccountManager.handleSigninResult(requestCode, resultCode, intent)) { Log.d(TAG, "Signin result was not processed by the GIT."); super.onActivityResult(requestCode, resultCode, intent); } } /** * Set up the app per the characteristics of the running device. * * @see android.app.Activity#onCreate(Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { // Initialize the app state as necessary. super.onCreate(savedInstanceState); mAccountManager = new AccountManagerImpl(savedInstanceState, getSharedPreferences(PREFS, 0)); mGameManager = new GameManagerImpl(savedInstanceState); mChatManager = new ChatManagerImpl(savedInstanceState); // Start the app. Setup the top level views: toolbar, action bar and drawer layout. setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setHomeAsUpIndicator(R.drawable.ic_menu); actionBar.setDisplayHomeAsUpEnabled(true); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // Setup the navigation view and the main app pager. // // Todo: extend this to work with specific device classes based on size to provide optimal layouts. NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view); navigationView.setNavigationItemSelectedListener(new NavigationHandler()); GameChatPagerAdapter adapter = new GameChatPagerAdapter(getSupportFragmentManager()); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(adapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout); tabLayout.setupWithViewPager(viewPager); // Determine if an account needs to be set up. if (!mAccountManager.hasAccount()) { // There is no account yet. Give the User a chance to sign in even though it is not strictly necessary, for // example when playing games with the computer. mAccountManager.signin(this); } } /** * Override to implement by passing a given intent to the account manager to see if it is consuming the intent. * * @param intent The given Intent object. */ @Override protected void onNewIntent(final Intent intent) { // Give the account manager a chance to consume the intent. if (!mAccountManager.handleIntent(intent)) { Log.d(TAG, "Signin intent was not processed by the GIT."); super.onNewIntent(intent); } } // Private instance methods // Private classes /** * Provide a class to handle the view pager setup. */ private class GameChatPagerAdapter extends FragmentStatePagerAdapter { /** * A list of panels ordered left to right. */ private List<Panel> panelList = new ArrayList<>(); /** * Build an adapter to handle the panels. * * @param fm The fragment manager. */ public GameChatPagerAdapter(final FragmentManager fm) { super(fm); panelList.add(Panel.ROOMS); panelList.add(Panel.CHAT); panelList.add(Panel.MEMBERS); panelList.add(Panel.GAME); } @Override public Fragment getItem(int position) { return panelList.get(position).getFragment(); } @Override public int getCount() { return panelList.size(); } @Override public CharSequence getPageTitle(int position) { return MainActivity.this.getString(panelList.get(position).getTitleId()); } } /** * Provide a handler for navigation panel selections. */ private class NavigationHandler implements NavigationView.OnNavigationItemSelectedListener { @Override public boolean onNavigationItemSelected(final MenuItem menuItem) { menuItem.setChecked(true); mDrawerLayout.closeDrawers(); Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show(); return true; } } }
pajato/game-chat-android
app/src/main/java/com/pajato/android/gamechat/MainActivity.java
Java
gpl-3.0
8,746
<?php require_once "user.class.php"; require_once '../config/config.php'; if(isset ($_POST['login']) && isset ($_POST['motdepasse'])){ $login = $_POST['login']; $pass = $_POST['motdepasse']; $user = new Utilisateur(); if($user->connexion($login, sha1($pass), $pdo)){ session_start(); $_SESSION['name'] = '$login'; $_SESSION['id'] = $user->id(); header('Location: ../pages/index.html'); } else{ header('Location: ../pages/page_connexion.html'); } }
DiarraDIOP/Pasteque
Code/script/connect.php
PHP
gpl-3.0
595
import pandas as pd from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.cross_validation import train_test_split from sklearn.metrics import mean_squared_error from .auto_segment_FEMPO import BasicSegmenter_FEMPO def demo(X = None, y = None, test_size = 0.1): if X == None: boston = load_boston() X = pd.DataFrame(boston.data) y = pd.DataFrame(boston.target) base_estimator = DecisionTreeRegressor(max_depth = 5) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size) print X_train.shape # If you want to compare with BaggingRegressor. # bench = BaggingRegressor(base_estimator = base_estimator, n_estimators = 10, max_samples = 1, oob_score = True).fit(X_train, y_train) # print bench.score(X_test, y_test) # print mean_squared_error(bench.predict(X_test), y_test) clf = BasicSegmenterEG_FEMPO(ngen=30,init_sample_percentage = 1, n_votes=10, n = 10, base_estimator = base_estimator, unseen_x = X_test, unseen_y = y_test) clf.fit(X_train, y_train) print clf.score(X_test,y_test) y = clf.predict(X_test) print mean_squared_error(y, y_test) print y.shape return clf, X_test, y_test
bhanu-mnit/EvoML
evoml/subsampling/test_auto_segmentEG_FEMPO.py
Python
gpl-3.0
1,357
package com.superman.letusgo.base; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.content.Context; import android.widget.Toast; import com.superman.letusgo.util.AppClient; import com.superman.letusgo.util.HttpUtil; public class BaseTaskPool { // task thread pool static private ExecutorService taskPool; // for HttpUtil.getNetType private Context context; public BaseTaskPool (BaseUi ui) { this.context = ui.getContext(); taskPool = Executors.newCachedThreadPool(); } // http post task with params public void addTask (int taskId, String taskUrl, HashMap<String, String> taskArgs, BaseTask baseTask, int delayTime) { baseTask.setId(taskId); try { taskPool.execute(new TaskThread(context, taskUrl, taskArgs, baseTask, delayTime)); } catch (Exception e) { taskPool.shutdown(); } } // http post task without params public void addTask (int taskId, String taskUrl, BaseTask baseTask, int delayTime) { baseTask.setId(taskId); try { Toast.makeText(context, "11111111111", Toast.LENGTH_SHORT); taskPool.execute(new TaskThread(context, taskUrl, null, baseTask, delayTime)); } catch (Exception e) { taskPool.shutdown(); } } // custom task public void addTask (int taskId, BaseTask baseTask, int delayTime) { baseTask.setId(taskId); try { taskPool.execute(new TaskThread(context, null, null, baseTask, delayTime)); } catch (Exception e) { taskPool.shutdown(); } } // task thread logic private class TaskThread implements Runnable { private Context context; private String taskUrl; private HashMap<String, String> taskArgs; private BaseTask baseTask; private int delayTime = 0; public TaskThread(Context context, String taskUrl, HashMap<String, String> taskArgs, BaseTask baseTask, int delayTime) { this.context = context; this.taskUrl = taskUrl; this.taskArgs = taskArgs; this.baseTask = baseTask; this.delayTime = delayTime; } @Override public void run() { try { baseTask.onStart(); String httpResult = null; // set delay time if (this.delayTime > 0) { Thread.sleep(this.delayTime); } try { // remote task if (this.taskUrl != null) { // init app client AppClient client = new AppClient(this.taskUrl); if (HttpUtil.WAP_INT == HttpUtil.getNetType(context)) { client.useWap(); } // http get if (taskArgs == null) { httpResult = client.get(); // http post } else { httpResult = client.post(this.taskArgs); } } // remote task if (httpResult != null) { baseTask.onComplete(httpResult); // local task } else { baseTask.onComplete(); } } catch (Exception e) { baseTask.onError(e.getMessage()); } } catch (Exception e) { e.printStackTrace(); } finally { try { baseTask.onStop(); } catch (Exception e) { e.printStackTrace(); } } } } }
superman-t/LetUsGo
src/com/superman/letusgo/base/BaseTaskPool.java
Java
gpl-3.0
3,152
<?php namespace Directus\Installation\Steps; use Directus\Bootstrap; class LanguageStep extends AbstractStep { protected $number = 1; protected $name = 'language'; protected $title = 'Language'; protected $shortTitle = 'Language'; protected $viewName = 'language.twig'; protected $fields = [ [ 'name' => 'default_language', 'label' => 'Default Language', 'rules' => 'required' ] ]; public function preRun(&$state) { $this->dataContainer->set('languages', Bootstrap::get('languagesManager')->getLanguagesAvailable()); return null; } public function run($formData, $step, &$state) { $response = parent::run($formData, $step, $state); $_SESSION['install_locale'] = $response->getData('lang_code'); return $response; } }
Sonans/directus
installation/includes/Steps/LanguageStep.php
PHP
gpl-3.0
869
package com.springdemo.learningMVC.common.src.main.java.com.common.tuple; /** * A mutable triple consisting of three {@code Object} elements. * <p> * Not #ThreadSafe# * * @param <L> the left element type * @param <M> the middle element type * @param <R> the right element type * @version $Id: MutableTriple.java 290 2014-10-27 08:48:18Z $ */ public class MutableTriple<L, M, R> extends Triple<L, M, R> { /** * Serialization version */ private static final long serialVersionUID = 1L; /** * Left object */ public L left; /** * Middle object */ public M middle; /** * Right object */ public R right; /** * Obtains an mutable triple of three objects inferring the generic types. * <p> * This factory allows the triple to be created using inference to * obtain the generic types. * * @param <L> the left element type * @param <M> the middle element type * @param <R> the right element type * @param left the left element, may be null * @param middle the middle element, may be null * @param right the right element, may be null * @return a triple formed from the three parameters, not null */ public static <L, M, R> MutableTriple<L, M, R> of( final L left, final M middle, final R right) { return new MutableTriple<>(left, middle, right); } /** * Create a new triple instance of three nulls. */ public MutableTriple() { super(); } /** * Create a new triple instance. * * @param left the left value, may be null * @param middle the middle value, may be null * @param right the right value, may be null */ public MutableTriple(final L left, final M middle, final R right) { super(); this.left = left; this.middle = middle; this.right = right; } //----------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public L getLeft() { return left; } /** * Sets the left element of the triple. * * @param left the new value of the left element, may be null */ public void setLeft(final L left) { this.left = left; } /** * {@inheritDoc} */ @Override public M getMiddle() { return middle; } /** * Sets the middle element of the triple. * * @param middle the new value of the middle element, may be null */ public void setMiddle(final M middle) { this.middle = middle; } /** * {@inheritDoc} */ @Override public R getRight() { return right; } /** * Sets the right element of the triple. * * @param right the new value of the right element, may be null */ public void setRight(final R right) { this.right = right; } }
simonpatrick/stepbystep-java
spring-demo/docs/learningMVC/common/src/main/java/com/common/tuple/MutableTriple.java
Java
gpl-3.0
2,978
require.config({ baseUrl: 'vendor', waitSeconds: 10, paths: { core: '../core', lang: '../lang', root: '..' }, shim: { 'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' }, 'underscore': { exports: '_' } } }); require(['root/config'],function(Config){ require.config({ paths: { theme: '../themes/'+ Config.theme } }); require(['jquery', 'core/app-utils', 'core/app', 'core/router', 'core/region-manager', 'core/stats', 'core/phonegap-utils'], function ($, Utils, App, Router, RegionManager, Stats, PhoneGap) { var launch = function() { // Initialize application before using it App.initialize( function() { RegionManager.buildHead(function(){ RegionManager.buildLayout(function(){ RegionManager.buildHeader(function(){ App.router = new Router(); require(['theme/js/functions'], function(){ App.sync( function(){ RegionManager.buildMenu(function(){ //Menu items are loaded by App.sync Stats.updateVersion(); Stats.incrementCountOpen(); Stats.incrementLastOpenTime(); if( Config.debug_mode == 'on' ){ Utils.log( 'App version : ', Stats.getVersionDiff() ); Utils.log( 'App opening count : ', Stats.getCountOpen() ); Utils.log( 'Last app opening was on ', Stats.getLastOpenDate() ); } App.launchRouting(); App.sendInfo('app-launched'); //triggers info:app-ready, info:app-first-launch and info:app-version-changed //Refresh at app launch can be canceled using the 'refresh-at-app-launch' App param, //this is useful if we set a specific launch page and don't want to be redirected //after the refresh. if( App.getParam('refresh-at-app-launch') ){ //Refresh at app launch : as the theme is now loaded, use theme-app : require(['core/theme-app'],function(ThemeApp){ last_updated = App.options.get( 'last_updated' ); refresh_interval = App.options.get( 'refresh_interval' ); if( undefined === last_updated || undefined === refresh_interval || Date.now() > last_updated.get( 'value' ) + ( refresh_interval.get( 'value' ) * 1000 ) ) { Utils.log( 'Refresh interval exceeded, refreshing', { last_updated: last_updated, refresh_interval: refresh_interval } ); ThemeApp.refresh(); } }); } PhoneGap.hideSplashScreen(); }); }, function(){ Backbone.history.start(); Utils.log("launch.js error : App could not synchronize with website."); PhoneGap.hideSplashScreen(); App.sendInfo('no-content'); }, false //true to force refresh local storage at each app launch. ); }, function(error){ Utils.log('Error : theme/js/functions.js not found', error); } ); }); }); }); }); }; if( PhoneGap.isLoaded() ){ PhoneGap.setNetworkEvents(App.onOnline,App.onOffline); document.addEventListener('deviceready', launch, false); }else{ window.ononline = App.onOnline; window.onoffline = App.onOffline; $(document).ready(launch); } }); },function(){ //Config.js not found //Can't use Utils.log here : log messages by hand : var message = 'WP AppKit error : config.js not found.'; console && console.log(message); document.write(message); //Check if we are simulating in browser : var query = window.location.search.substring(1); if( query.length && query.indexOf('wpak_app_id') != -1 ){ message = 'Please check that you are connected to your WordPress back office.'; console && console.log(message); document.write('<br>'+ message); } });
HammyHavoc/Voidance-Records-App
core/launch.js
JavaScript
gpl-3.0
4,158
import {EMPTY_CONCEPT_ID} from '../registry'; import {DdfDataSet} from '../../ddf-definitions/ddf-data-set'; import {Issue} from '../issue'; export const rule = { rule: (ddfDataSet: DdfDataSet) => ddfDataSet .getConcept() .getAllData() .filter(conceptRecord => !conceptRecord.concept) .map(conceptRecordWithEmptyId => new Issue(EMPTY_CONCEPT_ID) .setPath(conceptRecordWithEmptyId.$$source) .setData({line: conceptRecordWithEmptyId.$$lineNumber}) ) };
Gapminder/ddf-validation
src/ddf-rules/concept-rules/empty-concept-id.ts
TypeScript
gpl-3.0
496
namespace Maticsoft.Web.Controls { using System; using System.Web.UI; using System.Web.UI.WebControls; public class ProductsBatchUploadDropList : UserControl { protected HiddenField hfSelectedNode; public bool IsNull; protected void Page_Load(object sender, EventArgs e) { } public string SelectedValue { get { return this.hfSelectedNode.Value; } set { this.hfSelectedNode.Value = value; } } } }
51zhaoshi/myyyyshop
Maticsoft.Web_Source/Maticsoft.Web.Controls/ProductsBatchUploadDropList.cs
C#
gpl-3.0
592
<?php class ControllerApiCurrency extends Controller { public function index() { $this->load->language('api/currency'); $json = array(); if (!isset($this->session->data['api_id'])) { $json['error'] = $this->language->get('error_permission'); } else { $this->load->model('localisation/currency'); $currency_info = $this->model_localisation_currency->getCurrencyByCode($this->request->post['currency']); if ($currency_info) { $this->currency->set($this->request->post['currency']); unset($this->session->data['shipping_method']); unset($this->session->data['shipping_methods']); $json['success'] = $this->language->get('text_success'); } else { $json['error'] = $this->language->get('error_currency'); } } if (isset($this->request->server['HTTP_ORIGIN'])) { $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']); $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); $this->response->addHeader('Access-Control-Max-Age: 1000'); $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } }
vincentgy/rubys
catalog/controller/api/currency.php
PHP
gpl-3.0
1,348
package com.DragonFire.recipe; import com.DragonFire.item.DFItems; import net.minecraft.init.Items; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.potion.PotionUtils; import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraftforge.registries.IForgeRegistryEntry.Impl; public class RecipePotionCookie extends Impl<IRecipe> implements IRecipe { public RecipePotionCookie() {setRegistryName("potion_cookie");} @Override public boolean matches(InventoryCrafting inv, World worldIn) { if (inv.getWidth() == 3 && inv.getHeight() == 3) { for (int i = 0; i < inv.getWidth(); ++i) { for (int j = 0; j < inv.getHeight(); ++j) { ItemStack itemstack = inv.getStackInRowAndColumn(i, j); if (itemstack.isEmpty()) return false; Item item = itemstack.getItem(); if (i == 1 && j == 1) { if (item != Items.LINGERING_POTION) return false; } else if (item != Items.COOKIE) return false; } } return true; } else return false; } @Override public ItemStack getCraftingResult(InventoryCrafting inv) { ItemStack itemstack = inv.getStackInRowAndColumn(1, 1); if (itemstack.getItem() != Items.LINGERING_POTION) return ItemStack.EMPTY; else { ItemStack itemstack1 = new ItemStack(DFItems.POTION_COOKIE, 8); PotionUtils.addPotionToItemStack(itemstack1, PotionUtils.getPotionFromItem(itemstack)); PotionUtils.appendEffects(itemstack1, PotionUtils.getFullEffectsFromItem(itemstack)); return itemstack1; } } public ItemStack getRecipeOutput() {return ItemStack.EMPTY;} public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) {return NonNullList.<ItemStack>withSize(inv.getSizeInventory(), ItemStack.EMPTY);} public boolean isHidden() {return true;} public boolean canFit(int width, int height) {return width == 3 && height == 3;} }
SirBlobman/DragonFire
src/main/java/com/DragonFire/recipe/RecipePotionCookie.java
Java
gpl-3.0
2,236
#!/usr/bin/env python # Version 0.1 # NDVI automated acquisition and calculation by Vladyslav Popov # Using landsat-util, source: https://github.com/developmentseed/landsat-util # Uses Amazon Web Services Public Dataset (Lansat 8) # Script should be run every day from os.path import join, abspath, dirname, exists import os import errno import shutil from tempfile import mkdtemp import subprocess import urllib2 import logging import sys import datetime import re from landsat.search import Search from landsat.ndvi import NDVIWithManualColorMap # Enable logging logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) # Get current date current_date = datetime.datetime.now().date() print 'Current date is:', current_date # Let`s subtract 1 day from current date sub_date = current_date - datetime.timedelta(days=1) print 'Subtract date is:', sub_date # Scene search by date and WRS-2 row and path search = Search() try: search_results = search.search(paths_rows='177,025', start_date=sub_date, end_date=current_date) search_string = str(search_results.get('results')) search_list = re.compile('\w+').findall(search_string) scene_id = str(search_list.pop(5)) print scene_id l = len(scene_id) print l #exit if we have no current image except Exception: raise SystemExit('Closing...') # String concat for building Red Band URL for download url_red = 'http://landsat-pds.s3.amazonaws.com/L8/177/025/' + scene_id + '/' + scene_id + '_B4.TIF' # String concat for building NIR Band URL for download url_nir = 'http://landsat-pds.s3.amazonaws.com/L8/177/025/' + scene_id + '/' + scene_id + '_B5.TIF' # Build filenames for band rasters and output NDVI file red_file = scene_id + '_B4.TIF' nir_file = scene_id + '_B5.TIF' ndvi_file = scene_id + '_NDVI.TIF' print 'Filenames builded succsessfuly' # Create directories for future pssing base_dir = os.getcwd() temp_folder = join(base_dir, "temp_folder") scene_folder = join(temp_folder, scene_id) if not os.path.exists(temp_folder): os.makedirs(temp_folder) if not os.path.exists(scene_folder): os.makedirs(scene_folder) # Download section for Band 4 using urllib2 file_name = url_red.split('/')[-1] u = urllib2.urlopen(url_red) f = open("temp_folder/"+scene_id+"/"+file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() # Download section for Band 5 using urllib2 file_name = url_nir.split('/')[-1] u = urllib2.urlopen(url_nir) f = open("temp_folder/"+scene_id+"/"+file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() # NDVI processing # Lets create new instance of class nd = NDVIWithManualColorMap(path=temp_folder+"/"+scene_id, dst_path=temp_folder) # Start process print nd.run() # Create virtual dataset for deviding tiff into tiles subprocess.call(["gdalbuildvrt", "-a_srs", "EPSG:3857", "NDVImap.vrt", "temp_folder/"+scene_id+"/"+ndvi_file]) # Remove old tiles shutil.rmtree("ndvi_tiles", ignore_errors=True) # Start process of deviding with virtual dataset subprocess.call(["./gdal2tilesp.py", "-w", "none", "-s EPSG:3857", "-p", "mercator", "-z 8-12", "--format=PNG", "--processes=4", "-o", "tms", "NDVImap.vrt", "ndvi_tiles"]) # Let`s clean temporary files (bands, ndvi, vrt) shutil.rmtree("temp_folder", ignore_errors=True) os.remove("NDVImap.vrt") print 'All temporary data was succsessfully removed' # Close script raise SystemExit('Closing...')
vladanti/ndvi_calc
ndvi.py
Python
gpl-3.0
4,318
<?php namespace console\models; class test extends \fw\base\Object { public function test() { return "test".$this->par; } }
hz86/myfw
console/models/test.php
PHP
gpl-3.0
131
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; namespace Blm.Models { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { } }
zypah/blm
blm/Models/ApplicationUser.cs
C#
gpl-3.0
319
require 'spec_helper_acceptance' describe 'Scenario: install foreman' do apache_service_name = ['debian', 'ubuntu'].include?(os[:family]) ? 'apache2' : 'httpd' before(:context) do case fact('osfamily') when 'RedHat' on default, 'yum -y remove foreman* tfm-* mod_passenger && rm -rf /etc/yum.repos.d/foreman*.repo' when 'Debian' on default, 'apt-get purge -y foreman*', { :acceptable_exit_codes => [0, 100] } on default, 'apt-get purge -y ruby-hammer-cli-*', { :acceptable_exit_codes => [0, 100] } on default, 'rm -rf /etc/apt/sources.list.d/foreman*' end on default, "systemctl stop #{apache_service_name}", { :acceptable_exit_codes => [0, 5] } end let(:pp) do <<-EOS # Workarounds ## Ensure repos are present before installing Yumrepo <| |> -> Package <| |> ## We want passenger from EPEL class { '::apache::mod::passenger': manage_repo => false, } $directory = '/etc/foreman' $certificate = "${directory}/certificate.pem" $key = "${directory}/key.pem" exec { 'Create certificate directory': command => "mkdir -p ${directory}", path => ['/bin', '/usr/bin'], creates => $directory, } -> exec { 'Generate certificate': command => "openssl req -nodes -x509 -newkey rsa:2048 -subj '/CN=${facts['fqdn']}' -keyout '${key}' -out '${certificate}' -days 365", path => ['/bin', '/usr/bin'], creates => $certificate, umask => '0022', } -> file { [$key, $certificate]: owner => 'root', group => 'root', mode => '0640', } -> class { '::foreman': repo => 'nightly', user_groups => [], initial_admin_username => 'admin', initial_admin_password => 'changeme', server_ssl_ca => $certificate, server_ssl_chain => $certificate, server_ssl_cert => $certificate, server_ssl_key => $key, server_ssl_crl => '', } EOS end it_behaves_like 'a idempotent resource' describe service(apache_service_name) do it { is_expected.to be_enabled } it { is_expected.to be_running } end describe service('dynflowd') do it { is_expected.to be_enabled } it { is_expected.to be_running } end describe package('foreman-journald') do it { is_expected.not_to be_installed } end describe package('foreman-telemetry') do it { is_expected.not_to be_installed } end describe port(80) do it { is_expected.to be_listening } end describe port(443) do it { is_expected.to be_listening } end describe command("curl -s --cacert /etc/foreman/certificate.pem https://#{host_inventory['fqdn']} -w '\%{redirect_url}' -o /dev/null") do its(:stdout) { is_expected.to eq("https://#{host_inventory['fqdn']}/users/login") } its(:exit_status) { is_expected.to eq 0 } end end
carrolcox/puppet-foreman
spec/acceptance/foreman_basic_spec.rb
Ruby
gpl-3.0
2,923
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.Text; using System.Windows.Forms; using OpenDental.UI; using OpenDentBusiness; namespace OpenDental { public partial class FormEquipment:Form { private List<Equipment> listEquip; private int pagesPrinted; private bool headingPrinted; private int headingPrintH; public FormEquipment() { InitializeComponent(); Lan.F(this); } private void FormEquipment_Load(object sender,EventArgs e) { FillGrid(); } private void radioPurchased_Click(object sender,EventArgs e) { FillGrid(); } private void radioSold_Click(object sender,EventArgs e) { FillGrid(); } private void radioAll_Click(object sender,EventArgs e) { FillGrid(); } private void textSn_TextChanged(object sender,EventArgs e) { FillGrid(); } private void butRefresh_Click(object sender,EventArgs e) { if(textDateStart.errorProvider1.GetError(textDateStart)!="" || textDateEnd.errorProvider1.GetError(textDateEnd)!="") { MsgBox.Show(this,"Invalid date."); return; } FillGrid(); } private void FillGrid(){ if(textDateStart.errorProvider1.GetError(textDateStart)!="" || textDateEnd.errorProvider1.GetError(textDateEnd)!="") { return; } DateTime fromDate; DateTime toDate; if(textDateStart.Text=="") { fromDate=DateTime.MinValue.AddDays(1);//because we don't want to include 010101 } else { fromDate=PIn.Date(textDateStart.Text); } if(textDateEnd.Text=="") { toDate=DateTime.MaxValue; } else { toDate=PIn.Date(textDateEnd.Text); } EnumEquipmentDisplayMode display=EnumEquipmentDisplayMode.All; if(radioPurchased.Checked){ display=EnumEquipmentDisplayMode.Purchased; } if(radioSold.Checked){ display=EnumEquipmentDisplayMode.Sold; } listEquip=Equipments.GetList(fromDate,toDate,display,textSnDesc.Text); gridMain.BeginUpdate(); if(radioPurchased.Checked) { gridMain.HScrollVisible=true; } else { gridMain.HScrollVisible=false; } gridMain.Columns.Clear(); ODGridColumn col=new ODGridColumn(Lan.g(this,"Description"),150); gridMain.Columns.Add(col); col=new ODGridColumn(Lan.g(this,"SerialNumber"),90); gridMain.Columns.Add(col); col=new ODGridColumn(Lan.g(this,"Yr"),40); gridMain.Columns.Add(col); col=new ODGridColumn(Lan.g(this,"DatePurchased"),90); gridMain.Columns.Add(col); if(display!=EnumEquipmentDisplayMode.Purchased) {//Purchased mode is designed for submission to tax authority, only certain columns col=new ODGridColumn(Lan.g(this,"DateSold"),90); gridMain.Columns.Add(col); } col=new ODGridColumn(Lan.g(this,"Cost"),80,HorizontalAlignment.Right); gridMain.Columns.Add(col); col=new ODGridColumn(Lan.g(this,"Est Value"),80,HorizontalAlignment.Right); gridMain.Columns.Add(col); if(display!=EnumEquipmentDisplayMode.Purchased) { col=new ODGridColumn(Lan.g(this,"Location"),80); gridMain.Columns.Add(col); } col=new ODGridColumn(Lan.g(this,"Status"),160); gridMain.Columns.Add(col); gridMain.Rows.Clear(); ODGridRow row; for(int i=0;i<listEquip.Count;i++){ row=new ODGridRow(); row.Cells.Add(listEquip[i].Description); row.Cells.Add(listEquip[i].SerialNumber); row.Cells.Add(listEquip[i].ModelYear); row.Cells.Add(listEquip[i].DatePurchased.ToShortDateString()); if(display!=EnumEquipmentDisplayMode.Purchased) { if(listEquip[i].DateSold.Year<1880) { row.Cells.Add(""); } else { row.Cells.Add(listEquip[i].DateSold.ToShortDateString()); } } row.Cells.Add(listEquip[i].PurchaseCost.ToString("f")); row.Cells.Add(listEquip[i].MarketValue.ToString("f")); if(display!=EnumEquipmentDisplayMode.Purchased) { row.Cells.Add(listEquip[i].Location); } row.Cells.Add(listEquip[i].Status.ToString()); gridMain.Rows.Add(row); } gridMain.EndUpdate(); } private void butAdd_Click(object sender,EventArgs e) { Equipment equip=new Equipment(); equip.SerialNumber=Equipments.GenerateSerialNum(); equip.DateEntry=DateTime.Today; equip.DatePurchased=DateTime.Today; FormEquipmentEdit form=new FormEquipmentEdit(); form.IsNew=true; form.Equip=equip; form.ShowDialog(); if(form.DialogResult==DialogResult.OK) { FillGrid(); } } private void gridMain_CellDoubleClick(object sender,ODGridClickEventArgs e) { FormEquipmentEdit form=new FormEquipmentEdit(); form.Equip=listEquip[e.Row]; form.ShowDialog(); if(form.DialogResult==DialogResult.OK) { FillGrid(); } } private void butPrint_Click(object sender,EventArgs e) { pagesPrinted=0; PrintDocument pd=new PrintDocument(); pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage); pd.DefaultPageSettings.Margins=new Margins(25,25,40,40); //pd.OriginAtMargins=true; //pd.DefaultPageSettings.Landscape=true; if(pd.DefaultPageSettings.PrintableArea.Height==0) { pd.DefaultPageSettings.PaperSize=new PaperSize("default",850,1100); } headingPrinted=false; try { #if DEBUG FormRpPrintPreview pView = new FormRpPrintPreview(); pView.printPreviewControl2.Document=pd; pView.ShowDialog(); #else if(PrinterL.SetPrinter(pd,PrintSituation.Default,0,"Equipment list printed")) { pd.Print(); } #endif } catch { MessageBox.Show(Lan.g(this,"Printer not available")); } } private void pd_PrintPage(object sender,System.Drawing.Printing.PrintPageEventArgs e) { Rectangle bounds=e.MarginBounds; //new Rectangle(50,40,800,1035);//Some printers can handle up to 1042 Graphics g=e.Graphics; string text; Font headingFont=new Font("Arial",13,FontStyle.Bold); Font subHeadingFont=new Font("Arial",10,FontStyle.Bold); int yPos=bounds.Top; int center=bounds.X+bounds.Width/2; #region printHeading if(!headingPrinted) { text=Lan.g(this,"Equipment List"); if(radioPurchased.Checked) { text+=" - "+Lan.g(this,"Purchased"); } if(radioSold.Checked) { text+=" - "+Lan.g(this,"Sold"); } if(radioAll.Checked) { text+=" - "+Lan.g(this,"All"); } g.DrawString(text,headingFont,Brushes.Black,center-g.MeasureString(text,headingFont).Width/2,yPos); yPos+=(int)g.MeasureString(text,headingFont).Height; text=textDateStart.Text+" "+Lan.g(this,"to")+" "+textDateEnd.Text; g.DrawString(text,subHeadingFont,Brushes.Black,center-g.MeasureString(text,subHeadingFont).Width/2,yPos); yPos+=20; headingPrinted=true; headingPrintH=yPos; } #endregion yPos=gridMain.PrintPage(g,pagesPrinted,bounds,headingPrintH); pagesPrinted++; if(yPos==-1) { e.HasMorePages=true; } else { e.HasMorePages=false; double total=0; for(int i=0;i<listEquip.Count;i++){ total+=listEquip[i].MarketValue; } g.DrawString(Lan.g(this,"Total Est Value:")+" "+total.ToString("c"),Font,Brushes.Black,550,yPos); } g.Dispose(); } private void butClose_Click(object sender,EventArgs e) { Close(); } } }
eae/opendental
OpenDental/Forms/FormEquipment.cs
C#
gpl-3.0
7,203
module.exports = function(el, state, container) { var ul = el.getElementsByTagName('ul')[0] var lastFlags = [] var controlsTouch = -1 var containerTouch = {"id":-1, "x":-1, "y":-1} el.addEventListener('touchstart', startTouchControls) el.addEventListener('touchmove', handleTouchControls) el.addEventListener('touchend', unTouchControls) container.addEventListener('touchstart', startTouchContainer) container.addEventListener('touchmove', handleTouchContainer) container.addEventListener('touchend', unTouchContainer) function startTouchControls(event) { if (controlsTouch === -1) { controlsTouch = event.targetTouches[0].identifier } handleTouchControls(event) } function handleTouchControls(event) { event.preventDefault() var touch = null if (event.targetTouches.length > 1) { for (t in event.targetTouches) { if (event.targetTouches[t].identifier === controlsTouch) { touch = event.targetTouches[t] break } } } else { touch = event.targetTouches[0] } if (touch === null) return var top=touch.clientY-el.offsetTop var left=touch.clientX-el.offsetLeft var flags=[] if (top < 50) flags.push('forward') if (left < 50 && top < 100) flags.push('left') if (left > 100 && top < 100) flags.push('right') if (top > 100 && left > 50 && left < 100) flags.push('backward') if (top > 50 && top < 100 && left > 50 && left < 100) flags.push('jump') if (flags.indexOf('jump') === -1) { for (flag in lastFlags) { if (flags.indexOf(lastFlags[flag]) !== -1) { lastFlags.splice(flag, 1) } } setState(lastFlags, 0) setState(flags, 1) lastFlags = flags } else if (lastFlags.indexOf('jump') === -1) { // Start jumping (in additional to existing movement) lastFlags.push('jump') setState(['jump'], 1) } } function unTouchControls() { setState(lastFlags, 0) lastFlags = [] controlsTouch = -1 } function setState(states, value) { var delta = {} for(s in states) { delta[states[s]] = value } state.write(delta) } function startTouchContainer(event) { if (containerTouch.id === -1) { containerTouch.id = event.targetTouches[0].identifier containerTouch.x = event.targetTouches[0].clientX containerTouch.y = event.targetTouches[0].clientY } handleTouchContainer(event) } function handleTouchContainer(event) { event.preventDefault() var touch = null, x = y = -1, delta = {} for (t in event.targetTouches) { if (event.targetTouches[t].identifier === containerTouch.id) { touch = event.targetTouches[t] break } } if (touch === null) return dx = containerTouch.x - touch.clientX dy = containerTouch.y - touch.clientY delta.x_rotation_accum = dy * 2 delta.y_rotation_accum = dx * 8 state.write(delta) containerTouch.x = touch.clientX containerTouch.y = touch.clientY } function unTouchContainer(event) { containerTouch = {"id":-1, "x":-1, "y":-1} } }
pauln/voxel-touchcontrols
index.js
JavaScript
gpl-3.0
3,130
/* This file is part of White - Storm: Lightning (alpha). Copyright 2012 Christopher Augustus Greeley White - Storm: Lightning (alpha) 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. White - Storm: Lightning (alpha) 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 White - Storm: Lightning (alpha). If not, see <http://www.gnu.org/licenses/>. */ #include "Bubble Sort.h" void WSL::Algorithmic::BubbleSort::BubbleSortAlgorithm( WSL::Containers::PointableVector< WSL::Containers::RenderType > *toBeSorted ) { WSL::Containers::RenderType transfer; const unsigned int SIZE = toBeSorted->vector.size(); for( unsigned int i = 0; i < SIZE; ++i ) { for( unsigned int j = 0; j < SIZE; ++j ) { if( ( j + 1 ) < SIZE ) { if( toBeSorted->vector[ j ].z > toBeSorted->vector[ ( j + 1 ) ].z ) { transfer = toBeSorted->vector[ j ]; toBeSorted->vector[ j ] = toBeSorted->vector[ ( j + 1 ) ]; toBeSorted->vector[ j + 1 ] = transfer; } } else if( toBeSorted->vector[ 0 ].z > toBeSorted->vector[ j ].z ) { transfer = toBeSorted->vector[ 0 ]; toBeSorted->vector[ 0 ] = toBeSorted->vector[ j ]; toBeSorted->vector[ j ] = transfer; } } } }
GCGGames/White-StormLightning
WSL/Bubble Sort.cpp
C++
gpl-3.0
1,657
######################################################################## # File : ARCComputingElement.py # Author : A.T. ######################################################################## """ ARC Computing Element """ __RCSID__ = "58c42fc (2013-07-07 22:54:57 +0200) Andrei Tsaregorodtsev <atsareg@in2p3.fr>" import os import stat import tempfile from types import StringTypes from DIRAC import S_OK, S_ERROR from DIRAC.Resources.Computing.ComputingElement import ComputingElement from DIRAC.Core.Utilities.Grid import executeGridCommand CE_NAME = 'ARC' MANDATORY_PARAMETERS = [ 'Queue' ] class ARCComputingElement( ComputingElement ): ############################################################################# def __init__( self, ceUniqueID ): """ Standard constructor. """ ComputingElement.__init__( self, ceUniqueID ) self.ceType = CE_NAME self.submittedJobs = 0 self.mandatoryParameters = MANDATORY_PARAMETERS self.pilotProxy = '' self.queue = '' self.outputURL = 'gsiftp://localhost' self.gridEnv = '' self.ceHost = self.ceName if 'Host' in self.ceParameters: self.ceHost = self.ceParameters['Host'] if 'GridEnv' in self.ceParameters: self.gridEnv = self.ceParameters['GridEnv'] ############################################################################# def _addCEConfigDefaults( self ): """Method to make sure all necessary Configuration Parameters are defined """ # First assure that any global parameters are loaded ComputingElement._addCEConfigDefaults( self ) def __writeXRSL( self, executableFile ): """ Create the JDL for submission """ workingDirectory = self.ceParameters['WorkingDirectory'] fd, name = tempfile.mkstemp( suffix = '.xrsl', prefix = 'ARC_', dir = workingDirectory ) diracStamp = os.path.basename( name ).replace( '.xrsl', '' ).replace( 'ARC_', '' ) xrslFile = os.fdopen( fd, 'w' ) xrsl = """ &(executable="%(executable)s") (inputFiles=(%(executable)s "%(executableFile)s")) (stdout="%(diracStamp)s.out") (stderr="%(diracStamp)s.err") (outputFiles=("%(diracStamp)s.out" "") ("%(diracStamp)s.err" "")) """ % { 'executableFile':executableFile, 'executable':os.path.basename( executableFile ), 'diracStamp':diracStamp } xrslFile.write( xrsl ) xrslFile.close() return name, diracStamp def _reset( self ): self.queue = self.ceParameters['Queue'] self.gridEnv = self.ceParameters['GridEnv'] ############################################################################# def submitJob( self, executableFile, proxy, numberOfJobs = 1 ): """ Method to submit job """ self.log.verbose( "Executable file path: %s" % executableFile ) if not os.access( executableFile, 5 ): os.chmod( executableFile, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH + stat.S_IXOTH ) batchIDList = [] stampDict = {} i = 0 while i < numberOfJobs: i += 1 xrslName, diracStamp = self.__writeXRSL( executableFile ) cmd = ['arcsub', '-j', self.ceParameters['JobListFile'], '-c', '%s' % self.ceHost, '%s' % xrslName ] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) os.unlink( xrslName ) if not result['OK']: break if result['Value'][0] != 0: break pilotJobReference = result['Value'][1].strip() if pilotJobReference and pilotJobReference.startswith('Job submitted with jobid:'): pilotJobReference = pilotJobReference.replace('Job submitted with jobid:', '').strip() batchIDList.append( pilotJobReference ) stampDict[pilotJobReference] = diracStamp else: break #os.unlink( executableFile ) if batchIDList: result = S_OK( batchIDList ) result['PilotStampDict'] = stampDict else: result = S_ERROR('No pilot references obtained from the glite job submission') return result def killJob( self, jobIDList ): """ Kill the specified jobs """ workingDirectory = self.ceParameters['WorkingDirectory'] fd, name = tempfile.mkstemp( suffix = '.list', prefix = 'KillJobs_', dir = workingDirectory ) jobListFile = os.fdopen( fd, 'w' ) jobList = list( jobIDList ) if type( jobIDList ) in StringTypes: jobList = [ jobIDList ] for job in jobList: jobListFile.write( job+'\n' ) cmd = ['arckill', '-c', self.ceHost, '-i', name] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) os.unlink( name ) if not result['OK']: return result if result['Value'][0] != 0: return S_ERROR( 'Failed kill job: %s' % result['Value'][0][1] ) return S_OK() ############################################################################# def getCEStatus( self ): """ Method to return information on running and pending jobs. """ cmd = ['arcstat', '-c', self.ceHost, '-j', self.ceParameters['JobListFile'] ] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) resultDict = {} if not result['OK']: return result if result['Value'][0] == 1 and result['Value'][1] == "No jobs\n": result = S_OK() result['RunningJobs'] = 0 result['WaitingJobs'] = 0 result['SubmittedJobs'] = 0 return result if result['Value'][0]: if result['Value'][2]: return S_ERROR(result['Value'][2]) else: return S_ERROR('Error while interrogating CE status') if result['Value'][1]: resultDict = self.__parseJobStatus( result['Value'][1] ) running = 0 waiting = 0 for ref in resultDict: status = resultDict[ref] if status == 'Scheduled': waiting += 1 if status == 'Running': running += 1 result = S_OK() result['RunningJobs'] = running result['WaitingJobs'] = waiting result['SubmittedJobs'] = 0 return result def __parseJobStatus( self, commandOutput ): """ """ resultDict = {} lines = commandOutput.split('\n') ln = 0 while ln < len( lines ): if lines[ln].startswith( 'Job:' ): jobRef = lines[ln].split()[1] ln += 1 line = lines[ln].strip() stateARC = '' if line.startswith( 'State' ): stateARC = line.replace( 'State:','' ).strip() line = lines[ln+1].strip() exitCode = None if line.startswith( 'Exit Code' ): line = line.replace( 'Exit Code:','' ).strip() exitCode = int( line ) # Evaluate state now if stateARC in ['Accepted','Preparing','Submitting','Queuing','Hold']: resultDict[jobRef] = "Scheduled" elif stateARC in ['Running','Finishing']: resultDict[jobRef] = "Running" elif stateARC in ['Killed','Deleted']: resultDict[jobRef] = "Killed" elif stateARC in ['Finished','Other']: if exitCode is not None: if exitCode == 0: resultDict[jobRef] = "Done" else: resultDict[jobRef] = "Failed" else: resultDict[jobRef] = "Failed" elif stateARC in ['Failed']: resultDict[jobRef] = "Failed" else: self.log.warn( "Unknown state %s for job %s" % ( stateARC, jobRef ) ) elif lines[ln].startswith( "WARNING: Job information not found:" ): jobRef = lines[ln].replace( 'WARNING: Job information not found:', '' ).strip() resultDict[jobRef] = "Scheduled" ln += 1 return resultDict def getJobStatus( self, jobIDList ): """ Get the status information for the given list of jobs """ workingDirectory = self.ceParameters['WorkingDirectory'] fd, name = tempfile.mkstemp( suffix = '.list', prefix = 'StatJobs_', dir = workingDirectory ) jobListFile = os.fdopen( fd, 'w' ) jobTmpList = list( jobIDList ) if type( jobIDList ) in StringTypes: jobTmpList = [ jobIDList ] jobList = [] for j in jobTmpList: if ":::" in j: job = j.split(":::")[0] else: job = j jobList.append( job ) jobListFile.write( job+'\n' ) cmd = ['arcstat', '-c', self.ceHost, '-i', name, '-j', self.ceParameters['JobListFile']] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) os.unlink( name ) resultDict = {} if not result['OK']: self.log.error( 'Failed to get job status', result['Message'] ) return result if result['Value'][0]: if result['Value'][2]: return S_ERROR(result['Value'][2]) else: return S_ERROR('Error while interrogating job statuses') if result['Value'][1]: resultDict = self.__parseJobStatus( result['Value'][1] ) if not resultDict: return S_ERROR('No job statuses returned') # If CE does not know about a job, set the status to Unknown for job in jobList: if not resultDict.has_key( job ): resultDict[job] = 'Unknown' return S_OK( resultDict ) def getJobOutput( self, jobID, localDir = None ): """ Get the specified job standard output and error files. If the localDir is provided, the output is returned as file in this directory. Otherwise, the output is returned as strings. """ if jobID.find( ':::' ) != -1: pilotRef, stamp = jobID.split( ':::' ) else: pilotRef = jobID stamp = '' if not stamp: return S_ERROR( 'Pilot stamp not defined for %s' % pilotRef ) arcID = os.path.basename(pilotRef) if "WorkingDirectory" in self.ceParameters: workingDirectory = os.path.join( self.ceParameters['WorkingDirectory'], arcID ) else: workingDirectory = arcID outFileName = os.path.join( workingDirectory, '%s.out' % stamp ) errFileName = os.path.join( workingDirectory, '%s.err' % stamp ) cmd = ['arcget', '-j', self.ceParameters['JobListFile'], pilotRef ] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) output = '' if result['OK']: if not result['Value'][0]: outFile = open( outFileName, 'r' ) output = outFile.read() outFile.close() os.unlink( outFileName ) errFile = open( errFileName, 'r' ) error = errFile.read() errFile.close() os.unlink( errFileName ) else: error = '\n'.join( result['Value'][1:] ) return S_ERROR( error ) else: return S_ERROR( 'Failed to retrieve output for %s' % jobID ) return S_OK( ( output, error ) ) #EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
miloszz/DIRAC
Resources/Computing/ARCComputingElement.py
Python
gpl-3.0
10,864
#!/usr/bin/env python3 import re a = [[0 for x in range(25)] for y in range(13)] f=open("../distrib/spiral.txt","r") s=f.readline().strip() dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] x, y, c = 0, -1, 1 l=0 for i in range(13+13-1): if i%2==0: for j in range((25+25-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1 else: for j in range((13+13-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1 for i in a: for k in i: k=re.sub(r"¦","█",k) k=re.sub(r"¯","▀",k) k=re.sub(r"_","▄",k) print(k,end="") print()
DISMGryphons/GryphonCTF2017-Challenges
challenges/misc/Spirals/solution/solution.py
Python
gpl-3.0
812
<?php require_once('../common/config.php'); require_once('./config.php'); if (!(defined('ACCOUNT_SERVER') && defined('ACCOUNT_LIST') && defined('RESPONSE_HEADER'))) //Fatal Error { exit(0); } $out=RESPONSE_HEADER; $buffer=file_get_contents("php://input"); if (substr($buffer,0,QUERY_HEADER_LEN)!=QUERY_HEADER) $out.=chr(RESPONSE_INVALID); else { // Check validity of device version $device=ord(substr($buffer,QUERY_HEADER_LEN,1)); if (!in_array($device,$validVersion)) $out.=chr(RESPONSE_DEVICE_UNSUPPORTED); else { // Check validity of option ID $option=ord(substr($buffer,QUERY_HEADER_LEN+1,1)); if (!($option==QUERY_LOGIN_TYPE_NONE || $option==QUERY_LOGIN_TYPE_GET_KEY || $option==QUERY_LOGIN_TYPE_LOGIN)) $out.=chr(RESPONSE_INVALID); else { include_once('../common/lib.php'); include_once('../common/enc.php'); switch($option) { case QUERY_LOGIN_TYPE_NONE: $out.=chr(RESPONSE_SUCCESS); break; case QUERY_LOGIN_TYPE_GET_KEY: // Extract real ID $ID=substr($buffer,QUERY_HEADER_LEN+2,QUERY_LOGIN_ACCOUNT_LEN); $key=substr($buffer,QUERY_HEADER_LEN+2+QUERY_LOGIN_ACCOUNT_LEN); $ID=fuse_R($ID,$key); if (!checkID($ID)) {$out.=chr(RESPONSE_INVALID); break;} // Extract pre-login key $db=new accDB(ACCOUNT_LIST); if (!$db->OK) {$out.=chr(RESPONSE_FAILED); break;} $password=$db->getPW($ID); $key=aes_decrypt($key,$password); if (!checkKey($key,QUERY_LOGIN_KEY_LEN)) {$out.=chr(RESPONSE_INVALID); break;} // Generate pre-encryption key $randKey=genKey(QUERY_LOGIN_KEY_LEN); $key=bytesXOR($randKey,$key); // Write pre-encryption information to database, // then return the pre-encryption key to client $db2=new loginDB(LOGIN_LIST); if (!$db2->OK) {$out.=chr(RESPONSE_FAILED); break;} $tempRecord=new loginRecord(); $tempRecord->ID=$ID; $tempRecord->ID_Encoded=substr(hmac($ID,$randKey),0,QUERY_LOGIN_ACCOUNT_LEN); $tempRecord->Key=$randKey; $tempRecord->LastTime=gmdate(TIME_FORMAT); $tempRecord->Device=$device; if (!$db2->setRecord($tempRecord)) $out.=chr(RESPONSE_FAILED); else $out.=chr(RESPONSE_SUCCESS).aes_encrypt($key,$password); break; case QUERY_LOGIN_TYPE_LOGIN: // Extract hashed ID $ID=substr($buffer,QUERY_HEADER_LEN+2,QUERY_LOGIN_ACCOUNT_LEN); // Read pre-encryption information from database $db=new loginDB(LOGIN_LIST); if (!$db->OK) {$out.=chr(RESPONSE_FAILED); break;} $tempRecord=$db->getRecord($ID,true); if (!$tempRecord) $out.=chr(RESPONSE_FAILED); else { // Reject device change or login timeout if ($tempRecord->Device != $device) {$out.=chr(RESPONSE_FAILED); break;} if (timeDiff($tempRecord->LastTime)>LOGIN_TIME_EXPIRE) {$out.=chr(RESPONSE_DATE_EXPIRED); break;} // Read double-hashed password from database $db2=new accDB(ACCOUNT_LIST); if (!$db2->OK) {$out.=chr(RESPONSE_FAILED); break;} $passwordAndSalt=$db2->getPW2($tempRecord->ID); // Extract hashed password, // then re-hash it with the given salt $plainText=aes_decrypt(substr($buffer,QUERY_HEADER_LEN+2+QUERY_LOGIN_ACCOUNT_LEN),$tempRecord->Key); $password=hmac(substr($plainText,0,ACCOUNT_KEY_LEN), substr($passwordAndSalt,ACCOUNT_KEY_SALTED_LEN)); // Compare double-hashed password if (substr($passwordAndSalt,0,ACCOUNT_KEY_SALTED_LEN) != substr($password,0,ACCOUNT_KEY_SALTED_LEN)) {$out.=chr(RESPONSE_FAILED); break;} // Extract online state $state=ord(substr($plainText,ACCOUNT_KEY_LEN,1)); if (!($state==ACCOUNT_STATE_HIDE || $state==ACCOUNT_STATE_ONLINE || $state==ACCOUNT_STATE_BUSY)) {$out.=chr(RESPONSE_INVALID);break;} // Update account information to database $account=$db2->getRecord($tempRecord->ID); $account->State=$state; $account->LastDevice=$device; if (!$db2->setRecord($account)) {$out.=chr(RESPONSE_FAILED); break;} // Generate session information, write it to database, // then return it to client $sessionID=genKey(ACCOUNT_SESSION_LEN); $sessionKey=genKey(ACCOUNT_COMMKEY_LEN,$tempRecord->Key); $db3=new commDB(COMM_LIST); if (!$db3->OK) {$out.=chr(RESPONSE_FAILED); break;} if (!$db3->setSession($tempRecord->ID,$sessionID,$sessionKey)) $out.=chr(RESPONSE_FAILED); else { $outContent=chr(RESPONSE_SUCCESS).chr($account->State).intToBytes(ACCOUNT_ACTIVE_TIME,2).$sessionKey.$account->Msg; $out.=chr(RESPONSE_SUCCESS).$sessionID.aes_encrypt(crc32sum($outContent).$outContent,$tempRecord->Key); } } break; default: $out.=chr(RESPONSE_INVALID); //Should never reach here } } } } echo($out); exit(0); ?>
zwpwjwtz/WiChat-server
Account/log/login.php
PHP
gpl-3.0
4,876
/* This file is part of the EnergyOptimizatorOfRoboticCells program. EnergyOptimizatorOfRoboticCells 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. EnergyOptimizatorOfRoboticCells 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 EnergyOptimizatorOfRoboticCells. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <cmath> #include <chrono> #include <map> #include <set> #include <string> #include "Settings.h" #include "SolverConfig.h" #include "Shared/Utils.h" #include "Shared/Exceptions.h" #include "ILPModel/SolverInterface.h" #include "ILPSolver/RoboticLineSolverILP.h" using namespace std; using namespace std::chrono; RoboticLineSolverILP::RoboticLineSolverILP(Robot* r, const PrecalculatedMapping& m) : mMapper(r) { ConstraintsGenerator generator(r, &m); construct(generator, false); } RoboticLineSolverILP::RoboticLineSolverILP(const RoboticLine& l, const PrecalculatedMapping& m) : mMapper(l) { ConstraintsGenerator generator(l, &m); construct(generator, l.robots().size() > 1); } Solution RoboticLineSolverILP::solve(double relGap, double timLim) const { #ifdef GUROBI_SOLVER initializeLocalEnvironments(1u); #endif Solution s; high_resolution_clock::time_point start = high_resolution_clock::now(); SolutionILP sILP = solveILP(mModel, Settings::VERBOSE, relGap, timLim, Settings::NUMBER_OF_THREADS); s.runTime = duration_cast<duration<double>>(high_resolution_clock::now()-start).count(); s.status = convert(sILP.status); if (sILP.status == ILP_OPTIMAL || sILP.status == ILP_FEASIBLE) { s.lowerBound = sILP.bound; s.totalEnergy = sILP.criterion; try { set<uint32_t> selectedActivities; map<uint32_t, double> idToStart = inverseMapping(sILP.solution, mMapper.s); map<uint32_t, double> idToDuration = inverseMapping(sILP.solution, mMapper.d); map<uint32_t, uint32_t> idToPoint = inverseMapping(sILP.solution, mMapper.x); map<uint32_t, uint32_t> idToPowerMode = inverseMapping(sILP.solution, mMapper.z); map<uint32_t, uint32_t> idToMovement = inverseMapping(sILP.solution, mMapper.y); if (idToStart.size() != idToDuration.size() && idToPoint.size() != idToPowerMode.size()) throw SolverException(caller(), "ILP model is invalid probably!"); double minStartTime = F64_MAX; for (const auto& p : idToPoint) { uint32_t aid = p.first, point = p.second; uint32_t pwrm = getValue(idToPowerMode, aid, caller()); setValue(s.pointAndPowerMode, aid, {point, pwrm}, caller()); minStartTime = min(minStartTime, getValue(idToStart, aid, caller())); selectedActivities.insert(aid); } for (const auto& p : idToMovement) { minStartTime = min(minStartTime, getValue(idToStart, p.first, caller())); selectedActivities.insert(p.first); } for (const uint32_t& aid : selectedActivities) { double start = getValue(idToStart, aid, caller())-minStartTime; // Set initial time of Gantt chart to zero. double duration = getValue(idToDuration, aid, caller()); setValue(s.startTimeAndDuration, aid, {start, duration}, caller()); } } catch (...) { throw_with_nested(SolverException(caller(), "Cannot map ILP solution to the problem solution!\nCheck validity of the model...")); } } else if (sILP.status != ILP_UNKNOWN) { s.lowerBound = sILP.bound; } return s; } double RoboticLineSolverILP::lowerBoundOnEnergy(const vector<Robot*>& robots, const PrecalculatedMapping& m) { double lowerBound = 0.0; for (Robot* r : robots) { RoboticLineSolverILP solver(r, m); Solution s = solver.solve(0.0, Settings::RUNTIME_OF_LOWER_BOUND/robots.size()); lowerBound += s.lowerBound; } return lowerBound; } void RoboticLineSolverILP::construct(ConstraintsGenerator& generator, bool addGlobalConstraints) { try { generator.addEnergyFunctions(mMapper.d, mMapper.W, mMapper.x, mMapper.z, mMapper.y); generator.addUniqueModeSelection(mMapper.x, mMapper.z); generator.addFlowConstraints(mMapper.x, mMapper.y); generator.addAllPrecedences(mMapper.s, mMapper.d, mMapper.y, mMapper.w); generator.addDurationConstraints(mMapper.d, mMapper.z, mMapper.y); if (addGlobalConstraints) generator.addGlobalConstraints(mMapper.s, mMapper.d, mMapper.x, mMapper.y, mMapper.c); mModel.c.resize(mMapper.numberOfVariables(), 0.0); for (const auto& p : mMapper.W) mModel.c[p.second] = 1.0; } catch (...) { string msg = "Cannot add constraints to the ILP model!\nEither variable mapping or RoboticLine data-structure is corrupted!"; throw_with_nested(SolverException(caller(), msg)); } mModel.x = move(mMapper.variables); mModel.varDesc = move(mMapper.varDesc); generator.moveConstraintsToModel(mModel); #ifndef NDEBUG mModel.checkFormulation(); #endif if (Settings::VERBOSE == true) { cout<<endl; mModel.printStatistics(); cout<<endl; } }
CTU-IIG/EnergyOptimizatorOfRoboticCells
src/ILPSolver/RoboticLineSolverILP.cpp
C++
gpl-3.0
5,243
/******************************************************************************* * ISPTAP - Instruction Scratchpad Timing Analysis Program * Copyright (C) 2013 Stefan Metzlaff, University of Augsburg, Germany * URL: <https://github.com/smetzlaff/isptap> * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program, see <LICENSE>. If not, see * <http://www.gnu.org/licenses/>. ******************************************************************************/ #ifndef _GRAPHVIZEXPORT_HPP_ #define _GRAPHVIZEXPORT_HPP_ #include "global.h" #include "graph_structure.h" #include <boost/graph/graphviz.hpp> /** * Export object for ControlFlogGraphs * Graphviz file is created, but the vertex and edge preferences are currently not written. */ class GraphVizExport { public: GraphVizExport(string filename); virtual ~GraphVizExport(); bool exportGraph(ControlFlowGraph cfg); bool exportGraph(ControlFlowGraph cfg, startaddrstring_t, edgename_t); bool exportGraph(FunctionCallGraph fcg); bool exportGraph(MemoryStateGraph msg); bool exportGraph(AbsStackMemGraph asmg); private: string export_filename; ofstream export_file_stream; }; #endif
smetzlaff/isptap
src/util/graphvizexport.hpp
C++
gpl-3.0
1,698
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package # from __future__ import (absolute_import, division, print_function, unicode_literals) from os import path from mantid import logger class WorkspaceLoader(object): @staticmethod def load_workspaces(directory, workspaces_to_load): """ The method that is called to load in workspaces. From the given directory and the workspace names provided. :param directory: String or string castable object; The project directory :param workspaces_to_load: List of Strings; of the workspaces to load """ if workspaces_to_load is None: return from mantid.simpleapi import Load # noqa for workspace in workspaces_to_load: try: Load(path.join(directory, (workspace + ".nxs")), OutputWorkspace=workspace) except Exception: logger.warning("Couldn't load file in project: " + workspace + ".nxs")
mganeva/mantid
qt/python/mantidqt/project/workspaceloader.py
Python
gpl-3.0
1,243
// This file is part of PapyrusDotNet. // // PapyrusDotNet 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. // // PapyrusDotNet 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 PapyrusDotNet. If not, see <http://www.gnu.org/licenses/>. // // Copyright 2016, Karl Patrik Johansson, zerratar@gmail.com #region using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; #endregion namespace PapyrusDotNet.PexInspector.Behaviours { public class DataGridBehaviour { #region DisplayRowNumber public static DependencyProperty DisplayRowNumberProperty = DependencyProperty.RegisterAttached("DisplayRowNumber", typeof (bool), typeof (DataGridBehaviour), new FrameworkPropertyMetadata(false, OnDisplayRowNumberChanged)); public static bool GetDisplayRowNumber(DependencyObject target) { return (bool) target.GetValue(DisplayRowNumberProperty); } public static void SetDisplayRowNumber(DependencyObject target, bool value) { target.SetValue(DisplayRowNumberProperty, value); } private static void OnDisplayRowNumberChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) { var dataGrid = target as DataGrid; if ((bool) e.NewValue) { EventHandler<DataGridRowEventArgs> loadedRowHandler = null; loadedRowHandler = (object sender, DataGridRowEventArgs ea) => { if (GetDisplayRowNumber(dataGrid) == false) { dataGrid.LoadingRow -= loadedRowHandler; return; } ea.Row.Header = new TextBlock {Text = ea.Row.GetIndex().ToString(), Margin = new Thickness(5)}; }; dataGrid.LoadingRow += loadedRowHandler; ItemsChangedEventHandler itemsChangedHandler = null; itemsChangedHandler = (object sender, ItemsChangedEventArgs ea) => { if (GetDisplayRowNumber(dataGrid) == false) { dataGrid.ItemContainerGenerator.ItemsChanged -= itemsChangedHandler; return; } GetVisualChildCollection<DataGridRow>(dataGrid). ForEach( d => d.Header = new TextBlock {Text = d.GetIndex().ToString(), Margin = new Thickness(5)}); }; dataGrid.ItemContainerGenerator.ItemsChanged += itemsChangedHandler; } } #endregion // DisplayRowNumber #region Get Visuals private static List<T> GetVisualChildCollection<T>(object parent) where T : Visual { var visualCollection = new List<T>(); GetVisualChildCollection(parent as DependencyObject, visualCollection); return visualCollection; } private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Visual { var count = VisualTreeHelper.GetChildrenCount(parent); for (var i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child is T) { visualCollection.Add(child as T); } if (child != null) { GetVisualChildCollection(child, visualCollection); } } } #endregion // Get Visuals } }
zerratar/PapyrusDotNet
Source/PexInspector/PapyrusDotNet.PexInspector/Behaviours/DataGridBehaviour.cs
C#
gpl-3.0
4,320
/** @license MIT License (c) copyright B Cavalier & J Hann */ /** * when * A lightweight CommonJS Promises/A and when() implementation * * when is part of the cujo.js family of libraries (http://cujojs.com/) * * Licensed under the MIT License at: * http://www.opensource.org/licenses/mit-license.php * * @version 1.3.0 */ (function(define) { define(function() { var freeze, reduceArray, slice, undef; // // Public API // when.defer = defer; when.reject = reject; when.isPromise = isPromise; when.all = all; when.some = some; when.any = any; when.map = map; when.reduce = reduce; when.chain = chain; /** Object.freeze */ freeze = Object.freeze || function(o) { return o; }; /** * Trusted Promise constructor. A Promise created from this constructor is * a trusted when.js promise. Any other duck-typed promise is considered * untrusted. * * @constructor */ function Promise() {} Promise.prototype = freeze({ always: function(alwaysback, progback) { return this.then(alwaysback, alwaysback, progback); }, otherwise: function(errback) { return this.then(undef, errback); } }); /** * Create an already-resolved promise for the supplied value * @private * * @param value anything * @return {Promise} */ function resolved(value) { var p = new Promise(); p.then = function(callback) { try { return promise(callback ? callback(value) : value); } catch(e) { return rejected(e); } }; return freeze(p); } /** * Create an already-rejected {@link Promise} with the supplied * rejection reason. * @private * * @param reason rejection reason * @return {Promise} */ function rejected(reason) { var p = new Promise(); p.then = function(callback, errback) { try { return errback ? promise(errback(reason)) : rejected(reason); } catch(e) { return rejected(e); } }; return freeze(p); } /** * Returns a rejected promise for the supplied promiseOrValue. If * promiseOrValue is a value, it will be the rejection value of the * returned promise. If promiseOrValue is a promise, its * completion value will be the rejected value of the returned promise * * @param promiseOrValue {*} the rejected value of the returned {@link Promise} * * @return {Promise} rejected {@link Promise} */ function reject(promiseOrValue) { return when(promiseOrValue, function(value) { return rejected(value); }); } /** * Creates a new, CommonJS compliant, Deferred with fully isolated * resolver and promise parts, either or both of which may be given out * safely to consumers. * The Deferred itself has the full API: resolve, reject, progress, and * then. The resolver has resolve, reject, and progress. The promise * only has then. * * @memberOf when * @function * * @returns {Deferred} */ function defer() { var deferred, promise, listeners, progressHandlers, _then, _progress, complete; listeners = []; progressHandlers = []; /** * Pre-resolution then() that adds the supplied callback, errback, and progback * functions to the registered listeners * * @private * * @param [callback] {Function} resolution handler * @param [errback] {Function} rejection handler * @param [progback] {Function} progress handler * * @throws {Error} if any argument is not null, undefined, or a Function */ _then = function unresolvedThen(callback, errback, progback) { var deferred = defer(); listeners.push(function(promise) { promise.then(callback, errback) .then(deferred.resolve, deferred.reject, deferred.progress); }); progback && progressHandlers.push(progback); return deferred.promise; }; /** * Registers a handler for this {@link Deferred}'s {@link Promise}. Even though all arguments * are optional, each argument that *is* supplied must be null, undefined, or a Function. * Any other value will cause an Error to be thrown. * * @memberOf Promise * * @param [callback] {Function} resolution handler * @param [errback] {Function} rejection handler * @param [progback] {Function} progress handler * * @throws {Error} if any argument is not null, undefined, or a Function */ function then(callback, errback, progback) { return _then(callback, errback, progback); } /** * Resolves this {@link Deferred}'s {@link Promise} with val as the * resolution value. * * @memberOf Resolver * * @param val anything */ function resolve(val) { complete(resolved(val)); } /** * Rejects this {@link Deferred}'s {@link Promise} with err as the * reason. * * @memberOf Resolver * * @param err anything */ function reject(err) { complete(rejected(err)); } /** * @private * @param update */ _progress = function(update) { var progress, i = 0; while (progress = progressHandlers[i++]) progress(update); }; /** * Emits a progress update to all progress observers registered with * this {@link Deferred}'s {@link Promise} * * @memberOf Resolver * * @param update anything */ function progress(update) { _progress(update); } /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the resolution or rejection * * @private * * @param completed {Promise} the completed value of this deferred */ complete = function(completed) { var listener, i = 0; // Replace _then with one that directly notifies with the result. _then = completed.then; // Replace complete so that this Deferred can only be completed // once. Also Replace _progress, so that subsequent attempts to issue // progress throw. complete = _progress = function alreadyCompleted() { // TODO: Consider silently returning here so that parties who // have a reference to the resolver cannot tell that the promise // has been resolved using try/catch throw new Error("already completed"); }; // Free progressHandlers array since we'll never issue progress events // for this promise again now that it's completed progressHandlers = undef; // Notify listeners // Traverse all listeners registered directly with this Deferred while (listener = listeners[i++]) { listener(completed); } listeners = []; }; /** * The full Deferred object, with both {@link Promise} and {@link Resolver} * parts * @class Deferred * @name Deferred */ deferred = {}; // Promise and Resolver parts // Freeze Promise and Resolver APIs promise = new Promise(); promise.then = deferred.then = then; /** * The {@link Promise} for this {@link Deferred} * @memberOf Deferred * @name promise * @type {Promise} */ deferred.promise = freeze(promise); /** * The {@link Resolver} for this {@link Deferred} * @memberOf Deferred * @name resolver * @class Resolver */ deferred.resolver = freeze({ resolve: (deferred.resolve = resolve), reject: (deferred.reject = reject), progress: (deferred.progress = progress) }); return deferred; } /** * Determines if promiseOrValue is a promise or not. Uses the feature * test from http://wiki.commonjs.org/wiki/Promises/A to determine if * promiseOrValue is a promise. * * @param promiseOrValue anything * * @returns {Boolean} true if promiseOrValue is a {@link Promise} */ function isPromise(promiseOrValue) { return promiseOrValue && typeof promiseOrValue.then === 'function'; } /** * Register an observer for a promise or immediate value. * * @function * @name when * @namespace * * @param promiseOrValue anything * @param {Function} [callback] callback to be called when promiseOrValue is * successfully resolved. If promiseOrValue is an immediate value, callback * will be invoked immediately. * @param {Function} [errback] callback to be called when promiseOrValue is * rejected. * @param {Function} [progressHandler] callback to be called when progress updates * are issued for promiseOrValue. * * @returns {Promise} a new {@link Promise} that will complete with the return * value of callback or errback or the completion value of promiseOrValue if * callback and/or errback is not supplied. */ function when(promiseOrValue, callback, errback, progressHandler) { // Get a promise for the input promiseOrValue // See promise() var trustedPromise = promise(promiseOrValue); // Register promise handlers return trustedPromise.then(callback, errback, progressHandler); } /** * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if * promiseOrValue is a foreign promise, or a new, already-resolved {@link Promise} * whose resolution value is promiseOrValue if promiseOrValue is an immediate value. * * Note that this function is not safe to export since it will return its * input when promiseOrValue is a {@link Promise} * * @private * * @param promiseOrValue anything * * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise} * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise} * whose resolution value is: * * the resolution value of promiseOrValue if it's a foreign promise, or * * promiseOrValue if it's a value */ function promise(promiseOrValue) { var promise, deferred; if(promiseOrValue instanceof Promise) { // It's a when.js promise, so we trust it promise = promiseOrValue; } else { // It's not a when.js promise. Check to see if it's a foreign promise // or a value. deferred = defer(); if(isPromise(promiseOrValue)) { // It's a compliant promise, but we don't know where it came from, // so we don't trust its implementation entirely. Introduce a trusted // middleman when.js promise // IMPORTANT: This is the only place when.js should ever call .then() on // an untrusted promise. promiseOrValue.then(deferred.resolve, deferred.reject, deferred.progress); promise = deferred.promise; } else { // It's a value, not a promise. Create an already-resolved promise // for it. deferred.resolve(promiseOrValue); promise = deferred.promise; } } return promise; } /** * Return a promise that will resolve when howMany of the supplied promisesOrValues * have resolved. The resolution value of the returned promise will be an array of * length howMany containing the resolutions values of the triggering promisesOrValues. * * @memberOf when * * @param promisesOrValues {Array} array of anything, may contain a mix * of {@link Promise}s and values * @param howMany * @param [callback] * @param [errback] * @param [progressHandler] * * @returns {Promise} */ function some(promisesOrValues, howMany, callback, errback, progressHandler) { checkCallbacks(2, arguments); return when(promisesOrValues, function(promisesOrValues) { var toResolve, results, ret, deferred, resolver, rejecter, handleProgress, len, i; len = promisesOrValues.length >>> 0; toResolve = Math.max(0, Math.min(howMany, len)); results = []; deferred = defer(); ret = when(deferred, callback, errback, progressHandler); // Wrapper so that resolver can be replaced function resolve(val) { resolver(val); } // Wrapper so that rejecter can be replaced function reject(err) { rejecter(err); } // Wrapper so that progress can be replaced function progress(update) { handleProgress(update); } function complete() { resolver = rejecter = handleProgress = noop; } // No items in the input, resolve immediately if (!toResolve) { deferred.resolve(results); } else { // Resolver for promises. Captures the value and resolves // the returned promise when toResolve reaches zero. // Overwrites resolver var with a noop once promise has // be resolved to cover case where n < promises.length resolver = function(val) { // This orders the values based on promise resolution order // Another strategy would be to use the original position of // the corresponding promise. results.push(val); if (!--toResolve) { complete(); deferred.resolve(results); } }; // Rejecter for promises. Rejects returned promise // immediately, and overwrites rejecter var with a noop // once promise to cover case where n < promises.length. // TODO: Consider rejecting only when N (or promises.length - N?) // promises have been rejected instead of only one? rejecter = function(err) { complete(); deferred.reject(err); }; handleProgress = deferred.progress; // TODO: Replace while with forEach for(i = 0; i < len; ++i) { if(i in promisesOrValues) { when(promisesOrValues[i], resolve, reject, progress); } } } return ret; }); } /** * Return a promise that will resolve only once all the supplied promisesOrValues * have resolved. The resolution value of the returned promise will be an array * containing the resolution values of each of the promisesOrValues. * * @memberOf when * * @param promisesOrValues {Array|Promise} array of anything, may contain a mix * of {@link Promise}s and values * @param [callback] {Function} * @param [errback] {Function} * @param [progressHandler] {Function} * * @returns {Promise} */ function all(promisesOrValues, callback, errback, progressHandler) { checkCallbacks(1, arguments); return when(promisesOrValues, function(promisesOrValues) { return _reduce(promisesOrValues, reduceIntoArray, []); }).then(callback, errback, progressHandler); } function reduceIntoArray(current, val, i) { current[i] = val; return current; } /** * Return a promise that will resolve when any one of the supplied promisesOrValues * has resolved. The resolution value of the returned promise will be the resolution * value of the triggering promiseOrValue. * * @memberOf when * * @param promisesOrValues {Array|Promise} array of anything, may contain a mix * of {@link Promise}s and values * @param [callback] {Function} * @param [errback] {Function} * @param [progressHandler] {Function} * * @returns {Promise} */ function any(promisesOrValues, callback, errback, progressHandler) { function unwrapSingleResult(val) { return callback ? callback(val[0]) : val[0]; } return some(promisesOrValues, 1, unwrapSingleResult, errback, progressHandler); } /** * Traditional map function, similar to `Array.prototype.map()`, but allows * input to contain {@link Promise}s and/or values, and mapFunc may return * either a value or a {@link Promise} * * @memberOf when * * @param promise {Array|Promise} array of anything, may contain a mix * of {@link Promise}s and values * @param mapFunc {Function} mapping function mapFunc(value) which may return * either a {@link Promise} or value * * @returns {Promise} a {@link Promise} that will resolve to an array containing * the mapped output values. */ function map(promise, mapFunc) { return when(promise, function(array) { return _map(array, mapFunc); }); } /** * Private map helper to map an array of promises * @private * * @param promisesOrValues {Array} * @param mapFunc {Function} * @return {Promise} */ function _map(promisesOrValues, mapFunc) { var results, len, i; // Since we know the resulting length, we can preallocate the results // array to avoid array expansions. len = promisesOrValues.length >>> 0; results = new Array(len); // Since mapFunc may be async, get all invocations of it into flight // asap, and then use reduce() to collect all the results for(i = 0; i < len; i++) { if(i in promisesOrValues) results[i] = when(promisesOrValues[i], mapFunc); } // Could use all() here, but that would result in another array // being allocated, i.e. map() would end up allocating 2 arrays // of size len instead of just 1. Since all() uses reduce() // anyway, avoid the additional allocation by calling reduce // directly. return _reduce(results, reduceIntoArray, results); } /** * Traditional reduce function, similar to `Array.prototype.reduce()`, but * input may contain {@link Promise}s and/or values, and reduceFunc * may return either a value or a {@link Promise}, *and* initialValue may * be a {@link Promise} for the starting value. * * @memberOf when * * @param promise {Array|Promise} array of anything, may contain a mix * of {@link Promise}s and values. May also be a {@link Promise} for * an array. * @param reduceFunc {Function} reduce function reduce(currentValue, nextValue, index, total), * where total is the total number of items being reduced, and will be the same * in each call to reduceFunc. * @param initialValue starting value, or a {@link Promise} for the starting value * * @returns {Promise} that will resolve to the final reduced value */ function reduce(promise, reduceFunc, initialValue) { var args = slice.call(arguments, 1); return when(promise, function(array) { return _reduce.apply(undef, [array].concat(args)); }); } /** * Private reduce to reduce an array of promises * @private * * @param promisesOrValues {Array} * @param reduceFunc {Function} * @param initialValue {*} * @return {Promise} */ function _reduce(promisesOrValues, reduceFunc, initialValue) { var total, args; total = promisesOrValues.length; // Skip promisesOrValues, since it will be used as 'this' in the call // to the actual reduce engine below. // Wrap the supplied reduceFunc with one that handles promises and then // delegates to the supplied. args = [ function (current, val, i) { return when(current, function (c) { return when(val, function (value) { return reduceFunc(c, value, i, total); }); }); } ]; if (arguments.length > 2) args.push(initialValue); return reduceArray.apply(promisesOrValues, args); } /** * Ensure that resolution of promiseOrValue will complete resolver with the completion * value of promiseOrValue, or instead with resolveValue if it is provided. * * @memberOf when * * @param promiseOrValue * @param resolver {Resolver} * @param [resolveValue] anything * * @returns {Promise} */ function chain(promiseOrValue, resolver, resolveValue) { var useResolveValue = arguments.length > 2; return when(promiseOrValue, function(val) { if(useResolveValue) val = resolveValue; resolver.resolve(val); return val; }, function(e) { resolver.reject(e); return rejected(e); }, resolver.progress ); } // // Utility functions // /** * Helper that checks arrayOfCallbacks to ensure that each element is either * a function, or null or undefined. * * @private * * @param arrayOfCallbacks {Array} array to check * @throws {Error} if any element of arrayOfCallbacks is something other than * a Functions, null, or undefined. */ function checkCallbacks(start, arrayOfCallbacks) { var arg, i = arrayOfCallbacks.length; while(i > start) { arg = arrayOfCallbacks[--i]; if (arg != null && typeof arg != 'function') throw new Error('callback is not a function'); } } /** * No-Op function used in method replacement * @private */ function noop() {} slice = [].slice; // ES5 reduce implementation if native not available // See: http://es5.github.com/#x15.4.4.21 as there are many // specifics and edge cases. reduceArray = [].reduce || function(reduceFunc /*, initialValue */) { // ES5 dictates that reduce.length === 1 // This implementation deviates from ES5 spec in the following ways: // 1. It does not check if reduceFunc is a Callable var arr, args, reduced, len, i; i = 0; arr = Object(this); len = arr.length >>> 0; args = arguments; // If no initialValue, use first item of array (we know length !== 0 here) // and adjust i to start at second item if(args.length <= 1) { // Skip to the first real element in the array for(;;) { if(i in arr) { reduced = arr[i++]; break; } // If we reached the end of the array without finding any real // elements, it's a TypeError if(++i >= len) { throw new TypeError(); } } } else { // If initialValue provided, use it reduced = args[1]; } // Do the actual reduce for(;i < len; ++i) { // Skip holes if(i in arr) reduced = reduceFunc(reduced, arr[i], i, arr); } return reduced; }; return when; }); })(typeof define == 'function' ? define : function (factory) { typeof module != 'undefined' ? (module.exports = factory()) : (this.when = factory()); } // Boilerplate for AMD, Node, and browser global ); /** * @license * Lo-Dash 1.2.0 <http://lodash.com/> * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.4.4 <http://underscorejs.org/> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. * Available under MIT license <http://lodash.com/license> */ ;(function(window) { /** Used as a safe reference for `undefined` in pre ES5 environments */ var undefined; /** Detect free variable `exports` */ var freeExports = typeof exports == 'object' && exports; /** Detect free variable `module` */ var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; /** Detect free variable `global`, from Node.js or Browserified code, and use it as `window` */ var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { window = freeGlobal; } /** Used to generate unique IDs */ var idCounter = 0; /** Used internally to indicate various things */ var indicatorObject = {}; /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ var keyPrefix = +new Date + ''; /** Used as the size when optimizations are enabled for large arrays */ var largeArraySize = 200; /** Used to match empty string literals in compiled template source */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g; /** * Used to match ES6 template delimiters * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6 */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match regexp flags from their coerced string values */ var reFlags = /\w*$/; /** Used to match "interpolate" template delimiters */ var reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match leading zeros to be removed */ var reLeadingZeros = /^0+(?=.$)/; /** Used to ensure capturing order of template delimiters */ var reNoMatch = /($^)/; /** Used to match HTML characters */ var reUnescapedHtml = /[&<>"']/g; /** Used to match unescaped characters in compiled string literals */ var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; /** Used to assign default `context` object properties */ var contextProps = [ 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', 'parseInt', 'setImmediate', 'setTimeout' ]; /** Used to fix the JScript [[DontEnum]] bug */ var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used to make template sourceURLs easier to identify */ var templateCounter = 0; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; /** Used to identify object classifications that `_.clone` supports */ var cloneableClasses = {}; cloneableClasses[funcClass] = false; cloneableClasses[argsClass] = cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] = cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** Used to escape characters for inclusion in compiled string literals */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; /*--------------------------------------------------------------------------*/ /** * Create a new `lodash` function using the given `context` object. * * @static * @memberOf _ * @category Utilities * @param {Object} [context=window] The context object. * @returns {Function} Returns the `lodash` function. */ function runInContext(context) { // Avoid issues with some ES3 environments that attempt to use values, named // after built-in constructors like `Object`, for the creation of literals. // ES5 clears this up by stating that literals must use built-in constructors. // See http://es5.github.com/#x11.1.5. context = context ? _.defaults(window.Object(), context, _.pick(window, contextProps)) : window; /** Native constructor references */ var Array = context.Array, Boolean = context.Boolean, Date = context.Date, Function = context.Function, Math = context.Math, Number = context.Number, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for `Array` and `Object` method references */ var arrayRef = Array(), objectRef = Object(); /** Used to restore the original `_` reference in `noConflict` */ var oldDash = context._; /** Used to detect if a method is native */ var reNative = RegExp('^' + String(objectRef.valueOf) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/valueOf|for [^\]]+/g, '.+?') + '$' ); /** Native method shortcuts */ var ceil = Math.ceil, clearTimeout = context.clearTimeout, concat = arrayRef.concat, floor = Math.floor, getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, hasOwnProperty = objectRef.hasOwnProperty, push = arrayRef.push, setImmediate = context.setImmediate, setTimeout = context.setTimeout, toString = objectRef.toString; /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind, nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray, nativeIsFinite = context.isFinite, nativeIsNaN = context.isNaN, nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys, nativeMax = Math.max, nativeMin = Math.min, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeSlice = arrayRef.slice; /** Detect various environments */ var isIeOpera = reNative.test(context.attachEvent), isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera); /** Used to lookup a built-in constructor by [[Class]] */ var ctorByClass = {}; ctorByClass[arrayClass] = Array; ctorByClass[boolClass] = Boolean; ctorByClass[dateClass] = Date; ctorByClass[objectClass] = Object; ctorByClass[numberClass] = Number; ctorByClass[regexpClass] = RegExp; ctorByClass[stringClass] = String; /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object, which wraps the given `value`, to enable method * chaining. * * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, * and `unshift` * * Chaining is supported in custom builds as long as the `value` method is * implicitly or explicitly included in the build. * * The chainable wrapper functions are: * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, * `compose`, `concat`, `countBy`, `createCallback`, `debounce`, `defaults`, * `defer`, `delay`, `difference`, `filter`, `flatten`, `forEach`, `forIn`, * `forOwn`, `functions`, `groupBy`, `initial`, `intersection`, `invert`, * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `push`, `range`, * `reject`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`, * `tap`, `throttle`, `times`, `toArray`, `union`, `uniq`, `unshift`, `unzip`, * `values`, `where`, `without`, `wrap`, and `zip` * * The non-chainable wrapper functions are: * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `has`, * `identity`, `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, * `isElement`, `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, * `isNull`, `isNumber`, `isObject`, `isPlainObject`, `isRegExp`, `isString`, * `isUndefined`, `join`, `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, * `pop`, `random`, `reduce`, `reduceRight`, `result`, `shift`, `size`, `some`, * `sortedIndex`, `runInContext`, `template`, `unescape`, `uniqueId`, and `value` * * The wrapper functions `first` and `last` return wrapped values when `n` is * passed, otherwise they return unwrapped values. * * @name _ * @constructor * @category Chaining * @param {Mixed} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(sum, num) { * return sum + num; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(num) { * return num * num; * }); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) ? value : new lodashWrapper(value); } /** * An object used to flag environments features. * * @static * @memberOf _ * @type Object */ var support = lodash.support = {}; (function() { var ctor = function() { this.x = 1; }, object = { '0': 1, 'length': 1 }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var prop in new ctor) { props.push(prop); } for (prop in arguments) { } /** * Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5). * * @memberOf _.support * @type Boolean */ support.argsObject = arguments.constructor == Object && !(arguments instanceof Array); /** * Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9). * * @memberOf _.support * @type Boolean */ support.argsClass = isArguments(arguments); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly sets a function's `prototype` property [[Enumerable]] * value to `true`. * * @memberOf _.support * @type Boolean */ support.enumPrototypes = ctor.propertyIsEnumerable('prototype'); /** * Detect if `Function#bind` exists and is inferred to be fast (all but V8). * * @memberOf _.support * @type Boolean */ support.fastBind = nativeBind && !isV8; /** * Detect if own properties are iterated after inherited properties (all but IE < 9). * * @memberOf _.support * @type Boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `arguments` object indexes are non-enumerable * (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1). * * @memberOf _.support * @type Boolean */ support.nonEnumArgs = prop != 0; /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an objects own properties, shadowing non-enumerable ones, are * made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug). * * @memberOf _.support * @type Boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if `Array#shift` and `Array#splice` augment array-like objects correctly. * * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` * and `splice()` functions that fail to remove the last element, `value[0]`, * of array-like objects even though the `length` property is set to `0`. * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. * * @memberOf _.support * @type Boolean */ support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index and IE 8 can only access * characters by index on string literals. * * @memberOf _.support * @type Boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; /** * Detect if a DOM node's [[Class]] is resolvable (all but IE < 9) * and that the JS engine errors when attempting to coerce an object to * a string without a `toString` function. * * @memberOf _.support * @type Boolean */ try { support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { support.nodeClass = true; } }(1)); /** * By default, the template delimiters used by Lo-Dash are similar to those in * embedded Ruby (ERB). Change the following template settings to use alternative * delimiters. * * @static * @memberOf _ * @type Object */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type RegExp */ 'escape': /<%-([\s\S]+?)%>/g, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type RegExp */ 'evaluate': /<%([\s\S]+?)%>/g, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type RegExp */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type String */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type Object */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type Function */ '_': lodash } }; /*--------------------------------------------------------------------------*/ /** * The template used to create iterator functions. * * @private * @param {Object} data The data object used to populate the text. * @returns {String} Returns the interpolated text. */ var iteratorTemplate = template( // the `iterable` may be reassigned by the `top` snippet 'var index, iterable = <%= firstArg %>, ' + // assign the `result` variable an initial value 'result = <%= init %>;\n' + // exit early if the first argument is falsey 'if (!iterable) return result;\n' + // add code before the iteration branches '<%= top %>;\n' + // array-like iteration: '<% if (arrays) { %>' + 'var length = iterable.length; index = -1;\n' + 'if (<%= arrays %>) {' + // add support for accessing string characters by index if needed ' <% if (support.unindexedChars) { %>\n' + ' if (isString(iterable)) {\n' + " iterable = iterable.split('')\n" + ' }' + ' <% } %>\n' + // iterate over the array-like value ' while (++index < length) {\n' + ' <%= loop %>\n' + ' }\n' + '}\n' + 'else {' + // object iteration: // add support for iterating over `arguments` objects if needed ' <% } else if (support.nonEnumArgs) { %>\n' + ' var length = iterable.length; index = -1;\n' + ' if (length && isArguments(iterable)) {\n' + ' while (++index < length) {\n' + " index += '';\n" + ' <%= loop %>\n' + ' }\n' + ' } else {' + ' <% } %>' + // avoid iterating over `prototype` properties in older Firefox, Opera, and Safari ' <% if (support.enumPrototypes) { %>\n' + " var skipProto = typeof iterable == 'function';\n" + ' <% } %>' + // iterate own properties using `Object.keys` if it's fast ' <% if (useHas && useKeys) { %>\n' + ' var ownIndex = -1,\n' + ' ownProps = objectTypes[typeof iterable] ? keys(iterable) : [],\n' + ' length = ownProps.length;\n\n' + ' while (++ownIndex < length) {\n' + ' index = ownProps[ownIndex];\n' + " <% if (support.enumPrototypes) { %>if (!(skipProto && index == 'prototype')) {\n <% } %>" + ' <%= loop %>\n' + ' <% if (support.enumPrototypes) { %>}\n<% } %>' + ' }' + // else using a for-in loop ' <% } else { %>\n' + ' for (index in iterable) {<%' + ' if (support.enumPrototypes || useHas) { %>\n if (<%' + " if (support.enumPrototypes) { %>!(skipProto && index == 'prototype')<% }" + ' if (support.enumPrototypes && useHas) { %> && <% }' + ' if (useHas) { %>hasOwnProperty.call(iterable, index)<% }' + ' %>) {' + ' <% } %>\n' + ' <%= loop %>;' + ' <% if (support.enumPrototypes || useHas) { %>\n }<% } %>\n' + ' }' + // Because IE < 9 can't set the `[[Enumerable]]` attribute of an // existing property and the `constructor` property of a prototype // defaults to non-enumerable, Lo-Dash skips the `constructor` // property when it infers it's iterating over a `prototype` object. ' <% if (support.nonEnumShadows) { %>\n\n' + ' var ctor = iterable.constructor;\n' + ' <% for (var k = 0; k < 7; k++) { %>\n' + " index = '<%= shadowedProps[k] %>';\n" + ' if (<%' + " if (shadowedProps[k] == 'constructor') {" + ' %>!(ctor && ctor.prototype === iterable) && <%' + ' } %>hasOwnProperty.call(iterable, index)) {\n' + ' <%= loop %>\n' + ' }' + ' <% } %>' + ' <% } %>' + ' <% } %>' + ' <% if (arrays || support.nonEnumArgs) { %>\n}<% } %>\n' + // add code to the bottom of the iteration function '<%= bottom %>;\n' + // finally, return the `result` 'return result' ); /** Reusable iterator options for `assign` and `defaults` */ var defaultsIteratorOptions = { 'args': 'object, source, guard', 'top': 'var args = arguments,\n' + ' argsIndex = 0,\n' + " argsLength = typeof guard == 'number' ? 2 : args.length;\n" + 'while (++argsIndex < argsLength) {\n' + ' iterable = args[argsIndex];\n' + ' if (iterable && objectTypes[typeof iterable]) {', 'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]", 'bottom': ' }\n}' }; /** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */ var eachIteratorOptions = { 'args': 'collection, callback, thisArg', 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : lodash.createCallback(callback, thisArg)", 'arrays': "typeof length == 'number'", 'loop': 'if (callback(iterable[index], index, collection) === false) return result' }; /** Reusable iterator options for `forIn` and `forOwn` */ var forOwnIteratorOptions = { 'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top, 'arrays': false }; /*--------------------------------------------------------------------------*/ /** * Creates a function optimized to search large arrays for a given `value`, * starting at `fromIndex`, using strict equality for comparisons, i.e. `===`. * * @private * @param {Array} array The array to search. * @param {Mixed} value The value to search for. * @returns {Boolean} Returns `true`, if `value` is found, else `false`. */ function cachedContains(array) { var length = array.length, isLarge = length >= largeArraySize; if (isLarge) { var cache = {}, index = -1; while (++index < length) { var key = keyPrefix + array[index]; (cache[key] || (cache[key] = [])).push(array[index]); } } return function(value) { if (isLarge) { var key = keyPrefix + value; return cache[key] && indexOf(cache[key], value) > -1; } return indexOf(array, value) > -1; } } /** * Used by `_.max` and `_.min` as the default `callback` when a given * `collection` is a string value. * * @private * @param {String} value The character to inspect. * @returns {Number} Returns the code unit of given character. */ function charAtCallback(value) { return value.charCodeAt(0); } /** * Used by `sortBy` to compare transformed `collection` values, stable sorting * them in ascending order. * * @private * @param {Object} a The object to compare to `b`. * @param {Object} b The object to compare to `a`. * @returns {Number} Returns the sort order indicator of `1` or `-1`. */ function compareAscending(a, b) { var ai = a.index, bi = b.index; a = a.criteria; b = b.criteria; // ensure a stable sort in V8 and other engines // http://code.google.com/p/v8/issues/detail?id=90 if (a !== b) { if (a > b || typeof a == 'undefined') { return 1; } if (a < b || typeof b == 'undefined') { return -1; } } return ai < bi ? -1 : 1; } /** * Creates a function that, when called, invokes `func` with the `this` binding * of `thisArg` and prepends any `partialArgs` to the arguments passed to the * bound function. * * @private * @param {Function|String} func The function to bind or the method name. * @param {Mixed} [thisArg] The `this` binding of `func`. * @param {Array} partialArgs An array of arguments to be partially applied. * @param {Object} [idicator] Used to indicate binding by key or partially * applying arguments from the right. * @returns {Function} Returns the new bound function. */ function createBound(func, thisArg, partialArgs, indicator) { var isFunc = isFunction(func), isPartial = !partialArgs, key = thisArg; // juggle arguments if (isPartial) { var rightIndicator = indicator; partialArgs = thisArg; } else if (!isFunc) { if (!indicator) { throw new TypeError; } thisArg = func; } function bound() { // `Function#bind` spec // http://es5.github.com/#x15.3.4.5 var args = arguments, thisBinding = isPartial ? this : thisArg; if (!isFunc) { func = thisArg[key]; } if (partialArgs.length) { args = args.length ? (args = nativeSlice.call(args), rightIndicator ? args.concat(partialArgs) : partialArgs.concat(args)) : partialArgs; } if (this instanceof bound) { // ensure `new bound` is an instance of `func` noop.prototype = func.prototype; thisBinding = new noop; noop.prototype = null; // mimic the constructor's `return` behavior // http://es5.github.com/#x13.2.2 var result = func.apply(thisBinding, args); return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); } return bound; } /** * Creates compiled iteration functions. * * @private * @param {Object} [options1, options2, ...] The compile options object(s). * arrays - A string of code to determine if the iterable is an array or array-like. * useHas - A boolean to specify using `hasOwnProperty` checks in the object loop. * useKeys - A boolean to specify using `_.keys` for own property iteration. * args - A string of comma separated arguments the iteration function will accept. * top - A string of code to execute before the iteration branches. * loop - A string of code to execute in the object loop. * bottom - A string of code to execute after the iteration branches. * @returns {Function} Returns the compiled function. */ function createIterator() { var data = { // data properties 'shadowedProps': shadowedProps, 'support': support, // iterator options 'arrays': 'isArray(iterable)', 'bottom': '', 'init': 'iterable', 'loop': '', 'top': '', 'useHas': true, 'useKeys': !!keys }; // merge options into a template data object for (var object, index = 0; object = arguments[index]; index++) { for (var key in object) { data[key] = object[key]; } } var args = data.args; data.firstArg = /^[^,]+/.exec(args)[0]; // create the function factory var factory = Function( 'hasOwnProperty, isArguments, isArray, isString, keys, ' + 'lodash, objectTypes', 'return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}' ); // return the compiled function return factory( hasOwnProperty, isArguments, isArray, isString, keys, lodash, objectTypes ); } /** * Used by `template` to escape characters for inclusion in compiled * string literals. * * @private * @param {String} match The matched character to escape. * @returns {String} Returns the escaped character. */ function escapeStringChar(match) { return '\\' + stringEscapes[match]; } /** * Used by `escape` to convert characters to HTML entities. * * @private * @param {String} match The matched character to escape. * @returns {String} Returns the escaped character. */ function escapeHtmlChar(match) { return htmlEscapes[match]; } /** * Checks if `value` is a DOM node in IE < 9. * * @private * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true` if the `value` is a DOM node, else `false`. */ function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } /** * A fast path for creating `lodash` wrapper objects. * * @private * @param {Mixed} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. */ function lodashWrapper(value) { this.__wrapped__ = value; } // ensure `new lodashWrapper` is an instance of `lodash` lodashWrapper.prototype = lodash.prototype; /** * A no-operation function. * * @private */ function noop() { // no operation performed } /** * A fallback implementation of `isPlainObject` which checks if a given `value` * is an object created by the `Object` constructor, assuming objects created * by the `Object` constructor have no inherited enumerable properties and that * there are no `Object.prototype` extensions. * * @private * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { // avoid non-objects and false positives for `arguments` objects var result = false; if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { return result; } // check that the constructor is `Object` (i.e. `Object instanceof Object`) var ctor = value.constructor; if (isFunction(ctor) ? ctor instanceof ctor : (support.nodeClass || !isNode(value))) { // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. if (support.ownLast) { forIn(value, function(value, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result === true; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. forIn(value, function(value, key) { result = key; }); return result === false || hasOwnProperty.call(value, result); } return result; } /** * Slices the `collection` from the `start` index up to, but not including, * the `end` index. * * Note: This function is used, instead of `Array#slice`, to support node lists * in IE < 9 and to ensure dense arrays are returned. * * @private * @param {Array|Object|String} collection The collection to slice. * @param {Number} start The start index. * @param {Number} end The end index. * @returns {Array} Returns the new array. */ function slice(array, start, end) { start || (start = 0); if (typeof end == 'undefined') { end = array ? array.length : 0; } var index = -1, length = end - start || 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = array[start + index]; } return result; } /** * Used by `unescape` to convert HTML entities to characters. * * @private * @param {String} match The matched character to unescape. * @returns {String} Returns the unescaped character. */ function unescapeHtmlChar(match) { return htmlUnescapes[match]; } /*--------------------------------------------------------------------------*/ /** * Checks if `value` is an `arguments` object. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is an `arguments` object, else `false`. * @example * * (function() { return _.isArguments(arguments); })(1, 2, 3); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return toString.call(value) == argsClass; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!support.argsClass) { isArguments = function(value) { return value ? hasOwnProperty.call(value, 'callee') : false; }; } /** * A fallback implementation of `Object.keys` which produces an array of the * given object's own enumerable property names. * * @private * @type Function * @param {Object} object The object to inspect. * @returns {Array} Returns a new array of property names. */ var shimKeys = createIterator({ 'args': 'object', 'init': '[]', 'top': 'if (!(objectTypes[typeof object])) return result', 'loop': 'result.push(index)', 'arrays': false }); /** * Creates an array composed of the own enumerable property names of `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns a new array of property names. * @example * * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); * // => ['one', 'two', 'three'] (order is not guaranteed) */ var keys = !nativeKeys ? shimKeys : function(object) { if (!isObject(object)) { return []; } if ((support.enumPrototypes && typeof object == 'function') || (support.nonEnumArgs && object.length && isArguments(object))) { return shimKeys(object); } return nativeKeys(object); }; /** * A function compiled to iterate `arguments` objects, arrays, objects, and * strings consistenly across environments, executing the `callback` for each * element in the `collection`. The `callback` is bound to `thisArg` and invoked * with three arguments; (value, index|key, collection). Callbacks may exit * iteration early by explicitly returning `false`. * * @private * @type Function * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|String} Returns `collection`. */ var each = createIterator(eachIteratorOptions); /** * Used to convert characters to HTML entities: * * Though the `>` character is escaped for symmetry, characters like `>` and `/` * don't require escaping in HTML and have no special meaning unless they're part * of a tag or an unquoted attribute value. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to convert HTML entities to characters */ var htmlUnescapes = invert(htmlEscapes); /*--------------------------------------------------------------------------*/ /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources will overwrite property assignments of previous * sources. If a `callback` function is passed, it will be executed to produce * the assigned values. The `callback` is bound to `thisArg` and invoked with * two arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @type Function * @alias extend * @category Objects * @param {Object} object The destination object. * @param {Object} [source1, source2, ...] The source objects. * @param {Function} [callback] The function to customize assigning values. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * _.assign({ 'name': 'moe' }, { 'age': 40 }); * // => { 'name': 'moe', 'age': 40 } * * var defaults = _.partialRight(_.assign, function(a, b) { * return typeof a == 'undefined' ? b : a; * }); * * var food = { 'name': 'apple' }; * defaults(food, { 'name': 'banana', 'type': 'fruit' }); * // => { 'name': 'apple', 'type': 'fruit' } */ var assign = createIterator(defaultsIteratorOptions, { 'top': defaultsIteratorOptions.top.replace(';', ';\n' + "if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" + ' var callback = lodash.createCallback(args[--argsLength - 1], args[argsLength--], 2);\n' + "} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" + ' callback = args[--argsLength];\n' + '}' ), 'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]' }); /** * Creates a clone of `value`. If `deep` is `true`, nested objects will also * be cloned, otherwise they will be assigned by reference. If a `callback` * function is passed, it will be executed to produce the cloned values. If * `callback` returns `undefined`, cloning will be handled by the method instead. * The `callback` is bound to `thisArg` and invoked with one argument; (value). * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to clone. * @param {Boolean} [deep=false] A flag to indicate a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @param- {Array} [stackA=[]] Tracks traversed source objects. * @param- {Array} [stackB=[]] Associates clones with source counterparts. * @returns {Mixed} Returns the cloned `value`. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * var shallow = _.clone(stooges); * shallow[0] === stooges[0]; * // => true * * var deep = _.clone(stooges, true); * deep[0] === stooges[0]; * // => false * * _.mixin({ * 'clone': _.partialRight(_.clone, function(value) { * return _.isElement(value) ? value.cloneNode(false) : undefined; * }) * }); * * var clone = _.clone(document.body); * clone.childNodes.length; * // => 0 */ function clone(value, deep, callback, thisArg, stackA, stackB) { var result = value; // allows working with "Collections" methods without using their `callback` // argument, `index|key`, for this method's `callback` if (typeof deep == 'function') { thisArg = callback; callback = deep; deep = false; } if (typeof callback == 'function') { callback = (typeof thisArg == 'undefined') ? callback : lodash.createCallback(callback, thisArg, 1); result = callback(result); if (typeof result != 'undefined') { return result; } result = value; } // inspect [[Class]] var isObj = isObject(result); if (isObj) { var className = toString.call(result); if (!cloneableClasses[className] || (!support.nodeClass && isNode(result))) { return result; } var isArr = isArray(result); } // shallow clone if (!isObj || !deep) { return isObj ? (isArr ? slice(result) : assign({}, result)) : result; } var ctor = ctorByClass[className]; switch (className) { case boolClass: case dateClass: return new ctor(+result); case numberClass: case stringClass: return new ctor(result); case regexpClass: return ctor(result.source, reFlags.exec(result)); } // check for circular references and return corresponding clone stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } // init cloned object result = isArr ? ctor(result.length) : {}; // add array properties assigned by `RegExp#exec` if (isArr) { if (hasOwnProperty.call(value, 'index')) { result.index = value.index; } if (hasOwnProperty.call(value, 'input')) { result.input = value.input; } } // add the source value to the stack of traversed objects // and associate it with its clone stackA.push(value); stackB.push(result); // recursively populate clone (susceptible to call stack limits) (isArr ? forEach : forOwn)(value, function(objValue, key) { result[key] = clone(objValue, deep, callback, undefined, stackA, stackB); }); return result; } /** * Creates a deep clone of `value`. If a `callback` function is passed, * it will be executed to produce the cloned values. If `callback` returns * `undefined`, cloning will be handled by the method instead. The `callback` * is bound to `thisArg` and invoked with one argument; (value). * * Note: This function is loosely based on the structured clone algorithm. Functions * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and * objects created by constructors other than `Object` are cloned to plain `Object` objects. * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the deep cloned `value`. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * var deep = _.cloneDeep(stooges); * deep[0] === stooges[0]; * // => false * * var view = { * 'label': 'docs', * 'node': element * }; * * var clone = _.cloneDeep(view, function(value) { * return _.isElement(value) ? value.cloneNode(true) : undefined; * }); * * clone.node == view.node; * // => false */ function cloneDeep(value, callback, thisArg) { return clone(value, true, callback, thisArg); } /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional defaults of the same property will be ignored. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The destination object. * @param {Object} [source1, source2, ...] The source objects. * @param- {Object} [guard] Allows working with `_.reduce` without using its * callback's `key` and `object` arguments as sources. * @returns {Object} Returns the destination object. * @example * * var food = { 'name': 'apple' }; * _.defaults(food, { 'name': 'banana', 'type': 'fruit' }); * // => { 'name': 'apple', 'type': 'fruit' } */ var defaults = createIterator(defaultsIteratorOptions); /** * This method is similar to `_.find`, except that it returns the key of the * element that passes the callback check, instead of the element itself. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to search. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the key of the found element, else `undefined`. * @example * * _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) { * return num % 2 == 0; * }); * // => 'b' */ function findKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg); forOwn(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; } /** * Iterates over `object`'s own and inherited enumerable properties, executing * the `callback` for each property. The `callback` is bound to `thisArg` and * invoked with three arguments; (value, key, object). Callbacks may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Dog(name) { * this.name = name; * } * * Dog.prototype.bark = function() { * alert('Woof, woof!'); * }; * * _.forIn(new Dog('Dagny'), function(value, key) { * alert(key); * }); * // => alerts 'name' and 'bark' (order is not guaranteed) */ var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, { 'useHas': false }); /** * Iterates over an object's own enumerable properties, executing the `callback` * for each property. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, key, object). Callbacks may exit iteration early by explicitly * returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * alert(key); * }); * // => alerts '0', '1', and 'length' (order is not guaranteed) */ var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions); /** * Creates a sorted array of all enumerable properties, own and inherited, * of `object` that have function values. * * @static * @memberOf _ * @alias methods * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns a new array of property names that have function values. * @example * * _.functions(_); * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] */ function functions(object) { var result = []; forIn(object, function(value, key) { if (isFunction(value)) { result.push(key); } }); return result.sort(); } /** * Checks if the specified object `property` exists and is a direct property, * instead of an inherited property. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to check. * @param {String} property The property to check for. * @returns {Boolean} Returns `true` if key is a direct property, else `false`. * @example * * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); * // => true */ function has(object, property) { return object ? hasOwnProperty.call(object, property) : false; } /** * Creates an object composed of the inverted keys and values of the given `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to invert. * @returns {Object} Returns the created inverted object. * @example * * _.invert({ 'first': 'moe', 'second': 'larry' }); * // => { 'moe': 'first', 'larry': 'second' } */ function invert(object) { var index = -1, props = keys(object), length = props.length, result = {}; while (++index < length) { var key = props[index]; result[object[key]] = key; } return result; } /** * Checks if `value` is an array. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is an array, else `false`. * @example * * (function() { return _.isArray(arguments); })(); * // => false * * _.isArray([1, 2, 3]); * // => true */ function isArray(value) { // `instanceof` may cause a memory leak in IE 7 if `value` is a host object // http://ajaxian.com/archives/working-aroung-the-instanceof-memory-leak return (support.argsObject && value instanceof Array) || (nativeIsArray ? nativeIsArray(value) : toString.call(value) == arrayClass); } /** * Checks if `value` is a boolean value. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a boolean value, else `false`. * @example * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || toString.call(value) == boolClass; } /** * Checks if `value` is a date. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a date, else `false`. * @example * * _.isDate(new Date); * // => true */ function isDate(value) { return value instanceof Date || toString.call(value) == dateClass; } /** * Checks if `value` is a DOM element. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true */ function isElement(value) { return value ? value.nodeType === 1 : false; } /** * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a * length of `0` and objects with no own enumerable properties are considered * "empty". * * @static * @memberOf _ * @category Objects * @param {Array|Object|String} value The value to inspect. * @returns {Boolean} Returns `true`, if the `value` is empty, else `false`. * @example * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({}); * // => true * * _.isEmpty(''); * // => true */ function isEmpty(value) { var result = true; if (!value) { return result; } var className = toString.call(value), length = value.length; if ((className == arrayClass || className == stringClass || (support.argsClass ? className == argsClass : isArguments(value))) || (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { return !length; } forOwn(value, function() { return (result = false); }); return result; } /** * Performs a deep comparison between two values to determine if they are * equivalent to each other. If `callback` is passed, it will be executed to * compare values. If `callback` returns `undefined`, comparisons will be handled * by the method instead. The `callback` is bound to `thisArg` and invoked with * two arguments; (a, b). * * @static * @memberOf _ * @category Objects * @param {Mixed} a The value to compare. * @param {Mixed} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @param- {Array} [stackA=[]] Tracks traversed `a` objects. * @param- {Array} [stackB=[]] Tracks traversed `b` objects. * @returns {Boolean} Returns `true`, if the values are equivalent, else `false`. * @example * * var moe = { 'name': 'moe', 'age': 40 }; * var copy = { 'name': 'moe', 'age': 40 }; * * moe == copy; * // => false * * _.isEqual(moe, copy); * // => true * * var words = ['hello', 'goodbye']; * var otherWords = ['hi', 'goodbye']; * * _.isEqual(words, otherWords, function(a, b) { * var reGreet = /^(?:hello|hi)$/i, * aGreet = _.isString(a) && reGreet.test(a), * bGreet = _.isString(b) && reGreet.test(b); * * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; * }); * // => true */ function isEqual(a, b, callback, thisArg, stackA, stackB) { // used to indicate that when comparing objects, `a` has at least the properties of `b` var whereIndicator = callback === indicatorObject; if (typeof callback == 'function' && !whereIndicator) { callback = lodash.createCallback(callback, thisArg, 2); var result = callback(a, b); if (typeof result != 'undefined') { return !!result; } } // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (!a || (type != 'function' && type != 'object')) && (!b || (otherType != 'function' && otherType != 'object'))) { return false; } // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior // http://es5.github.com/#x15.3.4.4 if (a == null || b == null) { return a === b; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `+0` vs. `-0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.com/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // unwrap any `lodash` wrapped values if (hasOwnProperty.call(a, '__wrapped__ ') || hasOwnProperty.call(b, '__wrapped__')) { return isEqual(a.__wrapped__ || a, b.__wrapped__ || b, callback, thisArg, stackA, stackB); } // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !( isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB )) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3) stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { length = a.length; size = b.length; // compare lengths to determine if a deep comparison is necessary result = size == a.length; if (!result && !whereIndicator) { return result; } // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (whereIndicator) { while (index--) { if ((result = isEqual(a[index], value, callback, thisArg, stackA, stackB))) { break; } } } else if (!(result = isEqual(a[size], value, callback, thisArg, stackA, stackB))) { break; } } return result; } // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly forIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && isEqual(a[key], value, callback, thisArg, stackA, stackB)); } }); if (result && !whereIndicator) { // ensure both objects have the same number of properties forIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } return result; } /** * Checks if `value` is, or can be coerced to, a finite number. * * Note: This is not the same as native `isFinite`, which will return true for * booleans and empty strings. See http://es5.github.com/#x15.1.2.5. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is finite, else `false`. * @example * * _.isFinite(-101); * // => true * * _.isFinite('10'); * // => true * * _.isFinite(true); * // => false * * _.isFinite(''); * // => false * * _.isFinite(Infinity); * // => false */ function isFinite(value) { return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); } /** * Checks if `value` is a function. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true */ function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return value instanceof Function || toString.call(value) == funcClass; }; } /** * Checks if `value` is the language type of Object. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.com/#x8 // and avoid a V8 bug // http://code.google.com/p/v8/issues/detail?id=2291 return value ? objectTypes[typeof value] : false; } /** * Checks if `value` is `NaN`. * * Note: This is not the same as native `isNaN`, which will return `true` for * `undefined` and other values. See http://es5.github.com/#x15.1.2.4. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // `NaN` as a primitive is the only value that is not equal to itself // (perform the [[Class]] check first to avoid errors with some host objects in IE) return isNumber(value) && value != +value } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(undefined); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is a number. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a number, else `false`. * @example * * _.isNumber(8.4 * 5); * // => true */ function isNumber(value) { return typeof value == 'number' || toString.call(value) == numberClass; } /** * Checks if a given `value` is an object created by the `Object` constructor. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`. * @example * * function Stooge(name, age) { * this.name = name; * this.age = age; * } * * _.isPlainObject(new Stooge('moe', 40)); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'name': 'moe', 'age': 40 }); * // => true */ var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { return false; } var valueOf = value.valueOf, objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; /** * Checks if `value` is a regular expression. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a regular expression, else `false`. * @example * * _.isRegExp(/moe/); * // => true */ function isRegExp(value) { return value instanceof RegExp || toString.call(value) == regexpClass; } /** * Checks if `value` is a string. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a string, else `false`. * @example * * _.isString('moe'); * // => true */ function isString(value) { return typeof value == 'string' || toString.call(value) == stringClass; } /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true */ function isUndefined(value) { return typeof value == 'undefined'; } /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined`, into the destination object. Subsequent sources * will overwrite property assignments of previous sources. If a `callback` function * is passed, it will be executed to produce the merged values of the destination * and source properties. If `callback` returns `undefined`, merging will be * handled by the method instead. The `callback` is bound to `thisArg` and * invoked with two arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @category Objects * @param {Object} object The destination object. * @param {Object} [source1, source2, ...] The source objects. * @param {Function} [callback] The function to customize merging properties. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @param- {Object} [deepIndicator] Indicates that `stackA` and `stackB` are * arrays of traversed objects, instead of source objects. * @param- {Array} [stackA=[]] Tracks traversed source objects. * @param- {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns the destination object. * @example * * var names = { * 'stooges': [ * { 'name': 'moe' }, * { 'name': 'larry' } * ] * }; * * var ages = { * 'stooges': [ * { 'age': 40 }, * { 'age': 50 } * ] * }; * * _.merge(names, ages); * // => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] } * * var food = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var otherFood = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(food, otherFood, function(a, b) { * return _.isArray(a) ? a.concat(b) : undefined; * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } */ function merge(object, source, deepIndicator) { var args = arguments, index = 0, length = 2; if (!isObject(object)) { return object; } if (deepIndicator === indicatorObject) { var callback = args[3], stackA = args[4], stackB = args[5]; } else { stackA = []; stackB = []; // allows working with `_.reduce` and `_.reduceRight` without // using their `callback` arguments, `index|key` and `collection` if (typeof deepIndicator != 'number') { length = args.length; } if (length > 3 && typeof args[length - 2] == 'function') { callback = lodash.createCallback(args[--length - 1], args[length--], 2); } else if (length > 2 && typeof args[length - 1] == 'function') { callback = args[--length]; } } while (++index < length) { (isArray(args[index]) ? forEach : forOwn)(args[index], function(source, key) { var found, isArr, result = source, value = object[key]; if (source && ((isArr = isArray(source)) || isPlainObject(source))) { // avoid merging previously merged cyclic sources var stackLength = stackA.length; while (stackLength--) { if ((found = stackA[stackLength] == source)) { value = stackB[stackLength]; break; } } if (!found) { var isShallow; if (callback) { result = callback(value, source); if ((isShallow = typeof result != 'undefined')) { value = result; } } if (!isShallow) { value = isArr ? (isArray(value) ? value : []) : (isPlainObject(value) ? value : {}); } // add `source` and associated `value` to the stack of traversed objects stackA.push(source); stackB.push(value); // recursively merge objects and arrays (susceptible to call stack limits) if (!isShallow) { value = merge(value, source, indicatorObject, callback, stackA, stackB); } } } else { if (callback) { result = callback(value, source); if (typeof result == 'undefined') { result = source; } } if (typeof result != 'undefined') { value = result; } } object[key] = value; }); } return object; } /** * Creates a shallow clone of `object` excluding the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a `callback` function is passed, it will be executed * for each property in the `object`, omitting the properties `callback` * returns truthy for. The `callback` is bound to `thisArg` and invoked * with three arguments; (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|String} callback|[prop1, prop2, ...] The properties to omit * or the function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object without the omitted properties. * @example * * _.omit({ 'name': 'moe', 'age': 40 }, 'age'); * // => { 'name': 'moe' } * * _.omit({ 'name': 'moe', 'age': 40 }, function(value) { * return typeof value == 'number'; * }); * // => { 'name': 'moe' } */ function omit(object, callback, thisArg) { var isFunc = typeof callback == 'function', result = {}; if (isFunc) { callback = lodash.createCallback(callback, thisArg); } else { var props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)); } forIn(object, function(value, key, object) { if (isFunc ? !callback(value, key, object) : indexOf(props, key) < 0 ) { result[key] = value; } }); return result; } /** * Creates a two dimensional array of the given object's key-value pairs, * i.e. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns new array of key-value pairs. * @example * * _.pairs({ 'moe': 30, 'larry': 40 }); * // => [['moe', 30], ['larry', 40]] (order is not guaranteed) */ function pairs(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } /** * Creates a shallow clone of `object` composed of the specified properties. * Property names may be specified as individual arguments or as arrays of property * names. If `callback` is passed, it will be executed for each property in the * `object`, picking the properties `callback` returns truthy for. The `callback` * is bound to `thisArg` and invoked with three arguments; (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Array|Function|String} callback|[prop1, prop2, ...] The function called * per iteration or properties to pick, either as individual arguments or arrays. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object composed of the picked properties. * @example * * _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name'); * // => { 'name': 'moe' } * * _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) { * return key.charAt(0) != '_'; * }); * // => { 'name': 'moe' } */ function pick(object, callback, thisArg) { var result = {}; if (typeof callback != 'function') { var index = -1, props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)), length = isObject(object) ? props.length : 0; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } } else { callback = lodash.createCallback(callback, thisArg); forIn(object, function(value, key, object) { if (callback(value, key, object)) { result[key] = value; } }); } return result; } /** * Creates an array composed of the own enumerable property values of `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns a new array of property values. * @example * * _.values({ 'one': 1, 'two': 2, 'three': 3 }); * // => [1, 2, 3] (order is not guaranteed) */ function values(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } /*--------------------------------------------------------------------------*/ /** * Creates an array of elements from the specified indexes, or keys, of the * `collection`. Indexes may be specified as individual arguments or as arrays * of indexes. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Array|Number|String} [index1, index2, ...] The indexes of * `collection` to retrieve, either as individual arguments or arrays. * @returns {Array} Returns a new array of elements corresponding to the * provided indexes. * @example * * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); * // => ['a', 'c', 'e'] * * _.at(['moe', 'larry', 'curly'], 0, 2); * // => ['moe', 'curly'] */ function at(collection) { var index = -1, props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)), length = props.length, result = Array(length); if (support.unindexedChars && isString(collection)) { collection = collection.split(''); } while(++index < length) { result[index] = collection[props[index]]; } return result; } /** * Checks if a given `target` element is present in a `collection` using strict * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used * as the offset from the end of the collection. * * @static * @memberOf _ * @alias include * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Mixed} target The value to check for. * @param {Number} [fromIndex=0] The index to search from. * @returns {Boolean} Returns `true` if the `target` element is found, else `false`. * @example * * _.contains([1, 2, 3], 1); * // => true * * _.contains([1, 2, 3], 1, 2); * // => false * * _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); * // => true * * _.contains('curly', 'ur'); * // => true */ function contains(collection, target, fromIndex) { var index = -1, length = collection ? collection.length : 0, result = false; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; if (typeof length == 'number') { result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex) ) > -1; } else { each(collection, function(value) { if (++index >= fromIndex) { return !(result = value === target); } }); } return result; } /** * Creates an object composed of keys returned from running each element of the * `collection` through the given `callback`. The corresponding value of each key * is the number of times the key was returned by the `callback`. The `callback` * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ function countBy(collection, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg); forEach(collection, function(value, key, collection) { key = String(callback(value, key, collection)); (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); }); return result; } /** * Checks if the `callback` returns a truthy value for **all** elements of a * `collection`. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias all * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Boolean} Returns `true` if all elements pass the callback check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // using "_.pluck" callback shorthand * _.every(stooges, 'age'); * // => true * * // using "_.where" callback shorthand * _.every(stooges, { 'age': 50 }); * // => false */ function every(collection, callback, thisArg) { var result = true; callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if (!(result = !!callback(collection[index], index, collection))) { break; } } } else { each(collection, function(value, index, collection) { return (result = !!callback(value, index, collection)); }); } return result; } /** * Examines each element in a `collection`, returning an array of all elements * the `callback` returns truthy for. The `callback` is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias select * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that passed the callback check. * @example * * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [2, 4, 6] * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.filter(food, 'organic'); * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }] * * // using "_.where" callback shorthand * _.filter(food, { 'type': 'fruit' }); * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }] */ function filter(collection, callback, thisArg) { var result = []; callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { result.push(value); } } } else { each(collection, function(value, index, collection) { if (callback(value, index, collection)) { result.push(value); } }); } return result; } /** * Examines each element in a `collection`, returning the first that the `callback` * returns truthy for. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias detect * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the found element, else `undefined`. * @example * * _.find([1, 2, 3, 4], function(num) { * return num % 2 == 0; * }); * // => 2 * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'banana', 'organic': true, 'type': 'fruit' }, * { 'name': 'beet', 'organic': false, 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.find(food, { 'type': 'vegetable' }); * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' } * * // using "_.pluck" callback shorthand * _.find(food, 'organic'); * // => { 'name': 'banana', 'organic': true, 'type': 'fruit' } */ function find(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { return value; } } } else { var result; each(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; } }); return result; } } /** * Iterates over a `collection`, executing the `callback` for each element in * the `collection`. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). Callbacks may exit iteration early * by explicitly returning `false`. * * @static * @memberOf _ * @alias each * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|String} Returns `collection`. * @example * * _([1, 2, 3]).forEach(alert).join(','); * // => alerts each number and returns '1,2,3' * * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); * // => alerts each number value (order is not guaranteed) */ function forEach(collection, callback, thisArg) { if (callback && typeof thisArg == 'undefined' && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if (callback(collection[index], index, collection) === false) { break; } } } else { each(collection, callback, thisArg); } return collection; } /** * Creates an object composed of keys returned from running each element of the * `collection` through the `callback`. The corresponding value of each key is * an array of elements passed to `callback` that returned the key. The `callback` * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false` * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': [4.2], '6': [6.1, 6.4] } * * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': [4.2], '6': [6.1, 6.4] } * * // using "_.pluck" callback shorthand * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ function groupBy(collection, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg); forEach(collection, function(value, key, collection) { key = String(callback(value, key, collection)); (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); }); return result; } /** * Invokes the method named by `methodName` on each element in the `collection`, * returning an array of the results of each invoked method. Additional arguments * will be passed to each invoked method. If `methodName` is a function, it will * be invoked for, and `this` bound to, each element in the `collection`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|String} methodName The name of the method to invoke or * the function invoked per iteration. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with. * @returns {Array} Returns a new array of the results of each invoked method. * @example * * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ function invoke(collection, methodName) { var args = nativeSlice.call(arguments, 2), index = -1, isFunc = typeof methodName == 'function', length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); }); return result; } /** * Creates an array of values by running each element in the `collection` * through the `callback`. The `callback` is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias collect * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * _.map([1, 2, 3], function(num) { return num * 3; }); * // => [3, 6, 9] * * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); * // => [3, 6, 9] (order is not guaranteed) * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // using "_.pluck" callback shorthand * _.map(stooges, 'name'); * // => ['moe', 'larry'] */ function map(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { while (++index < length) { result[index] = callback(collection[index], index, collection); } } else { each(collection, function(value, key, collection) { result[++index] = callback(value, key, collection); }); } return result; } /** * Retrieves the maximum value of an `array`. If `callback` is passed, * it will be executed for each value in the `array` to generate the * criterion by which the value is ranked. The `callback` is bound to * `thisArg` and invoked with three arguments; (value, index, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.max(stooges, function(stooge) { return stooge.age; }); * // => { 'name': 'larry', 'age': 50 }; * * // using "_.pluck" callback shorthand * _.max(stooges, 'age'); * // => { 'name': 'larry', 'age': 50 }; */ function max(collection, callback, thisArg) { var computed = -Infinity, result = computed; if (!callback && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value > result) { result = value; } } } else { callback = (!callback && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg); each(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current > computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the minimum value of an `array`. If `callback` is passed, * it will be executed for each value in the `array` to generate the * criterion by which the value is ranked. The `callback` is bound to `thisArg` * and invoked with three arguments; (value, index, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.min(stooges, function(stooge) { return stooge.age; }); * // => { 'name': 'moe', 'age': 40 }; * * // using "_.pluck" callback shorthand * _.min(stooges, 'age'); * // => { 'name': 'moe', 'age': 40 }; */ function min(collection, callback, thisArg) { var computed = Infinity, result = computed; if (!callback && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value < result) { result = value; } } } else { callback = (!callback && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg); each(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current < computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the value of a specified property from all elements in the `collection`. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {String} property The property to pluck. * @returns {Array} Returns a new array of property values. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.pluck(stooges, 'name'); * // => ['moe', 'larry'] */ var pluck = map; /** * Reduces a `collection` to a value which is the accumulated result of running * each element in the `collection` through the `callback`, where each successive * `callback` execution consumes the return value of the previous execution. * If `accumulator` is not passed, the first element of the `collection` will be * used as the initial `accumulator` value. The `callback` is bound to `thisArg` * and invoked with four arguments; (accumulator, value, index|key, collection). * * @static * @memberOf _ * @alias foldl, inject * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [accumulator] Initial value of the accumulator. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the accumulated value. * @example * * var sum = _.reduce([1, 2, 3], function(sum, num) { * return sum + num; * }); * // => 6 * * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * return result; * }, {}); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function reduce(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; callback = lodash.createCallback(callback, thisArg, 4); if (isArray(collection)) { var index = -1, length = collection.length; if (noaccum) { accumulator = collection[++index]; } while (++index < length) { accumulator = callback(accumulator, collection[index], index, collection); } } else { each(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection) }); } return accumulator; } /** * This method is similar to `_.reduce`, except that it iterates over a * `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [accumulator] Initial value of the accumulator. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the accumulated value. * @example * * var list = [[0, 1], [2, 3], [4, 5]]; * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, callback, accumulator, thisArg) { var iterable = collection, length = collection ? collection.length : 0, noaccum = arguments.length < 3; if (typeof length != 'number') { var props = keys(collection); length = props.length; } else if (support.unindexedChars && isString(collection)) { iterable = collection.split(''); } callback = lodash.createCallback(callback, thisArg, 4); forEach(collection, function(value, index, collection) { index = props ? props[--length] : --length; accumulator = noaccum ? (noaccum = false, iterable[index]) : callback(accumulator, iterable[index], index, collection); }); return accumulator; } /** * The opposite of `_.filter`, this method returns the elements of a * `collection` that `callback` does **not** return truthy for. * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that did **not** pass the * callback check. * @example * * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [1, 3, 5] * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.reject(food, 'organic'); * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }] * * // using "_.where" callback shorthand * _.reject(food, { 'type': 'fruit' }); * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }] */ function reject(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg); return filter(collection, function(value, index, collection) { return !callback(value, index, collection); }); } /** * Creates an array of shuffled `array` values, using a version of the * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to shuffle. * @returns {Array} Returns a new shuffled collection. * @example * * _.shuffle([1, 2, 3, 4, 5, 6]); * // => [4, 1, 6, 3, 5, 2] */ function shuffle(collection) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { var rand = floor(nativeRandom() * (++index + 1)); result[index] = result[rand]; result[rand] = value; }); return result; } /** * Gets the size of the `collection` by returning `collection.length` for arrays * and array-like objects or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to inspect. * @returns {Number} Returns `collection.length` or number of own enumerable properties. * @example * * _.size([1, 2]); * // => 2 * * _.size({ 'one': 1, 'two': 2, 'three': 3 }); * // => 3 * * _.size('curly'); * // => 5 */ function size(collection) { var length = collection ? collection.length : 0; return typeof length == 'number' ? length : keys(collection).length; } /** * Checks if the `callback` returns a truthy value for **any** element of a * `collection`. The function returns as soon as it finds passing value, and * does not iterate over the entire `collection`. The `callback` is bound to * `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias any * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Boolean} Returns `true` if any element passes the callback check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.some(food, 'organic'); * // => true * * // using "_.where" callback shorthand * _.some(food, { 'type': 'meat' }); * // => false */ function some(collection, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if ((result = callback(collection[index], index, collection))) { break; } } } else { each(collection, function(value, index, collection) { return !(result = callback(value, index, collection)); }); } return !!result; } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in the `collection` through the `callback`. This method * performs a stable sort, that is, it will preserve the original sort order of * equal elements. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of sorted elements. * @example * * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); * // => [3, 1, 2] * * // using "_.pluck" callback shorthand * _.sortBy(['banana', 'strawberry', 'apple'], 'length'); * // => ['apple', 'banana', 'strawberry'] */ function sortBy(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); callback = lodash.createCallback(callback, thisArg); forEach(collection, function(value, key, collection) { result[++index] = { 'criteria': callback(value, key, collection), 'index': index, 'value': value }; }); length = result.length; result.sort(compareAscending); while (length--) { result[length] = result[length].value; } return result; } /** * Converts the `collection` to an array. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to convert. * @returns {Array} Returns the new converted array. * @example * * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); * // => [2, 3, 4] */ function toArray(collection) { if (collection && typeof collection.length == 'number') { return (support.unindexedChars && isString(collection)) ? collection.split('') : slice(collection); } return values(collection); } /** * Examines each element in a `collection`, returning an array of all elements * that have the given `properties`. When checking `properties`, this method * performs a deep comparison between values to determine if they are equivalent * to each other. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Object} properties The object of property values to filter by. * @returns {Array} Returns a new array of elements that have the given `properties`. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.where(stooges, { 'age': 40 }); * // => [{ 'name': 'moe', 'age': 40 }] */ var where = filter; /*--------------------------------------------------------------------------*/ /** * Creates an array with all falsey values of `array` removed. The values * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. * @returns {Array} Returns a new filtered array. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value) { result.push(value); } } return result; } /** * Creates an array of `array` elements not present in the other arrays * using strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to process. * @param {Array} [array1, array2, ...] Arrays to check. * @returns {Array} Returns a new array of `array` elements not present in the * other arrays. * @example * * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); * // => [1, 3, 4] */ function difference(array) { var index = -1, length = array ? array.length : 0, flattened = concat.apply(arrayRef, nativeSlice.call(arguments, 1)), contains = cachedContains(flattened), result = []; while (++index < length) { var value = array[index]; if (!contains(value)) { result.push(value); } } return result; } /** * This method is similar to `_.find`, except that it returns the index of * the element that passes the callback check, instead of the element itself. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the index of the found element, else `-1`. * @example * * _.findIndex(['apple', 'banana', 'beet'], function(food) { * return /^b/.test(food); * }); * // => 1 */ function findIndex(array, callback, thisArg) { var index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg); while (++index < length) { if (callback(array[index], index, array)) { return index; } } return -1; } /** * Gets the first element of the `array`. If a number `n` is passed, the first * `n` elements of the `array` are returned. If a `callback` function is passed, * elements at the beginning of the array are returned as long as the `callback` * returns truthy. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias head, take * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|Number|String} [callback|n] The function called * per element or the number of elements to return. If a property name or * object is passed, it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the first element(s) of `array`. * @example * * _.first([1, 2, 3]); * // => 1 * * _.first([1, 2, 3], 2); * // => [1, 2] * * _.first([1, 2, 3], function(num) { * return num < 3; * }); * // => [1, 2] * * var food = [ * { 'name': 'banana', 'organic': true }, * { 'name': 'beet', 'organic': false }, * ]; * * // using "_.pluck" callback shorthand * _.first(food, 'organic'); * // => [{ 'name': 'banana', 'organic': true }] * * var food = [ * { 'name': 'apple', 'type': 'fruit' }, * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.first(food, { 'type': 'fruit' }); * // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }] */ function first(array, callback, thisArg) { if (array) { var n = 0, length = array.length; if (typeof callback != 'number' && callback != null) { var index = -1; callback = lodash.createCallback(callback, thisArg); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array[0]; } } return slice(array, 0, nativeMin(nativeMax(0, n), length)); } } /** * Flattens a nested array (the nesting can be to any depth). If `isShallow` * is truthy, `array` will only be flattened a single level. If `callback` * is passed, each element of `array` is passed through a callback` before * flattening. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to flatten. * @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * * _.flatten([1, [2], [3, [[4]]]]); * // => [1, 2, 3, 4]; * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; * * var stooges = [ * { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, * { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } * ]; * * // using "_.pluck" callback shorthand * _.flatten(stooges, 'quotes'); * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] */ function flatten(array, isShallow, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = []; // juggle arguments if (typeof isShallow != 'boolean' && isShallow != null) { thisArg = callback; callback = isShallow; isShallow = false; } if (callback != null) { callback = lodash.createCallback(callback, thisArg); } while (++index < length) { var value = array[index]; if (callback) { value = callback(value, index, array); } // recursively flatten arrays (susceptible to call stack limits) if (isArray(value)) { push.apply(result, isShallow ? value : flatten(value)); } else { result.push(value); } } return result; } /** * Gets the index at which the first occurrence of `value` is found using * strict equality for comparisons, i.e. `===`. If the `array` is already * sorted, passing `true` for `fromIndex` will run a faster binary search. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Mixed} value The value to search for. * @param {Boolean|Number} [fromIndex=0] The index to search from or `true` to * perform a binary search on a sorted `array`. * @returns {Number} Returns the index of the matched value or `-1`. * @example * * _.indexOf([1, 2, 3, 1, 2, 3], 2); * // => 1 * * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 4 * * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { var index = -1, length = array ? array.length : 0; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0) - 1; } else if (fromIndex) { index = sortedIndex(array, value); return array[index] === value ? index : -1; } while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * Gets all but the last element of `array`. If a number `n` is passed, the * last `n` elements are excluded from the result. If a `callback` function * is passed, elements at the end of the array are excluded from the result * as long as the `callback` returns truthy. The `callback` is bound to * `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|Number|String} [callback|n=1] The function called * per element or the number of elements to exclude. If a property name or * object is passed, it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] * * _.initial([1, 2, 3], 2); * // => [1] * * _.initial([1, 2, 3], function(num) { * return num > 1; * }); * // => [1] * * var food = [ * { 'name': 'beet', 'organic': false }, * { 'name': 'carrot', 'organic': true } * ]; * * // using "_.pluck" callback shorthand * _.initial(food, 'organic'); * // => [{ 'name': 'beet', 'organic': false }] * * var food = [ * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' }, * { 'name': 'carrot', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.initial(food, { 'type': 'vegetable' }); * // => [{ 'name': 'banana', 'type': 'fruit' }] */ function initial(array, callback, thisArg) { if (!array) { return []; } var n = 0, length = array.length; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg); while (index-- && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : callback || n; } return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); } /** * Computes the intersection of all the passed-in arrays using strict equality * for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} [array1, array2, ...] Arrays to process. * @returns {Array} Returns a new array of unique elements that are present * in **all** of the arrays. * @example * * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); * // => [1, 2] */ function intersection(array) { var args = arguments, argsLength = args.length, cache = { '0': {} }, index = -1, length = array ? array.length : 0, isLarge = length >= largeArraySize, result = [], seen = result; outer: while (++index < length) { var value = array[index]; if (isLarge) { var key = keyPrefix + value; var inited = cache[0][key] ? !(seen = cache[0][key]) : (seen = cache[0][key] = []); } if (inited || indexOf(seen, value) < 0) { if (isLarge) { seen.push(value); } var argsIndex = argsLength; while (--argsIndex) { if (!(cache[argsIndex] || (cache[argsIndex] = cachedContains(args[argsIndex])))(value)) { continue outer; } } result.push(value); } } return result; } /** * Gets the last element of the `array`. If a number `n` is passed, the * last `n` elements of the `array` are returned. If a `callback` function * is passed, elements at the end of the array are returned as long as the * `callback` returns truthy. The `callback` is bound to `thisArg` and * invoked with three arguments;(value, index, array). * * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|Number|String} [callback|n] The function called * per element or the number of elements to return. If a property name or * object is passed, it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the last element(s) of `array`. * @example * * _.last([1, 2, 3]); * // => 3 * * _.last([1, 2, 3], 2); * // => [2, 3] * * _.last([1, 2, 3], function(num) { * return num > 1; * }); * // => [2, 3] * * var food = [ * { 'name': 'beet', 'organic': false }, * { 'name': 'carrot', 'organic': true } * ]; * * // using "_.pluck" callback shorthand * _.last(food, 'organic'); * // => [{ 'name': 'carrot', 'organic': true }] * * var food = [ * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' }, * { 'name': 'carrot', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.last(food, { 'type': 'vegetable' }); * // => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }] */ function last(array, callback, thisArg) { if (array) { var n = 0, length = array.length; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg); while (index-- && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array[length - 1]; } } return slice(array, nativeMax(0, length - n)); } } /** * Gets the index at which the last occurrence of `value` is found using strict * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used * as the offset from the end of the collection. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Mixed} value The value to search for. * @param {Number} [fromIndex=array.length-1] The index to search from. * @returns {Number} Returns the index of the matched value or `-1`. * @example * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); * // => 4 * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var index = array ? array.length : 0; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to but not including `end`. * * @static * @memberOf _ * @category Arrays * @param {Number} [start=0] The start of the range. * @param {Number} end The end of the range. * @param {Number} [step=1] The value to increment or decrement by. * @returns {Array} Returns a new range array. * @example * * _.range(10); * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] * * _.range(1, 11); * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * * _.range(0, 30, 5); * // => [0, 5, 10, 15, 20, 25] * * _.range(0, -10, -1); * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] * * _.range(0); * // => [] */ function range(start, end, step) { start = +start || 0; step = +step || 1; if (end == null) { end = start; start = 0; } // use `Array(length)` so V8 will avoid the slower "dictionary" mode // http://youtu.be/XAqIpGU8ZZk#t=17m25s var index = -1, length = nativeMax(0, ceil((end - start) / step)), result = Array(length); while (++index < length) { result[index] = start; start += step; } return result; } /** * The opposite of `_.initial`, this method gets all but the first value of * `array`. If a number `n` is passed, the first `n` values are excluded from * the result. If a `callback` function is passed, elements at the beginning * of the array are excluded from the result as long as the `callback` returns * truthy. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias drop, tail * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|Number|String} [callback|n=1] The function called * per element or the number of elements to exclude. If a property name or * object is passed, it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] * * _.rest([1, 2, 3], 2); * // => [3] * * _.rest([1, 2, 3], function(num) { * return num < 3; * }); * // => [3] * * var food = [ * { 'name': 'banana', 'organic': true }, * { 'name': 'beet', 'organic': false }, * ]; * * // using "_.pluck" callback shorthand * _.rest(food, 'organic'); * // => [{ 'name': 'beet', 'organic': false }] * * var food = [ * { 'name': 'apple', 'type': 'fruit' }, * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.rest(food, { 'type': 'fruit' }); * // => [{ 'name': 'beet', 'type': 'vegetable' }] */ function rest(array, callback, thisArg) { if (typeof callback != 'number' && callback != null) { var n = 0, index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); } return slice(array, n); } /** * Uses a binary search to determine the smallest index at which the `value` * should be inserted into `array` in order to maintain the sort order of the * sorted `array`. If `callback` is passed, it will be executed for `value` and * each element in `array` to compute their sort ranking. The `callback` is * bound to `thisArg` and invoked with one argument; (value). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to inspect. * @param {Mixed} value The value to evaluate. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Number} Returns the index at which the value should be inserted * into `array`. * @example * * _.sortedIndex([20, 30, 50], 40); * // => 2 * * // using "_.pluck" callback shorthand * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 2 * * var dict = { * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } * }; * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return dict.wordToNumber[word]; * }); * // => 2 * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return this.wordToNumber[word]; * }, dict); * // => 2 */ function sortedIndex(array, value, callback, thisArg) { var low = 0, high = array ? array.length : low; // explicitly reference `identity` for better inlining in Firefox callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; value = callback(value); while (low < high) { var mid = (low + high) >>> 1; (callback(array[mid]) < value) ? low = mid + 1 : high = mid; } return low; } /** * Computes the union of the passed-in arrays using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} [array1, array2, ...] Arrays to process. * @returns {Array} Returns a new array of unique values, in order, that are * present in one or more of the arrays. * @example * * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); * // => [1, 2, 3, 101, 10] */ function union(array) { if (!isArray(array)) { arguments[0] = array ? nativeSlice.call(array) : arrayRef; } return uniq(concat.apply(arrayRef, arguments)); } /** * Creates a duplicate-value-free version of the `array` using strict equality * for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` * for `isSorted` will run a faster algorithm. If `callback` is passed, each * element of `array` is passed through a callback` before uniqueness is computed. * The `callback` is bound to `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias unique * @category Arrays * @param {Array} array The array to process. * @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a duplicate-value-free array. * @example * * _.uniq([1, 2, 1, 3, 1]); * // => [1, 2, 3] * * _.uniq([1, 1, 2, 2, 3], true); * // => [1, 2, 3] * * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); }); * // => [1, 2, 3] * * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); * // => [1, 2, 3] * * // using "_.pluck" callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniq(array, isSorted, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = [], seen = result; // juggle arguments if (typeof isSorted != 'boolean' && isSorted != null) { thisArg = callback; callback = isSorted; isSorted = false; } // init value cache for large arrays var isLarge = !isSorted && length >= largeArraySize; if (isLarge) { var cache = {}; } if (callback != null) { seen = []; callback = lodash.createCallback(callback, thisArg); } while (++index < length) { var value = array[index], computed = callback ? callback(value, index, array) : value; if (isLarge) { var key = keyPrefix + computed; var inited = cache[key] ? !(seen = cache[key]) : (seen = cache[key] = []); } if (isSorted ? !index || seen[seen.length - 1] !== computed : inited || indexOf(seen, computed) < 0 ) { if (callback || isLarge) { seen.push(computed); } result.push(value); } } return result; } /** * The inverse of `_.zip`, this method splits groups of elements into arrays * composed of elements from each group at their corresponding indexes. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to process. * @returns {Array} Returns a new array of the composed arrays. * @example * * _.unzip([['moe', 30, true], ['larry', 40, false]]); * // => [['moe', 'larry'], [30, 40], [true, false]]; */ function unzip(array) { var index = -1, length = array ? array.length : 0, tupleLength = length ? max(pluck(array, 'length')) : 0, result = Array(tupleLength); while (++index < length) { var tupleIndex = -1, tuple = array[index]; while (++tupleIndex < tupleLength) { (result[tupleIndex] || (result[tupleIndex] = Array(length)))[index] = tuple[tupleIndex]; } } return result; } /** * Creates an array with all occurrences of the passed values removed using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to filter. * @param {Mixed} [value1, value2, ...] Values to remove. * @returns {Array} Returns a new filtered array. * @example * * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); * // => [2, 3, 4] */ function without(array) { return difference(array, nativeSlice.call(arguments, 1)); } /** * Groups the elements of each array at their corresponding indexes. Useful for * separate data sources that are coordinated through matching array indexes. * For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix * in a similar fashion. * * @static * @memberOf _ * @category Arrays * @param {Array} [array1, array2, ...] Arrays to process. * @returns {Array} Returns a new array of grouped elements. * @example * * _.zip(['moe', 'larry'], [30, 40], [true, false]); * // => [['moe', 30, true], ['larry', 40, false]] */ function zip(array) { var index = -1, length = array ? max(pluck(arguments, 'length')) : 0, result = Array(length); while (++index < length) { result[index] = pluck(arguments, index); } return result; } /** * Creates an object composed from arrays of `keys` and `values`. Pass either * a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or * two arrays, one of `keys` and one of corresponding `values`. * * @static * @memberOf _ * @alias object * @category Arrays * @param {Array} keys The array of keys. * @param {Array} [values=[]] The array of values. * @returns {Object} Returns an object composed of the given keys and * corresponding values. * @example * * _.zipObject(['moe', 'larry'], [30, 40]); * // => { 'moe': 30, 'larry': 40 } */ function zipObject(keys, values) { var index = -1, length = keys ? keys.length : 0, result = {}; while (++index < length) { var key = keys[index]; if (values) { result[key] = values[index]; } else { result[key[0]] = key[1]; } } return result; } /*--------------------------------------------------------------------------*/ /** * If `n` is greater than `0`, a function is created that is restricted to * executing `func`, with the `this` binding and arguments of the created * function, only after it is called `n` times. If `n` is less than `1`, * `func` is executed immediately, without a `this` binding or additional * arguments, and its result is returned. * * @static * @memberOf _ * @category Functions * @param {Number} n The number of times the function must be called before * it is executed. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var renderNotes = _.after(notes.length, render); * _.forEach(notes, function(note) { * note.asyncSave({ 'success': renderNotes }); * }); * // `renderNotes` is run once, after all notes have saved */ function after(n, func) { if (n < 1) { return func(); } return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that, when called, invokes `func` with the `this` * binding of `thisArg` and prepends any additional `bind` arguments to those * passed to the bound function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to bind. * @param {Mixed} [thisArg] The `this` binding of `func`. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var func = function(greeting) { * return greeting + ' ' + this.name; * }; * * func = _.bind(func, { 'name': 'moe' }, 'hi'); * func(); * // => 'hi moe' */ function bind(func, thisArg) { // use `Function#bind` if it exists and is fast // (in V8 `Function#bind` is slower except when partially applied) return support.fastBind || (nativeBind && arguments.length > 2) ? nativeBind.call.apply(nativeBind, arguments) : createBound(func, thisArg, nativeSlice.call(arguments, 2)); } /** * Binds methods on `object` to `object`, overwriting the existing method. * Method names may be specified as individual arguments or as arrays of method * names. If no method names are provided, all the function properties of `object` * will be bound. * * @static * @memberOf _ * @category Functions * @param {Object} object The object to bind and assign the bound methods to. * @param {String} [methodName1, methodName2, ...] Method names on the object to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'onClick': function() { alert('clicked ' + this.label); } * }; * * _.bindAll(view); * jQuery('#docs').on('click', view.onClick); * // => alerts 'clicked docs', when the button is clicked */ function bindAll(object) { var funcs = arguments.length > 1 ? concat.apply(arrayRef, nativeSlice.call(arguments, 1)) : functions(object), index = -1, length = funcs.length; while (++index < length) { var key = funcs[index]; object[key] = bind(object[key], object); } return object; } /** * Creates a function that, when called, invokes the method at `object[key]` * and prepends any additional `bindKey` arguments to those passed to the bound * function. This method differs from `_.bind` by allowing bound functions to * reference methods that will be redefined or don't yet exist. * See http://michaux.ca/articles/lazy-function-definition-pattern. * * @static * @memberOf _ * @category Functions * @param {Object} object The object the method belongs to. * @param {String} key The key of the method. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'name': 'moe', * 'greet': function(greeting) { * return greeting + ' ' + this.name; * } * }; * * var func = _.bindKey(object, 'greet', 'hi'); * func(); * // => 'hi moe' * * object.greet = function(greeting) { * return greeting + ', ' + this.name + '!'; * }; * * func(); * // => 'hi, moe!' */ function bindKey(object, key) { return createBound(object, key, nativeSlice.call(arguments, 2), indicatorObject); } /** * Creates a function that is the composition of the passed functions, * where each function consumes the return value of the function that follows. * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. * Each function is executed with the `this` binding of the composed function. * * @static * @memberOf _ * @category Functions * @param {Function} [func1, func2, ...] Functions to compose. * @returns {Function} Returns the new composed function. * @example * * var greet = function(name) { return 'hi ' + name; }; * var exclaim = function(statement) { return statement + '!'; }; * var welcome = _.compose(exclaim, greet); * welcome('moe'); * // => 'hi moe!' */ function compose() { var funcs = arguments; return function() { var args = arguments, length = funcs.length; while (length--) { args = [funcs[length].apply(this, args)]; } return args[0]; }; } /** * Produces a callback bound to an optional `thisArg`. If `func` is a property * name, the created callback will return the property value for a given element. * If `func` is an object, the created callback will return `true` for elements * that contain the equivalent object properties, otherwise it will return `false`. * * Note: All Lo-Dash methods, that accept a `callback` argument, use `_.createCallback`. * * @static * @memberOf _ * @category Functions * @param {Mixed} [func=identity] The value to convert to a callback. * @param {Mixed} [thisArg] The `this` binding of the created callback. * @param {Number} [argCount=3] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // wrap to create custom callback shorthands * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); * return !match ? func(callback, thisArg) : function(object) { * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; * }; * }); * * _.filter(stooges, 'age__gt45'); * // => [{ 'name': 'larry', 'age': 50 }] * * // create mixins with support for "_.pluck" and "_.where" callback shorthands * _.mixin({ * 'toLookup': function(collection, callback, thisArg) { * callback = _.createCallback(callback, thisArg); * return _.reduce(collection, function(result, value, index, collection) { * return (result[callback(value, index, collection)] = value, result); * }, {}); * } * }); * * _.toLookup(stooges, 'name'); * // => { 'moe': { 'name': 'moe', 'age': 40 }, 'larry': { 'name': 'larry', 'age': 50 } } */ function createCallback(func, thisArg, argCount) { if (func == null) { return identity; } var type = typeof func; if (type != 'function') { if (type != 'object') { return function(object) { return object[func]; }; } var props = keys(func); return function(object) { var length = props.length, result = false; while (length--) { if (!(result = isEqual(object[props[length]], func[props[length]], indicatorObject))) { break; } } return result; }; } if (typeof thisArg != 'undefined') { if (argCount === 1) { return function(value) { return func.call(thisArg, value); }; } if (argCount === 2) { return function(a, b) { return func.call(thisArg, a, b); }; } if (argCount === 4) { return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; } return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return func; } /** * Creates a function that will delay the execution of `func` until after * `wait` milliseconds have elapsed since the last time it was invoked. Pass * an `options` object to indicate that `func` should be invoked on the leading * and/or trailing edge of the `wait` timeout. Subsequent calls to the debounced * function will return the result of the last `func` call. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to debounce. * @param {Number} wait The number of milliseconds to delay. * @param {Object} options The options object. * [leading=false] A boolean to specify execution on the leading edge of the timeout. * [trailing=true] A boolean to specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * var lazyLayout = _.debounce(calculateLayout, 300); * jQuery(window).on('resize', lazyLayout); */ function debounce(func, wait, options) { var args, result, thisArg, timeoutId, trailing = true; function delayed() { timeoutId = null; if (trailing) { result = func.apply(thisArg, args); } } if (options === true) { var leading = true; trailing = false; } else if (options && objectTypes[typeof options]) { leading = options.leading; trailing = 'trailing' in options ? options.trailing : trailing; } return function() { var isLeading = leading && !timeoutId; args = arguments; thisArg = this; clearTimeout(timeoutId); timeoutId = setTimeout(delayed, wait); if (isLeading) { result = func.apply(thisArg, args); } return result; }; } /** * Defers executing the `func` function until the current call stack has cleared. * Additional arguments will be passed to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to defer. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with. * @returns {Number} Returns the timer id. * @example * * _.defer(function() { alert('deferred'); }); * // returns from the function before `alert` is called */ function defer(func) { var args = nativeSlice.call(arguments, 1); return setTimeout(function() { func.apply(undefined, args); }, 1); } // use `setImmediate` if it's available in Node.js if (isV8 && freeModule && typeof setImmediate == 'function') { defer = bind(setImmediate, context); } /** * Executes the `func` function after `wait` milliseconds. Additional arguments * will be passed to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to delay. * @param {Number} wait The number of milliseconds to delay execution. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with. * @returns {Number} Returns the timer id. * @example * * var log = _.bind(console.log, console); * _.delay(log, 1000, 'logged later'); * // => 'logged later' (Appears after one second.) */ function delay(func, wait) { var args = nativeSlice.call(arguments, 2); return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * passed, it will be used to determine the cache key for storing the result * based on the arguments passed to the memoized function. By default, the first * argument passed to the memoized function is used as the cache key. The `func` * is executed with the `this` binding of the memoized function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] A function used to resolve the cache key. * @returns {Function} Returns the new memoizing function. * @example * * var fibonacci = _.memoize(function(n) { * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); * }); */ function memoize(func, resolver) { var cache = {}; return function() { var key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]); return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); }; } /** * Creates a function that is restricted to execute `func` once. Repeat calls to * the function will return the value of the first call. The `func` is executed * with the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` executes `createApplication` once */ function once(func) { var ran, result; return function() { if (ran) { return result; } ran = true; result = func.apply(this, arguments); // clear the `func` variable so the function may be garbage collected func = null; return result; }; } /** * Creates a function that, when called, invokes `func` with any additional * `partial` arguments prepended to those passed to the new function. This * method is similar to `_.bind`, except it does **not** alter the `this` binding. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { return greeting + ' ' + name; }; * var hi = _.partial(greet, 'hi'); * hi('moe'); * // => 'hi moe' */ function partial(func) { return createBound(func, nativeSlice.call(arguments, 1)); } /** * This method is similar to `_.partial`, except that `partial` arguments are * appended to those passed to the new function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var defaultsDeep = _.partialRight(_.merge, _.defaults); * * var options = { * 'variable': 'data', * 'imports': { 'jq': $ } * }; * * defaultsDeep(options, _.templateSettings); * * options.variable * // => 'data' * * options.imports * // => { '_': _, 'jq': $ } */ function partialRight(func) { return createBound(func, nativeSlice.call(arguments, 1), null, indicatorObject); } /** * Creates a function that, when executed, will only call the `func` function * at most once per every `wait` milliseconds. If the throttled function is * invoked more than once during the `wait` timeout, `func` will also be called * on the trailing edge of the timeout. Pass an `options` object to indicate * that `func` should be invoked on the leading and/or trailing edge of the * `wait` timeout. Subsequent calls to the throttled function will return * the result of the last `func` call. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to throttle. * @param {Number} wait The number of milliseconds to throttle executions to. * @param {Object} options The options object. * [leading=true] A boolean to specify execution on the leading edge of the timeout. * [trailing=true] A boolean to specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * var throttled = _.throttle(updatePosition, 100); * jQuery(window).on('scroll', throttled); */ function throttle(func, wait, options) { var args, result, thisArg, timeoutId, lastCalled = 0, leading = true, trailing = true; function trailingCall() { lastCalled = new Date; timeoutId = null; if (trailing) { result = func.apply(thisArg, args); } } if (options === false) { leading = false; } else if (options && objectTypes[typeof options]) { leading = 'leading' in options ? options.leading : leading; trailing = 'trailing' in options ? options.trailing : trailing; } return function() { var now = new Date; if (!timeoutId && !leading) { lastCalled = now; } var remaining = wait - (now - lastCalled); args = arguments; thisArg = this; if (remaining <= 0) { clearTimeout(timeoutId); timeoutId = null; lastCalled = now; result = func.apply(thisArg, args); } else if (!timeoutId) { timeoutId = setTimeout(trailingCall, remaining); } return result; }; } /** * Creates a function that passes `value` to the `wrapper` function as its * first argument. Additional arguments passed to the function are appended * to those passed to the `wrapper` function. The `wrapper` is executed with * the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {Mixed} value The value to wrap. * @param {Function} wrapper The wrapper function. * @returns {Function} Returns the new function. * @example * * var hello = function(name) { return 'hello ' + name; }; * hello = _.wrap(hello, function(func) { * return 'before, ' + func('moe') + ', after'; * }); * hello(); * // => 'before, hello moe, after' */ function wrap(value, wrapper) { return function() { var args = [value]; push.apply(args, arguments); return wrapper.apply(this, args); }; } /*--------------------------------------------------------------------------*/ /** * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their * corresponding HTML entities. * * @static * @memberOf _ * @category Utilities * @param {String} string The string to escape. * @returns {String} Returns the escaped string. * @example * * _.escape('Moe, Larry & Curly'); * // => 'Moe, Larry &amp; Curly' */ function escape(string) { return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); } /** * This function returns the first argument passed to it. * * @static * @memberOf _ * @category Utilities * @param {Mixed} value Any value. * @returns {Mixed} Returns `value`. * @example * * var moe = { 'name': 'moe' }; * moe === _.identity(moe); * // => true */ function identity(value) { return value; } /** * Adds functions properties of `object` to the `lodash` function and chainable * wrapper. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object of function properties to add to `lodash`. * @example * * _.mixin({ * 'capitalize': function(string) { * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); * } * }); * * _.capitalize('moe'); * // => 'Moe' * * _('moe').capitalize(); * // => 'Moe' */ function mixin(object) { forEach(functions(object), function(methodName) { var func = lodash[methodName] = object[methodName]; lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = [value]; push.apply(args, arguments); var result = func.apply(lodash, args); return (value && typeof value == 'object' && value == result) ? this : new lodashWrapper(result); }; }); } /** * Reverts the '_' variable to its previous value and returns a reference to * the `lodash` function. * * @static * @memberOf _ * @category Utilities * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { context._ = oldDash; return this; } /** * Converts the given `value` into an integer of the specified `radix`. * * Note: This method avoids differences in native ES3 and ES5 `parseInt` * implementations. See http://es5.github.com/#E. * * @static * @memberOf _ * @category Utilities * @param {Mixed} value The value to parse. * @returns {Number} Returns the new integer value. * @example * * _.parseInt('08'); * // => 8 */ var parseInt = nativeParseInt('08') == 8 ? nativeParseInt : function(value, radix) { // Firefox and Opera still follow the ES3 specified implementation of `parseInt` return nativeParseInt(isString(value) ? value.replace(reLeadingZeros, '') : value, radix || 0); }; /** * Produces a random number between `min` and `max` (inclusive). If only one * argument is passed, a number between `0` and the given number will be returned. * * @static * @memberOf _ * @category Utilities * @param {Number} [min=0] The minimum possible value. * @param {Number} [max=1] The maximum possible value. * @returns {Number} Returns a random number. * @example * * _.random(0, 5); * // => a number between 0 and 5 * * _.random(5); * // => also a number between 0 and 5 */ function random(min, max) { if (min == null && max == null) { max = 1; } min = +min || 0; if (max == null) { max = min; min = 0; } return min + floor(nativeRandom() * ((+max || 0) - min + 1)); } /** * Resolves the value of `property` on `object`. If `property` is a function, * it will be invoked with the `this` binding of `object` and its result returned, * else the property value is returned. If `object` is falsey, then `undefined` * is returned. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object to inspect. * @param {String} property The property to get the value of. * @returns {Mixed} Returns the resolved value. * @example * * var object = { * 'cheese': 'crumpets', * 'stuff': function() { * return 'nonsense'; * } * }; * * _.result(object, 'cheese'); * // => 'crumpets' * * _.result(object, 'stuff'); * // => 'nonsense' */ function result(object, property) { var value = object ? object[property] : undefined; return isFunction(value) ? object[property]() : value; } /** * A micro-templating method that handles arbitrary delimiters, preserves * whitespace, and correctly escapes quotes within interpolated code. * * Note: In the development build, `_.template` utilizes sourceURLs for easier * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl * * For more information on precompiling templates see: * http://lodash.com/#custom-builds * * For more information on Chrome extension sandboxes see: * http://developer.chrome.com/stable/extensions/sandboxingEval.html * * @static * @memberOf _ * @category Utilities * @param {String} text The template text. * @param {Object} data The data object used to populate the text. * @param {Object} options The options object. * escape - The "escape" delimiter regexp. * evaluate - The "evaluate" delimiter regexp. * interpolate - The "interpolate" delimiter regexp. * sourceURL - The sourceURL of the template's compiled source. * variable - The data object variable name. * @returns {Function|String} Returns a compiled function when no `data` object * is given, else it returns the interpolated text. * @example * * // using a compiled template * var compiled = _.template('hello <%= name %>'); * compiled({ 'name': 'moe' }); * // => 'hello moe' * * var list = '<% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>'; * _.template(list, { 'people': ['moe', 'larry'] }); * // => '<li>moe</li><li>larry</li>' * * // using the "escape" delimiter to escape HTML in data property values * _.template('<b><%- value %></b>', { 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter * _.template('hello ${ name }', { 'name': 'curly' }); * // => 'hello curly' * * // using the internal `print` function in "evaluate" delimiters * _.template('<% print("hello " + epithet); %>!', { 'epithet': 'stooge' }); * // => 'hello stooge!' * * // using custom template delimiters * _.templateSettings = { * 'interpolate': /{{([\s\S]+?)}}/g * }; * * _.template('hello {{ name }}!', { 'name': 'mustache' }); * // => 'hello mustache!' * * // using the `sourceURL` option to specify a custom sourceURL for the template * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector * * // using the `variable` option to ensure a with-statement isn't used in the compiled template * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' }); * compiled.source; * // => function(data) { * var __t, __p = '', __e = _.escape; * __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!'; * return __p; * } * * // using the `source` property to inline compiled templates for meaningful * // line numbers in error messages and a stack trace * fs.writeFileSync(path.join(cwd, 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(text, data, options) { // based on John Resig's `tmpl` implementation // http://ejohn.org/blog/javascript-micro-templating/ // and Laura Doktorova's doT.js // https://github.com/olado/doT var settings = lodash.templateSettings; text || (text = ''); // avoid missing dependencies when `iteratorTemplate` is not defined options = iteratorTemplate ? defaults({}, options, settings) : settings; var imports = iteratorTemplate && defaults({}, options.imports, settings.imports), importsKeys = iteratorTemplate ? keys(imports) : ['_'], importsValues = iteratorTemplate ? values(imports) : [lodash]; var isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // compile the regexp to match each delimiter var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // escape characters that cannot be included in string literals source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar); // replace delimiters with snippets if (escapeValue) { source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // the JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value return match; }); source += "';\n"; // if `variable` is not specified, wrap a with-statement around the generated // code to add the data object to the top of the scope chain var variable = options.variable, hasVariable = variable; if (!hasVariable) { variable = 'obj'; source = 'with (' + variable + ') {\n' + source + '\n}\n'; } // cleanup code by stripping empty strings source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // frame code as the function body source = 'function(' + variable + ') {\n' + (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') + "var __t, __p = '', __e = _.escape" + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; // Use a sourceURL for easier debugging and wrap in a multi-line comment to // avoid issues with Narwhal, IE conditional compilation, and the JS engine // embedded in Adobe products. // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl var sourceURL = '\n/*\n//@ sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/'; try { var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues); } catch(e) { e.source = source; throw e; } if (data) { return result(data); } // provide the compiled function's source via its `toString` method, in // supported environments, or the `source` property as a convenience for // inlining compiled templates during the build process result.source = source; return result; } /** * Executes the `callback` function `n` times, returning an array of the results * of each `callback` execution. The `callback` is bound to `thisArg` and invoked * with one argument; (index). * * @static * @memberOf _ * @category Utilities * @param {Number} n The number of times to execute the callback. * @param {Function} callback The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * var diceRolls = _.times(3, _.partial(_.random, 1, 6)); * // => [3, 6, 4] * * _.times(3, function(n) { mage.castSpell(n); }); * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively * * _.times(3, function(n) { this.cast(n); }, mage); * // => also calls `mage.castSpell(n)` three times */ function times(n, callback, thisArg) { n = (n = +n) > -1 ? n : 0; var index = -1, result = Array(n); callback = lodash.createCallback(callback, thisArg, 1); while (++index < n) { result[index] = callback(index); } return result; } /** * The inverse of `_.escape`, this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their * corresponding characters. * * @static * @memberOf _ * @category Utilities * @param {String} string The string to unescape. * @returns {String} Returns the unescaped string. * @example * * _.unescape('Moe, Larry &amp; Curly'); * // => 'Moe, Larry & Curly' */ function unescape(string) { return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar); } /** * Generates a unique ID. If `prefix` is passed, the ID will be appended to it. * * @static * @memberOf _ * @category Utilities * @param {String} [prefix] The value to prefix the ID with. * @returns {String} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return String(prefix == null ? '' : prefix) + id; } /*--------------------------------------------------------------------------*/ /** * Invokes `interceptor` with the `value` as the first argument, and then * returns `value`. The purpose of this method is to "tap into" a method chain, * in order to perform operations on intermediate results within the chain. * * @static * @memberOf _ * @category Chaining * @param {Mixed} value The value to pass to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {Mixed} Returns `value`. * @example * * _([1, 2, 3, 4]) * .filter(function(num) { return num % 2 == 0; }) * .tap(alert) * .map(function(num) { return num * num; }) * .value(); * // => // [2, 4] (alerted) * // => [4, 16] */ function tap(value, interceptor) { interceptor(value); return value; } /** * Produces the `toString` result of the wrapped value. * * @name toString * @memberOf _ * @category Chaining * @returns {String} Returns the string result. * @example * * _([1, 2, 3]).toString(); * // => '1,2,3' */ function wrapperToString() { return String(this.__wrapped__); } /** * Extracts the wrapped value. * * @name valueOf * @memberOf _ * @alias value * @category Chaining * @returns {Mixed} Returns the wrapped value. * @example * * _([1, 2, 3]).valueOf(); * // => [1, 2, 3] */ function wrapperValueOf() { return this.__wrapped__; } /*--------------------------------------------------------------------------*/ // add functions that return wrapped values when chaining lodash.after = after; lodash.assign = assign; lodash.at = at; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.compact = compact; lodash.compose = compose; lodash.countBy = countBy; lodash.createCallback = createCallback; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.filter = filter; lodash.flatten = flatten; lodash.forEach = forEach; lodash.forIn = forIn; lodash.forOwn = forOwn; lodash.functions = functions; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.invert = invert; lodash.invoke = invoke; lodash.keys = keys; lodash.map = map; lodash.max = max; lodash.memoize = memoize; lodash.merge = merge; lodash.min = min; lodash.omit = omit; lodash.once = once; lodash.pairs = pairs; lodash.partial = partial; lodash.partialRight = partialRight; lodash.pick = pick; lodash.pluck = pluck; lodash.range = range; lodash.reject = reject; lodash.rest = rest; lodash.shuffle = shuffle; lodash.sortBy = sortBy; lodash.tap = tap; lodash.throttle = throttle; lodash.times = times; lodash.toArray = toArray; lodash.union = union; lodash.uniq = uniq; lodash.unzip = unzip; lodash.values = values; lodash.where = where; lodash.without = without; lodash.wrap = wrap; lodash.zip = zip; lodash.zipObject = zipObject; // add aliases lodash.collect = map; lodash.drop = rest; lodash.each = forEach; lodash.extend = assign; lodash.methods = functions; lodash.object = zipObject; lodash.select = filter; lodash.tail = rest; lodash.unique = uniq; // add functions to `lodash.prototype` mixin(lodash); /*--------------------------------------------------------------------------*/ // add functions that return unwrapped values when chaining lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.contains = contains; lodash.escape = escape; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.has = has; lodash.identity = identity; lodash.indexOf = indexOf; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isBoolean = isBoolean; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isNaN = isNaN; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isString = isString; lodash.isUndefined = isUndefined; lodash.lastIndexOf = lastIndexOf; lodash.mixin = mixin; lodash.noConflict = noConflict; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.result = result; lodash.runInContext = runInContext; lodash.size = size; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.template = template; lodash.unescape = unescape; lodash.uniqueId = uniqueId; // add aliases lodash.all = every; lodash.any = some; lodash.detect = find; lodash.foldl = reduce; lodash.foldr = reduceRight; lodash.include = contains; lodash.inject = reduce; forOwn(lodash, function(func, methodName) { if (!lodash.prototype[methodName]) { lodash.prototype[methodName] = function() { var args = [this.__wrapped__]; push.apply(args, arguments); return func.apply(lodash, args); }; } }); /*--------------------------------------------------------------------------*/ // add functions capable of returning wrapped and unwrapped values when chaining lodash.first = first; lodash.last = last; // add aliases lodash.take = first; lodash.head = first; forOwn(lodash, function(func, methodName) { if (!lodash.prototype[methodName]) { lodash.prototype[methodName]= function(callback, thisArg) { var result = func(this.__wrapped__, callback, thisArg); return callback == null || (thisArg && typeof callback != 'function') ? result : new lodashWrapper(result); }; } }); /*--------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type String */ lodash.VERSION = '1.2.0'; // add "Chaining" functions to the wrapper lodash.prototype.toString = wrapperToString; lodash.prototype.value = wrapperValueOf; lodash.prototype.valueOf = wrapperValueOf; // add `Array` functions that return unwrapped values each(['join', 'pop', 'shift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { return func.apply(this.__wrapped__, arguments); }; }); // add `Array` functions that return the wrapped value each(['push', 'reverse', 'sort', 'unshift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { func.apply(this.__wrapped__, arguments); return this; }; }); // add `Array` functions that return new wrapped values each(['concat', 'slice', 'splice'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { return new lodashWrapper(func.apply(this.__wrapped__, arguments)); }; }); // avoid array-like object bugs with `Array#shift` and `Array#splice` // in Firefox < 10 and IE < 9 if (!support.spliceObjects) { each(['pop', 'shift', 'splice'], function(methodName) { var func = arrayRef[methodName], isSplice = methodName == 'splice'; lodash.prototype[methodName] = function() { var value = this.__wrapped__, result = func.apply(value, arguments); if (value.length === 0) { delete value[0]; } return isSplice ? new lodashWrapper(result) : result; }; }); } // add pseudo private property to be used and removed during the build process lodash._each = each; lodash._iteratorTemplate = iteratorTemplate; lodash._shimKeys = shimKeys; return lodash; } /*--------------------------------------------------------------------------*/ // expose Lo-Dash var _ = runInContext(); // some AMD build optimizers, like r.js, check for specific condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lo-Dash to the global object even when an AMD loader is present in // case Lo-Dash was injected by a third-party script and not intended to be // loaded as a module. The global assignment can be reverted in the Lo-Dash // module via its `noConflict()` method. window._ = _; // define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module define(function() { return _; }); } // check for `exports` after `define` in case a build optimizer adds an `exports` object else if (freeExports && !freeExports.nodeType) { // in Node.js or RingoJS v0.8.0+ if (freeModule) { (freeModule.exports = _)._ = _; } // in Narwhal or RingoJS v0.7.0- else { freeExports._ = _; } } else { // in a browser or Rhino window._ = _; } }(this)); /*global setImmediate: false, setTimeout: false, console: false */ (function () { var async = {}; // global on the server, window in the browser var root, previous_async; root = this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { var called = false; return function() { if (called) throw new Error("Callback was already called."); called = true; fn.apply(root, arguments); } } //// cross-browser compatiblity functions //// var _each = function (arr, iterator) { if (arr.forEach) { return arr.forEach(iterator); } for (var i = 0; i < arr.length; i += 1) { iterator(arr[i], i, arr); } }; var _map = function (arr, iterator) { if (arr.map) { return arr.map(iterator); } var results = []; _each(arr, function (x, i, a) { results.push(iterator(x, i, a)); }); return results; }; var _reduce = function (arr, iterator, memo) { if (arr.reduce) { return arr.reduce(iterator, memo); } _each(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; }; var _keys = function (obj) { if (Object.keys) { return Object.keys(obj); } var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// if (typeof process === 'undefined' || !(process.nextTick)) { if (typeof setImmediate === 'function') { async.setImmediate = setImmediate; async.nextTick = setImmediate; } else { async.setImmediate = async.nextTick; async.nextTick = function (fn) { setTimeout(fn, 0); }; } } else { async.nextTick = process.nextTick; if (typeof setImmediate !== 'undefined') { async.setImmediate = setImmediate; } else { async.setImmediate = async.nextTick; } } async.each = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, only_once(function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(null); } } })); }); }; async.forEach = async.each; async.eachSeries = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; var iterate = function () { iterator(arr[completed], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(null); } else { iterate(); } } }); }; iterate(); }; async.forEachSeries = async.eachSeries; async.eachLimit = function (arr, limit, iterator, callback) { var fn = _eachLimit(limit); fn.apply(null, [arr, iterator, callback]); }; async.forEachLimit = async.eachLimit; var _eachLimit = function (limit) { return function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length || limit <= 0) { return callback(); } var completed = 0; var started = 0; var running = 0; (function replenish () { if (completed >= arr.length) { return callback(); } while (running < limit && started < arr.length) { started += 1; running += 1; iterator(arr[started - 1], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; running -= 1; if (completed >= arr.length) { callback(); } else { replenish(); } } }); } })(); }; }; var doParallel = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.each].concat(args)); }; }; var doParallelLimit = function(limit, fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [_eachLimit(limit)].concat(args)); }; }; var doSeries = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.eachSeries].concat(args)); }; }; var _asyncMap = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (err, v) { results[x.index] = v; callback(err); }); }, function (err) { callback(err, results); }); }; async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = function (arr, limit, iterator, callback) { return _mapLimit(limit)(arr, iterator, callback); }; var _mapLimit = function(limit) { return doParallelLimit(limit, _asyncMap); }; // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.reduce = function (arr, memo, iterator, callback) { async.eachSeries(arr, function (x, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; // inject alias async.inject = async.reduce; // foldl alias async.foldl = async.reduce; async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, function (x) { return x; }).reverse(); async.reduce(reversed, memo, iterator, callback); }; // foldr alias async.foldr = async.reduceRight; var _filter = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.filter = doParallel(_filter); async.filterSeries = doSeries(_filter); // select alias async.select = async.filter; async.selectSeries = async.filterSeries; var _reject = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (!v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.reject = doParallel(_reject); async.rejectSeries = doSeries(_reject); var _detect = function (eachfn, arr, iterator, main_callback) { eachfn(arr, function (x, callback) { iterator(x, function (result) { if (result) { main_callback(x); main_callback = function () {}; } else { callback(); } }); }, function (err) { main_callback(); }); }; async.detect = doParallel(_detect); async.detectSeries = doSeries(_detect); async.some = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (v) { main_callback(true); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(false); }); }; // any alias async.any = async.some; async.every = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (!v) { main_callback(false); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(true); }); }; // all alias async.all = async.every; async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { var fn = function (left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }; callback(null, _map(results.sort(fn), function (x) { return x.value; })); } }); }; async.auto = function (tasks, callback) { callback = callback || function () {}; var keys = _keys(tasks); if (!keys.length) { return callback(null); } var results = {}; var listeners = []; var addListener = function (fn) { listeners.unshift(fn); }; var removeListener = function (fn) { for (var i = 0; i < listeners.length; i += 1) { if (listeners[i] === fn) { listeners.splice(i, 1); return; } } }; var taskComplete = function () { _each(listeners.slice(0), function (fn) { fn(); }); }; addListener(function () { if (_keys(results).length === keys.length) { callback(null, results); callback = function () {}; } }); _each(keys, function (k) { var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; var taskCallback = function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _each(_keys(results), function(rkey) { safeResults[rkey] = results[rkey]; }); safeResults[k] = args; callback(err, safeResults); // stop subsequent errors hitting callback multiple times callback = function () {}; } else { results[k] = args; async.setImmediate(taskComplete); } }; var requires = task.slice(0, Math.abs(task.length - 1)) || []; var ready = function () { return _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); }; if (ready()) { task[task.length - 1](taskCallback, results); } else { var listener = function () { if (ready()) { removeListener(listener); task[task.length - 1](taskCallback, results); } }; addListener(listener); } }); }; async.waterfall = function (tasks, callback) { callback = callback || function () {}; if (tasks.constructor !== Array) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } var wrapIterator = function (iterator) { return function (err) { if (err) { callback.apply(null, arguments); callback = function () {}; } else { var args = Array.prototype.slice.call(arguments, 1); var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } async.setImmediate(function () { iterator.apply(null, args); }); } }; }; wrapIterator(async.iterator(tasks))(); }; var _parallel = function(eachfn, tasks, callback) { callback = callback || function () {}; if (tasks.constructor === Array) { eachfn.map(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; eachfn.each(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.parallel = function (tasks, callback) { _parallel({ map: async.map, each: async.each }, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); }; async.series = function (tasks, callback) { callback = callback || function () {}; if (tasks.constructor === Array) { async.mapSeries(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; async.eachSeries(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.iterator = function (tasks) { var makeCallback = function (index) { var fn = function () { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); }; fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; }; return makeCallback(0); }; async.apply = function (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply( null, args.concat(Array.prototype.slice.call(arguments)) ); }; }; var _concat = function (eachfn, arr, fn, callback) { var r = []; eachfn(arr, function (x, cb) { fn(x, function (err, y) { r = r.concat(y || []); cb(err); }); }, function (err) { callback(err, r); }); }; async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { if (test()) { iterator(function (err) { if (err) { return callback(err); } async.whilst(test, iterator, callback); }); } else { callback(); } }; async.doWhilst = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } if (test()) { async.doWhilst(iterator, test, callback); } else { callback(); } }); }; async.until = function (test, iterator, callback) { if (!test()) { iterator(function (err) { if (err) { return callback(err); } async.until(test, iterator, callback); }); } else { callback(); } }; async.doUntil = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } if (!test()) { async.doUntil(iterator, test, callback); } else { callback(); } }); }; async.queue = function (worker, concurrency) { if (concurrency === undefined) { concurrency = 1; } function _insert(q, data, pos, callback) { if(data.constructor !== Array) { data = [data]; } _each(data, function(task) { var item = { data: task, callback: typeof callback === 'function' ? callback : null }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.saturated && q.tasks.length === concurrency) { q.saturated(); } async.setImmediate(q.process); }); } var workers = 0; var q = { tasks: [], concurrency: concurrency, saturated: null, empty: null, drain: null, push: function (data, callback) { _insert(q, data, false, callback); }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (workers < q.concurrency && q.tasks.length) { var task = q.tasks.shift(); if (q.empty && q.tasks.length === 0) { q.empty(); } workers += 1; var next = function () { workers -= 1; if (task.callback) { task.callback.apply(task, arguments); } if (q.drain && q.tasks.length + workers === 0) { q.drain(); } q.process(); }; var cb = only_once(next); worker(task.data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; } }; return q; }; async.cargo = function (worker, payload) { var working = false, tasks = []; var cargo = { tasks: tasks, payload: payload, saturated: null, empty: null, drain: null, push: function (data, callback) { if(data.constructor !== Array) { data = [data]; } _each(data, function(task) { tasks.push({ data: task, callback: typeof callback === 'function' ? callback : null }); if (cargo.saturated && tasks.length === payload) { cargo.saturated(); } }); async.setImmediate(cargo.process); }, process: function process() { if (working) return; if (tasks.length === 0) { if(cargo.drain) cargo.drain(); return; } var ts = typeof payload === 'number' ? tasks.splice(0, payload) : tasks.splice(0); var ds = _map(ts, function (task) { return task.data; }); if(cargo.empty) cargo.empty(); working = true; worker(ds, function () { working = false; var args = arguments; _each(ts, function (data) { if (data.callback) { data.callback.apply(null, args); } }); process(); }); }, length: function () { return tasks.length; }, running: function () { return working; } }; return cargo; }; var _console_fn = function (name) { return function (fn) { var args = Array.prototype.slice.call(arguments, 1); fn.apply(null, args.concat([function (err) { var args = Array.prototype.slice.call(arguments, 1); if (typeof console !== 'undefined') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _each(args, function (x) { console[name](x); }); } } }])); }; }; async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || function (x) { return x; }; var memoized = function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { callback.apply(null, memo[key]); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([function () { memo[key] = arguments; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, arguments); } }])); } }; memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; async.times = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.map(counter, iterator, callback); }; async.timesSeries = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.mapSeries(counter, iterator, callback); }; async.compose = function (/* functions... */) { var fns = Array.prototype.reverse.call(arguments); return function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([function () { var err = arguments[0]; var nextargs = Array.prototype.slice.call(arguments, 1); cb(err, nextargs); }])) }, function (err, results) { callback.apply(that, [err].concat(results)); }); }; }; var _applyEach = function (eachfn, fns /*args...*/) { var go = function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); return eachfn(fns, function (fn, cb) { fn.apply(that, args.concat([cb])); }, callback); }; if (arguments.length > 2) { var args = Array.prototype.slice.call(arguments, 2); return go.apply(this, args); } else { return go; } }; async.applyEach = doParallel(_applyEach); async.applyEachSeries = doSeries(_applyEach); async.forever = function (fn, callback) { function next(err) { if (err) { if (callback) { return callback(err); } throw err; } fn(next); } next(); }; // AMD / RequireJS if (typeof define !== 'undefined' && define.amd) { define([], function () { return async; }); } // Node.js else if (typeof module !== 'undefined' && module.exports) { module.exports = async; } // included directly via <script> tag else { root.async = async; } }()); /*! * Platform.js v1.0.0 <http://mths.be/platform> * Copyright 2010-2012 John-David Dalton <http://allyoucanleet.com/> * Available under MIT license <http://mths.be/mit> */ ;(function(window) { 'use strict'; /** Backup possible window/global object */ var oldWin = window; /** Detect free variable `exports` */ var freeExports = typeof exports == 'object' && exports; /** Detect free variable `global` */ var freeGlobal = typeof global == 'object' && global && (global == global.global ? (window = global) : global); /** Opera regexp */ var reOpera = /Opera/; /** Used to resolve a value's internal [[Class]] */ var toString = {}.toString; /** Detect Java environment */ var java = /Java/.test(getClassOf(window.java)) && window.java; /** A character to represent alpha */ var alpha = java ? 'a' : '\u03b1'; /** A character to represent beta */ var beta = java ? 'b' : '\u03b2'; /** Browser document object */ var doc = window.document || {}; /** Used to check for own properties of an object */ var hasOwnProperty = {}.hasOwnProperty; /** Browser navigator object */ var nav = window.navigator || {}; /** * Detect Opera browser * http://www.howtocreate.co.uk/operaStuff/operaObject.html * http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini */ var opera = window.operamini || window.opera; /** Opera [[Class]] */ var operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null); /** Possible global object */ var thisBinding = this; /** Browser user agent string */ var userAgent = nav.userAgent || ''; /*--------------------------------------------------------------------------*/ /** * Capitalizes a string value. * * @private * @param {String} string The string to capitalize. * @returns {String} The capitalized string. */ function capitalize(string) { string = String(string); return string.charAt(0).toUpperCase() + string.slice(1); } /** * An iteration utility for arrays and objects. * * @private * @param {Array|Object} object The object to iterate over. * @param {Function} callback The function called per iteration. */ function each(object, callback) { var index = -1, length = object.length; if (length == length >>> 0) { while (++index < length) { callback(object[index], index, object); } } else { forOwn(object, callback); } } /** * Trim and conditionally capitalize string values. * * @private * @param {String} string The string to format. * @returns {String} The formatted string. */ function format(string) { string = trim(string); return /^(?:webOS|i(?:OS|P))/.test(string) ? string : capitalize(string); } /** * Iterates over an object's own properties, executing the `callback` for each. * * @private * @param {Object} object The object to iterate over. * @param {Function} callback The function executed per own property. */ function forOwn(object, callback) { for (var key in object) { hasKey(object, key) && callback(object[key], key, object); } } /** * Gets the internal [[Class]] of a value. * * @private * @param {Mixed} value The value. * @returns {String} The [[Class]]. */ function getClassOf(value) { return value == null ? capitalize(value) : toString.call(value).slice(8, -1); } /** * Checks if an object has the specified key as a direct property. * * @private * @param {Object} object The object to check. * @param {String} key The key to check for. * @returns {Boolean} Returns `true` if key is a direct property, else `false`. */ function hasKey() { // lazy define for others (not as accurate) hasKey = function(object, key) { var parent = object != null && (object.constructor || Object).prototype; return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); }; // for modern browsers if (getClassOf(hasOwnProperty) == 'Function') { hasKey = function(object, key) { return object != null && hasOwnProperty.call(object, key); }; } // for Safari 2 else if ({}.__proto__ == Object.prototype) { hasKey = function(object, key) { var result = false; if (object != null) { object = Object(object); object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; } return result; }; } return hasKey.apply(this, arguments); } /** * Host objects can return type values that are different from their actual * data type. The objects we are concerned with usually return non-primitive * types of object, function, or unknown. * * @private * @param {Mixed} object The owner of the property. * @param {String} property The property to check. * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`. */ function isHostType(object, property) { var type = object != null ? typeof object[property] : 'number'; return !/^(?:boolean|number|string|undefined)$/.test(type) && (type == 'object' ? !!object[property] : true); } /** * Prepares a string for use in a RegExp constructor by making hyphens and * spaces optional. * * @private * @param {String} string The string to qualify. * @returns {String} The qualified string. */ function qualify(string) { return String(string).replace(/([ -])(?!$)/g, '$1?'); } /** * A bare-bones` Array#reduce` like utility function. * * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function called per iteration. * @param {Mixed} accumulator Initial value of the accumulator. * @returns {Mixed} The accumulator. */ function reduce(array, callback) { var accumulator = null; each(array, function(value, index) { accumulator = callback(accumulator, value, index, array); }); return accumulator; } /** * Removes leading and trailing whitespace from a string. * * @private * @param {String} string The string to trim. * @returns {String} The trimmed string. */ function trim(string) { return String(string).replace(/^ +| +$/g, ''); } /*--------------------------------------------------------------------------*/ /** * Creates a new platform object. * * @memberOf platform * @param {String} [ua = navigator.userAgent] The user agent string. * @returns {Object} A platform object. */ function parse(ua) { ua || (ua = userAgent); /** Temporary variable used over the script's lifetime */ var data; /** The CPU architecture */ var arch = ua; /** Platform description array */ var description = []; /** Platform alpha/beta indicator */ var prerelease = null; /** A flag to indicate that environment features should be used to resolve the platform */ var useFeatures = ua == userAgent; /** The browser/environment version */ var version = useFeatures && opera && typeof opera.version == 'function' && opera.version(); /* Detectable layout engines (order is important) */ var layout = getLayout([ { 'label': 'WebKit', 'pattern': 'AppleWebKit' }, 'iCab', 'Presto', 'NetFront', 'Tasman', 'Trident', 'KHTML', 'Gecko' ]); /* Detectable browser names (order is important) */ var name = getName([ 'Adobe AIR', 'Arora', 'Avant Browser', 'Camino', 'Epiphany', 'Fennec', 'Flock', 'Galeon', 'GreenBrowser', 'iCab', 'Iceweasel', 'Iron', 'K-Meleon', 'Konqueror', 'Lunascape', 'Maxthon', 'Midori', 'Nook Browser', 'PhantomJS', 'Raven', 'Rekonq', 'RockMelt', 'SeaMonkey', { 'label': 'Silk', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, 'Sleipnir', 'SlimBrowser', 'Sunrise', 'Swiftfox', 'WebPositive', 'Opera Mini', 'Opera', 'Chrome', { 'label': 'Chrome Mobile', 'pattern': '(?:CriOS|CrMo)' }, { 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' }, { 'label': 'IE', 'pattern': 'MSIE' }, 'Safari' ]); /* Detectable products (order is important) */ var product = getProduct([ 'BlackBerry', { 'label': 'Galaxy S', 'pattern': 'GT-I9000' }, { 'label': 'Galaxy S2', 'pattern': 'GT-I9100' }, 'Google TV', 'iPad', 'iPod', 'iPhone', 'Kindle', { 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, 'Nook', 'PlayBook', 'PlayStation Vita', 'TouchPad', 'Transformer', 'Xoom' ]); /* Detectable manufacturers */ var manufacturer = getManufacturer({ 'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 }, 'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 }, 'Asus': { 'Transformer': 1 }, 'Barnes & Noble': { 'Nook': 1 }, 'BlackBerry': { 'PlayBook': 1 }, 'Google': { 'Google TV': 1 }, 'HP': { 'TouchPad': 1 }, 'LG': { }, 'Motorola': { 'Xoom': 1 }, 'Nokia': { }, 'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1 }, 'Sony': { 'PlayStation Vita': 1 } }); /* Detectable OSes (order is important) */ var os = getOS([ 'Android', 'CentOS', 'Debian', 'Fedora', 'FreeBSD', 'Gentoo', 'Haiku', 'Kubuntu', 'Linux Mint', 'Red Hat', 'SuSE', 'Ubuntu', 'Xubuntu', 'Cygwin', 'Symbian OS', 'hpwOS', 'webOS ', 'webOS', 'Tablet OS', 'Linux', 'Mac OS X', 'Macintosh', 'Mac', 'Windows 98;', 'Windows ' ]); /*------------------------------------------------------------------------*/ /** * Picks the layout engine from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected layout engine. */ function getLayout(guesses) { return reduce(guesses, function(result, guess) { return result || RegExp('\\b' + ( guess.pattern || qualify(guess) ) + '\\b', 'i').exec(ua) && (guess.label || guess); }); } /** * Picks the manufacturer from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected manufacturer. */ function getManufacturer(guesses) { return reduce(guesses, function(result, value, key) { // lookup the manufacturer by product or scan the UA for the manufacturer return result || ( value[product] || value[0/*Opera 9.25 fix*/, /^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] || RegExp('\\b' + (key.pattern || qualify(key)) + '(?:\\b|\\w*\\d)', 'i').exec(ua) ) && (key.label || key); }); } /** * Picks the browser name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected browser name. */ function getName(guesses) { return reduce(guesses, function(result, guess) { return result || RegExp('\\b' + ( guess.pattern || qualify(guess) ) + '\\b', 'i').exec(ua) && (guess.label || guess); }); } /** * Picks the OS name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected OS name. */ function getOS(guesses) { return reduce(guesses, function(result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) { // platform tokens defined at // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx // http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx data = { '6.2': '8', '6.1': 'Server 2008 R2 / 7', '6.0': 'Server 2008 / Vista', '5.2': 'Server 2003 / XP 64-bit', '5.1': 'XP', '5.01': '2000 SP1', '5.0': '2000', '4.0': 'NT', '4.90': 'ME' }; // detect Windows version from platform tokens if (/^Win/i.test(result) && (data = data[0/*Opera 9.25 fix*/, /[\d.]+$/.exec(result)])) { result = 'Windows ' + data; } // correct character case and cleanup result = format(String(result) .replace(RegExp(pattern, 'i'), guess.label || guess) .replace(/ ce$/i, ' CE') .replace(/hpw/i, 'web') .replace(/Macintosh/, 'Mac OS') .replace(/_PowerPC/i, ' OS') .replace(/(OS X) [^ \d]+/i, '$1') .replace(/\/(\d)/, ' $1') .replace(/_/g, '.') .replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '') .replace(/x86\.64/gi, 'x86_64') .split(' on ')[0]); } return result; }); } /** * Picks the product name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected product name. */ function getProduct(guesses) { return reduce(guesses, function(result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) || RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua) )) { // split by forward slash and append product version if needed if ((result = String(guess.label || result).split('/'))[1] && !/[\d.]+/.test(result[0])) { result[0] += ' ' + result[1]; } // correct character case and cleanup guess = guess.label || guess; result = format(result[0] .replace(RegExp(pattern, 'i'), guess) .replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ') .replace(RegExp('(' + guess + ')(\\w)', 'i'), '$1 $2')); } return result; }); } /** * Resolves the version using an array of UA patterns. * * @private * @param {Array} patterns An array of UA patterns. * @returns {String|Null} The detected version. */ function getVersion(patterns) { return reduce(patterns, function(result, pattern) { return result || (RegExp(pattern + '(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null; }); } /*------------------------------------------------------------------------*/ /** * Returns `platform.description` when the platform object is coerced to a string. * * @name toString * @memberOf platform * @returns {String} Returns `platform.description` if available, else an empty string. */ function toStringPlatform() { return this.description || ''; } /*------------------------------------------------------------------------*/ // convert layout to an array so we can add extra details layout && (layout = [layout]); // detect product names that contain their manufacturer's name if (manufacturer && !product) { product = getProduct([manufacturer]); } // clean up Google TV if ((data = /Google TV/.exec(product))) { product = data[0]; } // detect simulators if (/\bSimulator\b/i.test(ua)) { product = (product ? product + ' ' : '') + 'Simulator'; } // detect iOS if (/^iP/.test(product)) { name || (name = 'Safari'); os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua)) ? ' ' + data[1].replace(/_/g, '.') : ''); } // detect Kubuntu else if (name == 'Konqueror' && !/buntu/i.test(os)) { os = 'Kubuntu'; } // detect Android browsers else if (manufacturer && manufacturer != 'Google' && /Chrome|Vita/.test(name + ';' + product)) { name = 'Android Browser'; os = /Android/.test(os) ? os : 'Android'; } // detect false positives for Firefox/Safari else if (!name || (data = !/\bMinefield\b/i.test(ua) && /Firefox|Safari/.exec(name))) { // escape the `/` for Firefox 1 if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) { // clear name of false positives name = null; } // reassign a generic name if ((data = product || manufacturer || os) && (product || manufacturer || /Android|Symbian OS|Tablet OS|webOS/.test(os))) { name = /[a-z]+(?: Hat)?/i.exec(/Android/.test(os) ? os : data) + ' Browser'; } } // detect non-Opera versions (order is important) if (!version) { version = getVersion([ '(?:Cloud9|CriOS|CrMo|Opera ?Mini|Raven|Silk(?!/[\\d.]+$))', 'Version', qualify(name), '(?:Firefox|Minefield|NetFront)' ]); } // detect stubborn layout engines if (layout == 'iCab' && parseFloat(version) > 3) { layout = ['WebKit']; } else if (data = /Opera/.test(name) && 'Presto' || /\b(?:Midori|Nook|Safari)\b/i.test(ua) && 'WebKit' || !layout && /\bMSIE\b/i.test(ua) && (/^Mac/.test(os) ? 'Tasman' : 'Trident')) { layout = [data]; } // leverage environment features if (useFeatures) { // detect server-side environments // Rhino has a global function while others have a global object if (isHostType(window, 'global')) { if (java) { data = java.lang.System; arch = data.getProperty('os.arch'); os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version'); } if (typeof exports == 'object' && exports) { // if `thisBinding` is the [ModuleScope] if (thisBinding == oldWin && typeof system == 'object' && (data = [system])[0]) { os || (os = data[0].os || null); try { data[1] = require('ringo/engine').version; version = data[1].join('.'); name = 'RingoJS'; } catch(e) { if (data[0].global == freeGlobal) { name = 'Narwhal'; } } } else if (typeof process == 'object' && (data = process)) { name = 'Node.js'; arch = data.arch; os = data.platform; version = /[\d.]+/.exec(data.version)[0]; } } else if (getClassOf(window.environment) == 'Environment') { name = 'Rhino'; } } // detect Adobe AIR else if (getClassOf(data = window.runtime) == 'ScriptBridgingProxyObject') { name = 'Adobe AIR'; os = data.flash.system.Capabilities.os; } // detect PhantomJS else if (getClassOf(data = window.phantom) == 'RuntimeObject') { name = 'PhantomJS'; version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch); } // detect IE compatibility modes else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) { // we're in compatibility mode when the Trident version + 4 doesn't // equal the document mode version = [version, doc.documentMode]; if ((data = +data[1] + 4) != version[1]) { description.push('IE ' + version[1] + ' mode'); layout[1] = ''; version[1] = data; } version = name == 'IE' ? String(version[1].toFixed(1)) : version[0]; } os = os && format(os); } // detect prerelease phases if (version && (data = /(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) || /(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) || /\bMinefield\b/i.test(ua) && 'a')) { prerelease = /b/i.test(data) ? 'beta' : 'alpha'; version = version.replace(RegExp(data + '\\+?$'), '') + (prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || ''); } // rename code name "Fennec" if (name == 'Fennec') { name = 'Firefox Mobile'; } // obscure Maxthon's unreliable version else if (name == 'Maxthon' && version) { version = version.replace(/\.[\d.]+/, '.x'); } // detect Silk desktop/accelerated modes else if (name == 'Silk') { if (!/Mobi/i.test(ua)) { os = 'Android'; description.unshift('desktop mode'); } if (/Accelerated *= *true/i.test(ua)) { description.unshift('accelerated'); } } // detect Windows Phone desktop mode else if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) { name += ' Mobile'; os = 'Windows Phone OS ' + data + '.x'; description.unshift('desktop mode'); } // add mobile postfix else if ((name == 'IE' || name && !product && !/Browser|Mobi/.test(name)) && (os == 'Windows CE' || /Mobi/i.test(ua))) { name += ' Mobile'; } // detect IE platform preview else if (name == 'IE' && useFeatures && typeof external == 'object' && !external) { description.unshift('platform preview'); } // detect BlackBerry OS version // http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp else if (/BlackBerry/.test(product) && (data = (RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] || version)) { os = 'Device Software ' + data; version = null; } // detect Opera identifying/masking itself as another browser // http://www.opera.com/support/kb/view/843/ else if (this != forOwn && ( (useFeatures && opera) || (/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) || (name == 'Firefox' && /OS X (?:\d+\.){2,}/.test(os)) || (name == 'IE' && ( (os && !/^Win/.test(os) && version > 5.5) || /Windows XP/.test(os) && version > 8 || version == 8 && !/Trident/.test(ua) )) ) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) { // when "indentifying", the UA contains both Opera and the other browser's name data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : ''); if (reOpera.test(name)) { if (/IE/.test(data) && os == 'Mac OS') { os = null; } data = 'identify' + data; } // when "masking", the UA contains only the other browser's name else { data = 'mask' + data; if (operaClass) { name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2')); } else { name = 'Opera'; } if (/IE/.test(data)) { os = null; } if (!useFeatures) { version = null; } } layout = ['Presto']; description.push(data); } // detect WebKit Nightly and approximate Chrome/Safari versions if ((data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) { // correct build for numeric comparison // (e.g. "532.5" becomes "532.05") data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data]; // nightly builds are postfixed with a `+` if (name == 'Safari' && data[1].slice(-1) == '+') { name = 'WebKit Nightly'; prerelease = 'alpha'; version = data[1].slice(0, -1); } // clear incorrect browser versions else if (version == data[1] || version == (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1]) { version = null; } // use the full Chrome version when available data = [data[0], (/\bChrome\/([\d.]+)/i.exec(ua) || 0)[1]]; // detect JavaScriptCore // http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi if (!useFeatures || (/internal|\n/i.test(toString.toString()) && !data[1])) { layout[1] = 'like Safari'; data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : '5'); } else { layout[1] = 'like Chrome'; data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : '21'); } // add the postfix of ".x" or "+" for approximate versions layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+'); // obscure version for some Safari 1-2 releases if (name == 'Safari' && (!version || parseInt(version) > 45)) { version = data; } } // detect Opera desktop modes if (name == 'Opera' && (data = /(?:zbov|zvav)$/.exec(os))) { name += ' '; description.unshift('desktop mode'); if (data == 'zvav') { name += 'Mini'; version = null; } else { name += 'Mobile'; } } // detect Chrome desktop mode else if (name == 'Safari' && /Chrome/.exec(layout[1])) { description.unshift('desktop mode'); name = 'Chrome Mobile'; version = null; if (/Mac OS X/.test(os)) { manufacturer = 'Apple'; os = 'iOS 4.3+'; } else { os = null; } } // strip incorrect OS versions if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 && ua.indexOf('/' + data + '-') > -1) { os = trim(os.replace(data, '')); } // add layout engine if (layout && !/Avant|Nook/.test(name) && ( /Browser|Lunascape|Maxthon/.test(name) || /^(?:Adobe|Arora|Midori|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(name) && layout[1])) { // don't add layout details to description if they are falsey (data = layout[layout.length - 1]) && description.push(data); } // combine contextual information if (description.length) { description = ['(' + description.join('; ') + ')']; } // append manufacturer if (manufacturer && product && product.indexOf(manufacturer) < 0) { description.push('on ' + manufacturer); } // append product if (product) { description.push((/^on /.test(description[description.length -1]) ? '' : 'on ') + product); } // parse OS into an object if (os) { data = / ([\d.+]+)$/.exec(os); os = { 'architecture': 32, 'family': data ? os.replace(data[0], '') : os, 'version': data ? data[1] : null, 'toString': function() { var version = this.version; return this.family + (version ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : ''); } }; } // add browser/OS architecture if ((data = / (?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) { if (os) { os.architecture = 64; os.family = os.family.replace(data, ''); } if (name && (/WOW64/i.test(ua) || (useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform)))) { description.unshift('32-bit'); } } ua || (ua = null); /*------------------------------------------------------------------------*/ /** * The platform object. * * @name platform * @type Object */ return { /** * The browser/environment version. * * @memberOf platform * @type String|Null */ 'version': name && version && (description.unshift(version), version), /** * The name of the browser/environment. * * @memberOf platform * @type String|Null */ 'name': name && (description.unshift(name), name), /** * The name of the operating system. * * @memberOf platform * @type Object */ 'os': os ? (name && !(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product)) && description.push(product ? '(' + os + ')' : 'on ' + os), os) : { /** * The CPU architecture the OS is built for. * * @memberOf platform.os * @type String|Null */ 'architecture': null, /** * The family of the OS. * * @memberOf platform.os * @type String|Null */ 'family': null, /** * The version of the OS. * * @memberOf platform.os * @type String|Null */ 'version': null, /** * Returns the OS string. * * @memberOf platform.os * @returns {String} The OS string. */ 'toString': function() { return 'null'; } }, /** * The platform description. * * @memberOf platform * @type String|Null */ 'description': description.length ? description.join(' ') : ua, /** * The name of the browser layout engine. * * @memberOf platform * @type String|Null */ 'layout': layout && layout[0], /** * The name of the product's manufacturer. * * @memberOf platform * @type String|Null */ 'manufacturer': manufacturer, /** * The alpha/beta release indicator. * * @memberOf platform * @type String|Null */ 'prerelease': prerelease, /** * The name of the product hosting the browser. * * @memberOf platform * @type String|Null */ 'product': product, /** * The browser's user agent string. * * @memberOf platform * @type String|Null */ 'ua': ua, // parses a user agent string into a platform object 'parse': parse, // returns the platform description 'toString': toStringPlatform }; } /*--------------------------------------------------------------------------*/ // expose platform // some AMD build optimizers, like r.js, check for specific condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // define as an anonymous module so, through path mapping, it can be aliased define(function() { return parse(); }); } // check for `exports` after `define` in case a build optimizer adds an `exports` object else if (freeExports) { // in Narwhal, Node.js, or RingoJS forOwn(parse(), function(value, key) { freeExports[key] = value; }); } // in a browser or Rhino else { // use square bracket notation so Closure Compiler won't munge `platform` // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export window['platform'] = parse(); } }(this)); var buster = this.buster = this.buster || {}; buster._ = buster.lodash = this._; buster.when = this.when; buster.async = this.async; buster.platform = this.platform; this.define = (function () { function resolve(ns) { var pieces = ns.replace(/^buster-test\//, "").replace(/^buster-/, "").replace(/-(.)/g, function (m, l) { return l.toUpperCase(); }).split("/"); return { property: pieces.pop(), object: buster._.reduce(pieces, function (ctx, name) { if (!ctx[name]) { ctx[name] = {}; } return ctx[name]; }, buster) }; } return function (id, dependencies, factory) { if (arguments.length === 2) { factory = dependencies; dependencies = []; } var deps = [], dep; for (var j, i = 0, l = dependencies.length; i < l; ++i) { dep = resolve(dependencies[i]); if (!dep.object[dep.property]) { throw new Error(id + " depends on unknown module " + dep.property); } deps.push(dep.object[dep.property]); } dep = resolve(id); dep.object[dep.property] = factory.apply(this, deps); }; }()); this.define.amd = true; ((typeof define === "function" && define.amd && function (m) { define("bane", m); }) || (typeof module === "object" && function (m) { module.exports = m(); }) || function (m) { this.bane = m(); } )(function () { "use strict"; var slice = Array.prototype.slice; function handleError(event, error, errbacks) { var i, l = errbacks.length; if (l > 0) { for (i = 0; i < l; ++i) { errbacks[i](event, error); } return; } setTimeout(function () { error.message = event + " listener threw error: " + error.message; throw error; }, 0); } function assertFunction(fn) { if (typeof fn !== "function") { throw new TypeError("Listener is not function"); } return fn; } function supervisors(object) { if (!object.supervisors) { object.supervisors = []; } return object.supervisors; } function listeners(object, event) { if (!object.listeners) { object.listeners = {}; } if (event && !object.listeners[event]) { object.listeners[event] = []; } return event ? object.listeners[event] : object.listeners; } function errbacks(object) { if (!object.errbacks) { object.errbacks = []; } return object.errbacks; } /** * @signature var emitter = bane.createEmitter([object]); * * Create a new event emitter. If an object is passed, it will be modified * by adding the event emitter methods (see below). */ function createEventEmitter(object) { object = object || {}; function notifyListener(event, listener, args) { try { listener.listener.apply(listener.thisp || object, args); } catch (e) { handleError(event, e, errbacks(object)); } } object.on = function (event, listener, thisp) { if (typeof event === "function") { return supervisors(this).push({ listener: event, thisp: listener }); } listeners(this, event).push({ listener: assertFunction(listener), thisp: thisp }); }; object.off = function (event, listener) { var fns, events, i, l; if (!event) { fns = supervisors(this); fns.splice(0, fns.length); events = listeners(this); for (i in events) { if (events.hasOwnProperty(i)) { fns = listeners(this, i); fns.splice(0, fns.length); } } fns = errbacks(this); fns.splice(0, fns.length); return; } if (typeof event === "function") { fns = supervisors(this); listener = event; } else { fns = listeners(this, event); } if (!listener) { fns.splice(0, fns.length); return; } for (i = 0, l = fns.length; i < l; ++i) { if (fns[i].listener === listener) { fns.splice(i, 1); return; } } }; object.once = function (event, listener, thisp) { var wrapper = function () { object.off(event, wrapper); listener.apply(this, arguments); }; object.on(event, wrapper, thisp); }; object.bind = function (object, events) { var prop, i, l; if (!events) { for (prop in object) { if (typeof object[prop] === "function") { this.on(prop, object[prop], object); } } } else { for (i = 0, l = events.length; i < l; ++i) { if (typeof object[events[i]] === "function") { this.on(events[i], object[events[i]], object); } else { throw new Error("No such method " + events[i]); } } } return object; }; object.emit = function (event) { var toNotify = supervisors(this); var args = slice.call(arguments), i, l; for (i = 0, l = toNotify.length; i < l; ++i) { notifyListener(event, toNotify[i], args); } toNotify = listeners(this, event).slice(); args = slice.call(arguments, 1); for (i = 0, l = toNotify.length; i < l; ++i) { notifyListener(event, toNotify[i], args); } }; object.errback = function (listener) { if (!this.errbacks) { this.errbacks = []; } this.errbacks.push(assertFunction(listener)); }; return object; } return { createEventEmitter: createEventEmitter }; }); ((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) || (typeof module === "object" && function (m) { module.exports = m(); }) || // Node function (m) { this.samsam = m(); } // Browser globals )(function () { var o = Object.prototype; var div = typeof document !== "undefined" && document.createElement("div"); function isNaN(value) { // Unlike global isNaN, this avoids type coercion // typeof check avoids IE host object issues, hat tip to // lodash var val = value; // JsLint thinks value !== value is "weird" return typeof value === "number" && value !== val; } function getClass(value) { // Returns the internal [[Class]] by calling Object.prototype.toString // with the provided value as this. Return value is a string, naming the // internal class, e.g. "Array" return o.toString.call(value).split(/[ \]]/)[1]; } /** * @name samsam.isArguments * @param Object object * * Returns ``true`` if ``object`` is an ``arguments`` object, * ``false`` otherwise. */ function isArguments(object) { if (typeof object !== "object" || typeof object.length !== "number" || getClass(object) === "Array") { return false; } if (typeof object.callee == "function") { return true; } try { object[object.length] = 6; delete object[object.length]; } catch (e) { return true; } return false; } /** * @name samsam.isElement * @param Object object * * Returns ``true`` if ``object`` is a DOM element node. Unlike * Underscore.js/lodash, this function will return ``false`` if ``object`` * is an *element-like* object, i.e. a regular object with a ``nodeType`` * property that holds the value ``1``. */ function isElement(object) { if (!object || object.nodeType !== 1 || !div) { return false; } try { object.appendChild(div); object.removeChild(div); } catch (e) { return false; } return true; } /** * @name samsam.keys * @param Object object * * Return an array of own property names. */ function keys(object) { var ks = [], prop; for (prop in object) { if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); } } return ks; } /** * @name samsam.isDate * @param Object value * * Returns true if the object is a ``Date``, or *date-like*. Duck typing * of date objects work by checking that the object has a ``getTime`` * function whose return value equals the return value from the object's * ``valueOf``. */ function isDate(value) { return typeof value.getTime == "function" && value.getTime() == value.valueOf(); } /** * @name samsam.isNegZero * @param Object value * * Returns ``true`` if ``value`` is ``-0``. */ function isNegZero(value) { return value === 0 && 1 / value === -Infinity; } /** * @name samsam.equal * @param Object obj1 * @param Object obj2 * * Returns ``true`` if two objects are strictly equal. Compared to * ``===`` there are two exceptions: * * - NaN is considered equal to NaN * - -0 and +0 are not considered equal */ function identical(obj1, obj2) { if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) { return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2); } } /** * @name samsam.deepEqual * @param Object obj1 * @param Object obj2 * * Deep equal comparison. Two values are "deep equal" if: * * - They are equal, according to samsam.identical * - They are both date objects representing the same time * - They are both arrays containing elements that are all deepEqual * - They are objects with the same set of properties, and each property * in ``obj1`` is deepEqual to the corresponding property in ``obj2`` * * Supports cyclic objects. */ function deepEqualCyclic(obj1, obj2) { // used for cyclic comparison // contain already visited objects var objects1 = [], objects2 = [], // contain pathes (position in the object structure) // of the already visited objects // indexes same as in objects arrays paths1 = [], paths2 = [], // contains combinations of already compared objects // in the manner: { "$1['ref']$2['ref']": true } compared = {}; /** * used to check, if the value of a property is an object * (cyclic logic is only needed for objects) * only needed for cyclic logic */ function isObject(value) { if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { return true; } return false; } /** * returns the index of the given object in the * given objects array, -1 if not contained * only needed for cyclic logic */ function getIndex(objects, obj) { var i; for (i = 0; i < objects.length; i++) { if (objects[i] === obj) { return i; } } return -1; } // does the recursion for the deep equal check return (function deepEqual(obj1, obj2, path1, path2) { var type1 = typeof obj1; var type2 = typeof obj2; // == null also matches undefined if (obj1 === obj2 || isNaN(obj1) || isNaN(obj2) || obj1 == null || obj2 == null || type1 !== "object" || type2 !== "object") { return identical(obj1, obj2); } // Elements are only equal if identical(expected, actual) if (isElement(obj1) || isElement(obj2)) { return false; } var isDate1 = isDate(obj1), isDate2 = isDate(obj2); if (isDate1 || isDate2) { if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) { return false; } } if (obj1 instanceof RegExp && obj2 instanceof RegExp) { if (obj1.toString() !== obj2.toString()) { return false; } } var class1 = getClass(obj1); var class2 = getClass(obj2); var keys1 = keys(obj1); var keys2 = keys(obj2); if (isArguments(obj1) || isArguments(obj2)) { if (obj1.length !== obj2.length) { return false; } } else { if (type1 !== type2 || class1 !== class2 || keys1.length !== keys2.length) { return false; } } var key, i, l, // following vars are used for the cyclic logic value1, value2, isObject1, isObject2, index1, index2, newPath1, newPath2; for (i = 0, l = keys1.length; i < l; i++) { key = keys1[i]; if (!o.hasOwnProperty.call(obj2, key)) { return false; } // Start of the cyclic logic value1 = obj1[key]; value2 = obj2[key]; isObject1 = isObject(value1); isObject2 = isObject(value2); // determine, if the objects were already visited // (it's faster to check for isObject first, than to // get -1 from getIndex for non objects) index1 = isObject1 ? getIndex(objects1, value1) : -1; index2 = isObject2 ? getIndex(objects2, value2) : -1; // determine the new pathes of the objects // - for non cyclic objects the current path will be extended // by current property name // - for cyclic objects the stored path is taken newPath1 = index1 !== -1 ? paths1[index1] : path1 + '[' + JSON.stringify(key) + ']'; newPath2 = index2 !== -1 ? paths2[index2] : path2 + '[' + JSON.stringify(key) + ']'; // stop recursion if current objects are already compared if (compared[newPath1 + newPath2]) { return true; } // remember the current objects and their pathes if (index1 === -1 && isObject1) { objects1.push(value1); paths1.push(newPath1); } if (index2 === -1 && isObject2) { objects2.push(value2); paths2.push(newPath2); } // remember that the current objects are already compared if (isObject1 && isObject2) { compared[newPath1 + newPath2] = true; } // End of cyclic logic // neither value1 nor value2 is a cycle // continue with next level if (!deepEqual(value1, value2, newPath1, newPath2)) { return false; } } return true; }(obj1, obj2, '$1', '$2')); } var match; function arrayContains(array, subset) { var i, l, j, k; for (i = 0, l = array.length; i < l; ++i) { if (match(array[i], subset[0])) { for (j = 0, k = subset.length; j < k; ++j) { if (!match(array[i + j], subset[j])) { return false; } } return true; } } return false; } /** * @name samsam.match * @param Object object * @param Object matcher * * Compare arbitrary value ``object`` with matcher. */ match = function match(object, matcher) { if (matcher && typeof matcher.test === "function") { return matcher.test(object); } if (typeof matcher === "function") { return matcher(object) === true; } if (typeof matcher === "string") { matcher = matcher.toLowerCase(); var notNull = typeof object === "string" || !!object; return notNull && (String(object)).toLowerCase().indexOf(matcher) >= 0; } if (typeof matcher === "number") { return matcher === object; } if (typeof matcher === "boolean") { return matcher === object; } if (getClass(object) === "Array" && getClass(matcher) === "Array") { return arrayContains(object, matcher); } if (matcher && typeof matcher === "object") { var prop; for (prop in matcher) { if (!match(object[prop], matcher[prop])) { return false; } } return true; } throw new Error("Matcher was not a string, a number, a " + "function, a boolean or an object"); }; return { isArguments: isArguments, isElement: isElement, isDate: isDate, isNegZero: isNegZero, identical: identical, deepEqual: deepEqualCyclic, match: match }; }); ((typeof define === "function" && define.amd && function (m) { define("evented-logger", ["lodash", "bane"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("lodash"), require("bane")); }) || function (m) { this.eventedLogger = m(this._, this.bane); } )(function (_, bane) { "use strict"; function formatMessage(logger, message) { if (!logger.logFunctions && typeof message === "function") { return logger.format(message()); } return logger.format(message); } function createLogger(name, level) { return function () { if (level > _.indexOf(this.levels, this.level)) { return; } var self = this; var message = _.reduce(arguments, function (memo, arg) { return memo.concat(formatMessage(self, arg)); }, []).join(" "); this.emit("log", { message: message, level: this.levels[level] }); }; } function Logger(opt) { var logger = this; logger.levels = opt.levels || ["error", "warn", "log", "debug"]; logger.level = opt.level || logger.levels[logger.levels.length - 1]; _.each(logger.levels, function (level, i) { logger[level] = createLogger(level, i); }); if (opt.formatter) { logger.format = opt.formatter; } logger.logFunctions = !!opt.logFunctions; } Logger.prototype = bane.createEventEmitter({ create: function (opt) { return new Logger(opt || {}); }, format: function (obj) { if (typeof obj !== "object") { return String(obj); } try { return JSON.stringify(obj); } catch (e) { return String(obj); } } }); return Logger.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("referee", ["lodash", "samsam", "bane"], m); }) || (typeof module === "object" && function (m) { module.exports = m(require("lodash"), require("samsam"), require("bane")); }) || function (m) { this.referee = m(this._, this.samsam, this.bane); } )(function (_, samsam, bane) { "use strict"; var toString = Object.prototype.toString; var slice = Array.prototype.slice; var assert, refute, referee = bane.createEventEmitter(); referee.countAssertion = function countAssertion() { if (typeof referee.count !== "number") { referee.count = 0; } referee.count += 1; }; function interpolate(string, prop, value) { return string.replace(new RegExp("\\$\\{" + prop + "\\}", "g"), value); } // Interpolate positional arguments. Replaces occurences of ${<index>} in // the string with the corresponding entry in values[<index>] function interpolatePosArg(message, values) { return _.reduce(values, function (msg, value, index) { return interpolate(msg, index, referee.format(value)); }, message); } function interpolateProperties(message, properties) { return _.reduce(_.keys(properties), function (msg, name) { return interpolate(msg, name, referee.format(properties[name])); }, message || ""); } // Fail an assertion. Interpolates message before calling referee.fail function fail(type, assertion, msg) { delete this.fail; var message = interpolateProperties(interpolatePosArg( referee[type][assertion][msg] || msg, [].slice.call(arguments, 3) ), this); referee.fail("[" + type + "." + assertion + "] " + message); } // Internal helper. Used throughout to fail assertions if they receive // too few arguments. The name is provided for a helpful error message. function assertArgNum(name, args, num) { if (args.length < num) { referee.fail("[" + name + "] Expected to receive at least " + num + " argument" + (num > 1 ? "s" : "")); return false; } return true; } // Internal helper. Not the most elegant of functions, but it takes // care of all the nitty-gritty of assertion functions: counting, // verifying parameter count, interpolating messages with actual // values and so on. function defineAssertion(type, name, func, minArgs, messageValues) { referee[type][name] = function () { referee.countAssertion(); var fullName = type + "." + name, failed = false; if (!assertArgNum(fullName, arguments, minArgs || func.length)) { return; } var ctx = { fail: function () { failed = true; var failArgs = [type, name].concat(slice.call(arguments)); fail.apply(this, failArgs); return true; } }; var args = slice.call(arguments, 0); if (typeof messageValues === "function") { args = messageValues.apply(this, args); } if (!func.apply(ctx, arguments)) { return fail.apply(ctx, [type, name, "message"].concat(args)); } if (!failed) { referee.emit.apply(referee, ["pass", fullName].concat(args)); } }; } referee.add = function (name, opt) { var refuteArgs; if (opt.refute) { refuteArgs = opt.refute.length; } else { refuteArgs = opt.assert.length; opt.refute = function () { return !opt.assert.apply(this, arguments); }; } var values = opt.values; defineAssertion("assert", name, opt.assert, opt.assert.length, values); defineAssertion("refute", name, opt.refute, refuteArgs, values); assert[name].message = opt.assertMessage; refute[name].message = opt.refuteMessage; if (opt.expectation) { if (referee.expect && referee.expect.wrapAssertion) { referee.expect.wrapAssertion(name, opt.expectation); } else { assert[name].expectationName = opt.expectation; refute[name].expectationName = opt.expectation; } } }; assert = referee.assert = function assert(actual, message) { referee.countAssertion(); if (!assertArgNum("assert", arguments, 1)) { return; } if (!actual) { var v = referee.format(actual); referee.fail(message || "[assert] Expected " + v + " to be truthy"); } else { referee.emit("pass", "assert", message || "", actual); } }; assert.toString = function () { return "referee.assert()"; }; refute = referee.refute = function (actual, message) { referee.countAssertion(); if (!assertArgNum("refute", arguments, 1)) { return; } if (actual) { var v = referee.format(actual); referee.fail(message || "[refute] Expected " + v + " to be falsy"); } else { referee.emit("pass", "refute", message || "", actual); } }; assert.message = "[assert] Expected ${0} to be truthy"; referee.count = 0; referee.fail = function (message) { var exception = new Error(message); exception.name = "AssertionError"; try { throw exception; } catch (e) { referee.emit("failure", e); } if (typeof referee.throwOnFailure !== "boolean" || referee.throwOnFailure) { throw exception; } }; referee.format = function (object) { return String(object); }; function msg(message) { if (!message) { return ""; } return message + (/[.:!?]$/.test(message) ? " " : ": "); } referee.prepareMessage = msg; function actualAndExpectedMessageValues(actual, expected, message) { return [actual, expected, msg(message)]; } function actualMessageValues(actual, message) { return [actual, msg(message)]; } function actualAndTypeOfMessageValues(actual, message) { return [actual, typeof actual, msg(message)]; } referee.add("same", { assert: function (actual, expected) { return samsam.identical(actual, expected); }, refute: function (actual, expected) { return !samsam.identical(actual, expected); }, assertMessage: "${2}${0} expected to be the same object as ${1}", refuteMessage: "${2}${0} expected not to be the same object as ${1}", expectation: "toBe", values: actualAndExpectedMessageValues }); // Extract/replace with separate module that does a more detailed // visualization of multi-line strings function multiLineStringDiff(actual, expected, message) { if (actual === expected) { return true; } var heading = assert.equals.multiLineStringHeading; message = interpolatePosArg(heading, [message]); var actualLines = actual.split("\n"); var expectedLines = expected.split("\n"); var lineCount = Math.max(expectedLines.length, actualLines.length); var i, lines = []; for (i = 0; i < lineCount; ++i) { if (expectedLines[i] !== actualLines[i]) { lines.push("line " + (i + 1) + ": " + (expectedLines[i] || "") + "\nwas: " + (actualLines[i] || "")); } } referee.fail("[assert.equals] " + message + lines.join("\n\n")); return false; } referee.add("equals", { // Uses arguments[2] because the function's .length is used to determine // the minimum required number of arguments. assert: function (actual, expected) { if (typeof actual === "string" && typeof expected === "string" && (actual.indexOf("\n") >= 0 || expected.indexOf("\n") >= 0)) { var message = msg(arguments[2]); return multiLineStringDiff(actual, expected, message); } return samsam.deepEqual(actual, expected); }, refute: function (actual, expected) { return !samsam.deepEqual(actual, expected); }, assertMessage: "${2}${0} expected to be equal to ${1}", refuteMessage: "${2}${0} expected not to be equal to ${1}", expectation: "toEqual", values: actualAndExpectedMessageValues }); assert.equals.multiLineStringHeading = "${0}Expected multi-line strings " + "to be equal:\n"; referee.add("greater", { assert: function (actual, expected) { return actual > expected; }, assertMessage: "${2}Expected ${0} to be greater than ${1}", refuteMessage: "${2}Expected ${0} to be less than or equal to ${1}", expectation: "toBeGreaterThan", values: actualAndExpectedMessageValues }); referee.add("less", { assert: function (actual, expected) { return actual < expected; }, assertMessage: "${2}Expected ${0} to be less than ${1}", refuteMessage: "${2}Expected ${0} to be greater than or equal to ${1}", expectation: "toBeLessThan", values: actualAndExpectedMessageValues }); referee.add("defined", { assert: function (actual) { return typeof actual !== "undefined"; }, assertMessage: "${2}Expected to be defined", refuteMessage: "${2}Expected ${0} (${1}) not to be defined", expectation: "toBeDefined", values: actualAndTypeOfMessageValues }); referee.add("isNull", { assert: function (actual) { return actual === null; }, assertMessage: "${1}Expected ${0} to be null", refuteMessage: "${1}Expected not to be null", expectation: "toBeNull", values: actualMessageValues }); referee.match = function (actual, matcher) { try { return samsam.match(actual, matcher); } catch (e) { throw new Error("Matcher (" + referee.format(matcher) + ") was not a string, a number, a function, " + "a boolean or an object"); } }; referee.add("match", { assert: function (actual, matcher) { var passed; try { passed = referee.match(actual, matcher); } catch (e) { // Uses arguments[2] because the function's .length is used // to determine the minimum required number of arguments. var message = msg(arguments[2]); return this.fail("exceptionMessage", e.message, message); } return passed; }, refute: function (actual, matcher) { var passed; try { passed = referee.match(actual, matcher); } catch (e) { return this.fail("exceptionMessage", e.message); } return !passed; }, assertMessage: "${2}${0} expected to match ${1}", refuteMessage: "${2}${0} expected not to match ${1}", expectation: "toMatch", values: actualAndExpectedMessageValues }); assert.match.exceptionMessage = "${1}${0}"; refute.match.exceptionMessage = "${1}${0}"; referee.add("isObject", { assert: function (actual) { return typeof actual === "object" && !!actual; }, assertMessage: "${2}${0} (${1}) expected to be object and not null", refuteMessage: "${2}${0} expected to be null or not an object", expectation: "toBeObject", values: actualAndTypeOfMessageValues }); referee.add("isFunction", { assert: function (actual) { return typeof actual === "function"; }, assertMessage: "${2}${0} (${1}) expected to be function", refuteMessage: "${2}${0} expected not to be function", expectation: "toBeFunction", values: function (actual) { // Uses arguments[1] because the function's .length is used to // determine the minimum required number of arguments. var message = msg(arguments[1]); return [String(actual).replace("\n", ""), typeof actual, message]; } }); referee.add("isTrue", { assert: function (actual) { return actual === true; }, assertMessage: "${1}Expected ${0} to be true", refuteMessage: "${1}Expected ${0} to not be true", expectation: "toBeTrue", values: actualMessageValues }); referee.add("isFalse", { assert: function (actual) { return actual === false; }, assertMessage: "${1}Expected ${0} to be false", refuteMessage: "${1}Expected ${0} to not be false", expectation: "toBeFalse", values: actualMessageValues }); referee.add("isString", { assert: function (actual) { return typeof actual === "string"; }, assertMessage: "${2}Expected ${0} (${1}) to be string", refuteMessage: "${2}Expected ${0} not to be string", expectation: "toBeString", values: actualAndTypeOfMessageValues }); referee.add("isBoolean", { assert: function (actual) { return typeof actual === "boolean"; }, assertMessage: "${2}Expected ${0} (${1}) to be boolean", refuteMessage: "${2}Expected ${0} not to be boolean", expectation: "toBeBoolean", values: actualAndTypeOfMessageValues }); referee.add("isNumber", { assert: function (actual) { return typeof actual === "number" && !isNaN(actual); }, assertMessage: "${2}Expected ${0} (${1}) to be a non-NaN number", refuteMessage: "${2}Expected ${0} to be NaN or a non-number value", expectation: "toBeNumber", values: actualAndTypeOfMessageValues }); referee.add("isNaN", { assert: function (actual) { return typeof actual === "number" && isNaN(actual); }, assertMessage: "${2}Expected ${0} to be NaN", refuteMessage: "${2}Expected not to be NaN", expectation: "toBeNaN", values: actualAndTypeOfMessageValues }); referee.add("isArray", { assert: function (actual) { return toString.call(actual) === "[object Array]"; }, assertMessage: "${2}Expected ${0} to be array", refuteMessage: "${2}Expected ${0} not to be array", expectation: "toBeArray", values: actualAndTypeOfMessageValues }); function isArrayLike(object) { return _.isArray(object) || (!!object && typeof object.length === "number" && typeof object.splice === "function") || _.isArguments(object); } referee.isArrayLike = isArrayLike; referee.add("isArrayLike", { assert: function (actual) { return isArrayLike(actual); }, assertMessage: "${2}Expected ${0} to be array like", refuteMessage: "${2}Expected ${0} not to be array like", expectation: "toBeArrayLike", values: actualAndTypeOfMessageValues }); function exactKeys(object, keys) { var keyMap = {}; var keyCnt = 0; for (var i=0; i < keys.length; i++) { keyMap[keys[i]] = true; keyCnt += 1; } for (var key in object) { if (object.hasOwnProperty(key)) { if (! keyMap[key]) { return false; } keyCnt -= 1; } } return keyCnt === 0; } referee.add('keys', { assert: function (actual, keys) { return exactKeys(actual, keys); }, assertMessage: "Expected ${0} to have exact keys ${1}!", refuteMessage: "Expected ${0} not to have exact keys ${1}!", expectation: "toHaveKeys" }); function captureException(callback) { try { callback(); } catch (e) { return e; } return null; } referee.captureException = captureException; assert.exception = function (callback, matcher, message) { referee.countAssertion(); if (!assertArgNum("assert.exception", arguments, 1)) { return; } if (!callback) { return; } if (typeof matcher === "string") { message = matcher; matcher = undefined; } var err = captureException(callback); message = msg(message); if (!err) { if (typeof matcher === "object") { return fail.call( {}, "assert", "exception", "typeNoExceptionMessage", message, referee.format(matcher) ); } else { return fail.call({}, "assert", "exception", "message", message); } } if (typeof matcher === "object" && !referee.match(err, matcher)) { return fail.call( {}, "assert", "exception", "typeFailMessage", message, referee.format(matcher), err.name, err.message, err.stack ); } if (typeof matcher === "function" && matcher(err) !== true) { return fail.call({}, "assert", "exception", "matchFailMessage", message, err.name, err.message); } referee.emit("pass", "assert.exception", message, callback, matcher); }; assert.exception.typeNoExceptionMessage = "${0}Expected ${1} but no " + "exception was thrown"; assert.exception.message = "${0}Expected exception"; assert.exception.typeFailMessage = "${0}Expected ${1} but threw ${2} " + "(${3})\n${4}"; assert.exception.matchFailMessage = "${0}Expected thrown ${1} (${2}) to " + "pass matcher function"; assert.exception.expectationName = "toThrow"; refute.exception = function (callback) { referee.countAssertion(); if (!assertArgNum("refute.exception", arguments, 1)) { return; } var err = captureException(callback); if (err) { // Uses arguments[1] because the function's .length is used to // determine the minimum required number of arguments. fail.call({}, "refute", "exception", "message", msg(arguments[1]), err.name, err.message, callback); } else { referee.emit("pass", "refute.exception", callback); } }; refute.exception.message = "${0}Expected not to throw but " + "threw ${1} (${2})"; refute.exception.expectationName = "toThrow"; referee.add("near", { assert: function (actual, expected, delta) { return Math.abs(actual - expected) <= delta; }, assertMessage: "${3}Expected ${0} to be equal to ${1} +/- ${2}", refuteMessage: "${3}Expected ${0} not to be equal to ${1} +/- ${2}", expectation: "toBeNear", values: function (actual, expected, delta, message) { return [actual, expected, delta, msg(message)]; } }); referee.add("hasPrototype", { assert: function (actual, protoObj) { return protoObj.isPrototypeOf(actual); }, assertMessage: "${2}Expected ${0} to have ${1} on its prototype chain", refuteMessage: "${2}Expected ${0} not to have ${1} on its " + "prototype chain", expectation: "toHavePrototype", values: actualAndExpectedMessageValues }); referee.add("contains", { assert: function (haystack, needle) { return _.include(haystack, needle); }, assertMessage: "${2}Expected [${0}] to contain ${1}", refuteMessage: "${2}Expected [${0}] not to contain ${1}", expectation: "toContain", values: actualAndExpectedMessageValues }); referee.add("tagName", { assert: function (element, tagName) { // Uses arguments[2] because the function's .length is used to // determine the minimum required number of arguments. if (!element.tagName) { return this.fail( "noTagNameMessage", tagName, element, msg(arguments[2]) ); } return tagName.toLowerCase && tagName.toLowerCase() === element.tagName.toLowerCase(); }, assertMessage: "${2}Expected tagName to be ${0} but was ${1}", refuteMessage: "${2}Expected tagName not to be ${0}", expectation: "toHaveTagName", values: function (element, tagName, message) { return [tagName, element.tagName, msg(message)]; } }); assert.tagName.noTagNameMessage = "${2}Expected ${1} to have tagName " + "property"; refute.tagName.noTagNameMessage = "${2}Expected ${1} to have tagName " + "property"; referee.add("className", { assert: function (element, name) { if (typeof element.className === "undefined") { // Uses arguments[2] because the function's .length is used to // determine the minimum required number of arguments. return this.fail( "noClassNameMessage", name, element, msg(arguments[2]) ); } var expected = typeof name === "string" ? name.split(" ") : name; var actual = element.className.split(" "); var i, l; for (i = 0, l = expected.length; i < l; i++) { if (!_.include(actual, expected[i])) { return false; } } return true; }, assertMessage: "${2}Expected object's className to include ${0} " + "but was ${1}", refuteMessage: "${2}Expected object's className not to include ${0}", expectation: "toHaveClassName", values: function (element, className, message) { return [className, element.className, msg(message)]; } }); assert.className.noClassNameMessage = "${2}Expected object to have " + "className property"; refute.className.noClassNameMessage = "${2}Expected object to have " + "className property"; if (typeof module !== "undefined" && typeof require === "function") { referee.expect = function () { referee.expect = require("./expect"); return referee.expect.apply(referee, arguments); }; } return referee; }); ((typeof define === "function" && define.amd && function (m) { define("referee/expect", ["lodash", "referee"], m); }) || (typeof module === "object" && function (m) { module.exports = m(require("lodash"), require("./referee")); }) || function (m) { this.referee.expect = m(this._, this.referee); } )(function (_, referee) { var expectation = {}; function F() {} var create = function (object) { F.prototype = object; return new F(); }; var expect = function (actual) { var expectation = _.extend(create(expect.expectation), { actual: actual, assertMode: true }); expectation.not = create(expectation); expectation.not.assertMode = false; return expectation; }; expect.expectation = expectation; expect.wrapAssertion = function (assertion, expectation) { expect.expectation[expectation] = function () { var args = [this.actual].concat(_.toArray(arguments)); var type = this.assertMode ? "assert" : "refute"; var callFunc; if (assertion === "assert") { callFunc = this.assertMode ? referee.assert : referee.refute; } else if (assertion === "refute") { callFunc = this.assertMode ? referee.refute : referee.assert; } else { callFunc = referee[type][assertion]; } try { return callFunc.apply(referee.expect, args); } catch (e) { e.message = (e.message || "").replace( "[" + type + "." + assertion + "]", "[expect." + (this.assertMode ? "" : "not.") + expectation + "]" ); throw e; } }; }; _.each(_.keys(referee.assert), function (name) { var expectationName = referee.assert[name].expectationName; if (expectationName) { expect.wrapAssertion(name, expectationName); } }); expect.wrapAssertion("assert", "toBeTruthy"); expect.wrapAssertion("refute", "toBeFalsy"); if (expect.expectation.toBeNear) { expect.expectation.toBeCloseTo = expect.expectation.toBeNear; } return expect; }); ((typeof define === "function" && define.amd && function (m) { define("formatio", ["samsam", "lodash"], m); }) || (typeof module === "object" && function (m) { module.exports = m(require("samsam"), require("lodash")); }) || function (m) { this.formatio = m(this.samsam, this._); } )(function (samsam, _) { "use strict"; var formatio = { excludeConstructors: ["Object", /^.$/], quoteStrings: true }; var hasOwn = Object.prototype.hasOwnProperty; var specialObjects = []; if (typeof global !== "undefined") { specialObjects.push({ object: global, value: "[object global]" }); } if (typeof document !== "undefined") { specialObjects.push({ object: document, value: "[object HTMLDocument]" }); } if (typeof window !== "undefined") { specialObjects.push({ object: window, value: "[object Window]" }); } function functionName(func) { if (!func) { return ""; } if (func.displayName) { return func.displayName; } if (func.name) { return func.name; } var matches = func.toString().match(/function\s+([^\(]+)/m); return (matches && matches[1]) || ""; } function constructorName(f, object) { var name = functionName(object && object.constructor); var excludes = f.excludeConstructors || formatio.excludeConstructors || []; var i, l; for (i = 0, l = excludes.length; i < l; ++i) { if (typeof excludes[i] === "string" && excludes[i] === name) { return ""; } else if (excludes[i].test && excludes[i].test(name)) { return ""; } } return name; } function isCircular(object, objects) { if (typeof object !== "object") { return false; } var i, l; for (i = 0, l = objects.length; i < l; ++i) { if (objects[i] === object) { return true; } } return false; } function ascii(f, object, processed, indent) { if (typeof object === "string") { var qs = f.quoteStrings; var quote = typeof qs !== "boolean" || qs; return processed || quote ? '"' + object + '"' : object; } if (typeof object === "function" && !(object instanceof RegExp)) { return ascii.func(object); } processed = processed || []; if (isCircular(object, processed)) { return "[Circular]"; } if (_.isArray(object)) { return ascii.array.call(f, object, processed); } if (!object) { return String(object === -0 ? "-0" : object); } if (samsam.isElement(object)) { return ascii.element(object); } if (typeof object.toString === "function" && object.toString !== Object.prototype.toString) { return object.toString(); } var i, l; for (i = 0, l = specialObjects.length; i < l; i++) { if (object === specialObjects[i].object) { return specialObjects[i].value; } } return ascii.object.call(f, object, processed, indent); } ascii.func = function (func) { return "function " + functionName(func) + "() {}"; }; ascii.array = function (array, processed) { processed = processed || []; processed.push(array); var i, l, pieces = []; for (i = 0, l = array.length; i < l; ++i) { pieces.push(ascii(this, array[i], processed)); } return "[" + pieces.join(", ") + "]"; }; ascii.object = function (object, processed, indent) { processed = processed || []; processed.push(object); indent = indent || 0; var pieces = [], properties = _.keys(object).sort(); var length = 3; var prop, str, obj, i, l; for (i = 0, l = properties.length; i < l; ++i) { prop = properties[i]; obj = object[prop]; if (isCircular(obj, processed)) { str = "[Circular]"; } else { str = ascii(this, obj, processed, indent + 2); } str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; length += str.length; pieces.push(str); } var cons = constructorName(this, object); var prefix = cons ? "[" + cons + "] " : ""; var is = ""; for (i = 0, l = indent; i < l; ++i) { is += " "; } if (length + indent > 80) { return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}"; } return prefix + "{ " + pieces.join(", ") + " }"; }; ascii.element = function (element) { var tagName = element.tagName.toLowerCase(); var attrs = element.attributes, attr, pairs = [], attrName, i, l, val; for (i = 0, l = attrs.length; i < l; ++i) { attr = attrs.item(i); attrName = attr.nodeName.toLowerCase().replace("html:", ""); val = attr.nodeValue; if (attrName !== "contenteditable" || val !== "inherit") { if (!!val) { pairs.push(attrName + "=\"" + val + "\""); } } } var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); var content = element.innerHTML; if (content.length > 20) { content = content.substr(0, 20) + "[...]"; } var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">"; return res.replace(/ contentEditable="inherit"/, ""); }; function Formatio(options) { for (var opt in options) { this[opt] = options[opt]; } } Formatio.prototype = { functionName: functionName, configure: function (options) { return new Formatio(options); }, constructorName: function (object) { return constructorName(this, object); }, ascii: function (object, processed, indent) { return ascii(this, object, processed, indent); } }; return Formatio.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("stack-filter", m); }) || (typeof module === "object" && function (m) { module.exports = m(); }) || function (m) { this.stackFilter = m(); } )(function () { "use strict"; var regexpes = {}; return { filters: [], configure: function (opt) { opt = opt || {}; var instance = Object.create(this); instance.filters = opt.filters || []; instance.cwd = opt.cwd; return instance; }, /** * Return true if the stack trace line matches any filter */ match: function (line) { var i, l, filters = this.filters; for (i = 0, l = filters.length; i < l; ++i) { if (!regexpes[filters[i]]) { // Backslashes must be double-escaped: // new RegExp("\\") is equivalent to /\/ - which is an invalid pattern // new RegExp("\\\\") is equivalent to /\\/ - an escaped backslash // This must be done for Windows paths to work properly regexpes[filters[i]] = new RegExp(filters[i].replace(/\\/g, "\\\\")); } if (regexpes[filters[i]].test(line)) { return true; } } return false; }, /** * Filter a stack trace and optionally trim off the current * working directory. Accepts a stack trace as a string, and * an optional cwd (also a string). The cwd can also be * configured directly on the instance. * * Returns an array of lines - a pruned stack trace. The * result only includes lines that point to a file and a * location - the initial error message is stripped off. If a * cwd is available, all paths will be stripped of it. Any * line matching any filter will not be included in the * result. */ filter: function (stack, cwd) { var lines = (stack || "").split("\n"); var i, l, line, stackLines = [], replacer = "./"; cwd = cwd || this.cwd; if (typeof cwd === "string") { cwd = cwd.replace(/\/?$/, "/"); } if (cwd instanceof RegExp && !/\/\/$/.test(cwd)) { replacer = "."; } for (i = 0, l = lines.length; i < l; ++i) { if (/(\d+)?:\d+\)?$/.test(lines[i])) { if (!this.match(lines[i])) { line = lines[i].replace(/^\s+|\s+$/g, ""); if (cwd) { line = line.replace(cwd, replacer); } stackLines.push(line); } } } return stackLines; } }; }); /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/ /*global module, require, __dirname, document*/ /** * Sinon core utilities. For internal use only. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; var sinon = (function (buster) { var div = typeof document != "undefined" && document.createElement("div"); var hasOwn = Object.prototype.hasOwnProperty; function isDOMNode(obj) { var success = false; try { obj.appendChild(div); success = div.parentNode == obj; } catch (e) { return false; } finally { try { obj.removeChild(div); } catch (e) { // Remove failed, not much we can do about that } } return success; } function isElement(obj) { return div && obj && obj.nodeType === 1 && isDOMNode(obj); } function isFunction(obj) { return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); } function mirrorProperties(target, source) { for (var prop in source) { if (!hasOwn.call(target, prop)) { target[prop] = source[prop]; } } } function isRestorable (obj) { return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; } var sinon = { wrapMethod: function wrapMethod(object, property, method) { if (!object) { throw new TypeError("Should wrap property of object"); } if (typeof method != "function") { throw new TypeError("Method wrapper should be function"); } var wrappedMethod = object[property]; if (!isFunction(wrappedMethod)) { throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + property + " as function"); } if (wrappedMethod.restore && wrappedMethod.restore.sinon) { throw new TypeError("Attempted to wrap " + property + " which is already wrapped"); } if (wrappedMethod.calledBefore) { var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; throw new TypeError("Attempted to wrap " + property + " which is already " + verb); } // IE 8 does not support hasOwnProperty on the window object. var owned = hasOwn.call(object, property); object[property] = method; method.displayName = property; method.restore = function () { // For prototype properties try to reset by delete first. // If this fails (ex: localStorage on mobile safari) then force a reset // via direct assignment. if (!owned) { delete object[property]; } if (object[property] === method) { object[property] = wrappedMethod; } }; method.restore.sinon = true; mirrorProperties(method, wrappedMethod); return method; }, extend: function extend(target) { for (var i = 1, l = arguments.length; i < l; i += 1) { for (var prop in arguments[i]) { if (arguments[i].hasOwnProperty(prop)) { target[prop] = arguments[i][prop]; } // DONT ENUM bug, only care about toString if (arguments[i].hasOwnProperty("toString") && arguments[i].toString != target.toString) { target.toString = arguments[i].toString; } } } return target; }, create: function create(proto) { var F = function () {}; F.prototype = proto; return new F(); }, deepEqual: function deepEqual(a, b) { if (sinon.match && sinon.match.isMatcher(a)) { return a.test(b); } if (typeof a != "object" || typeof b != "object") { return a === b; } if (isElement(a) || isElement(b)) { return a === b; } if (a === b) { return true; } if ((a === null && b !== null) || (a !== null && b === null)) { return false; } var aString = Object.prototype.toString.call(a); if (aString != Object.prototype.toString.call(b)) { return false; } if (aString == "[object Array]") { if (a.length !== b.length) { return false; } for (var i = 0, l = a.length; i < l; i += 1) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (aString == "[object Date]") { return a.valueOf() === b.valueOf(); } var prop, aLength = 0, bLength = 0; for (prop in a) { aLength += 1; if (!deepEqual(a[prop], b[prop])) { return false; } } for (prop in b) { bLength += 1; } return aLength == bLength; }, functionName: function functionName(func) { var name = func.displayName || func.name; // Use function decomposition as a last resort to get function // name. Does not rely on function decomposition to work - if it // doesn't debugging will be slightly less informative // (i.e. toString will say 'spy' rather than 'myFunc'). if (!name) { var matches = func.toString().match(/function ([^\s\(]+)/); name = matches && matches[1]; } return name; }, functionToString: function toString() { if (this.getCall && this.callCount) { var thisValue, prop, i = this.callCount; while (i--) { thisValue = this.getCall(i).thisValue; for (prop in thisValue) { if (thisValue[prop] === this) { return prop; } } } } return this.displayName || "sinon fake"; }, getConfig: function (custom) { var config = {}; custom = custom || {}; var defaults = sinon.defaultConfig; for (var prop in defaults) { if (defaults.hasOwnProperty(prop)) { config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; } } return config; }, format: function (val) { return "" + val; }, defaultConfig: { injectIntoThis: true, injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true }, timesInWords: function timesInWords(count) { return count == 1 && "once" || count == 2 && "twice" || count == 3 && "thrice" || (count || 0) + " times"; }, calledInOrder: function (spies) { for (var i = 1, l = spies.length; i < l; i++) { if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { return false; } } return true; }, orderByFirstCall: function (spies) { return spies.sort(function (a, b) { // uuid, won't ever be equal var aCall = a.getCall(0); var bCall = b.getCall(0); var aId = aCall && aCall.callId || -1; var bId = bCall && bCall.callId || -1; return aId < bId ? -1 : 1; }); }, log: function () {}, logError: function (label, err) { var msg = label + " threw exception: " sinon.log(msg + "[" + err.name + "] " + err.message); if (err.stack) { sinon.log(err.stack); } setTimeout(function () { err.message = msg + err.message; throw err; }, 0); }, typeOf: function (value) { if (value === null) { return "null"; } else if (value === undefined) { return "undefined"; } var string = Object.prototype.toString.call(value); return string.substring(8, string.length - 1).toLowerCase(); }, createStubInstance: function (constructor) { if (typeof constructor !== "function") { throw new TypeError("The constructor should be a function."); } return sinon.stub(sinon.create(constructor.prototype)); }, restore: function (object) { if (object !== null && typeof object === "object") { for (var prop in object) { if (isRestorable(object[prop])) { object[prop].restore(); } } } else if (isRestorable(object)) { object.restore(); } } }; var isNode = typeof module == "object" && typeof require == "function"; if (isNode) { try { buster = { format: require("buster-format") }; } catch (e) {} module.exports = sinon; module.exports.spy = require("./sinon/spy"); module.exports.stub = require("./sinon/stub"); module.exports.mock = require("./sinon/mock"); module.exports.collection = require("./sinon/collection"); module.exports.assert = require("./sinon/assert"); module.exports.sandbox = require("./sinon/sandbox"); module.exports.test = require("./sinon/test"); module.exports.testCase = require("./sinon/test_case"); module.exports.assert = require("./sinon/assert"); module.exports.match = require("./sinon/match"); } if (buster) { var formatter = sinon.create(buster.format); formatter.quoteStrings = false; sinon.format = function () { return formatter.ascii.apply(formatter, arguments); }; } else if (isNode) { try { var util = require("util"); sinon.format = function (value) { return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; }; } catch (e) { /* Node, but no util module - would be very old, but better safe than sorry */ } } return sinon; }(typeof buster == "object" && buster)); /** * @depend ../sinon.js * @depend match.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy calls * * @author Christian Johansen (christian@cjohansen.no) * @author Maximilian Antoni (mail@maxantoni.de) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen * Copyright (c) 2013 Maximilian Antoni */ "use strict"; var commonJSModule = typeof module == "object" && typeof require == "function"; if (!this.sinon && commonJSModule) { var sinon = require("../sinon"); } (function (sinon) { function throwYieldError(proxy, text, args) { var msg = sinon.functionName(proxy) + text; if (args.length) { msg += " Received [" + slice.call(args).join(", ") + "]"; } throw new Error(msg); } var slice = Array.prototype.slice; var callProto = { calledOn: function calledOn(thisValue) { if (sinon.match && sinon.match.isMatcher(thisValue)) { return thisValue.test(this.thisValue); } return this.thisValue === thisValue; }, calledWith: function calledWith() { for (var i = 0, l = arguments.length; i < l; i += 1) { if (!sinon.deepEqual(arguments[i], this.args[i])) { return false; } } return true; }, calledWithMatch: function calledWithMatch() { for (var i = 0, l = arguments.length; i < l; i += 1) { var actual = this.args[i]; var expectation = arguments[i]; if (!sinon.match || !sinon.match(expectation).test(actual)) { return false; } } return true; }, calledWithExactly: function calledWithExactly() { return arguments.length == this.args.length && this.calledWith.apply(this, arguments); }, notCalledWith: function notCalledWith() { return !this.calledWith.apply(this, arguments); }, notCalledWithMatch: function notCalledWithMatch() { return !this.calledWithMatch.apply(this, arguments); }, returned: function returned(value) { return sinon.deepEqual(value, this.returnValue); }, threw: function threw(error) { if (typeof error === "undefined" || !this.exception) { return !!this.exception; } return this.exception === error || this.exception.name === error; }, calledWithNew: function calledWithNew(thisValue) { return this.thisValue instanceof this.proxy; }, calledBefore: function (other) { return this.callId < other.callId; }, calledAfter: function (other) { return this.callId > other.callId; }, callArg: function (pos) { this.args[pos](); }, callArgOn: function (pos, thisValue) { this.args[pos].apply(thisValue); }, callArgWith: function (pos) { this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); }, callArgOnWith: function (pos, thisValue) { var args = slice.call(arguments, 2); this.args[pos].apply(thisValue, args); }, "yield": function () { this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); }, yieldOn: function (thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (typeof args[i] === "function") { args[i].apply(thisValue, slice.call(arguments, 1)); return; } } throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); }, yieldTo: function (prop) { this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); }, yieldToOn: function (prop, thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (args[i] && typeof args[i][prop] === "function") { args[i][prop].apply(thisValue, slice.call(arguments, 2)); return; } } throwYieldError(this.proxy, " cannot yield to '" + prop + "' since no callback was passed.", args); }, toString: function () { var callStr = this.proxy.toString() + "("; var args = []; for (var i = 0, l = this.args.length; i < l; ++i) { args.push(sinon.format(this.args[i])); } callStr = callStr + args.join(", ") + ")"; if (typeof this.returnValue != "undefined") { callStr += " => " + sinon.format(this.returnValue); } if (this.exception) { callStr += " !" + this.exception.name; if (this.exception.message) { callStr += "(" + this.exception.message + ")"; } } return callStr; } }; callProto.invokeCallback = callProto.yield; function createSpyCall(spy, thisValue, args, returnValue, exception, id) { if (typeof id !== "number") { throw new TypeError("Call id is not a number"); } var proxyCall = sinon.create(callProto); proxyCall.proxy = spy; proxyCall.thisValue = thisValue; proxyCall.args = args; proxyCall.returnValue = returnValue; proxyCall.exception = exception; proxyCall.callId = id; return proxyCall; }; createSpyCall.toString = callProto.toString; // used by mocks sinon.spyCall = createSpyCall; }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy functions * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = Array.prototype.push; var slice = Array.prototype.slice; var callId = 0; function spy(object, property) { if (!property && typeof object == "function") { return spy.create(object); } if (!object && !property) { return spy.create(function () { }); } var method = object[property]; return sinon.wrapMethod(object, property, spy.create(method)); } function matchingFake(fakes, args, strict) { if (!fakes) { return; } var alen = args.length; for (var i = 0, l = fakes.length; i < l; i++) { if (fakes[i].matches(args, strict)) { return fakes[i]; } } } function incrementCallCount() { this.called = true; this.callCount += 1; this.notCalled = false; this.calledOnce = this.callCount == 1; this.calledTwice = this.callCount == 2; this.calledThrice = this.callCount == 3; } function createCallProperties() { this.firstCall = this.getCall(0); this.secondCall = this.getCall(1); this.thirdCall = this.getCall(2); this.lastCall = this.getCall(this.callCount - 1); } var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; function createProxy(func) { // Retain the function length: var p; if (func.length) { eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) + ") { return p.invoke(func, this, slice.call(arguments)); });"); } else { p = function proxy() { return p.invoke(func, this, slice.call(arguments)); }; } return p; } var uuid = 0; // Public API var spyApi = { reset: function () { this.called = false; this.notCalled = true; this.calledOnce = false; this.calledTwice = false; this.calledThrice = false; this.callCount = 0; this.firstCall = null; this.secondCall = null; this.thirdCall = null; this.lastCall = null; this.args = []; this.returnValues = []; this.thisValues = []; this.exceptions = []; this.callIds = []; if (this.fakes) { for (var i = 0; i < this.fakes.length; i++) { this.fakes[i].reset(); } } }, create: function create(func) { var name; if (typeof func != "function") { func = function () { }; } else { name = sinon.functionName(func); } var proxy = createProxy(func); sinon.extend(proxy, spy); delete proxy.create; sinon.extend(proxy, func); proxy.reset(); proxy.prototype = func.prototype; proxy.displayName = name || "spy"; proxy.toString = sinon.functionToString; proxy._create = sinon.spy.create; proxy.id = "spy#" + uuid++; return proxy; }, invoke: function invoke(func, thisValue, args) { var matching = matchingFake(this.fakes, args); var exception, returnValue; incrementCallCount.call(this); push.call(this.thisValues, thisValue); push.call(this.args, args); push.call(this.callIds, callId++); try { if (matching) { returnValue = matching.invoke(func, thisValue, args); } else { returnValue = (this.func || func).apply(thisValue, args); } } catch (e) { push.call(this.returnValues, undefined); exception = e; throw e; } finally { push.call(this.exceptions, exception); } push.call(this.returnValues, returnValue); createCallProperties.call(this); return returnValue; }, getCall: function getCall(i) { if (i < 0 || i >= this.callCount) { return null; } return sinon.spyCall(this, this.thisValues[i], this.args[i], this.returnValues[i], this.exceptions[i], this.callIds[i]); }, calledBefore: function calledBefore(spyFn) { if (!this.called) { return false; } if (!spyFn.called) { return true; } return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; }, calledAfter: function calledAfter(spyFn) { if (!this.called || !spyFn.called) { return false; } return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; }, withArgs: function () { var args = slice.call(arguments); if (this.fakes) { var match = matchingFake(this.fakes, args, true); if (match) { return match; } } else { this.fakes = []; } var original = this; var fake = this._create(); fake.matchingAguments = args; push.call(this.fakes, fake); fake.withArgs = function () { return original.withArgs.apply(original, arguments); }; for (var i = 0; i < this.args.length; i++) { if (fake.matches(this.args[i])) { incrementCallCount.call(fake); push.call(fake.thisValues, this.thisValues[i]); push.call(fake.args, this.args[i]); push.call(fake.returnValues, this.returnValues[i]); push.call(fake.exceptions, this.exceptions[i]); push.call(fake.callIds, this.callIds[i]); } } createCallProperties.call(fake); return fake; }, matches: function (args, strict) { var margs = this.matchingAguments; if (margs.length <= args.length && sinon.deepEqual(margs, args.slice(0, margs.length))) { return !strict || margs.length == args.length; } }, printf: function (format) { var spy = this; var args = slice.call(arguments, 1); var formatter; return (format || "").replace(/%(.)/g, function (match, specifyer) { formatter = spyApi.formatters[specifyer]; if (typeof formatter == "function") { return formatter.call(null, spy, args); } else if (!isNaN(parseInt(specifyer), 10)) { return sinon.format(args[specifyer - 1]); } return "%" + specifyer; }); } }; function delegateToCalls(method, matchAny, actual, notCalled) { spyApi[method] = function () { if (!this.called) { if (notCalled) { return notCalled.apply(this, arguments); } return false; } var currentCall; var matches = 0; for (var i = 0, l = this.callCount; i < l; i += 1) { currentCall = this.getCall(i); if (currentCall[actual || method].apply(currentCall, arguments)) { matches += 1; if (matchAny) { return true; } } } return matches === this.callCount; }; } delegateToCalls("calledOn", true); delegateToCalls("alwaysCalledOn", false, "calledOn"); delegateToCalls("calledWith", true); delegateToCalls("calledWithMatch", true); delegateToCalls("alwaysCalledWith", false, "calledWith"); delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); delegateToCalls("calledWithExactly", true); delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); delegateToCalls("neverCalledWith", false, "notCalledWith", function () { return true; }); delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", function () { return true; }); delegateToCalls("threw", true); delegateToCalls("alwaysThrew", false, "threw"); delegateToCalls("returned", true); delegateToCalls("alwaysReturned", false, "returned"); delegateToCalls("calledWithNew", true); delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); delegateToCalls("callArg", false, "callArgWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgWith = spyApi.callArg; delegateToCalls("callArgOn", false, "callArgOnWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgOnWith = spyApi.callArgOn; delegateToCalls("yield", false, "yield", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. spyApi.invokeCallback = spyApi.yield; delegateToCalls("yieldOn", false, "yieldOn", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); delegateToCalls("yieldTo", false, "yieldTo", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); spyApi.formatters = { "c": function (spy) { return sinon.timesInWords(spy.callCount); }, "n": function (spy) { return spy.toString(); }, "C": function (spy) { var calls = []; for (var i = 0, l = spy.callCount; i < l; ++i) { var stringifiedCall = " " + spy.getCall(i).toString(); if (/\n/.test(calls[i - 1])) { stringifiedCall = "\n" + stringifiedCall; } push.call(calls, stringifiedCall); } return calls.length > 0 ? "\n" + calls.join("\n") : ""; }, "t": function (spy) { var objects = []; for (var i = 0, l = spy.callCount; i < l; ++i) { push.call(objects, sinon.format(spy.thisValues[i])); } return objects.join(", "); }, "*": function (spy, args) { var formatted = []; for (var i = 0, l = args.length; i < l; ++i) { push.call(formatted, sinon.format(args[i])); } return formatted.join(", "); } }; sinon.extend(spy, spyApi); spy.spyCall = sinon.spyCall; if (commonJSModule) { module.exports = spy; } else { sinon.spy = spy; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend match.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy calls * * @author Christian Johansen (christian@cjohansen.no) * @author Maximilian Antoni (mail@maxantoni.de) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen * Copyright (c) 2013 Maximilian Antoni */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function throwYieldError(proxy, text, args) { var msg = sinon.functionName(proxy) + text; if (args.length) { msg += " Received [" + slice.call(args).join(", ") + "]"; } throw new Error(msg); } var slice = Array.prototype.slice; var callProto = { calledOn: function calledOn(thisValue) { if (sinon.match && sinon.match.isMatcher(thisValue)) { return thisValue.test(this.thisValue); } return this.thisValue === thisValue; }, calledWith: function calledWith() { for (var i = 0, l = arguments.length; i < l; i += 1) { if (!sinon.deepEqual(arguments[i], this.args[i])) { return false; } } return true; }, calledWithMatch: function calledWithMatch() { for (var i = 0, l = arguments.length; i < l; i += 1) { var actual = this.args[i]; var expectation = arguments[i]; if (!sinon.match || !sinon.match(expectation).test(actual)) { return false; } } return true; }, calledWithExactly: function calledWithExactly() { return arguments.length == this.args.length && this.calledWith.apply(this, arguments); }, notCalledWith: function notCalledWith() { return !this.calledWith.apply(this, arguments); }, notCalledWithMatch: function notCalledWithMatch() { return !this.calledWithMatch.apply(this, arguments); }, returned: function returned(value) { return sinon.deepEqual(value, this.returnValue); }, threw: function threw(error) { if (typeof error === "undefined" || !this.exception) { return !!this.exception; } return this.exception === error || this.exception.name === error; }, calledWithNew: function calledWithNew(thisValue) { return this.thisValue instanceof this.proxy; }, calledBefore: function (other) { return this.callId < other.callId; }, calledAfter: function (other) { return this.callId > other.callId; }, callArg: function (pos) { this.args[pos](); }, callArgOn: function (pos, thisValue) { this.args[pos].apply(thisValue); }, callArgWith: function (pos) { this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); }, callArgOnWith: function (pos, thisValue) { var args = slice.call(arguments, 2); this.args[pos].apply(thisValue, args); }, "yield": function () { this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); }, yieldOn: function (thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (typeof args[i] === "function") { args[i].apply(thisValue, slice.call(arguments, 1)); return; } } throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); }, yieldTo: function (prop) { this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); }, yieldToOn: function (prop, thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (args[i] && typeof args[i][prop] === "function") { args[i][prop].apply(thisValue, slice.call(arguments, 2)); return; } } throwYieldError(this.proxy, " cannot yield to '" + prop + "' since no callback was passed.", args); }, toString: function () { var callStr = this.proxy.toString() + "("; var args = []; for (var i = 0, l = this.args.length; i < l; ++i) { args.push(sinon.format(this.args[i])); } callStr = callStr + args.join(", ") + ")"; if (typeof this.returnValue != "undefined") { callStr += " => " + sinon.format(this.returnValue); } if (this.exception) { callStr += " !" + this.exception.name; if (this.exception.message) { callStr += "(" + this.exception.message + ")"; } } return callStr; } }; callProto.invokeCallback = callProto.yield; function createSpyCall(spy, thisValue, args, returnValue, exception, id) { if (typeof id !== "number") { throw new TypeError("Call id is not a number"); } var proxyCall = sinon.create(callProto); proxyCall.proxy = spy; proxyCall.thisValue = thisValue; proxyCall.args = args; proxyCall.returnValue = returnValue; proxyCall.exception = exception; proxyCall.callId = id; return proxyCall; }; createSpyCall.toString = callProto.toString; // used by mocks if (commonJSModule) { module.exports = createSpyCall; } else { sinon.spyCall = createSpyCall; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend spy.js */ /*jslint eqeqeq: false, onevar: false*/ /*global module, require, sinon*/ /** * Stub functions * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function stub(object, property, func) { if (!!func && typeof func != "function") { throw new TypeError("Custom stub should be function"); } var wrapper; if (func) { wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; } else { wrapper = stub.create(); } if (!object && !property) { return sinon.stub.create(); } if (!property && !!object && typeof object == "object") { for (var prop in object) { if (typeof object[prop] === "function") { stub(object, prop); } } return object; } return sinon.wrapMethod(object, property, wrapper); } function getChangingValue(stub, property) { var index = stub.callCount - 1; var values = stub[property]; var prop = index in values ? values[index] : values[values.length - 1]; stub[property + "Last"] = prop; return prop; } function getCallback(stub, args) { var callArgAt = getChangingValue(stub, "callArgAts"); if (callArgAt < 0) { var callArgProp = getChangingValue(stub, "callArgProps"); for (var i = 0, l = args.length; i < l; ++i) { if (!callArgProp && typeof args[i] == "function") { return args[i]; } if (callArgProp && args[i] && typeof args[i][callArgProp] == "function") { return args[i][callArgProp]; } } return null; } return args[callArgAt]; } var join = Array.prototype.join; function getCallbackError(stub, func, args) { if (stub.callArgAtsLast < 0) { var msg; if (stub.callArgPropsLast) { msg = sinon.functionName(stub) + " expected to yield to '" + stub.callArgPropsLast + "', but no object with such a property was passed." } else { msg = sinon.functionName(stub) + " expected to yield, but no callback was passed." } if (args.length > 0) { msg += " Received [" + join.call(args, ", ") + "]"; } return msg; } return "argument at index " + stub.callArgAtsLast + " is not a function: " + func; } var nextTick = (function () { if (typeof process === "object" && typeof process.nextTick === "function") { return process.nextTick; } else if (typeof setImmediate === "function") { return setImmediate; } else { return function (callback) { setTimeout(callback, 0); }; } })(); function callCallback(stub, args) { if (stub.callArgAts.length > 0) { var func = getCallback(stub, args); if (typeof func != "function") { throw new TypeError(getCallbackError(stub, func, args)); } var callbackArguments = getChangingValue(stub, "callbackArguments"); var callbackContext = getChangingValue(stub, "callbackContexts"); if (stub.callbackAsync) { nextTick(function() { func.apply(callbackContext, callbackArguments); }); } else { func.apply(callbackContext, callbackArguments); } } } var uuid = 0; sinon.extend(stub, (function () { var slice = Array.prototype.slice, proto; function throwsException(error, message) { if (typeof error == "string") { this.exception = new Error(message || ""); this.exception.name = error; } else if (!error) { this.exception = new Error("Error"); } else { this.exception = error; } return this; } proto = { create: function create() { var functionStub = function () { callCallback(functionStub, arguments); if (functionStub.exception) { throw functionStub.exception; } else if (typeof functionStub.returnArgAt == 'number') { return arguments[functionStub.returnArgAt]; } else if (functionStub.returnThis) { return this; } return functionStub.returnValue; }; functionStub.id = "stub#" + uuid++; var orig = functionStub; functionStub = sinon.spy.create(functionStub); functionStub.func = orig; functionStub.callArgAts = []; functionStub.callbackArguments = []; functionStub.callbackContexts = []; functionStub.callArgProps = []; sinon.extend(functionStub, stub); functionStub._create = sinon.stub.create; functionStub.displayName = "stub"; functionStub.toString = sinon.functionToString; return functionStub; }, resetBehavior: function () { var i; this.callArgAts = []; this.callbackArguments = []; this.callbackContexts = []; this.callArgProps = []; delete this.returnValue; delete this.returnArgAt; this.returnThis = false; if (this.fakes) { for (i = 0; i < this.fakes.length; i++) { this.fakes[i].resetBehavior(); } } }, returns: function returns(value) { this.returnValue = value; return this; }, returnsArg: function returnsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.returnArgAt = pos; return this; }, returnsThis: function returnsThis() { this.returnThis = true; return this; }, "throws": throwsException, throwsException: throwsException, callsArg: function callsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAts.push(pos); this.callbackArguments.push([]); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, callsArgOn: function callsArgOn(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(pos); this.callbackArguments.push([]); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, callsArgWith: function callsArgWith(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAts.push(pos); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, callsArgOnWith: function callsArgWith(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(pos); this.callbackArguments.push(slice.call(arguments, 2)); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, yields: function () { this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 0)); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, yieldsOn: function (context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, yieldsTo: function (prop) { this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(undefined); this.callArgProps.push(prop); return this; }, yieldsToOn: function (prop, context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 2)); this.callbackContexts.push(context); this.callArgProps.push(prop); return this; } }; // create asynchronous versions of callsArg* and yields* methods for (var method in proto) { // need to avoid creating anotherasync versions of the newly added async methods if (proto.hasOwnProperty(method) && method.match(/^(callsArg|yields|thenYields$)/) && !method.match(/Async/)) { proto[method + 'Async'] = (function (syncFnName) { return function () { this.callbackAsync = true; return this[syncFnName].apply(this, arguments); }; })(method); } } return proto; }())); if (commonJSModule) { module.exports = stub; } else { sinon.stub = stub; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false*/ /*global module, require, sinon*/ /** * Mock functions. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = [].push; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function mock(object) { if (!object) { return sinon.expectation.create("Anonymous mock"); } return mock.create(object); } sinon.mock = mock; sinon.extend(mock, (function () { function each(collection, callback) { if (!collection) { return; } for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } return { create: function create(object) { if (!object) { throw new TypeError("object is null"); } var mockObject = sinon.extend({}, mock); mockObject.object = object; delete mockObject.create; return mockObject; }, expects: function expects(method) { if (!method) { throw new TypeError("method is falsy"); } if (!this.expectations) { this.expectations = {}; this.proxies = []; } if (!this.expectations[method]) { this.expectations[method] = []; var mockObject = this; sinon.wrapMethod(this.object, method, function () { return mockObject.invokeMethod(method, this, arguments); }); push.call(this.proxies, method); } var expectation = sinon.expectation.create(method); push.call(this.expectations[method], expectation); return expectation; }, restore: function restore() { var object = this.object; each(this.proxies, function (proxy) { if (typeof object[proxy].restore == "function") { object[proxy].restore(); } }); }, verify: function verify() { var expectations = this.expectations || {}; var messages = [], met = []; each(this.proxies, function (proxy) { each(expectations[proxy], function (expectation) { if (!expectation.met()) { push.call(messages, expectation.toString()); } else { push.call(met, expectation.toString()); } }); }); this.restore(); if (messages.length > 0) { sinon.expectation.fail(messages.concat(met).join("\n")); } else { sinon.expectation.pass(messages.concat(met).join("\n")); } return true; }, invokeMethod: function invokeMethod(method, thisValue, args) { var expectations = this.expectations && this.expectations[method]; var length = expectations && expectations.length || 0, i; for (i = 0; i < length; i += 1) { if (!expectations[i].met() && expectations[i].allowsCall(thisValue, args)) { return expectations[i].apply(thisValue, args); } } var messages = [], available, exhausted = 0; for (i = 0; i < length; i += 1) { if (expectations[i].allowsCall(thisValue, args)) { available = available || expectations[i]; } else { exhausted += 1; } push.call(messages, " " + expectations[i].toString()); } if (exhausted === 0) { return available.apply(thisValue, args); } messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ proxy: method, args: args })); sinon.expectation.fail(messages.join("\n")); } }; }())); var times = sinon.timesInWords; sinon.expectation = (function () { var slice = Array.prototype.slice; var _invoke = sinon.spy.invoke; function callCountInWords(callCount) { if (callCount == 0) { return "never called"; } else { return "called " + times(callCount); } } function expectedCallCountInWords(expectation) { var min = expectation.minCalls; var max = expectation.maxCalls; if (typeof min == "number" && typeof max == "number") { var str = times(min); if (min != max) { str = "at least " + str + " and at most " + times(max); } return str; } if (typeof min == "number") { return "at least " + times(min); } return "at most " + times(max); } function receivedMinCalls(expectation) { var hasMinLimit = typeof expectation.minCalls == "number"; return !hasMinLimit || expectation.callCount >= expectation.minCalls; } function receivedMaxCalls(expectation) { if (typeof expectation.maxCalls != "number") { return false; } return expectation.callCount == expectation.maxCalls; } return { minCalls: 1, maxCalls: 1, create: function create(methodName) { var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); delete expectation.create; expectation.method = methodName; return expectation; }, invoke: function invoke(func, thisValue, args) { this.verifyCallAllowed(thisValue, args); return _invoke.apply(this, arguments); }, atLeast: function atLeast(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.maxCalls = null; this.limitsSet = true; } this.minCalls = num; return this; }, atMost: function atMost(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.minCalls = null; this.limitsSet = true; } this.maxCalls = num; return this; }, never: function never() { return this.exactly(0); }, once: function once() { return this.exactly(1); }, twice: function twice() { return this.exactly(2); }, thrice: function thrice() { return this.exactly(3); }, exactly: function exactly(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not a number"); } this.atLeast(num); return this.atMost(num); }, met: function met() { return !this.failed && receivedMinCalls(this); }, verifyCallAllowed: function verifyCallAllowed(thisValue, args) { if (receivedMaxCalls(this)) { this.failed = true; sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); } if ("expectedThis" in this && this.expectedThis !== thisValue) { sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + this.expectedThis); } if (!("expectedArguments" in this)) { return; } if (!args) { sinon.expectation.fail(this.method + " received no arguments, expected " + sinon.format(this.expectedArguments)); } if (args.length < this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + "), expected " + sinon.format(this.expectedArguments)); } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + "), expected " + sinon.format(this.expectedArguments)); } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + ", expected " + sinon.format(this.expectedArguments)); } } }, allowsCall: function allowsCall(thisValue, args) { if (this.met() && receivedMaxCalls(this)) { return false; } if ("expectedThis" in this && this.expectedThis !== thisValue) { return false; } if (!("expectedArguments" in this)) { return true; } args = args || []; if (args.length < this.expectedArguments.length) { return false; } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { return false; } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { return false; } } return true; }, withArgs: function withArgs() { this.expectedArguments = slice.call(arguments); return this; }, withExactArgs: function withExactArgs() { this.withArgs.apply(this, arguments); this.expectsExactArgCount = true; return this; }, on: function on(thisValue) { this.expectedThis = thisValue; return this; }, toString: function () { var args = (this.expectedArguments || []).slice(); if (!this.expectsExactArgCount) { push.call(args, "[...]"); } var callStr = sinon.spyCall.toString.call({ proxy: this.method || "anonymous mock expectation", args: args }); var message = callStr.replace(", [...", "[, ...") + " " + expectedCallCountInWords(this); if (this.met()) { return "Expectation met: " + message; } return "Expected " + message + " (" + callCountInWords(this.callCount) + ")"; }, verify: function verify() { if (!this.met()) { sinon.expectation.fail(this.toString()); } else { sinon.expectation.pass(this.toString()); } return true; }, pass: function(message) { sinon.assert.pass(message); }, fail: function (message) { var exception = new Error(message); exception.name = "ExpectationError"; throw exception; } }; }()); if (commonJSModule) { module.exports = mock; } else { sinon.mock = mock; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js * @depend mock.js */ /*jslint eqeqeq: false, onevar: false, forin: true*/ /*global module, require, sinon*/ /** * Collections of stubs, spies and mocks. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = [].push; var hasOwnProperty = Object.prototype.hasOwnProperty; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function getFakes(fakeCollection) { if (!fakeCollection.fakes) { fakeCollection.fakes = []; } return fakeCollection.fakes; } function each(fakeCollection, method) { var fakes = getFakes(fakeCollection); for (var i = 0, l = fakes.length; i < l; i += 1) { if (typeof fakes[i][method] == "function") { fakes[i][method](); } } } function compact(fakeCollection) { var fakes = getFakes(fakeCollection); var i = 0; while (i < fakes.length) { fakes.splice(i, 1); } } var collection = { verify: function resolve() { each(this, "verify"); }, restore: function restore() { each(this, "restore"); compact(this); }, verifyAndRestore: function verifyAndRestore() { var exception; try { this.verify(); } catch (e) { exception = e; } this.restore(); if (exception) { throw exception; } }, add: function add(fake) { push.call(getFakes(this), fake); return fake; }, spy: function spy() { return this.add(sinon.spy.apply(sinon, arguments)); }, stub: function stub(object, property, value) { if (property) { var original = object[property]; if (typeof original != "function") { if (!hasOwnProperty.call(object, property)) { throw new TypeError("Cannot stub non-existent own property " + property); } object[property] = value; return this.add({ restore: function () { object[property] = original; } }); } } if (!property && !!object && typeof object == "object") { var stubbedObj = sinon.stub.apply(sinon, arguments); for (var prop in stubbedObj) { if (typeof stubbedObj[prop] === "function") { this.add(stubbedObj[prop]); } } return stubbedObj; } return this.add(sinon.stub.apply(sinon, arguments)); }, mock: function mock() { return this.add(sinon.mock.apply(sinon, arguments)); }, inject: function inject(obj) { var col = this; obj.spy = function () { return col.spy.apply(col, arguments); }; obj.stub = function () { return col.stub.apply(col, arguments); }; obj.mock = function () { return col.mock.apply(col, arguments); }; return obj; } }; if (commonJSModule) { module.exports = collection; } else { sinon.collection = collection; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend collection.js * @depend util/fake_timers.js * @depend util/fake_server_with_clock.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global require, module*/ /** * Manages fake collections as well as fake utilities such as Sinon's * timers and fake XHR implementation in one convenient object. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; if (typeof module == "object" && typeof require == "function") { var sinon = require("../sinon"); sinon.extend(sinon, require("./util/fake_timers")); } (function () { var push = [].push; function exposeValue(sandbox, config, key, value) { if (!value) { return; } if (config.injectInto) { config.injectInto[key] = value; } else { push.call(sandbox.args, value); } } function prepareSandboxFromConfig(config) { var sandbox = sinon.create(sinon.sandbox); if (config.useFakeServer) { if (typeof config.useFakeServer == "object") { sandbox.serverPrototype = config.useFakeServer; } sandbox.useFakeServer(); } if (config.useFakeTimers) { if (typeof config.useFakeTimers == "object") { sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); } else { sandbox.useFakeTimers(); } } return sandbox; } sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { useFakeTimers: function useFakeTimers() { this.clock = sinon.useFakeTimers.apply(sinon, arguments); return this.add(this.clock); }, serverPrototype: sinon.fakeServer, useFakeServer: function useFakeServer() { var proto = this.serverPrototype || sinon.fakeServer; if (!proto || !proto.create) { return null; } this.server = proto.create(); return this.add(this.server); }, inject: function (obj) { sinon.collection.inject.call(this, obj); if (this.clock) { obj.clock = this.clock; } if (this.server) { obj.server = this.server; obj.requests = this.server.requests; } return obj; }, create: function (config) { if (!config) { return sinon.create(sinon.sandbox); } var sandbox = prepareSandboxFromConfig(config); sandbox.args = sandbox.args || []; var prop, value, exposed = sandbox.inject({}); if (config.properties) { for (var i = 0, l = config.properties.length; i < l; i++) { prop = config.properties[i]; value = exposed[prop] || prop == "sandbox" && sandbox; exposeValue(sandbox, config, prop, value); } } else { exposeValue(sandbox, config, "sandbox", value); } return sandbox; } }); sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; if (typeof module == "object" && typeof require == "function") { module.exports = sinon.sandbox; } }()); /* @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Match functions * * @author Maximilian Antoni (mail@maxantoni.de) * @license BSD * * Copyright (c) 2012 Maximilian Antoni */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function assertType(value, type, name) { var actual = sinon.typeOf(value); if (actual !== type) { throw new TypeError("Expected type of " + name + " to be " + type + ", but was " + actual); } } var matcher = { toString: function () { return this.message; } }; function isMatcher(object) { return matcher.isPrototypeOf(object); } function matchObject(expectation, actual) { if (actual === null || actual === undefined) { return false; } for (var key in expectation) { if (expectation.hasOwnProperty(key)) { var exp = expectation[key]; var act = actual[key]; if (match.isMatcher(exp)) { if (!exp.test(act)) { return false; } } else if (sinon.typeOf(exp) === "object") { if (!matchObject(exp, act)) { return false; } } else if (!sinon.deepEqual(exp, act)) { return false; } } } return true; } matcher.or = function (m2) { if (!isMatcher(m2)) { throw new TypeError("Matcher expected"); } var m1 = this; var or = sinon.create(matcher); or.test = function (actual) { return m1.test(actual) || m2.test(actual); }; or.message = m1.message + ".or(" + m2.message + ")"; return or; }; matcher.and = function (m2) { if (!isMatcher(m2)) { throw new TypeError("Matcher expected"); } var m1 = this; var and = sinon.create(matcher); and.test = function (actual) { return m1.test(actual) && m2.test(actual); }; and.message = m1.message + ".and(" + m2.message + ")"; return and; }; var match = function (expectation, message) { var m = sinon.create(matcher); var type = sinon.typeOf(expectation); switch (type) { case "object": if (typeof expectation.test === "function") { m.test = function (actual) { return expectation.test(actual) === true; }; m.message = "match(" + sinon.functionName(expectation.test) + ")"; return m; } var str = []; for (var key in expectation) { if (expectation.hasOwnProperty(key)) { str.push(key + ": " + expectation[key]); } } m.test = function (actual) { return matchObject(expectation, actual); }; m.message = "match(" + str.join(", ") + ")"; break; case "number": m.test = function (actual) { return expectation == actual; }; break; case "string": m.test = function (actual) { if (typeof actual !== "string") { return false; } return actual.indexOf(expectation) !== -1; }; m.message = "match(\"" + expectation + "\")"; break; case "regexp": m.test = function (actual) { if (typeof actual !== "string") { return false; } return expectation.test(actual); }; break; case "function": m.test = expectation; if (message) { m.message = message; } else { m.message = "match(" + sinon.functionName(expectation) + ")"; } break; default: m.test = function (actual) { return sinon.deepEqual(expectation, actual); }; } if (!m.message) { m.message = "match(" + expectation + ")"; } return m; }; match.isMatcher = isMatcher; match.any = match(function () { return true; }, "any"); match.defined = match(function (actual) { return actual !== null && actual !== undefined; }, "defined"); match.truthy = match(function (actual) { return !!actual; }, "truthy"); match.falsy = match(function (actual) { return !actual; }, "falsy"); match.same = function (expectation) { return match(function (actual) { return expectation === actual; }, "same(" + expectation + ")"); }; match.typeOf = function (type) { assertType(type, "string", "type"); return match(function (actual) { return sinon.typeOf(actual) === type; }, "typeOf(\"" + type + "\")"); }; match.instanceOf = function (type) { assertType(type, "function", "type"); return match(function (actual) { return actual instanceof type; }, "instanceOf(" + sinon.functionName(type) + ")"); }; function createPropertyMatcher(propertyTest, messagePrefix) { return function (property, value) { assertType(property, "string", "property"); var onlyProperty = arguments.length === 1; var message = messagePrefix + "(\"" + property + "\""; if (!onlyProperty) { message += ", " + value; } message += ")"; return match(function (actual) { if (actual === undefined || actual === null || !propertyTest(actual, property)) { return false; } return onlyProperty || sinon.deepEqual(value, actual[property]); }, message); }; } match.has = createPropertyMatcher(function (actual, property) { if (typeof actual === "object") { return property in actual; } return actual[property] !== undefined; }, "has"); match.hasOwn = createPropertyMatcher(function (actual, property) { return actual.hasOwnProperty(property); }, "hasOwn"); match.bool = match.typeOf("boolean"); match.number = match.typeOf("number"); match.string = match.typeOf("string"); match.object = match.typeOf("object"); match.func = match.typeOf("function"); match.array = match.typeOf("array"); match.regexp = match.typeOf("regexp"); match.date = match.typeOf("date"); if (commonJSModule) { module.exports = match; } else { sinon.match = match; } }(typeof sinon == "object" && sinon || null)); /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Minimal Event interface implementation * * Original implementation by Sven Fuchs: https://gist.github.com/995028 * Modifications and tests by Christian Johansen. * * @author Sven Fuchs (svenfuchs@artweb-design.de) * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2011 Sven Fuchs, Christian Johansen */ "use strict"; if (typeof sinon == "undefined") { this.sinon = {}; } (function () { var push = [].push; sinon.Event = function Event(type, bubbles, cancelable, target) { this.initEvent(type, bubbles, cancelable, target); }; sinon.Event.prototype = { initEvent: function(type, bubbles, cancelable, target) { this.type = type; this.bubbles = bubbles; this.cancelable = cancelable; this.target = target; }, stopPropagation: function () {}, preventDefault: function () { this.defaultPrevented = true; } }; sinon.EventTarget = { addEventListener: function addEventListener(event, listener, useCapture) { this.eventListeners = this.eventListeners || {}; this.eventListeners[event] = this.eventListeners[event] || []; push.call(this.eventListeners[event], listener); }, removeEventListener: function removeEventListener(event, listener, useCapture) { var listeners = this.eventListeners && this.eventListeners[event] || []; for (var i = 0, l = listeners.length; i < l; ++i) { if (listeners[i] == listener) { return listeners.splice(i, 1); } } }, dispatchEvent: function dispatchEvent(event) { var type = event.type; var listeners = this.eventListeners && this.eventListeners[type] || []; for (var i = 0; i < listeners.length; i++) { if (typeof listeners[i] == "function") { listeners[i].call(this, event); } else { listeners[i].handleEvent(event); } } return !!event.defaultPrevented; } }; }()); /** * @depend ../../sinon.js * @depend event.js */ /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Fake XMLHttpRequest object * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; if (typeof sinon == "undefined") { this.sinon = {}; } sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest }; // wrapper for global (function(global) { var xhr = sinon.xhr; xhr.GlobalXMLHttpRequest = global.XMLHttpRequest; xhr.GlobalActiveXObject = global.ActiveXObject; xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined"; xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined"; xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; /*jsl:ignore*/ var unsafeHeaders = { "Accept-Charset": true, "Accept-Encoding": true, "Connection": true, "Content-Length": true, "Cookie": true, "Cookie2": true, "Content-Transfer-Encoding": true, "Date": true, "Expect": true, "Host": true, "Keep-Alive": true, "Referer": true, "TE": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, "User-Agent": true, "Via": true }; /*jsl:end*/ function FakeXMLHttpRequest() { this.readyState = FakeXMLHttpRequest.UNSENT; this.requestHeaders = {}; this.requestBody = null; this.status = 0; this.statusText = ""; var xhr = this; var events = ["loadstart", "load", "abort", "loadend"]; function addEventListener(eventName) { xhr.addEventListener(eventName, function (event) { var listener = xhr["on" + eventName]; if (listener && typeof listener == "function") { listener(event); } }); } for (var i = events.length - 1; i >= 0; i--) { addEventListener(events[i]); } if (typeof FakeXMLHttpRequest.onCreate == "function") { FakeXMLHttpRequest.onCreate(this); } } function verifyState(xhr) { if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { throw new Error("INVALID_STATE_ERR"); } if (xhr.sendFlag) { throw new Error("INVALID_STATE_ERR"); } } // filtering to enable a white-list version of Sinon FakeXhr, // where whitelisted requests are passed through to real XHR function each(collection, callback) { if (!collection) return; for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } function some(collection, callback) { for (var index = 0; index < collection.length; index++) { if(callback(collection[index]) === true) return true; }; return false; } // largest arity in XHR is 5 - XHR#open var apply = function(obj,method,args) { switch(args.length) { case 0: return obj[method](); case 1: return obj[method](args[0]); case 2: return obj[method](args[0],args[1]); case 3: return obj[method](args[0],args[1],args[2]); case 4: return obj[method](args[0],args[1],args[2],args[3]); case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]); }; }; FakeXMLHttpRequest.filters = []; FakeXMLHttpRequest.addFilter = function(fn) { this.filters.push(fn) }; var IE6Re = /MSIE 6/; FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) { var xhr = new sinon.xhr.workingXHR(); each(["open","setRequestHeader","send","abort","getResponseHeader", "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"], function(method) { fakeXhr[method] = function() { return apply(xhr,method,arguments); }; }); var copyAttrs = function(args) { each(args, function(attr) { try { fakeXhr[attr] = xhr[attr] } catch(e) { if(!IE6Re.test(navigator.userAgent)) throw e; } }); }; var stateChange = function() { fakeXhr.readyState = xhr.readyState; if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { copyAttrs(["status","statusText"]); } if(xhr.readyState >= FakeXMLHttpRequest.LOADING) { copyAttrs(["responseText"]); } if(xhr.readyState === FakeXMLHttpRequest.DONE) { copyAttrs(["responseXML"]); } if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr); }; if(xhr.addEventListener) { for(var event in fakeXhr.eventListeners) { if(fakeXhr.eventListeners.hasOwnProperty(event)) { each(fakeXhr.eventListeners[event],function(handler) { xhr.addEventListener(event, handler); }); } } xhr.addEventListener("readystatechange",stateChange); } else { xhr.onreadystatechange = stateChange; } apply(xhr,"open",xhrArgs); }; FakeXMLHttpRequest.useFilters = false; function verifyRequestSent(xhr) { if (xhr.readyState == FakeXMLHttpRequest.DONE) { throw new Error("Request done"); } } function verifyHeadersReceived(xhr) { if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { throw new Error("No headers received"); } } function verifyResponseBodyType(body) { if (typeof body != "string") { var error = new Error("Attempted to respond to fake XMLHttpRequest with " + body + ", which is not a string."); error.name = "InvalidBodyException"; throw error; } } sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { async: true, open: function open(method, url, async, username, password) { this.method = method; this.url = url; this.async = typeof async == "boolean" ? async : true; this.username = username; this.password = password; this.responseText = null; this.responseXML = null; this.requestHeaders = {}; this.sendFlag = false; if(sinon.FakeXMLHttpRequest.useFilters === true) { var xhrArgs = arguments; var defake = some(FakeXMLHttpRequest.filters,function(filter) { return filter.apply(this,xhrArgs) }); if (defake) { return sinon.FakeXMLHttpRequest.defake(this,arguments); } } this.readyStateChange(FakeXMLHttpRequest.OPENED); }, readyStateChange: function readyStateChange(state) { this.readyState = state; if (typeof this.onreadystatechange == "function") { try { this.onreadystatechange(); } catch (e) { sinon.logError("Fake XHR onreadystatechange handler", e); } } this.dispatchEvent(new sinon.Event("readystatechange")); switch (this.readyState) { case FakeXMLHttpRequest.DONE: this.dispatchEvent(new sinon.Event("load", false, false, this)); this.dispatchEvent(new sinon.Event("loadend", false, false, this)); break; } }, setRequestHeader: function setRequestHeader(header, value) { verifyState(this); if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { throw new Error("Refused to set unsafe header \"" + header + "\""); } if (this.requestHeaders[header]) { this.requestHeaders[header] += "," + value; } else { this.requestHeaders[header] = value; } }, // Helps testing setResponseHeaders: function setResponseHeaders(headers) { this.responseHeaders = {}; for (var header in headers) { if (headers.hasOwnProperty(header)) { this.responseHeaders[header] = headers[header]; } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); } else { this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; } }, // Currently treats ALL data as a DOMString (i.e. no Document) send: function send(data) { verifyState(this); if (!/^(get|head)$/i.test(this.method)) { if (this.requestHeaders["Content-Type"]) { var value = this.requestHeaders["Content-Type"].split(";"); this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8"; } else { this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; } this.requestBody = data; } this.errorFlag = false; this.sendFlag = this.async; this.readyStateChange(FakeXMLHttpRequest.OPENED); if (typeof this.onSend == "function") { this.onSend(this); } this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); }, abort: function abort() { this.aborted = true; this.responseText = null; this.errorFlag = true; this.requestHeaders = {}; if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) { this.readyStateChange(sinon.FakeXMLHttpRequest.DONE); this.sendFlag = false; } this.readyState = sinon.FakeXMLHttpRequest.UNSENT; this.dispatchEvent(new sinon.Event("abort", false, false, this)); if (typeof this.onerror === "function") { this.onerror(); } }, getResponseHeader: function getResponseHeader(header) { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return null; } if (/^Set-Cookie2?$/i.test(header)) { return null; } header = header.toLowerCase(); for (var h in this.responseHeaders) { if (h.toLowerCase() == header) { return this.responseHeaders[h]; } } return null; }, getAllResponseHeaders: function getAllResponseHeaders() { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return ""; } var headers = ""; for (var header in this.responseHeaders) { if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) { headers += header + ": " + this.responseHeaders[header] + "\r\n"; } } return headers; }, setResponseBody: function setResponseBody(body) { verifyRequestSent(this); verifyHeadersReceived(this); verifyResponseBodyType(body); var chunkSize = this.chunkSize || 10; var index = 0; this.responseText = ""; do { if (this.async) { this.readyStateChange(FakeXMLHttpRequest.LOADING); } this.responseText += body.substring(index, index + chunkSize); index += chunkSize; } while (index < body.length); var type = this.getResponseHeader("Content-Type"); if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { try { this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); } catch (e) { // Unable to parse XML - no biggie } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.DONE); } else { this.readyState = FakeXMLHttpRequest.DONE; } }, respond: function respond(status, headers, body) { this.setResponseHeaders(headers || {}); this.status = typeof status == "number" ? status : 200; this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; this.setResponseBody(body || ""); if (typeof this.onload === "function"){ this.onload(); } } }); sinon.extend(FakeXMLHttpRequest, { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 }); // Borrowed from JSpec FakeXMLHttpRequest.parseXML = function parseXML(text) { var xmlDoc; if (typeof DOMParser != "undefined") { var parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(text); } return xmlDoc; }; FakeXMLHttpRequest.statusCodes = { 100: "Continue", 101: "Switching Protocols", 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 206: "Partial Content", 300: "Multiple Choice", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 422: "Unprocessable Entity", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported" }; sinon.useFakeXMLHttpRequest = function () { sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) { if (xhr.supportsXHR) { global.XMLHttpRequest = xhr.GlobalXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = xhr.GlobalActiveXObject; } delete sinon.FakeXMLHttpRequest.restore; if (keepOnCreate !== true) { delete sinon.FakeXMLHttpRequest.onCreate; } }; if (xhr.supportsXHR) { global.XMLHttpRequest = sinon.FakeXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = function ActiveXObject(objId) { if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { return new sinon.FakeXMLHttpRequest(); } return new xhr.GlobalActiveXObject(objId); }; } return sinon.FakeXMLHttpRequest; }; sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; })(this); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ /*global module, require, window*/ /** * Fake timer API * setTimeout * setInterval * clearTimeout * clearInterval * tick * reset * Date * * Inspired by jsUnitMockTimeOut from JsUnit * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; if (typeof sinon == "undefined") { var sinon = {}; } (function (global) { var id = 1; function addTimer(args, recurring) { if (args.length === 0) { throw new Error("Function requires at least 1 parameter"); } var toId = id++; var delay = args[1] || 0; if (!this.timeouts) { this.timeouts = {}; } this.timeouts[toId] = { id: toId, func: args[0], callAt: this.now + delay, invokeArgs: Array.prototype.slice.call(args, 2) }; if (recurring === true) { this.timeouts[toId].interval = delay; } return toId; } function parseTime(str) { if (!str) { return 0; } var strings = str.split(":"); var l = strings.length, i = l; var ms = 0, parsed; if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { throw new Error("tick only understands numbers and 'h:m:s'"); } while (i--) { parsed = parseInt(strings[i], 10); if (parsed >= 60) { throw new Error("Invalid time " + str); } ms += parsed * Math.pow(60, (l - i - 1)); } return ms * 1000; } function createObject(object) { var newObject; if (Object.create) { newObject = Object.create(object); } else { var F = function () {}; F.prototype = object; newObject = new F(); } newObject.Date.clock = newObject; return newObject; } sinon.clock = { now: 0, create: function create(now) { var clock = createObject(this); if (typeof now == "number") { clock.now = now; } if (!!now && typeof now == "object") { throw new TypeError("now should be milliseconds since UNIX epoch"); } return clock; }, setTimeout: function setTimeout(callback, timeout) { return addTimer.call(this, arguments, false); }, clearTimeout: function clearTimeout(timerId) { if (!this.timeouts) { this.timeouts = []; } if (timerId in this.timeouts) { delete this.timeouts[timerId]; } }, setInterval: function setInterval(callback, timeout) { return addTimer.call(this, arguments, true); }, clearInterval: function clearInterval(timerId) { this.clearTimeout(timerId); }, tick: function tick(ms) { ms = typeof ms == "number" ? ms : parseTime(ms); var tickFrom = this.now, tickTo = this.now + ms, previous = this.now; var timer = this.firstTimerInRange(tickFrom, tickTo); var firstException; while (timer && tickFrom <= tickTo) { if (this.timeouts[timer.id]) { tickFrom = this.now = timer.callAt; try { this.callTimer(timer); } catch (e) { firstException = firstException || e; } } timer = this.firstTimerInRange(previous, tickTo); previous = tickFrom; } this.now = tickTo; if (firstException) { throw firstException; } return this.now; }, firstTimerInRange: function (from, to) { var timer, smallest, originalTimer; for (var id in this.timeouts) { if (this.timeouts.hasOwnProperty(id)) { if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) { continue; } if (!smallest || this.timeouts[id].callAt < smallest) { originalTimer = this.timeouts[id]; smallest = this.timeouts[id].callAt; timer = { func: this.timeouts[id].func, callAt: this.timeouts[id].callAt, interval: this.timeouts[id].interval, id: this.timeouts[id].id, invokeArgs: this.timeouts[id].invokeArgs }; } } } return timer || null; }, callTimer: function (timer) { if (typeof timer.interval == "number") { this.timeouts[timer.id].callAt += timer.interval; } else { delete this.timeouts[timer.id]; } try { if (typeof timer.func == "function") { timer.func.apply(null, timer.invokeArgs); } else { eval(timer.func); } } catch (e) { var exception = e; } if (!this.timeouts[timer.id]) { if (exception) { throw exception; } return; } if (exception) { throw exception; } }, reset: function reset() { this.timeouts = {}; }, Date: (function () { var NativeDate = Date; function ClockDate(year, month, date, hour, minute, second, ms) { // Defensive and verbose to avoid potential harm in passing // explicit undefined when user does not pass argument switch (arguments.length) { case 0: return new NativeDate(ClockDate.clock.now); case 1: return new NativeDate(year); case 2: return new NativeDate(year, month); case 3: return new NativeDate(year, month, date); case 4: return new NativeDate(year, month, date, hour); case 5: return new NativeDate(year, month, date, hour, minute); case 6: return new NativeDate(year, month, date, hour, minute, second); default: return new NativeDate(year, month, date, hour, minute, second, ms); } } return mirrorDateProperties(ClockDate, NativeDate); }()) }; function mirrorDateProperties(target, source) { if (source.now) { target.now = function now() { return target.clock.now; }; } else { delete target.now; } if (source.toSource) { target.toSource = function toSource() { return source.toSource(); }; } else { delete target.toSource; } target.toString = function toString() { return source.toString(); }; target.prototype = source.prototype; target.parse = source.parse; target.UTC = source.UTC; target.prototype.toUTCString = source.prototype.toUTCString; return target; } var methods = ["Date", "setTimeout", "setInterval", "clearTimeout", "clearInterval"]; function restore() { var method; for (var i = 0, l = this.methods.length; i < l; i++) { method = this.methods[i]; if (global[method].hadOwnProperty) { global[method] = this["_" + method]; } else { delete global[method]; } } // Prevent multiple executions which will completely remove these props this.methods = []; } function stubGlobal(method, clock) { clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method); clock["_" + method] = global[method]; if (method == "Date") { var date = mirrorDateProperties(clock[method], global[method]); global[method] = date; } else { global[method] = function () { return clock[method].apply(clock, arguments); }; for (var prop in clock[method]) { if (clock[method].hasOwnProperty(prop)) { global[method][prop] = clock[method][prop]; } } } global[method].clock = clock; } sinon.useFakeTimers = function useFakeTimers(now) { var clock = sinon.clock.create(now); clock.restore = restore; clock.methods = Array.prototype.slice.call(arguments, typeof now == "number" ? 1 : 0); if (clock.methods.length === 0) { clock.methods = methods; } for (var i = 0, l = clock.methods.length; i < l; i++) { stubGlobal(clock.methods[i], clock); } return clock; }; }(typeof global != "undefined" && typeof global !== "function" ? global : this)); sinon.timers = { setTimeout: setTimeout, clearTimeout: clearTimeout, setInterval: setInterval, clearInterval: clearInterval, Date: Date }; if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /** * @depend fake_xml_http_request.js */ /*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/ /*global module, require, window*/ /** * The Sinon "server" mimics a web server that receives requests from * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, * both synchronously and asynchronously. To respond synchronuously, canned * answers have to be provided upfront. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; if (typeof sinon == "undefined") { var sinon = {}; } sinon.fakeServer = (function () { var push = [].push; function F() {} function create(proto) { F.prototype = proto; return new F(); } function responseArray(handler) { var response = handler; if (Object.prototype.toString.call(handler) != "[object Array]") { response = [200, {}, handler]; } if (typeof response[2] != "string") { throw new TypeError("Fake server response body should be string, but was " + typeof response[2]); } return response; } var wloc = typeof window !== "undefined" ? window.location : {}; var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); function matchOne(response, reqMethod, reqUrl) { var rmeth = response.method; var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); var url = response.url; var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); return matchMethod && matchUrl; } function match(response, request) { var requestMethod = this.getHTTPMethod(request); var requestUrl = request.url; if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { requestUrl = requestUrl.replace(rCurrLoc, ""); } if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { if (typeof response.response == "function") { var ru = response.url; var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1)); return response.response.apply(response, args); } return true; } return false; } function log(response, request) { var str; str = "Request:\n" + sinon.format(request) + "\n\n"; str += "Response:\n" + sinon.format(response) + "\n\n"; sinon.log(str); } return { create: function () { var server = create(this); this.xhr = sinon.useFakeXMLHttpRequest(); server.requests = []; this.xhr.onCreate = function (xhrObj) { server.addRequest(xhrObj); }; return server; }, addRequest: function addRequest(xhrObj) { var server = this; push.call(this.requests, xhrObj); xhrObj.onSend = function () { server.handleRequest(this); }; if (this.autoRespond && !this.responding) { setTimeout(function () { server.responding = false; server.respond(); }, this.autoRespondAfter || 10); this.responding = true; } }, getHTTPMethod: function getHTTPMethod(request) { if (this.fakeHTTPMethods && /post/i.test(request.method)) { var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); return !!matches ? matches[1] : request.method; } return request.method; }, handleRequest: function handleRequest(xhr) { if (xhr.async) { if (!this.queue) { this.queue = []; } push.call(this.queue, xhr); } else { this.processRequest(xhr); } }, respondWith: function respondWith(method, url, body) { if (arguments.length == 1 && typeof method != "function") { this.response = responseArray(method); return; } if (!this.responses) { this.responses = []; } if (arguments.length == 1) { body = method; url = method = null; } if (arguments.length == 2) { body = url; url = method; method = null; } push.call(this.responses, { method: method, url: url, response: typeof body == "function" ? body : responseArray(body) }); }, respond: function respond() { if (arguments.length > 0) this.respondWith.apply(this, arguments); var queue = this.queue || []; var request; while(request = queue.shift()) { this.processRequest(request); } }, processRequest: function processRequest(request) { try { if (request.aborted) { return; } var response = this.response || [404, {}, ""]; if (this.responses) { for (var i = 0, l = this.responses.length; i < l; i++) { if (match.call(this, this.responses[i], request)) { response = this.responses[i].response; break; } } } if (request.readyState != 4) { log(response, request); request.respond(response[0], response[1], response[2]); } } catch (e) { sinon.logError("Fake server request processing", e); } }, restore: function restore() { return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); } }; }()); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /** * @depend fake_server.js * @depend fake_timers.js */ /*jslint browser: true, eqeqeq: false, onevar: false*/ /*global sinon*/ /** * Add-on for sinon.fakeServer that automatically handles a fake timer along with * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, * it polls the object for completion with setInterval. Dispite the direct * motivation, there is nothing jQuery-specific in this file, so it can be used * in any environment where the ajax implementation depends on setInterval or * setTimeout. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function () { function Server() {} Server.prototype = sinon.fakeServer; sinon.fakeServerWithClock = new Server(); sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { if (xhr.async) { if (typeof setTimeout.clock == "object") { this.clock = setTimeout.clock; } else { this.clock = sinon.useFakeTimers(); this.resetClock = true; } if (!this.longestTimeout) { var clockSetTimeout = this.clock.setTimeout; var clockSetInterval = this.clock.setInterval; var server = this; this.clock.setTimeout = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetTimeout.apply(this, arguments); }; this.clock.setInterval = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetInterval.apply(this, arguments); }; } } return sinon.fakeServer.addRequest.call(this, xhr); }; sinon.fakeServerWithClock.respond = function respond() { var returnVal = sinon.fakeServer.respond.apply(this, arguments); if (this.clock) { this.clock.tick(this.longestTimeout || 0); this.longestTimeout = 0; if (this.resetClock) { this.clock.restore(); this.resetClock = false; } } return returnVal; }; sinon.fakeServerWithClock.restore = function restore() { if (this.clock) { this.clock.restore(); } return sinon.fakeServer.restore.apply(this, arguments); }; }()); // Based on seedrandom.js version 2.2. // Original author: David Bau // Date: 2013 Jun 15 // // LICENSE (BSD): // // Copyright 2013 David Bau, all rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of this module nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // (typeof global === "object" ? global : this).seedRandom = (function (pool, math, width, chunks, digits) { var startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1; function ARC4(key) { var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; if (!keylen) { key = [keylen++]; } while (i < width) { s[i] = i++; } for (i = 0; i < width; i++) { s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))]; s[j] = t; } (me.g = function(count) { var t, r = 0, i = me.i, j = me.j, s = me.S; while (count--) { t = s[i = mask & (i + 1)]; r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))]; } me.i = i; me.j = j; return r; })(width); } function flatten(obj, depth) { var result = [], typ = (typeof obj)[0], prop; if (depth && typ == 'o') { for (prop in obj) { try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} } } return (result.length ? result : typ == 's' ? obj : obj + '\0'); } function mixkey(seed, key) { var stringseed = seed + '', smear, j = 0; while (j < stringseed.length) { key[mask & j] = mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++)); } return tostring(key); } function tostring(a) { return String.fromCharCode.apply(0, a); } mixkey(math.random(), pool); return function(seed, use_entropy) { var key = []; var shortseed = mixkey(flatten( use_entropy ? [seed, tostring(pool)] : typeof seed !== "undefined" ? seed : [new Date().getTime(), pool], 3), key); var arc4 = new ARC4(key); mixkey(tostring(arc4.S), pool); var random = function() { var n = arc4.g(chunks), d = startdenom, x = 0; while (n < significance) { n = (n + x) * width; d *= width; x = arc4.g(1); } while (n >= overflow) { n /= 2; d /= 2; x >>>= 1; } return (n + x) / d; }; random.seed = shortseed; return random; }; }([], Math, 256, 6, 52)); ((typeof define === "function" && define.amd && function (m) { define("buster-test/browser-env", ["lodash"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("lodash")); }) || function (m) { this.buster = this.buster || {}; this.buster.browserEnv = m(this._); })(function (_) { "use strict"; function BrowserEnv(rootElement) { this.element = rootElement; this.originalContent = ""; } BrowserEnv.prototype = { create: function (rootElement) { return new BrowserEnv(rootElement); }, listen: function (runner) { var clear = _.bind(this.clear, this); runner.on("suite:start", _.bind(function () { this.originalContent = this.element.innerHTML; }, this)); runner.on("test:success", clear); runner.on("test:failure", clear); runner.on("test:error", clear); runner.on("test:timeout", clear); }, clear: function () { this.element.innerHTML = this.originalContent; } }; return BrowserEnv.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/test-context", ["bane", "when", "lodash"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("bane"), require("when"), require("lodash")); }) || function (m) { this.buster = this.buster || {}; this.buster.testContext = m(this.bane, this.when, this._); })(function (bane, when, _) { "use strict"; var bctx = bane.createEventEmitter(); function empty(context) { return context.tests.length === 0 && context.contexts.length === 0; } function filterContexts(contexts, filter, prefix) { return _.reduce(contexts, function (filtered, context) { var ctx = bctx.filter(context, filter, prefix); if (ctx.tests.length > 0 || ctx.contexts.length > 0) { filtered.push(ctx); } return filtered; }, []); } function filterTests(tests, filter, prefix) { return _.reduce(tests, function (filtered, test) { if (!filter || filter.test(prefix + test.name)) { filtered.push(test); } return filtered; }, []); } function makeFilter(filter) { if (typeof filter === "string") { return new RegExp(filter, "i"); } if (Object.prototype.toString.call(filter) !== "[object Array]") { return filter; } return { test: function (string) { return filter.length === 0 || _.some(filter, function (f) { return new RegExp(f).test(string); }); } }; } function parse(context) { if (!context.tests && typeof context.parse === "function") { return context.parse(); } return context; } function compile(contexts, filter) { return _.reduce(contexts, function (compiled, ctx) { if (when.isPromise(ctx)) { var deferred = when.defer(); ctx.then(function (context) { deferred.resolve(bctx.filter(parse(context), filter)); }); deferred.promise.name = ctx.name; compiled.push(deferred.promise); } else { ctx = bctx.filter(parse(ctx), filter); if (!empty(ctx)) { compiled.push(ctx); } } return compiled; }, []); } function filter(ctx, filterContent, name) { filterContent = makeFilter(filterContent); name = (name || "") + ctx.name + " "; return _.extend({}, ctx, { tests: filterTests(ctx.tests || [], filterContent, name), contexts: filterContexts(ctx.contexts || [], filterContent, name) }); } bctx.compile = compile; bctx.filter = filter; return bctx; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/spec", ["lodash", "when", "buster-test/test-context"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("lodash"), require("when"), require("./test-context")); }) || function (m) { this.buster.spec = m(this._, this.when, this.buster.testContext); })(function (_, when, testContext) { "use strict"; var current = []; var bspec = {}; var bddNames = { contextSetUp: "beforeAll", contextTearDown: "afterAll" }; function supportRequirement(property) { return function (requirements) { return { describe: function () { var context = bspec.describe.apply(bspec, arguments); context[property] = requirements; return context; } }; }; } bspec.ifAllSupported = supportRequirement("requiresSupportForAll"); bspec.ifAnySupported = supportRequirement("requiresSupportForAny"); bspec.ifSupported = bspec.ifAllSupported; function addContext(parent, name, spec) { var context = bspec.describe.context.create(name, spec, parent).parse(); parent.contexts.push(context); return context; } function createContext(name, spec) { return bspec.describe.context.create(name, spec).parse(); } function asyncContext(name, callback) { var d = when.defer(); callback(function (spec) { d.resolver.resolve(createContext(name, spec)); }); d.promise.name = name; testContext.emit("create", d.promise); return d.promise; } var FOCUS_ROCKET = /^\s*=>\s*/; function markFocused(block, parent) { var focused = block.focused || (parent && parent.forceFocus); block.focused = focused || FOCUS_ROCKET.test(block.name); block.name = block.name.replace(FOCUS_ROCKET, ""); while (parent) { parent.focused = parent.focused || block.focused; parent = parent.parent; } } bspec.describe = function (name, spec) { if (current.length > 0) { return addContext(current[current.length - 1], name, spec); } if (spec && spec.length > 0) { return asyncContext(name, spec); } var context = createContext(name, spec); testContext.emit("create", context); return context; }; function markDeferred(spec, func) { spec.deferred = typeof func !== "function"; if (!spec.deferred && /^\/\//.test(spec.name)) { spec.deferred = true; spec.name = spec.name.replace(/^\/\/\s*/, ""); } spec.comment = spec.deferred ? func : ""; } bspec.it = function (name, func, extra) { var context = current[current.length - 1]; var spec = { name: name, func: arguments.length === 3 ? extra : func, context: context }; markDeferred(spec, func); spec.deferred = spec.deferred || context.deferred; markFocused(spec, context); context.tests.push(spec); return spec; }; bspec.itEventually = function (name, comment, func) { if (typeof comment === "function") { func = comment; comment = ""; } return bspec.it(name, comment, func); }; bspec.before = bspec.beforeEach = function (func) { var context = current[current.length - 1]; context.setUp = func; }; bspec.after = bspec.afterEach = function (func) { var context = current[current.length - 1]; context.tearDown = func; }; bspec.beforeAll = function (func) { var context = current[current.length - 1]; context.contextSetUp = func; }; bspec.afterAll = function (func) { var context = current[current.length - 1]; context.contextTearDown = func; }; function F() {} function create(object) { F.prototype = object; return new F(); } bspec.describe.context = { create: function (name, spec, parent) { if (!name || typeof name !== "string") { throw new Error("Spec name required"); } if (!spec || typeof spec !== "function") { throw new Error("spec should be a function"); } var context = create(this); context.name = name; context.parent = parent; context.spec = spec; markDeferred(context, spec); if (parent) { context.deferred = context.deferred || parent.deferred; } markFocused(context, parent); context.forceFocus = context.focused; return context; }, parse: function () { if (!this.spec) { return this; } this.testCase = { before: bspec.before, beforeEach: bspec.beforeEach, beforeAll: bspec.beforeAll, after: bspec.after, afterEach: bspec.afterEach, afterAll: bspec.afterAll, it: bspec.it, itEventually: bspec.itEventually, describe: bspec.describe, name: function (thing) { return bddNames[thing] || thing; } }; this.tests = []; current.push(this); this.contexts = []; this.spec.call(this.testCase); current.pop(); delete this.spec; return this; } }; var g = (typeof global !== "undefined" && global) || this; bspec.expose = function (env) { env = env || g; env.describe = bspec.describe; env.it = bspec.it; env.itEventually = bspec.itEventually; env.beforeAll = bspec.beforeAll; env.before = bspec.before; env.beforeEach = bspec.beforeEach; env.afterAll = bspec.afterAll; env.after = bspec.after; env.afterEach = bspec.afterEach; }; return bspec; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/test-case", ["bane", "when", "buster-test/test-context"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m( require("bane"), require("when"), require("./test-context") ); }) || function (m) { this.buster.testCase = m(this.bane, this.when, this.buster.testContext); })(function (bane, when, testContext) { "use strict"; var xUnitNames = { contextSetUp: "prepare", contextTearDown: "conclude" }; var testCase = function (name, tests) { if (!name || typeof name !== "string") { throw new Error("Test case name required"); } if (!tests || (typeof tests !== "object" && typeof tests !== "function")) { throw new Error("Tests should be an object or a function"); } var context = testCase.context.create(name, tests); var d = when.defer(); when(context).then(function (ctx) { d.resolver.resolve(ctx.parse()); }); var promise = context.then ? d.promise : context; promise.name = name; testContext.emit("create", promise); return promise; }; bane.createEventEmitter(testCase); function nonTestNames(context) { return { prepare: true, conclude: true, setUp: true, tearDown: true, requiresSupportFor: true, requiresSupportForAll: true }; } var DEFERRED_PREFIX = /^\s*\/\/\s*/; var FOCUSED_PREFIX = /^\s*=>\s*/; function createContext(context, name, tests, parent) { context.name = name; context.content = tests; context.parent = parent; context.testCase = { name: function (thing) { return xUnitNames[thing] || thing; } }; return context; } function asyncContext(context, name, callback, parent) { var d = when.defer(); callback(function (tests) { d.resolver.resolve(createContext(context, name, tests, parent)); }); return d.promise; } function F() {} function create(obj) { F.prototype = obj; return new F(); } testCase.context = { create: function (name, tests, parent) { var context = create(this); if (typeof tests === "function") { return asyncContext(context, name, tests, parent); } return createContext(context, name, tests, parent); }, parse: function (forceFocus) { this.getSupportRequirements(); this.deferred = DEFERRED_PREFIX.test(this.name); if (this.parent) { this.deferred = this.deferred || this.parent.deferred; } this.focused = forceFocus || FOCUSED_PREFIX.test(this.name); this.name = this.name. replace(DEFERRED_PREFIX, ""). replace(FOCUSED_PREFIX, ""); this.tests = this.getTests(this.focused); this.contexts = this.getContexts(this.focused); this.focused = this.focused || this.contexts.focused || this.tests.focused; delete this.tests.focused; delete this.contexts.focused; this.contextSetUp = this.getContextSetUp(); this.contextTearDown = this.getContextTearDown(); this.setUp = this.getSetUp(); this.tearDown = this.getTearDown(); return this; }, getSupportRequirements: function () { this.requiresSupportForAll = this.content.requiresSupportForAll || this.content.requiresSupportFor; delete this.content.requiresSupportForAll; delete this.content.requiresSupportFor; this.requiresSupportForAny = this.content.requiresSupportForAny; delete this.content.requiresSupportForAny; }, getTests: function (focused) { var prop, isFunc, tests = []; for (prop in this.content) { isFunc = typeof this.content[prop] === "function"; if (this.isTest(prop)) { var testFocused = focused || FOCUSED_PREFIX.test(prop); tests.focused = tests.focused || testFocused; tests.push({ name: prop.replace(DEFERRED_PREFIX, ""). replace(FOCUSED_PREFIX, ""), func: this.content[prop], context: this, deferred: this.deferred || DEFERRED_PREFIX.test(prop) || !isFunc, focused: testFocused, comment: !isFunc ? this.content[prop] : "" }); } } return tests; }, getContexts: function (focused) { var ctx, prop, contexts = []; contexts.focused = focused; for (prop in this.content) { if (this.isContext(prop)) { ctx = testCase.context.create( prop, this.content[prop], this ); ctx = ctx.parse(focused); contexts.focused = contexts.focused || ctx.focused; contexts.push(ctx); } } return contexts; }, getContextSetUp: function () { return this.content.prepare; }, getContextTearDown: function () { return this.content.conclude; }, getSetUp: function () { return this.content.setUp; }, getTearDown: function () { return this.content.tearDown; }, isTest: function (prop) { var type = typeof this.content[prop]; return this.content.hasOwnProperty(prop) && (type === "function" || type === "string") && !nonTestNames(this)[prop]; }, isContext: function (prop) { return this.content.hasOwnProperty(prop) && typeof this.content[prop] === "object" && !!this.content[prop]; } }; return testCase; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/test-runner", ["bane", "when", "lodash", "async", "platform"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { require("./seedrandom"); module.exports = m( require("bane"), require("when"), require("lodash"), require("async"), require("platform"), function (cb) { process.nextTick(cb); }, true ); }) || function (m) { // In case someone overwrites/mocks out timers later on var setTimeout = window.setTimeout; this.buster = this.buster || {}; this.buster.test = this.buster.test || {}; this.buster.test.runner = m( this.bane, this.when, this._, this.async, this.platform ); })(function (bane, when, _, async, platform, nextTick, isNode) { "use strict"; var onUncaught = function () {}; var partial = function (fn) { var args = [].slice.call(arguments, 1); return function () { return fn.apply(this, args.concat([].slice.call(arguments))); }; }; function F() {} function create(obj) { F.prototype = obj; return new F(); } // Events var errorEvents = { "TimeoutError": "test:timeout", "AssertionError": "test:failure", "DeferredTestError": "test:deferred" }; function emit(runner, event, test, err, thisp) { var data = { name: test.name, runtime: runner.runtime }; if (err) { data.error = err; } if (typeof test.func === "string") { data.comment = test.func; } if (thisp) { data.testCase = thisp; } if (event === "test:success") { data.assertions = runner.assertionCount; } runner.emit(event, data); } function emitTestAsync(runner, test) { if (test && !test.async && !test.deferred) { test.async = true; emit(runner, "test:async", test); } } function testResult(runner, test, err) { if (!test) { err.runtime = runner.runtime; return runner.emit("uncaughtException", err); } if (test.complete) { return; } test.complete = true; var event = "test:success"; if (err) { event = errorEvents[err.name] || "test:error"; if (err.name === "TimeoutError") { emitTestAsync(runner, test); } } emit(runner, event, test, err); if (event === "test:error") { runner.results.errors += 1; } if (event === "test:failure") { runner.results.failures += 1; } if (event === "test:timeout") { runner.results.timeouts += 1; } if (event === "test:deferred") { runner.results.deferred += 1; } else { runner.results.assertions += runner.assertionCount; runner.results.tests += 1; } } function emitIfAsync(runner, test, isAsync) { if (isAsync) { emitTestAsync(runner, test); } } function emitUnsupported(runner, context, requirements) { runner.emit("context:unsupported", { runtime: runner.runtime, context: context, unsupported: requirements }); } // Data helper functions function setUps(context) { var setUpFns = []; while (context) { if (context.setUp) { setUpFns.unshift(context.setUp); } context = context.parent; } return setUpFns; } function tearDowns(context) { var tearDownFns = []; while (context) { if (context.tearDown) { tearDownFns.push(context.tearDown); } context = context.parent; } return tearDownFns; } function satiesfiesRequirement(requirement) { if (typeof requirement === "function") { return !!requirement(); } return !!requirement; } function unsatiesfiedRequirements(context) { var name, requirements = context.requiresSupportForAll; for (name in requirements) { if (!satiesfiesRequirement(requirements[name])) { return [name]; } } var unsatiesfied = []; requirements = context.requiresSupportForAny; for (name in requirements) { if (satiesfiesRequirement(requirements[name])) { return []; } else { unsatiesfied.push(name); } } return unsatiesfied; } function isAssertionError(err) { return err && err.name === "AssertionError"; } function prepareResults(results) { return _.extend({}, results, { ok: results.failures + results.errors + results.timeouts === 0 }); } function propWithDefault(obj, prop, defaultValue) { return obj && obj.hasOwnProperty(prop) ? obj[prop] : defaultValue; } // Async flow function promiseSeries(objects, fn) { var deferred = when.defer(); async.series(_.map(objects, function (obj) { return function (next) { var value = fn(obj); value.then(partial(next, null), next); return value; }; }), function (err) { if (err) { return deferred.reject(err); } deferred.resolve(); }); return deferred.promise; } function asyncDone(resolver) { function resolve(method, err) { try { resolver[method](err); } catch (e) { throw new Error("done() was already called"); } } return function (fn) { if (typeof fn !== "function") { return resolve("resolve"); } return function () { try { var retVal = fn.apply(this, arguments); resolve("resolve"); return retVal; } catch (up) { resolve("reject", up); } }; }; } function asyncFunction(fn, thisp) { if (fn.length > 0) { var deferred = when.defer(); fn.call(thisp, asyncDone(deferred.resolver)); return deferred.promise; } return fn.call(thisp); } function timeoutError(ms) { return { name: "TimeoutError", message: "Timed out after " + ms + "ms" }; } function timebox(promise, timeout, callbacks) { var timedout, complete, timer; function handler(method) { return function () { complete = true; clearTimeout(timer); if (!timedout) { callbacks[method].apply(this, arguments); } }; } when(promise).then(handler("resolve"), handler("reject")); var ms = typeof timeout === "function" ? timeout() : timeout; timer = setTimeout(function () { timedout = true; if (!complete) { callbacks.timeout(timeoutError(ms)); } }, ms); } function callAndWait(func, thisp, timeout, next) { var reject = function (err) { next(err || {}); }; var promise = asyncFunction(func, thisp); timebox(promise, timeout, { resolve: partial(next, null), reject: reject, timeout: reject }); return promise; } function callSerially(functions, thisp, timeout, source) { var d = when.defer(); var fns = functions.slice(); var isAsync = false; function next(err) { if (err) { err.source = source; return d.reject(err); } if (fns.length === 0) { return d.resolve(isAsync); } try { var promise = callAndWait(fns.shift(), thisp, timeout, next); isAsync = isAsync || when.isPromise(promise); } catch (e) { return d.reject(e); } } next(); return d.promise; } function asyncWhen(value) { if (when.isPromise(value)) { return value; } else { var d = when.defer(); TestRunner.prototype.nextTick(partial(d.resolve, value)); return d.promise; } } function chainPromises(fn, resolution) { var r = typeof resolution === "function" ? [resolution, resolution] : resolution; return function () { fn().then(partial(resolution, null), r[0], r[1]); }; } function rejected(deferred) { if (!deferred) { deferred = when.defer(); } deferred.reject(); return deferred.promise; } function listenForUncaughtExceptions() { var listener, listening = false; onUncaught = function (l) { listener = l; if (!listening) { listening = true; process.on("uncaughtException", function (e) { if (listener) { listener(e); } }); } }; } if (typeof process === "object") { listenForUncaughtExceptions(); } // Private runner functions function callTestFn(runner, test, thisp, next) { emit(runner, "test:start", test, null, thisp); if (test.deferred) { return next({ name: "DeferredTestError" }); } try { var promise = asyncFunction(test.func, thisp); if (when.isPromise(promise)) { emitTestAsync(runner, test); } timebox(promise, thisp.timeout || runner.timeout, { resolve: function () { // When the promise resolves, it's a success so we don't // want to propagate the resolution value. If we do, Buster // will think the value represents an error, and will fail // the test. return next.apply(this); }, reject: next, timeout: function (err) { err.source = "test function"; next(err); } }); } catch (e) { next(e); } } function checkAssertions(runner, expected) { if (runner.failOnNoAssertions && runner.assertionCount === 0) { return { name: "AssertionError", message: "No assertions!" }; } var actual = runner.assertionCount; if (typeof expected === "number" && actual !== expected) { return { name: "AssertionError", message: "Expected " + expected + " assertions, ran " + actual }; } } function triggerOnCreate(listeners, runner) { _.each(listeners, function (listener) { listener(runner); }); } function initializeResults() { return { contexts: 0, tests: 0, errors: 0, failures: 0, assertions: 0, timeouts: 0, deferred: 0 }; } function focused(items) { return _.filter(items, function (item) { return item.focused; }); } function dynamicTimeout(testCase, runner) { return function () { return testCase.timeout || runner.timeout; }; } // Craaaazy stuff // https://gist.github.com/982883 function uuid(a) { if (a) { return (a ^ Math.random() * 16 >> a/4).toString(16); } return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, uuid); } function parseRuntime(env) { if (!env) { return null; } var runtime = platform.parse(env); runtime.uuid = uuid(); return runtime; } function countTests(context) { if (!context) { return 0; } if (!_.isArray(context)) { return (context.tests || []).length + countTests(context.contexts); } return _.reduce(context, function (num, ctx) { return num + countTests(ctx); }, 0); } function emitConfiguration(runner, ctxs) { runner.emit("suite:configuration", { runtime: runner.runtime, name: runner.configuration, tests: countTests(ctxs), seed: runner.seed }); } function TestRunner(opt) { triggerOnCreate(TestRunner.prototype.onCreateListeners, this); this.results = initializeResults(); this.runtime = parseRuntime(opt.runtime); this.configuration = opt.configuration; this.clients = 1; this.concurrent = false; if (opt.random === false) { this.randomize = function (coll) { return coll; }; } else { var random = seedRandom(opt.randomSeed); this.seed = random.seed; this.randomize = function (coll) { return coll.sort(function () { return Math.round(random() * 2) - 1; }); }; } this.failOnNoAssertions = propWithDefault( opt, "failOnNoAssertions", false ); if (typeof opt.timeout === "number") { this.timeout = opt.timeout; } } TestRunner.prototype = bane.createEventEmitter({ timeout: 250, onCreateListeners: [], create: function (opt) { return new TestRunner(opt || {}); }, onCreate: function (listener) { this.onCreateListeners.push(listener); }, runSuite: function (ctxs) { this.focusMode = _.some(ctxs, function (c) { return c.focused; }); this.results = initializeResults(); onUncaught(_.bind(function (err) { testResult(this, this.currentTest, err); }, this)); var d = when.defer(); this.emit("suite:start", { runtime: this.runtime }); if (this.runtime) { emitConfiguration(this, ctxs); } if (this.focusMode) { this.emit("runner:focus", { runtime: this.runtime }); } this.results.contexts = ctxs.length; this.runContexts(ctxs).then(_.bind(function () { var res = prepareResults(this.results); res.runtime = this.runtime; this.emit("suite:end", res); d.resolve(res); }, this), d.reject); return d.promise; }, runContexts: function (contexts, thisProto) { var self = this; if (this.focusMode) { contexts = focused(contexts); } return promiseSeries( this.randomize(contexts || []), function (context) { return self.runContext(context, thisProto); } ); }, runContext: function (context, thisProto) { if (!context) { return rejected(); } var reqs = unsatiesfiedRequirements(context); if (reqs.length > 0) { return when(emitUnsupported(this, context, reqs)); } var d = when.defer(), s = this, thisp, ctx; var emitAndResolve = function () { s.emit("context:end", _.extend(context, { runtime: s.runtime })); d.resolve(); }; var end = function (err) { s.runContextUpDown(ctx, "contextTearDown", thisp).then( emitAndResolve, emitAndResolve ); }; this.emit("context:start", _.extend(context, { runtime: this.runtime })); asyncWhen(context).then(function (c) { ctx = c; thisp = create(thisProto || c.testCase); var fns = s.randomize(c.tests); var runTests = chainPromises( _.bind(s.runTests, s, fns, setUps(c), tearDowns(c), thisp), end ); s.runContextUpDown(ctx, "contextSetUp", thisp).then( function () { s.runContexts(c.contexts, thisp).then(runTests); }, end ); }); return d; }, runContextUpDown: function (context, prop, thisp) { var fn = context[prop]; if (!fn) { return when(); } var d = when.defer(); var s = this; var reject = function (err) { err = err || new Error(); err.message = context.name + " " + thisp.name(prop) + "(n) " + (/Timeout/.test(err.name) ? "timed out" : "failed") + ": " + err.message; err.runtime = s.runtime; s.emit("uncaughtException", err); d.reject(err); }; try { var timeout = dynamicTimeout(thisp, this); timebox(asyncFunction(fn, thisp), timeout, { resolve: d.resolve, reject: reject, timeout: reject }); } catch (e) { reject(e); } return d.promise; }, callSetUps: function (test, setUps, thisp) { if (test.deferred) { return when(); } emit(this, "test:setUp", test, null, thisp); var timeout = dynamicTimeout(thisp, this); var emitAsync = partial(emitIfAsync, this, test); return callSerially(setUps, thisp, timeout, "setUp").then( emitAsync ); }, callTearDowns: function (test, tearDowns, thisp) { if (test.deferred) { return when(); } emit(this, "test:tearDown", test, null, thisp); var timeout = dynamicTimeout(thisp, this); var emitAsync = partial(emitIfAsync, this, test); return callSerially(tearDowns, thisp, timeout, "tearDown").then( emitAsync ); }, runTests: function (tests, setUps, tearDowns, thisp) { if (this.focusMode) { tests = focused(tests); } return promiseSeries(tests, _.bind(function (test) { return this.runTest(test, setUps, tearDowns, create(thisp)); }, this)); }, runTest: function (test, setUps, tearDowns, thisp) { this.running = true; var d = when.defer(); test = create(test); this.assertionCount = 0; this.currentTest = test; var callSetUps = _.bind(this.callSetUps, this, test, setUps, thisp); var callTearDowns = _.bind( this.callTearDowns, this, test, tearDowns, thisp ); var callTest = partial(callTestFn, this, test, thisp); var tearDownEmitResolve = _.bind(function (err) { var resolution = _.bind(function (err2) { var e = err || err2 || this.queued; this.running = false; this.queued = null; e = e || checkAssertions(this, thisp.expectedAssertions); testResult(this, test, e); delete this.currentTest; d.resolve(); }, this); callTearDowns().then(partial(resolution, null), resolution); }, this); var callTestAndTearDowns = partial(callTest, tearDownEmitResolve); callSetUps().then(callTestAndTearDowns, tearDownEmitResolve); return d.promise; }, assertionPass: function () { this.assertionCount += 1; }, error: function (error, test) { if (this.running) { if (!this.queued) { this.queued = error; } return; } testResult(this, test || this.currentTest, error); }, // To be removed assertionFailure: function (error) { this.error(error); } }); TestRunner.prototype.nextTick = nextTick || function (cb) { setTimeout(cb, 0); }; return TestRunner.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/reporters/runtime-throttler", ["bane", "lodash"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("bane"), require("lodash")); }) || function (m) { this.buster = this.buster || {}; this.buster.reporters = this.buster.reporters || {}; this.buster.reporters.runtimeThrottler = m(this.bane, this._); } )(function (bane, _) { "use strict"; function runtime(env) { return { uuid: env.uuid, contexts: 0, events: [], queue: function (name, data) { this.events.push({ name: name, data: data }); }, flush: function (emitter) { _.forEach(this.events, function (event) { emitter.emit(event.name, event.data); }); } }; } function getRuntime(runtimes, env) { return runtimes.filter(function (r) { return r.uuid === env.uuid; })[0]; } function proxy(name) { return function (e) { var rt = getRuntime(this.runtimes, e.runtime); if (rt && rt.contexts > 0) { rt.queue(name, e); } else { this.emit(name, e); } }; } function RuntimeThrottler() { this.runtimes = []; this.results = []; } RuntimeThrottler.prototype = bane.createEventEmitter({ create: function () { return new RuntimeThrottler(); }, listen: function (runner) { runner.bind(this); if (runner.console) { runner.console.on("log", this.log, this); } return this; }, "suite:start": function (e) { if (this.runtimes.length === 0) { this.emit("suite:start", {}); } this.runtimes.push(runtime(e.runtime)); }, "suite:configuration": function (e) { this.emit("suite:configuration", e); }, "context:unsupported": function (e) { var rt = getRuntime(this.runtimes, e.runtime); if (rt.contexts === 0) { this.emit("context:unsupported", e); } else { rt.queue("context:unsupported", e); } }, "context:start": function (e) { var rt = getRuntime(this.runtimes, e.runtime); if (this.runtimes.length > 1) { rt.queue("context:start", e); rt.contexts += 1; } else { this.emit("context:start", e); } }, "test:setUp": proxy("test:setUp"), "test:tearDown": proxy("test:tearDown"), "test:start": proxy("test:start"), "test:error": proxy("test:error"), "test:failure": proxy("test:failure"), "test:timeout": proxy("test:timeout"), "test:success": proxy("test:success"), "test:async": proxy("test:async"), "test:deferred": proxy("test:deferred"), "context:end": function (e) { var rt = getRuntime(this.runtimes, e.runtime); if (rt) { rt.queue("context:end", e); rt.contexts -= 1; if (rt.contexts <= 0) { rt.contexts = 0; rt.flush(this); } } else { this.emit("context:end", e); } }, "suite:end": function (e) { this.results.push(e); if (this.results.length === this.runtimes.length || this.runtimes.length === 0) { this.emit("suite:end", _.reduce(this.results, function (res, r) { return { contexts: (res.contexts || 0) + r.contexts, tests: (res.tests || 0) + r.tests, errors: (res.errors || 0) + r.errors, failures: (res.failures || 0) + r.failures, assertions: (res.assertions || 0) + r.assertions, timeouts: (res.timeouts || 0) + r.timeouts, deferred: (res.deferred || 0) + r.deferred, ok: res.ok && r.ok }; }, { ok: true })); } }, "runner:focus": function () { if (!this.runnerFocus) { this.emit("runner:focus"); this.runnerFocus = true; } }, uncaughtException: function (e) { this.emit("uncaughtException", e); }, log: function (e) { this.emit("log", e); } }); return RuntimeThrottler.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/reporters/html", ["buster-test/reporters/runtime-throttler"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { try { var jsdom = require("jsdom").jsdom; } catch (e) { // Is handled when someone actually tries using the HTML reporter // on node without jsdom } module.exports = m(require("./runtime-throttler"), jsdom, true); }) || function (m) { this.buster = this.buster || {}; this.buster.reporters = this.buster.reporters || {}; this.buster.reporters.html = m(this.buster.reporters.runtimeThrottler); } )(function (runtimeThrottler, jsdom, isNodeJS) { "use strict"; function filterStack(reporter, stack) { if (!stack) { return []; } if (reporter.stackFilter) { return reporter.stackFilter.filter(stack); } return stack.split("\n"); } function getDoc(options) { return options && options.document || (typeof document != "undefined" ? document : createDocument()); } function addCSS(head, cssPath) { if (isNodeJS) { var fs = require("fs"); var path = require("path"); head.appendChild(el(head.ownerDocument, "style", { type: "text/css", innerHTML: fs.readFileSync( path.join(__dirname, "../../resources/buster-test.css") ) })); } else { head.appendChild(el(document, "link", { rel: "stylesheet", type: "text/css", media: "all", href: cssPath })); } } function insertTitle(doc, body, title) { if (doc.getElementsByTagName("h1").length == 0) { body.insertBefore(el(doc, "h1", { innerHTML: "<span class=\"title\">" + title + "</span>" }), body.firstChild); } } function insertLogo(h1) { h1.innerHTML = "<span class=\"buster-logo\"></span>" + h1.innerHTML; } function createDocument() { if (!jsdom) { util.puts("Unable to load jsdom, html reporter will not work " + "for node runs. Spectacular fail coming up."); } var dom = jsdom("<!DOCTYPE html><html><head></head><body></body></html>"); return dom.createWindow().document; } function pluralize(num, phrase) { num = typeof num == "undefined" ? 0 : num; return num + " " + (num == 1 ? phrase : phrase + "s"); } function el(doc, tagName, properties) { var el = doc.createElement(tagName), value; for (var prop in properties) { value = properties[prop]; if (prop == "http-equiv") { el.setAttribute(prop, value); } if (prop == "text") { prop = "innerHTML"; } el[prop] = value; } return el; } function addListItem(tagName, test, className) { var prefix = tagName ? "<" + tagName + ">" : ""; var suffix = tagName ? "</" + tagName + ">" : ""; var item = el(this.doc, "li", { className: className, text: prefix + test.name + suffix }); this.list().appendChild(item); return item; } function addException(reporter, li, error) { if (!error) { return; } var name = error.name == "AssertionError" ? "" : error.name + ": "; li.appendChild(el(li.ownerDocument || document, "p", { innerHTML: name + error.message, className: "error-message" })); var stack = filterStack(reporter, error.stack); if (stack.length > 0) { if (stack[0].indexOf(error.message) >= 0) { stack.shift(); } li.appendChild(el(li.ownerDocument || document, "ul", { className: "stack", innerHTML: "<li>" + stack.join("</li><li>") + "</li>" })); } } function busterTestPath(document) { var scripts = document.getElementsByTagName("script"); for (var i = 0, l = scripts.length; i < l; ++i) { if (/buster-test\.js$/.test(scripts[i].src)) { return scripts[i].src.replace("buster-test.js", ""); } } return ""; } function getOutputStream(opt) { if (opt.outputStream) { return opt.outputStream; } if (isNodeJS) { var util = require("util"); return { write: function (bytes) { util.print(bytes); } }; } } function HtmlReporter(opt) { opt = opt || {}; this._listStack = []; this.doc = getDoc(opt); var cssPath = opt.cssPath; if (!cssPath && opt.detectCssPath !== false) { cssPath = busterTestPath(this.doc) + "buster-test.css"; } this.setRoot(opt.root || this.doc.body, cssPath); this.out = getOutputStream(opt); this.stackFilter = opt.stackFilter; } HtmlReporter.prototype = { create: function (opt) { return new HtmlReporter(opt); }, setRoot: function (root, cssPath) { this.root = root; this.root.className += " buster-test"; var body = this.doc.body; if (this.root == body) { var head = this.doc.getElementsByTagName("head")[0]; head.parentNode.className += " buster-test"; head.appendChild(el(this.doc, "meta", { "name": "viewport", "content": "width=device-width, initial-scale=1.0" })); head.appendChild(el(this.doc, "meta", { "http-equiv": "Content-Type", "content": "text/html; charset=utf-8" })); if (cssPath) addCSS(head, cssPath); insertTitle(this.doc, body, this.doc.title || "Buster.JS Test case"); insertLogo(this.doc.getElementsByTagName("h1")[0]); } }, listen: function (runner) { var proxy = runtimeThrottler.create(); proxy.listen(runner).bind(this); if (runner.console) { runner.console.on("log", this.log, this); } return this; }, "context:start": function (context) { var container = this.root; if (this._list) { container = el(this.doc, "li"); this._list.appendChild(container); } container.appendChild(el(this.doc, "h2", { text: context.name })); this._list = el(this.doc, "ul"); container.appendChild(this._list); this._listStack.unshift(this._list); }, "context:end": function (context) { this._listStack.shift(); this._list = this._listStack[0]; }, "test:success": function (test) { var li = addListItem.call(this, "h3", test, "success"); this.addMessages(li); }, "test:failure": function (test) { var li = addListItem.call(this, "h3", test, "failure"); this.addMessages(li); addException(this, li, test.error); }, "test:error": function (test) { var li = addListItem.call(this, "h3", test, "error"); this.addMessages(li); addException(this, li, test.error); }, "test:deferred": function (test) { var li = addListItem.call(this, "h3", test, "deferred"); }, "test:timeout": function (test) { var li = addListItem.call(this, "h3", test, "timeout"); var source = test.error && test.error.source; if (source) { li.firstChild.innerHTML += " (" + source + " timed out)"; } this.addMessages(li); }, log: function (msg) { this.messages = this.messages || []; this.messages.push(msg); }, addMessages: function (li) { var messages = this.messages || []; var html = ""; if (messages.length == 0) { return; } for (var i = 0, l = messages.length; i < l; ++i) { html += "<li class=\"" + messages[i].level + "\">"; html += messages[i].message + "</li>"; } li.appendChild(el(this.doc, "ul", { className: "messages", innerHTML: html })); this.messages = []; }, success: function (stats) { return stats.failures == 0 && stats.errors == 0 && stats.tests > 0 && stats.assertions > 0; }, startTimer: function () { this.startedAt = new Date(); }, "suite:end": function (stats) { var diff = (new Date() - this.startedAt) / 1000; var className = "stats " + (this.success(stats) ? "success" : "failure"); var statsEl = el(this.doc, "div", { className: className }); var h1 = this.doc.getElementsByTagName("h1")[0]; this.root.insertBefore(statsEl, h1.nextSibling); statsEl.appendChild(el(this.doc, "h2", { text: this.success(stats) ? "Tests OK" : "Test failures!" })); var html = ""; html += "<li>" + pluralize(stats.contexts, "test case") + "</li>"; html += "<li>" + pluralize(stats.tests, "test") + "</li>"; html += "<li>" + pluralize(stats.assertions, "assertion") + "</li>"; html += "<li>" + pluralize(stats.failures, "failure") + "</li>"; html += "<li>" + pluralize(stats.errors, "error") + "</li>"; html += "<li>" + pluralize(stats.timeouts, "timeout") + "</li>"; if (stats.deferred > 0) { html += "<li>" + stats.deferred + " deferred</li>"; } statsEl.appendChild(el(this.doc, "ul", { innerHTML: html })); statsEl.appendChild(el(this.doc, "p", { className: "time", innerHTML: "Finished in " + diff + "s" })); this.writeIO(); }, list: function () { if (!this._list) { this._list = el(this.doc, "ul", { className: "test-results" }); this._listStack.unshift(this._list); this.root.appendChild(this._list); } return this._list; }, writeIO: function () { if (!this.out) { return; } this.out.write(this.doc.doctype.toString()); this.out.write(this.doc.innerHTML); } }; return HtmlReporter.prototype; }); if (typeof module === "object" && typeof require === "function") { module.exports = { specification: require("./reporters/specification"), jsonProxy: require("./reporters/json-proxy"), xml: require("./reporters/xml"), tap: require("./reporters/tap"), brief: require("./reporters/brief"), html: require("./reporters/html"), teamcity: require("./reporters/teamcity"), load: function (reporter) { if (module.exports[reporter]) { return module.exports[reporter]; } return require(reporter); } }; module.exports.defaultReporter = module.exports.brief; } else if (typeof define === "function") { define("buster-test/reporters", ["buster-test/reporters/html"], function (html) { var reporters = { html: html, load: function (reporter) { return reporters[reporter]; } }; reporters.defaultReporter = reporters.brief; return reporters; }); } else { buster.reporters = buster.reporters || {}; buster.reporters.defaultReporter = buster.reporters.brief; buster.reporters.load = function (reporter) { return buster.reporters[reporter]; }; } ((typeof define === "function" && define.amd && function (m) { define("buster-test/auto-run", ["lodash", "buster-test/test-context", "buster-test/test-runner", "buster-test/reporters"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m( require("lodash"), require("./test-context"), require("./test-runner"), require("./reporters") ); }) || function (m) { this.buster.autoRun = m( this._, this.buster.testContext, this.buster.testRunner, this.buster.reporters ); })(function (_, testContext, testRunner, reporters) { "use strict"; function browserEnv() { var env = {}; var key, value, pieces, params = window.location.search.slice(1).split("&"); for (var i = 0, l = params.length; i < l; ++i) { pieces = params[i].split("="); key = pieces.shift(); value = pieces.join("=") || "1"; if (key) { key = "BUSTER_" + key.match(/(^|[A-Z])[a-z]+/g).join("_").toUpperCase(); env[key] = value; } } return env; } function env() { if (typeof process !== "undefined") { return process.env; } if (typeof window === "undefined") { return {}; } return browserEnv(); } function autoRun(opt, callbacks) { var runners = 0, contexts = [], timer; testRunner.onCreate(function (runner) { runners += 1; }); if (typeof opt === "function") { callbacks = opt; opt = {}; } if (typeof callbacks !== "object") { callbacks = { end: callbacks }; } return function (tc) { contexts.push(tc); clearTimeout(timer); timer = setTimeout(function () { if (runners === 0) { opt = _.extend(autoRun.envOptions(env()), opt); autoRun.run(contexts, opt, callbacks); } }, 10); }; } autoRun.envOptions = function (env) { return { reporter: env.BUSTER_REPORTER, filters: (env.BUSTER_FILTERS || "").split(","), color: env.BUSTER_COLOR === "false" ? false : true, bright: env.BUSTER_BRIGHT === "false" ? false : true, timeout: env.BUSTER_TIMEOUT && parseInt(env.BUSTER_TIMEOUT, 10), failOnNoAssertions: env.BUSTER_FAIL_ON_NO_ASSERTIONS === "false" ? false : true, random: env.BUSTER_RANDOM === "0" || env.BUSTER_RANDOM === "false" ? false : true, randomSeed: env.BUSTER_RANDOM_SEED }; }; function initializeReporter(runner, opt) { var reporter; if (typeof document !== "undefined" && document.getElementById) { reporter = "html"; opt.root = document.getElementById("buster") || document.body; } else { reporter = opt.reporter || "brief"; } reporter = reporters.load(reporter).create(opt); reporter.listen(runner); if (typeof reporter.log === "function" && typeof buster === "object" && typeof buster.console === "function") { buster.console.on("log", reporter.log, reporter); } } function ua() { if (typeof navigator !== "undefined") { return navigator.userAgent; } return [process.title, process.version + ",", process.platform, process.arch].join(" "); } autoRun.run = function (contexts, opt, callbacks) { callbacks = callbacks || {}; if (contexts.length === 0) { return; } opt = _.extend({ color: true, bright: true }, opt); var runner = testRunner.create(_.extend({ timeout: 750, failOnNoAssertions: false, runtime: ua(), random: typeof opt.random === "boolean" ? opt.random : true, randomSeed: opt.randomSeed }, opt)); if (typeof callbacks.start === "function") { callbacks.start(runner); } initializeReporter(runner, opt); if (typeof callbacks.end === "function") { runner.on("suite:end", callbacks.end); } runner.runSuite(testContext.compile(contexts, opt.filters)); }; return autoRun; }); ((typeof define === "function" && define.amd && function (m) { define("referee-sinon", m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(); }) || function (m) { this.refereeSinon = m(); } )(function () { return function (referee, sinon) { sinon.expectation.pass = function (assertion) { referee.emit("pass", assertion); }; sinon.expectation.fail = function (message) { referee.fail(message); }; // Lazy bind the format method to referee's. This way, Sinon will // always format objects like referee does, even if referee is configured // after referee-sinon is loaded sinon.format = function () { return referee.format.apply(referee, arguments); }; function verifyFakes() { var method, isNot, i, l; for (i = 0, l = arguments.length; i < l; ++i) { method = arguments[i]; isNot = (method || "fake") + " is not "; if (!method) { this.fail(isNot + "a spy"); } if (typeof method !== "function") { this.fail(isNot + "a function"); } if (typeof method.getCall !== "function") { this.fail(isNot + "stubbed"); } } return true; } var sf = sinon.spy.formatters; var spyValues = function (spy) { return [spy, sf.c(spy), sf.C(spy)]; }; referee.add("called", { assert: function (spy) { verifyFakes.call(this, spy); return spy.called; }, assertMessage: "Expected ${0} to be called at least once but was " + "never called", refuteMessage: "Expected ${0} to not be called but was called ${1}${2}", expectation: "toHaveBeenCalled", values: spyValues }); function slice(arr, from, to) { return [].slice.call(arr, from, to); } referee.add("callOrder", { assert: function (spy) { var type = Object.prototype.toString.call(spy); var isArray = type === "[object Array]"; var args = isArray ? spy : arguments; verifyFakes.apply(this, args); if (sinon.calledInOrder(args)) { return true; } this.expected = [].join.call(args, ", "); this.actual = sinon.orderByFirstCall(slice(args)).join(", "); }, assertMessage: "Expected ${expected} to be called in order but " + "were called as ${actual}", refuteMessage: "Expected ${expected} not to be called in order" }); function addCallCountAssertion(count) { var c = count.toLowerCase(); referee.add("called" + count, { assert: function (spy) { verifyFakes.call(this, spy); return spy["called" + count]; }, assertMessage: "Expected ${0} to be called " + c + " but was called ${1}${2}", refuteMessage: "Expected ${0} to not be called exactly " + c + "${2}", expectation: "toHaveBeenCalled" + count, values: spyValues }); } addCallCountAssertion("Once"); addCallCountAssertion("Twice"); addCallCountAssertion("Thrice"); function valuesWithThis(spy, thisObj) { return [spy, thisObj, (spy.printf && spy.printf("%t")) || ""]; } referee.add("calledOn", { assert: function (spy, thisObj) { verifyFakes.call(this, spy); return spy.calledOn(thisObj); }, assertMessage: "Expected ${0} to be called with ${1} as this but was " + "called on ${2}", refuteMessage: "Expected ${0} not to be called with ${1} as this", expectation: "toHaveBeenCalledOn", values: valuesWithThis }); referee.add("alwaysCalledOn", { assert: function (spy, thisObj) { verifyFakes.call(this, spy); return spy.alwaysCalledOn(thisObj); }, assertMessage: "Expected ${0} to always be called with ${1} as this " + "but was called on ${2}", refuteMessage: "Expected ${0} not to always be called with ${1} " + "as this", expectation: "toHaveAlwaysBeenCalledOn", values: valuesWithThis }); function formattedArgs(args, i) { var l, result; for (l = args.length, result = []; i < l; ++i) { result.push(sinon.format(args[i])); } return result.join(", "); } function spyAndCalls(spy) { return [ spy, formattedArgs(arguments, 1), spy.printf && spy.printf("%C") ]; } referee.add("calledWith", { assert: function (spy) { verifyFakes.call(this, spy); return spy.calledWith.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to be called with arguments ${1}${2}", refuteMessage: "Expected ${0} not to be called with arguments ${1}${2}", expectation: "toHaveBeenCalledWith", values: spyAndCalls }); referee.add("alwaysCalledWith", { assert: function (spy) { verifyFakes.call(this, spy); return spy.alwaysCalledWith.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to always be called with " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to always be called with " + "arguments${1}${2}", expectation: "toHaveAlwaysBeenCalledWith", values: spyAndCalls }); referee.add("calledOnceWith", { assert: function (spy) { verifyFakes.call(this, spy); return spy.calledOnce && spy.calledWith.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to be called once with " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to be called once with " + "arguments ${1}${2}", expectation: "toHaveBeenCalledOnceWith", values: spyAndCalls }); referee.add("calledWithExactly", { assert: function (spy) { verifyFakes.call(this, spy); return spy.calledWithExactly.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to be called with exact " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to be called with exact " + "arguments${1}${2}", expectation: "toHaveBeenCalledWithExactly", values: spyAndCalls }); referee.add("alwaysCalledWithExactly", { assert: function (spy) { verifyFakes.call(this, spy); return spy.alwaysCalledWithExactly.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to always be called with exact " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to always be called with exact " + "arguments${1}${2}", expectation: "toHaveAlwaysBeenCalledWithExactly", values: spyAndCalls }); referee.add("calledWithMatch", { assert: function (spy) { verifyFakes.call(this, spy); return spy.calledWithMatch.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to be called with matching " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to be called with matching " + "arguments${1}${2}", expectation: "toHaveAlwaysBeenCalledWithExactly", values: spyAndCalls }); referee.add("alwaysCalledWithMatch", { assert: function (spy) { verifyFakes.call(this, spy); return spy.alwaysCalledWithMatch.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to always be called with matching " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to always be called with matching " + "arguments${1}${2}", expectation: "toHaveAlwaysBeenCalledWithExactly", values: spyAndCalls }); function spyAndException(spy, exception) { return [spy, spy.printf && spy.printf("%C")]; } referee.add("threw", { assert: function (spy) { verifyFakes.call(this, spy); return spy.threw(arguments[1]); }, assertMessage: "Expected ${0} to throw an exception${1}", refuteMessage: "Expected ${0} not to throw an exception${1}", expectation: "toHaveThrown", values: spyAndException }); referee.add("alwaysThrew", { assert: function (spy) { verifyFakes.call(this, spy); return spy.alwaysThrew(arguments[1]); }, assertMessage: "Expected ${0} to always throw an exception${1}", refuteMessage: "Expected ${0} not to always throw an exception${1}", expectation: "toAlwaysHaveThrown", values: spyAndException }); }; }); ((typeof define === "function" && define.amd && function (m) { define("buster-sinon", m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(); }) || function (m) { this.busterSinon = m(); } )(function () { return function (sinon, bt, stackFilter, formatio) { if (stackFilter) { stackFilter.filters.push("lib/sinon"); } bt.testRunner.onCreate(function (runner) { runner.on("test:setUp", function (test) { var config = sinon.getConfig(sinon.config); config.useFakeServer = false; var sandbox = sinon.sandbox.create(); sandbox.inject(test.testCase); test.testCase.useFakeTimers = function () { return sandbox.useFakeTimers.apply(sandbox, arguments); }; test.testCase.useFakeServer = function () { return sandbox.useFakeServer.apply(sandbox, arguments); }; test.testCase.sandbox = sandbox; var testFunc = test.func; }); runner.on("test:tearDown", function (test) { try { test.testCase.sandbox.verifyAndRestore(); } catch (e) { runner.assertionFailure(e); } }); sinon.expectation.pass = function () { runner.assertionPass(); }; }); }; }); (function (glbl, buster, sinon) { if (typeof require == "function" && typeof module == "object") { var busterTest = require("buster-test"); var path = require("path"); var fs = require("fs"); var referee = require("referee"); var stackFilter = require("stack-filter"); sinon = require("sinon"); buster = module.exports = { testCase: busterTest.testCase, spec: busterTest.spec, testRunner: busterTest.testRunner, testContext: busterTest.testContext, reporters: busterTest.reporters, autoRun: busterTest.autoRun, referee: referee, assertions: referee, formatio: require("formatio"), eventedLogger: require("evented-logger"), frameworkExtension: require("./framework-extension"), wiringExtension: require("./wiring-extension"), sinon: require("buster-sinon"), refereeSinon: require("referee-sinon") }; Object.defineProperty(buster, "VERSION", { get: function () { if (!this.version) { var pkgJSON = path.resolve(__dirname, "..", "package.json"); var pkg = JSON.parse(fs.readFileSync(pkgJSON, "utf8")); this.version = pkg.version; } return this.version; } }); } var logFormatter = buster.formatio.configure({ quoteStrings: false }); var asciiFormat = function () { return logFormatter.ascii.apply(logFormatter, arguments); }; if (asciiFormat) { buster.console = buster.eventedLogger.create({ formatter: asciiFormat, logFunctions: true }); } buster.log = function () { return buster.console.log.apply(buster.console, arguments); }; buster.captureConsole = function () { glbl.console = buster.console; if (glbl.console !== buster.console) { glbl.console.log = buster.log; } }; if (asciiFormat) { buster.referee.format = asciiFormat; } buster.assert = buster.referee.assert; buster.refute = buster.referee.refute; buster.expect = buster.referee.expect; if (Object.defineProperty) { Object.defineProperty(buster, "assertions", { get: function () { console.log("buster.assertions is provided for backwards compatibility. Please update your code to use buster.referee"); return buster.referee; } }); Object.defineProperty(buster, "format", { get: function () { console.log("buster.format is provided for backwards compatibility. Please update your code to use buster.formatio"); return buster.formatio; } }); } else { buster.assertions = buster.referee; buster.format = buster.formatio; } buster.testRunner.onCreate(function (runner) { buster.referee.on("pass", function () { runner.assertionPass(); }); buster.referee.on("failure", function (err) { runner.assertionFailure(err); }); runner.on("test:async", function () { buster.referee.throwOnFailure = false; }); runner.on("test:setUp", function () { buster.referee.throwOnFailure = true; }); runner.on("context:start", function (context) { if (context.testCase) { context.testCase.log = buster.log; } }); }); var sf = typeof stackFilter !== "undefined" && stackFilter; buster.sinon(sinon, buster, sf, logFormatter); buster.refereeSinon(buster.referee, sinon); }(typeof global != "undefined" ? global : this, typeof buster == "object" ? buster : null, typeof sinon == "object" ? sinon : null)); (function (B) { B.env = B.env || {}; // Globally uncaught errors will be emitted as messages through // the test runner function uncaughtErrors(runner) { window.onerror = function (message, url, line) { if (arguments.length === 3) { var cp = B.env.contextPath || window.location; var index = (url || "").indexOf(cp); if (index >= 0) { url = "." + url.slice(index + cp.length); } if (line === 1 && message === "Error loading script") { message = "Unable to load script " + url; } else { message = url + ":" + line + " " + message; } } runner.emit("uncaughtException", { name: "UncaughtError", message: message }); return true; }; } // Emit messages from the evented logger buster.console through // the test runner function logger(runner) { B.console.on("log", function (msg) { runner.emit("log", msg); }); } // Collect test cases and specs created with buster.testCase // and buster.spec.describe function testContexts() { var contexts = []; B.addTestContext = function (context) { contexts.push(context); }; B.testContext.on("create", B.addTestContext); return contexts; } // Clear scripts and use the browserEnv object from buster-test to // reset the document between tests runs function documentState(runner) { var scripts = document.getElementsByTagName("script"), script; while ((script = scripts[0])) { script.parentNode.removeChild(script); } var env = B.browserEnv.create(document.body); env.listen(runner); } function shouldAutoRun(config) { var autoRunPropertyIsSet = config.hasOwnProperty("autoRun"); return config.autoRun || !autoRunPropertyIsSet; } function shouldResetDoc(config) { var resetDocumentPropertyIsSet = config.hasOwnProperty("resetDocument"); return config.resetDocument || !resetDocumentPropertyIsSet; } // Wire up the test runner. It will start running tests when // the environment is ready and when we've been told to run. // Note that run() and ready() may occur in any order, and // we cannot do anything until both have happened. // // When running tests with buster-server, we'll be ready() when // the server sends the "tests:run" message. This message is sent // by the server when it receives the "loaded all scripts" message // from the browser. We'll usually run as soon as we're ready. // However, if the autoRun option is false, we will not run // until buster.run() is explicitly called. // // For static browser runs, the environment is ready() when // ready() is called, which happens after all files have been // loaded in the browser. Tests will run immediately for autoRun: // true, and on run() otherwise. // function testRunner(runner) { var ctxts = B.wire.testContexts(); var ready, started, alreadyRunning, config; function attemptRun() { if (!ready || !started || alreadyRunning) { return; } alreadyRunning = true; if (typeof runner === "function") { runner = runner(); } if (shouldResetDoc(config)) { B.wire.documentState(runner); } if (config.captureConsole) { B.captureConsole(); } for (var prop in config) { runner[prop] = config[prop]; } runner.runSuite(B.testContext.compile(ctxts, config.filters)); } return { ready: function (options) { config = options || {}; ready = true; started = started || shouldAutoRun(config); attemptRun(); }, run: function () { started = true; attemptRun(); } }; } B.wire = function (testRunner) { var wiring = B.wire.testRunner(testRunner); B.ready = wiring.ready; B.run = wiring.run; return wiring; }; B.wire.uncaughtErrors = uncaughtErrors; B.wire.logger = logger; B.wire.testContexts = testContexts; B.wire.documentState = documentState; B.wire.testRunner = testRunner; }(buster)); // TMP Performance fix (function () { var i = 0; buster.nextTick = function (cb) { i += 1; if (i === 10) { setTimeout(function () { cb(); }, 0); i = 0; } else { cb(); } }; }()); buster.sinon = sinon; delete this.sinon; delete this.define; delete this.when; delete this.async; delete this.platform; delete this._; if (typeof module === "object" && typeof require === "function") { var buster = module.exports = require("./buster/buster-wiring"); } (function (glbl) { var tc = buster.testContext; if (tc.listeners && (tc.listeners.create || []).length > 0) { return; } tc.on("create", buster.autoRun({ cwd: typeof process != "undefined" ? process.cwd() : null })); }(typeof global != "undefined" ? global : this));
busterjs/lt-instabuster
node_modules/buster/resources/buster-test.js
JavaScript
gpl-3.0
524,225
// This file is part of PapyrusDotNet. // // PapyrusDotNet 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. // // PapyrusDotNet 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 PapyrusDotNet. If not, see <http://www.gnu.org/licenses/>. // // Copyright 2016, Karl Patrik Johansson, zerratar@gmail.com #region using System.Collections.Generic; using System.Linq; using PapyrusDotNet.PapyrusAssembly; #endregion namespace PapyrusDotNet.PexInspector.ViewModels { public class PapyrusParameterEditorViewModel : PapyrusVariableParameterEditorViewModel { private readonly PapyrusParameterDefinition parameter; public PapyrusParameterEditorViewModel(IEnumerable<string> types, PapyrusParameterDefinition parameter = null) : base(types) { this.parameter = parameter; if (this.parameter != null) { Name = this.parameter.Name.Value; if (parameter.TypeName.Value.Contains("[]")) IsArray = true; var ft = parameter.TypeName.Value.ToLower(); ft = ft.Replace("[]", ""); SelectedType = TypeReferences.FirstOrDefault(t => t.ToString().ToLower() == ft); if (SelectedType == null) SelectedType = this.parameter.TypeName.Value.ToLower(); } } } }
zerratar/PapyrusDotNet
Source/PexInspector/PapyrusDotNet.PexInspector.ViewModels/PapyrusParameterEditorViewModel.cs
C#
gpl-3.0
1,906
package cm.aptoide.pt.util; import android.content.Context; public class MarketResourceFormatter { private String marketName; public MarketResourceFormatter(String marketName) { this.marketName = marketName; } public String formatString(Context context, int id, String... optParamaters) { return context.getString(id); } }
Aptoide/aptoide-client-v8
app/src/vanilla/java/cm/aptoide/pt/util/MarketResourceFormatter.java
Java
gpl-3.0
346
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Question controller * * @package mod_groupformation * @author Eduard Gallwas, Johannes Konert, Rene Roepke, Nora Wester, Ahmed Zukic * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * */ require_once($CFG->dirroot . '/mod/groupformation/classes/questionnaire/radio_question.php'); require_once($CFG->dirroot . '/mod/groupformation/classes/questionnaire/topics_table.php'); require_once($CFG->dirroot . '/mod/groupformation/classes/questionnaire/range_question.php'); require_once($CFG->dirroot . '/mod/groupformation/classes/questionnaire/dropdown_question.php'); require_once($CFG->dirroot . '/mod/groupformation/classes/questionnaire/question_table.php'); require_once($CFG->dirroot . '/mod/groupformation/classes/moodle_interface/user_manager.php'); require_once($CFG->dirroot . '/mod/groupformation/classes/moodle_interface/storage_manager.php'); require_once($CFG->dirroot . '/mod/groupformation/classes/util/util.php'); require_once($CFG->dirroot . '/mod/groupformation/classes/util/define_file.php'); require_once($CFG->dirroot . '/mod/groupformation/locallib.php'); if (!defined('MOODLE_INTERNAL')) { die ('Direct access to this script is forbidden.'); // It must be included from a Moodle page. } class mod_groupformation_questionnaire_controller { private $status; private $numbers = array(); private $categories = array(); private $groupformationid; private $store; private $data; private $usermanager; private $scenario; private $lang; private $userid; private $cmid; private $context; private $currentcategoryposition = 0; private $numberofcategory; private $hasanswer; private $currentcategory; private $highlight = false; /** * mod_groupformation_questionnaire_controller constructor. * @param $groupformationid * @param $lang * @param $userid * @param $oldcategory * @param $cmid */ public function __construct($groupformationid, $lang, $userid, $oldcategory, $cmid) { $this->groupformationid = $groupformationid; $this->lang = $lang; $this->userid = $userid; $this->cmid = $cmid; $this->store = new mod_groupformation_storage_manager ($groupformationid); $this->data = new mod_groupformation_data(); $this->usermanager = new mod_groupformation_user_manager ($groupformationid); $this->scenario = $this->store->get_scenario(); $this->categories = $this->store->get_categories(); $this->numberofcategory = count($this->categories); $this->init($userid); $this->set_internal_number($oldcategory); $this->context = context_module::instance($this->cmid); } /** * Triggers going a category page back */ public function go_back() { $this->currentcategoryposition = max($this->currentcategoryposition - 2, 0); } /** * Regulates not going on and highlighting missing answers */ public function not_go_on() { $this->currentcategoryposition = max($this->currentcategoryposition - 1, 0); $this->highlight = true; } /** * Returns percent of progress in questionnaire * * @param string $category * @return number */ public function get_percent($category = null) { if (!is_null($category)) { $categories = $this->store->get_categories(); $pos = array_search($category, $categories); return 100.0 * ((1.0 * $pos) / count($categories)); } $total = 0; $sub = 0; $temp = 0; foreach ($this->numbers as $num) { if ($num != 0) { $total++; if ($temp < $this->currentcategoryposition) { $sub++; } } $temp++; } return ($sub / $total) * 100; } /** * Handles initialization * * @param unknown $userid */ private function init($userid) { if (!$this->store->catalog_table_not_set()) { $this->numbers = $this->store->get_numbers($this->categories); } $this->status = $this->usermanager->get_answering_status($userid); } /** * Sets internal page number * * @param unknown $category */ private function set_internal_number($category) { if ($category != "") { $this->currentcategoryposition = $this->store->get_position($category); $this->currentcategoryposition++; } } /** * Returns whether there is a next category or not * * @return boolean */ public function has_next() { return ($this->currentcategoryposition != -1 && $this->currentcategoryposition < $this->numberofcategory); } /** * Returns question in current language or possible default language * * @param int $i * @param int $version * @return stdClass */ public function get_question($i, $version) { $record = $this->store->get_catalog_question($i, $this->currentcategory, $this->lang, $version); if (empty ($record)) { if ($this->lang != 'en') { $record = $this->store->get_catalog_question($i, $this->currentcategory, $this->lang, $version); } else { $lang = $this->store->get_possible_language($this->currentcategory); $record = $this->store->get_catalog_question($i, $this->currentcategory, $lang, $version); } } return $record; } /** * Returns whether current category is 'topic' or not * * @return boolean */ public function is_topics() { return $this->currentcategoryposition == $this->store->get_position('topic'); } /** * Returns whether current category is 'knowledge' or not * * @return boolean */ public function is_knowledge() { return $this->currentcategoryposition == $this->store->get_position('knowledge'); } /** * Returns whether current category is 'points' or not * * @return boolean */ public function is_points() { return $this->currentcategoryposition == $this->store->get_position('points'); } /** * Returns questions * * @return array */ public function get_next_questions() { if ($this->currentcategoryposition != -1) { $questions = array(); $this->hasanswer = $this->usermanager->has_answers($this->userid, $this->currentcategory); if ($this->is_knowledge() || $this->is_topics()) { $temp = $this->store->get_knowledge_or_topic_values($this->currentcategory); $xmlcontent = '<?xml version="1.0" encoding="UTF-8" ?> <OPTIONS> ' . $temp . ' </OPTIONS>'; $values = mod_groupformation_util::xml_to_array($xmlcontent); $text = ''; $type = 'range'; if ($this->is_topics()) { $type = 'topics'; } $options = $options = array( 100 => get_string('excellent', 'groupformation'), 0 => get_string('none', 'groupformation')); $position = 1; $questionsfirst = array(); $answerposition = array(); $i = 1; foreach ($values as $value) { $question = array(); $question ['type'] = $type; $question ['question'] = $text . $value; $question ['options'] = $options; if ($this->hasanswer) { $answer = $this->usermanager->get_single_answer( $this->userid, $this->currentcategory, $position); if ($answer != false) { $question ['answer'] = $answer; } else { $question ['answer'] = -1; } $answerposition [$answer] = $position - 1; $position++; } else { $question ['answer'] = -1; } $question ['questionid'] = $i; $questionsfirst [] = $question; $i++; } $l = count($answerposition); if ($l > 0 && $this->currentcategoryposition == $this->store->get_position('topic')) { for ($k = 1; $k <= $l; $k++) { $h = $questionsfirst [$answerposition [$k]]; $h ['answer'] = $answerposition [$k]; $questions [] = $h; } } else { $questions = $questionsfirst; } } else if ($this->is_points()) { $records = $this->store->get_questions_randomized_for_user($this->currentcategory, $this->userid); foreach ($records as $record) { $question = array(); if (count($record) == 0) { echo '<div class="alert">'; echo 'This questionnaire site is neither available in your favorite language nor in english!'; echo '</div>'; return null; } else { $question ['type'] = 'range'; $question ['question'] = $record->question; $question ['questionid'] = $record->questionid; $question ['options'] = array( $this->store->get_max_points() => get_string('excellent', 'groupformation'), 0 => get_string('bad', 'groupformation')); $answer = $this->usermanager->get_single_answer($this->userid, $this->currentcategory, $record->questionid); if ($answer != false) { $question ['answer'] = $answer; } else { $question ['answer'] = -1; } } $questions [] = $question; } } else { $records = $this->store->get_questions_randomized_for_user($this->currentcategory, $this->userid); foreach ($records as $record) { $question = $this->prepare_question($record); $questions [] = $question; } } return $questions; } } /** * Returns question array constructed by question record * * * @param unknown $record * @return multitype:number NULL multitype:string Ambigous <number, mixed> */ public function prepare_question($record) { $question = array(); if (count($record) == 0) { echo '<div class="alert">This questionnaire site is neither available in your favorite language nor in english!</div>'; return null; } else { $question ['type'] = $record->type; $question ['question'] = $record->question; $question ['questionid'] = $record->questionid; $temp = '<?xml version="1.0" encoding="UTF-8" ?> <OPTIONS> ' . $record->options . ' </OPTIONS>'; $question ['options'] = mod_groupformation_util::xml_to_array($temp); $answer = $this->usermanager->get_single_answer($this->userid, $this->currentcategory, $record->questionid); if ($answer != false) { $question ['answer'] = intval($answer); } else { $question ['answer'] = -1; } } return $question; } /** * Prints action buttons for questionnaire page */ public function print_action_buttons() { echo '<div class="grid"> <div class="col_m_100 questionaire_button_row"> <button type="submit" name="direction" value="0" class="gf_button gf_button_pill gf_button_small">' . get_string('previous') . '</button> <button type="submit" name="direction" value="1" class="gf_button gf_button_pill gf_button_small">' . get_string('next') . '</button> </div> </div>'; } /** * Prints navigation bar * * @param string $activecategory */ public function print_navbar($activecategory = null) { $tempcategories = $this->store->get_categories(); $categories = array(); foreach ($tempcategories as $category) { if ($this->store->get_number($category) > 0) { $categories [] = $category; } } echo '<div id="questionaire_navbar">'; echo '<ul id="accordion">'; $prevcomplete = !$this->data->all_answers_required(); foreach ($categories as $category) { $url = new moodle_url ('questionnaire_view.php', array( 'id' => $this->cmid, 'category' => $category)); $positionactivecategory = $this->store->get_position($activecategory); $positioncategory = $this->store->get_position($category); $beforeactive = ($positioncategory <= $positionactivecategory); $class = 'no-active'; if (has_capability('mod/groupformation:editsettings', $this->context) || $beforeactive || $prevcomplete) { $class = ''; } echo '<li class="' . (($activecategory == $category) ? 'current' : 'accord_li') . '">'; echo '<span>' . ($positioncategory + 1) . '</span><a class="' . $class . '" href="' . $url . '">' . get_string('category_' . $category, 'groupformation') . '</a>'; echo '</li>'; } echo '</ul>'; echo '</div>'; } /** * Prints final page of questionnaire */ public function print_final_page() { echo '<div class="col_m_100"><h4>' . get_string('questionnaire_no_more_questions', 'groupformation') . '</h></div>'; echo ' <form action="' . htmlspecialchars($_SERVER ["PHP_SELF"]) . '" method="post" autocomplete="off">'; echo ' <input type="hidden" name="category" value="no"/>'; echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />'; $activityid = optional_param('id', $this->groupformationid, PARAM_INT); echo ' <input type="hidden" name="id" value="' . $activityid . '"/>'; if (has_capability('mod/groupformation:editsettings', $this->context)) { echo '<div class="alert col_m_100 questionaire_hint">' . get_string('questionnaire_submit_disabled_teacher', 'groupformation') . '</div>'; } $url = new moodle_url ('/mod/groupformation/view.php', array( 'id' => $this->cmid, 'do_show' => 'view')); echo '<div class="grid">'; echo ' <div class="questionaire_button_text">' . get_string('questionnaire_press_beginning_submit', 'groupformation') . '</div>'; echo ' <div class="col_m_100 questionaire_button_row">'; echo ' <a href=' . $url->out() . '><span class="gf_button gf_button_pill gf_button_small">' . get_string('questionnaire_go_to_start', 'groupformation') . '</span></a>'; echo ' </div>'; echo '</div>'; echo '</form>'; } /** * Prints questionnaire page */ public function print_page() { if ($this->has_next()) { $this->currentcategory = $this->categories[$this->currentcategoryposition]; $isteacher = has_capability('mod/groupformation:editsettings', $this->context); if ($isteacher) { echo '<div class="alert">' . get_string('questionnaire_preview', 'groupformation') . '</div>'; } if ($this->usermanager->is_completed($this->userid) || !$this->store->is_questionnaire_available()) { echo '<div class="alert" id="commited_view">' . get_string('questionnaire_committed', 'groupformation') . '</div>'; } $category = $this->currentcategory; $percent = $this->get_percent($category); if ($this->store->ask_for_participant_code() && !$isteacher) { $this->print_participant_code(); } $this->print_navbar($category); $this->print_progressbar($percent); $questions = $this->get_next_questions(); $this->print_questions($questions, $percent); // Log access to page. groupformation_info($this->userid, $this->groupformationid, '<view_questionnaire_category_' . $category . '>'); } else { $this->print_final_page(); if ($this->usermanager->has_answered_everything($this->userid)) { $this->usermanager->set_evaluation_values($this->userid); } // Log access to page. groupformation_info($this->userid, $this->groupformationid, '<view_questionnaire_final_page>'); } } /** * Prints table with questions * * @param array $questions * @param unknown $percent */ public function print_questions($questions, $percent) { echo '<form style="width:100%; float:left;" action="' . htmlspecialchars($_SERVER ["PHP_SELF"]) . '" method="post" autocomplete="off">'; if (!is_null($questions) && count($questions) != 0) { $tabletype = $questions [0]['type']; $headeroptarray = $questions [0] ['options']; $category = $this->currentcategory; $table = new mod_groupformation_question_table (); $topics = new mod_groupformation_topics_table (); // Here is the actual category and groupformationid is sent hidden. echo '<input type="hidden" name="category" value="' . $category . '"/>'; echo '<input type="hidden" name="percent" value="' . $percent . '"/>'; echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />'; $activityid = optional_param('id', $this->groupformationid, PARAM_INT); echo '<input type="hidden" name="id" value="' . $activityid . '"/>'; echo ' <h4 class="view_on_mobile">' . get_string('category_' . $category, 'groupformation') . '</h4>'; // Print the header of a table or unordered list. $table->print_header($category, $tabletype, $headeroptarray); foreach ($questions as $q) { $questionid = $q['questionid']; $question = $q ['question']; $options = $q ['options']; $answer = $q ['answer']; $type = $q['type']; if ($type == 'topics') { $topics->print_html($question, $category, $answer + 1); } else { $name = 'mod_groupformation_' . $type . '_question'; $object = new $name(); $object->print_html($category, $questionid, $question, $options, $answer, $this->highlight); } } // Print the footer of a table or unordered list. $table->print_footer($tabletype); } $this->print_action_buttons(); echo '</form>'; } /** * Prints progress bar * * @param unknown $percent */ public function print_progressbar($percent) { echo '<div class="progress">'; echo ' <div class="questionaire_progress-bar" role="progressbar" aria-valuenow="' . $percent . '" aria-valuemin="0" aria-valuemax="100" style="width:' . $percent . '%"></div>'; echo '</div>'; } /** * Prints participant code for user */ public function print_participant_code() { echo '<div class="participantcode">'; echo get_string('participant_code_footer', 'groupformation'); echo ': '; echo $this->usermanager->get_participant_code($this->userid); echo '</div>'; } /** * Saves answers for user * * @param $category * @return bool */ public function save_answers($category) { $go = true; $number = $this->store->get_number($category); if ($category == 'topic') { for ($i = 1; $i <= $number; $i++) { $temp = $category . $i; $paratemp = optional_param($temp, null, PARAM_ALPHANUM); if (isset ($paratemp)) { $this->usermanager->save_answer($this->userid, $category, $paratemp, $i); } } } else if ($category == 'knowledge') { for ($i = 1; $i <= $number; $i++) { $tempvalidaterangevalue = $category . $i . '_valid'; $temp = $category . $i; $paravalidaterange = optional_param($tempvalidaterangevalue, null, PARAM_ALPHANUM); $paratemp = optional_param($temp, null, PARAM_ALPHANUM); if (isset ($paratemp) && $paravalidaterange == '1') { $this->usermanager->save_answer($this->userid, $category, $paratemp, $i); } } } else { $questions = $this->store->get_questions_randomized_for_user($category, $this->userid); foreach ($questions as $question) { $temp = $category . $question->questionid; $paratemp = optional_param($temp, null, PARAM_ALPHANUM); if (isset($paratemp)) { $this->usermanager->save_answer($this->userid, $category, $paratemp, $question->questionid); } } } if ($this->data->all_answers_required() && $this->usermanager->get_number_of_answers( $this->userid, $category) != $number) { $go = false; } return $go; } }
nitro2010/moodle
mod/groupformation/classes/controller/questionnaire_controller.php
PHP
gpl-3.0
23,044
define("view/mission", ["jquery", "laces.tie", "lodash", "view", "tmpl/joboutput", "tmpl/mission"], function($, Laces, _, View, tmpl) { "use strict"; return View.extend({ initialize: function(options) { this.mission = options.mission; this.mission.jobs.on("add", this._onNewJobs, { context: this }); this.subscribe("server-push:missions:job-output", this._onJobOutput); this.$jobs = null; }, events: { "click .action-expand-job": "_expandJob" }, remove: function() { this.mission.jobs.off("add", this._onNewJobs); }, render: function() { var lastJob = this.mission.jobs[this.mission.jobs.length - 1]; if (lastJob) { lastJob.expanded = true; lastJob.fetchResults({ context: this }).then(function() { var tie = new Laces.Tie(lastJob, tmpl.joboutput); var $jobOutput = this.$(".js-job-output[data-job-id='" + lastJob.id + "']"); $jobOutput.replaceWith(tie.render()); }); } var tie = new Laces.Tie(this.mission, tmpl.mission); this.$el.html(tie.render()); this.$jobs = this.$(".js-jobs"); _.each(this.mission.jobs, _.bind(this._renderJob, this)); return this.$el; }, _expandJob: function(event) { var jobId = this.targetData(event, "job-id"); var job = _.find(this.mission.jobs, { id: jobId }); job.expanded = !job.expanded; if (job.expanded) { job.fetchResults(); } }, _onNewJobs: function(event) { _.each(event.elements, _.bind(this._renderJob, this)); }, _onJobOutput: function(data) { if (data.missionId === this.mission.id) { var job = _.find(this.mission.jobs, { id: data.jobId }); if (job && job.expanded) { var $output = this.$(".js-job-output[data-job-id=" + $.jsEscape(data.jobId) + "] .js-output"); if ($output.length) { $output[0].innerHTML += $.colored(data.output); } } } }, _renderJob: function(job) { if (this.$jobs) { var tie = new Laces.Tie(job, tmpl.joboutput); this.$jobs.prepend(tie.render()); } } }); });
arendjr/CI-Joe
www/js/view/mission.js
JavaScript
gpl-3.0
2,619
#include "NPC.h" #include "Application.h" #include "ModuleEntityManager.h" #include "Player.h" #include "ModuleCamera.h" #include "ModuleAudio.h" #include <random> NPC::NPC(Entity::Types entityType, iPoint iniPos, short int hp, Direction facing) : Creature(entityType, iniPos, hp, facing) { facing = LEFT; } NPC::~NPC() {} bool NPC::Start() { if (NPC::LoadConfigFromJSON(CONFIG_FILE) == false) return false; return Creature::Start(); } bool NPC::LoadConfigFromJSON(const char* fileName) { JSON_Value* root_value; JSON_Object* moduleObject; root_value = json_parse_file(fileName); if (root_value != nullptr) moduleObject = json_object(root_value); else return false; if (soundFxNPCHit == 0) soundFxNPCHit = App->audio->LoadFx(json_object_dotget_string(moduleObject, "NPC.soundFxNPCHit")); if (soundFxNPCDie == 0) soundFxNPCDie = App->audio->LoadFx(json_object_dotget_string(moduleObject, "NPC.soundFxNPCDie")); json_value_free(root_value); return true; } // Update: draw background update_status NPC::Update() { behaviour(); Creature::Update(); return UPDATE_CONTINUE; } void NPC::hit(Creature* c2) { App->audio->PlayFx(soundFxNPCHit); Creature::hit(c2); } void NPC::die() { App->audio->PlayFx(soundFxNPCDie); Creature::die(); } void NPC::behaviour() { // If the Player is in attack range then attack: attack or retreat // else if the Player is close be aggressive: attack, chase, retreat // else take it easy: patrol, wait switch (action) { case APPROACH: if (position.x > App->entities->player->position.x) velocity.x = -1.0f; else velocity.x = 1.0f; if (depth > App->entities->player->depth) --depth; else if (depth < App->entities->player->depth) ++depth; if (getDistanceToPlayer() < 50 && abs(depth - App->entities->player->depth) <= DEPTH_THRESHOLD + 2) { if (canBeAttacked()) { NPCTimer.reset(); action = ATTACK; } else { NPCTimer.reset(); action = WAIT; } } break; case WAIT: velocity = { 0.0f, 0.0f }; if (status != UNAVAILABLE && NPCTimer.getDelta() > waitingTime) { action = APPROACH; } break; case ATTACK: velocity = { 0.0f, 0.0f }; status = ATTACKING; setCurrentAnimation(&attack); attackTimer.reset(); NPCTimer.reset(); action = ATTACK_RECOVER; break; case ATTACK_RECOVER: // if the hit has landed continue to attack // else retreat if (NPCTimer.getDelta() > 300) if (getDistanceToPlayer() < 50 && abs(depth - App->entities->player->depth) <= DEPTH_THRESHOLD + 2) { if (canBeAttacked()) { NPCTimer.reset(); action = ATTACK; } else { NPCTimer.reset(); action = WAIT; } } break; } } void NPC::chooseNextAction() { /* if (getDistanceToPlayer() < 50) { if (rollDice(2) == 1) { action = ATTACK; attack(); } else { action = RETREAT; retreat(); } } else if (getDistanceToPlayer() < 150) { // action = CHASE; chase(); } else { if (rollDice(2) == 1) { action = PATROL; switch (rollDice(8)) { case 1: velocity = { 0.0f, -1.0f }; break; case 2: velocity = { 1.0f, -1.0f }; break; case 3: velocity = { 1.0f, 0.0f }; break; case 4: velocity = { 1.0f, 1.0f }; break; case 5: velocity = { 0.0f, 1.0f }; break; case 6: velocity = { -1.0f, 1.0f }; break; case 7: velocity = { -1.0f, 0.0f }; break; case 8: velocity = { -1.0f, -1.0f }; break; } } else { action = WAIT; velocity = { 0.0f, 0.0f }; waitingTime = 500 + 100 * rollDice(5); } } NPCTimer.reset();*/ } float NPC::getDistanceToPlayer() const { short int depthDist = this->depth - App->entities->player->depth; short int xDist = this->position.x - App->entities->player->position.x; return (float)(sqrt(pow(depthDist, 2) + pow(xDist, 2))); } const unsigned short int NPC::rollDice(unsigned short int nrDiceFaces) const { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, nrDiceFaces); return dis(gen); } void NPC::retreat() { if (getDistanceToPlayer() < 100) getAwayFromPlayer(); } void NPC::getAwayFromPlayer() { if (App->entities->player->position.x + App->camera->coord.x > (int)(SCREEN_WIDTH / 2)) this->velocity.x = -2.0f; else this->velocity.x = 2.0f; if (App->entities->player->depth > (int)(53 / 2)) this->velocity.y = 1.0f; else this->velocity.y = -1.0f; } void NPC::chase() { if (App->entities->player->position.x + App->camera->coord.x > (int)(SCREEN_WIDTH / 2)) this->velocity.x = +2.0f; else this->velocity.x = -2.0f; if (App->entities->player->depth > (int)(53 / 2)) this->velocity.y = -1.0f; else this->velocity.y = +1.0f; } /*void NPC::doAttack() { status = ATTACKING; setCurrentAnimation(&chop); }*/
azarrias/sor
src/NPC.cpp
C++
gpl-3.0
4,702
package com.koushikdutta.async.http.server; import android.annotation.TargetApi; import android.content.Context; import android.content.res.AssetManager; import android.os.Build; import android.text.TextUtils; import com.koushikdutta.async.AsyncSSLSocket; import com.koushikdutta.async.AsyncSSLSocketWrapper; import com.koushikdutta.async.AsyncServer; import com.koushikdutta.async.AsyncServerSocket; import com.koushikdutta.async.AsyncSocket; import com.koushikdutta.async.ByteBufferList; import com.koushikdutta.async.DataEmitter; import com.koushikdutta.async.Util; import com.koushikdutta.async.callback.CompletedCallback; import com.koushikdutta.async.callback.ListenCallback; import com.koushikdutta.async.http.AsyncHttpGet; import com.koushikdutta.async.http.AsyncHttpHead; import com.koushikdutta.async.http.AsyncHttpPost; import com.koushikdutta.async.http.Headers; import com.koushikdutta.async.http.HttpUtil; import com.koushikdutta.async.http.Multimap; import com.koushikdutta.async.http.Protocol; import com.koushikdutta.async.http.WebSocket; import com.koushikdutta.async.http.WebSocketImpl; import com.koushikdutta.async.http.body.AsyncHttpRequestBody; import com.koushikdutta.async.util.StreamUtility; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; @TargetApi(Build.VERSION_CODES.ECLAIR) public class AsyncHttpServer { ArrayList<AsyncServerSocket> mListeners = new ArrayList<AsyncServerSocket>(); public void stop() { if (mListeners != null) { for (AsyncServerSocket listener: mListeners) { listener.stop(); } } } protected boolean onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) { return false; } protected void onRequest(HttpServerRequestCallback callback, AsyncHttpServerRequest request, AsyncHttpServerResponse response) { if (callback != null) callback.onRequest(request, response); } protected AsyncHttpRequestBody onUnknownBody(Headers headers) { return new UnknownRequestBody(headers.get("Content-Type")); } ListenCallback mListenCallback = new ListenCallback() { @Override public void onAccepted(final AsyncSocket socket) { AsyncHttpServerRequestImpl req = new AsyncHttpServerRequestImpl() { HttpServerRequestCallback match; String fullPath; String path; boolean responseComplete; boolean requestComplete; AsyncHttpServerResponseImpl res; boolean hasContinued; @Override protected AsyncHttpRequestBody onUnknownBody(Headers headers) { return AsyncHttpServer.this.onUnknownBody(headers); } @Override protected void onHeadersReceived() { Headers headers = getHeaders(); // should the negotiation of 100 continue be here, or in the request impl? // probably here, so AsyncResponse can negotiate a 100 continue. if (!hasContinued && "100-continue".equals(headers.get("Expect"))) { pause(); // System.out.println("continuing..."); Util.writeAll(mSocket, "HTTP/1.1 100 Continue\r\n\r\n".getBytes(), new CompletedCallback() { @Override public void onCompleted(Exception ex) { resume(); if (ex != null) { report(ex); return; } hasContinued = true; onHeadersReceived(); } }); return; } // System.out.println(headers.toHeaderString()); String statusLine = getStatusLine(); String[] parts = statusLine.split(" "); fullPath = parts[1]; path = fullPath.split("\\?")[0]; method = parts[0]; synchronized (mActions) { ArrayList<Pair> pairs = mActions.get(method); if (pairs != null) { for (Pair p: pairs) { Matcher m = p.regex.matcher(path); if (m.matches()) { mMatcher = m; match = p.callback; break; } } } } res = new AsyncHttpServerResponseImpl(socket, this) { @Override protected void report(Exception e) { super.report(e); if (e != null) { socket.setDataCallback(new NullDataCallback()); socket.setEndCallback(new NullCompletedCallback()); socket.close(); } } @Override protected void onEnd() { super.onEnd(); mSocket.setEndCallback(null); responseComplete = true; // reuse the socket for a subsequent request. handleOnCompleted(); } }; boolean handled = onRequest(this, res); if (match == null && !handled) { res.code(404); res.end(); return; } if (!getBody().readFullyOnRequest()) { onRequest(match, this, res); } else if (requestComplete) { onRequest(match, this, res); } } @Override public void onCompleted(Exception e) { // if the protocol was switched off http, ignore this request/response. if (res.code() == 101) return; requestComplete = true; super.onCompleted(e); // no http pipelining, gc trashing if the socket dies // while the request is being sent and is paused or something mSocket.setDataCallback(new NullDataCallback() { @Override public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) { super.onDataAvailable(emitter, bb); mSocket.close(); } }); handleOnCompleted(); if (getBody().readFullyOnRequest()) { onRequest(match, this, res); } } private void handleOnCompleted() { if (requestComplete && responseComplete) { if (HttpUtil.isKeepAlive(Protocol.HTTP_1_1, getHeaders())) { onAccepted(socket); } else { socket.close(); } } } @Override public String getPath() { return path; } @Override public Multimap getQuery() { String[] parts = fullPath.split("\\?", 2); if (parts.length < 2) return new Multimap(); return Multimap.parseQuery(parts[1]); } }; req.setSocket(socket); socket.resume(); } @Override public void onCompleted(Exception error) { report(error); } @Override public void onListening(AsyncServerSocket socket) { mListeners.add(socket); } }; public AsyncServerSocket listen(AsyncServer server, int port) { return server.listen(null, port, mListenCallback); } private void report(Exception ex) { if (mCompletedCallback != null) mCompletedCallback.onCompleted(ex); } public AsyncServerSocket listen(int port) { return listen(AsyncServer.getDefault(), port); } public void listenSecure(final int port, final SSLContext sslContext) { AsyncServer.getDefault().listen(null, port, new ListenCallback() { @Override public void onAccepted(AsyncSocket socket) { AsyncSSLSocketWrapper.handshake(socket, null, port, sslContext.createSSLEngine(), null, null, false, new AsyncSSLSocketWrapper.HandshakeCallback() { @Override public void onHandshakeCompleted(Exception e, AsyncSSLSocket socket) { if (socket != null) mListenCallback.onAccepted(socket); } }); } @Override public void onListening(AsyncServerSocket socket) { mListenCallback.onListening(socket); } @Override public void onCompleted(Exception ex) { mListenCallback.onCompleted(ex); } }); } public ListenCallback getListenCallback() { return mListenCallback; } CompletedCallback mCompletedCallback; public void setErrorCallback(CompletedCallback callback) { mCompletedCallback = callback; } public CompletedCallback getErrorCallback() { return mCompletedCallback; } private static class Pair { Pattern regex; HttpServerRequestCallback callback; } final Hashtable<String, ArrayList<Pair>> mActions = new Hashtable<String, ArrayList<Pair>>(); public void removeAction(String action, String regex) { synchronized (mActions) { ArrayList<Pair> pairs = mActions.get(action); if (pairs == null) return; for (int i = 0; i < pairs.size(); i++) { Pair p = pairs.get(i); if (regex.equals(p.regex.toString())) { pairs.remove(i); return; } } } } public void addAction(String action, String regex, HttpServerRequestCallback callback) { Pair p = new Pair(); p.regex = Pattern.compile("^" + regex); p.callback = callback; synchronized (mActions) { ArrayList<Pair> pairs = mActions.get(action); if (pairs == null) { pairs = new ArrayList<AsyncHttpServer.Pair>(); mActions.put(action, pairs); } pairs.add(p); } } public static interface WebSocketRequestCallback { public void onConnected(WebSocket webSocket, AsyncHttpServerRequest request); } public void websocket(String regex, final WebSocketRequestCallback callback) { websocket(regex, null, callback); } public void websocket(String regex, final String protocol, final WebSocketRequestCallback callback) { get(regex, new HttpServerRequestCallback() { @Override public void onRequest(final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) { boolean hasUpgrade = false; String connection = request.getHeaders().get("Connection"); if (connection != null) { String[] connections = connection.split(","); for (String c: connections) { if ("Upgrade".equalsIgnoreCase(c.trim())) { hasUpgrade = true; break; } } } if (!"websocket".equalsIgnoreCase(request.getHeaders().get("Upgrade")) || !hasUpgrade) { response.code(404); response.end(); return; } String peerProtocol = request.getHeaders().get("Sec-WebSocket-Protocol"); if (!TextUtils.equals(protocol, peerProtocol)) { response.code(404); response.end(); return; } callback.onConnected(new WebSocketImpl(request, response), request); } }); } public void get(String regex, HttpServerRequestCallback callback) { addAction(AsyncHttpGet.METHOD, regex, callback); } public void post(String regex, HttpServerRequestCallback callback) { addAction(AsyncHttpPost.METHOD, regex, callback); } public static android.util.Pair<Integer, InputStream> getAssetStream(final Context context, String asset) { AssetManager am = context.getAssets(); try { InputStream is = am.open(asset); return new android.util.Pair<Integer, InputStream>(is.available(), is); } catch (IOException e) { return null; } } static Hashtable<String, String> mContentTypes = new Hashtable<String, String>(); { mContentTypes.put("js", "application/javascript"); mContentTypes.put("json", "application/json"); mContentTypes.put("png", "image/png"); mContentTypes.put("jpg", "image/jpeg"); mContentTypes.put("html", "text/html"); mContentTypes.put("css", "text/css"); mContentTypes.put("mp4", "video/mp4"); mContentTypes.put("mov", "video/quicktime"); mContentTypes.put("wmv", "video/x-ms-wmv"); } public static String getContentType(String path) { String type = tryGetContentType(path); if (type != null) return type; return "text/plain"; } public static String tryGetContentType(String path) { int index = path.lastIndexOf("."); if (index != -1) { String e = path.substring(index + 1); String ct = mContentTypes.get(e); if (ct != null) return ct; } return null; } public void directory(Context context, String regex, final String assetPath) { final Context _context = context.getApplicationContext(); addAction(AsyncHttpGet.METHOD, regex, new HttpServerRequestCallback() { @Override public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) { String path = request.getMatcher().replaceAll(""); android.util.Pair<Integer, InputStream> pair = getAssetStream(_context, assetPath + path); if (pair == null || pair.second == null) { response.code(404); response.end(); return; } final InputStream is = pair.second; response.getHeaders().set("Content-Length", String.valueOf(pair.first)); response.code(200); response.getHeaders().add("Content-Type", getContentType(assetPath + path)); Util.pump(is, response, new CompletedCallback() { @Override public void onCompleted(Exception ex) { response.end(); StreamUtility.closeQuietly(is); } }); } }); addAction(AsyncHttpHead.METHOD, regex, new HttpServerRequestCallback() { @Override public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) { String path = request.getMatcher().replaceAll(""); android.util.Pair<Integer, InputStream> pair = getAssetStream(_context, assetPath + path); if (pair == null || pair.second == null) { response.code(404); response.end(); return; } final InputStream is = pair.second; StreamUtility.closeQuietly(is); response.getHeaders().set("Content-Length", String.valueOf(pair.first)); response.code(200); response.getHeaders().add("Content-Type", getContentType(assetPath + path)); response.writeHead(); response.end(); } }); } public void directory(String regex, final File directory) { directory(regex, directory, false); } public void directory(String regex, final File directory, final boolean list) { assert directory.isDirectory(); addAction("GET", regex, new HttpServerRequestCallback() { @Override public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) { String path = request.getMatcher().replaceAll(""); File file = new File(directory, path); if (file.isDirectory() && list) { ArrayList<File> dirs = new ArrayList<File>(); ArrayList<File> files = new ArrayList<File>(); for (File f: file.listFiles()) { if (f.isDirectory()) dirs.add(f); else files.add(f); } Comparator<File> c = new Comparator<File>() { @Override public int compare(File lhs, File rhs) { return lhs.getName().compareTo(rhs.getName()); } }; Collections.sort(dirs, c); Collections.sort(files, c); files.addAll(0, dirs); return; } if (!file.isFile()) { response.code(404); response.end(); return; } try { FileInputStream is = new FileInputStream(file); response.code(200); Util.pump(is, response, new CompletedCallback() { @Override public void onCompleted(Exception ex) { response.end(); } }); } catch (FileNotFoundException ex) { response.code(404); response.end(); } } }); } private static Hashtable<Integer, String> mCodes = new Hashtable<Integer, String>(); static { mCodes.put(200, "OK"); mCodes.put(206, "Partial Content"); mCodes.put(101, "Switching Protocols"); mCodes.put(301, "Moved Permanently"); mCodes.put(302, "Found"); mCodes.put(404, "Not Found"); } public static String getResponseCodeDescription(int code) { String d = mCodes.get(code); if (d == null) return "Unknown"; return d; } }
omerjerk/RemoteDroid
app/src/main/java/com/koushikdutta/async/http/server/AsyncHttpServer.java
Java
gpl-3.0
20,350
function GCList(field, multipleSelection, uploadFile, refreshParent = false) { this.field = field; this.multipleSelection = multipleSelection; this.uploadFile = uploadFile; this.refreshParent = refreshParent; this.dialogId = 'list_dialog'; this.options = {}; this.urls = { 'ajax/dataList.php': ['data'], 'ajax/fileList.php': ['filename'], 'ajax/lookupList.php': ['lookup_table'], 'ajax/fieldList.php': ['class_text', 'label_angle', 'label_color', 'label_outlinecolor', 'label_size', 'label_font', 'label_priority', 'angle', 'color', 'outlinecolor', 'size', 'labelitem', 'labelsizeitem', 'classitem', 'classtitle', 'field_name', 'qt_field_name', 'data_field_1', 'data_field_2', 'data_field_3', 'table_field_1', 'table_field_2', 'table_field_3', 'filter_field_name'], 'ajax/dbList.php': ['field_format', 'table_name', 'symbol_ttf_name', 'symbol_name', 'symbol_user_pixmap'], 'ajax/fontList.php': ['symbol_user_font'] }; this.requireSquareBrackets = ['class_text', 'label_angle', 'label_color', 'label_outlinecolor', 'label_size', 'label_font', 'label_priority', 'angle', 'color', 'outlinecolor', 'size', 'classtitle']; this.listData = {}; this.selectedData = {}; this.currentStep = null; this.totSteps = null; this.getUrl = function() { var self = this; var requestUrl = null; $.each(self.urls, function (url, fields) { if ($.inArray(self.field, fields) > -1) { requestUrl = url; return false; } }); if (requestUrl === null) { alert('Not implemented'); return; } return requestUrl; }; this.getParams = function(data) { var params = {}; if (!$.isArray(data)) { if (data.length > 0) { data = data.split('@'); } else { data = new Array(); } } $.each(data, function (e, field) { if ($('#' + field).length > 0 && $('#' + field).val()) { params[field] = $('#' + field).val(); } }); return params; }; this.checkResponse = function(response) { var errorMsg = null; if (typeof response !== 'object') { errorMsg = 'response is not in JSON format'; } else if (response === null) { errorMsg = 'response is null'; } else if (typeof response.result === 'undefined' || response.result !== 'ok') { errorMsg = 'invalid result field'; } else if ( typeof response.fields !== 'object' || typeof response.data !== 'object' || typeof response.step === 'undefined' || typeof response.steps === 'undefined') { errorMsg = 'invalid server response format'; } else if (typeof response.error !== 'undefined') { if ($.inArray(response.error, ['catalog_id', 'layertype_id', 'data']) > -1) { errorMsg = 'invalid '.response.error; } else { errorMsg = response.error; } } return errorMsg; }; this.loadStructuredList = function (params) { $.extend(this.selectedData, params); params.selectedField = this.field; var component = $('#' + this.dialogId).find('div'); $('#' + this.dialogId).find('table').css("display", "none"); component.css("display", ""); component.empty(); component.append(ajaxBuildSelector(this, params, "main")); component.addClass("treeMenuDiv"); if(!this.uploadFile) { component.css("max-height", "95%"); $(".uploadFile_listDialog").css("display","none"); } $('#main').treeview(); createFileListBehaviour(params['selectedField'], this.multipleSelection); } this.loadList = function (params) { var self = this; var dialogId = this.dialogId; var options = this.options; var dialogElement = $('#' + dialogId); dialogElement.find('div').css("display", "none"); var resultTable = dialogElement.find('table'); resultTable.css("display", ""); var requestUrl = self.getUrl(); self.listData = {}; $.extend(self.selectedData, params); params.selectedField = self.field; if(!this.uploadFile) { dialogElement.css("max-height", "100%"); $(".uploadFile_listDialog").css("display","none"); } $.ajax({ url: requestUrl, type: 'POST', dataType: 'json', data: params, success: function (response) { var errorMsg = self.checkResponse(response); if (errorMsg !== null) { alert('Error: ' + errorMsg); dialogElement.dialog('close'); return; } resultTable.empty(); self.currentStep = response.step; self.totSteps = response.steps; // create table header var html = '<tr>'; $.each(response.fields, function (fieldName, fieldTitle) { html += '<th class="tableSelectorHeader">' + fieldTitle + '</th>'; }); html += '</tr>'; // add rows with symbols to table $.each(response.data, function (rowId, rowData) { html += '<tr data-row_id=' + rowId + '>'; $.each(response.fields, function (fieldName, foo) { if (typeof rowData[fieldName] === 'undefined' || rowData[fieldName] === null) { html += '<td class="data-' + fieldName + ' tableSelectorRow"></td>'; return; } html += '<td class="data-' + fieldName + ' tableSelectorRow">' + rowData[fieldName] + '</td>'; }); html += '</tr>'; }); resultTable.append(html); $.each(response.data_objects, function (rowId, rowData) { self.listData[rowId] = rowData; }); resultTable.find('td').hover(function () { $(this).css('cursor', 'pointer'); }, function () { $(this).css('cursor', 'default'); }); if (typeof options.handle_click === 'undefined' || options.handle_click) { resultTable.find('td').click(function (event) { var rowId = $(this).parent().attr('data-row_id'); $.extend(self.selectedData, self.listData[rowId]); if (self.currentStep == self.totSteps || typeof (self.listData[rowId].is_final_step) != 'undefined' && self.listData[rowId].is_final_step == 1) { $.each(self.selectedData, function (key, val) { if ($.inArray(key, self.requireSquareBrackets) > -1) val = '[' + val + ']'; $('#' + key).val(val); }); dialogElement.dialog('close'); //questa istruzione funziona solo nel caso openListAndRefreshEntity venga invocato //a livello di configurazione layer. Negli altri casi non ci entra... - MZ if(self.refreshParent) { var input = $("<input>").attr("type", "hidden").attr("name", "reloadFields").val("true"); $('#frm_data').append($(input)); } } else { self.currentStep += 1; if(self.selectedData.directory != undefined && self.selectedData.directory.endsWith("../")) { var navDir = self.selectedData.directory.replace("../",""); var index = (navDir.substr(0, navDir.length -1 )).lastIndexOf("/"); var back = navDir.substr(0, index + 1); self.selectedData.directory = (back != "") ? back : undefined; } self.selectedData.step = self.currentStep; self.loadList(self.selectedData); } }); } if (typeof options.events !== 'undefined' && typeof options.events.list_loaded !== 'undefined') { options.events.list_loaded(); } }, error: function () { alert('AJAX request returned with error'); } }); }; this.loadData = function(params, callback) { var self = this; var requestUrl = self.getUrl(); params.selectedField = self.field; $.ajax({ url: requestUrl, type: 'POST', dataType: 'json', data: params, success: function (response) { var errorMsg = self.checkResponse(response); if (errorMsg !== null) { alert('Error'); return; } callback(response); }, error: function () { alert('AJAX request returned with error'); } }); }; } function getSelectedField(txt_field) { var selectedField; if (txt_field.indexOf('.') > 0) { var tmp = txt_field.split('.'); selectedField = tmp[0]; } else { selectedField = txt_field; } return selectedField; } function openListAndRefreshEntity(txt_field, data) { genericOpenList(txt_field, data, true); } function openList(txt_field, data) { genericOpenList(txt_field, data); } function genericOpenList(txt_field, data, refresh = false) { var selectedField = getSelectedField(txt_field); $('#list_dialog').dialog({ width: 500, height: 350, title: '', modal: true, open: function () { var list = new GCList(selectedField, false, false, refresh); list.loadList(list.getParams(data)); } }); } function openFileTree(txt_field, data, multipleSelection = false, uploadFile = false) { var selectedField = getSelectedField(txt_field); var list = new GCList(selectedField, multipleSelection, uploadFile); $('#list_dialog').dialog({ width: 500, height: 350, title: '', modal: true, open: function () { list.loadStructuredList(list.getParams(data)); } }); $('#submitFile').click(function(event) { event.preventDefault(); var file_data = $('#fileToUpload').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); $.ajax({ url: 'ajax/upload.php', dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(response){ if(response!="") alert(response); // display response from the PHP script, if any else { list.loadFileList(list.getParams(data)); $('#fileToUpload').val(""); } } }); }); } function buildSelector(response, obj, directory, id) { if(response.fields['file'] != undefined && response.fields['file'] != null) $('#' + obj.dialogId ).dialog("option", "title", response.fields['file']); var html = ""; if(response.data_objects.length > 0) { if(id != undefined) { html += "<ul id=\""+id+"\" class=\"filetree treeview-famfamfam\">"; html += "<li><span class='folder'>" html += (obj.multipleSelection ? "<input type=\"checkbox\" id=\"p_ckb_\">" : ""); html += "</span>"; } html += "<ul>"; $.each(response.data_objects, function(rowId, rowData) { obj.listData[rowId] = rowData; if(rowData['directory'] != undefined && rowData['directory']!= null && !rowData['directory'].endsWith("../")){ html += "<li><span class='folder'>"; html += (obj.multipleSelection ? "<input type=\"checkbox\" id=\"p_ckb_"+directoryForCheckbox(rowData['directory'])+"\">" : ""); html += directoryForTreeOutput(rowData['directory'])+"</span>"; html += ajaxBuildSelector(obj, $.extend({}, obj.selectedData, obj.listData[rowId])); html += "</li>"; } else if(rowData[obj.field] != undefined && rowData[obj.field]!= null) { var check = fieldContainsString($("#"+obj.field).val(), directory+rowData[obj.field]); html += "<li><span class='file'><input type=\"checkbox\" "+(check ? "checked" : "")+" id=\"ckb_" + directoryForCheckbox(directory)+rowData[obj.field]+"\" name=\"checkList\" value=\""+directory+rowData[obj.field] + "\"/>"+rowData[obj.field]+"</span></li>"; if(!directory) checkTreeConsistency("ckb_"+directoryForCheckbox(directory), check); } }); html += '</ul>'; if(id != undefined) { html += "</li></ul>"; } } else { html += "<ul id=\""+id+"\" class=\"filetree treeview-famfamfam\">"; html += "<li><span class='folder'>- no files -</span>"; html += "</li></ul>"; } return html; } function fieldContainsString(fieldVal, searchKey) { var arr = fieldVal.split(' '); var result = false $.each(arr, function(index, val) { if(val == searchKey) { result = true; return false; } }); return result; } function directoryForTreeOutput(inputDir) { var output = inputDir.substring(0, inputDir.length-1); return output.lastIndexOf("/")!=-1 ? output.substring(output.lastIndexOf("/")+1) : output; } function directoryForCheckbox(inputDir) { return inputDir.replace(/\//g,"_"); } function ajaxBuildSelector(obj, params, id){ var result = ""; $.ajax({ url: obj.getUrl(), type: 'POST', async: false, dataType: 'json', data: params, success: function (response) { var errorMsg = obj.checkResponse(response); if (errorMsg !== null) { alert('Error: ' + errorMsg); $('#' + obj.dialogId ).dialog('close'); return; } var directory = params['directory']!=undefined ? params['directory'] : ""; // create table header result = buildSelector(response, obj, directory, id); }, error: function () { alert('AJAX request returned with error'); } }); return result; } function populateTextField(field, checked, value) { //circondo stringa con spazi in modo da poter essere sicuro di beccare esattamente la stringa che mi interessa in caso di "eliminazione" var fieldText = checked ? $('#' + field).val() : " "+$('#' + field).val()+" "; fieldText = $.trim(checked ? fieldText.concat(" " + value) : fieldText.replace(new RegExp("[ ]{1}"+value+"[ ]{1}"), " ")); $('#' + field).val(fieldText.replace(/\s+/g, " ")); } function updateExtent(txt_field) { var selectedField = getSelectedField(txt_field); var data = ["catalog_id", "layertype_id", "layergroup", "project", "data", "data_geom", "data_type", "data_srid"]; var list = new GCList(selectedField); var params = list.getParams(data); // skip step params.step = 1; // force request for data_extent params.data_extent = null; list.loadData(params, function(response) { $.each(response.data_objects, function (rowId, rowData) { if (rowData.data_unique === $('#data_unique').val()) { $('#data_extent').val(rowData.data_extent); } }); }); } function createFileListBehaviour(field, multipleSelection) { $('[id^=p_ckb_]').change(function() { var newstate = $(this).is(":checked") ? ":not(:checked)" : ":checked"; var id_leaf = $(this).attr("id").substring(2); $('[id^='+$(this).attr("id")+']'+newstate).click(); $('[id^='+id_leaf+']'+newstate).click(); }); $('[id^=ckb_]').change(function() { var checked = $(this).is(":checked"); var currentId = $(this).attr("id"); var currentFile = $(this).val().substring($(this).val().lastIndexOf("/")+1); if(!multipleSelection) { var group = "input:checkbox[name='checkList']"; $(group).prop("checked", false); $(this).prop("checked", checked); $("#" + field).val(""); } populateTextField(field, checked, $(this).val()); var dirId = currentId.replace(currentFile, ""); checkTreeConsistency(dirId, checked); }); } function checkTreeConsistency(parentDir, check) { var workingDir = parentDir; var allSelected = ($('[id^='+workingDir+']').length == $('[id^='+workingDir+']:checked').length); if((check && allSelected) || !check) { $("#p_"+workingDir).attr("checked", check); workingDir = workingDir.substring(0, workingDir.length -1); if (workingDir.indexOf("_") != -1) checkTreeConsistency(workingDir.substring(0, workingDir.lastIndexOf("_") + 1), check); } }
OldSnapo/gisclient-3
public/admin/js/list.js
JavaScript
gpl-3.0
17,763
// QChartGallery.js --- // // Author: Julien Wintz // Created: Thu Feb 13 23:43:13 2014 (+0100) // Version: // Last-Updated: // By: // Update #: 13 // // Change Log: // // // ///////////////////////////////////////////////////////////////// // Line Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartLineData = { labels: [], datasets: [{ fillColor: "rgba(151,187,205,0.5)", strokeColor: "grey", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "grey", data: [] }/**, { fillColor: "rgba(151,187,205,0.5)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#ffffff", data: [] }**/] } // ///////////////////////////////////////////////////////////////// // Polar Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartPolarData = [{ value: 30, color: "#D97041" }, { value: 90, color: "#C7604C" }, { value: 24, color: "#21323D" }, { value: 58, color: "#9D9B7F" }, { value: 82, color: "#7D4F6D" }, { value: 8, color: "#584A5E" }] // ///////////////////////////////////////////////////////////////// // Radar Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartRadarData = { labels: ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"], datasets: [{ fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", data: [65,59,90,81,56,55,40] }, { fillColor: "rgba(151,187,205,0.5)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", data: [28,48,40,19,96,27,100] }] } // ///////////////////////////////////////////////////////////////// // Pie Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartPieData = [{ value: 30, color: "#F38630" }, { value: 50, color: "#E0E4CC" }, { value: 100, color: "#69D2E7" }] // ///////////////////////////////////////////////////////////////// // Doughnut Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartDoughnutData = [{ value: 30, color: "#F7464A" }, { value: 50, color: "#E2EAE9" }, { value: 100, color: "#D4CCC5" }, { value: 40, color: "#949FB1" }, { value: 120, color: "#4D5360" }] // ///////////////////////////////////////////////////////////////// // Bar Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartBarData = { labels: ["January","February","March","April","May","June","July"], datasets: [{ fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,1)", data: [65,59,90,81,56,55,40] }, { fillColor: "rgba(151,187,205,0.5)", strokeColor: "rgba(151,187,205,1)", data: [28,48,40,19,96,27,100] }] }
SensorNet-UFAL/environmentMonitoring
laccansense/jbQuick/QChartGallery.js
JavaScript
gpl-3.0
3,346