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 com.brejza.matt.habmodem;
import group.pals.android.lib.ui.filechooser.FileChooserActivity;
import group.pals.android.lib.ui.filechooser.io.localfile.LocalFile;
import java.io.File;
import java.util.List;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.view.Menu;
public class StartActivity extends Activity implements FirstRunMessage.NoticeDialogListener, MapFileMessage.NoticeDialogListener {
private static final int _ReqChooseFile = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_start, menu);
return true;
}
@Override
public void onResume()
{
super.onResume();
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("firstrun1", false);
if (!firstrun){
FragmentManager fm = getFragmentManager();
FirstRunMessage di = new FirstRunMessage();
di.show(fm, "firstrun");
}
else
{
String mapst = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getString("pref_map_path", "");
File file = new File(mapst);
if(file.exists())
{
//start main activity
Intent intent = new Intent(this, Map_Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity(intent);
finish();
}
else
{
FragmentManager fm = getFragmentManager();
MapFileMessage di = new MapFileMessage();
di.show(fm, "mapmessage");
}
}
}
@Override
public void onDialogPositiveClickFirstRun(DialogFragment dialog) {
// TODO Auto-generated method stub
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("firstrun1", true)
.commit();
FragmentManager fm = getFragmentManager();
MapFileMessage di = new MapFileMessage();
di.show(fm, "mapmessage");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case _ReqChooseFile:
if (resultCode == RESULT_OK) {
List<LocalFile> files = (List<LocalFile>)
data.getSerializableExtra(FileChooserActivity._Results);
for (File f : files)
{
PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).edit().putString("pref_map_path", f.getPath()).commit();
System.out.println(f.toString());
}
}
break;
}
}
private void showMapChooser()
{
Intent intent = new Intent(StartActivity.this, FileChooserActivity.class);
intent.putExtra(FileChooserActivity._Rootpath, (Parcelable) new LocalFile(Environment.getExternalStorageDirectory().getPath() ));
intent.putExtra(FileChooserActivity._RegexFilenameFilter, "(?si).*\\.(map)$");
intent.putExtra(FileChooserActivity._Theme, android.R.style.Theme_Dialog);
startActivityForResult(intent, _ReqChooseFile);
}
@Override
public void onDialogNegativeClickFirstRun(DialogFragment dialog) {
// TODO Auto-generated method stub
this.finish();
}
@Override
public void onDialogPositiveClickMapHelp(DialogFragment dialog) {
// TODO Auto-generated method stub
showMapChooser();
}
@Override
public void onDialogNegativeClickMapHelp(DialogFragment dialog) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, StatusScreen.class);
startActivity(intent);
}
}
| mattbrejza/rtty_modem | habmodem/src/com/brejza/matt/habmodem/StartActivity.java | Java | gpl-3.0 | 4,104 |
#!/usr/bin/env python
# sample module
from jira.client import JIRA
def main():
jira = JIRA()
JIRA(options={'server': 'http://localhost:8100'})
projects = jira.projects()
print projects
for project in projects:
print project.key
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main() | selvait90/jira-automation | sample.py | Python | gpl-3.0 | 349 |
package ai.hellbound;
import l2s.commons.util.Rnd;
import l2s.gameserver.ai.CtrlEvent;
import l2s.gameserver.ai.Mystic;
import l2s.gameserver.model.Creature;
import l2s.gameserver.model.Playable;
import l2s.gameserver.model.World;
import l2s.gameserver.model.instances.NpcInstance;
import bosses.BelethManager;
/**
* @author pchayka
*/
public class Beleth extends Mystic
{
private long _lastFactionNotifyTime = 0;
private static final int CLONE = 29119;
public Beleth(NpcInstance actor)
{
super(actor);
}
@Override
protected void onEvtDead(Creature killer)
{
BelethManager.setBelethDead();
super.onEvtDead(killer);
}
@Override
protected void onEvtAttacked(Creature attacker, int damage)
{
NpcInstance actor = getActor();
if(System.currentTimeMillis() - _lastFactionNotifyTime > _minFactionNotifyInterval)
{
_lastFactionNotifyTime = System.currentTimeMillis();
for(NpcInstance npc : World.getAroundNpc(actor))
if(npc.getNpcId() == CLONE)
npc.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, attacker, Rnd.get(1, 100));
}
super.onEvtAttacked(attacker, damage);
}
@Override
protected boolean randomWalk()
{
return false;
}
@Override
protected boolean randomAnimation()
{
return false;
}
@Override
public boolean canSeeInSilentMove(Playable target)
{
return true;
}
@Override
public boolean canSeeInHide(Playable target)
{
return true;
}
@Override
public void addTaskAttack(Creature target)
{
return;
}
} | pantelis60/L2Scripts_Underground | dist/gameserver/data/scripts/ai/hellbound/Beleth.java | Java | gpl-3.0 | 1,491 |
#ifndef PHOTONS_PhaseSpace_Generate_Dipole_Photon_Angle_H
#define PHOTONS_PhaseSpace_Generate_Dipole_Photon_Angle_H
#include "ATOOLS/Math/Vector.H"
namespace PHOTONS {
class Generate_Dipole_Photon_Angle {
private:
double m_b1;
double m_b2;
double m_c;
double m_theta;
double m_phi;
ATOOLS::Vec4D m_dir;
double CalculateBeta(const ATOOLS::Vec4D&);
void GenerateDipoleAngle();
void GenerateNullVector();
public:
Generate_Dipole_Photon_Angle(ATOOLS::Vec4D, ATOOLS::Vec4D);
Generate_Dipole_Photon_Angle(const double&, const double&);
~Generate_Dipole_Photon_Angle();
inline double GetCosTheta() { return m_c; }
inline double GetTheta() { return m_theta; }
inline double GetPhi() { return m_phi; }
inline const ATOOLS::Vec4D& GetVector() { return m_dir; }
};
/*!
\file Generate_Dipole_Photon_Angle.H
\brief contains the class Generate_Dipole_Photon_Angle
*/
/*!
\class Generate_Dipole_Photon_Angle
\brief generates the photon angular distribution in dipoles
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// Description of the member variables for Generate_Dipole_Photon_Angle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*!
\var double Generate_Dipole_Photon_Angle::m_b1
\brief \f$ \beta_1 \f$
*/
/*!
\var double Generate_Dipole_Photon_Angle::m_b2
\brief \f$ \beta_2 \f$
*/
/*!
\var double Generate_Dipole_Photon_Angle::m_c
\brief \f$ c = \cos\theta \f$
*/
/*!
\var double Generate_Dipole_Photon_Angle::m_theta
\brief \f$ \theta \f$
*/
/*!
\var double Generate_Dipole_Photon_Angle::m_phi
\brief \f$ \varphi \f$
*/
/*!
\var Vec4D Generate_Dipole_Photon_Angle::m_dir
\brief null vector of unit spatial length in direction \f$ (\theta,\varphi) \f$
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// Description of member methods for Generate_Dipole_Photon_Angle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*!
\fn Generate_Dipole_Photon_Angle::Generate_Dipole_Photon_Angle(Vec4D, Vec4D)
\brief generates dipole angles for two arbitrary timelike 4-vectors \f$ p_1 \f$ and \f$ p_2 \f$
\f$ p_1 \f$ and \f$ p_2 \f$ are boosted in their CMS, there the photon angles are calculated and m_dir is generated. Finally, m_dir is boosted to the original system of \f$ p_1 \f$ and \f$ p_2 \f$ and \f$ \theta \f$ and \f$ \varphi \f$ are recalculated.
This constructor is used by the Generate_Multipole_Photon_Angle class.
*/
/*!
\fn Generate_Dipole_Photon_Angle::Generate_Dipole_Photon_Angle(double, double)
\brief generates dipole angles for two 4-vectors with \f$ \beta_1 \f$ and \f$ \beta_2 \f$ assumed to be in their CMS and aligned along the z-axis
Both angles are calculated via <tt>GenerateDipoleAngle()</tt>. No null vector will be produced.
This constructor is used by the Generate_One_Photon class.
*/
/*!
\fn double Generate_Dipole_Photon_Angle::CalculateBeta(Vec4D)
\brief calculates \f$ \beta \f$ for a given 4-vector
*/
/*!
\fn void Generate_Dipole_Photon_Angle::GenerateDipoleAngle()
\brief generates both photon angles
Works in the dipole's CMS. \f$ \varphi \f$ is distributed uniformly, \f$ \theta \f$ according to the eikonal factor \f$ \tilde{S}_{ij} \f$ .
*/
/*!
\fn void Generate_Dipole_Photon_Angle::GenerateNullVector()
\brief m_dir is generated
This null vector can be Poincare transformed to any frame to have the photon angular configuration there. To get the full photon its energy/3-momentum simply has to be multiplied by the generated energy.
*/
/*!
\fn double Generate_Dipole_Photon_Angle::GetCosTheta()
\brief returns m_c ( \f$ c = \cos\theta \f$ )
*/
/*!
\fn double Generate_Dipole_Photon_Angle::GetTheta()
\brief returns m_theta ( \f$ \theta \f$ )
*/
/*!
\fn double Generate_Dipole_Photon_Angle::GetPhi()
\brief returns m_phi ( \f$ \varphi \f$ )
*/
/*!
\fn Vec4D Generate_Dipole_Photon_Angle::GetVector()
\brief returns m_dir
*/
}
// this class will take two four vectors and generate a null vector of unit 3D length which is distributed according to eikonal factor
// if two doubles (b1,b2) are given it assumed they are in their respective rest frame and then this vector is generated in that frame
#endif
| cms-externals/sherpa | PHOTONS++/PhaseSpace/Generate_Dipole_Photon_Angle.H | C++ | gpl-3.0 | 4,769 |
/**********************************************************
* Filename: MDBRow.cpp
* Text Encoding: utf-8
*
* Description:
*
*
* Author: moxichang (ishego@gmail.com)
* Harbin Engineering University
* Information Security Research Center
*
*********************************************************/
#include "Exception.h"
#include "MDB/MDBRow.h"
MDB::MDBRow:: MDBRow(MDBField** fields_, int numcols_ )
: field_m(fields_), numcols_m(numcols_)
{
}
MDB::MDBRow:: ~MDBRow()
{
for(int i=0; i< numcols_m; i++)
{
delete field_m[i];
}
delete [] field_m;
}
MDB::MDBField& MDB::MDBRow:: operator [] (int index_)
{
if(index_ >= numcols_m || index_ < 0)
{
Throw("Row index out of range", MException::ME_OUTRANGE);
}
return **(field_m + index_);
}
| moxichang/libmo | src/MDB/MDBRow.cpp | C++ | gpl-3.0 | 801 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Model")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Model")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4d2c65ee-e3a3-41f0-aeef-4b412134fa25")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| brusini/SimpleTwitter | Model/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,422 |
<?php
// include.php - Handles options for subscribe2
// DO NOT EDIT THIS FILE AS IT IS SET BY THE OPTIONS PAGE
if (!isset($this->subscribe2_options['autosub'])) {
$this->subscribe2_options['autosub'] = "no";
} // option to autosubscribe registered users to new categories
if (!isset($this->subscribe2_options['newreg_override'])) {
$this->subscribe2_options['newreg_override'] = "no";
} // option to autosubscribe registered users to new categories
if (!isset($this->subscribe2_options['wpregdef'])) {
$this->subscribe2_options['wpregdef'] = "no";
} // option to check registration form box by default
if (!isset($this->subscribe2_options['autoformat'])) {
$this->subscribe2_options['autoformat'] = "post";
} // option for default auto-subscription email format
if (!isset($this->subscribe2_options['show_autosub'])) {
$this->subscribe2_options['show_autosub'] = "yes";
} // option to display auto-subscription option to registered users
if (!isset($this->subscribe2_options['autosub_def'])) {
$this->subscribe2_options['autosub_def'] = "yes";
} // option for user default auto-subscription to new categories
if (!isset($this->subscribe2_options['comment_subs'])) {
$this->subscribe2_options['comment_subs'] = "no";
} // option for commenters to subscribe as public subscribers
if (!isset($this->subscribe2_options['comment_def'])) {
$this->subscribe2_options['comment_def'] = "no";
} // option for comments box to be checked by default
if (!isset($this->subscribe2_options['one_click_profile'])) {
$this->subscribe2_options['one_click_profile'] = "no";
} // option for displaying 'one-click' option on profile page
if (!isset($this->subscribe2_options['bcclimit'])) {
$this->subscribe2_options['bcclimit'] = 1;
} // option for default bcc limit on email notifications
if (!isset($this->subscribe2_options['admin_email'])) {
$this->subscribe2_options['admin_email'] = "subs";
} // option for sending new subscriber notifications to admins
if (!isset($this->subscribe2_options['tracking'])) {
$this->subscribe2_options['tracking'] = "";
} // option for tracking
if (!isset($this->subscribe2_options['s2page'])) {
$this->subscribe2_options['s2page'] = 0;
} // option for default WordPress page for Subscribe2 to use
if (!isset($this->subscribe2_options['stylesheet'])) {
$this->subscribe2_options['stylesheet'] = "yes";
} // option to include link to theme stylesheet from HTML notifications
if (!isset($this->subscribe2_options['pages'])) {
$this->subscribe2_options['pages'] = "no";
} // option for sending notifications for WordPress pages
if (!isset($this->subscribe2_options['password'])) {
$this->subscribe2_options['password'] = "no";
} // option for sending notifications for posts that are password protected
if (!isset($this->subscribe2_options['stickies'])) {
$this->subscribe2_options['stickies'] = "no";
} // option for including sticky posts in digest notifications
if (!isset($this->subscribe2_options['private'])) {
$this->subscribe2_options['private'] = "no";
} // option for sending notifications for posts that are private
if (!isset($this->subscribe2_options['email_freq'])) {
$this->subscribe2_options['email_freq'] = "never";
} // option for sending emails per-post or as a digest email on a cron schedule
if (!isset($this->subscribe2_options['cron_order'])) {
$this->subscribe2_options['cron_order'] = "desc";
} // option for ordering of posts in digest email
if (!isset($this->subscribe2_options['compulsory'])) {
$this->subscribe2_options['compulsory'] = "";
} // option for compulsory categories
if (!isset($this->subscribe2_options['exclude'])) {
$this->subscribe2_options['exclude'] = "";
} // option for excluded categories
if (!isset($this->subscribe2_options['sender'])) {
$this->subscribe2_options['sender'] = "blogname";
} // option for email notification sender
if (!isset($this->subscribe2_options['reg_override'])) {
$this->subscribe2_options['reg_override'] = "1";
} // option for excluded categories to be overriden for registered users
if (!isset($this->subscribe2_options['show_meta'])) {
$this->subscribe2_options['show_meta'] = "0";
} // option to display link to subscribe2 page from 'meta'
if (!isset($this->subscribe2_options['show_button'])) {
$this->subscribe2_options['show_button'] = "1";
} // option to show Subscribe2 button on Write page
if (!isset($this->subscribe2_options['ajax'])) {
$this->subscribe2_options['ajax'] = "0";
} // option to enable an AJAX style form
if (!isset($this->subscribe2_options['widget'])) {
$this->subscribe2_options['widget'] = "1";
} // option to enable Subscribe2 Widget
if (!isset($this->subscribe2_options['counterwidget'])) {
$this->subscribe2_options['counterwidget'] = "0";
} // option to enable Subscribe2 Counter Widget
if (!isset($this->subscribe2_options['s2meta_default'])) {
$this->subscribe2_options['s2meta_default'] = "0";
} // option for Subscribe2 over ride postmeta to be checked by default
if (!isset($this->subscribe2_options['entries'])) {
$this->subscribe2_options['entries'] = 25;
} // option for the number of subscribers displayed on each page
if (!isset($this->subscribe2_options['barred'])) {
$this->subscribe2_options['barred'] = "";
} // option containing domains barred from public registration
if (!isset($this->subscribe2_options['exclude_formats'])) {
$this->subscribe2_options['exclude_formats'] = "";
} // option for excluding post formats as supported by the current theme
if (!isset($this->subscribe2_options['mailtext'])) {
$this->subscribe2_options['mailtext'] = __("{BLOGNAME} has posted a new item, '{TITLE}'\n\n{POST}\n\nYou may view the latest post at\n{PERMALINK}\n\nYou received this e-mail because you asked to be notified when new updates are posted.\nBest regards,\n{MYNAME}\n{EMAIL}", "subscribe2");
} // Default notification email text
if (!isset($this->subscribe2_options['notification_subject'])) {
$this->subscribe2_options['notification_subject'] = "[{BLOGNAME}] {TITLE}";
} // Default notification email subject
if (!isset($this->subscribe2_options['confirm_email'])) {
$this->subscribe2_options['confirm_email'] = __("{BLOGNAME} has received a request to {ACTION} for this email address. To complete your request please click on the link below:\n\n{LINK}\n\nIf you did not request this, please feel free to disregard this notice!\n\nThank you,\n{MYNAME}.", "subscribe2");
} // Default confirmation email text
if (!isset($this->subscribe2_options['confirm_subject'])) {
$this->subscribe2_options['confirm_subject'] = "[{BLOGNAME}] " . __('Please confirm your request', 'subscribe2');
} // Default confirmation email subject
if (!isset($this->subscribe2_options['remind_email'])) {
$this->subscribe2_options['remind_email'] = __("This email address was subscribed for notifications at {BLOGNAME} ({BLOGLINK}) but the subscription remains incomplete.\n\nIf you wish to complete your subscription please click on the link below:\n\n{LINK}\n\nIf you do not wish to complete your subscription please ignore this email and your address will be removed from our database.\n\nRegards,\n{MYNAME}", "subscribe2");
} // Default reminder email text
if (!isset($this->subscribe2_options['remind_subject'])) {
$this->subscribe2_options['remind_subject'] = "[{BLOGNAME}] " . __('Subscription Reminder', 'subscribe2');;
} // Default reminder email subject
?> | Signl/subscribe2 | include/options.php | PHP | gpl-3.0 | 7,366 |
/**
*/
package net.paissad.waqtsalat.core.impl;
import java.util.Calendar;
import net.paissad.waqtsalat.core.WaqtSalatPackage;
import net.paissad.waqtsalat.core.api.Pray;
import net.paissad.waqtsalat.core.api.PrayName;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
/**
* <!-- begin-user-doc --> An implementation of the model object ' <em><b>Pray</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getName <em>Name</em>}</li>
* <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getTime <em>Time</em>}</li>
* <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#isPlayingAdhan <em>Playing Adhan</em>}</li>
* <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getAdhanPlayer <em>Adhan Player</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class PrayImpl extends MinimalEObjectImpl.Container implements Pray {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getName()
* @generated
* @ordered
*/
protected static final PrayName NAME_EDEFAULT = PrayName.FADJR;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getName()
* @generated
* @ordered
*/
protected PrayName name = NAME_EDEFAULT;
/**
* The default value of the '{@link #getTime() <em>Time</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getTime()
* @generated
* @ordered
*/
protected static final Calendar TIME_EDEFAULT = null;
/**
* The cached value of the '{@link #getTime() <em>Time</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getTime()
* @generated
* @ordered
*/
protected Calendar time = TIME_EDEFAULT;
/**
* The default value of the '{@link #isPlayingAdhan() <em>Playing Adhan</em>}' attribute. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPlayingAdhan()
* @generated
* @ordered
*/
protected static final boolean PLAYING_ADHAN_EDEFAULT = false;
/**
* The cached value of the '{@link #isPlayingAdhan() <em>Playing Adhan</em>}' attribute. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPlayingAdhan()
* @generated
* @ordered
*/
protected boolean playingAdhan = PLAYING_ADHAN_EDEFAULT;
/**
* The default value of the '{@link #getAdhanPlayer() <em>Adhan Player</em>}' attribute. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getAdhanPlayer()
* @generated
* @ordered
*/
protected static final Object ADHAN_PLAYER_EDEFAULT = null;
/**
* The cached value of the '{@link #getAdhanPlayer() <em>Adhan Player</em>}' attribute. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @see #getAdhanPlayer()
* @generated
* @ordered
*/
protected Object adhanPlayer = ADHAN_PLAYER_EDEFAULT;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected PrayImpl() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return WaqtSalatPackage.Literals.PRAY;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public PrayName getName() {
return name;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setName(PrayName newName) {
PrayName oldName = name;
name = newName == null ? NAME_EDEFAULT : newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__NAME, oldName, name));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public Calendar getTime() {
return time;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setTime(Calendar newTime) {
Calendar oldTime = time;
time = newTime;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__TIME, oldTime, time));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public boolean isPlayingAdhan() {
return playingAdhan;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setPlayingAdhan(boolean newPlayingAdhan) {
boolean oldPlayingAdhan = playingAdhan;
playingAdhan = newPlayingAdhan;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__PLAYING_ADHAN,
oldPlayingAdhan, playingAdhan));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public Object getAdhanPlayer() {
return adhanPlayer;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setAdhanPlayer(Object newAdhanPlayer) {
Object oldAdhanPlayer = adhanPlayer;
adhanPlayer = newAdhanPlayer;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__ADHAN_PLAYER, oldAdhanPlayer,
adhanPlayer));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case WaqtSalatPackage.PRAY__NAME:
return getName();
case WaqtSalatPackage.PRAY__TIME:
return getTime();
case WaqtSalatPackage.PRAY__PLAYING_ADHAN:
return isPlayingAdhan();
case WaqtSalatPackage.PRAY__ADHAN_PLAYER:
return getAdhanPlayer();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case WaqtSalatPackage.PRAY__NAME:
setName((PrayName) newValue);
return;
case WaqtSalatPackage.PRAY__TIME:
setTime((Calendar) newValue);
return;
case WaqtSalatPackage.PRAY__PLAYING_ADHAN:
setPlayingAdhan((Boolean) newValue);
return;
case WaqtSalatPackage.PRAY__ADHAN_PLAYER:
setAdhanPlayer(newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case WaqtSalatPackage.PRAY__NAME:
setName(NAME_EDEFAULT);
return;
case WaqtSalatPackage.PRAY__TIME:
setTime(TIME_EDEFAULT);
return;
case WaqtSalatPackage.PRAY__PLAYING_ADHAN:
setPlayingAdhan(PLAYING_ADHAN_EDEFAULT);
return;
case WaqtSalatPackage.PRAY__ADHAN_PLAYER:
setAdhanPlayer(ADHAN_PLAYER_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case WaqtSalatPackage.PRAY__NAME:
return name != NAME_EDEFAULT;
case WaqtSalatPackage.PRAY__TIME:
return TIME_EDEFAULT == null ? time != null : !TIME_EDEFAULT.equals(time);
case WaqtSalatPackage.PRAY__PLAYING_ADHAN:
return playingAdhan != PLAYING_ADHAN_EDEFAULT;
case WaqtSalatPackage.PRAY__ADHAN_PLAYER:
return ADHAN_PLAYER_EDEFAULT == null ? adhanPlayer != null : !ADHAN_PLAYER_EDEFAULT.equals(adhanPlayer);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: "); //$NON-NLS-1$
result.append(name);
result.append(", time: "); //$NON-NLS-1$
result.append(time);
result.append(", playingAdhan: "); //$NON-NLS-1$
result.append(playingAdhan);
result.append(", adhanPlayer: "); //$NON-NLS-1$
result.append(adhanPlayer);
result.append(')');
return result.toString();
}
} // PrayImpl
| paissad/waqtsalat-eclipse-plugin | plugins/net.paissad.waqtsalat.core/src/net/paissad/waqtsalat/core/impl/PrayImpl.java | Java | gpl-3.0 | 9,597 |
import {
DASHBOARD_ACTIVE_COIN_CHANGE,
DASHBOARD_ACTIVE_COIN_BALANCE,
DASHBOARD_ACTIVE_COIN_SEND_FORM,
DASHBOARD_ACTIVE_COIN_RECEIVE_FORM,
DASHBOARD_ACTIVE_COIN_RESET_FORMS,
DASHBOARD_ACTIVE_SECTION,
DASHBOARD_ACTIVE_TXINFO_MODAL,
ACTIVE_COIN_GET_ADDRESSES,
DASHBOARD_ACTIVE_COIN_NATIVE_BALANCE,
DASHBOARD_ACTIVE_COIN_NATIVE_TXHISTORY,
DASHBOARD_ACTIVE_COIN_NATIVE_OPIDS,
DASHBOARD_ACTIVE_COIN_SENDTO,
DASHBOARD_ACTIVE_ADDRESS,
DASHBOARD_ACTIVE_COIN_GETINFO_FAILURE,
SYNCING_NATIVE_MODE,
DASHBOARD_UPDATE,
DASHBOARD_ELECTRUM_BALANCE,
DASHBOARD_ELECTRUM_TRANSACTIONS,
DASHBOARD_REMOVE_COIN,
DASHBOARD_ACTIVE_COIN_NET_PEERS,
DASHBOARD_ACTIVE_COIN_NET_TOTALS,
KV_HISTORY,
DASHBOARD_ETHEREUM_BALANCE,
DASHBOARD_ETHEREUM_TRANSACTIONS,
DASHBOARD_CLEAR_ACTIVECOIN,
} from '../actions/storeType';
// TODO: refactor current coin props copy on change
const defaults = {
native: {
coin: null,
mode: null,
send: false,
receive: false,
balance: 0,
addresses: null,
activeSection: 'default',
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
txhistory: [],
opids: null,
lastSendToResponse: null,
progress: null,
rescanInProgress: false,
getinfoFetchFailures: 0,
net: {
peers: null,
totals: null,
},
},
spv: {
coin: null,
mode: null,
send: false,
receive: false,
balance: 0,
addresses: null,
activeSection: 'default',
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
txhistory: [],
lastSendToResponse: null,
},
eth: {
coin: null,
mode: null,
send: false,
receive: false,
balance: 0,
addresses: null,
activeSection: 'default',
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
txhistory: [],
lastSendToResponse: null,
},
};
const checkCoinObjectKeys = (obj, mode) => {
if (Object.keys(obj).length &&
mode) {
for (let key in obj) {
if (!defaults[mode].hasOwnProperty(key)) {
delete obj[key];
}
}
}
return obj;
};
export const ActiveCoin = (state = {
coins: {
native: {},
spv: {},
eth: {},
},
coin: null,
mode: null,
send: false,
receive: false,
balance: 0,
addresses: null,
activeSection: 'default',
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
txhistory: [],
opids: null,
lastSendToResponse: null,
activeAddress: null,
progress: null,
rescanInProgress: false,
getinfoFetchFailures: 0,
net: {
peers: null,
totals: null,
},
}, action) => {
switch (action.type) {
case DASHBOARD_REMOVE_COIN:
delete state.coins[action.mode][action.coin];
if (state.coin === action.coin) {
return {
...state,
...defaults[action.mode],
};
} else {
return {
...state,
};
}
case DASHBOARD_ACTIVE_COIN_CHANGE:
if (state.coins[action.mode] &&
state.coins[action.mode][action.coin]) {
let _coins = state.coins;
if (action.mode === state.mode) {
const _coinData = state.coins[action.mode][action.coin];
const _coinDataToStore = checkCoinObjectKeys({
addresses: state.addresses,
coin: state.coin,
mode: state.mode,
balance: state.balance,
txhistory: state.txhistory,
send: state.send,
receive: state.receive,
showTransactionInfo: state.showTransactionInfo,
showTransactionInfoTxIndex: state.showTransactionInfoTxIndex,
activeSection: state.activeSection,
lastSendToResponse: state.lastSendToResponse,
opids: state.mode === 'native' ? state.opids : null,
activeAddress: state.activeAddress,
progress: state.mode === 'native' ? state.progress : null,
rescanInProgress: state.mode === 'native' ? state.rescanInProgress : false,
getinfoFetchFailures: state.mode === 'native' ? state.getinfoFetchFailures : 0,
net: state.mode === 'native' ? state.net : {},
}, action.mode);
if (!action.skip) {
_coins[action.mode][state.coin] = _coinDataToStore;
}
delete _coins.undefined;
return {
...state,
coins: _coins,
...checkCoinObjectKeys({
addresses: _coinData.addresses,
coin: _coinData.coin,
mode: _coinData.mode,
balance: _coinData.balance,
txhistory: _coinData.txhistory,
send: _coinData.send,
receive: _coinData.receive,
showTransactionInfo: _coinData.showTransactionInfo,
showTransactionInfoTxIndex: _coinData.showTransactionInfoTxIndex,
activeSection: _coinData.activeSection,
lastSendToResponse: _coinData.lastSendToResponse,
opids: _coinData.mode === 'native' ? _coinData.opids : null,
activeAddress: _coinData.activeAddress,
progress: _coinData.mode === 'native' ? _coinData.progress : null,
rescanInProgress: _coinData.mode === 'native' ? _coinData.rescanInProgress : false,
getinfoFetchFailures: _coinData.mode === 'native' ? _coinData.getinfoFetchFailures : 0,
net: _coinData.mode === 'native' ? _coinData.net : {},
}, _coinData.mode),
};
} else {
delete _coins.undefined;
return {
...state,
coins: state.coins,
...checkCoinObjectKeys({
coin: action.coin,
mode: action.mode,
balance: 0,
addresses: null,
txhistory: 'loading',
send: false,
receive: false,
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
activeSection: 'default',
progress: null,
rescanInProgress: false,
net: {
peers: null,
totals: null,
},
}, action.mode),
};
}
} else {
if (state.coin) {
const _coinData = checkCoinObjectKeys({
addresses: state.addresses,
coin: state.coin,
mode: state.mode,
balance: state.balance,
txhistory: state.txhistory,
send: state.send,
receive: state.receive,
showTransactionInfo: state.showTransactionInfo,
showTransactionInfoTxIndex: state.showTransactionInfoTxIndex,
activeSection: state.activeSection,
lastSendToResponse: state.lastSendToResponse,
opids: state.mode === 'native' ? state.opids : null,
activeAddress: state.activeAddress,
progress: state.mode === 'native' ? state.progress : null,
rescanInProgress: state.mode === 'native' ? state.rescanInProgress : false,
getinfoFetchFailures: state.mode === 'native' ? state.getinfoFetchFailures : 0,
net: state.mode === 'native' ? state.net : {},
}, state.mode);
let _coins = state.coins;
if (!action.skip &&
_coins[action.mode]) {
_coins[action.mode][state.coin] = _coinData;
}
return {
...state,
coins: _coins,
...checkCoinObjectKeys({
coin: action.coin,
mode: action.mode,
balance: 0,
addresses: null,
txhistory: 'loading',
send: false,
receive: false,
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
activeSection: 'default',
progress: null,
rescanInProgress: false,
net: {
peers: null,
totals: null,
},
}, action.mode),
};
} else {
return {
...state,
...checkCoinObjectKeys({
coin: action.coin,
mode: action.mode,
balance: 0,
addresses: null,
txhistory: 'loading',
send: false,
receive: false,
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
activeSection: 'default',
progress: null,
rescanInProgress: false,
net: {
peers: null,
totals: null,
},
}, action.mode),
};
}
}
case DASHBOARD_ELECTRUM_BALANCE:
return {
...state,
balance: action.balance,
};
case DASHBOARD_ELECTRUM_TRANSACTIONS:
return {
...state,
txhistory: action.txhistory,
};
case DASHBOARD_ACTIVE_COIN_BALANCE:
return {
...state,
balance: action.balance,
};
case DASHBOARD_ACTIVE_COIN_SEND_FORM:
return {
...state,
send: action.send,
receive: false,
};
case DASHBOARD_ACTIVE_COIN_RECEIVE_FORM:
return {
...state,
send: false,
receive: action.receive,
};
case DASHBOARD_ACTIVE_COIN_RESET_FORMS:
return {
...state,
send: false,
receive: false,
};
case ACTIVE_COIN_GET_ADDRESSES:
return {
...state,
addresses: action.addresses,
};
case DASHBOARD_ACTIVE_SECTION:
return {
...state,
activeSection: action.section,
};
case DASHBOARD_ACTIVE_TXINFO_MODAL:
return {
...state,
showTransactionInfo: action.showTransactionInfo,
showTransactionInfoTxIndex: action.showTransactionInfoTxIndex,
};
case DASHBOARD_ACTIVE_COIN_NATIVE_BALANCE:
return {
...state,
balance: action.balance,
};
case DASHBOARD_ACTIVE_COIN_NATIVE_TXHISTORY:
return {
...state,
txhistory: action.txhistory,
};
case DASHBOARD_ACTIVE_COIN_NATIVE_OPIDS:
return {
...state,
opids: action.opids,
};
case DASHBOARD_ACTIVE_COIN_SENDTO:
return {
...state,
lastSendToResponse: action.lastSendToResponse,
};
case DASHBOARD_ACTIVE_ADDRESS:
return {
...state,
activeAddress: action.address,
};
case SYNCING_NATIVE_MODE:
return {
...state,
progress: state.mode === 'native' ? action.progress : null,
getinfoFetchFailures: typeof action.progress === 'string' && action.progress.indexOf('"code":-777') ? state.getinfoFetchFailures + 1 : 0,
};
case DASHBOARD_ACTIVE_COIN_GETINFO_FAILURE:
return {
...state,
getinfoFetchFailures: state.getinfoFetchFailures + 1,
};
case DASHBOARD_UPDATE:
if (state.coin === action.coin) {
return {
...state,
opids: action.opids,
txhistory: action.txhistory,
balance: action.balance,
addresses: action.addresses,
rescanInProgress: action.rescanInProgress,
};
}
case DASHBOARD_ACTIVE_COIN_NET_PEERS:
return {
...state,
net: {
peers: action.peers,
totals: state.net.totals,
},
};
case DASHBOARD_ACTIVE_COIN_NET_TOTALS:
return {
...state,
net: {
peers: state.net.peers,
totals: action.totals,
},
};
case DASHBOARD_ETHEREUM_BALANCE:
return {
...state,
balance: action.balance,
};
case DASHBOARD_ETHEREUM_TRANSACTIONS:
return {
...state,
txhistory: action.txhistory,
};
case DASHBOARD_CLEAR_ACTIVECOIN:
return {
coins: {
native: {},
spv: {},
eth: {},
},
coin: null,
mode: null,
balance: 0,
addresses: null,
txhistory: 'loading',
send: false,
receive: false,
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
activeSection: 'default',
progress: null,
rescanInProgress: false,
net: {
peers: null,
totals: null,
},
getinfoFetchFailures: 0,
};
default:
return state;
}
}
export default ActiveCoin; | pbca26/EasyDEX-GUI | react/src/reducers/activeCoin.js | JavaScript | gpl-3.0 | 12,574 |
package ninja.mbedded.ninjaterm.util.rxProcessing.timeStamp;
import javafx.scene.paint.Color;
import ninja.mbedded.ninjaterm.JavaFXThreadingRule;
import ninja.mbedded.ninjaterm.util.rxProcessing.streamedData.StreamedData;
import ninja.mbedded.ninjaterm.util.rxProcessing.streamingFilter.StreamingFilter;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.time.Instant;
import java.time.ZoneId;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for the {@link TimeStampParser} class.
*
* @author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja)
* @since 2016-11-23
* @last-modified 2016-11-23
*/
public class TimeStampParserTests {
/**
* Including this variable in class allows JavaFX objects to be created in tests.
*/
@Rule
public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule();
private TimeStampParser timeStampParser;
private StreamedData inputStreamedData;
private StreamedData outputStreamedData;
@Before
public void setUp() throws Exception {
timeStampParser = new TimeStampParser("EOL");
inputStreamedData = new StreamedData();
outputStreamedData = new StreamedData();
}
@Test
public void firstCharTest() throws Exception {
inputStreamedData.append("abc");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abc", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
}
@Test
public void oneNewLineTest() throws Exception {
inputStreamedData.append("abcEOLd");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOLd", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
}
@Test
public void temporalTest() throws Exception {
inputStreamedData.append("abcEOL");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOL", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
// Sleep enough that the next TimeStamp is guaranteed to be greater than
// the first (delay must be larger than the min. LocalDateTime resolution)
Thread.sleep(10);
//==============================================//
//====================== RUN 2 =================//
//==============================================//
inputStreamedData.append("d");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOLd", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
// Check time
Instant time0 = outputStreamedData.getTimeStampMarkers().get(0).localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Instant time1 = outputStreamedData.getTimeStampMarkers().get(1).localDateTime.atZone(ZoneId.systemDefault()).toInstant();
assertEquals(true, time1.isAfter(time0));
}
@Test
public void partialLineTest() throws Exception {
inputStreamedData.append("123EO");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("EO", inputStreamedData.getText());
// Check output
assertEquals("123", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
inputStreamedData.append("L456");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("123EOL456", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
}
// @Test
// public void multipleLinesTest() throws Exception {
//
// inputStreamedData.append("abcEOLabcEOLdefEOL");
// inputStreamedData.addNewLineMarkerAt(6);
// inputStreamedData.addNewLineMarkerAt(12);
// inputStreamedData.addNewLineMarkerAt(18);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input. Since "defEOL" counts as a valid line, but has no match,
// // it should be removed from the input
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getColourMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
// }
//
// @Test
// public void MatchedLinesBetweenNonMatchTest() throws Exception {
//
// inputStreamedData.append("abcEOLdefEOLabcEOL");
// inputStreamedData.addNewLineMarkerAt(6);
// inputStreamedData.addNewLineMarkerAt(12);
// inputStreamedData.addNewLineMarkerAt(18);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input. Since "defEOL" counts as a valid line, but has no match,
// // it should be removed from the input
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getColourMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
// }
//
// @Test
// public void streamTest() throws Exception {
//
// inputStreamedData.append("ab");
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", inputStreamedData.getText());
// assertEquals("ab", outputStreamedData.getText());
//
// inputStreamedData.append("cEOL");
// inputStreamedData.addNewLineMarkerAt(4);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void streamWithNonMatchLineInMiddleTest() throws Exception {
//
// //==============================================//
// //==================== PASS 1 ==================//
// //==============================================//
//
// inputStreamedData.append("ab");
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals("", inputStreamedData.getText());
//
// // Check output
// assertEquals("ab", outputStreamedData.getText());
//
// //==============================================//
// //==================== PASS 2 ==================//
// //==============================================//
//
// inputStreamedData.append("cEOLde");
// inputStreamedData.addNewLineMarkerAt(4);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "de");
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 3 ==================//
// //==============================================//
//
// inputStreamedData.append("fEOLa");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length() - 1);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "");
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOLa", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 4 ==================//
// //==============================================//
//
// inputStreamedData.append("bcEOL");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "");
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
//
// }
//
// @Test
// public void coloursAndNewLinesTest() throws Exception {
//
// inputStreamedData.append("abcEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addNewLineMarkerAt(6);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void complexNodesTest() throws Exception {
//
// inputStreamedData.append("abcdefEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addColour(3, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(9);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcdefEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getColourMarkers().size());
//
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// assertEquals(3, outputStreamedData.getColourMarkers().get(1).position);
// assertEquals(Color.GREEN, outputStreamedData.getColourMarkers().get(1).color);
//
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(9, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void complexNodes2Test() throws Exception {
//
// //==============================================//
// //==================== PASS 1 ==================//
// //==============================================//
//
// inputStreamedData.append("abcEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addNewLineMarkerAt(6);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 2 ==================//
// //==============================================//
//
// inputStreamedData.append("defEOL");
// inputStreamedData.addColour(0, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void bigTest() throws Exception {
//
// streamingFilter.setFilterPattern("d");
//
// inputStreamedData.append("re");
// inputStreamedData.addColour(0, Color.RED);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
//
// inputStreamedData.append("dEOL");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("redEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Nothing should of changed
// assertEquals("redEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// inputStreamedData.append("greenEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// inputStreamedData.append("redEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 6, Color.RED);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// inputStreamedData.append("greenEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("redEOLredEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getColourMarkers().size());
//
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// assertEquals(6, outputStreamedData.getColourMarkers().get(1).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(1).color);
// }
} | mbedded-ninja/NinjaTerm | src/test/java/ninja/mbedded/ninjaterm/util/rxProcessing/timeStamp/TimeStampParserTests.java | Java | gpl-3.0 | 17,393 |
// urlParams is null when used for embedding
window.urlParams = window.urlParams || {};
// isLocalStorage controls access to local storage
window.isLocalStorage = window.isLocalStorage || false;
// Checks for SVG support
window.isSvgBrowser = window.isSvgBrowser || (navigator.userAgent.indexOf('MSIE') < 0 || document.documentMode >= 9);
// CUSTOM_PARAMETERS - URLs for save and export
window.EXPORT_URL = window.EXPORT_URL || 'https://exp.draw.io/ImageExport4/export';
window.SAVE_URL = window.SAVE_URL || 'save';
window.OPEN_URL = window.OPEN_URL || 'open';
window.PROXY_URL = window.PROXY_URL || 'proxy';
// Paths and files
window.SHAPES_PATH = window.SHAPES_PATH || 'shapes';
// Path for images inside the diagram
window.GRAPH_IMAGE_PATH = window.GRAPH_IMAGE_PATH || 'img';
window.ICONSEARCH_PATH = window.ICONSEARCH_PATH || (navigator.userAgent.indexOf('MSIE') >= 0 ||
urlParams['dev']) ? 'iconSearch' : 'https://www.draw.io/iconSearch';
window.TEMPLATE_PATH = window.TEMPLATE_PATH || '/templates';
// Directory for i18 files and basename for main i18n file
window.RESOURCES_PATH = window.RESOURCES_PATH || 'resources';
window.RESOURCE_BASE = window.RESOURCE_BASE || RESOURCES_PATH + '/dia';
// URL for logging
window.DRAWIO_LOG_URL = window.DRAWIO_LOG_URL || '';
// Sets the base path, the UI language via URL param and configures the
// supported languages to avoid 404s. The loading of all core language
// resources is disabled as all required resources are in grapheditor.
// properties. Note that in this example the loading of two resource
// files (the special bundle and the default bundle) is disabled to
// save a GET request. This requires that all resources be present in
// the special bundle.
window.mxLoadResources = window.mxLoadResources || false;
window.mxLanguage = window.mxLanguage || (function()
{
var lang = (urlParams['offline'] == '1') ? 'en' : urlParams['lang'];
// Known issue: No JSON object at this point in quirks in IE8
if (lang == null && typeof(JSON) != 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
if (value != null)
{
lang = JSON.parse(value).language || null;
}
}
catch (e)
{
// cookies are disabled, attempts to use local storage will cause
// a DOM error at a minimum on Chrome
isLocalStorage = false;
}
}
}
return lang;
})();
// Add new languages here. First entry is translated to [Automatic]
// in the menu defintion in Diagramly.js.
window.mxLanguageMap = window.mxLanguageMap ||
{
'i18n': '',
'id' : 'Bahasa Indonesia',
'ms' : 'Bahasa Melayu',
'bs' : 'Bosanski',
'ca' : 'Català',
'cs' : 'Čeština',
'da' : 'Dansk',
'de' : 'Deutsch',
'et' : 'Eesti',
'en' : 'English',
'es' : 'Español',
'eo' : 'Esperanto',
'fil' : 'Filipino',
'fr' : 'Français',
'it' : 'Italiano',
'hu' : 'Magyar',
'nl' : 'Nederlands',
'no' : 'Norsk',
'pl' : 'Polski',
'pt-br' : 'Português (Brasil)',
'pt' : 'Português (Portugal)',
'ro' : 'Română',
'fi' : 'Suomi',
'sv' : 'Svenska',
'vi' : 'Tiếng Việt',
'tr' : 'Türkçe',
'el' : 'Ελληνικά',
'ru' : 'Русский',
'sr' : 'Српски',
'uk' : 'Українська',
'he' : 'עברית',
'ar' : 'العربية',
'th' : 'ไทย',
'ko' : '한국어',
'ja' : '日本語',
'zh' : '中文(中国)',
'zh-tw' : '中文(台灣)'
};
if (typeof window.mxBasePath === 'undefined')
{
window.mxBasePath = 'mxgraph';
}
if (window.mxLanguages == null)
{
window.mxLanguages = [];
// Populates the list of supported special language bundles
for (var lang in mxLanguageMap)
{
// Empty means default (ie. browser language), "en" means English (default for unsupported languages)
// Since "en" uses no extension this must not be added to the array of supported language bundles.
if (lang != 'en')
{
window.mxLanguages.push(lang);
}
}
}
/**
* Returns the global UI setting before runngin static draw.io code
*/
window.uiTheme = window.uiTheme || (function()
{
var ui = urlParams['ui'];
// Known issue: No JSON object at this point in quirks in IE8
if (ui == null && typeof JSON !== 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
if (value != null)
{
ui = JSON.parse(value).ui || null;
}
}
catch (e)
{
// cookies are disabled, attempts to use local storage will cause
// a DOM error at a minimum on Chrome
isLocalStorage = false;
}
}
}
return ui;
})();
/**
* Global function for loading local files via servlet
*/
function setCurrentXml(data, filename)
{
if (window.parent != null && window.parent.openFile != null)
{
window.parent.openFile.setData(data, filename);
}
};
/**
* Overrides splash URL parameter via local storage
*/
(function()
{
// Known issue: No JSON object at this point in quirks in IE8
if (typeof JSON !== 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
var showSplash = true;
if (value != null)
{
showSplash = JSON.parse(value).showStartScreen;
}
// Undefined means true
if (showSplash == false)
{
urlParams['splash'] = '0';
}
}
catch (e)
{
// ignore
}
}
}
})();
// Customizes export URL
var ex = urlParams['export'];
if (ex != null)
{
if (ex.substring(0, 7) != 'http://' && ex.substring(0, 8) != 'https://')
{
ex = 'http://' + ex;
}
EXPORT_URL = ex;
}
// Enables offline mode
if (urlParams['offline'] == '1' || urlParams['demo'] == '1' || urlParams['stealth'] == '1' || urlParams['local'] == '1')
{
urlParams['analytics'] = '0';
urlParams['picker'] = '0';
urlParams['gapi'] = '0';
urlParams['db'] = '0';
urlParams['od'] = '0';
urlParams['gh'] = '0';
}
// Disables math in offline mode
if (urlParams['offline'] == '1' || urlParams['local'] == '1')
{
urlParams['math'] = '0';
}
// Lightbox enabled chromeless mode
if (urlParams['lightbox'] == '1')
{
urlParams['chrome'] = '0';
}
// Adds hard-coded logging domain for draw.io domains
var host = window.location.host;
var searchString = 'draw.io';
var position = host.length - searchString.length;
var lastIndex = host.lastIndexOf(searchString, position);
if (lastIndex !== -1 && lastIndex === position && host != 'test.draw.io')
{
// endsWith polyfill
window.DRAWIO_LOG_URL = 'https://log.draw.io';
} | crazykeyboard/draw.io | war/js/diagramly/Init.js | JavaScript | gpl-3.0 | 6,535 |
<?php
/**
* Part of the Sentinel package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file.
*
* @package Sentinel
* @version 2.0.18
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011-2019, Cartalyst LLC
* @link http://cartalyst.com
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class MigrationCartalystSentinel extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('activations', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->boolean('completed')->default(0);
$table->timestamp('completed_at')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
});
Schema::create('persistences', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('code');
});
Schema::create('reminders', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->boolean('completed')->default(0);
$table->timestamp('completed_at')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('slug');
$table->string('name');
$table->text('permissions')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('slug');
});
Schema::create('role_users', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->nullableTimestamps();
$table->engine = 'InnoDB';
$table->primary(['user_id', 'role_id']);
});
Schema::create('throttle', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->string('type');
$table->string('ip')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->index('user_id');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password');
$table->text('permissions')->nullable();
$table->timestamp('last_login')->nullable();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('email');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('activations');
Schema::drop('persistences');
Schema::drop('reminders');
Schema::drop('roles');
Schema::drop('role_users');
Schema::drop('throttle');
Schema::drop('users');
}
}
| kaoz70/flexcms | flexcms/vendor/cartalyst/sentinel/src/migrations/2014_07_02_230147_migration_cartalyst_sentinel.php | PHP | gpl-3.0 | 3,705 |
/*
* File: Worker2.cpp
* Author: saulario
*
* Created on 15 de septiembre de 2016, 6:40
*/
#include "Worker2.h"
#include "Csoft.h"
using namespace csoft::mod2;
Worker2::Worker2(const csoft::Csoft * csoft) {
}
Worker2::Worker2(const Worker2& orig) {
}
Worker2::~Worker2() {
}
void Worker2::doIt(void) {
BOOST_LOG_SEV(lg, boost::log::trivial::info) << __PRETTY_FUNCTION__ << "---> Begin";
BOOST_LOG_SEV(lg, boost::log::trivial::info) << __PRETTY_FUNCTION__ << "<--- End";
} | saulario/pruebas | csoft/csoft/src/mod2/Worker2.cpp | C++ | gpl-3.0 | 499 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YSchool
{
public class Person
{
public int id;
public string name ;
public int gender;//1
public string birthDate;//"1900-00-00T00:00:00"
public int mobileNumber;
public int altMobileNumber;
public string fatherName;
public string motherName;
public int batchType;//2
}
} | ravilogaiya/yujvidya | android-client/YSchool/Person.cs | C# | gpl-3.0 | 476 |
var chai = require('chai')
, sinon = require('sinon')
, sinonChai = require('sinon-chai')
, expect = chai.expect
, Promise = require('es6-promise').Promise
, UpdateTemplatesController = require('../../../platypi-cli/controllers/cli/updatetemplates.controller');
chai.use(sinonChai);
describe('TemplateUpdate controller', function () {
it('should return a new controller', function (done) {
try {
var controller = new UpdateTemplatesController({
viewStuff: 'fakeview'
});
expect(controller).to.be.an.object;
expect(controller.model).to.be.an.object;
expect(controller.view).to.be.an.object;
expect(controller.view.model).to.equal(controller.model);
done();
} catch (e) {
done(e);
}
});
describe('getResponseView method', function () {
var sandbox, controller, updateFunc;
beforeEach(function (done) {
sandbox = sinon.sandbox.create();
controller = new UpdateTemplatesController({
viewStuff: 'fakeview'
});
updateFunc = sandbox.stub(controller.__provider, 'update');
done();
});
afterEach(function (done) {
sandbox.restore();
done();
});
it('should call the clean method and return the view', function (done) {
updateFunc.returns(Promise.resolve(''));
controller.getResponseView().then(function (view) {
try {
expect(updateFunc).to.have.been.called;
expect(controller.model.successMessage).not.to.equal('');
expect(view).to.exist;
done();
} catch (e) {
done(e);
}
}, function (err) {
done(err);
});
});
it('should call the update method and throw an error', function (done) {
updateFunc.returns(Promise.reject('Err'));
controller.getResponseView().then(function (view) {
try {
expect(updateFunc).to.have.been.called;
expect(controller.model.errorMessage).not.to.equal('');
expect(view).to.exist;
done();
} catch (e) {
done(e);
}
}, function (err) {
done(err);
});
});
});
}); | tonylegrone/platypi-cli | test/controllers/cli/updatetemplates.controller.test.js | JavaScript | gpl-3.0 | 2,558 |
""" Class that contains client access to the transformation DB handler. """
__RCSID__ = "$Id$"
import types
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Base.Client import Client
from DIRAC.Core.Utilities.List import breakListIntoChunks
from DIRAC.Resources.Catalog.FileCatalogueBase import FileCatalogueBase
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
rpc = None
url = None
class TransformationClient( Client, FileCatalogueBase ):
""" Exposes the functionality available in the DIRAC/TransformationHandler
This inherits the DIRAC base Client for direct execution of server functionality.
The following methods are available (although not visible here).
Transformation (table) manipulation
deleteTransformation(transName)
getTransformationParameters(transName,paramNames)
getTransformationWithStatus(status)
setTransformationParameter(transName,paramName,paramValue)
deleteTransformationParameter(transName,paramName)
TransformationFiles table manipulation
addFilesToTransformation(transName,lfns)
addTaskForTransformation(transName,lfns=[],se='Unknown')
getTransformationStats(transName)
TransformationTasks table manipulation
setTaskStatus(transName, taskID, status)
setTaskStatusAndWmsID(transName, taskID, status, taskWmsID)
getTransformationTaskStats(transName)
deleteTasks(transName, taskMin, taskMax)
extendTransformation( transName, nTasks)
getTasksToSubmit(transName,numTasks,site='')
TransformationLogging table manipulation
getTransformationLogging(transName)
File/directory manipulation methods (the remainder of the interface can be found below)
getFileSummary(lfns)
exists(lfns)
Web monitoring tools
getDistinctAttributeValues(attribute, selectDict)
getTransformationStatusCounters()
getTransformationSummary()
getTransformationSummaryWeb(selectDict, sortList, startItem, maxItems)
"""
def __init__( self, **kwargs ):
Client.__init__( self, **kwargs )
opsH = Operations()
self.maxResetCounter = opsH.getValue( 'Productions/ProductionFilesMaxResetCounter', 10 )
self.setServer( 'Transformation/TransformationManager' )
def setServer( self, url ):
self.serverURL = url
def getCounters( self, table, attrList, condDict, older = None, newer = None, timeStamp = None,
rpc = '', url = '' ):
rpcClient = self._getRPC( rpc = rpc, url = url )
return rpcClient. getCounters( table, attrList, condDict, older, newer, timeStamp )
def addTransformation( self, transName, description, longDescription, transType, plugin, agentType, fileMask,
transformationGroup = 'General',
groupSize = 1,
inheritedFrom = 0,
body = '',
maxTasks = 0,
eventsPerTask = 0,
addFiles = True,
rpc = '', url = '', timeout = 1800 ):
""" add a new transformation
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addTransformation( transName, description, longDescription, transType, plugin,
agentType, fileMask, transformationGroup, groupSize, inheritedFrom,
body, maxTasks, eventsPerTask, addFiles )
def getTransformations( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationDate',
orderAttribute = None, limit = 100, extraParams = False, rpc = '', url = '', timeout = None ):
""" gets all the transformations in the system, incrementally. "limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformations = []
# getting transformations - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformations( condDict, older, newer, timeStamp, orderAttribute, limit,
extraParams, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformations = transformations + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformations )
def getTransformation( self, transName, extraParams = False, rpc = '', url = '', timeout = None ):
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getTransformation( transName, extraParams )
def getTransformationFiles( self, condDict = {}, older = None, newer = None, timeStamp = 'LastUpdate',
orderAttribute = None, limit = 10000, rpc = '', url = '', timeout = 1800 ):
""" gets all the transformation files for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformationFiles = []
# getting transformationFiles - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformationFiles( condDict, older, newer, timeStamp, orderAttribute, limit, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformationFiles = transformationFiles + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformationFiles )
def getTransformationTasks( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationTime',
orderAttribute = None, limit = 10000, inputVector = False, rpc = '',
url = '', timeout = None ):
""" gets all the transformation tasks for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformationTasks = []
# getting transformationFiles - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformationTasks( condDict, older, newer, timeStamp, orderAttribute, limit,
inputVector, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformationTasks = transformationTasks + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformationTasks )
def cleanTransformation( self, transID, rpc = '', url = '', timeout = None ):
""" Clean the transformation, and set the status parameter (doing it here, for easier extensibility)
"""
# Cleaning
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
res = rpcClient.cleanTransformation( transID )
if not res['OK']:
return res
# Setting the status
return self.setTransformationParameter( transID, 'Status', 'TransformationCleaned' )
def moveFilesToDerivedTransformation( self, transDict, resetUnused = True ):
""" move files input to a transformation, to the derived one
"""
prod = transDict['TransformationID']
parentProd = int( transDict.get( 'InheritedFrom', 0 ) )
movedFiles = {}
if not parentProd:
gLogger.warn( "[None] [%d] .moveFilesToDerivedTransformation: Transformation was not derived..." % prod )
return S_OK( ( parentProd, movedFiles ) )
# get the lfns in status Unused/MaxReset of the parent production
res = self.getTransformationFiles( condDict = {'TransformationID': parentProd, 'Status': [ 'Unused', 'MaxReset' ]} )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error getting Unused files from transformation %s:" % ( prod, parentProd ), res['Message'] )
return res
parentFiles = res['Value']
lfns = [lfnDict['LFN'] for lfnDict in parentFiles]
if not lfns:
gLogger.info( "[None] [%d] .moveFilesToDerivedTransformation: No files found to be moved from transformation %d" % ( prod, parentProd ) )
return S_OK( ( parentProd, movedFiles ) )
# get the lfns of the derived production that were Unused/MaxReset in the parent one
res = self.getTransformationFiles( condDict = { 'TransformationID': prod, 'LFN': lfns} )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error getting files from derived transformation" % prod, res['Message'] )
return res
derivedFiles = res['Value']
suffix = '-%d' % parentProd
derivedStatusDict = dict( [( derivedDict['LFN'], derivedDict['Status'] ) for derivedDict in derivedFiles] )
newStatusFiles = {}
parentStatusFiles = {}
force = False
for parentDict in parentFiles:
lfn = parentDict['LFN']
derivedStatus = derivedStatusDict.get( lfn )
if derivedStatus:
parentStatus = parentDict['Status']
if resetUnused and parentStatus == 'MaxReset':
status = 'Unused'
moveStatus = 'Unused from MaxReset'
force = True
else:
status = parentStatus
moveStatus = parentStatus
if derivedStatus.endswith( suffix ):
# This file is Unused or MaxReset while it was most likely Assigned at the time of derivation
parentStatusFiles.setdefault( 'Moved-%s' % str( prod ), [] ).append( lfn )
newStatusFiles.setdefault( ( status, parentStatus ), [] ).append( lfn )
movedFiles[moveStatus] = movedFiles.setdefault( moveStatus, 0 ) + 1
elif parentDict['Status'] == 'Unused':
# If the file was Unused already at derivation time, set it NotProcessed
parentStatusFiles.setdefault( 'NotProcessed', [] ).append( lfn )
# Set the status in the parent transformation first
for status, lfnList in parentStatusFiles.items():
for lfnChunk in breakListIntoChunks( lfnList, 5000 ):
res = self.setFileStatusForTransformation( parentProd, status, lfnChunk )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d "
% ( prod, status, len( lfnList ), parentProd ),
res['Message'] )
# Set the status in the new transformation
for ( status, oldStatus ), lfnList in newStatusFiles.items():
for lfnChunk in breakListIntoChunks( lfnList, 5000 ):
res = self.setFileStatusForTransformation( prod, status, lfnChunk, force = force )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files; resetting them %s in transformation %d"
% ( prod, status, len( lfnChunk ), oldStatus, parentProd ),
res['Message'] )
res = self.setFileStatusForTransformation( parentProd, oldStatus, lfnChunk )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d"
% ( prod, oldStatus, len( lfnChunk ), parentProd ),
res['Message'] )
return S_OK( ( parentProd, movedFiles ) )
def setFileStatusForTransformation( self, transName, newLFNsStatus = {}, lfns = [], force = False,
rpc = '', url = '', timeout = 120 ):
""" sets the file status for LFNs of a transformation
For backward compatibility purposes, the status and LFNs can be passed in 2 ways:
- newLFNsStatus is a dictionary with the form:
{'/this/is/an/lfn1.txt': 'StatusA', '/this/is/an/lfn2.txt': 'StatusB', ... }
and at this point lfns is not considered
- newLFNStatus is a string, that applies to all the LFNs in lfns
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
# create dictionary in case newLFNsStatus is a string
if type( newLFNsStatus ) == type( '' ):
newLFNsStatus = dict( [( lfn, newLFNsStatus ) for lfn in lfns ] )
# gets status as of today
tsFiles = self.getTransformationFiles( {'TransformationID':transName, 'LFN': newLFNsStatus.keys()} )
if not tsFiles['OK']:
return tsFiles
tsFiles = tsFiles['Value']
if tsFiles:
# for convenience, makes a small dictionary out of the tsFiles, with the lfn as key
tsFilesAsDict = {}
for tsFile in tsFiles:
tsFilesAsDict[tsFile['LFN']] = [tsFile['Status'], tsFile['ErrorCount'], tsFile['FileID']]
# applying the state machine to the proposed status
newStatuses = self._applyTransformationFilesStateMachine( tsFilesAsDict, newLFNsStatus, force )
if newStatuses: # if there's something to update
# must do it for the file IDs...
newStatusForFileIDs = dict( [( tsFilesAsDict[lfn][2], newStatuses[lfn] ) for lfn in newStatuses.keys()] )
res = rpcClient.setFileStatusForTransformation( transName, newStatusForFileIDs )
if not res['OK']:
return res
return S_OK( newStatuses )
def _applyTransformationFilesStateMachine( self, tsFilesAsDict, dictOfProposedLFNsStatus, force ):
""" For easier extension, here we apply the state machine of the production files.
VOs might want to replace the standard here with something they prefer.
tsFiles is a dictionary with the lfn as key and as value a list of [Status, ErrorCount, FileID]
dictOfNewLFNsStatus is a dictionary with the proposed status
force is a boolean
It returns a dictionary with the status updates
"""
newStatuses = {}
for lfn in dictOfProposedLFNsStatus.keys():
if lfn not in tsFilesAsDict.keys():
continue
else:
newStatus = dictOfProposedLFNsStatus[lfn]
# Apply optional corrections
if tsFilesAsDict[lfn][0].lower() == 'processed' and dictOfProposedLFNsStatus[lfn].lower() != 'processed':
if not force:
newStatus = 'Processed'
elif tsFilesAsDict[lfn][0].lower() == 'maxreset':
if not force:
newStatus = 'MaxReset'
elif dictOfProposedLFNsStatus[lfn].lower() == 'unused':
errorCount = tsFilesAsDict[lfn][1]
# every 10 retries (by default)
if errorCount and ( ( errorCount % self.maxResetCounter ) == 0 ):
if not force:
newStatus = 'MaxReset'
if tsFilesAsDict[lfn][0].lower() != newStatus:
newStatuses[lfn] = newStatus
return newStatuses
def setTransformationParameter( self, transID, paramName, paramValue, force = False,
rpc = '', url = '', timeout = 120 ):
""" Sets a transformation parameter. There's a special case when coming to setting the status of a transformation.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
if paramName.lower() == 'status':
# get transformation Type
transformation = self.getTransformation( transID )
if not transformation['OK']:
return transformation
transformationType = transformation['Value']['Type']
# get status as of today
originalStatus = self.getTransformationParameters( transID, 'Status' )
if not originalStatus['OK']:
return originalStatus
originalStatus = originalStatus['Value']
transIDAsDict = {transID: [originalStatus, transformationType]}
dictOfProposedstatus = {transID: paramValue}
# applying the state machine to the proposed status
value = self._applyTransformationStatusStateMachine( transIDAsDict, dictOfProposedstatus, force )
else:
value = paramValue
return rpcClient.setTransformationParameter( transID, paramName, value )
def _applyTransformationStatusStateMachine( self, transIDAsDict, dictOfProposedstatus, force ):
""" For easier extension, here we apply the state machine of the transformation status.
VOs might want to replace the standard here with something they prefer.
transIDAsDict is a dictionary with the transID as key and as value a list with [Status, Type]
dictOfProposedstatus is a dictionary with the proposed status
force is a boolean
It returns the new status (the standard is just doing nothing: everything is possible)
"""
return dictOfProposedstatus.values()[0]
#####################################################################
#
# These are the file catalog interface methods
#
def isOK( self ):
return self.valid
def getName( self, DN = '' ):
""" Get the file catalog type name
"""
return self.name
def addDirectory( self, path, force = False, rpc = '', url = '', timeout = None ):
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addDirectory( path, force )
def getReplicas( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfns = res['Value'].keys()
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getReplicas( lfns )
def addFile( self, lfn, force = False, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addFile( lfndicts, force )
def addReplica( self, lfn, force = False, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addReplica( lfndicts, force )
def removeFile( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfns = res['Value'].keys()
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
successful = {}
failed = {}
listOfLists = breakListIntoChunks( lfns, 100 )
for fList in listOfLists:
res = rpcClient.removeFile( fList )
if not res['OK']:
return res
successful.update( res['Value']['Successful'] )
failed.update( res['Value']['Failed'] )
resDict = {'Successful': successful, 'Failed':failed}
return S_OK( resDict )
def removeReplica( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
successful = {}
failed = {}
# as lfndicts is a dict, the breakListIntoChunks will fail. Fake it!
listOfDicts = []
localdicts = {}
for lfn, info in lfndicts.items():
localdicts.update( { lfn : info } )
if len( localdicts.keys() ) % 100 == 0:
listOfDicts.append( localdicts )
localdicts = {}
for fDict in listOfDicts:
res = rpcClient.removeReplica( fDict )
if not res['OK']:
return res
successful.update( res['Value']['Successful'] )
failed.update( res['Value']['Failed'] )
resDict = {'Successful': successful, 'Failed':failed}
return S_OK( resDict )
def getReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getReplicaStatus( lfndict )
def setReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.setReplicaStatus( lfndict )
def setReplicaHost( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.setReplicaHost( lfndict )
def removeDirectory( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def createDirectory( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def createLink( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def removeLink( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def __returnOK( self, lfn ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
successful = {}
for lfn in res['Value'].keys():
successful[lfn] = True
resDict = {'Successful':successful, 'Failed':{}}
return S_OK( resDict )
def __checkArgumentFormat( self, path ):
if type( path ) in types.StringTypes:
urls = {path:False}
elif type( path ) == types.ListType:
urls = {}
for url in path:
urls[url] = False
elif type( path ) == types.DictType:
urls = path
else:
return S_ERROR( "TransformationClient.__checkArgumentFormat: Supplied path is not of the correct format." )
return S_OK( urls )
| avedaee/DIRAC | TransformationSystem/Client/TransformationClient.py | Python | gpl-3.0 | 22,189 |
from django.db import models
from django.contrib.auth.models import User
import MySQLdb
# Create your models here.
class Comentario(models.Model):
"""Comentario"""
contenido = models.TextField(help_text='Escribe un comentario')
fecha_coment = models.DateField(auto_now=True)
def __unicode__(self):
return self.contenido
class Estado(models.Model):
"""Estado"""
nom_estado = models.CharField(max_length=50)
def __unicode__(self):
return nom_estado
class Categoria(models.Model):
"""Categoria"""
nombre = models.CharField(max_length=50)
descripcion = models.TextField(help_text='Escribe una descripcion de la categoria')
class Entrada(models.Model):
"""Entrada"""
autor = models.ForeignKey(User)
comentario = models.ForeignKey(Comentario)
estado = models.ForeignKey(Estado)
titulo = models.CharField(max_length=100)
contenido = models.TextField(help_text='Redacta el contenido')
fecha_pub = models.DateField(auto_now=True)
def __unicode__(self):
return self.titulo
class Agregador(models.Model):
"""agreador"""
entrada = models.ForeignKey(Entrada)
categoria = models.ManyToManyField(Categoria) | darciga/cf | blog/models.py | Python | gpl-3.0 | 1,127 |
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/** @file CommonIO.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <libsolutil/CommonIO.h>
#include <libsolutil/Assertions.h>
#include <fstream>
#if defined(_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#include <termios.h>
#endif
using namespace std;
using namespace solidity::util;
namespace
{
template <typename T>
inline T readFile(boost::filesystem::path const& _file)
{
assertThrow(boost::filesystem::exists(_file), FileNotFound, _file.string());
// ifstream does not always fail when the path leads to a directory. Instead it might succeed
// with tellg() returning a nonsensical value so that std::length_error gets raised in resize().
assertThrow(boost::filesystem::is_regular_file(_file), NotAFile, _file.string());
T ret;
size_t const c_elementSize = sizeof(typename T::value_type);
std::ifstream is(_file.string(), std::ifstream::binary);
// Technically, this can still fail even though we checked above because FS content can change at any time.
assertThrow(is, FileNotFound, _file.string());
// get length of file:
is.seekg(0, is.end);
streamoff length = is.tellg();
if (length == 0)
return ret; // do not read empty file (MSVC does not like it)
is.seekg(0, is.beg);
ret.resize((static_cast<size_t>(length) + c_elementSize - 1) / c_elementSize);
is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<streamsize>(length));
return ret;
}
}
string solidity::util::readFileAsString(boost::filesystem::path const& _file)
{
return readFile<string>(_file);
}
string solidity::util::readUntilEnd(istream& _stdin)
{
ostringstream ss;
ss << _stdin.rdbuf();
return ss.str();
}
string solidity::util::readBytes(istream& _input, size_t _length)
{
string output;
output.resize(_length);
_input.read(output.data(), static_cast<streamsize>(_length));
// If read() reads fewer bytes it sets failbit in addition to eofbit.
if (_input.fail())
output.resize(static_cast<size_t>(_input.gcount()));
return output;
}
#if defined(_WIN32)
class DisableConsoleBuffering
{
public:
DisableConsoleBuffering()
{
m_stdin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(m_stdin, &m_oldMode);
SetConsoleMode(m_stdin, m_oldMode & (~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT)));
}
~DisableConsoleBuffering()
{
SetConsoleMode(m_stdin, m_oldMode);
}
private:
HANDLE m_stdin;
DWORD m_oldMode;
};
#else
class DisableConsoleBuffering
{
public:
DisableConsoleBuffering()
{
tcgetattr(0, &m_termios);
m_termios.c_lflag &= ~tcflag_t(ICANON);
m_termios.c_lflag &= ~tcflag_t(ECHO);
m_termios.c_cc[VMIN] = 1;
m_termios.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &m_termios);
}
~DisableConsoleBuffering()
{
m_termios.c_lflag |= ICANON;
m_termios.c_lflag |= ECHO;
tcsetattr(0, TCSADRAIN, &m_termios);
}
private:
struct termios m_termios;
};
#endif
int solidity::util::readStandardInputChar()
{
DisableConsoleBuffering disableConsoleBuffering;
return cin.get();
}
string solidity::util::absolutePath(string const& _path, string const& _reference)
{
boost::filesystem::path p(_path);
// Anything that does not start with `.` is an absolute path.
if (p.begin() == p.end() || (*p.begin() != "." && *p.begin() != ".."))
return _path;
boost::filesystem::path result(_reference);
// If filename is "/", then remove_filename() throws.
// See: https://github.com/boostorg/filesystem/issues/176
if (result.filename() != boost::filesystem::path("/"))
result.remove_filename();
for (boost::filesystem::path::iterator it = p.begin(); it != p.end(); ++it)
if (*it == "..")
result = result.parent_path();
else if (*it != ".")
result /= *it;
return result.generic_string();
}
string solidity::util::sanitizePath(string const& _path) {
return boost::filesystem::path(_path).generic_string();
}
| ethereum/solidity | libsolutil/CommonIO.cpp | C++ | gpl-3.0 | 4,494 |
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.reminders;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import com.todoroo.astrid.activity.AstridActivity;
import com.todoroo.astrid.activity.TaskListFragment;
import org.tasks.Broadcaster;
import org.tasks.R;
import org.tasks.reminders.SnoozeActivity;
import javax.inject.Inject;
/**
* This activity is launched when a user opens up a notification from the
* tray. It launches the appropriate activity based on the passed in parameters.
*
* @author timsu
*
*/
public class NotificationFragment extends TaskListFragment {
public static final String TOKEN_ID = "id"; //$NON-NLS-1$
@Inject Broadcaster broadcaster;
@Override
protected void initializeData() {
displayNotificationPopup();
super.initializeData();
}
private void displayNotificationPopup() {
final String title = extras.getString(Notifications.EXTRAS_TITLE);
final long taskId = extras.getLong(TOKEN_ID);
final AstridActivity activity = (AstridActivity) getActivity();
new Dialog(activity, R.style.ReminderDialog) {{
setContentView(R.layout.astrid_reminder_view_portrait);
findViewById(R.id.speech_bubble_container).setVisibility(View.GONE);
// set up listeners
findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dismiss();
}
});
findViewById(R.id.reminder_snooze).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dismiss();
activity.startActivity(new Intent(activity, SnoozeActivity.class) {{
putExtra(SnoozeActivity.TASK_ID, taskId);
}});
}
});
findViewById(R.id.reminder_complete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
broadcaster.completeTask(taskId);
dismiss();
}
});
findViewById(R.id.reminder_edit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
activity.onTaskListItemClicked(taskId);
}
});
((TextView) findViewById(R.id.reminder_title)).setText(activity.getString(R.string.rmd_NoA_dlg_title) + " " + title);
setOwnerActivity(activity);
}}.show();
}
}
| xVir/tasks | src/main/java/com/todoroo/astrid/reminders/NotificationFragment.java | Java | gpl-3.0 | 2,884 |
package com.simplecity.amp_library.model;
import android.content.Context;
import com.simplecity.amp_library.R;
import java.io.File;
public class ArtworkModel {
private static final String TAG = "ArtworkModel";
@ArtworkProvider.Type
public int type;
public File file;
public ArtworkModel(@ArtworkProvider.Type int type, File file) {
this.type = type;
this.file = file;
}
public static String getTypeString(Context context, @ArtworkProvider.Type int type) {
switch (type) {
case ArtworkProvider.Type.MEDIA_STORE:
return context.getString(R.string.artwork_type_media_store);
case ArtworkProvider.Type.TAG:
return context.getString(R.string.artwork_type_tag);
case ArtworkProvider.Type.FOLDER:
return "Folder";
case ArtworkProvider.Type.REMOTE:
return context.getString(R.string.artwork_type_internet);
}
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ArtworkModel that = (ArtworkModel) o;
if (type != that.type) return false;
return file != null ? file.equals(that.file) : that.file == null;
}
@Override
public int hashCode() {
int result = type;
result = 31 * result + (file != null ? file.hashCode() : 0);
return result;
}
} | timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/model/ArtworkModel.java | Java | gpl-3.0 | 1,505 |
package com.newppt.android.ui;
import com.newppt.android.data.AnimUtils2;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
public class ScaleImage extends ImageView {
final private int FLIP_DISTANCE = 30;
public ScaleImage(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public ScaleImage(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public ScaleImage(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
private int count = 0;
private long firClick;
private long secClick;
private boolean scaleTip = true;
private float x;
private float y;
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (MotionEvent.ACTION_DOWN == event.getAction()) {
count++;
if (count == 1) {
firClick = System.currentTimeMillis();
x = event.getX();
y = event.getY();
} else if (count == 2) {
secClick = System.currentTimeMillis();
float mx = event.getX();
float my = event.getY();
if (secClick - firClick < 700
&& Math.abs(mx - x) < FLIP_DISTANCE
&& Math.abs(my - y) < FLIP_DISTANCE) {
// ˫���¼�
if (scaleTip) {
x = event.getX();
y = event.getY();
AnimUtils2 animUtils2 = new AnimUtils2();
animUtils2.imageZoomOut(this, 200, x, y);
scaleTip = false;
}
else {
AnimUtils2 animUtils2 = new AnimUtils2();
animUtils2.imageZoomIn(this, 200, x, y);
scaleTip = true;
}
}
count = 0;
firClick = 0;
secClick = 0;
}
}
return true;
// return super.onTouchEvent(event);
}
}
| beyondckw/SynchronizeOfPPT | Android_v5/src/com/newppt/android/ui/ScaleImage.java | Java | gpl-3.0 | 1,835 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**************************************************************************
*
* Copyright 2010 American Public Media Group
*
* This file is part of AIR2.
*
* AIR2 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.
*
* AIR2 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 AIR2. If not, see <http://www.gnu.org/licenses/>.
*
*************************************************************************/
require_once "AIR2Logger.php";
require_once 'AirValidHtml.php'; //custom validator extension
require_once 'AirValidNoHtml.php'; //custom validator extension
/**
* AIR2_Record base class
*
* @author pkarman
* @package default
*/
abstract class AIR2_Record extends Doctrine_Record {
/* fields which the discriminator will treat as case-insensitive */
protected static $DISC_CASE_INSENSITIVE_FLDS = array('src_username',
'src_first_name', 'src_last_name', 'src_middle_initial', 'src_pre_name',
'src_post_name', 'sa_name', 'sa_first_name', 'sa_last_name', 'sa_post_name',
'smadd_line_1', 'smadd_line_2', 'smadd_city', 'sf_src_value');
/**
* tests validity of the record using the current data.
*
* (This is an override of base Doctrine functionality, to fix a bug with validation.)
*
* @param boolean $deep (optional) run the validation process on the relations
* @param boolean $hooks (optional) invoke save hooks before start
* @return boolean whether or not this record is valid
*/
public function isValid($deep = false, $hooks = true) {
if ( ! $this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) {
return true;
}
if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) {
return true;
}
if ($hooks) {
$this->invokeSaveHooks('pre', 'save');
$this->invokeSaveHooks('pre', $this->exists() ? 'update' : 'insert');
}
// Clear the stack from any previous errors.
$this->getErrorStack()->clear();
// Run validation process
$event = new Doctrine_Event($this, Doctrine_Event::RECORD_VALIDATE);
$this->preValidate($event);
$this->getTable()->getRecordListener()->preValidate($event);
if ( ! $event->skipOperation) {
$validator = new Doctrine_Validator();
$validator->validateRecord($this);
$this->validate();
if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) {
$this->validateOnInsert();
}
else {
$this->validateOnUpdate();
}
}
$this->getTable()->getRecordListener()->postValidate($event);
$this->postValidate($event);
$valid = $this->getErrorStack()->count() == 0 ? true : false;
if ($valid && $deep) {
$stateBeforeLock = $this->_state;
$this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED;
foreach ($this->_references as $reference) {
if ($reference instanceof Doctrine_Record) {
if ( ! $valid = $reference->isValid($deep)) {
break;
}
}
elseif ($reference instanceof Doctrine_Collection) {
foreach ($reference as $record) {
if ( ! $valid = $record->isValid($deep, $hooks)) {
break;
}
}
// Bugfix.
if (!$valid) {
break;
}
}
}
$this->_state = $stateBeforeLock;
}
return $valid;
}
/**
* Save the record to the database
*
* @param object $conn (optional)
*/
public function save( Doctrine_Connection $conn=null ) {
// unless explicitly passed, we find the _master connection
// for the current env.
if ( $conn === null ) {
$conn = AIR2_DBManager::get_master_connection();
}
parent::save($conn);
}
/**
* Insert or update record in the database.
*
* @param object $conn (optional)
*/
public function replace( Doctrine_Connection $conn=null ) {
// unless explicitly passed, we find the _master connection
// for the current env.
if ( $conn === null ) {
$conn = AIR2_DBManager::get_master_connection();
}
parent::replace($conn);
}
/**
* All AIR2_Record tables should be UTF8
*/
public function setTableDefinition() {
// utf8 charset
$this->option('collate', 'utf8_unicode_ci');
$this->option('charset', 'utf8');
}
/**
* Detect whether to add CreUser and UpdUser relations
*/
public function setUp() {
parent::setUp();
$cols = $this->getTable()->getColumnNames();
foreach ($cols as $name) {
if (preg_match('/_cre_user$/', $name)) {
$this->hasOne('UserStamp as CreUser',
array('local' => $name, 'foreign' => 'user_id')
);
}
elseif (preg_match('/_upd_user$/', $name)) {
$this->hasOne('UserStamp as UpdUser',
array('local' => $name, 'foreign' => 'user_id')
);
}
}
}
/**
* Custom AIR2 validation before update/save
*
* @param Doctrine_Event $event
*/
public function preValidate($event) {
air2_model_prevalidate($this);
}
/**
* Determines if a record produced from the tank can be safely moved into
* AIR2, or if it conflicts with existing AIR2 data.
*
* @param array $data
* @param TankSource $tsrc
* @param int $op
*/
public function discriminate($data, &$tsrc, $op=null) {
// update the record
$exists = $this->exists();
foreach ($data as $key => $val) {
// trim any incoming string values
if ($val && is_string($val)) {
$val = trim($val);
}
// always update new records
if (!$exists) {
$this->$key = $val;
}
// replace NULLs
elseif (is_null($this->$key)) {
$this->$key = $val;
}
// check for conflict
elseif ($this->disc_is_conflict($key, $this->$key, $val)) {
// CONFLICT! check the $op value
if ($op == AIR2_DISCRIM_REPLACE) {
$this->$key = $val;
}
else {
$this->disc_add_conflict($tsrc, $key, $this->$key, $val);
}
}
}
}
/**
* Compares 2 values, and determines if there is a conflict. Returning
* false will NOT update the field, so do it yourself if that's what you
* want.
*
* @param string $field
* @param mixed $oldval
* @param mixed $newval
* @return boolean
*/
protected function disc_is_conflict($field, $oldval, $newval) {
// check for case-insensitive fields
if (in_array($field, self::$DISC_CASE_INSENSITIVE_FLDS)) {
$oldval = strtolower($oldval);
$newval = strtolower($newval);
}
$result = ($oldval != $newval); // default php comparison
return $result;
}
/**
* Add a conflict to the tank_source
*
* @param TankSource $tsrc
* @param string $field
* @param mixed $oldval
* @param mixed $newval
*/
protected function disc_add_conflict($tsrc, $field, $oldval, $newval) {
$cls = $this->getTable()->getClassnameToReturn();
$uuidcol = air2_get_model_uuid_col($cls);
$uuid = $this->$uuidcol;
$tsrc->add_conflict($cls, $field, 'Conflicting tank value', $uuid);
}
/**
* Determine if a User has permission to read this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_read(User $u) {
throw new Exception('user_may_read not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission to write to this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_write(User $u) {
throw new Exception('user_may_write not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission to manage this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_manage(User $u) {
throw new Exception('user_may_manage not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission delete this record.
* By default calls through to user_may_manage().
*
* @param User $u
* @return authz integer
*/
public function user_may_delete(User $u) {
return $this->user_may_manage($u);
}
/**
* Record a visit against this record by a given user, at a given IPv4 address.
*
* @return void
* @author sgilbertson
* @param array $config Keys: user (@see User); ip (string|int).
* */
public function visit($config) {
$user = null;
$ip = null;
extract($config);
UserVisit::create_visit(
array(
'record' => $this,
'user' => $user,
'ip' => $ip,
)
);
}
/**
* Add User reading-authorization conditions to a Doctrine Query. By
* default, any restrictions must come from subclasses.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_read(AIR2_Query $q, User $u, $alias=null) {
//TODO: alter query in subclasses
}
/**
* Add User write-authorization conditions to a Doctrine Query.
* TODO: by default, this is the same as read permissions.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_write(AIR2_Query $q, User $u, $alias=null) {
self::query_may_read($q, $u, $alias);
}
/**
* Add User managing-authorization conditions to a Doctrine Query.
* TODO: by default, this is the same as write permissions.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_manage(AIR2_Query $q, User $u, $alias=null) {
self::query_may_write($q, $u, $alias);
}
/**
*
*
* @param string $model_name
* @param string $uuid
* @return AIR2_Record object for $model_name
*/
public static function find($model_name, $uuid) {
$tbl = Doctrine::getTable($model_name);
$col = air2_get_model_uuid_col($model_name);
return $tbl->findOneBy($col, $uuid);
}
/**
* Preinsert hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function preInsert($event) {
parent::preInsert($event);
AIR2Logger::log($this, 'insert');
}
/**
* Preupdate hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function preUpdate($event) {
parent::preUpdate($event);
AIR2Logger::log($this, 'update');
}
/**
* Postdelete hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function postDelete($event) {
AIR2Logger::log($this, 'delete');
parent::postDelete($event);
}
/**
* Returns object as JSON string. Only immediate columns
* (no related objects) are encoded.
*
* @return $json
*/
public function asJSON() {
$cols = $this->toArray(false);
return Encoding::json_encode_utf8($cols);
}
/**
* Custom mutator to reset timestamp to NULL value.
*
* @param unknown $field
* @param timestamp $value
*/
public function _set_timestamp($field, $value) {
if (empty($value) || !isset($value)) {
$this->_set($field, null);
}
else {
$this->_set($field, $value);
}
}
}
| publicinsightnetwork/audience-insight-repository | lib/AIR2_Record.php | PHP | gpl-3.0 | 13,214 |
<?php
/*
oauthcallback.php
This script handles the oAuth grant 'code' that is returned from the provider
(google/fb/openid), and calls the 'authenticate' method of the PBS_LAAS_Client.
That method exchanges the grant 'code' with PBS's endpoints to get access and refresh tokens,
uses those to get user info (email, name, etc), and then stores the tokens and userinfo encrypted
in session variables.
If the 'rememberme' variable was true, those tokens are also stored in an encrypted cookie.
*/
show_admin_bar(false);
remove_all_actions('wp_footer',1);
remove_all_actions('wp_header',1);
$defaults = get_option('pbs_passport_authenticate');
$passport = new PBS_Passport_Authenticate(dirname(__FILE__));
$laas_client = $passport->get_laas_client();
// log any current session out
$laas_client->logout();
$login_referrer = !empty($defaults['landing_page_url']) ? $defaults['landing_page_url'] : site_url();
if (!empty($_COOKIE["pbsoauth_login_referrer"])){
$login_referrer = $_COOKIE["pbsoauth_login_referrer"];
setcookie( 'pbsoauth_login_referrer', '', 1, '/', $_SERVER['HTTP_HOST']);
}
$membership_id = false;
// where to direct a logged in visitor who isn't a member
$not_member_path = 'pbsoauth/userinfo';
if (isset($_GET["state"])){
$state=($_GET["state"]);
$jwt = $passport->read_jwt($state);
if ($jwt) {
$membership_id = !empty($jwt['sub']) ? $jwt['sub'] : false;
// allow the jwt to override the current value with a return_path
$login_referrer = !empty($jwt['return_path']) ? site_url($jwt['return_path']) : $login_referrer;
// allow the jwt to set where the authenticated visitor who is not a member is sent
$not_member_path = !empty($jwt['not_member_path']) ? $jwt['not_member_path'] : $not_member_path;
} else {
// fallback case for older clients when membership_id was passed as a plaintext string
$membership_id = (!empty($state) ? $state : false);
}
}
$rememberme = false;
if (!empty($_COOKIE["pbsoauth_rememberme"])) {
$rememberme = $_COOKIE["pbsoauth_rememberme"];
}
// nonce is going to be in the jwt
$nonce = false;
$errors = array();
if (isset($_GET["code"])){
$code = $_GET["code"];
$userinfo = $laas_client->authenticate($code, $rememberme, $nonce);
}
// now we either have userinfo or null.
if (isset($userinfo["pid"])){
$pbs_uid = $userinfo["pid"];
// now we work with the mvault
$mvault_client = $passport->get_mvault_client();
$mvaultinfo = array();
if ($membership_id) {
// this is an activation!
$mvaultinfo = $mvault_client->get_membership($membership_id);
if (isset($mvaultinfo["membership_id"])) {
$mvaultinfo = $mvault_client->activate($membership_id, $pbs_uid);
}
}
// is the person activated now?
if (!isset($mvaultinfo["membership_id"])) {
$mvaultinfo = $mvault_client->get_membership_by_uid($pbs_uid);
if (!isset($mvaultinfo["membership_id"])) {
// still not activated, redirect the member as needed
$login_referrer = site_url($not_member_path);
}
}
}
wp_redirect($login_referrer);
exit();
?>
| tamw-wnet/pbs-passport-authenticate | templates/oauthcallback.php | PHP | gpl-3.0 | 3,067 |
#ifndef MUSPLAY_USE_WINAPI
#include <QtDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QSlider>
#include <QSettings>
#include <QMenu>
#include <QDesktopServices>
#include <QUrl>
#include "ui_mainwindow.h"
#include "musplayer_qt.h"
#include "../Player/mus_player.h"
#include "../AssocFiles/assoc_files.h"
#include "../Effects/reverb.h"
#include <math.h>
#include "../version.h"
MusPlayer_Qt::MusPlayer_Qt(QWidget *parent) : QMainWindow(parent),
MusPlayerBase(),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
PGE_MusicPlayer::setMainWindow(this);
#ifdef Q_OS_MAC
this->setWindowIcon(QIcon(":/cat_musplay.icns"));
#endif
#ifdef Q_OS_WIN
this->setWindowIcon(QIcon(":/cat_musplay.ico"));
#endif
ui->fmbank->clear();
int totalBakns = MIX_ADLMIDI_getTotalBanks();
const char *const *names = MIX_ADLMIDI_getBankNames();
for(int i = 0; i < totalBakns; i++)
ui->fmbank->addItem(QString("%1 = %2").arg(i).arg(names[i]));
ui->centralWidget->window()->setWindowFlags(
Qt::WindowTitleHint |
Qt::WindowSystemMenuHint |
Qt::WindowCloseButtonHint |
Qt::WindowMinimizeButtonHint |
Qt::MSWindowsFixedSizeDialogHint);
connect(&m_blinker, SIGNAL(timeout()), this, SLOT(_blink_red()));
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenu(QPoint)));
connect(ui->volume, &QSlider::valueChanged, [this](int x)
{
on_volume_valueChanged(x);
});
connect(ui->fmbank, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int x)
{
on_fmbank_currentIndexChanged(x);
});
connect(ui->volumeModel, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int x)
{
on_volumeModel_currentIndexChanged(x);
});
connect(ui->tremolo, &QCheckBox::clicked, this, [this](int x)
{
on_tremolo_clicked(x);
});
connect(ui->vibrato, &QCheckBox::clicked, this, [this](int x)
{
on_vibrato_clicked(x);
});
connect(ui->modulation, &QCheckBox::clicked, this, [this](int x)
{
on_modulation_clicked(x);
});
connect(ui->adlibMode, &QCheckBox::clicked, this, [this](int x)
{
on_adlibMode_clicked(x);
});
connect(ui->logVolumes, &QCheckBox::clicked, this, [this](int x)
{
on_logVolumes_clicked(x);
});
connect(ui->playListPush, &QPushButton::clicked, this, &MusPlayer_Qt::playList_pushCurrent);
connect(ui->playListPop, &QPushButton::clicked, this, &MusPlayer_Qt::playList_popCurrent);
QApplication::setOrganizationName(_COMPANY);
QApplication::setOrganizationDomain(_PGE_URL);
QApplication::setApplicationName("PGE Music Player");
ui->playList->setModel(&playList);
ui->playList->setVisible(false);
ui->playListPush->setVisible(false);
ui->playListPop->setVisible(false);
ui->sfx_testing->setVisible(false);
QSettings setup;
restoreGeometry(setup.value("Window-Geometry").toByteArray());
ui->mididevice->setCurrentIndex(setup.value("MIDI-Device", 0).toInt());
ui->opnmidi_extra->setVisible(ui->mididevice->currentIndex() == 3);
ui->adlmidi_xtra->setVisible(ui->mididevice->currentIndex() == 0);
switch(ui->mididevice->currentIndex())
{
case 0:
MIX_SetMidiDevice(MIDI_ADLMIDI);
break;
case 1:
MIX_SetMidiDevice(MIDI_Timidity);
break;
case 2:
MIX_SetMidiDevice(MIDI_Native);
break;
case 3:
MIX_SetMidiDevice(MIDI_OPNMIDI);
break;
case 4:
MIX_SetMidiDevice(MIDI_Fluidsynth);
break;
default:
MIX_SetMidiDevice(MIDI_ADLMIDI);
break;
}
ui->fmbank->setCurrentIndex(setup.value("ADLMIDI-Bank-ID", 58).toInt());
MIX_ADLMIDI_setBankID(ui->fmbank->currentIndex());
ui->volumeModel->setCurrentIndex(setup.value("ADLMIDI-VolumeModel", 0).toInt());
MIX_ADLMIDI_setVolumeModel(ui->volumeModel->currentIndex());
ui->tremolo->setChecked(setup.value("ADLMIDI-Tremolo", true).toBool());
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
ui->vibrato->setChecked(setup.value("ADLMIDI-Vibrato", true).toBool());
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
ui->adlibMode->setChecked(setup.value("ADLMIDI-AdLib-Drums-Mode", false).toBool());
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
ui->modulation->setChecked(setup.value("ADLMIDI-Scalable-Modulation", false).toBool());
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
ui->logVolumes->setChecked(setup.value("ADLMIDI-LogarithmicVolumes", false).toBool());
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->logVolumes->isChecked()));
ui->volume->setValue(setup.value("Volume", 128).toInt());
m_prevTrackID = ui->trackID->value();
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(false);
ui->gme_setup->setVisible(false);
currentMusic = setup.value("RecentMusic", "").toString();
m_testSfxDir = setup.value("RecentSfxDir", "").toString();
adjustSize();
}
MusPlayer_Qt::~MusPlayer_Qt()
{
on_stop_clicked();
if(m_testSfx)
Mix_FreeChunk(m_testSfx);
m_testSfx = nullptr;
Mix_CloseAudio();
QSettings setup;
setup.setValue("Window-Geometry", saveGeometry());
setup.setValue("MIDI-Device", ui->mididevice->currentIndex());
setup.setValue("ADLMIDI-Bank-ID", ui->fmbank->currentIndex());
setup.setValue("ADLMIDI-VolumeModel", ui->volumeModel->currentIndex());
setup.setValue("ADLMIDI-Tremolo", ui->tremolo->isChecked());
setup.setValue("ADLMIDI-Vibrato", ui->vibrato->isChecked());
setup.setValue("ADLMIDI-AdLib-Drums-Mode", ui->adlibMode->isChecked());
setup.setValue("ADLMIDI-Scalable-Modulation", ui->modulation->isChecked());
setup.setValue("ADLMIDI-LogarithmicVolumes", ui->logVolumes->isChecked());
setup.setValue("Volume", ui->volume->value());
setup.setValue("RecentMusic", currentMusic);
setup.setValue("RecentSfxDir", m_testSfxDir);
delete ui;
}
void MusPlayer_Qt::dropEvent(QDropEvent *e)
{
this->raise();
this->setFocus(Qt::ActiveWindowFocusReason);
if(ui->recordWav->isChecked())
return;
for(const QUrl &url : e->mimeData()->urls())
{
const QString &fileName = url.toLocalFile();
currentMusic = fileName;
}
ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
this->raise();
e->accept();
}
void MusPlayer_Qt::dragEnterEvent(QDragEnterEvent *e)
{
if(e->mimeData()->hasUrls())
e->acceptProposedAction();
}
void MusPlayer_Qt::contextMenu(const QPoint &pos)
{
QMenu x;
QAction *open = x.addAction("Open");
QAction *playpause = x.addAction("Play/Pause");
QAction *stop = x.addAction("Stop");
x.addSeparator();
QAction *reverb = x.addAction("Reverb");
reverb->setCheckable(true);
reverb->setChecked(PGE_MusicPlayer::reverbEnabled);
QAction *assoc_files = x.addAction("Associate files");
QAction *play_list = x.addAction("Play-list mode [WIP]");
play_list->setCheckable(true);
play_list->setChecked(playListMode);
QAction *sfx_testing = x.addAction("SFX testing");
sfx_testing->setCheckable(true);
sfx_testing->setChecked(ui->sfx_testing->isVisible());
x.addSeparator();
QMenu *about = x.addMenu("About");
QAction *version = about->addAction("SDL Mixer X Music Player v." _FILE_VERSION);
version->setEnabled(false);
QAction *license = about->addAction("Licensed under GNU GPLv3 license");
about->addSeparator();
QAction *source = about->addAction("Get source code");
QAction *ret = x.exec(this->mapToGlobal(pos));
if(open == ret)
on_open_clicked();
else if(playpause == ret)
on_play_clicked();
else if(stop == ret)
on_stop_clicked();
else if(reverb == ret)
{
PGE_MusicPlayer::reverbEnabled = reverb->isChecked();
if(PGE_MusicPlayer::reverbEnabled)
Mix_RegisterEffect(MIX_CHANNEL_POST, reverbEffect, reverbEffectDone, NULL);
else
Mix_UnregisterEffect(MIX_CHANNEL_POST, reverbEffect);
}
else if(assoc_files == ret)
{
AssocFiles af(this);
af.setWindowModality(Qt::WindowModal);
af.exec();
}
else if(ret == play_list)
{
setPlayListMode(!playListMode);
}
else if(ret == sfx_testing)
{
ui->sfx_testing->setVisible(!ui->sfx_testing->isVisible());
updateGeometry();
adjustSize();
}
else if(ret == license)
QDesktopServices::openUrl(QUrl("http://www.gnu.org/licenses/gpl"));
else if(ret == source)
QDesktopServices::openUrl(QUrl("https://github.com/WohlSoft/PGE-Project"));
}
void MusPlayer_Qt::openMusicByArg(QString musPath)
{
if(ui->recordWav->isChecked()) return;
currentMusic = musPath;
//ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::setPlayListMode(bool plMode)
{
on_stop_clicked();
playListMode = plMode;
if(!plMode)
{
playList.clear();
} else {
playList_pushCurrent();
}
ui->playList->setVisible(plMode);
ui->playListPush->setVisible(plMode);
ui->playListPop->setVisible(plMode);
if(ui->recordWav->isChecked())
ui->recordWav->click();
ui->recordWav->setVisible(!plMode);
PGE_MusicPlayer::setPlayListMode(playListMode);
adjustSize();
}
void MusPlayer_Qt::playList_pushCurrent(bool)
{
PlayListEntry e;
e.name = ui->musTitle->text();
e.fullPath = currentMusic;
e.gme_trackNum = ui->trackID->value();
e.midi_device = ui->mididevice->currentIndex();
e.adl_bankNo = ui->fmbank->currentIndex();
e.adl_cmfVolumes = ui->volumeModel->currentIndex();
e.adl_tremolo = ui->tremolo->isChecked();
e.adl_vibrato = ui->vibrato->isChecked();
e.adl_adlibDrums = ui->adlibMode->isChecked();
e.adl_modulation = ui->modulation->isChecked();
e.adl_cmfVolumes = ui->logVolumes->isChecked();
playList.insertEntry(e);
}
void MusPlayer_Qt::playList_popCurrent(bool)
{
playList.removeEntry();
}
void MusPlayer_Qt::playListNext()
{
PlayListEntry e = playList.nextEntry();
currentMusic = e.fullPath;
switchMidiDevice(e.midi_device);
ui->trackID->setValue(e.gme_trackNum);
ui->fmbank->setCurrentIndex(e.adl_bankNo);
ui->volumeModel->setCurrentIndex(e.adl_volumeModel);
ui->tremolo->setChecked(e.adl_tremolo);
ui->vibrato->setChecked(e.adl_vibrato);
ui->adlibMode->setChecked(e.adl_adlibDrums);
ui->modulation->setChecked(e.adl_modulation);
ui->logVolumes->setChecked(e.adl_cmfVolumes);
MIX_ADLMIDI_setBankID(e.adl_bankNo);
MIX_ADLMIDI_setVolumeModel(e.adl_volumeModel);
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
MIX_ADLMIDI_setLogarithmicVolumes(static_cast<int>(ui->logVolumes->isChecked()));
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::switchMidiDevice(int index)
{
ui->midi_setup->setVisible(false);
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(true);
switch(index)
{
case 0:
MIX_SetMidiDevice(MIDI_ADLMIDI);
ui->adlmidi_xtra->setVisible(true);
break;
case 1:
MIX_SetMidiDevice(MIDI_Timidity);
break;
case 2:
MIX_SetMidiDevice(MIDI_Native);
break;
case 3:
MIX_SetMidiDevice(MIDI_OPNMIDI);
ui->opnmidi_extra->setVisible(true);
break;
case 4:
MIX_SetMidiDevice(MIDI_Fluidsynth);
break;
default:
MIX_SetMidiDevice(MIDI_ADLMIDI);
ui->adlmidi_xtra->setVisible(true);
break;
}
}
void MusPlayer_Qt::on_open_clicked()
{
QString file = QFileDialog::getOpenFileName(this, tr("Open music file"),
(currentMusic.isEmpty() ? QApplication::applicationDirPath() : currentMusic), "All (*.*)");
if(file.isEmpty())
return;
currentMusic = file;
//ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::on_stop_clicked()
{
PGE_MusicPlayer::MUS_stopMusic();
ui->play->setText(tr("Play"));
if(ui->recordWav->isChecked())
{
ui->recordWav->setChecked(false);
PGE_MusicPlayer::stopWavRecording();
ui->open->setEnabled(true);
ui->play->setEnabled(true);
ui->frame->setEnabled(true);
m_blinker.stop();
ui->recordWav->setStyleSheet("");
}
}
void MusPlayer_Qt::on_play_clicked()
{
if(Mix_PlayingMusic())
{
if(Mix_PausedMusic())
{
Mix_ResumeMusic();
ui->play->setText(tr("Pause"));
return;
}
else
{
Mix_PauseMusic();
ui->play->setText(tr("Resume"));
return;
}
}
ui->play->setText(tr("Play"));
m_prevTrackID = ui->trackID->value();
if(PGE_MusicPlayer::MUS_openFile(currentMusic + "|" + ui->trackID->text()))
{
PGE_MusicPlayer::MUS_changeVolume(ui->volume->value());
PGE_MusicPlayer::MUS_playMusic();
ui->play->setText(tr("Pause"));
}
ui->musTitle->setText(PGE_MusicPlayer::MUS_getMusTitle());
ui->musArtist->setText(PGE_MusicPlayer::MUS_getMusArtist());
ui->musAlbum->setText(PGE_MusicPlayer::MUS_getMusAlbum());
ui->musCopyright->setText(PGE_MusicPlayer::MUS_getMusCopy());
ui->gme_setup->setVisible(false);
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(false);
ui->frame->setVisible(false);
ui->frame->setVisible(true);
ui->smallInfo->setText(PGE_MusicPlayer::musicType());
ui->gridLayout->update();
switch(PGE_MusicPlayer::type)
{
case MUS_MID:
ui->adlmidi_xtra->setVisible(ui->mididevice->currentIndex() == 0);
ui->opnmidi_extra->setVisible(ui->mididevice->currentIndex() == 3);
ui->midi_setup->setVisible(true);
ui->frame->setVisible(true);
break;
case MUS_SPC:
ui->gme_setup->setVisible(true);
ui->frame->setVisible(true);
break;
default:
break;
}
adjustSize();
}
void MusPlayer_Qt::on_mididevice_currentIndexChanged(int index)
{
switchMidiDevice(index);
adjustSize();
if(Mix_PlayingMusic())
{
if(PGE_MusicPlayer::type == MUS_MID)
{
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
}
}
void MusPlayer_Qt::on_trackID_editingFinished()
{
if(Mix_PlayingMusic())
{
if((PGE_MusicPlayer::type == MUS_SPC) && (m_prevTrackID != ui->trackID->value()))
{
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
}
}
void MusPlayer_Qt::on_recordWav_clicked(bool checked)
{
if(checked)
{
PGE_MusicPlayer::MUS_stopMusic();
ui->play->setText(tr("Play"));
QFileInfo twav(currentMusic);
PGE_MusicPlayer::stopWavRecording();
QString wavPathBase = twav.absoluteDir().absolutePath() + "/" + twav.baseName();
QString wavPath = wavPathBase + ".wav";
int count = 1;
while(QFile::exists(wavPath))
wavPath = wavPathBase + QString("-%1.wav").arg(count++);
PGE_MusicPlayer::startWavRecording(wavPath);
on_play_clicked();
ui->open->setEnabled(false);
ui->play->setEnabled(false);
ui->frame->setEnabled(false);
m_blinker.start(500);
}
else
{
on_stop_clicked();
PGE_MusicPlayer::stopWavRecording();
ui->open->setEnabled(true);
ui->play->setEnabled(true);
ui->frame->setEnabled(true);
m_blinker.stop();
ui->recordWav->setStyleSheet("");
}
}
void MusPlayer_Qt::on_resetDefaultADLMIDI_clicked()
{
ui->fmbank->setCurrentIndex(58);
ui->tremolo->setChecked(true);
ui->vibrato->setChecked(true);
ui->adlibMode->setChecked(false);
ui->modulation->setChecked(false);
ui->logVolumes->setChecked(false);
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
MIX_ADLMIDI_setLogarithmicVolumes(static_cast<int>(ui->logVolumes->isChecked()));
on_volumeModel_currentIndexChanged(ui->volumeModel->currentIndex());
on_fmbank_currentIndexChanged(ui->fmbank->currentIndex());
}
void MusPlayer_Qt::_blink_red()
{
m_blink_state = !m_blink_state;
if(m_blink_state)
ui->recordWav->setStyleSheet("background-color : red; color : black;");
else
ui->recordWav->setStyleSheet("background-color : black; color : red;");
}
void MusPlayer_Qt::on_sfx_open_clicked()
{
QString file = QFileDialog::getOpenFileName(this, tr("Open SFX file"),
(m_testSfxDir.isEmpty() ? QApplication::applicationDirPath() : m_testSfxDir), "All (*.*)");
if(file.isEmpty())
return;
if(m_testSfx)
{
Mix_HaltChannel(0);
Mix_FreeChunk(m_testSfx);
m_testSfx = nullptr;
}
m_testSfx = Mix_LoadWAV(file.toUtf8().data());
if(!m_testSfx)
QMessageBox::warning(this, "SFX open error!", QString("Mix_LoadWAV: ") + Mix_GetError());
else
{
QFileInfo f(file);
m_testSfxDir = f.absoluteDir().absolutePath();
ui->sfx_file->setText(f.fileName());
}
}
void MusPlayer_Qt::on_sfx_play_clicked()
{
if(!m_testSfx)
return;
if(Mix_PlayChannelTimedVolume(0,
m_testSfx,
ui->sfx_loops->value(),
ui->sfx_timed->value(),
ui->sfx_volume->value()) == -1)
{
QMessageBox::warning(this, "SFX play error!", QString("Mix_PlayChannelTimedVolume: ") + Mix_GetError());
}
}
void MusPlayer_Qt::on_sfx_fadeIn_clicked()
{
if(!m_testSfx)
return;
if(Mix_FadeInChannelTimedVolume(0,
m_testSfx,
ui->sfx_loops->value(),
ui->sfx_fadems->value(),
ui->sfx_timed->value(),
ui->sfx_volume->value()) == -1)
{
QMessageBox::warning(this, "SFX play error!", QString("Mix_PlayChannelTimedVolume: ") + Mix_GetError());
}
}
void MusPlayer_Qt::on_sfx_stop_clicked()
{
if(!m_testSfx)
return;
Mix_HaltChannel(0);
}
void MusPlayer_Qt::on_sfx_fadeout_clicked()
{
if(!m_testSfx)
return;
Mix_FadeOutChannel(0, ui->sfx_fadems->value());
}
#endif
| jpmac26/PGE-Project | MusicPlayer/MainWindow/musplayer_qt.cpp | C++ | gpl-3.0 | 19,656 |
namespace Freenex.FeexRanks.Database
{
public enum EQueryType
{
Scalar,
Reader,
NonQuery
}
} | Freenex1911/FeexRanks | Database/EQueryType.cs | C# | gpl-3.0 | 128 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace guess_word_game
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DAOForm());
}
}
}
| AironSkythe/guess-word-game | guess_game/guess_game/Program.cs | C# | gpl-3.0 | 518 |
// tinygettext - A gettext replacement that works directly on .po files
// Copyright (C) 2006 Ingo Ruhnke <grumbel@gmx.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include <assert.h>
#include "log_stream.hpp"
#include "dictionary.hpp"
namespace tinygettext {
Dictionary::Dictionary(const std::string& charset_) :
entries(),
ctxt_entries(),
charset(charset_),
plural_forms()
{
m_has_fallback = false;
}
Dictionary::~Dictionary()
{
}
std::string
Dictionary::get_charset() const
{
return charset;
}
void
Dictionary::set_plural_forms(const PluralForms& plural_forms_)
{
plural_forms = plural_forms_;
}
PluralForms
Dictionary::get_plural_forms() const
{
return plural_forms;
}
std::string
Dictionary::translate_plural(const std::string& msgid, const std::string& msgid_plural, int num)
{
return translate_plural(entries, msgid, msgid_plural, num);
}
std::string
Dictionary::translate_plural(const Entries& dict, const std::string& msgid, const std::string& msgid_plural, int count)
{
Entries::const_iterator i = dict.find(msgid);
const std::vector<std::string>& msgstrs = i->second;
if (i != dict.end())
{
unsigned int n = 0;
n = plural_forms.get_plural(count);
assert(/*n >= 0 &&*/ n < msgstrs.size());
if (!msgstrs[n].empty())
return msgstrs[n];
else
if (count == 1) // default to english rules
return msgid;
else
return msgid_plural;
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
//log_info << "Candidates: " << std::endl;
//for (i = dict.begin(); i != dict.end(); ++i)
// log_info << "'" << i->first << "'" << std::endl;
if (count == 1) // default to english rules
return msgid;
else
return msgid_plural;
}
}
std::string
Dictionary::translate(const std::string& msgid)
{
return translate(entries, msgid);
}
std::string
Dictionary::translate(const Entries& dict, const std::string& msgid)
{
Entries::const_iterator i = dict.find(msgid);
if (i != dict.end() && !i->second.empty())
{
return i->second[0];
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
if (m_has_fallback) return m_fallback->translate(msgid);
else return msgid;
}
}
std::string
Dictionary::translate_ctxt(const std::string& msgctxt, const std::string& msgid)
{
CtxtEntries::iterator i = ctxt_entries.find(msgctxt);
if (i != ctxt_entries.end())
{
return translate(i->second, msgid);
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
return msgid;
}
}
std::string
Dictionary::translate_ctxt_plural(const std::string& msgctxt,
const std::string& msgid, const std::string& msgidplural, int num)
{
CtxtEntries::iterator i = ctxt_entries.find(msgctxt);
if (i != ctxt_entries.end())
{
return translate_plural(i->second, msgid, msgidplural, num);
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
if (num != 1) // default to english
return msgidplural;
else
return msgid;
}
}
void
Dictionary::add_translation(const std::string& msgid, const std::string& ,
const std::vector<std::string>& msgstrs)
{
// Do we need msgid2 for anything? its after all supplied to the
// translate call, so we just throw it away here
entries[msgid] = msgstrs;
}
void
Dictionary::add_translation(const std::string& msgid, const std::string& msgstr)
{
std::vector<std::string>& vec = entries[msgid];
if (vec.empty())
{
vec.push_back(msgstr);
}
else
{
log_warning << "collision in add_translation: '"
<< msgid << "' -> '" << msgstr << "' vs '" << vec[0] << "'" << std::endl;
vec[0] = msgstr;
}
}
void
Dictionary::add_translation(const std::string& msgctxt,
const std::string& msgid, const std::string& msgid_plural,
const std::vector<std::string>& msgstrs)
{
std::vector<std::string>& vec = ctxt_entries[msgctxt][msgid];
if (vec.empty())
{
vec = msgstrs;
}
else
{
log_warning << "collision in add_translation(\"" << msgctxt << "\", \"" << msgid << "\", \"" << msgid_plural << "\")" << std::endl;
vec = msgstrs;
}
}
void
Dictionary::add_translation(const std::string& msgctxt, const std::string& msgid, const std::string& msgstr)
{
std::vector<std::string>& vec = ctxt_entries[msgctxt][msgid];
if (vec.empty())
{
vec.push_back(msgstr);
}
else
{
log_warning << "collision in add_translation(\"" << msgctxt << "\", \"" << msgid << "\")" << std::endl;
vec[0] = msgstr;
}
}
} // namespace tinygettext
/* EOF */
| clbr/stk | src/tinygettext/dictionary.cpp | C++ | gpl-3.0 | 5,378 |
/*
Copyright 2011 Anton Kraievoy akraievoy@gmail.com
This file is part of Holonet.
Holonet 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.
Holonet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty
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 Holonet. If not, see <http://www.gnu.org/licenses/>.
*/
package algores.holonet.core.events;
import algores.holonet.core.CommunicationException;
import algores.holonet.core.Network;
import algores.holonet.core.Node;
import algores.holonet.core.RequestPair;
import algores.holonet.core.api.Address;
import algores.holonet.core.api.Key;
import algores.holonet.core.api.tier1.delivery.LookupService;
import com.google.common.base.Optional;
import org.akraievoy.cnet.gen.vo.EntropySource;
import java.util.Collection;
/**
* Lookup entry event.
*/
public class EventNetLookup extends Event<EventNetLookup> {
protected int retries = 1;
public Result executeInternal(final Network network, final EntropySource eSource) {
Result aggregateResult = Result.PASSIVE;
for (int sequentialIndex = 0; sequentialIndex < retries; sequentialIndex++) {
Optional<RequestPair> optRequest =
network.generateRequestPair(eSource);
if (!optRequest.isPresent()) {
if (sequentialIndex > 0) {
throw new IllegalStateException(
"request model became empty amid request generation streak?"
);
}
break;
}
RequestPair request = optRequest.get();
Collection<Key> serverKeys =
request.server.getServices().getStorage().getKeys();
final Key mapping =
serverKeys.isEmpty() ?
// we may also pull other keys from the range, not only the greatest one
request.server.getServices().getRouting().ownRoute().getRange().getRKey().prev() :
eSource.randomElement(serverKeys);
final LookupService lookupSvc =
request.client.getServices().getLookup();
final Address address;
try {
address = lookupSvc.lookup(
mapping.getKey(), true, LookupService.Mode.GET,
Optional.of(request.server.getAddress())
);
} catch (CommunicationException e) {
if (!aggregateResult.equals(Result.FAILURE)) {
aggregateResult = handleEventFailure(e, null);
}
continue;
}
final Node lookupResult = network.getEnv().getNode(address);
if (
!lookupResult.equals(request.server)
) {
network.getInterceptor().reportInconsistentLookup(LookupService.Mode.GET);
}
aggregateResult = Result.SUCCESS;
}
return aggregateResult;
}
public void setRetries(int retryCount) {
this.retries = retryCount;
}
public EventNetLookup withRetries(int retryCount) {
setRetries(retryCount);
return this;
}
}
| akraievoy/holonet | src/main/java/algores/holonet/core/events/EventNetLookup.java | Java | gpl-3.0 | 3,225 |
var path = require('path');
var Q = require('q');
var fs = require('fs');
var mv = require('mv');
var Upload = require('./upload.model');
exports.upload = function (req, res) {
var tmpPath = req.files[0].path;
var newFileName = Math.random().toString(36).substring(7)+path.extname(tmpPath);
var targetPath = path.resolve(process.env.UPLOAD_PATH, newFileName);
var defer = Q.defer();
mv(tmpPath, targetPath, function (err) {
if (err) {
return nextIteration.reject(err);
}
targetPath = targetPath.substring(targetPath.indexOf('upload'));
Upload.createUpload(targetPath).then(function(upload) {
defer.resolve(upload);
}, function(err) {
defer.reject(err);
});
});
defer.promise.then(function (upload) {
res.json({
status: true,
data: upload._id
});
}, function(err) {
console.log(err);
res.json({
status: false,
reason: err.toString()
});
});
}; | NishantDesai1306/lost-and-found | server/api/upload/upload.controller.js | JavaScript | gpl-3.0 | 1,066 |
// Karma configuration
// Generated on Thu Jul 24 2014 18:11:41 GMT-0700 (PDT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'src/*.js',
'test/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| bthaase/DDWarden | html/lib/angular-abortable-requests/karma.conf.js | JavaScript | gpl-3.0 | 1,741 |
package br.ifrn.meutcc.visao;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.ifrn.meutcc.modelo.Aluno;
import br.ifrn.meutcc.modelo.Orientador;
@WebServlet("/ViewAlunoCandidatou")
public class ViewAlunoCandidatou extends HttpServlet {
private static final long serialVersionUID = 1L;
public ViewAlunoCandidatou() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
int idCandidato = 2;
int idTema = -1;
try {
idTema = Integer.parseInt(id);
} catch (NumberFormatException nfex) {
nfex.printStackTrace();
}
Orientador a = new Orientador();
Orientador orientador = a.getOrientadorPorTema(idTema);
Aluno logic = new Aluno();
logic.registraObserver(orientador);
boolean aluno = logic.addCandidato(idTema, idCandidato);
request.setAttribute("candidatou", logic.getStatus());
request.setAttribute("aluno", aluno);
request.getRequestDispatcher("viewAluno.jsp").forward(request, response);
}
}
| hayssac/MeuTCC_Grupo1 | MeuTCCApp/src/br/ifrn/meutcc/visao/ViewAlunoCandidatou.java | Java | gpl-3.0 | 1,286 |
package com.idega.development.presentation;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWMainApplication;
import com.idega.presentation.IWContext;
import com.idega.presentation.Image;
import com.idega.presentation.Layer;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.Table;
import com.idega.presentation.text.HorizontalRule;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.IFrame;
import com.idega.repository.data.RefactorClassRegistry;
/**
* Title: idega Framework
* Description:
* Copyright: Copyright (c) 2001
* Company: idega
* @author <a href=mailto:"tryggvi@idega.is">Tryggvi Larusson</a>
* @version 1.0
*/
public class IWDeveloper extends com.idega.presentation.app.IWApplication {
private static final String localizerParameter = "iw_localizer";
private static final String localeswitcherParameter = "iw_localeswitcher";
private static final String bundleCreatorParameter = "iw_bundlecreator";
private static final String bundleComponentManagerParameter = "iw_bundlecompmanager";
private static final String applicationPropertiesParameter = "iw_application_properties_setter";
private static final String bundlesPropertiesParameter = "iw_bundle_properties_setter";
public static final String actionParameter = "iw_developer_action";
public static final String dbPoolStatusViewerParameter = "iw_poolstatus_viewer";
public static final String updateManagerParameter = "iw_update_manager";
public static final String frameName = "iwdv_rightFrame";
public static final String PARAMETER_CLASS_NAME = "iwdv_class_name";
public IWDeveloper() {
super("idegaWeb Developer");
add(IWDeveloper.IWDevPage.class);
super.setResizable(true);
super.setScrollbar(true);
super.setScrolling(1, true);
super.setWidth(800);
super.setHeight(600);
//super.setOnLoad("moveTo(0,0);");
}
public static class IWDevPage extends com.idega.presentation.ui.Window {
public IWDevPage() {
this.setStatus(true);
}
private Table mainTable;
private Table objectTable;
private IFrame rightFrame;
private int count = 1;
public void main(IWContext iwc) throws Exception {
IWBundle iwbCore = getBundle(iwc);
if (iwc.isIE()) {
getParentPage().setBackgroundColor("#B0B29D");
}
Layer topLayer = new Layer(Layer.DIV);
topLayer.setZIndex(3);
topLayer.setPositionType(Layer.FIXED);
topLayer.setTopPosition(0);
topLayer.setLeftPosition(0);
topLayer.setBackgroundColor("#0E2456");
topLayer.setWidth(Table.HUNDRED_PERCENT);
topLayer.setHeight(25);
add(topLayer);
Table headerTable = new Table();
headerTable.setCellpadding(0);
headerTable.setCellspacing(0);
headerTable.setWidth(Table.HUNDRED_PERCENT);
headerTable.setAlignment(2,1,Table.HORIZONTAL_ALIGN_RIGHT);
topLayer.add(headerTable);
Image idegaweb = iwbCore.getImage("/editorwindow/idegaweb.gif","idegaWeb");
headerTable.add(idegaweb,1,1);
Text adminTitle = new Text("idegaWeb Developer");
adminTitle.setStyleAttribute("color:#FFFFFF;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;margin-right:5px;");
headerTable.add(adminTitle,2,1);
Layer leftLayer = new Layer(Layer.DIV);
leftLayer.setZIndex(2);
leftLayer.setPositionType(Layer.FIXED);
leftLayer.setTopPosition(25);
leftLayer.setLeftPosition(0);
leftLayer.setPadding(5);
leftLayer.setBackgroundColor("#B0B29D");
leftLayer.setWidth(180);
leftLayer.setHeight(Table.HUNDRED_PERCENT);
add(leftLayer);
DeveloperList list = new DeveloperList();
leftLayer.add(list);
Layer rightLayer = new Layer(Layer.DIV);
rightLayer.setZIndex(1);
rightLayer.setPositionType(Layer.ABSOLUTE);
rightLayer.setTopPosition(25);
rightLayer.setPadding(5);
if (iwc.isIE()) {
rightLayer.setBackgroundColor("#FFFFFF");
rightLayer.setWidth(Table.HUNDRED_PERCENT);
rightLayer.setHeight(Table.HUNDRED_PERCENT);
rightLayer.setLeftPosition(180);
}
else {
rightLayer.setLeftPosition(190);
}
add(rightLayer);
if (iwc.isParameterSet(PARAMETER_CLASS_NAME)) {
String className = IWMainApplication.decryptClassName(iwc.getParameter(PARAMETER_CLASS_NAME));
PresentationObject obj = (PresentationObject) RefactorClassRegistry.getInstance().newInstance(className, this.getClass());
rightLayer.add(obj);
}
else {
rightLayer.add(new Localizer());
}
}
}
public static Table getTitleTable(String displayString, Image image) {
Table titleTable = new Table(1, 2);
titleTable.setCellpadding(0);
titleTable.setCellspacing(0);
titleTable.setWidth("100%");
Text headline = getText(displayString);
headline.setFontSize(Text.FONT_SIZE_14_HTML_4);
headline.setFontColor("#0E2456");
if (image != null) {
image.setHorizontalSpacing(5);
titleTable.add(image, 1, 1);
}
titleTable.add(headline, 1, 1);
titleTable.add(new HorizontalRule("100%", 2, "color: #FF9310", true), 1, 2);
return titleTable;
}
public static Table getTitleTable(String displayString) {
return getTitleTable(displayString, null);
}
public static Table getTitleTable(Class classToUse, Image image) {
return getTitleTable(classToUse.getName().substring(classToUse.getName().lastIndexOf(".") + 1), image);
}
public static Table getTitleTable(Class classToUse) {
return getTitleTable(classToUse, null);
}
public static Text getText(String text) {
Text T = new Text(text);
T.setBold();
T.setFontFace(Text.FONT_FACE_VERDANA);
T.setFontSize(Text.FONT_SIZE_10_HTML_2);
return T;
}
}
| idega/platform2 | src/com/idega/development/presentation/IWDeveloper.java | Java | gpl-3.0 | 5,611 |
package itaf.WsCartItemService;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>bzCollectionOrderDto complex typeµÄ Java Àà¡£
*
* <p>ÒÔÏÂģʽƬ¶ÎÖ¸¶¨°üº¬ÔÚ´ËÀàÖеÄÔ¤ÆÚÄÚÈÝ¡£
*
* <pre>
* <complexType name="bzCollectionOrderDto">
* <complexContent>
* <extension base="{itaf.framework.ws.server.cart}operateDto">
* <sequence>
* <element name="bzDistributionOrderDto" type="{itaf.framework.ws.server.cart}bzDistributionOrderDto" minOccurs="0"/>
* <element name="receivableAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="actualAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="distributionAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "bzCollectionOrderDto", propOrder = {
"bzDistributionOrderDto",
"receivableAmount",
"actualAmount",
"distributionAmount"
})
public class BzCollectionOrderDto
extends OperateDto
{
protected BzDistributionOrderDto bzDistributionOrderDto;
protected BigDecimal receivableAmount;
protected BigDecimal actualAmount;
protected BigDecimal distributionAmount;
/**
* »ñÈ¡bzDistributionOrderDtoÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BzDistributionOrderDto }
*
*/
public BzDistributionOrderDto getBzDistributionOrderDto() {
return bzDistributionOrderDto;
}
/**
* ÉèÖÃbzDistributionOrderDtoÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BzDistributionOrderDto }
*
*/
public void setBzDistributionOrderDto(BzDistributionOrderDto value) {
this.bzDistributionOrderDto = value;
}
/**
* »ñÈ¡receivableAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getReceivableAmount() {
return receivableAmount;
}
/**
* ÉèÖÃreceivableAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setReceivableAmount(BigDecimal value) {
this.receivableAmount = value;
}
/**
* »ñÈ¡actualAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getActualAmount() {
return actualAmount;
}
/**
* ÉèÖÃactualAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setActualAmount(BigDecimal value) {
this.actualAmount = value;
}
/**
* »ñÈ¡distributionAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getDistributionAmount() {
return distributionAmount;
}
/**
* ÉèÖÃdistributionAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setDistributionAmount(BigDecimal value) {
this.distributionAmount = value;
}
}
| zpxocivuby/freetong_mobile_server | itaf-aggregator/itaf-ws-simulator/src/test/java/itaf/WsCartItemService/BzCollectionOrderDto.java | Java | gpl-3.0 | 3,557 |
# -*- coding: utf8 -*-
SQL = """select SQL_CALC_FOUND_ROWS * FROM doc_view order by `name` asc limit %(offset)d,%(limit)d ;"""
FOUND_ROWS = True
ROOT = "doc_view_list"
ROOT_PREFIX = "<doc_view_edit />"
ROOT_POSTFIX= None
XSL_TEMPLATE = "data/af-web.xsl"
EVENT = None
WHERE = ()
PARAM = None
TITLE="Список видов документов"
MESSAGE="ошибка получения списка видов документов"
ORDER = None
| ffsdmad/af-web | cgi-bin/plugins2/doc_view_list.py | Python | gpl-3.0 | 444 |
/*
* Copyright 2018 Mauricio Colli <mauriciocolli@outlook.com>
* AnimationUtils.java is part of NewPipe
*
* License: GPL-3.0+
* 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.schabi.newpipe.util;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.res.ColorStateList;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.FloatRange;
import androidx.core.view.ViewCompat;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import org.schabi.newpipe.MainActivity;
public final class AnimationUtils {
private static final String TAG = "AnimationUtils";
private static final boolean DEBUG = MainActivity.DEBUG;
private AnimationUtils() { }
public static void animateView(final View view, final boolean enterOrExit,
final long duration) {
animateView(view, Type.ALPHA, enterOrExit, duration, 0, null);
}
public static void animateView(final View view, final boolean enterOrExit,
final long duration, final long delay) {
animateView(view, Type.ALPHA, enterOrExit, duration, delay, null);
}
public static void animateView(final View view, final boolean enterOrExit, final long duration,
final long delay, final Runnable execOnEnd) {
animateView(view, Type.ALPHA, enterOrExit, duration, delay, execOnEnd);
}
public static void animateView(final View view, final Type animationType,
final boolean enterOrExit, final long duration) {
animateView(view, animationType, enterOrExit, duration, 0, null);
}
public static void animateView(final View view, final Type animationType,
final boolean enterOrExit, final long duration,
final long delay) {
animateView(view, animationType, enterOrExit, duration, delay, null);
}
/**
* Animate the view.
*
* @param view view that will be animated
* @param animationType {@link Type} of the animation
* @param enterOrExit true to enter, false to exit
* @param duration how long the animation will take, in milliseconds
* @param delay how long the animation will wait to start, in milliseconds
* @param execOnEnd runnable that will be executed when the animation ends
*/
public static void animateView(final View view, final Type animationType,
final boolean enterOrExit, final long duration,
final long delay, final Runnable execOnEnd) {
if (DEBUG) {
String id;
try {
id = view.getResources().getResourceEntryName(view.getId());
} catch (final Exception e) {
id = view.getId() + "";
}
final String msg = String.format("%8s → [%s:%s] [%s %s:%s] execOnEnd=%s", enterOrExit,
view.getClass().getSimpleName(), id, animationType, duration, delay, execOnEnd);
Log.d(TAG, "animateView()" + msg);
}
if (view.getVisibility() == View.VISIBLE && enterOrExit) {
if (DEBUG) {
Log.d(TAG, "animateView() view was already visible > view = [" + view + "]");
}
view.animate().setListener(null).cancel();
view.setVisibility(View.VISIBLE);
view.setAlpha(1f);
if (execOnEnd != null) {
execOnEnd.run();
}
return;
} else if ((view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE)
&& !enterOrExit) {
if (DEBUG) {
Log.d(TAG, "animateView() view was already gone > view = [" + view + "]");
}
view.animate().setListener(null).cancel();
view.setVisibility(View.GONE);
view.setAlpha(0f);
if (execOnEnd != null) {
execOnEnd.run();
}
return;
}
view.animate().setListener(null).cancel();
view.setVisibility(View.VISIBLE);
switch (animationType) {
case ALPHA:
animateAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
case SCALE_AND_ALPHA:
animateScaleAndAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
case LIGHT_SCALE_AND_ALPHA:
animateLightScaleAndAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
case SLIDE_AND_ALPHA:
animateSlideAndAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
case LIGHT_SLIDE_AND_ALPHA:
animateLightSlideAndAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
}
}
/**
* Animate the background color of a view.
*
* @param view the view to animate
* @param duration the duration of the animation
* @param colorStart the background color to start with
* @param colorEnd the background color to end with
*/
public static void animateBackgroundColor(final View view, final long duration,
@ColorInt final int colorStart,
@ColorInt final int colorEnd) {
if (DEBUG) {
Log.d(TAG, "animateBackgroundColor() called with: "
+ "view = [" + view + "], duration = [" + duration + "], "
+ "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]");
}
final int[][] empty = {new int[0]};
final ValueAnimator viewPropertyAnimator = ValueAnimator
.ofObject(new ArgbEvaluator(), colorStart, colorEnd);
viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator());
viewPropertyAnimator.setDuration(duration);
viewPropertyAnimator.addUpdateListener(animation ->
ViewCompat.setBackgroundTintList(view,
new ColorStateList(empty, new int[]{(int) animation.getAnimatedValue()})));
viewPropertyAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
ViewCompat.setBackgroundTintList(view,
new ColorStateList(empty, new int[]{colorEnd}));
}
@Override
public void onAnimationCancel(final Animator animation) {
onAnimationEnd(animation);
}
});
viewPropertyAnimator.start();
}
/**
* Animate the text color of any view that extends {@link TextView} (Buttons, EditText...).
*
* @param view the text view to animate
* @param duration the duration of the animation
* @param colorStart the text color to start with
* @param colorEnd the text color to end with
*/
public static void animateTextColor(final TextView view, final long duration,
@ColorInt final int colorStart,
@ColorInt final int colorEnd) {
if (DEBUG) {
Log.d(TAG, "animateTextColor() called with: "
+ "view = [" + view + "], duration = [" + duration + "], "
+ "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]");
}
final ValueAnimator viewPropertyAnimator = ValueAnimator
.ofObject(new ArgbEvaluator(), colorStart, colorEnd);
viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator());
viewPropertyAnimator.setDuration(duration);
viewPropertyAnimator.addUpdateListener(animation ->
view.setTextColor((int) animation.getAnimatedValue()));
viewPropertyAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setTextColor(colorEnd);
}
@Override
public void onAnimationCancel(final Animator animation) {
view.setTextColor(colorEnd);
}
});
viewPropertyAnimator.start();
}
public static ValueAnimator animateHeight(final View view, final long duration,
final int targetHeight) {
final int height = view.getHeight();
if (DEBUG) {
Log.d(TAG, "animateHeight: duration = [" + duration + "], "
+ "from " + height + " to → " + targetHeight + " in: " + view);
}
final ValueAnimator animator = ValueAnimator.ofFloat(height, targetHeight);
animator.setInterpolator(new FastOutSlowInInterpolator());
animator.setDuration(duration);
animator.addUpdateListener(animation -> {
final float value = (float) animation.getAnimatedValue();
view.getLayoutParams().height = (int) value;
view.requestLayout();
});
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.getLayoutParams().height = targetHeight;
view.requestLayout();
}
@Override
public void onAnimationCancel(final Animator animation) {
view.getLayoutParams().height = targetHeight;
view.requestLayout();
}
});
animator.start();
return animator;
}
public static void animateRotation(final View view, final long duration,
final int targetRotation) {
if (DEBUG) {
Log.d(TAG, "animateRotation: duration = [" + duration + "], "
+ "from " + view.getRotation() + " to → " + targetRotation + " in: " + view);
}
view.animate().setListener(null).cancel();
view.animate()
.rotation(targetRotation).setDuration(duration)
.setInterpolator(new FastOutSlowInInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(final Animator animation) {
view.setRotation(targetRotation);
}
@Override
public void onAnimationEnd(final Animator animation) {
view.setRotation(targetRotation);
}
}).start();
}
private static void animateAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.animate().setInterpolator(new FastOutSlowInInterpolator()).alpha(1f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.animate().setInterpolator(new FastOutSlowInInterpolator()).alpha(0f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
/*//////////////////////////////////////////////////////////////////////////
// Internals
//////////////////////////////////////////////////////////////////////////*/
private static void animateScaleAndAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.setScaleX(.8f);
view.setScaleY(.8f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(1f).scaleX(1f).scaleY(1f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.setScaleX(1f);
view.setScaleY(1f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(0f).scaleX(.8f).scaleY(.8f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
private static void animateLightScaleAndAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.setAlpha(.5f);
view.setScaleX(.95f);
view.setScaleY(.95f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(1f).scaleX(1f).scaleY(1f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.setAlpha(1f);
view.setScaleX(1f);
view.setScaleY(1f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(0f).scaleX(.95f).scaleY(.95f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
private static void animateSlideAndAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.setTranslationY(-view.getHeight());
view.setAlpha(0f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator()).alpha(1f).translationY(0)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(0f).translationY(-view.getHeight())
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
private static void animateLightSlideAndAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.setTranslationY(-view.getHeight() / 2.0f);
view.setAlpha(0f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator()).alpha(1f).translationY(0)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.animate().setInterpolator(new FastOutSlowInInterpolator())
.alpha(0f).translationY(-view.getHeight() / 2.0f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
public static void slideUp(final View view, final long duration, final long delay,
@FloatRange(from = 0.0f, to = 1.0f)
final float translationPercent) {
final int translationY = (int) (view.getResources().getDisplayMetrics().heightPixels
* (translationPercent));
view.animate().setListener(null).cancel();
view.setAlpha(0f);
view.setTranslationY(translationY);
view.setVisibility(View.VISIBLE);
view.animate()
.alpha(1f)
.translationY(0)
.setStartDelay(delay)
.setDuration(duration)
.setInterpolator(new FastOutSlowInInterpolator())
.start();
}
public enum Type {
ALPHA,
SCALE_AND_ALPHA, LIGHT_SCALE_AND_ALPHA,
SLIDE_AND_ALPHA, LIGHT_SLIDE_AND_ALPHA
}
}
| theScrabi/NewPipe | app/src/main/java/org/schabi/newpipe/util/AnimationUtils.java | Java | gpl-3.0 | 20,120 |
import {Component, OnInit} from '@angular/core';
import {EvaluationService} from '../service/evaluation.service';
@Component({
selector: 'app-evaluation',
templateUrl: './evaluation.component.html',
styleUrls: ['./evaluation.component.css']
})
export class EvaluationComponent implements OnInit {
public result: number[];
private quadrantWith = 200;
constructor(public evaluationService: EvaluationService) {
}
ngOnInit() {
this.result = this.evaluationService.evaluate();
}
calc(points: number): number {
const value = 1 / 30 * (points - 10) * this.quadrantWith
return (value < 0) ? 0 : value;
}
}
| david-0/disg | src/app/evaluation/evaluation.component.ts | TypeScript | gpl-3.0 | 638 |
#include "session.h"
// This file is part of MCI_Host.
// MCI_Host 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.
// MCI_Host 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 MCI_Host under the LICENSE.md file. If not, see
// <http://www.gnu.org/licenses/>.
Session::Session(uint sesId, qintptr newPtr, QObject *parent) : QTcpSocket(0)
{
timer = new QTimer();
bits = 0;
flags = 0;
dSize = 0;
sessionId = 0;
slotId = 0;
baseSlot = 0;
rdHash = 0;
wrHash = 0;
cmdListMode = 0;
cmdListCaseSensitive = false;
cmdListenabled = false;
keyOk = false;
verOk = false;
onBaseSlot = false;
timer->setSingleShot(true);
timer->setInterval(6000);
// the timer object provides a 6sec timeout for the client to send the
// header before the session is forced closed.
connect(this, SIGNAL(readyRead()), this, SLOT(dataFromClient()));
connect(this, SIGNAL(destroyed()), timer, SLOT(deleteLater()));
connect(timer, SIGNAL(timeout()), this, SLOT(sessionTimeout()));
connect(parent, SIGNAL(destroyed()), this, SLOT(deleteLater()));
setSocketDescriptor(newPtr);
if (inBanList(peerAddress().toString()))
{
// any session that still has a session id of zero after running the
// contructor is considered a blocked ip so the session will get killed
// externally at Server::incomingConnection().
sessionEnding = true;
addIpAction(tr("IP address blocked"), peerAddress().toString());
}
else
{
// Session represents the TCP connection with the client. it provides the
// xOR encryption, version negotiation and an interface for CmdHub objects.
// it starts in it's own thread from within the contructor and kills
// itself when the client disconnects but does not kill the CmdHub it's
// currently connected to.
addIpAction(tr("Connected, assigned session id: ") + QString::number(sesId), peerAddress().toString());
sessionEnding = false;
sessionId = sesId;
QThread *thr = new QThread();
connect(thr, SIGNAL(finished()), thr, SLOT(deleteLater()));
connect(thr, SIGNAL(started()), timer, SLOT(start()));
connect(this, SIGNAL(destroyed()), thr, SLOT(quit()));
connect(this, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
timer->moveToThread(thr);
moveToThread(thr);
thr->start();
}
}
bool Session::loadProfile(const QString &proName, QByteArray &key)
{
// this function runs 3 database queries to read the following profile
// data:
// keyHash - this is used in the Hash object to setup encryption.
// groupName - this indicates what group the profile belongs to.
// the group can contain host privileges that profile
// is allowed to do.
// cmdListCaseSensitive - indicates if the profileCmdList is casesSensitive.
// cmdListenabled - indicates if the profileCmdList is enabled.
// cmdListMode - indicates what the profileCmdList does when the
// sent in command line is matched.
// baseSlot - this indicates the fallback slot in cases when the
// the slot the session is currently connected is
// killed.
// profileCmdList - this is the group command line list that is used
// allowed or disallow certain commands depending
// on what is loaded into cmdListMode or
// cmdListCaseSensitive.
bool ret = false;
Query db(this);
db.setType(Query::PULL, TABLE_PROFILES);
db.addColumn(COLUMN_PRONAME);
db.addColumn(COLUMN_PROKEY);
db.addColumn(COLUMN_GRNAME);
db.addCondition(COLUMN_PRONAME, proName);
db.exec();
if (db.rows())
{
ret = true;
profileName = db.getData(COLUMN_PRONAME).toString();
groupName = db.getData(COLUMN_GRNAME).toString();
key = db.getData(COLUMN_PROKEY).toByteArray();
db.setType(Query::PULL, TABLE_GROUPS);
db.addColumn(COLUMN_CS);
db.addColumn(COLUMN_LS_MODE);
db.addColumn(COLUMN_LS_STATE);
db.addColumn(COLUMN_BASE_SL);
db.addCondition(COLUMN_GRNAME, groupName);
db.exec();
cmdListCaseSensitive = db.getData(COLUMN_CS).toBool();
cmdListenabled = db.getData(COLUMN_LS_STATE).toBool();
cmdListMode = db.getData(COLUMN_LS_MODE).toUInt();
baseSlot = db.getData(COLUMN_BASE_SL).toUInt();
profileCmdList.clear();
db.setType(Query::PULL, TABLE_CMD_LIST);
db.addColumn(COLUMN_CMD_LINE);
db.addCondition(COLUMN_GRNAME, groupName);
db.exec();
for (int i = 0; i < db.rows(); ++i)
{
profileCmdList.append(db.getData(COLUMN_CMD_LINE, i).toString());
}
}
return ret;
}
bool Session::inBanList(const QString &ip)
{
// simple database select query with the provided ip address in the where
// clause. if a row is found, that indicates that the ip address is in
// the ban list.
Query db(this);
db.setType(Query::PULL, TABLE_IPBANS);
db.addColumn(COLUMN_IPADDR);
db.addCondition(COLUMN_IPADDR, ip);
db.exec();
return db.rows();
}
void Session::addIpAction(const QString &action, const QString &ip)
{
// insert database query for the ip address action log (ip_hist).
Query db(this);
db.setType(Query::PUSH, TABLE_IPHIST);
db.addColumn(COLUMN_IPADDR, ip);
db.addColumn(COLUMN_LOGENTRY, action);
db.exec();
}
uint Session::id()
{
return sessionId;
}
void Session::slotClosed()
{
// this function is connected to CmdHub::destroyed() as a way to catch if the currently
// connected command interperter has been killed. command interperters (CmdHub) running in the
// background are considered slots in this application so when a command interperter dies, its
// the same as a slot getting closed so the session will attempt to re-create or re-attach to
// the base slot defined in the profile when this happens. this behavior should not be allowed
// if the session is closing so sessionEnding is checked.
if (!sessionEnding)
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<300> Slot id: ") + QString::number(slotId) + tr(" was killed. falling back to slot id: ") + QString::number(baseSlot) + tr("."));
emit createSlot(sessionId, 0, baseSlot);
}
}
void Session::groupBaseSlotChanged(const QString &grpName, uint id)
{
if (grpName.toLower() == groupName.toLower())
{
if (onBaseSlot)
{
// force the session to create or attach to the new base slot if currently connected
// to the old base slot.
emit createSlot(sessionId, baseSlot, id);
}
baseSlot = id;
}
}
void Session::groupCmdListChanged(const QString &grpName, const QStringList &ls)
{
if (grpName.toLower() == groupName.toLower())
{
profileCmdList = ls;
}
}
void Session::groupCSListChanged(const QString &grpName, bool cs)
{
if (grpName.toLower() == groupName.toLower())
{
cmdListCaseSensitive = cs;
}
}
void Session::groupEnabledListChanged(const QString &grpName, bool state)
{
if (grpName.toLower() == groupName.toLower())
{
cmdListenabled = state;
}
}
void Session::groupCmdLsModeChanged(const QString &grpName, uint mode)
{
if (grpName.toLower() == groupName.toLower())
{
cmdListMode = mode;
}
}
void Session::profileGroupChanged(const QString &proName)
{
if (profileName.toLower() == proName.toLower())
{
QByteArray unused;
loadProfile(profileName, unused);
groupBaseSlotChanged(groupName, baseSlot);
}
}
void Session::profileNameChanged(const QString &oldName, const QString &newName)
{
if (profileName.toLower() == oldName.toLower())
{
profileName = newName;
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<301> Your current profile name was changed to: ") + newName);
}
}
void Session::groupRenamed(const QString &oldName, const QString &newName)
{
if (groupName.toLower() == oldName.toLower())
{
groupName = newName;
}
}
void Session::profileDeleted(const QString &proName)
{
if (profileName.toLower() == proName.toLower())
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<302> Your current profile got deleted, ending this session."));
sessionEnding = true;
emit deleteSession(sessionId);
}
}
void Session::sessionSlotChanged(uint sesId, uint slId)
{
// this should be connected to the Server object's sessionSlotChanged() signal to help this
// object keep track of the slotId it is currently connected to.
if (sesId == sessionId)
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<201> Connected to slot id: ") + QString::number(slId) + tr("."));
slotId = slId;
onBaseSlot = (slotId == baseSlot);
}
}
void Session::clientDisconnected()
{
addIpAction(tr("Disconnected"), peerAddress().toString());
if (!sessionEnding)
{
sessionEnding = true;
emit deleteSession(sessionId);
}
}
void Session::sessionTimeout()
{
sessionEnding = true;
emit deleteSession(sessionId);
}
void Session::requestedToClose(uint sesId)
{
if (sesId == 0)
{
sessionEnding = true;
emit deleteSession(sessionId);
}
else if (sesId == sessionId)
{
emit okToDelete(sesId);
close();
}
}
void Session::dataToClient(const QByteArray &data, uint exclude, uchar flgs)
{
if (keyOk && (exclude != sessionId))
{
// data format: [num_of_bits][flags][data_size][data]
// it's very important that the data is sent in this format and encrypted to avoid
// undefined behavior.
QByteArray lenBa = wrInt(data.size());
QByteArray flagsBa = QByteArray(1, flgs);
QByteArray bitsBa = QByteArray(1, (uchar) lenBa.size() * 8);
write(wrHash->xOR(Hash::ENCODE, bitsBa + flagsBa + lenBa + data));
}
}
void Session::textFromCmd(uint sesId, bool cr, const QString &line)
{
QTextCodec *codec = QTextCodec::codecForName("UTF-16LE");
if (cr) dataToClient(codec->fromUnicode(line), 0, TEXT_CH);
else dataToClient(codec->fromUnicode(line), sesId, TEXT_CH);
}
void Session::textFromServer(uint sesId, const QString &line)
{
if ((sesId == sessionId) || (sesId == 0))
{
textFromCmd(sessionId, true, line);
}
}
void Session::binFromCmd(uint sesId, bool cr, bool priv, const QByteArray &bin)
{
if (priv)
{
if (sesId == sessionId)
{
dataToClient(bin, 0, BIN_CH);
}
}
else
{
if (cr) dataToClient(bin, 0, BIN_CH);
else dataToClient(bin, sesId, BIN_CH);
}
}
void Session::dataFilter(const QByteArray &data, uchar flgs)
{
// this take the decrypted data from dataFromClient() and converts it to a
// QString if the flgs TEXT_CH is present or reads the command name from
// the raw data if BIN_CH is present. the the command name or full command
// line is then checked with profileAllowedCmd() at this point.
QString line;
if (flgs & TEXT_CH)
{
line = QTextCodec::codecForName("UTF-16LE")->toUnicode(data);
if (profileAllowedCmd(line))
{
emit textToCmd(sessionId, &profileName, line);
}
}
else if (flgs & BIN_CH)
{
if (activeHook)
{
emit binToCmd(sessionId, &profileName, data);
}
else
{
bool found = false;
for (int i = 0; i < data.size(); i += 2)
{
QByteArray chrPair(data.mid(i, 2));
if (chrPair.size() == 2)
{
if ((chrPair[0] == (char) 0) && (chrPair[1] == (char) 0))
{
line = QTextCodec::codecForName("UTF-16LE")->toUnicode(data.left(i));
if (profileAllowedCmd(line))
{
emit binToCmd(sessionId, &profileName, data);
}
found = true;
break;
}
}
}
if (!found)
{
textFromCmd(sessionId, true, tr("<105> Call to binary command has no terminator."));
}
}
}
}
void Session::setHookState(bool state)
{
// this is used in Server::attach() to make this class aware of the
// hook state of the currently connected CmdHub.
activeHook = state;
}
bool Session::profileAllowedCmd(const QString &line)
{
// this take in the sent in command line from the client and attempts
// the match it with the patterns defined in the profileCmdList if the
// list is enabled. empty lines are allowed no matter what.
bool ret = true;
// command filtering need to be completely bypassed if there is an
// active hook on the currently attached CmdHub.
if (!activeHook)
{
if (cmdListenabled && !line.isEmpty())
{
bool matched = false;
for (int i = 0; (i < profileCmdList.size()) && !matched; ++i)
{
QRegExp regEx(profileCmdList[i]);
regEx.setPatternSyntax(QRegExp::Wildcard);
if (cmdListCaseSensitive) regEx.setCaseSensitivity(Qt::CaseSensitive);
else regEx.setCaseSensitivity(Qt::CaseInsensitive);
matched = regEx.exactMatch(line);
}
// matched == true at this point indicate that a pattern was found
// of cmdListMode is checked to determine if the command should be
// allowed to run or not.
if (matched && (cmdListMode == CMD_LINES_DISALLOWED_TO_RUN))
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<108> Command rejected by the host."));
ret = false;
}
else if (!matched && (cmdListMode == CMD_LINES_ALLOWED_TO_RUN))
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<108> Command rejected by the host."));
ret = false;
}
else if (matched && (cmdListMode != CMD_LINES_ALLOWED_TO_RUN))
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<108> host bug! - command list mode not recognized. mode: ") + QString::number(cmdListMode));
ret = false;
}
}
}
return ret;
}
void Session::dataFromClient()
{
if (keyOk && !sessionEnding)
{
if (dSize) //stage 5
{
if (bytesAvailable() >= dSize)
{
dataFilter(rdHash->xOR(Hash::DECODE, read(dSize)), flags);
dSize = 0;
bits = 0;
flags = 0;
dataFromClient();
}
}
else if (bits) //stage 4
{
if (bytesAvailable() >= bits / 8)
{
dSize = rdInt(rdHash->xOR(Hash::DECODE, read(bits / 8)));
if (dSize)
{
dataFromClient();
}
else if (flags & TEXT_CH)
{
// 0 on dSize at this point assumes empty text was sent to the
// host so this code will actually locally create empty text
// and send it through dataFilter().
dataFilter(QTextCodec::codecForName("UTF-16LE")->fromUnicode(tr("")), flags);
flags = 0;
bits = 0;
}
else
{
// just like above, this will locally create an empty QByteArray()
// to send through dataFilter().
dataFilter(QByteArray(), flags);
flags = 0;
bits = 0;
}
}
}
else if (bytesAvailable() >= 2) //stage 3
{
QByteArray data = rdHash->xOR(Hash::DECODE, read(2));
bits = (uchar) data[0];
flags = (uchar) data[1];
if ((bits > MAX_BITS) || (bits < 8))
{
bits = 0;
flags = 0;
addIpAction(tr("Out-of-sync event (int bits over maximum or < 8)"), peerAddress().toString());
// the client will must likely end up de-synced with the server
// at this point. the best way to recover will be to re-start
// a new session. (disconnect-reconnect)
}
else
{
dataFromClient();
}
}
}
else if (verOk) //stage 2
{
// SHA3-512 == 64 bytes.
if (bytesAvailable() >= 64)
{
if (rdHash->passHash() == rdHash->xOR(Hash::DECODE, read(64)))
{
// numeric value 1 indicates that the passHash matches with
// the host and will unlock stage 3-5 until the session closes.
// a successful match also resets the ban increment.
keyOk = true;
write(wrInt(1, 8));
waitForBytesWritten();
emit createSlot(sessionId, 0, baseSlot);
emit clearIPBanCount(peerAddress().toString());
}
else
{
// numeric value 2 indicates that the passHash sent in from the
// client is invalid. clients are free to make more attempts at this
// stage but keep in mind that the ban increment will only grow with
// each failed attempt.
addIpAction(tr("Client passHash missmatch"), peerAddress().toString());
write(wrInt(2, 8));
emit incrementIPBan(sessionId, peerAddress().toString());
}
}
}
else
{
if ((bytesAvailable() >= CLIENT_HEADER_LEN) && !sessionEnding) //stage 1
{
// client header format: [3bytes(tag)][2bytes(major)][2bytes(minor)][2bytes(patch)][58bytes(profile)]
// tag = 0x4D, 0x43, 0x49 (MCI)
// major = 16bit little endian int
// minor = 16bit little endian int
// patch = 16bit little endian int
// profile = UTF-16LE string (padded with white spaces to fill 29 max chars)
// note: profile names in this app are case insensitive.
timer->stop();
if (read(3) == QByteArray(SERVER_HEADER_TAG))
{
clientMajor = rdInt(read(2));
clientMinor = rdInt(read(2));
clientPatch = rdInt(read(2));
QByteArray servHeader;
QByteArray reply;
QByteArray key;
QByteArray proName = read(60);
addIpAction(tr("Client version: ") + QString::number(clientMajor) + "."
+ QString::number(clientMinor) + "."
+ QString::number(clientPatch), peerAddress().toString());
if ((clientMajor >= 1) && (clientMinor > 0))
{
QString proStr = QTextCodec::codecForName("UTF-16LE")->toUnicode(proName).trimmed();
addIpAction(tr("Profile name: ") + proStr, peerAddress().toString());
if (loadProfile(proStr, key))
{
reply = wrInt(1, 8);
verOk = true;
addIpAction(tr("Client version and profile ok"), peerAddress().toString());
}
else
{
reply = wrInt(2, 8);
addIpAction(tr("Profile not found"), peerAddress().toString());
}
}
else
{
reply = wrInt(3, 8);
addIpAction(tr("Client version rejected"), peerAddress().toString());
}
QStringList ver = QApplication::applicationVersion().split('.');
servHeader.append(reply);
servHeader.append(wrInt(ver[0].toShort(), 16));
servHeader.append(wrInt(ver[1].toShort(), 16));
servHeader.append(wrInt(ver[2].toShort(), 16));
if (verOk)
{
rdHash = new Hash(key + TO_SERV_SALT, sessionId, this);
wrHash = new Hash(key + FROM_SERV_SALT, sessionId, this);
servHeader.append(rdHash->seqBytes());
servHeader.append(wrHash->seqBytes());
servHeader.append(rdHash->sessionIdBytes());
if (servHeader.size() != SERVER_HEADER_LEN)
{
addIpAction(tr("Host bug! - header len != ") + QString::number(SERVER_HEADER_LEN), peerAddress().toString());
}
write(servHeader);
}
else
{
servHeader.append(QByteArray(NUM_OF_SEQ + 4, 0));
write(servHeader);
waitForBytesWritten();
sessionEnding = true;
emit deleteSession(sessionId);
}
}
else
{
addIpAction(tr("Invalid tag"), peerAddress().toString());
sessionEnding = true;
emit deleteSession(sessionId);
}
}
}
}
| Zi-i/MCI_Host | src/session.cpp | C++ | gpl-3.0 | 23,063 |
class UsersController < ApplicationController
def index
users = User.all
render json: users
end
end
| ShawnTe/daily-planner-rails-api | app/controllers/users_controller.rb | Ruby | gpl-3.0 | 112 |
export * from './results.handler';
| olimungo/planning-poker | src/pages/common/handlers/results-handler/index.ts | TypeScript | gpl-3.0 | 35 |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Kontract.IO;
namespace Kontract.Compression
{
public class LZSSVLE
{
public static byte[] Decompress(Stream input, bool leaveOpen = false)
{
using (var br = new BinaryReader(input, Encoding.Default, leaveOpen))
{
Tuple<int, int> GetNibbles(byte b) => new Tuple<int, int>(b >> 4, b & 0xF);
int ReadVLC(int seed = 0)
{
while (true)
{
var b = br.ReadByte();
seed = (seed << 7) | (b / 2);
if (b % 2 != 0) return seed;
}
}
var filesize = ReadVLC();
var unk1 = ReadVLC(); // filetype maybe???
var unk2 = ReadVLC(); // compression type = 1 (LZSS?)
var buffer = new List<byte>();
while (buffer.Count < filesize)
{
// literal
var copiesSize = GetNibbles(br.ReadByte());
var copies = copiesSize.Item1;
var size = copiesSize.Item2;
if (size == 0) size = ReadVLC();
if (copies == 0) copies = ReadVLC();
buffer.AddRange(br.ReadBytes(size));
// copy stuff
while (copies-- > 0)
{
var lengthOffset = GetNibbles(br.ReadByte());
var length = lengthOffset.Item1;
var offset = lengthOffset.Item2;
if (offset % 2 == 0) offset = ReadVLC(offset / 2) * 2;
else offset >>= 1;
if (length == 0) length = ReadVLC(length);
while (length-- >= 0) buffer.Add(buffer[buffer.Count - offset / 2 - 1]);
}
}
return buffer.ToArray();
}
}
}
}
| IcySon55/Kuriimu | src/Kontract/Compression/LZSSVLE.cs | C# | gpl-3.0 | 2,086 |
<? if($this->uri->segment(3,'add') == 'add'): ?>
<h2>Create user</h2>
<? else: ?>
<h2>Edit user "<?= $member->full_name; ?>"</h2>
<? endif; ?>
<?=form_open($this->uri->uri_string()); ?>
<fieldset>
<legend>Details</legend>
<div class="field">
<label for="first_name">First Name</label>
<?= form_input('first_name', $member->first_name, 'class="text"'); ?>
</div>
<div class="field">
<label for="first_name">Surname</label>
<?= form_input('last_name', $member->last_name, 'class="text"'); ?>
</div>
<div class="field">
<label for="email">E-mail</label>
<?= form_input('email', $member->email, 'class="text"'); ?>
</div>
<div class="field">
<label for="active">Activate</label>
<?= form_checkbox('is_active', 1, $member->is_active == 1); ?>
</div>
</fieldset>
<fieldset>
<legend>Password</legend>
<div class="field">
<label for="password">Password</label>
<?= form_password('password', '', 'class="text"'); ?>
</div>
<div class="field">
<label for="confirm_password">Confirm Password</label>
<?= form_password('confirm_password', '', 'class="text"'); ?>
</div>
</fieldset>
<? $this->load->view('admin/layout_fragments/table_buttons', array('buttons' => array('save', 'cancel') )); ?>
<?=form_close(); ?> | bema2004sw/pyrocms | application/modules/users/views/admin/form.php | PHP | gpl-3.0 | 1,262 |
#include <vigir_footstep_planning_plugins/plugin_aggregators/world_model.h>
namespace vigir_footstep_planning
{
WorldModel::WorldModel()
: ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>("WorldModel")
{
}
void WorldModel::loadPlugins(bool print_warning)
{
ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::loadPlugins(print_warning);
// get terrain model
vigir_pluginlib::PluginManager::getPlugin(terrain_model_);
if (terrain_model_)
{
ROS_INFO("[WorldModel] Found terrain model:");
ROS_INFO(" %s (%s)", terrain_model_->getName().c_str(), terrain_model_->getTypeClass().c_str());
}
}
bool WorldModel::loadParams(const vigir_generic_params::ParameterSet& params)
{
bool result = ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::loadParams(params);
if (terrain_model_)
result &= terrain_model_->loadParams(params);
return result;
}
void WorldModel::resetPlugins()
{
ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::resetPlugins();
if (terrain_model_)
terrain_model_->reset();
}
bool WorldModel::isAccessible(const State& s) const
{
for (CollisionCheckPlugin::Ptr plugin : getPlugins())
{
if (plugin && plugin->isCollisionCheckAvailable() && !plugin->isAccessible(s))
return false;
}
return true;
}
bool WorldModel::isAccessible(const State& next, const State& current) const
{
for (CollisionCheckPlugin::Ptr plugin : getPlugins())
{
if (plugin && plugin->isCollisionCheckAvailable() && !plugin->isAccessible(next, current))
return false;
}
return true;
}
void WorldModel::useTerrainModel(bool enabled)
{
use_terrain_model_ = enabled;
}
bool WorldModel::isTerrainModelAvailable() const
{
return terrain_model_ && terrain_model_->isTerrainModelAvailable();
}
TerrainModelPlugin::ConstPtr WorldModel::getTerrainModel() const
{
return terrain_model_;
}
bool WorldModel::getHeight(double x, double y, double& height) const
{
if (!use_terrain_model_ || !isTerrainModelAvailable())
return true;
return terrain_model_->getHeight(x, y, height);
}
bool WorldModel::update3DData(State& s) const
{
if (!use_terrain_model_ || !isTerrainModelAvailable())
return true;
return terrain_model_->update3DData(s);
}
}
| team-vigir/vigir_footstep_planning_basics | vigir_footstep_planning_plugins/src/plugin_aggregators/world_model.cpp | C++ | gpl-3.0 | 2,257 |
# -*- encoding: utf-8 -*-
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import logging
from openerp.osv import osv, fields
_logger = logging.getLogger(__name__)
class res_users(osv.osv):
_inherit = "res.users"
_columns = {
'xis_user_external_id': fields.integer('XIS external user',
required=True),
}
| Xprima-ERP/odoo_addons | xpr_xis_connector/res_users.py | Python | gpl-3.0 | 1,160 |
package com.lizardtech.djvubean.outline;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
public class ImageListCellRenderer implements ListCellRenderer
{
/**
* From <a href="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:" title="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:">http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:</a>
*
* Return a component that has been configured to display the specified value.
* That component's paint method is then called to "render" the cell.
* If it is necessary to compute the dimensions of a list because the list cells do not have a fixed size,
* this method is called to generate a component on which getPreferredSize can be invoked.
*
* jlist - the jlist we're painting
* value - the value returned by list.getModel().getElementAt(index).
* cellIndex - the cell index
* isSelected - true if the specified cell is currently selected
* cellHasFocus - true if the cell has focus
*/
public Component getListCellRendererComponent(JList jlist,
Object value,
int cellIndex,
boolean isSelected,
boolean cellHasFocus)
{
if (value instanceof JPanel)
{
Component component = (Component) value;
component.setForeground (Color.white);
component.setBackground (isSelected ? UIManager.getColor("Table.focusCellForeground") : Color.white);
return component;
}
else
{
// TODO - I get one String here when the JList is first rendered; proper way to deal with this?
//System.out.println("Got something besides a JPanel: " + value.getClass().getCanonicalName());
return new JLabel("???");
}
}} | DJVUpp/Desktop | djuvpp-djvureader-_linux-f9cd57d25c2f/DjVuReader++/src/com/lizardtech/djvubean/outline/ImageListCellRenderer.java | Java | gpl-3.0 | 2,058 |
/*
* Copyright (c) by Michał Niedźwiecki 2016
* Contact: nkg753 on gmail or via GitHub profile: dzwiedziu-nkg
*
* This file is part of Bike Road Quality.
*
* Bike Road Quality 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.
*
* Bike Road Quality 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 Foobar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package pl.nkg.brq.android.ui;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pl.nkg.brq.android.R;
import pl.nkg.brq.android.events.SensorsRecord;
import pl.nkg.brq.android.events.SensorsServiceState;
import pl.nkg.brq.android.services.SensorsService;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSION_RESPONSE = 29;
@Bind(R.id.button_on)
Button mButtonOn;
@Bind(R.id.button_off)
Button mButtonOff;
@Bind(R.id.speedTextView)
TextView mSpeedTextView;
@Bind(R.id.altitudeTextView)
TextView mAltitudeTextView;
@Bind(R.id.shakeTextView)
TextView mShakeTextView;
@Bind(R.id.noiseTextView)
TextView mNoiseTextView;
@Bind(R.id.distanceTextView)
TextView mDistanceTextView;
@Bind(R.id.warningTextView)
TextView mWarningTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Prompt for permissions
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Log.w("BleActivity", "Location access not granted!");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH},
MY_PERMISSION_RESPONSE);
}
}
ButterKnife.bind(this);
}
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
@OnClick(R.id.button_on)
public void onButtonOnClick() {
startService(new Intent(MainActivity.this, SensorsService.class));
}
@OnClick(R.id.button_off)
public void onButtonOffClick() {
stopService(new Intent(MainActivity.this, SensorsService.class));
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(SensorsServiceState state) {
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(SensorsRecord record) {
mSpeedTextView.setText((int) (record.speed * 3.6) + " km/h");
mAltitudeTextView.setText((int) record.altitude + " m n.p.m.");
mShakeTextView.setText((int) (record.shake * 100) / 100.0 + " m/s²");
mNoiseTextView.setText((int) record.soundNoise + " db");
mDistanceTextView.setText((double) record.distance / 100.0 + " m");
if (record.distance < 120 && record.distance != 0) {
mWarningTextView.setVisibility(View.VISIBLE);
mWarningTextView.setText((double) record.distance / 100.0 + " m");
mWarningTextView.setTextSize(Math.min(5000 / record.distance, 100));
} else {
mWarningTextView.setVisibility(View.GONE);
}
}
}
| dzwiedziu-nkg/cyclo-bruxism | proof-of-concept/apk/app/src/main/java/pl/nkg/brq/android/ui/MainActivity.java | Java | gpl-3.0 | 5,333 |
package com.malak.yaim.model;
import java.util.List;
public class FlickrFeed {
private String title;
private String link;
private String description;
private String modified;
private String generator;
private List<Item> items = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getGenerator() {
return generator;
}
public void setGenerator(String generator) {
this.generator = generator;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
} | xavarius/FlickrFeed | app/src/main/java/com/malak/yaim/model/FlickrFeed.java | Java | gpl-3.0 | 1,050 |
"""
Contains format specification class and methods to parse it from JSON.
.. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz>
"""
import json
import re
def get_root_input_type_from_json(data):
"""Return the root input type from JSON formatted string."""
return parse_format(json.loads(data))
def parse_format(data):
"""Returns root input type from data."""
input_types = {}
data = data['ist_nodes']
root_id = data[0]['id'] # set root type
for item in data:
input_type = _get_input_type(item)
if input_type is not None:
input_types[input_type['id']] = input_type # register by id
_substitute_ids_with_references(input_types)
return input_types[root_id]
SCALAR = ['Integer', 'Double', 'Bool', 'String', 'Selection', 'FileName']
def is_scalar(input_type):
"""Returns True if input_type is scalar."""
return input_type['base_type'] in SCALAR
RE_PARAM = re.compile('^<([a-zA-Z][a-zA-Z0-9_]*)>$')
def is_param(value):
"""Determine whether given value is a parameter string."""
if not isinstance(value, str):
return False
return RE_PARAM.match(value)
def _substitute_ids_with_references(input_types):
"""Replaces ids or type names with python object references."""
input_type = {}
def _substitute_implementations():
"""Replaces implementation ids with input_types."""
impls = {}
for id_ in input_type['implementations']:
type_ = input_types[id_]
impls[type_['name']] = type_
input_type['implementations'] = impls
def _substitute_default_descendant():
"""Replaces default descendant id with input_type."""
id_ = input_type.get('default_descendant', None)
if id_ is not None:
input_type['default_descendant'] = input_types[id_]
def _substitute_key_type():
"""Replaces key type with input_type."""
# pylint: disable=unused-variable, invalid-name
for __, value in input_type['keys'].items():
value['type'] = input_types[value['type']]
# pylint: disable=unused-variable, invalid-name
for __, input_type in input_types.items():
if input_type['base_type'] == 'Array':
input_type['subtype'] = input_types[input_type['subtype']]
elif input_type['base_type'] == 'Abstract':
_substitute_implementations()
_substitute_default_descendant()
elif input_type['base_type'] == 'Record':
_substitute_key_type()
def _get_input_type(data):
"""Returns the input_type data structure that defines an input type
and its constraints for validation."""
if 'id' not in data or 'input_type' not in data:
return None
input_type = dict(
id=data['id'],
base_type=data['input_type']
)
input_type['name'] = data.get('name', '')
input_type['full_name'] = data.get('full_name', '')
input_type['description'] = data.get('description', '')
input_type['attributes'] = data.get('attributes', {})
if input_type['base_type'] in ['Double', 'Integer']:
input_type.update(_parse_range(data))
elif input_type['base_type'] == 'Array':
input_type.update(_parse_range(data))
if input_type['min'] < 0:
input_type['min'] = 0
input_type['subtype'] = data['subtype']
elif input_type['base_type'] == 'FileName':
input_type['file_mode'] = data['file_mode']
elif input_type['base_type'] == 'Selection':
input_type['values'] = _list_to_dict(data['values'], 'name')
elif input_type['base_type'] == 'Record':
input_type['keys'] = _list_to_dict(data['keys'])
input_type['implements'] = data.get('implements', [])
input_type['reducible_to_key'] = data.get('reducible_to_key', None)
elif input_type['base_type'] == 'Abstract':
input_type['implementations'] = data['implementations']
input_type['default_descendant'] = data.get('default_descendant', None)
return input_type
def _parse_range(data):
"""Parses the format range properties - min, max."""
input_type = {}
try:
input_type['min'] = data['range'][0]
except (KeyError, TypeError): # set default value
input_type['min'] = float('-inf')
try:
input_type['max'] = data['range'][1]
except (KeyError, TypeError): # set default value
input_type['max'] = float('inf')
return input_type
def _list_to_dict(list_, key_label='key'):
"""
Transforms a list of dictionaries into a dictionary of dictionaries.
Original dictionaries are assigned key specified in each of them
by key_label.
"""
dict_ = {}
for item in list_:
dict_[item[key_label]] = item
return dict_
| GeoMop/GeoMop | src/gm_base/model_data/format.py | Python | gpl-3.0 | 4,784 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
using System.IO;
public class Serializer : MonoBehaviour {
//save defaults are only used to set the data used when initializing that map the next time.
string saveFile;
string loadFile;
string fileName;
public string saveData;
public string defaults;
CharacterControllerScript player;
// Use this for initialization
void Start () {
player = Globals.playerScript;
//save on disc
saveData = Path.Combine(Application.persistentDataPath, "SaveData");
// defaults included in project
defaults = "Assets/Resources/Defaults/";
CreateDirectories();
}
// Update is called once per frame
void Update () {
}
void CreateDirectories()
{
if(!Directory.Exists(saveData))
{
Directory.CreateDirectory(saveData);
}
/*if(!Directory.Exists(defaults))
{
Directory.CreateDirectory(defaults);
}*/
}
public void SavePlayerData()
{
PlayerSaveData playerData = new PlayerSaveData()
{
level = player.level,
statPoints = player.statPoints,
skillPoints = player.skillPoints,
spentStatPoints = player.spentStatPoints,
spentSkillPoints = player.spentSkillPoints,
currentHealth = player.currentHealth,
maxHealth = player.maxHealth,
currentXP = player.currentXP,
xpToLevel = player.xpToLevel,
atk = player.atk,
atkItemBonus = player.atkItemBonus,
statAtk = player.statAtk,
def = player.def,
defItemBonus = player.defItemBonus,
statDef = player.statDef,
skill1Lvl = player.skills[0].level,
skill2Lvl = player.skills[1].level,
skill3Lvl = player.skills[2].level,
skill4Lvl = player.skills[3].level,
lookingX = (int)player.looking.x,
lookingY = (int)player.looking.y,
direction = player.direction,
bronzeKeys = player.bronzeKeys,
silverKeys = player.silverKeys,
goldKeys = player.goldKeys,
currentMap = Globals.currentMap,
redOrbState = player.redOrbState,
blueOrbState = player.blueOrbState,
storyProgress = player.storyProgress,
sideQuests = new List<PlayerSaveData.PlayerQuests>()
};
foreach(Quest q in player.quests)
{
PlayerSaveData.PlayerQuests quest = new PlayerSaveData.PlayerQuests();
quest.questName = q.questName;
quest.description = q.description;
quest.complete = q.complete;
quest.progress = q.progress;
playerData.sideQuests.Add(quest);
}
string json = JsonUtility.ToJson(playerData);
string fileName = Path.Combine(saveData, "player.json");
if(File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
SavePlayerInventory();
//Debug.Log(json);
Debug.Log(fileName);
}
public void SavePlayerInventory()
{
PlayerInventory playerInventory = new PlayerInventory();
try
{
foreach (InventoryItemBase i in player.inventory)
{
playerInventory.inventoryItems.Add(i);
}
}
catch
{
Debug.Log("Empty Inventory");
}
string json = JsonUtility.ToJson(playerInventory);
string fileName = Path.Combine(saveData, "inventory.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
public void LoadPlayerInventory()
{
try
{
fileName = Path.Combine(saveData, "inventory.json");
loadFile = File.ReadAllText(fileName);
PlayerInventory load = JsonUtility.FromJson<PlayerInventory>(loadFile);
if (load.inventoryItems.Count > 0)
{
player.inventory.Clear();
foreach (InventoryItemBase i in load.inventoryItems)
{
player.inventory.Add(i);
}
}
}
catch
{
Debug.Log("Problem loading inventory");
}
}
public void LoadPlayerData()
{
fileName = Path.Combine(saveData, "player.json");
loadFile = File.ReadAllText(fileName);
PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile);
//Debug.Log(load.level+ "" + load.statPoints+""+ load.skillPoints+ "" +load.currentMap);
player.level = load.level;
player.statPoints = load.statPoints;
player.skillPoints = load.skillPoints;
player.spentStatPoints = load.spentStatPoints;
player.spentSkillPoints = load.spentSkillPoints;
player.maxHealth = load.maxHealth;
player.currentHealth = load.currentHealth;
player.xpToLevel = load.xpToLevel;
player.currentXP = load.currentXP;
player.atk = load.atk;
player.statAtk = load.statAtk;
player.atkItemBonus = load.atkItemBonus;
player.def = load.def;
player.statDef = load.statDef;
player.defItemBonus = load.defItemBonus;
player.skills[0].level = load.skill1Lvl;
player.skills[1].level = load.skill2Lvl;
player.skills[2].level = load.skill3Lvl;
player.skills[3].level = load.skill4Lvl;
player.looking = new Vector2(load.lookingX, load.lookingY);
player.direction = load.direction;
player.bronzeKeys = load.bronzeKeys;
player.silverKeys = load.silverKeys;
player.goldKeys = load.goldKeys;
player.redOrbState = load.redOrbState;
player.blueOrbState = load.blueOrbState;
player.storyProgress = load.storyProgress;
//for (int x = 0; x < load.sideQuests.Count; x++)
// {
// Debug.Log(load.sideQuests[x].questName);
// Debug.Log(load.sideQuests[x].description);
// Debug.Log(load.sideQuests[x].complete);
// Debug.Log(load.sideQuests[x].progress);
// player.quests.Add(new Quest(load.sideQuests[x].questName, load.sideQuests[x].description, load.sideQuests[x].complete, load.sideQuests[0].progress));
//}
foreach (PlayerSaveData.PlayerQuests q in load.sideQuests)
{
//Debug.Log(q.questName);
//Debug.Log(q.description);
//Debug.Log(q.complete);
//Debug.Log(q.progress);
player.quests.Add(new Quest(q.questName, q.description, q.complete, q.progress));
//Debug.Log(player.quests[0].questName);
}
LoadPlayerInventory();
}
public string SavedFloor()
{
//used to load in saved floor
fileName = Path.Combine(saveData, "player.json");
loadFile = File.ReadAllText(fileName);
PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile);
return load.currentMap;
}
//public void SaveMap(int x, int y)
//{
// MapSaveData mapData = new MapSaveData()
// {
// returnPointX = x,
// returnPointY = y
// };
// string json = JsonUtility.ToJson(mapData);
// string fileName = Path.Combine(saveData, SceneManager.GetActiveScene().name + ".json");
// if (File.Exists(fileName))
// {
// File.Delete(fileName);
// }
// File.WriteAllText(fileName, json);
//}
//public void LoadMap(string nextMap)
//{
// fileName = Path.Combine(saveData, nextMap + ".json");
// loadFile = File.ReadAllText(fileName);
// MapSaveData load = JsonUtility.FromJson<MapSaveData>(loadFile);
// player.gameObject.transform.position = new Vector2(load.returnPointX + .5f, load.returnPointY-.5f);
//}
/*public void SaveEnemies()
{
try
{
EnemiesOnMap mapEnemies = new EnemiesOnMap
{
mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>()
};
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapEnemies.mapEnemyInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapEnemies);
string fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Enemies here");
}
}
public void SaveEnemiesDefault()
{
try
{
EnemiesOnMap mapEnemies = new EnemiesOnMap
{
mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>()
};
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapEnemies.mapEnemyInfo.Add(newInfo);
Destroy(enemy);
}
string json = JsonUtility.ToJson(mapEnemies);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Enemies here");
}
}
public void LoadEnemies()
{try
{
StartCoroutine(LoadEnemiesDelay());
}
catch
{
Debug.Log("No Enemies Loaded");
}
}
public IEnumerator LoadEnemiesDelay()
{
yield return new WaitForSeconds(.5f);
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "enemies.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json");
}
Debug.Log("loading enemies from " + fileName);
loadFile = File.ReadAllText(fileName);
EnemiesOnMap load = JsonUtility.FromJson<EnemiesOnMap>(loadFile);
Container enemyContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (EnemiesOnMap.EnemyInfo info in load.mapEnemyInfo)
//{
// //load into a list.
// //enemyContainer.CreateEnemy(info.enemyName, info.posX, info.posY, info.alive);
//}
for(int x = load.mapEnemyInfo.Count -1; x>-1; x--)
{
//start new enemy
//set its info to load[x]
//create from container
//clear entry from list
EnemiesOnMap.EnemyInfo e = load.mapEnemyInfo[x];
enemyContainer.CreateEnemy(e.enemyName, e.posX, e.posY, e.alive,e.heldItem);
load.mapEnemyInfo.RemoveAt(x);
}
yield return null;
}
public void SaveItems()
{
try
{
ItemsOnMap mapItems = new ItemsOnMap
{
mapItemInfo = new List<ItemsOnMap.ItemInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapItems.mapItemInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapItems);
string fileName = Path.Combine(saveData, Globals.currentMap + "items.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Items Here");
}
}
public void SaveItemsDefault()
{
try
{
ItemsOnMap mapItems = new ItemsOnMap
{
mapItemInfo = new List<ItemsOnMap.ItemInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapItems.mapItemInfo.Add(newInfo);
Destroy(item);
}
string json = JsonUtility.ToJson(mapItems);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Items Here");
}
}
public void LoadItems()
{
try
{
StartCoroutine(LoadItemsDelay());
}
catch
{
Debug.Log("No items loaded");
}
}
public IEnumerator LoadItemsDelay()
{
yield return new WaitForSeconds(.5f);
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "items.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "items.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json");
}
Debug.Log("loading items from " + fileName);
loadFile = File.ReadAllText(fileName);
ItemsOnMap load = JsonUtility.FromJson<ItemsOnMap>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (ItemsOnMap.ItemInfo info in load.mapItemInfo)
//{
// Debug.Log(info.itemName);
// itemContainer.CreateItem(info.itemName, info.value, info.posX, info.posY, info.active);
//}
for (int x = load.mapItemInfo.Count - 1; x > -1; x--)
{
ItemsOnMap.ItemInfo i = load.mapItemInfo[x];
itemContainer.CreateItem(i.itemName,i.value, i.posX, i.posY);
load.mapItemInfo.RemoveAt(x);
}
yield return null;
}
public void SaveDoors()
{
try
{
DoorsOnMap mapDoors = new DoorsOnMap
{
mapDoorInfo = new List<DoorsOnMap.DoorInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = item.GetComponent<DoorBase>();
DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo();
{
newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapDoors.mapDoorInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapDoors);
string fileName = Path.Combine(saveData, Globals.currentMap + "doors.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Doors Here");
}
}
public void SaveDoorsDefault()
{
try
{
DoorsOnMap mapDoors = new DoorsOnMap
{
mapDoorInfo = new List<DoorsOnMap.DoorInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = item.GetComponent<DoorBase>();
DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo();
{
newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapDoors.mapDoorInfo.Add(newInfo);
Destroy(item);
}
string json = JsonUtility.ToJson(mapDoors);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Doors Here");
}
}
public void LoadDoors()
{
StartCoroutine(LoadDoorsDelay());
}
public IEnumerator LoadDoorsDelay()
{
yield return new WaitForSeconds(.5f);
try
{
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "doors.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "doors.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json");
}
Debug.Log("loading doors from " + fileName);
loadFile = File.ReadAllText(fileName);
DoorsOnMap load = JsonUtility.FromJson<DoorsOnMap>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (DoorsOnMap.DoorInfo info in load.mapDoorInfo)
//{
// itemContainer.CreateDoor(info.doorType, info.posX, info.posY);
//}
try
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
DoorsOnMap.DoorInfo d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorType, d.doorName, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
catch
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
DoorsOnMap.DoorInfo d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorType, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
}
catch { }
yield return null;
}*/
public void SaveMapData(bool d)
{
//true = default; false = other
fileName = "";
MapData mapData = new MapData
{
mapDoorInfo = new List<MapData.Door>(),
mapEnemyInfo = new List<MapData.Enemy>(),
mapItemInfo = new List<MapData.Item>(),
mapBinaryObjectInfo = new List<MapData.BinaryObject>()
};
//Save Doors
try
{
foreach (GameObject door in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = door.GetComponent<DoorBase>();
MapData.Door newInfo = new MapData.Door();
{
//newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapData.mapDoorInfo.Add(newInfo);
Destroy(door);
}
}
catch
{
Debug.Log("problem saving doors");
}
//Save Items
try
{
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
MapData.Item newInfo = new MapData.Item();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapData.mapItemInfo.Add(newInfo);
Destroy(item);
}
}
catch
{
Debug.Log("problem saving items");
}
//Save Enemies
try
{
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
MapData.Enemy newInfo = new MapData.Enemy();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapData.mapEnemyInfo.Add(newInfo);
Destroy(enemy);
}
}
catch
{
Debug.Log("problem saving enemies");
}
//Save BinaryItems
try
{
foreach(GameObject binary in GameObject.FindGameObjectsWithTag("Button"))
{
BinaryObject currentObject = binary.GetComponent<BinaryObject>();
MapData.BinaryObject newObject = new MapData.BinaryObject();
{
newObject.objectName = currentObject.objectName.ToString();
newObject.buttonState = currentObject.buttonState;
newObject.objectState = currentObject.objectState;
newObject.buttonX = (int)currentObject.transform.position.x;
newObject.buttonY = (int)currentObject.transform.position.y;
newObject.objectX = currentObject.objectLocationX;
newObject.objectY = currentObject.objectLocationY;
newObject.canToggle = currentObject.canToggle;
}
}
}
catch
{
//nothing to save
}
string json = JsonUtility.ToJson(mapData);
if(d == true)
{
fileName = Path.Combine(defaults, Globals.currentMap + ".json");
Debug.Log(d);
}
else
{
fileName = Path.Combine(saveData, Globals.currentMap + ".json");
Debug.Log(d);
}
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
Debug.Log("save complete" + fileName);
}
public IEnumerator LoadMapData()
{
yield return new WaitForSeconds(.5f);
Debug.Log("loading map data");
try
{
if (File.Exists(Path.Combine(saveData, Globals.currentMap + ".json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + ".json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + ".json");
}
Debug.Log("loading from " + fileName);
loadFile = File.ReadAllText(fileName);
MapData load = JsonUtility.FromJson<MapData>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
try
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
MapData.Door d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorName, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
catch
{
Debug.Log("problem loading doors");
}
try
{
for (int x = load.mapItemInfo.Count - 1; x > -1; x--)
{
MapData.Item i = load.mapItemInfo[x];
itemContainer.CreateItem(i.itemName, i.value, i.posX, i.posY);
load.mapItemInfo.RemoveAt(x);
}
}
catch
{
}
try
{
for (int x = load.mapEnemyInfo.Count - 1; x > -1; x--)
{
MapData.Enemy e = load.mapEnemyInfo[x];
itemContainer.CreateEnemy(e.enemyName, e.posX, e.posY,e.alive,e.heldItem);
load.mapEnemyInfo.RemoveAt(x);
}
}
catch
{
}
try
{
for (int x = load.mapBinaryObjectInfo.Count - 1; x > -1; x--)
{
MapData.BinaryObject o = load.mapBinaryObjectInfo[x];
itemContainer.CreateBinaryObject(o.objectName, o.buttonState, o.objectState, o.buttonX, o.buttonY, o.objectX, o.objectY, o.canToggle);
load.mapBinaryObjectInfo.RemoveAt(x);
}
}
catch
{
}
}
catch { }
yield return null;
}
}
| ZepedaJake/2D-RPG-Unity | Terry's Tower/Assets/Scripts/Serializer.cs | C# | gpl-3.0 | 27,853 |
package grid;
import java.util.Comparator;
import world.World;
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2002-2006 College Entrance Examination Board
* (http://www.collegeboard.com).
*
* This 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.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Alyce Brady
* @author Chris Nevison
* @author APCS Development Committee
* @author Cay Horstmann
*/
/**
* A <code>Location</code> object represents the row and column of a location
* in a two-dimensional grid. <br />
* The API of this class is testable on the AP CS A and AB exams.
*/
public class Location implements Comparable
{
private int row; // row location in grid
private int col; // column location in grid
/**
* The turn angle for turning 90 degrees to the left.
*/
public static final int LEFT = -90;
/**
* The turn angle for turning 90 degrees to the right.
*/
public static final int RIGHT = 90;
/**
* The turn angle for turning 45 degrees to the left.
*/
public static final int HALF_LEFT = -45;
/**
* The turn angle for turning 45 degrees to the right.
*/
public static final int HALF_RIGHT = 45;
/**
* The turn angle for turning a full circle.
*/
public static final int FULL_CIRCLE = 360;
/**
* The turn angle for turning a half circle.
*/
public static final int HALF_CIRCLE = 180;
/**
* The turn angle for making no turn.
*/
public static final int AHEAD = 0;
/**
* The compass direction for north.
*/
public static final int NORTH = 0;
/**
* The compass direction for northeast.
*/
public static final int NORTHEAST = 45;
/**
* The compass direction for east.
*/
public static final int EAST = 90;
/**
* The compass direction for southeast.
*/
public static final int SOUTHEAST = 135;
/**
* The compass direction for south.
*/
public static final int SOUTH = 180;
/**
* The compass direction for southwest.
*/
public static final int SOUTHWEST = 225;
/**
* The compass direction for west.
*/
public static final int WEST = 270;
/**
* The compass direction for northwest.
*/
public static final int NORTHWEST = 315;
/**
* Constructs a location with given row and column coordinates.
* @param r the row
* @param c the column
*/
public Location(int r, int c)
{
row = r;
col = c;
}
/**
* Gets the row coordinate.
* @return the row of this location
*/
public int getRow()
{
return row;
}
/**
* Gets the column coordinate.
* @return the column of this location
*/
public int getCol()
{
return col;
}
/**
* Gets the adjacent location in any one of the eight compass directions.
* @param direction the direction in which to find a neighbor location
* @return the adjacent location in the direction that is closest to
* <tt>direction</tt>
*/
public Location getAdjacentLocation(int direction)
{
// reduce mod 360 and round to closest multiple of 45
int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE;
if (adjustedDirection < 0)
adjustedDirection += FULL_CIRCLE;
adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT;
int dc = 0;
int dr = 0;
if (adjustedDirection == EAST)
dc = 1;
else if (adjustedDirection == SOUTHEAST)
{
dc = 1;
dr = 1;
}
else if (adjustedDirection == SOUTH)
dr = 1;
else if (adjustedDirection == SOUTHWEST)
{
dc = -1;
dr = 1;
}
else if (adjustedDirection == WEST)
dc = -1;
else if (adjustedDirection == NORTHWEST)
{
dc = -1;
dr = -1;
}
else if (adjustedDirection == NORTH)
dr = -1;
else if (adjustedDirection == NORTHEAST)
{
dc = 1;
dr = -1;
}
return new Location(getRow() + dr, getCol() + dc);
}
/**
* Returns the direction from this location toward another location. The
* direction is rounded to the nearest compass direction.
* @param target a location that is different from this location
* @return the closest compass direction from this location toward
* <code>target</code>
*/
public int getDirectionToward(Location target)
{
int dx = target.getCol() - getCol();
int dy = target.getRow() - getRow();
// y axis points opposite to mathematical orientation
int angle = (int) Math.toDegrees(Math.atan2(-dy, dx));
// mathematical angle is counterclockwise from x-axis,
// compass angle is clockwise from y-axis
int compassAngle = RIGHT - angle;
// prepare for truncating division by 45 degrees
compassAngle += HALF_RIGHT / 2;
// wrap negative angles
if (compassAngle < 0)
compassAngle += FULL_CIRCLE;
// round to nearest multiple of 45
return (compassAngle / HALF_RIGHT) * HALF_RIGHT;
}
/**
* Indicates whether some other <code>Location</code> object is "equal to"
* this one.
* @param other the other location to test
* @return <code>true</code> if <code>other</code> is a
* <code>Location</code> with the same row and column as this location;
* <code>false</code> otherwise
*/
public boolean equals(Object other)
{
if (!(other instanceof Location))
return false;
Location otherLoc = (Location) other;
return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol();
}
/**
* Generates a hash code.
* @return a hash code for this location
*/
public int hashCode()
{
return getRow() * 3737 + getCol();
}
/**
* Compares this location to <code>other</code> for ordering. Returns a
* negative integer, zero, or a positive integer as this location is less
* than, equal to, or greater than <code>other</code>. Locations are
* ordered in row-major order. <br />
* (Precondition: <code>other</code> is a <code>Location</code> object.)
* @param other the other location to test
* @return a negative integer if this location is less than
* <code>other</code>, zero if the two locations are equal, or a positive
* integer if this location is greater than <code>other</code>
*/
public int compareTo(Object other)
{
Location otherLoc = (Location) other;
if (getRow() < otherLoc.getRow())
return -1;
if (getRow() > otherLoc.getRow())
return 1;
if (getCol() < otherLoc.getCol())
return -1;
if (getCol() > otherLoc.getCol())
return 1;
return 0;
}
/**
* (Added for RatBots) Calculates the distance to another location.
* The distance is reported as the sum of the x and y distances
* and therefore doesn't consider diagonal movement.
* @param other the location that the distance is calculated to
* @return the distance
*/
public int distanceTo(Location other)
{
int dx = Math.abs(row - other.getRow());
int dy = Math.abs(col - other.getCol());
return dx+dy;
}
public boolean isValidLocation()
{
if(this.getRow() < 0 || this.getRow() >= World.DEFAULT_ROWS)
return false;
if(this.getCol() < 0 || this.getCol() >= World.DEFAULT_COLS)
return false;
return true;
}
/**
* Creates a string that describes this location.
* @return a string with the row and column of this location, in the format
* (row, col)
*/
public String toString()
{
return "(r:" + getRow() + ", c:" + getCol() + ")";
}
}
| fazerlicourice7/botWorld2017 | src/grid/Location.java | Java | gpl-3.0 | 8,439 |
/* This file is part of LiveCG.
*
* Copyright (C) 2013 Sebastian Kuerten
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.topobyte.livecg.ui.geometryeditor.preferences;
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import de.topobyte.livecg.preferences.Configuration;
public class LAFSelector extends JComboBox
{
private static final long serialVersionUID = 6856865390726849784L;
public LAFSelector(Configuration configuration)
{
super(buildValues());
setRenderer(new Renderer());
setEditable(false);
String lookAndFeel = configuration.getSelectedLookAndFeel();
setSelectedIndex(-1);
for (int i = 0; i < getModel().getSize(); i++) {
LookAndFeelInfo info = (LookAndFeelInfo) getModel().getElementAt(i);
if (info.getClassName().equals(lookAndFeel)) {
setSelectedIndex(i);
break;
}
}
}
private static LookAndFeelInfo[] buildValues()
{
LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();
return lafs;
}
private class Renderer extends BasicComboBoxRenderer
{
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (value != null) {
LookAndFeelInfo item = (LookAndFeelInfo) value;
setText(item.getName());
} else {
setText("default");
}
return this;
}
}
}
| sebkur/live-cg | project/src/main/java/de/topobyte/livecg/ui/geometryeditor/preferences/LAFSelector.java | Java | gpl-3.0 | 2,265 |
package com.yoavst.quickapps.calendar;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import com.yoavst.quickapps.Preferences_;
import com.yoavst.quickapps.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.TimeZone;
import static android.provider.CalendarContract.Events.ALL_DAY;
import static android.provider.CalendarContract.Events.DISPLAY_COLOR;
import static android.provider.CalendarContract.Events.DTEND;
import static android.provider.CalendarContract.Events.DTSTART;
import static android.provider.CalendarContract.Events.DURATION;
import static android.provider.CalendarContract.Events.EVENT_LOCATION;
import static android.provider.CalendarContract.Events.RRULE;
import static android.provider.CalendarContract.Events.TITLE;
import static android.provider.CalendarContract.Events._ID;
/**
* Created by Yoav.
*/
public class CalendarUtil {
private CalendarUtil() {
}
private static final SimpleDateFormat dayFormatter = new SimpleDateFormat(
"EEE, MMM d, yyyy");
private static final SimpleDateFormat dateFormatter = new SimpleDateFormat(
"EEE, MMM d, HH:mm");
private static final SimpleDateFormat hourFormatter = new SimpleDateFormat("HH:mm");
private static final SimpleDateFormat fullDateFormat = new SimpleDateFormat("EEE, MMM d");
private static final SimpleDateFormat otherDayFormatter = new SimpleDateFormat("MMM d, HH:mm");
private static final TimeZone timezone = Calendar.getInstance().getTimeZone();
public static ArrayList<Event> getCalendarEvents(Context context) {
CalendarResources.init(context);
boolean showRepeating = new Preferences_(context).showRepeatingEvents().get();
ArrayList<Event> events = new ArrayList<>();
String selection = "((" + DTSTART + " >= ?) OR (" + DTEND + " >= ?))";
String milli = String.valueOf(System.currentTimeMillis());
String[] selectionArgs = new String[]{milli, milli};
Cursor cursor = context.getContentResolver()
.query(
Events.CONTENT_URI,
new String[]{_ID, TITLE, DTSTART, DTEND, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, selection,
selectionArgs, null
);
cursor.moveToFirst();
int count = cursor.getCount();
if (count != 0) {
//<editor-fold desc="Future Events">
for (int i = 0; i < count; i++) {
int id = cursor.getInt(0);
String title = cursor.getString(1);
long startDate = Long.parseLong(cursor.getString(2));
String endDateString = cursor.getString(3);
String location = cursor.getString(4);
boolean isAllDay = cursor.getInt(5) != 0;
int color = cursor.getInt(6);
String rRule = cursor.getString(7);
String duration = cursor.getString(8);
if (!isAllDay) {
// If the event not repeat itself - regular event
if (rRule == null) {
long endDate = endDateString == null || endDateString.equals("null") ? 0 : Long.parseLong(endDateString);
if (endDate == 0)
events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color));
else
events.add(new Event(id, title, startDate, endDate, location).setColor(color));
} else if (showRepeating) {
// Event that repeat itself
events = addEvents(events, getEventFromRepeating(context, rRule, startDate, duration, location, color, title, id, false));
}
} else {
if (rRule == null) {
// One day event probably
if (endDateString == null || Long.parseLong(endDateString) == 0)
events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color));
else if (showRepeating) {
int offset = timezone.getOffset(startDate);
long newTime = startDate - offset;
long endTime = Long.parseLong(endDateString) - offset;
events.add(new Event(id, title, newTime, endTime, location, true).setColor(color));
}
} else if (showRepeating) {
// Repeat all day event, god why?!?
events = addEvents(events, getEventFromRepeating(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true));
}
}
cursor.moveToNext();
}
//</editor-fold>
}
cursor.close();
if (showRepeating) {
String repeatingSections = "((" + DURATION + " IS NOT NULL) AND (" + RRULE + " IS NOT NULL) AND ((" + DTSTART + " < ?) OR (" + DTEND + " < ?)))";
Cursor repeatingCursor = context.getContentResolver()
.query(
Events.CONTENT_URI,
new String[]{_ID, TITLE, DTSTART, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, repeatingSections,
selectionArgs, null
);
repeatingCursor.moveToFirst();
int repeatingCount = repeatingCursor.getCount();
if (repeatingCount != 0) {
//<editor-fold desc="repeating past Events">
for (int i = 0; i < repeatingCount; i++) {
int id = repeatingCursor.getInt(0);
String title = repeatingCursor.getString(1);
long startDate = Long.parseLong(repeatingCursor.getString(2));
String location = repeatingCursor.getString(3);
boolean isAllDay = repeatingCursor.getInt(4) != 0;
int color = repeatingCursor.getInt(5);
String rRule = repeatingCursor.getString(6);
String duration = repeatingCursor.getString(7);
if (!isAllDay) {
ArrayList<Event> repeatingEvents = getEventFromRepeating(context, rRule, startDate, duration, location, color, title, id, false);
events = addEvents(events, repeatingEvents);
} else {
ArrayList<Event> repeatingEvents = getEventFromRepeating(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true);
events = addEvents(events, repeatingEvents);
}
repeatingCursor.moveToNext();
}
//</editor-fold>
repeatingCursor.close();
}
}
Collections.sort(events, new Comparator<Event>() {
@Override
//an integer < 0 if lhs is less than rhs, 0 if they are equal, and > 0 if lhs is greater than rhs.
public int compare(Event lhs, Event rhs) {
int first = (lhs.getStartDate() - rhs.getStartDate()) < 0 ? -1 : lhs.getStartDate() == rhs.getStartDate() ? 0 : 1;
int second = (lhs.getEndDate() - rhs.getEndDate()) < 0 ? -1 : lhs.getEndDate() == rhs.getEndDate() ? 0 : 1;
return first != 0 ? first : second;
}
});
return events;
}
private static ArrayList<Event> addEvents(ArrayList<Event> list, ArrayList<Event> toAdd) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 6);
long milli = DateUtils.clearTime(calendar).getTimeInMillis();
long now = System.currentTimeMillis();
for (Event event : toAdd) {
if (event.getEndDate() <= milli && event.getEndDate() >= now) list.add(event);
}
return list;
}
private static ArrayList<Event> getEventFromRepeating(Context context, String rRule, long startDate, String duration, String location, int color, String title, int id, boolean isAllDay) {
ArrayList<Event> events = new ArrayList<>();
final String[] INSTANCE_PROJECTION = new String[]{
CalendarContract.Instances.EVENT_ID, // 0
CalendarContract.Instances.BEGIN, // 1
CalendarContract.Instances.END // 2
};
Calendar endTime = Calendar.getInstance();
endTime.add(Calendar.MONTH, 6);
String selection = CalendarContract.Instances.EVENT_ID + " = ?";
Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, System.currentTimeMillis());
ContentUris.appendId(builder, endTime.getTimeInMillis());
Cursor cursor = context.getContentResolver().query(builder.build(),
INSTANCE_PROJECTION,
selection,
new String[]{Integer.toString(id)},
null);
if (cursor.moveToFirst()) {
do {
events.add(new Event(id, title, cursor.getLong(1) - (isAllDay ? timezone.getOffset(startDate) : 0),
cursor.getLong(2) - (isAllDay ? timezone.getOffset(startDate) : 0), location, isAllDay).setColor(color));
} while (cursor.moveToNext());
}
return events;
}
public static String getDateFromEvent(Event event) {
if (event.getDate() != null) return event.getDate();
else if (event.isAllDay()) {
Calendar startPlusOneDay = Calendar.getInstance();
startPlusOneDay.setTimeInMillis(event.getStartDate());
startPlusOneDay.add(Calendar.DAY_OF_YEAR, 1);
Calendar endTime = Calendar.getInstance();
endTime.setTimeInMillis(event.getEndDate());
if (DateUtils.isSameDay(startPlusOneDay, endTime)) {
startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1);
if (DateUtils.isToday(startPlusOneDay))
return CalendarResources.today + " " + CalendarResources.allDay;
else if (DateUtils.isTomorrow(startPlusOneDay))
return CalendarResources.tomorrow + " " + CalendarResources.allDay;
return dayFormatter.format(new Date(event.getStartDate()));
} else {
endTime.add(Calendar.DAY_OF_YEAR, -1);
startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1);
if (DateUtils.isToday(startPlusOneDay)) {
if (DateUtils.isTomorrow(endTime))
return CalendarResources.today + " - " + CalendarResources.tomorrow;
else
return CalendarResources.today + " " + CalendarResources.allDay + " - " + fullDateFormat.format(endTime.getTime());
} else if (DateUtils.isTomorrow(startPlusOneDay))
return CalendarResources.tomorrow + " - " + fullDateFormat.format(endTime.getTime());
return fullDateFormat.format(new Date(event.getStartDate())) + " - " + fullDateFormat.format(endTime.getTime());
}
} else {
String text;
Date first = new Date(event.getStartDate());
Date end = new Date(event.getEndDate());
if (DateUtils.isSameDay(first, end)) {
if (DateUtils.isToday(first))
text = CalendarResources.today + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end);
else if (DateUtils.isWithinDaysFuture(first, 1))
text = CalendarResources.tomorrow + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end);
else
text = dateFormatter.format(first) + " - " + hourFormatter.format(end);
} else if (DateUtils.isToday(first)) {
text = CalendarResources.today + hourFormatter.format(first) + " - " + otherDayFormatter.format(end);
} else {
text = otherDayFormatter.format(first) + " - " + otherDayFormatter.format(end);
}
return text;
}
}
public static Intent launchEventById(long id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri.Builder uri = Events.CONTENT_URI.buildUpon();
uri.appendPath(Long.toString(id));
intent.setData(uri.build());
return intent;
}
public static String getTimeToEvent(Event event) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(event.getStartDate());
Calendar now = Calendar.getInstance();
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
if (calendar.getTimeInMillis() <= now.getTimeInMillis()) return CalendarResources.now;
else {
long secondsLeft = (calendar.getTimeInMillis() - now.getTimeInMillis()) / 1000;
if (secondsLeft < 60) return CalendarResources.in + " 1 " + CalendarResources.minute;
long minutesLeft = secondsLeft / 60;
if (minutesLeft < 60)
return CalendarResources.in + " " + minutesLeft + " " + (minutesLeft > 1 ? CalendarResources.minutes : CalendarResources.minute);
long hoursLeft = minutesLeft / 50;
if (hoursLeft < 24)
return CalendarResources.in + " " + hoursLeft + " " + (hoursLeft > 1 ? CalendarResources.hours : CalendarResources.hour);
int days = (int) (hoursLeft / 24);
if (days < 30)
return CalendarResources.in + " " + days + " " + (days > 1 ? CalendarResources.days : CalendarResources.day);
int months = days / 30;
if (months < 12)
return CalendarResources.in + " " + months + " " + (months > 1 ? CalendarResources.months : CalendarResources.month);
else return CalendarResources.moreThenAYearLeft;
}
}
public static class CalendarResources {
public static String today;
public static String tomorrow;
public static String allDay;
public static String now;
public static String in;
public static String minute;
public static String minutes;
public static String hour;
public static String hours;
public static String day;
public static String days;
public static String week;
public static String weeks;
public static String month;
public static String months;
public static String moreThenAYearLeft;
public static void init(Context context) {
if (today == null || moreThenAYearLeft == null) {
today = context.getString(R.string.today);
tomorrow = context.getString(R.string.tomorrow);
allDay = context.getString(R.string.all_day);
now = context.getString(R.string.now);
in = context.getString(R.string.in);
String[] min = context.getString(R.string.minute_s).split("/");
minute = min[0];
minutes = min[1];
String[] hoursArray = context.getString(R.string.hour_s).split("/");
hour = hoursArray[0];
hours = hoursArray[1];
String[] dayArray = context.getString(R.string.day_s).split("/");
day = dayArray[0];
days = dayArray[1];
String[] weekArray = context.getString(R.string.week_s).split("/");
week = weekArray[0];
weeks = weekArray[1];
String[] monthArray = context.getString(R.string.month_s).split("/");
month = monthArray[0];
months = monthArray[1];
moreThenAYearLeft = context.getString(R.string.more_then_year);
}
}
}
}
| gaich/quickapps | app/src/main/java/com/yoavst/quickapps/calendar/CalendarUtil.java | Java | gpl-3.0 | 13,741 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("3. Get Minion Names")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("3. Get Minion Names")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bc91e659-ee53-4238-ab47-d6f903948cb6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| PlamenHP/Softuni | Entity Framework/Introduction to DB Apps/3. Get Minion Names/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,432 |
#===============================================================================
# Filename: rgss.rb
#
# Developer: Raku (rakudayo@gmail.com)
#
# Description: This is the core file to include to enable loading and dumping
# of RMXP's .rxdata files.
#===============================================================================
require_relative 'rgss_internal'
require_relative 'rgss_rpg'
require_relative 'rgss_mod' | griest024/PokemonEssentialsEditor | lib/pkmnee/import/plugin/rmxp/rgss.rb | Ruby | gpl-3.0 | 427 |
package uk.tim740.skUtilities.util;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import uk.tim740.skUtilities.skUtilities;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/**
* Created by tim740 on 11/09/2016
*/
public class ExprTimeInTimeZone extends SimpleExpression<String> {
private Expression<String> str;
@Override
@Nullable
protected String[] get(Event e) {
String s = str.getSingle(e);
String[] sl = new String[0];
try {
BufferedReader br = new BufferedReader(new FileReader(new File("plugins/Skript/config.sk").getAbsoluteFile()));
sl = br.lines().toArray(String[]::new);
br.close();
} catch (Exception x) {
skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x);
}
String sf = "";
for (String aSl : sl) {
if (aSl.contains("date format: ")) {
sf = aSl.replaceFirst("date format: ", "");
}
}
String ff;
if (sf.equalsIgnoreCase("default")) {
ff = new SimpleDateFormat().toPattern();
} else {
ff = sf;
}
return new String[]{ZonedDateTime.ofInstant(Instant.now(), ZoneId.of(s)).format(DateTimeFormatter.ofPattern(ff))};
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] e, int i, Kleenean k, SkriptParser.ParseResult p) {
str = (Expression<String>) e[0];
return true;
}
@Override
public Class<? extends String> getReturnType() {
return String.class;
}
@Override
public boolean isSingle() {
return true;
}
@Override
public String toString(@Nullable Event e, boolean b) {
return getClass().getName();
}
}
| tim740/skUtilities | src/uk/tim740/skUtilities/util/ExprTimeInTimeZone.java | Java | gpl-3.0 | 1,995 |
"""
Page view class
"""
import os
from Server.Importer import ImportFromModule
class PageView(ImportFromModule("Server.PageViewBase", "PageViewBase")):
"""
Page view class.
"""
_PAGE_TITLE = "Python Web Framework"
def __init__(self, htmlToLoad):
"""
Constructor.
- htmlToLoad : HTML to load
"""
self.SetPageTitle(self._PAGE_TITLE)
self.AddMetaData("charset=\"UTF-8\"")
self.AddMetaData("name=\"viewport\" content=\"width=device-width, initial-scale=1\"")
self.AddStyleSheet("/css/styles.css")
self.AddJavaScript("/js/http.js")
self.LoadHtml(os.path.join(os.path.dirname(__file__), "%s.html" % htmlToLoad))
self.SetPageData({ "PageTitle" : self._PAGE_TITLE })
| allembedded/python_web_framework | WebApplication/Views/PageView.py | Python | gpl-3.0 | 781 |
/*
* Copyright (C) 2010 The UAPI Authors
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at the LICENSE file.
*
* You must gained the permission from the authors if you want to
* use the project into a commercial product
*/
package uapi.service;
import uapi.InvalidArgumentException;
import uapi.helper.ArgumentChecker;
import java.util.HashMap;
import java.util.Map;
/**
* Define response code
*/
public abstract class ResponseCode {
private final Map<String, String> _codeMsgKeyMapping = new HashMap<>();
private final MessageExtractor _msgExtractor = new MessageExtractor(this.getClass().getClassLoader());
public void init() {
getMessageLoader().registerExtractor(this._msgExtractor);
}
protected abstract MessageLoader getMessageLoader();
public String getMessageKey(final String code) {
ArgumentChecker.required(code, "code");
return this._codeMsgKeyMapping.get("code");
}
protected void addCodeMessageKeyMapping(String code, String messageKey) {
ArgumentChecker.required(code, "code");
ArgumentChecker.required(messageKey, "messageKey");
if (this._codeMsgKeyMapping.containsKey(code)) {
throw new InvalidArgumentException("Overwrite existing code message key is not allowed - {}", code);
}
this._codeMsgKeyMapping.put(code, messageKey);
this._msgExtractor.addDefinedKeys(messageKey);
}
}
| minjing/uapi | uapi.service/src/main/java/uapi/service/ResponseCode.java | Java | gpl-3.0 | 1,491 |
<?php
namespace SHC\Event;
//Imports
use RWF\Date\DateTime;
use RWF\Util\StringUtils;
use SHC\Condition\Condition;
use SHC\Condition\ConditionEditor;
use SHC\Core\SHC;
use SHC\Switchable\Switchable;
use SHC\Switchable\SwitchableEditor;
/**
* Ereignise Verwalten
*
* @author Oliver Kleditzsch
* @copyright Copyright (c) 2014, Oliver Kleditzsch
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @since 2.0.0-0
* @version 2.0.0-0
*/
class EventEditor {
/**
* Ereignis Luftfeuchte steigt
*
* @var Integer
*/
const EVENT_HUMIDITY_CLIMB = 1;
/**
* Ereignis Luftfeuchte faellt
*
* @var Integer
*/
const EVENT_HUMIDITY_FALLS = 2;
/**
* Ereignis Eingang wechselt von LOW auf HIGH
*
* @var Integer
*/
const EVENT_INPUT_HIGH = 4;
/**
* Ereignis EIngang wechselt von HIGH auf LOW
*
* @var Integer
*/
const EVENT_INPUT_LOW = 8;
/**
* Ereignis Lichtstaerke steigt
*
* @var Integer
*/
const EVENT_LIGHTINTENSITY_CLIMB = 16;
/**
* Ereignis Lichtsaerke faellt
*
* @var Integer
*/
const EVENT_LIGHTINTENSITY_FALLS = 32;
/**
* Ereignis Feuchtigkeit steigt
*
* @var Integer
*/
const EVENT_MOISTURE_CLIMB = 64;
/**
* Ereignis Feuchtigkeit steigt
*
* @var Integer
*/
const EVENT_MOISTURE_FALLS = 128;
/**
* Ereignis Temperatur steigt
*
* @var Integer
*/
const EVENT_TEMPERATURE_CLIMB = 256;
/**
* Ereignis Temperatur faellt
*
* @var Integer
*/
const EVENT_TEMPERATURE_FALLS = 512;
/**
* Ereignis Benutzer kommt nach Hause
*
* @var Integer
*/
const EVENT_USER_COMES_HOME = 1024;
/**
* Ereignis Benutzer verlaesst das Haus
*
* @var Integer
*/
const EVENT_USER_LEAVE_HOME = 2048;
/**
* Ereignis Sonnenaufgang
*
* @var Integer
*/
const EVENT_SUNRISE = 4096;
/**
* Ereignis Sonnenuntergang
*
* @var Integer
*/
const EVENT_SUNSET = 8192;
/**
* Ereignis Datei erstellt
*
* @var Integer
*/
const EVENT_FILE_CREATE = 16384;
/**
* Ereignis Datei geloescht
*
* @var Integer
*/
const EVENT_FILE_DELETE = 32768;
/**
* nach ID sortieren
*
* @var String
*/
const SORT_BY_ID = 'id';
/**
* nach Namen sortieren
*
* @var String
*/
const SORT_BY_NAME = 'name';
/**
* nicht sortieren
*
* @var String
*/
const SORT_NOTHING = 'unsorted';
/**
* Ereignisse
*
* @var Array
*/
protected $events = array();
/**
* Singleton Instanz
*
* @var \SHC\Event\EventEditor
*/
protected static $instance = null;
/**
* name der HashMap
*
* @var String
*/
protected static $tableName = 'shc:events';
protected function __construct() {
$this->loadData();
}
/**
* laedt die Ereignisse aus den XML Daten und erzeugt die Objekte
*/
public function loadData() {
//Daten Vorbereiten
$oldEvents = $this->events;
$this->events = array();
$events = SHC::getDatabase()->hGetAllArray(self::$tableName);
//Daten einlesen
foreach ($events as $event) {
//Variablen Vorbereiten
$class = (string) $event['class'];
$data = array();
foreach ($event as $index => $value) {
if (!in_array($index, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) {
$data[$index] = $value;
}
}
/* @var $eventObj \SHC\Event\Event */
$eventObj = new $class(
(int) $event['id'], (string) $event['name'], $data, ((int) $event['enabled'] == true ? true : false), DateTime::createFromDatabaseDateTime((string) $event['lastExecute'])
);
//Bedingungen anhaengen
foreach ($event['conditions'] as $conditionId) {
$condition = ConditionEditor::getInstance()->getConditionByID($conditionId);
if ($condition instanceof Condition) {
$eventObj->addCondition($condition);
}
}
//schaltbare Elemente Hinzufuegen
if(isset($event['switchable'])) {
foreach ($event['switchable'] as $switchable) {
$switchableObject = SwitchableEditor::getInstance()->getElementById((int) $switchable['id']);
if ($switchableObject instanceof Switchable) {
$eventObj->addSwitchable($switchableObject, (int) $switchable['command']);
}
}
}
//Objekt status vom alten Objekt ins neue übertragen
if(isset($oldEvents[(int) $event['id']])) {
/* @var $eventObj \SHC\Event\Event */
$eventObj->setState($oldEvents[(int) $event['id']]->getState());
if($oldEvents[(int) $event['id']]->getTime() instanceof DateTime) {
$eventObj->setTime($oldEvents[(int) $event['id']]->getTime());
}
}
$this->events[(int) $event['id']] = $eventObj;
}
}
/**
* gibt das Ereignis mit der IOD zurueck
*
* @param int $id Ereignis ID
* @return \SHC\Event\Event
*/
public function getEventById($id) {
if (isset($this->events[$id])) {
return $this->events[$id];
}
return null;
}
/**
* prueft ob der Name des Events schon verwendet wird
*
* @param String $name Name
* @return Boolean
*/
public function isEventNameAvailable($name) {
foreach ($this->events as $event) {
/* @var $condition \SHC\Event\Event */
if (StringUtils::toLower($event->getName()) == StringUtils::toLower($name)) {
return false;
}
}
return true;
}
/**
* gibt eine Liste mit allen Bedingungen zurueck
*
* @param String $orderBy Art der Sortierung (
* id => nach ID sorieren,
* name => nach Namen sortieren,
* unsorted => unsortiert
* )
* @return Array
*/
public function listEvents($orderBy = 'id') {
if ($orderBy == 'id') {
//nach ID sortieren
$events = $this->events;
ksort($events, SORT_NUMERIC);
return $events;
} elseif ($orderBy == 'name') {
//nach Namen sortieren
$events = $this->events;
//Sortierfunktion
$orderFunction = function($a, $b) {
if ($a->getName() == $b->getName()) {
return 0;
}
if ($a->getName() < $b->getName()) {
return -1;
}
return 1;
};
usort($events, $orderFunction);
return $events;
}
return $this->events;
}
/**
* erstellt ein Event
*
* @param String $class Klassenname
* @param String $name Name
* @param Boolean $enabled Aktiv
* @param Array $data Zusatzdaten
* @param Array $conditions Liste der Bedingunen
* @return Boolean
* @throws \Exception
*/
protected function addEvent($class, $name, array $data = array(), $enabled = true, array $conditions) {
//Ausnahme wenn Name des Events schon belegt
if (!$this->isEventNameAvailable($name)) {
throw new \Exception('Der Name des Events ist schon vergeben', 1502);
}
$db = SHC::getDatabase();
$index = $db->autoIncrement(self::$tableName);
$newEvent = array(
'id' => $index,
'class' => $class,
'name' => $name,
'enabled' => ($enabled == true ? true : false),
'conditions' => $conditions,
'lastExecute' => '2000-01-01 00:00:00',
'switchable' => array()
);
foreach ($data as $tag => $value) {
if (!in_array($tag, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) {
$newEvent[$tag] = $value;
}
}
if($db->hSetNxArray(self::$tableName, $index, $newEvent) == 0) {
return false;
}
return true;
}
/**
* bearbeitet ein Event
*
* @param Integer $id ID
* @param String $name Name
* @param Array $data Zusatzdaten
* @param Boolean $enabled Aktiv
* @param Array $conditions Liste der Bedingunen
* @return Boolean
* @throws \Exception
*/
protected function editEvent($id, $name = null, array $data = null, $enabled = null, array $conditions = null) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $id)) {
$event = $db->hGetArray(self::$tableName, $id);
//Name
if ($name !== null) {
//Ausnahme wenn Name der Bedingung schon belegt
if ((string) $event['name'] != $name && !$this->isEventNameAvailable($name)) {
throw new \Exception('Der Name der Bedingung ist schon vergeben', 1502);
}
$event['name'] = $name;
}
//Aktiv
if ($enabled !== null) {
$event['enabled'] = ($enabled == true ? 1 : 0);
}
//Bedingungen
if($conditions !== null) {
$event['conditions'] = implode(',', $conditions);
}
//Zusatzdaten
foreach($data as $tag => $value) {
if (!in_array($tag, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) {
if($value !== null) {
$event[$tag] = $value;
}
}
}
if($db->hSetArray(self::$tableName, $id, $event) == 0) {
return true;
}
}
return false;
}
/**
* Speichert den Zeitpunkt der letzten Ausfuehrung fuer ein Ereignis
*
* @param Integer $id Ereignis ID
* @param \RWF\Date\DateTime $lastExecute letzte Ausfuehrung
* @return Boolean
*/
public function updateLastExecute($id, DateTime $lastExecute) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $id)) {
$event = $db->hGetArray(self::$tableName, $id);
if(isset($event['id']) && $event['id'] == $id) {
$event['lastExecute'] = $lastExecute->getDatabaseDateTime();
if($db->hSetArray(self::$tableName, $id, $event) == 0) {
return true;
}
} else {
//Datensatz nicht mehr vorhanden
return false;
}
}
return false;
}
/**
* erstellt ein Luftfeuchte Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addHumidityClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\HumidityClimbOver', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Luftfeuchte Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editHumidityClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Luftfeuchte Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addHumidityFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\HumidityFallsBelow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Luftfeuchte Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editHumidityFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Lichtstaerke Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addLightIntensityClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\LightIntensityClimbOver', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Lichtstaerke Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editLightIntensityClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Lichtstaerke Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addLightIntensityFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\LightIntensityFallsBelow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Lichtstaerke Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editLightIntensityFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Feuchtigkeits Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addMoistureClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\MoistureClimbOver', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Feuchtigkeits Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editMoistureClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Feuchtigkeits Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addMoistureFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\MoistureFallsBelow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Feuchtigkeits Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editMoistureFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Temperatur Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addTemperatureClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\TemperatureClimbOver', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Temperatur Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editTemperatureClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Temperatur Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addTemperatureFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\TemperatureFallsBelow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Temperatur Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editTemperatureFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Eingangsevent
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $inputs Eingaenge
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addInputHighEvent($name, $enabled, array $inputs, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'inputs' => implode(',', $inputs),
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\InputHigh', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Eingangsevent
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $inputs Eingaenge
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editInputHighEvent($id, $name = null, $enabled = null, array $inputs = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'inputs' => implode(',', $inputs),
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Eingangsevent
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $inputs Eingaenge
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addInputLowEvent($name, $enabled, array $inputs, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'inputs' => implode(',', $inputs),
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\InputLow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Eingangsevent
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $inputs Eingaenge
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editInputLowEvent($id, $name = null, $enabled = null, array $inputs = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'inputs' => implode(',', $inputs),
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Benutzerevent
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $users benutzer zu Hause
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addUserComesHomeEvent($name, $enabled, array $users, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'users' => implode(',', $users),
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\UserComesHome', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Benutzerevent
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $users benutzer zu Hause
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editUserComesHomeEvent($id, $name = null, $enabled = null, array $users = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'users' => implode(',', $users),
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Benutzerevent
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $users benutzer zu Hause
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addUserLeavesHomeEvent($name, $enabled, array $users, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'users' => implode(',', $users),
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\UserLeavesHome', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Benutzerevent
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $users benutzer zu Hause
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editUserLeavesHomeEvent($id, $name = null, $enabled = null, array $users = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'users' => implode(',', $users),
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein neuen Event Sonnenaufgang
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $conditions Liste der Bedingunen
*/
public function addSunriseEvent($name, $enabled, array $conditions = null) {
//Speichern
return $this->addEvent('\SHC\Event\Events\Sunrise', $name, array(), $enabled, $conditions);
}
/**
* bearbeitet ein Event Sonnenaufgang
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $conditions Liste der Bedingunen
*/
public function editSunriseEvent($id, $name = null, $enabled = null, array $conditions = null) {
//Speichern
return $this->editEvent($id, $name, array(), $enabled, $conditions);
}
/**
* erstellt ein neuen Event Sonnenuntergang
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $conditions Liste der Bedingunen
*/
public function addSunsetEvent($name, $enabled, array $conditions = null) {
//Speichern
return $this->addEvent('\SHC\Event\Events\Sunset', $name, array(), $enabled, $conditions);
}
/**
* bearbeitet ein Event Sonnenuntergang
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $conditions Liste der Bedingunen
*/
public function editSunsetEvent($id, $name = null, $enabled = null, array $conditions = null) {
//Speichern
return $this->editEvent($id, $name, array(), $enabled, $conditions);
}
/**
* erstellt ein Datei erstellt Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param String $file Datei
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addFileCreateEvent($name, $enabled, $file, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'file' => $file,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\FileCreate', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Datei erstellt Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param String $file Datei
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editFileCreateEvent($id, $name = null, $enabled = null, $file = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'file' => $file,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Datei geloescht Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param String $file Datei
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addFileDeleteEvent($name, $enabled, $file, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'file' => $file,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\FileDelete', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Datei geloescht Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param String $file Datei
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editFileDeleteEvent($id, $name = null, $enabled = null, $file = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'file' => $file,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* loascht ein Event
*
* @param Integer $id ID
* @return Boolean
*/
public function removeEvent($id) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $id)) {
if($db->hDel(self::$tableName, $id)) {
return true;
}
}
return false;
}
/**
* fuegt einem Event eine Bedingung hinzu
*
* @param Integer $eventId ID des Events
* @param Integer $conditionId ID der Bedingung
* @return Boolean
*/
public function addConditionToEvent($eventId, $conditionId) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
$event['conditions'][] = $conditionId;
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* entfernt eine Bedingung aus einem Event
*
* @param Integer $eventId ID des Events
* @param Integer $conditionId ID der Bedingung
* @return Boolean
*/
public function removeConditionFromEvent($eventId, $conditionId) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
$event['conditions'] = array_diff($event['conditions'], array($conditionId));
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* fuegt einem Event ein Schaltbares Element hinzu
*
* @param Integer $eventId ID des Events
* @param Integer $switchableId ID des Schaltbaren Elements
* @param Integer $command Befehl
* @return Boolean
*/
public function addSwitchableToEvent($eventId, $switchableId, $command) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
$event['switchable'][] = array('id' => $switchableId, 'command' => $command);
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* setzt den Befehl eines Schaltbaren Elements in einem Event
*
* @param Integer $eventId ID des Events
* @param Integer $switchableId ID des Schaltbaren Elements
* @param Integer $command Befehl
* @return Boolean
*/
public function setEventSwitchableCommand($eventId, $switchableId, $command) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
foreach($event['switchable'] as $index => $switchable) {
if($switchable['id'] == $switchableId) {
$event['switchable'][$index]['command'] = $command;
break;
}
}
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* entfernt ein Schaltbares Element von einem Event
*
* @param Integer $eventId ID des Events
* @param Integer $switchableId ID des Schaltbaren Elements
* @return Boolean
*/
public function removeSwitchableFromEvent($eventId, $switchableId) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
foreach($event['switchable'] as $index => $switchable) {
if($switchable['id'] == $switchableId) {
unset($event['switchable'][$index]);
break;
}
}
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* geschuetzt wegen Singleton
*/
private function __clone() {
}
/**
* gibt den Ereignis Editor Editor zurueck
*
* @return \SHC\Event\EventEditor
*/
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new EventEditor();
}
return self::$instance;
}
}
| agent4788/SHC_Framework | shc/lib/event/eventeditor.class.php | PHP | gpl-3.0 | 39,876 |
/*
* jQuery JavaScript Library v1.10.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-30T21:49Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.1",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.9.4-pre
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-27
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function() { return 0; },
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied if the test fails
* @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler
*/
function addHandle( attrs, handler, test ) {
attrs = attrs.split("|");
var current,
i = attrs.length,
setHandle = test ? null : handler;
while ( i-- ) {
// Don't override a user's handler
if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) {
Expr.attrHandle[ attrs[i] ] = setHandle;
}
}
}
/**
* Fetches boolean attributes by node
* @param {Element} elem
* @param {String} name
*/
function boolHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
var val = elem.getAttributeNode( name );
return val && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
/**
* Fetches attributes without interpolation
* http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
* @param {Element} elem
* @param {String} name
*/
function interpolationHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
/**
* Uses defaultValue to retrieve value in IE6/7
* @param {Element} elem
* @param {String} name
*/
function valueHandler( elem ) {
// Ignore the value *property* on inputs by using defaultValue
// Fallback to Sizzle.attr by returning undefined where appropriate
// XML does not need to be checked as this will not be assigned for XML documents
if ( elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns Returns -1 if a precedes b, 1 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.parentWindow;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
if ( parent && parent.frameElement ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
// Support: IE<8
// Prevent attribute/property "interpolation"
div.innerHTML = "<a href='#'></a>";
addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" );
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
addHandle( booleans, boolHandler, div.getAttribute("disabled") == null );
div.className = "i";
return !div.getAttribute("className");
});
// Support: IE<9
// Retrieving value should defer to defaultValue
support.input = assert(function( div ) {
div.innerHTML = "<input>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
});
// IE6/7 still return empty string for value,
// but are actually retrieving the property
addHandle( "value", valueHandler, support.attributes && support.input );
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( doc.createElement("div") ) & 1;
});
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined );
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Initialize against the default document
setDocument();
// Support: Chrome<<14
// Always assume duplicates if they aren't passed to the comparison function
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Finish early in limited (non-browser) environments
all = div.getElementsByTagName("*") || [];
a = div.getElementsByTagName("a")[ 0 ];
if ( !a || !a.style || !all.length ) {
return support;
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName("tbody").length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName("link").length;
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Will be defined later
support.inlineBlockNeedsLayout = false;
support.shrinkWrapBlocks = false;
support.pixelPosition = false;
support.deleteExpando = true;
support.noCloneEvent = true;
support.reliableMarginRight = true;
support.boxSizingReliable = true;
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: IE<9
// Iteration over object's inherited properties before its own.
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior.
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})({});
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"applet": true,
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
data = null,
i = 0,
elem = this[0];
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = ret.push( cur );
break;
}
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
})( window ); | michaelBenin/raptor-editor | src/dependencies/jquery.js | JavaScript | gpl-3.0 | 274,078 |
#include <iostream>
using namespace std;
#define FLOAT(name, value) float name = value
#define CONST_FLOAT(name, value) const FLOAT(name, value)
#define VAR_FLOAT(name) FLOAT(name, 0)
#define VAR_INT(name) int name = 0
#define DEFINE_LINEAR_EQUATION(n)\
VAR_FLOAT(a##n);\
VAR_FLOAT(b##n);\
VAR_FLOAT(c##n)\
#define READ(input) cin >> input
#define IS_LESS_THAN_EPSILON(diff) ((diff < EPSILON) && (diff > -EPSILON))
#define READ_LINEAR_EQUATION(n)\
READ(a##n);\
READ(b##n);\
READ(c##n)\
#define IS_ZERO(value) IS_LESS_THAN_EPSILON(value)
#define IS_NOT_ZERO(value) (!IS_LESS_THAN_EPSILON(value))
#define IS_NOT_ZERO_LINE(line) (IS_NOT_ZERO(a##line) || IS_NOT_ZERO(b##line) || IS_NOT_ZERO(c##line))
#define SOLUTION_PART_1(n, divisor) c##n / divisor##n
#define SOLUTION_PART_2(n, multiplier, found, divisor) (c##n - (multiplier##n * found)) / divisor##n
#define ONE_SOLUTION() solution = One
#define NO_SOLUTION() solution = No
#define GAUSE(n1, n2, n3, cnt , calc)\
CONST_FLOAT(k##n1, (-cnt##n2) / cnt##n1);\
CONST_FLOAT(calc##n3, (calc##n1 * k##n1) + calc##n2);\
CONST_FLOAT(c##n3, (c##n1 * k##n1) + c##n2)\
#define IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(zero, first, second, divisor1, divisor2, n1, n2)\
if(IS_ZERO(zero) && (solution == Many)) {\
if IS_ZERO(divisor1##n1) {\
NO_SOLUTION();\
} else {\
first = SOLUTION_PART_1(n1, divisor1);\
second = SOLUTION_PART_2(n2, divisor1, first, divisor2);\
ONE_SOLUTION();\
}\
}\
#define FIND_SOLUTION(n, first, second, k, divisor1, divisor2)\
CONST_FLOAT(first##n, SOLUTION_PART_1(k, divisor1));\
CONST_FLOAT(second##n, SOLUTION_PART_2(n, divisor1, first##n, divisor2))\
#define DIFF(F, f) CONST_FLOAT(DIFF_##F, f##1 - f##2)
#define PRINT(value) cout << value
#define PRINT_CASE(what, message)\
case what:\
PRINT(message);\
break\
#define IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(a, b, m)\
if((absWholePart >= a) && (absWholePart < b)) {\
multiplier = m;\
}\
#define FORMAT(num)\
sign = (num <= -EPSILON ? -1 : 1);\
wholePart = num + (sign * EPSILON);\
multiplier = 1;\
absWholePart = sign * wholePart;\
IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(0, 10, 10000)\
IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(10, 100, 1000)\
IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(100, 1000, 100)\
IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(1000, 10000, 10)\
floatPart = (int)((num + (sign * EPSILON)) * multiplier) - (wholePart * multiplier);\
num = ((float)floatPart / multiplier) + wholePart\
/* @begin */
enum Solution {
No,
One,
Many
};
CONST_FLOAT(EPSILON, 0.00001);
int main() {
DEFINE_LINEAR_EQUATION(1);
DEFINE_LINEAR_EQUATION(2);
VAR_FLOAT(x);
VAR_FLOAT(y);
Solution solution = Many;
READ_LINEAR_EQUATION(1);
READ_LINEAR_EQUATION(2);
if(IS_NOT_ZERO_LINE(1) && IS_NOT_ZERO_LINE(2)) {
IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(a1, y, x, b, a, 1, 2)
IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(a2, y, x, b, a, 2, 1)
IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(b1, x, y, a, b, 1, 2)
IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(b2, x, y, a, b, 2, 1)
if(solution == Many) {
GAUSE(1, 2, 3, a, b);
GAUSE(2, 1, 4, b, a);
if((IS_ZERO(b3) && IS_NOT_ZERO(c3)) || (IS_ZERO(a4) && IS_NOT_ZERO(c4))) {
NO_SOLUTION();
} else {
FIND_SOLUTION(1, y, x, 3, b, a);
FIND_SOLUTION(2, x, y, 4, a, b);
DIFF(X, x);
DIFF(Y, y);
if(IS_LESS_THAN_EPSILON(DIFF_X) && IS_LESS_THAN_EPSILON(DIFF_Y)) {
x = x1;
y = y1;
ONE_SOLUTION();
}
}
}
}
switch(solution) {
PRINT_CASE(No, "No solution");
PRINT_CASE(Many, "Many solutions");
case One:
VAR_INT(sign);
VAR_INT(wholePart);
VAR_INT(absWholePart);
VAR_INT(floatPart);
VAR_INT(multiplier);
FORMAT(x);
FORMAT(y);
PRINT(x) << ' ' << y;
break;
}
PRINT('\n');
return 0;
} | NoHomey/FMI-introduction-to-programming-course | homework1/task10.cc | C++ | gpl-3.0 | 4,135 |
/**
* Copyright (C) 2011 Whisper Systems
*
* 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.smssecure.smssecure.recipients;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import org.smssecure.smssecure.contacts.avatars.ContactPhotoFactory;
import org.smssecure.smssecure.database.CanonicalAddressDatabase;
import org.smssecure.smssecure.util.Util;
import org.whispersystems.libaxolotl.util.guava.Optional;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
public class RecipientFactory {
private static final RecipientProvider provider = new RecipientProvider();
public static Recipients getRecipientsForIds(Context context, String recipientIds, boolean asynchronous) {
if (TextUtils.isEmpty(recipientIds))
return new Recipients();
return getRecipientsForIds(context, Util.split(recipientIds, " "), asynchronous);
}
public static Recipients getRecipientsFor(Context context, List<Recipient> recipients, boolean asynchronous) {
long[] ids = new long[recipients.size()];
int i = 0;
for (Recipient recipient : recipients) {
ids[i++] = recipient.getRecipientId();
}
return provider.getRecipients(context, ids, asynchronous);
}
public static Recipients getRecipientsFor(Context context, Recipient recipient, boolean asynchronous) {
long[] ids = new long[1];
ids[0] = recipient.getRecipientId();
return provider.getRecipients(context, ids, asynchronous);
}
public static Recipient getRecipientForId(Context context, long recipientId, boolean asynchronous) {
return provider.getRecipient(context, recipientId, asynchronous);
}
public static Recipients getRecipientsForIds(Context context, long[] recipientIds, boolean asynchronous) {
return provider.getRecipients(context, recipientIds, asynchronous);
}
public static Recipients getRecipientsFromString(Context context, @NonNull String rawText, boolean asynchronous) {
StringTokenizer tokenizer = new StringTokenizer(rawText, ",");
List<String> ids = new LinkedList<>();
while (tokenizer.hasMoreTokens()) {
Optional<Long> id = getRecipientIdFromNumber(context, tokenizer.nextToken());
if (id.isPresent()) {
ids.add(String.valueOf(id.get()));
}
}
return getRecipientsForIds(context, ids, asynchronous);
}
private static Recipients getRecipientsForIds(Context context, List<String> idStrings, boolean asynchronous) {
long[] ids = new long[idStrings.size()];
int i = 0;
for (String id : idStrings) {
ids[i++] = Long.parseLong(id);
}
return provider.getRecipients(context, ids, asynchronous);
}
private static Optional<Long> getRecipientIdFromNumber(Context context, String number) {
number = number.trim();
if (number.isEmpty()) return Optional.absent();
if (hasBracketedNumber(number)) {
number = parseBracketedNumber(number);
}
return Optional.of(CanonicalAddressDatabase.getInstance(context).getCanonicalAddressId(number));
}
private static boolean hasBracketedNumber(String recipient) {
int openBracketIndex = recipient.indexOf('<');
return (openBracketIndex != -1) &&
(recipient.indexOf('>', openBracketIndex) != -1);
}
private static String parseBracketedNumber(String recipient) {
int begin = recipient.indexOf('<');
int end = recipient.indexOf('>', begin);
String value = recipient.substring(begin + 1, end);
return value;
}
public static void clearCache() {
provider.clearCache();
}
}
| matlink/SMSSecure | src/org/smssecure/smssecure/recipients/RecipientFactory.java | Java | gpl-3.0 | 4,267 |
/*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn 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.
*
* Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*
*/
package ai.grakn.generator;
import ai.grakn.concept.Label;
import ai.grakn.graql.admin.RelationPlayer;
import ai.grakn.graql.admin.VarPatternAdmin;
import static ai.grakn.graql.Graql.var;
/**
* @author Felix Chapman
*/
public class RelationPlayers extends AbstractGenerator<RelationPlayer> {
public RelationPlayers() {
super(RelationPlayer.class);
}
@Override
public RelationPlayer generate() {
if (random.nextBoolean()) {
return RelationPlayer.of(gen(VarPatternAdmin.class));
} else {
VarPatternAdmin varPattern;
if (random.nextBoolean()) {
varPattern = var().label(gen(Label.class)).admin();
} else {
varPattern = gen(VarPatternAdmin.class);
}
return RelationPlayer.of(varPattern, gen(VarPatternAdmin.class));
}
}
} | burukuru/grakn | grakn-test/test-integration/src/test/java/ai/grakn/generator/RelationPlayers.java | Java | gpl-3.0 | 1,612 |
package org.janus.miniforth;
import org.janus.data.DataContext;
public class Compare extends WordImpl {
public enum Comp {
EQ, NEQ, LT, GT, LEQ, GEQ
}
Comp comp;
public Compare(Comp comp) {
super(-1);
this.comp = comp;
}
@Override
public void perform(DataContext context) {
super.perform(context);
MiniForthContext withStack = (MiniForthContext) context;
Comparable a = (Comparable) withStack.pop();
Comparable b = (Comparable) withStack.pop();
boolean result = false;
if (a.getClass().equals(b.getClass())) {
result = compare(a, b);
} else {
throw new IllegalArgumentException("Vergleich nicht möglich");
}
withStack.pushBoolean(result);
}
private boolean compare(Comparable a, Comparable b) {
int c = a.compareTo(b);
if (c == 0) {
if (comp.equals(Comp.NEQ)) {
return false;
} else {
return comp.equals(Comp.EQ) || comp.equals(Comp.LEQ)
|| comp.equals(Comp.GEQ);
}
} else {
if (c > 0) {
return comp.equals(Comp.NEQ) || comp.equals(Comp.LEQ)
|| comp.equals(Comp.LT);
} else {
return comp.equals(Comp.NEQ) || comp.equals(Comp.GEQ)
|| comp.equals(Comp.GT);
}
}
}
}
| ThoNill/JanusMiniForth | JanusMiniForth/src/org/janus/miniforth/Compare.java | Java | gpl-3.0 | 1,226 |
/*
SuperCollider Qt IDE
Copyright (c) 2012 Jakob Leben & Tim Blechmann
http://www.audiosynth.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef SCIDE_SC_SYNTAX_HIGHLIGHTER_HPP_INCLUDED
#define SCIDE_SC_SYNTAX_HIGHLIGHTER_HPP_INCLUDED
#include "tokens.hpp"
#include <QSyntaxHighlighter>
#include <QVector>
namespace ScIDE {
namespace Settings { class Manager; }
class Main;
enum SyntaxFormat
{
PlainFormat,
ClassFormat,
KeywordFormat,
BuiltinFormat,
PrimitiveFormat,
SymbolFormat,
StringFormat,
CharFormat,
NumberFormat,
EnvVarFormat,
CommentFormat,
FormatCount
};
struct SyntaxRule
{
SyntaxRule(): type(Token::Unknown) {}
SyntaxRule( Token::Type t, const QString &s ): type(t), expr(s) {}
Token::Type type;
QRegExp expr;
};
class SyntaxHighlighterGlobals : public QObject
{
Q_OBJECT
public:
SyntaxHighlighterGlobals( Main *, Settings::Manager * settings );
inline const QTextCharFormat * formats() const
{
return mFormats;
}
inline const QTextCharFormat & format( SyntaxFormat type ) const
{
return mFormats[type];
}
inline static const SyntaxHighlighterGlobals * instance() { Q_ASSERT(mInstance); return mInstance; }
public Q_SLOTS:
void applySettings( Settings::Manager * );
Q_SIGNALS:
void syntaxFormatsChanged();
private:
friend class SyntaxHighlighter;
void initSyntaxRules();
void initKeywords();
void initBuiltins();
void applySettings( Settings::Manager*, const QString &key, SyntaxFormat );
QTextCharFormat mFormats[FormatCount];
QVector<SyntaxRule> mInCodeRules;
QRegExp mInSymbolRegexp, mInStringRegexp;
static SyntaxHighlighterGlobals *mInstance;
};
class SyntaxHighlighter:
public QSyntaxHighlighter
{
Q_OBJECT
static const int inCode = 0;
static const int inString = 1;
static const int inSymbol = 2;
static const int inComment = 100;
// NOTE: Integers higher than inComment are reserved for multi line comments,
// and indicate the comment nesting level!
public:
SyntaxHighlighter(QTextDocument *parent = 0);
private:
void highlightBlock(const QString &text);
void highlightBlockInCode(const QString& text, int & currentIndex, int & currentState);
void highlightBlockInString(const QString& text, int & currentIndex, int & currentState);
void highlightBlockInSymbol(const QString& text, int & currentIndex, int & currentState);
void highlightBlockInComment(const QString& text, int & currentIndex, int & currentState);
Token::Type findMatchingRule(QString const & text, int & currentIndex, int & lengthOfMatch);
const SyntaxHighlighterGlobals *mGlobals;
};
}
#endif
| wdkk/iSuperColliderKit | editors/sc-ide/widgets/code_editor/highlighter.hpp | C++ | gpl-3.0 | 3,435 |
/*
* Copyright (C) 2018 The "MysteriumNetwork/node" Authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 service
import (
"encoding/json"
"errors"
log "github.com/cihub/seelog"
"github.com/mysteriumnetwork/node/communication"
"github.com/mysteriumnetwork/node/identity"
"github.com/mysteriumnetwork/node/market"
"github.com/mysteriumnetwork/node/session"
)
var (
// ErrorLocation error indicates that action (i.e. disconnect)
ErrorLocation = errors.New("failed to detect service location")
// ErrUnsupportedServiceType indicates that manager tried to create an unsupported service type
ErrUnsupportedServiceType = errors.New("unsupported service type")
)
// Service interface represents pluggable Mysterium service
type Service interface {
Serve(providerID identity.Identity) error
Stop() error
ProvideConfig(publicKey json.RawMessage) (session.ServiceConfiguration, session.DestroyCallback, error)
}
// DialogWaiterFactory initiates communication channel which waits for incoming dialogs
type DialogWaiterFactory func(providerID identity.Identity, serviceType string) (communication.DialogWaiter, error)
// DialogHandlerFactory initiates instance which is able to handle incoming dialogs
type DialogHandlerFactory func(market.ServiceProposal, session.ConfigNegotiator) communication.DialogHandler
// DiscoveryFactory initiates instance which is able announce service discoverability
type DiscoveryFactory func() Discovery
// Discovery registers the service to the discovery api periodically
type Discovery interface {
Start(ownIdentity identity.Identity, proposal market.ServiceProposal)
Stop()
Wait()
}
// NewManager creates new instance of pluggable instances manager
func NewManager(
serviceRegistry *Registry,
dialogWaiterFactory DialogWaiterFactory,
dialogHandlerFactory DialogHandlerFactory,
discoveryFactory DiscoveryFactory,
) *Manager {
return &Manager{
serviceRegistry: serviceRegistry,
servicePool: NewPool(),
dialogWaiterFactory: dialogWaiterFactory,
dialogHandlerFactory: dialogHandlerFactory,
discoveryFactory: discoveryFactory,
}
}
// Manager entrypoint which knows how to start pluggable Mysterium instances
type Manager struct {
dialogWaiterFactory DialogWaiterFactory
dialogHandlerFactory DialogHandlerFactory
serviceRegistry *Registry
servicePool *Pool
discoveryFactory DiscoveryFactory
}
// Start starts an instance of the given service type if knows one in service registry.
// It passes the options to the start method of the service.
// If an error occurs in the underlying service, the error is then returned.
func (manager *Manager) Start(providerID identity.Identity, serviceType string, options Options) (id ID, err error) {
service, proposal, err := manager.serviceRegistry.Create(serviceType, options)
if err != nil {
return id, err
}
dialogWaiter, err := manager.dialogWaiterFactory(providerID, serviceType)
if err != nil {
return id, err
}
providerContact, err := dialogWaiter.Start()
if err != nil {
return id, err
}
proposal.SetProviderContact(providerID, providerContact)
dialogHandler := manager.dialogHandlerFactory(proposal, service)
if err = dialogWaiter.ServeDialogs(dialogHandler); err != nil {
return id, err
}
discovery := manager.discoveryFactory()
discovery.Start(providerID, proposal)
instance := Instance{
state: Starting,
options: options,
service: service,
proposal: proposal,
dialogWaiter: dialogWaiter,
discovery: discovery,
}
id, err = manager.servicePool.Add(&instance)
if err != nil {
return id, err
}
go func() {
instance.state = Running
serveErr := service.Serve(providerID)
if serveErr != nil {
log.Error("Service serve failed: ", serveErr)
}
instance.state = NotRunning
stopErr := manager.servicePool.Stop(id)
if stopErr != nil {
log.Error("Service stop failed: ", stopErr)
}
discovery.Wait()
}()
return id, nil
}
// List returns array of running service instances.
func (manager *Manager) List() map[ID]*Instance {
return manager.servicePool.List()
}
// Kill stops all services.
func (manager *Manager) Kill() error {
return manager.servicePool.StopAll()
}
// Stop stops the service.
func (manager *Manager) Stop(id ID) error {
return manager.servicePool.Stop(id)
}
// Service returns a service instance by requested id.
func (manager *Manager) Service(id ID) *Instance {
return manager.servicePool.Instance(id)
}
| MysteriumNetwork/node | core/service/manager.go | GO | gpl-3.0 | 5,078 |
/*
* This file is part of Track It!.
* Copyright (C) 2013 Henrique Malheiro
* Copyright (C) 2015 Pedro Gomes
*
* TrackIt! 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.
*
* Track It! 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 Track It!. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.trackit.business.domain;
import java.util.ArrayList;
import java.util.List;
import com.trackit.business.exception.TrackItException;
import com.trackit.presentation.event.Event;
import com.trackit.presentation.event.EventManager;
import com.trackit.presentation.event.EventPublisher;
public class Folder extends TrackItBaseType implements DocumentItem {
private String name;
private List<GPSDocument> documents;
public Folder(String name) {
super();
this.name = name;
documents = new ArrayList<GPSDocument>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<GPSDocument> getDocuments() {
return documents;
}
public void add(GPSDocument document) {
documents.add(document);
}
public void remove(GPSDocument document) {
documents.remove(document);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Folder other = (Folder) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return String.format("Folder [name=%s]", name);
}
@Override
public void publishSelectionEvent(EventPublisher publisher) {
EventManager.getInstance().publish(publisher, Event.FOLDER_SELECTED, this);
}
@Override
public void accept(Visitor visitor) throws TrackItException {
visitor.visit(this);
}
}
| Spaner/TrackIt | src/main/java/com/trackit/business/domain/Folder.java | Java | gpl-3.0 | 2,498 |
<?php namespace eduTrac\Classes\Models;
if ( ! defined('BASE_PATH') ) exit('No direct script access allowed');
/**
* Profile Model
*
* PHP 5.4+
*
* eduTrac(tm) : Student Information System (http://www.7mediaws.org/)
* @copyright (c) 2013 7 Media Web Solutions, LLC
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License, version 3
* @link http://www.7mediaws.org/
* @since 3.0.0
* @package eduTrac
* @author Joshua Parker <josh@7mediaws.org>
*/
use \eduTrac\Classes\Core\DB;
use \eduTrac\Classes\Libraries\Util;
class ProfileModel {
private $_auth;
public function __construct() {
$this->_auth = new \eduTrac\Classes\Libraries\Cookies;
}
public function index() {}
public function runProfile($data) {
$update1 = [
"fname" => $data['fname'],"lname" => $data['lname'],
"mname" => Util::_trim($data['mname']),"email" => Util::_trim($data['email']),
"ssn" => Util::_trim($data['ssn']),"dob" => $data['dob']
];
$bind = [ ":personID" => $this->_auth->getPersonField('personID') ];
$q = DB::inst()->update("person",$update1,"personID = :personID",$bind);
if(!empty($data['password'])) {
$update2 = ["password" => et_hash_password($data['password'])];
DB::inst()->update("person",$update2,"personID = :personID",$bind);
}
redirect( BASE_URL . 'profile/' );
}
public function __destruct() {
DB::inst()->close();
}
} | vb2005xu/eduTrac | eduTrac/Classes/Models/ProfileModel.php | PHP | gpl-3.0 | 2,264 |
using System;
namespace UnstuckMeLoggers
{
public enum ERR_TYPES_SERVER
{
// if you add one of these please add it in the switch statement to be handled
SERVER_GUI_LOGIN,
SERVER_GUI_LOGOUT,
SERVER_CONNECTION_ERROR,
SERVER_GUI_INTERACTION_ERROR,
SERVER_START,
SERVER_STOP,
DATABASE_RETURN_ERROR,
DATABASE_CONNECTION_ERROR
}
internal class ErrContainerServer
{
string i_ErrorMsg; // the error message string contained by the thrown exception
string i_ErrTypeStartMark; // the xml like tag that defines the start of the error
string i_ErrTypeEndMark; // the xml like tag that defines the end of the error
string i_ErrorTime; // the string representaition of the time the errors occurance
string i_AdditionalInfo; // a string that holds any additional info you would like logged such as what caused the error
internal ErrContainerServer(string ErrorMsg, string ErrTypeStartMark, string ErrTypeEndMark, string ErrorTime, string AdditionalInfo = null)
{
i_ErrorMsg = ErrorMsg;
i_ErrTypeStartMark = ErrTypeStartMark;
i_ErrTypeEndMark = ErrTypeEndMark;
i_ErrorTime = ErrorTime;
i_AdditionalInfo = AdditionalInfo;
}
public override string ToString()
{
string temp = i_ErrTypeStartMark + Environment.NewLine + "\t" + "<ErrMsg=" + i_ErrorMsg + "/>";
if (i_AdditionalInfo != null)
temp = temp + Environment.NewLine + "<AdditionalInfo=" + i_AdditionalInfo + "/>";
temp = temp + Environment.NewLine + "\t" + "<ErrTime=" + i_ErrorTime + "/>" + Environment.NewLine + i_ErrTypeEndMark;
return temp;
}
}
}
| UnstuckME/UnstuckME | UnstuckME/UnstuckMeLoggers/ErrContainerServer.cs | C# | gpl-3.0 | 1,846 |
import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
| IODisrupt/OmegaBot | cogs/runescapecompare.py | Python | gpl-3.0 | 2,978 |
package com.snail.webgame.game.protocal.relation.getRequest;
import org.epilot.ccf.config.Resource;
import org.epilot.ccf.core.processor.ProtocolProcessor;
import org.epilot.ccf.core.processor.Request;
import org.epilot.ccf.core.processor.Response;
import org.epilot.ccf.core.protocol.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.snail.webgame.game.common.GameMessageHead;
import com.snail.webgame.game.common.util.Command;
import com.snail.webgame.game.protocal.relation.service.RoleRelationMgtService;
public class GetAddRequestProcessor extends ProtocolProcessor{
private static Logger logger = LoggerFactory.getLogger("logs");
private RoleRelationMgtService roleRelationMgtService;
public void setRoleRelationMgtService(RoleRelationMgtService roleRelationMgtService) {
this.roleRelationMgtService = roleRelationMgtService;
}
@Override
public void execute(Request request, Response response) {
Message msg = request.getMessage();
GameMessageHead header = (GameMessageHead) msg.getHeader();
header.setMsgType(Command.GET_ADD_REQUEST_RESP);
int roleId = header.getUserID0();
GetAddRequestReq req = (GetAddRequestReq) msg.getBody();
GetAddRequestResp resp = roleRelationMgtService.getAddFriendRequestList(roleId, req);
msg.setHeader(header);
msg.setBody(resp);
response.write(msg);
if(logger.isInfoEnabled()){
logger.info(Resource.getMessage("game", "GAME_ROLE_RELATION_INFO_4") + ": result=" + resp.getResult() + ",roleId="
+ roleId);
}
}
}
| bozhbo12/demo-spring-server | spring-game/src/main/java/com/spring/game/game/protocal/relation/getRequest/GetAddRequestProcessor.java | Java | gpl-3.0 | 1,541 |
'use strict';
var ParameterDef = function(object) {
this.id = object.id;
this.summary = object.summary;
this.description = object.description;
this.type = object.type;
this.mandatory = object.mandatory;
this.defaultValue = object.defaultValue;
};
module.exports = ParameterDef;
| linagora/mupee | backend/rules/parameter-definition.js | JavaScript | gpl-3.0 | 292 |
/*******************************************************************************
* Copyright (c) 2000, 2013 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.core;
import java.util.ArrayList;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IModuleDescription;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
/**
* @see IJavaElementRequestor
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class JavaElementRequestor implements IJavaElementRequestor {
/**
* True if this requestor no longer wants to receive
* results from its <code>IRequestorNameLookup</code>.
*/
protected boolean canceled= false;
/**
* A collection of the resulting fields, or <code>null</code>
* if no field results have been received.
*/
protected ArrayList fields= null;
/**
* A collection of the resulting initializers, or <code>null</code>
* if no initializer results have been received.
*/
protected ArrayList initializers= null;
/**
* A collection of the resulting member types, or <code>null</code>
* if no member type results have been received.
*/
protected ArrayList memberTypes= null;
/**
* A collection of the resulting methods, or <code>null</code>
* if no method results have been received.
*/
protected ArrayList methods= null;
/**
* A collection of the resulting package fragments, or <code>null</code>
* if no package fragment results have been received.
*/
protected ArrayList packageFragments= null;
/**
* A collection of the resulting types, or <code>null</code>
* if no type results have been received.
*/
protected ArrayList types= null;
/**
* A collection of the resulting modules, or <code>null</code>
* if no module results have been received
*/
protected ArrayList<IModuleDescription> modules = null;
/**
* Empty arrays used for efficiency
*/
protected static final IField[] EMPTY_FIELD_ARRAY= new IField[0];
protected static final IInitializer[] EMPTY_INITIALIZER_ARRAY= new IInitializer[0];
protected static final IType[] EMPTY_TYPE_ARRAY= new IType[0];
protected static final IPackageFragment[] EMPTY_PACKAGE_FRAGMENT_ARRAY= new IPackageFragment[0];
protected static final IMethod[] EMPTY_METHOD_ARRAY= new IMethod[0];
protected static final IModuleDescription[] EMPTY_MODULE_ARRAY= new IModuleDescription[0];
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptField(IField field) {
if (this.fields == null) {
this.fields= new ArrayList();
}
this.fields.add(field);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptInitializer(IInitializer initializer) {
if (this.initializers == null) {
this.initializers= new ArrayList();
}
this.initializers.add(initializer);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptMemberType(IType type) {
if (this.memberTypes == null) {
this.memberTypes= new ArrayList();
}
this.memberTypes.add(type);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptMethod(IMethod method) {
if (this.methods == null) {
this.methods = new ArrayList();
}
this.methods.add(method);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptPackageFragment(IPackageFragment packageFragment) {
if (this.packageFragments== null) {
this.packageFragments= new ArrayList();
}
this.packageFragments.add(packageFragment);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptType(IType type) {
if (this.types == null) {
this.types= new ArrayList();
}
this.types.add(type);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptModule(IModuleDescription module) {
if (this.modules == null) {
this.modules= new ArrayList();
}
this.modules.add(module);
}
/**
* @see IJavaElementRequestor
*/
public IField[] getFields() {
if (this.fields == null) {
return EMPTY_FIELD_ARRAY;
}
int size = this.fields.size();
IField[] results = new IField[size];
this.fields.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IInitializer[] getInitializers() {
if (this.initializers == null) {
return EMPTY_INITIALIZER_ARRAY;
}
int size = this.initializers.size();
IInitializer[] results = new IInitializer[size];
this.initializers.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IType[] getMemberTypes() {
if (this.memberTypes == null) {
return EMPTY_TYPE_ARRAY;
}
int size = this.memberTypes.size();
IType[] results = new IType[size];
this.memberTypes.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IMethod[] getMethods() {
if (this.methods == null) {
return EMPTY_METHOD_ARRAY;
}
int size = this.methods.size();
IMethod[] results = new IMethod[size];
this.methods.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IPackageFragment[] getPackageFragments() {
if (this.packageFragments== null) {
return EMPTY_PACKAGE_FRAGMENT_ARRAY;
}
int size = this.packageFragments.size();
IPackageFragment[] results = new IPackageFragment[size];
this.packageFragments.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IType[] getTypes() {
if (this.types== null) {
return EMPTY_TYPE_ARRAY;
}
int size = this.types.size();
IType[] results = new IType[size];
this.types.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IModuleDescription[] getModules() {
if (this.modules == null) {
return EMPTY_MODULE_ARRAY;
}
int size = this.modules.size();
IModuleDescription[] results = new IModuleDescription[size];
this.modules.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
@Override
public boolean isCanceled() {
return this.canceled;
}
/**
* Reset the state of this requestor.
*/
public void reset() {
this.canceled = false;
this.fields = null;
this.initializers = null;
this.memberTypes = null;
this.methods = null;
this.packageFragments = null;
this.types = null;
}
/**
* Sets the #isCanceled state of this requestor to true or false.
*/
public void setCanceled(boolean b) {
this.canceled= b;
}
}
| Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementRequestor.java | Java | gpl-3.0 | 6,654 |
import string
import ast
from state_machine import PSM, Source
class SpecialPattern:
individual_chars = ('t', 'n', 'v', 'f', 'r', '0')
range_chars = ('d', 'D', 'w', 'W', 's', 'S')
special_chars = ('^', '$', '[', ']', '(', ')', '{', '}', '\\', '.', '*',
'?', '+', '|', '.')
restrict_special_chars = ('\\', '[', ']')
posix_classes = ("alnum", "alpha", "blank", "cntrl", "digit", "graph",
"lower", "print", "punct", "space", "upper", "xdigit",
"d", "w", "s")
min_len_posix_class = 1
#-------------------------------------
# Group
class WrappedGroup:
def __init__(self):
self.group = ast.Group()
self.is_alt = False
def add(self, other):
if self.is_alt:
last_alt = self.alt.parts[-1] + (other,)
self.alt.parts = self.alt.parts[:-1] + (last_alt,)
else:
self.group.seq = self.group.seq + (other,)
@property
def alt(self) -> ast.Alternative:
assert self.is_alt
return self.group.seq[0]
def collapse_alt(self):
if self.is_alt:
self.alt.parts = self.alt.parts + ((),)
else:
self.is_alt = True
first_alt_elems = self.group.seq
self.group.seq = (ast.Alternative(),)
self.alt.parts = (first_alt_elems,())
class OpeningOfGroup:
def __init__(self, parent: None, initial: bool=False):
self.is_initial = initial
self.parent = parent # OpeningOfGroup or ContentOfGroup
self.g = WrappedGroup()
self.content_of_initial = None
# forward of function
self.add = self.g.add
# if this group is the initial, their is no parent but we must refer
# to itself as the returning state
# but if it is a nested group, it must be added into its global group
if self.is_initial:
self.content_of_initial = ContentOfGroup(self, initial)
else:
self.parent.add(self.g.group)
def next(self, psm: PSM):
if not self.is_initial and psm.char == "?":
return FirstOptionOfGroup(self)
elif psm.char == ")":
if self.is_initial:
psm.error = 'unexpected ")"'
else:
return self.parent
elif psm.char == "(":
return OpeningOfGroup(self)
elif self.is_initial:
return self.content_of_initial.next(psm)
else:
t = ContentOfGroup(self)
return t.next(psm)
class FirstOptionOfGroup:
def __init__(self, parent: OpeningOfGroup):
self.parent = parent
def next(self, psm: PSM):
if psm.char == ":":
self.parent.g.group.ignored = True
return ContentOfGroup(self.parent)
elif psm.char == "!":
self.parent.g.group.lookhead = ast.Group.NegativeLookhead
return ContentOfGroup(self.parent)
elif psm.char == "=":
self.parent.g.group.lookhead = ast.Group.PositiveLookhead
return ContentOfGroup(self.parent)
elif psm.char == "<":
self.parent.g.group.name = ""
return NameOfGroup(self.parent)
else:
psm.error = 'expected ":", "!", "<" or "="'
class NameOfGroup:
def __init__(self, parent: OpeningOfGroup):
self.parent = parent
def next(self, psm: PSM):
if psm.char.isalpha() or psm.char == "_":
self.parent.g.group.name += psm.char
return self
elif psm.char == ">":
return self.parent
else:
psm.error = 'expected a letter, "_" or ">"'
class ContentOfGroup:
NotQuantified = 0
Quantified = 1
UngreedyQuantified = 2
def __init__(self, parent: OpeningOfGroup, initial: bool=False):
self.parent = parent
self.is_initial = initial
self.limited_prev = parent if initial else self
self.quantified = ContentOfGroup.NotQuantified
# forward of function
self.add = self.parent.add
def next(self, psm: PSM):
quantified = self.quantified
self.quantified = ContentOfGroup.NotQuantified
if psm.char == ")":
if self.is_initial:
psm.error = "unbalanced parenthesis"
else:
return self.parent.parent
elif psm.char == "(":
return OpeningOfGroup(self.limited_prev)
elif psm.char == "^":
self.add(ast.MatchBegin())
return self.limited_prev
elif psm.char == "$":
self.add(ast.MatchEnd())
return self.limited_prev
elif psm.char == ".":
t = ast.PatternChar()
t.pattern = psm.char
self.add(t)
return self.limited_prev
elif psm.char == "\\":
return EscapedChar(self.limited_prev,
as_single_chars=SpecialPattern.special_chars)
elif psm.char == "[":
return CharClass(self.limited_prev)
elif psm.char == "|":
self.parent.g.collapse_alt()
return self.limited_prev
# >>> Quantifiers
elif psm.char == "?" and quantified == ContentOfGroup.NotQuantified:
self.quantified = ContentOfGroup.Quantified
last = self._last_or_fail(psm)
if last:
last.quantifier = ast.NoneOrOnce()
return self.limited_prev
elif psm.char == "*" and quantified == ContentOfGroup.NotQuantified:
self.quantified = ContentOfGroup.Quantified
last = self._last_or_fail(psm)
if last:
last.quantifier = ast.NoneOrMore()
return self.limited_prev
elif psm.char == "+" and quantified == ContentOfGroup.NotQuantified:
self.quantified = ContentOfGroup.Quantified
last = self._last_or_fail(psm)
if last:
last.quantifier = ast.OneOrMore()
return self.limited_prev
elif psm.char == "{" and quantified == ContentOfGroup.NotQuantified:
self.quantified = ContentOfGroup.Quantified
t = MinimumOfRepetition(self.limited_prev)
last = self._last_or_fail(psm)
if last:
last.quantifier = t.between
return t
elif psm.char == "?" and quantified == ContentOfGroup.Quantified:
self.quantified = ContentOfGroup.UngreedyQuantified
last = self._last_or_fail(psm)
if last:
last.quantifier.greedy = False
return self.limited_prev
elif quantified == ContentOfGroup.Quantified:
psm.error = "unexpected quantifier"
elif quantified == ContentOfGroup.UngreedyQuantified:
psm.error = "quantifier repeated"
# <<< Quantifier
else:
t = ast.SingleChar()
t.char = psm.char
self.add(t)
return self.limited_prev
def _last_or_fail(self, psm: PSM):
if self.parent.g.group.seq:
return self.parent.g.group.seq[-1]
else:
psm.error = "nothing to repeat"
class MinimumOfRepetition:
def __init__(self, parent: ContentOfGroup):
self.parent = parent
self.between = ast.Between()
self.min = []
def next(self, psm: PSM):
if psm.char.isdigit():
self.min.append(psm.char)
return self
elif psm.char == ",":
self._interpret()
return MaximumOfRepetition(self)
elif psm.char == "}":
self._interpret()
return self.parent
else:
psm.error = 'expected digit, "," or "}"'
def _interpret(self):
if not self.min:
return
try:
count = int("".join(self.min))
except ValueError:
assert False, "internal error: cannot convert to number minimum of repetition"
self.between.min = count
class MaximumOfRepetition:
def __init__(self, repeat: MinimumOfRepetition):
self.repeat = repeat
self.max = []
def next(self, psm: PSM):
if psm.char.isdigit():
self.max.append(psm.char)
return self
elif psm.char == "}":
self._interpret()
return self.repeat.parent
else:
psm.error = 'expected digit, "," or "}"'
def _interpret(self):
if not self.max:
return
try:
count = int("".join(self.max))
except ValueError:
assert False, "internal error: cannot convert to number maximum of repetition"
self.repeat.between.max = count
#--------------------------------------
# Escaping
class EscapedChar:
def __init__(self, prev, as_single_chars=(), as_pattern_chars=()):
self.prev = prev # ContentOfGroup or CharClass
self.single_chars = as_single_chars
self.pattern_chars = as_pattern_chars
def next(self, psm: PSM):
if psm.char in SpecialPattern.individual_chars \
or psm.char in SpecialPattern.range_chars \
or psm.char in self.pattern_chars:
t = ast.PatternChar()
t.pattern = psm.char
self.prev.add(t)
return self.prev
elif psm.char in self.single_chars:
t = ast.SingleChar()
t.char = psm.char
self.prev.add(t)
return self.prev
elif psm.char == "x":
return AsciiChar(self.prev)
elif psm.char == "u":
return UnicodeChar(self.prev)
else:
psm.error = "unauthorized escape of {}".format(psm.char)
class AsciiChar:
def __init__(self, prev):
self.prev = prev # ContentOfGroup or CharClass
self.pattern = ast.PatternChar()
self.pattern.type = ast.PatternChar.Ascii
self.prev.add(self.pattern)
def next(self, psm: PSM):
if psm.char in string.hexdigits:
self.pattern.pattern += psm.char
count = len(self.pattern.pattern)
return self.prev if count >= 2 else self
else:
psm.error = "expected ASCII hexadecimal character"
class UnicodeChar:
def __init__(self, prev):
self.prev = prev # ContentOfGroup or CharClass
self.pattern = ast.PatternChar()
self.pattern.type = ast.PatternChar.Unicode
self.prev.add(self.pattern)
def next(self, psm: PSM):
if psm.char in string.hexdigits:
self.pattern.pattern += psm.char
count = len(self.pattern.pattern)
return self.prev if count >= 4 else self
else:
psm.error = "expected ASCII hexadecimal character"
#-------------------------------------
# Character class
class WrappedCharClass:
def __init__(self):
# ast is CharClass or may be changed to PatternClass in one case
self.ast = ast.CharClass()
def add(self, other):
assert isinstance(self.ast, ast.CharClass)
self.ast.elems = self.ast.elems + (other,)
def pop(self):
assert isinstance(self.ast, ast.CharClass)
last = self.ast.elems[-1]
self.ast.elems = self.ast.elems[:-1]
return last
class CharClass:
def __init__(self, prev):
self.prev = prev # ContentOfGroup or CharClass
self.q = WrappedCharClass()
# forward function
self.add = self.q.add
self.next_is_range = False
self.empty = True
self.can_mutate = True
def next(self, psm: PSM):
this_should_be_range = self.next_is_range
self.next_is_range = False
this_is_empty = self.empty
self.empty = False
if psm.char == "\\":
self.can_mutate = False
self.next_is_range = this_should_be_range
return EscapedChar(self,
as_single_chars=SpecialPattern.restrict_special_chars)
elif this_should_be_range and psm.char != "]":
assert isinstance(self.q.ast, ast.CharClass)
assert len(self.q.ast.elems) >= 1
self.next_is_range = False
t = ast.Range()
t.begin = self.q.pop()
t.end = ast.SingleChar()
t.end.char = psm.char
self.q.add(t)
return self
elif psm.char == "^":
# if at the begining, it has a special meaning
if this_is_empty:
self.can_mutate = False
self.q.ast.negate = True
else:
t = ast.SingleChar()
t.char = psm.char
self.q.add(t)
return self
elif psm.char == "]":
if this_should_be_range:
t = ast.SingleChar()
t.char = "-"
self.q.add(t)
else:
self.mutate_if_posix_like()
self.prev.add(self.q.ast)
return self.prev
elif psm.char == "[":
return CharClass(self)
elif psm.char == "-" and len(self.q.ast.elems) >= 1:
self.next_is_range = True
return self
else:
t = ast.SingleChar()
t.char = psm.char
self.q.add(t)
return self
def mutate_if_posix_like(self):
"""
Change from character class to pattern char if the content is matching
POSIX-like classe.
"""
assert isinstance(self.q.ast, ast.CharClass)
# put in this variable everything that had happen but not saved into
# the single char object
# because mutation is only possible if the exact string of the content
# match a pre-definied list, so if an unlogged char is consumed, it
# must prevent mutation
if not self.can_mutate:
return
if len(self.q.ast.elems) < SpecialPattern.min_len_posix_class + 2:
return
opening = self.q.ast.elems[0]
if not isinstance(opening, ast.SingleChar) or opening.char != ":":
return
closing = self.q.ast.elems[-1]
if not isinstance(closing, ast.SingleChar) or closing.char != ":":
return
is_only_ascii = lambda x: (isinstance(x, ast.SingleChar)
and len(x.char) == 1
and x.char.isalpha())
class_may_be_a_word = not any(
not is_only_ascii(x) for x in self.q.ast.elems[1:-1])
if not class_may_be_a_word:
return
word = "".join(s.char for s in self.q.ast.elems[1:-1])
if word not in SpecialPattern.posix_classes:
return
t = ast.PatternChar()
t.pattern = word
t.type = ast.PatternChar.Posix
self.q.ast = t
#-------------------------------------
def parse(expr, **kw):
sm = PSM()
sm.source = Source(expr)
sm.starts_with(OpeningOfGroup(parent=None, initial=True))
sm.pre_action = kw.get("pre_action", None)
sm.post_action = kw.get("post_action", None)
sm.parse()
return sm.state.g.group
| VaysseB/id_generator | src/parser.py | Python | gpl-3.0 | 15,217 |
Fox.define('views/email/fields/from-email-address', 'views/fields/link', function (Dep) {
return Dep.extend({
listTemplate: 'email/fields/from-email-address/detail',
detailTemplate: 'email/fields/from-email-address/detail',
});
});
| ilovefox8/zhcrm | client/src/views/email/fields/from-email-address.js | JavaScript | gpl-3.0 | 261 |
export function Bounds(width, height) {
this.width = width;
this.height = height;
}
Bounds.prototype.equals = function(o) {
return ((o != null) && (this.width == o.width) && (this.height == o.height));
};
| elkonurbaev/nine-e | src/utils/Bounds.js | JavaScript | gpl-3.0 | 219 |
import {
ATTENDANCE_STATUS_CONFIG_ID,
AttendanceStatusType,
NullAttendanceStatusType,
} from "./attendance-status";
import { DatabaseField } from "../../../core/entity/database-field.decorator";
/**
* Simple relationship object to represent an individual child's status at an event including context information.
*/
export class EventAttendance {
private _status: AttendanceStatusType;
@DatabaseField({
dataType: "configurable-enum",
innerDataType: ATTENDANCE_STATUS_CONFIG_ID,
})
get status(): AttendanceStatusType {
return this._status;
}
set status(value) {
if (typeof value === "object") {
this._status = value;
} else {
this._status = NullAttendanceStatusType;
}
}
@DatabaseField() remarks: string;
constructor(
status: AttendanceStatusType = NullAttendanceStatusType,
remarks: string = ""
) {
this.status = status;
this.remarks = remarks;
}
}
| NGO-DB/ndb-core | src/app/child-dev-project/attendance/model/event-attendance.ts | TypeScript | gpl-3.0 | 934 |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';
import 'bootstrap-vue/dist/bootstrap-vue.css';
import 'bootstrap/dist/css/bootstrap.css';
import { mapActions } from 'vuex';
import App from './App';
import websock from './websock';
import * as mtype from './store/mutation-types';
import store from './store';
Vue.config.productionTip = false;
Vue.use(BootstrapVue);
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
store,
components: { App },
created() {
websock.connect(message => this.newMessage(message));
setInterval(() => { store.commit(mtype.UPDATE_CALLS_DUR); }, 1000);
},
methods: mapActions(['newMessage']),
});
| staskobzar/amiws | web_root_vue/src/main.js | JavaScript | gpl-3.0 | 826 |
#include "hal/time/time.hpp"
namespace hal
{
namespace time
{
static u64 currentTime = 0;
u64 milliseconds()
{
return currentTime;
}
} // namespace time
} // namespace hal
namespace stub
{
namespace time
{
void setCurrentTime(u64 milliseconds)
{
hal::time::currentTime = milliseconds;
}
void forwardTime(u64 milliseconds)
{
hal::time::currentTime += milliseconds;
}
} // namespace time
} // namespace stub
| matgla/AquaLampWiFiModule | test/UT/src/stub/timeStub.cpp | C++ | gpl-3.0 | 464 |
<?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/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_utils.php';
require_once 'cc_version_base.php';
require_once 'cc_organization.php';
/**
* Version 1 class of Common Cartridge
*
*/
class cc_version1 extends cc_version_base {
const webcontent = 'webcontent';
const questionbank = 'imsqti_xmlv1p2/imscc_xmlv1p0/question-bank';
const assessment = 'imsqti_xmlv1p2/imscc_xmlv1p0/assessment';
const associatedcontent = 'associatedcontent/imscc_xmlv1p0/learning-application-resource';
const discussiontopic = 'imsdt_xmlv1p0';
const weblink = 'imswl_xmlv1p0';
public static $checker = array(self::webcontent,
self::assessment,
self::associatedcontent,
self::discussiontopic,
self::questionbank,
self::weblink);
/**
* Validate if the type are valid or not
*
* @param string $type
* @return bool
*/
public function valid($type) {
return in_array($type, self::$checker);
}
public function __construct() {
$this->ccnamespaces = array('imscc' => 'http://www.imsglobal.org/xsd/imscc/imscp_v1p1',
'lomimscc' => 'http://ltsc.ieee.org/xsd/imscc/LOM',
'lom' => 'http://ltsc.ieee.org/xsd/LOM',
'voc' => 'http://ltsc.ieee.org/xsd/LOM/vocab',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance'
);
$this->ccnsnames = array('imscc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/imscp_v1p2_localised.xsd' ,
'lom' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_2/lomLoose_localised.xsd' ,
'lomimscc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_1/lomLoose_localised.xsd',
'voc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_2/vocab/loose.xsd'
);
$this->ccversion = '1.0.0';
$this->camversion = '1.0.0';
$this->_generator = 'Moodle 2 Common Cartridge generator';
}
protected function on_create(DOMDocument &$doc, $rootmanifestnode=null,$nmanifestID=null) {
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$this->manifestID = is_null($nmanifestID) ? cc_helpers::uuidgen('M_') : $nmanifestID;
$mUUID = $doc->createAttribute('identifier');
$mUUID->nodeValue = $this->manifestID;
if (is_null($rootmanifestnode)) {
if (!empty($this->_generator)) {
$comment = $doc->createComment($this->_generator);
$doc->appendChild($comment);
}
$rootel = $doc->createElementNS($this->ccnamespaces['imscc'],'manifest');
$rootel->appendChild($mUUID);
$doc->appendChild($rootel);
//add all namespaces
foreach ($this->ccnamespaces as $key => $value) {
if ($key != 'lom' ){
$dummy_attr = $key.":dummy";
$doc->createAttributeNS($value,$dummy_attr);
}
}
// add location of schemas
$schemaLocation='';
foreach ($this->ccnsnames as $key => $value) {
$vt = empty($schemaLocation) ? '' : ' ';
$schemaLocation .= $vt.$this->ccnamespaces[$key].' '.$value;
}
$aSchemaLoc = $doc->createAttributeNS($this->ccnamespaces['xsi'],'xsi:schemaLocation');
$aSchemaLoc->nodeValue=$schemaLocation;
$rootel->appendChild($aSchemaLoc);
} else {
$rootel = $doc->createElementNS($this->ccnamespaces['imscc'],'imscc:manifest');
$rootel->appendChild($mUUID);
}
$metadata = $doc->createElementNS($this->ccnamespaces['imscc'],'metadata');
$schema = $doc->createElementNS($this->ccnamespaces['imscc'],'schema','IMS Common Cartridge');
$schemaversion = $doc->createElementNS($this->ccnamespaces['imscc'],'schemaversion',$this->ccversion);
$metadata->appendChild($schema);
$metadata->appendChild($schemaversion);
$rootel->appendChild($metadata);
if (!is_null($rootmanifestnode)) {
$rootmanifestnode->appendChild($rootel);
}
$organizations = $doc->createElementNS($this->ccnamespaces['imscc'],'organizations');
$rootel->appendChild($organizations);
$resources = $doc->createElementNS($this->ccnamespaces['imscc'],'resources');
$rootel->appendChild($resources);
return true;
}
protected function update_attribute(DOMDocument &$doc, $attrname, $attrvalue, DOMElement &$node) {
$busenew = (is_object($node) && $node->hasAttribute($attrname));
$nResult = null;
if (!$busenew && is_null($attrvalue)) {
$node->removeAttribute($attrname);
} else {
$nResult = $busenew ? $node->getAttributeNode($attrname) : $doc->createAttribute($attrname);
$nResult->nodeValue = $attrvalue;
if (!$busenew) {
$node->appendChild($nResult);
}
}
return $nResult;
}
protected function update_attribute_ns(DOMDocument &$doc, $attrname, $attrnamespace,$attrvalue, DOMElement &$node) {
$busenew = (is_object($node) && $node->hasAttributeNS($attrnamespace, $attrname));
$nResult = null;
if (!$busenew && is_null($attrvalue)) {
$node->removeAttributeNS($attrnamespace, $attrname);
} else {
$nResult = $busenew ? $node->getAttributeNodeNS($attrnamespace, $attrname) : $doc->createAttributeNS($attrnamespace, $attrname);
$nResult->nodeValue = $attrvalue;
if (!$busenew) {
$node->appendChild($nResult);
}
}
return $nResult;
}
protected function get_child_node(DOMDocument &$doc, $itemname, DOMElement &$node) {
$nlist = $node->getElementsByTagName($itemname);
$item = is_object($nlist) && ($nlist->length > 0) ? $nlist->item(0) : null;
return $item;
}
protected function update_child_item(DOMDocument &$doc, $itemname, $itemvalue, DOMElement &$node, $attrtostore=null) {
$tnode = $this->get_child_node($doc,'title',$node);
$usenew = is_null($tnode);
$tnode = $usenew ? $doc->createElementNS($this->ccnamespaces['imscc'], $itemname) : $tnode;
if (!is_null($attrtostore)) {
foreach ($attrtostore as $key => $value) {
$this->update_attribute($doc,$key,$value,$tnode);
}
}
$tnode->nodeValue = $itemvalue;
if ($usenew) {
$node->appendChild($tnode);
}
}
protected function update_items($items, DOMDocument &$doc, DOMElement &$xmlnode) {
foreach ($items as $key => $item) {
$itemnode = $doc->createElementNS($this->ccnamespaces['imscc'], 'item');
$this->update_attribute($doc, 'identifier' , $key , $itemnode);
$this->update_attribute($doc, 'identifierref', $item->identifierref, $itemnode);
$this->update_attribute($doc, 'parameters' , $item->parameters , $itemnode);
if (!empty($item->title)) {
$titlenode = $doc->createElementNS($this->ccnamespaces['imscc'],
'title',
$item->title);
$itemnode->appendChild($titlenode);
}
if ($item->has_child_items()) {
$this->update_items($item->childitems, $doc, $itemnode);
}
$xmlnode->appendChild($itemnode);
}
}
/**
* Create a Resource (How to)
*
* @param cc_i_resource $res
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_resource(cc_i_resource &$res, DOMDocument &$doc, $xmlnode=null) {
$usenew = is_object($xmlnode);
$dnode = $usenew ? $xmlnode : $doc->createElementNS($this->ccnamespaces['imscc'], "resource");
$this->update_attribute($doc,'identifier',$res->identifier,$dnode);
$this->update_attribute($doc,'type' ,$res->type ,$dnode);
!is_null($res->href) ? $this->update_attribute($doc,'href',$res->href,$dnode): null;
$this->update_attribute($doc,'base' ,$res->base ,$dnode);
foreach ($res->files as $file) {
$nd = $doc->createElementNS($this->ccnamespaces['imscc'],'file');
$ndatt = $doc->createAttribute('href');
$ndatt->nodeValue = $file;
$nd->appendChild($ndatt);
$dnode->appendChild($nd);
}
$this->resources[$res->identifier] = $res;
foreach ($res->dependency as $dependency){
$nd = $doc->createElementNS($this->ccnamespaces['imscc'],'dependency');
$ndatt = $doc->createAttribute('identifierref');
$ndatt->nodeValue = $dependency;
$nd->appendChild($ndatt);
$dnode->appendChild($nd);
}
return $dnode;
}
/**
* Create an Item Folder (How To)
*
* @param cc_i_organization $org
* @param DOMDocument $doc
* @param DOMElement $xmlnode
*/
protected function create_item_folder (cc_i_organization &$org, DOMDocument &$doc, DOMElement &$xmlnode=null){
$itemfoldernode = $doc->createElementNS($this->ccnamespaces['imscc'],'item');
$this->update_attribute($doc,'identifier', "root", $itemfoldernode);
if ($org->has_items()) {
$this->update_items($org->itemlist, $doc, $itemfoldernode);
}
if (is_null($this->organizations)) {
$this->organizations = array();
}
$this->organizations[$org->identifier] = $org;
$xmlnode->appendChild($itemfoldernode);
}
/**
* Create an Organization (How To)
*
* @param cc_i_organization $org
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_organization (cc_i_organization &$org, DOMDocument &$doc, $xmlnode=null){
$usenew = is_object($xmlnode);
$dnode = $usenew ? $xmlnode : $doc->createElementNS($this->ccnamespaces['imscc'], "organization");
$this->update_attribute($doc,'identifier' ,$org->identifier,$dnode);
$this->update_attribute($doc,'structure' ,$org->structure ,$dnode);
$this->create_item_folder($org,$doc,$dnode);
return $dnode;
}
/**
* Create Metadata For Manifest (How To)
*
* @param cc_i_metadata_manifest $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_manifest (cc_i_metadata_manifest $met,DOMDocument &$doc,$xmlnode=null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lomimscc'], "lom");
if (!empty($xmlnode)) {
$xmlnode->appendChild($dnode);
}
$dnodegeneral = empty($met->arraygeneral ) ? null : $this->create_metadata_general ($met, $doc, $xmlnode);
$dnodetechnical = empty($met->arraytech ) ? null : $this->create_metadata_technical($met, $doc, $xmlnode);
$dnoderights = empty($met->arrayrights ) ? null : $this->create_metadata_rights ($met, $doc, $xmlnode);
$dnodelifecycle = empty($met->arraylifecycle) ? null : $this->create_metadata_lifecycle($met, $doc, $xmlnode);
!is_null($dnodegeneral)?$dnode->appendChild($dnodegeneral):null;
!is_null($dnodetechnical)?$dnode->appendChild($dnodetechnical):null;
!is_null($dnoderights)?$dnode->appendChild($dnoderights):null;
!is_null($dnodelifecycle)?$dnode->appendChild($dnodelifecycle):null;
return $dnode;
}
/**
* Create Metadata For Resource (How To)
*
* @param cc_i_metadata_resource $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_resource (cc_i_metadata_resource $met,DOMDocument &$doc,$xmlnode=null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lom'], "lom");
!empty($xmlnode)? $xmlnode->appendChild($dnode):null;
!empty($met->arrayeducational) ? $this->create_metadata_educational($met,$doc,$dnode):null;
return $dnode;
}
/**
* Create Metadata For File (How To)
*
* @param cc_i_metadata_file $met
* @param DOMDocument $doc
* @param Object $xmlnode
* @return DOMNode
*/
protected function create_metadata_file (cc_i_metadata_file $met,DOMDocument &$doc,$xmlnode=null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lom'], "lom");
!empty($xmlnode)? $xmlnode->appendChild($dnode):null;
!empty($met->arrayeducational) ? $this->create_metadata_educational($met,$doc,$dnode):null;
return $dnode;
}
/**
* Create General Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_general($met,DOMDocument &$doc,$xmlnode){
($xmlnode);
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'general');
foreach ($met->arraygeneral as $name => $value) {
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
if ($name != 'language' && $name != 'catalog' && $name != 'entry'){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'string',$v[1]);
$ndatt = $doc->createAttribute('language');
$ndatt->nodeValue = $v[0];
$nd3->appendChild($ndatt);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
}else{
if ($name == 'language'){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]);
$nd->appendChild($nd2);
}
}
}
}
if (!empty($met->arraygeneral['catalog']) || !empty($met->arraygeneral['entry'])){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'identifier');
$nd->appendChild($nd2);
if (!empty($met->arraygeneral['catalog'])){
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'catalog',$met->arraygeneral['catalog'][0][0]);
$nd2->appendChild($nd3);
}
if (!empty($met->arraygeneral['entry'])){
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'entry',$met->arraygeneral['entry'][0][0]);
$nd2->appendChild($nd4);
}
}
return $nd;
}
/**
* Create Technical Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_technical($met,DOMDocument &$doc,$xmlnode){
($xmlnode);
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'technical');
$xmlnode->appendChild($nd);
foreach ($met->arraytech as $name => $value) {
($name);
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]);
$nd->appendChild($nd2);
}
}
return $nd;
}
/**
* Create Rights Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_rights($met,DOMDocument &$doc,$xmlnode){
($xmlnode);
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'rights');
foreach ($met->arrayrights as $name => $value) {
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
if ($name == 'description'){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'string',$v[1]);
$ndatt = $doc->createAttribute('language');
$ndatt->nodeValue = $v[0];
$nd3->appendChild($ndatt);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
}elseif ($name == 'copyrightAndOtherRestrictions' || $name == 'cost'){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'value',$v[0]);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
}
}
}
return $nd;
}
/**
* Create LifeCyle Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_lifecycle($met,DOMDocument &$doc,$xmlnode){
($xmlnode);
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'lifeCycle');
$nd2= $doc->createElementNS($this->ccnamespaces['lomimscc'],'contribute');
$nd->appendChild ($nd2);
$xmlnode->appendChild ($nd);
foreach ($met->arraylifecycle as $name => $value) {
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
if ($name == 'role'){
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd2->appendChild($nd3);
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'value',$v[0]);
$nd3->appendChild($nd4);
}else{
if ($name == 'date'){
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd2->appendChild($nd3);
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'dateTime',$v[0]);
$nd3->appendChild($nd4);
}else{
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]);
$nd2->appendChild($nd3);
}
}
}
}
return $nd;
}
/**
* Create Education Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_educational ($met,DOMDocument &$doc, $xmlnode){
$nd = $doc->createElementNS($this->ccnamespaces['lom'],'educational');
$nd2 = $doc->createElementNS($this->ccnamespaces['lom'],'intendedEndUserRole');
$nd3 = $doc->createElementNS($this->ccnamespaces['voc'],'vocabulary');
$xmlnode->appendChild($nd);
$nd->appendChild($nd2);
$nd2->appendChild($nd3);
foreach ($met->arrayeducational as $name => $value) {
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
$nd4 = $doc->createElementNS($this->ccnamespaces['voc'],$name,$v[0]);
$nd3->appendChild($nd4);
}
}
return $nd;
}
} | ouyangyu/fdmoodle | backup/cc/cc_lib/cc_version1.php | PHP | gpl-3.0 | 21,798 |
package com.programandoapasitos.facturador.gui;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import com.programandoapasitos.facturador.gui.superclases.FramePadre;
import com.programandoapasitos.facturador.utiles.ManejadorProperties;
@SuppressWarnings("serial")
public class MenuPrincipal extends FramePadre {
// Propiedades
private JLabel lblIcono;
private JMenuBar menuBar;
private JMenu mnClientes;
private JMenu mnFacturas;
private JMenuItem mntmNuevaFactura;
private JMenuItem mntmNuevoCliente;
private JMenuItem mntmBuscarFactura;
private JMenuItem mntmBuscarCliente;
// Constructor
public MenuPrincipal(int ancho, int alto, String titulo) {
super(ancho, alto, titulo);
this.inicializar();
}
// Métodos
public void inicializar() {
this.inicializarMenuBar();
this.iniciarLabels();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sobrescribe setDefaultCloseOperation de FramePadre
setVisible(true);
}
public void inicializarMenuBar() {
menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 900, 21);
this.panel.add(menuBar);
this.inicializarMenuFacturas();
this.inicializarMenuClientes();
}
/**
* Initialize submenu Bills
*/
public void inicializarMenuFacturas() {
mnFacturas = new JMenu(ManejadorProperties.verLiteral("MENU_FACTURAS"));
menuBar.add(mnFacturas);
mntmNuevaFactura = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_NEW_BILL"));
mntmNuevaFactura.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new FrameNuevaFactura(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_NEW_BILL"));
}
});
mnFacturas.add(mntmNuevaFactura);
mntmBuscarFactura = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_BILL"));
mntmBuscarFactura.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new FrameBuscarFacturas(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_BILL"));
}
});
mnFacturas.add(mntmBuscarFactura);
}
public void inicializarMenuClientes() {
mnClientes = new JMenu(ManejadorProperties.verLiteral("MENU_CLIENTES"));
menuBar.add(mnClientes);
mntmNuevoCliente = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_NEW_CLIENT"));
mntmNuevoCliente.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new FrameNuevoCliente(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_NEW_CLIENT"));
}
});
mnClientes.add(mntmNuevoCliente);
mntmBuscarCliente = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_CLIENT"));
mntmBuscarCliente.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new FrameBuscarClientes(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_CLIENT"));
}
});
mnClientes.add(mntmBuscarCliente);
}
/**
* Initialize icon label
*/
public void iniciarLabels() {
lblIcono = new JLabel("");
lblIcono.setIcon(new ImageIcon(ManejadorProperties.verRuta("MENU_ITEM_SEARCH_CLIENT")));
lblIcono.setBounds(342, 240, 210, 124);
this.panel.add(lblIcono);
}
}
| inazense/java-generate-bills | src/main/java/com/programandoapasitos/facturador/gui/MenuPrincipal.java | Java | gpl-3.0 | 3,783 |
<?php
use Respect\Validation\Validator as DataValidator;
/**
* @api {post} /staff/search-tickets Search tickets
* @apiVersion 4.5.0
*
* @apiName Search tickets
*
* @apiGroup Staff
*
* @apiDescription This path search some tickets.
*
* @apiPermission staff1
*
* @apiParam {String} query Query string to search.
* @apiParam {Number} page The page number.
*
* @apiUse NO_PERMISSION
* @apiUse INVALID_QUERY
* @apiUse INVALID_PAGE
*
* @apiSuccess {Object} data Information about tickets
* @apiSuccess {[Ticket](#api-Data_Structures-ObjectTicket)[]} data.tickets Array of tickets found
* @apiSuccess {Number} data.pages Number of pages
*
*/
class SearchTicketStaffController extends Controller {
const PATH = '/search-tickets';
const METHOD = 'POST';
public function validations() {
return[
'permission' => 'staff_1',
'requestData' => [
'query' => [
'validation' => DataValidator::length(1),
'error' => ERRORS::INVALID_QUERY
],
'page' => [
'validation' => DataValidator::numeric(),
'error' => ERRORS::INVALID_PAGE
]
]
];
}
public function handler() {
Response::respondSuccess([
'tickets' => $this->getTicketList()->toArray(),
'pages' => $this->getTotalPages()
]);
}
private function getTicketList() {
$query = $this->getSearchQuery();
return Ticket::find($query, [
Controller::request('query') . '%',
'%' . Controller::request('query') . '%',
Controller::request('query') . '%'
]);
}
private function getSearchQuery() {
$page = Controller::request('page');
$query = " (title LIKE ? OR title LIKE ?) AND ";
$query .= $this->getStaffDepartmentsQueryFilter();
$query .= "ORDER BY CASE WHEN (title LIKE ?) THEN 1 ELSE 2 END ASC LIMIT 10 OFFSET " . (($page-1)*10);
return $query;
}
private function getTotalPages() {
$query = " (title LIKE ? OR title LIKE ?) AND ";
$query .= $this->getStaffDepartmentsQueryFilter();
$ticketQuantity = Ticket::count($query, [
Controller::request('query') . '%',
'%' . Controller::request('query') . '%'
]);
return ceil($ticketQuantity / 10);
}
private function getStaffDepartmentsQueryFilter() {
$user = Controller::getLoggedUser();
$query = ' (';
foreach ($user->sharedDepartmentList as $department) {
$query .= 'department_id=' . $department->id . ' OR ';
}
$query = substr($query, 0, -3);
$query .= ') ';
return $query;
}
} | ivandiazwm/opensupports | server/controllers/staff/search-tickets.php | PHP | gpl-3.0 | 2,810 |
/*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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/>.
*/
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {SharedModule} from '../../../../shared/shared.module';
import {SearchAllComponent} from './search-all.component';
import {SearchCollectionsModule} from '../search-collections/search-collections.module';
import {SearchViewsModule} from '../search-views/search-views.module';
import {SearchTasksModule} from '../search-tasks/search-tasks.module';
@NgModule({
imports: [CommonModule, SharedModule, SearchCollectionsModule, SearchViewsModule, SearchTasksModule],
declarations: [SearchAllComponent],
exports: [SearchAllComponent],
})
export class SearchAllModule {}
| Lumeer/web-ui | src/app/view/perspectives/dashboard/search-all/search-all.module.ts | TypeScript | gpl-3.0 | 1,450 |
package com.diggime.modules.email.model.impl;
import com.diggime.modules.email.model.EMail;
import com.diggime.modules.email.model.MailContact;
import org.json.JSONObject;
import java.time.LocalDateTime;
import java.util.List;
import static org.foilage.utils.checkers.NullChecker.notNull;
public class PostmarkEMail implements EMail {
private final int id;
private final String messageId;
private final LocalDateTime sentDate;
private final MailContact sender;
private final List<MailContact> receivers;
private final List<MailContact> carbonCopies;
private final List<MailContact> blindCarbonCopies;
private final String subject;
private final String tag;
private final String htmlBody;
private final String textBody;
public PostmarkEMail(LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) {
this.id = 0;
this.messageId = "";
this.sentDate = notNull(sentDate);
this.sender = notNull(sender);
this.receivers = notNull(receivers);
this.carbonCopies = notNull(carbonCopies);
this.blindCarbonCopies = notNull(blindCarbonCopies);
this.subject = notNull(subject);
this.tag = notNull(tag);
this.htmlBody = notNull(htmlBody);
this.textBody = notNull(textBody);
}
public PostmarkEMail(String messageId, LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) {
this.id = 0;
this.messageId = notNull(messageId);
this.sentDate = notNull(sentDate);
this.sender = notNull(sender);
this.receivers = notNull(receivers);
this.carbonCopies = notNull(carbonCopies);
this.blindCarbonCopies = notNull(blindCarbonCopies);
this.subject = notNull(subject);
this.tag = notNull(tag);
this.htmlBody = notNull(htmlBody);
this.textBody = notNull(textBody);
}
public PostmarkEMail(EMail mail, String messageId) {
this.id = mail.getId();
this.messageId = notNull(messageId);
this.sentDate = mail.getSentDate();
this.sender = mail.getSender();
this.receivers = mail.getReceivers();
this.carbonCopies = mail.getCarbonCopies();
this.blindCarbonCopies = mail.getBlindCarbonCopies();
this.subject = mail.getSubject();
this.tag = mail.getTag();
this.htmlBody = mail.getHtmlBody();
this.textBody = mail.getTextBody();
}
public PostmarkEMail(int id, String messageId, LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) {
this.id = id;
this.messageId = notNull(messageId);
this.sentDate = notNull(sentDate);
this.sender = notNull(sender);
this.receivers = notNull(receivers);
this.carbonCopies = notNull(carbonCopies);
this.blindCarbonCopies = notNull(blindCarbonCopies);
this.subject = notNull(subject);
this.tag = notNull(tag);
this.htmlBody = notNull(htmlBody);
this.textBody = notNull(textBody);
}
@Override
public int getId() {
return id;
}
@Override
public String getMessageId() {
return messageId;
}
@Override
public LocalDateTime getSentDate() {
return sentDate;
}
@Override
public MailContact getSender() {
return sender;
}
@Override
public List<MailContact> getReceivers() {
return receivers;
}
@Override
public List<MailContact> getCarbonCopies() {
return carbonCopies;
}
@Override
public List<MailContact> getBlindCarbonCopies() {
return blindCarbonCopies;
}
@Override
public String getSubject() {
return subject;
}
@Override
public String getTag() {
return tag;
}
@Override
public String getHtmlBody() {
return htmlBody;
}
@Override
public String getTextBody() {
return textBody;
}
@Override
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
obj.put("From", sender.getName()+" <"+sender.getAddress()+">");
addReceivers(obj, receivers, "To");
addReceivers(obj, carbonCopies, "Cc");
addReceivers(obj, blindCarbonCopies, "Bcc");
obj.put("Subject", subject);
if(tag.length()>0) {
obj.put("Tag", tag);
}
if(htmlBody.length()>0) {
obj.put("HtmlBody", htmlBody);
} else {
obj.put("HtmlBody", textBody);
}
if(textBody.length()>0) {
obj.put("TextBody", textBody);
}
return obj;
}
private void addReceivers(JSONObject obj, List<MailContact> sendList, String jsonType) {
boolean first = true;
StringBuilder sb = new StringBuilder();
for(MailContact contact: sendList) {
if(first) {
first = false;
} else {
sb.append(", ");
}
sb.append(contact.getName());
sb.append(" <");
sb.append(contact.getAddress());
sb.append(">");
}
if(sendList.size()>0) {
obj.put(jsonType, sb.toString());
}
}
}
| drbizzaro/diggime | base/main/src/com/diggime/modules/email/model/impl/PostmarkEMail.java | Java | gpl-3.0 | 5,687 |
/*
* Copyright (C) 2014 Hector Espert Pardo
*
* 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 es.blackleg.libdam.geometry;
import es.blackleg.libdam.utilities.Calculadora;
/**
*
* @author Hector Espert Pardo
*/
public class Circulo extends Figura {
private double radio;
public Circulo() {
}
public Circulo(double radio) {
this.radio = radio;
}
public void setRadio(double radio) {
this.radio = radio;
}
public double getRadio() {
return radio;
}
public double getDiametro() {
return 2 * radio;
}
@Override
public double calculaArea() {
return Calculadora.areaCirculo(radio);
}
@Override
public double calculaPerimetro() {
return Calculadora.perimetroCirculo(radio);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Circulo other = (Circulo) obj;
return Double.doubleToLongBits(this.radio) == Double.doubleToLongBits(other.radio);
}
@Override
public int hashCode() {
int hash = 5;
hash = 67 * hash + (int) (Double.doubleToLongBits(this.radio) ^ (Double.doubleToLongBits(this.radio) >>> 32));
return hash;
}
@Override
public String toString() {
return String.format("Circulo: x=%d, y=%d, R=%.2f.", super.getCentro().getX(), super.getCentro().getY(), radio);
}
}
| blackleg/libdam | src/main/java/es/blackleg/libdam/geometry/Circulo.java | Java | gpl-3.0 | 2,177 |
<?php
return [
'facebook' => [
'appId' => '', //application api id for facebook
'appSecret' => '', //application api secret for facebook
'scope' => 'email, user_birthday, publish_actions' //facebook scopes
],
'twitter' => [
'appId' => '', //twitter application consumer key
'appSecret' => '' //twitter application consumer secret
//Twitter scopes must be defined in dev.twitter.com
]
]; | jlorente/social-abstract-client | config/config.php | PHP | gpl-3.0 | 450 |
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Engine;
using Micropolis.Common;
using Microsoft.ApplicationInsights;
namespace Micropolis.ViewModels
{
public class EvaluationPaneViewModel : BindableBase, Engine.IListener
{
private Engine.Micropolis _engine;
private MainGamePageViewModel _mainPageViewModel;
/// <summary>
/// Sets the engine.
/// </summary>
/// <param name="newEngine">The new engine.</param>
public void SetEngine(Engine.Micropolis newEngine)
{
if (_engine != null)
{
//old engine
_engine.RemoveListener(this);
}
_engine = newEngine;
if (_engine != null)
{
//new engine
_engine.AddListener(this);
LoadEvaluation();
}
}
public EvaluationPaneViewModel()
{
DismissCommand = new DelegateCommand(OnDismissClicked);
try
{
_telemetry = new TelemetryClient();
}
catch (Exception)
{
}
}
/// <summary>
/// Called when user clicked the dismiss button to close the window.
/// </summary>
private void OnDismissClicked()
{
try {
_telemetry.TrackEvent("EvaluationPaneDismissClicked");
}
catch (Exception) { }
_mainPageViewModel.HideEvaluationPane();
}
private string _headerPublicOpinionTextBlockText;
public string HeaderPublicOpinionTextBlockText
{
get
{
return this._headerPublicOpinionTextBlockText;
}
set
{
this.SetProperty(ref this._headerPublicOpinionTextBlockText, value);
}
}
private string _pubOpTextBlockText;
public string PubOpTextBlockText
{
get
{
return this._pubOpTextBlockText;
}
set
{
this.SetProperty(ref this._pubOpTextBlockText, value);
}
}
private string _pubOp2TextBlockText;
public string PubOp2TextBlockText
{
get
{
return this._pubOp2TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp2TextBlockText, value);
}
}
private string _pubOp3TextBlockText;
public string PubOp3TextBlockText
{
get
{
return this._pubOp3TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp3TextBlockText, value);
}
}
private string _pubOp4TextBlockText;
public string PubOp4TextBlockText
{
get
{
return this._pubOp4TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp4TextBlockText, value);
}
}
/// <summary>
/// Makes the public opinion pane.
/// </summary>
/// <returns></returns>
private void MakePublicOpinionPane()
{
HeaderPublicOpinionTextBlockText = Strings.GetString("public-opinion");
PubOpTextBlockText = Strings.GetString("public-opinion-1");
PubOp2TextBlockText = Strings.GetString("public-opinion-2");
PubOp3TextBlockText = Strings.GetString("public-opinion-yes");
PubOp4TextBlockText = Strings.GetString("public-opinion-no");
VoterProblem1TextBlockText = "";
VoterCount1TextBlockText = "";
VoterProblem2TextBlockText = "";
VoterCount2TextBlockText = "";
VoterProblem3TextBlockText = "";
VoterCount3TextBlockText = "";
VoterProblem4TextBlockText = "";
VoterCount4TextBlockText = "";
}
private string _voterProblem4TextBlockText;
public string VoterProblem4TextBlockText
{
get
{
return this._voterProblem4TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem4TextBlockText, value);
}
}
private string _voterProblem3TextBlockText;
public string VoterProblem3TextBlockText
{
get
{
return this._voterProblem3TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem3TextBlockText, value);
}
}
private string _voterProblem2TextBlockText;
public string VoterProblem2TextBlockText
{
get
{
return this._voterProblem2TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem2TextBlockText, value);
}
}
private string _voterProblem1TextBlockText;
public string VoterProblem1TextBlockText
{
get
{
return this._voterProblem1TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem1TextBlockText, value);
}
}
private string _voterCount1TextBlockText;
public string VoterCount1TextBlockText
{
get
{
return this._voterCount1TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount1TextBlockText, value);
}
}
private string _voterCount2TextBlockText;
public string VoterCount2TextBlockText
{
get
{
return this._voterCount2TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount2TextBlockText, value);
}
}
private string _voterCount3TextBlockText;
public string VoterCount3TextBlockText
{
get
{
return this._voterCount3TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount3TextBlockText, value);
}
}
private string _voterCount4TextBlockText;
public string VoterCount4TextBlockText
{
get
{
return this._voterCount4TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount4TextBlockText, value);
}
}
/// <summary>
/// Makes the statistics pane.
/// </summary>
/// <returns></returns>
private void MakeStatisticsPane()
{
HeaderStatisticsTextBlockText = Strings.GetString("statistics-head");
CityScoreHeaderTextBlockText = Strings.GetString("city-score-head");
StatPopTextBlockText = Strings.GetString("stats-population");
StatMigTextBlockText = Strings.GetString("stats-net-migration");
StatsLastYearTextBlockText = Strings.GetString("stats-last-year");
StatsAssessedValueTextBlockText = Strings.GetString("stats-assessed-value");
StatsCategoryTextBlockText = Strings.GetString("stats-category");
StatsGameLevelTextBlockText = Strings.GetString("stats-game-level");
CityScoreCurrentTextBlockText = Strings.GetString("city-score-current");
CityScoreChangeTextBlockText = Strings.GetString("city-score-change");
}
private string _headerStatisticsTextBlockText;
public string HeaderStatisticsTextBlockText
{
get
{
return this._headerStatisticsTextBlockText;
}
set
{
this.SetProperty(ref this._headerStatisticsTextBlockText, value);
}
}
private string _cityScoreHeaderTextBlockText;
public string CityScoreHeaderTextBlockText
{
get
{
return this._cityScoreHeaderTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreHeaderTextBlockText, value);
}
}
private string _statPopTextBlockText;
public string StatPopTextBlockText
{
get
{
return this._statPopTextBlockText;
}
set
{
this.SetProperty(ref this._statPopTextBlockText, value);
}
}
private string _statMigTextBlockText;
public string StatMigTextBlockText
{
get
{
return this._statMigTextBlockText;
}
set
{
this.SetProperty(ref this._statMigTextBlockText, value);
}
}
private string _statsLastYearTextBlockText;
public string StatsLastYearTextBlockText
{
get
{
return this._statsLastYearTextBlockText;
}
set
{
this.SetProperty(ref this._statsLastYearTextBlockText, value);
}
}
private string _statsAssessedValueTextBlockText;
public string StatsAssessedValueTextBlockText
{
get
{
return this._statsAssessedValueTextBlockText;
}
set
{
this.SetProperty(ref this._statsAssessedValueTextBlockText, value);
}
}
private string _statsCategoryTextBlockText;
public string StatsCategoryTextBlockText
{
get
{
return this._statsCategoryTextBlockText;
}
set
{
this.SetProperty(ref this._statsCategoryTextBlockText, value);
}
}
private string _statsGameLevelTextBlockText;
public string StatsGameLevelTextBlockText
{
get
{
return this._statsGameLevelTextBlockText;
}
set
{
this.SetProperty(ref this._statsGameLevelTextBlockText, value);
}
}
private string _cityScoreCurrentTextBlockText;
public string CityScoreCurrentTextBlockText
{
get
{
return this._cityScoreCurrentTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreCurrentTextBlockText, value);
}
}
private string _cityScoreChangeTextBlockText;
public string CityScoreChangeTextBlockText
{
get
{
return this._cityScoreChangeTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreChangeTextBlockText, value);
}
}
private string _yesTextBlockText;
public string YesTextBlockText
{
get
{
return this._yesTextBlockText;
}
set
{
this.SetProperty(ref this._yesTextBlockText, value);
}
}
private string _noTextBlockText;
public string NoTextBlockText
{
get
{
return this._noTextBlockText;
}
set
{
this.SetProperty(ref this._noTextBlockText, value);
}
}
/// <summary>
/// Loads the evaluation.
/// </summary>
private void LoadEvaluation()
{
YesTextBlockText = ((_engine.Evaluation.CityYes).ToString()+"%");
NoTextBlockText = ((_engine.Evaluation.CityNo).ToString()+"%");
CityProblem p;
int numVotes;
p = 0 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[0]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem1TextBlockText = ("problem." + p); //name
VoterCount1TextBlockText = (0.01*numVotes).ToString();
VoterProblem1IsVisible = true;
VoterCount1IsVisible = true;
}
else
{
VoterProblem1IsVisible = false;
VoterCount1IsVisible = false;
}
p = 1 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[1]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem2TextBlockText = ("problem." + p); //name
VoterCount2TextBlockText = (0.01 * numVotes).ToString();
VoterProblem2IsVisible = true;
VoterCount2IsVisible = true;
}
else
{
VoterProblem2IsVisible = false;
VoterCount2IsVisible = false;
}
p = 2 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[2]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem3TextBlockText = ("problem." + p); //name
VoterCount3TextBlockText = (0.01 * numVotes).ToString();
VoterProblem3IsVisible = true;
VoterCount3IsVisible = true;
}
else
{
VoterProblem3IsVisible = false;
VoterCount3IsVisible = false;
}
p = 3 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[3]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem4TextBlockText = ("problem." + p); //name
VoterCount4TextBlockText = (0.01 * numVotes).ToString();
VoterProblem4IsVisible = true;
VoterCount4IsVisible = true;
}
else
{
VoterProblem4IsVisible = false;
VoterCount4IsVisible = false;
}
PopTextBlockText = (_engine.Evaluation.CityPop).ToString();
DeltaTextBlockText = (_engine.Evaluation.DeltaCityPop).ToString();
AssessTextBlockText = (_engine.Evaluation.CityAssValue).ToString();
CityClassTextBlockText = (GetCityClassName(_engine.Evaluation.CityClass));
GameLevelTextBlockText = (GetGameLevelName(_engine.GameLevel));
ScoreTextBlockText = (_engine.Evaluation.CityScore).ToString();
ScoreDeltaTextBlockText = (_engine.Evaluation.DeltaCityScore).ToString();
}
private bool _voterCount4IsVisible;
public bool VoterCount4IsVisible
{
get
{
return this._voterCount4IsVisible;
}
set
{
this.SetProperty(ref this._voterCount4IsVisible, value);
}
}
private bool _voterCount3IsVisible;
public bool VoterCount3IsVisible
{
get
{
return this._voterCount3IsVisible;
}
set
{
this.SetProperty(ref this._voterCount3IsVisible, value);
}
}
private bool _voterCount2IsVisible;
public bool VoterCount2IsVisible
{
get
{
return this._voterCount2IsVisible;
}
set
{
this.SetProperty(ref this._voterCount2IsVisible, value);
}
}
private bool _voterCount1IsVisible;
public bool VoterCount1IsVisible
{
get
{
return this._voterCount1IsVisible;
}
set
{
this.SetProperty(ref this._voterCount1IsVisible, value);
}
}
private bool _voterProblem4IsVisible;
public bool VoterProblem4IsVisible
{
get
{
return this._voterProblem4IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem4IsVisible, value);
}
}
private bool _voterProblem3IsVisible;
public bool VoterProblem3IsVisible
{
get
{
return this._voterProblem3IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem3IsVisible, value);
}
}
private bool _voterProblem2IsVisible;
public bool VoterProblem2IsVisible
{
get
{
return this._voterProblem2IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem2IsVisible, value);
}
}
private bool _voterProblem1IsVisible;
public bool VoterProblem1IsVisible
{
get
{
return this._voterProblem1IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem1IsVisible, value);
}
}
private string _scoreDeltaTextBlockText;
public string ScoreDeltaTextBlockText
{
get
{
return this._scoreDeltaTextBlockText;
}
set
{
this.SetProperty(ref this._scoreDeltaTextBlockText, value);
}
}
private string _scoreTextBlockText;
public string ScoreTextBlockText
{
get
{
return this._scoreTextBlockText;
}
set
{
this.SetProperty(ref this._scoreTextBlockText, value);
}
}
private string _gameLevelTextBlockText;
public string GameLevelTextBlockText
{
get
{
return this._gameLevelTextBlockText;
}
set
{
this.SetProperty(ref this._gameLevelTextBlockText, value);
}
}
private string _cityClassTextBlockText;
public string CityClassTextBlockText
{
get
{
return this._cityClassTextBlockText;
}
set
{
this.SetProperty(ref this._cityClassTextBlockText, value);
}
}
private string _assessTextBlockText;
public string AssessTextBlockText
{
get
{
return this._assessTextBlockText;
}
set
{
this.SetProperty(ref this._assessTextBlockText, value);
}
}
private string _deltaTextBlockText;
public string DeltaTextBlockText
{
get
{
return this._deltaTextBlockText;
}
set
{
this.SetProperty(ref this._deltaTextBlockText, value);
}
}
private string _popTextBlockText;
public string PopTextBlockText
{
get
{
return this._popTextBlockText;
}
set
{
this.SetProperty(ref this._popTextBlockText, value);
}
}
/// <summary>
/// Gets the name of the city class.
/// </summary>
/// <param name="cityClass">The city class.</param>
/// <returns></returns>
private static String GetCityClassName(int cityClass)
{
return Strings.GetString("class." + cityClass);
}
/// <summary>
/// Gets the name of the game level.
/// </summary>
/// <param name="gameLevel">The game level.</param>
/// <returns></returns>
private static String GetGameLevelName(int gameLevel)
{
return Strings.GetString("level." + gameLevel);
}
public DelegateCommand DismissCommand { get; private set; }
private string _dismissButtonText;
private TelemetryClient _telemetry;
public string DismissButtonText
{
get
{
return this._dismissButtonText;
}
set
{
this.SetProperty(ref this._dismissButtonText, value);
}
}
internal void SetupAfterBasicInit(MainGamePageViewModel mainPageViewModel, Engine.Micropolis engine)
{
_mainPageViewModel = mainPageViewModel;
DismissButtonText = Strings.GetString("dismiss-evaluation");
MakePublicOpinionPane();
MakeStatisticsPane();
SetEngine(engine);
LoadEvaluation();
}
#region implements Micropolis.IListener
/// <summary>
/// Cities the message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="loc">The loc.</param>
public void CityMessage(MicropolisMessage message, CityLocation loc)
{
}
/// <summary>
/// Cities the sound.
/// </summary>
/// <param name="sound">The sound.</param>
/// <param name="loc">The loc.</param>
public void CitySound(Sound sound, CityLocation loc)
{
}
/// <summary>
/// Fired whenever the "census" is taken, and the various historical counters have been updated. (Once a month in
/// game.)
/// </summary>
public void CensusChanged()
{
}
/// <summary>
/// Fired whenever resValve, comValve, or indValve changes. (Twice a month in game.)
/// </summary>
public void DemandChanged()
{
}
/// <summary>
/// Fired whenever the mayor's money changes.
/// </summary>
public void FundsChanged()
{
}
/// <summary>
/// Fired whenever autoBulldoze, autoBudget, noDisasters, or simSpeed change.
/// </summary>
public void OptionsChanged()
{
}
#endregion
#region implements Engine.IListener
/// <summary>
/// Fired whenever the city evaluation is recalculated. (Once a year.)
/// </summary>
public void EvaluationChanged()
{
LoadEvaluation();
}
#endregion
}
}
| andreasbalzer/MicropolisForWindows | Micropolis.W10/ViewModels/EvaluationPaneViewModel.cs | C# | gpl-3.0 | 24,009 |
<?php
/**
* KR_Custom_Posts
*/
class KR_Custom_Posts extends Odin_Post_Type {
private $_labels = array();
private $_arguments = array();
private $_dashicon = 'dashicons-';
private $_supports = array( 'title', 'editor', 'thumbnail' );
private $_slug;
private $_singular;
private $_plural;
private $_rewrite;
private $_exclude_search;
public function __construct( $post_slug = null, $singular = null, $plural = null, $supports = array(), $dashicon = 'admin-post', $rewrite = null, $exclude_search = false ) {
if(empty($post_slug)) {
echo '<pre>' . print_r( __('The Parameter <code>$post_slug</code> is required!!'), true ) . '</pre>';
die();
}
$this->_slug = $post_slug;
$this->_dashicon = $this->_dashicon . $dashicon;
$this->_singular = (!empty($singular)) ? $singular : $this->_slug;
$this->_plural = (!empty($plural)) ? $plural : $this->_slug;
$this->_supports = (count($supports) > 0) ? $supports : $this->_supports;
$this->_rewrite = (!empty($rewrite)) ? array('slug' => $rewrite) : array('slug' => $this->_slug);
$this->_exclude_search = $exclude_search;
$this->kr_init();
}
private function kr_init() {
parent::__construct( $this->_slug, $this->_slug );
$this->kr_set_labels();
$this->kr_set_arguments();
$this->set_labels($this->_labels); # odin method set_labels
$this->set_arguments($this->_arguments); # odin method set_arguments
$this->kr_cleaner();
}
private function kr_set_labels() {
$this->_labels = array(
'name' => $this->_plural,
'singular_name' => $this->_singular,
'menu_name' => $this->_plural,
'all_items' => $this->_plural,
'add_new' => 'Adicionar Novo',
'add_new_item' => 'Adicionar Novo',
'search_items' => 'Buscar',
'not_found' => 'Nada encontrado',
'not_found_in_trash' => 'Nada encontrado na lixeira',
);
}
private function kr_set_arguments() {
$this->_arguments = array(
'supports' => $this->_supports,
'menu_icon' => $this->_dashicon,
'rewrite' => $this->_rewrite,
'exclude_from_search' => $this->_exclude_search,
// 'menu_position' => '1.36',
'capability_type' => 'page',
);
}
private function kr_cleaner() {
unset($this->_slug);
unset($this->_dashicon);
unset($this->_singular);
unset($this->_plural);
unset($this->_supports);
unset($this->_exclude_search);
unset($this->_rewrite);
unset($this->_labels);
unset($this->_arguments);
}
} # End Class KR_Custom_Posts
| abracce/theme-abracce.org.br | app/class/custom-posts.php | PHP | gpl-3.0 | 2,596 |
<?php
/* core/modules/system/templates/block--system-branding-block.html.twig */
class __TwigTemplate_f1b301a70237e4e176f4b41c2721030700b3dd2e5c3f618f2513416e3a699971 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("block.html.twig", "core/modules/system/templates/block--system-branding-block.html.twig", 1);
$this->blocks = array(
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "block.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("if" => 19);
$filters = array("t" => 20);
$functions = array("path" => 20);
try {
$this->env->getExtension('sandbox')->checkSecurity(
array('if'),
array('t'),
array('path')
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 18
public function block_content($context, array $blocks = array())
{
// line 19
echo " ";
if ((isset($context["site_logo"]) ? $context["site_logo"] : null)) {
// line 20
echo " <a href=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($this->env->getExtension('drupal_core')->getPath("<front>")));
echo "\" title=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home")));
echo "\" rel=\"home\">
<img src=\"";
// line 21
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_logo"]) ? $context["site_logo"] : null), "html", null, true));
echo "\" alt=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home")));
echo "\" />
</a>
";
}
// line 24
echo " ";
if ((isset($context["site_name"]) ? $context["site_name"] : null)) {
// line 25
echo " <a href=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($this->env->getExtension('drupal_core')->getPath("<front>")));
echo "\" title=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home")));
echo "\" rel=\"home\">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_name"]) ? $context["site_name"] : null), "html", null, true));
echo "</a>
";
}
// line 27
echo " ";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_slogan"]) ? $context["site_slogan"] : null), "html", null, true));
echo "
";
}
public function getTemplateName()
{
return "core/modules/system/templates/block--system-branding-block.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 86 => 27, 76 => 25, 73 => 24, 65 => 21, 58 => 20, 55 => 19, 52 => 18, 11 => 1,);
}
}
/* {% extends "block.html.twig" %}*/
/* {#*/
/* /***/
/* * @file*/
/* * Default theme implementation for a branding block.*/
/* **/
/* * Each branding element variable (logo, name, slogan) is only available if*/
/* * enabled in the block configuration.*/
/* **/
/* * Available variables:*/
/* * - site_logo: Logo for site as defined in Appearance or theme settings.*/
/* * - site_name: Name for site as defined in Site information settings.*/
/* * - site_slogan: Slogan for site as defined in Site information settings.*/
/* **/
/* * @ingroup themeable*/
/* *//* */
/* #}*/
/* {% block content %}*/
/* {% if site_logo %}*/
/* <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">*/
/* <img src="{{ site_logo }}" alt="{{ 'Home'|t }}" />*/
/* </a>*/
/* {% endif %}*/
/* {% if site_name %}*/
/* <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}</a>*/
/* {% endif %}*/
/* {{ site_slogan }}*/
/* {% endblock %}*/
/* */
| acastellon/smtcc | sites/default/files/php/twig/42a2597a_block--system-branding-block.html.twig_c69e55da788ed29c4c90e83e1c7f08c4006237988dbbe9f913bdfe4f6f661444/498169c485adefe3bb313999225832f5bbdd2ab6ac9b397903eae1c54b5b0ab3.php | PHP | gpl-3.0 | 5,470 |
#region using directives
using System;
using PoGo.PokeMobBot.Logic.Event;
using PoGo.PokeMobBot.Logic.Event.Egg;
using PoGo.PokeMobBot.Logic.Event.Fort;
using PoGo.PokeMobBot.Logic.Event.Global;
using PoGo.PokeMobBot.Logic.Event.GUI;
using PoGo.PokeMobBot.Logic.Event.Item;
using PoGo.PokeMobBot.Logic.Event.Logic;
using PoGo.PokeMobBot.Logic.Event.Obsolete;
using PoGo.PokeMobBot.Logic.Event.Player;
using PoGo.PokeMobBot.Logic.Event.Pokemon;
using PoGo.PokeMobBot.Logic.State;
using PoGo.PokeMobBot.Logic.Utils;
using POGOProtos.Networking.Responses;
#endregion
namespace PoGo.PokeMobBot.Logic
{
public class StatisticsAggregator
{
public void HandleEvent(ProfileEvent evt, ISession session)
{
session.Stats.SetUsername(evt.Profile);
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(ErrorEvent evt, ISession session)
{
}
public void HandleEvent(NoticeEvent evt, ISession session)
{
}
public void HandleEvent(FortLureStartedEvent evt, ISession session)
{
}
public void HandleEvent(ItemUsedEvent evt, ISession session)
{
}
public void HandleEvent(WarnEvent evt, ISession session)
{
}
public void HandleEvent(UseLuckyEggEvent evt, ISession session)
{
}
public void HandleEvent(PokemonEvolveEvent evt, ISession session)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(TransferPokemonEvent evt, ISession session)
{
session.Stats.TotalPokemonsTransfered++;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(EggHatchedEvent evt, ISession session)
{
session.Stats.TotalPokemons++;
session.Stats.HatchedNow++;
session.Stats.RefreshStatAndCheckLevelup(session);
session.Stats.RefreshPokeDex(session);
}
public void HandleEvent(VerifyChallengeEvent evt, ISession session)
{
}
public void HandleEvent(CheckChallengeEvent evt, ISession session)
{
}
public void HandleEvent(BuddySetEvent evt, ISession session)
{
}
public void HandleEvent(BuddyWalkedEvent evt, ISession session)
{
}
public void HandleEvent(ItemRecycledEvent evt, ISession session)
{
session.Stats.TotalItemsRemoved += evt.Count;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(FortUsedEvent evt, ISession session)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.TotalPokestops++;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(FortTargetEvent evt, ISession session)
{
}
public void HandleEvent(PokemonActionDoneEvent evt, ISession session)
{
}
public void HandleEvent(PokemonCaptureEvent evt, ISession session)
{
if (evt.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.TotalPokemons++;
session.Stats.TotalStardust = evt.Stardust;
session.Stats.RefreshStatAndCheckLevelup(session);
session.Stats.RefreshPokeDex(session);
}
session.Stats.PokeBalls++;
}
public void HandleEvent(NoPokeballEvent evt, ISession session)
{
}
public void HandleEvent(UseBerryEvent evt, ISession session)
{
}
public void HandleEvent(DisplayHighestsPokemonEvent evt, ISession session)
{
}
public void HandleEvent(UpdatePositionEvent evt, ISession session)
{
}
public void HandleEvent(NewVersionEvent evt, ISession session)
{
}
public void HandleEvent(UpdateEvent evt, ISession session)
{
}
public void HandleEvent(BotCompleteFailureEvent evt, ISession session)
{
}
public void HandleEvent(DebugEvent evt, ISession session)
{
}
public void HandleEvent(EggIncubatorStatusEvent evt, ISession session)
{
}
public void HandleEvent(EggsListEvent evt, ISession session)
{
}
public void HandleEvent(ForceMoveDoneEvent evt, ISession session)
{
}
public void HandleEvent(FortFailedEvent evt, ISession session)
{
}
public void HandleEvent(InvalidKeepAmountEvent evt, ISession session)
{
}
public void HandleEvent(InventoryListEvent evt, ISession session)
{
}
public void HandleEvent(InventoryNewItemsEvent evt, ISession session)
{
}
public void HandleEvent(EggFoundEvent evt, ISession session)
{
}
public void HandleEvent(NextRouteEvent evt, ISession session)
{
}
public void HandleEvent(PlayerLevelUpEvent evt, ISession session)
{
}
public void HandleEvent(PlayerStatsEvent evt, ISession session)
{
}
public void HandleEvent(PokemonDisappearEvent evt, ISession session)
{
session.Stats.EncountersNow++;
}
public void HandleEvent(PokemonEvolveDoneEvent evt, ISession session)
{
session.Stats.TotalEvolves++;
session.Stats.RefreshPokeDex(session);
}
public void HandleEvent(PokemonFavoriteEvent evt, ISession session)
{
}
public void HandleEvent(PokemonSettingsEvent evt, ISession session)
{
}
public void HandleEvent(PokemonsFoundEvent evt, ISession session)
{
}
public void HandleEvent(PokemonsWildFoundEvent evt, ISession session)
{
}
public void HandleEvent(PokemonStatsChangedEvent evt, ISession session)
{
}
public void HandleEvent(PokeStopListEvent evt, ISession session)
{
}
public void HandleEvent(SnipeEvent evt, ISession session)
{
}
public void HandleEvent(SnipeModeEvent evt, ISession session)
{
}
public void HandleEvent(UseLuckyEggMinPokemonEvent evt, ISession session)
{
}
public void HandleEvent(PokemonListEvent evt, ISession session)
{
}
public void HandleEvent(GymPokeEvent evt, ISession session)
{
}
public void HandleEvent(PokestopsOptimalPathEvent evt, ISession session)
{
}
public void HandleEvent(TeamSetEvent evt, ISession session)
{
}
public void HandleEvent(ItemLostEvent evt, ISession session)
{
}
public void Listen(IEvent evt, ISession session)
{
try
{
dynamic eve = evt;
HandleEvent(eve, session);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
}
}
}
} | Lunat1q/Catchem-PoGo | Source/PoGo.PokeMobBot.Logic/StatisticsAggregator.cs | C# | gpl-3.0 | 7,499 |
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member (no intention to document this file)
namespace RobinHood70.WallE.Base
{
public class AllCategoriesItem
{
#region Constructors
internal AllCategoriesItem(string category, int files, bool hidden, int pages, int size, int subcats)
{
this.Category = category;
this.Files = files;
this.Hidden = hidden;
this.Pages = pages;
this.Size = size;
this.Subcategories = subcats;
}
#endregion
#region Public Properties
public string Category { get; }
public int Files { get; }
public bool Hidden { get; }
public int Pages { get; }
public int Size { get; }
public int Subcategories { get; }
#endregion
#region Public Override Methods
public override string ToString() => this.Category;
#endregion
}
}
| RobinHood70/HoodBot | WallE/Base/Outputs/AllCategoriesItem.cs | C# | gpl-3.0 | 839 |
'''WARCAT: Web ARChive (WARC) Archiving Tool
Tool and library for handling Web ARChive (WARC) files.
'''
from .version import *
| chfoo/warcat | warcat/__init__.py | Python | gpl-3.0 | 130 |
/*
* Symphony - A modern community (forum/SNS/blog) platform written in Java.
* Copyright (C) 2012-2017, b3log.org & hacpai.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 org.b3log.symphony.processor;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.Latkes;
import org.b3log.latke.ioc.inject.Inject;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.After;
import org.b3log.latke.servlet.annotation.Before;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer;
import org.b3log.latke.util.Locales;
import org.b3log.latke.util.Stopwatchs;
import org.b3log.latke.util.Strings;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.processor.advice.AnonymousViewCheck;
import org.b3log.symphony.processor.advice.PermissionGrant;
import org.b3log.symphony.processor.advice.stopwatch.StopwatchEndAdvice;
import org.b3log.symphony.processor.advice.stopwatch.StopwatchStartAdvice;
import org.b3log.symphony.service.*;
import org.b3log.symphony.util.Emotions;
import org.b3log.symphony.util.Markdowns;
import org.b3log.symphony.util.Symphonys;
import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;
/**
* Index processor.
* <p>
* <ul>
* <li>Shows index (/), GET</li>
* <li>Shows recent articles (/recent), GET</li>
* <li>Shows hot articles (/hot), GET</li>
* <li>Shows perfect articles (/perfect), GET</li>
* <li>Shows about (/about), GET</li>
* <li>Shows b3log (/b3log), GET</li>
* <li>Shows SymHub (/symhub), GET</li>
* <li>Shows kill browser (/kill-browser), GET</li>
* </ul>
* </p>
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @version 1.12.3.24, Dec 26, 2016
* @since 0.2.0
*/
@RequestProcessor
public class IndexProcessor {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(IndexProcessor.class.getName());
/**
* Article query service.
*/
@Inject
private ArticleQueryService articleQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* User management service.
*/
@Inject
private UserMgmtService userMgmtService;
/**
* Data model service.
*/
@Inject
private DataModelService dataModelService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Timeline management service.
*/
@Inject
private TimelineMgmtService timelineMgmtService;
/**
* Shows md guide.
*
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/guide/markdown", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showMDGuide(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("other/md-guide.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
InputStream inputStream = null;
try {
inputStream = IndexProcessor.class.getResourceAsStream("/md_guide.md");
final String md = IOUtils.toString(inputStream, "UTF-8");
String html = Emotions.convert(md);
html = Markdowns.toHTML(html);
dataModel.put("md", md);
dataModel.put("html", html);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Loads markdown guide failed", e);
} finally {
IOUtils.closeQuietly(inputStream);
}
dataModelService.fillHeaderAndFooter(request, response, dataModel);
}
/**
* Shows index.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = {"", "/"}, method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showIndex(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("index.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
final List<JSONObject> recentArticles = articleQueryService.getIndexRecentArticles(avatarViewMode);
dataModel.put(Common.RECENT_ARTICLES, recentArticles);
JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null == currentUser) {
userMgmtService.tryLogInWithCookie(request, context.getResponse());
}
currentUser = userQueryService.getCurrentUser(request);
if (null != currentUser) {
if (!UserExt.finshedGuide(currentUser)) {
response.sendRedirect(Latkes.getServePath() + "/guide");
return;
}
final String userId = currentUser.optString(Keys.OBJECT_ID);
final int pageSize = Symphonys.getInt("indexArticlesCnt");
final List<JSONObject> followingTagArticles = articleQueryService.getFollowingTagArticles(
avatarViewMode, userId, 1, pageSize);
dataModel.put(Common.FOLLOWING_TAG_ARTICLES, followingTagArticles);
final List<JSONObject> followingUserArticles = articleQueryService.getFollowingUserArticles(
avatarViewMode, userId, 1, pageSize);
dataModel.put(Common.FOLLOWING_USER_ARTICLES, followingUserArticles);
} else {
dataModel.put(Common.FOLLOWING_TAG_ARTICLES, Collections.emptyList());
dataModel.put(Common.FOLLOWING_USER_ARTICLES, Collections.emptyList());
}
final List<JSONObject> perfectArticles = articleQueryService.getIndexPerfectArticles(avatarViewMode);
dataModel.put(Common.PERFECT_ARTICLES, perfectArticles);
final List<JSONObject> timelines = timelineMgmtService.getTimelines();
dataModel.put(Common.TIMELINES, timelines);
dataModel.put(Common.SELECTED, Common.INDEX);
dataModelService.fillHeaderAndFooter(request, response, dataModel);
dataModelService.fillIndexTags(dataModel);
}
/**
* Shows recent articles.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = {"/recent", "/recent/hot", "/recent/good", "/recent/reply"}, method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showRecent(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("recent.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
int pageSize = Symphonys.getInt("indexArticlesCnt");
final JSONObject user = userQueryService.getCurrentUser(request);
if (null != user) {
pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE);
if (!UserExt.finshedGuide(user)) {
response.sendRedirect(Latkes.getServePath() + "/guide");
return;
}
}
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
String sortModeStr = StringUtils.substringAfter(request.getRequestURI(), "/recent");
int sortMode;
switch (sortModeStr) {
case "":
sortMode = 0;
break;
case "/hot":
sortMode = 1;
break;
case "/good":
sortMode = 2;
break;
case "/reply":
sortMode = 3;
break;
default:
sortMode = 0;
}
final JSONObject result = articleQueryService.getRecentArticles(avatarViewMode, sortMode, pageNum, pageSize);
final List<JSONObject> allArticles = (List<JSONObject>) result.get(Article.ARTICLES);
dataModel.put(Common.SELECTED, Common.RECENT);
final List<JSONObject> stickArticles = new ArrayList<>();
final Iterator<JSONObject> iterator = allArticles.iterator();
while (iterator.hasNext()) {
final JSONObject article = iterator.next();
final boolean stick = article.optInt(Article.ARTICLE_T_STICK_REMAINS) > 0;
article.put(Article.ARTICLE_T_IS_STICK, stick);
if (stick) {
stickArticles.add(article);
iterator.remove();
}
}
dataModel.put(Common.STICK_ARTICLES, stickArticles);
dataModel.put(Common.LATEST_ARTICLES, allArticles);
final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION);
final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT);
final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModelService.fillHeaderAndFooter(request, response, dataModel);
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
dataModel.put(Common.CURRENT, StringUtils.substringAfter(request.getRequestURI(), "/recent"));
}
/**
* Shows hot articles.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/hot", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHotArticles(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("hot.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
int pageSize = Symphonys.getInt("indexArticlesCnt");
final JSONObject user = userQueryService.getCurrentUser(request);
if (null != user) {
pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE);
}
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
final List<JSONObject> indexArticles = articleQueryService.getHotArticles(avatarViewMode, pageSize);
dataModel.put(Common.INDEX_ARTICLES, indexArticles);
dataModel.put(Common.SELECTED, Common.HOT);
Stopwatchs.start("Fills");
try {
dataModelService.fillHeaderAndFooter(request, response, dataModel);
if (!(Boolean) dataModel.get(Common.IS_MOBILE)) {
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
}
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
} finally {
Stopwatchs.end();
}
}
/**
* Shows SymHub page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/symhub", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showSymHub(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("other/symhub.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
final List<JSONObject> syms = Symphonys.getSyms();
dataModel.put("syms", (Object) syms);
Stopwatchs.start("Fills");
try {
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
dataModelService.fillHeaderAndFooter(request, response, dataModel);
if (!(Boolean) dataModel.get(Common.IS_MOBILE)) {
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
}
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
} finally {
Stopwatchs.end();
}
}
/**
* Shows perfect articles.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/perfect", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showPerfectArticles(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("perfect.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
int pageSize = Symphonys.getInt("indexArticlesCnt");
final JSONObject user = userQueryService.getCurrentUser(request);
if (null != user) {
pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE);
if (!UserExt.finshedGuide(user)) {
response.sendRedirect(Latkes.getServePath() + "/guide");
return;
}
}
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
final JSONObject result = articleQueryService.getPerfectArticles(avatarViewMode, pageNum, pageSize);
final List<JSONObject> perfectArticles = (List<JSONObject>) result.get(Article.ARTICLES);
dataModel.put(Common.PERFECT_ARTICLES, perfectArticles);
dataModel.put(Common.SELECTED, Common.PERFECT);
final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION);
final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT);
final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModelService.fillHeaderAndFooter(request, response, dataModel);
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
}
/**
* Shows about.
*
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/about", method = HTTPRequestMethod.GET)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = StopwatchEndAdvice.class)
public void showAbout(final HttpServletResponse response) throws Exception {
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", "https://hacpai.com/article/1440573175609");
response.flushBuffer();
}
/**
* Shows b3log.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/b3log", method = HTTPRequestMethod.GET)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showB3log(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("other/b3log.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
}
/**
* Shows kill browser page with the specified context.
*
* @param context the specified context
* @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response
*/
@RequestProcessing(value = "/kill-browser", method = HTTPRequestMethod.GET)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = StopwatchEndAdvice.class)
public void showKillBrowser(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
renderer.setTemplateName("other/kill-browser.ftl");
context.setRenderer(renderer);
final Map<String, Object> dataModel = renderer.getDataModel();
final Map<String, String> langs = langPropsService.getAll(Locales.getLocale());
dataModel.putAll(langs);
Keys.fillRuntime(dataModel);
dataModelService.fillMinified(dataModel);
}
}
| BrickCat/symphony | src/main/java/org/b3log/symphony/processor/IndexProcessor.java | Java | gpl-3.0 | 21,728 |
/*
Copyright 2011 MCForge
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
http://www.osedu.org/licenses/ECL-2.0
http://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.IO;
namespace MCForge
{
public class CmdMap : Command
{
public override string name { get { return "map"; } }
public override string shortcut { get { return ""; } }
public override string type { get { return "mod"; } }
public override bool museumUsable { get { return true; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public CmdMap() { }
public override void Use(Player p, string message)
{
if (message == "") message = p.level.name;
Level foundLevel;
if (message.IndexOf(' ') == -1)
{
foundLevel = Level.Find(message);
if (foundLevel == null)
{
if (p != null)
{
foundLevel = p.level;
}
}
else
{
Player.SendMessage(p, "MOTD: &b" + foundLevel.motd);
Player.SendMessage(p, "Finite mode: " + FoundCheck(foundLevel.finite));
Player.SendMessage(p, "Animal AI: " + FoundCheck(foundLevel.ai));
Player.SendMessage(p, "Edge water: " + FoundCheck(foundLevel.edgeWater));
Player.SendMessage(p, "Grass growing: " + FoundCheck(foundLevel.GrassGrow));
Player.SendMessage(p, "Physics speed: &b" + foundLevel.speedPhysics);
Player.SendMessage(p, "Physics overload: &b" + foundLevel.overload);
Player.SendMessage(p, "Survival death: " + FoundCheck(foundLevel.Death) + "(Fall: " + foundLevel.fall + ", Drown: " + foundLevel.drown + ")");
Player.SendMessage(p, "Killer blocks: " + FoundCheck(foundLevel.Killer));
Player.SendMessage(p, "Unload: " + FoundCheck(foundLevel.unload));
Player.SendMessage(p, "Auto physics: " + FoundCheck(foundLevel.rp));
Player.SendMessage(p, "Instant building: " + FoundCheck(foundLevel.Instant));
Player.SendMessage(p, "RP chat: " + FoundCheck(!foundLevel.worldChat));
return;
}
}
else
{
foundLevel = Level.Find(message.Split(' ')[0]);
if (foundLevel == null || message.Split(' ')[0].ToLower() == "ps" || message.Split(' ')[0].ToLower() == "rp") foundLevel = p.level;
else message = message.Substring(message.IndexOf(' ') + 1);
}
if (p != null)
if (p.group.Permission < LevelPermission.Operator) { Player.SendMessage(p, "Setting map options is reserved to OP+"); return; }
string foundStart;
if (message.IndexOf(' ') == -1) foundStart = message.ToLower();
else foundStart = message.Split(' ')[0].ToLower();
try
{
switch (foundStart)
{
case "theme": foundLevel.theme = message.Substring(message.IndexOf(' ') + 1); foundLevel.ChatLevel("Map theme: &b" + foundLevel.theme); break;
case "finite": foundLevel.finite = !foundLevel.finite; foundLevel.ChatLevel("Finite mode: " + FoundCheck(foundLevel.finite)); break;
case "ai": foundLevel.ai = !foundLevel.ai; foundLevel.ChatLevel("Animal AI: " + FoundCheck(foundLevel.ai)); break;
case "edge": foundLevel.edgeWater = !foundLevel.edgeWater; foundLevel.ChatLevel("Edge water: " + FoundCheck(foundLevel.edgeWater)); break;
case "grass": foundLevel.GrassGrow = !foundLevel.GrassGrow; foundLevel.ChatLevel("Growing grass: " + FoundCheck(foundLevel.GrassGrow)); break;
case "ps":
case "physicspeed":
if (int.Parse(message.Split(' ')[1]) < 10) { Player.SendMessage(p, "Cannot go below 10"); return; }
foundLevel.speedPhysics = int.Parse(message.Split(' ')[1]);
foundLevel.ChatLevel("Physics speed: &b" + foundLevel.speedPhysics);
break;
case "overload":
if (int.Parse(message.Split(' ')[1]) < 500) { Player.SendMessage(p, "Cannot go below 500 (default is 1500)"); return; }
if (p.group.Permission < LevelPermission.Admin && int.Parse(message.Split(' ')[1]) > 2500) { Player.SendMessage(p, "Only SuperOPs may set higher than 2500"); return; }
foundLevel.overload = int.Parse(message.Split(' ')[1]);
foundLevel.ChatLevel("Physics overload: &b" + foundLevel.overload);
break;
case "motd":
if (message.Split(' ').Length == 1) foundLevel.motd = "ignore";
else foundLevel.motd = message.Substring(message.IndexOf(' ') + 1);
foundLevel.ChatLevel("Map MOTD: &b" + foundLevel.motd);
break;
case "death": foundLevel.Death = !foundLevel.Death; foundLevel.ChatLevel("Survival death: " + FoundCheck(foundLevel.Death)); break;
case "killer": foundLevel.Killer = !foundLevel.Killer; foundLevel.ChatLevel("Killer blocks: " + FoundCheck(foundLevel.Killer)); break;
case "fall": foundLevel.fall = int.Parse(message.Split(' ')[1]); foundLevel.ChatLevel("Fall distance: &b" + foundLevel.fall); break;
case "drown": foundLevel.drown = int.Parse(message.Split(' ')[1]) * 10; foundLevel.ChatLevel("Drown time: &b" + (foundLevel.drown / 10)); break;
case "unload": foundLevel.unload = !foundLevel.unload; foundLevel.ChatLevel("Auto unload: " + FoundCheck(foundLevel.unload)); break;
case "rp":
case "restartphysics": foundLevel.rp = !foundLevel.rp; foundLevel.ChatLevel("Auto physics: " + FoundCheck(foundLevel.rp)); break;
case "instant":
if (p.group.Permission < LevelPermission.Admin) { Player.SendMessage(p, "This is reserved for Super+"); return; }
foundLevel.Instant = !foundLevel.Instant; foundLevel.ChatLevel("Instant building: " + FoundCheck(foundLevel.Instant)); break;
case "chat":
foundLevel.worldChat = !foundLevel.worldChat; foundLevel.ChatLevel("RP chat: " + FoundCheck(!foundLevel.worldChat)); break;
default:
Player.SendMessage(p, "Could not find option entered.");
return;
}
foundLevel.changed = true;
if (p.level != foundLevel) Player.SendMessage(p, "/map finished!");
}
catch { Player.SendMessage(p, "INVALID INPUT"); }
}
public string FoundCheck(bool check)
{
if (check) return "&aON";
else return "&cOFF";
}
public override void Help(Player p)
{
Player.SendMessage(p, "/map [level] [toggle] - Sets [toggle] on [map]");
Player.SendMessage(p, "Possible toggles: theme, finite, ai, edge, ps, overload, motd, death, fall, drown, unload, rp, instant, killer, chat");
Player.SendMessage(p, "Edge will cause edge water to flow.");
Player.SendMessage(p, "Grass will make grass not grow without physics");
Player.SendMessage(p, "Finite will cause all liquids to be finite.");
Player.SendMessage(p, "AI will make animals hunt or flee.");
Player.SendMessage(p, "PS will set the map's physics speed.");
Player.SendMessage(p, "Overload will change how easy/hard it is to kill physics.");
Player.SendMessage(p, "MOTD will set a custom motd for the map. (leave blank to reset)");
Player.SendMessage(p, "Death will allow survival-style dying (falling, drowning)");
Player.SendMessage(p, "Fall/drown set the distance/time before dying from each.");
Player.SendMessage(p, "Killer turns killer blocks on and off.");
Player.SendMessage(p, "Unload sets whether the map unloads when no one's there.");
Player.SendMessage(p, "RP sets whether the physics auto-start for the map");
Player.SendMessage(p, "Instant mode works by not updating everyone's screens");
Player.SendMessage(p, "Chat sets the map to recieve no messages from other maps");
}
}
} | colinodell/mcforge | Commands/CmdMap.cs | C# | gpl-3.0 | 9,301 |
require 'test/unit'
class FizzbuzzTest < Test::Unit::TestCase
# Called before every test method runs. Can be used
# to set up fixture information.
def setup
# Do nothing
end
# Called after every test method runs. Can be used to tear
# down fixture information.
def teardown
# Do nothing
end
# Fake test
def test_fail
expected = 1
actual =1
assert_same expected, actual
# fail('Not implemented')
end
def test_fizzbuzz
require './fizzbuzz.d/rb-fizzbuzz'
res=[]
1.upto(100).each {|e|
next if fizbuz e, res
next if fiz e, res
next if buz e, res
res << e
}
assert_same 100, res.length
end
end | rogeraaut/rogeraaut.github.io | lang.ruby.d/tests/fizzbuzz_test.rb | Ruby | gpl-3.0 | 688 |
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Newegg.Oversea.Silverlight.ControlPanel.Core.Base;
using ECCentral.BizEntity.Enum;
using ECCentral.BizEntity.MKT;
using Newegg.Oversea.Silverlight.Utilities.Validation;
using ECCentral.BizEntity;
namespace ECCentral.Portal.UI.MKT.Models
{
public class AmbassadorNewsVM : ModelBase
{
public string CompanyCode { get; set; }
public int? SysNo { get; set; }
private int? _ReferenceSysNo;
public int? ReferenceSysNo
{
get { return _ReferenceSysNo; }
set { base.SetValue("ReferenceSysNo", ref _ReferenceSysNo, value); }
}
private string _Title;
[Validate(ValidateType.Required)]
[Validate(ValidateType.MaxLength,100)]
public string Title
{
get { return _Title; }
set { base.SetValue("Title", ref _Title, value); }
}
private string _Content;
[Validate(ValidateType.Required)]
public string Content
{
get { return _Content; }
set { base.SetValue("Content", ref _Content, value); }
}
private AmbassadorNewsStatus? status;
[Validate(ValidateType.Required)]
public AmbassadorNewsStatus? Status
{
get { return status; }
set { base.SetValue("Status", ref status, value); }
}
}
}
| ZeroOne71/ql | 02_ECCentral/02_Portal/UI/ECCentral.Portal.UI.MKT/NeweggCN/Models/AmbassadorNewsVM.cs | C# | gpl-3.0 | 1,650 |
using ServiceStack.OrmLite;
using System;
using System.Configuration;
using System.Data;
namespace Bm2s.Data.Utils
{
/// <summary>
/// Data access point
/// </summary>
public class Datas
{
/// <summary>
/// Database provider
/// </summary>
private IOrmLiteDialectProvider _dbProvider;
/// <summary>
/// Gets the database provider
/// </summary>
public IOrmLiteDialectProvider DbProvider
{
get
{
if (this._dbProvider == null)
{
switch (ConfigurationManager.AppSettings["DbProvider"].ToLower())
{
case "oracle":
this._dbProvider = OracleDialect.Provider;
break;
case "mysql" :
this._dbProvider = MySqlDialect.Provider;
break;
case "postgresql":
this._dbProvider = PostgreSqlDialect.Provider;
break;
case "mssqlserver":
this._dbProvider = SqlServerDialect.Provider;
break;
default:
this._dbProvider = null;
break;
}
}
return this._dbProvider;
}
}
/// <summary>
/// Database connection
/// </summary>
private IDbConnection _dbConnection;
/// <summary>
/// Gets the database connection
/// </summary>
public IDbConnection DbConnection
{
get
{
if (this._dbConnection == null)
{
this._dbConnection = this.DbConnectionFactory.OpenDbConnection();
}
return this._dbConnection;
}
}
/// <summary>
/// Database connection factory
/// </summary>
private IDbConnectionFactory _dbConnectionFactory;
/// <summary>
/// Gets the database connection factory
/// </summary>
public IDbConnectionFactory DbConnectionFactory
{
get
{
if (this._dbConnectionFactory == null)
{
this._dbConnectionFactory = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["bm2s"].ConnectionString, this.DbProvider);
}
return this._dbConnectionFactory;
}
}
/// <summary>
/// Constructor for the singleton
/// </summary>
protected Datas()
{
this.CheckDatabaseSchema();
}
/// <summary>
/// Creation of the schemas
/// </summary>
public virtual void CheckDatabaseSchema()
{
}
/// <summary>
/// Create datas for the first use
/// </summary>
public virtual void CheckFirstUseDatas()
{
}
}
}
| Csluikidikilest/Bm2sServer | Bm2s.Data.Utils/Datas.cs | C# | gpl-3.0 | 2,584 |
/**
* Created by caimiao on 15-6-14.
*/
define(function(require, exports, module) {
exports.hello= function (echo) {
alert(echo);
};
}) | caimmy/prehistory | static/js/js_modules/archjs_tools.js | JavaScript | gpl-3.0 | 154 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_sciclubpadova
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
* SciClubPadova Model
*
* @since 0.0.1
*/
class SciClubPadovaModelSciClubPadova extends JModelItem
{
/**
* @var object item
*/
protected $item;
/**
* Method to auto-populate the model state.
*
* This method should only be called once per instantiation and is designed
* to be called on the first call to the getState() method unless the model
* configuration flag to ignore the request is set.
*
* Note. Calling getState in this method will result in recursion.
*
* @return void
* @since 2.5
*/
protected function populateState()
{
// Get the message id
$jinput = JFactory::getApplication()->input;
$id = $jinput->get('id', 1, 'INT');
$this->setState('message.id', $id);
// Load the parameters.
$this->setState('params', JFactory::getApplication()->getParams());
parent::populateState();
}
/**
* Method to get a table object, load it if necessary.
*
* @param string $type The table name. Optional.
* @param string $prefix The class prefix. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return JTable A JTable object
*
* @since 1.6
*/
public function getTable($type = 'SciClubPadova', $prefix = 'SciClubPadovaTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
/**
* Get the message
* @return object The message to be displayed to the user
*/
public function getItem()
{
if (!isset($this->item))
{
$id = $this->getState('message.id');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('h.greeting, h.params, c.title as category')
->from('#__sciclubpadova as h')
->leftJoin('#__categories as c ON h.catid=c.id')
->where('h.id=' . (int)$id);
$db->setQuery((string)$query);
if ($this->item = $db->loadObject())
{
// Load the JSON string
$params = new JRegistry;
$params->loadString($this->item->params, 'JSON');
$this->item->params = $params;
// Merge global params with item params
$params = clone $this->getState('params');
$params->merge($this->item->params);
$this->item->params = $params;
}
}
return $this->item;
}
}
| lancillot72/JSCE | com_sciclubpadova/site/models/sciclubpadova.php | PHP | gpl-3.0 | 2,647 |
<?php
/** PHPExcel root directory */
if (!defined('PHPEXCEL_ROOT')) {
/**
* @ignore
*/
define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}
/**
* PHPExcel_Reader_SYLK
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Reader
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_Reader_SYLK extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader
{
/**
* Input encoding
*
* @var string
*/
private $inputEncoding = 'ANSI';
/**
* Sheet index to read
*
* @var int
*/
private $sheetIndex = 0;
/**
* Formats
*
* @var array
*/
private $formats = array();
/**
* Format Count
*
* @var int
*/
private $format = 0;
/**
* Create a new PHPExcel_Reader_SYLK
*/
public function __construct()
{
$this->readFilter = new PHPExcel_Reader_DefaultReadFilter();
}
/**
* Validate that the current file is a SYLK file
*
* @return boolean
*/
protected function isValidFormat()
{
// Read sample data (first 2 KB will do)
$data = fread($this->fileHandle, 2048);
// Count delimiters in file
$delimiterCount = substr_count($data, ';');
if ($delimiterCount < 1) {
return false;
}
// Analyze first line looking for ID; signature
$lines = explode("\n", $data);
if (substr($lines[0], 0, 4) != 'ID;P') {
return false;
}
return true;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'ANSI')
{
$this->inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->inputEncoding;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
*
* @param string $pFilename
* @throws PHPExcel_Reader_Exception
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->openFile($pFilename);
if (!$this->isValidFormat()) {
fclose($this->fileHandle);
throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->fileHandle;
rewind($fileHandle);
$worksheetInfo = array();
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
// Loop through file
$rowData = array();
// loop through one row (line) at a time in the file
$rowIndex = 0;
while (($rowData = fgets($fileHandle)) !== false) {
$columnIndex = 0;
// convert SYLK encoded $rowData to UTF-8
$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
$dataType = array_shift($rowData);
if ($dataType == 'C') {
// Read cell value data
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$columnIndex = substr($rowDatum, 1) - 1;
break;
case 'R':
case 'Y':
$rowIndex = substr($rowDatum, 1);
break;
}
$worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex);
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex);
}
}
}
$worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
// Close file
fclose($fileHandle);
return $worksheetInfo;
}
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel_Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel
$objPHPExcel = new PHPExcel();
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel $objPHPExcel
* @return PHPExcel
* @throws PHPExcel_Reader_Exception
*/
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
{
// Open file
$this->openFile($pFilename);
if (!$this->isValidFormat()) {
fclose($this->fileHandle);
throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->fileHandle;
rewind($fileHandle);
// Create new PHPExcel
while ($objPHPExcel->getSheetCount() <= $this->sheetIndex) {
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex($this->sheetIndex);
$fromFormats = array('\-', '\ ');
$toFormats = array('-', ' ');
// Loop through file
$rowData = array();
$column = $row = '';
// loop through one row (line) at a time in the file
while (($rowData = fgets($fileHandle)) !== false) {
// convert SYLK encoded $rowData to UTF-8
$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
$dataType = array_shift($rowData);
// Read shared styles
if ($dataType == 'P') {
$formatArray = array();
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'P':
$formatArray['numberformat']['code'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1));
break;
case 'E':
case 'F':
$formatArray['font']['name'] = substr($rowDatum, 1);
break;
case 'L':
$formatArray['font']['size'] = substr($rowDatum, 1);
break;
case 'S':
$styleSettings = substr($rowDatum, 1);
for ($i=0; $i<strlen($styleSettings); ++$i) {
switch ($styleSettings{$i}) {
case 'I':
$formatArray['font']['italic'] = true;
break;
case 'D':
$formatArray['font']['bold'] = true;
break;
case 'T':
$formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'B':
$formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'L':
$formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'R':
$formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
$this->formats['P'.$this->format++] = $formatArray;
// Read cell value data
} elseif ($dataType == 'C') {
$hasCalculatedValue = false;
$cellData = $cellDataFormula = '';
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
case 'K':
$cellData = substr($rowDatum, 1);
break;
case 'E':
$cellDataFormula = '='.substr($rowDatum, 1);
// Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"', $cellDataFormula);
$key = false;
foreach ($temp as &$value) {
// Only count/replace in alternate array entries
if ($key = !$key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER+PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
// the formula
$cellReferences = array_reverse($cellReferences);
// Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
// then modify the formula to use that new reference
foreach ($cellReferences as $cellReference) {
$rowReference = $cellReference[2][0];
// Empty R reference is the current row
if ($rowReference == '') {
$rowReference = $row;
}
// Bracketed R references are relative to the current row
if ($rowReference{0} == '[') {
$rowReference = $row + trim($rowReference, '[]');
}
$columnReference = $cellReference[4][0];
// Empty C reference is the current column
if ($columnReference == '') {
$columnReference = $column;
}
// Bracketed C references are relative to the current column
if ($columnReference{0} == '[') {
$columnReference = $column + trim($columnReference, '[]');
}
$A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference;
$value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
}
}
}
unset($value);
// Then rebuild the formula string
$cellDataFormula = implode('"', $temp);
$hasCalculatedValue = true;
break;
}
}
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
$cellData = PHPExcel_Calculation::unwrapResult($cellData);
// Set cell value
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
if ($hasCalculatedValue) {
$cellData = PHPExcel_Calculation::unwrapResult($cellData);
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData);
}
// Read cell formatting
} elseif ($dataType == 'F') {
$formatStyle = $columnWidth = $styleSettings = '';
$styleData = array();
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
case 'P':
$formatStyle = $rowDatum;
break;
case 'W':
list($startCol, $endCol, $columnWidth) = explode(' ', substr($rowDatum, 1));
break;
case 'S':
$styleSettings = substr($rowDatum, 1);
for ($i=0; $i<strlen($styleSettings); ++$i) {
switch ($styleSettings{$i}) {
case 'I':
$styleData['font']['italic'] = true;
break;
case 'D':
$styleData['font']['bold'] = true;
break;
case 'T':
$styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'B':
$styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'L':
$styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'R':
$styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
if (($formatStyle > '') && ($column > '') && ($row > '')) {
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
if (isset($this->formats[$formatStyle])) {
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->formats[$formatStyle]);
}
}
if ((!empty($styleData)) && ($column > '') && ($row > '')) {
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData);
}
if ($columnWidth > '') {
if ($startCol == $endCol) {
$startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
} else {
$startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
$endCol = PHPExcel_Cell::stringFromColumnIndex($endCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
do {
$objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
} while ($startCol != $endCol);
}
}
} else {
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
}
}
}
}
// Close file
fclose($fileHandle);
// Return
return $objPHPExcel;
}
/**
* Get sheet index
*
* @return int
*/
public function getSheetIndex()
{
return $this->sheetIndex;
}
/**
* Set sheet index
*
* @param int $pValue Sheet index
* @return PHPExcel_Reader_SYLK
*/
public function setSheetIndex($pValue = 0)
{
$this->sheetIndex = $pValue;
return $this;
}
}
| Aiwings/FNMNS_Formations | assets/PHPExcel/Classes/PHPExcel/Reader/SYLK.php | PHP | gpl-3.0 | 12,367 |
import math
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtGui import QCloseEvent
from PyQt5.QtWidgets import QDialog, QInputDialog
from urh import settings
from urh.models.FuzzingTableModel import FuzzingTableModel
from urh.signalprocessing.ProtocoLabel import ProtocolLabel
from urh.signalprocessing.ProtocolAnalyzerContainer import ProtocolAnalyzerContainer
from urh.ui.ui_fuzzing import Ui_FuzzingDialog
class FuzzingDialog(QDialog):
def __init__(self, protocol: ProtocolAnalyzerContainer, label_index: int, msg_index: int, proto_view: int,
parent=None):
super().__init__(parent)
self.ui = Ui_FuzzingDialog()
self.ui.setupUi(self)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowFlags(Qt.Window)
self.protocol = protocol
msg_index = msg_index if msg_index != -1 else 0
self.ui.spinBoxFuzzMessage.setValue(msg_index + 1)
self.ui.spinBoxFuzzMessage.setMinimum(1)
self.ui.spinBoxFuzzMessage.setMaximum(self.protocol.num_messages)
self.ui.comboBoxFuzzingLabel.addItems([l.name for l in self.message.message_type])
self.ui.comboBoxFuzzingLabel.setCurrentIndex(label_index)
self.proto_view = proto_view
self.fuzz_table_model = FuzzingTableModel(self.current_label, proto_view)
self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked()
self.ui.tblFuzzingValues.setModel(self.fuzz_table_model)
self.fuzz_table_model.update()
self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
self.ui.spinBoxFuzzingStart.setMaximum(len(self.message_data))
self.ui.spinBoxFuzzingEnd.setMaximum(len(self.message_data))
self.update_message_data_string()
self.ui.tblFuzzingValues.resize_me()
self.create_connects()
self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes))
@property
def message(self):
return self.protocol.messages[int(self.ui.spinBoxFuzzMessage.value() - 1)]
@property
def current_label_index(self):
return self.ui.comboBoxFuzzingLabel.currentIndex()
@property
def current_label(self) -> ProtocolLabel:
if len(self.message.message_type) == 0:
return None
cur_label = self.message.message_type[self.current_label_index].get_copy()
self.message.message_type[self.current_label_index] = cur_label
cur_label.fuzz_values = [fv for fv in cur_label.fuzz_values if fv] # Remove empty strings
if len(cur_label.fuzz_values) == 0:
cur_label.fuzz_values.append(self.message.plain_bits_str[cur_label.start:cur_label.end])
return cur_label
@property
def current_label_start(self):
if self.current_label and self.message:
return self.message.get_label_range(self.current_label, self.proto_view, False)[0]
else:
return -1
@property
def current_label_end(self):
if self.current_label and self.message:
return self.message.get_label_range(self.current_label, self.proto_view, False)[1]
else:
return -1
@property
def message_data(self):
if self.proto_view == 0:
return self.message.plain_bits_str
elif self.proto_view == 1:
return self.message.plain_hex_str
elif self.proto_view == 2:
return self.message.plain_ascii_str
else:
return None
def create_connects(self):
self.ui.spinBoxFuzzingStart.valueChanged.connect(self.on_fuzzing_start_changed)
self.ui.spinBoxFuzzingEnd.valueChanged.connect(self.on_fuzzing_end_changed)
self.ui.comboBoxFuzzingLabel.currentIndexChanged.connect(self.on_combo_box_fuzzing_label_current_index_changed)
self.ui.btnRepeatValues.clicked.connect(self.on_btn_repeat_values_clicked)
self.ui.btnAddRow.clicked.connect(self.on_btn_add_row_clicked)
self.ui.btnDelRow.clicked.connect(self.on_btn_del_row_clicked)
self.ui.tblFuzzingValues.deletion_wanted.connect(self.delete_lines)
self.ui.chkBRemoveDuplicates.stateChanged.connect(self.on_remove_duplicates_state_changed)
self.ui.sBAddRangeStart.valueChanged.connect(self.on_fuzzing_range_start_changed)
self.ui.sBAddRangeEnd.valueChanged.connect(self.on_fuzzing_range_end_changed)
self.ui.checkBoxLowerBound.stateChanged.connect(self.on_lower_bound_checked_changed)
self.ui.checkBoxUpperBound.stateChanged.connect(self.on_upper_bound_checked_changed)
self.ui.spinBoxLowerBound.valueChanged.connect(self.on_lower_bound_changed)
self.ui.spinBoxUpperBound.valueChanged.connect(self.on_upper_bound_changed)
self.ui.spinBoxRandomMinimum.valueChanged.connect(self.on_random_range_min_changed)
self.ui.spinBoxRandomMaximum.valueChanged.connect(self.on_random_range_max_changed)
self.ui.spinBoxFuzzMessage.valueChanged.connect(self.on_fuzz_msg_changed)
self.ui.btnAddFuzzingValues.clicked.connect(self.on_btn_add_fuzzing_values_clicked)
self.ui.comboBoxFuzzingLabel.editTextChanged.connect(self.set_current_label_name)
def update_message_data_string(self):
fuz_start = self.current_label_start
fuz_end = self.current_label_end
num_proto_bits = 10
num_fuz_bits = 16
proto_start = fuz_start - num_proto_bits
preambel = "... "
if proto_start <= 0:
proto_start = 0
preambel = ""
proto_end = fuz_end + num_proto_bits
postambel = " ..."
if proto_end >= len(self.message_data) - 1:
proto_end = len(self.message_data) - 1
postambel = ""
fuzamble = ""
if fuz_end - fuz_start > num_fuz_bits:
fuz_end = fuz_start + num_fuz_bits
fuzamble = "..."
self.ui.lPreBits.setText(preambel + self.message_data[proto_start:self.current_label_start])
self.ui.lFuzzedBits.setText(self.message_data[fuz_start:fuz_end] + fuzamble)
self.ui.lPostBits.setText(self.message_data[self.current_label_end:proto_end] + postambel)
self.set_add_spinboxes_maximum_on_label_change()
def closeEvent(self, event: QCloseEvent):
settings.write("{}/geometry".format(self.__class__.__name__), self.saveGeometry())
super().closeEvent(event)
@pyqtSlot(int)
def on_fuzzing_start_changed(self, value: int):
self.ui.spinBoxFuzzingEnd.setMinimum(self.ui.spinBoxFuzzingStart.value())
new_start = self.message.convert_index(value - 1, self.proto_view, 0, False)[0]
self.current_label.start = new_start
self.current_label.fuzz_values[:] = []
self.update_message_data_string()
self.fuzz_table_model.update()
self.ui.tblFuzzingValues.resize_me()
@pyqtSlot(int)
def on_fuzzing_end_changed(self, value: int):
self.ui.spinBoxFuzzingStart.setMaximum(self.ui.spinBoxFuzzingEnd.value())
new_end = self.message.convert_index(value - 1, self.proto_view, 0, False)[1] + 1
self.current_label.end = new_end
self.current_label.fuzz_values[:] = []
self.update_message_data_string()
self.fuzz_table_model.update()
self.ui.tblFuzzingValues.resize_me()
@pyqtSlot(int)
def on_combo_box_fuzzing_label_current_index_changed(self, index: int):
self.fuzz_table_model.fuzzing_label = self.current_label
self.fuzz_table_model.update()
self.update_message_data_string()
self.ui.tblFuzzingValues.resize_me()
self.ui.spinBoxFuzzingStart.blockSignals(True)
self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
self.ui.spinBoxFuzzingStart.blockSignals(False)
self.ui.spinBoxFuzzingEnd.blockSignals(True)
self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
self.ui.spinBoxFuzzingEnd.blockSignals(False)
@pyqtSlot()
def on_btn_add_row_clicked(self):
self.current_label.add_fuzz_value()
self.fuzz_table_model.update()
@pyqtSlot()
def on_btn_del_row_clicked(self):
min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
self.delete_lines(min_row, max_row)
@pyqtSlot(int, int)
def delete_lines(self, min_row, max_row):
if min_row == -1:
self.current_label.fuzz_values = self.current_label.fuzz_values[:-1]
else:
self.current_label.fuzz_values = self.current_label.fuzz_values[:min_row] + self.current_label.fuzz_values[
max_row + 1:]
_ = self.current_label # if user deleted all, this will restore a fuzz value
self.fuzz_table_model.update()
@pyqtSlot()
def on_remove_duplicates_state_changed(self):
self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked()
self.fuzz_table_model.update()
self.remove_duplicates()
@pyqtSlot()
def set_add_spinboxes_maximum_on_label_change(self):
nbits = self.current_label.end - self.current_label.start # Use Bit Start/End for maximum calc.
if nbits >= 32:
nbits = 31
max_val = 2 ** nbits - 1
self.ui.sBAddRangeStart.setMaximum(max_val - 1)
self.ui.sBAddRangeEnd.setMaximum(max_val)
self.ui.sBAddRangeEnd.setValue(max_val)
self.ui.sBAddRangeStep.setMaximum(max_val)
self.ui.spinBoxLowerBound.setMaximum(max_val - 1)
self.ui.spinBoxUpperBound.setMaximum(max_val)
self.ui.spinBoxUpperBound.setValue(max_val)
self.ui.spinBoxBoundaryNumber.setMaximum(int(max_val / 2) + 1)
self.ui.spinBoxRandomMinimum.setMaximum(max_val - 1)
self.ui.spinBoxRandomMaximum.setMaximum(max_val)
self.ui.spinBoxRandomMaximum.setValue(max_val)
@pyqtSlot(int)
def on_fuzzing_range_start_changed(self, value: int):
self.ui.sBAddRangeEnd.setMinimum(value)
self.ui.sBAddRangeStep.setMaximum(self.ui.sBAddRangeEnd.value() - value)
@pyqtSlot(int)
def on_fuzzing_range_end_changed(self, value: int):
self.ui.sBAddRangeStart.setMaximum(value - 1)
self.ui.sBAddRangeStep.setMaximum(value - self.ui.sBAddRangeStart.value())
@pyqtSlot()
def on_lower_bound_checked_changed(self):
if self.ui.checkBoxLowerBound.isChecked():
self.ui.spinBoxLowerBound.setEnabled(True)
self.ui.spinBoxBoundaryNumber.setEnabled(True)
elif not self.ui.checkBoxUpperBound.isChecked():
self.ui.spinBoxLowerBound.setEnabled(False)
self.ui.spinBoxBoundaryNumber.setEnabled(False)
else:
self.ui.spinBoxLowerBound.setEnabled(False)
@pyqtSlot()
def on_upper_bound_checked_changed(self):
if self.ui.checkBoxUpperBound.isChecked():
self.ui.spinBoxUpperBound.setEnabled(True)
self.ui.spinBoxBoundaryNumber.setEnabled(True)
elif not self.ui.checkBoxLowerBound.isChecked():
self.ui.spinBoxUpperBound.setEnabled(False)
self.ui.spinBoxBoundaryNumber.setEnabled(False)
else:
self.ui.spinBoxUpperBound.setEnabled(False)
@pyqtSlot()
def on_lower_bound_changed(self):
self.ui.spinBoxUpperBound.setMinimum(self.ui.spinBoxLowerBound.value())
self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value()
- self.ui.spinBoxLowerBound.value()) / 2))
@pyqtSlot()
def on_upper_bound_changed(self):
self.ui.spinBoxLowerBound.setMaximum(self.ui.spinBoxUpperBound.value() - 1)
self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value()
- self.ui.spinBoxLowerBound.value()) / 2))
@pyqtSlot()
def on_random_range_min_changed(self):
self.ui.spinBoxRandomMaximum.setMinimum(self.ui.spinBoxRandomMinimum.value())
@pyqtSlot()
def on_random_range_max_changed(self):
self.ui.spinBoxRandomMinimum.setMaximum(self.ui.spinBoxRandomMaximum.value() - 1)
@pyqtSlot()
def on_btn_add_fuzzing_values_clicked(self):
if self.ui.comboBoxStrategy.currentIndex() == 0:
self.__add_fuzzing_range()
elif self.ui.comboBoxStrategy.currentIndex() == 1:
self.__add_fuzzing_boundaries()
elif self.ui.comboBoxStrategy.currentIndex() == 2:
self.__add_random_fuzzing_values()
def __add_fuzzing_range(self):
start = self.ui.sBAddRangeStart.value()
end = self.ui.sBAddRangeEnd.value()
step = self.ui.sBAddRangeStep.value()
self.fuzz_table_model.add_range(start, end + 1, step)
def __add_fuzzing_boundaries(self):
lower_bound = -1
if self.ui.spinBoxLowerBound.isEnabled():
lower_bound = self.ui.spinBoxLowerBound.value()
upper_bound = -1
if self.ui.spinBoxUpperBound.isEnabled():
upper_bound = self.ui.spinBoxUpperBound.value()
num_vals = self.ui.spinBoxBoundaryNumber.value()
self.fuzz_table_model.add_boundaries(lower_bound, upper_bound, num_vals)
def __add_random_fuzzing_values(self):
n = self.ui.spinBoxNumberRandom.value()
minimum = self.ui.spinBoxRandomMinimum.value()
maximum = self.ui.spinBoxRandomMaximum.value()
self.fuzz_table_model.add_random(n, minimum, maximum)
def remove_duplicates(self):
if self.ui.chkBRemoveDuplicates.isChecked():
for lbl in self.message.message_type:
seq = lbl.fuzz_values[:]
seen = set()
add_seen = seen.add
lbl.fuzz_values = [l for l in seq if not (l in seen or add_seen(l))]
@pyqtSlot()
def set_current_label_name(self):
self.current_label.name = self.ui.comboBoxFuzzingLabel.currentText()
self.ui.comboBoxFuzzingLabel.setItemText(self.ui.comboBoxFuzzingLabel.currentIndex(), self.current_label.name)
@pyqtSlot(int)
def on_fuzz_msg_changed(self, index: int):
self.ui.comboBoxFuzzingLabel.setDisabled(False)
sel_label_ind = self.ui.comboBoxFuzzingLabel.currentIndex()
self.ui.comboBoxFuzzingLabel.blockSignals(True)
self.ui.comboBoxFuzzingLabel.clear()
if len(self.message.message_type) == 0:
self.ui.comboBoxFuzzingLabel.setDisabled(True)
return
self.ui.comboBoxFuzzingLabel.addItems([lbl.name for lbl in self.message.message_type])
self.ui.comboBoxFuzzingLabel.blockSignals(False)
if sel_label_ind < self.ui.comboBoxFuzzingLabel.count():
self.ui.comboBoxFuzzingLabel.setCurrentIndex(sel_label_ind)
else:
self.ui.comboBoxFuzzingLabel.setCurrentIndex(0)
self.fuzz_table_model.fuzzing_label = self.current_label
self.fuzz_table_model.update()
self.update_message_data_string()
@pyqtSlot()
def on_btn_repeat_values_clicked(self):
num_repeats, ok = QInputDialog.getInt(self, self.tr("How many times shall values be repeated?"),
self.tr("Number of repeats:"), 1, 1)
if ok:
self.ui.chkBRemoveDuplicates.setChecked(False)
min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
if min_row == -1:
start, end = 0, len(self.current_label.fuzz_values)
else:
start, end = min_row, max_row + 1
self.fuzz_table_model.repeat_fuzzing_values(start, end, num_repeats)
| jopohl/urh | src/urh/controller/dialogs/FuzzingDialog.py | Python | gpl-3.0 | 15,833 |
<?php
class ControllerCheckoutRegister extends Controller {
public function index() {
$this->language->load('checkout/checkout');
$this->data['text_checkout_payment_address'] = __('text_checkout_payment_address');
$this->data['text_your_details'] = __('text_your_details');
$this->data['text_your_address'] = __('text_your_address');
$this->data['text_your_password'] = __('text_your_password');
$this->data['text_select'] = __('text_select');
$this->data['text_none'] = __('text_none');
$this->data['text_modify'] = __('text_modify');
$this->data['entry_firstname'] = __('entry_firstname');
$this->data['entry_lastname'] = __('entry_lastname');
$this->data['entry_email'] = __('entry_email');
$this->data['entry_telephone'] = __('entry_telephone');
$this->data['entry_fax'] = __('entry_fax');
$this->data['entry_company'] = __('entry_company');
$this->data['entry_customer_group'] = __('entry_customer_group');
$this->data['entry_address_1'] = __('entry_address_1');
$this->data['entry_address_2'] = __('entry_address_2');
$this->data['entry_postcode'] = __('entry_postcode');
$this->data['entry_city'] = __('entry_city');
$this->data['entry_country'] = __('entry_country');
$this->data['entry_zone'] = __('entry_zone');
$this->data['entry_newsletter'] = sprintf(__('entry_newsletter'), $this->config->get('config_name'));
$this->data['entry_password'] = __('entry_password');
$this->data['entry_confirm'] = __('entry_confirm');
$this->data['entry_shipping'] = __('entry_shipping');
$this->data['button_continue'] = __('button_continue');
$this->data['customer_groups'] = array();
if (is_array($this->config->get('config_customer_group_display'))) {
$this->load->model('account/customer_group');
$customer_groups = $this->model_account_customer_group->getCustomerGroups();
foreach ($customer_groups as $customer_group) {
if (in_array($customer_group['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$this->data['customer_groups'][] = $customer_group;
}
}
}
$this->data['customer_group_id'] = $this->config->get('config_customer_group_id');
if (isset($this->session->data['shipping_addess']['postcode'])) {
$this->data['postcode'] = $this->session->data['shipping_addess']['postcode'];
} else {
$this->data['postcode'] = '';
}
if (isset($this->session->data['shipping_addess']['country_id'])) {
$this->data['country_id'] = $this->session->data['shipping_addess']['country_id'];
} else {
$this->data['country_id'] = $this->config->get('config_country_id');
}
if (isset($this->session->data['shipping_addess']['zone_id'])) {
$this->data['zone_id'] = $this->session->data['shipping_addess']['zone_id'];
} else {
$this->data['zone_id'] = '';
}
$this->load->model('localisation/country');
$this->data['countries'] = $this->model_localisation_country->getCountries();
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info) {
$this->data['text_agree'] = sprintf(__('text_agree'), $this->url->link('information/information/info', 'information_id=' . $this->config->get('config_account_id'), 'SSL'), $information_info['title'], $information_info['title']);
} else {
$this->data['text_agree'] = '';
}
} else {
$this->data['text_agree'] = '';
}
$this->data['shipping_required'] = $this->cart->hasShipping();
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/register.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/register.tpl';
} else {
$this->template = 'default/template/checkout/register.tpl';
}
$this->response->setOutput($this->render());
}
public function save() {
$this->language->load('checkout/checkout');
$json = array();
// Validate if customer is already logged out.
if ($this->customer->isLogged()) {
$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate cart has products and has stock.
if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$json['redirect'] = $this->url->link('checkout/cart');
}
// Validate minimum quantity requirments.
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$json['redirect'] = $this->url->link('checkout/cart');
break;
}
}
if (!$json) {
$this->load->model('account/customer');
if ((utf8_strlen($this->request->post['firstname']) < 1) || (utf8_strlen($this->request->post['firstname']) > 32)) {
$json['error']['firstname'] = __('error_firstname');
}
if ((utf8_strlen($this->request->post['lastname']) < 1) || (utf8_strlen($this->request->post['lastname']) > 32)) {
$json['error']['lastname'] = __('error_lastname');
}
if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) {
$json['error']['email'] = __('error_email');
}
if ($this->model_account_customer->getTotalCustomersByEmail($this->request->post['email'])) {
$json['error']['warning'] = __('error_exists');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$json['error']['telephone'] = __('error_telephone');
}
// Customer Group
$this->load->model('account/customer_group');
if (isset($this->request->post['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
$customer_group = $this->model_account_customer_group->getCustomerGroup($customer_group_id);
if ($customer_group) {
}
if ((utf8_strlen($this->request->post['address_1']) < 3) || (utf8_strlen($this->request->post['address_1']) > 128)) {
$json['error']['address_1'] = __('error_address_1');
}
if ((utf8_strlen($this->request->post['city']) < 2) || (utf8_strlen($this->request->post['city']) > 128)) {
$json['error']['city'] = __('error_city');
}
$this->load->model('localisation/country');
$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);
if ($country_info && $country_info['postcode_required'] && (utf8_strlen($this->request->post['postcode']) < 2) || (utf8_strlen($this->request->post['postcode']) > 10)) {
$json['error']['postcode'] = __('error_postcode');
}
if ($this->request->post['country_id'] == '') {
$json['error']['country'] = __('error_country');
}
if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '') {
$json['error']['zone'] = __('error_zone');
}
if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
$json['error']['password'] = __('error_password');
}
if ($this->request->post['confirm'] != $this->request->post['password']) {
$json['error']['confirm'] = __('error_confirm');
}
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info && !isset($this->request->post['agree'])) {
$json['error']['warning'] = sprintf(__('error_agree'), $information_info['title']);
}
}
}
if (!$json) {
$this->model_account_customer->addCustomer($this->request->post);
$this->session->data['account'] = 'register';
if ($customer_group && !$customer_group['approval']) {
$this->customer->login($this->request->post['email'], $this->request->post['password']);
// Default Payment Address
$this->load->model('account/address');
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
if (!empty($this->request->post['shipping_address'])) {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
} else {
$json['redirect'] = $this->url->link('account/success');
}
unset($this->session->data['guest']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
}
$this->response->setOutput(json_encode($json));
}
}
?> | maddes/madcart | catalog/controller/checkout/register.php | PHP | gpl-3.0 | 9,487 |